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
movmov/cc
vendor/Twisted-10.0.0/doc/words/examples/jabber_client.py
Python
apache-2.0
881
0.012486
# Copyright (c) 2009 Twisted Matrix Laboratories. # See LICENSE for details. # Originally written by Darryl Vandorp # http://randomthoughts.vandorp.ca/ from twisted.words.protocols.jabber import client, jid from twisted.words.xish import domish from twisted.internet import reactor def authd(xmlstream): p...
nce) xmlstream.addObserver('/message', debug) xmlstream.addObserver('/presence', debug) xmlstream.addObserver('/iq', debug) def debug(elem): print elem.toXml().encode('utf-8') print "="*20 myJid = jid.JID('[email protected]/twisted_words') factory = client.basicClientFactor...
nt/stream/authd',authd) reactor.connectTCP('server.jabber',5222,factory) reactor.run()
bastibl/gnuradio
gr-zeromq/python/zeromq/qa_zeromq_pubsub.py
Python
gpl-3.0
2,008
0.003486
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2014 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio 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...
cv_tb = None def test_001 (self): vlen = 10 src_data = list(range(vlen))*100 src = blocks.vector_source_f(src_data, False, vlen) zeromq_pub_sink = zeromq.pub_sink(gr.sizeof_float, vlen, "tcp://127.0.0.1:0", 0)
address = zeromq_pub_sink.last_endpoint() zeromq_sub_source = zeromq.sub_source(gr.sizeof_float, vlen, address, 1000) sink = blocks.vector_sink_f(vlen) self.send_tb.connect(src, zeromq_pub_sink) self.recv_tb.connect(zeromq_sub_source, sink) self.recv_tb.start() time.s...
smarr/GraalCompiler
mx.graal/mx_graal.py
Python
gpl-2.0
21,852
0.003936
# # ---------------------------------------------------------------------------------------------------- # # Copyright (c) 2007, 2015, Oracle and/or its affiliates. All rights reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # # This code is free software; you can redistribute it and/or modify ...
e forking = True for i in range(len(jmhArgs)): arg = jmhArgs[i] if arg.startswith('-f'): containsF = True if arg == '-f' and (i+1) < len(jmhArg
s): arg += jmhArgs[i+1] try: if int(arg[2:]) == 0: forking = False except ValueError: pass # default to -f1 if not specified otherwise if not containsF: jmhArgs += ['-f1'] # find all projects with a direct ...
f-santos/elasticsearch-dsl-py
test_elasticsearch_dsl/test_search.py
Python
apache-2.0
15,005
0.003932
from copy import deepcopy from elasticsearch_dsl import search, query, Q, DocType, utils def test_execute_uses_cache(): s = search.Search() r = object() s._response = r assert r is s.execute() def test_cache_can_be_ignored(mock_client): s = search.Search(using='mock') r = object() s._re...
x_score', 'max', field='score') d = { 'aggs': { 'per_tag': { 'terms': {'field': 'f'}, 'aggs': {'max_score': {'max': {'field': 'score'}}} } }, 'query': {'match': {'f': 42}} } assert d == s.to_dict() s = search.Search(extr
a={"size": 5}) assert {"query": {"match_all": {}}, "size": 5} == s.to_dict() s = s.extra(from_=42) assert {"query": {"match_all": {}}, "size": 5, "from": 42} == s.to_dict() def test_complex_example(): s = search.Search() s = s.query('match', title='python') \ .query(~Q('match', title='ruby...
sciunto/inforevealer
src/action.py
Python
gpl-2.0
5,161
0.045146
# -*- coding: utf-8 -*- # Inforevealer # Copyright (C) 2010 Francois Boulogne <fboulogne at april dot org> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or...
#find the substitute user command and run the script if pexpect.which('su') != None: message=_("Please, enter the root password.") root_instance
= str(pexpect.which('su')) + " - -c \'"+ os.path.abspath(sys.argv[0])+" --runfile "+ tmp_configfile+"\'" elif pexpect.which('sudo') != None: #TODO checkme message=_("Please, enter your user password.") root_instance = str(pexpect.which('sudo')) + ' ' + os.path.abspath(sys.argv[0])+' --runfile '+ tmp_confi...
FrancoisRheaultUS/dipy
dipy/tracking/tests/test_propagation.py
Python
bsd-3-clause
2,183
0
import numpy as np from dipy.data import default_sphere from dipy.tracking.propspeed import ndarray_offset, eudx_both_directions from numpy.testing import (assert_array_almost_equal, assert_equal, assert_raises, run_module_suite) def stepped_1d(arr_1d): # Make a version of `arr_1d` wh...
here.vertices, 0.5, 0.1, 1., 1., 2) assert_raises(ValueError, eudx_both_directions,
seed, 0, qa, ind[..., ::2], sphere.vertices, 0.5, 0.1, 1., 1., 2) assert_raises(ValueError, eudx_both_directions, seed, 0, qa, ind, sphere.vertices[::2], 0.5, 0.1, 1., 1., 2) if __name__ == '__main__': run_module_suite()
ep0s/soulmaster
menu.py
Python
gpl-3.0
4,205
0.000476
# -*- coding: utf-8 -*- from sdl2 import SDL_Delay,\ SDL_GetTicks,\ SDL_KEYDOWN,\ SDL_KEYUP,\ SDL_QUIT,\ SDL_Rect,\ SDL_RenderCopy,\ SDLK_ESCAPE,\ SDLK_UP,\ SDLK_DOWN,\ SDLK_RETURN,\ SDL_Quit from sdl2.ext import Resources,\ get_events from const import WindowSize, Col...
rsor elif menu_input.was_key_pressed(SDLK_UP): if self.cursor_position != 0: self.cursor_position -= 1 elif menu_input.was_key_pressed(SDLK_DOWN): if self.cursor_position != 2: self.cursor_position += 1 # Select...
if self.cursor_position == 0: self.launch_game() current_time = SDL_GetTicks() # units.MS elapsed_time = current_time - last_update_time # units.MS self.update(min(elapsed_time, MAX_FRAME_TIME)) last_update_time = current_time s...
Balannen/LSMASOMM
atom3/Models/TMWQuestDragonEggActions_MDL.py
Python
gpl-3.0
56,827
0.017632
""" __TMWQuestDragonEggActions_MDL.py_____________________________________________________ Automatically generated AToM3 Model File (Do not modify directly) Author: bogdan Modified: Wed May 2 00:27:03 2018 ______________________________________________________________________________________ """ from stickylink impor...
self.obj104.ID.setValue('R|0') #
name self.obj104.name.setValue('Scout') self.obj104.graphClass_= graph_Role if self.genGraphics: new_obj = graph_Role(190.0,730.0,self.obj104) new_obj.DrawObject(self.UMLmodel) self.UMLmodel.addtag_withtag("Role", new_obj.tag) new_obj.layConstraints = dict() # Graphical Layout C...
brython-dev/brython
www/src/Lib/turtle.py
Python
bsd-3-clause
51,962
0.002656
# A revised version of CPython's turtle module written for Brython # # Note: This version is not intended to be used in interactive mode, # nor use help() to look up methods/functions definitions. The docstrings # have thus been shortened considerably as compared with the CPython's version. # # All public methods/func...
ackground with the given color if color is not None, else return current background color. """ if color is None: return self.background_color self.background_color = color width = _CFG['canvwidth'] height = _CFG['canvheight'] if self.mode() in ['logo',...
/ 2 else: x = 0 y = -height self.frame_index += 1 rect = svg.rect(x=x, y=y, width=width, height=height, fill=color, style={'display': 'none'}) an = svg.animate(Id="animation_frame%s" % self.frame_index, at...
ceph/autotest
frontend/afe/frontend_test_utils.py
Python
gpl-2.0
7,043
0.00213
import atexit, datetime, os, tempfile, unittest import common from autotest_lib.frontend import setup_test_environment from autotest_lib.frontend import thread_local from autotest_lib.frontend.afe import models, model_attributes from autotest_lib.client.common_lib import global_config from autotest_lib.client.common_li...
): """An alternative interface to _create_job""" args = {'hosts' : [], 'metahosts' : []} if use_metahost: args['metahosts'] = hosts else: args['hosts'] = hosts return self._create_job(priority=priority, active=ac
tive, drone_set=drone_set, **args)
jbradberry/django-starsweb
starsweb/tests/test_plugins.py
Python
mit
2,406
0
from __future__ import absolute_import from django
.contrib.auth.models import User from django.test import TestCase from .. import models, plugins class TurnGenerationTestCase(TestCase): def setUp(self): self.plugin = plugins.TurnGeneration()
self.user = User.objects.create_user(username='test', password='password') self.game = models.Game( name="Foobar", slug="foobar", host=self.user, description="This *game* is foobared.", ) self.game.sav...
fzimmermann89/pyload
module/plugins/internal/Captcha.py
Python
gpl-3.0
4,078
0.006866
# -*- coding: utf-8 -*- from __future__ import with_statement import os import time from module.plugins.internal.Plugin import Plugin from module.plugins.internal.utils import encode class Captcha(Plugin): __name__ = "Captcha" __type__ = "captcha" __version__ = "0.47" __status__ = "stable" ...
put :param data: image raw data :param get: get part for request :param post: post part for request
:param cookies: True if cookies should be enabled :param input_type: Type of the Image :param output_type: 'textual' if text is written on the captcha\ or 'positional' for captcha where the user have to click\ on a specific region on the captcha :param ocr: if True, ocr i...
learningequality/kolibri
kolibri/core/analytics/management/commands/benchmark.py
Python
mit
5,977
0.002008
import sys from django.conf import settings from django.core.management.base import BaseCommand from morango.models import InstanceIDModel import kolibri from kolibri.core.analytics import SUPPORTED_OS from kolibri.core.analytics.measurements import get_channels_usage_info from kolibri.core.analytics.measurements imp...
mended channels: 0.01 s * Channels: 0.02 s Device info * Version: (version) * OS: (os) * Installer: (installer) * Database: (database_path) * Device name: ...
_space) * Server time: (server_time) * Server timezone: (server_timezone) """ help = "Outputs performance info and statistics of usage for the running Kolibri instance in this server" def handle(self, *args, **options): if not SUPPORTED_OS: print...
jamtot/HackerEarth
Problems/Small Factorials/smlfc.py
Python
mit
213
0.014085
def fac(n): if n == 0: return 1 else: return n * fac(n-1) def smallfacs(T): for t in xrange(
T):
print fac(int(raw_input())) if __name__ == "__main__": smallfacs(int(raw_input()))
lukasjuhrich/pycroft
setup.py
Python
apache-2.0
2,320
0
""" Pycroft ------- Pycroft is the user management system of the AG DSN (Arbeitsgemeinschaft Dresdner Studentennetz) Notes for developers -------------------- When editing this file, you need to re-build the docker image for the changes to take effect. On a running system, you can just execute ``pip install -e .`` ...
'nose', 'pydot', ], entry_points={ 'console_scripts': [ 'pycroft = scripts.server_run:main', 'pycroft_ldap_sync = ldap_sync.__main__:main', ] }, license="Apache Software License", classifiers=[ 'Development Status :: 3 - Alpha', ...
'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Topic :: Intern...
maxpumperla/hyperas
hyperas/optim.py
Python
mit
11,301
0.002124
import inspect import os import re import sys import nbformat import numpy as np from hyperopt import fmin from nbconvert import PythonExporter from .ensemble import VotingModel from .utils import ( remove_imports, remove_all_comments, extract_imports, temp_string, write_temp_files, determine_indent, with_lin...
space, find_signature_end) sys.path.append(".") def minimize(model, data, algo, max_evals, trials, functions=None, rseed=1337, notebook_name=None, verbose=True,
eval_space=False, return_space=False, keep_temp=False, data_args=None): """ Minimize a keras model for given data and implicit hyperparameters. Parameters ---------- model: A function defining a keras model with hyperas templates, which returns a va...
the-gigi/quote-service
grpc_demo/grpc_quote_server.py
Python
mit
1,420
0.001408
import random from concurrent import futures import time from collections import defaultdict import grpc import sys from pathlib import Path sys.path.insert(0, '') from quote_service_pb2 import QuoteReply from quote_service_pb2_grpc import (add_QuoterServicer_to_server, QuoterSer...
p()) all_authors = tuple(quotes.keys()) class QuoteService(QuoterServicer): def GetQuote(self, request, context): # Choose random author if it re
quested author doesn't has quotes if request.author in all_authors: author = request.author else: author = random.choice(all_authors) # Choose random quote from this author quote = random.choice(quotes[author]) return QuoteReply(quote=quote, author=au...
horazont/aioxmpp
tests/presence/__init__.py
Python
lgpl-3.0
877
0.00114
#
####################################################################### # File name: __init__.py # This file is part of: aioxmpp # # LICENSE # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as # published by the Free Software Foundati...
cense, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have rec...
dimagi/commcare-hq
corehq/apps/data_interfaces/migrations/0006_case_rule_refactor.py
Python
bsd-3-clause
4,903
0.003671
# Generated by Django 1.10.6 on 2017-04-04 12:54 import django.db.models.deletion from django.db import migrations, models import jsonfield.fields class Migration(migrations.Migration): dependencies = [ ('data_interfaces', '0005_remove_match_type_choices'), ] operations = [ migrations....
], options={ 'abstract': False, }, ), migrations.AddField( model_name='automaticupdaterule', name='migrated', field=models.BooleanField(default=False), ), migrations.AddField( model_name='cas...
ey(null=True, on_delete=django.db.models.deletion.CASCADE, to='data_interfaces.ClosedParentDefinition'), ), migrations.AddField( model_name='caserulecriteria', name='custom_match_definition', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCA...
honzamach/pynspect
pynspect/filters.py
Python
mit
10,618
0.005086
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #------------------------------------------------------------------------------- # This file is part of Pynspect package (https://pypi.python.org/pypi/pynspect). # Originally part of Mentat system (https://mentat.cesnet.cz/). # # Copyright (C) since 2016 CESNET, z.s.p.o (h...
. Should be empty, but :return: The time in seconds since the epoch as a floating point number. :rtype: float """ if args: raise FilteringRuleException("The 'time' function does not take any arguments.") return time.time() def grfcbk_utcnow(args): """ Grammar rule function callback:...
ist args: List of function arguments. Should be empty, but :return: Current datetime in UTC timezone. :rtype: datetime.datetime """ if args: raise FilteringRuleException("The 'utcnow' function does not take any arguments.") return datetime.datetime.utcnow() #--------------------------------...
robertmattmueller/sdac-compiler
options.py
Python
gpl-3.0
1,765
0.001133
# -*- coding: utf-8 -*- import argparse import sys def parse_args(): argparser = argparse.ArgumentParser() argparser.add_argument( "domain", help="path to domain pddl file") argparser.add_argument( "task", help="path to task pddl file") argparser.add_argument( "--full-encoding"...
dd_argument( "--viz", action="store_true", help="visualization for evmdd based action cost transformation") argparser.add_argument( "--order", dest="order", help="path to EVMDD variable ordering file") return argparser.parse_args() def copy_args_to_module(args): module_dic...
key] = value def setup(): args = parse_args() copy_args_to_module(args) setup()
fbradyirl/home-assistant
homeassistant/components/mqtt/vacuum/schema_legacy.py
Python
apache-2.0
19,586
0.000817
"""Support for Legacy MQTT vacuum.""" import logging import json import voluptuous as vol from homeassistant.components import mqtt from homeassistant.components.vacuum import ( SUPPORT_BATTERY, SUPPORT_CLEAN_SPOT, SUPPORT_FAN_SPEED, SUPPORT_LOCATE, SUPPORT_PAUSE, SUPPORT_RETURN_HOME, SUPP...
d", SUPPORT_LOCATE:
"locate", SUPPORT_CLEAN_SPOT: "clean_spot", } STRING_TO_SERVICE = {v: k for k, v in SERVICE_TO_STRING.items()} DEFAULT_SERVICES = ( SUPPORT_TURN_ON | SUPPORT_TURN_OFF | SUPPORT_STOP | SUPPORT_RETURN_HOME | SUPPORT_STATUS | SUPPORT_BATTERY | SUPPORT_CLEAN_SPOT ) ALL_SERVICES = ( DE...
fake-name/ReadableWebProxy
WebMirror/management/rss_parser_funcs/feed_parse_extractKoreanovelsCom.py
Python
bsd-3-clause
933
0.030011
def extractKoreanovelsCom(item): ''' Parser for 'koreanovels.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None if item['title'].startswith("Link ") and item['tags'] == ['RSS']: return buildReleaseMessageW...
eton', vol, chp, frag=frag, postfix=postfix, tl_type='translated') if item['title'].startswith("MoS Link ") and item['tags'] == ['RSS']: return buildReleaseMessageWithType(item, 'Master of Strength', vol, chp, frag=frag, postfix=postfix, tl_type='transl
ated') tagmap = [ ('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel'), ] for tagname, name, tl_type in tagmap: if tagname in item['tags']: return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type) retur...
crossbario/crossbar-examples
prompt/cbf.py
Python
apache-2.0
3,778
0.006617
import click from click_repl import register_repl class CmdGlobal(object): def __init__(self): self.current_resource_type = None self.current_resource = None def __str__(self): return 'CmdGlobal(current_resource_type={}, current_resource={})'.format(self.current_resource_type, self.cu...
@click.option( '--name', required=True ) @click.pass_obj def cmd_start_realm(cfg, resource, name): pass #@click.command() #@click.option('--count', default=1, help='Number of greetings.') #@click.option('--name', prompt='Your name',
# help='The person to greet.') #def hello(count, name): # """Simple program that greets NAME for a total of COUNT times.""" # for x in range(count): # click.echo('Hello %s!' % name) register_repl(cli) if __name__ == '__main__': cli()
xuweiliang/Codelibrary
openstack_dashboard/dashboards/admin/systemlogs/trans.py
Python
apache-2.0
6,683
0.004938
__author__ = 'Zero' from django.utils.translation import pgettext_lazy STATUS_DISPLAY_CHOICES = ( ("CREATE INSTANCE", pgettext_lazy("Action of an Instance", u"Create Instance")), ("DELETE INSTANCE", pgettext_lazy("Action of an Instance", u"Delete Instance")), ("UPDATE INSTANCE", pgettext_lazy("Action of an...
", pgettext_lazy("Action of a volume", u"Delete Volume")), ("UPDATE VOLUME", pgettext_lazy("Action of a volume", u"Update Volume")), ("UPDATE VOLUME STATUS", pgettext_lazy("Action of a volume", u"Update Volume Status")), ("CREATE VOLUME SNAPSHOT", pgettext_lazy("Action of a volume", u"Create
Volume Snapshot")), ("DELETE VOLUME SNAPSHOT", pgettext_lazy("Action of a volume", u"Delete Volume Snapshot")), ("UPLOAD IMAGE TO VOLUME", pgettext_lazy("Action of a volume", u"Upload Image To Volume")), ("REGISTER LICENSE", pgettext_lazy("Action of admin", u"Register License")), ("ADD AGENT", pgettext...
jmartinz/pyCrawler
10.contratacionE/pce_extrae_detalle_contrato.py
Python
apache-2.0
7,393
0.010299
# coding=utf-8 # -*- coding: utf-8 -*- from selenium import webdriver from selenium.common.exceptions import NoSuchElementException, TimeoutException from bs4 import BeautifulSoup from datetime import datetime from decimal import * import sys #phantonPath = "/home/jmartinz/00.py/phantomjs/phantomjs" phantonPath = "...
f.cargaPagina() #Introduce contrato contrato = self.driver.find_element_by_id('viewns_Z7_AVEQAI930OBRD02JPMTPG21004_:form1:text71ExpMAQ') contrato.send_keys(self.numExpediente) #Introduce ´organo contrataci´on orgcont = self.driver.find_element_by_id('viewns_Z7_AVEQAI930OBRD02J...
end_keys(self.OrgContratacion) # pulsa el botón de buscar self.driver.find_element_by_id('viewns_Z7_AVEQAI930OBRD02JPMTPG21004_:form1:button1').click() #Obtener enlace self.driver.find_element_by_id('viewns_Z7_AVEQAI930OBRD02JPMTPG21004_:form1:enlaceExpediente_0').click() #sólo sirve...
putcn/Paddle
python/paddle/fluid/tests/unittests/test_parallel_executor_fetch_feed.py
Python
apache-2.0
4,981
0.000201
# Copyright (c) 2018 PaddlePaddle 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 appli...
up): data = fluid.layers.data( name='image', shape=[3, 224, 224], dtype='float32') label = fluid.layers.data( name='label', shape=[1], dtype='int64') out = Lenet(data, class_dim=102) loss = fluid.layers.cross_entropy...
opt = fluid.optimizer.Momentum( learning_rate=0.1, momentum=0.9, regularization=fluid.regularizer.L2Decay(1e-4)) opt.minimize(loss) place = fluid.CUDAPlace(0) feeder = fluid.DataFeeder(place=place, feed_list=[data, label]...
bastorer/SPINSpy
matpy/__init__.py
Python
mit
506
0.011858
# Initialization for pack
age.
__author__ = "Ben Storer <[email protected]>" __date__ = "29th of April, 2015" # Read in the defined functions. Not strictly necessary, # but makes usage nicer. i.e. now we can use # matpy.cheb(5) instead of matpy.cheb.cheb(5). from .cheb import cheb from .darkjet import darkjet #from .circular_map import circul...
aacoppa/inglorious-gangsters
weather.py
Python
mit
601
0.021631
import urllib2,json def almanac(zip): url = "http://api.wunderground.com/api/4997e70515d4c
bbd/almanac/q/%d.json"%(zip) r = urllib2.urlopen(url) data = json.loads(r.read()) almanac = {"record low":data['almanac']['temp_low']['record']['F'].encode("ascii"), "record high":data['almanac']['temp_high']['record']['F'].encode("ascii"), "normal low":data['almanac']['temp_
low']['normal']['F'].encode("ascii"), "normal high":data['almanac']['temp_high']['normal']['F'].encode("ascii") } return almanac print(almanac(11214))
JohnKendrick/PDielec
PDielec/GUI/NoteBook.py
Python
mit
21,778
0.009505
import sys import copy import psutil import os from PyQt5.QtWidgets import QWidget, QTabWidget from PyQt5.QtWidgets import QVBoxLayout from PyQt5.QtWidgets import QApplication from PyQt5.QtWidgets import QFileDialog from PyQt5.QtWid...
layout.addWidget(self.tabs) self.setLayout(self.layout) de
bugger.print('Finished:: Initialising') return def requestRefresh(self): debugger.print('Start:: requestRefresh') self.refreshRequired = True debugger.print('Finished:: requestRefresh') return def addScenario(self,scenarioType=None,copyFromIndex=-2): """Add Scen...
pmaidens/CMPUT404-project
BloggingAPI/BloggingAPI/migrations/0004_auto_20160331_0018.py
Python
apache-2.0
432
0
# -*- coding: utf-8
-*- # Generated by Django 1.9 on 2016-03-31 00:18 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('BloggingAPI', '0003_post_image'), ] operations = [ migrations.RenameField( model_name='friend'...
ame='display_name', new_name='displayName', ), ]
alonbl/ovirt-host-deploy
src/plugins/ovirt-host-common/hosted-engine/configureha.py
Python
lgpl-2.1
3,975
0
# # ovirt-host-deploy -- ovirt host deployer # Copyright (C) 2015 Red Hat, Inc. # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) ...
ycons.FileLocations.HOSTED_ENGINE_CONF, content='', modifiedList=self.environment[ otopicons.CoreEnv.MODIFIED_FILES ], ), ) @plugin.event( stage=plugin.Stages.STAGE_MISC, condition=lambda self: self.environment[...
set_ha_conf(self): self.logger.info(_('Updating hosted-engine configuration')) content = ( 'ca_cert={ca_cert}\n' ).format( ca_cert=os.path.join( odeploycons.FileLocations.VDSM_TRUST_STORE, odeploycons.FileLocations.VDSM_SPICE_CA_FILE ...
michaelarnauts/home-assistant
homeassistant/components/light/demo.py
Python
mit
1,834
0
""" homeassistant.components.light.demo ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Demo platform that implements lights. """ import random from homeassistant.components.light import ( Light, ATTR_BRIGHTNESS, ATTR_XY_COLOR) LIGHT_COLORS = [ [0.861, 0.3259], [0.6389, 0.3028], [0.1684, 0.0416] ] def setup_...
property def name
(self): """ Returns the name of the device if any. """ return self._name @property def brightness(self): """ Brightness of this light between 0..255. """ return self._brightness @property def color_xy(self): """ XY color value. """ return self._xy @...
davidcaste/fabtools
fabtools/require/python.py
Python
bsd-2-clause
6,264
0.000798
""" Python environments and packages ================================ This module provides high-level tools for using Python `virtual environments`_ and installing Python packages using the `pip`_ installer. .. _virtual environments: http://www.virtualenv.org/ .. _pip: http://www.pip-installer.org/ """ from fabtool...
.system import UnsupportedFamily, distrib_family MIN_SETUPTOOLS_VERSION = '0.7' MIN_PIP_VE
RSION = '1.5' def setuptools(version=MIN_SETUPTOOLS_VERSION, python_cmd='python'): """ Require `setuptools`_ to be installed. If setuptools is not installed, or if a version older than *version* is installed, the latest version will be installed. .. _setuptools: http://pythonhosted.org/setuptool...
ducky64/labelmaker
labelmaker.py
Python
gpl-2.0
5,429
0.016025
import argparse import csv import codecs import configparser import xml.etree.ElementTree as ET import re from SvgTemplate import SvgTemplate, TextFilter, ShowFilter, BarcodeFilter, StyleFilter, SvgFilter from SvgTemplate import clean_units, units_to_pixels, strip_tag class LabelmakerInputException(Exception): pass...
help="CSV data") parser.add_argument('output', type=str, help="SVG generated labels output") parser.add_argument('--on
ly', type=str, default=None, help="only process rows which have this key nonempty") parser.add_argument('--start_row', type=int, default=0, help="starting row, zero is topmost") parser.add_argument('--start_col', type=int, default=0, help="starting c...
iaddict/mercurial.rb
vendor/mercurial/tests/silenttestrunner.py
Python
mit
593
0.003373
import unittest, sys def main(modulename): '''run the tests found in module, printing nothing when all tests pass''' module = sys.modules[modulename] suite = unittest.defaultTestLoader.loadT
estsFromModule(module) results = unittest.TestResult() suite.run(results) if results.errors or results.failures: for tc, exc in results.errors: print 'ERROR:', tc print sys.stdout.write(exc) for tc, exc in results.failures: print 'FAIL:', tc ...
yamt/tempest
tempest/services/compute/json/images_client.py
Python
apache-2.0
5,741
0
# Copyright 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 requ...
sponseBody(resp, body['meta']) def delete_image_metadata_item(self, image_id, key): """Deletes a single image metadata key/value pair.""" resp, body = self.delete("images/%s/metadata/%s" % (str(image_i
d), key)) self.validate_response(schema.delete, resp, body) return service_client.ResponseBody(resp, body) def is_resource_deleted(self, id): try: self.show_image(id) except lib_exc.NotFound: return True return False @property def resource_ty...
dockerera/func
func/minion/AuthedXMLRPCServer.py
Python
gpl-2.0
5,696
0.00316
# This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # bu...
cketServer class AuthedSimpleXMLRPCRequestHandler(SimpleXMLRPCServer.SimpleXMLRPCRequestHandler): # For some reason, httplib closes the connection right after headers # have been sent if the connection is _not_ HTTP/1.1, which results in # a "Bad file descriptor" error when the client tries to read from ...
sure WHY this is, but this is backed up by comments in socket.py and SSL/connection.c """ self.connection = self.request # for doPOST self.rfile = socket._fileobject(self.request, "rb", self.rbufsize) self.wfile = socket._fileobject(self.request, "wb", self.wbufsize) def do...
Elbandi/PyMunin
pysysinfo/phpfpm.py
Python
gpl-3.0
2,487
0.006836
"""Implements PHPfpmInfo Class for gathering stats from PHP FastCGI Process Manager using the status page. The status interface of PHP FastCGI Process Manager must be enabled. """ import re import util __author__ = "Ali Onur Uyar" __copyright__ = "Copyright 2011, Ali Onur Uyar" __credits__ = [] __license__ = "GPL...
am monpath: PHP FPM path relative to Document Root. (Default: fpm_status.php) @param ssl: Use SSL if True. (Default: False) """ if host is not None: self._host = host else: self._host = '127.0.0.1' if port is no...
self._user = user self._password = password if ssl: self._proto = 'https' else: self._proto = 'http' if monpath: self._monpath = monpath else: self._monpath = 'fpm_status.php' def getStats(self): """Query and par...
brahle/fitmarket-python-api
test/test_status_api.py
Python
apache-2.0
2,605
0.001543
# coding: utf-8 """ Fitmarket Mali broj ljudi - donori - dijele dnevna mjerenja svoje težine. Iz dnevne težine jednog donora određujemo vrijednosti dviju dionica: - dionica X ima vrijednost koja odgovara težini donora na taj dan. - inverzna dionica ~X ima vrijednost (150 kg - X). Primjetimo da: - kako X r...
sa trenutnim cijenama svih dionica. """ pass def test_mystate_get(self): """ Test case for mystate_get Dohvaca JSON koji prikazuje korisnikovu ukupnu vrijednost, neinvestiranu vrijednost i vrijednosti investirane u dionice. """ pass def test_plot_txt_g...
for plot_txt_get Dohvaca CSV sa cijenama svih dionica u svim prijasnjim mjerenjima. """ pass if __name__ == '__main__': unittest.main()
jenniferwx/Programming_Practice
FindNextHigherNumberWithSameDigits.py
Python
bsd-3-clause
578
0.020761
''' Given a number, find the next higher number using only the digits in the given number. For example if the given number is 1234, next higher number with same digits is 1243 ''' def F
indNext(num): number = str(num) length = len(number)
for i in range(length-2,-1,-1): current = number[i] right = number[i+1] if current < right: temp = sorted(number[i:]) Next = temp[temp.index(current)+1] temp.remove(Next) temp = ''.join(temp) return int(number[:i]+Next+temp) return num ...
ThomasMarcel/webapp-course
resources/gae-boilerplate/bp_includes/external/babel/messages/tests/checkers.py
Python
apache-2.0
12,764
0.012614
# -*- coding: utf-8 -*- # # Copyright (C) 2008 Edgewall Software # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at http://babel.edgewall.org/wiki/License. # # This software consists of v...
e TestProject # project. # FIRST AUTHOR <EMAIL@ADDRESS>, 2007. # msgid "" msgstr "" "Project-Id-Version: TestProject 0.1\n" "Report-Msgid-Bugs-To: [email protected]\n" "POT-Creation-Date: 2007-04-01 15:30+0200\n" "PO-Revision-Date: %(date)s\n" "Last-Translator: FULL NAME <EMAIL@ADDRESS>\n" "Language-Team: %(locale...
nt-Transfer-Encoding: 8bit\n" "Generated-By: Babel %(version)s\n" #. This will be a translator comment, #. that will include several lines #: project/file1.py:8 msgid "bar" msgstr "" #: project/file2.py:9 msgid "foobar" msgid_plural "foobars" msgstr[0] "" msgstr[1] "" msgstr[2] "" """ % dict(locale = _locale, ...
harikvpy/django-popupcrud
demo/library/migrations/0002_auto_20170919_0319.py
Python
bsd-3-clause
2,833
0.003177
# -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2017-09-19 03:19 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('library', '0001_initial'), ] operations = [ ...
'verbose_name': 'Author Ratings', },
), migrations.CreateModel( name='BookRating', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('rating', models.CharField(choices=[('1', '1 Star'), ('2', '2 Stars'), ('3', '3 Stars'), ('4', '4 Sta...
whav/hav
src/hav/apps/webassets/management/commands/recreate_webassets.py
Python
gpl-3.0
3,208
0.000935
from django.core.management.base import BaseCommand, CommandError from django.db.models import Q from django.template.defaultfilters import filesizeformat from hav.apps.media.models import Media from hav.apps.hav_collections.models import Collection from hav.apps.archive.models import ArchiveFile from ...tasks import c...
with=ext) archived_files = archived_files.filter(q) return archived_files def process_file(self, archived_file): a
rchived_file.webasset_set.all().delete() create.delay(archived_file.pk) def handle(self, *args, **options): # gather all options to limit the resulting queryset media_ids = options.get("media", []) collection_slugs = options.get("collection", []) extensions = options.get("ex...
qedsoftware/commcare-hq
corehq/apps/accounting/migrations/0019_remove_softwareplanversion_product_rates.py
Python
bsd-3-clause
392
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations class Migration(migrati
ons.Migration): dependencies = [ ('accounting', '0018_datamigration_product_rates_to_
product_rate'), ] operations = [ migrations.RemoveField( model_name='softwareplanversion', name='product_rates', ), ]
BeenzSyed/tempest
tempest/services/compute/xml/tenant_usages_client.py
Python
apache-2.0
1,915
0
# Copyright 2013 NEC Corporation # 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 ...
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 urllib from lxml import etree from tempest.common.rest_client import RestClientXML from t
empest.services.compute.xml.common import xml_to_json class TenantUsagesClientXML(RestClientXML): def __init__(self, config, username, password, auth_url, tenant_name=None): super(TenantUsagesClientXML, self).__init__(config, username, password, auth_ur...
OtagoPolytechnic/LanguageCards
admin/wordproject/migrations/0002_auto_20160331_1111.py
Python
mit
464
0
# -*- coding: utf-8 -*- # Generated by Django 1.9.4 on 2016-03-30 22:11 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migrat
ion): dependencies = [ ('wordproject', '0001_initial'), ] operations = [ migrations.AlterFi
eld( model_name='wordrecord', name='description', field=models.TextField(max_length=200, null=True), ), ]
IPFR33LY/EverwingHax
Everwing_data.py
Python
mit
8,827
0.002606
from ast import literal_eval from json import dumps, loads from urllib2 import Request, urlopen from requests import post, get from p3lzstring import LZString def user_input(data): i = 0 while i < len(data): if 'xp' in data[i]['dragondata']['sidekick_name'][9:][5:]: data[i]['d...
state_dict['instances'][key] = list[x][XP] i = i
+ 1 return 'THIS IS IT' def build_state_dict(list): i = 0 while i < len(list): try: if list[i]["Maturity"]: key_index = list[i]['Maturity']['key'] rebuild_loop(key_index, list, i, maturity='Maturity', XP=2) pass excep...
ramonsaraiva/sgce
sgce/person/views.py
Python
mit
1,162
0.024138
# -*- coding: utf-8 -* from django.views.generic.edit import CreateView from person.models import Person from person.forms import PersonForm from django.contrib.auth import authenticate, login as auth_login, logout as auth_logout from django.shortcuts import render_to_response, redirect from django.template import Req...
me'] password = request.POST['password'] if not request.user.is_authenticated(): user = authenticate(username=username, password=password) if user is not None: if user.is_active: auth_login(request, user); if user.stype == 'P': return redirect('/sgceusr/') elif user.stype == 'O' or user....
return redirect('/sgceman/') else: context['error'] = 'Usuário inativo' else: context['error'] = 'Usuário ou senha incorretos' return render_to_response('person/login.html', context, RequestContext(request))
fraserphysics/F_UNCLE
F_UNCLE/Models/Ptw.py
Python
gpl-2.0
14,166
0.000141
# !/usr/bin/pthon2 """Preston-Tonks-Wallace Flow Stress Model This module implements the PTW flow stress model Authors ------- - Stephen A. Andrews (SA) - Diane E. Vaughan (DEV) Version History --------------- 0.0: 13/05/2016 - Initial class creation References ---------- [1] Preston, D. L.; Tonks, D. L. & Wall...
- (s_o - s_inf) * erf_psi_norm shock_flow_stress = s_o * psi_norm**beta glide_yield_stress = y_o - (y_o - y_inf) * erf_psi_norm shock_yield_stress = y_1 * psi_norm**y_2 flow_stress = max((glide_flow_stress, sh
ock_flow_stress)) yield_stress = max((glide_yield_stress, min((shock_yield_stress, shock_flow_stress)))) flow_stress *= g_modu yield_stress *= g_modu return flow_stress, yield_stress def get_stress_strain(self, temp, strain_rate, material, min_strain=0....
dabura667/electrum
lib/transaction.py
Python
mit
35,844
0.003348
#!/usr/bin/env python # # Electrum - lightweight Bitcoin client # Copyright (C) 2011 Thomas Voegtlin # # 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...
self.reverseLookup = reverseLookup def __getattr__(self, attr): if attr not in self.lookup: raise AttributeError return self.lookup[attr] def whatis(self, value): return self.reverseLookup[value] # This function comes from
bitcointools, bct-LICENSE.txt. def long_hex(bytes): return bytes.encode('hex_codec') # This function comes from bitcointools, bct-LICENSE.txt. def short_hex(bytes): t = bytes.encode('hex_codec') if len(t) < 11: return t return t[0:4]+"..."+t[-4:] opcodes = Enumeration("Opcodes", [ ("OP_0...
dualphase90/Learning-Neural-Networks
deep_net.py
Python
mit
2,387
0.016757
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("/tmp/data/", one_hot = True) n_nodes_hl1 = 500 n_nodes_hl2 = 500 n_nodes_hl3 = 500 n_classes = 10 batch_size = 100 x = tf.placeholder('float', [None, 784]) y = tf.placeholder('float') def neural_net...
n_2_layer['weights']), hidden_2_layer['biases']) l2 = tf.nn.relu(l2) l3 = tf.add(tf.matmul(l2,hidden_3_layer['weights']), hidden_3_layer['biases']) l3 = tf.nn.relu(l3) output = tf.matmul(l3,o
utput_layer['weights']) + output_layer['biases'] return output def train_neural_network(x): prediction = neural_network_model(x) cost = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(prediction,y) ) optimizer = tf.train.AdamOptimizer().minimize(cost) hm_epochs = 10 with tf.Sessio...
mrachinskiy/jewelcraft
lib/ui_lib.py
Python
gpl-3.0
1,174
0
# ##### BEGIN GP
L LICENSE BLOCK ##### # # JewelCraft jewelry design toolkit for Blender. # Copyright (C) 2015-2022 Mikhail Rachinskiy # # 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 ...
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 have received a copy of the GNU General Public License # along with this program. If no...
SNoiraud/gramps
gramps/gen/filters/rules/repository/_matchesnamesubstringof.py
Python
gpl-2.0
1,903
0.005255
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2011 Helge Herz # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option)...
Of(Rule): """Repository name containing <substring>""" labels = [ _('Text:')] name = _('Repositories with name containing <text>') description = _("Matches repositories whose name contains a certain s
ubstring") category = _('General filters') allow_regex = True def apply(self, db, repository): """ Apply the filter """ return self.match_substring(0, repository.get_name())
DEVSENSE/PTVS
Python/Templates/Web/ProjectTemplates/Python/Web/PollsFlaskJade/PollsFlaskJade/models/azuretablestorage.py
Python
apache-2.0
4,285
0.0014
""" Repository of polls that stores data in Azure Table Storage. """ from azure import WindowsAzureMissingResourceError from azure.storage import TableService from . import Poll, Choice, PollNotFound from . import _load_samples_json def _partition_and_row_to_key(partition, row): """Builds a poll/choice key out o...
self.svc.update_entity(self.choice_table, partition, row, entity) except WindowsAzureMissingResourceError: raise PollNotFound() def add_sample_polls(self): """Adds a set of polls from data stored in a samples.json file.""" poll_partition = '2014' poll_row = 0 ...
in _load_samples_json(): poll_entity = { 'PartitionKey': poll_partition, 'RowKey': str(poll_row), 'Text': sample_poll['text'], } self.svc.insert_entity(self.poll_table, poll_entity) for sample_choice in sample_poll['choice...
cpaulik/xray
xray/core/dataarray.py
Python
apache-2.0
41,458
0.000169
import contextlib import functools import warnings import numpy as np import pandas as pd from ..plot.plot import _PlotMethods from . import indexing from . import groupby from . import ops from . import utils from . import variable from .alignment import align from .common import AbstractArray, BaseDataObject from ...
elf.data_array.dims, key)) def __getitem__(self, key): return self.data_array[self._remap_key(key)] def __setitem__(self, key, value): self.data_array[self._remap_key(key)] = value class DataArray(AbstractArray, BaseDataObject): """N-dimensional array with labeled coordinates and dimensi...
es to support metadata aware operations. The API is similar to that for the pandas Series or DataFrame, but DataArray objects can have any number of dimensions, and their contents have fixed data types. Additional features over raw numpy arrays: - Apply operations over dimensions by name: ``x.sum(...
codeforanchorage/collective-development
app/mod_proposal/constants.py
Python
mit
219
0.004566
# Place within a proposal lif
e cycle LIFE_ORIGIN = 1 LIFE_PLANNING = 2 LIFE_CLASS = 3 LIFE_FINISHED =
4 IS_COLLECTION = 100 # Source of a proposal SOURCE_UNKNOWN = 0 SOURCE_WEBSITE = 1 SOURCE_API = 2 SOURCE_OFFLINE = 3
wontfix-org/wtf
wtf/services.py
Python
apache-2.0
6,365
0.000314
# -*- coding: ascii -*- # # Copyright 2006-2012 # Andr\xe9 Malo or his licensors, as applicable # # 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-...
uld just be returned, the initialized middleware (wrapping `func`) otherwise. :rtype: ``callable`` """ class ServiceManager(object): """ Service manager :IVariables: - `_finalized`: Manager was finalized - `_down`: Manager was shut down - `...
- `_services`: ``list`` """ _finalized, _down, _services = False, False, () def __init__(self): """ Initialization """ self._services = [] def __del__(self): """ Destruction """ self.shutdown() def finalize(self): """ Lock the manager. No more services ...
ecreall/lagendacommun
lac/content/artist.py
Python
agpl-3.0
7,788
0.000257
# Copyright (c) 2016 by Ecreall under licence AGPL terms # available on http://www.gnu.org/licenses/agpl.html # licence: AGPL # author: Amen Souissi import colander import deform import hashlib from functools import reduce from zope.interface import implementer from substanced.schema import NameSchemaNode from subst...
reindex() self.setproperty('productions', []) for connection in self.co
nnections_to: if connection not in connections_to: source.addtoproperty('connections_to', connection) self.setproperty('connections_to', []) for branch in self.branches: source.addtoproperty('branches', branch) original = self.ori...
babbel/floto
tests/unit/specs/task/test_child_workflow.py
Python
mit
2,677
0.00635
import pytest import floto.specs.task @pytest.fixture def child_workflow(): retry_strategy = floto.specs.retry_strategy.Strategy() cw = floto.specs.task.ChildWorkflow(workflow_type_name='wft_name', workflow_type_version='wft_version', ...
n='wft_version',
domain='d', input={'foo': 'bar'}) assert cw.id_ == 'did' def test_deserialized(self, serialized_child_workflow): cw = floto.specs.task.ChildWorkflow.deserialized(**seri...
faithsws/WWR
WeixinPlugin/WeixinPlugin.py
Python
mit
3,338
0.042241
''' Created on 2014-9-3 @author: songwensheng ''' import WeixinIF from lxml import etree import sys import os import web import time import tts class WxTextPlugin(WeixinIF.TextPlugin): def __init__(self,xml,ctx,usr): WeixinIF.TextPlugin.__init__(self, xml, ctx) self.FromUser = usr self.ToUs...
in,tips): WeixinIF.State.__init__(self,plugin,tips) def Enter(self,plugin,text): return plugin.render.reply_FirstState(plugin,"enter "+text + " Mode",int(time.time())) def Process(self,plugin,text): file = tts.GetAac(text) #xml = plugin.render.reply_TTS(plugin,text,"http://mc.fai...
/"+file,int(time.time())) #print(xml) #return xml return plugin.render.reply_FirstState(plugin,file,int(time.time())) def Leave(self,plugin,text): return plugin.render.reply_FirstState(plugin,"leave "+text,int(time.time())) class SecondState(WeixinIF.State): def __init__(self,plugin,...
phil65/script.home
TrailerWindow.py
Python
gpl-2.0
2,625
0.001524
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2014 Philipp Temminghoff ([email protected]) # # 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 ...
the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # import xbmcaddon import xbmcgui from Utils import * __addon__ = xbmcaddon.Addon() __addonid__ = __addon__.get...
sgp715/simple_image_annotator
app.py
Python
mit
3,289
0.008209
import sys from os import walk import imghdr import csv import argparse from flask import Flask, redirect, url_for, request from flask import render_template from flask import send_file app = Flask(__name__) app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0 @app.route('/tagger') def tagger(): if (app.config["HEAD"] =...
AD"] = 0 if args.out == None: app.config["OUT"] = "out.csv" else: app.config["OUT"] = args.out p
rint(files) with open("out.csv",'w') as f: f.write("image,id,name,xMin,xMax,yMin,yMax\n") app.run(debug="True")
tiagochiavericosta/edx-platform
openedx/core/djangoapps/credit/models.py
Python
agpl-3.0
24,095
0.001494
# -*- coding: utf-8 -*- """ Models for Credit Eligibility for courses. Credit courses allow students to receive university credit for successful completion of a course on EdX """ import datetime from collections import defaultdict import logging import pytz from django.conf import settings from django.core.cache im...
ple_history.models import HistoricalRecords from jsonfield.fields import JSONField from model_utils.models import TimeStampedModel from xmodule_django.models import CourseKeyField from django.utils.translation import ugettext_lazy log = lo
gging.getLogger(__name__) class CreditProvider(TimeStampedModel): """ This model represents an institution that can grant credit for a course. Each provider is identified by unique ID (e.g., 'ASU'). CreditProvider also includes a `url` where the student will be sent when he/she will try to get cr...
bmz0/project0
test/world/circle.py
Python
gpl-3.0
817
0.00612
# encoding: utf-8 from pygame import Surface, Rect from pygame.draw import circle as drawCircle from pygame.sprite import Sprite from random import randint from test.config import * class circle(Sprite): def __init__(self, x=0, y=0, *args): Sprite.__init__(self, *args) self.x, self.y = x
, y self.radius = radiusMin self.color = randint(1, 255), randint(1, 255), randint(1, 255), randint(92, 208) self.redraw() def redraw(self): self.image = Surface((s
elf.radius * 2,) * 2).convert_alpha() self.image.fill((0,) * 4) self.rect = self.image.get_rect() self.rect.centerx = self.x self.rect.centery = self.y drawCircle(self.image, (255,)*3, (self.radius, self.radius), self.radius) drawCircle(self.image, self.color, (self.radius, self.radius), self.ra...
odtvince/APITaxi
APITaxi/tasks/clean_geoindex.py
Python
agpl-3.0
1,030
0.005825
from ..extensions import celery, redis_store from ..models.taxis import Taxi import time from flask import current_app @celery.task def clean_geoindex(): keys_to_clean = [] cursor = 0 taxi_id =
set() cursor = None while cursor != 0: if cursor == None: cursor = 0 cursor, result = redis_store.scan(cursor, 'taxi:*') pipe = redis_store.pipeline() for key in result: pipe.hvals(key) values = pipe.execute() lower_bound = int(time.time()...
0 * 60 pipe = redis_store.pipeline() for (key, l) in zip(result, values): if any(map(lambda v: Taxi.parse_redis(v)['timestamp'] >= lower_bound, l)): continue pipe.zrem(current_app.config['REDIS_GEOINDEX'], key) pipe.execute() #Maybe it'll more efficient to...
thtrieu/essence
src/modules/recurring.py
Python
gpl-3.0
2,099
0.008576
from .module import Module from src.utils import xavier, guass import numpy as np from .activations import * class Recurring(Module): """ Recurring is a type of module that cache intermediate activations in a stack during unrolling of recurrent layers Its backward() is expected to be called
several times during Back Propagation Through Time, either full or truncated. """ def __init__(self, *args, **kwargs): self._stack = list() self._setup(*args, **kwargs) def _setup(*args, **kwargs): pass def _push(self, *objs): objs = list(objs) if len(objs)...
k.append(objs) def _pop(self): objs = self._stack[-1] del self._stack[-1] return objs def flush(self): self._stack = list() self._flush() def _flush(self): pass class gate(Recurring): """ Gates are special case of Recurring modules It star...
FermiParadox/ipy_student_exercises
never_importer.py
Python
mit
384
0.002604
# DO NOT IMPORT ANY PROJECT MODULES HERE # to avoid circular imports. # DO NOT MOVE THIS FILE; IT MUST REMAIN INSIDE THE PROJECT FOLDER (check below) import os # WARNING: project-path assumes this file is in the project folder itself. CURRENT_F
ILE_PATH = os.path.abspath(__file__) PROJECT_PATH = os.path.dirname(CURRENT_FILE_PATH) PROJECT_PARENT_PATH = os.pat
h.dirname(PROJECT_PATH)
nkoech/trialscompendium
trialscompendium/search/api/views.py
Python
mit
109
0
from .globalsearch.globalsearchviews imp
ort global_search_views global_search_views = global
_search_views()
callidus/PyKMIP
kmip/tests/unit/core/factories/payloads/test_request.py
Python
apache-2.0
6,504
0
# Copyright (c) 2014 The Johns Hopkins University/Applied Physics Laboratory # 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/LICEN...
PayloadFactory, self).setUp() self.factory = RequestPayloadFactory() def tearDown(self): super(TestRequestPayloadFactory, self).tearDown() def _test_not_implemented(self, func, args): self.assertRaises(NotImplementedError, func, args) def _test_payload_type(self, payloa
d, payload_type): msg = "expected {0}, received {1}".format(payload_type, payload) self.assertIsInstance(payload, payload_type, msg) def test_create_create_payload(self): payload = self.factory.create(Operation.CREATE) self._test_payload_type(payload, create.CreateRequestPayload) ...
bsipocz/astropy
astropy/visualization/stretch.py
Python
bsd-3-clause
15,324
0
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ Classes that deal with stretching, i.e. mapping a range of [0:1] values onto another set of [0:1] values with a transformation """ import numpy as np from .transform import BaseTransform from .transform import CompositeTransform __all__ = ["BaseSt...
dStretch", "LogStretch", "AsinhStretch", "SinhStretch", "HistEqStretch", "ContrastBiasStretch", "CompositeStretch"] def _logn(n, x, out=None): """Calculate the log base n of x.""" # We define this because numpy.lib.scimath.logn doesn't support out= if out is
None: return np.log(x) / np.log(n) else: np.log(x, out=out) np.true_divide(out, np.log(n), out=out) return out def _prepare(values, clip=True, out=None): """ Prepare the data by optionally clipping and copying, and return the array that should be subsequently used for i...
fdiehl/apsis
code/apsis/tests/test_models/test_experiment.py
Python
mit
4,273
0.000936
__author__ = 'Frederik Diehl' from apsis.models.experiment import Experiment from nose.tools import assert_equal, assert_raises, assert_dict_equal, \ assert_true, assert_false from apsis.models.candidate import Candidate from apsis.models.parameter_definition import * class TestExperiment(object): exp = None ...
experiment" param_def = { "x": MinMaxNumericParamDef(0, 1), "name": NominalParamDef(["A", "B", "C"]) } param_def_wrong = { "x": MinMaxNumericParamDef(0, 1), "name": ["A", "B", "C"] } minimization = True self.exp = Experiment...
ion_problem, minimization) with assert_raises(ValueError): Experiment("fails", False) with assert_raises(ValueError): Experiment("fails too", param_def_wrong) def test_add(self): cand = Candidate({"x": 1, "name": "A"}) cand_invalid = Candidate({"x": 1}) ...
akretion/delivery-carrier
base_delivery_carrier_label/tests/__init__.py
Python
agpl-3.0
30
0
from . import test_ge
t_weight
Debian/debsources
lib/debsources/tests/test_archiver.py
Python
agpl-3.0
6,666
0.0012
# Copyright (C) 2014-2021 The Debsources developers # <[email protected]>. # See the AUTHORS file at the top-level directory of this distribution and at # https://salsa.debian.org/qa/debsources/blob/master/AUTHORS # # This file is part of Debsources. Debsources is free software: you can # redistrib...
on package %s/%s" % (package, version) ) def assertHasStickyPackage(self, p
ackage, version): p = self.assertHasPackage(package, version) self.assertTrue( p.sticky, msg="missing sticky bit on package %s/%s" % (package, version) ) def assertLacksStickyPackage(self, package, version): p = db_storage.lookup_package(self.session, package, version) ...
austinzheng/swift
utils/gyb_syntax_support/AvailabilityNodes.py
Python
apache-2.0
4,872
0
from Child import Child from Node import Node # noqa: I201 AVAILABILITY_NODES = [ # availability-spec-list -> availability-entry availability-spec-list? Node('AvailabilitySpecList', kind='SyntaxCollection', element='AvailabilityArgument'), # Wrapper for all the different entries that may occur i...
l # | float-literal # | float-literal '.' integer-literal Node('VersionTuple', kind='Syntax', description=''' A version number of the form major.minor.patch in which the minor \ and patch part may be ommited. ''', children=[ ...
ode_choices=[ Child('Major', kind='IntegerLiteralToken'), Child('MajorMinor', kind='FloatingLiteralToken') ], description=''' In case the version consists only of the major version, an \ integer literal that specifies...
photoninger/ansible
lib/ansible/modules/packaging/os/homebrew_cask.py
Python
gpl-3.0
18,051
0.000499
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2013, Daniel Jaouen <[email protected]> # (c) 2016, Indrajit Raychaudhuri <[email protected]> # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass_...
ashes '''.format(sep=os.path.sep) VALID_CASK_CHARS = r''' \w # alphanumeric characters (i.e., [a-zA-Z0-9_]) . # dots /
# slash (for taps) - # dashes ''' INVALID_PATH_REGEX = _create_regex_group(VALID_PATH_CHARS) INVALID_BREW_PATH_REGEX = _create_regex_group(VALID_BREW_PATH_CHARS) INVALID_CASK_REGEX = _create_regex_group(VALID_CASK_CHARS) # /class regexes ----------------------...
bswartz/cinder
cinder/tests/unit/test_quota_utils.py
Python
apache-2.0
10,416
0
# Copyright 2016 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 requ...
port cfg from oslo_config import fixture as config_fixture CONF = cfg.CONF class QuotaUtilsTest(test.TestCase): class FakeProject(object): def __init__(self, id='foo', parent_id=None): self.id = id self.parent_id = parent_id self.subtree = None self.parents...
one self.domain_id = 'default' def setUp(self): super(QuotaUtilsTest, self).setUp() self.auth_url = 'http://localhost:5000' self.context = context.RequestContext('fake_user', 'fake_proj_id') self.fixture = self.useFixture(config_fixture.Config(CONF)) self.fixtur...
aluminiumgeek/psychedelizer
pynbome/filters/glass.py
Python
gpl-3.0
805
0.008696
# -*- coding: utf-8 -*- #!/usr/bin/env python # # pynbome library # glass.py (c) Mikhail Mezyakov <[email protected]> # # View through tiled glass import os import subprocess from wand.image import Image from . import prepare_filter @prepare_filter def apply_filter(input_filename, output_filename): setting
s = { 'amount': 25, 'granularity': 5 } script_path = os.path.join(os.path.dirname(__file__), '../lib/glasseffects') command = '{0} -e displace -a {3} -g {4} -w 0 -n 100 {1} {2}'.format( script_path, input_filename, output_filename, settings['amount'],...
.wait() return Image(filename=output_filename), settings
lanyuwen/openthread
tests/scripts/thread-cert/Cert_5_1_06_RemoveRouterId.py
Python
bsd-3-clause
4,328
0
#!/usr/bin/env python3 # # Copyright (c) 2016, The OpenThread Authors. # 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. Redistributions of source code must retain the above copyright # ...
ILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # import unittest import command import mle import thread_cert from command import
CheckType LEADER = 1 ROUTER1 = 2 class Cert_5_1_06_RemoveRouterId(thread_cert.TestCase): TOPOLOGY = { LEADER: { 'mode': 'rsdn', 'panid': 0xface, 'whitelist': [ROUTER1] }, ROUTER1: { 'mode': 'rsdn', 'panid': 0xface, 'r...
JonSteinn/Kattis-Solutions
src/Coloring Socks/Python 3/main.py
Python
gpl-3.0
689
0.024673
def machines_needed(socks,cap,diff,colors): if colors[0]-colors[-1] <= diff and cap >= socks: return 1 machines,curr_cap,i,j = (0,cap,0,0) while True: if curr_cap == 0: machines += 1 curr_cap = cap i = j elif colors[i]-colors[j] > diff: ...
r_cap -= 1 else: return machines + 1 def main(): s,c,k = map(int,input().split()) colors = sorted(map(int,input().split()),reverse=True) print(ma
chines_needed(s,c,k,colors)) if __name__ == "__main__": main()
mdaus/coda-oss
modules/python/math.linear/tests/test_math_linear.py
Python
lgpl-3.0
9,396
0.004151
#!/usr/bin/env python """ * ========================================================================= * This file is part of math.linear-c++ * ========================================================================= * * (C) Copyright 2004 - 2014, MDA Information Systems LLC * * math.linear-c++ is free software...
either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesse
r General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; If not, * see <http://www.gnu.org/licenses/>. * * """ import sys import numpy as np from copy import deepcopy from coda.math_linear import * if sys.version_info[0] ==...
ksmit799/Toontown-Source
toontown/coghq/DistributedCogKartAI.py
Python
mit
2,463
0.004872
from direct.directnotify import DirectNotifyGlobal from toontown.safezone import DistributedGolfKartAI from toontown.building import DistributedElevatorExtAI from toontown.building import ElevatorConstants from toontown.toonbase import ToontownGlobals class DistributedCogKartAI(DistributedElevatorExtAI.DistributedElev...
courseIndex = index if self.courseIndex == 0: self.countryClubId = ToontownGlobals.BossbotCountryClubIntA elif self.courseIndex == 1: self.countryClubId = ToontownGlobals.BossbotCountryClubIntB elif self.courseIndex == 2: self.countryClubId = ToontownGlobals.B...
self): numPlayers = self.countFullSeats() if numPlayers > 0: players = [] for i in self.seats: if i not in [None, 0]: players.append(i) countryClubZone = self.bldg.createCountryClub(self.countryClubId, players) for seat...
mitchellcash/ion
contrib/linearize/linearize-hashes.py
Python
mit
3,123
0.032341
#!/usr/bin/python # # linearize-hashes.py: List blocks in a linear, no-fork version of the chain. # # Copyright (c) 2013-2014 The Bitcoin developers # Copyright (c) 2015-2018 The PIVX developers # Copyright (c) 2018 The Ion developers # Distributed under the MIT/X11 software license, see the accompanying # file COPYIN...
ttings
: settings['port'] = 51473 if 'min_height' not in settings: settings['min_height'] = 0 if 'max_height' not in settings: settings['max_height'] = 313000 if 'rpcuser' not in settings or 'rpcpassword' not in settings: print("Missing username and/or password in cfg file", file=stderr) sys.exit(1) settings['p...
pearu/sympycore
sympycore/heads/neg.py
Python
bsd-3-clause
4,464
0.001792
__all__ = ['NEG'] from .base import heads_precedence, ArithmeticHead from ..core import init_module init_module.import_heads() init_module.import_lowlevel_operations() init_module.import_numbers() class NegHead(ArithmeticHead): """ NegHead represents negative unary operation where operand (data) is an ...
Algebra, lhs, Algebra(NUMBER, rhs), inplace) def algebra_add(self, Algebra, lhs, rhs, inplace): rhead, rdata = rhs.pair if rhead is ADD: data = [lhs] + rdata elif rhead is TERM_COEFF_DICT or rhead is EXP_COEFF_DICT: data = [lhs] + rhs
.to(ADD).data else: data = [lhs, rhs] if Algebra.algebra_options.get('evaluate_addition'): ADD.combine_add_list(Algebra, data) return add_new(Algebra, data) def algebra_mul_number(self, Algebra, lhs, rhs, inplace): if Algebra.algebra_options.get('is_additive_...
colloquium/spacewalk
client/rhel/yum-rhn-plugin/test/settestpath.py
Python
gpl-2.0
992
0
# yum-rhn-plugin - RHN support for yum # # Copyright (C) 2006 Red Hat, Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) a...
s.
# # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA import sys # Adjust path so we can see the src modules running from branch as well # as test dir...
cmr/cmr_rrt
src/map.py
Python
gpl-3.0
2,764
0.002894
# This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # bu...
ue except IndexError: print "Wtf IndexError? It's inbounds! %s" % str((pt[0], pt[1])) return True return False def inbounds(self, mi, ma, dbg=True):
if mi[0] < self.xmin or mi[0] >= self.xmax or ma[0] < self.xmin or ma[0] >= self.xmax: return False if mi[1] < self.ymin or mi[1] >= self.ymax or ma[1] < self.ymin or ma[1] >= self.ymax: return False return True def collides_any(self, mi, ma, dbg=True): self.inb...
ugoertz/django-familio
comments/migrations/0001_initial.py
Python
bsd-3-clause
1,415
0.003534
# -*- coding: utf-8 -*- from __future__ im
port unicode_literals from django.db import models, migrations from django.contrib.postgres.fields
import ArrayField from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('sites', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('contenttypes', '0001_initial'), ] operations = [ migrations.CreateModel( ...
google/smbios-validation-tool
setup.py
Python
apache-2.0
296
0.033784
from setupt
ools import setup setup( name = "smbios_validation_tool", author = "Xu Han", author_email = "", license = "Apache", url = "https://github.com/google/smbios-validation-tool", packages=['smbios_validation_tool', '
dmiparse'], scripts=['smbios_validation'], )
ClovisDj/Playconnect4
Connect4/urls.py
Python
mit
909
0.0022
"""Connect4 URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-b...
'^profile
/', include('userprofile.urls')), url(r'^$', views.Home.as_view(), name = "home"), ]
kyleabeauchamp/EnsemblePaper
code/figures/old/plot_ALA3_karplus.py
Python
gpl-3.0
1,981
0.021706
import matplotlib.pyplot as plt import numpy as np import schwalbe_couplings import experiment_loader import matplotlib matplotlib.rcParams.update({'font.size': 20}) outdir = "/home/kyleb/src/pymd/Papers/maxent/figures/" alpha = 0.2 num_grid = 500 phi = np.linspace(-180,180,num_grid) O = np.ones(num_grid) colors = ["...
ojecting $\phi$ onto J Couplings") plt.legend(loc=0) plt.xlim(-180,180) plt.ylim(-0.5,10.5) #plt.savefig(outdir+"/single_karplus.pdf",bbox_inches='tight') plt.figure() for i,key in enumerate(["J3_HN_HA_2","J3_HN_Cprime_2","J3_HA_Cprime_2","J3_HN_CB_2"]): plt.plot(phi,simulation_data[key],"%s" % colors[i]) yi...
.plot(phi,O*yi,"%s" % colors[i]) lower = yi - oi upper = yi + oi plt.fill_between(phi,lower*O,upper*O,color=colors[i],alpha=alpha) plt.xlabel(r"$\phi$ [$\circ$]") plt.ylabel(r"$f_i(\phi) = $ J") plt.xlim(-180,180) plt.ylim(-0.5,10.5) plt.title("Projecting $\phi$ onto J Couplings") plt.savefig(outd...
talonchandler/dipsim
notes/2017-10-10-voxel-reconstruction/figures/my_draw_scene.py
Python
mit
5,943
0.004038
import numpy as np import subprocess import matplotlib import matplotlib.pyplot as plt import matplotlib.image as mpimg def draw_scene(scene_string, filename='out.png', my_ax=None, dpi=500, save_file=False, chop=True): asy_string = """ import three; import graph3; setti...
(shift((x, y, z))*rotate(angle=degrees(Phi), u=O, v=Z)*rotate(angle=degrees
(Theta), u=O, v=Y)*rotate(angle=degrees(Phi_i), u=(0,0,0), v=(0,0,1))*phi_path); } } real len = 50; draw((-len,-len)--(len,-len)--(len,len)--(-len,len)--(-len,-len), white); draw(scale(50, 50, 0)*unitplane, surfacepen=white+opacity(0.5)); defaultpen(fontsize(8pt)); draw((0, -10, 0)--(10, -1...
ifwe/tasr
src/py/tasr/client_legacy.py
Python
apache-2.0
8,458
0.000946
''' Created on May 6, 2014 @author: cmills The idea here is to provide client-side functions to interact with the TASR repo. We use the requests package here. We provide both stand-alone functions and a class with methods. The class is easier if you are using non-default values for the host or port. ''' import re...
eaders = {'content-type': 'application/json; charset=utf8', } resp = requests.post(url, data=schema_str, headers=headers, timeout=timeout) if resp == None: raise TASRError('Timeout for request to %s' % url) if 200 == resp.status_code: # success -- return a normal reg...
hema_meta = SchemaHeaderBot.extract_metadata(resp) ras.update_from_schema_metadata(schema_meta) return ras elif 404 == resp.status_code and object_on_miss: ras = RegisteredAvroSchema() ras.schema_str = schema_str schema_meta = SchemaHeaderBot.extract_metadata(resp) ra...
alexlo03/ansible
lib/ansible/modules/cloud/google/gcp_storage_bucket_access_control.py
Python
gpl-3.0
12,479
0.003125
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2017 Google # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # ---------------------------------------------------------------------------- # # *** AUTO GENERATED CODE *** AUTO GENERATED CODE *** # ...
----------------------------------------------------------- from __future__ import absolute_import, division, print_function __metaclass__ = type ############################################################
#################### # Documentation ################################################################################ ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ["preview"], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: gcp_storage_bucket_access_con...
mahim97/zulip
tools/documentation_crawler/documentation_crawler/spiders/check_documentation.py
Python
apache-2.0
669
0.004484
import os import pathlib from typing import List from .common.spiders import BaseDocumentationSpider def get_start_url() -> List[str]: # Get index html file as start url and convert it to file uri dir_p
ath = os.path.dirname(os.path.realpath(__file__)) start_file = os.path.join(dir_path, os.path.join(*[os.pardir] * 4), "docs/_build/html/index.html") return [ pathlib.Path(os.path.abspath(start_file)).as_uri() ] class DocumentationSpider(BaseDocument
ationSpider): name = "documentation_crawler" deny_domains = ['localhost:9991'] deny = ['\_sources\/.*\.txt'] start_urls = get_start_url()
ryanbressler/pydec
pydec/math/volume.py
Python
bsd-3-clause
2,450
0.014694
__all__ = ['unsigned_volume','signed_volume'] from scipy import sqrt,inner,shape,asarray from scipy.misc import factorial from scipy.linalg import det def unsigned_volume(pts): """Unsigned volume of a simplex Computes the unsigned volume of an M-simp
lex embedded in N-dimensional space. The points are stored row-wise in an array with shape (M+1,N). Parameters ---------- pts
: array Array with shape (M+1,N) containing the coordinates of the (M+1) vertices of the M-simplex. Returns ------- volume : scalar Unsigned volume of the simplex Notes ----- Zero-dimensional simplices (points) are assigned unit volumes. Examples -----...
tgbugs/pyontutils
librdflib/setup.py
Python
mit
1,448
0.000691
import re from setuptools import setup def find_version(filename): _version_re = re.compile(r"__version__ = '(.*)'") for line in open(filename): version_match = _version_re.match(line) if version_match: return version_match.group(1) __version__ = find_version('librdflib/__init__....
thor_email='[email protected]', lice
nse='MIT', classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', ], keywords='rdflib librdf rdf parser parsing ttl rdfxml', packages=['librdflib'], python_requires='>=3', tests_require=tests_requi...
dronly/python
lxfpython/advance/do_iter.py
Python
apache-2.0
382
0.039267
#!/bin/python3.5 from collections import Iterable d = {'a':1, 'b':2, 'c':3} for key in d: print(key) for value in d.values(): print(value) for ch in 'ABC': pr
int(ch) print(isinstance('abc', Iterable) ) print(isinstance(123,Iterable)) for i, value in enumerate(['a', 'b', 'c
']): print(i, value) for x,y in [(1,1), (2,4), (3,9)]: print(x,y) list(range(1, 11)) print(list)
Udayraj123/dashboard_IITG
Binder/Binder/wsgi.py
Python
mit
390
0
"""
WSGI config for Binder project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS...
ication()
dwhswenson/contact_map
contact_map/frequency_task.py
Python
lgpl-2.1
4,417
0.000679
""" Task-based implementation of :class:`.ContactFrequency`. The overall algorithm is: 1. Identify how we're go
ing to slice up the trajectory into task-based chunks (:meth:`block_slices`, :meth:`default_slices`) 2. On each node a. Load the trajectory segment (:meth:`load_trajectory_task`) b. Run the analysis on the segment (:meth:`map_task`) 3. Once all the results h
ave been collected, combine them (:meth:`reduce_all_results`) Notes ----- Includes versions where messages are Python objects and versions (labelled with _json) where messages have been JSON-serialized. However, we don't yet have a solution for JSON serialization of MDTraj objects, so if JSON serialization is the c...
coreycb/horizon
openstack_dashboard/enabled/_9020_resource_browser.py
Python
apache-2.0
799
0
# (c) Copyright 2015 Hewlett Packard Enterprise Development Company LP # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0
# # Unless required by applicable law or agreed to in writing, software # distributed under the License is 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. ...
= 'default' PANEL_DASHBOARD = 'developer' ADD_PANEL = 'openstack_dashboard.contrib.developer.resource_browser.panel.ResourceBrowser' # noqa