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
ekasitk/sahara
sahara/service/validations/edp/job_binary_internal.py
Python
apache-2.0
1,066
0
# Copyright (c) 2013 Mirantis 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 writ...
er the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. import sahara.exceptions as e from sahara.i18n import _ from sahara.utils import api_val...
n() if "name" in kwargs: name = kwargs["name"] if not a.validate_name_format(name): raise e.BadJobBinaryInternalException(_("%s is not a valid name") % name)
lief-project/LIEF
examples/python/dex_reader.py
Python
apache-2.0
6,753
0.00696
#!/usr/bin/env python # -*- coding: utf-8 -*- # Description # ----------- # Print information about Android DEX files import sys import os import argparse import traceback import lief from lief import DEX EXIT_STATUS = 0 terminal_rows, terminal_columns = 100, 100 try: terminal_rows, terminal_columns = os.popen('s...
ck = on_except_callback def __call__(self, *args, **kwargs): if self.func is None: self.func = args[0] return self try: return self.func(*args, **kwargs) except self.exceptions as e: global EXIT_STATUS print("{} raised: {}".format(...
self.on_except_callback(e) else: print("-" * 60) print("Exception in {}: {}".format(self.func.__name__, e)) exc_type, exc_value, exc_traceback = sys.exc_info() traceback.print_tb(exc_traceback) print("-" * 60) @except...
dongjoon-hyun/tensorflow
tensorflow/python/util/decorator_utils.py
Python
apache-2.0
3,614
0.010238
# Copyright 2016 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...
'__qualname__'): return function.__qualname__ # Python 2 if hasattr(function, 'im_class'): return function.im_class.__name__ + '.' + function.__name__ return function.__name__ def _normalize_docstring(docstring): """Normalizes the docstring. Replaces tabs with spaces, removes leading and trailing...
cstring-indentation Args: docstring: the docstring to normalize Returns: The normalized docstring """ if not docstring: return '' # Convert tabs to spaces (following the normal Python rules) # and split into a list of lines: lines = docstring.expandtabs().splitlines() # Determine minimum i...
mrcslws/nupic.research
packages/backprop_structure/src/nupic/research/frameworks/backprop_structure/experiments/mixins/rezero_weights.py
Python
agpl-3.0
1,207
0
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2019, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This progra...
ro Public License version 3 as # published by the Free Software 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 Affero Public Licens
e for more details. # # You should have received a copy of the GNU Affero Public License # along with this program. If not, see http://www.gnu.org/licenses. # # http://numenta.org/licenses/ # ---------------------------------------------------------------------- from nupic.torch.modules import rezero_weights class ...
kangareuben/PuppysPen
archive/test_gtk.py
Python
mit
2,805
0.010339
#!/usr/bin/python # what's the difference between these two? #from gi.repository import Gtk #from gtk import gdk import os import gobject import gtk import Constants class Window(gtk.Window): def __init__(self): gtk.Window.__init__(self) self.set_resizable(False) self.set_size_request(C...
self.start_btn, True, False, 10) self.add(self.main_bbox) print(self.main_bbox) def game_screen(self): if (self.main_bbox): self.remove(self.main_bbox) self.main_bbox = None self.game_bbox = gtk.HButtonBox() self.back_btn = gtk.Button("Menu") ...
ack_start(self.back_btn, True, False, 10) self.add(self.game_bbox) print(self.game_bbox) def game_clicked(self, event): print("Start clicked") self.game_screen() def menu_clicked(self, event): print("Menu clicked") self.main_screen() def draw_background(sel...
google/gazoo-device
gazoo_device/tests/unit_tests/utils/dli_powerswitch_logs.py
Python
apache-2.0
1,345
0
# 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 agreed to in writing, ...
S OF ANY KIND, either express or implied. # See the License
for the specific language governing permissions and # limitations under the License. """Device logs for DLI powerswitch devices.""" RETURN_CODE = "200\n" ERROR_RETURN_CODE = "409\n" DEFAULT_BEHAVIOR = { "http://123.45.67.89/restapi/config/=version/": { "text": '["1.7.15.0"]', "status_code": "207"...
rgeorgiev583/dsp-practicum-2015-16
util/prmergeall.py
Python
mit
761
0.003942
#!/usr/bin/python from urllib2 import Request, urlop
en import json from subprocess import call import argparse parser = argparse.ArgumentParser(description='Automatically merges all pull requests in a fork of the GitHub repo for the DSP 2015/16 practicum course @ FMI.') parser.add_argument('assignment_id', metavar='assignment-id', type=int, help='the assignment to whic...
acticum-2015-16/pulls?state=open", headers={"Accept": "application/vnd.github.v3+json"}) pullData = urlopen(r).read() pulls = json.loads(pullData) for pull in pulls: subprocess.call(["./prmerge.sh", pull["user"]["login"], aid])
futursolo/FutureFinity
futurefinity/utils.py
Python
apache-2.0
5,938
0.001684
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright 2016 Futur Solo # # 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 # # ...
.** """ def add(self, name: str, value: str): lower_name = name.lower() return MagicDict.add(self, lower_name, value) def get_list(self, name: str, default: Optional[str]=None): lower_name = name.lower() return MagicDict.get_list(self,
lower_name, default=default) def get_first(self, name: str, default: Optional[str]=None): lower_name = name.lower() return MagicDict.get_first(self, lower_name, default=default) def __setitem__(self, name: str, value: str): lower_name = name.lower() return MagicDict.__setitem__...
Yelp/paasta
paasta_tools/autoscaling/ec2_fitness.py
Python
apache-2.0
1,916
0.005219
""" Provides functions for evaluating the 'fitness' of ec2 instances. This module really just provides functions for deciding which instance is best to be killed by the autoscaler. """ def sort_by_system_instance_health(instances): return sorted( instances, key=lambda i: ( i.instance_s...
us.get("Events", []))) def sort_by_total_tasks(instances): return sorted(instances, key=lambda i: i.task_counts.count, reverse=True) def sort_by_running_batch_count(instances): return sorted(instances, key=lambda i: i.task_counts.batch_count, reverse=True) def sort_by_ec2_fitnes
s(instances): """ Sort a list according to their fitness. This will return the list of instances in order of 'fitness': that is, that which is least desirable to kill is first in the list. Fitness is judged according to the following rules: - any instance considered to have a non 'ok' syste...
SeleniumK/data_structures2
tests/test_quicksort.py
Python
mit
337
0.005935
import pytest fro
m itertools import permutations fro
m src.quicksort import quick_sort TO_SORT = ( [[]] + [[1]]+ list(map(list, permutations(range(4))))+ list(map(list, permutations(range(6)))) ) @pytest.mark.parametrize("lst", TO_SORT) def test_quick(lst): copy = lst[:] assert quick_sort(lst) == sorted(copy)
joshavenue/python_notebook
notebook2/set_1.py
Python
unlicense
366
0.030055
low_primes = {1,3,5,7,11,13} low_primes.
add(17) # It will be {1,3,5,7,11,13,17} low_primes.update({19,23},{2,29}) # It will be {1,2,3,5,7,11,13,17,19,23,29}, sorted order while low_primes: print(low_primes.pop()/3) #It will pop the first one (1) out, but because it is within a while loop, it will eventually pop everything...
t
nexdatas/recselector
test/TestServer.py
Python
gpl-3.0
49,959
0
# "$Name: $"; # "$Header: $"; # ============================================================================ # # file : TestServer.py # # description : Python source for the TestServer and its commands. # The class is derived from Device. It represents the # CORBA servant ob...
-------------
----------------------------------------- # Device initialization # ----------------------------------------------------------------- def init_device(self): self.set_state(PyTango.DevState.ON) self.get_device_properties(self.get_device_class()) env = {'new': {'ActiveMntGrp': 'nxs...
agiovann/Constrained_NMF
use_cases/CaImAnpaper/edge-cutter/generate_GT_tight_overlap.py
Python
gpl-2.0
16,620
0.007341
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Created on Wed Oct 11 11:35:22 2017 @author: agiovann """ import os import numpy as np import caiman as cm import scipy import pylab as pl import cv2 import glob #%% import itertools def grouper(n, iterable, fillvalue=None): "grouper(3, 'ABCDEFG', 'x') --> ABC ...
at are displayed all_pos_crops = [] all_neg_crops = [] all_dubious_crops = [] base_name = fname_new.split('/')[5] dims = (d1, d2) idx_included = np.array([x for x in idx_included if x is not None]) base_name = base_name + '_' + \ str(idx_included[0]) +...
luded[-1]) print(base_name) idx_excluded = np.setdiff1d(np.arange(A_gt.shape[-1]), idx_included) Npeaks = 5 YrA_gt[np.abs(YrA_gt) > np.std(YrA_gt) * 10] = 0 traces_gt = YrA_gt + C_gt downsampfact = 500 elm_missing = int(np.ceil(T * 1.0 / downsampfact) * downsampf...
xmaruto/mcord
xos/core/models/slice.py
Python
apache-2.0
9,216
0.009983
import os from django.db import models from core.models import PlCoreBase from core.models import Site from core.models.site import SitePrivilege from core.models import User from core.models import Role from core.models import Controller,ControllerLinkManager,ControllerLinkDeletionManager from core.models import Servi...
lated_name='slices', blank=True, null=True) # for tenant view default_flavor = models.ForeignKey(Flavor, related_name = "slices", null=True, blank=True) defaul
t_image = models.ForeignKey(Image, related_name = "slices", null=True, blank=True); default_node = models.ForeignKey(Node, related_name = "slices", null=True, blank=True) mount_data_sets = StrippedCharField(default="GenBank",null=True, blank=True, max_length=256) default_isolation = models.CharField(null=F...
fr0609/timesched
data/convert.py
Python
bsd-3-clause
7,831
0.000766
import os import re import math import json from itertools import chain from xml.etree import cElementTree as et os.chdir(os.path.abspath(os.path.dirname(__file__))) def convert_countries(): countries = {} with open('raw/countryInfo.txt', 'rb') as f: for line in f: line = line.decode('u...
if not line: continue main_name = line[2] country = line[8] state = country == 'US' and line[10] or None population = int(line[14]) timezone = line[17] is_capital = line[7] == 'PPLC' city_key = ('%s/%s%s' % (country,...
state and '/' + state or '')).replace(' ', '_') old_city = cities.get(city_key) # There was already a city with that name, let the one # with the higher population win. if old_city is not None: if population < old_city['population']: ...
QuLogic/iris
lib/iris/tests/unit/fileformats/pyke_rules/compiled_krb/fc_rules_cf_fc/test_reorder_bounds_data.py
Python
gpl-3.0
2,647
0
# (C) British Crown Copyright 2014 - 2017, Met Office # # This file is part of Iris. # # Iris 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 l...
nd. self.assertArrayEqual(res, bounds_data) def test_slowest_varying(self): bounds_data = np.arange(24).reshape(4, 2, 3) cf_bounds_var = m
ock.Mock(dimensions=('nv', 'foo', 'bar')) cf_coord_var = mock.Mock(dimensions=('foo', 'bar')) res = reorder_bounds_data(bounds_data, cf_bounds_var, cf_coord_var) # Move zeroth dimension (nv) to the end. expected = np.rollaxis(bounds_data, 0, bounds_data.ndim) self.assertArrayEqu...
AzamYahya/shogun
applications/tapkee/samples/lltsa.py
Python
gpl-3.0
611
0
import modshogun as sg import data # load data feature_matrix = data.swissroll() # create features instance featur
es = sg.RealFeatures(feature_matrix) # create Linear Local Tangent Space Alignment converter instance converter = sg.LinearLocalTangent
SpaceAlignment() # set target dimensionality converter.set_target_dim(2) # set number of neighbors converter.set_k(10) # set number of threads converter.parallel.set_num_threads(2) # set nullspace shift (optional) converter.set_nullspace_shift(-1e-6) # compute embedding with Linear Local Tangent Space Alignment metho...
Nic30/hwtLib
hwtLib/examples/timers.py
Python
mit
4,810
0
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from hwt.hdl.constants import Time from hwt.interfaces.std import Signal, HandshakeSync, VectSignal from hwt.interfaces.utils import addClkRstn, propagateClkRstn from hwt.simulator.simTestCase import SimTestCase from hwt.synthesizer.interfaceLevel.unitImplHelpers import g...
for i in range(CLK // 2 - 1)]) self.assertSequenceEqual(u.tick16._ag.data, [((i + 1) * 160 + RST) * Time.ns for i in range(CLK // 16)]) self.assertSequenceEqual(u.tick17._ag.data, [((i + 1) * 170 + R...
17)]) self.assertSequenceEqual(u.tick34._ag.data, [((i + 1) * 340 + RST) * Time.ns for i in range(CLK // 34)]) self.assertSequenceEqual(u.tick256._ag.data, [((i + 1) * 2560 + RST) * Time.ns ...
tomatohater/django-pgcryptoauth
setup.py
Python
mit
1,290
0.002326
from setuptools import setup, find_packages import os import pgcryptoauth def read(fname): return open(os.path.join(os.path.dirname(__file__), fna
me)).read() README = read('README.rst') setup( name='django-pgcryptoauth', version=pgcryptoauth.__version__, description='Django hasher for pgcrypto encoded passwords.', long_description=README, url='https://github.com/tomatohater/django-pgcryptoauth', author='Drew Engelson', author_email=...
s=find_packages(), include_package_data=True, package_data={}, classifiers = [ 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'Natural Language :: English', 'License :: OSI Approved :: MIT License', 'Operating Syste...
foursquare/fsqio
src/python/fsqio/pants/buildgen/core/register.py
Python
apache-2.0
1,606
0.008717
# coding=utf-8 # Copyright 2017 Foursquare Labs Inc. All Rights Reserved. from __future__ import absolute_import, division, print_function from pants.build_graph.build_file_aliases import BuildFileAliases from pants.goal.task_registrar import TaskRegistrar as task from fsqio.pants.buildgen.core.buildgen import Build...
n.core.s
ubsystems.buildgen_subsystem import BuildgenSubsystem def build_file_aliases(): return BuildFileAliases( targets={ 'buildgen_target_bag': BuildgenTargetBag, }, ) def global_subsystems(): return (BuildgenSubsystem.Factory,) def register_goals(): task( name='map-derived-targets', actio...
aam-at/tensorflow
tensorflow/python/eager/benchmarks_test.py
Python
apache-2.0
50,309
0.010555
# Copyright 2017 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...
t" return name def _run(self, func, num_iters, execution_mode=None): self.run_report(run_benchmark, func, num_iters, execution_mode) def benchmark_create_np_array(self): func = lambda: np.array([3.0]) self._run(func, 30000) def _benchmark_create_tensor(self, value, dtype, device): """Benchm...
device) def func(): ops.EagerTensor(value, device=device, dtype=dtype) self._run(func, 30000) def _benchmark_create_constant(self, value, dtype, cached=True): global GLOBAL_TEST_VALUE GLOBAL_TEST_VALUE = value def cached_func(): constant_op.constant(value, dtype=dtype) def unc...
open-craft/XBlock
xblock/exceptions.py
Python
apache-2.0
3,757
0.001863
""" Module for all xblock exception classes """ from webob import Response try: import simplesjson as json # pylint: disable=F0401 except ImportError: import json class XBlockNotFoundError(Exception): """ Raised to indicate that an XBlock could not be found with the requested usage_id """ def...
class NoSuchViewError(Exception): """ Raised to indicate that the view requested was not found. """ def __init__(self, block, view_name): """ Create a new NoSuchViewError :param block: The XBlock without a view :
param view_name: The name of the view that couldn't be found """ # Can't use super because Exception is an old-style class Exception.__init__(self, "Unable to find view {!r} on block {!r}".format(view_name, block)) class NoSuchHandlerError(Exception): """ Raised to indicate that the re...
chrischaplin/IngesTune
src/srcPostgres/db_classes.py
Python
mit
6,970
0.023673
import psycopg2 import psycopg2.extras # This is a wrapper around psycopg2 (python-postgreSQL) class pyToPostgres: _db_conn = None _db_curs = None def __init__(self,credentials): # Credentials is a dict of access paramaters # (dbname, user, host, password) self.credenti...
latency float8, \ #record_size int8,batch_size int8,linger_ms int8, max_in int8, \ #comp varchar, acks int8) assert self.isOpen cs = "CREATE TABLE {0} {1};".forma
t(table_name,schema) self._db_curs.execute(cs) self._db_conn.commit() def deleteTable(self,table_name): assert self.isOpen cs = "DROP TABLE {0};".format(table_name) self._db_curs.execute(cs) self._db_conn.commit() ...
hangpark/kaistusc
apps/ksso/models.py
Python
bsd-2-clause
3,434
0
""" KAIST 단일인증서비스 모델. """ from django.db import models from django.utils.translation import ugettext_lazy as _ class PortalInfoManager(models.Manager): """ :class:`PortalInfo` 에 대한 커스텀 매니저. KAIST 단일인증서비스를 통해 최초 로그인 한 사용자는 자신의 정보를 총학생회에 제공하는 것에 동의해야 최종 가입이 됩니다. 만약 동의하지 않을 경우에는 자동 탈퇴처리가 됩니다. 그러나, ...
""" return cls(user=user, kaist_ui
d=kaist_uid) @property def enter_year(self): if self.ku_std_no and len(self.ku_std_no) == 8: return self.ku_std_no[2:4] return None
L-F-A/Machine-Learning
General/__init__.py
Python
mit
79
0
from .Conf
usion_MI import* from .Cov_Mat import * from .SaveLoadModel imp
ort *
rishig/zulip
zerver/lib/feedback.py
Python
apache-2.0
2,665
0.002627
from django.conf import settings from django.core.mail import EmailMessage from typing import Any, Mapping, Optional from zerver.lib.actions import internal_send_message from zerver.lib.send_email import FromAddress from zerver.lib.redis_utils import get_redis_client from zerver.models import get_system_bot import t...
sender_email: str, min_delay: float) -> bool: # This function returns a boolean, but it also has the side effect # of noting that a new message was received. key = 'zilencer:feedback:%s' % (sender_email,) t = int(time.time()) last_time = client.getset(key, t) # type: Optional[bytes] if last_tim...
ay = t - int(last_time) return delay > min_delay def deliver_feedback_by_zulip(message: Mapping[str, Any]) -> None: subject = "%s" % (message["sender_email"],) if len(subject) > 60: subject = subject[:57].rstrip() + "..." content = '' sender_email = message['sender_email'] # We gener...
wevote/WeVoteServer
candidate/controllers.py
Python
mit
134,381
0.004338
# candidate/controllers.py # Brought to you by We Vote. Be good. # -*- coding: UTF-8 -*- import datetime as the_other_datetime import json import urllib.request from socket import timeout from django.http import HttpResponse from django.utils.timezone import now import wevote_functions.admin from apis_v1.views.views_ex...
er from exception.models import handle_exception from image.controllers import retrieve_all_images_for_one_candidate, cache_master_and_resized_image, \ IMAGE_SOURCE_BALLOTPEDIA, \ LINKEDIN, TWITTER, WIKIPEDIA, FACEBOOK from import_export_vote_smart.co
ntrollers import retrieve_and_match_candidate_from_vote_smart, \ retrieve_candidate_photo_from_vote_smart from office.models import ContestOfficeManager from politician.models import PoliticianManager from position.controllers import move_positions_to_another_candidate, update_all_position_details_from_candidate fr...
cfe-lab/MiCall
micall/tests/test_run_info.py
Python
agpl-3.0
777
0
from unittest import TestCase from micall.drivers.run_info import RunInfo from micall.drivers.sample import Sample from micall.drivers.sample_group import SampleGroup class RunInfoTest(TestCase): def test_get_all_samples(self): expected_fastq_paths = ['1a_R1_001.fastq', '1...
), SampleGroup(Sample(fastq1='2_R1_001.fastq'))]) fastq_paths = [sample.fastq1 for sample in run_info.get_all_samples(
)] self.assertEqual(expected_fastq_paths, fastq_paths)
nosix/PyCraft
src/pycraft/service/primitive/fuzzy/gaussian.py
Python
lgpl-3.0
658
0.00152
# -*- coding: utf8 -*- import math from pycraft
.common.util import ndarray, product class GaussianKernel: __slots__ = ['_size', '_kernel'] def __init__(self, size): self._size = size self._kernel = ndarray(2*size + 1, 2*size + 1) bell_size = 1.0 / size bell_height = 2 * size for dx, dz in product(range(-size, ...
self._kernel[dx+size][dz+size] = \ bell_height * math.exp(-(bx**2 + bz**2) / 2) def get(self, dx, dz): return self._kernel[dx+self._size][dz+self._size]
egottcha/AHEaD
node/sensor/sensor_type.py
Python
apache-2.0
326
0.003067
class SensorType(): TEMPERATURE = "TEMPERATURE" # Celsius degree (C) HUMIDITY = "HUMIDITY" # percent (%) TEMP_HUM = "TEMP_HUM" LUX = "LUX" # lux MOTION = "MOTION" # boolean DISTANCE = "DISTANCE"
# centimeter (cm) POWER = "POWER" # Watt (W) CURREN
T = "CURRENT" # Amper (A)
IshitaTakeshi/Louds-Trie
python/test.py
Python
mit
1,193
0.013412
from trie import Trie #constructs a tree of this shape ('*' means root) # # * # /|\ # a i o # / /|\ # n f n u # | |\ # e r t # #The LOUDS bit-string is then #[1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0] words = ['an', 'i', 'of', 'one', 'our', 'out'] test_set =...
answer)) ##parent [0, 0, 1, 1, 1, 1, 2, 2, 3, 4, 4, 4, 4, 5, 6, 7, 7, 8, 8, 8, 9, 0, 1] ##bit_array [1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0] ##child [1, -, 2, 3, 4, -, 5, -, -, 6, 7, 8, -, -, -, 9, -, 0, 1, -, -, -, -] ##index [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, ...
8, 9, 0, 1, 2] #labels ['', '', 'a', 'i', 'o', 'n', 'f', 'n', 'u', 'e', 'r', 't'] ##index [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1]
emschimmel/CameraPi
camera_try.py
Python
apache-2.0
2,985
0.031826
# quick demo of some python image filters # using raspberry pi camera import Tkinter as tk from picamera import PiCamera from time import sleep from PIL import Image,ImageFilter,ImageChops,ImageTk imagefile = "image.jpg" w = 320 h = 240 lastfilter = "none" camera = PiCamera() def takephoto(): camera.capture(imagefi...
tkimage1 # Add some buttons buttonrow = tk.Frame(root) buttonrow.place(y=0,x=0) button = tk.Button(buttonrow, text='CAMERA',command = lambda: newphoto()) button.pack(side='left',) button = tk.Button(buttonrow, text='LOOP',command = lambda: photoloop()) button.pack(side='left',) button = tk.Button(buttonrow, text='INV...
on = tk.Button(buttonrow, text='BLUR',command = lambda: dofilter(image1,ImageFilter.BLUR)) button.pack(side='left') button = tk.Button(buttonrow, text='CONTOUR',command = lambda: dofilter(image1,ImageFilter.CONTOUR)) button.pack(side='left') button = tk.Button(buttonrow, text='FIND_EDGES',command = lambda: dofilter(ima...
aljoscha/flink
flink-python/pyflink/version.py
Python
apache-2.0
1,132
0.00265
################################################################################ # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this...
ou 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 wri
ting, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ########################################################...
jku/telepathy-gabble
tests/twisted/connect/test-success.py
Python
lgpl-2.1
558
0.010753
""" Test connecting t
o a server. """ from gabbletest import exec_test import constants as cs def test(q, bus, conn, stream): conn.Connect() q.expect('dbus-signal', signal='StatusChanged', args=[cs.CONN_STATUS_CONNECTING, cs.CSR_REQUESTED]) q.expect('stream-authenticated') q.expect('dbus-signal', signal='PresenceUpdate', ...
ilable': {}})}]) q.expect('dbus-signal', signal='StatusChanged', args=[cs.CONN_STATUS_CONNECTED, cs.CSR_REQUESTED]) if __name__ == '__main__': exec_test(test, do_connect=False)
youtube/cobalt
third_party/skia/gn/highest_version_dir.py
Python
bsd-3-clause
304
0
#!/usr/bin/env python # # Copyright 2017 Google Inc. # # Use of this source code is governed by a BSD-style license th
at can be # found in the LICENSE file. import os import re import sys dirpath = sys.argv[1] regex = re.compile(sys.argv[2]) print sorted(filter(regex.match, os.listdir
(dirpath)))[-1]
pyspace/test
pySPACE/missions/operations/merge.py
Python
gpl-3.0
19,410
0.008964
""" Define train and test data for One versus Rest or Rest versus One in cross validation fashion The result summary of this operation contains one dataset for every dataset of the *input_path*, which uses data from this dataset as test data and the data of all other datasets as training data. For instance, if the inp...
t" # We create the collection Rest_vs_Collection source_test_collection_name = \ source_test_collection_path.split(os.sep)[-2] test_base_collection_name = \ source_test_collection_name.strip("}{").split("}{")[0...
n_name = source_test_collection_name.replace( test_base_collection_name, test_base_collection_name + "_vs_Rest") key = "train" else: target_collection_name = source_test_collection_name.replace(...
rice-apps/rice-elections
src/controllers/vote.py
Python
mit
365
0.00274
""" Controller for voting related requests. """ import webapp2 from models.vote import VoteHandler from models.vote_.cast_ballot import BallotHandler from models.vote_.view_results import ResultsHandler app = webapp2.WSGIApplication([
('/vote', VoteHandler), ('/vote/cast-ballot', BallotHandler), ('/vote/view-results', Res
ultsHandler) ], debug=True)
grnet/snf-image-creator
image_creator/distro/netbsd.py
Python
gpl-3.0
1,608
0
# -*- coding: utf-8 -*- # # Copyright (C) 2011-2018 GRNET S.A. # # 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. # # Thi...
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/>. """This module hosts OS-specific code for NetBSD.""" import re from image_creator.distro.bsd imp...
enabled at boot""" sshd_enabled = False sshd_service = re.compile(r'\bsshd=') sshd_yes = re.compile(r"\bsshd=(['\"]?)(YES|TRUE|ON|1)\1\b") for rc_conf in ('/etc/defaults/rc.conf', '/etc/rc.conf'): if not self.image.g.is_file(rc_conf): self.out.warn("File: `...
SambitAcharya/coala
coalib/settings/ConfigurationGathering.py
Python
agpl-3.0
9,703
0.000103
import os import sys from coalib.settings.Setting import Setting from coalib.misc import Constants from coalib.output.ConfWriter import ConfWriter from coalib.output.printers.LOG_LEVEL import LOG_LEVEL from coalib.parsing.CliParsing import parse_cli from coalib.parsing.ConfParser import ConfParser from coalib.settings...
ed dict. """ for name in higher: if name in lower: lower[name].update(higher[name], ignore_defaults=True) else: # no deep copy needed lower[name] = higher[name] return lower def load_config_file(filename, log_printer, silent=False): """ Loads se...
ig file. Prints an appropriate warning if it doesn't exist and returns a section dict containing an empty default section in that case. It assumes that the cli_sections are available. :param filename: The file to load settings from. :param log_printer: The log printer to log the warning/error t...
urwen/urscrape
urscrape/__init__.py
Python
mit
186
0
#!/usr/bin/env python3 # __init__.py -*-python-*- # Copyright 2016 by urwen (urwen@mail.ru) # This program comes with ABSOLUTELY NO WARRANTY. from urscrape.log import * DIEF_log_
init()
Ghost-script/dyno-chat
kickchat/apps/pulsar/apps/data/odm/fields.py
Python
gpl-2.0
12,075
0
import pickle from base64 import b64encode from pulsar.utils.html import UnicodeMixin class FieldError(RuntimeError): pass def get_field_type(field): return getattr(field, 'repr_type', 'text') class Field(UnicodeMixin): '''Base class of all :mod:`.odm` Fields. Each field is specified as a :class...
dex if primary_key: self.unique = True self.required = True self.index = True self.as_cache = False extras['default'] = None else: self.unique = unique self.required = required self.as_cache = as_cache ...
else index if self.as_cache: self.required = False self.unique = False self.index = False self._meta = None self.name = None self.model = None self._default = extras.pop('default', self._default) self._handle_extras(**extras) s...
Widiot/simpleblog
venv/lib/python3.5/site-packages/flask_admin/tests/pymongo/__init__.py
Python
mit
289
0
import pymongo from flask import Flask from fl
ask_admin import Admin def setup(): app = Flask(__name__) app.config['SECRET_KEY'] = '1' app.config['CS
RF_ENABLED'] = False conn = pymongo.Connection() db = conn.tests admin = Admin(app) return app, db, admin
FinancialSentimentAnalysis-team/Finanical-annual-reports-analysis-code
wangyi/wk1/self testing/excel_diff.py
Python
apache-2.0
3,299
0.015762
# coding: utf-8 # In[1]: import xlrd import xlwt import os def read_excel(path): wbk=xlrd.open_workbook(path) sheet_annual=wbk.sheet_by_name('Annual') sheet_interim=wbk.sheet_by_name('Interim') ncols_annual=sheet_annual.ncols data_annual=[] for col in range(ncols_annual): data_...
ta, year if __name__=='__main__': result_path = '/usr/yyy/self testing/excel_diff/' root_path = '/usr/yyy/self testing/excel_freq/' if not os.path.exists(result_path): os.mkdir(result_path) excel_list=os.listdir(root_path) for excel
_name in excel_list: wbk=xlwt.Workbook() stock = excel_name[0:5] file_name = root_path + excel_name data_annual, data_interim = read_excel(file_name) res_data, year = countDiff0(data_annual) save_into_sheet(res_data, year, 'Annual_Diff0', wbk) res...
fidelcoria/AYFM-Scheduling
ScheduleParsing/scripts/schedule/convert_docx.py
Python
agpl-3.0
5,644
0.015946
#https://python-docx.readthedocs.io/en/latest/user/install.html #python-docx may be installed with pip if you have it available: # pip install python-docx #python-docx can also be installed using easy_install, although this is #discouraged: # easy_install python-docx #If neither pip nor easy_install is available, it...
h the assignments''' assignments = [] # participants for first assgn participants = row.cells[SECTION_A_PARTICIPANTS].text.strip() if participants != '': # if there are participants assgn = Assignment() # new empty assignment
# begin populating fields assgn.date = date assgn.type = aType assgn.lesson = row.cells[SECTION_A_LESSON].text.strip() assgn.section = SECTION_A # be sure to strip each element of the array `students` in case split leaves white space students = participants...
ElementalAlchemist/txircd
txircd/modules/rfc/cmd_rehash.py
Python
bsd-3-clause
4,740
0.038397
from twisted.plugin import IPlugin from twisted.words.protocols import irc from txircd.config import ConfigError from txircd.module_interface import Command, ICommand, IModuleData, ModuleData from zope.interface import implements from fnmatch import fnmatchcase class RehashCommand(ModuleData): implements(IPlugin, IMo...
("REHASHNOTICE", 1, ServerRehashNotice(self.ircd)) ] def restrictRehashToOpers(self, user, data): if not self.ircd.runActionUntilValue("userhasoperpermission", user, "command-rehash", users=[user]): user.sendMessage(irc.ERR_NOPRIVILEGES, "Permission denied - You do not have the correct operator privileges")...
Params(self, user, params, prefix, tags): if not params: return {} servers = [] serverMask = params[0] if fnmatchcase(self.ircd.name, serverMask): servers.append(None) for server in self.ircd.servers.itervalues(): if fnmatchcase(server.name, serverMask): servers.append(server) if not servers: ...
buffer/thug
thug/DOM/W3C/HTML/HTMLFormElement.py
Python
gpl-2.0
1,891
0.011105
#!/usr/bin/env python import logging from .HTMLElement import HTMLElement from .HTMLFormControlsCollection import HTMLFormControlsCollection from .attr_property import attr_property log = logging.getLogger("Thug") class HTMLFormElement(HTMLElement): name = attr_property("name") acceptCharset = att...
/x-www-form-urlencoded") encoding = attr_property("enctype", default = "application/x-www
-form-urlencoded") method = attr_property("method", default = "get") target = attr_property("target", default = "") def __init__(self, doc, tag): HTMLElement.__init__(self, doc, tag) def __getattr__(self, key): for tag in self.tag.children: if tag.name not in ...
m4tx/egielda
orders/migrations/0001_initial.py
Python
agpl-3.0
729
0.001372
# -*- coding: utf-8 -*- from __future__ import unicode_lite
rals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Order', fields=[ ...
ey=True)), ('date', models.DateTimeField(auto_now_add=True)), ('fulfilled', models.BooleanField(default=False)), ('user', models.ForeignKey(to=settings.AUTH_USER_MODEL)), ], ), ]
TaliesinSkye/evennia
src/scripts/migrations/0011_convert_attrdata.py
Python
bsd-3-clause
24,172
0.005875
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import DataMigration from django.db import models from django.contrib.contenttypes.models import ContentType from src.utils.utils import to_str from src.utils.dbserialize import to_pickle try: import cPickle as pickle except ImportError...
the attribute object storing this set the 'parent' property is set to 'init' at creation, this stops the system from saving itself over and over when first assigning the dict. once initialization is over, the attribute from_attr() method will assign the parent (or none, if ...
Set, self).__init__(*args, **kwargs) def __str__(self): return "{%s}" % ", ".join(str(val) for val in self) def save(self): "relay save operation upwards in tree until we hit the root." if self.parent == 'init': pass elif self.parent: self.parent.save() ...
RedHatInsights/insights-core
insights/parsers/virt_who_conf.py
Python
apache-2.0
1,776
0
""" VirtWhoConf - File ``/etc/virt-who.conf`` and ``/etc/virt-who.d/*.conf`` ======================================================================== The ``VirtWhoConf`` class parses the virt-who configuration files in `ini-like` format. .. note:: The configuration files under ``/etc/virt-who.d/`` might ...
nfig template: [global] interval=3600 #reporter_id= debug=False oneshot
=False #log_per_config=False #log_dir= #log_file= #configs= [defaults] owner=Satellite env=Satellite Examples: >>> type(conf) <class 'insights.parsers.virt_who_conf.VirtWhoConf'> >>> 'global' in conf True >>> conf.has_...
nkgilley/home-assistant
homeassistant/components/github/sensor.py
Python
apache-2.0
9,350
0.000214
"""Support for GitHub.""" from datetime import timedelta import logging import github import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import ( ATTR_NAME, CONF_ACCESS_TOKEN, CONF_NAME, CONF_PATH, CONF_URL, ) import homeassistant.helpers....
commit_sha, ATTR_LATEST_RELEASE_URL: self._latest_rel
ease_url, ATTR_LATEST_OPEN_ISSUE_URL: self._latest_open_issue_url, ATTR_OPEN_ISSUES: self._open_issue_count, ATTR_LATEST_OPEN_PULL_REQUEST_URL: self._latest_open_pr_url, ATTR_OPEN_PULL_REQUESTS: self._pull_request_count, ATTR_STARGAZERS: self._stargazers, ...
nylas/nylas-python
nylas/__init__.py
Python
mit
169
0
from pkg
util import extend_path from .client.client import APIClient # Allow out-of-tree submodules. __path__ = extend_path(__path__, __name__) __all__ = ["APIClient
"]
dasbruns/netzob
src/netzob/Import/PrismaImporter/__init__.py
Python
gpl-3.0
20
0
__author__ = 'd
smp'
h2oai/h2o-dev
h2o-py/h2o/estimators/xgboost.py
Python
apache-2.0
29,759
0.003999
#!/usr/bin/env python # -*- encoding: utf-8 -*- # # This file is auto-generated by h2o-3/h2o-bindings/bin/gen_python.py # Copyright 2016 H2O.ai; Apache License Version 2.0 (see LICENSE for details) # from __future__ import absolute_import, division, print_function, unicode_literals from h2o.estimators.estimator_base ...
__(self, **kwargs): super(H2OXGBoo
stEstimator, self).__init__() self._parms = {} names_list = {"model_id", "training_frame", "validation_frame", "nfolds", "keep_cross_validation_models", "keep_cross_validation_predictions", "keep_cross_validation_fold_assignment", "score_each_iteration", "fold...
goncalopp/mexbtcapi
mexbtcapi/test/test_currency.py
Python
cc0-1.0
7,419
0.005931
'''Tests for currency.py''' import unittest from decimal import Decimal from mexbtcapi.currency import Currency, ExchangeRate, Amount, CurrencyPair class CurrencytTest(unittest.TestCase): def test_create(self): c1 = Currency("c1") self.assertIsInstance(c1, Currency) def test_equality(self):
c1, c1_, c2 = Currency("c1"), Currency("c1"), Currency("c2") self.assertEqual(c1, c1_) self.assertNotEqual(c1, c2) def test_hash(self): c1, c1_, c2 = Currency("c1"), Currency("c1"), Currency("c2")
self.assertEqual(set((c1,c1_)), set((c1,))) self.assertEqual(len({c1:1, c1_:1}), 1) self.assertEqual(len({c1:1, c2:1}), 2) self.assertEqual(len({c1:1, "c1":1}), 2) class CurrencyPairTest(unittest.TestCase): @staticmethod def create_pair(): c1, c2, c3 = Currency("c1"), Curr...
Katharsis/unfrozen_binary
uncompyle2/Scanner.py
Python
mit
37,532
0.005968
# Copyright (c) 1999 John Aycock # Copyright (c) 2000-2002 by hartmut Goebel <h.goebel@crazy-compilers.com> # Copyright (c) 2005 by Dan Pascu <dan@windowmaker.org> # # See main module for license. # __all__ = ['Token', 'Scanner', 'getscanner'] import types import dis from collections import namedtuple from array ...
m += 2 self.code = code = fixed_code for i in self.op_range(0, m): if code[i] in dis.hasjrel: #import pdb; pdb.set_trace() old_jump = code[i+1] + code[i+2]*256 old_target = new_to_old[i] + 3 + old_jump new_target =...
% 256 code[i+2] = new_jump // 256 if code[i] in dis.hasjabs: old_target = code[i+1] + code[i+2]*256 new_target = old_to_new[old_target] code[i+1] = new_target % 256 code[i+2] = new_target // 256 for i in range(...
web2py/pydal
pydal/representers/__init__.py
Python
bsd-3-clause
8,805
0.001704
from collections import defaultdict from .._compat import PY2, with_metaclass, iteritems, to_unicode, to_bytes, string_types from .._gae import gae from ..helpers._internals import Dispatcher from ..helpers.regex import REGEX_TYPE representers = Dispatcher("representer") class for_type(object): def __init__(self...
self.call = self._call if self.obj.encode and PY2: self.inner_call = self._inner_call_with_encode else: self.inner_call = self._inner_call if self.obj.adapt: self.adapt = self._adapt else: self.adapt = self._no_adapt def _adapt(self,...
return self.representer.adapt(value) def _no_adapt(self, value): return value def _inner_call(self, value, **kwargs): return self.obj.f(self.representer, value, **kwargs) def _inner_call_with_encode(self, value, **kwargs): if isinstance(value, unicode): value = ...
Philippe-Lawrence/pyBar
classPrefs.py
Python
gpl-3.0
8,101
0.012488
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright 2007 Philippe LAWRENCE # # This file is part of pyBar. # pyBar 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 Licen...
d 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 pyBar; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA import configparser, os import Const class Singleton(object): def __new__(cls, *args, **kwargs): if '_inst' not in vars(cls): cls._inst = object.__new__(cls, *args, **kwar...
ge0rgi/cinder
cinder/tests/unit/volume/drivers/test_nfs.py
Python
apache-2.0
66,415
0.000015
# Copyright (c) 2012 NetApp, 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...
ine_nas_security_option_setting( secure_file_operations, nas_mount, is_new_install) self.assertEqual('true', nas_option) @mock.patch('os.path.join') @mock.patch('os.path.isfile') def test_determine_nas_security_options_when_auto_and_old_install(self, ...
isfile, join): """Test the setting of the NAS Security Option In this test case, the marker file does not exist. There are also pre-existing Cinder volumes. """ drv = self._driver drv._mounted_s...
brkt/brkt-cli
brkt_cli/brkt_jwt/jwk.py
Python
apache-2.0
2,317
0
# Copyright 2017 Bracket Computing, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). # You may not use this file except in compliance with the License. # A copy of the License is located at # # https://github.com/brkt/brkt-cli/blob/master/LICENSE # # or in the "license" file...
4_KEY_LEN_BYTES): bys = bytearray() while long_int: long_int, r = divmod(long_int, 256) bys.insert(0, r) if len(bys) < pad_to_len: # pad with leading zeros bys = bytearray(pad_to_len - len(bys)) + bys return bys def _long_to_base64(n): bys = _long_to_byte_array(n) ...
urlsafe_b64encode(bys).rstrip(b'=') return s.decode("ascii") def get_jwk(x, y): """ Return the JSON web key representation of an ECDSA public key. :param x the X value of the ECDSA public key as a long integer :param y the Y value of hte ECDSA public key as a long integer :return the JSON web key...
ydre/kit-soft
ImageProcessing/soobash/scanconverter.1.py
Python
bsd-3-clause
1,675
0.00597
__author__ = 'mehdibenchoufi' from filereader import FileReader from data import Data import constants import sys sys.path.append('/usr/local/lib/python2.7/site-packages') import cv2 class ScanConverter: def get_input(self, value): return self.input def set_input(self, value): self.input = ...
e_input def set_intermediate_input(self, value): self.intermediate_input = value def get_output(self, value): return self.output def set_output(self, value): self.output = value def __init__(self, file_reader): #sel
f.file_reader = FileReader() self.file_reader = file_reader self.data = Data() self.set_io(self.data) def set_io(self, data): self.set_input(data.get_src()) self.set_intermediate_input(data.get_intermediate_src()) self.set_output(data.get_destination()) def conv...
CityGenerator/Megacosm-Generator
tests/test_gem.py
Python
gpl-2.0
980
0.005102
#!/usr/bin/env python # -*- coding: utf-8 -*- "Fully test this module's functionality through the use of fixtures." from megacosm.generators import
Gem import unittest2 as unittest import fakeredis from config import TestConfiguration import fix
tures class TestGem(unittest.TestCase): def setUp(self): """ """ self.redis = fakeredis.FakeRedis() fixtures.gem.import_fixtures(self) def tearDown(self): self.redis.flushall() def test_random_gem(self): """ """ gem = Gem(self.redis) self.assertN...
redondomarco/useradm
doc/python-cyrus-0.8.5/cyruslib.py
Python
gpl-3.0
24,712
0.00781
# -*- coding: utf-8 -*- # # Cyruslib v0.8.5-20090401 # Copyright (C) 2007-2009 Reinaldo de Carvalho <reinaldoc@gmail.com> # Copyright (C) 2003-2006 Gianluigi Tiesi <sherpya@netfarm.it> # Copyright (C) 2003-2006 NetFarm S.r.l. [http://www.netfarm.it] # # This program is free software; you can redistribute it and/or modi...
rn False def id(self): try: typ, dat = self._simple_command('ID', 'NIL') res, dat = self._untagged_response(typ, dat, 'ID') except: return False, dat[0] return ok(res), dat[0] def getannotation(self, mailbox, pattern='*'): typ, dat = self._si...
NOTATION', mailbox, quote(pattern), quote('value.shared')) return self._untagged_response(typ, dat, 'ANNOTATION') def setannotation(self, mailbox, desc, value): if value: value = quote(value) else: value = "NIL" typ, dat = self._simple_command('SETANNOTATION'...
anhstudios/swganh
data/scripts/templates/object/tangible/ship/attachment/weapon/shared_blacksun_heavy_weapon2_s02.py
Python
mit
474
0.046414
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Tangible() result.template = "object/tangible/ship/attachment/weapon/shared
_blacksun_heavy_weapon2_s02.iff" result.attribute_template_id = 8 result.stfName("item_n
","ship_attachment") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
barche/k3d
share/k3d/scripts/animation/keyframes.py
Python
gpl-2.0
2,449
0.037158
import k3d class control_point: def __init__(self, position, weight): self.position = position self.weight = weight class nucurve: def __init__(self, order): self.order = order self.control_points=[] self.knots = [] class arc_length: def __init__(self, T, Point, Length): self.t = T self.point = Poin...
is(i + 1, k - 1, t, knots) d2 = knots[i + k + 1] - knots[i + 1] if d1 > 0.0001 or d1 < -0.0001: a = n1 / d1 else: a = 0 if
d2 > 0.0001 or d2 < -0.0001: b = n2 / d2 else: b = 0 ret = a + b else: if knots[i] <= t and t <= knots[i + 1]: ret = 1 else: ret = 0 return ret def evaluate(Curve, T): c = k3d.vector3(0, 0, 0) for i in range(len(Curve.control_points)): control_point = Curve.control_points[i] w = control_p...
Yelp/dumb-init
tests/conftest.py
Python
mit
1,129
0
import os from unittest import mock import pytest @pytest.fixture(autouse=True, scope='function') def clean_environment(): """Ensure all tests start with a clean environment. Even if tests properly clean up after themselves, we still need this in case the user runs tests with an already-polluted environ...
{'DUMB_INIT_DEBUG': '', 'DUMB_INIT_SETSID': ''}, ): yield @pytest.fixture(params=['1', '0']) def both_d
ebug_modes(request): with mock.patch.dict(os.environ, {'DUMB_INIT_DEBUG': request.param}): yield @pytest.fixture def debug_disabled(): with mock.patch.dict(os.environ, {'DUMB_INIT_DEBUG': '0'}): yield @pytest.fixture(params=['1', '0']) def both_setsid_modes(request): with mock.patch.dict...
genialis/resolwe
resolwe/toolkit/tests/test_files.py
Python
apache-2.0
1,832
0.002729
# pylint: disable=missing-docstring import os from resolwe.test import ProcessTestCase, tag_process, with_docker_executor class FilesProcessTestCase(ProcessTestCase): def setUp(self): super().setUp() self.files_path = os.path.abspath( os.path.join(os.path.dirname(__file__), "files") ...
@with_docker_executor @tag_process("upload-file") def test_upload_file_compressed(self): """Test that compressed files are processed correctly.""" upload_file = self.run_process( "upload-file", {"src": "upload_file/input_file.txt.gz"} ) self.assertFile( ...
@tag_process("upload-file") def test_upload_zip_file(self): upload_file = self.run_process("upload-file", {"src": "input_file.txt.zip"}) self.assertFile(upload_file, "file", "input_file.txt.gz", compression="gzip") @with_docker_executor @tag_process("upload-file") def test_upload_tar_gz...
wupeiran/ursula
library/mongodb_replication.py
Python
mit
15,988
0.006005
#!/usr/bin/python # (c) 2015-2016, Sergei Antipov, 2GIS LLC # # 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) ...
escription: The port of the host, which should be added/deleted from RS returned: success type: int sample: 27017 host_type: description: The type of the host in replica set returned: success type: string sample: "replica" ''' import ConfigParser import time from distutils.version import LooseVersion try:...
igurationError from pymongo.errors import AutoReconnect from pymongo.errors import ServerSelectionTimeoutError from pymongo import version as PyMongoVersion from pymongo import MongoClient from pymongo import MongoReplicaSetClient except ImportError: pymongo_found = False else: pymongo_found...
vbenavente/data-structures
src/test_stack.py
Python
mit
1,251
0
# -*- coding: utf-8 -*- """File tests Stack module functionality.""" import pytest from stack import Stack TEST_INIT_DATA = [ ("encyclopedia", "a"), ([4, 5, 6], 6) ] TEST_PUSH_DATA = [ ("dictionary", "y", "y"), ("bigandsmall", "word", "word") ]
TEST_POP_DATA = [ ("dictionary", "y"), ("bigandsmall", "l") ] @pytest.mark.parametrize("initial, result", TEST_INIT_DATA) def test_stack_init(initial, result): """Function tests Stack init method.""" test_case = Stack(initial) assert test_case.ll.head.data == result @pytest.mark.parametrize("in...
tion tests Stack push method.""" test_case = Stack(initial) test_case.push(value) assert test_case.ll.head.data == result @pytest.mark.parametrize("initial, result", TEST_POP_DATA) def test_stack_pop(initial, result): """Function tests Stack pop method.""" test_case = Stack(initial) assert tes...
realms-team/solmanager
libs/smartmeshsdk-REL-1.3.0.1/vmanager_apps/VMgr_SendPing.py
Python
bsd-3-clause
4,789
0.008561
#!/usr/bin/python ''' This script sends a ping to a specific mote and waits for the pingResponse notification. If any other pingResponses are received, the program continues listening and waits until the correct one is received. ''' #============================ adjust path ===================================== impor...
c SmartMeshSDK imports from SmartMeshSDK import sdk_version # VManager-specific imports from VManagerSDK.vmanager import Configuration fro
m VManagerSDK.vmgrapi import VManagerApi from VManagerSDK.vmanager.rest import ApiException #============================ defines ========================================= DFLT_MGR_HOST = "127.0.0.1" DFLT_MOTE_MAC = "00-17-0D-00-00-60-08-DC" urllib3.disable_warnings() # disable warnin...
redbox-mint/redbox
config/src/main/config/portal/default/redbox/scripts/workflows/inbox.py
Python
gpl-2.0
5,512
0.003266
import time from com.googlecode.fascinator.common import JsonSimple from com.googlecode.fascinator.api.storage import StorageException from java.io import ByteArrayInputStream from org.apache.commons.lang import StringEscapeUtils def truncate(s, maxLength): return s[:maxLength] + (s[maxLength:] and "...") class I...
request
Data.getJsonObject() formFields = self.__formData.getFormFields() for formField in formFields: if formField in requestFields: data.put(formField, self.__formData.get(formField)) description = self.__formData.get("redbox:submissionProcess.dc:descrip...
fillest/rtmp_load
run.py
Python
mit
5,727
0.034922
#!/usr/bin/env python import subprocess import sys import signal import datetime import argparse import requests import calendar import json import zlib import time def get_median (values): sv = sorted(values) if len(sv) % 2 == 1: return sv[(len(sv) + 1) / 2 - 1] else: lower = sv[len(sv) / 2 - 1] upper = sv[...
-stat-host', default = '10.40.25.155:7778', help = "stat server host[
:port]") return parser.parse_args() def parse_line (line): parts = line.strip().split() try: t = datetime.datetime.strptime(parts[0] + ' ' + parts[1], '%Y-%m-%d %H:%M:%S.%f') except: print >> sys.stderr, "Invalid line:", line raise rtype = parts[2] return rtype, t, parts def mistress_server_start_test (t...
inteldcie/PtasHorizon
horizon/openstack_dashboard/dashboards/admin/alarmhistory/urls.py
Python
apache-2.0
891
0.003367
# # Copyright (c) 2015 Intel Corporation # # 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 License is distrib
uted on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from django.conf.urls import patterns # noqa from django.conf.urls import url # noqa from openstack_dashboard...
CountZer0/PipelineConstructionSet
python/maya/site-packages/pymel-1.0.5/pymel/internal/cmdcache.py
Python
bsd-3-clause
51,191
0.011525
# Built-in imports import os, re, inspect, keyword # Maya imports import maya.cmds as cmds import maya.mel as mm # PyMEL imports import pymel.util as util import pymel.versions as versions # Module imports from . import plogging from . import startup _logger = plogging.getLogger(__name__) moduleNameShortToLong = {...
( 'postSaveScript', None, ['save'] ), ( 'type', None, ['open', 'newFile', 'save', 'exportAll', 'exportSelected', 'exportAnim', 'exportSelectedAnim', 'exportAnimFromReference', 'exportSelectedAnimFromReference' ] ), ), 'joint' : ( ( 'absolute', ...
ative', True, ['position'] ) ) } UI_COMMANDS ="""attrColorSliderGrp attrControlGrp attrEnumOptionMenu attrEnumOptionMenuGrp attrFieldGrp attrFieldSliderGrp attrNavigationControlGrp attributeMenu colorIndexSliderGrp ...
Jawoll/automatchthreads
modules/scrapers/owl.py
Python
mit
47
0.021277
class OWL: def __init__(self
):
pass
google/citest
tests/base/journal_navigator_test.py
Python
apache-2.0
2,737
0.003288
# Copyright 2018 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 a...
ed. # See the License for the specific language governing permissions and # limitations under the License. """Test citest.reporting.html_renderer module.""" imp
ort os import shutil import tempfile import unittest from citest.base import ( Journal, StreamJournalNavigator) class StreamNavigatorTest(unittest.TestCase): # pylint: disable=missing-docstring @classmethod def setUpClass(cls): cls.temp_dir = tempfile.mkdtemp(prefix='journal_nav_test') @classme...
WarrenWeckesser/heatmapcluster
setup.py
Python
bsd-2-clause
1,668
0
# Copyright (c) 2015, Warren Weckesser. All rights reserved. # This software is licensed according to the "BSD 2-clause" license. from __future__ import print_function from setuptools import setup from os import path def get_heatmapcluster_version(
): """ Find the value assigned to __version__ in heatmapcluster.py. This function assumes that there is a line of the form __version__ = "version-string" the file. It returns the string version-string, or None if such a line is not found. """ with open("heatmapcluster.py", "r") a...
d s[0] == "__version__": return s[1][1:-1] # Get the long description from README.rst. _here = path.abspath(path.dirname(__file__)) with open(path.join(_here, 'README.rst')) as f: _long_description = f.read() setup(name='heatmapcluster', version=get_heatmapcluster_version(), author="W...
iulian787/spack
lib/spack/spack/test/buildrequest.py
Python
lgpl-2.1
1,708
0
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) import pytest import spack.installer as inst import spack.repo import spack.spec def test_build_request_errors(install_...
alueError, match='must have a concrete spec'):
inst.BuildRequest(pkg, {}) def test_build_request_basics(install_mockery): spec = spack.spec.Spec('dependent-install') spec.concretize() assert spec.concrete # Ensure key properties match expectations request = inst.BuildRequest(spec.package, {}) assert not request.pkg.stop_before_phase...
kevin-coder/tensorflow-fork
tensorflow/python/data/experimental/kernel_tests/serialization/shuffle_dataset_serialization_test.py
Python
apache-2.0
5,623
0.004624
# Copyright 2017 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...
generated non-deterministically. reshuffle_each_iteration=reshuffle_each_iteration) # pylint: enable=cell-var-from-loop # We checkpoint the initial state of the Dataset so that we can restore # the seeds in the next run. Since the seeding is non-deterministic # the datas...
t_saved=False, verify_exhausted=False, save_checkpoint_at_end=False) actual = self.gen_outputs( ds_fn, break_points=self.gen_break_points(num_outputs), num_outputs=num_outputs, ckpt_saved=True, verify_exhausted=False) se...
vlasovskikh/funcparserlib
tests/test_json.py
Python
mit
3,554
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals import unittest from typing import Text, Optional from funcparserlib.parser import NoParseError from funcparserlib.lexer import LexerError from . import json class JsonTest(unittest.TestCase): def t(self, data, expected=None): # type: (Tex...
e NoParseError") def test_numbers(self):
# type: () -> None self.t( """\ [ 0, 1, -1, 14, -14, 65536, 0.0, 3.14, -3.14, -123.456, 6.67428e-11, -1.602176e-19, 6.67428E-11 ] """, [ 0, 1, -1, ...
persandstrom/home-assistant
homeassistant/components/logger.py
Python
apache-2.0
3,869
0
""" Component that will help set the level of logging for components. For more details about this component, please refer to the documentation at https://home-assistant.io/components/logger/ """ import logging from collections import OrderedDict import voluptuous as vol import homeassistant.helpers.config_validation...
f service.service == SERVICE_SET_DEFAULT_LEVEL: set_default_log_level(service.data.get(ATTR_LEVEL)) else: set_log_levels(service.data) hass.services.async_register( DOMAIN, SERVICE_SET_DEFAULT_LEVEL, async_service_handler, schema=SERVICE_SET_DEFAULT_LEVEL_SCHEMA)
hass.services.async_register( DOMAIN, SERVICE_SET_LEVEL, async_service_handler, schema=SERVICE_SET_LEVEL_SCHEMA) return True
MalloyPower/parsing-python
front-end/testsuite-python-lib/Python-3.6.0/Lib/venv/__init__.py
Python
mit
18,240
0.000548
""" Virtual environment (venv) package for Python. Based on PEP 405. Copyright (C) 2011-2014 Vinay Sajip. Licensed to the PSF under a contributor agreement. """ import logging import os import shutil import subprocess import sys import types logger = logging.getLogger(__name__) class EnvBuilder: """ This cl...
os.remove(fn) elif os.path.isdir(fn): shutil.rmtree(fn) def ensure_directories(self, env_dir): """ Create the directories for the environment. Returns a context object which holds paths in the environment,
for use by subsequent logic. """ def create_if_needed(d): if not os.path.exists(d): os.makedirs(d) elif os.path.islink(d) or os.path.isfile(d): raise ValueError('Unable to create directory %r' % d) if os.path.exists(env_dir) and sel...
quanix/PenBlog
PenBlog/admin/urls.py
Python
apache-2.0
1,174
0.01209
#!/usr/bin/env python # -*- coding:utf-8 -*- from PenBlog.admin import article,category,link,other __author__ = 'lihaoquan' from django.conf.urls import patterns, include, url urlpatterns = patterns('', # 文章 url(r'^$', article.show_articles), url(r'^new-article/$', article.new), url(r'^edit-article...
category.edit), url(r'^delete-category/([0-9a-f]+)/$', category.delete), # 连接 url( r'^show-links/$', link.show_all), url( r'^new-link/$', link.new), url( r'^edit-link/([0-9a-f]+)/$', link.edit), url( r'^delete-link/([0-9a-f]+)/$', link.delete), # 设置 url( r'^blog-settings/$', other.sho...
url( r'^import-xml/(.+?)/$', other.import_xml), url( r'^import-and-export/$', other.import_and_export), )
sergeyf/scikit-learn
sklearn/cluster/_kmeans.py
Python
bsd-3-clause
77,660
0.000489
"""K-means clustering.""" # Authors: Gael Varoquaux <gael.varoquaux@normalesup.org> # Thomas Rueckstiess <ruecksti@in.tum.de> # James Bergstra <james.bergstra@umontreal.ca> # Jan Schlueter <scikit-learn@jan-schlueter.de> # Nelle Varoquaux # Peter Prettenhofer <peter.pretten...
n_local_trials : int, default=None The number of seeding trials for each center (except the first), of
which the one reducing inertia the most is greedily chosen. Set to None to make the number of trials depend logarithmically on the number of seeds (2+log(k)); this is the default. Returns ------- centers : ndarray of shape (n_clusters, n_features) The initial centers for k-means. ...
treveradams/openerp-freeswitch-connector
freeswitch_click2dial/freeswitch_click2dial.py
Python
agpl-3.0
21,454
0.002144
# -*- encoding: utf-8 -*- ############################################################################## # # FreeSWITCH Click2dial module for OpenERP # Copyright (C) 2014 Trever L. Adams # Copyright (C) 2010-2013 Alexis de Lattre <alexis@via.ecp.fr> # # This program is free software: you can redistribute it...
'alert_info', 'password'] )] def _reformat_number( self, cr, uid, erp_number, fs_server=None, context=None): ''' This function is dedicated to the transformation of the number available in OpenERP to the number that FreeSWITCH should dial. You may have to inherit...
ng phone number' _logger.debug('Number before reformat = %s' % erp_number) if not fs_server: fs_server = self._get_freeswitch_server_from_user( cr, uid, context=context) # erp_number are supposed to be in E.164 format, so no need to # give a country code here...
minad/thinkpad-tools
thinkpad/ThinkpadFanDriver.py
Python
gpl-3.0
869
0.035673
from FanDriver import FanDriver from Util import slurp, burp import os class ThinkpadFanDriver(FanDriver): def __init__(self): FanDriver.__init__(self, 0, 255) if not os.access('/sys/devices/platform/thinkpad_hwmon/pwm1', os.W_OK): raise SystemError() def driverStart(self): self.__setWatchdog(8) self._...
elf): return slurp('/sy
s/devices/platform/thinkpad_hwmon/pwm1') def __setWatchdog(self, time): burp('/sys/bus/platform/drivers/thinkpad_hwmon/fan_watchdog', '%d' % time) def __setMode(self, mode): if mode in [1, 2]: # Manual, auto print 'Fan mode %d' % mode burp('/sys/devices/platform/thinkpad_hwmon/pwm1_enable', '%d' % mode...
wiki-ai/wikilabels
tests/test_stats_routes.py
Python
mit
342
0
from .routes_test_fixture import app # noqa def test_stats_wiki_campai
gn(client): # t
est active campaign assert client.get("/stats/enwiki/1")._status_code == 200 # test archived campaign assert client.get("/stats/enwiki/7")._status_code == 200 def test_stats(client): assert client.get("/stats/")._status_code == 200
robertnishihara/ray
python/ray/util/sgd/tests/test_torch.py
Python
apache-2.0
23,491
0
import numpy as np import os import pytest import torch import torch.nn as nn import torch.distributed as dist from torch.utils.data import DataLoader import ray from ray import tune from ray.util.sgd.torch import TorchTrainer from ray.util.sgd.torch.training_operator import ( get_test_operator, get_test_metrics_o...
trainer1.shutdown() trainer2 = TorchTrainer( config={"custom_func": train_epoch}, training_operator_cls=TestOperator, num_workers=num_workers, use_local=use_local, use_gpu=False, ) trainer2.load_state_dict(state) models2 = trainer2.get_model()
for model_1, model_2 in zip(models1, models2): model1_state_dict = model_1.state_dict() model2_state_dict = model_2.state_dict() assert set(model1_state_dict.keys()) == set(model2_state_dict.keys()) for k in model1_state_dict: assert torch.equal(model1_state_dict[k], mo...
mgaitan/beppo
icons/text_gif.py
Python
gpl-2.0
2,953
0.024721
#Done with imageEmbedder 1.0 utility img2pytk.py from # http://www.3dartist.com/WP/python/pycode.htm#img2pytk import Tkinter as tk root = tk.Tk() img00 = tk.PhotoImage(format='gif',data= 'R0lGODlhJgAYAOf/AB4aGR8bGh4fHSIeHR8gHicdGSYdHSobHSMfHiocHiAh' +'HywcGiceHiUgGigeHy4dGyEjICUhICUhIC4eHCAk...
+'AHkQ5Ake0H9AX5oJo+3BCDbTvEELAmWQradQNV574O2NkD8IUE2ztoqBnJ0a' +'wz
6MN6PSrQGN8GThEWwZMzQyBs2yF/fhP0pPvNmIowjPoRtomBnTVUKLomKG' +'5TLc5iBYHxmUCA0KpazCqmC+HEHAw0me4YdZ+BgzIIiQoEfR/D0qwusWLylA' +'BM2K51AzQU8spjnh8kjQoFzx+unzoYdXrVUasDzaVrxhvhC4Kv6NuCRIUCZ2' +'/lYmi7AKV605MfB4IryxYRo1zA5AuEDCg4whQxwxhBAIVLGKLKsUocQhmNVX' +'kDIZWNMHFVQwUcUTUm...
bvalerius/py-babymaker
tests/test_babymaker.py
Python
mit
9,457
0.000211
from babymaker import BabyMaker, EnumType, IntType, StringType, UUIDType, FieldType, DatetimeType, FloatType, EmbedType import unittest import string import sys from datetime import datetime, timedelta class TestMakeSomeBabies(unittest.TestCase): def test_make_one(self): fields = { "id": UUID...
n female_of_the_species.make_some(100): the_id = baby.get("id") self.assertIsInstance(the_id, float) self.assertTrue(the_id >= 0.0) self.assertTrue(the_id <= 1.0) fields = { "id": FloatType(min_value=1.0) } female_of_the_species = BabyM...
_species.make_one() the_id = one.get("id") self.assertIsInstance(the_id, float) self.assertTrue(the_id >= 1.0) self.assertTrue(the_id <= 2.0) def test_string_field(self): fields = { "id": StringType(min_size=10, max_size=22) } female_of_the_specie...
hiteshagrawal/python
networking/subnet-cal.py
Python
gpl-2.0
620
0.025806
#!/usr/bin/python #my_subnet = input("Enter Subnet address:") my_ip = "192.168.1.100" my_subnet = "255.255.255.0" ip = my_ip.split(".") print ip # Check the validity of the ip address while True: #my_ip = input("Enter a ip address:") if int(ip[0]) <= 223 and (int(ip[1]) != 169 or int(ip[2]) != 254) and (int(ip[...
(ip[3]) <= 254): print "You entered a valid ip" break els
e: print "You entered a wrong ip" continue bin_ip = "" for a in ip: print bin(int(a)).split("b")[1].zfill(8) bin_ip += bin(int(a)).split("b")[1].zfill(8) print bin_ip print type(bin_ip)
jeremiahyan/odoo
addons/website_event_booth_exhibitor/__manifest__.py
Python
gpl-3.0
974
0.002053
# -*- coding: utf-8 -*- { 'name': 'Booths/Exhibitors Bridge', 'category': 'Marketing/Events', 'version': '1.0', 'summary': 'Event Booths, automatically create a sponsor.', 'description': """ Automatically create a sponsor when renting a booth. """, 'depends': ['website_event_exhibitor', 'we...
l_templates.xml' ], 'auto_install': True, 'assets': { 'web.assets_frontend': [
'/website_event_booth_exhibitor/static/src/js/booth_sponsor_details.js', ], 'web.assets_tests': [ 'website_event_booth_exhibitor/static/tests/tours/website_event_booth_exhibitor.js', ], }, 'license': 'LGPL-3', }
jwoschitz/SimpleAuth
src/mail.py
Python
mit
3,973
0.010571
import smtplib from email.mime.text import MIMEText from email.MIMEMultipart import MIMEMultipart from email.Header import Header from email import Charset class MailConfig(object): def __init__(self, config): self.smtp_host = config.smtp_host self.smtp_port = config.smtp_port self.smtp_loc...
,self.config.smtp_password) server.set_debuglevel(1) server.sendmail(from_addr, receiver_addr, msg.as_string()) server.quit() def _append_header(self, msg, from_addr, receiver_addr, subject, is_multipart = False): #header_charset = 'ISO-8859-1' #msg['Subject
'] = Header(unicode(subject), header_charset) msg['Subject'] = Header(subject.encode('utf-8'), 'UTF-8').encode() msg['From'] = from_addr msg['To'] = receiver_addr if is_multipart: msg.preamble = 'This is a multi-part message in MIME format.' return msg def _g...
medialab/ricardo
analysis/WorldTradeWeb/sageo_decenal_agg.py
Python
agpl-3.0
737
0.02578
import csv import itertools with open('./data/SAGEO_RICardo_edges.csv', 'r', encoding='utf8') as input_f, open('./data/SAGEO_RICardo_periode_edges.csv', 'w', encoding='utf8') as output_f: edges = csv.DictReader(input_f) agg_edges_csv = csv.DictWriter(output_f, fieldnames=('idorigine','iddestination','volume','...
od_group = lambda e : (e['idorigine'],e['iddestination'],e['periode']) edges = sorted(edges, key = period_group) for key, agg_edges in itertools.groupby(edges, key = period_group): agg_edges_csv.writerow({'idorigine':key[0], 'iddestination':key[1], 'periode':key[2], 'volume': sum(float(e['volume']) for ...
!='undefined')})
dtschan/weblate
weblate/api/views.py
Python
gpl-3.0
13,604
0
# -*- coding: utf-8 -*- # # Copyright © 2012 - 2016 Michal Čihař <michal@cihar.com> # # This file is part of Weblate <https://weblate.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, eith...
e: data['remote_commit'] = obj.get_last_remote_commit() if isinstance(obj, Translation):
subproject = obj.subproject data['url'] = reverse( 'api:translation-repository', kwargs={ 'subproject__project__slug': subproject.project.slug, 'subproject__slug': subproject.slug, ...
aaronxsu/raster-foundry
app-tasks/rf/src/rf/utils/emr.py
Python
apache-2.0
1,771
0.002823
import logging import time import boto3 import dns.resolver from retrying import retry logger = logging.getLogger(__name__) def get_cluster_id(): """Determine EMR cluster ID via DNS""" resolver = dns.resolver.Reso
lver() cluster_id = resolver.query('dataproc.rasterfoundry.com', 'TXT')[0] return cluster_id.to_text().strip('"') @retry(wait_exponential_multiplier=2000, wait_exponential_max=30000, stop_max_attempt_number=5) def wait_for_emr_success(step_id, cluster_id): """Wait for batch success/failure given an initia...
of step in Returns: boolean """ emr = boto3.client('emr') get_description = lambda: emr.describe_step(ClusterId=cluster_id, StepId=step_id) logger.info('Starting to check for status updates for step %s', step_id) step_description = get_description() current_status = step_descriptio...
ptdtan/Ragout
lib/newick/lexer.py
Python
gpl-3.0
3,236
0.00309
''' A Python module for parsing Newick files. Copyright (C) 2003-2008, Thomas Mailund <mailund@birc.au.dk> This module contains the functionality for lexical analysis. You rarely need to access it in your own modules and should probably only use the parser or tree modules, and from those most likely only the objects...
((\"[^\"]+\")|('[^']+')|(\w[^,:(); \t\n]*|_)+)\s*")), (tokens.Colon, re.compile(r'\s*(:)\s*')), (tokens.SemiColon, re.compile(r'\s*(;)\s*')), (tokens.Comma, re.compile(r'\s*(,)\s*')), (tokens.LParen, re.compile(r'\s*(\()\s*')), (tokens.RParen, re.compile(r'\s*(\))\s*')) ] class LexerError(...
err class Lexer(object): '''Lexicographical analysis of a Newick tree.''' def __init__(self, input): self.input = input self.next_token = None def remaining(self): ''' The remaining input stream, i.e. the stream that hasn't been split into tokens. ''' result = Non...
ArnaudBelcour/liasis
test/test_pbsea.py
Python
gpl-3.0
9,677
0.017361
import numpy as np import os import pandas as pa import scipy.stats as stats import unittest from pbsea import PandasBasedEnrichmentAnalysis, EnrichmentAnalysisExperimental, preprocessing_files from unittest.mock import patch test_data_directory = 'test_data/' test_data_directory_cdf = test_data_directory + 'test_cdf...
884863e-8 ''' print("\nTesting normal approximation sf on dataframe ") counts_df = pa.read_csv(test_data_directory_sf + 'data_interest_test_sf_normal' + ".tsv", sep = "
\t") counts_df_reference = pa.read_csv(test_data_directory_sf + 'data_reference_test_sf_normal' + ".tsv", sep = "\t") counts_df.set_index('Genes', inplace = True) counts_df_reference.set_index('Genes', inplace = True) df_joined = counts_df.join(counts_df_reference) df_joined_w...
edx/edx-enterprise
enterprise/migrations/0110_add_default_contract_discount.py
Python
agpl-3.0
1,163
0.00172
# Generated by Django 2.2.14 on 2020-09-03 02:09 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('enterprise', '0109_remove_use_enterprise_catalog
_sample'), ] o
perations = [ migrations.AddField( model_name='enterprisecustomer', name='default_contract_discount', field=models.DecimalField(blank=True, decimal_places=5, help_text='Specifies the discount percent used for enrollments from the enrollment API where capturing the discount pe...
ljm516/big-challenge
chanllenge/util/wayknew.py
Python
apache-2.0
1,625
0.004947
from json import dumps import requests d = {'yolar': 535, 'galaxy': 536, 'solar': 551, 'swordkeeper': 552, 'civilization': 553, 'CurvatureDrive': 554, 'singer': 555, 'hdfragments': 556, 'evans': 557, 'dagon': 558, 'di-foil': 559, 'dimension': 560, 'farmer': 562, 'hibernation': 564, 'huformation': 565, 'ment...
I1NiIsImlhdCI6MTQ5NzU4MDY5NywiZXhwIjoxNTEzMTMyNjk3fQ.eyJpZCI6MjB9.uo8JdyzBBQ-oGxzMyoiFDlycWk-fqagZLVgwrwqTSBM', 'Content-Type': 'application/json', 'Host': 'api.wayknew.com', 'Referer': 'https://wayknew.com/articles/535/edit', 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/53...
_wayknew(repo_name, str_doc): if repo_name not in d.keys(): print('article not in wayknew, please create a null article in wayknew!') exit(-1) title = repo_name + ' 线上API文档' url = 'https://api.wayknew.com/api/articles/' + str(d[repo_name]) html_content = '<p>' + str_doc + '</p>' requ...
rwl/muntjac
muntjac/demo/sampler/features/link/LinkCurrentWindowExample.py
Python
apache-2.0
1,076
0.002788
from muntjac.api import VerticalLayout, Link from muntjac.terminal.theme_resource import ThemeResource from muntjac.terminal.external_resource import ExternalResource class LinkCurrentWindowExample(VerticalLayout): _CAPTION
= 'Open Google' _TOOLTIP = 'http://www.google.com' _ICON = ThemeResource('../sampler/icons/icon_world.gif') def __init__(self): super(LinkCurrentWindowExample, self).__init__() self.setSpacing(True) # Link w/ text and tooltip l = Link(self._CAPTION, ExternalResource('http...
APTION, ExternalResource('http://www.google.com')) l.setDescription(self._TOOLTIP) l.setIcon(self._ICON) self.addComponent(l) # Link w/ icon and tooltip l = Link() l.setResource(ExternalResource('http://www.google.com')) l.setDescription(self._TOOLTIP) l....