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
ai-se/parGALE
algorithms/serial/gale/where.py
Python
unlicense
11,293
0.013814
from __future__ import print_function, division import sys, os sys.path.append(os.path.abspath(".")) from binary_tree import BinaryTree from utils.lib import * from algorithms.serial.algorithm import Algorithm def settings(): return O( verbose = False, b4 = '|.. ', seed = 1, is_binary = True, ) ...
hest(problem, pop) self.c = self.west.dist(problem, self.east, is_obj=False) for one in pop: a = one.dist(problem, self.west, is_obj=False) b = one.dist(problem, self.east, is_obj=False) one.x = Node.projection(a, b, self.c) one.c = self.c one.a = a one.b = b pop = sorted...
def split(self, pop, cut): """ Split the population at the midpoint :param pop: :return: """ self.x = pop[cut].x self.east = pop[0] self.west = pop[-1] return pop[:cut], pop[cut:] def divide(self, threshold, abort = False): """ Recursively partition tree :param thresh...
joshmoore/openmicroscopy
components/tools/OmeroWeb/omeroweb/webadmin/controller/uploadfile.py
Python
gpl-2.0
1,449
0.008972
#!/usr/bin/env python # # # # Copyright (c) 2008 University of Dundee. # # This program 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 your option) any la...
ot, see <http://www.gnu.org/licenses/>. # # Author: Aleksandra Tarkowska <A(dot)Tarkowska(at)dundee(dot)ac(dot)uk>, 2008. # # Version: 1.0 # from omero.rtypes import * from omero.model import ExperimenterAnnotationLinkI from django.utils.encoding import smart_str from webadmin.controller import BaseController cla...
if newFile.content_type.startswith("image"): f = newFile.content_type.split("/") format = f[1].upper() else: format = newFile.content_type self.conn.uploadMyUserPhoto(smart_str(newFile.name), format, newFile.read())
gkmngrgn/puding
puding/constants.py
Python
gpl-3.0
1,582
0
#!/usr/bin/python # -*- coding: utf-8 -*- # # author: Gökmen Görgen # license: GPLv3 (Read COPYING file.) # from os import getenv LOCALE = "/usr/share/locale" VERSION = "0.2" HOME = "%s/.puding" % getenv("HOME") SYSLINUX = "/usr/lib/syslinux" URL = "http://www.gokmengorgen.net/puding" CORE_DEVELOPER = u"Gökmen Görgen...
at] googlemail.com es: Klemens Häckel click3d [at] linuxmail. org fr: Philippe Svetoslavsky, philsvet [at] gmail.com nl: Anton Tolboom, atolboo [at] gmail.com sv: Patrik Karlsson, patrik [at] pardus.nu tr: Necmettin Begiter, necmettin.beg
iter [at] gmail.com """ SUMMARY = "An USB Image Creator For Pardus Linux." DESCRIPTION = "Puding is an USB image creator for Pardus Linux." YEAR = "2009" COPYRIGHT = u"Copyright (c) %s TUBITAK / UEKAE" % YEAR LICENSE_NAME = "GPLv3" LICENSE = """%s Puding is a free software; you can redistribute it and/or modify it und...
ANCIR/siyazana.co.za
connectedafrica/scrapers/npo.py
Python
mit
4,358
0.000688
import logging import json import os import re #from pprint import pprint #from itertools import count from urlparse import urljoin from lxml import html from thready import threaded import requests from scrapekit.util import collapse_whitespace from connectedafrica.scrapers.util import MultiCSV from connectedafrica....
: yield i def scrape_npo(csv, i): url = URL_PATTERN % i cache_path = make_cache(i) if not os.path.exists(cache_path): res = requests.get(url) page = { 'url': url, 'http_status': res.status_code,
'content': res.content.decode('utf-8') } with open(cache_path, 'wb') as fh: json.dump(page, fh) else: with open(cache_path, 'rb') as fh: page = json.load(fh) if 'internal server error' in page['content']: return data = {} doc = html.fromstr...
HorizonFoxtrot/Redlist
redlist.py
Python
gpl-3.0
13,314
0.005558
# Redlist - a user tracker for Reddit # Version 1.1.9 import praw, time, cmd, tabulate from colorama import init, Fore, Back, Style init(autoreset = True) print("What platform are you running Redlist on?\nThis is required by the Reddit API guidelines.") PLATFORM = input("--> ").lower() print("\n") CLIENT_VERSION = ...
ywords or subreddits have been marked. Do you want to initiate tracking?") decision = input(Fore.CYAN + "[y/n]--> " + Style.BRIGHT) if decision.lower() == "n": return False elif decision.lower() == "y": break if self.alert...
print(Fore.WHITE + "No alerts have been activated. Do you want to initiate tracking?") decision = input(Fore.CYAN + "[y/n]--> " + Style.BRIGHT) if decision.lower() == "n": return False elif decision.lower() == "y": break ...
rmikio/lottery
testjson.py
Python
gpl-3.0
1,125
0.018667
import string import urllib, json # MassCash - start date: March 1991 #print("id;date;n1;n2;n3;n4;n5") for year in xrange(1991,2018): for month in xrange(1,12): drawdate=str(year)+str(month).zfill(2) url = "http://www.masslottery.com/data/json/search/lotterygames/12/"+drawdate+".json" # prin...
"No draws on %s"%(drawdate)) # print(";;;;;;")
pass
SUSE/azure-sdk-for-python
azure-batch/azure/batch/models/cloud_pool.py
Python
mit
16,446
0.001094
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
property and virtualMachineConfiguration are mutually exclusive and one of the properties must be specified. This property cannot be specified if the Batch account was created with its poolAllocationMode property set to 'UserSubscription'. :type cloud_service_configuration: :class:`CloudServiceConfig...
for the pool. This property and cloudServiceConfiguration are mutually exclusive and one of the properties must be specified. :type virtual_machine_configuration: :class:`VirtualMachineConfiguration <azure.batch.models.VirtualMachineConfiguration>` :param resize_timeout: The timeout for allocation...
SohKai/ChronoLogger
web/flask/lib/python2.7/site-packages/tempita/__init__.py
Python
mit
39,809
0.000955
""" A small templating language This implements a small templating language. This language implements if/elif/else, for/continue/break, expressions, and blocks of Python code. The syntax is:: {{any expression (function calls etc)}} {{any expression | filter}} {{for x in y}}...{{endfor}} {{if x}}x{{elif y}}y...
' % ( msg, self.position[0], self.position[1]) if self.name: msg += ' in %s'
% self.name return msg class _TemplateContinue(Exception): pass class _TemplateBreak(Exception): pass def get_file_template(name, from_template): path = os.path.join(os.path.dirname(from_template.name), name) return from_template.__class__.from_filename( path, namespace=from_templa...
okuta/chainer
tests/chainer_tests/functions_tests/math_tests/test_average.py
Python
mit
6,055
0
import unittest import numpy import six from chainer import functions from chainer import testing from chainer.testing import attr from chainer import utils @testing.parameterize(*( testing.product({ 'shape': [(3, 2, 4)], 'axis': [None, 0, 1, 2, -1, (0, 1), (1, -1)], 'dtype': [numpy.floa...
x = numpy.random.uniform(3000, 7000, self
.shape).astype(self.dtype) return x, def forward(self, inputs, device): x, = inputs y = functions.average( x, self.axis, keepdims=self.keepdims) return y, def forward_expected(self, inputs): x, = inputs y_expect = numpy.mean( x.astype(num...
shastah/spacewalk
backend/server/rhnHandler.py
Python
gpl-2.0
3,217
0.000311
# # Copyright (c) 2008
--2015 Red Hat, Inc. # # This software is licensed to you under the GNU General Public License, # version 2 (GPLv2). There is NO WARRANTY for this software, express or # implied, including the implied warranties of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2 # along w...
-2.0.txt. # # Red Hat trademarks are not licensed under GPLv2. No permission is # granted to use or replicate Red Hat trademarks that are incorporated # in this software or its documentation. # # from spacewalk.common.rhnLog import log_debug, log_error from spacewalk.common.rhnConfig import CFG from spacewalk.common.r...
rkmaddox/mne-python
mne/io/nirx/nirx.py
Python
bsd-3-clause
19,728
0
# Authors: Robert Luke <mail@robertluke.net> # # License: BSD (3-clause) from configparser import ConfigParser, RawConfigParser import glob as glob import re as re import os.path as op import datetime as dt import json import numpy as np from ..base import BaseRaw from ..utils import _mult_cal_one from ..constants i...
nfo']['Version']}") else: if hdr['GeneralInfo']['NIRStar'] not in ['"15.0"', '"15.2"', '"15.3"']: raise RuntimeError('MNE does not support thi
s NIRStar version' ' (%s)' % (hdr['GeneralInfo']['NIRStar'],)) if "NIRScout" not in hdr['GeneralInfo']['Device'] \ and "NIRSport" not in hdr['GeneralInfo']['Device']: warn("Only import of data from NIRScout devices have been " ...
Teamxrtc/webrtc-streaming-node
third_party/depot_tools/gcl.py
Python
mit
52,013
0.011151
#!/usr/bin/env python # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """\ Wrapper script around Rietveld's upload.py that simplifies working with groups of files. """ import json import optparse impo...
while True: line = p.stdout.readline() if not line: break if print_output: print line.strip('\n') output_array.append(line) output = "".join(output_array) else: output =
p.stdout.read() p.wait() p.stdout.close() return output, p.returncode def RunShell(command, print_output=False): """Executes a
sebp/scikit-survival
tests/test_forest.py
Python
gpl-3.0
9,388
0.001704
import numpy from numpy.testing import assert_array_almost_equal import pytest from sklearn.pipeline import make_pipeline from sksurv.datasets import load_breast_cancer from sksurv.ensemble import ExtraSurvivalTrees, RandomSurvivalForest from sksurv.preprocessing import OneHotEncoder from sksurv.testing import assert_...
orest_cls(oob_score=True, random_state=2).fit(whas500.x[50:], y[50:]) forest_i =
forest_cls(oob_score=True, random_state=2).fit(whas500.x[50:], y_int[50:]) assert len(forest_f.estimators_) == len(forest_i.estimators_) assert forest_f.n_features_in_ == forest_i.n_features_in_ assert forest_f.oob_score_ == forest_i.oob_score_ assert_array_almost_equal(forest_f.event_times_, forest_i....
thorbenk/knossos-svn
tools/kconfig.py
Python
gpl-2.0
9,251
0.003567
# # This file is a part of KNOSSOS. # # (C) Copyright 2007-2011 # Max-Planck-Gesellschaft zur Foerderung der Wissenschaften e.V. # # KNOSSOS is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 of # the License as published by the Free So...
except AttributeError: raise DataError("Error matching file name") return xlen_datacubes, ylen_datacubes, zlen_datacubes = 0, 0, 0 for file in files: try: x = int(self.xReg.search(file).groups()[0]) y = int(self.yReg.search(file).gro...
if x > xlen_datacubes and x < 9999: xlen_datacubes = x if y > ylen_datacubes and y < 9999: ylen_datacubes = y if z > zlen_datacubes and z < 9999: zlen_datacubes = z xlen_px = (xlen_datacubes + 1) * edgeLength ylen_px...
PythonScanClient/PyScanClient
Test/test_alignment.py
Python
epl-1.0
1,016
0.002953
"""Unit test of the AlignmentScan @author: Kay Kasemir """ from __future__ import print_function import unittest from scan.commands import Set, CommandSequence from scan.alignment import AlignmentScan class AlignmentTest(unittest.TestCase): def testBasics(self): align = AlignmentScan("motor_x", 0, 10,...
signal', 'motor_x'), Script('WriteDataToPV', 'motor_x', 'Demo:CS:Scan:Fit:Data:X'), Script('WriteDataT
oPV', 'signal', 'Demo:CS:Scan:Fit:Data:Y', '-', '1') ]), Script('FindPeak', 'motor_x', 'signal', '-', '1', 'Demo:CS:Scan:Fit:Pos', 'Demo:CS:Scan:Fit:Height', 'Demo:CS:Scan:Fit:Width')]") if __name__ == "__main__": unittest.main()
SintefRaufossManufacturing/python-hcn
demo.py
Python
lgpl-3.0
842
0.017815
import numpy as np import hcn from IPython
import embed, get_ipython import vtk_visualizer as vv if __name__ == "__main__": m = hcn.Model3D.from_file("b4.obj", "m") m = m.select_x(0, 1) m = m.select_y(0, 1) m = m.select_z(0.01, 1) vv.plotxyz(m.to_array(), block=True) sm = m.smoothed(knn=160, order=1) vv.plotxyz(sm.to_array(), block...
= sm.sampled(0.01) #vv.plotxyz(new.to_array(), block=True) #nn = m.compute_normals(20, 2) #a = nn.to_array() #print(a) #b = nn.normals_to_array() #print(b) #res = np.hstack((a, b)) #print(res) #vv.plothh(res, block=True) #s = m.create_surface_model(0.1) #embed()
mkyl/Physical-Web-CMS-Server
server/presentation.py
Python
apache-2.0
5,186
0.005594
import os import json import urllib.request import mimetypes from pathlib import Path from distutils.dir_util import copy_tree HTML_PAGE_HEADER = '<!DOCTYPE html> \n <html> \n <head> \ <title> Physical Web Exhibit </title>\ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/shoelace-css/1.0.0-beta13/...
e: id = json.load(data_file)["active-exhibit"] active_exhibit_folder = os.path.join(exhibits_folder, str(id)) return active_exhibit_folder def _find_beacon_friendly_names(exhibits_folder): metadata_file = os.path.join(exhibits_folder, 'metadata.json') with open(metadata_file) as data_file: ...
ata_file) as data_file: return json.load(data_file) def build_website(exhibits_folder, public_folder): print(" [i] Creating HTML") os.makedirs(public_folder, exist_ok=True) active_exhibit_folder = _find_active_exhibit(exhibits_folder) beacon_friendly_names = _find_beacon_friendly_names(exhi...
aspectron/jsx
extern/v8/tools/js2c.py
Python
mit
16,982
0.010894
#!/usr/bin/env python # # Copyright 2012 the V8 project 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: # # * Redistributions of source code must retain the above copyright # noti...
.compile(r'^const\s+([a-zA-Z0-9_]+)\s*=\s*([^;]*);$') MACRO_PATTERN =
re.compile(r'^macro\s+([a-zA-Z0-9_]+)\s*\(([^)]*)\)\s*=\s*([^;]*);$') PYTHON_MACRO_PATTERN = re.compile(r'^python\s+macro\s+([a-zA-Z0-9_]+)\s*\(([^)]*)\)\s*=\s*([^;]*);$') def ReadMacros(lines): constants = [] macros = [] for line in lines.split('\n'): hash = line.find('#') if hash != -1: line = line[:...
tbenthompson/taskloaf
setup.py
Python
mit
689
0.039187
from setuptools import setup version = open('VERSION').read() try: i
mport pypandoc description = pypandoc.convert('README.md', 'rst') except (IOError, ImportError): description = open('README.md').read() setup( packages = ['taskloaf'], install_requires = ['uvloop', 'cloudpickle', 'pycapnp', 'attrs', 'structlog', 'p
yzmq'], zip_safe = False, include_package_data = True, name = 'taskloaf', version = version, description = '', long_description = description, url = 'https://github.com/tbenthompson/taskloaf', author = 'T. Ben Thompson', author_email = 't.ben.thompson@gmail.com', license = 'MIT...
IIazertyuiopII/PDS_sonification
python/VirtualScreen.py
Python
mit
2,759
0.047119
import math class VirtualScreen: #cet ecran est normal a l'axe Z du Leap def __init__(self,Xoffset=0,Yoffset=50,Zoffset=-50,Zlimit=220,length=350,height=300): #en mm self.Xoffset = Xoffset; # position du milieu du bord bas de l'ecran par rapport au centre du Leap self.Yoffset = Yoffset; # position du milieu ...
sition): #donner un vecteur position 3d en mm suivant les axes du Leapmotion ([x,y,z]) isXvalid = (position[0] <= self.Xoffset+self.length/float(2)) and (position[0] >= self.Xoffset-self.length/float(2)) isYvalid = (position[1] <= self.Yoffset+self.height) and (position[1] >= self.Yoffset) isZvalid = (position[2]...
set) return isXvalid and isYvalid and isZvalid def getScreenZonePointedAt(self,position,direction): if not self.isFacingTheScreen(position): return -1 else: lambdaIntersection = (self.Zoffset-position[2])/direction[2] # (Zoffset-Zpoint)/Zdirecteur xIntersection = position[0] + lambdaIntersection*direc...
tlatzko/spmcluster
.tox/docs/bin/rst2latex.py
Python
bsd-2-clause
828
0.001208
#!/Users/latzko/work/spmcluster/.tox/docs/bin/python2.7 # $Id: rst2latex.py 5905 2009-04-16 12:04:49Z milde $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ A minimal front end to the Docutils Publisher, producing LaTeX. """ try: import locale ...
'<destination> (default is stdout). See ' '<http://docutils.sourceforge.net/docs/user/latex.html> for ' 'the full reference.') publish_cmdline(writer_name='latex', desc
ription=description)
dNG-git/pas_upnp
src/dNG/data/upnp/service.py
Python
gpl-2.0
19,564
0.007872
# -*- coding: utf-8 -*- """ direct PAS Python Application Services ---------------------------------------------------------------------------- (C) direct Netware Group - All
rights reserved https://www.direct-netware.de/redirect?pas;upnp The following license agreement remains valid unless any additions or changes are being made by direct Netware Group in a written form. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public Lice...
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, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License...
tamasgal/rlogbook
rlogbook/computing/migrations/0005_auto_20141127_1436.py
Python
mit
1,018
0.001965
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('computing', '0004_auto_20141127_1425'), ] operations = [ migrations.CreateModel( name='Subnet', fiel...
imary_key=True)), ('name', models.CharField(max_length=200)), ('from_ip', models.CharField(max_length=15)), ('to_ip', models.CharField(max_length=15)), ], options={ }, bases=(models.Model,), ), migrations.Del...
model_name='computer', name='subnet', field=models.ForeignKey(blank=True, to='computing.Subnet', null=True), preserve_default=True, ), ]
HunanTV/redis-ctl
test/auto_balance.py
Python
mit
15,140
0
import json import hashlib from daemonutils.auto_balance import add_node_to_balance_for import config import base import models.node import
models.cluster import models.task from models.cluster_plan import ClusterBalancePlan, get_balance_plan_by_addr REDIS_SHA = hashlib.sha1('redis').hexdigest() def _get_balance_plan(plan): return ClusterBalancePlan(balance_plan_json=json.dumps(plan)) class AutoBalance(base.TestCase): def test_get_plan(se
lf): with self.app.test_client() as client: n0 = models.node.create_instance('10.0.0.1', 6301) n1 = models.node.create_instance('10.0.0.1', 6302) n2 = models.node.create_instance('10.0.0.2', 6301) c0 = models.cluster.create_cluster('the quick brown fox') ...
fake-name/ReadableWebProxy
WebMirror/management/rss_parser_funcs/feed_parse_extractFujoshimoshiBlogspotCom.py
Python
bsd-3-clause
562
0.033808
def extractFujoshimoshiBlogspotCom(item): ''' Parser for 'fujoshimoshi.blogspot.com' ''' vol, chp, frag, postfix =
extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None 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) return False
mindbender-studio/core
avalon/lib.py
Python
mit
7,716
0
"""Helper functions""" import os import sys import json import logging import datetime import importlib import subprocess import types from . import schema from .vendor import six, toml PY2 = sys.version_info[0] == 2 log_ = logging.getLogger(__name__) # Backwards compatibility logger = log_ __all__ = [ "time"...
>>> myclass.log.info('Hello World') """ modul
e = cls.__module__ name = cls.__name__ # Package name appended, for filtering of LogRecord instances logname = "%s.%s" % (module, name) cls.log = logging.getLogger(logname) # All messages are handled by root-logger cls.log.propagate = True return cls def dict_format(original, **kwargs):...
linostar/timeline-clone
source/timelinelib/plugin/pluginbase.py
Python
gpl-3.0
1,075
0
# Copyright (C) 2009, 2010, 2011 Rickard Lindberg, Roger Lindberg # # This file is part of Timeline. # # Timeline 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...
RTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Timeline. If not, see <http://www.gnu.org/licenses/>. class PluginBase(object): def isplugin(self): return True def display_name(self): ...
*args, **kwargs): raise NotImplementedError("run not implemented.")
kuggenhoffen/CoAPthon
coapthon/client/coap_protocol.py
Python
mit
23,736
0.000843
import os import random import re import time import twisted from twisted.application.service import Application from twisted.internet.error import AlreadyCancelled from twisted.python import log from twisted.python.log import ILogObserver, FileLogObserver from twisted.python.logfile import DailyLogFile from coapthon i...
def send(self, message): # print "SEND\n" serializer = Serializer() if message.destination is None: message.destination = self.server host, port = message.destination print "Message sent to " + host + ":" + str(port) print "------------------------------
----------" print message print "----------------------------------------" datagram = serializer.serialize(message) log.msg("Send datagram") self.transport.write(datagram, message.destination) def send_callback(self, req, callback, client_callback): if req.mid is Non...
tseaver/google-cloud-python
monitoring/google/cloud/monitoring_v3/gapic/metric_service_client.py
Python
apache-2.0
43,991
0.002114
# -*- coding: utf-8 -*- # # Copyright 2019 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law...
dentials``; providing both will raise an exception. credentials (google.auth.credentials.Credentials): The authorization credentials to attach to requests. These credentials identify this application to the service. If none are specified, the c
lient will attempt to ascertain the credentials from the environment. This argument is mutually exclusive with providing a transport instance to ``transport``; doing so will raise an exception. client_config (dict): DEPRECATED. A dictionary of ...
ella/mypage
mypage/rsswidgets/migrations/0003_add_config.py
Python
bsd-3-clause
1,553
0.01159
from south.db import db from django.db import models from mypage.rsswidgets.models import * class Migration: def forwards(self, orm): # Adding field 'MultiRSSWidget.config_json' db.add_column('rsswidgets_multirsswidget', 'config_json', models.TextField()) def b...
.models.Widget']}, 'config_json': ('models.TextField', [], {}), 'widget_ptr': ('models
.OneToOneField', ["orm['widgets.Widget']"], {}) } } complete_apps = ['rsswidgets']
stefangri/s_s_productions
PHY341/V_302_Brueckenschaltung/Messdaten/auswertung.py
Python
mit
10,629
0.029342
import numpy as np import uncertainties.unumpy as unp from uncertainties import ufloat import math from scipy.optimize import curve_fit import matplotlib.pyplot as plt from pint import UnitRegistry u = UnitRegistry() Q_ = u.Quantity #umrechnung einheiten mit var.to('unit') # Einheiten für pint:dimensionless, meter, s...
andberechnung def wider(R_2,R_3,R_4): teil_a_r_3durch4=R_3/R_4 return R_2*teil_a_r_3durch4 teil_a_widerstand_x=wider(teil_a_widerstand_2,teil_a_widerstand_3,teil_a_widerstand_4) print(teil_a_widerstand_x) teil_a_widerstand_x
_mittel=mittel_und_abweichung_intervall(teil_a_widerstand_x,3) #print('Teil a, Widerstand R_x',teil_a_widerstand_x) print('\n') print('Teil a, r_2', teil_a_widerstand_2) print('Teil a, R_3 und r_4', teil_a_widerstand_3,teil_a_widerstand_4) print('Teil a, Widerstand R_x ',teil_a_widerstand_x) print('Teil a, Widerstand ...
brickman1444/hft-wordchain
chain_generator/generateChains.py
Python
bsd-3-clause
2,594
0.032382
import json import copy import pdb # constants wordPairFileName = "wordPairs.json" wordChainFileName = "wordLists.json" chainLength = 6 def appendWordsToChain(partialChain, retList, shortList, pairDictionary): lastWord = partialChain[-1] if lastWord not in pairDictionary: # end of the line shortList.append...
re too short for firstWord in pairDictionary: chain = [firstWord] chain = appendWordsToChain(chain,retList,shortList,pairDictionary) print("Short List:") shortCount = 0 for list in shortList: if len(list) == (chainLength - 1) and list[0] not in reverseDictionary: print(list) shortCount += 1 print(...
rseDictionary(pairDictionary): retDict = {} # go through the whole list for firstWord, secondWords in pairDictionary.items(): # for each second word for secondWord in secondWords: # only process a second word once if secondWord in retDict: continue retDict[secondWord] = [] # go through the...
mohamedhagag/dvit-odoo
product_pack_pos/__manifest__.py
Python
agpl-3.0
665
0
{ 'name': 'Product Pack POS َfor IngAdhoc', 'summary': 'Product packs on POS', 'description': """ This module is extension َfor INGADHOC's module product_pack that will Process product_pack pickings َfrom POS sales. Note: this module works
with Fixed price packs only. """, 'version': '10.0.0.2', 'category': 'Point oَf Sale', 'author': 'DVIT.me', '
website': 'http://dvit.me', 'license': 'AGPL-3', 'depends': ['product_pack', 'point_oَf_sale'], 'data': [], 'demo': [], "images": [ 'static/description/banner.png' ], 'installable': True, 'auto_install': True, 'application': False, }
matsumoto-r/synciga
src/build/android/bb_run_sharded_steps.py
Python
bsd-3-clause
7,158
0.0095
#!/usr/bin/env python # # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Helper script to shard build bot steps and save results to disk. Our buildbot infrastructure requires each slave to run steps...
if not ports.ResetTestServerPortAllocation(): raise Exception('Failed to reset test server port.') # Sort the devices so that we'll try to always run a step in the same device. devices = sorted(android_commands.GetAttachedDevices()) if not devices: print 'You must attach a device' return 1 with f...
[] if options.flaky_steps: with file(options.flaky_steps, 'r') as f: flaky_steps = json.load(f) return _RunShardedSteps(steps, flaky_steps, devices) if __name__ == '__main__': sys.exit(main(sys.argv))
bgarrels/sky
sky/money.py
Python
bsd-3-clause
3,699
0.002163
import re locale_US = {'symbol': r'\$', 'currency': r'dollar[s]*', 'units': [('million', 10**6), ('m', 10**6), ('mn', 10**6), ('mil', 10**6), ('thousand', 10**3), ('k', 10**3), ('billion', 10**9), ('b', 10**9), ('bn', 10**9), ...
lue(
x[1]), x[0].start, x[0].stop) for x in matches] return [r for r in results if min_amount < r[1] < max_amount] def convertMatchToValue(self, match): value = match[0].replace(',', '.').strip('.') modifier = 1000 ** (len(re.findall(r'\.\d{3}[^0-9]', value)) + bool...
brajput24/fabric-bolt
fabric_bolt/wsgi.py
Python
mit
352
0.008523
import os import os.
path import sys # Add the project to the python path sys.path.insert(0, os.path.join(os.path.dirname(__file__), os.pardir)) sys.stdout = sys.stderr # Configure the application (Logan) from fabric_bolt.utils.runner import config
ure configure() from django.core.wsgi import get_wsgi_application application = get_wsgi_application()
hugovk/coveragepy
ci/parse_relnotes.py
Python
apache-2.0
3,133
0.001596
#!/usr/bin/env python3 """ Parse CHANGES.md into a JSON structure. Run with two arguments: the .md file to parse, and the JSON file to write: python parse_relnotes.py CHANGES.md relnotes.json Every section that has something that looks like a version number in it will be recorded as the release notes for that versi...
"version": version, "text": text, "prerelease": prerelease, "when": when, } def parse(md_filename, json_filename): """Main function: parse markdown and write JSON.""" with open(md_filename) as mf: markdown = mf.read() with open(json_file...
# pylint: disable=no-value-for-parameter
hbock/bgasync
bgasync/aio/__init__.py
Python
bsd-2-clause
47
0.021277
"""
bgasync.aio - asyncio support for B
GAPI """
Chandra-MARX/marxs
marxs/math/polarization.py
Python
gpl-3.0
6,636
0.005274
# Licensed under GPL version 3 - see LICENSE.rst import numpy as np import astropy.units as u from .utils import norm_vector, e2h __all__ = ['polarization_vectors', 'Q_reflection', 'paralleltransport_matrix', 'parallel_transport'] def polarization_vectors(dir_array, angles): '''Converts polarization...
3, Oininv) pmat[~ind, :, :] = np.einsum('ijk,ikl->ijl', Oout, temp) factor = 1 if replace_nans else
np.nan pmat[ind, :, :] = factor * np.eye(3)[None, :, :] return pmat def parallel_transport(dir_old, dir_new, pol_old, **kwargs): '''Parallel transport of the polarization vector with no polarization happening. Parameters ---------- dir_old, dir_new : np.array of shape (n, 4) Old and n...
isohybrid/dotfile
vim/bundle/git:--github.com-klen-python-mode/pylibs/rope/contrib/codeassist.py
Python
bsd-2-clause
25,440
0.00055
import keyword import sys import warnings import rope.base.codeanalyze import rope.base.evaluate from rope.base import pyobjects, pyobjectsdef, pynames, builtins, exceptions, worder from rope.base.codeanalyze import SourceLinesAdapter from rope.contrib import fixsyntax from rope.refactor import functionutils def cod...
None: warnings.warn('Codeassist no longer
supports templates', DeprecationWarning, stacklevel=2) assist = _PythonCodeAssist( project, source_code, offset, resource=resource, maxfixes=maxfixes, later_locals=later_locals) return assist() def starting_offset(source_code, offset): """Return the offset in which th...
AnshulYADAV007/Lean
Algorithm.Python/CoarseFundamentalTop3Algorithm.py
Python
apache-2.0
3,479
0.010929
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. # Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corpo
ration. # # Licensed under the Apache License, V
ersion 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, ...
mvendra/mvtools
git/collect_git_patch.py
Python
mit
20,127
0.005366
#!/usr/bin/env python3 import sys import os import git_lib import path_utils import fsquery_adv_filter ERRMSG_EMPTY = "Empty contents" def _known_states(): st = ["??", "R ", "D ", "A ", "M ", " M", " D", "UU", "MM", "AM", "DD", "UA", "UD", "DU", "AA", "AU", "RM"] return st def _test_repo_status(repo_path...
_full, "w") as f: f.write(content) return True, output_filename_full def collect_git_patch_head(repo, storage_path, default_filter, include_list, exclude_list): head_items_final = [] head_items = [] funcs = [git_lib.get_head_modified_files, git_lib.get_head_deleted_files, gi
t_lib.get_head_updated_files, git_lib.get_head_modified_modified_files, git_lib.get_head_added_modified_files] v, r = _assemble_list_from_functions(repo, funcs) if not v: return False, "Unable to assemble list of head items on repo [%s]: [%s]" % (repo, r) head_items = r head_items_filtered = _a...
sataako/fmio-server
fmio/forecast.py
Python
mit
1,752
0.001142
# coding: utf-8 from __future__ import absolute_import, division, print_function, unicode_literals __metaclass__ = type import pandas as pd from pyoptflow import utils from pyoptflow.core import extract_motion_proesmans from pyoptflow.extrapolation import semilagrangian def read_rainrate(filename): return def ...
eries') tmax = c
ropped_rainrates.index.max() tmin = cropped_rainrates.index.min() dt = tmax-tmin index = pd.DatetimeIndex(freq=dt, periods=steps, start=tmax+dt) rr_ubyte = cropped_rainrates.apply(rr2ubyte) v = motion(rr_ubyte.iloc[0], rr_ubyte.iloc[1]) fcast_list = [] for t in range(steps): fcast_li...
OpenLD/enigma2-wetek
lib/python/Screens/ResolutionSelection.py
Python
gpl-2.0
1,827
0.031199
from Screen import Screen from Screens.ChoiceBox import ChoiceBox class ResolutionSelection(Screen): def __init__(self, session, infobar=None): Screen.__init__(self, session) self.session = session xresString = open("/proc/stb/vmpeg/0/xres", "r").read() yresString = open("/proc/stb/vmpeg/0/yres", "r").read()...
ist.append(("576p", "576p50")) tlist.append(("720p", "720p50")) tlist.append(("1080i", "1080i50")) tlist.append(("1080p@23.976hz", "1080p23")) tlist.append(("1080p@24hz", "1080p24")) tlist.append(("1080p@25hz", "1080p25")) keys = ["green", "yellow", "blue", "", "0", "1", "2", "3", "4", "5", "6", "7", "8", ...
(len(tlist)): if tlist[x][1] == mode: selection = x self.session.openWithCallback(self.ResolutionSelected, ChoiceBox, title=_("Please select a resolution..."), list = tlist, selection = selection, keys = keys) #return def ResolutionSelected(self, Resolution): if not Resolution is None: if isinstance(...
spring-week-topos/horizon-week
openstack_dashboard/test/test_data/utils.py
Python
apache-2.0
4,617
0
# Copyright 2012 Nebula, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agree...
return TestData(*loaders) class TestData(object): """Holder object for test data. Any functions passed to the init method will be called wi
th the ``TestData`` object as their only argument. They can then load data onto the object as desired. The idea is to use the instantiated object like this:: >>> import glance_data >>> TEST = TestData(glance_data.data) >>> TEST.images.list() [<Image: visible_image>, <Image: inv...
banglakit/spaCy
spacy/tests/sv/test_tokenizer.py
Python
mit
882
0.00344
# encoding: utf8 from __future__ import unicode_literals import pytest SV_TOKEN_EXCEPTION_TESTS = [ ('Smörsåsen används bl.a. till fisk', ['Smörsåsen', 'används', 'bl.a.', 'till', 'fisk']), ('Jag kommer först kl. 13 p.g.a. diverse förseningar', ['Jag', 'kommer', 'först', 'kl.', '13', 'p.g.a.', 'diverse', 'fö...
jaru", "Serru", "Fixaru"])
def test_tokenizer_handles_verb_exceptions(sv_tokenizer, text): tokens = sv_tokenizer(text) assert len(tokens) == 2 assert tokens[1].text == "u"
antong/ldaptor
ldaptor/samba/smbpassword.py
Python
lgpl-2.1
2,466
0.006894
import string, warnings from ldaptor import md4, config lower='abcdefghijklmnopqrstuvwxyz' upper=lower.upper() toupper=string.maketrans(lower, upper) def nthash(password=''): """Generates nt md4 password hash for a given password.""" password=password[:128] password=''.join([c+'\000' for c in password]) ...
ts[2] << 5) + (bits[3] << 4) + (bits[4] << 3)
+ (bits[5] << 2) + (bits[6] << 1)) return x bytes = (_pack(bits[:7]), _pack(bits[7:14]), _pack(bits[14:21]), _pack(bits[21:28]), _pack(bits[28:35]), _pack(bits[35:42]), _pack(bits[42:49]), _pack(...
mpi-sws-rse/datablox
blox/bookmark_client__1_0/bookmarks_ui/distributer.py
Python
apache-2.0
847
0.014168
import subprocess from subprocess import PIPE import sys if len(sys.argv) != 5: print "%s: requires a script name, URL file name arguments, number of instances and number of URLs to distribute" sys.exit(1) script = s
ys.argv[1] url_file = sys.argv[2] instances = int(sys.argv[3]) num_urls = int(sys.argv[4]) start_index = 0 distance = int(num_urls/instances) print "Num urls per instance:", distance pipes = [] while(instances > 0): end_index = start_index + distance if instances > 1 else num_urls if end_index > num_urls:
end_index = num_urls command = [sys.executable, script, url_file, str(start_index), str(end_index)] p1 = subprocess.Popen(command, stdout=PIPE) instances -= 1 start_index += distance pipes.append(p1) f = open("distributer_output", 'w') for p in pipes: f.write(p.communicate()[0]) sys.exit(0)
Shopify/shopify_python_api
test/tender_transaction_test.py
Python
mit
526
0.003802
import shopify from test.test_helper import TestCase class TenderTransactionTest(TestCase): def setUp(self): super(TenderTransactionTest, self).setUp() self.fake("tender_transactions", method="GET", body=self.load_fixture("tender_transactions")) def test_should_load_all_tender_transactions(se...
t
ender_transactions = shopify.TenderTransaction.find() self.assertEqual(3, len(tender_transactions)) self.assertEqual([1, 2, 3], list(map(lambda t: t.id, tender_transactions)))
dufresnedavid/canada
account_tax_expense_include/__init__.py
Python
agpl-3.0
1,045
0
# -*- encoding: utf-8 -*- ############################################################################## # # Odoo, Open Source M
anagement Solution # Copyright (C) 2010 - 2014 Savoir-faire Linux # (<http://www.savoirfairelinux.com>). # # This program 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 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 # MERCHANTA...
tritoanst/ccxt
python/ccxt/bitfinex2.py
Python
mit
19,036
0.003572
# -*- coding: utf-8 -*- from ccxt.bitfinex import bitfinex import hashlib from ccxt.base.errors import ExchangeError from ccxt.base.errors import NotSupported from ccxt.base.errors import InsufficientFunds class bitfinex2 (bitfinex): def describe(self): return self.deep_extend(super(bitfinex2, self).des...
ers': False, 'withdraw': True, 'deposit': False, }, 'timeframes': { '1m': '1m', '5m': '5m', '15m': '15m', '30m': '30m', '1h': '1h', '3h': '3h', '6h': '6...
2w': '14D', '1M': '1M', }, 'rateLimit': 1500, 'urls': { 'logo': 'https://user-images.githubusercontent.com/1294454/27766244-e328a50c-5ed2-11e7-947b-041416579bb3.jpg', 'api': 'https://api.bitfinex.com', 'www': 'https://ww...
andrejb/leap_mail
src/leap/mail/imap/tests/__init__.py
Python
gpl-3.0
13,000
0
# -*- encoding: utf-8 -*- """ leap/email/imap/tests/__init__.py ---------------------------------- Module intialization file for leap.mx.tests, a module containing unittesting code, using twisted.trial, for testing leap_mx. @authors: Kali Kaneko, <kali@leap.se> @license: GPLv3, see included LICENSE file @copyright: © ...
= Mock(side_effect=_put_doc_side_effect) def __call__(self): return self Soledad._shared_db = MockSharedDB() return Soledad( uuid, passphrase, secrets_path=secrets_path, local_db_path=local_db_path, server_url=se...
Down(self): self._db1.close() self._db2.close() self._soledad.close() # Key material for testing KEY_FINGERPRINT = "E36E738D69173C13D709E44F2F455E2824D18DDF" PUBLIC_KEY = """ -----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG v1.4.10 (GNU/Linux) mQINBFC9+dkBEADNRfwV23TWEoGc/x0wWH1P7PlXt8MnC2...
wanghaven/nupic
src/nupic/support/pymysqlhelpers.py
Python
agpl-3.0
4,179
0.003589
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2013, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This progra...
t; see nupic.support.initLogging() @retrySQL() def jobInfo(self, jobID): ... """ if logger is None: logger = logging.getLogger(__name__) def retryFilter(e, a
rgs, kwargs): if isinstance(e, (pymysql.InternalError, pymysql.OperationalError)): if e.args and e.args[0] in _ALL_RETRIABLE_ERROR_CODES: return True elif isinstance(e, pymysql.Error): if (e.args and inspect.isclass(e.args[0]) and issubclass(e.args[0], socket_error)): ret...
saiias/pymamemose
test/__init__.py
Python
bsd-3-clause
341
0.01173
#
! /usr/bin/env python # -*- coding: utf-8 -*- import sys from subprocess import Popen,STDOUT import os.path def suite(): cmd = ['py.test','r'] cmd.append(os.path.dirname(os.path.abspath(__file__))) errno = Popen(cmd, stdout=sys.stdout, st
derr=STDOUT).wait() raise SystemExit(errno) if __name__ == "__main__": suite()
vkscool/nupic
nupic/simple_server.py
Python
gpl-3.0
3,594
0.005565
#! /usr/bin/env python # ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2015, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions...
) def POST(self, name): """ /models/{name} schema: { "modelParams": dict containing model parameters "predictedFieldName": str } returns: {"success":name} """ global g_models data = json.loads(web.data()) modelParams = data["modelParams"]
predictedFieldName = data["predictedFieldName"] if name in g_models.keys(): raise web.badrequest("Model with name <%s> already exists" % name) model = ModelFactory.create(modelParams) model.enableInference({'predictedField': predictedFieldName}) g_models[name] = model return json.dumps({...
creyer/nursery
nursery.py
Python
apache-2.0
7,857
0.013491
#!/usr/bin/env python from __future__ import with_statement import argparse import sys import logging import urllib, urllib2 import json from fabric.operations import local from fabric.api import hide import yaml VERSION = "0.0.1" SERVER_FILE = ".server" logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) d...
else: req = urllib2.Request(url_2) try: logging.debug("executing get on: %s" % (url_2)) rsp = urllib2.urlopen(req)
except urllib2.URLError, e: logging.error("Error 3: couldn't communicate with the server on: %s" % (url_2)) sys.exit() return rsp.read() else: logging.error("Error 4: Can't comunicate with the server") sys.exit() class DeployAction(a...
Ziloi/ArrayHQ
tools/remove-after-character/remove-after-character.py
Python
unlicense
758
0.010554
import sys # Get
Filename and get file contents filename = raw_input('Enter a file name: ') file = open(filename) filecontents = filename.readlines() f.close() # Process... But first get input after how many letters or certain letter process_option = raw_input('Would you prefer to remove everything from a line after a certain characte...
n amount of characters "2" (1/2): ') if process_option == 1: letter = raw_input('Which letter?: ') if process_option == 2: number = raw_input('How many characters?: ') for line in filecontents: [line[i:i+number] for i in range(0, len(line), n)] array_option = raw_input('Would you like to print an array in...
MithileshCParab/HackerRank-10DaysOfStatistics
Problem Solving/Data Structure/Stacks/maximum_element.py
Python
apache-2.0
1,142
0.056918
class ArrayStack: def __init__(self): self._data = [] self.max = 0 def __len__(self): return len(self._data) def is_empty(self): return len(self._data) == 0 def get_max(self
): return self.max def push(self, e): self._data.
append(e) if self.max < e: self.max = e def pop(self): if self.is_empty(): raise Empty('Stack is empty') else: delelem = self._data[-1] del(self._data[-1]) if self.is_empty(): self.max = 0 elif self.max == delelem: self._cal_max() def _cal_max(self): self.max = 0 for elem in s...
zofuthan/airmozilla
bin/crontab/gen-crons.py
Python
bsd-3-clause
1,205
0
#!/usr/bin/env python import os from optparse import OptionParser from jinja2 import Template HEADER = '!!AUTO-GENERATED!! Edit bin/crontab/crontab.tpl instead.' TEMPLATE = open(os.path.join(os.path.dirname(__file__), 'crontab.tpl')).read() def main(): parser = OptionParser() parser.add_option('-w', '--web...
efined') ctx = {'django': 'cd %s; %s manage.py' % (opts.webapp, opts.python)} ctx['cron'] = '%s cron' % ctx['django'] if opts.user: for k, v in ct
x.iteritems(): ctx[k] = '%s %s' % (opts.user, v) # Needs to stay below the opts.user injection. ctx['python'] = opts.python ctx['header'] = HEADER print Template(TEMPLATE).render(**ctx) if __name__ == '__main__': main()
deeptir96/my_proj
src/my_proj/views.py
Python
mit
248
0.008065
from django.views import
generic class HomePage(generic.TemplateView): template_name = "home.html" class AboutPage(generic.TemplateView): template_name = "about.html" class GBNC(generic.TemplateView): template_name = "menug.h
tml"
nbari/db-sandbox
riak/cluster_read.py
Python
bsd-3-clause
597
0.001675
import riak import time from random import randint start_time = time.time() pool = ['10.15.129.215', '10.15.129.216', '10.15.129.217', '10.15.129.218', '10.15.129.219'] # Connect to Riak. client = [] for ip in pool: print ip c = riak.RiakClient(host=ip) c = c.bucket('test...
): print 'Stored data for key %d-%s: %s' % ( key, pool[key % 5], client[randint(0, 4)].g
et('%d-%s' % (key, pool[key % 5])).data) elapsed_time = time.time() - start_time print 'Execution time: %.4f' % (elapsed_time)
thekingofkings/ChicagoTaxi
dataPreprocess.py
Python
mit
2,086
0.009588
""" Pre-process Chicago taxi data for visualization. Author: Hongjian Date: 11/7/2015 The raw file is in the ../../../dataset/ChicagoTaxi/2013-dec.txt We map those trips to CA """ from shapely.geometry import Polygon, Point, box from Block import Block fraw = '../../dataset/ChicagoTaxi/2013-dec.txt' if __name_...
containPoint(p): trp.append(str(t)) # meter on CA id flag = True break if not flag: trp.append('-1')
trp.append(pickup) # meter on position trp.append(ls[8]) # meter off time dropoff = ls[11].replace('"', '') dc = dropoff.split(",") d = Point( float(dc[1]), float(dc[0]) ) fla...
jahs/ssexp
test.py
Python
mit
2,221
0.004052
import unittest import ssexp class JsonTests(unittest.TestCase): def setUp(self): class Parrot(object): def __init__(self, is_dead=True, from_egg=None): self.is_dead = is_dead self.from_egg = from_egg self.preserializer = ssexp.SsexpPreserializer() ...
class Egg(object): def __init__(self, from_parrot=None):
self.from_parrot = from_parrot self.preserializer.register(Egg) self.parrot = Parrot() self.parrot.from_egg = Egg(from_parrot=self.parrot) def test_int(self): obj = 123 result = u"123" self.assertEqual(ssexp.dumps(obj), result) def test_float(self): o...
adrn/gala
gala/util.py
Python
mit
4,794
0.000417
""" General utilities. """ # Standard library from collections.abc import Mapping # Third-party import numpy as np __all__ = ['rolling_window', 'atleast_2d', 'assert_angles_allclose'] class ImmutableDict(Mapping): @classmethod def from_dict(cls, somedict): return cls(**somedict) def __init__(...
= int(stride) if window_size < 0 or stride < 1: raise ValueError arr_len = len(arr) if arr_len < window_size: if return_idx: yield (0, arr_len), arr else: yield arr ix1 = 0 while ix1 < arr_len: ix2 = ix1 + window_size result = arr[i...
(ix1, ix2), result else: yield result if len(result) < window_size or ix2 >= arr_len: break ix1 += stride def atleast_2d(*arys, **kwargs): """ View inputs as arrays with at least two dimensions. Parameters ---------- arys1, arys2, ... : array_like ...
jespino/python-taiga
tests/test_roles.py
Python
mit
530
0.001887
from taiga.requestmaker import RequestMaker from taiga.models import Role, Roles import unittest from mock import patch class TestRoles(unittest.TestCa
se): @patch('taiga.models.base.ListResource._new_resource') def test_create_role(self, mock_new_resource):
rm = RequestMaker('/api/v1', 'fakehost', 'faketoken') mock_new_resource.return_value = Role(rm) sv = Roles(rm).create(1, 'RL 1') mock_new_resource.assert_called_with( payload={'project': 1, 'name': 'RL 1'} )
antoinecarme/pyaf
tests/artificial/transf_Fisher/trend_MovingMedian/cycle_0/ar_/test_artificial_1024_Fisher_MovingMedian_0__100.py
Python
bsd-3-clause
266
0.086466
import pyaf
.Bench.TS_datasets as tsds import tests.artificial.process_artificial_dataset as art art.process_dataset(N = 1024 , FREQ = 'D', seed = 0, trendtype = "MovingMedian", cycle_length = 0, transform = "Fisher", sigma = 0.0, e
xog_count = 100, ar_order = 0);
jcchoiling/learningPython
s13/Day12/practice/rpc_server.py
Python
gpl-3.0
1,091
0.008249
#!/usr/bin/env python # -*- coding: utf-8 -*- # Author: Janice Cheng import pika import json creds_broker = pika.PlainCredentials("janice", "janice123") conn_params = pika.ConnectionParameters("172.16.201.134", virtual_host = "/", credent...
queue="ping", consumer_tag="ping") print("Waiting for RPC calls...") channel.start_consuming() conn_broker.close()
capergroup/bayou
src/main/python/bayou/experiments/low_level_sketches/utils.py
Python
apache-2.0
2,543
0.00118
# Copyright 2017 Rice University # # Licensed under the A
pache License, Version 2.0 (the "License"); # you may not use this file excep
t 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...
cjahangir/geodash
geonode/documents/tests.py
Python
gpl-3.0
11,741
0.000767
# -*- coding: utf-8 -*- ######################################################################### # # Copyright (C) 2016 OSGeo # # 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 ...
doc_file=f, owner=superuser, title='theimg') c.set_default_permissions() self.assertEquals(Document.objects.get(pk=c.id).title, 'theimg') def test_create_document_with_rel(self): """Tests the creation of a document with no a map related""" f = SimpleUploaded...
'image/gif') superuser = get_user_model().objects.get(pk=2) m = Map.objects.all()[0] ctype = ContentType.objects.get_for_model(m) c = Document.objects.create( doc_file=f, owner=superuser, title='theimg', content_type=ctype, ...
frreiss/tensorflow-fred
tensorflow/python/distribute/multi_process_runner.py
Python
apache-2.0
57,381
0.004305
# Lint as: python3 # Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless ...
t from tensorflow.python.framework import test_util from tensorflow.python.util.tf_export import tf_export multiprocessing = multi_process_lib.multiprocessing # pylint: disable=g-import-not-at-top try: # `faulthan
dler` is not available in py2. import faulthandler except ImportError: faulthandler = None # TODO(b/150264776): Remove after resolving CI issue. try: import dill except ImportError: dill = None # TODO(b/150264776): Remove after resolving CI issue. try: import tblib.pickling_support # For pickling tracebac...
opennode/nodeconductor-assembly-waldur
src/waldur_mastermind/booking/urls.py
Python
mit
466
0.004292
from django.conf.urls import url from waldur_mastermind.
booking import views def register_in(router): router.register( r'booking-resources', views.ResourceViewSet, basename='booking-resource' ) router.register( r'booking-offerings', views.OfferingViewSet, basename='booking-offering' ) urlpatterns = [ url( r'^api/marketplace-bo...
P<uuid>[a-f0-9]+)/$', views.OfferingBookingsViewSet.as_view(), ), ]
eagleamon/home-assistant
tests/components/emulated_hue/test_hue_api.py
Python
apache-2.0
14,968
0
"""The tests for the emulated Hue component.""" import asyncio import json from unittest.mock import patch import pytest from homeassistant import bootstrap, const, core import homeassistant.components as core_components from homeassistant.components import ( emulated_hue, http, light, script, media_player, fan )...
yncio.coroutine def test_discover_lights(hue_client): """Test the discovery of lights.""" result = yield from hue_client.get('/api/username/lights') assert result.status == 200 assert 'application/json' in result.headers['content-type'] result_json = yield from result.json() devices = set(val...
)) # Make sure the lights we added to the config are there assert 'light.ceiling_lights' in devices assert 'light.bed_light' in devices assert 'script.set_kitchen_light' in devices assert 'light.kitchen_lights' not in devices assert 'media_player.living_room' in devices assert 'media_player...
kagklis/Frequent-Itemset-Hiding-Toolbox-x86
Heuristic_Coeff.py
Python
mit
4,188
0.010267
#------------------------------------------------------------------------------- # Name: Heuristic_Coeff.py # Purpose: Implements FIH algorithm found in "An Integer Linear Programming Scheme to Sanitize Sensitive Frequent Itemsets" by Kagklis et al. # Author: Vasileios Kagklis # Created: 20/03/2...
'w') for i in xrange(lines): k = ' '.join(sorted(tid[i])) print(k, file = out_file) out_file.close() tid = None return("Not Applicabl
e", change_raw_data, rev_t+exec_time)
francisar/rds_manager
aliyun/api/rest/Rds20130528SwitchDBInstanceNetTypeRequest.py
Python
mit
380
0.026316
''' Created by auto_sdk on 2015.06.23 ''' from aliyun.api.base import RestApi class Rds20130528SwitchDBInstanceNetTypeRequest(RestApi): def __init__(self,domain='rds.aliyuncs.com',port=80): RestApi.__init__(self,domain, port) self.ConnectionStringPrefix = None se
lf.DBInstanceId = None def getapiname(self): re
turn 'rds.aliyuncs.com.SwitchDBInstanceNetType.2013-05-28'
matwey/rpmlint
test/test_cli.py
Python
gpl-2.0
1,865
0.001609
from pathlib import PosixPath import pytest from rpmlint.cli import process_lint_args from rpmlint.config import Config from rpmlint.lint import Lint @pytest.mark.parametrize('test_arguments', [['-c', 'rpmlint/configs/thisdoesntexist.toml']]) def test_parsing_non_existing_config_file(test_arguments): with pytest...
def test_parsing_opensuse_conf(test_arguments): parsed = process_lint_args(test_arguments) assert len(parsed['config']) == 7 assert PosixPath('configs/openSUSE/opensuse.toml') in parsed['config'] assert PosixPath('configs/openSUSE/licenses.
toml') in parsed['config'] assert PosixPath('configs/openSUSE/pie-executables.toml') in parsed['config'] defaultcfg = Config() lint = Lint(parsed) default_checks = defaultcfg.configuration['Checks'] checks = lint.config.configuration['Checks'] # Verify that all original Checks are enabled and s...
ijzer/cwbot-ndy
kol/request/BootClanMemberRequest.py
Python
bsd-3-clause
475
0.002105
from GenericRequest import
GenericRequest class BootClanMemberRequest(GenericRequest): def __init__(self, session, userId): super(BootClanMemberRequest,
self).__init__(session) self.url = session.serverURL + "clan_members.php" self.requestData['pwd'] = session.pwd self.requestData['action'] = 'modify' self.requestData['begin'] = '1' self.requestData['pids[]'] = userId self.requestData['boot%s' % userId] = 'on'
dideher/ekloges_dieuthinton
ekloges.py
Python
gpl-2.0
18,757
0.007097
#!/usr/bin/python # -*- coding: utf-8 -*- import csv import codecs import re import argparse import os from prettytable import PrettyTable report08_schools = {} report08_employees = {} report08_school_employees = {} report16_employee = None # The following (combined with report16_absence_reasons) is used when an ...
firstRow = False continue #exclude some school types if row[4] in excluded_school_types: continue # check if the school id is excluded if row[6] in excluced_schools: continue # get school object ...
t school schoolObj = { 'id': row[6], 'title': row[7], 'email': row[10], 'employees': list() } # add school to dict report08_schools[row[6]] = schoolObj # fetch em...
fastmonkeys/vakautin
vakautin/__init__.py
Python
mit
49
0
from . i
mport app __
version__ = app.__version__
klen/pyserve
pyserve/icons.py
Python
lgpl-3.0
2,305
0
by_ext = [ ('py.png'
, 'py'), ('python.png', 'pyc'), ('page_white_text_width.png', ['md', 'markdown', 'rst', 'rtf']), ('page_white_text.png', 'txt'), ('page_white_code.png', ['html', 'htm', 'cgi']), ('page_white_visualstudio.png', ['asp', 'vb']), ('page_white_ruby.png', 'rb'), ('page_code.png', 'xhtml'), ('p...
e_white_code_red.png', ['xml', 'xsl', 'xslt', 'yml']), ('script.png', ['js', 'json', 'applescript', 'htc']), ('layout.png', ['css', 'less']), ('page_white_php.png', 'php'), ('page_white_c.png', 'c'), ('page_white_cplusplus.png', 'cpp'), ('page_white_h.png', 'h'), ('database.png', ['db', 'sql...
mhnatiuk/phd_sociology_of_religion
scrapper/build/lxml/benchmark/bench_objectify.py
Python
gpl-2.0
3,322
0.001204
import sys, copy from itertools import * import benchbase from benchbase import (with_attributes, with_text, onlylib, serialized, children, nochange) ############################################################ # Benchmarks ############################################################ class Ben...
path(root) @nochange def bench_objectpath_deep_cached(self, root): "1 2 4" cache1 = root.zzzzz cache2 = cache1['{cdefg}a00001']
path = self.objectify.ObjectPath(".zzzzz.{cdefg}a00001") for i in self.repeat3000: path(root) @with_text(text=True, utext=True, no_text=True) def bench_annotate(self, root): self.objectify.annotate(root) @nochange def bench_descendantpaths(self, root): root.desc...
pablodecm/cartographer
cartographer/coverers.py
Python
mit
4,786
0
""" Coverers of the filtrated space """ from __future__ import print_function from sklearn.base import BaseEstimator, TransformerMixin import numpy as np class HyperRectangleCoverer(BaseEstimator, TransformerMixin): """ Covers the space using overlapping hyperectangles Parameters ---------- interv...
ft in zip(bbs, ws * overlap)])) \ .T.reshape(-1, X.shape[1]) return self def transform(self, X, y=None): """ Returns boolean array of space partition membership Returns a (n_samples, n_partitions) boolean array whose elements ...
---------- X: array-like, shape=(n_samples, n_features) Data which will be partition in hyperectangles. Returns ------- m_matrix: boolean array, shape=(n_samples, n_partitions) Boolean matrix of sample membership to each partition """ if y is not N...
kasbah/sooperlooper
src/test_plugin/testdef_simple_state_record_undoall.py
Python
gpl-2.0
1,543
0.004537
import time from nose_parameterized import parameterized import testdef_simple_state import engine_wrapper class simpleStateTestsRecordUndoAll(testdef_simple_state.simpleStateTest): def setUp(self): testdef_simple_state.simpleStateTest.setUp(self) self.engine.request("RECORD") self.engine...
ECORD")
self.engine.request("UNDO_ALL") def testOff(self): time.sleep(0.001) self.assertState("Off") def testUndo(self): self.engine.request("RECORD") self.engine.request("UNDO") time.sleep(0.001) self.assertState("Off") def testUndoAll(self): self.engin...
jarvisqi/learn_python
flaskweb/core/doc2vector.py
Python
mit
1,476
0.004219
# -*- coding: UTF-8 -*- import sys sys.path.append("./") import pandas as pd import gensim from utility.mongodb import MongoDBManager from utility.sentence import segment, sent2vec class Doc2Vector(object): """ 文本转向量 """ def __init__(self): """ :param keep_val: 设定的阈值 """ ...
content_vect = sent2vec(model, ' '.join(seg_content)) title_vect = sent2vec(model, ' '.join(seg_title)) content_vect = map(str, content_vect.tolist()) title_vect = map(str, title_vect.tolist()) conten
t.append({"_id": int(idx) + 1, "data": list(content_vect)}) title.append({"_id": int(idx) + 1, "data": list(title_vect)}) self.mongo_db.insert("content_vector", content) self.mongo_db.insert("title_vector", title) print("finished") if __name__ == '__main__': doc2vect ...
ecreall/lagendacommun
lac/views/admin_process/manage_keywords.py
Python
agpl-3.0
2,736
0
# Copyright (c) 2014 by Ecreall under licence AGPL terms # available on http://www.gnu.org/licenses/agpl.html # licence: AGPL # author: Amen Souissi import colander from pyramid.view import view_config from dace.processinstance.core import DEFAULTMAPPING_ACTIONS_VIEWS from pontus.default_behavior import Cancel from ...
_templates/grid.pt', ) class ManageKeywordsView(MultipleView): title = _('Manage keywords') name = 'managekeywords' viewid = 'managekeywords' template = 'd
aceui:templates/mergedmultipleview.pt' views = (ManageKeywordsViewStudyReport, ManageKeywordsFormView) validators = [ManageKeywords.get_validator()] DEFAULTMAPPING_ACTIONS_VIEWS.update({ManageKeywords: ManageKeywordsView})
integricho/heroku-buildpack-python-ffmpeg2-lame
vendor/pip-1.2.1/tests/test_all_pip.py
Python
mit
3,610
0.001939
import os import re import sys import subprocess import shutil from os.path import dirname, abspath from pip.backwardcompat import urllib from pip.util import rmtree src_folder = dirname(dirname(abspath(__file__))) def all_projects(): data = urllib.urlopen('http://pypi.python.org/simple/').read() projects ...
p'), 'uninstall', '-y', 'pip']) assert not code, 'pip uninstallation failed' print('Installing development pip') code = subprocess.check_call([os.path.join(dest_dir, 'bin', 'python'),
'setup.py', 'install'], cwd=src_folder) assert not code, 'pip installation failed' print('Trying installation of %s' % dest_dir) code = subprocess.check_call([os.path.join(dest_dir, 'bin', 'pip'), 'install', package]) if ...
facom/GeoTrans
PaperFigures.py
Python
gpl-2.0
75,999
0.031632
from geotrans import * from system import * ######################################### #SYSTEM ######################################### Ringed=System NotRinged=copyObject(Ringed) NotRinged.Ringext.b=NotRinged.Ringint.b=0.0 VAR=1 FIX=0 SHOW=1 HIDE=0 DEF=0 MIN=1 MAX=2 FUNC=3 SCAL=4 STAT=5 IDENT=lambda x:x POW10=lamb...
xp=direction*sqrt((1+direction*sign*a)**2-B**2) return xp a=fe*Rp b=fe*Rp*cos(i) xp=direction*sqrt(1-a**2*(sin(t)-sign*B/a)**2*\ (1-b**2/a))+\ sign*a*cos(t) #COMPARE WITH THE NOT-RINGED CASE xpP=direction*sqrt((1+direction*sign*Rp...
p def testTransitDepth(): print BARL,"Test Transit Depth",RBAR #======================================== #FIX RINGED PROPERTIES BY HAND #======================================== #MANUAL i,t i=60.0*DEG;t=30*DEG Ringed.ieff=i;Ringed.teff=t Ringed.Ringext.b=Ringed.Ringext.a*cos(i) ...
codetry/mgsub
mgsub/forms.py
Python
mit
2,627
0.000381
import logging import six from django import forms from django.conf import settings from django.template import Context from django.utils.translation import ugettext as _ from django.core.mail import EmailMultiAlternatives from django.template.loader import get_template, TemplateDoesNotExist from mgsub.mailgun import...
[reply_to] context = Context() welcome_txt = get_template(welcome_plain).render(context) attach_html = True try: welcome_html = get_template(welcome_template).render(context) except TemplateDoesNotExist: attach_html = False
message = EmailMultiAlternatives(subject, welcome_txt, from_address, to=[email], reply_to=reply_to) if attach_html: message.attach_alternative(welcome_html, 'text/html') message.send() return True
snnn/tensorflow
tensorflow/python/ops/sparse_ops.py
Python
apache-2.0
90,456
0.002819
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
ape, shape_after], axis=0) # Create the output sparse tensor. return sparse_tensor.SparseTensor( indices=indices, values=sp_input.values, dense_shape=shape) @tf_export("sparse.eye") def sparse_eye(num_rows, num_column
s=None, dtype=dtypes.float32, name=None): """Creates a two-dimensional sparse tensor with ones along the diagonal. Args: num_rows: Non-negative integer or `int32` scalar `tensor` giving the number of rows in the resulting matrix. num_columns: Optional non-negative intege...
whatevsz/autobackup
autobackup/cron.py
Python
gpl-3.0
17,954
0.000279
# -*- encoding: utf-8 -*- # Copyright (c) 2013 Hannes Körber <hannes.koerber@gmail.com> # # T
his file is part of autobackup. # # autoba
ckup 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. # # autobackup is distributed in the hope that it will be useful, # but WITHOUT AN...
googleapis/python-bigquery
samples/magics/_helpers.py
Python
apache-2.0
823
0.001215
# Copyright 2021 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
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. def strip_region_tags(sample_text): """Remove blank lines and region tags from sa
mple text""" magic_lines = [ line for line in sample_text.split("\n") if len(line) > 0 and "# [" not in line ] return "\n".join(magic_lines)
shearern/python-text-objects
src/txtobjs_test/servers_use_case/ServiceSchema.py
Python
gpl-2.0
519
0.001927
from txtobjs.schema.TextO
bjectSchema import TextObjectSchema from txtobjs.schema.SimpleTextField import SimpleTextField from txtobjs.schema.SubObjectDict import SubObjectDict from txtobjs.schema.ValueListField import ValueListField class ServiceSchema(TextObjectSchema): text_class = 'Service' name = SubObjectDictKey() ...
st('hosts', text_class='Machine') firewall = SubObjectDict('firewall', schema=ServiceFirewallSchema())
Mobleyta/GasChromino
PythonCode/serial_ports.py
Python
gpl-3.0
1,189
0
#!/usr/bin/env python """This utility script was adopted from StackExchange: http://stackoverflow.com/questions/12090503/listing-available-com-ports-with-python Adopted for use with arduino_GC connection project """ import sys import glob import serial def serial_ports(): """ Lists serial port names :ra...
% (i + 1) for i in range(256)] elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'): # this exclu
des your current terminal "/dev/tty" ports = glob.glob('/dev/cu[A-Za-z]*') elif sys.platform.startswith('darwin'): ports = glob.glob('/dev/cu.*') else: raise EnvironmentError('Unsupported platform') result = [] for port in ports: try: s = serial.Serial(port) ...
MAECProject/python-maec
maec/bundle/behavior.py
Python
bsd-3-clause
4,501
0.00511
# MAEC Behavior Class # Copyright (c) 2018, The MITRE Corporation # All rights reserved from mixbox import fields from mixbox import idgen import maec from . import _namespace import maec.bindings.maec_bundle as bundle_binding from cybox.core.action_reference import ActionReference from cybox.common.meas...
eference', BehavioralActionEquivalenceReference, multiple=True) class PlatformList(maec.EntityList): _binding = bundle_binding _binding_class = bundle_binding.PlatformListType _namespace = _namespace platform = fields.TypedField("Platform", PlatformSpecification, multiple=True) class CVEVulner...
_namespace = _namespace cve_id = fields.TypedField('cve_id') description = fields.TypedField('Description') class Exploit(maec.Entity): _binding = bundle_binding _binding_class = bundle_binding.ExploitType _namespace = _namespace known_vulnerability = fields.TypedField('known_vuln...
Tan0/ironic
ironic/tests/test_raid.py
Python
apache-2.0
10,900
0
# Copyright 2014 Hewlett-Packard Development Company, L.P. # # 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 applicabl...
alidate_configuration_invalid_is_root_volume(self): raid_config_str = raid_constants.RAID_CONFIG_INVALID_IS_ROOT_VOL raid_config = json.loads(raid_config_str) self.assertRaises(exception.InvalidParameterValue, raid.validate_configuration,
raid_config, raid_config_schema=self.schema) def test_validate_configuration_invalid_multiple_is_root_volume(self): raid_config_str = raid_constants.RAID_CONFIG_MULTIPLE_IS_ROOT_VOL raid_config = json.loads(raid_config_str) self.assertRaises(exception.Inval...
spacy-io/spaCy
spacy/lang/id/syntax_iterators.py
Python
mit
1,515
0.00132
from typing import Union, Iterator from ...symbols import NOUN, PROPN, PRON from ...errors import Errors from ...tokens import Doc, Span def noun_chunks(doclike: Union[Doc, Span]) -> Iterator[Span]: """ Detect base noun phrases from a dependency parse. Works on both Doc and Span. """ # fmt: off l...
"obj", "iobj", "ROOT", "appos", "nmod", "nmod:poss"] # fmt: on doc = doclike.doc # Ensure works on both Doc and Span. if not doc.has_annotation("DEP"): raise ValueError(Errors.E029) np_deps = [doc.vocab.strings[label] for label in labels] conj
= doc.vocab.strings.add("conj") np_label = doc.vocab.strings.add("NP") prev_end = -1 for i, word in enumerate(doclike): if word.pos not in (NOUN, PROPN, PRON): continue # Prevent nested chunks from being produced if word.left_edge.i <= prev_end: continue ...
chakki-works/elephant_sense
scripts/data/normalization.py
Python
apache-2.0
477
0.004376
# -
*- coding: utf-8 -*- import re import unicodedata def lower_text(text): return text.lower() def normalize_unicode(text, form='NFKC'): normalized_text = unicodedata.normalize(form, text) return normalized_text def normalize_number(text): """ pattern = r'\d+' replacer = re.compile(pattern) ...
return replaced_text
clicumu/uspto-tools
scripts/zip_to_sqlite.py
Python
mit
10,428
0.000575
""" Patent ZIP-archive to sqlite. This script parses and transfer patents from the stupid text-format in bulk_download.py to a query-friendly sqlite datbase. """ import collections import sqlite3 import re import os import itertools import datetime import numpy as np import hashlib with open(os.path.join(os.path.dir...
ts(cursor, fulltexts, root_dir) referred = set((ref, ) for p, ref in references) cursor.executemany(INSERT_IGNORE_PNUM, referred) cursor.executemany(INSERT_CITATION, references) def save_fulltexts(cursor, fulltexts, root_dir=None): to_db = list() for pnum, key, body in fulltexts: md5 = ha...
md5[:16], 16) % 100 bottom_dir = int(md5[16:], 16) % 100 path = '{}/{}/{}/{}.txt'.format(key, top_dir, bottom_dir, pnum) if root_dir is not None: path = '{}/{}'.format(root_dir, path) os_path = os.path.join(*path.split('/')) os.makedirs(os.path.dirname(os_path), exis...
oleg-cherednik/hackerrank
Python/Strings/Mutations/solution.py
Python
apache-2.0
257
0.003891
#!/bin/python3 def mutate_string(string, position, chara
cter): return string[:position] + character + string[position + 1:] if __name__ == '__main__': s = input() i, c = input().split() s_new = mutate
_string(s, int(i), c) print(s_new)
badp/ganeti
qa/qa_instance.py
Python
gpl-2.0
44,869
0.01023
# # # Copyright (C) 2007, 2011, 2012, 2013 Google 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) any later version. # # This progr...
along with this program; if not, write to the Free Software # F
oundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. """Instance related QA tests. """ import os import re import time from ganeti import utils from ganeti import constants from ganeti import query from ganeti import pathutils import qa_config import qa_utils import qa_error from qa_ut...
Raynxxx/CUIT-ACM-Website
view/ajax.py
Python
mit
35,176
0.00426
# coding=utf-8 import os from __init__ import * import traceback, cStringIO, re from flask import current_app from werkzeug.datastructures import FileStorage from server import user_server, article_server, status_server, form, \ account_server, news_server, resource_server from server import general, honor_server f...
return jsonify(items=[get_user_list_item(user) for user in pagination.items], prev_num=pagination.prev_num, next_num=pagination.next_num, page_list=page_list, page=pagination.page, pages=pagination.pages) # # @brief: add...
n and coach # @ajax return: 用户是否添加成功 # @ajax.route('/ajax/create_user', methods=["POST"]) @login_required def create_user(): if not current_user.is_admin and not current_user.is_coach: return redirect(url_for('main.index')) reg_form = form.RegisterForm() if reg_form.validate_on_submit(): try...