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
google/differentiable-atomistic-potentials
dap/tf/visualize.py
Python
apache-2.0
4,530
0.001987
# Copyright 2018 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,...
or_shape.dim]) dot.node(n.name, label=f'{n.name} {shape}', shape=shapes.get(n.op, None)) for i in n.inpu
t: dot.edge(i, n.name) m = hashlib.md5() m.update(str(dot).encode('utf-8')) if fname is None: fname = 'tf-graph-' + m.hexdigest() if format is None: base, ext = os.path.splitext(fname) fname = base format = ext[1:] or 'png' dot.format = format dot....
jjconti/ayrton
ayrton/ast_pprinter.py
Python
gpl-3.0
18,702
0.020426
from ast import Module, ImportFrom, Expr, Call, Name, FunctionDef, Assign, Str from ast import dump, If, Compare, Eq, For, Attribute, Gt, Num, IsNot, BinOp from ast import NameConstant, Mult, Add, Import, List, Dict, Is, BoolOp, And from ast import Subscript, Index, Tuple, Lt, Sub, Global, Return, AugAssign from ast im...
t==ClassDef: # ClassDef(name='ToExpand', bases=[Name(id='object', ctx=Load())], # keywords=[], starargs=None, kwargs=None, body=[...] yield 'class ' yield node.name # TODO: more if len (node.bas
es)>0: yield ' (' for i in pprint_seq (node.bases): yield i yield ')' yield ':' for i in pprint_body (node.body, level+1): yield i elif t==Compare: # Compare(left=Name(id='t', ctx=Load()), ops=[Eq()], comparators=[Name(id='Module', ctx=Load())]) ...
JuezUN/INGInious
inginious/frontend/plugins/problem_bank/pages/api/filter_tasks_api.py
Python
agpl-3.0
2,183
0
import web from inginious.frontend.plugins.utils.admin_api import AdminApi from inginious.frontend.plugins.utils import get_mandatory_parameter class FilterTasksApi(AdminApi): def API_POST(self): parameters = web.input() task_query = get_mandatory_parameter(pa
rameters, "task_query") limit = int(get_mandatory_parameter(parameters, "limit")) page = int(get_mandatory_parameter(parameters, "page")) course_ids = set(bank["courseid"] for bank in self.database.problem_banks.find()) for course_id, course in self.course_fact...
.items(): if self.user_manager.has_admin_rights_on_course(course): course_ids.add(course_id) tasks = list(self.database.tasks_cache.aggregate([ { "$match": { "$text": { "$search": tas...
WilliamYi96/Machine-Learning
LeetCode/0154.py
Python
apache-2.0
701
0.002853
class Solution: def findMin(self, nums): mlength = len(nums) if mlength == 0: return -1 left = 0 right = mlength - 1 while left <= right: mid = (left + right) >> 1 if mid ==
mlength - 1: return nums[0] if nums[mid] > nums[mid+1]: return nums[mid+1] else: if nums[left] > nums[mid]: right = mid - 1 elif nums[lef
t] == nums[mid]: left += 1 elif nums[left] < nums[mid]: left = mid + 1 return nums[0] # There is some problems of this file
mganeva/mantid
scripts/Inelastic/Direct/dgreduce.py
Python
gpl-3.0
15,191
0.009413
# 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 + #pylint: disable=invalid-name """ Empty class...
r background tests second_white - If provided an addit
ional set of tests is performed on this. (default = None) hardmaskPlus - A file specifying those spectra that should be masked without testing (default=None) tiny - Minimum threshold for acceptance (default = 1e-10) large - Maximum threshold for acceptance (default = 1e10) bkg...
obi-two/Rebelion
data/scripts/templates/object/draft_schematic/community_crafting/component/shared_reinforced_wall_module.py
Python
mit
480
0.045833
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMP
LES from swgp
y.object import * def create(kernel): result = Intangible() result.template = "object/draft_schematic/community_crafting/component/shared_reinforced_wall_module.iff" result.attribute_template_id = -1 result.stfName("string_id_table","") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return ...
mjbradburn/masters_project
node_modules/neo4j-driver/neokit/neorun.py
Python
apache-2.0
6,800
0.004118
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Copyright (c) 2002-2016 "Neo Technology," # Network Engine for Objects in Lund AB [http://neotechnology.com] # # This file is part of Neo4j. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the Li...
topped (status = STOPPED) within 4 mins. # Return 0 if the test
success, otherwise 1 def test_neo4j_status(status = ServerStatus.STARTED): success = False start_time = time() timeout = 60 * 4 # in seconds count = 0 while not success: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) actual_status = s.connect_ex(("localhost", 7474)) if...
UdK-VPT/Open_eQuarter
mole3/stat_corr/window_wall_ratio_east_SDH_by_building_age_correlation.py
Python
gpl-2.0
520
0.040385
# OeQ autogenerate
d correlation for 'Window/Wall Ratio East in Correlation to the Building Age' import math import numpy as np from . import oeqCorrelation as oeq def get(*xin): # OeQ autogenerated correlation for 'Window to Wall Ratio in Eastern Direction' A_WIN_E_BY_AW= oeq.correlation( const= -6820.10365041, a= ...
_E_BY_AW.lookup(*xin))
xalt/xalt
contrib/upgradeDB_From0.7.1.py
Python
lgpl-2.1
5,640
0.009929
#!/usr/bin/env python # -*- python -*- # # Git Version: @git@ #----------------------------------------------------------------------- # XALT: A tool that tracks users jobs and environments on a cluster. # Copyright (C) 2013-2014 University of Texas at Austin # Copyright (C) 2013-2014 University of Tennessee # # This...
ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free # Software Foundatio...
----------------------------------------------------------------- from __future__ import print_function import os, sys, re, MySQLdb dirNm, execName = os.path.split(os.path.realpath(sys.argv[0])) sys.path.append(os.path.realpath(os.path.join(dirNm, "../libexec"))) from XALTdb import XALTdb from xalt_util import ...
radioprotector/flask-admin
examples/methodview/app.py
Python
bsd-3-clause
1,160
0
from flask import Flask, redirect, request import flask_admin as admin from flask.views import MethodView class ViewWithMethodViews(admin.BaseView): @admin.expose('/') def index(self): return self.render('methodtest.html') @admin.expose_plugview('/_api/1') class API_v1(MethodView): d...
urn redirect('/admin') if __name__ == '__main__': # Create admin
interface admin = admin.Admin(name="Example: MethodView") admin.add_view(ViewWithMethodViews()) admin.init_app(app) # Start app app.run(debug=True)
sajuptpm/neutron-ipam
neutron/plugins/ml2/driver_api.py
Python
apache-2.0
21,394
0
# Copyright (c) 2013 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 ...
ion context on session to release a tenant or provider network's type-specific resource. Runtime errors are not expected, but raising an exception will result in rollback of the transaction. """ pass @six.add_metaclass(ABCMeta) class NetworkContext(object): """Context passe...
ts from expensive operations are cached so that other MechanismDrivers can freely access the same information. """ @abstractproperty def current(self): """Return the current state of the network. Return the current state of the network, as defined by NeutronPluginBaseV2.cre...
kawamon/hue
desktop/core/ext-py/pyasn1-0.4.6/pyasn1/codec/ber/decoder.py
Python
apache-2.0
58,050
0.001602
# # This file is part of pyasn1 software. # # Copyright (c) 2005-2019, Ilya Etingof <etingof@gmail.com> # License: http://snmplabs.com/pyasn1/license.html # from pyasn1 import debug from pyasn1 import error from pyasn1.codec.ber import eoo from pyasn1.compat.integer import from_bytes from pyasn1.compat.octets import oc...
raise error.PyAsn1Error('Indefinite length mode decoder not implemented for %s' % (tagSet,)) class AbstractSimpleDecoder(AbstractDecoder): @staticmethod def substrateCollector(asn1Object, substrate, length): return substrate[:length], substrate[leng
th:] def _createComponent(self, asn1Spec, tagSet, value, **options): if options.get('native'): return value elif asn1Spec is None: return self.protoComponent.clone(value, tagSet=tagSet) elif value is noValue: return asn1Spec else: retu...
waveform80/presentations
concurrency/demo3.py
Python
cc0-1.0
390
0
impo
rt zmq ctx = zmq.Context.instance() server = ctx.socket(zmq.PUSH) server.bind('inproc://foo') clients = [ctx.socket(zmq.PULL) for i in range(10)] poller = zmq.Poller() for client in clients: client.connect('inproc://foo') poller.register(client, zmq.POLLIN) for client in clients: server.send(b'DATA') for ...
))
diszgaurav/projecture
projecture/projects/python/myproject/myproject/myproject.py
Python
mit
353
0.005666
"""myproject """ __author__ = 'my
project:author_name' __email_
_ = 'myproject:author_email' #---------------------------------------------------------------------- def hello_world(extend_hello=False): """prints hello world :returns: None :rtype: None """ print 'Hello World!{}'.format(' Beautiful World!' if extend_hello else '')
wlan0/cattle
tests/integration-v1/cattletest/core/test_compose.py
Python
apache-2.0
5,735
0
from common import * # NOQA SERVICE = 'com.docker.compose.service' PROJECT = 'com.docker.compose.project' NUMBER = 'com.docker.compose.container-number' def test_container_create_count(client, context): project, service, c = _create_service(client, context) assert c.labels['io.rancher.service.deployment.u...
' def test_service_remove(client, context): project, service, c = _create_service(client, context) s = find_one(c.services) map = find_one(s.serviceExposeMaps) s = client.wait_success(s) env = client.wait_success(s.environment()) assert s
.state == 'active' s = client.delete(s) s = client.wait_success(s) assert s.state == 'removed' map = client.wait_success(map) assert map.state == 'removed' c = client.wait_success(c) assert c.state == 'removed' env = client.wait_success(env) assert env.state == 'removed' def te...
zielmicha/satori
satori.events/satori/events/__init__.py
Python
mit
1,410
0.002128
# vim:ts=4:sts=4:sw=4:expandtab """Package. Manages event queues. Writing event-driven code ------------------------- Event-driven procedures should be written as python coroutines (extended generators). To call the event API, yield an instance of the appropriate command. You can use sub-procedures - just yield the a...
port Map, Unmap from .protocol import Send, Receive from .protocol import KeepAlive, Disconnect, ProtocolError from .api import Manager from .master import Master from .slave import Slave from .client2 import Client2 from .slave2 import Slave2 __all__ = ( 'Event', 'MappingId', 'QueueId', 'Attach', 'Detach', ...
nmap', 'Send', 'Receive', 'KeepAlive', 'ProtocolError', 'Master', 'Slave', )
uclouvain/OSIS-Louvain
base/migrations/0277_auto_20180601_1458.py
Python
agpl-3.0
682
0.001466
# -*- coding: utf-8 -*- # Generated by Django 1.11.2 on 2018-06-01 12:58 from __future__ import unicode_literals from django.db
import migrations, models c
lass Migration(migrations.Migration): dependencies = [ ('base', '0276_professional_integration'), ] operations = [ migrations.AlterField( model_name='learningunit', name='end_year', field=models.IntegerField(blank=True, null=True, verbose_name='end_year_...
Duke-GCB/DukeDSHandoverService
download_service/views.py
Python
mit
899
0.003337
from django.http import StreamingHttpResponse, HttpResponseServerError from download_service.zipbuilder import DDSZipBuilder, NotFoundException, NotSupportedException from django.contrib.auth.decorators import login_required from download_service.utils import make_client from django.http import Http404 @login_require...
ke_client(request.user
) builder = DDSZipBuilder(project_id, client) try: builder.raise_on_filename_mismatch(filename) response = StreamingHttpResponse(builder.build_streaming_zipfile(), content_type='application/zip') response['Content-Disposition'] = 'attachment; filename={}'.format(filename) return ...
tpltnt/SimpleCV
SimpleCV/examples/detection/MotionTracker.py
Python
bsd-3-clause
1,540
0.012987
#!/usr/bin/python ''' This SimpleCV example uses a technique called frame differencing to determine if motion has occured. You take an initial image, then another, subtract the difference, what is left over is what has changed between those two images this are typically blobs on the images, so we do a blob s
earch to count the number of blobs and if they exist then motion has occured ''' from __future__ import print_function import sys, time, socket from SimpleCV import * cam = Camera() #setup the camera #settings for the project min_size = 0.1*cam.getProperty("width")*cam.getProperty("height") #make the threshold adapat...
the amount of seconds to show the motion detected message motion_timestamp = int(time.time()) message_text = "Motion detected" draw_message = False lastImg = cam.getImage() lastImg.show() while True: newImg = cam.getImage() trackImg = newImg - lastImg # diff the images blobs = trackImg.findBlobs() #use ...
jralls/gramps
gramps/plugins/drawreport/fanchart.py
Python
gpl-2.0
33,745
0.001245
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2003-2006 Donald N. Allingham # Copyright (C) 2007-2012 Brian G. Matherly # Copyright (C) 2010 Jakim Friant # Copyright (C) 2012-2014 Paul Franklin # Copyright (C) 2012 Nicolas Adenis-Lamarre # Copyright (C) 2012 Benny Malengier # # This...
this report user - a gen.user.User instance This report needs the following pa
rameters (class variables) that come in the options class. maxgen - Maximum number of generations to include. circle - Draw a full circle, half circle, or quarter circle. background - Background color is generation dependent or white. radial - Print radial te...
Reat0ide/plugin.video.pelisalacarta
pelisalacarta/channels/itastreaming.py
Python
gpl-3.0
11,292
0.021891
# -*- coding: utf-8 -*- #------------------------------------------------------------ #------------------------------------------------------------ import selenium from selenium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities import time import urlparse,urllib2,urllib,re,...
__ , action="movies", title="HD-MD" , url="http://itastreaming.co/qualita/hd-md" )) itemlist.append( Item(channel=__channel__ , action="movies", title="HD-TS" , url="http://itastreaming.co/qualita/hd-ts" )) return itemlist #searching for films def search(item, text): createCookies() itemlist = [] ...
eaming.co/?s=" + text try: biscotto = cookielib.MozillaCookieJar() biscotto.load(COOKIEFILE) data = requests.get(item.url, cookies=biscotto, headers=h) data = data.text.encode('utf-8') data = data.replace('&#8211;','-').replace('&#8217;',' ') pattern = '<img class="...
kartikeys98/coala
coalib/bearlib/aspects/Spelling.py
Python
agpl-3.0
2,014
0
from coalib.bearlib.aspects import Root, Taste @Root.subaspect class Spelling: """ How words should be written. """ class docs: example = """ 'Tihs si surly som incoreclt speling. `Coala` is always written with a lowercase `c`. """ example_language = 'reStructur...
ey are supposed to be; standardisation facilitates communication. """ fix_suggestions = """ Use the correct spelling for the misspelled words. """ @Spelling.subaspect class DictionarySpelling: """ Valid language's words spelling. """ class docs: example ...
This is toatly wonrg. """ example_language = 'reStructuredText' importance_reason = """ Good spelling facilitates communication and avoids confusion. By following the same rules for spelling words, we can all understand the text we read. Poor spelling distracts the rea...
smerritt/swift
doc/source/conf.py
Python
apache-2.0
8,171
0
# -*- coding: utf-8 -*- # 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...
sion of # liberasurecode which comes from Ubuntu 16.04. # pyeclib emits a warning message if liberasurecode <1.3.1 is used [1] and # this causes the doc build failure if warning-is-error is enabled in Sphinx. # As a workaround we suppress the warn
ing message from pyeclib until we use # a newer version of liberasurecode in our doc build job. # [1] https://github.com/openstack/pyeclib/commit/d163972b logging.getLogger('pyeclib').setLevel(logging.ERROR) # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys....
Spycho/aimmo
aimmo-game-worker/simulation/location.py
Python
agpl-3.0
529
0
class Location(object): def __init__(self, x, y): self.x = x self.y = y def __add__(self, direction): return Location(self.x + d
irection.x, self.y + direction.y) def __sub__(self, direction): return Location(self.x - direction.x, self.y - direction.y) def __repr__(self): return 'Location({}, {})'.format(self.x, self.y) def __eq__(self, other): return self.x == other.x and self.
y == other.y def __hash__(self): return hash((self.x, self.y))
xuru/pyvisdk
pyvisdk/esxcli/handlers/ha_cli_handler_storage_core_device_world.py
Python
mit
877
0.010262
from pyvisdk.esxcli.executer im
port execute_soap from pyvisdk.esxcli.base import Base class StorageCoreDeviceWorld(Base): ''' Operations on worlds pertaining to the pluggable storage architectures' logical devices on the system. ''' moid = 'ha-cli-handler-storage-core-device-world' def list(self, device=None): ''' ...
e worlds that are currently using devices on the ESX host. :param device: string, Filter the output of the command to limit the output to a specific device. This device name can be any of the UIDs registered for a device. :returns: vim.EsxCLI.storage.core.device.world.list.ScsiDeviceWorld[] '''...
adrienemery/auv-control-pi
navio/rcinput.py
Python
mit
484
0.004132
class RCInput(): CHANNEL_COUNT = 14 channels = [] def __init__(self): for i in range(0
, self.CHANNEL_COUNT): try: f = open("/sys/kernel/rcio/rcin/ch%d" % i, "r") self.channels.append(f) except: print ("Can't open file /sys/kernel/rcio/rcin/ch%d" % i) def read(self, ch): value = self.channels[ch].read() position ...
billiob/papyon
papyon/msnp2p/webcam.py
Python
gpl-2.0
9,665
0.001242
# -*- coding: utf-8 -*- # # papyon - a python client library for Msn # # Copyright (C) 2007 Ali Sabil <ali.sabil@gmail.com> # Copyright (C) 2008 Richard Spiers <richard.spiers@gmail.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as pu...
def send_data(self, data): message_bytes = data.encode("utf-16-le") + "\x00\x00" id = (self._generate_id() << 8) | 0x80 header = struct.pack("<LHL", id, 8, len(message
_bytes)) self._send_data(header + message_bytes) def send_binary_syn(self): self.send_data('syn') self._sent_syn = True def send_binary_ack(self): self.send_data('ack') def send_binary_viewer_data(self): self.send_data('receivedViewerData') def _send_xml(self)...
tarnheld/ted-editor
hm/apkhm.py
Python
unlicense
3,380
0.012722
from skimage import measure import numpy as np import struct import math as m from PIL import Image from simplify import simplify import argparse parser = argparse.ArgumentParser(description='convert apk heightmaps to floating point tiff') parser.add_argument('file', type=str, help='the apk heightmap file') args ...
append(cs)
np.savez_compressed(args.file+"-contours", *contours) # mi,ma = float(np.amin(img)),float(np.amax(img)) # print("contour",mi,ma) # for i in range(50): # d = float(mi*(1-i/50)+ma*i/50) # print("contour",d) # npc = measure.find_contours(img, d) # f...
Varriount/Colliberation
libs/twisted/internet/task.py
Python
mit
24,723
0.002346
# -*- test-case-name: twisted.test.test_task,twisted.test.test_cooperator -*- # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Scheduling utility methods and classes. @author: Jp Calderone """ __metaclass__ = type import time from zope.interface import implements from twisted.python imp...
cb) d.addErrback(eb) def _reschedule(self): """ Schedule the next iteration of this looping call.
""" if self.interval == 0: self.call = self.clock.callLater(0, self) return currentTime = self.clock.seconds() # Find how long is left until the interval comes around again. untilNextTime = (self._expectNextCallAt - currentTime) % self.interval # Make ...
google-research/jax3d
jax3d/projects/nesf/nerfstatic/utils/types_test.py
Python
apache-2.0
2,544
0.008648
# Copyright 2022 The jax3d 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 law or agreed to in wr...
, 10, 10]), direction=jnp.asarray([1, 0, 0]), scene_id=None) i = bbox.intersect_rays(rays) assert i[1] < i[0] def test_point_cloud(): h, w = 6, 8 normalize = lambda x: x / np.linalg.norm(x, axis=-1, keepdims=True) rays = types.Rays(scene_id=np.zeros((h, w, 1), dtype=n...
types.Views(rays=rays, depth=np.random.rand(h, w, 1), semantics=np.random.randint(0, 5, size=(h, w, 1))) # Construct point cloud. point_cloud = views.point_cloud # Only valid points. assert np.all(point_cloud.points >= -1) assert np.all(point_cloud.points <= 1) ...
tbabej/astropy
astropy/coordinates/builtin_frames/ecliptic.py
Python
bsd-3-clause
6,080
0.000987
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import (absolute_import, unicode_literals, division, print_function) from ..representation import SphericalRepresentation from ..baseframe import BaseCoordinateFrame, TimeFrameAttribute from ...
e None). b : `Angle`, optional, must be keyword The ecliptic latitude for this object
(``l`` must also be given and ``representation`` must be None). r : `~astropy.units.Quantity`, optional, must be keyword The Distance for this object from the sun's center. (``representation`` must be None). copy : bool, optional If `True` (default), make copies of the input coor...
FreedomBen/terminator
terminatorlib/prefseditor.py
Python
gpl-2.0
57,238
0.002009
#!/usr/bin/python """Preferences Editor for Terminator. Load a UIBuilder config file, display it, populate it with our current config, then optionally read that back out and write it to a config file """ import os import gtk from util import dbg, err import config from keybindings import Keybindings, KeymapError f...
'rxvt': '#000000:#cd0000:#00cd00:#cdcd00:#0000cd:\ #cd00cd:#00cdcd:#faebd7:#404040:#ff0000:#00ff00:#ffff00:#0000ff:\ #ff00ff:#00ffff:#ffffff', 'ambience': '#2e3436:#cc0000:#4e9a06:#c4a000:\ #3465a4:#75507b:#06989a:#d3d7cf:#555753:#ef2929:#8ae234:#fce94f:\ #729fcf:#ad7fa8:#34e2e2:#eeeeec', ...
'zoom_in' : 'Increase font size', 'zoom_out' : 'Decrease font size', 'zoom_normal' : 'Restore original font size', 'new_tab' : 'Create a new tab', 'cycle_next' : 'Focus the next terminal...
robwebset/script.ebooks
resources/lib/kiehinen/ebook.py
Python
gpl-2.0
8,604
0.002092
from struct import unpack, pack, calcsize from mobi_languages import LANGUAGES from lz77 import uncompress def LOG(*args): pass MOBI_HDR_FIELDS = ( ("id", 16, "4s"), ("header_len", 20, "I"), ("mobi_type", 24, "I"), ("encoding", 28, "I"), ("UID", 32, "I"), ("generator_version", 36, "I"), ...
_idx", 108, "I"), ("huff/cdic_record", 112, "I"), ("huff/cdic_count", 116, "I"), ("datp_record", 120, "I"), ("datp_count", 124, "I"), ("exth_flags", 128, "I"), ("unknowni@132", 132, "32s"), ("unknown@164", 164, "I"), ("drm_offs", 168, "I"), ("drm_count", 172, "I"), ("drm_size", 1...
("unknown@188", 188, "I"), ("unknown@192", 192, "H"), ("last_image_record", 194, "H"), ("unknown@196", 196, "I"), ("fcis_record", 200, "I"), ("unknown@204", 204, "I"), ("flis_record", 208, "I"), ("unknown@212", 212, "I"), ("extra_data_flags", 242, "H") ) EXTH_FMT = ">4x2I" '''4x...
PBR/chebi2gene
chebi2gene.py
Python
bsd-3-clause
17,793
0.001124
#!/usr/bin/python """ Small web application to retrieve information from uniprot and itag for a given compound. The idea is that for one compound we are able to find out in which reactions it is involved and what are the proteins involved in these reactions. For each of these proteins we can find if there are genes a...
proteins = list(set(proteins)) query = ''' PREFIX gene:<http://pbr.wur.nl/GENE#> PREFIX uniprot:<http://purl.uniprot.org/core/> PREFIX rdfs:<http://www.w3.org/2000/01/rdf-schema#> SELECT DISTINCT ?prot ?desc FROM <%(uniprot)s> WHERE { ?prot uniprot...
rdfs:comment ?desc . FILTER ( ?prot IN ( <http://purl.uniprot.org/uniprot
valeth/apex-sigma
sigma/plugins/searches/google/google.py
Python
gpl-3.0
1,478
0.003392
import aiohttp import discord import random from config import GoogleAPIKey from config import GoogleCSECX async def google(cmd, message, args): if not args: await message.channel.send(cmd.help()) return else: search = ' '.join(args) url = 'https://www.googleapis.com/customsea...
, url='https://www
.google.com/search?q=' + search) embed.add_field(name=title, value='[**Link Here**](' + url + ')') await message.channel.send(None, embed=embed) except Exception as e: cmd.log.error(e) embed = discord.Embed(color=0xDB0000, title='❗ Daily Limit Reached.') ...
jpbarrette/moman
finenight/python/iadfa.py
Python
mit
4,303
0.006739
from fsa import * from nameGenerator import * class IncrementalAdfa(Dfa): """This class is an Acyclic Deterministic Finite State Automaton constructed by a list of words. """ def __init__(self, words, nameGenerator = None, sorted = False): if nameGenerator is None: nameGenerator ...
e = self.startState index = 0 nextStateName = stateName whi
le nextStateName is not None: symbol = word[index] stateName = nextStateName if symbol in self.states[stateName].transitions: nextStateName = self.states[stateName].transitions[symbol] index += 1 else: nextStateName = None ...
alfredodeza/pytest
src/_pytest/setupplan.py
Python
mit
818
0
import pytest def pytest_addoption(parser): group = parser.getgroup("debugconfig") group.addoption( "--setupplan", "--setup-plan", action="store_true", help="show what fixtures and tests would be execute
d but " "don't execute anything.",
) @pytest.hookimpl(tryfirst=True) def pytest_fixture_setup(fixturedef, request): # Will return a dummy fixture if the setuponly option is provided. if request.config.option.setupplan: my_cache_key = fixturedef.cache_key(request) fixturedef.cached_result = (None, my_cache_key, None) re...
markalansmith/draftmim
web/draftmim/core.py
Python
apache-2.0
189
0
from draftmim import app from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.restless import APIManager db = SQLAlchemy(app) api_manager = APIManager(app, fl
ask_sqlalchemy_db=db
)
jairideout/q2cli
q2cli/dev.py
Python
bsd-3-clause
1,137
0
# ---------------------------------------------------------------------------- # Copyright (c) 2016-2017, QIIME 2 development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file LICENSE, distributed with this software. # ------------------------------------------------...
"changes to take effect in the CLI. A refresh of the cache " "is necessary becaus
e package versions do not typically " "change each time an update is made to a package's code. " "Setting the environment variable Q2CLIDEV to any value " "will always refresh the cache when a command is run.") def refresh_cache(): import q2cli.cache q2cli.c...
Didou09/tofu
tofu/imas2tofu/_comp_mesh.py
Python
mit
6,909
0
# Built-in import os import warnings # Common import numpy as np # ############################################################################# # Triangular meshes # ############################################################################# def tri_checkformat_NodesFaces(nodes, indfaces, ids=...
[ii for ii in range(0, nfaces) if ii not in indfacesu] msg += (" Duplicate faces: {}\n".format(nfaces - facesu.shape[0
]) + "\t- faces.shape: {}\n".format(indfaces.shape) + "\t- unique faces.shape: {}".format(facesu.shape) + "\t- duplicate facess indices: {}\n".format(dupf)) if lc[2]: nfu = facesuu.size nodnotf = [ii for ii in range(0, nnodes) i...
mgraupe/acq4
setup.py
Python
mit
7,496
0.007204
DESCRIPTION = """\ ACQ4 is a python-based platform for experimental neurophysiology. It includes support for standard electrophysiology, multiphoton imaging, scanning laser photostimulation, and many other experimental techniques. ACQ4 is highly modular and extensible, allowing support to be added for new types of d...
RIPTION, license='MIT', url='http
://www.acq4.org', author='Luke Campagnola', author_email='luke.campagnola@gmail.com', ) from setuptools import setup import distutils.dir_util import distutils.sysconfig import os, sys, re from subprocess import check_output ## generate list of all sub-packages path = os.path.abspath(os.path.dirname(__file_...
Strangemother/python-state-machine
scatter/__init__.py
Python
mit
36
0
from root
import * version = '
v0.1'
Zomboided/VPN-Manager
managefiles.py
Python
gpl-2.0
11,679
0.007192
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2016 Zomboided # # 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)...
if not list_item in all_user: all_user.append(list_item) all_user.sort() # Offer a delete all option if there are multiple keys all_item = "[I]Delete all key and certificate files[/I]"
if usesMultipleKeys(provider): all_user.append(all_item) # Add in a finished option
govenius/plotbridge
examples/gnuplot_with_direction/expected_output/gnuplot.interactive.py
Python
gpl-2.0
3,554
0.019977
#!/usr/bin/python import os import sys import time import logging import subprocess replot_poll_period = 1 plot_script_extension = '.gnuplot' plot_script = None for f in os.listdir('.'): if f.endswith(plot_script_extension): plot_script = f break assert plot_script != None, 'No file ending with "%s" found ...
ame, 'r') as f: print '---start of %s---' % fname for i,l in enumerate(f.read().split('\n')): print '%3d %s' % (i,l) print '---end of %s---\n' % fname sys.stdout.flush() exit_if_locked() # technically, this and the lock file creation should be done atomically... try: refresh_lock() file_to_monitor...
_script ] plotted_once = False # Watch directory for changes and replot when necessary. # Use simple polling of st_mtime since it works on Linux and Windows # and the polling period is reasonably slow (~seconds). gp = None while not plotted_once or gp.poll() == None: # keep polling as long as gnuplot is ...
dmnfarrell/epitopemap
modules/pepdata/pmbec.py
Python
apache-2.0
2,894
0.001382
# Copyright (c) 2014. Mount Sinai School of Medicine # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
tter)] = value with open(
filename, 'r') as f: lines = [line for line in f.read().split('\n') if len(line) > 0] header = lines[0] if verbose: print(header) residues = [x for x in header.split(' ') if len(x) == 1 and x != ' ' and x != '\t'] assert len(residues) == 20 if verbose: ...
openstack/designate
designate/tests/unit/agent/backends/test_knot2.py
Python
apache-2.0
7,785
0
# Copyright 2016 Hewlett Packard Enterprise Development Company LP # # Author: Federico Ceratto <federico.ceratto@hpe.com> # # 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....
re # 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 limitat
ions # under the License. from unittest import mock from unittest.mock import call from oslo_concurrency import processutils from designate.backend.agent_backend import impl_knot2 from designate import exceptions import designate.tests from designate.tests.unit.agent import backends class Knot2AgentBackendTestCase(...
Heathckliff/SU2
SU2_PY/SU2/io/config.py
Python
lgpl-2.1
30,190
0.016827
#!/usr/bin/env python ## \file config.py # \brief python package for config # \author T. Lukaczyk, F. Palacios # \version 4.0.1 "Cardinal" # # SU2 Lead Developers: Dr. Francisco Palacios (Francisco.D.Palacios@boeing.com). # Dr. Thomas D. Economon (economon@stanford.edu). # # SU2 Developers: Pr...
ion) any later version. # # SU2 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
# Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with SU2. If not, see <http://www.gnu.org/licenses/>. # ---------------------------------------------------------------------- # Imports # -------------------------------------------...
jtrobec/pants
tests/python/pants_test/bin/test_goal_runner.py
Python
apache-2.0
756
0.005291
# coding=utf-8 # Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import pytest from p...
']) with pytest.raises(BuildConfigurationError): OptionsInitializer(options_bootstrapper, WorkingSet()).s
etup()
fake-name/ReadableWebProxy
WebMirror/management/rss_parser_funcs/feed_parse_extractTokyoESPScans.py
Python
bsd-3-clause
230
0.030435
def extract
TokyoESPScans(item): """ Tokyo ESP Scans """ vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol
or frag) or 'preview' in item['title'].lower(): return None return False
skevy/django
tests/modeltests/files/models.py
Python
bsd-3-clause
1,085
0.001843
""" 42. Storing files according to a custom storage system ``FileField`` and its variations can take a ``storage`` argument to specify how and where files should be stored. """ import random import tempfile from django.db import models from django.core.files.base import ContentFile from django.core.files.storage imp...
once. return '%s/%s' % (random.randint(100, 999), filename) normal = models.FileField(storage=temp_storage, upload_to='tests') custom = models.FileField(storage=temp_storage, upload_to=custom_upload_to) random = models.FileField(storage=temp_storage, upload_to=random_upload_to) default
= models.FileField(storage=temp_storage, upload_to='tests', default='tests/default.txt')
ssebastianj/pywebtasks
pywebtasks/__init__.py
Python
mit
546
0
# -*- coding: utf-8 -*- __title__ = 'pywebtask' __version__ = '0.1.8' __build__ = 0x000108 __author__ = 'Sebastián José Seba'
__license__ = 'MIT' __copyright__ = 'Copyright 2016 Sebastián José Seba' from .webtasks import run, run_file # Set defau
lt logging handler to avoid "No handler found" warnings. import logging try: # Python 2.7+ from logging import NullHandler except ImportError: class NullHandler(logging.Handler): def emit(self, record): pass logging.getLogger(__name__).addHandler(NullHandler())
jb-old/chii
quoth/uwsgi_app.py
Python
unlicense
148
0.006757
i
mport os os.environ['DJANGO_SETTINGS_MODULE'] = 'settin
gs' import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler()
christophercrouzet/hienoi
hienoi/gui.py
Python
mit
20,220
0
"""Graphical user interface.""" import collections import ctypes import sdl2 import hienoi.renderer from hienoi._common import GLProfile, GraphicsAPI, ParticleDisplay, UserData from hienoi._vectors import Vector2i, Vector2f, Vector4f class NavigationAction(object): """Enumerator for the current nagivation acti...
view_zoom_range=Vector2f(1e-6, 1e+6), mouse_wheel_step=0.01, grid_density=10.0, grid_adaptive_threshold=3.0, show_grid=True, background_color=Vector4f(0.15, 0.15, 0.15, 1.0),
grid_color=Vector4f(0.85, 0.85, 0.85, 0.05), grid_origin_color=Vector4f(0.85, 0.25, 0.25, 0.25), particle_display=ParticleDisplay.DISC, point_size=4, edge_feather=2.0, stroke_width=0.0, initialize_callback=None, ...
hcosta/escueladevideojuegos.net-backend-django
edv/reddit/migrations/0005_auto_20170520_2005.py
Python
gpl-3.0
788
0.001271
# -*- coding: utf-8 -*- # Generated by Django 1.11.1 on 2017-05-20 18:05 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('reddit', '0004_auto_20170520_1931'), ] operations = [ migrations.AddField( ...
e='label', field=models.IntegerField(choices=[(0, ''), (1, 'Ayuda!'), (2, 'Resuelta'), (3, 'Discusión'), (4, 'Tutorial'), (5, 'Ejemplo'), (6, 'Recurso'), (7, 'Juego')], default=0, verbose_name=
'Etiqueta'), ), ]
ChengchenZhao/DrSeq2
ceas_lib/annotator.py
Python
gpl-3.0
75,107
0.022807
"""Module Description Copyright (c) 2008 H. Gene Shin <shin@jimmy.harvard.edu> This code is free software; you can redistribute it and/or modify it under the terms of the BSD License (see the file COPYING included with the distribution). @status: experimental @version: $Revision$ @author: H. Gene Shin @contact: s...
m=(2500, 5000), down=(1000, 2000, 3000), gene_div=(3,5),quantize=True): """Annotate given coordinates based on the given gene table.""" # get the chromsomes of the gene table and genome coordinates try: chroms_gc=genome_coordinates.keys() chroms_gt=gene_table.get...
roms) chroms.sort() num_coordinates={} num_genes={} for chrom in chroms: num_coordinates[chrom]=len(genome_coordinates[chrom]) num_genes[chrom]=len(gene_table[chrom][gene_table[chrom].keys()[0]]) except AttributeError: r...
smdabdoub/phylotoast
bin/PCoA.py
Python
mit
10,870
0.004416
#!/usr/bin/env python import argparse from collections import OrderedDict import itertools import sys from phylotoast import util, graph_util as gu errors = [] try: from palettable.colorbrewer.qualitative import Set3_12 except ImportError as ie: errors.append("No module named palettable") try: import matplo...
equired=True, help="Any mapping categories, such as treatment type, that will "
"be used to group the data in the output iTol table. For example," " one category with three types will result in three data columns" " in the final output. Two categories with three types each will " "result in six data columns. Default is n...
jellybean4/yosaipy2
yosaipy2/core/event/event_bus.py
Python
apache-2.0
1,390
0
#!/usr/bin/env python # -*- coding: utf-8 -*- from blinker import signal, Namespace, NamedSignal from yosaipy2.core.event.abcs import EventBus from typing import Dict from functools import wraps class BlinkerEventBus(EventBus): def __init__(self): # type: (str) -> None self.AUTO_TOPIC = "blinker_e...
self._signals[topic_name] = sig else: sig = self._signals[topic_name] sig.send(None,
**kwargs) def subscribe(self, func, topic_name): if topic_name not in self._signals: sig = signal(topic_name) self._signals[topic_name] = sig else: sig = self._signals[topic_name] callback = self._adapter(func, topic_name) sig.connect(callback) ...
lantius/ndb-key
repro.py
Python
mit
1,545
0.005825
import webapp2 from google.appengine.ext import db from google.appengine.ext import ndb from db_class import DerivedClass as OldDerivedClass from ndb_class import BaseClass as NewBaseClass from ndb_class import DerivedClass as NewDerivedClass class Repro(webapp2.RequestHandler): def get(self): self.response...
rivedClass, ndb_key.id()) obj = derived_key.get() if not obj: self.response.write('failed (None): %s\n' % str(derived_key)) # Attempt to create a new key using the ndb bas
e class base_key = ndb.Key(NewBaseClass, ndb_key.id()) obj = derived_key.get() if not obj: self.response.write('failed (None): %s\n' % str(base_key)) # Manually create a new key using the ndb derived class name force_key = ndb.Key('DerivedClass', ndb_key.id()) try: force_key.get() ...
nii-cloud/dodai-compute
nova/db/sqlalchemy/migrate_repo/versions/007_add_ipv6_to_fixed_ips.py
Python
apache-2.0
2,067
0
# Copyright 2011
OpenStack LLC # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file exc
ept 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 distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS ...
valery-barysok/skyscanner-python-sdk
docs/conf.py
Python
apache-2.0
8,466
0.005315
#!/usr/bin/env python # -*- coding: utf-8 -*- # # skyscanner documentation build configuration file, created by # sphinx-quickstart on Tue Jul 9 22:26:36 2013. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # ...
a lis
t of supported languages. #language = None # There are two options for replacing |today|: either, you set today to # some non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match fil...
opentechinstitute/commotion-router-test-suite
tests/__init__.py
Python
agpl-3.0
69
0
""" Initializat
ion code related to Commotion Rout
er UI unit tests"""
stdweird/aquilon
lib/python2.6/aquilon/worker/commands/show_rack_rack.py
Python
apache-2.0
1,055
0
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2008,2009,2010,2011,2013 Contributor # # 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 t...
): required_parameters = ["rack"] d
ef render(self, session, rack, **arguments): return Rack.get_unique(session, rack, compel=True)
tidalf/plugin.audio.qobuz
resources/lib/qobuz/extension/kooli/kooli/script/kooli-xbmc-service.py
Python
gpl-3.0
4,243
0.002593
''' qobuz.extension.kooli.script.kooli-xbmc-service ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :part_of: kodi-qobuz :copyright: (c) 2012-2018 by Joachim Basmaison, Cyril Leclerc :license: GPLv3, see LICENSE for more details. ''' from os import path as P import SocketServer import socket import...
buz service / HTTPD', 'Service is disabled from configuration') monitor.start_all_service() alive = True while alive: abort = False try: abort = monitor.abortRequested except Exception as e: logger.error('Error while getting abortRequested ...
000) monitor.stop_all_service()
wldisaster/Alice
blog/admin.py
Python
gpl-3.0
339
0.009063
from django.contrib import admin from .models import Post, Category, Tag # Register your models here. cla
ss PostAdmin(admin.ModelAdmin): list_display = ['title', 'created_time', 'modified_time', 'category', 'author'] # 注册新增PostAdmin admin.site.register(Post, PostAdmin) admin.site.register(Category) admin.site.re
gister(Tag)
Mustapha90/IV16-17
tango_with_django_project/dev_settings.py
Python
gpl-3.0
375
0.002667
# -*- coding: utf-8 -*- from .common_settings import * DEBUG = True TEMPLATE_DEBUG = DEBUG # SEC
URITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'dz(#w(lfve24ck!!yrt3l7$jfdoj+fgf+ru@w)!^gn9aq$s+&y' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } }
caioariede/pyintercept
setup.py
Python
mit
1,498
0
import sys from setuptools import setup, find_packages from setuptools.command.test import test as TestCommand VERSION = '0.4.1' class PyTest(TestCommand): user_options = [('pytest-args=', 'a', "Arguments to pass to py.test")] def initialize_options(self): TestCommand.initialize_options(self) ...
ariede@gmail.com", url="http://github.com/caioariede/pyintercept", license="MIT", zip_safe=False, platforms=["any"], packages=find_packages(), classifiers=[ "Intended Audience :: Developers", "Operating System :: OS Independent", "License :: OSI Approved :: MIT License", ...
], include_package_data=True, install_requires=[ 'byteplay', ], tests_require=[ 'pytest', 'uncompyle6', ], test_suite='py.test', cmdclass={'test': PyTest}, )
Mirio/captcha2upload
setup.py
Python
bsd-2-clause
647
0.001546
from distutils.core import setup setup( name='captcha2upload', packages=['captcha2upload'], package_dir={'captcha2upload': 'src/captcha2upload'}, version='0.2', install_requires=['requests'], description='Upload your image and solve captche usi
ng the 2Captcha ' 'Service', author='Alessandro Sbarbati', author_email='miriodev@gmail.com', url='https://github.com/Mirio/captcha2upload', download_url='https://github.com/Mirio/captcha2upload/tarball/0.1', keywords=['2captcha', 'captcha', 'Image Recognition'], classifiers=["...
cientific/Engineering :: Image Recognition"], )
alshedivat/tensorflow
tensorflow/python/data/experimental/kernel_tests/optimization/map_and_filter_fusion_test.py
Python
apache-2.0
4,199
0.009288
# Copyright 2018 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...
lambda x, y: constant_op.constant(True))) tests.append( ("Multi2", lambda x: (x, 2), lambda x, y: math_ops.equal(x * math_ops.cast(y, dtypes.int64), 0))) return tuple(tests) class MapAndFilterFusionTest(test_base.DatasetTestBase, parameterized.TestCase): def _testMapAndFilter(self,...
xt = iterator.get_next() with self.cached_session() as sess: for x in range(10): r = function(x) if isinstance(r, tuple): b = predicate(*r) # Pass tuple as multiple arguments. else: b = predicate(r) if sess.run(b): result = sess.run(get_next) ...
jjmontesl/cubetl
cubetl/template/__init__.py
Python
mit
1,587
0.00189
# CubETL # Copyright (c) 2013-2019 Jose Juan Montes # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge...
#template = ctx.interpolate(self.te
mplate, m) result = self.render(ctx, {'m': m}) m['templated'] = result yield m
ESOedX/edx-platform
cms/djangoapps/contentstore/management/commands/tests/test_export_olx.py
Python
agpl-3.0
3,608
0.000554
""" Tests for exporting OLX content. """ from __future__ import absolute_import import shutil import tarfile import unittest from six import StringIO from tempfile import mkdtemp import ddt import six from django.core.management import CommandError, call_command from path import Path as path from xmodule.modulestor...
aisesRegexp(CommandError, errstring): call_command('export_olx') @ddt.ddt class TestCourseExportOlx(ModuleStoreTestCase): """ Test exporting OLX content from a cour
se or library. """ def test_invalid_course_key(self): """ Test export command with an invalid course key. """ errstring = "Unparsable course_id" with self.assertRaisesRegexp(CommandError, errstring): call_command('export_olx', 'InvalidCourseID') def test...
bsmr-eve/Pyfa
eos/effects/subsystembonuscaldarioffensive3remoteshieldboosterheat.py
Python
gpl-3.0
459
0.004357
# subsystemBonusCaldariOffensive3RemoteShieldBoosterHeat # # Used by: # Subsystem: Tengu Offensive - Support Processor type = "passive" def handler(fit, src, context
): fit.modules.filteredItemBoost(lambda mod: mod.item.requiresSkill("Shield Emission Systems"),
"overloadSelfDurationBonus", src.getModifiedItemAttr("subsystemBonusCaldariOffensive3"), skill="Caldari Offensive Systems")
111t8e/h2o-2
py/testdir_single_jvm/test_GLM2_syn_2659x1049.py
Python
apache-2.0
1,417
0.012703
import unittest, time, sys sys.path.extend(['.','..','../..','py']) import h2o, h2o_cmd, h2o_glm, h2o_import as h2i params = { 'response': 1049, 'family': 'binomial', 'beta_epsilon': 0.0001, 'alpha': 1.0, 'lambda': 1e-05, 'n_folds': 1, 'max_iter': 20, } class Basic(unittest.TestCase):...
o.check_sandbox_fo
r_errors() @classmethod def setUpClass(cls): h2o.init(1) @classmethod def tearDownClass(cls): h2o.tear_down_cloud() def test_GLM2_syn_2659x1049(self): csvFilename = "syn_2659x1049.csv" csvPathname = 'logreg' + '/' + csvFilename parseResult = h2i.import_pars...
leapcode/soledad
tests/e2e/test_incoming_mail_pipeline.py
Python
gpl-3.0
1,604
0
# This script does the following: # # - create a user using bonafide and and invite code given as an environment # variable. # # - create and upload an OpenPGP key manually, as that would be # a responsibility of bitmask-dev. # # - send an email to the user using sendmail, with a secret in the body. # # - start a s...
en_key from utils import put_key from utils import send_email from utils import get_incoming_fd from utils import get_received_secret @pytest.inlineCallbacks def test_incoming_
mail_pipeline(soledad_client, tmpdir): # create a user and login session = yield get_session(tmpdir) # create a OpenPGP key and upload it key = gen_key(session.username) yield put_key(session.uuid, session.token, str(key.pubkey)) # get a soledad client for that user client = soledad_clien...
jasonsahl/LS-BSR
tools/compare_BSR.py
Python
gpl-3.0
3,059
0.012422
#!/usr/bin/env python """compares BSR values between two groups in a BSR matrix Numpy and BioPython need to be installed. Python version must be at least 2.7 to use collections""" from optparse import OptionParser import subprocess from ls_bsr.util import prune_matrix from ls_bsr.util import compare_values from ls_b...
ids", dest="group2", help="new line separated file with group2 ids [REQUIRED]", action="callback", callback=test_file, type="string") parser.add_option("-u", "--upper_bound", dest="upper", help="upper bound for BSR comparisons, defaults to 0.8", ...
or BSR comparisons, defaults to 0.4", default="0.4", type="float") options, args = parser.parse_args() mandatories = ["matrix", "group1", "group2", "fasta"] for m in mandatories: if not options.__dict__[m]: print("\nMust provide %s.\n" %m) parser.print_help() ...
sistason/kinksorter2
src/kinksorter_app/management/commands/kink_besteffortsync.py
Python
gpl-3.0
2,449
0.004492
from os import path, access, W_OK, R_OK import argparse import logging from django.core.management.base import BaseCommand, CommandError from kinksorter_app.functionality.movie_handling import merge_movie, recognize_movie from kinksorter_app.models import Movie, PornDirectory from kinksorter_app.functionality.directo...
er): parser.add_argument('src_directory', type=argcheck_dir) parser.add_argument('dst_directory', type=argcheck_dir) def handle(self, *args, **options): src_dir = options['src_directory'] dst_dir = options['dst_directory'] logger.info("Start") if PornDirectory.obje...
xists(): dst_handler = PornDirectoryHandler(0) else: dst_handler = PornDirectoryHandler(None, init_path=dst_dir, name="dest", id_=0) dst_handler.scan() # only scan initially, since the merged files get added to the db if PornDirectory.objects.filter(path=src_dir).ex...
hanyassasa87/ns3-802.11ad
doc/manual/source/conf.py
Python
gpl-2.0
10,879
0.001287
# -*- coding: utf-8 -*- # # test documentation build configuration file, created by # sphinx-quickstart on Sun Jun 26 00:00:43 2016. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All ...
it_index = False # If true, links to the reST sources are added to the pages. # # html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. # # html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. # # html_show_copyrigh...
ntain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. # # html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). # html_file_suffix = None # Language to be used for generating the HTML full-text search index. # Sph...
OddBloke/sphinx-git
tests/test_git_changelog.py
Python
gpl-3.0
11,748
0
# -*- coding: utf-8 -*- import os from datetime import datetime import six from bs4 import BeautifulSoup from git import InvalidGitRepositoryError, Repo from mock import ANY, call from nose.tools import ( assert_equal, assert_greater, assert_in, assert_less_equal, assert_not_in, assert_raises, ...
list_markup = BeautifulSoup(str(nodes[0]), features='xml') item = list_markup.bullet_list.list_item children = list(item.childGe
nerator()) assert_equal(1, len(children)) par_children = list(item.paragraph.childGenerator()) assert_equal(5, len(par_children)) assert_equal('my root commit', par_children[0].text) assert_equal('Test User', par_children[2].text) def test_single_commit_message_and_user_disp...
threemeninaboat3247/kuchinawa
kuchinawa/__init__.py
Python
mit
687
0.020378
# -*- coding: utf-8 -*- """ Created on Mon Oct 23 03:24:37 2017 @a
uthor: Yuki """ import os,sys,logging ENTRYPOINT=__path__[0] ICONPATH=os.path.join(ENTRYPOINT,'Icons','logo.png') KUCHINAWA='Kuchinawa' from kuchinawa.Compile import compileUi from kuchinawa.Thread import Main #change the multiprocessing's context to 'spawn' try: import multiprocessing multipr
ocessing.set_start_method('spawn') except: print('The context of multiprocessing is already set.') def run_sample(): '''Run a sample program''' from PyQt5.QtWidgets import QApplication from kuchinawa.Examples import SinCos app = QApplication([]) s=SinCos.Sample() sys.exit(app.exec_())
krarkrrrc/vidpager
db/DbTools.py
Python
gpl-3.0
2,503
0.029165
import sys import sqlite3 import CONST import re """ Provides the low-level functions to insert, query and update the db """ def init(): con = sqlite3.connect( CONST.db_name ) # asr value is auto-speech-recognition rendered captions, either 0 (false) or 1 (true) con.execute( '''CREATE TABLE IF NOT EXISTS...
ll( r'(\d\d:\d
\d:\d\d\.\d\d\d\s-->\s\d\d:\d\d:\d\d\.\d\d\d)\\n([\w\s\d\\\,\.\;\:\$\!\%\)\(\?\/\'\"\-]+)\\n\\n', subtitles ) captions = "" timestamps = "" count = 0 for match in matches: captions += '<' + str( count ) + '>' + match[1] timestamps += '<' + str( count ) + '>' + match[0] count += ...
TuSimple/simpledet
config/RepPoints/reppoints_moment_dcn_r101v1b_fpn_multiscale_2x.py
Python
apache-2.0
7,766
0.000644
from models.RepPoints.builder import RepPoints as Detector from models.dcn.builder import DCNResNetFPN as Backbone from models.RepPoints.builder import RepPointsNeck as Neck from models.RepPoints.builder import RepPointsHea
d as Head from mxnext.complicate import normalizer_factory def get_config(is_train): class General: log_frequency = 10 name = __name__.rsplit("/")[-1].rsplit(".")[-1] batch_image = 2 if is_train else 1 fp16 = False class KvstoreParam: kvstore = "nccl" batch_ima...
n", ndev=8, wd_mult=1.0) normalizer = normalizer_factory(type="gn") class BackboneParam: fp16 = General.fp16 # normalizer = NormalizeParam.normalizer normalizer = normalizer_factory(type="fixbn") depth = 101 num_c3_block = 0 num_c4_block = 3 class NeckPa...
thomazs/geraldo
site/newsite/django_1_0/tests/regressiontests/modeladmin/models.py
Python
lgpl-3.0
31,422
0.002005
# coding: utf-8 from datetime import date from django.db import models from django.contrib.auth.models import User class Band(models.Model): name = models.CharField(max_length=100) bio = models.TextField() sign_date = models.DateField() def __unicode__(self): return self.name class Conce...
afa.base_fields['opening_band'].widget.choices) [(u'', u'None'), (1, u'The Doors')] >>> type(cmafa.base_fields['day'].widget) <class 'django.contrib.admin.widgets.AdminRadioSelect'> >>> cmafa.base_fields['day'].widget.attrs {'class': 'radiolist'} >>> list(cmafa.base_fields['day'].widget.choices) [(1, 'Fri'), (2, '
Sat')] >>> type(cmafa.base_fields['transport'].widget) <class 'django.contrib.admin.widgets.AdminRadioSelect'> >>> cmafa.base_fields['transport'].widget.attrs {'class': 'radiolist inline'} >>> list(cmafa.base_fields['transport'].widget.choices) [('', u'None'), (1, 'Plane'), (2, 'Train'), (3, 'Bus')] >>> band.delete()...
lmotta/Roam
src/configmanager/editorwidgets/listwidget.py
Python
gpl-2.0
5,997
0.001501
import os from functools import partial from PyQt4.QtGui import QWidget from PyQt4.QtCore import Qt from qgis.core import QgsMapLayer from qgis.gui import QgsExpressionBuilderDialog from roam.api.utils import layer_by_name from configmanager.models import QgsLayerModel, QgsFieldModel from configmanager.editorwidget...
ayerCombo.setModel(self.layermodel) self.keyCombo.setModel(self.fieldmodel) self.valueCombo.setModel(self.fieldmodel) self.filterButton.pressed.connect(self.define_filter) self.fieldmodel.setLayerFilter(self.layerCombo.view().selectionModel()) self.reset() self.blockSign...
if not layer: return layer = layer_by_name(layer) dlg = QgsExpressionBuilderDialog(layer, "List filter", self) text = self.filterText.toPlainText() dlg.setExpressionText(text) if dlg.exec_(): self.filterText.setPlainText(dlg.expressionText()) ...
tiangolo/fastapi
docs_src/header_params/tutorial003.py
Python
mit
216
0
from typing import List, Optional from fastapi import FastAPI, Header app
= FastAPI() @app.get("/items/") async def read_items(x_token: Optional[List[str]] = Header(None)): return {"X-Token values"
: x_token}
rlishtaba/py-algorithms
py_algorithms/challenges/challenges.py
Python
mit
1,505
0
import re class Challenges: @staticmethod def first_factorial(number: int) -> int: """ Iterative approach :param number: an input, first factorial of a number :return: factorial """ found = 1 step = 2 w
hile step <= number: found *= step step += 1 return found @staticmethod def longest_word(sentence: str) -> str: """ Detect longest word in a sentence :param sentence: :return: """ trimmed = re.compile('[^a-zA-Z0-9 ]').sub('',
sentence) chunks = trimmed.split(' ') longest = 0 index = -1 for i, x in enumerate(chunks): if len(x) > longest: longest = len(x) index = i return chunks[index] @staticmethod def letter_mutation(string): """ Co...
tdhooper/starstoloves
starstoloves/lib/user/user_repository.py
Python
gpl-2.0
564
0.007092
import sys from starstoloves.models import User as UserModel from starstoloves import model_repository from starstoloves.lib.track import lastfm_track_repo
sitory from .user import User def from_session_key(session_key): user_model, created = UserModel.objects.get_or_create(session_key=session_key) return User( session_key=session_key, repository=sys.modules[__name__], ); def delete(user
): try: user_model = model_repository.from_user(user) user_model.delete() except UserModel.DoesNotExist: pass;
romonzaman/newfies-dialer
newfies/dnc/constants.py
Python
mpl-2.0
748
0
# # Newfies-Dialer License # http://www.newfies-dialer.org # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at http://mozilla.org/MPL/2.0/. # # Copyright (C) 2011-201
5 Star2Billing S.L. # # The primary maintainer of this project is # Arezqui Belaid <info@star2
billing.com> # from django.utils.translation import ugettext_lazy as _ from django_lets_go.utils import Choice class DNC_COLUMN_NAME(Choice): id = _('ID') name = _('name') date = _('date') contacts = _('contacts') class DNC_CONTACT_COLUMN_NAME(Choice): id = _('ID') dnc = _('DNC') phone_...
fossilet/ansible
lib/ansible/module_utils/facts.py
Python
gpl-3.0
132,636
0.004976
# (c) 2012, Michael DeHaan <michael.dehaan@gmail.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any lat...
_facts() elif self.facts['system'] == 'AIX': # Attempt t
o use getconf to figure out architecture # fall back to bootinfo if needed if module.get_bin_path('getconf'): rc, out, err = module.run_command([module.get_bin_path('getconf'), 'MACHINE_ARCHITECTURE']) data = out....
humancompatibleai/imitation
src/imitation/data/buffer.py
Python
mit
13,770
0.001888
import dataclasses from typing import Dict, Mapping, Optional, Tuple import numpy as np from stable_baselines3.common import vec_env from imitation.data import types class Buffer: """A FIFO ring buffer for NumPy arrays of a fixed shape and dtype. Supports random sampling with replacement. """ capa...
pacity: int, sample_shapes: Mapp
ing[str, Tuple[int, ...]], dtypes: Mapping[str, np.dtype], ): """Constructs a Buffer. Args: capacity: The number of samples that can be stored. sample_shapes: A dictionary mapping string keys to the shape of samples associated with that key. ...
emilybache/texttest-runner
src/main/python/storytext/lib/storytext/javarcptoolkit/describer.py
Python
mit
2,499
0.008003
from storytext.javaswttoolkit import describer as swtdescriber from org.eclipse.core.internal.runtime impo
rt InternalPlatform from org.eclipse.ui.forms.widgets import ExpandableComposite import os from pprint import pprint class Describer(
swtdescriber.Describer): swtdescriber.Describer.stateWidgets = [ ExpandableComposite ] + swtdescriber.Describer.stateWidgets swtdescriber.Describer.ignoreChildren = (ExpandableComposite,) + swtdescriber.Describer.ignoreChildren def buildImages(self): swtdescriber.Describer.buildImages(self) ...
Polychart/builder
server/polychartQuery/csv/__init__.py
Python
agpl-3.0
65
0
#!/usr/bin/env python from connection
import Conn as Connection
karrtikr/ete
ete3/tools/ete_extract.py
Python
gpl-3.0
2,246
0.00089
# #START_LICENSE########################################################### # # # This file is part of the Environment for Tree Exploration program # (ETE). http://etetoolkit.org # # ETE is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the...
uerta-Cepas, Joaquin Dopazo and Toni Gabaldon. # ETE: a python Enviro
nment for Tree Exploration. Jaime BMC # Bioinformatics 2010,:24doi:10.1186/1471-2105-11-24 # # Note that extra references to the specific methods implemented in # the toolkit may be available in the documentation. # # More info at http://etetoolkit.org. Contact: huerta@embl.de # # # #END_LICENSE########################...
dwlehman/blivet
blivet/devices/md.py
Python
lgpl-2.1
22,939
0.000915
# devices/md.py # # Copyright (C) 2009-2014 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) any later version. # This program is distributed in the...
D level for this
type of device.""" return mdraid.RAID_levels @level.setter def level(self, value): """ Set the RAID level and enforce restrictions based on it. :param value: new raid level :param type: object :raises :class:`~.errors.DeviceError`: if value does not descri...
keras-team/keras-io
examples/vision/siamese_contrastive.py
Python
apache-2.0
11,646
0.001717
""" Title: Im
age similarity estimation using a Siamese Net
work with a contrastive loss Author: Mehdi Date created: 2021/05/06 Last modified: 2021/05/06 Description: Similarity learning using a siamese network trained with a contrastive loss. """ """ ## Introduction [Siamese Networks](https://en.wikipedia.org/wiki/Siamese_neural_network) are neural networks which share weigh...
tensorflow/hub
tensorflow_hub/compressed_module_resolver.py
Python
apache-2.0
3,271
0.006114
# Copyright 2018 The TensorFlow Hub 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 app...
port hashlib import urllib import tensorflow as tf from tenso
rflow_hub import resolver LOCK_FILE_TIMEOUT_SEC = 10 * 60 # 10 minutes _COMPRESSED_FORMAT_QUERY = ("tf-hub-format", "compressed") def _module_dir(handle): """Returns the directory where to cache the module.""" cache_dir = resolver.tfhub_cache_dir(use_temp=True) return resolver.create_local_module_dir( ...
jart/tensorflow
tensorflow/contrib/data/python/kernel_tests/get_single_element_test.py
Python
apache-2.0
3,539
0.004521
# 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...
taset) with
self.test_session() as sess: if error is None: dense_val, sparse_val = sess.run( element, feed_dict={ skip_t: skip, take_t: take }) self.assertEqual(skip * skip, dense_val) self.assertAllEqual([[skip]], sparse_val.indices) se...
gltn/stdm
stdm/third_party/sqlalchemy/dialects/sqlite/json.py
Python
gpl-2.0
2,292
0
from ... import types as sqltypes class JSON(sqltypes.JSON): """SQLite JSON type. SQLite supports JSON as of version 3.9 through its JSON1_ extension. Note that JSON1_ is a `loadable extension <https://www.sqlite.org/loadext.html>`_ and as such may not be available, or may require run-time loadin...
return value class JSONPathType(_FormatTypeMixin, sqltypes.JSON.JSONPathType): def _format_value(self, value): return "$%s" % ( "".join(
[ "[%s]" % elem if isinstance(elem, int) else '."%s"' % elem for elem in value ] ) )
afunTW/moth-graphcut
src/view/graphcut_app.py
Python
mit
11,346
0.003552
import logging import os import sys import tkinter from tkinter import ttk sys.path.append('../..') import cv2 from src.image.imnp import ImageNP from src.support.tkconvert import TkConverter from src.view.template import TkViewer from src.view.tkfonts import TkFonts from src.view.tkframe import TkFrame, TkLabelFrame ...
kBold.TLabel', theme=theme, font=('', 24, 'bold'), background='white', foreground='black') TTKStyle('H2RedBold.TLabel', theme=theme, font=('', 24, 'bold'), background='white', foreground='red') self.font = TkFonts() # init frame def _init_frame(self): # root self.frame_root = Tk...
0, sticky='news') self.set_all_grid_rowconfigure(self.frame_root, 0, 1, 2) self.set_all_grid_columnconfigure(self.frame_root, 0) # head self.frame_head = TkFrame(self.frame_root, bg='white') self.frame_head.grid(row=0, column=0, sticky='news') self.set_all_grid_rowconfig...
krahman/BuildingMachineLearningSystemsWithPython
ch02/seeds_threshold.py
Python
mit
921
0
# This code is supporting material for the book # Building Machine Learning Systems with Python # by Willi Richert and Luis Pedro Coelho # published by PACKT Publishing # # It is made available under the MIT License from load import load_dataset import numpy as np from threshold import learn_m
odel, apply_model, accuracy features, labels = load_dataset('seeds') # Turn the labels into a binary array labels = (labels == 'Canadian') error = 0.0 for fold in range(10): training = np.ones(len(features), bool) # numpy magic to make an array with 10% of 0s starting at fold training[fold::10] = 0 ...
raining is for testing testing = ~training model = learn_model(features[training], labels[training]) test_error = accuracy(features[testing], labels[testing], model) error += test_error error /= 10.0 print('Ten fold cross-validated error was {0:.1%}.'.format(error))
fujy/ROS-Project
src/rbx2/rbx2_tasks/nodes/patrol_smach_iterator.py
Python
mit
9,741
0.01314
#!/usr/bin/env python """ patrol_smach_iterator.py - Version 1.0 2013-10-23 Control a robot using SMACH to patrol a square area a specified number of times Created for the Pi Robot Project: http://www.pirobot.org Copyright (c) 2013 Patrick Goebel. All rights reserved. This program is free software;...
y.on_shutdown(self.shutdown) # Initialize a number of parameters and variables self.init() # Subscribe to the move_base action server self.move_base = actionlib.SimpleActionClient("move_base", MoveBaseAction) rospy.loginfo("Waiting for move_base action ...
for the action server to become available self.move_base.wait_for_server(rospy.Duration(60)) rospy.loginfo("Connected to move_base action server") # Track success rate of getting to the goal locations self.n_succeeded = 0 self.n_aborted = 0 self.n_preem...
adamgreig/agg-kicad
scripts/check_mod.py
Python
mit
4,233
0
""" check_mod.py Copyright 2015 Adam Greig Licensed u
nder the MIT licence, see LICENSE file for details. Check all footprint files in a directory against a set of consistency fules. """ from __future__ import print_function, division import sys import os import glob from decimal import Decimal import argparse from sexp import parse as sexp_parse def checkrefval(mod...
"value"): continue layer = [n for n in fp_text if n[0] == "layer"][0] if layer[1] != "F.Fab": errs.append("Value and Reference fields must be on F.Fab") if fp_text[1] == "reference" and fp_text[2] != "REF**": errs.append("Reference field must contain REF**") ...