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
Fakor/congov
cli/lib/command.py
Python
mit
530
0.001887
import collections class Command: def __init__(self, template): self._values = template def __getitem__(self, key): value = self._values[key] if isinstance(value, dict) or isinstance(value, list): return
Command(value) return self._values[key] def __setitem__(self, key, value): try: self._values[key] = type(self._va
lues[key])(value) except ValueError: raise CommandSetValueError class CommandSetValueError(Exception): pass
twitterdev/data-ads-sample
home/frequency.py
Python
mit
1,443
0.000693
from django.conf import settings from gnip_search.gnip_search_api import GnipSearchAPI from gnip_search.gnip_search_api import QueryError as GNIPQueryError class Frequency: """ Class collection for Frequency """ DATE_FORMAT = "%Y-%m-%d %H:
%M" def __init__(self, query, sample, start, end): self.query = query self.sample = sample self.start = start self.end = end self.freq = self.get(self.get_da
ta()) def get_data(self): """ Returns data for frequency in list view """ # New gnip client with fresh endpoint (this one sets to counts.json) g = GnipSearchAPI(settings.GNIP_USERNAME, settings.GNIP_PASSWORD, settings.GNIP...
industrydive/fileflow
fileflow/operators/__init__.py
Python
apache-2.0
141
0
from dive_operat
or import DiveOperator from dive_python_operator import DivePythonOperator __all__ = ['DiveOperator', 'DivePythonOpe
rator']
marciocg/palpite-megasena
palpite-megasena.py
Python
gpl-2.0
708
0.009887
#!/usr/bin/python # -*- coding: utf-8 -*- from bottle import route, get, post, view, run, app, default_app, static_file from palpite import palpite @get('/') @view('index.html') def index_get(): return
dict() @post('/') @view('index.html') def index_post(): gera_palpite = palpite() return d
ict(jogo=gera_palpite) @get('/favicon.ico') @get('/favicon.png') def favicon(): return static_file('/static/favicon.png', root='.') @get('/normalize.css') def normalizecss(): return static_file('normalize.css', root='static') @get('/skeleton.css') def skeletoncss(): arq = 'skeleton.css' return static...
c4fcm/CivilServant
utils/data_migrations/12.06.2016.updated_page_created_at_to_utc.py
Python
mit
2,850
0.022105
""" ONE-TIME UPDATE OF converting SubredditPage.created_at, FrontPage.created_at to utc Daylight Savings Time = Nov 6 2am if we see the ET time Nov 6 12am, then it is EDT: EDT-->UTC = +4 = Nov 6 4am if we see the ET time Nov 6 1-2am, then it is unclear whether it is EDT or EST; assume it is EST > assumption is bec...
sts = 0 last_et_time_utc = datetime.datetime.min last_edt_time = datetime.datetime.min num_confusing_et_times = 0 print("Testing {0} posts...".format(total_posts)) for post in posts.all(): if not post.is_utc: created_at_et = post.created_at if created_at_et < DST_LIMIT_ET: # is EDT; in DST; before Nov...
_et]) else: # is EST; out of DST if created_at_et < DST_LIMIT_ET + datetime.timedelta(hours=1): # if between 1am and 2am on Nov 6 num_confusing_et_times += 1 created_at_utc = created_at_et - EST_TO_UTC post.created_at = created_at_utc post.is_utc = True num_updated_posts += 1 last_...
Sirs0ri/PersonalAssistant
samantha/plugins/plugin.py
Python
mit
4,002
0
"""Contains a baseclass for plugins.""" ############################################################################### # # TODO: [ ] # ############################################################################### # standard library imports from collections import Iterable from functools import wraps import loggin...
party imports # application specific imports from samantha.core import subscribe_to __version__ = "1.4.10" # Initialize the logger LOGGER = logging.getLogger(__name_
_) class Plugin(object): """Baseclass, that holds the mandatory methods a plugin must support.""" def __init__(self, name="Plugin", active=False, logger=None, file_path=None, plugin_type="s"): """Set the plugin's attributes, if they're not set already.""" self.name = name ...
aptana/Pydev
tests/org.python.pydev.refactoring.tests/src/python/visitor/selectionextension/testSelectionExtensionExprFail.py
Python
epl-1.0
286
0.027972
class A: def test(sel
f): print "I##|nitializing A", "test"##| attribute = "hello" def my_method(self): print self.attribute a = A() a.test() ##r Should expand to Full String "Initializing A" # Invalid selection: # nitializing A", "
test"
SkyTruth/CrowdProjects
Data/FrackFinder/PA/2013/Transformations_and_QAQC/MoorFrog/bin/task2shp.py
Python
bsd-3-clause
22,106
0.002171
#!/usr/bin/env python # This document is part of CrowdProjects # https://github.com/skytruth/CrowdProjects # =========================================================================== # # # Copyright (c) 2014, SkyTruth # All rights reserved. # # Redistribution and use in source and binary forms, with or without...
ate clicks file --no-wellpad -> Don't generate wellpads file
--of=driver -> Output driver name/file type - default='ESRI Shapefile' --epsg=int -> EPSG code for coordinates in task.json - default='4326' """ % __docname__) return 1 #/* ======================================================================= */# #/* Define print_license() function #/* ================...
robwarm/gpaw-symm
gpaw/eigensolvers/rmm_diis_old.py
Python
gpl-3.0
4,714
0.001697
"""Module defining ``Eigensolver`` classes.""" import numpy as np from gpaw.utilities.blas import axpy from gpaw.eigensolvers.eigensolver import Eigensolver from gpaw import extra_parameters class RMM_DIIS(Eigensolver): """RMM-DIIS eigensolver It is expected that the trial wave functions are orthonormal ...
else:
lam2 = self.fixed_trial_step R_G *= lam + lam2 axpy(lam * lam2, dR_G, R_G) self.timer.start('precondition') psit_xG[:] += self.preconditioner(R_xG, kpt, ekin_x) self.timer.stop('precondition') self.timer.stop('RM...
litnimax/astconfman
astconfman/migrations/versions/2728b7328b78_.py
Python
agpl-3.0
724
0.012431
"""empty message Revision ID: 2728b7328b78 Revises: d7c7f3be40a Create Date: 2015-10-20 13:44:12.129389 """
# revision identifiers, used by Alembic. revision = '2728b7328b78' down_revision = 'd7c7f3be40a' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - please adjust! ### op.drop_table('conference_schedule') ### end Alembic commands ### def downgrade(): ...
, sa.VARCHAR(length=256), nullable=True), sa.PrimaryKeyConstraint('id') ) ### end Alembic commands ###
GoogleCloudPlatform/declarative-resource-client-library
python/services/identitytoolkit/alpha/tenant.py
Python
apache-2.0
10,881
0.002022
# Copyright 2022 Google LLC. 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 o...
lf.name): request.resource.name = Primitive.to_proto(self.name) if Primitive.to_proto(self.display_name): request.resource.display_name = Primitive.to_proto(self.display_name) if Primitive.to_proto(self.allow_password_signup): request.resource.allow_passwo
rd_signup = Primitive.to_proto( self.allow_password_signup ) if Primitive.to_proto(self.enable_email_link_signin): request.resource.enable_email_link_signin = Primitive.to_proto( self.enable_email_link_signin ) if Primitive.to_proto(s...
LamCiuLoeng/internal
tribal/model/__init__.py
Python
mit
6,536
0.009945
# -*- coding: utf-8 -*- """The application's model objects""" from zope.sqlalchemy import ZopeTransactionExtension from sqlalchemy.orm import scoped_session, sessionmaker # from sqlalchemy import MetaData from sqlalchemy.ext.declarative import declarative_base # Global session manager: DBSession() returns the Thread-l...
mit = False, # extension = [ LogSessionExtension(), ZopeTransactionExtension(), ]) maker = sessionmaker(autoflush = True, autocommit = False, extension = ZopeTransactionExtension()) DBSession = scoped_session(maker) # Base class f
or all of our model classes: By default, the data model is # defined with SQLAlchemy's declarative extension, but if you need more # control, you can switch to the traditional method. DeclarativeBase = declarative_base() # There are two convenient ways for you to spare some typing. # You can have a query property on a...
joshalbrecht/memdam
memdam/server/web/utils.py
Python
gpl-2.0
1,213
0.003298
import os import flask import memdam.blobstore.localfolder import memdam.eventstore.sqlite from memdam.server.web import app def get_archive(username): """ :param username: the name of the user for which we should get the event archive :type username: string :returns: a new (or cached) archive ...
sk.g._archives[username] assert db_file != '' db_file = os.path.join(db_file, username) if not os.path.exists(db_file): os.makedirs(db_file) archive = memdam.eventstore.sqlite.Eventstore(db_file) return archive def get_blobstore(username): """ :param username: the name of the user ...
he blobstore folder. :type username: string :returns: a new (or cached) blobstore :rtype: memdam.blobstore.api.Blobstore """ base_folder = app.config['BLOBSTORE_FOLDER'] user_folder = os.path.join(base_folder, username) if not os.path.exists(user_folder): os.makedirs(user_folder) ...
wanderine/nipype
nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSInitializedControlPoints.py
Python
bsd-3-clause
1,433
0.020237
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT from nipype.testing import assert_equal from nipype.interfaces.semtools.utilities.brains import BRAINSInitializedControlPoints def test_BRAINSInitializedControlPoints_inputs(): input_map = dict(args=dict(argstr='%s', ), environ=dict(nohash=True, use...
utput_map.items(): for metakey, value in metadata.items():
yield assert_equal, getattr(outputs.traits()[key], metakey), value
camsas/qjump-nsdi15-plotting
table1/do_hist.py
Python
bsd-3-clause
2,737
0.008403
#! /usr/bin/python # Copyright (c) 2015, Matthew P. Grosvenor # 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 # ...
ENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF
USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF 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. import sys import os import n...
arizvisa/syringe
src/hooktest.py
Python
bsd-2-clause
3,457
0.01186
import psyco psyco.full() import linker.coff from linker import store m,n='python26.dll','Py_DecRef' localname = None,'__imp__<%s!%s>'%(m,n) if True: # this should import from python26.lib,Py_DecRef # this should export ia32.obj,stuff a = linker.coff.object.open('~/work/syringe/src/ia32.obj') # impor...
or: pass continue continue if True: z[store.BaseAddress] = 0x10000000 for x in z.undefined: z[x] = 0xbbbbbbbb if True: print '-'*25 out = file('blah','wb') for x in z.segments: y = z.getsegment(x) ...
a[x] = 0xbbbbbbbb a[store.BaseAddress] = 0x10000000 b = a.getsegment('.text') c = a.relocatesegment('.text',b) # import ptypes # print ptypes.hexdump(c, a['.text'])
Nic30/hwtLib
hwtLib/tests/all.py
Python
mit
22,367
0.001162
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys from unittest import TestLoader, TextTestRunner, TestSuite from hwt.simulator.simTestCase import SimTestCase from hwtLib.abstract.busEndpoint_test import BusEndpointTC from hwtLib.abstract.frame_utils.alignment_utils_test import FrameAlignmentUtilsTC from hwtL...
from hwtLib.examples.arithmetic.cntr_test import CntrTC, CntrResourceAnalysisTC from hwtLib.examples.arithmetic.multiplierBooth_test import MultiplierBoothTC from hwtLib.examples.arithmetic.privateSignals_test
import PrivateSignalsOfStructTypeTC from hwtLib.examples.arithmetic.selfRefCntr_test import SelfRefCntrTC from hwtLib.examples.arithmetic.twoCntrs_test import TwoCntrsTC from hwtLib.examples.arithmetic.vhdl_vector_auto_casts import VhdlVectorAutoCastExampleTC from hwtLib.examples.arithmetic.widthCasting import WidthCa...
244xiao/blender-java
blender-java/src/resources/release/scripts/ui/properties_data_metaball.py
Python
gpl-2.0
3,814
0.000524
# ##### BEGIN GPL LICENSE BLOCK ##### # # 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 2 # of the License, or (at your option) any later version. # # This program is ...
layout = self.layout ob = context.object mball = context.meta_ball space = context.space_data if ob: layout.template_ID(ob, "data", unlink="None") elif mball: layout.template_ID(space, "pin_id", unlink="None") class DATA_PT_metaball(D...
all split = layout.split() col = split.column() col.label(text="Resolution:") sub = col.column(align=True) sub.prop(mball, "resolution", text="View") sub.prop(mball, "render_resolution", text="Render") col = split.column() col.label(text="Set...
ldu4/criu
test/inhfd/pipe.py
Python
lgpl-2.1
215
0.037209
import os def create_fds(): (fd1, fd2) = os.pipe() return (os.fdopen(fd2, "w"), os.fdo
pen(fd1, "r")) def filename(pipef): return 'pipe:[%d]' % os.fstat(pipef.fileno())
.st_ino def dump_opts(sockf): return [ ]
teeple/pns_server
work/install/Python-2.7.4/Lib/plat-mac/MiniAEFrame.py
Python
gpl-2.0
6,519
0.004295
"""MiniAEFrame - A minimal AppleEvent Application framework. There are two classes: AEServer -- a mixin class offering nice AE handling. MiniApplication -- a very minimal alternative to FrameWork.py, only suitable for the simplest of AppleEvent servers. """ from warnings import warnpy3k warnpy3k("In 3...
elf.applemenu = applemenu = Menu.NewMenu(self.appleid, "\024") applemenu.AppendMenu("%s;(-" % self.getaboutmenutext()) if MacOS.runtimemodel == 'ppc': applemenu.AppendResMenu('DRVR') applemenu.InsertMenu(0) self.quitmenu = Menu.NewMenu(self.quitid, "File") self.quitme...
self.quitmenu.InsertMenu(0) Menu.DrawMenuBar() def __del__(self): self.close() def close(self): pass def mainloop(self, mask = everyEvent, timeout = 60*60): while not self.quitting: self.dooneevent(mask, timeout) def _quit(self): self.quitting = ...
endlessm/chromium-browser
third_party/llvm/lldb/test/API/commands/expression/import-std-module/weak_ptr/TestWeakPtrFromStdModule.py
Python
bsd-3-clause
944
0.003178
""" Test ba
sic std::weak_ptr functionality. """ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil class TestSharedPtr(TestBase): mydir = TestBase.compute_mydir(__file__) @add_test_categories(["libc++"]) @skipIf(compiler=no_match("clang")) def test...
gs set target.import-std-module true") self.expect("expr (int)*w.lock()", substrs=['(int) $0 = 3']) self.expect("expr (int)(*w.lock() = 5)", substrs=['(int) $1 = 5']) self.expect("expr (int)*w.lock()", substrs=['(int) $2 = 5']) self.expect("expr w.use_count()", substrs=['(long) $3 = 1']...
postlund/home-assistant
homeassistant/components/alexa/auth.py
Python
apache-2.0
5,485
0.000365
"""Support for Alexa skill auth.""" import asyncio from datetime import timedelta import json import logging import aiohttp import async_timeout from homeassistant.core import callback from homeassistant.helpers import aiohttp_client from homeassistant.util import dt _LOGGER = logging.getLogger(__name__) LWA_TOKEN_...
nces(se
lf): """Load preferences with stored tokens.""" self._prefs = await self._store.async_load() if self._prefs is None: self._prefs = { STORAGE_ACCESS_TOKEN: None, STORAGE_REFRESH_TOKEN: None, STORAGE_EXPIRE_TIME: None, } ...
mrnohr/pi-temperature-firebase
firebase_log_roll.py
Python
mit
1,702
0.006463
import requests import time import json # ------------ Do data need to roll def roll_data_if_needed(secondsAllowed): # calculate last time last_roll_time = get_status() now = int(time.time()) time_since_roll = now - last_roll_time # do I need to roll? if time_since_roll > secondsAllowed: ...
mperatures-backup.json') # update status time data = '{{"lastRollTime": {:d}}}'.format(int(time.time())) firebasePut('status.json', data) # get current values response = firebaseGet('temperatures.json') current_values = response.text # add to backup firebasePut('temperatures-backup.js...
nt_values) # delete current values firebaseDelete('temperatures.json') # ------------ Firebase calls def firebaseGet(path): return requests.get(getFirebaseUrl(path), params=getFirebaseQueryParams()) def firebasePut(path, data): requests.put(getFirebaseUrl(path), params=getFirebaseQueryParams(), data=...
ESOedX/edx-platform
openedx/core/lib/tests/test_course_tab_api.py
Python
agpl-3.0
653
0
""" Tests for the plugin API """ from __futu
re__ import absolute_import from django.test import TestCase from openedx.core.lib.plugins import PluginError from openedx.core.lib.course_tabs import CourseTabPluginManager class TestCourseTabApi(TestCase): """ Unit tests fo
r the course tab plugin API """ def test_get_plugin(self): """ Verify that get_plugin works as expected. """ tab_type = CourseTabPluginManager.get_plugin("instructor") self.assertEqual(tab_type.title, "Instructor") with self.assertRaises(PluginError): ...
tanaes/decontaminate
decontaminate_unitary.py
Python
mit
40,011
0.006148
#!/usr/bin/env python # File created on 09 Aug 2012 from __future__ import division __author__ = "Jon Sanders" __copyright__ = "Copyright 2014, Jon Sanders" __credits__ = ["Jon Sanders"] __license__ = "GPL" __version__ = "1.9.1" __maintainer__ = "Jon Sanders" __email__ = "jonsan@gmail.com" __status__ = "Development" ...
m_fasta_filepath from bfillings.usearch import usearch_qf from scipy.stats import spearmanr import os.path from biom import load_table import numpy as np options_lookup = get_options_lookup() script_info = {} script_info['brief_description'] = """ A script to filt
er sequences by potential contaminants""" script_info['script_description'] = """ This script performs a series of filtering steps on a sequence file with the intent of removing contaminant sequences. It requires input of an OTU table, a sample map, an OTU map, a sequence FASTA file, and an output directory. There ar...
catapult-project/catapult
devil/devil/android/tools/device_recovery.py
Python
bsd-3-clause
9,284
0.010448
#!/usr/bin/env vpython # Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """A script to recover devices in a known bad state.""" import argparse import glob import logging import os import signal import sys ...
if denylist: denylist.Extend([device.adb.GetDeviceSerial()], reason='reboot_fai
lure') except device_errors.CommandTimeoutError: logger.exception('Timed out while rebooting %s.', str(device)) if denylist: denylist.Extend([device.adb.GetDeviceSerial()], reason='reboot_timeout') try: device.WaitUntilFullyBooted( retries=0, timeout=device.REBOOT_DEFAULT_TI...
tanglu-org/laniakea
src/lighthouse/lighthouse/events_receiver.py
Python
gpl-3.0
3,808
0.002101
# -*- coding: utf-8 -*- # # Copyright (C) 2018-2019 Matthias Klumpp <matthias@tenstral.net> # # Licensed under the GNU Lesser General Public License Version 3 # # 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...
_read_verify_key self._socket = None self._ctx = zmq.Context.instance() self._pub_queue = pub_queue self._endpoint = endpoint self._trusted_keys = {} # TODO: Implement auto-reloading of valid keys list if directory changes for keyfname in glob(os.path.join(Loc...
signer_id, verify_key = keyfile_read_verify_key(keyfname) if signer_id and verify_key: self._trusted_keys[signer_id] = verify_key def _event_message_received(self, socket, msg): data = str(msg[1], 'utf-8', 'replace') try: event = json.loads(data) ...
mumrah/kafka-python
kafka/structs.py
Python
apache-2.0
801
0.008739
from __future__ import absolute_import from collections import namedtuple # Other useful structs TopicPartition = namedtuple("TopicPartition", ["topic", "partition"]) BrokerMetadata = namedtuple("BrokerMetadata", ["nodeId", "host", "por
t", "rack"]) PartitionMetadata = namedtuple("PartitionMetadata", ["topic", "partition", "leader", "replicas", "isr", "error"]) OffsetAndMetadata = namedtuple("OffsetAndMetadata", # TODO add leaderEpoch: OffsetAndMetadata(offset, leaderEpoch, metadata) ["offset", "metadata"]) OffsetAndTimestamp = namedtup...
lue: int >= 0, 0 means no retries RetryOptions = namedtuple("RetryOptions", ["limit", "backoff_ms", "retry_on_timeouts"])
bcwaldon/changeling-client
changeling_client/core.py
Python
apache-2.0
386
0
import argparse import changeling_client.api import changeling_client.commands parser = argparse.ArgumentP
arser() parser.add_argument('--endpoint', required=True) subparsers = parser.add_subparsers() changeling_client.commands.register(subparsers) def main(): args = parser.parse_args() service = changeling_client.api.Service(args.endpoint)
args.func(service, args)
aouyar/PyMunin
pysysinfo/util.py
Python
gpl-3.0
13,551
0.006937
"""Implements generic utilities for monitoring classes. """ import sys import re import subprocess import urllib, urllib2 import socket import telnetlib __author__ = "Ali Onur Uyar" __copyright__ = "Copyright 2011, Ali Onur Uyar" __credits__ = [] __license__ = "GPL" __version__ = "0.9.12" __maintainer__ = "Ali Onur...
""" if isinstance(patterns, basestring): patt_list = (patterns,) elif isinstance(patterns, (tuple, list)): patt_list = list(patterns) else: raise ValueError("The patterns parameter must either be as
string " "or a tuple / list of strings.") if is_regex: if ignore_case: flags = re.IGNORECASE else: flags = 0 patt_exprs = [re.compile(pattern, flags) for pattern in patt_list] else: if ignore_ca...
Eagles2F/sync-engine
migrations/versions/115_eas_twodevices_turn.py
Python
agpl-3.0
3,146
0.003179
"""EAS two-devices turn Revision ID: 17dc9c049f8b Revises: ad7b856bcc0 Create Date: 2014-10-21 20:38:14.311747 """ # revision identifiers, used by Alembic. revision = '17dc9c049f8b' down_revision = 'ad7b856bcc0' from datetime import datetime from alembic import op import sqlalchemy as sa from sqlalchemy.sql import...
"""SELECT id, secondary_device_id from easaccount"""))) print 'acct_device_map: ', acct_device_map for acct_id, device_id in acct_device_map.iteritems(): conn.execute(text(""" UPDATE easfoldersyncstatus SET device_id=:device_id WHERE account_id=:acct_id ...
conn.execute(text(""" UPDATE easuid SET device_id=:device_id WHERE easaccount_id=:acct_id """), device_id=device_id, acct_id=acct_id) def downgrade(): raise Exception('!')
Wicloz/AnimeNotifierBot
bot.py
Python
mit
8,060
0.005335
import asyncio import pip import pickle import os.path try: import discord except: pip.main(['install', 'git+https://github.com/Rapptz/discord.py@async#egg=discord.py']) try: import win_unicode_console except: 0 try: from lxml import html except ImportError: pip.main(['install', 'lxml']) t...
lf.users.append(user)
print('Added user \'%s\' with url \'%s\'' % (userId, userUrl)) else: self.get_user(userId).userUrl = userUrl print('Updated bookmark url for user \'%s\'' % userId) with open('config/users.txt', 'wb') as file: pickle.dump(self.users, file) def han...
trec-dd/trec-dd-simulation-harness
trec_dd/__init__.py
Python
mit
272
0
'''tr
ec_dd.* namespace package can have several subpackages, see http://github.com/trec-dd for more info .. This software is released under an MIT/X11 open source license. Copyright 2015 Diffeo, Inc. ''' import pkg_resources pkg_resources.declare_namespace(__name__
)
CanalTP/navitia
source/jormungandr/jormungandr/scenarios/journey_filter.py
Python
agpl-3.0
32,453
0.00265
# Copyright (c) 2001-2015, Canal TP and/or its affiliates. All rights reserved. # # This file is part of Navitia, # the software to build cool stuff with public transport. # # Hope you'll enjoy and contribute to this project, # powered by Canal TP (www.canaltp.fr). # Help us simplify mobility and open public tr...
dp != 'indifferent': filters.append(FilterDirectPath(dp=dp)) dp_mode = request.get('direct_path_mode', []) if dp_mode: filters.append(FilterDirectPathMode(dp_mode)) # compose filters composed_filter = ComposedFilter()
for f in filters: composed_filter.add_filter(filter_wrapper(is_debug=is_debug, filter_obj=f)) journey_generator = get_qualified_journeys if is_debug: journey_generator = get_all_journeys return composed_filter.compose_filters()(journey_generator(responses)) class FilterTooShortHeavyJou...
lirui0081/depotwork
depotwork/questions/forms.py
Python
mit
1,000
0.023
from django import forms from depotwork.questions.models import Question, Answer class QuestionForm(forms.ModelForm): title = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}), max_length=255) description = forms.CharField(widget=forms.Textarea(attrs={'class':'form-control'}), ...
max_length=2000) tags = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}), max_length=255, required=False, help_text='Use spaces to separate the tags, such as "asp.net mvc5 javascript"') class Meta: model = Question fields = ['title', 'description...
orm(forms.ModelForm): question = forms.ModelChoiceField(widget=forms.HiddenInput(), queryset=Question.objects.all()) description = forms.CharField(widget=forms.Textarea(attrs={'class':'form-control', 'rows':'4'}), max_length=2000) class Meta: model = Answer fields = ['question', 'd...
tylerbrockett/reddit-bot-buildapcsales
src/bot_modules/reddit_handler.py
Python
mit
3,944
0.002535
""" ========================================== Author: Tyler Brockett Username: /u/tylerbrockett Description: Alert Bot (Formerly sales__bot) Date Created: 11/13/2015 Date Last Edited: 12/20/2016 Version: v2.0 ========================================== """ import praw im...
age_id) def send_message(self, redditor, subject, body): try: self.reddit.redditor(redditor).message(subject, body) except: Logger.log(traceback.format_exc(), Color.RED) raise RedditHelperException(RedditHelperException.SEND_MESSAGE_EXCEPTION) def get_submis...
try: subs = self.reddit.subreddit(subreddit).new(limit=posts) for submission in subs: submissions.append(submission) except Forbidden as e: Logger.log(traceback.format_exc(), Color.RED) return [] except Exception as e: Logg...
Wosser1sProductions/gr-lora
examples/lora-whitening/createWhiteningValues.py
Python
gpl-3.0
3,178
0.011328
#!/usr/bin/python2 import collections import os from loranode import RN2483Controller # from ../_examplify.py import Examplify import os os.sys.path.append(os.path.dirname(os.path.abspath('.'))) from _examplify import Examplify import lora, pmt, osmosdr from gnuradio import gr, blocks class ReceiveWhitening: de...
hitening = ReceiveWhitening(settings[0], dataf) for i in range(8): print("Sample {0:d} of 16".format(i)) examplifr.transmitToFile(['0' * 256] * 4, ofile) w
hitening.captureSequence(ofile) for i in range(8): print("Sample {0:d} of 16".format(i + 8)) examplifr.transmitToFile(['0' * 256] * 8, ofile) whitening.captureSequence(ofile) examplifr = None whitening = None
exaile/exaile
xl/externals/sigint.py
Python
gpl-2.0
2,472
0.002427
# # Allows GTK 3 python applications to exit when CTRL-C is raised # From htt
ps://bugzilla.gnome.org/show_bug.cgi?id=622084 # # Author: Simon Feltman # License: Presume same as pygobject # import sys import signal from typing import ClassVar, List from gi.repository import GLi
b class InterruptibleLoopContext: """ Context Manager for GLib/Gtk based loops. Usage of this context manager will install a single GLib unix signal handler and allow for multiple context managers to be nested using this single handler. """ #: Global stack context loops. This is added to per...
skosukhin/spack
var/spack/repos/builtin/packages/texlive/package.py
Python
lgpl-2.1
3,446
0.00058
############################################################################## # 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...
hed by the Free Software Foundation) versio
n 2.1, February 1999. # # 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 terms and # conditions of the GNU Lesser General Public License for more details. # # You should have ...
jeffrimko/Qprompt
examples/ask_2.py
Python
mit
177
0
import os import qprompt path = qpro
mpt.ask_str("Enter path to file", vld=lambda x: os.path.isfile(x)) size = qprompt.ask_int("Enter numb
er less than 10", vld=lambda x: x < 10)
jomolinare/kobocat
onadata/apps/main/tests/test_form_show.py
Python
bsd-2-clause
18,586
0
import os from unittest import skip from django.core.files.base import ContentFile from django.core.urlresolvers import reverse from onadata.apps.main.views import show, form_photos, update_xform, profile,\ enketo_preview from onadata.apps.logger.models import XForm from onadata.apps.logger.views import download_...
objects.latest('date_cr
eated') show_url = reverse(show, kwargs={ 'username': self.user.username, 'id_string': self.xform.id_string }) map_url = reverse(map_view, kwargs={ 'username': self.user.username, 'id_string': self.xform.id_string }) response = sel...
ceph/ceph-docker
maint-lib/stagelib/git.py
Python
apache-2.0
1,889
0.004764
# Copyright (c) 2017 SUSE LLC import logging import re import subprocess # Run a command, and return the result in string format, stripped. Return None if command fails. def _run_cmd(cmd_array): try: return subprocess.check_output(cmd_array).decode("utf-8").strip() except subprocess.CalledProcessErro...
ile_path): """If a file is new, modified, or deleted in git's tracking return True. False otherwise.""" file_status_msg = _run_cmd(['git', 'status', '--untracked-files=all', str(file_path)]) # git outputs filename on a line prefixed by whitespace if the file is new/modified/deleted if re.match(r'^\s*' +...
return False def branch_is_dirty(): """ If any files are new, modified, or deleted in git's tracking return True. False otherwise. """ branch_status_msg = _run_cmd(['git', 'status', '--untracked-files=all', '--porcelain']) # --porcelain returns no output if no changes if branch_status_msg: ...
brunetto/MasterThesisCode
master_code/otherMiscCode/CF_CCF-code-template/serial.py
Python
mit
14,251
0.008841
#!/usr/bin/env python ########################## # Modules import. ########################## import f_dist # to prevent segmentation fault import os import logging import sys, argparse import numpy as np import time from shutil import copy as shcopy import modules as mod ####################################...
ables passed to Main as a function (Guido docet # http://www.artima.com/weblogs/viewpost.jsp?thread=4829). for i in argv.keys(): if i in ("-f1", "--file_1"): v.file_1 = argv[i] elif i in ("-f2", "--file_2"): v.file_2 = argv[i] elif i ...
v.n_sel = argv[i] elif i in ("-s", "--strategy"): v.strategy = argv[i] elif i in ("-log", "-lg", "--log"): v.strategy = argv[i] elif i in ("-t", "--test"): v.test = True elif i in ("-c", "--console"): ...
devnull5475/SI_ORAWSV_POC
src/test/py/test.py
Python
gpl-2.0
206
0.004854
#!/bin/python import suds from suds.client import Client u = 'http://owsx:owsx_user@l
ocalhost:8080/orawsv/OWSX/OWSX_UTL/PAY_RAISE' h = {'User-Agent':'Mozilla/4.0'} client = Client(
u) print(client)
xeroz/admin-django
apps/players/migrations/0007_auto_20170806_1435.py
Python
mit
561
0.001783
# -*- coding: utf-8 -*- #
Generated by Django 1.11.1 on 2017-08-06 14:35 from __future__ import unicode_literals from d
jango.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('players', '0006_statistics'), ] operations = [ migrations.AlterField( model_name='statistics', name='player', field=models.One...
federicotdn/piter
src/colors.py
Python
gpl-3.0
477
0.069182
import curses from pygments import token class ColorProfile: def __init__(self): self._map = { token.Text : 4, token.Keyword : 3, token.Comment : 2, token.Number : 5, token.Name : 6, token.Error : 7, token.Punctuation : 8, token.Whitespace : 0 } def color_for(self, attr): #this shoul...
'attr', which is a Pygments token type if not attr in self._map: return 1
else: return self._map[attr]
0909023/Dev6B_English_Website
DjangoWebProject1/DjangoWebProject1/app/models.py
Python
mit
1,227
0.00978
""" Definition of models. """ from django.db import models from django.contrib.auth.models import User # Create your models here. # python manage.py makemigrations app progress = models.IntegerField(default=0) progress_v1 = models.IntegerField(default=0) progress_v2 = models.IntegerField(default=0) progress_v3 = mod...
contribute_to_class(User, 'progress_g1') progress_g2.contribute_to_class(User, 'progress_g2') progress_g3.cont
ribute_to_class(User, 'progress_g3') progress.contribute_to_class(User, 'progress') class exersize(models.Model): category = models.CharField(max_length = 50, default=0) question = models.CharField(max_length = 150, default=0) level = models.CharField(max_length = 2, default=0) class exersizeAnswerJoin(...
DanielAndreasen/SWEET-Cat
checkDuplicates.py
Python
mit
4,561
0.000658
import pandas as pd import numpy as np import warnings from clint.textui import colored warnings.simplefilter("ignore") class Sweetcat: """Load SWEET-Cat database""" def __init__(self): # self.fname_sc = 'WEBSITE_online_EU-NASA_full_database.rdb' self.fname_sc = 'WEBSITE_online_EU-NASA_full_d...
'\nApproximate RA/DEC ...')) # Remove the characters after the . in the coordinates
ra_sc = sc.SC['ra'].values.tolist() ra_approx = list(map(lambda i: i[:i.find('.')], ra_sc)) dec_sc = sc.SC['dec'].values.tolist() dec_approx = list(map(lambda i: i[:i.find('.')], dec_sc)) # Check for similar RA/DEC idx_duplicate = [] for idx, (ra, dec) in enumerate(zip(ra_approx, dec_approx)):...
imminent-tuba/thesis
server/chatterbot/chatterbot/adapters/logic/no_knowledge_adapter.py
Python
mit
659
0
from .logic import LogicAdapt
er class NoKnowledgeAdapter(LogicAdapter): """ This is a system adapter that is automatically added to the list of logic adapters durring initialization. This adapter is placed at the beginning of the list to be given the highest priority. """ def process(self, statement): """ ...
atabase, then a confidence of 1 should be returned with the input statement. Otherwise, a confidence of 0 should be returned. """ if self.context.storage.count(): return 0, statement return 1, statement
Ambuj-UF/ConCat-1.0
src/Utils/Bio/AlignIO/NexusIO.py
Python
gpl-2.0
7,881
0.002665
# Copyright 2008-2010 by Peter Cock. All rights reserved. # # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. """Bio.AlignIO support for the "nexus" file format. You are expected to use this module...
name=old_name, description="") for old_name, new_name in zip(n.unaltered_taxlabels, n.taxlabels)) # All done yield MultipleSeqAlignment(records, n.alphabet) class NexusWriter(AlignmentWriter):
"""Nexus alignment writer. Note that Nexus files are only expected to hold ONE alignment matrix. You are expected to call this class via the Bio.AlignIO.write() or Bio.SeqIO.write() functions. """ def write_file(self, alignments): """Use this to write an entire file containing the giv...
dimagi/commcare-hq
corehq/sql_db/__init__.py
Python
bsd-3-clause
5,334
0.002437
from django.apps import apps from django.conf import settings from django.core import checks from django.db import connections as django_connections, DEFAULT_DB_ALIAS, router from corehq.sql_db.exceptions import PartitionValidationError @checks.register('settings') def custom_db_checks(app_configs, **kwargs): er...
vs env_specific_apps = { 'icds_reports': settings.ICDS_ENVS, 'aaa': ('none',), } ignored_models = [ 'DeprecatedXFormAttachmentSQL' ] def _check_model(model_class, using=None): db = using or router.db_for_read(model_class)
try: with django_connections[db].cursor() as cursor: cursor.execute("SELECT %s::regclass", [model_class._meta.db_table]) except Exception as e: errors.append(checks.Error('checks.Error querying model on database "{}": "{}.{}": {}.{}({})'.format( using or...
marineam/nagcat
python/snapy/netsnmp/unittests/test_netsnmp.py
Python
apache-2.0
4,936
0.003241
# 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 Software Foundation. # # This program is distributed in the hope that it will be ...
elf.assert_(len(result[0][1]) > 0) return self.finishGet() class TestSessionV2c(TestSessionV1): version = "2c" def test_hrSystemDate(self): # This is a special string that gets formatted using the # MIB's DISPLAY-HINT value. Also, strip off everything # other than the date an
d hour to avoid a race condition. # And one more quirk, these dates are not zero padded # so we must format the date manually, whee... now = time.localtime() now = "%d-%d-%d,%d" % (now[0], now[1], now[2], now[3]) result = self.session.sget([OID(".1.3.6.1.2.1.25.1.2.0")]) ...
neuropower/neuropower
neuropower/apps/blog/views.py
Python
mit
393
0.015267
from __future__ import unicode_literals import sys
sys.path = sys.path[1:] from django.http import HttpResponseRedirect, HttpResponse from django.shortcuts import render, render_to_response from django.core.mail import send_mail from django.conf import settings import os def blog(request): context = {} context['thanks'] = Tru
e return render(request, "blog/blog.html", context)
CodeHuntersLab/RaspberryPi
WEB/Raspberry/manage.py
Python
gpl-3.0
807
0
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Raspberry.settings") try: from dja
ngo.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avo
id masking other # exceptions on Python 2. try: import django except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "f...
lachouettecoop/chouette-odoo
addons/chouette/pos_meal_voucher/models/__init__.py
Python
gpl-2.0
168
0
f
rom . import account_journal from . import barcode_rule from . import pos_config from .
import pos_order from . import product_category from . import product_template
fhqgfss/MoHa
moha/system/state.py
Python
mit
741
0.017544
import numpy as np from moha.system.basis import SlaterDeterminant class state(o
bject): def __init__(self): pass class WaveFunction(state): def __init__(self): pass class HFWaveFunction(WaveFunction): """ """ def __init__(self,dim,occ,coefficient,density,fock,eorbitals,Eelec,Etot): self.dim = dim self.occ = occ self.coefficient = coeffi...
@property def configuration(self): c = {} for spin in self.occ: c[spin] = [1]*self.occ[spin] + [0]*(self.dim - self.occ[spin]) return c
davidkleiven/PLOD
setup.py
Python
mit
534
0.001873
from setuptools import setup ''' The packages subprocess and tkinter is al
so required from the standard library ''' setup( name='PLOD', version='1.0', description='Matplotlib plot designer', author='David Kleiven', licence='MIT', author_email='dav
idkleiven446@gmail.com', install_requires=['numpy', 'matplotlib'], url='https://github.com/davidkleiven/PLOD', classifiers=[ 'Programming Language :: Python :: 3', ], #py_modules=['plotHandler', 'controlGUI'], packages=['PLOD'] )
chrfrantz/op-papers
oosd/week02/blackjack/hand.py
Python
gpl-3.0
952
0.003151
import deck class
Hand: def __init__(self): self.cards = [] def
add(self, card): self.cards.append(card) def size(self): return len(self.cards) def score(self): # sperate cards into aces and others regular_cards = [c for c in self.cards if c.value != "A"] aces = [c for c in self.cards if c.value == "A"] #tally up regular ca...
googleapis/python-dialogflow-cx
google/cloud/dialogflowcx_v3/services/flows/transports/base.py
Python
apache-2.0
9,463
0.001585
# -*- 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...
meout=None, client_info=client_info, ), self.get_flow: gapic_v1.method.wrap_method( self.get_flow, default_timeout=None, client_info=client_info, ), self.update_flow: gapic_v1.method.wrap_method( self.update_flow, default_timeout=None, clie...
ault_timeout=None, client_info=client_info, ), self.validate_flow: gapic_v1.method.wrap_method( self.validate_flow, default_timeout=None, client_info=client_info, ), self.get_flow_validation_result: gapic_v1.method.wrap_method( self.get_flo...
HelsinkiHacklab/urpobotti
python/motorctrl.py
Python
mit
3,257
0.00522
#!/usr/bin/env python # -*- coding: utf-8 -*- import zmq from zmq.eventloop import ioloop as ioloop_mod import zmqdecorators import time SERVICE_NAME = "urpobot.motor" SERVICE_PORT = 7575 SIGNALS_PORT = 7576 # How long to wait for new commands before stopping automatically COMMAND_GRACE_TIME = 0.250 class motorserv...
vice_name, service_port, serialport): super(motorserver, self).__init__(service_name, service_port) self.serial_port = serialport self.input_buffer = "" self.evthandler = ioloop_mod.IOLoop.instance().add_handler(self.serial_port.fileno(), self.handle_serial_event, ioloo
p_mod.IOLoop.instance().READ) self.last_command_time = time.time() self.pcb = ioloop_mod.PeriodicCallback(self.check_data_reveived, COMMAND_GRACE_TIME) self.pcb.start() def check_data_reveived(self, *args): if (time.time() - self.last_command_time > COMMAND_GRACE_TIME): ...
anithag/Shield
Authenticate.py
Python
gpl-2.0
851
0.025852
# Include the Dropbox SDK import dropbox class DropBoxSDK(): # Get your app key and secret from the Dropbox developer website app_key = '' app_secret = '' def authorize(self): flow = dropbox.client.DropboxOAuth2FlowNoRedirect(self.app_key, self.app_secret) authorize_url = flow.start() # Have the ...
in and authorize this token authorize_url = flow.start() print '1. Go to: ' + authorize_url print '2. Click "Allow" (you might have to log in first)' print '3. Copy the authorization code.' code = raw_input("Enter the authorization code here: ").strip() # This will fail if the user enters an invalid...
alculquicondor/psqlparse
setup.py
Python
bsd-3-clause
1,405
0
from setuptools import setup, Extension from setuptools.command.build_ext import build_ext import os.path import subprocess import sys libpg_query = os.path.join('.', 'libpg_query') class PSqlParseBuildExt(build_ext): def run(self): return_code = subprocess.call(['make', '-C', libpg_query, 'build']) ...
eSQL query parser', install_requires=['six'], license='BSD', cmdclass={'build_ext': PSqlParseBuildExt}, pack
ages=['psqlparse', 'psqlparse.nodes'], ext_modules=extensions)
koonsolo/MysticMine
monorail/koon/app.py
Python
mit
4,111
0.016784
import sys import gc import pygame from pygame.locals import * from input import * import snd TICKS_PER_SECOND = 25 GAMETICKS = 1000 / TICKS_PER_SECOND def set_game_speed( slowdown ): global TICKS_PER_SECOND global GAMETICKS TICKS_PER_SECOND = int( 25 * slowdown ) GAMETICKS = 100...
key.feed_up( event.key ) elif event.type == MOUSEBUTTONDOWN: self.userinput.mouse.feed_down( event.button ) self.state.mouse_down( event.button ) elif event.type == MOUSEBUTTONUP:
self.userinput.mouse.feed_up( event.button ) elif event.type == JOYBUTTONDOWN: self.userinput.joys[event.joy].feed_down( event.button ) elif event.type == JOYBUTTONUP: self.userinput.joys[event.joy].feed_up( event.button ) def draw_fps( self, surfa...
apophys/err
errbot/plugin_wizard.py
Python
gpl-3.0
4,848
0.001444
#!/usr/bin/env python import errno import os import re import sys from configparser import ConfigParser import jinja2 from errbot.version import VERSION def new_plugin_wizard(directory=None): """ Start the wizard to create a new plugin in the current working directory. """ if directory is None: ...
te a new plugin for you in the c
urrent directory.") directory = os.getcwd() else: print(f'This wizard will create a new plugin for you in "{directory}".') if os.path.exists(directory) and not os.path.isdir(directory): print(f'Error: The path "{directory}" exists but it isn\'t a directory') sys.exit(1) nam...
clearclaw/xxpaper
xxpaper/contents.py
Python
gpl-3.0
590
0.030508
#! /usr/bin/env python import logging, logtool from .page import Page from .xlate_frame import XlateFrame LOG = logging.getLogger (__name__) class Contents: @logtool.log_call def __init__ (self, canvas, objects): self.canvas = canvas self.objects = objects @logtool.log_call def render (self): w...
, *coords, inset_by = "ma
rgin"): # print ("Obj: ", obj.asset) obj.render ()
UVicRocketry/Hybrid-Test-Stand-Control
client/hybrid_test_backend.py
Python
gpl-3.0
4,879
0.005124
from PyQt5 import QtWidgets, uic, QtCore import sys class MainWindow(QtWidgets.QMainWindow): def __init__(self, *args, **kwargs): # Load the UI Page. uic is the thing that lets us use a .ui file # This only works if the .ui file is in the same directory super(MainWindow, self).__in...
on.clicked.connect(self._NCV_btn_on) self.RV_btn_off.clicked.connect(self._RV_btn_off) self.RV_btn_on.clicked.connect(self._RV_btn_on) self.VV_btn_off.clicked.connect(self._VV_btn_off) self.VV_btn_on.clicked.connect(self._VV_btn_on) self.abort_btn.clicke
d.connect(self._abort_btn) self.run_btn.clicked.connect(self._run_btn) def _connect_btn(self): self.state_connected = True print(self.state_connected) def _disconnect_btn(self): self.state_connected = False print(self.state_connected) def _ig...
hryamzik/ansible
lib/ansible/parsing/yaml/dumper.py
Python
gpl-3.0
2,336
0.001284
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # # This file is part of Ansible # # Ansible 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) an...
rs import HostVars, HostVarsVars class AnsibleDumper(yaml.SafeDumper): ''' A simple stub class that allows us to add representers for our overridden object types. ''' pass def represent_hostvars(self, data): return self.represent_dict(dict(data)) # Note: only want to represent the encrypte...
data def represent_vault_encrypted_unicode(self, data): return self.represent_scalar(u'!vault', data._ciphertext.decode(), style='|') if PY3: represent_unicode = yaml.representer.SafeRepresenter.represent_str else: represent_unicode = yaml.representer.SafeRepresenter.represent_unicode AnsibleDumper.add_r...
hachreak/invenio-access
invenio_access/alembic/67ba0de65fbb_create_access_branch.py
Python
gpl-2.0
1,279
0
# # This file is part of Invenio. # Copyright (C) 2016, 2017 CERN. # # Invenio is free software; you can redistribute it # and/or modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your option) any later version. # # Inve...
nc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307, USA. # # In applying this license, CERN does not # waive the privileges and immunities granted to it by virtue of its status # as an Intergovernmental Organizati
on or submit itself to any jurisdiction. """Create access branch.""" import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision = '67ba0de65fbb' down_revision = None branch_labels = (u'invenio_access', ) depends_on = 'dbdbc1b19cf2' def upgrade(): """Upgrade database.""" ...
iamahuman/angr
angr/procedures/posix/socket.py
Python
bsd-2-clause
728
0.005495
import angr ###################################### # socket ################################
###### class socket(angr.SimProcedure): #pylint:disable=arguments-differ def run(self, domain, typ, protocol): c
onc_domain = self.state.solver.eval(domain) conc_typ = self.state.solver.eval(typ) conc_protocol = self.state.solver.eval(protocol) if self.state.posix.uid != 0 and conc_typ == 3: # SOCK_RAW return self.state.libc.ret_errno('EPERM') nonce = self.state.globals.get('socket_co...
philrosenfield/TPAGB-calib
selection_tests.py
Python
bsd-3-clause
8,573
0.008748
import os import numpy as np import sfh_tests import ResolvedStellarPops as rsp from TPAGBparams import snap_src import galaxy_tests def ms_color_cut(): comp90 = sfh_tests.read_completeness_table(absmag=True) tri_dir = os.environ['TRILEGAL_ROOT'] # make these simulations by editing a constant sf trilegal f...
ter1, photsys, **m2m) mag2 = rsp.astronomy_utils.Mag2mag(Mag2, filter2, photsys, **m2m) color = mag1 - mag2 color_uncert = comp90_uncert[i]['%s_color' % band] print target, fi
lter1, filter2, '%.2f' % (color+color_uncert) def find_contamination_by_phases(output_files=None): if output_files is None: output_files = [ snap_src + '/models/varysfh/ddo71/caf09_s_nov13/mc/output_ddo71_caf09_s_nov13.dat', #snap_src + '/models/varysfh/ddo78/caf09_s_nov13/mc/ou...
bnoi/scikit-tracker
sktracker/trajectories/tests/test_trajectories.py
Python
bsd-3-clause
14,672
0.003476
# -*- coding: utf-8 -*- from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import from __future__ import print_function from nose.tools import assert_raises from nose.tools import assert_dict_equal from numpy.testing import assert_array_equal from numpy.testing ...
(4, 4): 24.644945052453025, (0, 2): np.nan, (2, 0): 5.6292750381105723, (4, 3): 13.209596167161628, (2, 2): -3.7469188310869228, (3, 4): -17.381636024737336, (1, 1): 13.827909766138866} ass...
s = trajs.get_speeds().tolist() real_speeds = [np.nan, np.nan, np.nan, np.nan, np.nan, 857.99153458573994, 1596.9530747771976, 873.15267834726137, 1282.30881745982...
cowlicks/dask
dask/array/reductions.py
Python
bsd-3-clause
22,730
0.001232
from __future__ import absolute_import, division, print_function from functools import partial, wraps from itertools import product, repeat from math import factorial, log, ceil import operator import numpy as np from toolz import compose, partition_all, merge, get, accumulate, pluck from . import chunk from .core i...
ncname(combine or aggregate)) + '-partial') func = compos
e(partial(aggregate, axis=axis, keepdims=keepdims), partial(_concatenate2, axes=axis)) return partial_reduce(func, x, split_every, keepdims=keepdims, dtype=dtype, name=(name or funcname(aggregate)) + '-aggregate') def partial_reduce(func, x, s...
oasis-open/cti-pattern-validator
stix2patterns/v21/grammars/STIXPatternVisitor.py
Python
bsd-3-clause
6,827
0.01787
# Generated from STIXPattern.g4 by ANTLR 4.9.2 from antlr4 import * if __name__ is not None and "." in __name__: from .STIXPatternParser import STIXPatternParser else: from STIXPatternParser import STIXPatternParser # This class defines a complete generic visitor for a parse tree produced by STIXPatternParser....
ernParser.ObjectPathContext): return self.visitChildren(ctx) # Visit a parse tree produced by STIXPatternParser#objectType. def visitObjectType(self, ctx:STIXPatternParser.ObjectTypeContext): return self.visitChildren(ctx) # Visit a parse tree produced by STIXPatternParser#firstPathCompo...
ntext): return self.visitChildren(ctx) # Visit a parse tree produced by STIXPatternParser#indexPathStep. def visitIndexPathStep(self, ctx:STIXPatternParser.IndexPathStepContext): return self.visitChildren(ctx) # Visit a parse tree produced by STIXPatternParser#pathStep. def visitPath...
forgeousgeorge/new_dir
code.py
Python
mit
179
0.01676
def Woody(): # comple
te print "Reach for the sky but don't burn your wings!"
# this will make it much easier in future problems to see that something is actually happening
evilhero/mylar
mylar/parseit.py
Python
gpl-3.0
36,412
0.010354
# This file is part of Mylar. # # Mylar 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. # # Mylar 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 d...
, UnicodeDammit import urllib2 import re import helpers import logger import datetime import sys from decimal import Decimal from HTMLParser import HTMLParseError from time import strptime import mylar def GCDScraper(ComicName, ComicYear, Total, ComicID, quickmatch=None): NOWyr = datetime.date.today().year if ...
offbyone/Flexget
flexget/webserver.py
Python
mit
9,166
0.002837
from __future__ import unicode_literals, division, absolute_import import logging import threading im
port hashlib import random import socket from sqlalchemy import Column, Integer, Unicode from flask import Flask, abort, redirect from flask.ext.login import UserMixin from flexget import options, plugin from flexget.event import event from flexget.config_schema import register_config_key from flexget.utils.tools im...
er('web_server') _home = None _app_register = {} _default_app = Flask(__name__) random = random.SystemRandom() web_config_schema = { 'oneOf': [ {'type': 'boolean'}, { 'type': 'object', 'properties': { 'bind': {'type': 'string', 'format': 'ipv4', 'default': ...
retr0h/ansible
lib/ansible/inventory/__init__.py
Python
gpl-3.0
15,950
0.005078
# (c) 2012, Michael DeHaan <michael.dehaan@gmail.com> # # This file is part of Ansible # # Ansible 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. # # Ansible 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 deta...
#################### import fnmatch import os import re import subprocess import ansible.constants as C from ansible.inventory.ini import InventoryParser from ansible.inventory.script import InventoryScript from ansible.inventory.dir import InventoryDirectory from ansible.inventory.group import Group from ansible.inv...
Saturn/champsleagueviz
qualify/dl.py
Python
mit
1,765
0.006799
import re, requests, csv, time, traceback from bs4 import BeautifulSoup teams = [] for group in ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']: try: url = "http://www.oddschecker.com/football/champions-league/champions-league-group-%s/to-qualify" % group print "getting {}".format(url) soup = Beau...
e = cols[1] if 'any other' in name.lower(): continue odds = [] isanodd = lambda t: (t.name=="td" and t.has_attr("class") and ('o' in t.attrs["class"] or 'oi' in t.attrs["class"] or ...
ds.append(None) else: odds.append(float(o)) assert len(odds) == len(sites), "{} {}".format(odds, sites) teams.append([name, group] + odds) except: print "Unexpected error. skipping" traceback.print_exc() t = str(time.time()).split(".")[0] with...
damien-dg/horizon
openstack_dashboard/contrib/sahara/api/sahara.py
Python
apache-2.0
15,639
0
# 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, software # distributed under the...
templates.list(search_opts=search_opts) def nodegroup_template_get(request, ngt_id): return client(request).node_group_templates.get(ng_template_id=ngt_id) def nodegroup_template_find(request, **kwargs): return client(request).node_group_templates.find(**kwargs) def nodegroup_template_delete(request, ngt_...
ates.delete(ng_template_id=ngt_id) def nodegroup_template_update(request, ngt_id, name, plugin_name, hadoop_version, flavor_id, description=None, volumes_per_node=None, volumes_size=None, node_processes=None, ...
Andrey-Tkachev/infection
models/room.py
Python
mit
6,066
0.000989
from bson.objectid import ObjectId import json class Room(): def __init__(self, players_num, objectid, table, current_color='purple'): if players_num: self.players_
num = players_num else: self.players_num = 0 for el in ['p', 'b', 'g', 'r']: if el in table: self.players_num += 1
self.objectid = objectid self.current_color = current_color self.players_dict = {} self.alredy_ex = [] self.colors = [] self.winner = None for col in ['p', 'b', 'g', 'r']: if col in table: self.colors.append( {'p': 'purpl...
trolleway/domofoto_parser
parce_city.py
Python
cc0-1.0
4,024
0.044757
#!/usr/bin/env python # -*- coding: utf-8 -*- # anchor extraction from html document from bs4 import BeautifulSoup import urllib2 import urlparse import re import csv import time cityId='712' webpage = urllib2.urlopen('http://domofoto.ru/list.php?cid='+cityId) soup = BeautifulSoup(webpage) maxST=0 for eleme...
n ogr2ogr vrt_file='''
<OGRVRTDataSource> <OGRVRTLayer name="'''+csvFileName+'''"> <LayerSRS>WGS84</LayerSRS> <SrcDataSource>'''+csvFileName+'''.csv</SrcDataSource> <GeometryType>wkbPoint</GeometryType> <GeometryField encoding="PointFromColumns" x="x" y="y"/> </OGRVRTLayer> </OGRVRTDataSource> ''' vrtf ...
mcclurmc/juju
juju/providers/orchestra/tests/test_bootstrap.py
Python
agpl-3.0
5,474
0
from xmlrpclib import Fault from yaml import dump from twisted.internet.defer import succeed, inlineCallbacks from juju.errors import ProviderError from juju.lib.testing import TestCase from juju.providers.orchestra.machine import OrchestraMachine from juju.providers.orchestra.tests.common import OrchestraTestMixin ...
tem", "some-handle", "mgmt_classes", ["available", "PRESERVE"], "TOKEN") self.mocker.result(succeed(True)) self.proxy_m.callRemote( "modify_system", "some-handle", "netboot_enabled", True, "TOKEN") self.mocker.result(succeed(True)) self.proxy_m.callRemote("save_s
ystem", "some-handle", "TOKEN") self.mocker.result(succeed(True)) self.proxy_m.callRemote( "background_power_system", {"power": "off", "systems": ["winston"]}, "TOKEN") self.mocker.result(succeed("ignored")) def test_already_bootstrapped(self): self.setup_moc...
eustislab/horton
horton/io/test/test_cp2k.py
Python
gpl-3.0
2,512
0.004379
# -*- coding: utf-8 -*- # HORTON: Helpful Open-source Research TOol for N-fermion systems. # Copyright (C) 2011-2015 The HORTON Development Team # # This file is part of HORTON. # # HORTON is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by th...
< 1e-5 assert abs(np.dot(cb.T, np.dot(olp._array, cb)) - np.identity(4)).max() < 1e-5 def test_atom_o_rks(): fn_out = context.get_fn('test/atom_om2.cp2k.out') mol = IOData.from_file(fn_out) assert (mol.numbers == [8]).all() assert (mol.pseudo_numbers == [6]).all() assert (mol.exp_alpha.occu...
assert abs(mol.exp_alpha.energies - [0.102709, 0.606458, 0.606458, 0.606458]).max() < 1e-4 assert abs(mol.energy - -15.464982778766) < 1e-10 assert (mol.obasis.shell_types == [0, 0, 1, 1, -2]).all() olp = mol.obasis.compute_overlap(mol.lf) ca = mol.exp_alpha.coeffs assert abs(np.dot(ca.T, np.d...
krakky/market
cloudera_cdh/bin/ubuntu/xenial/12-activate-parcel.py
Python
apache-2.0
1,599
0.026892
#!/usr/bin/python from cm_api.api_client import ApiResource import time api = ApiResource(sys.argv[1], 7180, "acm", "SCALE42secretly", version=15) cluster = None try: cluster = api.get_cluster(name = "ACM Cluster") except Exception, e: if e.message[-
10:-1].lower() == "not found": print "<ACM CLUSTER> NOT FOUND ! - not proceeding any further..." exit() #Find available parcels... available_parcels = cluster.get_all_parcels() CDH_TARGET = None for p in available_parcels: if p.product.lower() == "cdh" and p.version[:1] == "5": CDH_TARGET ...
ersion" : p.version } break if CDH_TARGET is not None: parcel = cluster.get_parcel(CDH_TARGET['name'] , CDH_TARGET['version']) if parcel.stage == "ACTIVATED": print "Parcel <{0}-v{1}> is already <ACTIVATED> across the entire cluster !".format(CDH_TARGET['name'] , CDH_TARGET['version']) elif parcel...
bobrock/eden
languages/ja.py
Python
mit
353,167
0.022626
# -*- coding: utf-8 -*- { "A location that specifies the geographic area for this region. This can be a location from the location hierarchy, or a 'group location', or a location that has a boundary for the area.": 'この地域を地理的に指定するロケーション。これはロケーションの階層構造のうちの一つか、ロケーショングループの一つか、この地域の境界に面するロケーションです。', "Acronym of the organ...
example, if 'district' is the smallest division in the hierarchy, then all specific loc
ations would be required to have a district as a parent.": 'もし全ての特定の場所が住所階層の最下層で親の場所を必要とするなら、これを選択して下さい。例えば、もし「地区」が階層の最小の地域なら、全ての特定の場所は親階層の地区を持っている必要が有るでしょう。', "Select this if all specific locations need a parent location in the location hierarchy. This can assist in setting up a 'region' representing an affected area...
j-mracek/dnf
tests/test_config.py
Python
gpl-2.0
5,503
0.000545
# -*- coding: utf-8 -*- # Copyright (C) 2012-2018 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) any later version. # This program is distributed ...
conf = Conf() # if repoconf reads value from config it no more inherits changes from conf conf.config_file_path = tests.support.resource_path('etc/repos.conf') with mock.patch('logging.Logger.warning'): reader = dnf.conf.read.RepoReader(conf, {})
repo = list(reader)[0] self.assertEqual(conf.minrate, 1000) self.assertEqual(repo.minrate, 4096) # after global change conf.minrate = 2000 self.assertEqual(conf.minrate, 2000) self.assertEqual(repo.minrate, 4096) def test_prepend_installroot(self): ...
telefonicaid/fiware-facts
tests/acceptance/fiwarecloto_client/client.py
Python
apache-2.0
4,297
0.002095
# -*- coding: utf-8 -*- # Copyright 2015 Telefonica Investigación y Desarrollo, S.A.U # # This file is part of FIWARE project. # # 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://w...
ssword=password, tenant_id=tenant_id, auth_url=auth_url) def _get_auth_token(self): """ Get token from Keystone :return: Token (String) """ __logger__.debug("Getting auth Token") return self.keystone_client.auth_ref['tok...
nt_id_resource_client(self): """ Create an API resource REST client :return: Rest client for 'TenantId' API resource """ __logger__.info("Creating TenantIdResource") return TenantIdResourceClient(protocol=self.api_protocol, host=self.api_host, ...
elamperti/bastardbot
webserver.py
Python
mit
507
0.013807
#!/usr/bin/env python #import logging from webserver import * if __name__ == '__main__': #logging.basicConfig( # format="[%(asctime)s] %(name)s/%(levelname)-6s - %(message)s", # level=logging.CRITICAL, # datefmt='%
Y-%m-%d %H:%M:%S' #) # Only enable debug level for
bbot #logger = logging.getLogger('bastardbot') #logger.setLevel(logging.DEBUG) print("Initializing BastardBot web server...") B = BastardBot() print("BastardBot server stopped.")
jsbueno/sc.blueprints.soundcloud
sc/blueprints/soundcloud/setuphandlers.py
Python
gpl-2.0
386
0
# -*- coding: u
tf-8 -*- import logging # define here the methods needed to be run at install time
def importVarious(context): if context.readDataFile('sc.blueprints.soundcloud_various.txt') is None: return logger = logging.getLogger('sc.blueprints.soundcloud') # add here your custom methods that need to be run when # sc.blueprints.soundcloud is installed
ronaldahmed/labor-market-demand-analysis
rule based major_extractor/count_custom_vhs.py
Python
mit
4,738
0.041368
import os, sys import json import copy import numpy as np import random from multiprocessing import Pool import ipdb ################################################################################################ utils_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),'nlp scripts') source_vh_dir = '/ho...
eemap_name+'.json','w').write(json.dumps(hierarchy,ensure_ascii=False, indent = 2)) per_hierarchy = dict(hierarchy) temp = [format(x,'.2f') for x in 100.0*freq_major/count_id_vh] tot = sorter(per_hierarchy,temp,file_dict) open(treemap_name+'_perc.
json','w').write(json.dumps(per_hierarchy,ensure_ascii=False, indent = 2)) # GENERATE ADJMATRIX.JSON sorted_ids = [] getSortedLeaves(hierarchy,sorted_ids,file_dict) adjmatrix = [] for k in sorted_ids: if freq_major[k]==0: continue u = file_dict.get_label_name(k) item = dict() item["name"] = nameByFile[...
gkc1000/pyscf
pyscf/gto/test/test_ecp.py
Python
apache-2.0
10,394
0.010391
#!/usr/bin/env python # Copyright 2014-2018 The PySCF Developers. 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 # # U...
Na 0. 0. 0.', basis={'Na':'bfd-vtz'}, ecp = {'Na':'bfd-pp'}, spin = 1, verbose=0) mf = scf.RHF(mol) self.assertAlmostEqual(mf.kernel(), -0.181799, 6) mol = gto.M(atom='Mg 0. 0. 0.', basis={'Mg':'...
spin = 0, verbose=0) mf = scf.RHF(mol) self.assertAlmostEqual(mf.kernel(), -0.784579, 6) # mol = gto.M(atom='Ne 0. 0. 0.', # basis={'Ne':'bfd-vdz'}, # ecp = {'Ne':'bfd-pp'}, # verbose=0) # mf = scf.RHF(mo...
almarklein/scikit-image
skimage/transform/tests/test_geometric.py
Python
bsd-3-clause
7,870
0
import numpy as np from numpy.testing import (assert_equal, assert_array_almost_equal, assert_raises) from skimage.transform._geometric import _stackcopy from skimage.transform._geometric import GeometricTransform from skimage.transform import (estimate_transform, matrix_transform, ...
.5025], [6.7905, -6.3765], [-6.1695, -0.8235], ]) DST = np.array([ [0, 0], [0, 5800], [4900, 5800], [4900, 0], [4479, 4580], [1176, 3660], [3754, 790], [1024, 1931], ]) def test_stackcopy(): layers = 4 x = np.empty((3, 3, layers)) y = np.eye(3, 3) _stackcopy(x, ...
], y) def test_estimate_transform(): for tform in ('similarity', 'affine', 'projective', 'polynomial'): estimate_transform(tform, SRC[:2, :], DST[:2, :]) assert_raises(ValueError, estimate_transform, 'foobar', SRC[:2, :], DST[:2, :]) def test_matrix_transform(): tform = AffineT...
antoinecarme/pyaf
tests/artificial/transf_BoxCox/trend_MovingAverage/cycle_12/ar_12/test_artificial_32_BoxCox_MovingAverage_12_12_20.py
Python
bsd-3-clause
266
0.086466
import pyaf.Bench.TS_datasets as tsds import tests.artificial.process_artificial_dataset as art art.pro
cess_dataset(N = 32 , FREQ = 'D', seed = 0, trendtype = "MovingAverage", cycle_length = 12, transform
= "BoxCox", sigma = 0.0, exog_count = 20, ar_order = 12);
ufjfeng/leetcode-jf-soln
python/220_contains_duplicate_iii.py
Python
mit
1,718
0.001746
""" Given an array of integers, find out whether there are two distinct indices i and j in the array such that the difference between nums[i] and nums[j] is at most t and the difference between i and j is at most k. """ class Solution(object): def containsNearbyAlmostDuplicate(self, nums, k, t): """ ...
y] = nums[i] if i >= k: del buckets[nums[i - k] // width] return False import collections a = Solution() print(a.containsNearbyAlmostDuplicate([-1, -1], 1, 0)) print(a.containsNearbyAlmostDuplicate([1, 3, 1], 1, 1)) print(a.containsNearbyAlmostDuplicate([10, 20, 30, 25, 50], 2, 6)) ...
difference <= t, one of the two will happen: (1) the two in the same bucket (2) the two in neighbor buckets https://discuss.leetcode.com/topic/27608/java-python-one-pass-solution-o-n-time-o-n-space-using-buckets """
Sparsh-Sharma/SteaPy
steapy/freestream.py
Python
mit
651
0.004608
import os import numpy from numpy import * import math from scipy import integrate, linalg from matplotlib import pyplot from pylab import * class Freestream:
""" Freestream conditions. """ def __init__(self, u_inf=1.0, alpha=0.0):
""" Sets the freestream speed and angle (in degrees). Parameters ---------- u_inf: float, optional Freestream speed; default: 1.0. alpha: float, optional Angle of attack in degrees; default 0.0. """ self.u...
ClinGen/clincoded
src/contentbase/upgrader.py
Python
mit
6,948
0.000288
from pkg_resources import parse_version from pyramid.interfaces import ( PHASE1_CONFIG, PHASE2_CONFIG, ) import venusian def includeme(config): config.registry['migrator'] = Migrator() config.add_directive('add_upgrade', add_upgrade) config.add_directive('add_upgrade_step', add_upgrade_step) c...
on, finalizer) self.schema_migrators[schema_name] = schema_migrator def upgrade(self, schema_name, value, current_version='', target_version=None, **kw): schema_migrator = self.schema_migrators[schema_name] return schema_migrator.upgrade( value, current_version, ...
in self.schema_migrators class SchemaMigrator(object): """ Manages upgrade steps """ def __init__(self, name, version, finalizer=None): self.__name__ = name self.version = version self.upgrade_steps = {} self.finalizer = finalizer def add_upgrade_step(self, step, sour...
PuchatekwSzortach/travelling_salesman_problem
main.py
Python
mit
1,223
0.004906
import tsp.algorithms import time if __name__ == "__main__": cities_number = 5 max_distance = 100 distances_matrix = tsp.algorithms.get_random_distances_matrix(cities_number, max_distance) start = time.time() optimal_path = tsp.algorithms.BruteForceTSPSolver(distances_matrix).solve() print(...
int("Distance is " + str(tsp.algorithms.get_trip_distance(distances_matrix, optimal_path))) print("Computational time is: {0:.2f} seconds".format(time.time() - start)) start = time.time() worst_path = tsp.algorithms.BruteForceTSPWorstPathSolver(distances_matrix).solve() print("\nWorst path is " + str(w...
istance(distances_matrix, worst_path))) print("Computational time is: {0:.2f} seconds".format(time.time() - start)) start = time.time() boltzmann_path = tsp.algorithms.BoltzmannMachineTSPSolver(distances_matrix).solve() print("\nBoltzmann path is " + str(boltzmann_path)) print("Distance is " + str(...
maehler/seqpoet
seqpoet/tests/test_sequence.py
Python
mit
1,544
0.000648
import os import re from nose.tools import raises import seqpoet class TestSequence: def setup(self): self.seq1 = 'ACATacacagaATAgagaCacata' self.illegal = 'agagcatgcacthisisnotcorrect' def test_sequence_length(self): s = seqpoet.Sequence(self.seq1) assert len(s) == len(self...
== '<Sequence: acata...>' assert repr(s.revcomp()) == '<Sequence: tatgt...>' def test_indexing(self): s = seqpoet.Sequence(self.seq1) assert s[4] == 'a' assert s[:5] == 'acata' assert s[-6:] == 'cacata' assert s[4:8] == 'acac' def test_equality(self): s ...
eError) def test_illegal_characters(self): s = seqpoet.Sequence(self.illegal)
alex-pardo/6degrees
twython-master/twython-master/tests/test_auth.py
Python
gpl-2.0
3,025
0.001983
from twython import Twython, TwythonError, TwythonAuthError from .config import app_key, app_secret, screen_name import unittest class TwythonAuthTestCase(unittest.TestCase): def setUp(self): self.api = Twython(app_key, app_secret) self.bad_api = Twython('BAD_APP_KEY', 'BAD_APP_SECRET') ...
ication_tokens(callback_url='http://google.com/', force_login=True, screen_name=screen_name) def test_get_authentication_tokens_bad_tokens(self): """Test getting authentication tokens with bad tokens raises Twytho...
hentication_tokens, callback_url='http://google.com/') def test_get_authorized_tokens_bad_tokens(self): """Test getting final tokens fails with wrong tokens""" self.assertRaises(TwythonError, self.bad_api.get_authorized_tokens, 'BAD_OAUTH_VERIFIER...
nvbn/Unofficial-Google-Music-API
gmusicapi/protocol/metadata.py
Python
bsd-3-clause
8,707
0.004709
# -*- coding: utf-8 -*- """ All known information on metadata is exposed in ``gmusicapi.protocol.metadata.md_expectations``. This holds a mapping of *name* to *Expectation*, where *Expectation* has the following fields: *name* key name in the song dictionary (equal to the *name* keying ``md_expectations``). *type...
num: 1: free/purchased, 2: uploaded/not matched, 6: uploaded/matched'), ('beatsPerMinute', 'integer', "the server does not calculate this - it's just what was in track metadata"), ('subjectToCuration', 'boolean', 'meaning unknown.'), ('curatedByUser', 'boolean'
, 'meaning unknown'), ('curationSuggested', 'boolean', 'meaning unknown'), ) ] + [ Expectation(name, type_str, mutable=False, optional=True, explanation=explain) for (name, type_str, explain) in ( ('storeId', 'string', 'an id of a matching track in the Play Store.'), ('reuploadin...