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
browning/shows
shows/manage.py
Python
mit
254
0
#!/usr/bin/env pytho
n import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "shows.settings.local") from django.core.management import ex
ecute_from_command_line execute_from_command_line(sys.argv)
Peter-Lavigne/Project-Euler
p081.py
Python
mit
699
0
# https://projecteuler.net/problem=81 from projecteuler.FileReader import file_to_2D_array_of_ints # this problem uses a similar solution to problem 18, "Maximum Path Sum 1." # this problem us
es a diamond instead of a pyramid matrix = file_to_2D_array_of_ints("p081.txt", ",") y_max = len(matrix) - 1 x_max = len(matrix[0]) - 1 for y in range(y_max, -1, -1): for x in range(x_max, -1, -1): if y == y_max and x == x_max: continue elif y == y_max: matrix[y][x] += mat...
y][x] += matrix[y + 1][x] else: matrix[y][x] += min(matrix[y][x + 1], matrix[y + 1][x]) print(matrix[0][0])
shubham0d/SmartClass
SmartClass/userhome/migrations/0003_auto_20161015_0037.py
Python
gpl-3.0
584
0
# -*- coding: utf-8 -*-
from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('userhome', '0002_auto_20161014_2208'), ] operations = [ migrations.AddField( model_name='notice', name='Path', f...
name='Topic', field=models.CharField(default=b'New Update', max_length=100), ), ]
blakehawkins/SheetSync
tests/test_backup.py
Python
mit
1,701
0.014109
# -*- coding: utf-8 -*- """ Test the "backup" function, which saves sheet data to file. """ import sheetsync import time, os CLIENT_ID = os.environ['SHEETSYNC_CLIENT_ID'] CLIENT_SECRET = os.environ['SHEETSYNC_CLIENT_SECRET'] TESTS_FOLDER_KEY = os.environ.get("SHEETSYNC_FOLDER_KEY") SHEET_TO_BE_BACKED_UP = "1-HpLBDv...
document_key = backup_key, worksheet_name = 'Simpsons', key_column_headers = ['Character'], header_row_ix=1) backup_data = backup_sheet.data() assert "Bart Simpson" in backup_data assert backup_data[...
ckup_sheet.drive_service.files().delete(fileId=backup_sheet.document_key).execute()
shakamunyi/neutron-vrrp
neutron/tests/unit/openvswitch/test_ovs_neutron_agent.py
Python
apache-2.0
71,665
0.000251
# Copyright (c) 2012 OpenStack Foundation. # # 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...
ovs_neutron_agent.create_agent_config_map(cfg.CONF) self.assertEqual(cfgmap['tunnel_types'], [p_const.TYPE_GRE])
def test_create_agent_config_map_fails_no_local_ip(self): # An ip address is required for tunneling but there is no default cfg.CONF.set_override('enable_tunneling', True, group='OVS') with testtools.ExpectedException(ValueError): ovs_neutron_agent.create_agent_config_map(cfg.CONF...
ctames/conference-host
webApp/urls.py
Python
mit
1,850
0.007027
from django.conf.urls import patterns, include, url from django.conf import settings f
rom django.conf.urls.static import static from django.contrib import admin admin.autodiscover() import views urlpatterns = patterns('', url(r'^pis', views.pis), url(r'^words', views.words, { 'titles': False }), url(r'^projects', views.projects), url(r'^posters', views.poste
rs), url(r'^posterpresenters', views.posterpresenters), url(r'^pigraph', views.pigraph), url(r'^institutions', views.institutions), url(r'^institution/(?P<institutionid>\d+)', views.institution), url(r'^profile/$', views.profile), url(r'^schedule/(?P<email...
ProjectSWGCore/NGECore2
scripts/object/tangible/wearables/boots/item_entertainer_boots_02_01.py
Python
lgpl-3.0
366
0.02459
import sys def setup(core, object): object.setStfFilename('static_item_n') object.setStfName('item
_entertainer_boots_02_01') object.setDetailFilename('static_item_d') object.setDetailName('item_entertainer_boots_02_01') object.setIntAttribute('cat_stat_mod_bonus.@stat_n:agility_modified', 3) object.setStringAt
tribute('class_required', 'Entertainer') return
kepbod/usefullib
test/bpkm.py
Python
mit
2,744
0.001822
#!/usr/bin/env python3 ''' bpkm.py - Calculate BPKM. author: Xiao-Ou Zhang version: 0.2.0 ''' import sys sys.path.insert(0, '/picb/rnomics1/xiaoou/program/usefullib/python') from map import mapto from subprocess import Popen, PIPE import os def calculatebpkm(chrom, sta, end, bam, total=0, length=0, getsegment=False)...
am, '{}:{}-{}
'.format(chrom, sta, end)], stdout=PIPE) as proc: for line in proc.stdout: str_line = line.decode('utf-8') pos = str_line.split()[3] cigar = str_line.split()[5] segment = readsplit(pos, cigar) read_segments.extend(segment) if not read_s...
ganeshgore/myremolab
server/src/test/unit/voodoo/gen/loader/test_SchemaChecker.py
Python
bsd-2-clause
2,998
0.004004
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2005 onwards University of Deusto # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. # # This software consists of contributions made by many individuals, # list...
hema_checker as SchemaChecker import voodoo.gen.exceptions.loader.LoaderErrors as LoaderErrors class WrappedSchemaChecker(SchemaChecker.SchemaChecker): def __init__(self, xml_conten
t, xsd_content): self.__xml_content = xml_content self.__xsd_content = xsd_content def _read_xml_file(self, xmlfile): return self.__xml_content def _read_xsd_file(self, xsdfile): return self.__xsd_content SAMPLE_XML_SCHEMA = """<?xml version="1.0"?> <xs:schema xmlns:xs="http...
tdr130/sec
lib/xml_parser.py
Python
mit
4,735
0.045829
#!/usr/bin/python __VERSION__ = '0.1' __AUTHOR__ = 'Galkan' __DATE__ = '06.08.2014' """ it is derived from https://github.com/argp/nmapdb/blob/master/nmapdb.py """ try: import sys import xml.dom.minidom from xml.etree import ElementTree except ImportError,e: import sys sys.stdout.write("%s\n" %e)...
etElementsByTagName("port") for port in ports: for script in port.getElementsByTagName("script"): script_id = script.getAttribute("id")
script_output = script.getAttribute("output") script_ret_2 = script_id + ":" + script_output self.script_list.append(script_ret_2) self.script[ip] = self.script_list self.script_list = [] self.os["os"] = self.os_list self.mac["mac"] = self.mac_list self.script_...
biomodels/MODEL1302010006
setup.py
Python
cc0-1.0
377
0.005305
from setuptools import setup, find_packages
setup(name='MODEL1302010006', version=20140916, description='MODEL1302010006 from BioModels', url='http://www.ebi.ac.uk/biomodels-main/MODEL1302010006', maintainer='Stanley Gu', maintainer_ur
l='[email protected]', packages=find_packages(), package_data={'': ['*.xml', 'README.md']}, )
samgeen/Hamu
Utils/CommandLine.py
Python
mit
464
0.006466
''' Load options from the command line Sam Geen, July 2013 ''' i
mport sys def Arg1(default=None): ''' Read the first argument default: Default value to return if no argument is found Return: First argument in sys.argv (minus program name) or default if none ''' if len(sys.argv) < 2: return
default else: return sys.argv[1] if __name__=="__main__": print "Test Arg1():" print Arg1() print Arg1("Bumface")
galactose/wviews
wview.py
Python
gpl-3.0
6,822
0.00044
""" Wviews: Worldview Solver for Epistemic Logic Programs Build 1.0 - Port from C++ -> Python. Copyright (C) 2014 Michael Kelly 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 Founda...
se if believes mod = 'K' + mod else: mod = 'M' + mod # 0x4 is epistemic negat
ion if (atom_details & 0x4) == 4: mod = '-' + mod return mod
kbase/transform
lib/biokbase/Transform/TextFileDecoder.py
Python
mit
9,547
0.003771
#!/usr/bin/env python import os import codecs def open_textdecoder(file=None, codec=None, chunkSize=1024): fp = open(file, 'rb') return TextFileDecoder(fp, codec, chunkSize) # TODO look into inheriting from a stream for this class class TextFileDecoder(object): """Class that wraps a file object and handl...
f._codec = codec # use chunk size of 1KB
self._chunkSize = chunkSize def close(self): """Calls file object close() method""" self._fp.close() def readline(self): """Reads chunks of bytes from the file, decoding each chunk until EOL is found. Once EOL is found, the file pointer is set to the b...
datawire/mdk
unittests/test_mdk.py
Python
apache-2.0
27,210
0.000919
""" Tests for the MDK public API that are easier to do in Python. """ from time import time from builtins import range from past.builtins import unicode from unittest import TestCase from tempfile import mkdtemp from collections import Counter import configparser import hypothesis.strategies as st from hypothesis imp...
ve: if isinstance(child, list): count(child) count(list_of_lists) return st.tuples(st.just(list_of_lists), st.tuples(*[st.sampled_from([True, False]) for i in l])) class InteractionTestCase(TestCase): """Tests for the Session interaction API.""" def init(self): """...
alize an empty environment.""" self.connector = MDKConnector(RecordingFailurePolicyFactory()) # Because we want to use blocking resolve() we need async message delivery: self.connector.runtime.dispatcher.pump() self.connector.runtime.dispatcher.callLater = _QuarkRuntimeLaterCaller() ...
rspavel/spack
var/spack/repos/builtin/packages/py-sphinxcontrib-devhelp/package.py
Python
lgpl-2.1
793
0.003783
# 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) from spack import * class PySphinxcontribDevhelp(PythonPackage): """sphinxcontrib-devhelp is a sphinx extension whic...
://sphinx-doc.org/" url = "https://pypi.io/packages/source/s/sphinxcontrib-devhelp/sphinxcontrib-devhelp-1.0.1.tar.gz" version('1.0.1', sha256='6c64b077937330a9128a4da74586e8c2130262f014689b4b89e2d08ee7294a34') depends_on('[email protected]:', type=('b
uild', 'run')) depends_on('py-setuptools', type='build') def test(self): # Requires sphinx, creating a circular dependency pass
yasserglez/arachne
tests/testresultqueue.py
Python
gpl-3.0
6,369
0.000628
# -*- coding: utf-8 -*- import os import sys import shutil import optparse import unittest TESTDIR = os.path.dirname(os.path.abspath(__file__)) SRCDIR = os.path.abspath(os.path.join(TESTDIR, os.path.pardir)) sys.path.insert(0, SRCDIR) from arachne.error import EmptyQueue from arachne.result import CrawlResult, Resul...
elf.assert
Equals(len(self._queue), num_results - i - 1) def test_populate(self): self.assertRaises(EmptyQueue, self._queue.get) self._populate_queue() for result in self._results: returned = self._queue.get() self.assertEquals(str(returned.task.url), str(result.task.url)) ...
bugsnag/bugsnag-python
tests/fixtures/django1/notes/urls.py
Python
mit
503
0
from django.conf.urls import url from . import views urlpatterns =
[ url(r'^$', views.index), url(r'unhandled-crash/', views.unhandled_crash, name='crash'), url(r'unhandled-crash-chain/', views.unhandled_crash_chain), url(r'unhandled-template-crash/', views.unhandled_crash_in_template), url(r'handled-exception/', views.handle_notify
), url(r'handled-exception-custom/', views.handle_notify_custom_info), url(r'crash-with-callback/', views.handle_crash_callback), ]
talumbau/datashape
datashape/type_symbol_table.py
Python
bsd-2-clause
4,644
0.001938
""" A symbol table object to hold types for the parser. """ from __future__ import absolute_import, division, print_function __all__ = ['TypeSymbolTable', 'sym'] import ctypes from . import coretypes as ct _is_64bit = (ctypes.sizeof(ctypes.c_void_p) == 8) def _complex(tp): """Simple temporary type constructor...
('complex64', ct.complex64), ('complex128', ct.complex128), ('real', ct.float64), ('complex', ct.complex_float64), ('string', ct.string), ('json', ct.json), ...
, ('time', ct.time_), ('datetime', ct.datetime_)]) # data types with a type constructor self.dtype_constr.update([('complex', _complex), ('string', ct.String), ('struct', _struct), ...
yxdong/ybk
ybk/lighttrade/trader.py
Python
mit
2,160
0.00141
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import time import yaml import logging import threading from ybk.lighttrade.sysframe import Client as SysframeClient log = logging.getLogger('trader') configfile = open(os.path.join(os.path.dirname(__file__), 'trading.yaml'), encoding='utf-8') config = yaml.loa...
= self else: old = self.traders[signature] self.client = old.client self.client.keep_alive() def __getattr__(self, key): if key in self.__dict__: return self.__dict__[key] else: return getattr(self.client, key) ...
et + self.client.latency * 3 if __name__ == '__main__': pass
richardmin97/PaintTheWorld
Server/painttheworld/game.py
Python
gpl-3.0
8,968
0.005352
# painttheworld/game.py # # Represent and track the current game state. import numpy as np import datetime import math from painttheworld import constants from painttheworld.constants import m1, m2, m3, m4, p1, p2, p3 ''' Note that Latitude is North/South and Longitude is West/East''' class GameState: """Keeps tr...
s might not work too well, as that's not really how nautical miles work). Additionally, it sets the start time to be 3 seconds from now. """ self.center_coord = np.mean(self.u
ser_coords, axis=0) self.conversion_rates = self.conversion_rates(self.center_coord) self.start_time = datetime.datetime.now() + datetime.timedelta(seconds=3) self.end_time = self.start_time + datetime.timedelta(minutes=3) def update(self, coord, team): """Update the game state arra...
SU-ECE-17-7/ibeis
ibeis/dev.py
Python
apache-2.0
32,707
0.003333
#!/usr/bin/env python2.7 # -*- coding: utf-8 -*- """ DEV SCRIPT This is a hacky script meant to be run mostly automatically with the option of interactions. dev.py is supposed to be a developer non-gui interface into the IBEIS software. dev.py runs experiments and serves as a scratchpad for new code and quick scripts...
t inc --db PZ_Master0 --noqcache --interactive-after 10000 --ninit 400 Example: >>> from ibeis.all_imports import * # NOQA >>> ibs = ibeis.opendb('PZ_MTEST') >>> qaid_list = ibs.get_valid_aids() >>> daid_list = None """ from ibeis.algo.hots import automated_matcher ibs1...
val('--ninit', type_=int, default=0) return automated_matcher.incremental_test(ibs1, num_initial) @devcmd('inspect') def inspect_matches(ibs, qaid_list, daid_list): print('<inspect_matches>') from ibeis.gui import inspect_gui return inspect_gui.test_review_widget(ibs, qaid_list, daid_list) def get_i...
gustaveroussy/98drivers
scripts/kart_racer.py
Python
mit
1,836
0.052288
#!/env/python3 import sys import argparse import os import csv import tabix import gzip import io from collections import Counter def chromosom_sizes(hg19_size_file): ''' Return chromosom size range ex: size["chr13"] = 234324 ''' results = {} with open(hg19_size_file) as file: reader = csv.reader(file, d...
sizes[c
hromosom] # Loop over genoms for pos in range(0, size): # get how many mutation at one position count = len([c for c in tabix_file.query(chromosom, pos, pos + 2)]) if count > 0 : speed += count * acceleration else: if speed > 0: speed -= deceleration else: speed = 0.0 print(chro...
tchakravarty/PythonExamples
Code/kirk2015/chapter3/bivariate_normal.py
Python
apache-2.0
582
0.008591
#========================
====================================================== # purpose: bivariate normal distribution simulation using PyMC # author: tirthankar chakravarty # created: 1/7/15 # revised: # comm
ents: # 1. install PyMC # 2. not clear on why we are helping the sampler along. We want to sample from the # bivariate #============================================================================== import random import numpy as np import matplotlib.pyplot as mpl sample_size = 5e5 rhp = 0.9 mean = [10, 20] std_dev...
jddixon/pysloc
tests/test_haskell_comments.py
Python
mit
1,084
0
#!/usr/bin/env python3 # testHaskellComments.py """ Test line counter for the Haskell programmig language. """ import
unittest from argparse import Namespace from pysloc import count_lines_double_dash, MapHolder class TestHaskellComments(unittest.TestCase): """ Test line counter for the Haskell programmig language. """ def setUp(self): pass def t
earDown(self): pass # utility functions ############################################# # actual unit tests ############################################# def test_name_to_func_map(self): """ Verify line counts returned from known Haskell file are correct. """ test_fi...
neuroo/equip
equip/analysis/dataflow/lattice.py
Python
apache-2.0
1,624
0.011084
# -*- coding: utf-8 -*- """ equip.analysis.dataflow.lattice ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The base lattice implementation (mostly used as semi-lattice). :copyright: (c) 2014 by Romain Gaucher (@rgaucher) :license: Apache 2, see LICENSE for more details. """ class Lattice(object): """ Interface for...
es): result_state = None for state in states: if result_state is None: result_state = state else: result_state = self.meet(result_state, state) return result_state
def meet(self, state1, state2): """ Returns the result of the meet \/ (infimum) between the two states. """ pass def lte(self, state1, state2): """ This is the <= operator between two lattice elements (states) as defined by: state1 <= state2 and state2 <= state1 <=> state1 == st...
Alberto-Beralix/Beralix
i386-squashfs-root/usr/lib/python2.7/dist-packages/google/protobuf/descriptor_pb2.py
Python
gpl-3.0
63
0.015873
../
../../../../share/pyshared/google/protobuf/descript
or_pb2.py
jondelmil/brainiac
config/settings/local.py
Python
bsd-3-clause
1,961
0.00051
# -*- coding: utf-8 -*- ''' Local settings - Run in Debug mode - Use console backend for emails - Add Django Debug Toolbar - Add django-extensions as app ''' from .common import * # noqa # DEBUG # ------------------------------------------------------------------------------ DEBUG = env.bool('DJANGO_DEBUG', default...
DJANGO_E
MAIL_BACKEND', default='django.core.mail.backends.console.EmailBackend') # CACHING # ------------------------------------------------------------------------------ CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': '' } } # djang...
asedunov/intellij-community
python/testData/completion/epydocTagsMiddle.after.py
Python
apache-2.0
32
0.03125
def foo
(bar): """ @param ""
"
plotly/plotly.py
packages/python/plotly/plotly/validators/surface/hoverlabel/font/_sizesrc.py
Python
mit
423
0.002364
import _plotly_utils.basevalidators class SizesrcValidator(_plotly_utils.basevalidators
.SrcValidator): def __init__( self, plotly_name="sizesrc", parent_name="surfa
ce.hoverlabel.font", **kwargs ): super(SizesrcValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "none"), **kwargs )
DevinDewitt/pyqt5
examples/quick/models/objectlistmodel/objectlistmodel.py
Python
gpl-3.0
3,424
0.00847
#!/usr/bin/env python ############################################################################# ## ## Copyright (C) 2013 Riverbank Computing Limited. ## Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ## ## This file is part of the examples of PyQt. ## ## $QT_BEGIN_LICENSE:BSD$ ## You may use this file ...
H DAMAGE." ## $QT_END_LICENSE$ ## ############################################################################# from PyQt5.QtCore import pyqtProperty, pyqtSignal, QObject, QUrl from PyQt5.QtGui import QGuiApplication from PyQt5.QtQuick import QQuickView import objec
tlistmodel_rc class DataObject(QObject): nameChanged = pyqtSignal() @pyqtProperty(str, notify=nameChanged) def name(self): return self._name @name.setter def name(self, name): if self._name != name: self._name = name self.nameChanged.emit() colorChan...
sean-/ansible
lib/ansible/utils/display.py
Python
gpl-3.0
6,949
0.003022
# (c) 2014, Michael DeHaan <[email protected]> # # 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 lat...
SS 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 Ansible. If not, see <http://www.gnu.org/licenses/>. # FIXME: copied mostly from old code, needs py3 improvements from __future_
_ import (absolute_import, division, print_function) __metaclass__ = type import textwrap import os import random import subprocess import sys from ansible import constants as C from ansible.errors import AnsibleError from ansible.utils.color import stringc class Display: def __init__(self, verbosity=0): ...
emmanuelle/scikits.image
skimage/graph/setup.py
Python
bsd-3-clause
1,429
0.0007
#!/usr/bin/env python from skimage._build import cython import
os.path base_path = os.path.abspath(os.path.dirname(__file__)) def configuration(parent_package='', top_path=None): from numpy.distutils.misc_util import Configurat
ion, get_numpy_include_dirs config = Configuration('graph', parent_package, top_path) config.add_data_dir('tests') # This function tries to create C files from the given .pyx files. If # it fails, try to build with pre-generated .c files. cython(['_spath.pyx'], working_path=base_path) cython(...
electrumalt/electrum-doge
scripts/merchant/merchant.py
Python
gpl-3.0
9,336
0.008462
#!/usr/bin/env python # # Electrum - lightweight Bitcoin client # Copyright (C) 2011 thomasv@gitorious # # 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...
le if needed check_create_table(conn) while
not stopping: cur = conn.cursor() # read pending requests from table cur.execute("SELECT address, amount, confirmations FROM electrum_payments WHERE paid IS NULL;") data = cur.fetchall() # add pending requests to the wallet for item in data: addr, amount, c...
srikary/sous-chef
modules/robotic_arm.py
Python
gpl-2.0
7,751
0.011869
from drivers.servo_driver import Servo import submodules.stepper_axis as stepper_axis from math import atan, degrees import time class RoboticArm: # Dimensions of the Arm vertical_offset_mm = 50 vertical_arm_mm = 100 horizontal_arm_mm = 100 level_arm_len= 20 claw_offset_to_center = 10 small_cup_positio...
components when the arm is at base base_pos = (100, 0, 30, 30, 30) # Dimensions of the Rail max_rail_translation_mm = 520 def __init__(self, rail_dir_pin, rail_step_pin, rail_enable_pin, base_servo_c
hannel, vertical_servo_channel, horizontal_servo_channel, level_servo_channel, tipping_servo_channel, grasp_servo_channel): self.base_servo = Servo(base_servo_channel) self.vertical_servo = Servo(vertical_servo_channel) self.horizont...
sippy/b2bua
sippy/SipURL.py
Python
bsd-2-clause
12,172
0.011009
# Copyright (c) 2003-2005 Maxim Sobolev. All rights reserved. # Copyright (c) 2006-2014 Sippy Software, Inc. All rights reserved. # # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistrib...
se
lf.host = '' elif hostport[0] == '[': # IPv6 host hpparts = hostport.split(']', 1) self.host = hpparts[0] + ']' if len(hpparts[1]) > 0: hpparts = hpparts[1].split(':', 1) if len(hpparts) > 1: parseport = hpparts[...
Teekuningas/mne-python
mne/io/fieldtrip/fieldtrip.py
Python
bsd-3-clause
6,508
0
# -*- coding: UTF-8 -*- # Authors: Thomas Hartmann <[email protected]> # Dirk Gütlin <[email protected]> # # License: BSD (3-clause) import numpy as np from .utils import _create_info, _set_tmin, _create_events, \ _create_event_metadata, _validate_ft_struct from .. import RawArray from ....
s data array events = _create_events(ft_struct, trialinfo_column) if events is not None: metadata = _create_event_metadata(ft_struct) else: metadata = None tmin = _set_tmin(ft_struct) # create start time epochs = EpochsArray(data=data, info=info, tmin=tmin,
events=events, metadata=metadata, proj=False) return epochs def read_evoked_fieldtrip(fname, info, comment=None, data_name='data'): """Load evoked data from a FieldTrip timelocked structure. This function expects to find timelocked data in the structure data_n...
abirafdirp/inventory
inventory/__init__.py
Python
bsd-3-clause
24
0
__author__ = 'abirafdi'
gruel/AphorismToTEI
tests/test_aphorism_to_xml.py
Python
bsd-3-clause
5,663
0.000883
import os import sys import pytest from .conftest import Process, AphorismsToXMLException file_path = os.path.realpath(__file__) path = os.path.dirname(file_path) sys.path.append(path) path_testdata = os.path.join(path, 'test_files') + os.sep # examples = os.path.join(path, '..', 'Examples', 'TextFiles') + os.sep te...
lines() # Read test footnotes with open(path_testdata + 'footnotes.txt', 'r', encoding="utf-8") as f: footnotes = f.readlines()
# Read full text file with open(path_testdata + 'aphorism_no_intro_title_text_footnotes.txt', 'r', encoding="utf-8") as f: comtoepi._text = f.read().strip() comtoepi.divide_document() assert comtoepi._title == title for i, line in enumerate(comtoepi._text.splitlin...
mobarski/sandbox
topic/tokens.py
Python
mit
455
0.035165
from
contrib import * import re def tokenize(text): tokens = re.findall('(?u)[\w.-]+',text) tokens = [t for t in tokens if not re.match('[\d.-]+$',t)] #tokens = [t for t in tokens if len(t)>2] # TODO remove stopwords return u' '.join(tokens) ## text = KV('data/text.db',5) ## tokens = KV('data/tokens.db'
,5) text = KO('data/text') tokens = KO('data/tokens') for k,v in text.items(): print(k) tokens[k] = tokenize(v.decode('utf8')) tokens.sync()
kreopt/aioweb
aioweb/middleware/csrf/__init__.py
Python
mit
3,212
0.001868
from aiohttp import web from aiohttp_session import get_session, SESSION_KEY as SESSION_COOKIE_NAME from aioweb.middleware.csrf.templatetags import CsrfTag, CsrfRawTag from aioweb.util import awaitable from aioweb.modules.template.backends.jinja2 import APP_KEY as JINJA_APP_KEY import random, string from aiohttp_sessi...
request, 'csrf_token', await get_token(request)) try: response = await awaitable(handler(request)) except web.HTTPException as e: raise e return response return middleware_handler def setup(app): app[JINJA_APP_KEY].add_extension(Cs
rfTag) app[JINJA_APP_KEY].add_extension(CsrfRawTag) async def pre_dispatch(request, controller, actionName): reason = None check_ok = True if request.method not in ('GET', 'HEAD', 'OPTIONS', 'TRACE'): action = getattr(controller, actionName) if not getattr(action, 'csrf_disabled', F...
ringemup/satchmo
satchmo/apps/tax/modules/percent/processor.py
Python
bsd-3-clause
2,581
0.008911
from decimal import Decimal from livesettings import config_value from tax.modules.base.processor import BaseProcessor class Processor(BaseProcessor): method="percent" #def __init__(self, order=None, user=None): # """ # Any preprocessing steps should go here # For instance, copyi...
0.00") for item in order.orderitem_set.filter(product__taxable=True): sub_
total += item.sub_total itemtax = sub_total * (percent/100) taxrates = {'%i%%' % percent : itemtax} if config_value('TAX','TAX_SHIPPING'): shipping = order.shipping_sub_total sub_total += shipping ship_tax = shipping * (percent/100) ...
kvark/claymore
etc/blender/io_kri/__init__.py
Python
apache-2.0
186
0
bl_info = { 'name': 'KRI common routines', 'author': 'Dzmitry Malysh
au', 'version': (0, 1,
0), 'blender': (2, 6, 2), 'warning': '', 'category': 'Import-Export' }
studio1247/gertrude
paques.py
Python
gpl-3.0
1,082
0.012015
# -*- coding: utf-8 -*- ## This file is part of Gertrude. ## ## Gertrude 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, o
r ## (at your option) any later version. ## ## Gertrude is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should...
License ## along with Gertrude; if not, see <http://www.gnu.org/licenses/>. import datetime def getPaquesDate(year): if year < 1583: m, n = 16, 6 else: m, n = 24, 5 a, b, c = year % 19, year % 4, year % 7 d = (19 * a + m) % 30 e = (2 * b + 4 * c + 6 * d + n) % 7 if d + e < 1...
gabrielloliveira/omc
omc/omc/urls.py
Python
mit
366
0.002732
from django.conf.urls import url, include from django.conf import settings from django.contrib import admin from django.conf.urls.static import static urlpatterns
= [ url(r'^admin/', admin.site.urls), url(r'', include('blog.urls')),
url(r'^ckeditor/', include('ckeditor_uploader.urls')), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
ericrrichards/rpgEngine
RpgEngine/RpgEngine/Scripts/Actions.py
Python
mit
242
0
class Actions: @staticmethod def Teleport(m
ap, tileX, tileY): def teleport(trigger, entity): entity.Til
eX = tileX entity.TileY = tileY TeleportEntity(entity, map) return teleport
mridang/django-eggnog
eggnog/migrations/0001_initial.py
Python
bsd-3-clause
1,561
0.007687
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'U
pdate' db.create_table('eggnog_update', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('package', self.gf('django.db.models.fields.CharField')(unique=True, max_length=2000)), ('installed', self.gf('django.db.models.fields.CharField')(max_length=16)...
d=True, blank=True)), )) db.send_create_signal('eggnog', ['Update']) def backwards(self, orm): # Deleting model 'Update' db.delete_table('eggnog_update') models = { 'eggnog.update': { 'Meta': {'ordering': "['-checked']", 'object_name': 'Update'}, ...
semiautomaticgit/SemiAutomaticClassificationPlugin
core/utils.py
Python
gpl-3.0
380,258
0.03463
# -*- coding: utf-8 -*- ''' /************************************************************************************************************************** SemiAutomaticClassificationPlugin The Semi-Automatic Classification Plugin for QGIS allows for the supervised classification of remote sensing images, providing to...
shed.connect(eL.quit) eL.exec_() cfg.replyR3.finished.disconnect(eL.quit) cfg.replyR3.finished.disconnect() cfg.replyR3.abort()
cfg.replyR3.close() try: if outputPath is None: cfg.replyP = qnamI.get(r) cfg.replyP.finished.connect(self.replyText) # loop eL = cfg.QtCoreSCP.QEventLoop() cfg.replyP.finished.connect(eL.quit) eL.exec_() cfg.replyP.finished.disconnect(eL.quit) cfg.replyP.finished.disconnect() ...
urashima9616/Leetcode_Python
Leet132_PalindromePartition3.py
Python
gpl-3.0
1,337
0.006731
""" Given a string s, partition s such that every substring of the partition is a palindrome. Return the minimum cuts needed for a palindrome partitioning of s. For example, given s = "aab", Return 1 since the palindrome partitioning ["aa","b"] could be produced using 1 cut. DFSearch solution """ class Solution(obj...
if not s: return [[]] if len(s) == 1: return [[s]] res = [] for i in xrange(len(s)): # check palindrom if s[:len(s)-i] == s[len(s)-i-1::-1]:
if i > 0: for each in self.PalindromePart(s[len(s)-i:], k+1, mincut): res.append([s[:len(s)-i]] + each) mincut[0] = k + len(each) if mincut[0] > k + len(each) - 1 else mincut[0] else: each = [] ...
rolando/crochet
crochet/_util.py
Python
mit
366
0
""" Utility functions
and classes. """ from functools import wraps def synchronized(method): """ Decorator that wraps a method with an acquire/release of self._lock. """ @wraps(method) def synced(s
elf, *args, **kwargs): with self._lock: return method(self, *args, **kwargs) synced.synchronized = True return synced
davisp/python-spidermonkey
tests/test-python-ctor.py
Python
mit
736
0.006793
# Copyright 2009 Paul J. Davis <[email protected]> # # This file is part of the python-spidermonkey package released # under the MIT license. import t touched = 0 class Foo(object): def __init__(self): self.bar = 2 def __del__(self): global touched touched = 1 @t.glbl("Foo", ...
_type(cx, glbl): t.eq(isinstance(cx.execute("var f = new Foo(); f;"), Foo), True) @t.glbl("Foo", Foo) def test_py_ctor_attribute_acc(cx, glbl): t.eq(cx.execute("var f = new Foo(); f;").bar, 2) @t.glbl("Foo", Foo) def test_py_
dtor_called(cx, glbl): t.eq(cx.execute('var f = {"baz": new Foo()}; f;').baz.bar, 2) cx.execute("delete f.baz;") cx.gc() t.eq(touched, 1)
jpoullet2000/cgs-benchmarks
highlander-benchmarks/vcf_import.py
Python
apache-2.0
7,545
0.009145
#!/usr/bin/python # -*- coding: utf-8 -*- import os import urllib import zlib import zipfile import math import sys from subprocess import * import subprocess # This script will: # 1. Download the public database from the broad institute # 2. Generate random vcf files thanks to the previous file thanks...
Done(starting_sample + first_sample) and checkIfSampleDone(starting_sample + first_sample + max_vcf_step - 1): print("Samples ["+str(starting_sample+first_sample)+"; "+str(starting_sample+first_sample+max_vcf_step - 1)+"] already done, we go to the next interval.") continue ...
_step)+" out of "+str(analyse[1])+" vcf.") args = [''+vcf_generation_jar_path+'', "--o", public_database_path, "--d", vcf_destination_path+"r_"+analyse[0], "--s", str(max_vcf_step), "--f", "false", "--t", str(threads_max), "--i", str(starting_sample + first_sample)] try: #jarWrapper(*args...
cjcjameson/gpdb
gpMgmt/bin/gpcheckcat_modules/mirror_matching_check.py
Python
apache-2.0
1,789
0.003354
from gppylib.gparray import FAULT_STRATEGY_FILE_REPLICATION, get_gparray_from_config class MirrorMa
tchingCheck: def run_check(self, db_connection, logger): logger.info('-----------------------------------
') logger.info('Checking mirroring_matching') is_config_mirror_enabled = get_gparray_from_config().getFaultStrategy() == FAULT_STRATEGY_FILE_REPLICATION # This query returns the mirroring status of all segments mirroring_query = """SELECT gp_segment_id, mirror_existence_state FROM gp_d...
zixiliuyue/pika
pika/connection.py
Python
bsd-3-clause
82,517
0.000594
"""Core connection objects""" import ast import sys import collections import copy import logging import math import numbers import platform import warnings if sys.version_info > (3,): import urllib.parse as urlparse # pylint: disable=E0611,F0401 else: import urlparse from pika import __version__ from pika i...
def channel_max(self): """ :returns: max preferred number of channels. Defaults to `DEFAULT_CHANNEL_MAX`. :rtype: int """ return self._channel_max @channel_max.setter def channel_max(self, value): """ :param int value: max preferred numbe...
nstance(value, numbers.Integral): raise TypeError('channel_max must be an int, but got %r' % (value,)) if value < 1 or value > pika.channel.MAX_CHANNELS: raise ValueError('channel_max must be <= %i and > 0, but got %r' % (pika.channel.MAX_C
talnoah/android_kernel_htc_dlx
virt/tools/perf/scripts/python/syscall-counts-by-pid.py
Python
gpl-2.0
1,927
0.033212
# system call counts, by pid # (c) 2010, Tom Zanussi <[email protected]> # Licensed under the terms of the GNU GPL License version 2 # # Displays system-wide system call totals, broken down by syscall. # If a [comm] arg is specified, only syscalls called by [comm] are displayed. import os, sys sys.path.append(os.env...
syscalls", "count"), print "%-40s %10s\n" % ("----------------------------------------", \ "----------"), comm_keys = syscalls.keys() for comm in comm_keys: pid_keys = syscalls[comm].keys() for pid in pid_keys: print "\n%s [%d]\n" % (comm, pid), id_ke...
yscall_name(id), val),
henzk/django-productline
django_productline/startup.py
Python
mit
2,282
0.001753
from __future__ import unicode_literals """ product initialization stuff """ import os import featuremonkey from .composer import get_composer from django_productline import compare_v
ersion _product_selected = False def select_product(): """ binds the frozen context the
selected features should be called only once - calls after the first call have no effect """ global _product_selected if _product_selected: # tss already bound ... ignore return _product_selected = True from django_productline import context, template featuremonkey.add...
logston/ipy.io
docker/jupyter_notebook_config.py
Python
bsd-3-clause
77
0.012987
c = get_config() c.NotebookApp.ip = '*' c.Noteb
ookApp.open_browser = Fal
se
mganeva/mantid
Framework/PythonInterface/test/python/plugins/algorithms/CreateWorkspaceTest.py
Python
gpl-3.0
4,168
0.013196
# Mantid Repository : https://github.com/mantidproject/mantid # # Copyright &copy; 2018 ISIS Rutherford Appleton Laboratory UKRI, # NScD Oak Ridge National Laboratory, European Spallation Source # & Institut Laue - Langevin # SPDX - License - Identifier: GPL - 3.0 + from __future__ import (absolute_import, divi...
class CreateWorkspaceTest(unittest.TestCase): def test_create_with_1D_numpy_array(self): x = np.array([1.,2.,3.,4.]) y = np.a
rray([1.,2.,3.]) e = np.sqrt(np.array([1.,2.,3.])) wksp = CreateWorkspace(DataX=x, DataY=y,DataE=e,NSpec=1,UnitX='TOF') self.assertTrue(isinstance(wksp, MatrixWorkspace)) self.assertEquals(wksp.getNumberHistograms(), 1) self.assertEquals(len(wksp.readY(0)), len(y)) self...
petervaro/tup
src/tup.py
Python
gpl-3.0
23,015
0.004519
## INFO ## ## INFO ## # TODO: %o is not available in output, nor input strings, only in command # TODO: !-macro and ^-flags should only be available # at the beginning of a command #-- CHEATSHEET ----------------------------------------------------------------# # HOWTO: http://sublimetext.info/docs/en/referenc...
[
{ 'name' : 'invalid.illegal.group_after_group.{SCOPE}', 'match': r'<.+?>.*' }, { ...
exaile/exaile
plugins/minimode/__init__.py
Python
gpl-2.0
9,528
0.00063
# Copyright (C) 2009-2010 Mathias Brodala # # 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, or (at your option) # any later version. # # This program is distributed in the hope...
c., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. from gi.repository import Gtk from xl import event, providers, settings from xl.nls import gettext as _ from xlgui.accelerators import Accele
rator from xlgui.widgets import menu from . import controls from . import minimode_preferences MINIMODE = None def __migrate_fixed_controls(): """ Makes sure fixed controls are selected, mostly for migration from older versions """ option_name = 'plugin/minimode/selected_controls' if settin...
dablak/saved_searches
setup.py
Python
bsd-3-clause
792
0
#!/usr/bin/env python # -*- coding: utf-8 -*- from distutils.core import setup setup( name='saved_searches', version='2.0.0-alpha', description='Saves user searches for integration with Haystack.', author='Daniel Lindsley', author_email='[email protected]', url='http://github.com/toastdriv...
ags', ], classifiers=
[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', '...
matematik7/STM
tests/test_filename.py
Python
mit
4,121
0.005156
#!/usr/bin/env python2 # -*- coding: utf-8 -*- # ---------------------------------------------------------------- # tests/test_filename.py # # Test thumbnail file name generation. # ---------------------------------------------------------------- # copyright (c) 2015 - Domen Ipavec # Distributed under The MIT License,...
") self.checkImage("input.jpg", "thumbs/input.png") self.checkImage("13 De_(com)čšž.test.jpg", "thumbs/13 De_(com)čšž.test.png") self.checkImage("/tmp/input.jpg", "/tmp/thumbs/input.png") def test_folder(self): self.conf.folder = "test-folder" self.checkImage("input.png", "t...
eckImage("input.jpg", "test-folder/input.png") self.checkImage("13 De_(com)čšž.test.jpg", "test-folder/13 De_(com)čšž.test.png") self.checkImage("/tmp/input.jpg", "/tmp/test-folder/input.png") def test_abs_folder(self): self.conf.folder = "/tmp" self.checkImage("input.png", "/tmp/in...
accraze/python-twelve-tone
tests/test_twelve_tone.py
Python
bsd-2-clause
186
0
from click.testing
import CliRunner from twelve_tone.cli import main def test_main(): runner = CliRunner() result =
runner.invoke(main, []) assert result.exit_code == 0
icyflame/batman
pywikibot/__init__.py
Python
mit
26,823
0.000336
# -*- coding: utf-8 -*- """The initialization file for the Pywikibot framework.""" # # (C) Pywikibot team, 2008-2015 # # Distributed under the terms of the MIT license. # from __future__ import absolute_import, unicode_literals __release__ = '2.0b3' __version__ = '$Id$' __url__ = 'https://www.mediawiki.org/wiki/Speci...
og', 'calledModuleName', 'Bot', 'CurrentPageBot', 'WikidataBot',
'Error', 'InvalidTitle', 'BadTitle', 'NoPage', 'NoMoveTarget', 'SectionError', 'SiteDefinitionError', 'NoSuchSite', 'UnknownSite', 'UnknownFamily', 'UnknownExtension', 'NoUsername', 'UserBlocked', 'UserActionRefuse', 'PageRelatedError', 'IsRedirectPage', 'IsNotRedirectPage', 'PageSaveRelatedE...
lgarren/spack
var/spack/repos/builtin/packages/r-affyio/package.py
Python
lgpl-2.1
1,756
0.001139
############################################################################## # 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, [email protected], All rights reserved. # LLNL-CODE-64...
ree Software Foundation) version 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 mor...
ite to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ############################################################################## from spack import * class RAffyio(RPackage): """Routines for parsing Affymetrix data files based upon file format information. Pr...
riverbird/djangoweblog
tinymce/widgets.py
Python
gpl-2.0
6,397
0.00297
# Copyright (c) 2008 Joost Cassee # Licensed under the terms of the MIT License (see LICENSE.txt) """ This TinyMCE widget was copied and extended from this code by John D'Agostino: http://code.djangoproject.com/wiki/CustomWidgetsTinyMCE """ from __future__ import unicode_literals #import tinymce.settings import demo....
spellchecker_languages' parameters by default. The first is
derived from the current Django language, the others from the 'content_language' parameter. """ def __init__(self, content_language=None, attrs=None, mce_attrs=None): super(TinyMCE, self).__init__(attrs) if mce_attrs is None: mce_attrs = {} self.mce_attrs = mce_attrs...
JoeGlancy/micropython
examples/reverb.py
Python
mit
1,345
0.006691
import audio def from_file(file, frame): ln = -1 while ln: ln = file.readinto(frame) yield frame def reverb_gen(src, buckets, reflect, fadeout): bucket_count = len(buckets) bucket = 0 for frame in src: echo = buckets[bucket] echo *= reflect echo += frame ...
+= 1 if bucket == bucket_count: bucket = 0 def reverb(src, delay, reflect): #Do all allocation up front, so we don't need to do any in the generator. bucket_count = delay>>2 buckets = [ None ] * bucket_count for i in range(bucket_count): buckets[i] = audio.AudioFrame() v...
1.0 fadeout = 0 while vol > 0.05: fadeout += bucket_count vol *= reflect return reverb_gen(src, buckets, reflect, fadeout) def play_file(name, delay=80, reflect=0.5): #Do allocation here, as we can't do it in an interrupt. frame = audio.AudioFrame() with open(name) as file: ...
ptMuta/python-node
pynode/runners/BabelRunner.py
Python
mit
2,294
0.003487
from Naked.toolshed.shell import muterun from pynode.exceptions import NodeExecutionFailedException from pynode.runners.Runner import Runner class BabelRunner(Runner): def __init__(self, ignore=None, extensions=None, presets=None, plugins=None): babel_arguments = '' if ignore is not None: ...
) if result.exitcode == 0: return result.stdout.decode('utf-8').strip() else: raise NodeExecutionFailedException(result.stderr) def execute_script_silent(self, script_path, *args): result = self.execute_babel
_node(script_path, self.args_to_string(args)) if result.exitcode == 0: return True else: raise NodeExecutionFailedException(result.stderr)
hzdg/django-google-search
googlesearch/__init__.py
Python
mit
662
0
from django.conf import settings """ Your GSE API key """ GOOGLE_SEARCH_API_KEY = getattr(settings, 'GOOGLE_SEARCH_API_KEY', None) """ The ID of the Google Custom Search
Engine """ GOOGLE_SEARCH_ENGINE_ID = getattr(settings, 'GOOGLE_SEARCH_ENGINE_ID', None) """ The API version. Defaults to 'v1' """ GOOGLE_SEARCH_API_VERSION = getattr( settings, 'GOOGLE_SEARCH_API_VERSION', 'v1') """ The number of search results to show per page """ GOOGLE_SEARCH_RESULTS_PER_PAGE = getattr( s...
E_SEARCH_MAX_PAGES = getattr(settings, 'GOOGLE_SEARCH_MAX_PAGES', 10)
h2so5/Twemoji4Android
nototools/opentype_data.py
Python
mit
2,449
0.000817
#!/usr/bin/python # # Copyright 2014 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...
RRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """OpenType-related data.""" __author__ = '[email protected] (Roozbeh Pournader)' import unicode_data OMPL = {} def _set_ompl(): """Set up OMPL....
in Unicode 5.1: http://www.microsoft.com/typography/otspec/ttochap1.htm#ltrrtl """ global OMPL unicode_data.load_data() bmg_data = unicode_data._bidi_mirroring_glyph_data OMPL = {char:bmg for (char, bmg) in bmg_data.items() if float(unicode_data.age(char)) <= 5.1} ZWSP = [0x200B]...
zeroc0d3/docker-lab
vim/rootfs/usr/lib/python2.7/dist-packages/powerline/segments/vim/__init__.py
Python
mit
24,099
0.024775
# vim:fileencoding=utf-8:noet from __future__ import (unicode_literals, division, absolute_import, print_function) import os import re import csv import sys from collections import defaultdict try: import vim except ImportError: vim = object() from powerline.bindings.vim import (vim_get_func, getbufvar, vim_getbu...
'S': 'S-LINE', '^S': 'S-BLCK', 'i': 'INSERT', 'ic': 'I-COMP', 'ix': 'I-C_X ', 'R': 'RPLACE', 'Rv': 'V-RPLC', 'Rc': 'R-COMP', 'Rx': 'R-C_X ', 'c': 'COMMND', 'cv': 'VIM-EX', 'ce': 'NRM-EX',
'r': 'PROMPT', 'rm': '-MORE-', 'r?': 'CNFIRM', '!': '!SHELL', } # TODO Remove cache when needed def window_cached(func): cache = {} @requires_segment_info @wraps(func) def ret(segment_info, **kwargs): window_id = segment_info['window_id'] if segment_info['mode'] == 'nc': return cache.get(window_id) ...
HuygensING/bioport-repository
bioport_repository/tests/test_common.py
Python
gpl-3.0
2,361
0.008895
########################################################################## # Copyright (C) 2009 - 2014 Huygens ING & Gerbrandy S.R.L. # # This file is part of bioport. # # bioport 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 ...
assertEqual(to_date('1200', ), datetime.datetime(1200, 1, 1, 0, 0)) def test_format_date(self): d
= datetime.datetime(1700, 3, 2) self.assertEqual(format_date(d), '1700-03-02 00:00') d = datetime.datetime(1, 3, 2) self.assertEqual(format_date(d), '0001-03-02 00:00') def test_suite(): return unittest.TestSuite(( unittest.makeSuite(CommonTestCase, 'test'), )) if ...
mattclark/osf.io
tests/test_registrations/test_registration_approvals.py
Python
apache-2.0
12,424
0.003139
import datetime import mock from django.utils import timezone from nose.tools import * # noqa from tests.base import fake, OsfTestCase from osf_tests.factories import ( EmbargoFactory, NodeFactory, ProjectFactory, RegistrationFactory, UserFactory, UnconfirmedUserFactory ) from framework.exceptions import Per...
um_of_approvals = sum([val['has_approved'] for val in self.registration.registration_approval.approval_state.valu
es()]) assert_equal(num_of_approvals, 2) def test_invalid_rejection_token_raises_InvalidSanctionRejectionToken(self): self.registration.require_approval( self.user ) self.registration.save() assert_true(self.registration.is_pending_registration) with asse...
botswana-harvard/edc-lab
old/lab_clinic_api/classes/edc_lab_results.py
Python
gpl-2.0
4,109
0.003651
from django.shortcuts import render_to_response from django.template.loader import render_to_string from lis.specimen.lab_result_item.classes import ResultItemFlag from lis.exim.lab_import_lis.classes import LisDataImporter from lis.exim.lab_import_dmis.classes import Dmis from ..models import Result, Order, ResultIt...
t_item) result_item.save() ordered = Order.objects.filter( aliquot__receive__registered_subject__subject_identifier=subject_identifier).exclude( order_identifier__in=[result.order.order_identifier for result in resulted]).order_by( '-aliquo...
': last_updated}) def results_template(self, subject_identifier, update=False): """This method is a refactor of the above render method except that it renders to response""" template = "result_status_bar.html" return render_to_response(template, self.context_data(subject_identifier, update)...
zhhf/charging
charging/tests/unit/test_db_plugin.py
Python
apache-2.0
180,785
0.000111
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (c)
2012 OpenStack Foundation. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by ap...
buted 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. import contextlib import copy import os import mock from oslo.config im...
jethrogb/episoder
test/episode.py
Python
gpl-3.0
2,607
0.018028
# episoder, https://code.ott.net/episoder # -*- coding: utf8 -*- # # Copyright (C) 2004-2020 Stefan Ott. All rights reserved. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 o...
"0XOR") def test_str_and_repr(self): show = Show(u"TvShow", u"") ep = Episode(u"First", 1, 1, date(2017, 1, 1), u"http://", 1) ep.show = show self.assertEqual(str(ep), "TvShow 1x01: First") self.assertEqual(repr(ep), 'Episode(u"First", 1, 1, ' 'date(2017, 1, 1), u"http://", 1)') def test_equality(s...
e(2017, 1, 1), u"http://", 1) ep2.show_id = 2 self.assertNotEqual(ep1, ep2) ep1.show_id = 2 self.assertNotEqual(ep1, ep2) ep1.season = 2 self.assertNotEqual(ep1, ep2) ep1.episode = 2 self.assertEqual(ep1, ep2) ep1.season = 1 self.assertNotEqual(ep1, ep2) ep1.season = 2 ep1.show_id = 1 se...
riusksk/riufuzz
tools/coverage/Utilities/Download.py
Python
apache-2.0
8,118
0.011333
import requests import time import string import os.path import urllib2 import sys import getopt from time import gmtime, strftime #variables class Downloader: extension = "pdf" signature = [0x25, 0x50, 0x44, 0x46] searchChars = ['a', 'a'] outputDir = "downloaded_" downloaded = [] successCou...
try: if os.path.isfile("%s/file%08d.%s" % (fDir, self.successCount, self.extension)): os.remove("%s/file%08d.%s" % (fDir, self.
successCount, self.extension)) break except: if x==9: raise time.sleep(1) return self.successCount += 1 def signatureText(self): result = "" for x in range(len(self.signa...
4dsolutions/Python5
qrays.py
Python
mit
11,110
0.016022
# -*- coding: utf-8 -*- """ Created on Sat Jun 4 09:07:22 2016 Vectors and Qvectors use the same metric i.e. the xyz vector and corresponding ivm vector always have the same length. In contrast, the tetravolume.py modules in some cases assumes that volume and area use R-edge cubes and triangles for XYZ units resp...
y def b(self): return self.coords.b @property def c(self): return self.coords.c
@property def d(self): return self.coords.d def __eq__(self, other): return self.coords == other.coords def __lt__(self, other): return self.coords < other.coords def __gt__(self, other): return self.coords > other.coords def __hash__(self): ...
tassmjau/duktape
tests/perf/test-hex-encode.py
Python
mit
341
0.043988
import math import random def test(): tmp1 = [] tmp2 = [] print('build') for i in xrange(1024): tmp1.append(chr(int(math.floor(random.random() * 256)))) tmp1 = ''.joi
n(tmp1) for i in xrange(1024): tmp2.append(tmp1) tmp2 = ''.join(tmp2) print(len(tmp2)) print('run') for i in xrange(5000): res = tmp2.encode('hex') test()
KirovVerst/qproject
deploy_config_example.py
Python
mit
276
0
DO_TOKEN = ''
SSH_KEY_PUB_PATH = '/home/user/.ssh/id_rsa.pub' # deploy all containe
rs to one droplet ONE_DROPLET_NAME = 'qproject-all' ONE_DROPLET_IMAGE = 'docker-16-04' ONE_DROPLET_SIZE = '512mb' # deploy all containers to multiple virtual machines SWARM_WORKER_NUMBER = 1
bucketzxm/wechat_template
movie/views.py
Python
gpl-3.0
2,018
0.000991
# -*- coding: utf-8 -*- from __future__ import print_function from django.shortcuts import render, HttpResponse from django.views.decorators.csrf import csrf_exempt import hashlib import xml.etree.ElementTree as ET import time from config import TOKEN # Create your views here. TOKEN = TOKEN @csrf_exempt def index(r...
<![CDATA[%s]]></FromUserName> <CreateTime>%s</CreateTime> <MsgType><![CDATA[%s]]></MsgType> <Content><![CDATA[%s]
]></Content> </xml> ''' res = template % (msg['FromUserName'], msg['ToUserName'], str(int(time.time())), 'text', reply_content) return res def parse_xml(root_elm): """ :param root_elm: :return: msg dict """ msg = {} if root_elm.tag == 'xml': for child in root_elm:...
koba-z33/nand2tetris
projects/python/assembler/n2tassembler/commandline.py
Python
gpl-3.0
3,587
0
from .commandtype import CommandType from .commandlineerror import CommandLineError class CommandLine(): """アセンブラコマンドラインオブジェクト """ def __init__(self, line_no: int, raw_data: str): """コンストラクタ Parameters ---------- line_no : int 行番号 raw_data : str ...
dest = 'null' else: dest = self.data[0:pos_e] if pos_s == -1: comp = self.data[pos
_e + 1:] else: comp = self.data[pos_e + 1:pos_s] if pos_s == -1: jump = 'null' else: jump = self.data[pos_s + 1:] return (dest, comp, jump) def __str__(self): return 'LineNo {} : {}'.format(self.line_no, self.__raw_data)
w1ll1am23/home-assistant
homeassistant/components/intent/__init__.py
Python
apache-2.0
2,573
0.001555
"""The Intent integration.""" import voluptuous as vol from homeassist
ant.components import http from homeassistant.components.http.data_validator import RequestDataValidator from homeassistant.const import SERVICE_TOGGLE, SERVICE_TURN_OFF, SERVICE_TURN_ON from homeassistant.core import DOMAIN as HA_DOMAIN, HomeAssistant from homeassistant.helpers import config_validation as cv, integrat...
_platform, intent from .const import DOMAIN async def async_setup(hass: HomeAssistant, config: dict): """Set up the Intent component.""" hass.http.register_view(IntentHandleView()) await integration_platform.async_process_integration_platforms( hass, DOMAIN, _async_process_intent ) hass...
pedro2d10/SickRage-FR
sickbeard/providers/bluetigers.py
Python
gpl-3.0
5,574
0.003409
# coding=utf-8 # Author: raver2046 <[email protected]> # # URL: https://sickrage.github.io # # This file is part of SickRage. # # SickRage 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 ...
each search mode sort all the items by seeders if available items.sort(key=lambda tup: tup[3], reverse=
True) results += items return results def seed_ratio(self): return self.ratio provider = BlueTigersProvider()
xujun10110/DIE
DIE/Lib/ParsedValue.py
Python
mit
1,350
0.002222
MAX_SCORE = 10 class ParsedValue(): """ Possible run-time value. The value data might either be definite or guessed. """ def __init__(self, data, description, score=0, raw=None, type_=None): """ Ctor @param data: The data`s human-readable representation. @param d...
E def is_guessed(self): """ Check if the value is guessed @return: True if the value is guessed, other
wise False """ return not self.score == 0
mgodek/music_recommendation_system
matrixFactor.py
Python
gpl-3.0
3,252
0.009533
############################################################################### import numpy import time ############################################################################### def matrixFactorization(R, P, Q, K, epochMax=1000, alpha=0.0002, beta=0.02): Q = Q.T for step in xrange(epochMax): f...
0 for i in xrange(len(R)): for j in xrange(len(R[i])): if R[i][j] > 0: e = e + pow(R[i][j] - numpy.dot(P[i,:],Q[:,j]), 2) for k in xrange(K): e = e + (beta/2) * ( pow(P[i][k],2) + pow(Q[k][j],2) ) if e < 0.001: ...
############################### def createUserRow(utp): userRow = numpy.zeros(shape=(1, utp.nextSongIndex), dtype=float) for songId in utp.user_feed_artists_tracks + utp.user_feed_tracks: if songId in utp.echoSongIdToIdxMap: userRow[0][utp.echoSongIdToIdxMap[songId]] = 20 # hardcoded estim...
kashif/scikit-learn
sklearn/metrics/tests/test_pairwise.py
Python
bsd-3-clause
25,509
0
import numpy as np from numpy import linalg from scipy.sparse import dok_matrix, csr_matrix, issparse from scipy.spatial.distance import cosine, cityblock, minkowski, wminkowski from sklearn.utils.testing import assert_greater from sklearn.utils.testing import assert_array_almost_equal from sklearn.utils.testing impo...
assert_array_almost_equal(S, S2) # The manhattan metric should be equivalent to cityblock. S = pairwise_distances(X, Y, metric="manhattan") S2 = pairwise_distances(X, Y, metric=cityblock) assert_equal(S.shape[0], X.shape[0]) assert_equal(S.shape[1], Y.shape[0]) assert_array_almost_equal(S, S2...
h memory during the broadcasting S3 = manhattan_distances(X, Y, size_threshold=10) assert_array_almost_equal(S, S3) # Test cosine as a string metric versus cosine callable # "cosine" uses sklearn metric, cosine (function) is scipy.spatial S = pairwise_distances(X, Y, metric="cosine") S2 = pairwi...
inovtec-solutions/OpenERP
openerp/addons/lunch/report/report_lunch_order.py
Python
agpl-3.0
2,799
0.009289
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
rder(osv.osv): _name = "report.lunch.order.line" _description = "Lunch Ord
ers Statistics" _auto = False _rec_name = 'date' _columns = { 'date': fields.date('Date Order', readonly=True, select=True), 'year': fields.char('Year', size=4, readonly=True), 'month':fields.selection([('01','January'), ('02','February'), ('03','March'), ('04','April'), ...
Juanlu001/xlwings
xlwings/utils.py
Python
apache-2.0
2,171
0.000921
from __future__ import division import
datetime as dt missing = object() try: import numpy as np except ImportError: np = None def int_to_rgb(number): """Given an integer, return the rgb""" number = int(number) r = numbe
r % 256 g = (number // 256) % 256 b = (number // (256 * 256)) % 256 return r, g, b def rgb_to_int(rgb): """Given an rgb, return an int""" return rgb[0] + (rgb[1] * 256) + (rgb[2] * 256 * 256) def get_duplicates(seq): seen = set() duplicates = set(x for x in seq if x in seen or seen.add(x...
liveblog/liveblog
server/liveblog/blogs/blog.py
Python
agpl-3.0
4,946
0.002022
import pymongo from bson.objectid import ObjectId from eve.utils import date_to_str from html5lib.html5parser import ParseError from lxml.html.html5parser import fragments_fromstring, HTMLParser from superdesk.utc import utcnow from superdesk import get_resource_service from liveblog.posts.mixins import AuthorsMixin...
filters.append({'sticky': True}) else: filters.append({'sticky': False}) if highlight: filters.append({'lb_highlight': True}) if len(tags) > 0: filters.append({'tags': {'$in': tags}}) return {'$and': filters} def get_ordering(self,...
by, sort = self.ordering[label] return order_by, sort except KeyError: return self.default_order_by, self.default_sort def check_html_markup(self, original_text): div_wrapped = '<div>{}</div>'.format(original_text) if not is_valid_html(original_text) and is_valid_htm...
waterblue13/tensor2tensor
tensor2tensor/models/cycle_gan.py
Python
apache-2.0
4,931
0.005678
# coding=utf-8 # Copyright 2017 The Tensor2Tensor Authors. # # 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...
ram
s.vocab_size, hparams.hidden_size, "embed", reuse=True) # Split the batch into input-input and target-target parts. inputs1, _ = split_on_batch(inputs) _, targets2 = split_on_batch(targets) # Define F and G, called inp2tgt and tgt2inp here. def inp2tgt(x, reuse=False): return transfo...
bruno1951/bruno1951-cmis-cs2
play.py
Python
cc0-1.0
414
0.007246
x = raw_in
put(" Take your wand out:") y = raw_input(" You're a wizard youngone: ") z = raw_input(" Please come with me and become a wizard: ") p = raw_input(" No, I a
m not a liar: " ) print str(x) + " and repeat " + str(y) + "I have never seen such potential in such a young boy" + str(z) + "Young one, you will be taken care of very well, theres nothing to be afraid of, I promise" + str(p) + "Come, it is time"
AntonGagin/GSAS_USE
patchSystErrors/modifiedOld/GSASIIstrMain.py
Python
gpl-3.0
85,029
0.01797
# -*- coding: utf-8 -*- ''' *GSASIIstrMain: main structure routine* --------------------------------------- ''' ########### SVN repository information ################### # $Date: 2018-07-13 22:44:01 +0300 (Fri, 13 Jul 2018) $ # $Author: toby $ # $Revision: 3471 $ # $URL: https://subversion.xray.aps.anl.gov/...
$ # $Id: GSASIIstrMain.py 3471 2018-07-13 19:44:01Z toby $ ########### SVN repository information ################### from __future__ import division, print_function import platform import sys import os.path as ospath import time import math import copy if '2' in platform.python_version_tuple()[0]: impor...
th.SetVersionNumber("$Revision: 3471 $") import GSASIIlattice as G2lat import GSASIIspc as G2spc import GSASIImapvars as G2mv import GSASIImath as G2mth import GSASIIstrIO as G2stIO import GSASIIstrMath as G2stMth import GSASIIobj as G2obj sind = lambda x: np.sin(x*np.pi/180.) cosd = lambda x: np.cos(x*np.pi...
wanderer2/pymc3
pymc3/glm/__init__.py
Python
apache-2.0
89
0
from . import familie
s from .glm import glm, linear_co
mponent, plot_posterior_predictive
marrow/wsgi.objects
examples/wsgify.py
Python
mit
521
0.003839
#!/usr/bin/env p
ython # encoding: utf-8 from __future__ import unicode_literals from pprint import pformat from marrow.server.http import HTTPServer from marrow.wsgi.objects.decorator import wsgify @wsgify def hello(request): resp = request.response resp.mime = "text/plain" resp.body = "%r\n\n%s\n\n%s" % (request, req...
HTTPServer(None, 8080, application=hello).start()
grafeas/client-python
grafeas/models/api_project_repo_id.py
Python
apache-2.0
4,162
0.00024
# coding: utf-8 """ An API to insert and retrieve metadata on cloud artifacts. No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501 OpenAPI spec version: v1alpha1 Generated by: https://github.com/swagger-api/swagger-codegen.git """ ...
attribute_map = { 'project_id': 'project_id', 'repo_name': 'repo_name' } def __init__(self, project_id=None, repo_name=None): # noqa: E501 """ApiProjectRepoId - a model defined in Swagger""" # noqa: E501 self._project_id = None self._repo_name = None self....
me is not None: self.repo_name = repo_name @property def project_id(self): """Gets the project_id of this ApiProjectRepoId. # noqa: E501 The ID of the project. # noqa: E501 :return: The project_id of this ApiProjectRepoId. # noqa: E501 :rtype: str """ ...
SUSE/azure-sdk-for-python
azure-mgmt-compute/azure/mgmt/compute/compute/v2017_03_30/models/virtual_machine_agent_instance_view.py
Python
mit
1,705
0.001173
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
.compute.compute.v2017_03_30.models.VirtualMachineExtensionHandlerInstanceView>` :param statuses: The resource status information. :type statuses: list of :class:`InstanceViewStatus <azure.mgmt.compute.comp
ute.v2017_03_30.models.InstanceViewStatus>` """ _attribute_map = { 'vm_agent_version': {'key': 'vmAgentVersion', 'type': 'str'}, 'extension_handlers': {'key': 'extensionHandlers', 'type': '[VirtualMachineExtensionHandlerInstanceView]'}, 'statuses': {'key': 'statuses', 'type': '[Instance...
pet1330/strands_qsr_lib
qsr_lib/dbg/dbg_world_qsr_trace_slicing_methods.py
Python
mit
4,049
0.004199
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function, division from qsrlib.qsrlib import QSRlib, QSRlib_Request_Message, QSRlib_Response_Message from qsrlib_io.world_trace import Object_State, World_Trace def print_world_trace(world_trace): for t in world_trace.get_sorted_timestamps...
nse_message.req_received_at) + " and fini
shed at " + str(qsrlib_response_message.req_finished_at)) print("---") print("Response is:") for t in qsrlib_response_message.qsrs.get_sorted_timestamps(): foo = str(t) + ": " for k, v in zip(qsrlib_response_message.qsrs.trace[t].qsrs.keys(), qsrlib_response_message.q...
eclee25/flu-SDI-exploratory-age
scripts/OR_urbanmetro_v6-7-13.py
Python
mit
11,462
0.02661
#!/usr/bin/python ############################################## ###Python template ###Author: Elizabeth Lee ###Date: 6/9/13 ###Function: #### 1) create scatter of OR by zipcode vs. urban metro RUCC avg 2013 ###Import data: zipcode_bysseas_cl.csv ###Command Line: python ############################################...
axjs10) plt.scatter(xaxjs1, ys1, marker='o', color = 'grey', label= "Season 1") plt.scatter(xaxjs2, ys2, marker='o', color = 'black', label= "Season 2") plt.scatter(xa
xjs3, ys3, marker='o', color = 'red', label= "Season 3") plt.scatter(xaxjs4, ys4, marker='o', color = 'orange', label= "Season 4") plt.scatter(xaxjs5, ys5, marker='o', color = 'gold', label= "Season 5") plt.scatter(xaxjs6,
guykisel/inline-plz
inlineplz/linters/coala.py
Python
isc
1,918
0.000521
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals import os import shutil import sys import dirtyjson as json from ..decorators import linter from ..parsers.base import ParserBase @linter( name="coala", install=[ ["pipx", "install", "--spec", "coala-bears", "coala"], ...
msgbody = msgdata["message"] for line in msgdata.get("affected_code", []): path = line.get("file") line = line.get("start", {}).get("line") messages.add((path, line, msgbody)) except (ValueError, KeyError): ...
ges