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
robotics-at-maryland/qubo
src/autonomy/src/tortuga_states.py
Python
mit
3,069
0.018573
#! /usr/bin/env python # State machine for tortuga 2016 competition # States given by kanga can be found at: imgur.com/C5KLSCJ import roslib; roslib.load_manifest('smach') import rospy import smach import smach_ros #TODO class gate_search(smach.State): def __init__(self): smach.State.__init__(self, ...
'not_found':'sonar_search'}, remapping={'sonar_position_vector':'sonar_position_vector'}) smach.StateMachine.add('sonar_travel', sonar_travel(), transitions={'centered':'search_bin_cover', ...
MTG/essentia
test/src/unittests/temporal/test_effectiveduration.py
Python
agpl-3.0
2,995
0.004341
#!/usr/bin/env python # Copyright (C) 2006-2021 Music Technology Group - Universitat Pompeu Fabra # # This file is part of Essentia # # Essentia 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 (FSF), e...
ertAlmostEqual(EffectiveDuration(thresholdRatio=1.)(input), 100/44100.0) def test30Sec(self): input = [randint(41, 100) for x in range(44100*30)] self.assertAlmostEqual(EffectiveDuration()(input), 30) def test15SecOf30Sec(self): input1 = [randint(41, 100...
input1[0] = 100 # to ensure that at least one element is 100 input2 = [randint(0, 39) for x in range(44100*15)] input = input1 + input2 self.assertAlmostEqual(EffectiveDuration()(input), 15) def testNegative20SecOf40Sec(self): # Note: this test assumes the thresholdRatio is 40%...
mysql/mysql-utilities
mysql/utilities/command/rpl_admin.py
Python
gpl-2.0
45,372
0.000242
# # Copyright (c) 2010, 2016, Oracle and/or its affiliates. All rights reserved. # # 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; version 2 of the License. # # This program is distributed in th...
# Decompose GTID set into a list of single transactions. gtid_items = gtid_set_itemize(gtids_to_skip) dryrun_mark = '(dry run) ' if dryrun else ''
print("
google-code/ampatu
models/db.py
Python
agpl-3.0
4,254
0.010343
# -*- coding: utf-8 -*- ######################################################################### ## This scaffolding model makes your app work on Google App Engine too ######################################################################### if request.env.web2py_runtime_gae: # if running on Google App E...
use OpenID, Facebook, MySpace, Twitter, Linkedin, etc. ## register with janrain.com, uncomment and customize following # from gluon.contrib.login_methods.rpx_account import RPXAccount # auth.settings.actions_disabled=['register','change_password','request_reset_password'] # auth.settings.login_form = RPXAccount(reques...
################################################################ crud.settings.auth = None # =auth to enforce authorization on crud ######################################################################### ## Define your tables below (or better in another model file) for example ## ## >>> db.defi...
sinraf96/electrum
qa/rpc-tests/bip9-softforks.py
Python
mit
9,959
0.004519
#!/usr/bin/env python3 # Copyright (c) 2015 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. from test_framework.test_framework import ComparisonTestFramework from test_framework.util import * from test_...
dexError ('key:"%s" not found' % key) def test_BIP(self, bipName, activated_version, invalidate, invalidatePostSignature, bitno): # generate some coins for later self.coinbase_blocks = self.nodes[
0].generate(2) self.height = 3 # height of the next block to build self.tip = int("0x" + self.nodes[0].getbestblockhash(), 0) self.nodeaddress = self.nodes[0].getnewaddress() self.last_block_time = int(time.time()) assert_equal(self.get_bip9_status(bipName)['status'], 'defined'...
seecr/meresco-lucene
meresco/lucene/composedquery.py
Python
gpl-2.0
11,941
0.003015
## begin license ## # # "Meresco Lucene" is a set of components and tools to integrate Lucene into Meresco # # Copyright (C) 2013-2016, 2019-2021 Seecr (Seek You Too B.V.) https://seecr.nl # Copyright (C) 2013-2014 Stichting Bibliotheek.nl (BNL) http://www.bibliotheek.nl # Copyright (C) 2015-2016, 2019 Koninklijke Bibl...
ationalFilterJson') del _makeProperty def setCoreQuery(self, core, query, filterQueries=None, facets=None): self.cores.add(core) self._qu
eries[core] = query if not filterQueries is None: for filterQuery in filterQueries: self.addFilterQuery(core, filterQuery) if not facets is None: for facet in facets: self.addFacet(core, facet) return self def addFilterQuery(self, core...
googleapis/python-analytics-admin
samples/generated_samples/analyticsadmin_v1alpha_generated_analytics_admin_service_approve_display_video360_advertiser_link_proposal_sync.py
Python
apache-2.0
1,697
0.002946
# -*- coding: utf-8 -*- # Copyright 2022 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
dvertiserLinkProposal_sync] from google.analytics import admin_v1alpha def sample_approve_
display_video360_advertiser_link_proposal(): # Create a client client = admin_v1alpha.AnalyticsAdminServiceClient() # Initialize request argument(s) request = admin_v1alpha.ApproveDisplayVideo360AdvertiserLinkProposalRequest( name="name_value", ) # Make the request response = clien...
dennisding/ether
protocols/game_to_game.py
Python
apache-2.0
472
0.040254
# -*- encoding:utf-8 -*- from network.protocol import pr
otocol, pdef, pret class GameToGame: create_stub_proxy = protocol( pdef('Eid', 'eid'), pdef('St
r', 'name'), pdef('Int', 'gameid'), ) entity_msg = protocol( pdef('Eid', 'eid'), pdef('Bytes', 'data'), ) entity_msg_with_return = protocol( pdef('Eid', 'eid'), pdef('Token', 'token'), pdef('Bytes', 'data') ) entity_msg_return = protocol( pdef('Token', 'token'), pdef('Bytes', 'data'), )
pramodh-bn/learn-data-edx
Week 7/qp.py
Python
unlicense
6,393
0.020178
# -*- coding: utf-8 -*- """ Created on Fri Nov 15 15:55:28 2013 @author: dyanna """ import numpy as np from sklearn.svm import SVC def getSample(pointA, pointB, numberOfPoints): pointList = list(zip(np.random.uniform(-1,1.00,numberOfPoints),np.random.uniform(-1,1.00,numberOfPoints))) sample = np.array([(i[0]...
= it + 1 mismatch = list() for i in sample: #print("point in question ", i , " weight ", w) yy = w[0] + w[1] * i[0] + w[2] * i[1] #print("this is after applying weight to a point ",yy) point = [i[0], i[1], sign(yy)] if any(np
.equal(sample, point).all(1)): #print "point not in sample" if(point[2] == -1): mismatch.append((1, (i[0]), (i[1]))) else: mismatch.append((-1, -(i[0]), -(i[1]))) #print " length ", len(mismatch), " mismatch list ",mismatch ...
yosi-dediashvili/SubiT
src/Settings/Updaters/WinUpdaterHelper.py
Python
gpl-3.0
5,462
0.005859
""" An external application for performing the update after is was downloaded from the net. This file is compiled into an exe file for windows platform and launch when the ApplyUpdate method of WinUpdater is called. The module will extract the zip file if it exists, and execute the update manifest...
E_NAME) if MANIFEST_NAME in zfile.namelist(): PrintOut('There is a manifest in the zip file') manifest_content = zfile.open(MANIFEST_NAME).read() exec(manifest_content) else: PrintOut('No manifest file in update zip') for _file_info in z...
# If the file is the config file, we place it under a different # name in the Settings directory, and call the upgrade() method # of SubiTConfig, and remove it afterwards. if _file_info.filename == _config_path_in_zip: _new_config_file_name = _config_path_in_zi...
Oozemeister/Gypsy
modules/pubmsg/fortunes.py
Python
gpl-2.0
393
0.020356
import random class fortunes: def on_pubmsg(self,
nick, connection, event): message = event.arguments()[0] source = event.source().split('!')[0] if message.startswith(".fortune"): fortunestxt = open("modules/pubmsg/fortunes", 'r') fortuneslist = fortu
nestxt.read().splitlines() response = random.choice(fortuneslist) connection.privmsg(event.target(), response)
Junji110/elephant
elephant/spectral.py
Python
bsd-3-clause
20,790
0.000192
# -*- coding: utf-8 -*- """ Identification of spectral properties in analog signals (e.g., the power spectrum). :copyright: Copyright 2015-2016 by the Elephant team, see AUTHORS.txt. :license: Modified BSD, see LICENSE.txt for details. """ import warnings import numpy as np import scipy.signal import scipy.fftpack a...
ft, 1.0 / fs) if axis != -1: Pxy = np.rollaxis(Pxy, -1, axis) return f, Pxy def welch_psd(signal, num_seg=8, len_seg=None, freq_res=None, overlap=0.5, fs=1.0, window='hanning', nfft=None, detrend='constant', return_onesided=True, scaling='density', axis=-1): """ E...
ity (PSD) of a given AnalogSignal using Welch's method, which works in the following steps: 1. cut the given data into several overlapping segments. The degree of overlap can be specified by parameter *overlap* (default is 0.5, i.e. segments are overlapped by the half of their length...
koodaamo/jetstream
tests/test_jetstream.py
Python
gpl-3.0
392
0.005102
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_jetstream ---------------------------------- Tests for `jetstream` module. """ import unittest from jetstream i
mport jetstream class TestJetstream(unittest.TestCase): def setUp(self): pass def test_something(self): pass def tearDown(self): pass if __name__ == '__main__': unitte
st.main()
adrien-mogenet/opengossip
src/python/analyzer/hierarchical-clustering.py
Python
gpl-3.0
7,280
0.001099
#!/usr/bin/env python # This file is part of OpenGossip. # # This program 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 3 of the License, or (at your # option) any later version. This...
ent number of the value in the map of metadata in 'n' key.""" self.values.append(value) self.counter += 1 if self.values.size > 1: self.orig.write(str(value) + '\n') vector = [ s
elf.values.mean(), self.values.shannon_entropy(), self.values.variance(), self.values.expected_value(), ] metadata = { 'n': self.counter, 'v': value } self.nodes.append(ClusterNode(vec=vector, meta=metadata)) def build_set_rec(self...
rajeevs1992/pyhealthvault
src/healthvaultlib/itemtypes/medication.py
Python
mit
865
0
from lxml import etree from healthvaultlib.util
s.xmlutils import XmlUtils from healthvaultlib.itemtypes.healthrecorditem import HealthRecordItem class Medication(HealthRecordItem): def __init__(self, thing_xml=None): super(Medication, self).__init__() self.type_id = '30cafccc-047d-4288-94ef-643571f7919d' if thing_xml is not None:
self.thing_xml = thing_xml self.parse_thing() def __str__(self): return 'Medication' def parse_thing(self): super(Medication, self).parse_thing() xmlutils = XmlUtils(self.thing_xml) def write_xml(self): thing = super(Medication, self).write_xml() ...
hamish2014/batchOpenMPI
examples/ex3.py
Python
mit
719
0.027816
""" example with 'calls_expected' in addtoBatch used """ import batchOpenMPI def f_mult(x) : return x*2.0 f = batchOpenMPI.batchFunction(f_mult) #creating function wrapper batchOpenMPI.begin
_MPI_loop() # both the workers and the master process run the same code up until here f.addtoBatch(4,calls_expected=4) batchOpenMPI.processBatch() #get the workers to calculate all the inputs res = [f(4),f(4),f(4)] print(res) #another test f.addtoBatch(1) batchOpenMPI.processBatch()
#get the workers to calculate all the inputs res = f(1), f(1) batchOpenMPI.end_MPI_loop(print_stats=True) #releases workers print("*** jobs executed by workers should be 2 ,(5 calls made),jobs uncollected should = 1, jobs_master=1")
Caranarq/01_Dmine
04_Edificaciones/P0406/P0406.py
Python
gpl-3.0
2,794
0.006102
# -*- coding: utf-8 -*- """ Started on mon, apr 23rd, 2018 @author: carlos.arana """ # Librerias utilizadas import pandas as pd import sys module_path = r'D:\PCCS\01_Dmine\Scripts' if module_path not in sys.path: sys.path.append(module_path) from VarInt.VarInt import VarInt from classes.Meta import Meta from Com...
----------------------------------- # Descripciones del Parametro M = Meta M.ClaveParametro = 'P0406' M.NombreParametro = 'Viviendas urbanas en PCU U1
y U2' M.DescParam = 'Numero de viviendas dentro de Perimetros de Contención Urbana tipo U1 o U2, por ciudad' M.UnidadesParam = 'Numero de viviendas' M.TituloParametro = 'VPCU' # Para nombrar la columna del parametro M.PeriodoParam = '2018' M.TipoInt = 1 # Handlings M.ParDtype = 'float' M.T...
deepmind/deepmind-research
catch_carry/trajectories.py
Python
apache-2.0
8,650
0.00659
# Copyright 2020 Deepmind Technologies Limited. # # 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...
the world frame in the specified orientation. """ if prop_proto.shape == mocap_pb2.Prop.BOX: return _get_rotated_bounding_box(prop_proto.size, quaternion)[2] elif prop_proto.shape == mocap_pb2.Prop.SPHERE: return prop_proto.size[0] else: raise NotImplementedError( 'Unsupported prop shap...
"""Mocap trajectory that assumes props start stationary on pedestals.""" def infer_pedestal_positions(self, num_averaged_steps=30, ground_height_tolerance=0.1, proto_modifier=None): proto = self._proto if proto_modifier is not None: proto...
bountyfunding/bountyfunding
bountyfunding/core/payment/paypal_standard.py
Python
agpl-3.0
2,667
0.003
import requests import urllib from bountyfunding.core.config import config from bountyfunding.core.models import db, Payment from bountyfunding.core.const import PaymentGateway from bountyfunding.core.errors import Error from bountyfunding.core.payment import get_paypal_url class PayPalStandardGateway: def cre...
return_url: raise Error('return_url cannot be blank') receiver_email = config[project_id].PAYPAL_RECEIVER_EMAIL args = { "cmd": "_donations", "business": receiver_email, "item_name": "Bounty", "amount": sponsorship.amount, "curren...
"no_note": 1, "no_shipping": 1, "return": return_url, "cancel_return": return_url } redirect_url = get_paypal_url(project_id) + "?" + urllib.urlencode(args) payment = Payment(sponsorship.project_id, sponsorship.sponsorship_id, PaymentGateway.PAYPAL_STANDA...
thenenadx/forseti-security
tests/common/gcp_api/compute_test.py
Python
apache-2.0
1,822
0
# Copyright 2017 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 agreed to in writing, s...
WITHOUT WARRAN
TIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests the Compute client.""" import mock from tests.unittest_utils import ForsetiTestCase from google.cloud.security.common.gcp_api import _base_client ...
gangadhar-kadam/nassimapp
selling/report/customers_not_buying_since_long_time/customers_not_buying_since_long_time.py
Python
agpl-3.0
1,985
0.039798
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import webnotes from webnotes.utils import cint def execute(filters=None): if not filters: filters ={} days_since_last_order = filters.get("days_...
ta:120", "Territory::120", "Customer Group::120", "Number of Order::120", "Total Order Value:Currency:120", "Total Order Considered:Currency:160", "Last Order Amount:Currency:160", "La
st Sales Order Date:Date:160", "Days Since Last Order::160" ]
ujdhesa/unisubs
utils/testeditor.py
Python
agpl-3.0
5,102
0.000392
# -*- coding: utf-8 -*- # Amara, universalsubtitles.org # # Copyright (C) 2013 Participatory Culture Foundation # # 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 #...
ter=False): """Make the HTTP requests to simulate the editor We will use test_factories.dxfp_sample() for the subtitle data. :param language_code: code for the language of these subtitles :param completed: simulate the completed checkbox being set :param save_for_later: simulat...
.subtitle_language(language_code) if existing_language is not None: subtitle_language_pk = existing_language.pk else: subtitle_language_pk = None response_data = self._submit_widget_rpc( 'start_editing', video_id=self.video.video_id, l...
adamcunnington/Flask-API
setup.py
Python
gpl-3.0
1,574
0
#!/usr/bin/env python3 from setuptools import setup, find_packages def get_readme(): with open("README.md") as f: return f.read() setup(name="Flask-API", version="0.1", description=("A library for Flask that provides a basic barebones web " "API to be used and extended.")...
", "Intended Audience :: End Users/Desktop", "License :: OSI Approved :: GNU General Public License v3 (GPLv3)", "Natural Language :: English", "Operating System :: OS Independent", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2....
: Python :: 3.0", "Programming Language :: Python :: 3.1", "Programming Language :: Python :: 3.2", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Topic :: Internet :: WWW/HTTP :: Dynamic Content"], keywords="adamcunnington flas...
Homebrain/Homebrain
homebrain/agents/devicemanager/__init__.py
Python
mit
66
0
# Imp
ort the agent class from .devicemanager import DeviceManager
plotly/python-api
packages/python/plotly/plotly/validators/scatterpolar/_hoverlabel.py
Python
mit
2,061
0.000485
import _plotly_utils.basevalidators class HoverlabelValidator(_plotly_utils.basevalidators.CompoundValidator): def __init__(self, plotly_name="hoverlabel", parent_name="scatterpolar", **kwargs): super(HoverlabelValida
tor, self).__init__( plotly_name=plotly_name, parent_name=paren
t_name, data_class_str=kwargs.pop("data_class_str", "Hoverlabel"), data_docs=kwargs.pop( "data_docs", """ align Sets the horizontal alignment of the text content within hover label box. Has an effect only...
ratschlab/ASP
examples/undocumented/python_modular/evaluation_meansquaredlogerror_modular.py
Python
gpl-2.0
727
0.023384
from tools.load import LoadMatrix from numpy import random lm=LoadMatrix() N = 100 random.seed
(17) ground_t
ruth = abs(random.randn(N)) predicted = abs(random.randn(N)) parameter_list = [[ground_truth,predicted]] def evaluation_meansquaredlogerror_modular(ground_truth, predicted): from shogun.Features import RegressionLabels from shogun.Evaluation import MeanSquaredLogError ground_truth_labels = RegressionLabels(ground...
michaupl/materialsapp
cuts/__init__.py
Python
apache-2.0
76
0.013158
# coding: utf-8 from __future__ im
port unicode_lite
rals DETAIL_TYPE = 'cut'
rafaellc28/Latex2MiniZinc
latex2minizinc/GenIndexingExpression.py
Python
mit
258
0.031008
from GenObj import * class GenIndexingExpres
sion(GenObj): def __init__(self, name, value): super(GenIndexingExpression, self).__init__(name) self.value = value def getValue(self): return self.value def setValue(self, value): self
.value = value
marineam/nagcat
python/snapy/netsnmp/unittests/__init__.py
Python
apache-2.0
6,157
0.001624
# snapy - a python snmp library # # Copyright (C) 2009 ITA Software, Inc. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # version 2 as published by the Free Softw
are Foundation. # # 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 PURPOSE. See the # GNU General Public License for more det
ails. import os import socket import signal import warnings import twisted from twisted.internet import defer, error, process, protocol, reactor from twisted.python import log, versions from twisted.trial import unittest def pick_a_port(): # XXX: Not perfect, there is a race condition between # the close and...
LegNeato/buck
python-dsl/buck_parser/buck.py
Python
apache-2.0
67,707
0.001403
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import with_statement import __builtin__ import __future__ import contextlib import collections from pathlib import Path, PurePath from pywatchman import WatchmanError from .deterministic_set i...
'is_macos', 'is_windows', 'is_freebsd', 'is_unknown', ], ) HostInfoArch = collections.namedtuple( 'HostInfoArch', [ 'is_aarch64', 'is_arm', 'is_armeb', 'is_i386', 'is_mips', 'is_mips64', 'is_mipsel', 'is_mipsel64', ...
_64', ] ) HostInfo = collections.namedtuple('HostInfo', ['os', 'arch']) __supported_oses = { 'darwin': 'macos', 'windows': 'windows', 'linux': 'linux', 'freebsd': 'freebsd', } # Pulled from com.facebook.buck.util.environment.Architecture.java as # possible values. amd64 and arm64 are remapped, b...
splotz90/urh
src/urh/dev/gr/SenderThread.py
Python
gpl-3.0
2,568
0.003115
import select import socket import numpy import numpy as np import time import zmq from urh.dev.gr.AbstractBaseThread import AbstractBaseThread from urh.util.Logger import logger class SenderThread(AbstractBaseThread): MAX_SAMPLES_PER_TRANSMISSION = 65536 def __init__(self, freq, sample_rate, bandwidth, ga...
ile self.current_index < len_data and not self.isInterruptionRequested(): time.sleep(0.1 * (self.samples_per_transmission / self.MAX_SAMPLES_PER_TRANSMISSION)) self.socket.send(self.data[self.current_index:self.current_index + self.samples_per_transmission].tostring()) se...
if self.current_index >= len_data: self.current_iteration += 1 else: continue if self.repeat_endless or self.current_iteration < self.max_repeats: self.current_index = 0 self.current_index = len_data - 1...
ecino/compassion-accounting
account_analytic_attribution/models/__init__.py
Python
agpl-3.0
499
0
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2015-2017 Compassion CH (http://www.compassion.ch) # Releasing children from poverty in Jesus'
name # @author: Emanuel Cino <ecino@compassion.ch> # # The licence is in the file __manifest__.py # ############
################################################################## from . import account_analytic_attribution from . import account_analytic_distribution_line
fpeyre/shinken
shinken/worker.py
Python
agpl-3.0
10,451
0.002871
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2009-2014: # Gabes Jean, naparuba@gmail.com # Gerhard Lausser, Gerhard.Lausser@consol.de # Gregory Starck, g.starck@gmail.com # Hartmut Goebel, h.goebel@goebel-consult.de # # This file is part of Shinken. # # Shinken is free software: you ca...
e(self): return self._process.is_alive() def is_killable(self): return self._mortal and self._idletime > self._timeout def add_idletime(self, time): self._idletime = sel
f._idletime + time def reset_idle(self): self._idletime = 0 def send_message(self, msg): self._c.put(msg) # A zombie is immortal, so kill not be kill anymore def set_zombie(self): self._mortal = False # Get new checks if less than nb_checks_max # If no new checks got ...
victor-lin/npact
virtualenv.py
Python
bsd-3-clause
99,413
0.003128
#!/usr/bin/env python """Create a "virtual" Python installation """ __version__ = "13.1.0" virtualenv_version = __version__ # legacy import base64 import sys import os import codecs import optparse import re import shutil import logging import tempfile import zlib import errno import glob import distutils.sysconfig ...
xe = 'pypy' elif is_jython: expected_exe = 'jython' else: expected_exe = 'python' # Return a mapping of version -> Python executable # Only provided for Windows, where the information in the registry is used if not is_win:
def get_installed_pythons(): return {} else: try: import winreg except ImportError: import _winreg as winreg def get_installed_pythons(): try: python_core = winreg.CreateKey(winreg.HKEY_LOCAL_MACHINE, "Software\\Python\\PythonCore") ...
stvstnfrd/edx-platform
openedx/core/djangoapps/theming/helpers.py
Python
agpl-3.0
10,226
0.002249
""" Helpers for accessing comprehensive theming related variables. This file is imported at startup. Imports of models or things which import models will break startup on Django 1.9+. If you need models here, please import them inside the function which uses them. """ import os import re from logging import getLogge...
h. e.g. '/red-theme/lms/templates/header.html' Returns:
(str): template path with site theme path removed. """ theme = get_current_theme() if not theme: return uri templates_path = "/".join([ theme.theme_dir_name, get_project_root_name(), "templates" ]) uri = re.sub(r'^/*' + templates_path + '/*', '', uri) re...
OpenDataAlex/dataNexus
setup.py
Python
gpl-2.0
1,846
0.001083
__author__ = 'ameadows' import sys from setuptools import setup, find_packages from setuptools.command.test import test as TestCommand import datanexus class Tox(TestCommand): def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True ...
t loaded import tox errcode = tox.cmdline(self.test_args) sys.exit(errcode) setup( name='dataNexus', version=datanexus.__versi
on__, url='https://github.com/OpenDataAlex/dataNexus', license='GNU GENERAL PUBLIC LICENSE Version 3', description='Data source version control and lineage tool.', author='Alex Meadows', author_email='alexmeadows@bluefiredatasolutions.com', packages=find_packages(), install_requires=[ ...
Katharine/ponytone
karaoke/routing.py
Python
mit
328
0.003049
from channels.routing import route from .consumer import party_connected, party_disconnected, party_message karaoke_routing = [ route("websocket.connect", party_connected, path=r"^/party/(?P<party_id>[
a-zA-Z0-9_-]
+)"), route("websocket.receive", party_message), route("websocket.disconnect", party_disconnected) ]
Kaian/guake
guake/tests/test_about.py
Python
gpl-2.0
650
0
# -*- coding: utf-8 -*- # pylint: disable=redefined-outer-name import os import py
test from guake import guake_version from guake.about import AboutDialog @pytest.fixture def dialog(mocker): mocker.patch("guake.simplegladeapp.Gtk.Widget.show_all") try: old_os_environ = os.environ os.environ["LANGUAGE"] = "en_US.UTF-8" ad = AboutDialog() yield ad finally...
(dialog): assert dialog.get_widget("aboutdialog").get_title() == "About Guake"
Synss/pyhard2
pyhard2/driver/_bronkhorst.py
Python
mit
7,674
0.026323
"""FLOW-BUS protocol for Bronkhorst instruments. The protocol is described in the instruction manual number 9.17.027. The implementation uses the `Construct library <http://construct.readthedocs.org/en/latest/>`__. """ from binascii import unhexlify import unittest from construct import * header = Struct("header",...
IfThenElse("value", lambda ctx: ctx["string_length"] is 0, CString(None), # read string_length bytes (PascalString) MetaField(None, lambda ctx:
ctx["string_length"])))) )[type_], Const(String(None, 3), "\x00\x0a\x52") if secured else Pass, Terminator ) error_message = Struct("FLOW-BUS error", Embed(header), Enum(Byte("error"), colon_missing = 1, first_byte = 2, message_length = 3, receiver = 4, comm...
pengzhangdev/PokemonGo-Bot
pokemongo_bot/cell_workers/incubate_eggs.py
Python
mit
11,384
0.002987
from datetime import datetime, timedelta from pokemongo_bot import inventory from pokemongo_bot.human_behaviour import sleep from pokemongo_bot.base_task import BaseTask from pokemongo_bot.worker_result import WorkerResult class IncubateEggs(BaseTask): SUPPORTED_TASK_API_VERSION = 1 last_km_walked = 0 ...
eggs_first) self._apply_incubators(eggs, self.ready_breakable_incubators) return WorkerResult.SUCCESS def _filter_sort_eggs(self, allowed, sorting): eligible_eggs = filter(lambda egg: int(egg["km"]) in allowed, self.eggs)
eligible_eggs.sort(key=lambda egg: egg["km"], reverse=sorting) return eligible_eggs def _apply_incubators(self, available_eggs, available_incubators): for incubator in available_incubators: for egg in available_eggs: if egg["used"] or egg["km"] == -1: ...
StongeEtienne/dipy
dipy/reconst/tests/__init__.py
Python
bsd-3-clause
32
0
# te
sts for re
construction code
t3dev/odoo
addons/test_mass_mailing/tests/test_mail_channel.py
Python
gpl-3.0
2,012
0.003479
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from email.utils import formataddr from odoo.addons.test_mail.tests import common class TestChannelPartnersNotification(common.MockEmails): def _join_channel(self, channel, partners): for partner in partner...
env['mail.c
hannel'].create({ 'name': 'Test', 'description': 'Description', 'alias_name': 'test', 'public': 'public', }) self.test_partner = self.env['res.partner'].create({ 'name': 'Test Partner', 'email': 'test@example.com', }) ...
aschnell/libstorage-ng
integration-tests/partitions/shrink.py
Python
gpl-2.0
645
0.004651
#!/usr/bin/python3 # requirements: partition /dev/sdc1 with size at leas
t 1 GiB from sys import exit from storage import * from storageitu import * set_logger(get_logfile_logger()) environment = Environment(False) storage = Storage(environment) storage.probe() staging = storage.get_staging() print(staging) partition = Partition.find_by_name(staging, "/dev/sdc1") region = partitio...
table().align(region, AlignPolicy_KEEP_START_ALIGN_END) partition.set_region(region) print(staging) commit(storage)
jnaulty/berkeley
python_logger/log_pres_2.py
Python
bsd-3-clause
529
0.028355
#!/usr/bin/python # Creator: Danie
l Wooten # License: GPL # import the python logging utility as log import logging as log # Set the root logger level ( what messages it will print ) log.basicConfig( level = 10 ) # Some sample messages for the root logger log.debug( "This is the debug level reporting in" ) log.info( "This is the info level reporting...
is the critical level reporting in" )
cnobile2012/inventory
inventory/projects/api/views.py
Python
mit
5,580
0.001075
# -*- coding: utf-8 -*- # # inventory/projects/api/views.py # """ Project API Views """ __docformat__ = "restructuredtext en" import logging from decimal import Decimal from django.contrib.auth import get_user_model from rest_framework.generics import ( ListCreateAPIView, RetrieveUpdateDestroyAPIView, RetrieveUp...
gs.DEFAULT_RENDERER_CLA
SSES) def get_serializer_class(self): serializer = None if self.request.version == Decimal("1"): serializer = InventoryTypeSerializerVer01 # elif self.request.version == Decimal("2"): # serializer = InventoryTypeSerializerVer02 return serializer class Inven...
kafana/ubik
lib/ubik/fab/filemap.py
Python
gpl-3.0
3,975
0.005283
# Copyright 2012 Lee Verberne <lee@blarg.org> # # 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. # # This program is dis...
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/licenses/>. import json import os, os.path import shutil as sh i...
kludgery maintains compatibility of this file with fabric 0.9, # but it is only possible because no remote calls are made in this file try: from fabric.api import lcd as cd except ImportError: from fabric.api import cd from ubik import builder, packager # filemap copies files directly from source to root, the...
evanthebouncy/nnhmm
mnist_haar/data.py
Python
mit
2,672
0.026946
import numpy as np import pywt from scipy.misc import imresize from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) X_L = 10 L = 14 N_BATCH = 50 OBS_SIZE = 30 # ---------------------------- helpers def vectorize(coords): retX, retY = np.zeros([L]...
en variable X # get a single thing out img, _x = get_img_class() imgs.append(img) # add to x x.append(_x[0]) # generate new observation _new_ob_coord, _new_ob_lab = gen_O(img)
_new_ob_x, _new_ob_y = vectorize(_new_ob_coord) new_ob_x.append(_new_ob_x) new_ob_y.append(_new_ob_y) new_ob_tf.append(_new_ob_lab) # generate observations for this hidden variable x for ob_idx in range(OBS_SIZE): _ob_coord, _ob_lab = gen_O(img) _ob_x, _ob_y = vectorize(_ob_coord) ...
wschaeferB/autopsy
InternalPythonModules/android/googlemaplocation.py
Python
apache-2.0
6,752
0.004443
""" Autopsy Forensic Browser Copyright 2016-2018 Basis Technology Corp. Contact: carrier <at> sleuthkit <dot> org 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...
ckboardArtifact from org.sleuthkit.datamodel import BlackboardAttribute from org.sleuthkit.dat
amodel import Content from org.sleuthkit.datamodel import TskCoreException from org.sleuthkit.datamodel.Blackboard import BlackboardException from org.sleuthkit.datamodel.blackboardutils import GeoArtifactsHelper from org.sleuthkit.datamodel.blackboardutils.attributes import GeoWaypoints from org.sleuthkit.datamodel.bl...
aldenjenkins/foobargamingwebsite
game/wsgi.py
Python
bsd-3-clause
484
0
""" WSGI config for game project. It exposes the WSGI callable as a modu
le-level variable named ``application``. For more information on thi
s file, see https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application from mezzanine.utils.conf import real_project_name os.environ.setdefault("DJANGO_SETTINGS_MODULE", "%s.settings" % real_project_name("game")) application = g...
ShyamSS-95/Bolt
example_problems/nonrelativistic_boltzmann/advected_gaussian_pulse_in_p_space/1V/with_only_E1/domain.py
Python
gpl-3.0
243
0.045267
q1_start = 0 q1_end = 1 N_q1 = 1 q2_start = 0 q2_end = 1 N_q2 = 1 p1_start = -10 p1_e
nd = 10 N_p1 = 32 p2_start = -0.5 p2_end =
0.5 N_p2 = 1 p3_start = -0.5 p3_end = 0.5 N_p3 = 1 N_ghost_q = 0 N_ghost_p = 0
genonfire/bbgo
core/utils.py
Python
mit
1,561
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render from django.utils.translation import ugettext as _ def error_page(request, errormsg=''): """Show error page with message""" if not errormsg:
errormsg = _('Wrong access') return render( reques
t, "error.html", { 'errormsg': errormsg, } ) def error_to_response(request, errormsg=''): """Show error response with msg""" if not errormsg: errormsg = _('Wrong access') return render( request, "error_response.html", { '...
pshchelo/vampy
calc/output.py
Python
bsd-3-clause
2,387
0.008379
#!/usr/bin/env python """ output of various data for VAMP project """ from numpy import ndarray class DataWriter(): def
__init__(self, datadict, title='Data export file'): self.title=title
self.data = datadict self.allfields = sorted(datadict.keys()) self.numparams= [] self.textparams=[] self.datafields = self.allfields self._extract_param_fields() def set_fields(self, fieldslist): self.datafields = fieldslist self._extract_param_field...
jomolinare/kobocat
onadata/apps/logger/management/commands/import_instances.py
Python
bsd-2-clause
2,293
0
#!/usr/bin/env python # vim: ai ts=4 sts=4 et sw=4 coding=utf-8 import os from django.contrib.auth.models import User from django.core.management.base import BaseCommand, CommandError from django.utils.translation import ugettext as _, ugettext_lazy from onadata.libs.logger.import_tools import import_instances_from_z...
username = args
[0] path = args[1] try: user = User.objects.get(username=username) except User.DoesNotExist: raise CommandError(_( "The specified user '%s' does not exist.") % username) # make sure path exists if not os.path.exists(path): rais...
synapsepayments/synapse_pay-python
synapsepay/resources/bank.py
Python
mit
1,073
0.021435
from ..apibits
import * from .. import Client from . import * class
Bank(APIResource): def remove(self, params={}, headers={}): params = ParamsBuilder.merge({ "bank_id" : self.id, }, params) method = APIMethod("post", "/bank/delete", params, headers, self) json = self.client.execute(method) return json # Everything below her...
krkeegan/lib-py-insteon
insteon/base_objects.py
Python
gpl-2.0
19,358
0.00031
import time import datetime import pprint from .helpers import * class ALDB(object): def __init__(self, parent): self._parent = parent self._aldb = {} def edit_record(self, position, record): self._aldb[position] = record def delete_record(self, position): ...
for key, value in self._aldb.items(): ret[key] = BYTE_TO_HEX(value) return ret def load_aldb_records(self, records): for key, record in records.items(): self.edit_record(key, bytearray.fromhex(record)) def clear_all_reco
rds(self): self._aldb = {} def edit_record_byte(self, aldb_pos, byte_pos, byte): self._aldb[aldb_pos][byte_pos] = byte def get_matching_records(self, attributes): '''Returns an array of positions of each records that matches ALL attributes''' ret = [] ...
stephenlienharrell/roster-dns-management
roster-core/roster_core/db_access.py
Python
bsd-3-clause
41,336
0.011128
#!/usr/bin/python # Copyright (c) 2009, Purdue University # 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 copyright notice, this # list ...
NESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY O
F LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """This module is an API to access the dnsManagement database. This module should only be run by servers with authe...
adybbroe/pypps_reader
test/test_ppsread.py
Python
gpl-3.0
1,228
0.001629
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2013 Adam.Dybbroe # Author(s): # Adam.Dybbroe <a000680@c14526.ad.smhi.se> # 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...
U General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """Unittests reading various PPS data files """ import os impor
t unittest from pypps_reader import NwcSafPpsData # The test data cases: # FIXME! class Test(unittest.TestCase): """Unit testing the pps reading""" def setUp(self): """Set up""" return def test_read(self): """Test that it is possible to read pps products""" re...
radomd92/botjagwar
api/importer/rakibolanamalagasy.py
Python
mit
1,609
0
from threading import Lock import requests from api.decorator import critical_section from api.importer import AdditionalDataImporter from api.importer import AdditionalDataImporterError from api.importer.wiktionary import dyn_backend rmi_lock = Lock() class DictionaryImporter(AdditionalDataImporter): def popu...
temp = self.data_type self.data_type = 'rakibolana/raw' tr
y: self.write_additional_data(title, language, additional_data) except AdditionalDataImporterError as exc: pass self.data_type = temp def get_data(self, template_title: str, wikipage: str, language: str): pass
pkimber/pay
pay/tests/test_management_command.py
Python
apache-2.0
280
0
# -*-
encoding: utf-8 -*- from django.test import TestCase from pay.management.commands import init_app_pay class TestCommand(TestCase): def test_init_app(self): """ Test the management command """ command
= init_app_pay.Command() command.handle()
ruchikd/Algorithms
Python/ShortestPalindrome/shortestPalindrome.py
Python
gpl-3.0
230
0.052174
def sh
ortestPalindrome(str): if str is None: return strlen = len(str) for x in xrange(strlen): print str[x] def main(): print "Hello, world" str = 'aacecaaa' shortestPalindrome(str) if __name__ == '__main__': ma
in()
amitskwalia/codesters
resources/migrations/0004_auto__add_featuredresource__add_unique_featuredresource_topic_resource.py
Python
mit
8,260
0.008354
# -*- 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 'FeaturedResource' db.create_table('resources_featuredresource', ( ('id', self.gf...
e_type'] db.delete_unique('resources_featuredresource', ['topic_id', 'resource_type_id']) # Deleting model 'FeaturedResource' db.delete_table('resources_featuredresource') models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models...
{'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permiss...
colloquium/rhevm-api
python/pool-test.py
Python
lgpl-2.1
1,969
0.013713
#!/usr/bin/env python # Copyright (C) 2010 Red Hat, Inc. # # This 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. # # This so...
., 51 Franklin St, Fifth Floor, Boston, MA # 02110-1301 USA, or see the FSF site: http://www.fsf.org. import http import xmlfmt import yamlfmt import jsonfmt from testutils import * opts = parseOptions() (cluster, template) = (None, None) if len(opts['oargs']) >= 2: (cluster, template) = opts['oargs'][0:2] links...
" ===" for pool in t.get(links['vmpools']): t.get(pool.href) if cluster is None: continue pool = fmt.VmPool() pool.name = randomName('foo') pool.size = "2" pool.cluster = fmt.Cluster() pool.cluster.id = t.find(links['clusters'], cluster).id pool.template = fmt.Template() pool.t...
amacd31/bom_data_parser
tests/test_observations_json.py
Python
bsd-3-clause
1,454
0.008253
import os import numpy as np import pandas as pd import six import unittest from datetime import datetime from bom_data_parser import read_obs_json class ObsJSONTest(unittest.TestCase): def setUp(self): self.test_obs_json_file = os.path.join(os.path.dirname(__file__), 'data', 'IDN60901.94767.json') ...
assertE
qual(data['press_tend'].iloc[0], 'F') self.assertEqual(data['rain_trace'].iloc[0], 3.4) self.assertEqual(data['rel_hum'].iloc[0], 69) self.assertEqual(data.index[-1], datetime(2014,9,9,10,30,0)) self.assertEqual(data['air_temp'].iloc[-1], 20.6) self.assertEqual(data['dewpt'].ilo...
DemocracyClub/UK-Polling-Stations
polling_stations/apps/pollingstations/tests/factories.py
Python
bsd-3-clause
591
0
import factory from councils.tests.factories import CouncilFactory from pollingstations.models import PollingS
tation, PollingDistrict class PollingStationFactory(factory.django.DjangoModelFactory): class Meta: model = PollingStation council = factory.SubFactory(CouncilFactory) internal_council_id = factory.Sequence(la
mbda n: f"PS-{n}") class PollingDistrictFactory(factory.django.DjangoModelFactory): class Meta: model = PollingDistrict council = factory.SubFactory(CouncilFactory) internal_council_id = factory.Sequence(lambda n: f"PD-{n}")
start-jsk/jsk_apc
demos/selective_dualarm_stowing/python/selective_dualarm_stowing/models/alex.py
Python
bsd-3-clause
4,007
0
import chainer import chainer.functions as F import chainer.links as L class Alex(chainer.Chain): """Single-GPU AlexNet without partition toward the channel axis.""" def __init__(self, n_class=1000, threshold=0.5, pt_func=None): self.threshold = threshold self.pt_func = pt_func self....
cc / float(len(acc_single) + len(acc_dual)) chainer.re
porter.report({ 'loss': self.loss, 'acc': self.acc, }, self) if chainer.config.train: return self.loss
LowieHuyghe/script-core
scriptcore/encoding/encoding.py
Python
apache-2.0
2,861
0.00035
import sys class Encoding(object): @staticmethod def normalize(value): """ Normalize value :param value: The value :return: The processed value """ # Python 2 vs Python 3 if sys.version_info < (3, 0): return Encoding.to_ascii(valu...
f unicode :param val
ue: The value :return: Ascii or not """ # Python 2 vs Python 3 if sys.version_info < (3, 0): return isinstance(value, unicode) else: return isinstance(value, str)
pizzapanther/GAE-Bulk-Mailer
bulkmail/middleware.py
Python
bsd-2-clause
2,043
0.029369
from django import http from django.conf import settings from google.appengine.api import users from .exceptions import ParameterRequired, ApiException class User (object): def __init__ (self): self._email = None self._is_super = None self._is_auth = None self._userid = None self.user = No...
il.lower() in settings.STAFF_USERS: self._is_staff = True else: for d in settings.STAFF_DOMAINS: if self._email.lower().endswith(d): self._is_staff = True break else: self._is_auth = False return sel...
self._is_auth is None: self.is_authorized() return self._is_super @property def is_staff (self): if self._is_auth is None: self.is_authorized() return self._is_staff @property def userid (self): if self._is_auth is None: self.is_authorized() ...
ChimeraCoder/GOctober
july/game/urls.py
Python
mit
1,757
0
from django.conf.urls import patterns, url from july.game import views urlpatterns = patterns( 'july.game.views', url(r'^people/$', views.PlayerList.as_view(), name='leaderboard'), url(r'^people/(?P<year>\d{4})/(?P<month>\d{1,2})/((?P<day>\d{1,2})/)?$', views.PlayerList.as_view(),...
day>\d{1,2})/)?$', views.BoardList.as_view(), name='projects'), url(r'^projects/(?P<slug>.+)/$', views.ProjectView.as_view(), name='project-details'), url(r'^languages/$', views.LanguageBoardList.as_view(), name='languages'), url(r'^languages/(?P<year>\d{4})/(...
# for local only debug purposes url(r'^events/(?P<action>pub|sub|ws)/(?P<channel>.*)$', 'events', name='events'), )
Furzoom/learnpython
usefull_scripts/multiprocessing/multiprocessing5_1.py
Python
mit
709
0.005642
import multiprocessing import sys import time def worker_with(f): fs = open(f, 'a+') n = 10 while n > 1: fs.write("Locked acquired via with\n") time.sleep(1) n -= 1 fs.close() def worker_no_with(f): fs = open(f, 'a+') n = 10 w...
tly\n") n -= 1 time.sleep(1) fs.close() if __name__ == "__main__": lock = multiprocessing.Lock() f = 'file.txt' w = multiprocessing.Process(target=worker_with, args=(f,)) nw = multiprocessing.Process(target=worker_no_with,
args=(f,)) w.start() nw.start() print('end')
arannasousa/pagseguro_xml
exemplos/testes_notificacao.py
Python
gpl-2.0
1,090
0.00276
# coding=utf-8 # --------------------------------------------------------------- # Desenvolvedor: Arannã Sousa Santos # Mês: 12 # Ano: 2015 # Projeto: pagseguro_xml # e-mail: asousas@live.com # --------------------------------------------------------------- import loggin...
IENTE = u'sandbox' PAGSEGURO_API_EMAIL = u'seu@email.com' PAGSEGURO_API_TOKEN_PRODUCAO = u'' PAGSEGURO_API_TOKEN_SANDBOX = u'' CHAVE_NOTIFICACAO = u'AA0000-AA00A0A0AA00-AA00AA000000-AA0000' # ela éh de producao api = ApiPagSeguroNotificacao_v3(ambiente=CONST_v3.AMBIENTE.SANDBOX) PAGSEGURO_API_TOKEN = PAGSEGURO...
-' * 50 print retorno.xml print u'-' * 50 for a in retorno.alertas: print a else: print u'Motivo do erro:', retorno
fastcoinproject/fastcoin
qa/rpc-tests/rest.py
Python
mit
3,264
0.010723
#!/usr/bin/env python2 # Copyright (c) 2014 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # # Test REST interface # from test_framework import BitcoinTestFramework from util import * import json try...
EPARATOR = "." def run_test(self): url = urlparse.urlparse(self.nodes[0].url) bb_h
ash = self.nodes[0].getbestblockhash() # check binary format response = http_get_call(url.hostname, url.port, '/rest/block/'+bb_hash+self.FORMAT_SEPARATOR+"bin", True) assert_equal(response.status, 200) assert_greater_than(int(response.getheader('content-length')), 10) ...
lantianlz/zx
www/stock/sync_stock_data_client.py
Python
gpl-2.0
1,935
0.0052
# -*- coding: utf-8 -*- import requests, re, json, time, datetime, traceback, random from pyquery import PyQuery as pq # host = "www.a.com:80
00" host = "www.zhixuan.com" headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36"} def get_stocks(): url = "http://%s/stock/get_stock_json" % host req = requests.get(url) return json.loads(req.text) def syn...
, stock['code']) resp = None for j in range(3): try: resp = requests.get(url, timeout=10, headers=headers) break except Exception, e: print stock, stock.id print e if not resp or resp.status_code != 200: ...
tuffery/Frog2
frowns/Depict/.happydoc.TkMoleculeDrawer.py
Python
gpl-3.0
4,720
0.134322
(S'7f2210613c44962221805a1b28aa76d6' p1 (ihappydoclib.parseinfo.moduleinfo ModuleInfo p2 (dp3 S'_namespaces' p4 ((dp5 S'TkDrawer' p6 (ihappydoclib.parseinfo.classinfo ClassInfo p7 (dp8 g4 ((dp9 (dp10 tp11 sS'_filename' p12 S'../python/frowns/Depict/TkMoleculeDrawer.py' p13 sS'_docstring' p14 S'' sS'_class_member_info' ...
7 g38 sg28 g39 sg29 S'' sbsS'_resize' p50 (ihappydoclib.parseinfo.functioninfo FunctionInfo p51 (dp52 g4 ((dp53 (dp54 tp55 sg41 (dp56 sg43 (S'self' p57 S'event' p58 tp59 sg46 (dp60 g57 (NNNtp61 sg58 (NNNtp62 ssg12 g13 sg14 S'(event) -> resive the drawing to eve
nt.height, event.width' p63 sg17 g50 sg18 g31 sg19 g20 sg25 (dp64 sg27 g53 sg28 g54 sg29 S'' sbsS'_clear' p65 (ihappydoclib.parseinfo.functioninfo FunctionInfo p66 (dp67 g4 ((dp68 (dp69 tp70 sg41 (dp71 sg43 (S'self' p72 tp73 sg46 (dp74 g72 (NNNtp75 ssg12 g13 sg14 S'' sg17 g65 sg18 g31 sg19 g20 sg25 (dp76 sg27 g68 sg28 ...
djsilenceboy/LearnTest
Python_Test/PyFinanceApiSample/com/djs/learn/test/TestCheckYahooFinanceCurrencyData.py
Python
apache-2.0
709
0.00141
''' Check Yahoo finance currency data helper. Update log: (date / version / author : comments) 2017-12-10 / 1.0.0 / Du Jiang : Creation 2017-12-13 / 2.0.0 / Du Jiang : Use new API ''' from com.djs.learn.financeapi import CheckFinanceDataRequests __data_type = 1 __inventory_info_file_path = "../../../../etc/Currency...
t_file_path] CheckFinanceDataRequests.main(argv) ''' Or run: python CheckFinanceDataRequests.py -d 1 -i "../../../../etc/CurrencyData.csv" -o "../../../../Temp/CurrencyDataY.json" ''' if
__name__ == '__main__': pass
frerepoulet/ZeroNet
src/lib/pyasn1/type/useful.py
Python
gpl-2.0
1,159
0
# # This file is part of pyasn1 software. # # Copyright (c) 2005-2017, Ilya Etingof <etingof@gmail.com> # License: http://pyasn1.sf.net/license.html # from pyasn1.type import univ, char, tag __all__ = ['ObjectDescriptor', 'GeneralizedTime', 'UTCTime'] NoValue = univ.NoValue noValue = univ.noValue class ObjectDescri...
(char.VisibleString): __doc__ = char.GraphicString.__doc__ #: Default :py:class:`~pyasn1.type.tag.TagSet` object for |ASN.1| objects tagSet = char.VisibleString.ta
gSet.tagImplicitly( tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 24) ) class UTCTime(char.VisibleString): __doc__ = char.GraphicString.__doc__ #: Default :py:class:`~pyasn1.type.tag.TagSet` object for |ASN.1| objects tagSet = char.VisibleString.tagSet.tagImplicitly( tag.Tag(tag...
byakatat/selenium-training
test_going_through_all_admin_sections.py
Python
apache-2.0
1,705
0.00176
import pytest from selenium import webdriver from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.common.by import By @pytest.fixture def driver(request): wd = webdriver.Chrome() request.addfinalizer(wd.quit) return wd def is_element_present(driver, *args): try: ...
lector("#app->a") # Find length of list with links and starting a loop for i in range(len(all_main_l
inks)): # Every loop find list with links all_main_links = driver.find_elements_by_css_selector("#app->a") # Click on link link = all_main_links[i] link.click() # Asserting presence of header is_element_present(driver, By.CSS_SELECTOR, "#content>h1") # Get...
cmsc421/mobility_base_tools
scripts/urdf_remove_pedestal.py
Python
bsd-3-clause
3,158
0.0057
#!/usr/bin/env python # Software License Agreement (BSD License) # # Copyright (c) 2014-2015, Dataspeed Inc. # 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 c...
ixed'") rospy.set_param(param_dest, urdf) if changed: rospy.loginfo("Updated parameter '%s'", param_dest) else:
rospy.loginfo("Copied parameter '%s' to '%s'", param_src, param_dest) else: rospy.logwarn("Parameter '%s' not found", param_src) except rospy.ROSInterruptException: pass
AnishShah/tensorflow
tensorflow/tools/api/tests/api_compatibility_test.py
Python
apache-2.0
12,593
0.005559
# 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...
from golden files. actual_dict: a ict of TFAPIObject protos constructed by reading from the TF package linked to the test. verbose: Whether to log the full diffs, or simply report which files were different.
update_goldens: Whether to update goldens when there are diffs found. additional_missing_object_message: Message to print when a symbol is missing. api_version: TensorFlow API version to test. """ diffs = [] verbose_diffs = [] expected_keys = set(expected_dict.keys()) actua...
tomka/CATMAID
django/applications/catmaid/tests/apis/test_stacks.py
Python
gpl-3.0
2,238
0.001787
# -*- coding: utf-8 -*- import json from .common import CatmaidApiTestCase class StacksApiTests(CatmaidApiTestCase): def test_stack_info(self): self
.fake_authentication() test_stack_id = 3 response = self.client.get('/%d/stack/%d/info' % (self.test_project_id, test_stack_id)) self.assertStatus(response) parsed_response = json.loads(response.content.decode('utf-8')) expected_result = { "attribution": None, ...
x": 0, "y": 0, "z": 0 }, "dimension": { "x": 2048, "y": 1536, "z": 460 }, "comment": '<p>&copy;2009 <a href="http://people.epfl.ch/graham.knott">Graham ' 'Knott</a>.</p>...
mrquim/mrquimrepo
script.module.myconnpy/lib/examples/engines.py
Python
gpl-2.0
1,881
0.002127
#!/usr/bin/env python # -*- coding: utf-8 -*- # MySQL Connector/Python - MySQL driver written in Python. # Copyright (c) 2009, 2013, Oracle and/or its affiliates. All rights reserved. # MySQL Connector/Python is licensed under the terms of the GPLv2 # <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most...
port Config config = Config.dbinfo().copy()
out = main(config) print('\n'.join(out))
geolinkedata/geolod-api
api/tests/test_triplestores.py
Python
gpl-2.0
1,415
0.001413
from rest_framewor
k.test import APITestCase from rest_framework.test import APIRequestFactory, APIClient, \ force_authenticate from api.views import TripleStoreList from api.tests.common import setup_user class TestTripleStoresView(APITestCase): def setUp(self): self.factory = APIRequ
estFactory() self.client = APIClient() self.user = setup_user() self.view = TripleStoreList.as_view() self.uri = '/v1/geo/data/triple-stores/' def test_not_authenticated_uri(self): """ not authorized access not allowed """ request = self.factory.get(s...
samuelcolvin/pydantic
tests/test_networks_ipaddress.py
Python
mit
17,339
0.002653
from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network import pytest from pydantic import BaseModel, IPvAnyAddress, IPvAnyInterface, IPvAnyNetwork, ValidationError # # ipaddress.IPv4Address # ipaddress.IPv6Address # pydantic.IPvAnyAddress # @pytest.mark.parametrize( ...
address', 'type': 'value_error.ipv4address'}], ), (-1, [{'loc': ('ipv4',), 'msg': 'value is
not a valid IPv4 address', 'type': 'value_error.ipv4address'}]), ( 2 ** 32 + 1, [{'loc': ('ipv4',), 'msg': 'value is not a valid IPv4 address', 'type': 'value_error.ipv4address'}], ), ( IPv6Address('::0:1:0'), [{'loc': ('ipv4',), 'msg': 'value is ...
philba/myblog
blog/migrations/0008_blogpage_categories.py
Python
mit
513
0.001949
# -*- coding:
utf-8 -*- # Generated by Django 1.10.5 on 2017-03-10 18:08 from __future__ import unicode_literals from django.db import migrations import modelcluster.fields class Migration(migrations.Migration): de
pendencies = [ ('blog', '0007_blogcategory'), ] operations = [ migrations.AddField( model_name='blogpage', name='categories', field=modelcluster.fields.ParentalManyToManyField(blank=True, to='blog.BlogCategory'), ), ]
ohsu-qin/qirest
qirest/test/unit/test_seed.py
Python
bsd-2-clause
19,873
0.002063
from nose.tools import (assert_is_none, assert_is_instance, assert_in, assert_is_not_none, assert_true, assert_false, assert_equal) from datetime import datetime from mongoengine import connect from qirest_client.model.subject import Subject from qirest_client.model.uom i...
def tearDown(self): self._connection.drop_database('qiprofile_test') def test_serialization(self): for saved_sbj in self._subjects: query = dict(project=saved_sbj.project, collection=saved_sbj.collection, number=saved_sbj.number) ...
tched_sbj) SESSION_CNT = dict( Breast=4, Sarcoma=3 ) def test_reseed(self): subjects = seed.seed() expected = set(str(sbj) for sbj in self._subjects) actual = set(str(sbj) for sbj in subjects) assert_equal(actual, expected, "Reseed result is incorrect -" ...
theopak/glassface
server/manage.py
Python
mit
252
0
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.
environ.setdefault("DJANGO_SETTINGS_MODULE", "glassface.settings") from django.core.management import execute_from_command_line execu
te_from_command_line(sys.argv)
mauricioabreu/speakerfight
deck/migrations/0014_event_anonymous_voting.py
Python
mit
485
0.002062
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Mig
ration(migrations.Migration): dependencies = [ ('deck', '0013_proposal_more_information'), ] operations = [ migrations.AddField( model_name='event', name='anonymous_voting', field=models.BooleanField(default=False, verbose_name='Anonymous Voting?'), ...
preserve_default=True, ), ]
daknuett/BeeKeeper
pythons/objs_graphics.py
Python
agpl-3.0
1,259
0.039714
from gi.repository import Gtk import os class ExportDialog(Gtk.Dialog): def __init__(self,parent,*args): Gtk.Dialog.__init__(self, "Exportieren", parent, 0, (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OK, Gtk.ResponseType.OK)) self.set_default_size(150,150) self.contentarea=self.get_content_are...
l_and_entry(self.combo_store) self.combo.connect("changed",self.update_select_type) self.combo.set_entry_text_column(0) self.contentarea.add(self.combo) self.filechooser = Gtk.FileChooserButton(Gtk.FileChooserAction.CREATE_FOLDER) self.filechooser.set_create_folders(True) self.filechooser.set_action(Gtk.Fi...
def update_select_type(self,combo,*args): treit=combo.get_active_iter() if(treit == None): return self.selection_type=combo.get_model()[treit][0] return def update_select_folder(self,chooser,*args): self.selection_folder=chooser.get_filename()
jkonecny12/blivet
blivet/tasks/fsmkfs.py
Python
lgpl-2.1
10,426
0.000575
# fsmkfs.py # Filesystem formatting classes. # # 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 progr...
ilesystem may use. :returns: UUID options :rtype: list of str :raises: FSWriteUUIDError """ if self.get_uuid_args is None or self.fs.uuid is None: return [] if self.fs.uuid_for
mat_ok(self.fs.uuid): return self.get_uuid_args(self.fs.uuid) else: raise FSWriteUUIDError("Choosing not to apply UUID (%s) during" " creation of filesystem %s. UUID format" " is unacceptable for this filesystem." ...
git-albertomarin/pinger
report/parser/writer.py
Python
mit
332
0.006024
from database.db import Database from report.db.models import PingerReport class Writer: def __init__(self): self.db = D
atabase() de
f report_insert(self, item): """ Save Pinger Reports to the database :param item: """ self.db.get_or_create(PingerReport, **item)
FlorisTurkenburg/ManyMan
b.L_frontend/widgets.py
Python
gpl-2.0
7,562
0.000264
""" ManyMan - A Many-core Visualization and Management System Copyright (C) 2015 University of Amsterdam - Computer Systems Architecture Jimi van der Woning and Roy Bakker Extended for big.LITTLE by: Floris Turkenburg This program is free software: you can redistribute it and/or modify it under the terms of the GNU Ge...
super(WRectangle, self).__init__(**kwargs) self.build() def build(self): """Render the
rectangle.""" with self.canvas: self.c = Color() self.c.rgba = self.color self.r = Rectangle(pos=self.pos, size=self.size) self.bind(pos=self.update_pos, size=self.update_size) def update_pos(self, instance, value): """Handler when the rectangle's positi...
haroldo-ok/really-old-stuff
mastersystem/zxb-sms-2012-02-23/zxb-sms/wip/zxb2wla.py
Python
apache-2.0
11,822
0.015564
from version import VERSION import sys, os, getpass import re import optparse def coalesce( *values ): for f in values: if f is not None: return f class ConversionError(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self...
t.inc" ;============================================================== ; Includes ;============================================================== .include "{wla_lib_dir}Useful functions.inc" .include "{wla_lib_dir}BBC Micro font.inc" .include "{wla_lib_dir}sprite.inc" .include "{wla_lib_dir}resource.inc" {code} {re...
inc file. """ def __init__(self, input = None): self.setInput(input) return # Accessors def setInput(self, input): if input == None: self._input = None else: self._input = [x.rstrip() for x in input] return self # The...
astone282/vactrack
vactrack/Expedia.py
Python
apache-2.0
6,312
0.00206
import re import urllib.request import logging import math from bs4 import BeautifulSoup from Vacation import VacationPackage, Departures, Destinations, Duration ALL_PAGES = True DEPARTURE_MAPPING = { Departures.OTTAWA: "YOW" } DEPARTURE_CITY_MAPPING = { Departures.OTTAWA: "Ottawa" } DESTINATION_MAPPING = ...
ifulSoup(html, "html.parser") for tag in soup.find_all("div", class_="flex-card"): # all stop information primaryBlock = tag.find_all('div', class_='flex-area-primary') name = primaryBlock[0].find_all('h5')[0].find_all('a')[0].get_text().strip() ...
ondary') city = primary_items[0].get_text().strip() descr = primary_items[1].get_text().strip() dates = primary_items[2].get_text().strip() oper = primary_items[3].find(text=True).strip() match = re.search('Operated by (.*),', oper) ...
PhillsProgrammingExperiments/dyleps
dyleps/tier1/exceptions.py
Python
mit
106
0.009434
from dy
leps
.utils.exceptions import Tier1Exception class Tier1ParsingException(Tier1Exception): pass
googleads/google-ads-python
google/ads/googleads/v9/services/services/geo_target_constant_service/transports/base.py
Python
apache-2.0
4,445
0
# -*- coding: utf-8 -*- # Copyright 2020 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
er-agent string along with API requests. If ``None``, then default info will be used. Generally, you only need to set this if you're
developing your own client library. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. if ":" not in host: host += ":443" self._host = host # If no credentials are provided, then determine the appropriate # defaults. ...
benjimons/FIR
fir_artifacts/migrations/0002_create_artifacts.py
Python
gpl-3.0
1,876
0.002665
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import fir_artifacts.models class Migration(migrations.Migration): dependencies = [ ('fir_artifacts', '0001_initial'), ('incid
ents', '0001_initial') ]
operations = [ migrations.CreateModel( name='Artifact', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('type', models.CharField(max_length=20)), ('value', models.CharField(max_le...
itszero/onenet
emulab/onenet/onenet/inject/infect.py
Python
mit
867
0.019608
from mininet.net import Mininet from ..util import findPyroObjectOrNone def monkeypatch(cls): def decorator(func): setattr(cls, func.__name__, func) return func return decorator def getOneNo
deByName(net, name): if name in net.nameToNode: return net.nameToNode[name] else: return findPyroObjectOrNone(name) @monkeypatch(Mininet) def intakeNodes(self, networks): for netName in networks: net = findPyroObjectOrNone(netName) if self.name == ne
t.getName(): continue print "-- Intake nodes from %s" % net.getName() for h in net.getHosts(): self.nameToNode[h.getName()] = h self.hosts.append(h) for s in net.getSwitches(): self.nameToNode[s.getName()] = s self.hosts.append(s) @monkeypatch(Mininet) def remoteExecute(self, ...
levilucio/SyVOLT
UMLRT2Kiltera_MM/ProcDef.py
Python
mit
3,435
0.029403
""" __ProcDef.py_____________________________________________________ Automatically generated AToM3 syntactic object (DO NOT MODIFY DIRECTLY) Author: gehan Modified: Sat Aug 30 18:23:40 2014 _________________________________________________________________ """ from ASGNode import * from ATOM3Type import * from ATOM3...
/PRE action trigger Constraint
s will be added/removed in a logical manner by other mechanisms. """ return # <---- Remove this to use QOCA """ Get the high level constraint helper and solver """ from Qoca.atom3constraints.OffsetConstraints import OffsetConstraints oc = OffsetConstraints(self.parent.qocaSolver) ...
google/coursebuilder_xblock_module
src/modules/xblock_module/xblock_module.py
Python
apache-2.0
54,112
0.000185
# Copyright 2013 Google 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 # # Unless required by applicable law or ...
.fields.Scope.user_state_summary: student_data, xblock.fields.Scope.user_state: student_data, xblock.fields.Scope.user_info: student_
data, xblock.fields.Scope.preferences: student_data}) class ForbiddenXBlockError(Exception): """Raised when a non-whitelisted XBlock is requested.""" def select_xblock(identifier, entry_points): """Hook called when loading XBlock classes, which enforces whitelist.""" entry_point = xblock.plu...
geekan/scrapy-live-portal
general_spider/general_spider/spiders/spider.py
Python
apache-2.0
3,707
0.002158
import re import json from urlparse import urlparse import urllib import pdb from scrapy.selector import Selector try: from scrapy.spiders import Spider except: from scrapy.spiders import BaseSpider as Spider from scrapy.utils.response import get_base_url from scrapy.spiders import CrawlSpide
r, Rule from scrapy.linkextractors import LinkExtractor as sle from general_spider.items import * from misc.log import * from misc.spider import CommonSpider import BasicSpiderConfig class general_spiderSpider(Comm
onSpider): name = 'general_spider' list_css_rules = {} def __init__(self, conf_module='TestSpiderConfig', *args, **kwargs): if conf_module.endswith(".py"): conf_module = conf_module[:-3] cm = __import__(conf_module, globals=globals()) conf = cm.Config() self.nam...
dodonator/ticTacToe
outdatet/ticTacToe.py
Python
gpl-3.0
3,105
0.055717
import random import os # TicTacToe def createNewField(): result = [] for i in range(3): tmp = [] for i2 in range(3): tmp.append(' ') result.append(tmp) return result def printField(field): print '' for element in field: print element print '' def isFieldFull(field): occupiedPlaces = 0 for row in...
: if row == ['X','X','X']: winner = 'User' return winner elif row == ['O','O','O']: winner = 'Computer' return winner else: winner = '' columns = [[],[],[]] for row in field: columns[0].append(row[0]) co
lumns[1].append(row[1]) columns[2].append(row[2]) for col in columns: if col == ['X','X','X']: winner = 'User' return winner elif col == ['O','O','O']: winner = 'Computer' return winner else: winner = '' dia1 = [field[0][0],field[1][1],field[2][2]] dia2 = [field[0][2],field[1][1],field[2][0...