repo_name
stringlengths
5
100
path
stringlengths
4
231
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
6
947k
score
float64
0
0.34
prefix
stringlengths
0
8.16k
middle
stringlengths
3
512
suffix
stringlengths
0
8.17k
PetePriority/home-assistant
homeassistant/components/smartthings/__init__.py
Python
apache-2.0
8,575
0
"""SmartThings Cloud integration for Home Assistant.""" import asyncio import logging from typing import Iterable from aiohttp.client_exceptions import ( ClientConnectionError, ClientResponseError) from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_ACCESS_TOKEN from homeass...
if not [flow for flow in flows if flow['handler'] == DOMAIN]: hass.async_create_task( hass.config_entries.flow.async_init( DOMAIN, context={'source': 'import'})) return False for component in SUPPORTED_PLATFORMS: hass.async_create_task(hass.config_en...
c_forward_entry_setup( entry, component)) return True async def async_unload_entry(hass: HomeAssistantType, entry: ConfigEntry): """Unload a config entry.""" broker = hass.data[DOMAIN][DATA_BROKERS].pop(entry.entry_id, None) if broker and broker.event_handler_disconnect: broker.eve...
Chilledheart/chromium
tools/telemetry/telemetry/internal/backends/chrome/ios_browser_backend.py
Python
bsd-3-clause
4,612
0.00954
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import contextlib import json import logging import re import urllib2 from telemetry.core import exceptions from telemetry.core import util from telemetry.i...
except urllib2.URLError as e: logging.debug('Error commu
nicating with iOS device.') logging.debug(e) return False try: # Retry a few times since it can take a few seconds for this API to be # ready, if ios_webkit_debug_proxy is just launched. data = util.WaitFor(GetData, 5) except exceptions.TimeoutException as e: ...
brunosmmm/hdltools
hdltools/patterns/__init__.py
Python
mit
2,709
0.000369
"""Signal pattern matching.""" import re from typing import Union class PatternError(Exception): """Pattern error.""" class Pattern: """Signal pattern representation.""" PATTERN_REGEX = re.compile(r"[01xX]+") PATTERN_REGEX_BYTES = re.compile(b"[01xX]+") def __init__(self, pattern: Union[str, ...
- len(self._pattern) pattern = "0" * count + self._pattern for value_bit, expected_bit in zip(value, pattern): if expected_bit in ("x", "X"): # don't care continue if expect
ed_bit != value_bit: return False return True @staticmethod def hex_to_bin(hexstr): """Convert hex to binary including don't cares.""" if hexstr.endswith("h"): hexstr = hexstr[:-1] hexstr = hexstr.replace("x", "X") split = hexstr.split("X") ...
FulcronZ/NyuziProcessor
tests/misc/perf_counters/runtest.py
Python
apache-2.0
1,011
0.007913
#!/usr/bin/env python # # Copyright 2011-2015 Jeff Bush # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable la...
c') result = test_harness.run_verilator() if result.find('PASS') == -1: raise test_harness.TestException('test p
rogram did not indicate pass\n' + result) test_harness.register_tests(perf_counters_test, ['perf_counters']) test_harness.execute_tests()
ampproject/amp-github-apps
project-metrics/metrics_service/server.py
Python
apache-2.0
6,263
0.009261
#!/usr/bin/env python """Entry point to run app. Used to launch the REST and Cron servers. """ import logging import io import os import flask from flask_api import status from google.cloud import storage from typing import Text logging.getLogger().setLevel(logging.INFO) from metrics import base import env import m...
Y_DAYS}) @app.route('/_cron/plot_metric_history/<history_days>') def render_metric_history_plot(history_days: Text): # This header is added to cron requests by GAE, and stripped from any external # requests. See # https://cloud.google.com/appengine/docs/standard/python3/scheduling-jobs-with-cron-yaml#validating_c...
to access internal endpoint.', status.HTTP_403_FORBIDDEN history_days = int(history_days) logging.info('Rendering metric history plots for last %d days', history_days) for metric_cls in base.Metric.get_active_metrics(): metric = metric_cls() plotter = metric_plot.MetricHistoryPlotter( metric, hi...
openstack/trove
trove/tests/unittests/api/common/test_extensions.py
Python
apache-2.0
3,517
0
# Copyright 2014 IBM Corp. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed t...
oup('mock', EP_TEXT)
mock_iter_eps.return_value = eps.values() extension_mgr = extensions.ExtensionManager() self.assertEqual(len(DEFAULT_EXTENSION_MAP.keys()), len(extension_mgr.extensions), "Loaded invalid extensions") self._assert_default_extensions(extensio...
hwroitzsch/BikersLifeSaver
src/bike_module/processor/CameraDataProcessor.py
Python
mit
5,814
0.023769
__author__ = 'Hans-Werner Roitzsch' from datetime import datetime import sched import cv2 as opencv import numpy as np from config import * from processor.SensorDataProcessor import SensorDataProcessor from model.ProcessedCameraData import ProcessedCameraData from writer.ImageFileWriter import ImageFileWriter cl...
el = np.ones((6, 6), dtype=np.float32) / 36 mean_filtered = opencv.filter2D(image, -1, kernel) t2_mean_filtering = datetime.now() # convert to HSV image # hsv_image = opencv.cvtColor(mean_filtered, opencv.COLOR_RGB2HSV) t1_hsv_image = datetime.now() hsv_image = opencv.cvtColor(mean_filtered, opencv....
.now() mask_image = opencv.inRange(hsv_image, self.lower_blinker_hsv, self.upper_blinker_hsv) # select only the pixels with HSV in the given range t2_mask = datetime.now() # closing to make segments compact t1_closing = datetime.now() kernel = self.create_kernel(rows=40, cols=40) closing_image = ope...
ruthger/Archipel
ArchipelAgent/archipel-agent-virtualmachine-storage/setup.py
Python
agpl-3.0
3,255
0.006452
# # setup.py # # Copyright (C) 2010 Antoine Mercadal <antoine.mercadal@inframonde.eu> # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option...
agent-virtualmachine-storage' SHORTDESCRIPTION = "Manage virtual machine storages" LONGDESCRIPTION = "" ENTRY_POINTS = { 'archipel.plugin.virtualmachine': [ 'factory=archipelagentvirtualmachinestorage:make_archipel_plugin'], 'archipel.plugin' : [ ...
0}\n".format(NAME) ## HACK FOR DEPS IN RPMS from setuptools.command.bdist_rpm import bdist_rpm def custom_make_spec_file(self): spec = self._original_make_spec_file() lineDescription = "%description" spec.insert(spec.index(lineDescription) - 1, "requires: %s" % RPM_REQUIRED_DEPS) spec.append(RPM_POST_I...
nacc/autotest
client/tests/kvm/kvm.py
Python
gpl-2.0
663
0
from autotest.client.virt import virt_test class kvm(virt_test.virt_test): """ Suite of KVM virtualization functional tests. Contains tests for testin
g both KVM kernel code and userspace code. @copyright: Red Hat 2008-2009 @author: Uri Lublin (uril@redhat.com) @author: Dror Russo (drusso@redhat.com) @author: Michael Goldish (mgoldish@redhat.com) @author: David Huff (dhuff@redhat.com) @author: Alexey Eromenko (aeromenk@redhat.com)
@author: Mike Burns (mburns@redhat.com) @see: http://www.linux-kvm.org/page/KVM-Autotest/Client_Install (Online doc - Getting started with KVM testing) """ pass
infobeisel/polyvr
extras/blender_scripts/remove_double_vertices_and_faces.py
Python
gpl-3.0
2,067
0.013062
#----------------------------------------------------------------------------- #remove duplicates v1.3 #best way to remove duplicates, just select the objects you want the duplicates removed, then run this scrpit import bpy for obj in bpy.context.selected_objects: if obj.type == 'MESH': bpy.data.scenes[0]...
bpy.ops.mesh.select_all(action='SELECT') bpy.ops.mesh.normals_make_consistent(inside=False) # recalculate normals bpy.ops.mesh.remove_doubles(thre
shold=0.0001, use_unselected=False) #remove doubles bpy.ops.mesh.normals_make_consistent(inside=False) # recalculate normals (this one or two lines above is redundant) bpy.ops.object.mode_set(mode='OBJECT', toggle=False) # set to Object Mode AGAIN
elerno/cascaBell
normalizeFiles.py
Python
agpl-3.0
1,436
0.026462
#!/usr/bin/python # -*- coding: UTF-8 -*- # Normalize soundfiles in a folder, and write them to a new folder # called normalized/ # Import Python modules import contextlib import os import shutil import sys import wave # Import user modules def normalize(): """ Normalizes a set of sound files to norm-To dB return ...
sound files and th
e sort type from the command-line # arguments. argValues = sys.argv inputCheck(argValues) folderToSort = argValues[1] try: normalizeTo = argValues[2] except IndexError: normalizeTo = -3 print 'Normalizing to -3dB' # Exectue the script. normalize()
gklyne/annalist
src/annalist_root/annalist_site/settings/devel.py
Python
mit
1,731
0.008666
""" Development settings Data is kept within the project directory (initialize as required, e.g. by copying initial testdata). Service configuration is kept under personal home directory to protect secret keys, etc. """ from __future__ import unicode_literals from __future__ import absolute_import, division, print_f...
'default']['NAME']
) # End.
dbmi-pitt/dbmi-annotator
translation/mp-evidence-base-ETL/deprecated/mpEvidenceQry.py
Python
apache-2.0
12,990
0.032333
# Copyright 2016-2017 University of Pittsburgh # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http:www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agr...
imAnn.claimid) return claimDataMatAnn ######################### QUERY MP Claim ########################## ## query all claim annotation by document URL ## return {{key: id-1, value: Ann-1"}, {key: i
d-2, value: Ann-2"}, ...} def queryAllMpClaim(conn): annotations = {} # key: id, value obj Annotation cur = conn.cursor() qry = """ select cann.id, t.has_source, cann.creator, cann.date_created, s.exact, s.prefix, s.suffix, cbody.label, qualifierrole(q.subject, q.predicate, q.object) as qtype, qvalue, cann.rejecte...
icoxfog417/pykintone
pykintone/user_api/export.py
Python
apache-2.0
1,411
0.002835
from pykintone.base_api import BaseAPI import pykintone.user_api.user_api_result as ur class Export(BaseAPI): def __init__(self, account, requests_options=()): super(Export, self).__init__(account=account, requests_options=requests_options) def get_users(self, ids=(), codes=(), offset=-1, size=0):
url = "https://{0}.cybozu.com/v1/users.json".format(self.account.domain) params = {} if len(ids) > 0: params["ids"] = ids if len(codes) > 0: params["codes"] = codes if offset > -1: params["offset"] = offset if size > 0: par...
size resp = self._request("GET", url, params_or_data=params) r = ur.GetUsersResult(resp) return r def get_user_organization_titles(self, code): url = "https://{0}.cybozu.com/v1/user/organizations.json".format(self.account.domain) params = { "code": code ...
PearsonIOKI/compose-forum
askbot/const/message_keys.py
Python
gpl-3.0
1,683
0.004753
''' This file must hold keys for translatable messages that are used as variables it is important that a dummy _() function is used here this way message key will be pulled into django.po and can still be used as a variable in python files.
''' _ = lambda v:v #NOTE: all strings must be explicitly put into this dictionary, #because you don't want to import _ from here with import * __all__ = [] #messages loaded in the templates via direct _ calls _('most relevant questions') _('click to see most relevant questions') _('by relevance') _('click to see the...
t recently updated questions') _('by activity') _('click to see the most recently updated questions') _('click to see the least answered questions') _('by answers') _('click to see the most answered questions') _('click to see least voted questions') _('by votes') _('click to see most voted questions') _('interesting')...
typesupply/glyph-nanny
source/code/glyphNanny/__init__.py
Python
mit
201
0.004975
from . imp
ort tests from . import defaults from .scripting import ( registeredTests, testGlyph, testLayer, testFont, formatGlyphRe
port, formatLayerReport, formatFontReport )
jsubpy/jsub
jsub/log.py
Python
mit
1,326
0.004525
import time import logging def time_zone(t): if t.tm_isdst == 1 and time.daylight == 1: tz_sec = time.altzone tz_name = time.tzname[1] else: tz_sec = time.timezone tz_name = time.tzname[0] if tz_sec > 0: tz_sign = '-' else: tz_sign = '+' tz_offset =...
time)s](%(name)s
:%(levelname)s) %(message)s', '%Y-%m-%d %H:%M:%S') def add_stream_logger(level): logger = logging.getLogger('JSUB') logger.setLevel(level) ch = logging.StreamHandler() ch.setFormatter(_FORMATTER) logger.addHandler(ch)
HackBulgaria/Programming101-2
week8/1-Generating-Tests/is_prime.py
Python
mit
33
0
def is_prime(n): ret
urn
True
csebastian2/study
study/__init__.py
Python
gpl-3.0
886
0
""" Study Project Copyright (C) 2015 Study Project Authors and Contributors This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Th...
e that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org...
ort absolute_import __license__ = "GNU General Public License Version 3" __authors__ = [ "Tomasz Kajtoch", ] VERSION = (1, 0, 0, 'alpha') __version__ = "1.0.0alpha"
sysadminmatmoz/odoo-clearcorp
TODO-7.0/hr_payroll_sort_employees/__init__.py
Python
agpl-3.0
1,063
0
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Addons modules by CLEARCORP S.A. # Copyright (C) 2009-TO
DAY CLEARCORP S.A. (<http://clearcorp.co.cr>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public Lic
ense as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR...
Garrett-R/scikit-learn
sklearn/gaussian_process/gaussian_process.py
Python
bsd-3-clause
34,404
0.000116
# -*- coding: utf-8 -*- # Author: Vincent Dubourg <vincent.dubourg@gmail.com> # (mostly translation, see implementation details) # Licence: BSD 3 clause from __future__ import print_function import numpy as np from scipy import linalg, optimize from ..base import BaseEstimator, RegressorMixin from ..metrics...
servations n_samples should be greater than the size p of this basis. Default assumes a simple constant regression trend. Available built-in regression models are:: 'constant', 'linear', 'quadratic'
corr : string or callable, optional A stationary autocorrelation function returning the autocorrelation between two points x and x'. Default assumes a squared-exponential autocorrelation model. Built-in correlation models are:: 'absolute_exponential', 'squared_exponential',...
Sutto/cloud-custodian
tests/test_redshift.py
Python
apache-2.0
20,641
0.001502
# Copyright 2016-2017 Capital One Services, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed ...
.run() self.assertEqual(len(resources), 1) arn = p.resource_manager.generate_arn(resources[0]["ClusterIdentifier"]) tags = client.describe_tags(ResourceName=arn)["TaggedResources"] tag_map = {t["Tag"]["Key"] for t in tags} self.assertTrue("maid_status" in tag_map) def test_r...
olicy( { "name": "redshift-cluster-unmark", "resource": "redshift", "filters": [ {"type": "value", "key": "ClusterIdentifier", "value": "c7n"} ], "actions": [{"type": "unmark"}], }, se...
mrachinskiy/blender-addon-jewelcraft
ops_utils/scene_ops.py
Python
mit
1,477
0
# ##### BEGIN GPL LICENSE BLOCK ##### # # JewelCraft jewelry design toolkit for Blender. # Copyright (C) 2015-2019 Mikhail Rachinskiy # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, eith...
elcraft_scene_units_set(Operator): bl_label = "Set Units" bl_description = "Set optimal unit settings for jewelry modelling" bl_idname = "scene.jewelcraft_scene_units_set" bl_options = {"REGISTER", "UNDO", "INTERNAL"} def execute(self, context): unit_settings = context.scene.unit_settings ...
h = 0.001 context.space_data.overlay.grid_scale = 0.001 self.report({"INFO"}, "Optimal unit settings are in use") return {"FINISHED"}
CiwPython/Ciw
ciw/data_record.py
Python
mit
371
0.002695
from collections import namedtuple DataRecord = namedtuple('Record', [
'id_number', 'customer_class', 'node', 'arrival_date', 'waiting_time', 'service_start_date', 'service
_time', 'service_end_date', 'time_blocked', 'exit_date', 'destination', 'queue_size_at_arrival', 'queue_size_at_departure', 'server_id' ])
justinpotts/mozillians
mozillians/users/migrations/0039_auto__add_externalaccount.py
Python
bsd-3-clause
12,687
0.008276
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'ExternalAccount' db.create_table('users_externalaccount', ( ('id', self.gf('djan...
django.db.models.fields.related.ForeignKey', [], {'to': "orm['users.UserProfile']"}), 'username': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '255', 'blank':
'True'}) }, 'users.usernameblacklist': { 'Meta': {'ordering': "['value']", 'object_name': 'UsernameBlacklist'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_regex': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), ...
40423118/2017springcd_hw
w10/appdiv.py
Python
agpl-3.0
78
0.051282
impor
t sys sys.path.append("./m1") import div sum=div.div(1,200000) pr
int(sum)
City-of-Helsinki/kore
schools/api.py
Python
agpl-3.0
24,286
0.002512
from rest_framework import routers, serializers, viewsets, mixins, filters, relations from munigeo.api import GeoModelSerializer from rest_framework.serializers import ListSerializer, LIST_SERIALIZER_KWARGS import datetime from .models import * import django_filters from django import forms from rest_framework.except...
orrect arguments must be passed on to the parent list_kwargs = {'child_relation': cls(*args, **kwargs)} for key in kwargs.keys(): if key in relations.MANY_RELATION_KWARGS: list_kwargs[
key] = kwargs[key] return CensoredManyRelatedField(**list_kwargs) class CensoredHyperlinkedModelSerializer(serializers.HyperlinkedModelSerializer): """ Handles view permissions for related field listings with Principal or Employership instances. """ serializer_related_field = CensoredHyperlink...
MaartenGr/BERTopic
bertopic/plotting/__init__.py
Python
mit
616
0
from ._topics import visualize_topics from ._heatmap import visualize_heatmap from ._barchart import visualize_barchart from ._term_ra
nk import visualize_term_rank from ._hierarchy import visualize_hierarchy from ._distribution import visualize_distribution from ._topics_over_time import visualize_topi
cs_over_time from ._topics_per_class import visualize_topics_per_class __all__ = [ "visualize_topics", "visualize_heatmap", "visualize_barchart", "visualize_term_rank", "visualize_hierarchy", "visualize_distribution", "visualize_topics_over_time", "visualize_topics_per_class" ]
capitalk/system_k
configuration_server/configuration_server.py
Python
agpl-3.0
4,240
0.014387
import zmq import sys import ConfigParser import os.path import proto_objs.venue_configuration_pb2 import daemon import signal import lockfile from optparse import OptionParser import datetime full_config = proto_objs.venue_configuration_pb2.configuration() bind_addr="tcp://127.0.0.1:11111" def parse(filename): ...
') print "Using config file: ", config_filename if os.path.exists(config_filename) == False: print "Config file: ", config_filename, " does not exist" raise Exception("Con
fig file: ", config_filename, " does not exist") if options.runAsDaemon == True: context = daemon.DaemonContext( working_directory='.', umask=0o002, #pidfile=lockfile.FileLock('./configuration_server.pid'), stdout=log, stderr=l...
houssine78/addons
website_product_subscription/__init__.py
Python
agpl-3.0
25
0.04
from . i
mport
controllers
Furzoom/learnpython
app/test/TsTclntSS.py
Python
mit
455
0
#!/usr/bin/env python # -*- coding: utf-8 -*- import socket HOST = 'localhost' PORT =
1234 ADDR = (HOST, PORT) BUFSIZE = 1024 while True: tcpCliSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) tcpCliSock.connect(ADDR) data = raw_input('> ') if not data: break tcpCliSock.send('{}\r\n'.format(data)) data = tcpCliSoc
k.recv(BUFSIZE) if not data: break print(data.strip()) tcpCliSock.close()
cieplak/msgr
setup.py
Python
apache-2.0
678
0
#!/usr/bin/env python from setupt
ools import setup requirements = [ 'kombu', 'pika', 'gevent', 'click', 'coid', 'click', 'kafka-python', # should use pykafka 'kazoo', 'pyes', 'redis', 'sqlalchemy', 'psycopg2', 'pilo', ] setup( name='msgr', version='0.0.1', url='https://www.github.com...
trick.cieplak@gmail.com', description='broker agnostic messaging library', packages=['msgr'], license=open('LICENSE').read(), include_package_data=True, install_requires=requirements, tests_require=['nose'], scripts=['bin/msgr'] )
PublicShawn/eye
util.py
Python
mit
2,148
0.006052
import glob import subprocess from threading import Timer import logging import distutils.dir_util import sys import multiprocessing import os from shutil import copy2 import eyetype import shutil logging.basicConfig() logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) def runWithTimeOutByDaemon(cmd...
g_dir, timeout_sec, verbose, idn, shell=False): outpipe = sys.stdout if verbose else subprocess.PIPE errpipe = sys.stderr if verbose else subprocess.PIPE try: proc = subprocess.Popen(cmd, cwd=working_dir, stdout=outpipe, stderr=errpipe, shell=shell) except Excep...
on as e: # TODO may clean up return idn, -1, "", str(e) kill_proc = lambda p: p.kill() timer = Timer(timeout_sec, kill_proc, [proc]) try: timer.start() stdout, stderr = proc.communicate() finally: timer.cancel() return idn, proc.returncode, stdout, stder...
herove/dotfiles
sublime/Packages/Package Control/package_control/upgraders/hg_upgrader.py
Python
mit
2,518
0
import os from ..cache import set_cache, get_cache from ..show_error import show_error from .vcs_upgrader import VcsUpgrader class HgUpgrader(VcsUpgrader): """ Allows upgrading a local mercurial-repository-based package """ cli_name = 'hg' def retrieve_binary(self): """ Returns...
default') self.execute(args, self.working_copy, meaningful_output=True) return
True def incoming(self): """:return: bool if remote revisions are available""" cache_key = self.working_copy + '.incoming' incoming = get_cache(cache_key) if incoming is not None: return incoming binary = self.retrieve_binary() if not binary: ...
dreglad/telesurvideos
telesurvideos/migrations/0007_remove_videolistpluginmodel_tiempo.py
Python
mit
413
0
# -*- coding: utf-8 -*- # Generated by Django 1.9.12 on 2017-01-10 23:56 from __future__ import unicode_literals
from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('telesurvideos', '0006_auto_20170110_1710'), ] operations = [ migrations.RemoveField( model_name='videolistpluginmodel', name='tiempo', ),
]
msfrank/terane
terane/bier/ql/__init__.py
Python
gpl-3.0
2,731
0.005492
# Copyright 2010,2011,2012 Michael Frank <msfrank@syntaxjockey.com> # # This file is part of Terane. # # Terane is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your op...
here['dateFrom'], where['dateTo'], where['fromExcl'], where['toE
xcl']) except ParseBaseException, e: raise QuerySyntaxError(e, string) @logger.tracedfunc def parseTailQuery(string): """ Parse the specified tail query. :param string: The query string. :type string: unicode :returns: A (query,period) tuple. :rtype: tuple """ try: ...
CCI-MOC/GUI-Backend
api/tests/v2/test_reporting.py
Python
apache-2.0
4,602
0.001956
import json from unittest import skip, skipUnless from django.core.urlresolvers import reverse from rest_framework.test import APITestCase, APIRequestFactory, force_authenticate from api.tests.factories import UserFactory, AnonymousUserFactory from api.v2.views import ReportingViewSet from core.models import Atmosphe...
orce_authenticate(request, user=sanity_user) response = self.view(request) self.assertEquals(response.status_code, 200) self.assertEquals(len(response.data), 1) received_data = json.loads(json.dumps(response.data, indent=2)) expected_data_json = '''[ { "id": 29792, ...
"staff_user": "False", "provider": "iPlant Workshop Cloud - Tucson", "image_name": "Ubuntu 14.04.2 XFCE Base", "version_name": "1.0", "is_featured_image": true, "hit_aborted": false, "hit_active_or_aborted": 1, "hit_active_or_aborted_or_error": 1, ...
gtimelog/gtimelog
setup.py
Python
gpl-2.0
2,464
0.000406
#!/usr/bin/env python import ast import os import re import sys from setuptools import find_packages, setup here = os.path.dirname(__file__) def read(filename): with open(os.path.join(here, filename), encoding='utf-8') as f: return f.read() metadata = { k: ast.literal_eval(v) for k, v in re.f...
imum required version") setup( name='gtimelog', version=version, author='Marius Gedminas', author_email='marius@gedmin.as', url='https://gtimelog.org/', description=short_description, long_description=long_description, license='GPL', keywords='time log logging timesheets gnome gtk',...
'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', 'Programming Language :: Python :: 3.10', 'Programming Language :: Python :: Implementation :: CPython', ...
phracek/devassistant
devassistant/__init__.py
Python
gpl-2.0
63
0
"""PEP-
396 compliant package version""" __version__
= '0.10.1'
centricular/meson
test cases/common/16 configure file/generator.py
Python
apache-2.0
223
0.004484
#!/usr/bin/env python3 import sys, os if len(sys.argv) != 3: print("Wrong amount of parameters.") assert(os.path.exists(sys.argv[1])) with open(sys.
argv[2], 'w') as
ofile: ofile.write("#define ZERO_RESULT 0\n")
Sunhick/hacker_rank
Algorithms/Bit Manipulation/Maximizing-Xor.py
Python
mit
418
0.007177
#!/usr/bin/python3 def maxXor(l, r): """ Max Xor """ i = l max_so_f
ar = 0 while(l <= i and i <= r): j = l while(l <= j and j <= r): tmp = i ^
j if max_so_far < tmp: max_so_far = tmp j += 1 i += 1 return max_so_far if __name__ == '__main__': l = int(input()) r = int(input()) print(maxXor(l, r))
ProfessorX/Config
.PyCharm30/system/python_stubs/-1247972723/samba/dcerpc/wkssvc/NetWkstaInfo1059.py
Python
gpl-2.0
675
0.007407
# encoding: utf-8 # module samba.dcerpc.wkssvc # from /usr/
lib/python2.7/dist-packages/samba/dcerpc/wkssvc.so # by generator 1.135 """ wkssvc DCE/RPC """ # imports import dcerpc as __dcerpc import talloc as __talloc class NetWkstaInfo1059(__talloc.Object): # no doc def __i
nit__(self, *args, **kwargs): # real signature unknown pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass buf_read_only_files = property(lambda ...
saltstack/salt
tests/unit/modules/test_drbd.py
Python
apache-2.0
6,104
0.000328
""" :codeauthor: Jayesh Kariya <jayeshk@saltstack.com> """ import salt.modules.drbd as drbd from tests.support.mixins import LoaderModuleMockMixin from tests.support.mock import MagicMock, patch from tests.support.unit import TestCase class DrbdTestCase(TestCase, LoaderModuleMockMixin): """ Test cases f...
"replication": "SyncSource", } ], "peernode name": "opensuse-node2", "role": "Secondary", } ]
, "resource name": "single", } ] mock = MagicMock( return_value=""" single role:Primary disk:UpToDate opensuse-node2 role:Secondary replication:SyncSource peer-disk:Inconsistent done:96.47 """ ) with patch.dict(drbd.__salt__, {"cmd.run": ...
ragibson/Steganography
tests/test_wavsteg.py
Python
mit
3,422
0.001461
import numpy as np import os from random import choice from stego_lsb.WavSteg import hide_data, recover_data import string import unittest import wave class TestWavSteg(unittest.TestCase): def write_random_wav(self, filename, num_channels, sample_width, framerate, num_frames): if sample_width != 1 and sam...
) def test_consistency_16bit(self): self.check_random_interleaving(byte_depth
=2) if __name__ == "__main__": unittest.main()
rivasd/djPsych
djstim/migrations/0006_auto_20161130_1641.py
Python
gpl-3.0
625
0
# -*- coding: utf-8 -*- # Generated by Django 1.9 on 2016-11-30 21:41 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('djstim', '0005_auto_20160414_2205'), ] operations = [ migrations.AlterField( ...
name='microcomponentpair', name='first', field=models.C
harField(max_length=128), ), migrations.AlterField( model_name='microcomponentpair', name='second', field=models.CharField(max_length=128), ), ]
ioGrow/iogrowCRM
crm/iomodels/casestatuses.py
Python
agpl-3.0
1,555
0.019293
from endpoints_proto_datastore.ndb import EndpointsModel from google.appengine.api import search from google.appengine.ext import ndb from protorpc import messages class CaseStatusSchema(messages.Message): name = messages.StringField(1) status_changed_at = messages.StringField(2) class Casestatus (Endpoints...
tion = ndb.KeyProperty() created_at = ndb.DateTimeProperty(auto_now_add=True) updated_at = ndb.DateTimeProperty(auto_now=True) status = ndb.StringProperty() created_by = ndb.KeyProperty() last_modified_by = ndb.KeyProperty() def put(self, **kwargs): ndb.Model.put
(self, **kwargs) self.put_index() def put_index(self): """ index the element at each""" empty_string = lambda x: x if x else "" organization = str(self.organization.id()) my_document = search.Document( doc_id = str(self.key.id()), fields=[ search.Text...
hairychris/energenie-test
src/mihome_energy_monitor.py
Python
mit
1,609
0.003729
# mihome_energy_monitor.py 28/05/2016 D.J.Whale # # A simple demo of monitoring and logging energy usage of mihome devices # # Logs all messages to screen and to a file energenie.csv # Any device that has a switch, it toggles it every 2 seconds. # Any device that offers a power reading, it displays it. import energe...
s") for d in energenie.registry.devices(): print(d) try: p = d.get_power() print("Power: %s" % str(p)) except: pass # Ignore it if can't provide a power time.sleep(APP_DELAY) if __name__ == "__main__": print("Starting energy monitor example") ...
e.init() # provide a default incoming message handler, useful for logging every message def incoming(address, message): print("\nIncoming from %s" % str(address)) Logger.logMessage(message) energenie.fsk_router.when_incoming(incoming) print("Logging to file:%s" % Logger.LOG_FILENAME) ...
renatopp/marioai
agents/__init__.py
Python
mit
27
0.037037
from .random_
agent
import *
mzdaniel/oh-mainline
vendor/packages/kombu/kombu/transport/beanstalk.py
Python
agpl-3.0
3,201
0.00125
""" kombu.transport.beanstalk ========================= Beanstalk transport. :copyright: (c) 2010 - 2011 by David Ziegler. :license: BSD, see LICENSE for more details. """ import socket from Queue import Empty from anyjson import serialize, deserialize from beanstalkc import Connection, BeanstalkcException, Socket...
, dest = self._parse_job(job) return item def _get_many(self, queues, timeout=1): # timeout of None will cause beanstalk to timeout waiting # for a new request if timeout is None: timeout = 1 watching = self.client.watching()
[self.client.watch(active) for active in queues if active not in watching] job = self.client.reserve(timeout=timeout) return self._parse_job(job) def _purge(self, queue): if queue not in self.client.watching(): self.client.watch(queue) [s...
BorgERP/borg-erp-6of3
verticals/garage61/acy_mrp_procurement_virtual_stock/procurement.py
Python
agpl-3.0
4,154
0.005296
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (c) 2013 Acysos S.L. (http://acysos.com) All Rights Reserved. # Ignacio Ibeas <ignacio@acysos.com> # $Id$ # # This program i...
rogram is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # ...
ram. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from datetime import datetime from dateutil.relativedelta import relativedelta from osv import fields from osv import osv from tools.translate import _ import ir import netsvc import time ...
philippks/OSMNames
tests/prepare_data/test_merge_corresponding_linestrings.py
Python
gpl-2.0
7,141
0.003781
from geoalchemy2.elements import WKTElement from osmnames.prepare_data.prepare_data import merge_corresponding_linestrings def test_touching_linestrings_with_same_name_and_parent_id_get_merged(session, tables): session.add( tables.osm_linestring( id=1, osm_id=1111, ...
883825, 944577.598658291 5985883.07702847)""", srid=3857) ) ) session.add( tables.osm_linestring( id=2, osm_id=2222, name="Dorfstrasse", parent_id=133
7, geometry=WKTElement("""LINESTRING(944410.8312014 5985761.48265348, 944216.360920161 5985861.25509228)""", srid=3857) ) ) session.add( tables.osm_linestring( id=3, osm_id=3333, name="Dorfstrasse", ...
ryjmacdonell/geomtools
setup.py
Python
mit
1,588
0
""" Setup script for the Gimbal package """ from setuptools import setup from setuptools import find_packages def readme(): """Ret
urns the contents of the README without the header image.""" header = '======\nGimbal\n===
===\n' with open('README.rst', 'r') as f: f.readline() return header + f.read() def requirements(): """Returns the requirement list.""" with open('requirements.txt', 'r') as f: return [line.strip() for line in f.readlines()] # read the current version number exec(open('gimbal/_ve...
adviti/melange
thirdparty/google_appengine/lib/webapp2/tests/extras_appengine_sessions_memcache_test.py
Python
apache-2.0
4,072
0.000491
# -*- coding: utf-8 -*- import webapp2 from webapp2_extras import sessions from webapp2_extras import sessions_memcache import test_base app = webapp2.WSGIApplication(config={ 'webapp2_extras.sessions': { 'secret_key': 'my-super-secret', }, }) class TestMemcacheSession(test_base.BaseTestCase): ...
store = sessions.SessionStore(req) session = store.get_session(backend='memcache') flashes = session.get_flashes() self.assertEqual(flashes, [(u'foo', None)]) flashes = session.get_flashes() self.assertEqual(flashes, []) session.add_flash('bar') session.a...
bapp2.Response() store.save_sessions(rsp) # Round 3 ------------------------------------------------------------- cookies = rsp.headers.get('Set-Cookie') req = webapp2.Request.blank('/', headers=[('Cookie', cookies)]) req.app = app store = sessions.SessionStore(req) ...
PG-TUe/tpot
tpot/config/regressor.py
Python
lgpl-3.0
5,754
0.000348
# -*- coding: utf-8 -*- """This file is part of the TPOT library. TPOT was primarily developed at the University of Pennsylvania by: - Randal S. Olson (rso@randalolson.com) - Weixuan Fu (weixuanf@upenn.edu) - Daniel Angell (dpa34@drexel.edu) - and many more generous open source contributors TPOT is f...
dify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. TPOT is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with TPOT. If not, see <http://www.gnu.org/licenses/>. """ import numpy as np # Check the TPOT...
ceramos/micropython
tests/basics/builtin_property.py
Python
mit
1,132
0.0053
# test builtin property # create a property object explicitly property() property(1, 2, 3) # use its accessor methods p = property() p.getter(1) p.setter(2) p.deleter(3) # basic use as a decorator class A: def __init__(se
lf, x): self._x = x @property def x(self): print("x get") return self._x a = A(1) print(a.x) try: a.x = 2 except AttributeError: print("AttributeError") # explicit use within a class class B: def __init__(self, x): self._x = x def xget(self): print("x...
et") self._x = value def xdel(self): print("x del") x = property(xget, xset, xdel) b = B(3) print(b.x) b.x = 4 print(b.x) del b.x # full use as a decorator class C: def __init__(self, x): self._x = x @property def x(self): print("x get") return self._x ...
django-salesforce/django-salesforce
tests/test_app_label/settings.py
Python
mit
439
0.004556
"""Test that app config can override a directory name conflict (.e.g. "salesforce")""" from salesforce.testrunner.settings import * # NOQA pylint: disable=unused-wildcard-import,wildcard
-import from salesforce.testrunner.settings import INSTALLED_APPS INSTALLED_APPS = [x for
x in INSTALLED_APPS if x != 'salesforce.testrunner.example'] INSTALLED_APPS += ['tests.test_app_label.salesforce.apps.TestSalesForceConfig'] ROOT_URLCONF = None
consultit/Ely
setup.py
Python
lgpl-3.0
1,423
0.009136
#!/usr/bin/env python ''' Created on Jan 6, 2018 @author: consultit ''' from panda3d.core import Filename import sys, os from subprocess import call ### NOTE: currently this script works only on GNU/Linux currdir = os.path.abspath(sys.path[0]) builddir = Filename.from_os_specific(os.path.join(currdir, '/ely/')).get...
edir = '..' + elydir + module args = ['build.py', '--dir', moduledir, '--libs', libtools, '--libs_src', toolsdir, '--clean'] call(['/usr/bin/python'] + args) #print('installing "' + modulelib + '"
...') #args = [modulelib, moduledir] #call(['/usr/bin/install'] + args)
MHenderson/graph-visualisations
lib/lombardi/LombardiSpirograph.py
Python
mit
18,845
0.005678
"""LombardiSpirograph - draw rotationally symmetric drawings in Lombardi style David Eppstein, UC Irvine, March 2010 For usage information type "python LombardiSpirography.py" without any additional arguments. """ from pyx import canvas,path,color from optparse import OptionParser from math import * import sys # ===...
radialzero = True # Parse out the letters for the circulant at each level circulant = [None]*levels for i in range(levels): circulant[i] = [ord(x) - ord('a') + 1 for x in vertexDescriptors
[i] if x >= "a" and x < "x"] vertexDescriptors[i] = vertexDescriptors[i][len(circulant[i]):] # Parse out the numbers for which other
smrmkt/project_euler
problem_029.py
Python
mit
657
0.004566
#!/usr/bin/env python #-*-coding:utf-8-*- ''' Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows: 21 22 23 24 25 20 7 8 9 10 19 6 1 2 11 18 5 4 3 12 17 16 15 14 13 It can be verified that the sum of the numbers on t
he diagonals is 101. What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed in the same way? ''' import timeit def calc(a, b): return len(set([i**j for i in range(2, a+1) for j in range(2
, b+1)])) if __name__ == '__main__': print calc(100, 100) print timeit.Timer('problem_029.calc(100, 100)', 'import problem_029').timeit(10)
Xelaadryth/Xelabot
quest_bot/quest_player_manager.py
Python
mit
11,668
0.0024
from copy import deepcopy import settings from twitch.player_manager import PlayerManager class QuestPlayerManager(PlayerManager): """ Functions like add_gold perform a raw store action and then save. __add_gold is the raw store action in this case. Properties of raw store actions: - Call usernam...
em to give to the specified player. :param username: str - The player who you are modifying :param item: str or list<str> - The name of the item(s) we are giving to the player """ self.__add_item(username, item) self.save_player(username) def __remove_item(self, username, it...
The name of the item(s) we are giving to the player """ if not isinstance(item, str): # We must be a list of items for single_item in item: self.__remove_item(username, single_item) else: # If we don't have the item, do nothing if i...
NicovincX2/Python-3.5
Représentations graphiques/Bitmap/bitmap.py
Python
gpl-3.0
2,087
0.001437
# -*- coding: utf-8 -*- import os from collections import namedtuple from copy import copy Colour = namedtuple('Colour', 'r,g,b') Colour.copy = lambda self: copy(self) black = Colour(0, 0, 0) white = Colour(255, 255, 255) # Colour ranges are not enforced. class Bitmap(): def __init__(self, width=40, height=...
ck): assert x >
= 0 and y >= 0 and width > 0 and height > 0 and type( colour) == Colour for h in range(height): for w in range(width): self.map[y + h][x + w] = colour.copy() def chardisplay(self): txt = [''.join(' ' if bit == self.background else '@' f...
cdcf/time_tracker
app/auth/forms.py
Python
bsd-3-clause
1,942
0.006179
__author__ = 'Cedric Da Costa Faro' from flask.ext.wtf import Form from wtforms import StringField, PasswordField, BooleanField, SubmitField, validators from wtforms.validators import Required, Length, Email, Reg
exp, EqualTo from wtfor
ms import ValidationError from ..models import User # We allow here a user to be created within the app, however this user will NOT be an admin user. # Users have to insert both an e-mail address which can be only unique and a username that we also want to be unique. class RegistrationForm(Form): email = StringFi...
pi19404/robosub-1
src/movement/fuzzification/test/xbox_controller.py
Python
gpl-3.0
2,612
0.011103
from xboxdrv_parser import Controller from time import sleep import argparse import os import sys sys.path.append(os.path.abspath("../../..")) from util.communication.grapevine import Communicator from robosub_settings import settings def main (args): com = Communicator (args.module_name) controller = Controll...
_Sets": outgoing_packet} com.publish_message (Fuzzy_Sets) except KeyError as i: pass sleep (args.epoch) def commandline(): parser = argparse.Argume
ntParser(description='Mock module.') parser.add_argument('-e', '--epoch', type=float, default=0.1, help='Sleep time per cycle.') parser.add_argument('-m', '--module_name', type=str, default='movement/fuzzification', help='Module name.') return parser.parse_arg...
containers-ftw/apps
tests/circle_urls.py
Python
bsd-3-clause
812
0.013547
#!/usr/bin/env python ''' circle_urls.py will rename all url files to not have extension .html ''' import sys import os from glob import glob site_dir = os.path.abspath(sys.argv[1]) print("Using site directory %s" %(site_dir)) files = glob("%s/*.html" %(site_dir)) # For each f
ile, we need to replace all links to have correct .html extension search_names = [os.path.basename(f).replace('.html','') for f in files] for html_file in files: with open(html_file,'r') as filey: content = filey.read() for search_name in search_names: content = content.replace('%s"' %(search_na...
sci-f.github.io/apps/assets/img/logo/logo.png') with open(html_file,'w') as filey: filey.write(content)
cwmartin/rez
src/rez/tests/test_copy_package.py
Python
lgpl-3.0
10,779
0
""" test package copying """ import shutil import time import os.path import os from rez.system import system from rez.build_process_ import create_build_process from rez.build_system import create_build_system from rez.resolved_context import ResolvedContext from rez.packages_ import get_latest_package from rez.packa...
f._get_dest_pkg("flaab", "5.4.1") result_variant = result["copied"][0][1] dest_va
riant = dest_pkg.iter_variants().next() self.assertEqual(dest_variant.handle, result_variant.handle) def test_5(self): """Package copy with standard, new timestamp.""" self._reset_dest_repository() # wait 1 second to guarantee newer timestamp in copied pkg time.sleep(1) ...
apache/incubator-airflow
airflow/providers/google/cloud/example_dags/example_automl_nl_text_extraction.py
Python
apache-2.0
3,542
0.000847
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
ator( task_id="create_dataset_task", dataset=DATASET, location=GCP_AUTOML_LOCATION ) dataset_id = create_dataset_task.output['dataset_id'] import_dataset_task = AutoMLImportDataOperator( task_id="import_dataset_task", dataset_id=dataset_id, location=GCP_AUTOML_LOCATIO
N, input_config=IMPORT_INPUT_CONFIG, ) MODEL["dataset_id"] = dataset_id create_model = AutoMLTrainModelOperator(task_id="create_model", model=MODEL, location=GCP_AUTOML_LOCATION) model_id = create_model.output['model_id'] delete_model_task = AutoMLDeleteModelOperator( task_id="de...
LeotomasMC/TheDerpyMemeBot
Blank Bot/commands.py
Python
gpl-3.0
2,467
0.008918
#commands.py #diode's custom commands # How to make a custom commands: # # In the function commands, type: # # if msg.startswith("<command>"): # # replace <command> with whatever you want to trigger the command. # # # # A list of functions: # bot.chat.shrug(<message>) # bot.chat.chat(<message>) # bo...
tartswith("@"): ## bot.chat("Lets all wave hello at " + arguments[1] + " ! Hello, " + arguments[1] + " !") ## else: ## bot.chat("Lets all wave hello at @" + arguments[1] + " ! Hello, @" + arguments[1] + " !") if msg.startswith("!afk"): if username in afkList:
try: afkList.remove(username) bot.chat.chat(username + " is now back! Welcome back!") except ValueError: pass else: afkList.append(username) bot.chat.chat(username + " is now AFK. See you soon!") ...
ondergetekende/python-panavatar
panavatar/color_scheme.py
Python
mit
5,222
0.000383
import colorsys def to_rgb(hsv): """Converts a color from HSV to a hex RGB. HSV should be in range 0..1, though hue wraps around. Output is a hexadecimal color value as used by CSS, HTML and SVG""" r, g, b = [int(min(255, max(0, component * 256))) for component in colorsys.hsv_to_rgb(...
[ base_color, (base_color[0] - .2, base_color[1], base_color[2]), (base_color[0] + .2, base_color[1], base_color[2]), (base_color[0], base_color[1], base_color[2] - .3), (base_color[0], base_color[1], base_color[2] + .1), ] class ColorNoise: def...
.05) saturation = params.uniform("saturation_variation", 0, .2) value = params.uniform("value_variation", 0, .5) base_scale = .1 * abs(params.size) self.samplers = [ params.perlin("hue_variation_spatial", size=base_scale, min_value=-hue, max_value=...
frankchin/mezzanine
mezzanine/generic/views.py
Python
bsd-2-clause
6,198
0
from __future__ import unicode_literals from future.builtins import str from json import dumps from string import punctuation from django.apps import apps from django.contrib.admin.views.decorators import staff_member_required from django.contrib.messages import error from django.core.urlresolvers import reverse from...
) keyword_id = str(kw.id) if keyword_id not in keyword_ids: keyword_ids.append(keyword_id) titles.append(title) return HttpResponse(
"%s|%s" % (",".join(keyword_ids), ", ".join(titles))) def initial_validation(request, prefix): """ Returns the related model instance and post data to use in the comment/rating views below. Both comments and ratings have a ``prefix_ACCOUNT_REQUIRED`` setting. If this is ``True`` and the user is u...
shouldmakemusic/yaas
helper/TrackHelper.py
Python
gpl-2.0
5,564
0.009166
# Copyright (C) 2015 Manuel Hirschauer (manuel@hirschauer.net) # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version...
s[trackIndex].devices): return all_tracks[trackIndex].devices[id] return None def get_selected_device(self): device = self._track.view.selected_device return device def get_send_value(self, index): if index is None: ...
d_value(self, index, value): if index is None: return value = float(value); max = self._track.mixer_device.sends[index].max min = self._track.mixer_device.sends[index].min if value > max: value = max if value < min: va...
toladata/TolaTables
silo/migrations/0019_auto_20170719_1146.py
Python
gpl-2.0
642
0
# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2017-07-19 18:46 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('silo', '0018_auto_20170710_1146'), ] operations = [ migrations.AddField( ...
ad', name='autopull_expiration', field=models.DateTimeField(blank=True, null=True), ), migrations.AddField( model_name='read', name='autopush_expiration', field=models.DateTimeField(blank=True, null=T
rue), ), ]
jawilson/Flexget
flexget/plugins/sites/frenchtorrentdb.py
Python
mit
2,131
0.001408
from __future__ import unicode_literals, division, absolute_import from builtins import * # noqa pylint: disable=unused-import, redefined-builtin import re import logging from flexget import plugin from flexget.event import event from flexget.plugins.internal.urlrewriting import UrlRewritingError from flexget.utils....
writingError(e) tag_a = soup.find("a", {"class": "dl_link"}) if not tag_a: if soup.findAll(text="Connexion ?"): raise UrlRewritingError('You are not logged in,\
check if your cookie for\ authentication is up to date') else: raise UrlRewritingError('You have reached your download\ limit per 24hours, so I cannot\ get the torrent...
tacaswell/dataportal
dataportal/muxer/data_muxer.py
Python
bsd-3-clause
38,457
0.000364
# ###################################################################### # Copyright (c) 2014, Brookhaven Science Associates, Brookhaven # # National Laboratory. All rights reserved. # # # # Redistribution and use in ...
turn input class DataMuxer(object): """ This class provides a wrapper layer of signals and slots around a pandas DataFrame to make plugging stuff in for live view easier. The data collection/event model being used is all measurements (that is values that come off of the hardware) are time sta...
of pandas data frames. The data model is that of a sparse table keyed on time stamps which is 'densified' on demand by propagating measurements forwards. Not all measurements (ex images) can be filled. This behavior is controlled by the `col_info` tuple. Parameters ---------- events : l...
goblin/p2pool
p2pool/util/forest.py
Python
gpl-3.0
11,137
0.007542
''' forest data structure ''' import itertools import weakref from p2pool.util import skiplist, variable class TrackerSkipList(skiplist.SkipList): def __init__(self, tracker): skiplist.SkipList.__init__(self) self.tracker = tracker self_ref = weakref.ref(self, lambda _: tracker....
_refs[delta2.tail] self.shares.pop(delta.head) self.reverse_shares[delta.tail].remove(delta.head) if not self.reverse_shares[delta.tail]: self.reverse_shares.pop(delta.tail) self.removed.happened(share) def get_height(self, share_hash): retu...
et_delta(share_hash).work def get_
DIRACGrid/DIRAC
src/DIRAC/Core/DISET/private/InnerRPCClient.py
Python
gpl-3.0
2,922
0.000342
""" This module hosts the logic for executing an RPC call. """ from DIRAC.Core.DISET.private.BaseClient import BaseClient from DIRAC.Core.Utilities.ReturnValues import S_OK from DIRAC.Core.Utilities.DErrno import cmpError, ENOAUTH class InnerRPCClient(BaseClient): """This class instruments the BaseClient to perfo...
._proposeAction(transport, ("RPC", functionName)) if not retVal["OK"]: if cmpError(retVal, ENOAUTH): # This query is unauthorized retVal["rpcStub"] = stub return retVal else: # we have network problem or the service is not responding ...
else: retVal["rpcStub"] = stub return retVal # Send the arguments to the function # Note: we need to convert the arguments to list # We do not need to deseralize it because variadic functions # can work ...
fblupi/master_informatica-SSBW
tarea8_bis/sitio_web/restaurantes/views.py
Python
gpl-3.0
4,124
0.005096
from django.shortcuts import render, HttpResponse, redirect from django.contrib.auth.decorators import login_required from django.http import JsonResponse from .models import restaurants, addr from .forms import RestaurantForm from lxml import etree import datetime import os.path import logging logger = logging.get...
%m-%d %H:%M:%S') + " - se ha consultado la imagen del restaurante con id " + str(r.restaurant_id)) return HttpResponse(image, content_type="image/" + r.photo.format) def number_of_restaurants(request): n = restaurants.objects.count()
return JsonResponse({'n': n})
mulkieran/bytesize
src/bytesize/_size.py
Python
gpl-2.0
18,819
0.000531
# Copyright (C) 2015 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) any later version. # This program is distributed in the hope that it will be u...
" ", "%(units)s", "%(bytes)s" ]) def __init__(self, value=0, units
=None): """ Initialize a new Size object. :param value: a size value, default is 0 :type value: Size, or any finite numeric type (possibly as str) :param units: the units of the size, default is None :type units: any of the publicly defined units constants or a S...
Flyingfox646/flyingfox
src/chunks/migrations/0007_spanish.py
Python
mit
669
0.00299
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-03-29 17:10 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('chunks', '0006_frenc
h'), ] operations = [ migrations.AddField( model_name='chunk', name='content_es', field=models.TextField(blank=True, null=True, verbose_name='content'),
), migrations.AddField( model_name='chunk', name='title_es', field=models.CharField(blank=True, max_length=255, null=True, verbose_name='title'), ), ]
garbersc/keras-galaxies
output_corr.py
Python
bsd-3-clause
1,543
0.051847
# TRAIN_LABELS_PATH = "data/raw/solutions_training.csv" TRAIN_LABELS_PATH = "data/raw/training_solutions_rev1.csv" TARGET_PATH = "data/solutions_train.npy" import pandas as pd import numpy as np from matplotlib import pyplot as plt from termcolor import colored import load_data output_names=["smooth","featureOrdisk...
n xrange(0,37): for j in xrange(i,37): output_corr[i][j]=np.corrcoef(targets[i],targets[j])[0][1] if i!=j and np.abs(output_corr[i][j])>0.3: if np.abs(output_corr[i][j])>0.7: print colored("%s, %s: %s" %(output_names[i],output_names[j],output_corr[i][j]),'green') else:
print("%s, %s: %s" %(output_names[i],output_names[j],output_corr[i][j])) plt.imshow(output_corr, interpolation='none') plt.colorbar() plt.savefig("targetsCorrelation_valid.jpeg") #print "Saving %s" % TARGET_PATH #np.save(TARGET_PATH, targets)
willemneal/CallMe
callMe.py
Python
mit
2,823
0.005668
''' The following is from http://stackoverflow.com/a/2022629 Thanks to Longpoke ''' import types class Event(list): """Event subscription. A list of callable objects. Calling an instance of this will cause a call to each item in the list in ascending order by index. Example Usage: >>> def f(x): ...
to Event() if there is no key name. Either way self[name] is returned and callback is appended''' self.setdefault(name, Event(repeat)).append(callback) def removeSub(self, name, callback): if name in self: self[name].remove(callback) if len(self[name]) == 0: ...
f return wrap def trigger(self, event): def wrap(f): def newFunc(*args, **kwargs): res = f(*args, **kwargs) self(event, res) return res return newFunc return wrap def __call__(self, event, *args, **kwargs): ...
christianurich/VIBe2UrbanSim
3rdparty/opus/src/washtenaw/configurations/jobs_event_model_configuration_creator.py
Python
gpl-2.0
2,232
0.010753
# Opus/UrbanSim urban simulation software. # Copyright (C) 2005-2009 University of Washington # See opus_core/LICENSE from opus_core.configuration import Configuration class JobsEventModelConfigurationCreator(object): _model_name = 'agent_event_model' def __init__(self, locatio...
execu
te() self.assertDictsEqual(result, expected) if __name__ == '__main__': opus_unittest.main()
idrogeno/IdroMips
lib/python/Screens/ScanSetup.py
Python
gpl-2.0
71,927
0.029725
from Screen import Screen from ServiceScan import ServiceScan from Components.config import config, ConfigSubsection, ConfigSelection, \ ConfigYesNo, ConfigInteger, getConfigListEntry, ConfigSlider, ConfigEnableDisable from Components.ActionMap import NumberActionMap, ActionMap from Components.Sources.StaticText impor...
ist.append(parm) def getInitialCableTransponderList(tlist, nim): list = nimmanager.getTranspondersCable(nim) for x in list: if x[0] == 1: #CABLE parm = eDVBFrontendParametersCable() parm.frequency = x[1] parm.symbol_rate = x[2] parm.modulation = x[3] parm.fec_inner = x[4] parm.inversion = x[5] ...
rametersTerrestrial.System_DVB_T_T2, skip_t2 = False): list = nimmanager.getTranspondersTerrestrial(region) #self.transponders[self.parsedTer].append((2,freq,bw,const,crh,crl,guard,transm,hierarchy,inv)) #def buildTerTransponder(frequency, inversion = 2, bandwidth = 3, fechigh = 6, feclow = 6, #modulation = 2,...
thefactory/marathon-python
marathon/models/events.py
Python
mit
7,466
0.001339
""" This module is used to translate Events from Marathon's EventBus system. See: * https://mesosphere.github.io/marathon/docs/event-bus.html * https://github.com/mesosphere/marathon/blob/master/src/main/scala/mesosphere/marathon/core/event/Events.scala """ from marathon.models.base import MarathonObject from marathon...
__(self): pass event_to_class = { 'api_post_event': MarathonApiPostEvent, 'status_update_event': MarathonStatusUpdateEvent, 'framework_message_event': MarathonFrameworkMessageEvent, 'subscribe_event': MarathonSubscribeEvent, 'unsubscribe_event': MarathonUnsubscribeEv...
lthCheckEvent, 'remove_health_check_event': MarathonRemoveHealthCheckEvent, 'failed_health_check_event': MarathonFailedHealthCheckEvent, 'health_status_changed_event': MarathonHealthStatusChangedEvent, 'unhealthy_task_kill_event': MarathonUnhealthyTaskKillEvent, 'group_change_suc...
pwndbg/pwndbg
pwndbg/which.py
Python
mit
3,111
0.001607
# This license covers everything within this project, except for a few pieces # of code that we either did not write ourselves or which we derived from code # that we did not write ourselves. These few pieces have their license specified # in a header, or by a file called LICENSE.txt, which will explain exactly what # ...
, else the first location or :const:`None` if not found. Example: >>> which('sh') '/bin/sh' """ # If name is a path, do not attempt to resolve it. if os.path.sep i
n name: return name isroot = os.getuid() == 0 out = set() try: path = os.environ['PATH'] except KeyError: log.exception('Environment variable $PATH is not set') for p in path.split(os.pathsep): p = os.path.join(p, name) if os.access(p, os.X_OK): s...
unhammer/gt-CorpusTools
corpustools/test/test_analyser.py
Python
gpl-3.0
8,941
0.000338
# -*- coding: utf-8 -*- # # This file contains a class to analyse text in giellatekno xml format # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # ...
' </author>\n' ' <translator>\n' ' <person firstname="Ibba" lastname="Ibbamar" sex="unknown" ' 'born="" nationality=""/>\n'
' </translator>\n' ' <translated_from xml:lang="nob"/>\n' ' <year>2005</year>\n' ' <publChannel>\n' ' <publication>\n' ' <publisher>Almmuheaddji OS</publisher>\n' ' </publication>\n' ' </publChannel>...
nimblecode/nimblecode
server/library/prompts/py/09-jsonDumps.py
Python
mit
79
0.037975
import json
a = [{'first':'Alan', 'last':'Turing'}] j =
json.dumps(a) print(j)
52ai/django-ccsds
tests/auth_tests/test_views.py
Python
bsd-3-clause
40,812
0.001323
# -*- coding: utf-8 -*- from __future__ import unicode_literals import itertools import re from importlib import import_module from django.apps import apps from django.conf import settings from django.contrib.admin.models import LogEntry from django.contrib.auth import REDIRECT_FIELD_NAME, SESSION_KEY from django.con...
"Named URLs should be reversible" expected_named_urls = [ ('login', [], {}), ('logout', [], {}), ('password_change', [], {}), ('password_change_done', [], {}), ('password_reset', [], {}),
('password_reset_done', [], {}), ('password_reset_confirm', [], { 'uidb64': 'aaaaaaa', 'token': '1111-aaaaa', }), ('password_reset_complete', [], {}), ] for name, args, kwargs in expected_named_urls: try: ...
kain88-de/mdanalysis
package/MDAnalysis/visualization/streamlines_3D.py
Python
gpl-2.0
25,088
0.006138
# -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding:utf-8 -*- # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 # # MDAnalysis --- http://www.mdanalysis.org # Copyright (c) 2006-2016 The MDAnalysis Development Team and contributors # (see the file AUTHORS for the full list of names) # # Released under th...
_set) vertex_array = np.array(current_list_cube_vertices) assert vertex_array.shape == (8, 3), "vertex_array has incorrect shape" cube_centroid = np.average(np.array(current_list_cube_vertices), axis=0) dictionary_cubes_centroids_indices[cube_counter] = { ...
'centroid': cube_centroid, 'vertex_list': current_list_cube_vertices} cube_counter += 1 current_index += 1 column_z_level += 1 if column_z_level == num_z_values - 1: # the loop will break but I should also increment the ...
mblayman/markwiki
docs/conf.py
Python
bsd-2-clause
8,182
0.006478
# -*- coding: utf-8 -*- # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys i...
ill be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme ...
Arno-Nymous/pyload
module/plugins/hoster/FilejokerNet.py
Python
gpl-3.0
1,357
0.003685
# -*- coding: utf-8 -*- from ..internal.XFSHoster import XFSHoster clas
s FilejokerNet(XFSHoster): __name__ = "FilejokerNet" __type__ = "ho
ster" __version__ = "0.04" __status__ = "testing" __pattern__ = r'https?://(?:www\.)?filejoker\.net/\w{12}' __config__ = [("activated", "bool", "Activated", True), ("use_premium", "bool", "Use premium account if available", True), ("fallback", "bool", "Fallback to fr...
kiahosseini/django-form-validation
form_validation/forms.py
Python
mit
5,956
0.004533
from django.conf import settings from django import forms from django.utils.translation import get_language from copy import deepcopy class ValidateForm(object): @property def media(self): # I don't use class Media, because I need current_language in path return super(ValidateForm, self).media...
ttr(fld, 'ext_whitelist', [])) if f in required_fields and ( hasattr(form_instance, 'instance') and getattr(form_instance.instance, f, False)): del fld.widge
t.attrs['required'] if forms.ImageField in fld.__class__.__bases__ or isinstance(fld, forms.ImageField): fld.widget.attrs['accept'] = 'image/*' fld.widget.attrs['extension'] = 'jpg,jpeg,gif,png' ValidateForm.clear_lists(form_instance) @staticmethod def clea...
zejn/prometapi
prometapi/encoders.py
Python
agpl-3.0
2,113
0.007099
# coding: ut
f-8 import math try: long_int = long except NameError: long_int = int def rshift(val, n): if val >= 0: val2 = val >> n else: val2 = val + 0x100000000 >> n return val2 def str_to_longs(e): t = [] pad = len(e) % 4 if pad != 0: e = e + (4 - pad) * '\x00' ...
(ord(e[4*r + 2]) << 16) + (ord(e[4*r + 3]) << 24) ) r += 1 return t def longs_to_str(e): t = [] for a in e: s = chr(255 & a) + chr(a >> 8 & 255) + chr(a >> 16 & 255) + chr(a >> 24 & 255) t.append(s) return ''.join(t) def encrypt(e, t): r = st...
dajohnso/cfme_tests
cfme/tests/cloud/test_cloud_events.py
Python
gpl-2.0
3,400
0.002059
# -*- coding: utf-8 -*- """This module tests only cloud specific events""" import pytest import yaml from cfme.common.vm import VM from cfme.cloud.provider.azure import AzureProvider from utils import testgen from utils.generators import random_vm_name pytestmark = [ pytest.mark.tier(3) ] pytest_generate_tests =...
, source=provider.type.upper(), event_type='networkSecurityGroups_delete_EndRequest') # creating and removing network security group provider.mgmt.create_netsec_group(nsg_name, resource_group) provider.mgmt.remove_netsec_group(nsg_name, resource_group) def test_vm_capture(request, prov...
r, setup_provider, register_event): """ tests that generalize and capture vm azure events are received and parsed by CFME """ mgmt = provider.mgmt vm = VM.factory(random_vm_name(context='capture'), provider) if not mgmt.does_vm_exist(vm.name): vm.create_on_provider(find_in_cfme=True, a...
photoninger/ansible
lib/ansible/modules/network/aci/aci_contract_subject_to_filter.py
Python
gpl-3.0
5,651
0.001947
#!/usr/bin/python # -*- coding: utf-8 -*- # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], ...
, M(aci_contract_subject), and M(aci_filter) modules can be used for these. options: contract: description: - The name of the contract. aliases: [ contract_name ] filter: description: - The name of the Filter to bind to the Subject. aliases: [ filter_name ] log: description: - Dete...
t to log. - The APIC defaults new Subject to Filter bindings to C(none). choices: [ log, none ] aliases: [ directive ] default: none subject: description: - The name of the Contract Subject. aliases: [ contract_subject, subject_name ] state: description: - Use C(present) or C(abs...
zenodo/invenio
invenio/legacy/bibclassify/ontology_reader.py
Python
gpl-2.0
44,242
0.000294
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015 CERN. # # Invenio is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of th...
if not no_cache and\ os.path.exists(cache_path) and\ not os.access(cache_path, os.W_OK): raise TaxonomyError('We cannot read/write into: %s. ' 'Aborting!' % cache_path)
elif not no_cache and os.path.exists(cache_path): log.warning('Cache %s exists, but is not readable!' % cache_path) log.info("Cache not available. Building it now: %s" % onto_path) return _build_cache(onto_path, skip_cache=no_cache) else: raise TaxonomyError("We miss both sou...
n054/totp-cgi
contrib/gitolite/command.py
Python
gpl-2.0
22,349
0.002058
#!/usr/bin/python -tt __author__ = 'mricon' import logging import os import sys import anyjson import totpcgi import totpcgi.backends import totpcgi.backends.file import totpcgi.utils import datetime import dateutil import dateutil.parser import dateutil.tz from string import Template import syslog #-------------...
'added': now_time.isoformat(sep=' '), 'expires': expires.isoformat(sep=' '), } # Try to lookup whois info if cymruwhois is available try: import cymruwhois cym = cymruwhois.Client() res = cym.lookup(remote_ip)
if res.owner and res.cc: whois = "%s/%s\n" % (res.owner, res.cc) valdata[remote_ip]['whois'] = whois logger.info('Whois information for %s: %s' % (remote_ip, whois)) except: pass try: geoip = get_geoip_crc(remote_ip) if geoip is not None: ...
DiCarloLab-Delft/PycQED_py3
pycqed/instrument_drivers/physical_instruments/ZurichInstruments/ZI_PQSC.py
Python
mit
9,278
0.00388
""" Driver for PQSC V1 Author: Michael Kerschbaum Date: 2019/09 """ import time import sys import os import logging import numpy as np import pycqed import json import copy import pycqed.instrument_drivers.physical_instruments.ZurichInstruments.ZI_base_instrument as zibase log = logging.getLogger(__name__) ########...
MIN_FWREVISION, self.geti('system/fwrevision'))) if self.geti('system/fpgarevision') < ZI_PQSC.MIN_FPGAREVISION: raise zibase.ziVersionError( 'Insufficient FPGA revision detected! Need {}, got {}!'.format( ZI_PQSC.MIN_FPGAREVISION, self.geti('...
hese are: qas_0_trans_offset_weightfunction - an offset correction parameter for all weight functions, this allows normalized calibration when performing cross-talk suppressed readout. The parameter is not actually used in this driver, but in some of the support classes that make use o...
msterin/play
vsc-play/python/helloworld/manage.py
Python
mit
666
0
#!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'helloworld.settings') try: from
django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ...
_line(sys.argv) if __name__ == '__main__': main()
imndszy/voluntary
excel.py
Python
mit
1,036
0.013078
# -*- coding:utf8 -*- # Author: shizhenyu96@gamil.com # github: https://github.com/imndszy from openpyxl import Workbook from openpyxl.compat import range import pymysql import time while True: try: conn = pymysql.connect(host='localhost',port=3306,user='szy',passwd='123456',db='voluntary',charset='utf8') ...
lt = cur.fetchall() cur.close() conn.close() except: print 'access database wrong' time.sleep(30) continue result = [list(x) for
x in result] wb = Workbook() dest_filename = '/home/ubuntu/www/voluntary/info.xlsx' ws1 = wb.active ws1.title = "data" info=[u'学号',u'总志愿时长',u'A类志愿服务时长',u'B类志愿服务时长'] i = 0 ws1.append(info) for row in range(2,len(result)+2): ws1.append(result[i]) i += 1 wb.save(filena...
emulbreh/vacuous
vacuous/transactions.py
Python
mit
641
0.00156
from vacuous.backends import iter_cached_backends class commit_on_success(object): def __init__(self, **kwargs): self.kwargs = kwargs def __enter__(self):
pass def __exit__(self, exc_type, exc_val, exc_tb): if exc_type: for backend in iter_cached_backends(): backend.rollback() else: for backend in iter_cached_backends(): backend.commit(**self.kwargs) def __call__(self, func): @wraps...
return decorated