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
bitkeeper/python-opcua
opcua/common/ua_utils.py
Python
lgpl-3.0
8,286
0.002414
""" Usefull method and classes not belonging anywhere and depending on opcua library """ from dateutil import parser from datetime import datetime from enum import Enum, IntEnum import uuid from opcua import ua from opcua.ua.uaerrors import UaError def val_to_string(val): """ convert a python object or pyth...
in case base datype can not be determined """ base = datatype while base: if base.nodeid.NamespaceIndex == 0 and isinstance(base.nodeid.Identifier, int) and base.nodeid.Identifier <= 30: return base base = get_node_supertype(base) raise ua.UaError("Datatype must be a subtype...
{0!s}".format(datatype)) def get_nodes_of_namespace(server, namespaces=None): """ Get the nodes of one or more namespaces . Args: server: opc ua server to use namespaces: list of string uri or int indexes of the namespace to export Returns: List of nodes that are part of...
mbbill/thefuck
thefuck/rules/no_command.py
Python
mit
580
0
from difflib import get_close_matches from thefuck.utils import sudo_support, get_all_executables, get_closest @sudo_support def match(command, settings): return 'not found' in command.stderr and \ bool(get_close_matches(co
mmand.script.split(' ')[0], get_all_executables())) @sudo_suppor
t def get_new_command(command, settings): old_command = command.script.split(' ')[0] new_command = get_closest(old_command, get_all_executables()) return ' '.join([new_command] + command.script.split(' ')[1:]) priority = 3000
akaihola/django
tests/modeltests/timezones/tests.py
Python
bsd-3-clause
49,481
0.002466
import datetime import os import sys import time import warnings try: import pytz except ImportError: pytz = None from django.conf import settings from django.core import serializers from django.core.urlresolvers import reverse from django.db import connection from django.db.models import Min, Max from django...
vent = Event.objects.get() self.assertIsNone(event.dt.tzinfo) # django.db.backend.utils.typecast_dt will just drop the # timezone, so a round-trip in the database alters the data (!) # interpret the naive datetime in local time and you get a wrong value self.assertNotEqual(event....
pUnlessDBFeature('supports_timezones') @skipIfDBFeature('needs_datetime_string_cast') def test_aware_datetime_in_other_timezone(self): dt = datetime.datetime(2011, 9, 1, 17, 20, 30, tzinfo=ICT) Event.objects.create(dt=dt) event = Event.objects.get() self.assertIsNone(event.dt.tzi...
hehongliang/tensorflow
tensorflow/python/keras/engine/training.py
Python
apache-2.0
109,170
0.004598
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # 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 applica...
skip_target_weighing_indices): """Sets sample weight related attributes on the model.""" sample_weights, sample_weight_modes = training_utils.prepare_sample_weights( self
.output_names, sample_weight_mode, skip_target_weighing_indices) self.sample_weights = sample_weights self.sample_weight_modes = sample_weight_modes self._feed_sample_weight_modes = [ sample_weight_modes[i] for i in range(len(self.outputs)) if i not in skip_target_weighing_indices ...
uwosh/uwosh.emergency.client
uwosh/emergency/client/importexport.py
Python
gpl-2.0
877
0.010262
import rsa from Products.CMFCore.utils import getToolByName from uwosh.simpleemergency.utils import disable_emergency se_default_profile = 'profile-uwosh.simpleemergency:default' def install(context): if not context.readDataFile('uwosh.emergency.client.txt'): return site = context.getSite()...
al_quickinstaller') if qi.isProductInstalled('uwosh.simpleemergency') or qi.isProductInstalled('uwosh.emergency.master'): raise Exception('You can not install uwosh.simpleemrgency or uwosh.emergency.master on the same site as the client.') portal_setup = getToolByName(site, 'portal_setup') port...
disable_emergency(site) # disable by default
mlecours/netman
netman/api/switch_api.py
Python
apache-2.0
29,194
0.002877
# Copyright 2015 Internap. # # 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 to in writing, so...
umber>/port-mode', view_func=self.set_bond_port_mode, methods=['PUT']) server.add_url_rule('/switches/<hostname>/bonds/<bond_number>/access-vlan', view_func=
self.set_bond_access_vlan, methods=['PUT']) server.add_url_rule('/switches/<hostname>/bonds/<bond_number>/access-vlan', view_func=self.remove_bond_access_vlan, methods=['DELETE']) server.add_url_rule('/switches/<hostname>/bonds/<bond_number>/trunk-vlans', view_func=self.add_bond_trunk_vlan, methods=['PO...
h2oloopan/easymerge
EasyMerge/merger/unparse.py
Python
mit
24,407
0.007211
"Usage: unparse.py <path to source file>" import sys import ast import cStringIO import os # Large float and imaginary literals get turned into infinities in the AST. # We unparse those infinities to INFSTR. INFSTR = "1e" + repr(sys.float_info.max_10_exp + 1) def interleave(inter, f, seq): """Call f on each item ...
print "t1,t2 have different types:",t1.__class__.__n
ame__,",",t2.__class__.__name__ return ("???",t1,t2) def _Module(self, t1,t2): nodes = {} if len(t1.body)!=len(t2.body): return (None, None) for i in range(len(t1.body)): nodes["body["+str(i)+"]"]=[t1.body[i],t2.body[i]] return ([],nodes...
Unifield/ufload
ufload/webdav.py
Python
mit
8,486
0.003889
# -*- coding: utf-8 -*- import cgi import logging import os import uuid from collections import namedtuple import requests from office365.runtime.auth.authentication_context import AuthenticationContext from office365.runtime.client_request import ClientRequest from office365.runtime.utilities.http_method import Htt...
ontext(self.baseurl, ctx_auth) if not ctx_auth.provider.FedAuth or not ctx_auth.provider.rtFa: raise ConnectionFailed(ctx_auth.get_last_error()) else: raise ConnectionFailed(ctx_auth.get_last_error()) def change_oc(self, baseurl, dir): if dir == 'OCA': ...
UF_OCA_msf_geneva_msf_org/' elif dir == 'OCB': dir = '/personal/UF_OCB_msf_geneva_msf_org/' elif dir == 'OCG': dir = '/personal/UF_OCG_msf_geneva_msf_org/' elif dir == 'OCP': dir = '/personal/UF_OCP_msf_geneva_msf_org/' self.baseurl = baseurl + dir ...
basnijholt/holoviews
holoviews/ipython/preprocessors.py
Python
bsd-3-clause
7,474
0.003077
""" Prototype demo: python holoviews/ipython/convert.py Conversion_Example.ipynb | python """ import ast from nbconvert.preprocessors import Preprocessor def comment_out_magics(source): """ Utility used to make sure AST parser does not choke on unrecognized magics. """ filtered = [] for line ...
artswith('%%'): filtered.append(line) return '\n'.join(filtered) def replace_line_magic(source, magic,
template='{line}'): """ Given a cell's source, replace line magics using a formatting template, where {line} is the string that follows the magic. """ filtered = [] for line in source.splitlines(): if line.strip().startswith(magic): substitution = template.format(line=line.r...
nelango/ViralityAnalysis
model/lib/nltk/treeprettyprinter.py
Python
mit
24,360
0.001314
# -*- coding: utf-8 -*- # Natural Language Toolkit: ASCII visualization of NLTK trees # # Copyright (C) 2001-2015 NLTK Project # Author: Andreas van Cranenburgh <A.W.vanCranenburgh@uva.nl> # Peter Ljunglöf <peter.ljunglof@gu.se> # URL: <http://nltk.org/> # For license information, see LICENSE.TXT """ Pretty-pr...
.subtrees(): if len(a) == 0: a.append(len(sentence)) sentence.append(None) elif any(not isinstance(b, Tree) for b in a): for n, b in enumerate(a): if not isinstance(b, Tree): ...
tree, sentence, highlight) def __str__(self): return self.text() def __repr__(self): return '<TreePrettyPrinter with %d nodes>' % len(self.nodes) @staticmethod def nodecoords(tree, sentence, highlight): """ Produce coordinates of nodes on a grid. Obj...
silly-wacky-3-town-toon/SOURCE-COD
toontown/catalog/CatalogNametagItem.py
Python
apache-2.0
3,692
0.002167
import CatalogItem from toontown.toonbase import ToontownGlobals from toontown.toonbase import TTLocalizer from otp.otpbase import OTPLocalizer from direc
t.interval.IntervalGlobal import * from direct.gui.DirectGui import * class CatalogNametagItem(CatalogItem.CatalogItem): sequenceNumber = 0 def makeNewItem(self, nametagStyle, isSpecial = False): self.nametagStyle = nametagStyle self.isSpecial = isSpecial CatalogItem.CatalogItem.makeNe...
dPurchaseLimit(self, avatar): if self in avatar.onOrder or self in avatar.mailboxContents or self in avatar.onGiftOrder or self in avatar.awardMailboxContents or self in avatar.onAwardOrder: return 1 if avatar.nametagStyle == self.nametagStyle: return 1 return 0 def ...
StepicOrg/codejail
codejail/tests/test_jail_code.py
Python
agpl-3.0
11,655
0.000601
"""Test jail_code.py""" import os import shutil import sys import textwrap import tempfile import unittest from nose.plugins.skip import SkipTest from codejail.jail_code import jail_code, is_configured, Jail, configure, auto_configure auto_configure() def jailpy(code=None, *args, **kwargs): """Run `jail_code`...
) self.assertResultOk(re
s) self.assertEqual( res.stdout, "This is doit.py!\nMy args are ['doit.py', '1', '2', '3']\n" ) def test_context_managers(self): first = textwrap.dedent(""" with open("hello.txt", "w") as f: f.write("Hello, second") """) se...
uclouvain/osis
assessments/views/common/score_encoding_progress_overview.py
Python
agpl-3.0
2,568
0.001558
############################################################################## # # OSIS stands for Open Student Information System. It's an application # designed to manage the core business of higher education institutions, # such as universities, faculties, institutes and professional schools. # The core ...
rom osis_role.contrib.views import PermissionRequiredMixi
n class ScoreEncodingProgressOverviewBaseView(PermissionRequiredMixin, CacheFilterMixin, TemplateView): # PermissionRequiredMixin permission_required = "assessments.can_access_scoreencoding" # CacheFilterMixin timeout = 10800 # seconds = 3 hours @cached_property def person(self): re...
jawilson/home-assistant
tests/components/litejet/__init__.py
Python
apache-2.0
1,438
0
"""Tests for the litejet component.""" from homeassistant.components import scene, switch from homeassistant.components.litejet import DOMAIN from homeassistant.const import CONF_PORT from homeassistant.helpers import entity_registry as er from tests.common import MockConfigEntry async def async_init_integration( ...
OMAIN, f"{entry.entry_id}_1",
suggested_object_id="mock_scene_1", disabled_by=None, ) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() return entry
ewheeler/rapidpro
temba/orgs/tasks.py
Python
agpl-3.0
1,662
0.001203
from __future__ import absolute_import, unicode_literals import time from datetime import timedelta from djcelery_transactions import task from django.utils import timezone from redis_cache import get_redis_connection from .models import CreditAlert, Invitation, Org, TopUpCredits @task(track_started=True, name='sen...
task(invitation_id): invitation = Invitation.objects.get(pk=invitation_id) invitation.send_email() @task(track_started=True, name='send_alert_email_task') def send_alert_email_task(alert_id): alert = CreditAlert.objects.get(pk=alert_id) alert.send_email()
@task(track_started=True, name='check_credits_task') def check_credits_task(): CreditAlert.check_org_credits() @task(track_started=True, name='calculate_credit_caches') def calculate_credit_caches(): """ Repopulates the active topup and total credits for each organization that received messages in th...
lizardsystem/flooding
gislib/vectors.py
Python
gpl-3.0
6,539
0.000153
# (c) Nelen & Schuurmans. GPL licensed, see LICENSE.rst. # -*- coding: utf-8 -*- from __future__ import print_function from __future__ import unicode_literals from __future__ import absolute_import from __future__ import division from osgeo import ogr import numpy as np from gislib import projections def array2p...
extent(self): """ Return x1, y1, x2, y2. """ x1, x2, y1, y2 = self.geometry.Ge
tEnvelope() return x1, y1, x2, y2 @property def envelope(self): """ Return polygon representing envelope. """ x1, x2, y1, y2 = self.geometry.GetEnvelope() points = (x1, y1), (x2, y1), (x2, y2), (x1, y2), (x1, y1) return points2polygon(points) @property def size(...
madedotcom/photon-pump
test/connection/fake_server.py
Python
mit
1,317
0
import asyncio class FakeProtocol(asyncio.Protocol): def __init__(self, name): self.name = name self.connections_made = 0 self.data = [] self.connection_errors = [] self.expected_received = 0 self.expected = 0 self.connected = asyncio.Future() self.c...
print("%s: connection made" % self.name) self.transport = transport self.connections_made += 1 self.connected.set_result(None) def data_received(self, data): print("%s: data received" % self.name) self.data.append(data) if self.expectation and not self.expectati...
esult(None) def connection_lost(self, exc): print("%s: connection lost" % self.name) self.closed.set_result(None) self.connected = asyncio.Future() self.connection_errors.append(exc) def expect(self, count): self.expected_received = 0 self.expected = count ...
daanwierstra/pybrain
pybrain/rl/environments/twoplayergames/capturegame.py
Python
bsd-3-clause
9,101
0.007911
__author__ = 'Tom Schaul, tom@idsia.ch' from random import choice from scipy import zeros from twoplayergame import TwoPlayerGame # TODO: undo operation class CaptureGame(TwoPlayerGame): """ the capture game is a simplified version of the Go game: the first player to capture a stone wins! Pass moves are f...
os[0], pos[1]-1)) if pos[0] < self.size -1: res.append((pos[0]+1, pos[1])) if pos[0] > 0: res.append((pos[0]-1, pos[1])) return res def _setStone(s
elf, c, pos): """ set stone, and update liberties and groups. """ self.b[pos] = c merge = False self.groups[pos] = self.size*pos[0]+pos[1] freen = filter(lambda n: self.b[n] == self.EMPTY, self._neighbors(pos)) self.liberties[self.groups[pos]] = set(freen) for n i...
yaelelmatad/EtsyApiTest
etsy/_core.py
Python
gpl-3.0
10,263
0.005164
from __future__ import with_statement from contextlib import closing import simplejson as json import urllib2 from urllib import urlencode import os import re import tempfile import time from _multipartformdataencode import encode_multipart_formdata missing = object() class TypeChecker(object): def __init__(s...
may be passed. If method_cache is explicitly set to None, no method table caching is performed. If the parameter is not passed, a file in $HOME/.etsy is used if that directory exists. Otherwise, a temp file is used. """ if not getattr(self, 'api_url', None): ...
pi_url.endswith('/'): raise AssertionError('api_url should not end with a slash.') if not getattr(self, 'api_version', None): raise AssertionError('API object should define api_version') if api_key and key_file: raise AssertionError('Keys can be read from a file or ...
nickmeharry/django-mysql
tests/testapp/test_operations.py
Python
bsd-3-clause
11,174
0
# -*- coding:utf-8 -*- from __future__ import ( absolute_import, division, print_function, unicode_literals ) from unittest import SkipTest import pytest from django.db import connect
ion, migrations, models, transaction from django.db.migrations.state impo
rt ProjectState from django.test import TransactionTestCase from django.test.utils import CaptureQueriesContext from django_mysql.operations import ( AlterStorageEngine, InstallPlugin, InstallSOName ) from django_mysql.test.utils import override_mysql_variables def plugin_exists(plugin_name): with connection...
mbox/django
tests/migrations/test_state.py
Python
bsd-3-clause
12,382
0.001131
from django.apps.registry import Apps from django.db import models from django.db.migrations.state import ProjectState, ModelState, InvalidBasesError from django.test import TestCase class StateTests(TestCase): """ Tests state construction, rendering and modification by operations. """ def test_creat...
ass Meta: app_label = "migrations"
apps = new_apps class Book(models.Model): title = models.CharField(max_length=1000) author = models.ForeignKey(Author) contributors = models.ManyToManyField(Author) class Meta: app_label = "migrations" apps = new_apps...
idea4bsd/idea4bsd
python/testData/copyPaste/multiLine/IndentInnerFunction2.dst.py
Python
apache-2.0
55
0.090909
def foo(se
lf): x = 1 y = 2 <care
t> z = 3
bussiere/pypyjs
website/demo/home/rfk/repos/pypy/lib-python/2.7/uuid.py
Python
mit
21,448
0.001958
r"""UUID objects (universally unique identifiers) according to RFC 4122. This module provides immutable UUID objects (class UUID) and the functions uuid1(), uuid3(), uuid4(), uuid5() for generating version 1, 3, 4, and 5 UUIDs as specified in RFC 4122. If all you want is a unique ID, you should probably call uuid1() ...
ID constructor accepts five possible forms: a similar string of hexadecimal digits, or a tuple of six integer fields (with 32-bit, 16-bit, 16-bit, 8-bit, 8-bit, and 48-bit values respectively) a
s an argument named 'fields', or a string of 16 bytes (with all the integer fields in big-endian order) as an argument named 'bytes', or a string of 16 bytes (with the first three fields in little-endian order) as an argument named 'bytes_le', or a single 128-bit integer as an argument named 'int'. ...
Comp-UFSCar/neural-networks-2
mutant-networks/experiments/cifar-genetic/cifar-genetic.py
Python
mit
2,889
0.000346
"""Training and Predicting Cifar10 with Mutant Networks. The networks mutate their architecture using genetic algorithms. Author: Lucas David -- <ld492@drexel.edu> Licence: MIT License 2016 (c) """ import logging import artificial as art import numpy as np import tensorflow as tf from artificial.utils.experiments i...
nv def run(self): try: self.env_.live(n_cycles=1) finally: answer = self.env_.current_state if answer: tf.logging.info('train and validation loss after %i epochs: ' '(%f, %f)', self.consts.n_epochs, ...
_ == '__main__': print(__doc__, flush=True) logging.basicConfig(level=logging.DEBUG) logging.getLogger('tensorflow').propagate = False (ExperimentSet(MutateOverCifar10Experiment) .load_from_json(arg_parser.parse_args().constants) .run())
grischa/django-tastypie
tests/alphanumeric/tests/http.py
Python
bsd-3-clause
4,725
0.002751
import httplib try: import json except ImportError: # < Python 2.6 from django.utils import simplejson as json from testcases import TestServerTestCase class HTTPTestCase(TestServerTestCase): def setUp(self): self.start_test_server(address='localhost', port=8001) def tearDown(self): s...
{ 'meta': { 'previous': None, 'total_count': 6, 'offset': 0, 'limit': 20, 'next': None }, 'objects': [ { 'updated': '2010-03-30T20:05:00', 'resourc...
i': '/api/v1/products/11111/', 'name': 'Skateboardrampe', 'artnr': '11111', 'created': '2010-03-30T20:05:00' }, { 'updated': '2010-05-04T20:05:00', 'resource_uri': '/api/v1/products/76123/...
13lcp2000/pythonExercises
script3.py
Python
mit
414
0.014493
def ContinueCurse(): test_note_1 = (int(input("Type first Test Value: "))) test_note_2 = (int(input("Type Second Test Value: "))) tmp_note = (((test_note_1 + test_note_2)/2)*0.6)
if ((3 - tmp_note)/0.4) <= 5: print "Keep Studying :D" else: print "C
ancel course :/" print "=== Program Finished ===" print " ==== Starting the -ContinueCourse- Script ====" ContinueCurse()
cloudbase/neutron-virtualbox
neutron/tests/unit/test_linux_dhcp.py
Python
apache-2.0
56,280
0.000018
# Copyright 2012 OpenStack Foundation # All Rights Reserved. # # 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 requ...
'dddddddd-dddd-dddd-dddd-dddddddddddd')] mac_address = '00:00:0f:dd:dd:dd' def __init__(self): self.extra_dhcp_opts = [] class FakePortMultipleAgents2(object): id = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa' admin_state_up = True device_owner = constants.DEVI...
.168.0.6', 'dddddddd-dddd-dddd-dddd-dddddddddddd')] mac_address = '00:00:0f:ee:ee:ee' def __init__(self): self.extra_dhcp_opts = [] class FakeV4HostRoute(object): destination = '20.0.0.1/24' nexthop = '20.0.0.1' class FakeV4HostRouteGateway(object): des...
Azure/azure-sdk-for-python
sdk/compute/azure-mgmt-compute/azure/mgmt/compute/v2021_07_01/operations/_operations.py
Python
mit
5,336
0.003936
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
t instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~azure.mgm
t.compute.v2021_07_01.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, des...
emilio-simoes/qt-rest-client
tools/test-service/server.py
Python
gpl-3.0
4,688
0.009812
#!/usr/bin/env python import os import json from flask import Flask, abort, jsonify, request, g, url_for from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.httpauth import HTTPBasicAuth from passlib.apps import custom_app_context as pwd_context from itsdangerous import (TimedJSONWebSignatureSerializer ...
t user: # try to authenticate with username/password user = User.query.filter_by(username=username_or_token).first() if not user or not user.verify_password(password): return False g.user = user return True @app.route('/api/users', methods=['POST']) def new_user(): user...
ort(400) # missing arguments if User.query.filter_by(username=username).first() is not None: abort(400) # existing user user = User(username=username) user.hash_password(password) db.session.add(user) db.session.commit() return (jsonify({'username': user.username}), 201, ...
offlinehacker-playground/sltv
sltv/input/xinput.py
Python
gpl-2.0
2,132
0.001876
# -*- coding: utf-8 -*- # Copyright (C) 2010 Holoscopio Tecnologia # Author: Marcelo Jorge Vieira <metal@holoscopio.com> # Author: Thadeu Lima de Souza Cascardo <cascardo@holoscopio.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as pu...
caps = gst.caps_from_string( "video/x-raw-rgb, framerate=%d/%d" % (num, den) ) self.
capsfilter.set_property("caps", caps)
lisiyuan656/Gesture-Recognizer
preprocessing/__init__.py
Python
gpl-2.0
250
0
from preprocessing.img_segmenting import ImgSegmenter from preprocessing.NoiseRemoval import NoiseRemoval from preprocessing.im
ageScaler import imageScaler noise_remover = NoiseRemoval() img_scaler = imageScaler() segmenter = ImgSegmenter(5)
aligoren/pyalgo
ruler_algorithm.py
Python
mit
1,641
0.014016
import sys def ruler_algorithm(n1, n2): """ Ruler Algorithm yani Cetvel Algoritmasi. Verilen aralik ikiye bolundugunde her alt parca da devamli olarak ikiye bolunmekte. Alt parcalarin uzunlugu onceden verilen degere erisinceye kadar devam edilir. """ dot = (n1+n2)/2 if a
bs((n2-n1)) < 2: return print("[%s]" % dot, end=' ') ruler_algorithm(n1, dot) ruler_algorithm(dot, n2) def ruler_algorithm_main(): sys.stdout.write("Ruler Algorithm
: ") ruler_algorithm(0,20000) ruler_algorithm_main() # profiling result for 20.000 numbers # profile: python -m profile ruler_algorithm.py """ 147457 func tion calls (114691 primitive calls) in 0.998 seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(func...
caspar/KentLab
scripts/GMRplot3.py
Python
mit
1,307
0.026014
import sys import numpy as np import matplotlib.pyplot as plt import math #from datetime import datetime #import os # load csv file PATH = "./data/" FILENAME = "Sample_F5_21_2_1mA_trial2"; #TIMESTAMP = datetime.now().strftime('%D_%H:%M') #OUTPUT = ''+ os.path.splitext(FILENAME)[0] + '_' + TIMESTAMP + '.png' field, res...
plt.show(); plt.savefig((OUTPUT), dpi=None, facecolor='w', edgecolor='w', orientation='p
ortrait', papertype=None, format=None, transparent=False, bbox_inches=None, pad_inches=0.1, frameon=None) plt.close(fig)
vivisect/synapse
synapse/tests/test_lib_fifo.py
Python
apache-2.0
9,331
0.000214
from synapse.tests.common import * import synapse.lib.fifo as s_fifo class FifoTest(SynTest): def test_fifo_nack_past(self): with self.getTestDir() as dirn: conf = { 'dir': dirn, 'file:maxsize': 1024, 'window:max': 4, 'window:mi...
aught) # the next should *not* make it in the window fifo.put('he
he') fifo.put('haha') fifo.put('hoho') self.len(4, fifo.wind.dequ) self.false(fifo.wind.caught) # ack 0 should shrink the window, but not fill() self.true(fifo.ack(sent[0][0])) self.len(3, fifo.wind.dequ) ...
apatriciu/OpenStackOpenCL
computeOpenCL/nova/nova/OpenCL/OpenCLClientException.py
Python
apache-2.0
173
0.017341
import exceptions class OpenCLClientException(
Exception): def __init__(self, value): self.value = value def __str__(self): return repr(se
lf.value)
gista/django-geoshortcuts
geoshortcuts/tests/test_app/models.py
Python
gpl-2.0
1,245
0.036948
from django.contrib.gis.db import models class TestTable(models.Model): field0 = models.CharField(max_length = 50) def __unicode__(self): return self.field0 class TestPoint(models.Model): field0 = models.CharField(max_length = 50) field1 = models.IntegerField() field2 = models.DateTimeField(
) field3 = models.FloatField() field4 = models.BooleanField() field5 = models.ForeignKey(TestTable) the_geom = models.PointField(srid=102067) objects = models.GeoManager() def __unicode__(self): return self.field0 class TestLineString(models.Model): field0 = models.CharField(max_length = 50) field1 = model...
eom = models.LineStringField() objects = models.GeoManager() def __unicode__(self): return self.field0 class TestPolygon(models.Model): field0 = models.CharField(max_length = 50) field1 = models.IntegerField() field2 = models.DateTimeField() field3 = models.FloatField() field4 = models.BooleanField() field5...
yw374cornell/e-mission-server
emission/analysis/configs/config_utils.py
Python
bsd-3-clause
967
0.004137
import logging import emission.storage.timeseries.abstract_timeseries as esta import emission.core.wrapper.entry as ecwe def get_last_entry(user_id, time_query, config_key): user_ts = esta.TimeSeries.get_time_series(user_id) # get the list of overrides for this time range. This should be non zero # o...
an override since the last run, which needs to be # saved back into the cache. config_overrides = list(user_ts.find_entries([config_key], time_query)) logging.debug("Found %d user overrides for user %s" % (len(config_overrides), user_id)) if len(config_overrides) == 0: logging.warning("No user ...
ted by the write_ts, we can take the last value coe = ecwe.Entry(config_overrides[-1]) logging.debug("last entry is %s" % coe) return (coe.data, coe.metadata.write_ts)
ttycl/keyhub
keyhub/wsgi.py
Python
apache-2.0
46
0
from fl
ask import Flask app = Flask('keyhub'
)
ryandoherty/RaceCapture_App
autosportlabs/racecapture/views/dashboard/widgets/graphicalgauge.py
Python
gpl-3.0
864
0.013889
import
kivy kivy.require('1.9.1') from utils import kvFind from kivy.core.window import Window from kivy.properties import NumericProperty from autosportlabs.racecapture.views.dashboard.widgets.gauge import CustomizableGauge class GraphicalGauge(CustomizableGauge): _gaugeView = None gauge_size = NumericProperty(0)
def _update_gauge_size(self, size): self.gauge_size = size def __init__(self, **kwargs): super(GraphicalGauge, self).__init__(**kwargs) def on_size(self, instance, value): width = value[0] height = value[1] size = width if width < height else height ...
kuropatkin/lte
src/virtual-net-device/bindings/callbacks_list.py
Python
gpl-2.0
1,101
0.00545
callback_classes = [ ['bool', 'ns3::Ptr<ns3::NetDevice>', 'ns3::Ptr<ns3::Packet const>', 'unsigned short', 'ns3::Address const&', 'ns3::Address const&', 'ns3::NetDevice::PacketType', 'ns3::empty', 'ns3::empty', 'ns3::empty'], ['bool', 'ns3::Ptr<ns3::NetDevice>', 'ns3::Ptr<ns3::Packet const>', 'unsigned short', ...
ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], ['void', 'ns3::Ptr<ns3::NetDevice>'
, 'ns3::Ptr<ns3::Packet const>', 'unsigned short', 'ns3::Address const&', 'ns3::Address const&', 'ns3::NetDevice::PacketType', 'ns3::empty', 'ns3::empty', 'ns3::empty'], ['unsigned char', 'ns3::Ptr<ns3::QueueItem>', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'n...
RomuloOliveira/django-dojo
minitwitter/app/views.py
Python
mit
544
0.005515
from django.shortcuts import render from django.http import HttpResponse, Http404 from minitwitter.app.models import Tweet def index(request): last_tweets = Tweet.objects.all().order_
by('-timestamp')[:15] return render(request, 'tweets/index.html', {'last_tweets': last_tw
eets}) def show(request, user, tweet_id): try: tweet = Tweet.objects.get(id=tweet_id, user=user) except Tweet.DoesNotExist, e: raise Http404('Tweet not found') else: return HttpResponse('Here\'s your tweet: ' + str(tweet))
warehouseman/trello-swagger-generator
processDefaults.py
Python
mit
931
0.025779
#!/usr/bin/env python from bs4 import BeautifulSoup # Constants DEFAULT = "Default:" # Methods def processDefaults(soup, swagger): default = '' for string in soup.code.stripped_strings : default = ' and'.join(
', '.join(string.split(',')).rsplit(',', 1)) swagger['default'] = default if "true" in default : swagger['default'] = True if "false" in default : swagger['default'] = False return # - - - - - - - - - - - # Main routine (for testing) def main(): from test.testdataDefaults import tes...
: print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") soup = BeautifulSoup(frag) # if idx == 1 : if idx != -1 : processDefaults(soup.body.li, swagger) print "swagger = {}".format(swagger) idx = idx + 1 print(">>~~~~~~~~~~~~~~~~~~~~~~~~~<<") if __name__ == "__main__": main()
tinloaf/home-assistant
homeassistant/components/sensor/elkm1.py
Python
apache-2.0
7,872
0
""" Support for control of ElkM1 sensors. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/sensor.elkm1/ """ from homeassistant.components.elkm1 import ( DOMAIN as ELK_DOMAIN, create_elk_entities, ElkEntity) DEPENDENCIES = [ELK_DOMAIN] async def asy...
discovery_info=None): """Create the Elk-M1 sensor platform.""" if discovery_info is None: return elk = hass.data[ELK_DOMAIN]['elk'] entities = create_elk_entities( hass, elk.coun
ters, 'counter', ElkCounter, []) entities = create_elk_entities( hass, elk.keypads, 'keypad', ElkKeypad, entities) entities = create_elk_entities( hass, [elk.panel], 'panel', ElkPanel, entities) entities = create_elk_entities( hass, elk.settings, 'setting', ElkSetting, entities) ...
ronas/PythonGNF
Eduardo/L01.ExeSeq01.py
Python
gpl-3.0
25
0.04
print (
"Hello World
!!")
nuagenetworks/vspk-python
vspk/v6/nuavatar.py
Python
bsd-3-clause
9,831
0.009155
# -*- coding: utf-8 -*- # # Copyright (c) 2015, Alcatel-Lucent Inc, 2017 Nokia # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyrigh...
"creationDate", attribute_type=str, is_required=False, is_uniq
ue=False) self.expose_attribute(local_name="owner", remote_name="owner", attribute_type=str, is_required=False, is_unique=False) self.expose_attribute(local_name="external_id", remote_name="externalID", attribute_type=str, is_required=False, is_unique=True) self.expose_attribute(local_name="type...
uclaros/QGIS
python/plugins/sagaprovider/SagaProviderPlugin.py
Python
gpl-2.0
1,562
0
# -*- coding: utf-8 -*- """ *************************************************************************** sagaproviderplugin.py --------------------- Date : May 2021 Copyright : (C) 2021 by Alexander Bruy Email : alexander dot bruy at gmail dot com **********...
e License, or * * (at your option) any later version. * * * *******************
******************************************************** """ __author__ = 'Alexander Bruy' __date__ = 'May 2021' __copyright__ = '(C) 2021, Alexander Bruy' from qgis.core import QgsApplication, QgsRuntimeProfiler with QgsRuntimeProfiler.profile('Import SAGA Provider'): from sagaprovider.SagaAlgorithmProvider im...
NeuroDataDesign/seelviz
scripts/clearity/__init__.py
Python
apache-2.0
5,716
0.013821
#!/usr/bin/python #-*- coding:utf-8 -*- __author__ = 'david' import numpy as np import nibabel as nib import resources as rs # from vispy import app from plot import Canvas import matplotlib.pyplot as plt import gc np.random.seed() class Clarity(object): def __init__(self,token,imgfile=None,pointsfile=None): ...
("Threshold should be within [0,1).") if not 0 < sample <= 1: raise ValueError("Sample rate should be within (0,1].") if self._img is None: raise ValueError("Img haven't loaded, please call loadImg() first.") total = self._shape[0]*self._shape[1]*self._shape[2] p...
%d\nmax=%f\nthreshold=%f\nsample=%f"\ %(self._token,total,self._max,threshold,sample)) print("(This will take couple minutes)") # threshold filt = self._img > threshold * self._max x, y, z = np.where(filt) v = self._img[filt] if optimize: self.d...
hsoft/dgeq-rdf
freebase_pull.py
Python
bsd-3-clause
2,455
0.004481
import argparse import os.path as op from datetime import datetime from rdflib import Graph, Literal from rdflib.namespace import RDF, OWL from ns import ns_property, ns_type from util import query_freebase def node2mid(node): s = node.toPython() return '/m/' + s.split('.')[-1] def pull_genelection(graph, ke...
ot op.exists('freebase_api_key'): print("You need a Freebase API key in the file 'freebase_api_key' to run this script.") return if not op.exists(rdfpath): print("Invalid path: %s" % rdfpath) return if domain not in PULL_FUNCTIONS:
print("Invalid domain: %s. Valid domains are %s" % (domain, ', '.join(PULL_FUNCTIONS.keys()))) return with open('freebase_api_key', 'rt') as fp: key = fp.read() graph = Graph() print("Loading RDF...") graph.parse(rdfpath) print("Starting linking operation for domain %s" % domain...
CityOfNewYork/NYCOpenRecords
tests/conftest.py
Python
apache-2.0
2,096
0.001431
# -*- coding: utf-8 -*- """ConfigTest Module This module handles the setup for running tests agains the OpenRecords application. .. _Flask Tutorial: http://flask.pocoo.org/docs/1.0/tutorial/ """ import sys import os import pytest from app import create_app, db as _db from flask import Flask from flask_sqlalchemy ...
"""Retrieve an instance of the Flask test_client. .. _Flask Test Client: http://flask.pocoo.org/docs/1.0/api/#flask.Flask.test_client Args: app (Flask): Instance of the Flask application Returns: app.test_client (Flask.test_client): Returns a client used to test the Flask appli...
est.yield_fixture(scope='session') def db(app: Flask): """ Create all of the database tables and yield an instance of the database. Args: app (Flask): Instance of the flask application. Yields: db (SQLAlchemy): Instance of the SQLAlchemy DB connector """ _db.app = app _db.cr...
jongha/stock-ai
modules/valuations/per.py
Python
mit
540
0.015385
#-*- coding: utf-8 -*- import os import pandas as pd import config import pandas import re import math from modules.val
uations.valuation import Valuation # 현 EPS 과거 5년 PER 평균을 곱한 값 class PER(Valuation): def __init__(self, valuation): data = valuation.get_data() json = valuation.get_json() Valuation.__init__(self, data, json) self.set_json('PER', self.valuate()) def valuate(self): try: json = self.get_j...
n None
wes342/EasyDevStudio
scripts/RomOther.py
Python
apache-2.0
18,124
0.008828
#Copyright 2012 EasyDevStdio , wes342 # #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 to in writing, ...
fileinput.input(Aroma, inplace=1): if line.startswith('ini_set("rom_name", "'): processing_change = True else: if processing_change: print r'ini_set("rom_name", "' + name.text + r'");' processing_chan...
if line.startswith(' "You are about to Install <b>'): processing_change = True else: if processing_change: print r' "You are about to Install <b>' + name.text + r'</b>. \n\n"+' processing_change = False pri...
estansifer/mape
src/thermo.py
Python
mit
10,645
0.007797
import math import scipy.optimize as opt log = math.log exp = math.exp small = 1e-20 # unitless T0 = 1 # K Tcrit = 650 # K zero_C = 273.15 # K p0 = 1 # Pa atm = 101325 # Pa bar = 100000 ...
+ log(y_s) + y_s * ell else: return ((cd + y * cv) * log(T / T0) - (1 + y) * log(p_star / p0) + log (y_s
) + (y_s - y) * ell) def compute_T_unsat(y, p, s): Ms = compute_M(y) * s if y < small: return T0 * exp((Md * s + log(p / p0)) / cd) else: return T0 * exp( (Ms + (1 + y) * log(p / p0) - (1 + y) * log(1 + y) + y * log(y)) / (cd + y * cv)...
home-assistant/home-assistant
homeassistant/components/mqtt/number.py
Python
apache-2.0
8,276
0.000967
"""Configure number in a device through MQTT topic.""" from __future__ import annotations import functools import logging import voluptuous as vol from homeassistant.components import number from homeassistant.components.number import ( DEFAULT_MAX_VALUE, DEFAULT_MIN_VALUE, DEFAULT_STEP, NumberEntity...
hass, async_add_entities, config, config_entry=None, discovery_data=None ): """Set up the MQTT number.""" async_add_entities([MqttNumber(hass, config, config_entry, discovery_data)]) class MqttNumber(MqttEntity, NumberEntity, RestoreEntity):
"""representation of an MQTT number.""" _entity_id_format = number.ENTITY_ID_FORMAT _attributes_extra_blocked = MQTT_NUMBER_ATTRIBUTES_BLOCKED def __init__(self, hass, config, config_entry, discovery_data): """Initialize the MQTT Number.""" self._config = config self._optimistic =...
hmpf/nav
python/nav/web/alertprofiles/views.py
Python
gpl-3.0
87,463
0.00104
# -*- coding: utf-8 -*- # # Copyright (C) 2007, 2008, 2011 Uninett AS # # This file is part of Network Administration Visualized (NAV). # # NAV is free software: you can redistribute it and/or modify it under the # terms of the GNU General Public License version 3 as published by the Free # Software Foundation. # # Thi...
try: active_profile = account.ge
t_active_profile() except ObjectDoesNotExist: active_profile = None if not active_profile: subscriptions = None else: periods = TimePeriod.objects.filter(profile=active_profile).order_by('start') subscriptions = alert_subscriptions_table(periods) # Get information about...
mc2014/anvil
setup.py
Python
apache-2.0
2,199
0
#!/usr/bin/env python # Copyright (C) 2014 Yahoo! Inc. All Rights Reserved. # # 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...
ine = line.strip() if not line or line.startswith("#"): continue requires.appe
nd(line) return requires setuptools.setup( name='anvil', description='A tool to forge raw OpenStack into a productive tool', author='OpenStack Foundation', author_email='anvil-dev@lists.launchpad.net', url='http://anvil.readthedocs.org/', long_description=open("README.rst", 'rb').read(), ...
krishauser/Klampt
Python/python2_version/klampt/math/symbolic_linalg.py
Python
bsd-3-clause
9,854
0.032576
"""Defines the symbolic functions: - norm(x): returns the L-2 norm of a vector - norm2(x): returns the squared L-2 norm of a vector - norm_L1(x): returns the L-1 norm of a vector - norm_Linf(x): returns the L-infinity norm of a vector - norm_fro(A): returns the Frobeneus norm of a matrix - distance(x,y): returns the L...
nction('norm_Linf',lambda x:np.lin
alg.norm(x,ord=_inf),returnType='N') norm_fro = Function('norm_fro',np.linalg.norm,['A'],returnType='N') norm2_fro = Function('norm2_fro',lambda x:np.linalg.norm(x)**2,['A'],returnType='N') distance = Function('distance',norm(_x-_y),['x','y'],returnType='N') distance2 = Function('distance2',norm2(_x-_y),['x','y'],retur...
sjaoudi/hangout-app
transcribe_streaming.py
Python
mit
8,465
0.000236
#!/usr/bin/python # Copyright (C) 2016 Google Inc. # # 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 ...
DEADLINE_SECS = 60 * 3 + 5 SPEECH_SCOPE = 'https://www.googleapis.com/auth/cloud-platform' def make_channel(host, port): """Creates a secure channel with auth credentials from the environment.""" # Grab application default cred
entials from the environment credentials, _ = google.auth.default(scopes=[SPEECH_SCOPE]) # Create a secure channel using the credentials. http_request = google.auth.transport.requests.Request() target = '{}:{}'.format(host, port) return google.auth.transport.grpc.secure_authorized_channel( ...
TravelModellingGroup/TMGToolbox
TMGToolbox/src/analysis/traffic/Export_Count_Station_Location.py
Python
gpl-3.0
5,176
0.013717
''' Copyright 2015 Travel Modelling Group, Department of Civil Engineering, University of Toronto This file is part of the TMG Toolbox. The TMG Toolbox 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 Fou...
escription] ''' #---VERSION HISTORY
''' 0.0.1 Created 0.1.1 Created on 2015-03-13 by David King ''' import inro.modeller as _m import csv import traceback as _traceback from contextlib import contextmanager from contextlib import nested _mm = _m.Modeller() net =_mm.scenario.get_network() _util = _mm.module('tmg.common.utilities') _tmg...
R3v1L/django-landingpages
landingpages/admin.py
Python
mit
813
0.012315
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Landing pages administratio
n module =============================================== .. module:: landingpages.admin :platform: Django :synopsis: Landing pages administration module .. moduleauthor:: (C) 2015 Oliver Gutiérrez """ # Django imports from djan
go.contrib import admin # Site tools imports from sitetools.admin import BaseModelAdmin # Application imports from landingpages.models import LandingPage class LandingPageAdmin(BaseModelAdmin): """ Landing page administration class """ list_display = ('name','url','language','template',) ...
dooma/Events
events/controllers/event.py
Python
mit
6,395
0.003911
__author__ = 'Călin Sălăgean' from events.models.event import Event from events.repositories.event import EventRepository from events.repositories.person_event import PersonEventRepository from events.repositories.person import PersonRepository class EventController(): def __init__(self): ''' Even...
y with given id :param array: :param id: :return: dictionary :raise: ValueError if id is not found ''' for elem in array: try: elem[id] return elem except KeyError: continue raise ValueEr
ror @staticmethod def find_dict2(array, id): ''' Find dictionary with given id :param array: :param id: :return: dictionary :raise: ValueError if id is not found ''' if not len(array): raise ValueError try: array[...
oli-kester/advanced-av-examples
amp-osc-lv2/.waf-1.8.5-3556be08f33a5066528395b11fed89fa/waflib/Tools/qt5.py
Python
gpl-2.0
14,329
0.056878
#! /usr/bin/env python # encoding: utf-8 # WARNING! Do not edit! http://waf.googlecode.com/git/docs/wafbook/single.html#_obtaining_the_waf_file try: from xml.sax import make_parser from xml.sax.handler import ContentHandler except ImportError: has_xml=False ContentHandler=object else: has_xml=True import os,sys f...
ode+'.qrc') t=self.create_task('qm2rcc',qmnodes,rcnode) k=create_rcc_task(self,t.outputs[0]) self.link_task.inputs.append(k.outputs[0]) lst=[] for flag in self.to_list(self.env['CXXFLAGS']): if len
(flag)<2:continue f=flag[0:2] if f in('-D','-I','/D','/I'): if(f[0]=='/'): lst.append('-'+flag[1:]) else: lst.append(flag) self.env.append_value('MOC_FLAGS',lst) @extension(*EXT_QT5) def cxx_hook(self,node): return self.create_compiled_task('qxx',node) class rcc(Task.Task): color='BLUE' run_str='$...
pinax/django-user-accounts
makemigrations.py
Python
mit
904
0
#!/usr/bin/env python import os import sys import django from django.conf import settings DEFAULT_SETTINGS = dict( INSTALLED_APPS=[ "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sites", "account", "account.tests" ], MIDDLEWARE_CLASSES=[], ...
if not settings.configured: s
ettings.configure(**DEFAULT_SETTINGS) django.setup() parent = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, parent) django.core.management.call_command( "makemigrations", "account", *args ) if __name__ == "__main__": run(*sys.argv[1:])
attente/snapcraft
snapcraft/tests/test_plugin_gulp.py
Python
gpl-3.0
5,389
0
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*- # # Copyright (C) 2016 Canonical Ltd # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in the h...
'type': 'string'}, 'source': {'type': 'string'}, 'source-branch': {'default': '', 'type': 'string'}, 'source-subdir': {'default': None, 'type': 'string'}, 'source-tag': {'default': '', 'type:': 'string'}, 'source-type': {'default': '', 'ty...
'disable-parallel': {'default': False, 'type': 'boolean'}}, 'pull-properties': ['source', 'source-type', 'source-branch', 'source-tag', 'source-subdir', 'node-engine'], 'build-properties': ['disable-parallel', 'gulp-tasks'], 'required': ...
annayqho/TheCannon
TheCannon/find_continuum_pixels.py
Python
mit
3,465
0.003463
import numpy as np LARGE = 200. SMALL = 1. / LARGE def _find_contpix_given_cuts(f_cut, sig_cut, wl, fluxes, ivars): """ Find and return continuum pixels given the flux and sigma cut Parameters ---------- f_cut: float the upper limit imposed on the quantity (fbar-1) sig_cut: float ...
variances, parallel to fluxes frac: float fraction of pixels in spectrum to be found as continuum ranges: list, array starts and ends indicating location of chunks in array Returns ------ contmask: numpy ndarray, boolean True indicates continuum pixel """ contmask ...
sk[start:stop] = _find_contpix( wl[start:stop], fluxes[:,start:stop], ivars[:,start:stop], frac) return contmask
Psychedelic-Engineering/sleep-machine
hardware/sensors.py
Python
mit
2,531
0.034374
import os import time import datetime import logging import gzip from hardware.channel import Channel """ Sensor Class - ggf. Logfile als Datasource per Parameter - Logging in eigene Klasse oder Scheduler """ class Sensor: def __init__(self, device):
self.initialized = False self.device = device self.initSensor() self.logging = False self.buffer = "" self.lastTime = 0 def initSensor(self): self.initialized = False try: header = self.device.sendCommand("?") header = header.split(";") logging.info("Initsensor: %s", header) self.initChannel...
channels = [] for sensor in header: if sensor != "": name, params = sensor.split(":") num, min, max = params.split(",") num = int(num) min, max = float(min), float(max) for i in range(num): self.channels.append(Channel(name, min, max, 100)) self.initialized = True def readData(self): ...
niavlys/kivy
kivy/config.py
Python
mit
27,319
0.000146
''' Configuration object ==================== The :class:`Config` object is an instance of a modified Python ConfigParser. See the `ConfigParser documentation <http://docs.python.org/library/configparser.html>`_ for more information. Kivy has a configuration file which determines the default settings. In order to cha...
creen`: int or string, one of 0, 1, 'fake' or 'auto' Activate fullscreen. If set to `1`, a resolution of `width` times `height` pixels will be used. If set to `auto`, your current display's resolution will be used instead. This is mos
t likely what you want. If you want to place the window in another display, use `fake` and adjust `width`, `height`, `top` and `left`. `width`: int Width of the :class:`~kivy.core.window.Window`, not used if `fullscreen` is set to `auto`. `height`: int Height of the :clas...
asgardproject/asgard-calendar
events/sitemaps.py
Python
bsd-3-clause
251
0.047809
from django.contrib.sitemaps import Sitemap fro
m events.model
s import Event class EventsSitemap(Sitemap): changefreq = "never" priority = 1.0 def items(self): return Event.objects.public() def lastmod(self, obj): return obj.date_modified
jeromecc/doctoctocbot
src/registration/views.py
Python
mpl-2.0
1,823
0.003291
import logging from django_registration.backends.one_step.views import RegistrationView from django.urls import reverse from django.contrib.auth import authenticate, get_user_model, login from django_registration import signals from django.conf import settings from invite.models import CategoryInvitation logger=loggin...
ey=key) except CategoryInvitation.DoesNotExist: return if registration_email != invitation.email: return new_user = form.save() new_user = authenticate( **{ User.USERNAME_FIELD: new_user.get_username(), "password": form....
lf.__class__, user=new_user, request=self.request ) return new_user def registration_allowed(self): """ Override this to enable/disable user registration, either globally or on a per-request basis. """ key = self.request.session.get(settings.INVITATION_SESSIO...
sfromm/snmpryte
lib/netspryte/db/influx.py
Python
gpl-3.0
4,597
0.00261
# Written by Stephen Fromm <stephenf nero net> # Copyright (C) 2016-2017 University of Oregon # # This file is part of netspryte # # netspryte 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 o...
client.switch_database(dbname) def influxdb_list_databases(client): dbs = client.get_list_database() return [ x['name'] for x in dbs ] def influxdb_write(client, data, ts=time.time()):
points = list() data_class = data.measurement_class.name data_title = data.presentation.title data_id = data.name data_host = data.host.name for k, v in list(data.items()): if k.startswith('_'): continue if hasattr(v, 'prettyPrint'): v = v.prettyPrint() ...
Piotr95/Yummy_Pies
UserManagement/urls.py
Python
mit
359
0.002786
from django.conf.urls import url from dja
ngo.contrib import admin from UserManagement import views from django.contrib.auth import views as auth_views app_name = 'UserManagement' urlpatterns = [ url(r'^register$', views.register, name="register"), url(r'^login$', views.login, name='login'), url(r'^logout_user/$', views.log_ou
t, name='logout'), ]
eunchong/build
third_party/buildbot_8_4p1/buildbot/manhole.py
Python
bsd-3-clause
11,523
0.001909
# This file is part of Buildbot. Buildbot 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, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without eve...
lass makeTelnetProtocol: # this curries the 'portal' argument into a later call to # TelnetTransport() def __init__(self, portal): self.portal = portal def __
call__(self): auth = telnet.AuthenticatingTelnetProtocol return telnet.TelnetTransport(auth, self.portal) class _TelnetRealm: implements(portal.IRealm) def __init__(self, namespace_maker): self.namespace_maker = namespace_maker def requestAvatar(self, avatarId, *interfaces): ...
brkt/brkt-cli
brkt_cli/test_version.py
Python
apache-2.0
2,893
0
# Copyright 2017 Bracket Computing, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). # You may not use this file except in compliance with the License. # A copy of the License is located at # # https://github.com/brkt/brkt-cli/blob/master/LICENSE # # or in the "license" file...
now = datetime.datetime.now(tz=iso8601.UTC) dt = now - datetime.timedelta(hours=25) version.set_last_version_check_time(cfg, dt=dt) self.assertTrue(version.is_version_check_needed(cfg)) # Set to 23 hours ago. dt = now - datetime.timed
elta(hours=23) version.set_last_version_check_time(cfg, dt=dt) self.assertFalse(version.is_version_check_needed(cfg))
Feandil/webapp-config
WebappConfig/selinux.py
Python
gpl-2.0
4,699
0.005533
#!/usr/bin/python -O # # /usr/sbin/webapp-config # Python script for managing the deployment of web-based # applications # # Originally written for the Gentoo Linux distribution # # Copyright (c) 1999-2007 Authors # Released under v2 of the GNU GPL # # ===========================================...
{}'.format(policy, self.package_name, self.vhost_hostname)) except IOError:
OUT.die('"semodule" was not found, please check you SELinux installation') shutil.rmtree(temp_dir) @staticmethod def filename_re_escape(string): return re.sub('\.', '\.', string)
bitkeeper/python-opcua
tests/tests_server.py
Python
lgpl-3.0
27,210
0.00294
import unittest import os import shelve import time from tests_common import CommonTests, add_server_methods from tests_xml import XmlTests from tests_subscriptions import SubscriptionTests from datetime import timedelta, datetime from tempfile import NamedTemporaryFile import opcua from opcua import Server from opcu...
add_server_methods(cls.srv) cls.srv.start() cls.opc = cls.srv cls.discovery = Server() cls.discovery.set_application_uri("urn:freeopcua:python:discovery") cls.discovery.set_
endpoint('opc.tcp://localhost:{0:d}'.format(port_discovery)) cls.discovery.start() @classmethod def tearDownClass(cls): cls.srv.stop() cls.discovery.stop() def test_discovery(self): client = Client(self.discovery.endpoint.geturl()) client.connect() try: ...
hellwen/mytrade
mytrade/form/widgets.py
Python
bsd-3-clause
8,982
0.001113
from jinja2 import escape from flask.globals import _request_ctx_stack from flask import json from wtforms import widgets from mytrade.utils import _, get_url class Select2Widget(widgets.Select): """ `Select2 <https://github.com/ivaynberg/select2>`_ styled select widget. You must include select2...
tringField': kwarg
s['data-type'] = 'text' elif subfield.type == 'TextAreaField': kwargs['data-type'] = 'textarea' kwargs['data-rows'] = '5' elif subfield.type == 'BooleanField': kwargs['data-type'] = 'select' # data-source = dropdown options kwargs['data-source'...
PhilHarnish/forge
src/data/meta.py
Python
mit
1,361
0.011756
import collections import typing from typing import TypeVar Key = TypeVar('Key') class Meta(collections.OrderedDict, typing.MutableMapping[Key, float]): def __init__(self, *args, **kwargs) -> None: self._smallest = float('inf') self._largest = 0 self._ordered =
True super(Meta, self).__init__(*args, **kwargs) def __setitem__(self, key: Key, value: float) -> None: if key in self and self[key]
== value: raise AssertionError('Redundant assignment: %s = %s' % (key, value)) if value > self._smallest: self._ordered = False else: self._smallest = value if value > self._largest: self._largest = value super(Meta, self).__setitem__(key, value) self._changed() def items...
Shopify/shopify_python
tests/functional/blank_line_after_class_required.py
Python
mit
178
0
# pylint:dis
able=missing-docstring,invalid-name,too-few-public-methods,old-style-class class SomeClass: # [blank-line-after-class-required] def __init__(self):
pass
anhstudios/swganh
data/scripts/templates/object/tangible/loot/tool/shared_recording_rod_broken.py
Python
mit
461
0.045553
#### NOTICE: THIS FILE
IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Tangible() result.template = "object/tangible/loot/tool/shared_recording_rod_broken.iff" result.attribute_template_id
= -1 result.stfName("item_n","recording_rod_broken") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
kingmotley/SickRage
sickrage/recompiled/tags.py
Python
gpl-3.0
869
0.002301
import re # Resolutions resolution = re.compile(r'(?P<vres>4320|2160|1080|720|480|360)(?P<scan>[pi])', re.I) # Sources tv = re.compile(r'([sph]d).?tv|tv(rip|mux)', re.I) dvd = re.compile(r'(?P<hd>hd)?dvd(?P<rip>rip|mux)?', re.I) web = re.compile(r'(web(?P<type>rip|mux|hd|.?dl|\b
))', re.I) bluray = re.compile(r'(blue?-?ray|b[rd](?:rip|mux))', re.I) sat = re.compile(r'(dsr|satrip)', re.I) itunes = re.compile(r'(itunes)', re.I) netflix = re.compile(r'netflix(hd|uhd)', re.I) # Codecs avc = re.compile(r'([xh].?26[45])', re.I) xvid = re.compile(r'(xvid|divx)', re.I) mpeg = re.compile(r'(mpeg-?2)',...
080p)', re.I) anime_bluray = re.compile(r'(blue?-?ray|b[rd](?:rip|mux)|(?:\b|_)bd(?:\b|_))', re.I)
lauhuiyik/same-page
src/lib/utils.py
Python
mit
1,770
0.015819
########## import os import web import pylibmc from etherpad_lite import EtherpadLiteClient from jinja2 import Environment,FileSystemLoader ########## def render(template_name, **context): """ Jinja2 Template Handler This function renders the html template Jinja2 style Extra parameters for substituti...
27.0.0.1'], binary = True, behaviors = { 'ketama': True, 'tcp_nodelay': True, }) ########## """ Initializes etherpad instance """ etherpad = EtherpadLiteClient(base_params = { ...
90ba9ef18ac274c' }) """ Configuration for db """ db = web.database(user = 'guanhao97', dbn = 'postgres', db = 'same_page', pw = '55popo')
lukasklein/django-newsletter2go
newsletter2go/backends.py
Python
bsd-3-clause
1,590
0.001258
# -*- coding: utf-8 -*- from django.core.mail.backends.base import BaseEmailBackend from django.core.mail.message import sanitize_address from django.conf import settings import
requests import logging logger = logging.getLogger(__name__) class Newsletter2GoEmailBackend(BaseEmailBackend): n2g_api_endpoint = 'h
ttps://www.newsletter2go.de/de/api/send/email/' def send_messages(self, emails): """ Sends one or more EmailMessage objects and returns the number of email messages sent. """ if not emails: return num_sent = 0 for email in emails: if...
yuxng/Deep_ISM
FCN/lib/setup.py
Python
mit
5,133
0.003702
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- import os from os.path import join as pjoin import numpy as np from dis...
e method into the class self._compile = _compile # run the customize_compiler class custom_build_ext(build_ext): def build_extensions(self): customize_compiler_for_nvcc(self.compiler) build_ext.build_extensions(self) ext_modules = [ Extension('normals.gpu_normals', ['normals/compu...
['lib64']], libraries=['cudart'], language='c++', runtime_library_dirs=[CUDA['lib64']], # this syntax is specific to this build system # we're only going to use certain compiler args with nvcc and not with gcc # the implementation of this trick is in customize_compiler() ...
futurepr0n/Books-solutions
Python-For-Everyone-Horstmann/Chapter3-Decisions/P3.22.py
Python
mit
2,601
0.001924
# Write a program that prompts for the day and month of the user’s birthday and then # prints a horoscope. Make up fortunes for programmers, like this: # Please enter your birthday. # month: 6 # day: 16 # Gemini are experts at figuring out the behavior of complicated programs. # You feel where bugs...
put()) sign = "" if month == 1: if day <= 19: sign = "Capricorn" else: sign = "Aquarius" elif month == 2: if day <= 18: sign = "Aquari
us" else: sign = "Pisces" elif month == 3: if day <= 20: sign = "Pisces" else: sign = "Aries" elif month == 4: if day <= 19: sign = "Aries" else: sign = "Taurus" elif month == 5: if day <= 20: sign = "Taurus" else: sign = "Gemini...
JohnSpeno/owney
owney/conf/settings.py
Python
mit
635
0.006299
from django.conf import settings _TRACKING_USPS_URL = 'http://trkcnfrm1.smi.usps.com/PTSInternetWeb/InterLabelInquiry.do?origTrackNum=' T
RACKING_USPS_URL = getattr(settings, 'OWNEY_USPS_TRACKING_URL', _TRACKING_USPS_URL) _USPS_API_URL = 'http://production.shippingapis.com/ShippingAPI.dll' USPS_API_URL = getattr(settings, 'OWNEY_USPS_API_URL', _USPS_API_URL) _USPS_API_USERID = 'Set your USPS API userid here' USPS_API_USERID = getattr(settings, 'OWNEY_U...
CKING_CS_URL = getattr(settings, 'OWNEY_TRACKING_CS_URL', _CS_URL)
Huyuwei/tvm
python/tvm/contrib/debugger/debug_runtime.py
Python
apache-2.0
8,948
0.000894
# 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 u...
le : GraphModuleDebug Debug Runtime graph module that can be used to execute the graph. """
if not isinstance(graph_json_str, string_types): try: graph_json_str = graph_json_str._tvm_graph_json() except AttributeError: raise ValueError("Type %s is not supported" % type(graph_json_str)) try: fcreate = get_global_func("tvm.graph_runtime_debug.create") ...
zhanqxun/cv_fish
pythonwin/pywin/Demos/dyndlg.py
Python
apache-2.0
2,568
0.030763
# dyndlg.py # contributed by Curt Hagenlocher <chi@earthlink.net> # Dialog Template params: # Parameter 0 - Window caption # Parameter 1 - Bounds (rect tuple) # Parameter 2 - Window style # Parameter 3 - Extended style # Parameter 4 - Font tuple # Parameter 5 - Menu name # Parameter 6 - Window class # Dialo...
T]) dlg.append([130, "New &Warehouse:", -1, (7, 29, 69, 9), cs | win32con.SS_LEFT]) s = win32con.WS_TABSTOP | cs # dlg.append([131, None, 130, (5, 40, 110, 48), # s | win32con.LBS_NOTIFY | win32con.
LBS_SORT | win32con.LBS_NOINTEGRALHEIGHT | win32con.WS_VSCROLL | win32con.WS_BORDER]) dlg.append(["{8E27C92B-1264-101C-8A2F-040224009C02}", None, 131, (5, 40, 110, 48),win32con.WS_TABSTOP]) dlg.append([128, "OK", win32con.IDOK, (124, 5, 50, 14), s | win32con.BS_DEFPUSHBUTTON]) s = win32con.BS_PUSHBUTTON | s d...
arunchaganty/presidential-debates
third-party/stanza/stanza/research/output.py
Python
mit
770
0
import sys def output_results(results, split_id='results', output_stream=None): ''' Log `results` readably to `output_stream`, with a header containing `split_id`. :param results: a dictionary of summary statistics from an evaluation :type results: dict(str -> object) :param str split_id: an...
.stdout output_stream.write('----- %s -----\n' % split_id) for name
in sorted(results.keys()): output_stream.write('%s: %s\n' % (name, repr(results[name]))) output_stream.flush()
plotly/plotly.py
packages/python/plotly/plotly/graph_objs/scattergeo/marker/_colorbar.py
Python
mit
78,668
0.000953
from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType import copy as _copy class ColorBar(_BaseTraceHierarchyType): # class properties # -------------------- _parent_path_str = "scattergeo.marker" _path_str = "scattergeo.marker.colorbar" _valid_props = { "bgco...
(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: aliceblue, antiquewhite, aqua, aquamarine, azure, beige, bisque, black, blanchedalmond, blue, blueviolet, brown, bur...
cornsilk, crimson, cyan, darkblue, darkcyan, darkgoldenrod, darkgray, darkgrey, darkgreen, darkkhaki, darkmagenta, darkolivegreen, darkorange, darkorchid, darkred, darksalmon, darkseagreen, darkslateblue, darkslategray, darkslategrey, ...
Hackplayers/Empire-mod-Hpys-tests
lib/modules/powershell/management/lock.py
Python
bsd-3-clause
3,056
0.008835
from lib.common import helpers class Module: def __init__(self, mainMenu, params=[]): self.info = { 'Name': 'Invoke-LockWorkStation', 'Author': ['@harmj0y'], 'Description': ("Locks the workstation's display."), 'Background' : False, 'OutputE...
ule on.', 'Required' : True, 'Value' : '' } } # save off a copy of the mainMenu object to access external functionality
# like listeners/agent handlers/etc. self.mainMenu = mainMenu for param in params: # parameter format is [Name, Value] option, value = param if option in self.options: self.options[option]['Value'] = value def generate(self): ...
XTAv2/Enigma2
lib/python/Screens/InstallWizard.py
Python
gpl-2.0
5,974
0.026783
from Screens.Screen import Screen from Components.ConfigList import ConfigListScreen, ConfigList from Components.ActionMap import ActionMap from Components.Sources.StaticText import StaticText from Components.config import config, ConfigSubsection, ConfigBoolean, getConfigListEntry, ConfigSelection, ConfigYesNo, Config...
settings-*'}) else: self.ipkg.startCmd(cmd, pkg) def ipkgCallback(self, event, param): if event == IpkgComponent.EVENT_DONE: if self.index == InstallWizard.STATE_UPDATE: config.misc.installwiz
ard.ipkgloaded.value = True elif self.index == InstallWizard.STATE_CHOISE_CHANNELLIST: if self.state == 0: self.ipkg.startCmd(IpkgComponent.CMD_INSTALL, self.pkg) self.state = 1 return else: config.misc.installwizard.channellistdownloaded.value = True eDVBDB.getInstance().reloadBouqu...
swxs/web
cloudplat/center/Models/Tools_todo_Model.py
Python
mit
1,457
0.004844
# -*- coding: utf-8 -*- from django.db import models from ..Models import * from center.Exceptions.ModelsExceptions import * class Tools_todo(models.Model): STATUS_TYPES = ( (1, u'New'), (2, u'Doing'), (3, u'Waiting'), (4, u'Done'), ) SPECIES_TYPES = ( (1, u'Task')...
super(Tools_todo, self).save(*args, **kwargs) except: raise createException(self.model_name) def update(self, *args, **kwargs):
try: super(Tools_todo, self).update(*args, **kwargs) except: raise updateException(self.model_name) def delete(self, *args, **kwargs): try: super(Tools_todo, self).delete(*args, **kwargs) except: raise updateException(self.model_name)
cooperlees/peerme
peerme/main.py
Python
bsd-2-clause
3,155
0.001585
import asyncio import click import logging import sys import time from os.path import expanduser from . import config as peerme_config from . import peeringdb_mysql from . import peeringdb_api from . import euroix_json from .commands.generate import GenerateConfigCli from .commands.discover import DiscoverCli from .co...
format=('[%(asctime)s] %(levelname)s: %(message)s (%(filename)s:%(lineno)d)'), level=log_level, ) return debug @click.group(context_settings=CLICK_CONTEXT_SETTINGS) @click.option( '-c', '-
-config', default='{}/.peerme.conf'.format(expanduser('~')), help='Config File Location - Default: ~/.peerme.conf', ) @click.option( '-d', '--debug', is_flag=True, help='Turn on verbose logging', callback=_handle_debug, ) @click.option( '--refresh-data', is_flag=True, help='Fetch...
cs-chan/fuzzyDCN
prune_neon/transformation/cost.py
Python
bsd-3-clause
979
0.003064
from neon.transforms.cost import Cost class MulticlsSVMLoss(Cost): def __init_
_(self, delta=1.): self.delta = delta def __call__(self, y, t): T = self.be.empty_like(y) T[:] = self.be.max(y * t, axis=0) # T = self.be.array(self.be.max(y * t, axis=0).asnumpyarray(), y.shape[0], axis=0) margin = self.be.square(self.be.maximum(0, y - T + self.delta)) * 0....
be.maximum(0, y - T + self.delta) / self.be.bsz class L1SVMLoss(Cost): def __init__(self, C=10): self.C = C def __call__(self, y, t): return self.C * self.be.sum(self.be.square(self.be.maximum(0, 1 - y * (t * 2 - 1)))) * 0.5 / y.shape[0] def bprop(self, y, t): return - self.C * (...
theouf/CMStools
CMS_Conf.py
Python
gpl-2.0
6,570
0.059209
#!/usr/bin/python # coding=utf-8 ''' @authors: David,Erwan, Theo version Python 2.7 and 3.4 This prog permits configure Precidot and Novar according to 2 input files. first one is created from eagle by a module "testeur_UM.pnp" and contains components and pins x & y coordonates second one is not yet defin...
d':[0,5,0,0]}, 'SOT23':{'Lab':'8','submission':223,'tool':2,'speed':[0,4,0,0]}, 'SOT89':{'Lab':'9','submission':223,'tool':2,'speed':[0,4,0,0]}, 'SOT143':{'Lab':'10','submission':148,'tool':3,'speed':[0,4,0,0]}, 'SOT194':{'Lab':'11','submission':148,'tool':3,'speed':[0,4,0,0]}, ...
ab':'13','submission':148,'tool':3,'speed':[0,4,0,0]}, 'SOD87':{'Lab':'14','submission':148,'tool':3,'speed':[0,4,0,0]}, '0402':{'Lab':'15','submission':400,'tool':2,'speed':[0,4,0,0]}, '0603':{'Lab':'16','submission':400,'tool':2,'speed':[0,4,0,0]}, '0805':{'Lab':'17','submissio...
maeotaku/leaf_recognition_sdk
src/Features/Morphology.py
Python
mit
3,273
0.018637
import numpy as np import cv2 import math from Contours import * #Basic measures def calcLeafMinAndMaxContourPoints(binaryImage, contours=None): if (contours==None): contours = getContours(binaryImage) xs = contours[0][:,0][:,0] ys = contours[0][:,0][:,1] minx = np.min(xs) miny = np.min(ys)...
leaf def calcLeafDiameter(binaryImage, contours=None, draw=False): return None #Proportions def calcLeafAspectRatio(binaryImage, width=None, length=None, contours=None, draw=False): if (width==None or length==None): length, width = calcLeafWidthAndLength(binaryImage, contours, draw) if (draw): ...
yImage else: return float(length) / float(width), binaryImage #differ between the shape and a circle, also called Form Factor def calcLeafRoundness(binaryImage, area=None, perimeter=None, draw=False): if (area==None): area= calcLeafArea(binaryImage) if (perimeter==None): perimete...
lowdev/alfred
robot/robotFactory.py
Python
gpl-3.0
721
0.006935
from .stt import ApiRobot from .stt import BingRobot from .stt import WatsonRobot from .stt import WitaiRobot from .stt import GoogleRobot class RobotFactory: @staticmethod def produce(config, speaker, actions): configSTT = config['stt'] if config
STT == 'bing': return BingRobot(config['bing'], speaker, actions) if configSTT == 'watson': return WatsonRobot(config['watson-stt'], speaker, actions) if configSTT == 'witai': return WitaiRobot(config['witai-stt'], speaker, actions) i
f configSTT == 'google': return GoogleRobot(config['google-stt'], speaker, actions) return ApiRobot(config['apiai'], speaker, actions)
satra/NiPypeold
nipype/externals/pynifti/funcs.py
Python
bsd-3-clause
2,788
0.001435
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: ''' Processor functions for images ''' import numpy as np def squeeze_image(img): ''' Return image, remove axes length 1 at end of image shape For example, an image may have shape (10,20,30,1,1). ...
, 1, 2) ''' klass = img.__class__ shape = img.get_shape()
slen = len(shape) if slen < 4: return klass.from_image(img) for bdim in shape[3::][::-1]: if bdim == 1: slen-=1 else: break if slen == len(shape): return klass.from_image(img) shape = shape[:slen] data = img.get_data() data = data.reshape...
EmreAtes/spack
var/spack/repos/builtin/packages/py-flask-socketio/package.py
Python
lgpl-2.1
2,117
0.000945
############################################################################## # Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
: """Flask-SocketIO gives Flask applications access to low latency bi-directional communications between the clients and the server. The client-side application can use any of the SocketIO official clients libraries in Javascript, C++, Java and Swift, or any compatible client to establish a permanen...
edocs.io" url = "https://pypi.io/packages/source/F/Flask-SocketIO/Flask-SocketIO-2.9.6.tar.gz" version('2.9.6', 'bca83faf38355bd91911f2f140f9b50f') depends_on('py-setuptools', type='build') depends_on('py-flask@0.9:', type=('build', 'run')) depends_on('py-python-socket...
Aloomaio/googleads-python-lib
examples/adwords/v201809/advanced_operations/add_multi_asset_responsive_display_ad.py
Python
apache-2.0
5,311
0.005649
#!/usr/bin/env python # # Copyright 2018 Google 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
""" from googleads import adwords import requests AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE' def UploadImageAsset(client, url): """Uploads the image from the specified url.
Args: client: An AdWordsClient instance. url: The image URL. Returns: The ID of the uploaded image. """ # Initialize appropriate service. asset_service = client.GetService('AssetService', version='v201809') # Download the image. image_request = requests.get(url) # Create the image asset....
sychan/RRoller
lib/RRoller/RRollerImpl.py
Python
mit
4,705
0.003826
# -*- coding: utf-8 -*- #BEGIN_HEADER # The header block is where all import statments should live import os import uuid from KBaseReport.KBaseReportClient import KBaseReport #END_HEADER class RRoller: ''' Module Name: RRoller Module Description: A KBase module: RRoller This sample module con...
te">'] html_report_lines += ['<a target="_blank" href="{}">{}</a>'.format(report_url, report_url)] html_report_lines += ['</body>'] html_report_lines += ['</html>']
reportObj['direct_html'] = "\n".join(html_report_lines) SERVICE_VER = 'release' report = KBaseReport(self.callbackURL, token=ctx['token'], service_ver=SERVICE_VER) report_info = report.create_extended_report(reportObj) output = {'report_name': report_info['name'], ...