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 |
|---|---|---|---|---|---|---|---|---|
nyaadevs/nyaa | utils/api_uploader_v2.py | Python | gpl-3.0 | 6,976 | 0.00258 | #!/usr/bin/env python3
import argparse
import json
import os
import requests
NYAA_HOST = 'https://nyaa.si'
SUKEBEI_HOST = 'https://sukebei.nyaa.si'
API_BASE = '/api'
API_UPLOAD = API_BASE + '/upload'
NYAA_CATS = '''1_1 - Anime - AMV
1_2 - Anime - English
1_3 - Anime - Non-English
1_4 - Anime - Raw
2_1 - Audio - Los... | , '--name', help='Display name for the torrent (optional)')
tor_group.ad | d_argument('-i', '--information', help='Information field (optional)')
tor_group.add_argument('-d', '--description', help='Description for the torrent (optional)')
tor_group.add_argument('-D', '--description-file', metavar='FILE',
help='Read description from a file (optional)')
tor_group.add_arg... |
ekopylova/burrito-fillings | bfillings/fastq_join.py | Python | bsd-3-clause | 8,636 | 0.000695 | #!/usr/bin/env python
#-----------------------------------------------------------------------------
# Copyright (c) 2013--, biocore development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-------------------------... | output_path = self._absolute(str(self.Parameters['-o'].Value))
else:
raise ValueError("No output path specified.")
return output_path
def _get_stitch_report_path(self):
"""Checks if stitch report label / path is set. Returns absolute path."""
if self.Parameters[... | ue))
return stitch_path
elif self.Parameters['-r'].isOff():
return None
def _get_result_paths(self, data):
"""Capture fastq-join output.
Three output files are produced, in the form of
outputjoin : assembled paired reads
outputun1 : unassembl... |
scottphilip/caller-lookup | CallerLookup/Responses.py | Python | gpl-3.0 | 1,950 | 0.000513 | # Author: Scott Philip ([email protected])
# Version: 1.2 (25 July 2017)
# Source: https://github.com/scottphilip/caller-lookup/
# Licence: GNU GENERAL PUBLIC LICENSE (Version 3, 29 June 2007)
from CallerLookup.Strings import CallerLookupLabel, CallerLookupKeys
from CallerLookup.Utils.Logs impor... | number_data)
if data is None or CallerLookupKeys.KEY_DATA not in data:
return result
data = data[CallerLookupKeys.KEY_DATA]
if len(data) == 0:
return result
data = data[0]
if CallerLookupKeys. | KEY_SCORE in data:
result[CallerLookupLabel.SCORE] = round(data[CallerLookupKeys.KEY_SCORE] * 100)
if CallerLookupKeys.KEY_ADDRESSES in data:
addresses = data[CallerLookupKeys.KEY_ADDRESSES]
if len(addresses) > 0:
if CallerLookupKeys.KEY_COUNTRY_CODE in addresses[0]:
... |
cnamejj/PollEngine | just-otp.py | Python | apache-2.0 | 4,562 | 0.014467 | #!/usr/bin/env python
"""
Driver for OpenVPN client
"""
import time
import base64
import hashlib
import struct
import hmac
import pollengine
# ---
class OVDriveData:
"""OpenVPN authentication data"""
def __init__( self ):
self.otp_secret = NO_SECRET
# ---
class ShellAdmin:
"""Driver for admin ... | min: set OTP secret' )
conn.queue_response( 'OTP secret' )
else:
conn.queue_response(
'The "secret" command takes one argument' )
elif __comm == ACR_SHOW:
PE.displaymsg( 'Admin: show c... | secret=self.ovdata.otp_secret) )
elif __comm == ACR_OTP:
__otp = gen_otp(self.ovdata)
PE.displaymsg( 'Admin: Generate OTP {otp}'.format(
otp=__otp[-6:]) )
conn.queue_response( 'OTP for {now} is... |
peastman/deepchem | deepchem/models/tests/test_predict.py | Python | mit | 1,984 | 0.006552 | """
Tests that deepchem models make deterministic predictions.
"""
__author__ = "Bharath Ramsundar"
__copyright__ = "Copyright 2016, Stanford University"
__license__ = "MIT"
import os
import tempfile
import numpy as np
import unittest
import sklearn
import shutil
import deepchem as dc
try:
import tensorflow as tf
... | metrics.mean_squared_error, task_averager=np.mean)
model = dc.models.ProgressiveMultitaskRegressor(
n_tasks,
n_features,
layer_sizes=[50],
bypass_layer_sizes=[10],
dropouts=[.25],
learning_rate=0.003,
weight_init_stddevs=[.1],
alpha_init_stddevs=[.02],... | pred_first = model.predict(dataset)
y_pred_second = model.predict(dataset)
np.testing.assert_allclose(y_pred_first, y_pred_second)
'''
|
physycom/QGIS | python/plugins/processing/algs/qgis/SetRasterStyle.py | Python | gpl-2.0 | 2,755 | 0.001452 | # -*- coding: utf-8 -*-
"""
***************************************************************************
SetRasterStyle.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
************************... | tRasterLayer)
from processing.algs.qgis | .QgisAlgorithm import QgisAlgorithm
class SetRasterStyle(QgisAlgorithm):
INPUT = 'INPUT'
STYLE = 'STYLE'
OUTPUT = 'OUTPUT'
def group(self):
return self.tr('Raster tools')
def groupId(self):
return 'rastertools'
def __init__(self):
super().__init__()
def flags(s... |
jiadaizhao/LeetCode | 0201-0300/0228-Summary Ranges/0228-Summary Ranges.py | Python | mit | 455 | 0 | class Solution:
def summaryRanges(self, nums: List[int]) -> List[str]:
i = 0
result = []
while i < len(nums):
start = i
while i + 1 < len(nums) and nums[i] + 1 == nums[i + 1]:
| i += 1
if i == start:
| result.append(str(nums[start]))
else:
result.append(str(nums[start]) + '->' + str(nums[i]))
i += 1
return result
|
rdio/sentry | src/sentry/management/commands/create_sample_event.py | Python | bsd-3-clause | 1,839 | 0.002719 |
"""
sentry.management.commands.create_sample_event
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2012 by the Sentry Team, see AUTHORS for more details.
:license | : BSD, see LICENSE for more details.
"""
from django.core.management.base import BaseCommand, CommandError, | make_option
class Command(BaseCommand):
help = 'Creates a sample event in Sentry (if applicable)'
option_list = BaseCommand.option_list + (
make_option('--project', dest='project', help="project ID or team-slug/project-slug"),
make_option('--platform', dest='platform'),
)
def handle... |
xpharry/Udacity-DLFoudation | tutorials/reinforcement/gym/gym/envs/safety/predict_actions_cartpole.py | Python | mit | 2,176 | 0.003217 | """
predict_actions_cartpole is the cartpole task but where the agent will
get extra reward for saying what its next 5 *actions* will be.
This is a toy problem but the principle is useful -- imagine a household robot
or a self-driving car that accurately tells you what it's going to do before it does it.
This'll inspi... | ration > TIME_BEFORE_BONUS_ALLOWED:
for i in xrange(min(NUM_PREDICTED_ACTIONS, len(self.predicted_actions))):
if self.predicted_actions[-(i + 1)][i] == current_action:
reward += | CORRECT_PREDICTION_BONUS
self.predicted_actions.append(action[1:])
self.iteration += 1
return observation, reward, done, info
def _reset(self):
observation = self.cartpole._reset()
self.predicted_actions = []
self.iteration = 0
return observation
|
geekybeaver/Billy | common/controller/base.py | Python | gpl-3.0 | 1,515 | 0.00264 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from __init__ import *
from common.models import Account
import logging
class BaseController(webapp.RequestHandler):
template_values = {}
template_module = ''
def get(self, action, key=None):
# FIXME mysterious bug this gets set over requests somehow
... | write(template.render(path, | self.template_values))
def _check_account(self, account):
current_account = Account().current()
if current_account.key() != account.key():
self.accessForbidden()
def accessForbidden(self):
self.response.out.write('You do not own that account')
self.response.set_sta... |
joeyb182/pynet_ansible | pynet_ansible/exercise_1_8.py | Python | apache-2.0 | 615 | 0.004878 | #!/usr/bin/env python
#8. Write a Python program using ciscoconfparse that par | ses cisco_crypto.txt. Note, this config file is not fully valid (i.e. parts of the configuration are missing). The script should find all of the crypto map entries in the file (lines that begin with 'crypto map CRYPTO') and for each crypto map entry print out its children.
from ciscoconfparse import CiscoConfParse
ci... | in line.children:
print kids.text
print
|
kingvuplus/EGAMI-D | lib/python/Plugins/Extensions/MediaPlayer/settings.py | Python | gpl-2.0 | 5,014 | 0.025329 | from Screens.Screen import Screen
from Screens.HelpMenu import HelpableScreen
from Components.FileList import FileList
from Components.Sources.StaticText import StaticText
from Components.config import config, getConfigListEntry, ConfigSubsection, ConfigText, ConfigYesNo, ConfigDirectory
from Components.ConfigList impo... | dNotifier(self.initConfigList)
self["setupActions"] = ActionMap(["SetupActions", "ColorActions"],
{
"green": self.save,
"red": self.cancel,
"cancel": self.cancel,
"ok": self.ok,
}, -2)
self.onLayoutFinish.append(self.layoutFinished)
def layoutFinished(self):
self.setTitle(self.setup... | t"), config.mediaplayer.repeat))
self.list.append(getConfigListEntry(_("save playlist on exit"), config.mediaplayer.savePlaylistOnExit))
self.list.append(getConfigListEntry(_("save last directory on exit"), config.mediaplayer.saveDirOnExit))
if not config.mediaplayer.saveDirOnExit.value:
self.list.append(g... |
adsass/astrometry | astrometry.net/SIMBAD.py | Python | mit | 12,840 | 0.009034 | #!/usr/bin/env python
"""Module implementing methods for SIMBAD.
Methods implemented in this module:
- makeQuery()
- getObjects()
For 'makeQuery' method:
Given a set of input parameters, the client sends a query
to the specified SIMBAD server. If the query is executed
successfully, the result will Python list of bibc... | elf.radius = rad
else:
self.radius = "%sd"%rad
if self.object:
if self.radius:
if self.radius[-1] not in ['h','m','s','d']:
raise IncorrectInputError, "radius is missing qualifier!"
self.elements.append('query ~... | ject)
elif self.ra and self.dec:
if self.dec[0] not in ['+','-']:
raise IncorrectInputError, "DEC must start with '+' or '-'!"
if self.radius:
if self.radius[-1] not in ['h','m','s','d']:
raise IncorrectInputError, "radius is missing qu... |
KEHANG/RMG-Py | rmgpy/rmg/model.py | Python | mit | 87,614 | 0.006106 | #!/usr/bin/python
# -*- coding: utf-8 -*-
################################################################################
#
# RMG - Reaction Mechanism Generator
#
# Copyright (c) 2002-2009 Prof. William H. Green ([email protected]) and the
# RMG Team ([email protected])
#
# Permission is hereby granted, free of charge, t... | ITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABI | LITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
#
################################################################################
"""
Contains classes for working with the reaction model generated by R... |
Andr3iC/juriscraper | opinions/united_states/state/indtc.py | Python | bsd-2-clause | 470 | 0 | """
Scraper for Indiana Tax Court
CourtID: indtc
Court Short Name: Ind. Tax.
Auth: Jon Andersen <[email protected]>
Reviewer: mlr
History:
2014-09-03: Created by Jon Andersen
"""
from juriscraper.opinions.united_states.state import ind
class Site(ind.Site):
def __init__(self, *args, **kwargs):
super(... | module__
self.url = 'h | ttp://www.in.gov/judiciary/opinions/taxcourt.html'
|
vileopratama/vitech | src/addons/point_of_sale/__openerp__.py | Python | mit | 2,836 | 0.001058 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Point of Sale',
'version': '1.0.1',
'category': 'Point Of Sale',
'sequence': 20,
'summary': 'Touchscreen Interface for Shops',
'description': """
Quick and Easy sale process
===========... | eport_saleslines.xml',
'views/report_detailsofsales.xml',
'views/report_payment.xml',
'views/report_sessionsumm | ary.xml',
'views/report_userlabel.xml',
'views/point_of_sale.xml',
'point_of_sale_dashboard.xml',
],
'demo': [
'point_of_sale_demo.xml',
],
'test': [
'../account/test/account_minimal_test.xml',
'test/tests_before.xml',
'test/00_register_open.yml',
... |
juanchodepisa/sbtk | SBTK_League_Helper/update_tournaments.py | Python | mit | 6,552 | 0.0058 | from src.interfacing.ogs.connect import Authentication
import codecs
import sys
import os
from time import sleep
def loadList(pNameFile):
iList = []
with codecs.open(pNameFile, "r", "utf-8") as f:
for line in f:
iList.append(line)
return iList
if __name__ == "__main__":
a = ... | (['tournaments'],{
"id":12650,
"name":"Test Tournament 2",
"group":515,
"tournament_type":"roundrobin",
"description":"<b>Test 3</b>",
"board_size":19,
"handicap":0, #default -1 for auto
"time_start": "2015-12-01T00:00:00Z",
"time_control_parameters":{
"time_control":"fischer",
"initial_time":... | xclude_provisional": False, # default
"auto_start_on_max": True, # default
"analysis_enabled": True, #default
"settings":{
"maximum_players":10,
},
"players_start": 6, #default
"first_pairing_method": "slide", #slaughter, random, slide, strength . default
"subsequent_pairing_method": "slide", # d... |
zubie7a/Algorithms | HackerRank/Cracking_The_Coding_Interview/Data_Structures/05_Balanced_Brackets.py | Python | mit | 1,286 | 0.004666 | # https://www.hackerrank.com/challenges/ctci-balanced-brackets
def is_matched(expression):
stack = []
symbols = {
"}" : "{",
")" : "(",
"]" : "["
}
for c in expression:
# If its an opening symbol, put it in the stack.
if c == "{" or c == "(" or c == "[":
... | symbols[c] == stack[-1]:
# Remove the symbol on top of the stack.
stack.pop()
# If it was a closing symbol and there's nothing in the stack,
# or if what was on top of the stack doesn't match it...
else:
# It is not balanced.
... | ) > 0:
return False
# If the stack was empty at the end, then it is matched.
else:
return True
t = int(raw_input())
for i in xrange(t):
expression = raw_input()
if is_matched(expression) == True:
print "YES"
else:
print "NO"
|
harveywwu/vnpy | vnpy/trader/gateway/tkproGateway/__init__.py | Python | mit | 242 | 0 | # encoding: UTF-8
from vnpy.trad | er import vtConstant
from .tkproGateway import TkproGateway
gatewayClass = TkproGateway
gatewayName = 'TKPRO'
gatewayDisplayName = 'TKPRO'
gatewayType = vtConstant.GATEWAYTYPE_EQUITY
gatewayQr | yEnabled = True
|
dongting/sdnac | sdnac/api/rpc.py | Python | apache-2.0 | 1,086 | 0.01105 | # adapted from zmq_server_example.py in tinyrpc
import time, sys
import zmq
from tinyrpc.protocols.jsonrpc import JSONRPCProtocol
from tinyrpc.transports.zmq import ZmqServerTransport
from tinyrpc.server import RPCServer
from tinyrpc.dispatch import RPCDispatcher
class Server(object):
def __init__(self, req_callba... | # sys.exit(0)
self.rpc_server.serve_forever()
# def start(self):
# self.rpc_server.serve_fo | rever()
def request(self, req):
return self.req_callback(req)
|
gsidhu/Pretty_Parser | setup.py | Python | mit | 683 | 0.027818 | import sys
from cx_Freeze import setup, Executable
# Dependencies are automatically detected, but it might need fine tuning.
build_exe_options = | {"packages": ["os","bs4","urllib.request","requests","lxml"], "excludes": ["tkinter"], "include_files":["style.css"]}
# GUI applications require a different base on Windows (the default is for a
# console application).
base = None
##if sys.platform == "win32":
## base = "Win32GUI"
setup( name = "Pretty P... | uild_exe_options},
executables = [Executable("PrettyParser.py", base=base)])
|
kdeldycke/smile_openerp_matrix_widget | smile_matrix_demo/smile_workload.py | Python | gpl-3.0 | 10,721 | 0.01026 | # -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2011-2012 Smile. All Rights Reserved
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU ... | elds.selection(LINE_RENDERING_MODES, 'Line rendering mode', select=True, required=True),
'workload_id': fields.many2one('smile.activity.workload', "Workload", required=True, ondelete='cascade'),
'profile_id': fields.many2one('smile.activity.profile', "Profile", required=False),
'employee_id': fi... | ds.one2many('smile.activity.workload.cell', 'line_id', "Cells"),
'performance_index': fields.function(_get_random_int, string="Performance index", type='float', readonly=True, method=True),
'productivity_index': fields.function(_get_random_int, string="Productivity index", type='float', readonly=True, m... |
trunca/enigma2 | lib/python/OPENDROID/OPD_panel.py | Python | gpl-2.0 | 35,438 | 0.028105 | from Plugins.Plugin import PluginDescriptor
from Screens.PluginBrowser import *
from Screens.Ipkg import Ipkg
from Screens.HarddiskSetup import HarddiskSetup
from Components.ProgressBar import ProgressBar
from Components.SelectionList import SelectionList
from Screens.NetworkSetup import *
from enigma import *
from Scr... | line, strip=1):
comandline = comandline + " >/tmp/command.txt"
os.system(comandline)
text = ""
if os.path.exists("/tmp/command.txt") is True:
file = open("/tmp/command.txt", "r")
if strip == 1:
for line in file:
text = text + line.strip() + '\n'
else:
for line in file:
te... | == '\n': text = text[:-1]
comandline = text
os.system("rm /tmp/command.txt")
return comandline
boxversion = getBoxType()
machinename = getMachineName()
machinebrand = getMachineBrand()
OEMname = getBrandOEM()
OPD_panel_Version = 'OPD PANEL V1.4 (By OPD-Team)'
print "[OPD_panel] machinebrand: %s" % (machinebran... |
cea-hpc/shine | lib/Shine/Configuration/ModelFile.py | Python | gpl-2.0 | 24,131 | 0.000622 | # Copyright (C) 2010-2014 CEA
#
# This file is part of shine
#
# 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 ... | t, as a reference for all the data that
it will have to manage.
"""
def __init__(self, orig_elem, fold=False):
self. | _origelem = orig_elem
self._elements = []
self.fold = fold
def emptycopy(self):
"""Return a new empty |
zmetcalf/Triple-Draw-Deuce-to-Seven-Lowball-Limit | triple_draw_poker/model/HandDetails.py | Python | gpl-2.0 | 1,109 | 0.000902 | from triple_draw_poker.model.Pot import Pot
class HandDetails:
def __init__(self):
self.pot = Pot()
self.raised = 0
self.street = 0
self.number_of_streets = 4
self.in_draw = False
self.hands = []
self.dealt_cards_index = 0
def getDealtCardsIndex(self):
... | (self):
self.raised += 1
def incrementStreet(self):
self | .street += 1
def changeInDraw(self):
self.in_draw = not self.in_draw
|
EternityForest/KaithemAutomation | kaithem/src/plugins/startup/DLNARenderPlugin/__init__.py | Python | gpl-3.0 | 2,277 | 0.004392 | from mako.lookup import TemplateLookup
from src import devices, alerts, scheduling, messagebus, workers
import subprocess
import os
import mako
import time
import threading
import logging
import weakref
import base64
import traceback
import shutil
import socket
import uuid
from src import widgets
logger = logging.Log... | estart = f
messagebus.subscribe("/system/jack/started", f)
f()
| except:
self.handleException()
def getManagementForm(self):
return templateGetter.get_template("manageform.html").render(data=self.data, obj=self)
devices.deviceTypes["DLNARenderAgent"] = DLNARenderAgent
|
jupito/dwilib | dwi/tools/pmapinfo.py | Python | mit | 3,191 | 0 | #!/usr/bin/python3
"""Print information about pmaps."""
import numpy as np
import dwi.conf
import dwi.files
from dwi.files import Path
import dwi.image
import dwi.mask
import dwi.util
lambdas = dict(
path=lambda x: x.info['path'],
name=lambda x: x.info['path'].name,
stem=lambda x: x.info['path'].stem,
... | = args.keys.split(',')
if args.masks:
mask = dwi.util.unify_masks(dwi.files.read_mask(x) for x in args.masks)
for path in args.path:
try:
pmap = dwi.image.Imag | e.read(path, params=args.params)
except Exception as e:
print('Could not read image: {}: {}'.format(path, e))
continue
if args.masks:
pmap.apply_mask(mask)
fmt = '{k}={v}' if args.verbose else '{v}'
fields = (fmt.format(k=x, v=lambdas[x](pmap)) for x i... |
atsheehan/pypogs | pypogs/game_container.py | Python | gpl-3.0 | 1,838 | 0.001088 | from pygame.locals import *
from pypogs import player_area
from pypogs import render
class GameContainer(object):
def __init__(self, world, dimensions):
self._player_areas = []
self._world = world
self._dimensions = dimensions
self._is_online = False
def render(self, screen)... | .handle_event(event)
def _handle_key_event(self, key):
if key == K_ESCAPE:
self._world.switch_to_menu()
def _handle_ | joy_button_down_event(self, button):
if button == 4:
self._world.switch_to_menu()
def start_new_game(self, player_count):
del self._player_areas[:]
posn = render.GamePositions(self._dimensions[0], self._dimensions[1],
player_count)
for... |
metaperture/autoargs | examples/usage.py | Python | bsd-3-clause | 857 | 0.011669 | import autoargs
def main(arg1: int, arg2: int, *, val=10, val2:int):
"""my docstring"""
return arg1 + arg2 + val + val2
def example(a, b: int, *others, d: float, e=10):
"" | "Here is my docstring"""
r | eturn str(locals())
import numpy
@cmdable
def f2(x: int, y: int, *z: int, op: {'sum', 'mul'}='mul'):
"aggregate x, y, and z's by mul or sum"
all_vals = [x, y] + list(z)
print(all_vals)
if op == 'sum':
return sum(all_vals)
elif op == 'mul':
return numpy.product(all_vals)
@cmdable
d... |
kemaswill/keras | tests/keras/wrappers/test_scikit_learn.py | Python | mit | 4,769 | 0.000629 | import pytest
import numpy as np
from keras.utils.test_utils import get_test_data
from keras.utils import np_utils
from keras import backend as K
from keras.models import Sequential
from keras.layers.core import Dense, Activation
from keras.wrappers.scikit_learn import KerasClassifier, KerasRegressor
input_dim = 5
h... | rs = dict(hidden_dims = [20, 30], batch_size=[64, 128], nb_epoch=[2], verbose=[0])
# regressor = Inherit_ | class_build_fn_reg()
# reg = grid_search.GridSearchCV(regressor, parameters, scoring='mean_squared_error', n_jobs=1, cv=2, verbose=2)
# reg.fit(X_train_reg, y_train_reg)
|
viaregio/cartridge | cartridge/shop/checkout.py | Python | bsd-2-clause | 8,239 | 0.000607 | """
Checkout process utilities.
"""
from django.contrib.auth.models import SiteProfileNotAvailable
from django.utils.translation import ugettext as _
from django.template.loader import get_template, TemplateDoesNotExist
from mezzanine.conf import settings
from mezzanine.utils.email import send_mail_template
from car... | ECKOUT_STEP_LAST = 1
if settings.SHOP_CHECKOUT_STEPS_SPLIT:
CHECKOUT_STEPS[0].update({"url": "billing-shipping",
"title": _("Address")})
if settings.SHOP_PAYMENT_STEP_ENABLED:
CHECKOUT_STEPS.append({"template": "payment", "url": "payment",
"t... | CKOUT_STEP_PAYMENT = CHECKOUT_STEP_LAST = 2
if settings.SHOP_CHECKOUT_STEPS_CONFIRMATION:
CHECKOUT_STEPS.append({"template": "confirmation", "url": "confirmation",
|
D4wN/brickv | src/build_data/windows/OpenGL/raw/GL/NV/texture_compression_vtc.py | Python | gpl-2.0 | 487 | 0.00616 | '''OpenGL extension NV.texture_compression_vtc
Automatically generated by the get_gl_extensions script, do not edit!
'''
from OpenGL import platform, constants, constant, arrays
from OpenGL import extensions
from OpenGL.GL import glget
i | mport ctypes
EXTENSION_NAME = 'GL_NV_texture_compression_vtc'
_DEPRECATED = False
def | glInitTextureCompressionVtcNV():
'''Return boolean indicating whether this extension is available'''
return extensions.hasGLExtension( EXTENSION_NAME )
|
TOTVS/mdmpublic | couchbase-cli/lib/python/pump_bfd2.py | Python | bsd-2-clause | 1,621 | 0.008637 | impor | t pump
import pump_bfd
class BFDSinkEx(pump_bfd.BFDSink):
de | f __init__(self, opts, spec, source_bucket, source_node,
source_map, sink_map, ctl, cur):
super(pump_bfd.BFDSink, self).__init__(opts, spec, source_bucket, source_node,
source_map, sink_map, ctl, cur)
self.mode = getattr(opts, "mode", "diff")
... |
mfergie/errorless | errorless.py | Python | gpl-2.0 | 3,992 | 0.003006 | #!/usr/bin/env python
import sys
import re
import subprocess
import cmd
error_regexps = [
"error:",
"warning:",
]
print_error_format = "{id}) {summary}"
class Error():
def __init__(self,
id,
error_type,
match_position):
self.id = id
self... | errors[-1].lines.append(line)
return err | ors
def main():
compiler_shell_command = ' '.join(sys.argv[1:])
def compile_fn():
print("Executing {}").format(compiler_shell_command)
compiler_output = capture_compiler_output(compiler_shell_command)
errors = parse_errors(compiler_output)
return errors
CommandLoop(compile... |
gdelnegro/django-translation-server | translation_server/models.py | Python | mit | 3,854 | 0.004411 | from django.db import models
from django.utils.translation import ugettext_lazy as _
class TranslationType(models.Model):
created = models.DateTimeField(_('DTSM1'), auto_now_add=True, null=True, blank=True, help_text=_('DTST1'))
updated = models.DateTimeField(_('DTSM2'), auto_now=True, null=True, blank=True, ... | = models.BooleanField(_('DTSM12'), help_text=_('DTST12'), default=False)
class Meta:
verbose_name = _('DTSMT2')
verbose_name_plural = _('DTSMTP2')
def __str__(self):
return "%s" % self.tag
|
def __unicode__(self):
return "%s" % self.tag
# @receiver(post_save, sender=Translation, dispatch_uid="update_stock_count")
# def update_translation(sender, instance, **kwargs):
# from django.core.management import call_command
# call_command('make_translation')
class LastTranslationTag(object):... |
xskylarx/skytube-web | CursoDjango/CursoDjango/settings/local.py | Python | lgpl-3.0 | 265 | 0.003774 | __author__ = 'soporte'
from .base import *
DEBUG = True
T | EMPLATE_DEBUG = True
ALLOWED_HOSTS = []
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': Path.join(BASE_DIR, 'db.sqlite3'),
}
}
STATI | C_URL = '/static/' |
legnaleurc/tornado | tornado/test/util.py | Python | apache-2.0 | 4,446 | 0.001125 | from __future__ import absolute_import, division, print_function
import contextlib
import os
import platform
import socket
import sys
import textwrap
from tornado.testing import bind_unused_port
# Delegate the choice of unittest or unittest2 to tornado.testing.
from tornado.testing import unittest
skipIfNonUnix = u... | n external network.
skipIfNoNetwork = unittest.skipIf('NO_NETWORK' in os.environ,
'network access disabled')
skipBefore33 = unittest.skipIf(sys.version_info < (3, 3), 'PEP 380 (yield from) not available')
skipBefore35 = unittest.skipIf(sys.version_info < (3, 5), 'PEP 492 (async/await)... | ython = unittest.skipIf(platform.python_implementation() != 'CPython',
'Not CPython implementation')
# Used for tests affected by
# https://bitbucket.org/pypy/pypy/issues/2616/incomplete-error-handling-in
# TODO: remove this after pypy3 5.8 is obsolete.
skipPypy3V58 = unittest.skipIf(p... |
bhagatyj/algorithms | dataStructures/priorityQ/c/priorityQTest.py | Python | mit | 1,399 | 0.042173 | # Input:
# N
# U:p,q
# U:x,y
# .....
# U:a,b
# C:a,y
# Output:
# TRUE/FALSE
import os
from subprocess import Popen, PIPE
import time
count = 0
def printline():
x = ''
for i in range(80):
x = x + "="
print x
def singleTest(qn, ansExp):
global count
child = Popen("./exe", stdin=PIPE, stdout=PIPE)
c... | id not compile")
def cleanup():
os.system('rm exe')
def test():
global count
sources = ["priorityQ_Impl1.c"]
for source in sources:
print
count = 0
compileCode(source)
runTests()
cleanup()
te | st()
|
noslenfa/tdjangorest | uw/lib/python2.7/site-packages/IPython/kernel/clientabc.py | Python | apache-2.0 | 2,081 | 0.004325 | """Abstract base class for kernel clients"""
#-----------------------------------------------------------------------------
# Copyright (C) 2013 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#------... | f):
pass
#--------------------------------------------------------------------------
# Channel management methods
#--------------------------------------------------------------------------
@abc.abstractmethod
def start_channels(self, shell=True, iopub=True, stdin=True, hb=True):
p... | hell_channel(self):
pass
@abc.abstractproperty
def iopub_channel(self):
pass
@abc.abstractproperty
def stdin_channel(self):
pass
@abc.abstractproperty
def hb_channel(self):
pass
|
chhao91/pysal | pysal/spreg/utils.py | Python | bsd-3-clause | 24,433 | 0.002865 | """
Tools for different procedure estimations
"""
__author__ = "Luc Anselin [email protected], \
Pedro V. Amaral [email protected], \
David C. Folch [email protected], \
Daniel Arribas-Bel [email protected]"
import numpy as np
from scipy import sparse as SP
import scipy.optimi... | == 3:
optim_par = lambda par: foptim_par(
np.array([[float(par[0]), float(par[0]) ** 2., float(par[1])]]).T, moments)
start = [0.0, 0.0]
bounds = [(-1.0, 1.0), (0.0, None)]
lambdaX = op.fmin_l_bfgs_b(
optim_par, start, approx_grad=True, bounds=bounds)
return la... | def foptim_par(par, moments):
"""
Preparation of the function of moments for minimization
...
Parameters
----------
lambdapar : float
Spatial autoregressive parameter
moments : list
List of Moments with G (moments[0]) an... |
TiagoBras/audio-clip-extractor | setup.py | Python | mit | 1,840 | 0.000543 | try:
from setuptools import setup, find_packages
except ImportError:
from distutils.core import setup, find_packages
import os
def version():
with open(os.path.abspath('VERSION')) as f:
return f.read().strip()
raise IOError("Error: 'VERSION' file not found.")
VERSION = version()
setup(
... | [
'Development Status :: 3 - Alpha',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: End Users/Desktop',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Operating System :: MacOS',
'Operating Sys... | 'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Topic :: Multimedia :: Sound/Audio :: Conversion',
'Topic :: Utilities'
],
entry_points='''
[co... |
unnikrishnankgs/va | venv/lib/python3.5/site-packages/mpl_toolkits/mplot3d/proj3d.py | Python | bsd-2-clause | 6,988 | 0.019176 | # 3dproj.py
#
"""
Various transforms used for by the 3D code
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import six
from six.moves import zip
from matplotlib.collections import LineCollection
from matplotlib.patches import Circle
import numpy as np
... | cos(alpha), np.sin(alpha)
M1 = np.array([[1,0,0,0],
[0,cosa,-sina,0],
[0,sina,cosa,0],
| [0,0,0,0]])
return np.dot(M1, V)
def test_rot():
V = [1,0,0,1]
print(rot_x(V, np.pi/6))
V = [0,1,0,1]
print(rot_x(V, np.pi/6))
if __name__ == "__main__":
test_proj()
|
Inspq/ansible | test/units/modules/identity/keycloak/test_keycloak_group.py | Python | gpl-3.0 | 7,158 | 0.013412 | import collections
import os
import unittest
from ansible.modules.identity.keycloak.keycloak_group import *
class KeycloakGroupTestCase(unittest.TestCase):
def test_create_group(self):
toCreate = {
"username":"admin",
"password":"admin",
"realm":"master",
... | ":"admin",
"password":"admin",
"realm":"master",
"url":"http://localhost:18081",
"n | ame":"test4",
"attributes": {
"attr1":["value1"],
"attr2":["value2"]
},
"realmRoles": [
"uma_athorization"
],
"clientRoles": {
"master-realm": [
"manage-users"
... |
openattic/openattic | backend/ceph/migrations/0005_cephpool_percent_used.py | Python | gpl-2.0 | 479 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db | import models, migrations
class Migration(migrations.Migration):
dependencies = [
('ceph', '0004_rm_models_based_on_storageobj'),
]
operations = [
migrations.AddField(
model_name='cephpool',
name='percent_used',
field=models.FloatField(default=None, ed... | alse, blank=True),
preserve_default=True,
),
]
|
TomTranter/OpenPNM | openpnm/algorithms/TransientNernstPlanck.py | Python | mit | 2,989 | 0 | from openpnm.algorithms import TransientReactiveTransport
from openpnm.utils import logging
logger = logging.getLogger(__name__)
class TransientNernstPlanck(TransientReactiveTransport):
r"""
A subclass of GenericTransport to perform steady and transient simulations
of pure diffusion, advection-diffusion a... | phase)
def setup(self, phase=None, quantity='', conductance='', ion='',
t_initial=None, t_final=None, t_step=None, t_output=None,
t_tolerance=None, t_precision=None, t_scheme='', **kwargs):
if phase:
self.settings['phase'] = phase.nam | e
if quantity:
self.settings['quantity'] = quantity
if conductance:
self.settings['conductance'] = conductance
if ion:
self.settings['ion'] = ion
if t_initial is not None:
self.settings['t_initial'] = t_initial
if t_final is not Non... |
FrancoisRheaultUS/dipy | doc/tools/apigen.py | Python | bsd-3-clause | 17,957 | 0.000223 | """
Attempt to generate templates for module reference with Sphinx
To include extension modules, first identify them as valid in the
``_uri2path`` method, then handle them in the ``_parse_module_with_import``
script.
Notes
-----
This parsing is based on the import and introspection of modules.
Previously functions an... | 'get/set package_name')
def _import(self, name):
""" Import namespace package """
mod = __import__(name)
components = name.split('.')
for comp in components[1:]:
mod = getattr(mod, comp)
return mod
def _get_object_name(self, line):
""" Get second tok... | riter._get_object_name(" class Klass(object): ")
'Klass'
>>> docwriter._get_object_name(" class Klass: ")
'Klass'
"""
name = line.split()[1].split('(')[0].strip()
# in case we have classes which are not derived from object
# ie. old style classes
retur... |
jackdpage/pylux | pylux/lib/tagger.py | Python | gpl-3.0 | 1,597 | 0.002505 | # Generates some automatic tags based on the value of other tags or information
# available.
import math
from pylux import reference
def tag_fixture_colour(fixture):
if 'gel' in fixture.data:
try:
fixture.data['colour'] = reference.gel_colours[fixture.data['gel']]
except KeyError:
... | xture.data['colour'] = 'White'
def tag_fixture_rotation(fixture):
# If we can't calculate the rotation (e.g. a moving head would not have any focus values) then set the rotation
# to zero to have the fixture point in its default orientation. Unless the rotation tag alread | y exists, in which
# case leave it as-is in case it was added manually.
if 'posX' in fixture.data and 'posY' in fixture.data and 'focusX' in fixture.data and 'focusY' in fixture.data:
pos = [float(fixture.data['posX']), float(fixture.data['posY'])]
focus = [float(fixture.data['focusX']), float(f... |
douban/code | vilya/views/api/gists.py | Python | bsd-3-clause | 2,398 | 0 | # -*- coding: utf-8 -*-
import json
from vilya.libs import api_errors
from vilya.models.gist import (
Gist, gist_detail, PRIVILEGE_PUBLIC, PRIVILEGE_SECRET)
from vilya.views.api.gist import GistUI
from vilya.views.api.utils import json_body
_q_exports = ['starred']
@json_body
def _q_index(request):
if reque... | removed in future, use json to post data
file_names = request.get_form_var('file_name', '')
file_contents = request.get_form_var('file_contents', '')
if not request.data.get('public' | ):
is_public = PRIVILEGE_SECRET
else:
is_public = PRIVILEGE_PUBLIC
files = request.data.get('files')
if files:
file_names = []
file_contents = []
for file_name, file in files.iteritems():
file_names.append(file_name)
... |
tsdmgz/ansible | lib/ansible/module_utils/ironware.py | Python | gpl-3.0 | 3,511 | 0.001139 | #
# Copyright (c) 2017, Paul Baker <[email protected]>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any... | ack, ['ANSIBLE_NET_AUTHORIZE']), type='bool'),
'auth_pass': dict(fallback=(env_fallback, ['ANSIBLE_NET_AUTH_PASS']), no_log=True),
'timeout': dict(type='int'),
}
ironware_argument_spec = {
'provider': dict(type='dict', options=ironware_provider_spec)
}
command_spec = {
'command': dict(key=True),
'... | f get_connection(module):
global _CONNECTION
if _CONNECTION:
return _CONNECTION
_CONNECTION = Connection(module._socket_path)
return _CONNECTION
def to_commands(module, commands):
if not isinstance(commands, list):
raise AssertionError('argument must be of type <list>')
trans... |
stitchfix/pybossa | pybossa/sched.py | Python | agpl-3.0 | 7,613 | 0.003678 | # -*- coding: utf8 -*-
# This file is part of PyBossa.
#
# Copyright (C) 2013 SF Isle of Man Limited
#
# PyBossa is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at... | _ip=None, n_answers=30, off | set=0):
"""Returns a random task for the user"""
app = db.slave_session.query(App).get(app_id)
from random import choice
if len(app.tasks) > 0:
return choice(app.tasks)
else:
return None
def get_incremental_task(app_id, user_id=None, user_ip=None, n_answers=30, offset=0):
"""
... |
tradej/pykickstart-old | tests/commands/url.py | Python | gpl-2.0 | 3,282 | 0.004875 | #
# Martin Gracik <[email protected]>
#
# Copyright 2009 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. This program is distributed in the hope that it
# will be use... | f Red Hat, Inc.
#
import unittest
from tests.baseclass import *
class FC3_TestCase(CommandTest):
def runTest(self):
# pass
self.assert_parse("url --url=http://domain.com", "url --url=\"http://domain.com\"\n")
# fail
# missing required option --url
self.assert_parse_error("... | artValueError)
self.assert_parse_error("url --url", KickstartParseError)
class F13_TestCase(FC3_TestCase):
def runTest(self):
# run FC3 test case
FC3_TestCase.runTest(self)
# pass
self.assert_parse("url --url=http://someplace/somewhere --proxy=http://wherever/other",
... |
SKIRT/PTS | modeling/component/component.py | Python | agpl-3.0 | 19,107 | 0.002355 | #!/usr/bin/env python
# -*- coding: utf8 -*-
# *****************************************************************
# ** PTS -- Python Toolkit for working with SKIRT **
# ** © Astronomical Observatory, Ghent University **
# *****************************************************************
##... | ved SED not defined for modeling types other than 'galax | y' or 'sed'")
# -----------------------------------------------------------------
@lazyproperty
def truncated_sed_path(self):
if not self.is_galaxy_modeling: raise RuntimeError("Something went wrong")
return self.environment.truncated_sed_path
# ---------------------------------------... |
gchrupala/reimaginet | imaginet/defn/audiovis_rhn.py | Python | mit | 5,671 | 0.011462 | from funktional.layer import Layer, Dense, StackedGRU, StackedGRUH0, Convolution1D, \
Embedding, OneHot, clipped_rectify, sigmoid, steeper_sigmoid, tanh, CosineDistance,\
last, softmax3d, params, Attention
from funktional.rhn import StackedRHN0
import funktiona... | def __call__(self, input):
return self.RHN(self.Conv(input))
class Visual(task.Task):
def __init__(self, config):
autoassign(locals())
self.margin_size = config.get('margin_size', 0.2)
self.updater = util.Adam(max_nor | m=config['max_norm'], lr=config['lr'])
self.Encode = Encoder(config['size_vocab'],
config['size'],
filter_length=config.get('filter_length', 6),
filter_size=config.get('filter_size', 1024),
... |
quantumlib/OpenFermion-Cirq | openfermioncirq/contrib/__init__.py | Python | apache-2.0 | 675 | 0 | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the Licen | se at
#
# https://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 Li | cense for the specific language governing permissions and
# limitations under the License.
"""Package for contributions.
Any contributions not ready for full production can be put in a subdirectory in
this package.
"""
|
shoyer/numpy | numpy/distutils/exec_command.py | Python | bsd-3-clause | 10,919 | 0.003114 | """
exec_command
Implements exec_command function that is (almost) equivalent to
commands.getstatusoutput function but on NT, DOS systems the
returned status is actually correct (though, the returned status
values may be different by a factor). In addition, exec_command
takes keyword arguments for (re-)defining enviro... | exec_dir = os.path.dirname(exec_dir)
if oldcwd!=execute_in:
os.chdir(execute_in)
log.debug('New cwd: %s' % execute_in)
else:
log.debug('Retaining cwd: %s' % oldcwd)
oldenv = _preserve_environment( list(env.keys()) )
_update_environment( **env )
try:
st = _ | exec_command(command,
|
GutiDeng/bcpy | KvDB/ImplSQLite.py | Python | gpl-3.0 | 9,116 | 0.00724 | from Interface import Interface
import sqlite3
import time
import types
import json
import os
class Implementation(Interface):
def __init__(self, connstr, *args, **kwargs):
dbfile = connstr
# automatically create parent directory
pdir = os.path.dirname(dbfile)
if not ... | ,))
row = self._cursor.fetchone()
if row:
t, v = row[0], row[1]
self._cursor.execute('''DELETE FROM %s WHE | RE k=? AND t=?''' % (tablename,), (k, t))
return v
else:
return v
def _init_dict(self, force=False):
tablename = self._get_tablename()
if force:
self._cursor.execute('''DROP TABLE IF EXISTS %s''' % (tablename,))
self._cursor.execute('''CREATE ... |
True-Demon/gitkali | gitkali.py | Python | gpl-3.0 | 5,391 | 0.004823 | #!/usr/bin/python3
"""
Written by: True Demon
The non-racist Kali repository grabber for all operating systems.
Git Kali uses Offensive Security's package repositories and their generous catalog
of extremely handy penetration testing tools. This project is possible because
of Offensive Security actually sticking to go... | R EVER EEEEEEEVVVVVEEEEEEEEEEEERRRRRRRRRRR DO THIS!!!
# TODO: EVENTUALLY...build a way for this to work safely...
| packager.install_all(args.directory)
if args.directory != __install__: # Usually /usr/share/
check_install_dir(args.directory) # Check that the directory exists
warn_non_standard_dir(args.directory) # Warn the user that this is not advised
... |
PiRSquared17/emacs-freex | test_regex.py | Python | gpl-3.0 | 465 | 0.008602 | #!/usr/bi | n/python
import os, re
aliases = os.listdir('/Users/greg/Documents/freex/')
aliases = [a.lower() for a in aliases if '.freex' in a]
aliases.sort(reverse=True)
aliases = [re.escape(a.lower()) for a in aliases]
aliasRegexpStr = '\\b'+'\\b|\\b'.join(aliases)+'\\b'
aliasRegexpStr = aliasRegexpStr.replace('\\ ', ' ?\\\n? ... | re.MULTILINE)
|
Gitweijie/first_project | networking_cisco/backwards_compatibility.py | Python | apache-2.0 | 5,581 | 0 | # Copyright 2016 Cisco Systems, Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requir... | t
def get_novaclient_images(nclient):
return nclient.images
if NEUTRON_VERSION >= NEUTRON_PIKE_VERSION:
from neutron.conf.agent import common as config
else:
from neutron.agent.common import config # noqa
core_opts = base_config.core_opts
# Bring in the union of all constants in neutron.common.... | in neutron_lib.
#
# In the plugin code, replace the following imports:
# from neutron.common import constants
# from neutron_lib import constants
# with (something like this):
# from networking_cisco import backward_compatibility as bc
# Then constants are referenced as shown in this example:
# port['de... |
joebowen/ChannelWorm | channelworm/fitter/__init__.py | Python | mit | 71 | 0.070423 | __all | __ = ["Initiator","Simulator","Evaluator","M | odelator","Validator"] |
jimyx17/jimh | lib/MultipartPostHandler.py | Python | gpl-3.0 | 3,642 | 0.005491 | #!/usr/bin/python
####
# 06/2010 Nic Wolfe <[email protected]>
# 02/2006 Will Holcomb <[email protected]>
#
# 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 ... | n multiple values by
# assigning a sequence.
doseq = 1
class MultipartPostHandler(urllib2.BaseHandler):
handler_order = urllib2.HTTPHandler.handler_order - 10 # needs to run first
def http_request(self, request):
data = request.get_data()
if data is not N | one and type(data) != str:
v_files = []
v_vars = []
try:
for(key, value) in data.items():
if type(value) in (file, list, tuple):
v_files.append((key, value))
else:
v_vars.a... |
nicholasmalaya/arcanus | disputatio/routines/drag_polars/90.py | Python | mit | 2,860 | 0.016783 | import numpy as np
import matplotlib.pyplot as plt
def poly_print(c,name):
#
# prints coefficients for lift or drag functions
#
p=0
print ''
for item in c:
# last step
if(p == len(c)-1):
print ' '+str(item)+'*x^'+str(p)+"'",
# first step
elif(p... | * np.pi * rad) * np.exp(-rad)
#cli = np.cos(2 * np.pi * rad)
#cli = np.where(abs(t) > np.pi/24., t, np.sin(2*t))
#cdi = np.where(abs(t) > np.pi/24., t*t*81/25., 1-0.8*np.cos(2*t))
pol | y_print(inter_cl,'lift')
poly_print(inter_cd,'drag')
#
# plot!
#
sz=25
plt.subplot(2, 1, 1)
plt.plot(anglecd, cd, 'ko-',label='COMSOL Data')
plt.plot(anglei, P.polyval(anglei,inter_cd), color='blue',label='Interpolant')
#plt.title(r'Coefficients of Drag/Lift as functions of $\alpha$')
#plt.subtitle(r'Coefficients of D... |
meerkat-cv/annotator-supreme | annotator_supreme/views/view_tools.py | Python | mit | 5,904 | 0.003557 | from flask import request, abort, session
from functools import wraps
import logging
import urllib.request as urllib2
import numpy as np
import cv2
import random
from annotator_supreme.views import error_views
from io import StringIO
from PIL import Image
from annotator_supreme import app
import os
import base64
def r... | m_url(url):
req = urllib2.Request(url, headers={'User-Agent' : "VirtualMakeup-API"})
res = urllib2.urlopen(req)
if res.getcode() != 200:
raise Exception('Invalid status code '+str(res | .getcode())+' from image url')
else:
return read_image_from_stream(res)
def read_image_b64(base64_string):
dec = base64.b64decode(base64_string)
npimg = np.fromstring(dec, dtype=np.uint8)
cvimg = cv2.imdecode(npimg, cv2.IMREAD_COLOR)
return cvimg
def image_to_dict(image):
anno_vec =... |
richard-fisher/repository | system/base/libffi/actions.py | Python | gpl-2.0 | 355 | 0.019718 |
#!/usr/bin/python
from pisi.actionsapi i | mport shelltools, get, autotools, pisitools
def setup():
autotools.configure ("--prefix=/usr\
--disable-static")
def build():
autotools.make ()
def install( | ):
autotools.rawInstall ("DESTDIR=%s" % get.installDIR())
pisitools.dodoc ("README", "ChangeLog", "LICENSE")
|
sirech/deliver | deliver/converter/simple.py | Python | mit | 5,674 | 0.001586 | import email
import re
from cStringIO import StringIO
from email.charset import add_charset, Charset, QP
from email.generator import Generator
from email.header import decode_header, Header
from utils import to_unicode
# Globally replace base64 with quoted-printable
add_charset('utf-8', QP, QP, 'utf-8')... | ame | )
|
elainenaomi/sciwonc-dataflow-examples | dissertation2017/Experiment 2/instances/11_0_wikiflow_1sh_1s_annot/longestsession_8/ConfigDB_Longest_8.py | Python | gpl-3.0 | 983 | 0.014242 | HOST = "wfSciwoncWiki:[email protected]:27001,172.31.29.102:27001,172.31.29.103:27001,172.31.29.104:27001,172.31.29.105:27001,172.31.29.106:27001,172.31.29.107:27001,172.31.29.108:27001,172.31.29.109:27001/?authSource=admin"
P | ORT = ""
USER = ""
PASSWORD = ""
DATABASE = "wiki"
READ_PREFERENCE = "primary"
COLLECTION_INPUT = "user_sessions"
COLLECTION_OUTPUT = "top_sessions"
PREFIX_COLUMN = "w_"
ATTRIBUTES = ["duration", "start time", "end time", "contributor_username", "edition_counts"]
SORT = ["duration", "end time"]
OPERATION_... | end time"
VALUE = [(1236381526, 1238973525),(1238973526, 1241565525),(1241565526, 1244157525),(1244157526, 1246749525),(1246749526, 1249341525),(1249341526, 1251933525),(1251933526, 1254525525),(1254525526, 1257113925),(1257113926, 1259705925),(1259705926, 1262297925),(1262297926, 1264889925),(1264889926, 1265098299)]... |
funkyfuture/inxs | tests/test_cli.py | Python | agpl-3.0 | 515 | 0.001942 | from pathlib import Path
from inxs.cli import main as _main
from tests import equal_documents
def main(*args):
_args = ()
for arg in | args:
if isinstance(arg, Path):
_args += (str(arg),)
else:
_args += (arg,)
_ | main(_args)
# TODO case-study with this use-case
def test_mods_to_tei(datadir):
main("--inplace", datadir / "mods_to_tei.py", datadir / "mods_to_tei.xml")
assert equal_documents(datadir / "mods_to_tei.xml", datadir / "mods_to_tei_exp.xml")
|
system7-open-source/imamd | imam/imam/preset/local_preset.py | Python | agpl-3.0 | 823 | 0.010936 | """local_preset.py is imported by default_settings.py when no URL environment variable is defined.
"""
#
# Alter this skeleto | n to agree with the needs of your local environment
# Note: if you are using a URL 12-Factor configuration scheme, you will not be using this file
# important thing we do here is to import all those symbols that are defined in settin | gs.py
from ..settings import * # get most settings from ../settings.py
# or perhaps you would prefer something like:
# from staging import * # which in turn imports ../settings.py
# # # and now you can override the settings which we just got from settings.py # # # #
# for example, choose a different database...
... |
dribnet/dagbldr | examples/faces_vae/flying_faces_vae.py | Python | bsd-3-clause | 2,380 | 0.001261 | import argparse
import numpy as np
import os
from dagbldr.datasets import fetch_fer
from dagbldr.utils import load_checkpoint, interpolate_between_points, make_gif
parser = argparse.ArgumentParser()
parser.add_argument("saved_functions_file",
help="Saved pickle file from vae training")
parser.add_... | log_sig = encode_function(arr)
| # No noise at test time
out, = decode_function(mu + np.exp(log_sig))
return out
# VAE specific plotting
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
samples = gen_samples(sample_X)
samples = np.dot(samples, pca_tf) + mean_norm
f, axarr = plt.subplots(n_plot_samples, 2)
for n, (X_i, s... |
cstbox/devel | bin/cbx-2to3.py | Python | lgpl-3.0 | 821 | 0.002439 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Data filter converting CSTBox v2 event logs to v3 format.
Usage: ./cbx-2to3.py < /path/ | to/input/file > /path/to/output/file
"""
__author__ = 'Eric Pascual - CSTB ([email protected])'
import fileinput
import json
for line in fileinput.input():
ts, var_type, var_name, value, data = line.split('\t')
# next 3 lines are specific to Actility box at home files conversion
if var_name.s | tartswith('home.'):
var_name = var_name[5:]
var_name = '.'.join((var_type, var_name))
data = data.strip().strip('{}')
if data:
pairs = data.split(',')
data = json.dumps(dict([(k.lower(), v) for k, v in (pair.split('=') for pair in pairs)]))
else:
data = "{}"
print('... |
velorientc/git_test7 | tests/hglib_encoding_test.py | Python | gpl-2.0 | 3,473 | 0.004607 | """Test for encoding helper functions of tortoisehg.util.hglib"""
from nose.tools import *
from tortoisehg.util import hglib
import helpers
JAPANESE_KANA_I = u'\u30a4' # Japanese katakana "i"
@helpers.with_encoding('utf-8')
def test_none():
"""None shouldn't be touched"""
for e in ('fromunicode', 'fromutf',... | A_I.encode('utf-8'),
hglib.fromunicode(JAPANESE_KANA_I))
@helpers.with_encoding('utf-8')
def test_fromunicode_unicodableobj():
"""fromunicode() accepts unicode-able obj like QString"""
class Unicodable(object):
def __unicode__(self):
return JAPANESE_KANA_I
assert_equa... | JAPANESE_KANA_I.encode('utf-8'),
hglib.fromunicode(JAPANESE_KANA_I))
@helpers.with_encoding('ascii')
def test_fromunicode_replace():
assert_equals('?', hglib.fromunicode(JAPANESE_KANA_I,
errors='replace'))
@helpers.with_encoding('ascii')
def test_fromunic... |
shobhitmishra/CodingProblems | epi_judge_python/max_safe_height.py | Python | mit | 308 | 0 | from test_framework import generic_test
def get_height(cases: int, drops: int) -> int:
# TODO - you fill in here. |
return 0
if __name__ == '__main__':
exit(
generic_test.generic_test_main('max_safe_height.py',
| 'max_safe_height.tsv', get_height))
|
BjerknesClimateDataCentre/QuinCe | DataPreparation/sqlite/sqlite_extractor.py | Python | gpl-3.0 | 2,156 | 0.016234 | import sys, os
import toml
import pandas as pd
import numpy as np
from DatabaseExtractor import DatabaseExtractor
def check_output_config(config):
""" Check that the configuration is valid"""
ok = True
if config['output']['sort_column'] not in config['output']['columns']:
print("Sort column not in output c... | ata.iloc[i, column_index] not in mapped_values:
all_data.iloc[i, column_index] = col_map['other']
# | Write the final CSV
all_data.to_csv(out_file, index=False)
finally:
if extractor is not None:
del extractor |
aglne/Solandra | scripts/get_initial_tokens.py | Python | apache-2.0 | 148 | 0.02027 | #!/usr/bin/python
import sys
def tokens(nodes):
| for i in range(0, nodes):
print (i * (2 ** 127 - 1) / nodes)
tokens(int(sys.argv[1]) | )
|
wright-group/WrightTools | tests/kit/remove_nans_1D.py | Python | mit | 875 | 0.004571 | #! /usr/bin/env python3
"""Test remove_nans_1D."""
# --- import -------------------------------------------------------------------------------------
import numpy as np
import WrightTools as wt
# --- test ---------------------------------------------------------------------------------------
def test_simple():... | all() == np.arange(0, 6, dtype=float).all()
def test_multiple():
arrs = [np.random.random(21) for _ in range(5)]
arrs[0][0] = np.nan
arrs[1][-1] = np.nan
arrs = wt.kit.remove_nans_1D(*arrs)
for arr in arrs:
assert arr.size == 19
de | f test_list():
assert np.all(wt.kit.remove_nans_1D([np.nan, 1, 2, 3])[0] == np.array([1, 2, 3]))
if __name__ == "__main__":
test_simple()
test_multiple()
test_list()
|
ariovistus/pyd | examples/interpcontext/setup.py | Python | mit | 286 | 0.006993 | from pyd.support import setup, Extension, pydexe_sanity_check
pydexe_sanity_check()
projName = 'interpcontext'
setu | p(
name=projName,
version='1.0',
ext_modules=[
Extension(projName, ['interpcontext.d'],
build_deimos | =True, d_lump=True
)
],
)
|
zenodo/invenio | invenio/legacy/websubmit/functions/Create_Upload_Files_Interface.py | Python | gpl-2.0 | 23,083 | 0.002643 | # $Id: Revise_Files.py,v 1.37 2009/03/26 15:11:05 jerome Exp $
# This file is part of Invenio.
# Copyright (C) 2009, 2010, 2011, 2014 CERN.
#
# Invenio is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either v... | 1) or not (0)
+ defaultFilenameDoctypes: Rename uploaded files to admin-chosen
values. List here the the files in
current submission directory that
| contain the names to use for each doctype.
Eg:
Main=RN|Additional=additional_filename
('=' separates doctype and file in curdir
'|' separates each doctype/file group).
... |
rajiteh/taiga-back | taiga/mdrender/service.py | Python | agpl-3.0 | 4,927 | 0.003655 | # Copyright (C) 2014 Andrey Antukh <[email protected]>
# Copyright (C) 2014 Jesús Espino <[email protected]>
# Copyright (C) 2014 David Barragán <[email protected]>
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public Licens | e 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,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the... | the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import hashlib
import functools
import bleach
# BEGIN PATCH
import html5lib
from html5lib.serializer.htmlserializer import HTMLSerializer
def _serialize(domtree):
walker = html5lib.treewalkers.getTreeWa... |
GDG-JSS-NOIDA/programmr | programmr/app/migrations/0003_submission_ques_id.py | Python | gpl-3.0 | 580 | 0.001724 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-01-06 05:21
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('app', '0002_auto_20170105_0206'),
]
operations = [... | lt=1, on_delete=django.db.models.deletion. | CASCADE, to='app.Question'),
preserve_default=False,
),
]
|
agry/NGECore2 | scripts/mobiles/naboo/naboo_shaupaut_elder.py | Python | lgpl-3.0 | 1,691 | 0.027203 | import sys
from services.spawn import MobileTemplate
from services.spawn import WeaponTemplate
from resources.datatables import WeaponType
from resources.datatables import Difficulty
from resources.datatables import Options
from java.util import Vector
def addTemplate(core):
mobileTemplate = MobileTemplate()
mobi... | paut_elder')
mobileTemplate.setLevel(14)
mobileTemplate.setDifficulty(Difficulty.NORMAL)
mobileTemplate.setMinSpawnDistance(4)
mobileTemplate.setMaxSpawnDistance(8)
mobileTemplate.setDeathblow(False)
mobileTemplate.setScale(1)
mobileTemplate.setMeatType("Carnivore Meat")
mobileTemplate.setMeatAmount(50)
mobil... | Hide")
mobileTemplate.setBoneAmount(30)
mobileTemplate.setSocialGroup("self")
mobileTemplate.setAssistRange(12)
mobileTemplate.setStalker(False)
mobileTemplate.setOptionsBitmask(Options.AGGRESSIVE | Options.ATTACKABLE)
templates = Vector()
templates.add('object/mobile/shared_greater_shaupaut.iff')
mobileTempl... |
webcomics/dosage | tests/mocks/extra/dummy.py | Python | mit | 193 | 0 | # SPDX-Li | cense-Identifier: MIT
# Copyright (C) 2021 Tobias Gruetzmacher
from ..scraper import _ParserScraper
class AnotherDummyTestScraper(_ParserScraper):
url = | 'https://dummy.example/'
|
3dfxsoftware/cbss-addons | smile_base/__init__.py | Python | gpl-2.0 | 1,012 | 0 | # -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2013 Smile (<http://www.smile.fr>). All Rights Reserved
#
# This pro | gram 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,
# ... | eral 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 ir_translation
import update
|
iulian787/spack | var/spack/repos/builtin/packages/perl-www-robotrules/package.py | Python | lgpl-2.1 | 637 | 0.006279 | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PerlWwwRobotrules(PerlPackage):
"""Database of robots.txt-derived permissions"""
home... | 6='46b502e7a288d559429891eeb5d979461dd3ecc6a5c491 | ead85d165b6e03a51e')
depends_on('perl-uri', type=('build', 'run'))
|
hylje/lbtcex | lbtcex/main/forms.py | Python | bsd-3-clause | 307 | 0.003257 | from django import forms
METHOD_CHOICES = (
("GET", "GET"),
("POST", "POST")
)
class ApiCallForm(forms.Form):
method = forms.ChoiceField(choices=METHOD_CHO | ICES, initial="GET")
path = forms.CharField(initial="/api | /myself/")
data = forms.CharField(widget=forms.Textarea, required=False)
|
chenjm1217/ryu_app | L2Switch.py | Python | apache-2.0 | 3,340 | 0.008683 | #!/usr/bin/env python
import struct
import logging
from ryu.base import app_manager
from ryu.controller import ofp_event
from ryu.controller import mac_to_port
from ryu.controller.handler import MAIN_DISPATCHER
from ryu.controller.handler import set_ev_cls
from ryu.ofproto import ofproto_v1_0
from ryu.lib.mac import ... | , msg.in_port, dst, actions)
#We always send the packet_out to handle the first packet.
data = None
if msg.buffer_id == ofproto.OFP_NO_BUFFER:
data = msg.data
packet_out = datapath.ofproto_parser.OFPPacketOut(
datapath=datapath, buffer_id=msg.buffer_id, in_port=... | s, MAIN_DISPATCHER)
def _port_status_handler(self, ev):
msg = ev.msg
reason = msg.reason
port_no = msg.desc.port_no
ofproto = msg.datapath.ofproto
if reason == ofproto.OFPPR_ADD:
self.logger.info("port added %s", port_no)
elif reason == ofproto.OFPPR_DEL... |
rachel-fenichel/blockly | scripts/i18n/create_messages.py | Python | apache-2.0 | 6,375 | 0.009882 | #!/usr/bin/python3
# Generate .js files defining Blockly core and language messages.
#
# Copyright 2013 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org... |
target_defs = read_json_fil | e(os.path.join(os.curdir, arg_file))
# Verify that keys are 'ascii'
bad_keys = [key for key in target_defs if not string_is_ascii(key)]
if bad_keys:
print(u'These keys in {0} contain non ascii characters: {1}'.format(
filename, ', '.join(bad_keys)))
# If there's a '\n' or '... |
qtproject/pyside-pyside | tests/signals/signal2signal_connect_test.py | Python | lgpl-2.1 | 4,620 | 0.007359 | # -*- coding: utf-8 -*-
#############################################################################
##
## Copyright (C) 2016 The Qt Company Ltd.
## Contact: https://www.qt.io/licensing/
##
## This file is part of the test suite of PySide2.
##
## $QT_BEGIN_LICENSE:GPL-EXCEPT$
## Commercial License Usage
## Licensees ... | e_slot():
pass
class TestSignal2SignalConnect(unittest.TestCase):
'''Test case for signal to signal connections'''
def setUp(self):
#Set up the basic resources needed
self.sender = QObject()
self.for | warder = QObject()
self.args = None
self.called = False
def tearDown(self):
#Delete used resources
try:
del self.sender
except:
pass
try:
del self.forwarder
except:
pass
del self.args
def callback_n... |
holly00shit/blogMM | app/models.py | Python | bsd-3-clause | 2,981 | 0.017108 | from app import db, app
from hashlib import md5
import flask.ext.whooshalchemy as whooshalchemy
ROLE_USER = 0
ROLE_ADMIN = 1
followers = db.Table('followers',
db.Column('follower_id', db.Integer, db.ForeignKey('user.id')),
db.Column('followed_id', db.Integer, db.ForeignKey('user.id'))
)
class User(db.Mod... | , user):
return self.followed.filter(followers.c.followed_id == user.id).count() > 0
def followed_posts(self):
return Post.query.join(followers,
(followers.c.followed_id == Post.user_id)).filter(followers.c.follower_id == self.id).order_by(Post.timestamp.desc())
... | body']
id = db.Column(db.Integer, primary_key = True)
body = db.Column(db.String(140))
timestamp = db.Column(db.DateTime)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
def __repr__(self):
return '<Post %r>' % (self.body)
@classmethod
def all_posts(self):
... |
reclosedev/lathermail | lathermail/compat.py | Python | mit | 421 | 0.002375 | import sys
IS_PY3 = sys. | version_info[0] == 3
if IS_PY3:
from http.client import NO_CONTENT
from email import encoders as Encoders
from urllib.parse import quote, urlencode
unicode = str
bytes = bytes
else:
from email import Encoders
from httplib import NO_CONTENT
fr | om urllib import quote, urlencode
unicode = unicode
_orig_bytes = bytes
bytes = lambda s, *a: _orig_bytes(s)
|
DarthMaulware/EquationGroupLeaks | Leak #5 - Lost In Translation/windows/Resources/Dsz/PyScripts/HelperScripts/_NotAvailable.py | Python | unlicense | 695 | 0.010072 | # uncompyle6 version 2.9.10
# Python bytecode 2.7 (62211)
# Decompiled from: Pyth | on 3.6.0b2 (default, Oct 11 2016, 05:27:10)
# [GCC 6.2.0 20161005]
# Embedded file name: _NotAvailable.py
import dsz
import sys
def main():
try:
cmdId = int(sys | .argv[1])
cmdName = dsz.cmd.data.Get('CommandMetaData::Name', dsz.TYPE_STRING, cmdId=cmdId, checkForStop=False)[0]
except:
cmdName = ''
if len(sys.argv) > 2:
reason = ' (%s)' % sys.argv[2]
else:
reason = ''
dsz.ui.Echo("Command '%s' is not available on this platform%s" %... |
Mapita/mapita_ci | mapita/mapita_ci/settings_geojson_rest.py | Python | mit | 8,582 | 0.006875 | import os
# Django settings for geonition project.
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True... | ('fi', 'Suomi'),)
# Language code for this installation. All choice | s can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en'
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a val... |
AndresYague/Snuppat | output/figuresAndTables/finalGraph.py | Python | mit | 7,072 | 0.015837 | import sys, math, os
import matplotlib.pyplot as plt
def main():
# Check that there's at least one argument
if len(sys.argv) < 2:
print("Usage python {} <file1> [<file2> ...]".format(sys.argv[0]))
return 1
# Automatically detect if decayed
if "decayed" in sys.argv[1]:
plotD... | "Ge":32, "Se":34, "Kr":36, "Sr":38, "Zr":40,
"Mo":42, "Pd":46, "Cd":48, "Sn":50, "Te":52, "Ba":56,
"Ce":58, "Nd":60, "Sm":62, "Gd":64, "Dy":66, "Er":68,
"Yb":70, "Hf":72, "W":74, "Os":76, "Hg":80, "Pb":82,
"Rb":37, "Cs":55}
rNamAtm = ["Rb", "Cs"]
for na... | yVal = 0
for ii in range(len(xx)):
if xx[ii] == namAtm[name]:
yVal = finalValues[-1][ii]
break
plt.text(namAtm[name] - 0.5, yVal*1.01, name, size = 14)
if name in rNamAtm:
plt.plot(namAtm[name], yVal, "ro")
... |
ptroja/spark2014 | testsuite/gnatprove/tests/PC07-016__flow_write_object_to_ali/test.py | Python | gpl-3.0 | 56 | 0 | fr | om test_support import *
do_flow(opt=["--mode=fl | ow"])
|
alexander-emelyanov/microblog | manage.py | Python | mit | 305 | 0.003279 | #!env/bin/python
from flask.ext.script imp | ort Manager
from flask.ext.migrate import Migrate, MigrateCommand
from app import app, db
app.config.from_object('config')
migrate = Migrate(app, db)
manager = Manager(a | pp)
manager.add_command('db', MigrateCommand)
if __name__ == '__main__':
manager.run() |
eeneku/baller | src/engine/system.py | Python | gpl-3.0 | 235 | 0.012766 | # -*- cod | ing: utf-8 -*-
class System(object):
""" This is the father class for all different systems. """
def __init__(self, *args, **kwargs):
pass
def update(self, dt):
raise NotImplementedEr | ror
|
btengels/supergametools | __init__.py | Python | gpl-3.0 | 101 | 0 | """
mats | tat docstrings
"""
# from supergame import supergame
# from supergamet | ools import supergame
|
arfar/art-py | apis.py | Python | gpl-2.0 | 2,779 | 0 | import urllib
import urllib2
import json
import difflib
import pylast
class iTunesAlbumArt(object):
def __init__(self):
self.base_url = 'https://itunes.apple.com/search'
self.limit = 50
def _form_url(self, artist):
args_dict = {'limit': self.limit,
'term': artist}... | = 0:
return None
tracks = response_json['results']
track = self._find_album(tracks, album)
if not track:
return None
| large_picture_url = self._get_largest_pic_url(track['artworkUrl100'])
return large_picture_url
class LastFMAlbumArt(object):
"""
Trivially stupid stub
I just wanted to make it look consistant with the iTunes one
"""
def __init__(self, key=None, secret=None):
if not key or not sec... |
FeiZhan/Algo-Collection | answers/leetcode/Generate Parentheses/Generate Parentheses.py | Python | mit | 597 | 0.001675 | class Solution(object):
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
parent_list = []
self.helper(0, n, "", parent_list)
return parent_list
def helper(self, left, total, parent, parent_list):
if left >= total and len(pa... | parent_list.append(parent)
return
if left < total:
self.helper(left + 1, total, parent + '(', parent_list)
if len(parent) < left + left:
| self.helper(left, total, parent + ')', parent_list)
|
vitaliykomarov/NEUCOGAR | nest/code_generator/run/generated/data.py | Python | gpl-2.0 | 11,367 | 0.012404 | import nest
import numpy as np
nest.ResetKernel()
nest.SetKernelStatus({'overwrite_files': True, 'local_num_threads': 4, 'resolution': 0.1})
number_of_neuron = 18567530
DEFAULT = 10
raphenucleus = (
)
lateralcortex_5HT_NN = int(1000 / 18567530 * number_of_neuron)
if lateralcortex_5HT_NN < DEFAULT : lateralcortex_5... | hippocampus_5HT_NN = int(4260000 / 18567530 * number_of_neuron)
if hippocampus_5HT_NN < DEFAULT : hippocampus_5HT_NN = DEFAULT
hippocampus = (
{'Name': 'hippocampus[hippocampus_5HT]', 'NN': hippocampus_5HT_NN, 'Model': 'iaf_psc_alpha', 'IDs': nest.Create('iaf_psc_alpha', hippocampus_5HT_NN)},
)
hippocampus_5HT = 0
R... | gmentalarea = (
{'Name': 'lateraltegmentalarea[lateraltegmentalarea_5HT]', 'NN': lateraltegmentalarea_5HT_NN, 'Model': 'iaf_psc_alpha', 'IDs': nest.Create('iaf_psc_alpha', lateraltegmentalarea_5HT_NN)},
)
lateraltegmentalarea_5HT = 0
neocortex_5HT_NN = int(100 / 18567530 * number_of_neuron)
if neocortex_5HT_NN < DEFAU... |
gburd/dbsql | src/py/doc/code/connect_db_1.py | Python | gpl-3.0 | 69 | 0 | from pysqlit | e2 import dbapi2 as sqlite
con = sqlite.connect("mydb | ")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.