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
forrestv/pyderiv
noise_test.py
Python
gpl-3.0
1,536
0.013672
# This file is part of pyderiv. http://forre.st/pyderiv # # pyderiv 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. # # pyderiv is distr...
.org/licenses/>. from __future__ import division def f(): a = noise(3) b = 8 + noise(2) return a, b, a + b, a /b, a*a, a*b, b*b def go():
for x in v: print x for x in v: print E(x) print for i in xrange(len(r)): for j in xrange(len(r)): print "%6.01f" % cov(r[i], r[j]), print from noise import noise, var, cov, cov_matrix, E r = f() v = r go() print cov_matrix(r) print print import random impor...
pdubroy/kurt
build/MacOS/PyInstaller/pyinstaller-svn-r812/hooks/django-import-finder.py
Python
gpl-2.0
2,102
0.00333
# Copyright (C) 2009, Lorenzo Berni # Based on previous work under copyright (c) 2001, 2002 McMillan Enterprises, 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...
our 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 for more details. # # You should have received a copy of the GN...
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA import os if not os.environ.get("DJANGO_SETTINGS_MODULE"): os.environ["DJANGO_SETTINGS_MODULE"] = "settings" from django.conf import settings hiddenimports = list(settings.AUTHENTICATION_BACKENDS) + \ [settings.DEFAULT_FILE_STORA...
crisely09/horton
horton/meanfield/test/test_project.py
Python
gpl-3.0
8,371
0.003225
# -*- coding: utf-8 -*- # HORTON: Helpful Open-source Research TOol for N-fermion systems. # Copyright (C) 2011-2016 The HORTON Development Team # # This file is part of HORTON. # # HORTON is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by th...
see <http://www.gnu.org/licenses/> # # -- from horton import * # pylint: disable=wildcard-import,unused-wildcard-import from horton.meanfield.test.common import helper_comput
e def test_project_msg_identical(): mol = IOData.from_file(context.get_fn('test/water_sto3g_hf_g03.fchk')) exp = mol.lf.create_expansion() project_orbitals_mgs(mol.obasis, mol.obasis, mol.exp_alpha, exp) assert (exp.energies == 0.0).all() assert (exp.occupations == mol.exp_alpha.occupations).all()...
dwillcox/pyreaclib
util/grid.py
Python
bsd-3-clause
2,575
0.008155
""" Integrate a grid of dens and temp using the defaults in net.par.default This could use some updating to be more user-friendly Donald Willcox """ from __future__ import print_function import numpy as np import subprocess import re num_dens = 100 num_temp = 100 dens = np.logspace(8.0, 11.0, num=num_dens, endpoint=...
ERROR , idens={} ,
dens={} , itemp={} , temp={}'.format(i,rho,j,t)) print(comm_err) exit() comm_out_utf = comm_out.decode('utf-8').split('\n') for line in comm_out_utf: rem = renuc.match(line) if rem: enucave = float(rem.group(1)) * (10.0**int(rem.group(2)))...
bobalazek/tensorflow-simple-trainer
simple_trainer/__init__.py
Python
mit
8,481
0.004716
import yaml, json import math import re import operator import tensorflow as tf import sys, os # We want to ignore those annoying "exceptions", # "Scipy not supported!", "hdf5 is not supported on this machine ...", .. sys.stdout = open(os.devnull, 'w') import tflearn sys.stdout = sys.__stdout__ os.environ['TF_CPP_MIN...
ts['failed']): print 'Failed:' for failed in test_results['failed']: print '-' * 8 print 'Text: ' + failed['text'] print 'Classes: ' + str(failed['classes']) print 'Matched classes: ' + str(failed['matched_cl...
2 ##### Helper methods ##### def get_top_classes(self, text, count = 3): text_vector = self.text_to_vector(text, self.words) class_vector = self.model.predict([text_vector])[0] top_classes = {} final_top_classes = {} i = 0 for cls in self.classes: to...
aspiers/crmsh
modules/pacemaker.py
Python
gpl-2.0
13,248
0.001736
# Copyright (C) 2009 Yan Gao <ygao@novell.com> # See COPYING for license information. import os import tempfile import copy from lxml import etree class PacemakerError(Exception): '''PacemakerError exceptions''' def get_validate_name(cib_elem): if cib_elem is not None: return cib_elem.get("validate...
"", file=""): schema_info = validate_name + " " + file crm_schema = self.get_schema_fn(validate_name, os.path.join(self.local_dir, file)) if not crm_schema: raise PacemakerError("Cannot get the Relax-NG schema: " + schema_info
) self.schema_str_docs[file] = crm_schema try: grammar = etree.fromstring(crm_schema) except Exception, msg: raise PacemakerError("Failed to parse the Relax-NG schema: " + str(msg) + schema_info) start_nodes = grammar.xpath(self.expr, name="start") if l...
sumeetsk/NEXT-1
apps/PoolBasedTripletMDS/algs/CrowdKernel/CrowdKernel.py
Python
apache-2.0
5,533
0.029279
""" CrowdKernel algorithm of the Online Learning Library for Next.Discovery author: Lalit Jain, kevin.g.jamieson@gmail.com last updated: 4/22/2015 """ import numpy import numpy.random from apps.PoolBasedTripletMDS.algs.CrowdKernel import utilsCrowdKernel import time class CrowdKernel: def initExp(self,butler,n,d,f...
ilsCrowdKernel.getLoss(X_old,S) X,tmp = utilsCrowdKernel.compu
teEmbeddingWithEpochSGD(n,d,S,mu,max_num_passes=16,epsilon=0,verbose=verbose) t_start = time.time() X,emp_loss_new,hinge_loss_new,log_loss_new,acc = utilsCrowdKernel.computeEmbeddingWithGD(X,S,mu,max_iters=1,epsilon=epsilon,verbose=verbose) k = 1 while (time.time()-t_start<.5*t_max) and (acc > epsilon):...
textioHQ/pattern
test/test_examples.py
Python
bsd-3-clause
2,048
0.000977
"""This creates a TestExamples test class and adds a method for each python file in the examples directory. examples/01-web/01-google.py -> TestExamples.test_01web_01google The test itself calls this python file, and asserts that it exits with exit code 0 (i.e. it was successful). If it wasn't it raises an AssertionE...
unittest.SkipTest("Test skipped due to an HTTPError or URLTimeout") if p.returncode != 0 and "translate API is a paid service" in err: raise unittest.SkipTest("Test skipped as translate API costs") if p.returncode != 0 and "NotI
mplementedError" in err and "2.6" in err: raise unittest.SkipTest("Example is not python 2.6 compatible") assert (p.returncode == 0), "%s exited with bad status %s\n\n%s" % ( example_py, p.returncode, err) _test.__name__ = test_name setattr(TestExamples, test_name, _test) d...
Skytells/Oxcoin
contrib/seeds/makeseeds.py
Python
mit
709
0.015515
#!/usr/bin/env python # # Generate pnSeed[] from Pieter's DNS seeder # NSEEDS=600 import re import sys from subprocess import check_output def main(): lines = sys.stdin.readlines() ips = [] pattern = re.compile(r"^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3}):18409") for line in lines: m = patt...
if m is None: continue ip = 0 for i in range(0,4): ip = ip + (int(m.group(i+1)) << (8*(i))) if ip == 0: continue
ips.append(ip) for row in range(0, min(NSEEDS,len(ips)), 8): print " " + ", ".join([ "0x%08x"%i for i in ips[row:row+8] ]) + "," if __name__ == '__main__': main()
mcallaghan/tmv
BasicBrowser/tmv_app/migrations/0116_runstats_lda_learning_method.py
Python
gpl-3.0
443
0.002257
# Generated by Django 2.2 on 2019-06-18 09:53 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('tmv_app', '0115_topic_
origi
nal_title'), ] operations = [ migrations.AddField( model_name='runstats', name='lda_learning_method', field=models.IntegerField(choices=[('on', 'Online'), ('ba', 'Batch')], null=True), ), ]
stuntgoat/metl
sinks/local.py
Python
epl-1.0
1,930
0.001036
#!/usr/bin/python import errno import os import sys import uuid from collections import defaultdict from datetime import datetime DATA_DIR = './data' DATETIME_METRICS = defaultdict(list) def mkdir(path): try: os.makedirs(path) except OSError as exception: if exception.errno != errno.EEXIST: ...
def getrows(): for line in sys.stdin.readlines(): try: sline = line.strip().split() yield (sline[0], ''.join(sline[1:])) except Exception as e: sys.stderr.wri
te(str(e)) continue sys.stderr.flush() def filename_from_path(path): return os.path.join(path, str(uuid.uuid4()) + '.txt') if __name__ == '__main__': if len(sys.argv) < 2: raise Exception("did not recieve the correct number of arguments") bucket = sys.argv[1] for ts, metric i...
domenicosolazzo/Earthquake
tests/tests_earthquake_parser.py
Python
mit
585
0.015385
import unittest from lib.earthquake import Parser class ParserTestCase(unittest.TestCase): def setUp(self
): self.parser = Parser() def test_parser_contains_a_parse_method(self): self.assertTrue(callable(getattr(self.parser, "parse")), "Parser contains a parse method") def test_parse_method_accepts_a_string_in_input(self): self.assertRaises(AssertionError, getattr(self.parser, "parse"), **{"...
, "Parse returns a list")
wenyu1001/scrapy
tests/test_feedexport.py
Python
bsd-3-clause
16,261
0.000492
from __future__ import absolute_import import os import csv import json from io import BytesIO import tempfile import shutil from six.moves.urllib.parse import urlparse from zope.interface.verify import verifyObject from twisted.trial import unittest from twisted.internet import defer from scrapy.crawler import Crawle...
'rb') as fp: self.assertEqual(fp.read(), b"content") # again, to check s3 objects are overwritten yield storage.store(BytesIO(b"new content")) with open(path, 'rb') as fp: self.assertEqual(fp.read(), b"new content") class BlockingFeedStorageTest(unittest.T
estCase): def get_test_spider(self, settings=None): class TestSpider(scrapy.Spider): name = 'test_spider' crawler = get_crawler(settings_dict=settings) spider = TestSpider.from_crawler(crawler) return spider def test_default_temp_dir(self): b = BlockingFeedS...
EPFL-LCSB/pytfa
pytfa/redgem/redgem.py
Python
apache-2.0
7,632
0.004324
#!/usr/bin/env python # -*- coding: utf-8 -*- """ .. module:: redgem :platform: Unix, Windows :synopsis: RedGEM Algorithm .. moduleauthor:: pyTFA team Model class """ from pytfa.redgem.network_expansion import NetworkExpansion from pytfa.redgem.lumpgem import LumpGEM from cobra import Reaction from .utils im...
= "auto": self.logger.info("Setting minimal growth rate to 95% of the TFA solution") obj_val = self._source_gem.slim_optimize() self.logger.info("Setting minimal growth rate
to {}".format(obj_val)) self.params["growth_rate"] = 0.95*obj_val if "force_solve" not in self.params: self.params["force_solve"] = False if "timeout" not in self.params: self.logger.info("Using default timeout : 3600s") self.params["timeout"] = 3600 ...
jimlawton/h800
tools/check-instructions.py
Python
gpl-2.0
5,065
0.000197
#!/usr/bin/env python # -*- coding: iso-8859-15 -*- # Check opcodes in ARGUS assembly source # # A script that uses the arguscard classes to read ARGUS assembly format source # and check for invalid opcodes. # # This is intended for debugging assembler development. import sys from optparse import OptionParser from c...
h800.instructions def main(): parser = OptionParser("usage: %prog filename [filename]...") parser.add_option('-a', '--all',
dest='all', action='store_true', default=False, help="Check for all errors.") parser.add_option('-c', '--count', dest='count', action='store_true', default=False, ...
ryanss/holidays.py
test/countries/test_malawi.py
Python
mit
1,455
0
# -*- coding: utf-8 -*- # python-holidays # --------------- # A fast, efficient Python library for generating country, province and state # specific sets of holidays on the fly. It aims to make determining whether a # specific date is a holiday as fast and flexible as possible. # # Authors: dr-prodigy <maurizio....
olidays) self.assertIn("2017-01-01", self.holidays) self.assertIn("2999-01-01", self.holidays) self.assertIn("2017-01-02
", self.holidays) # sunday def test_good_friday(self): self.assertIn("2022-04-15", self.holidays) self.assertIn("2018-03-30", self.holidays) def test_easter(self): self.assertIn(date(2017, 4, 14), self.holidays) self.assertIn(date(2020, 4, 10), self.holidays) self.asse...
dstansby/heliopy
heliopy/data/omni.py
Python
gpl-3.0
1,833
0
""" Methods for importing data from the OMNI. """ from heliopy.data import cdasrest def _docstring(identifier, description): return cdasrest._docstring(identifier, 'O', description) def _omni(starttime, endtime, identifier, intervals='monthly', warn_missing_units=True): """ Generic method for ...
als='monthly') hro2_1min.__doc__ = _docstring( 'OMNI_HRO2_1MIN', '1 minute averaged definitive multi-spacecraft ' 'interplanetary parameters.') def hro2_5min(starttime, endtime): identifier = 'OMNI_HRO2_5MIN' return _omni(starttime, endtime, identifier, warn_missing_units=False, ...
s.')
cocrawler/cocrawler
tests/unit/test_datalayer.py
Python
apache-2.0
1,764
0.000567
import tempfile import os import pytest from cocrawler.urls import URL import cocrawler.datalayer as datalayer import cocrawler.config as config def test_seen(): c = {'Robots': {'RobotsCacheSize': 1, 'RobotsCacheTimeout': 1}} config.set_config(c) dl = datalayer.Datalayer() assert not dl.seen(URL('http...
def test_saveload(): tf = tempfile.NamedTemporaryFile(delete=False) name = tf.name c = {'Robots': {'RobotsCacheSize': 1, 'RobotsCacheTimeout': 1}} config.set_config(c) dl = datalayer.Datalayer() dl.add_seen(URL('http://example.com')) assert dl.seen(URL('http://example.com')) with open(...
f) dl.add_seen(URL('http://example2.com')) with open(name, 'rb') as f: dl.load(f) assert dl.seen(URL('http://example.com')) assert not dl.seen(URL('http://example2.com')) os.unlink(name) assert not os.path.exists(name) def test_summarize(capsys): c = {'Robots': {'RobotsCacheSize':...
adbrant/zuma-fpga
source/InitFpga.py
Python
bsd-2-clause
18,645
0.01019
# use this if you want to include modules from a subforder import os, sys, inspect cmd_subfolder = os.path.realpath(os.path.abspath( os.path.join(os.path.split \ (inspect.getfile( inspect.currentframe() ))[0],"VprParsers"))) if cmd_subfolder not in sys.path: sys.path.insert(0, cmd_subfolder) import structs import ...
y): # make inodes for internal cluster connection for lut in range(globs.params.N): cluster.LUT_input_nodes.append([]) for pin in range(globs.params.K):#input nodes ino
de = structs.Node() inode.type = 7 inode.location = key # append it to the nodegraph. now it got a proper id globs.addNode(inode) #append the input node to the cluster interconnect list. cluster.LUT_input_nodes[lut].append(inode.id) ...
endlessm/chromium-browser
v8/tools/run_perf.py
Python
bsd-3-clause
40,465
0.008822
# Copyright 2014 the V8 project authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Performance runner for d8. Call e.g. with tools/run-perf.py --arch ia32 some_suite.json The suite json format is expected to be: { "path": <relativ...
['graphs'] existing_entry['durations'].append(duration) def ToDict(self): return { 'traces': self.traces.values(), 'errors': self.errors, 'runnables': self.runnables.values(), } def WriteToFile(self, file_name): with open(file_name, 'w') as f: f.write(json.dumps(sel...
trace config is within 0.1% of the true value with the specified confidence level. This assumes Gaussian distribution of the noise and based on https://en.wikipedia.org/wiki/68%E2%80%9395%E2%80%9399.7_rule. Args: graph_config: An instance of GraphConfig. confidence_level: Number of standa...
GoogleCloudPlatform/django-cloud-deploy
django_cloud_deploy/tests/unit/skeleton/source_generator_test.py
Python
apache-2.0
34,033
0.0005
# Copyright 2018 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, ...
: file_content = f.read() with open(wsgi_path, 'wt') as f: file_content = file_content.replace( '\'{}.settings\''.format(project_name), 'module_variable') f.write(file_content) self._generator.generate_fro
m_existing(project_name, self._project_dir, settings_path) with open(wsgi_path) as f: content = f.read() # Test wsgi uses cloud settings. self.assertIn(project_name + '.cloud_settings', content) def test_settings_file_not_in...
acsone/connector-magento
magentoerpconnect_export_partner/__openerp__.py
Python
agpl-3.0
1,687
0
# -*- coding: utf-8 -*- ############################################################################## # # Author: Guewen Baconnier # Copyright 2013 Camptocamp SA #
# 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 i...
e the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## {'name': 'Magento Co...
AJHMvR/django-jsrender
jsrender/translate.py
Python
gpl-3.0
15,374
0.000846
from __future__ import unicode_literals import operator from contextlib import contextmanager import six from django.conf import settings from django.template import defaulttags from django.template.base import FilterExpression, VariableDoesNotExist from django.template.smartif import TokenBase, Literal from django.uti...
ssert re
curse return 'aa' else: return six.unichr(ord(v) + 1) else: pre, last = v[:-1], v[-1] next = get_next_varname(last, recurse=True) if len(next) == 1: return pre + next else: # We can improve this and allow for arbitrary many vari...
checco/yate
fabfile.py
Python
apache-2.0
985
0.006091
#!/usr/bin/python3 import sys from fabric.api import env, task, local __author__ = 'flat' __version__ = '1.0' env.hosts = ['localhost'] env.colorize_errors = 'True' env.disable_known_hosts = 'True' args = sys.argv[1:] if not args: print("Usage: fab { git | add | commmit | push | pull | status} \n") print("D...
de on the GIT server") print("* pull: pull new code from the GIT server") print("* status: check the status of the local repository \n") sys.exit(1) @task def add(): local('/usr/bin/git add -A .') @task def commit(): local('/usr/bin/git commit') @task def push(): local('/usr/bin/git push') @...
tus') @task def git(): add() commit() push()
montoyjh/pymatgen
pymatgen/analysis/defects/defect_compatibility.py
Python
mit
25,384
0.006815
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. from monty.json import MSONable from pymatgen.core import PeriodicSite from pymatgen.analysis.defects.corrections import FreysoldtCorrection, \ BandFillingCorrection, BandEdgeShiftingCorrection from pymatg...
gov" __status__ = "Development" __date
__ = "Mar 15, 2018" class DefectCompatibility(MSONable): """ The DefectCompatibility class combines a list of DefectEntries for a given system and applies corrections / suggests failed jobs that should not be considered Args: defect_entries: List of defect_entries to consider. use...
huangsam/ciscochef
places/views.py
Python
mit
778
0.001285
from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic import TemplateView from django.views.generic.detail import DetailView from django.views.generic.edit import UpdateView from django.views.generic.list import ListView from places.
models import Restaurant class HomeView(TemplateView): template_name = "places/home.html" class RestaurantListView(ListView): model = Restaurant context_object_name = "restaurant_list" class RestaurantDetailView(DetailView): model = Restaurant context_object_name = "restaurant" class Resta
urantUpdateView(LoginRequiredMixin, UpdateView): model = Restaurant fields = ["name", "description", "address", "min_party", "max_party", "yelp_link"] template_name_suffix = "_update"
KIAaze/bin_and_dotfiles_public
bins/public_bin/count_words.py
Python
gpl-3.0
373
0.010724
#!/us
r/bin/env python # counts the number of words in a text file. Also works for the same word multiple times on one line. # usage: script FILE WORD # cf: http:
//bytes.com/topic/python/answers/797207-regular-expressions-get-number-matches import sys import re txt=open(sys.argv[1]).read() len(txt) rexp = re.compile(sys.argv[2]) match=rexp.findall(txt) print len(match)
slezica/bleg
cfg/settings.py
Python
mit
2,064
0.000484
""" Django settings for cfg project. For more information on this file, see https://docs.djangoproject.com/en/1.6/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.6/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import...
WARNING: keep the secret key used in production secret! SECRET_KEY = 'lj1yj!4x3t(pi1n3uwak5iwmc2-29zb)v1#86w7p5cj5hdb9&#' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True TEMPLATE_DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( # 'django.contrib.admin'...
ngo.contrib.messages', 'django.contrib.staticfiles', 'django_extensions', 'app' ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.Authenti...
janpipek/hlava
hlava/cli/__init__.py
Python
mit
39
0.025641
from .app im
port
console_app, run_app
bob1b/yj
yj/admin.py
Python
apache-2.0
1,165
0.0103
from django import forms from django.contrib import admin from api.models import Customer, Ticket, Note, ActionItem, Token class CustomerAdmin(admin.ModelAdmin): list_display = ("id", "full_name", "phone") class Meta: model = Customer class TicketAdmin(admin.ModelAdmin): list_display = ("id", "cu...
tails", "status") class Meta: model = Ticket class NoteAdmin(admin.ModelAdmin): list_display = ("id", "ticket_id", "rep_id", "created_da
te", "note_text") class Meta: model = Note class ActionItemAdmin(admin.ModelAdmin): list_display = ("id", "rep_id", "created_by", "description", "due_date", "is_complete") class Meta: model = ActionItem class TokenAdmin(admin.ModelAdmin): list_display = ("id", "user_id", "jwt") cla...
msumit/qds-sdk-py
qds_sdk/template.py
Python
apache-2.0
9,095
0.008576
""" The Template Module contains the base definition for Executing Templates """ import json import logging import os from argparse import ArgumentParser from qds_sdk.qubole import Qubole from qds_sdk.resource import Resource log = logging.getLogger("qds_template") from qds_sdk.commands import * class TemplateCmdLi...
atus (0: success, 1: failure) """ conn = Qubole.agent() path = str(id) + "/run" res = conn.post(Template.element_path(path), data) cmdType = res['command_type'] cmdId = res['id'] cmdClass = eval(cmdType) cmd = cmdClass.find(cmdId) while not Command...
def getResult(cmdClass, cmd): if Command.is_success(cmd.status): log.info("Fetching results for %s, Id: %s" % (cmdClass.__name__, cmd.id)) cmd.get_resul
cfe-lab/Kive
api/example_5.py
Python
bsd-3-clause
1,920
0.000521
"Run the keyword-names example pipeline, which has keyword-style inputs." import kiveapi import example_tools # Use HTTPS on a real server, so your password is encrypted. # Don't put your real password in source code, store it in a text file # that is only readable by your user account or some more secure storage. ses...
to collate names_dataset = session.find_datasets(name="example_names.csv")[0] salutations_dataset = session.find_datasets(name="salutations.csv")[0] # Get the collation app from the samplecode
container kwsalutationsapp = session.endpoints.containerapps.filter("name", "kw_salutations")[0] appargs = session.get(kwsalutationsapp["argument_list"]).json() # Start a run of the app providing the datasets as arguments inputargs = {a["name"]: a["url"] for a in appargs if a["type"] == "I"} runspec = { "name":...
h4wldev/Frest
app/config.py
Python
mit
1,244
0.000804
# -*- coding: utf-8 -*- # ----------------------------- # COMMON CONFIG # ----------------------------- # ENVIRONMENT (development, production) ENVIRONMENT = 'development' # DEFAULT URL DEFAULT_URL = 'http://0.0.0.0:5000' # LOGGER FORMATTING LOGGER_FORMAT = '[%(levelname)s][%(filename)s:%(lineno)s] %(message)s' ...
ME = 60 * 60 * 24 * 30 * 6 # ----------------------------- # API CONFIG # ----------------------------- # API VERSION API_VERSION = 1 # API ACCEPT HEADER API_ACCEPT_HEADER = 'application/json' # ----------------------------- # MOBILE APPLICATION CONFIG # ----------------------------- # APPLICATI
ON VERSION APP_VERSION = '1.0.0' # ----------------------------- # DATABASE CONFIG # ----------------------------- # DATABASE URL & SETTING DATABASE = { 'engine': 'postgres', 'host': 'localhost', 'port': '5432', 'user': '', 'password': '', 'database': '' } DATABASE_URI = '%(engine)s://%(use...
kartikeys98/coala
tests/processes/LogPrinterThreadTest.py
Python
agpl-3.0
879
0
import queue import unittest from testfixtures import LogCapture from coalib.processes.LogPrinterThread import LogPrinterThread class LogPrinterThreadTest(unittest.TestCase): def test_run(self): log_queue = queue.Queue() self.uut = LogPrinterThread(log_queue) log_queue.put(item='Sample ...
self.uut.start() while self.uut.message_queue.qsize() > 0: continue
self.uut.running = False self.uut.join() capture.check( ('root', 'INFO', 'Sample message 1'), ('root', 'INFO', 'Sample message 2'), ('root', 'INFO', 'Sample message 3') )
DougBurke/astropy
astropy/io/fits/scripts/fitsheader.py
Python
bsd-3-clause
12,441
0.00008
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ ``fitsheader`` is a command line script based on astropy.io.fits for printing the header(s) of one or more FITS file(s) to the standard output in a human- readable format. Example uses of fitsheader: 1. Print the header of all the HDUs of a .fits fil...
ains the meat of the formatting. ""
" def _parse_internal(self, hdukeys, keywords, compressed): """Method called by the parse method in the parent class.""" tablerows = [] for hdu in hdukeys: try: for card in self._get_cards(hdu, keywords, compressed): tablerows.append({'filename...
Pixdigit/MultiUserPython
player.py
Python
lgpl-3.0
2,249
0.026234
# -*- coding: utf-8 -*- import pygame from pygame.locals import MOUSEMOTION, MOUSEBUTTONDOWN import client import utility import user_input class new_local_player(): def __init__(self, ip, port): global goal_pos self.client = client.new_client(ip, port) used_id_pool = self.client.get_id_pool() self.id = ...
e.image.load("./player2_remote.png") self.size = self.img.get_rect().size self.players = {} self.update() def blit(self, screen, local_user_id): for player_id in self.players: if player_id != local_user_i
d: center = (int(self.players[player_id][0]), int(self.players[player_id][1])) pos = pygame.Rect((0, 0), self.size) pos.center = center screen.blit(self.img, pos) def update(self): self.players = self.client.get_pos_data()
start-jsk/jsk_apc
demos/grasp_fusion/grasp_fusion_lib/contrib/grasp_fusion/__init__.py
Python
bsd-3-clause
131
0
#
flake8: NOQA from . import datasets from . import evaluations from . import extensions from . import models from . impor
t utils
galgeek/firefox-ui-tests
firefox_ui_harness/cli_update.py
Python
mpl-2.0
492
0
# This Sou
rce Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from firefox_ui_harness.arguments import UpdateArguments from firefox_ui_harness.runners import UpdateTestRunner from firefox_ui_h...
li_update()
GoogleCloudPlatform/SourceXCloud
lib/sxc/actuator.py
Python
apache-2.0
1,235
0.00081
# Copyright 2015 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
gs): """Push an image to a target.""" raise NotImplementedError() class ActuatorExtension(Actuator): """Actuator extension consist
ing of hook programs.""" def __init__(self, actuator_root_dir): self.root = actuator_root_dir self.name = os.path.basename(actuator_root_dir) def push(self, core, image, args): result = core.get_utils().run_hook( self.root, 'push', core.get_source_directory(), *args, ...
jmanday/Informatica
DAI/Practicas/Practica4/a/code2.py
Python
gpl-3.0
1,189
0.038688
#!/bin/bash # -*- coding: utf-18 -*- from lxml import etree import re import sys import urllib total_noticias = 0 total_imagenes = 0 total_palabra = 0 j = 0 termino = sys.argv[1] tree = etree.parse('portada.xml') # Root element rss = tree.getroot() # Los elementos funcionan como listas # First child channel = rss...
palabra else: if (i.get('type') == "image/jpeg"): # comprobamos que son imagenes total_imagenes += 1 name = "0000%s.jpeg" % j # descargamos las imagenes j += 1 image = urllib.URLopener() image.retrieve(i.get('url'), name) if (e.tag == "image"): # comprobamos si hay ...
s imagenes total_imagenes += 1 print ('Hay %s noticias' % total_noticias) print ('Hay %s imagenes' % total_imagenes) print ('Hay %s apariciones del termino %s' % (total_palabra,termino))
Ecogenomics/GtdbTk
gtdbtk/external/hmm_aligner.py
Python
gpl-3.0
13,858
0.001371
############################################################################### # # # 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 # ...
ct = manager.dict() p_workers = [mp.Process(target=self._worker, args=(q_worker, q_writer, out_dict)) for _ in range(self.threads)] p_writer = mp.Process(target=self._writer, args=(q_writer, len(db_genome_ids))) ...
# Gracefully terminate the program. if p_worker.exitcode != 0: raise GTDBTkException( 'hmmalign returned a non-zero exit code.') q_writer.put(None) p_writer.join() except Exception: for p in p_work...
unoduetre/MovieRecommendator
featuremaker/plugins/IsCountryBrasil.py
Python
gpl-3.0
390
0.017949
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from Feature import Feature class IsCountryBrasil(Feature): description = """ Regi
onal: Production country: is it Brasil? """.strip() def __init__(self, *args, **kwargs): Feature.__init__(self) def extract(self, m): for pc in m.production_countries: if pc['iso_3166_1'] =
= 'BR': return True return False
ActiveState/code
recipes/Python/577852_Iterator_Offsetter/recipe-577852.py
Python
mit
833
0.0012
import itertools def offsetter(iterable, offsets=(0, 1), longest=False): """ Return offset element from an iterable. Pad offset element with None at boundaries. """ # clone the iterable clones = itertools.tee(iterable, len(offsets)) # set up the clone iterables itera
bles = [] for offset, clone in zip(offsets, clones): if offset > 0: # fast for
ward the start clone = itertools.islice(clone, offset, None) elif offset < 0: # pad the front of the iterable clone = itertools.chain(itertools.repeat(None, -offset), clone) else: # nothing to do pass iterables.append(clone) if lo...
rodluger/everest
debug/overfit_test.py
Python
mit
3,422
0.025716
import numpy as np import everest from everest.gp import GetCovariance from everest.transit import TransitShape, TransitModel, Get_rhos import matplotlib.pyplot as pl from scipy.linalg import cholesky, cho_solve from tqdm import tqdm import os # The injected depth depth = 0.001 # Load the light curve star = everest.E...
t0 = t0, per = 3.56789, rhos = Get_rhos(0.1, per = 3.56789), single = True) star.compute_joint() d = star.transit_depth star.transit_model = None JOMbf[n] = 1 - d / depth # Save! np.savez('overfit.npz...
Mbf = data['MOMbf'] JOMbf = data['JOMbf'] # Plot fig, ax = pl.subplots(3, figsize = (10, 6)) # Unmasked ax[0].plot(star.apply_mask(star.time), star.apply_mask(1 - (overfit._O2 + overfit._O3 / depth) / overfit._O1), 'k-', lw = 1) ax[0].plot(star.apply_mask(star.time), UOMbf, 'r-', lw = 1, alpha = 0.5) ax[0].set_xl...
mudler/entropy
lib/entropy/db/mysql.py
Python
gpl-2.0
36,707
0.001253
# -*- coding: utf-8 -*- """ @author: Fabio Erculiani <lxnay@sabayon.org> @contact: lxnay@sabayon.org @copyright: Fabio Erculiani @license: GPL-2 I{EntropyRepository} is the MySQL implementation of the repository interface. """ import os import hashlib import time try: import thread except...
(self._excs, self._con.ping) def unicode(self): """ Reimplemented from SQLConnectionWrapper. """ # This is a NO-OP, we are always un
icode return class EntropyMySQLRepository(EntropySQLRepository): """ EntropyMySQLRepository implements MySQL based storage. In a Model-View based design pattern, this can be considered the "model". """ # bump this every time schema changes and databaseStructureUpdate # should be trig...
gajjanag/6111_Project
assets/binaryToDecimal.py
Python
gpl-3.0
224
0.017857
# Shawn Jain # Python scrip
t to generate LUT for BCD.v for i in range(100): print str(i) + '
: begin ' + 'ones <= ' + str(i%10) + '; ' + 'tens <= ' + str(i/10) + ';' + ' end' print 'default: begin ones <= 0; tens <= 0; end'
cshallue/models
research/object_detection/utils/object_detection_evaluation.py
Python
apache-2.0
40,753
0.003362
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
weight=self._group_of_weight) self._image_ids = set([]) self._evaluate_corlocs = evaluate_corlocs self._metric_prefix = (metric_prefix + '_') if metric_prefix else '' def add_single_ground_truth_image_info(self, image_id, groundtruth_dict): """Adds groundtruth for a single i
mage to be used for evaluation. Args: image_id: A unique string/integer identifier for the image. groundtruth_dict: A dictionary containing - standard_fields.InputDataFields.groundtruth_boxes: float32 numpy array of shape [num_boxes, 4] containing `num_boxes` groundtruth boxes of ...
weiyirong/crosswalk-1
build/android/merge_java_srcs.py
Python
bsd-3-clause
2,054
0.012171
#!/usr/bin/env python # Copyright (c) 2014 Intel Corporation. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import optparse import os import re import sys import shutil def DoCopy(path, target_path): if os.path.isfile(path): package ...
ckage_re = re.compile( '^package (?P<package>([a-zA-Z0-9_]+.)*[a-zA-Z0-9
_]+);$') for line in open(path).readlines(): match = package_re.match(line) if match: package = match.group('package') break sub_path = os.path.sep.join(package.split('.')) shutil.copy(path, os.path.join(target_path, sub_path)) return for dirpath, _, files in os.walk(path)...
ProfessorKaos64/psutil
test/test_psutil.py
Python
bsd-3-clause
96,442
0.000114
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ psutil test suite. Run it with: $ make test If you're on Python < 2.7 unittest2 module must be installe...
cess.Popen(cmdline, shell=True, stdout=stdout, stderr=stderr) stdout, stderr = p.communicate() if p.returncode != 0: raise RuntimeError(stderr) if stderr: warn(stderr) if PY3: stdout = str(stdout, sys.stdout.encoding) return st
dout.strip() def which(program): """Same as UNIX which command. Return None on command not found.""" def is_exe(fpath): return os.path.isfile(fpath) and os.access(fpath, os.X_OK) fpath, fname = os.path.split(program) if fpath: if is_exe(program): return program else: ...
gxyang/hstore
build.py
Python
gpl-3.0
13,198
0.002349
#!/usr/bin/env python # -*- coding: utf-8 -*- import os, sys, commands, string, glob from buildtools import * # usage: # The following all work as you might expect: # python build.py # ./build.py debug # python build.py release # python build.py test # ./build.py clean # ./build.py release clean # python build.py rel...
unionexecutor.cpp updat
eexecutor.cpp """ CTX.INPUT['expressions'] = """ abstractexpression.cpp expressionutil.cpp tupleaddressexpression.cpp """ CTX.INPUT['plannodes'] = """ abstractjoinnode.cpp abstractoperationnode.cpp abstractplannode.cpp abstractscannode.cpp aggregatenode.cpp deletenode.cpp distinctnode.cpp indexscannode.cpp...
ThePerkinrex/PercOS
PercOS_filesystem/bin/rm.py
Python
gpl-3.0
406
0
from command import Command import os class Rm(Command): name = 'rm' desc = 'Removes a file or directory' usage = 'rm <file|dir>' author = 'native' def call(self, args=None): if args is not None and len(args) > 0: path = self.dire.realdir + '/' + args[0] try: ...
r(path)
ldong/vim_youcompleteme
third_party/jedi/test/test_evaluate/test_pyc.py
Python
gpl-3.0
1,546
0.001294
""" Test completions from *.pyc files: - generate a dummy python module - compile the dummy module to generate a *.pyc - delete the pure python dummy module - try jedi on the generated *.pyc """ import compileall import os import shutil import sys import jedi from ..helpers import cwd_at SRC = """class Foo: ...
# Python3 specific: # To import pyc modules, we must move them out of the __pycache__ # directory and rename them to remove ".cpython-%s%d" # see: http://stackoverflow.com/questions/11648440/python-does-not-detect-pyc-files for f in os.listdir("dummy_package/__pycache__"): ds...
%s' % sys.version_info[:2], "") dst = os.path.join("dummy_package", dst) shutil.copy(os.path.join("dummy_package/__pycache__", f), dst) @cwd_at('test/test_evaluate') def test_pyc(): """ The list of completion must be greater than 2. """ try: generate_pyc() s = j...
dpetter/Eowyne
src/core/administration/rules.py
Python
gpl-2.0
4,258
0.015031
# -*- coding: utf-8 -*- # # Rule # # Blueprint for rule administration. # # Created by dp on 2014-12-25. # ================================================================================ # from flask.blueprints import Blueprint from flask.globals import g from wtforms.fields.core import SelectField from wtforms.fields...
if not item: return mismatch() headline = localize("core", "rules.delete_headline") text = localize("core", "rules.delete_description") % (item.route) message = localize("core", "rules.delete_success") return delete_form(item, headline, text, message, "/rules", template = "cor...
navigation = navigation) # Edit Rule # -------------------------------------------------------------------------------- # @blueprint.route("/rules/<identifier>/update", methods = ["GET", "POST"]) def update(identifier): navigation = menubar("administration", g.role.id) item = Rule.get(int(identifier...
alexsilva/openvpn-admin
manage.py
Python
mit
811
0
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "openvpn_admin.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure tha
t the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your
PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv)
giacomov/3ML
threeML/utils/photometry/filter_library.py
Python
bsd-3-clause
10,414
0.002785
from __future__ import print_function from future import standard_library standard_library.install_aliases() from builtins import object import pandas as pd import os import yaml import astropy.io.votable as votable import astropy.units as u import urllib.request, urllib.error, urllib.parse import xml.etree.ElementTre...
sponse).to_table() # save the waveunit waveunit = data["Wavelength"].unit # the filter files are masked arra
ys, which do not go to zero on # the boundaries. This confuses speclite and will throw an error. # so we add a zero on the boundaries if data["Transmission"][0] != 0.0: w1 = data["Wavelength"][0] * 0.9 data.insert_row(0, [w1, 0]) if data["Transmission"][-1] != ...
Faraaz54/python_training_problems
codecademy_scripts/class_time.py
Python
mit
908
0.036344
def print_time(t): print "%2d : %2d : %2d" % (t.hour, t.minute, t.second) def time_to_int(time): minutes = time.hour * 60 + time.minute seconds = minutes * 60 + time.second return seconds def int_to_time(seconds): time = Time() minutes, time.second = divmod(seconds, 60) time...
s a class which gives you the time at
tributes: hours, minutes, seconds """ def print_time(self): print "%2d : %2d : %2d" % (self.hour, self.minute, self.second) def __init__(self, hour=0, minute=0, second=0): self.hour = hour self.minute = minute self.second = second time = Time() ...
shinpeimuraoka/ryu
ryu/services/protocols/bgp/info_base/vrf.py
Python
apache-2.0
25,658
0
# Copyright (C) 2014 Nippon Telegraph and Telephone Corporation. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
self): """Returns count of local and remote p
aths.""" remote_route_count = 0 local_route_count = 0 for dest in self.values(): for path in dest.known_path_list: if (hasattr(path.source, 'version_num') or path.source == VPN_TABLE): remote_route_count += 1 ...
mrwsr/monotone
test/test_monotone.py
Python
mit
7,143
0
""" Tests for L{monotone}. """ from hypothesis import given, strategies as st import errno from monotone import get_clock_info, monotonic from monotone import _api, _bindings import os import platform import pytest needs_posix = pytest.mark.skipif( os.name == "posix" and platform.system() == "Darwin", reas...
Two instances with equal C{__dict__}s are equal. """ assert _api._SimpleNamespace(a=1) == _api._SimpleNamespace(a=1) @needs_posix class TestGetClockInfoPosix(object): """ Tests for L{get_clock_info}. """ def test_non_monotonic(self): """ L{get_clock_info} only know
s about the monotonic clock. """ with pytest.raises(ValueError): get_clock_info("not monotonic") def test_failure(self, apply_failing_clock_call, errno_value, strerror): """ A failure in C{clock_getres} results in an L{OSError} that presents the failure's errno. ...
lucekdudek/si
lab07/Food.py
Python
apache-2.0
78
0
from enum import Enum
class Food(Enum): rancid =
0 delicious = 10
hawkerpl/k2
utils/django/db/models/sql/aggregates.py
Python
gpl-2.0
154
0.012987
from d
jango.db.models.sql.aggregates import * class IfnullSum(Aggregate): sql_function = 'SUM' sq
l_template = 'IFNULL(%(function)s(%(field)s),0)'
lixiangning888/whole_project
modules/signatures_merge_tmp/hawkeye_apis.py
Python
lgpl-3.0
6,041
0.001329
# -*- coding: utf-8 -*- # Copyright (C) 2015 KillerInstinct # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This p...
wargs) self.badness = 0 self.sockets = dict() self.lastcall = str() self.nodename = str() self.badsocks = set() self.keywords = [ # SMTP Keywords "AUTH", "MAIL FROM", "RCPT TO", # FTP Keywords...
er", "dear hawkeye customers", "dear invisiblesoft users", ] self.guidpat = "([0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{13})\.\d+Event" self.evguid = str() self.evmatch = False def on_call(self, call, process): if...
ayushjain786/Wtproject
blog/migrations/0003_comment.py
Python
mit
978
0.003067
# -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2017-09-18 07:59 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import django
.utils.timezone class Migration(migrations.Migration):
dependencies = [ ('blog', '0002_post_subtitle'), ] operations = [ migrations.CreateModel( name='Comment', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('author', models.Cha...
Jumpscale/jumpscale_portal8
apps/gridportal/base/Grid/.macros/wiki/workersjobs/3_workersjobs.py
Python
apache-2.0
635
0.007874
def main(j, args, params, tags, tasklet): doc = args.doc nid = args.getTag('nid') node =j.apps.system.gridmanager.getNodes(
nid=nid) if node: node = node[0].to_dict() workerscl = j.clients.agentcontroller.getProxy(category="worker") jobs = workerscl.getQueuedJobs(queue=None, format='json', _agentid=nid) # TODO: does not work ques not implemented in ac2 #accl = j.clients.agentcontroller.getAdvanced() #jobs = ...
.applyTemplate({'name': node['name'], 'jobs': jobs}) params.result = (doc, doc) return params def match(j, args, params, tags, tasklet): return True
wkeeling/ansible
lib/ansible/utils/module_docs_fragments/dnos9.py
Python
gpl-3.0
3,305
0
# 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 later version. # # Ansible is distributed in the hope that ...
GNU General Pu
blic License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. class ModuleDocFragment(object): # Standard files documentation fragment DOCUMENTATION = """ options: host: description: - Specifies the DNS host name or address for connecting to the remote device over the sp...
thaJeztah/compose
tests/integration/metrics_test.py
Python
apache-2.0
4,620
0.000866
import logging import os import socket from http.server import BaseHTTPRequestHandler from http.server import HTTPServer from threading import Thread import requests from docker.transport import UnixHTTPAdapter from tests.acceptance.cli_test import dispatch from tests.integration.testcases import DockerClientTestCase...
n resp.content def start_server(uri=TEST_SOCKET_FILE): try: os.remove(uri) except OSError: pass httpd = HTTPServer(uri, MetricsHTTPRequestHandler, False) sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) sock.bind(TEST_SOCKET_FILE) sock.listen(0) httpd.socket = sock ...
cket.SHUT_RDWR) sock.close() os.remove(uri) class MetricsServer: @classmethod def start(cls): t = Thread(target=start_server, daemon=True) t.start() class MetricsHTTPRequestHandler(BaseHTTPRequestHandler): usages = [] def do_GET(self): self.client_address = ('',) # ...
armadill-odyssey/aima-python
grading/game-submissions.py
Python
mit
5,465
0.004941
import importlib import traceback from games import alphabeta_search from grading.util import roster, print_table from io import StringIO import sys class MyException(Exception): pass def play_game(game, *players, verbose=False): """Play an n-person, move-alternating game.""" state = game.initial if...
if not ver
bose: game.display(state) return game.utility(state, game.to_move(game.initial)) class TiredOfPlaying(Exception): pass def make_ab(depth): function = lambda game, state: alphabeta_search(state, game, d=depth) function.label = "AB(" + str(depth) + ")" return function...
unnikrishnankgs/va
venv/lib/python3.5/site-packages/IPython/core/magics/basic.py
Python
bsd-2-clause
21,310
0.002628
"""Implementation of basic magic functions.""" import argparse import textwrap import io import sys from pprint import pformat from IPython.core import magic_arguments, page from IPython.core.error import UsageError from IPython.core.magic import Magics, magics_class, line_magic, magic_escapes from IPython.utils.tex...
'No line or cell magic with name `%s` found.' % target ) args.line = bool(m_line) args.cell = bool(m_cell) params_str = "" if params is None else " " + params if args.line: mman.register_alias(name, target, 'line', params) ...
magic_escapes['line'], target, params_str)) if args.cell: mman.register_alias(name, target, 'cell', params) print('Created `%s%s` as an alias for `%s%s%s`.' % ( magic_escapes['cell'], name, magic_escapes['cell'], target, params_str)) @...
bearstech/modoboa
modoboa/core/signals.py
Python
isc
1,828
0
"""Modoboa core signals.""" from __future__ import unicode_literals import django.dispatch account_auto_created = django.dispatch.Signal(providing_args=["user"]) account_exported = django.dispatch.Signal(providing_args=["account"]
) account_imported = django.dispatch.Signal( providing_args=["user", "account", "row"]) account_deleted = django.dispatch.Signal(providing_args=["user"]) account_role_changed = django.dispatch.Signal( providing_args=["account", "role"]) account_password_updated = django.dispatch.Si
gnal( providing_args=["account", "password", "created"]) allow_password_change = django.dispatch.Signal(providing_args=["user"]) can_create_object = django.dispatch.Signal( providing_args=["context", "klass", "object_type", "count", "instance"]) extra_account_actions = django.dispatch.Signal(providing_args=["ac...
colincsl/pyKinectTools
pyKinectTools/dataset_readers/BasePlayer.py
Python
bsd-2-clause
3,177
0.029588
import numpy as np import cv2 from skimage.morphology import closing, erosion, opening from pyKinectTools.algs.BackgroundSubtraction import * class BasePlayer(object): depthIm = None colorIm = None users = None backgroundModel = None foregroundMask = None mask = None prevcolorIm = None def __init__(self, b...
r='./', get_depth=True, get_color=False, get_skeleton=False, bg_subtraction=False, fill_images=False, background_model=None, background_param=None): self.base_dir = base_dir self.deviceID = '[]' if bg_
subtraction and background_model is None: raise Exception, "Must specify background_model" self.get_depth = get_depth self.get_color = get_color self.get_skeleton =get_skeleton self.enable_bg_subtraction = bg_subtraction self.fill_images = fill_images if background_model is not None: print 'Setting...
scorphus/eg
test/color_test.py
Python
mit
5,718
0.000175
import os from collections import namedtuple from eg import color from eg import config from mock import patch # Some hardcoded real colors. _YELLOW = '\x1b[33m' _MAGENTA = '\x1b[35m' _BLACK = '\x1b[30m' _GREEN = '\x1b[32m' # The flags in the test file marking where substitutions should/can occur. SubFlags = namedt...
er = color.EgColorizer(color_config) actual = colorizer.colorize_heading(clean) assert actual == target def test_colori
ze_block_indents(): """Makes sure we colorize block indents correctly.""" color_config = config.ColorConfig( _BLACK, _MAGENTA, 'C', _YELLOW, 'P', '', '', 'res', '', 'res' ) clean = get_clean_find_file() raw_file = get_...
open-power-ref-design-toolkit/cluster-genesis
scripts/python/show_status.py
Python
apache-2.0
6,393
0.000626
#!/usr/bin/env python3 # Copyright 2019 IBM Corp. # # 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...
( GEN_CONTAINER_ADDR, log=log, ssh_log=ssh_log_filename, username='deployer', look_for_keys=False, key_filename=GEN_CONTAINER_SSH_KEY_PRIVATE) except SSH_Exception as exc: ...
H to container {} using private key {}' .format(GEN_CONTAINER_NAME, GEN_CONTAINER_SSH_KEY_PRIVATE)) print(exc) if not ssh_cont: PASSWORD = 'ubuntu' print('Trying password "{}"'.format(PASSWORD)) while PASSWORD[-1:] != '.': ...
SivaCn/Bigdata.model
src/utils/chains.py
Python
mit
2,013
0.00149
#! /usr/bin/python """Linked list Representation and implementation. """ # -*- coding: utf-8 -*- ## ------ Imports ------ ## ## ------ Imports ------ ## __author__ = "Siva Cn (cnsiva.in@gmail.com)" __website__ = "http://www.cnsiva.com" class Node: """Referential Structure used to create new nodes""" def ...
""" def __init__(self, **kwargs): """Constructor."""
self.start = None self.size = 0 self._id_start, self._id_end = kwargs.get('_id_range', (-1, -1)) def __repr__(self): """.""" return "SubList({0}, {1})".format(self._id_start, self._id_end) class LinkedList: def __init__(self, **kwargs): """Constructor.""" s...
kogotko/carburetor
openstack_dashboard/dashboards/admin/overview/tests.py
Python
apache-2.0
10,491
0
# Copyright 2012 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # 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...
g_ip_list(IsA(http.HttpRequest)) \ .AndReturn(self.floating_ips.list()) api.network.security_group_list(IsA(http.HttpRequest)) \ .AndReturn(self.q_secgroups.list()) api.cinder.tenant_absolute_limits(IsA(http.HttpRequest)) \ .AndReturn(self.cinder_limits['absolute'])
self.mox.ReplayAll() res = self.client.get(reverse('horizon:admin:overview:index')) self.assertTemplateUsed(res, 'admin/overview/usage.html') self.assertIsInstance(res.context['usage'], usage.GlobalUsage) self.assertEqual(nova_stu_enabled, res.context['...
rhefner1/c3po
c3po/util/twitter_api.py
Python
apache-2.0
1,485
0
"""Utility functions for Twitter API interactions""" from datetime import datetime import twitter TWITTER_DATE_FORMAT = "%a %b %d %H:%M:%S +0000 %Y" def pretty_twitter_date(tweet): """Converts a Twitter formatted date to a Python object.""" py_date = datetime.strptime(tweet.created_at, TWITTER_DATE_FORMAT)...
= msg.settings.twitter_conf return twitter.Api(consumer_key=conf.consume
r_key, consumer_secret=conf.consumer_secret, access_token_key=conf.access_token_key, access_token_secret=conf.access_token_secret) def pretty_date(date): """ Returns a natural language description of a date. Adapted from: https://stackov...
vpodzime/lvm-dubstep
lvmdbus/fetch.py
Python
gpl-3.0
1,576
0.000635
# This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # bu...
es = load_pvs(refresh=refresh) num_total_changes += num_changes for p in pvs: cfg.om.register_object(p, refresh) vgs, num_changes = load_vgs(refresh=refresh)
num_total_changes += num_changes for v in vgs: cfg.om.register_object(v, refresh) lvs, num_changes = load_lvs(refresh=refresh) num_total_changes += num_changes for l in lvs: cfg.om.register_object(l, refresh) return num_total_changes
leopard7777777/taobao_deal_history
taobao/spiders/spider1.py
Python
apache-2.0
2,267
0.005734
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Date: 2016-07-18 15:53:21 @Author: King @Desc: """ import re from ..items import DealData from scrapy.loader.processors import TakeFirst, Join from scrapy import Selector from scrapy.loader import ItemLoader import scrapy class DealItemLoader(ItemLoa...
r): default_output_processor = TakeFirst() class DealHistory(scrapy.Spider): name = 'deal_history' def __init__(self, seller_id=None, item_id=None, size=100, *args, **kwargs): super(DealHistory, self).__init__(*args, **kwargs) self.seller_id = seller_id self.item_id = item_id ...
&page_size=%s" % (self.page, self.item_id, self.seller_id, self.size), meta={'dont_obey_robotstxt': True}, callback=self._history)] def _history(self, response): content = re.findall('\$callback\({html:"(.*?)"}\)', response.body) if content: sel = Selector(text=content[0].replace(r'\"',...
j4v/pyProjects
pyWorker/pyworker.py
Python
gpl-3.0
5,287
0.002081
#!/usr/env/python2 """ Implements multi-threaded job handler that solves a classic network problem: When processing a network job, often there will be data transferred but at such a slow rate that the connection is in fact "hung". In this case, the thread should be considered as "dead", and another thread ...
s so. If it eventually finishes its job, it will introspect its state and stop. A new thread is created in its place, so that there is always the same amount of "
alive" threads working. Good programming practice is to kill network job after a certain amount of time without receiving any data. """ import datetime import threading import thread import Queue import time __author__ = "j4v" __copyright__ = "Copyright 2016, www" __license__ = "GPL" __version__ = "3" __maintaine...
nuwainfo/treeio
core/api/resource.py
Python
mit
815
0.002454
# encoding: utf-8 # Copyright 2011 Tree.io Limited # This file is part of Treeio. # License www.tree.io/license #-*- coding: utf-8 -*- import sys import utils sys.modules['piston.utils'] = utils from piston.resource import Resource class CsrfExemptResource(Resource): """A Custom Resource that is csrf exempt""...
def __init__(self, handler, authentication=None): super(CsrfExemptResource, self).__init__(handler, authentication) self.csrf_exempt = getattr(self.handler, 'csrf_exempt', True) def __call__(self, request, *args, **kwargs): res = super(CsrfExemptResource, sel
f).__call__( request, *args, **kwargs) if hasattr(self.handler, 'status'): res.status_code = self.handler.status del self.handler.status return res
stripe/stripe-python
stripe/api_resources/plan.py
Python
mit
505
0
# File generated from o
ur OpenAPI spec from __future__ import ab
solute_import, division, print_function from stripe.api_resources.abstract import CreateableAPIResource from stripe.api_resources.abstract import DeletableAPIResource from stripe.api_resources.abstract import ListableAPIResource from stripe.api_resources.abstract import UpdateableAPIResource class Plan( Createab...
dreadrel/UWF_2014_spring_COP3990C-2507
notebooks/scripts/book_code/code/manynames.py
Python
apache-2.0
1,122
0.00713
X = 11 # Global (module) name/attribute (X, or manynames.X) def f(): print(X) # Access global X (11) def g(): X = 22 # Local (function) variable (X, hides module X) print(X) class C: X = 33 # Class attribute (C.X) def m(sel...
X) self.X = 55 # Instance attribute (instance.X) if __name__ == '__main__': print(X) # 11: module (a.k.a. manynames.X outside file) f() # 11: global g() # 22: local print(X) # 11: module name unchanged obj =...
ance obj.m() # Attach attribute name X to instance now print(obj.X) # 55: instance print(C.X) # 33: class (a.k.a. obj.X if no X in instance) #print(C.m.X) # FAILS: only visible in method #print(g.X) # FAILS: only visible in functio...
portfors-lab/sparkle
sparkle/gui/dialogs/channel_dlg.py
Python
gpl-3.0
1,792
0.003906
from sparkle.QtWrapper import QtCore, QtGui from sparkle.acq.daq_tasks import get_ai_chans class ChannelDialog(QtGui.QDialog): def __init__(self, device_name): super(ChannelDialog, self).__init__() layout = QtGui.QGridLayout() cnames = get_ai_chans(device_name) layout.add...
row += 1 if row > max_row:
row = 1 col +=1 okBtn = QtGui.QPushButton("OK") okBtn.clicked.connect(self.accept) cancelBtn = QtGui.QPushButton("Cancel") cancelBtn.clicked.connect(self.reject) layout.addWidget(okBtn, max_row+1, 0) row += 1 layout.addWidget(cancelBtn, max_row...
xiyuw123/Tax-Calculator
taxcalc/functions.py
Python
mit
44,187
0.010207
import pandas as pd from pandas import DataFrame import math import numpy as np from .decorators import * @iterate_jit(nopython=True) def FilingStatus(MARS): if MARS == 3 or MARS == 6: _sep = 2 else: _sep = 1 return _sep @iterate_jit(parameters=["ALD_StudentLoan_HC", "ALD_SelfEmploymentTax_HC", ...
2500) @iterate_jit(parameters=["II_em", "II_em_ps", "II_prt"], nopython=True) def AGI( _ymod1, c02500, c02700, e02615, c02900, e00100, e02500, XTOT, II_em, II_em_ps, MARS, _sep, _fixup, II_prt): # Adjusted Gross Income c02650 = _ymod1 + c02500 - c02700 + e02615 # Gross Income c00100...
ed Gross Income if _fixup >= 1: c00100 = c00100 + _agierr _posagi = max(c00100, 0) _ywossbe = e00100 - e02500 _ywossbc = c00100 - c02500 _prexmp = XTOT * II_em # Personal Exemptions (_phaseout smoothed) _dispc_numer = II_prt * (_posagi - II_em_ps[MARS - 1]) _dispc_denom =...
ashishtanwer/DFS
conf/flowDurationPercentile.py
Python
gpl-2.0
280
0.021429
import sys import re from subprocess import Popen, PIPE import os.path import glob totalflowsum=0 fi = open("Hflowstart.txt","r") for line in fi: if line.strip()!=
"": Flow=line.strip().split(" ") totalflo
wsum=totalflowsum+float(Flow[0]) print totalflowsum
feranick/GES_AT
GridEdgeAT/gridedgeat/configDMWindow.py
Python
gpl-3.0
9,495
0.005161
''' Data Management Window ------------------ Class for providing a graphical user interface for Data Management Window Copyright (C) 2017-2019 Nicola Ferralis <ferralis@mit.edu> 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 ...
bel") self.gridLayout.addWidget(self.dbHttpPathLabel, 7, 0, 1, 1) self.gridLayout.addWidget(QHLine(), 8, 0, 1, 1) self.gridLayout.addWidget(QHLine(), 8, 1, 1, 1) self.dbTestConnectButton = QPushButton(Panel) self.dbTestConnectButton.setGeometry(QRect(10, 260, 270, 40
)) self.dbTestConnectButton.setObjectName("dbTestConnectButton") self.dbSetDefaultButton = QPushButton(Panel) self.dbSetDefaultButton.setGeometry(QRect(10, 300, 270, 40)) self.dbSetDefaultButton.setObjectName("dbSetDefaultButton") self.dbRestoreDefaultButton = QPushButton(Panel) ...
rock-simulation/phobos
phobos/io/entities/submechanisms.py
Python
lgpl-3.0
2,046
0.002933
#!/usr/bin/python3 # coding=utf-8 # ------------------------------------------------------------------------------- # This file is part of Phobos, a Blender Add-On to edit robot models. # Copyright (C) 2020 University of Bremen & DFKI GmbH Robotics Innovation Center # # You should have received a copy of the 3-Clause ...
ader'] objects = [ o for link in linkobjs for o in link.children if o.phobostype in ['visual', 'collision', 'inertial'] ] + linkobjs model = deriveModelD
ictionary(root, root['submechanism/name'], objects) jointname = nUtils.getObjectName(root, 'joint') if jointname in model['joints']: del model['joints'][jointname] log('Removed joint which is not part of submodel: ' + jointname, 'DEBUG') exportModel(model, path, ['urdf'])...
cedadev/cloudhands-ops
functional/cloudclient/aws/test_aws_client.py
Python
bsd-3-clause
1,689
0.007105
''' Created on Nov 08, 2013 @author: philipkershaw ''' from os import path import unittest import logging log = logging.getLogger(__name__) logging.basicConfig(format='%(asctime)s %(message)s', level=logging.DEBUG) from libcloud import security from libcloud.compute.types import Provider from libcloud.compute.provide...
or node in nodes: self.assert_(node) log.info('node = %r', node) @unittest.skip("Pending AWS account") class TestEuWestAwsCloudClient(unittest.TestCase): security.CA_CERTS_PATH = [CA_CERTS_PATH] def setUp(self): USERNAME, PASSWORD = open(CREDS_FILEPATH).read().split('...
odes(self): nodes = self.conn.list_nodes() for node in nodes: self.assert_(node) log.info('node = %r', node) if __name__ == "__main__": #import sys;sys.argv = ['', 'Test.testName'] unittest.main()
gitaarik/django
tests/migrations/test_migrations_conflict/0002_conflicting_second.py
Python
bsd-3-clause
384
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): depende
ncies = [("migrations", "0001_initial")] operations = [ migrations.CreateM
odel( "Something", [ ("id", models.AutoField(primary_key=True)), ], ) ]
spencertiberi/compsci.one
application.py
Python
mit
1,476
0.002033
# Source: David Malan. https://github.com/cs50/manual50 import os from flask import Flask, abort, redirect, request, send_file from r
aven.contrib.flask import Sentry # application app = Flask(__name__) # monitoring sentry = Sentry(app) # no-cache @app.after_request def after_request(response): response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate" response.headers["Expires"] = 0 response.headers["Pragma"] = "no-cach...
@app.route("/<path:path>") def index(path): p = os.path.realpath(os.path.join(_site, path)) if not p.startswith(_site): abort(403) if os.path.isfile(p): basename = os.path.basename(path) if basename == "index.html": return redirect(os.path.dirname(path)) elif base...
alvin319/CarnotKE
jyhton/tests/java/org/python/indexer/data/pkg/other/color/green.py
Python
apache-2.0
20
0
r =
0 g = 255 b =
0
Microsoft/PTVS
Python/Tests/GlassTests/PythonTests/Python/Eval_InNative/py_mod.py
Python
apache-2.0
111
0.018018
impor
t cpp_mod class Foo(object): pass foo = Foo() foo.x = ([foo],) foo.y = {'foo': 123} cpp_mod.global_func
()
jvrsantacruz/XlsxWriter
xlsxwriter/test/comparison/test_simple04.py
Python
bsd-2-clause
4,422
0
#####################################################################
########## # # Tests for XlsxWriter. # # Copyright (c), 2013-2015, John McNamara, jmcnamara@cpan.org # from ..excel_comparsion_test import ExcelComparisonTest from datetime import datetime, date, time from ...workbook imp
ort Workbook class TestCompareXLSXFiles(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.maxDiff = None filename = 'simple04.xlsx' test_dir = 'xlsxwriter/test/comparison/' self.got_filename = test_d...
Orange9000/Codewars
Solutions/5kyu/5kyu_regex_password_validation.py
Python
mit
60
0.016667
re
gex= '^(?=.*[0-9])(?=.*[A-Z])(?=
.*[a-z])[a-zA-Z0-9]{6,}$'
devendermishrajio/nova
nova/tests/unit/virt/ironic/test_driver.py
Python
apache-2.0
76,926
0.000312
# Copyright 2015 Red Hat, Inc. # Copyright 2013 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/L...
imitations # under the License. """Tests for the ironic driver.""" from ironicclient import exc as ironic_exception import mock from oslo_config import cfg from oslo_serialization import jsonutils from oslo_service import loopingcall from oslo_utils import uuidutils import six from testtools.matchers import HasLen...
ova_states from nova.compute import task_states from nova.compute import vm_states from nova import context as nova_context from nova import exception from nova import objects from nova import test from nova.tests.unit import fake_instance from nova.tests.unit import utils from nova.tests.unit.virt.ironic import utils ...
ASaiun/saiun_bysj
app/__init__.py
Python
apache-2.0
785
0.001274
from flask import Flask from flask_bootstrap import Bootstrap from flask_mail import Mail from flask_moment import Moment
from flask_sqlalchemy import SQLAlchemy from config import config import chartkick bootstrap = Bootstrap() mail = Mail() moment = Moment() db = SQLAlchemy() def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) app.jinja_env.add_extension("chartkick.ext.charts") ...
config[config_name].init_app(app) bootstrap.init_app(app) mail.init_app(app) moment.init_app(app) db.init_app(app) from .main import main as main_blueprint app.register_blueprint(main_blueprint) from .crawler import crawler as crawler_blueprint app.register_blueprint(crawler_blueprint...
dnaextrim/django_adminlte_x
adminlte/static/plugins/datatables/extensions/ColVis/examples/button_order.html.py
Python
mit
16,631
0.037941
XXXXXXXXX XXXXX XXXXXX XXXXXX XXXXX XXXXXXXXXXXXXXXX XXXXX XXXXXXXXXXXXX XXXXX XXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXX XXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXX X XXXXXX XXXXXXXXXXXXXXXX XXXXX XXXXXXXXXXXXXXXX XXXXXXXXXXXXXXX XXXXXXXXXXXXXXX...
XXXX XXXXXXXXXXXXX XXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXX XXXXXXXXXXXX XXXXXXXXX XXXXXXXXX XXXXXXXXXXXXXXX XXXXX XXXXXXXX XXXXXXX XXXX XXXXXXXXX XXXXXXXXXX XXXXXXXXXX XXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXX X
XXXXXXXXXX XXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXX XXXXX XXXX XXXXXXXXXXX XXXXXXXXXXXX XXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXX XXXXXXXXXXX XXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXX XXXXX XXXX XXXXXXXXXX XXXXXXXX XXXXXXXXXX XXXXXXXXX XXXXXXXXXXX ...
csutherl/sos
sos/plugins/ntp.py
Python
gpl-2.0
1,526
0
# 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; eit
her 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 for more details. # You...
write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. from sos.plugins import Plugin, RedHatPlugin, DebianPlugin, UbuntuPlugin class Ntp(Plugin): """Network time protocol """ plugin_name = "ntp" profiles = ('system', 'services') packages = ('ntp',) def setu...
chippey/gaffer
apps/test/test-1.py
Python
bsd-3-clause
3,907
0.029178
########################################################################## # # Copyright (c) 2011-2012, John Haddon. All rights reserved. # Copyright (c) 2011-2013, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted prov...
any other contributor
s to this software may be used to endorse or # promote products derived from this software without specific prior # written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS # IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED W...
Rufflewind/calico
tools/utils.py
Python
mit
5,989
0.003006
import io, os, re, subprocess, sys #@snip/WorkDir[ #@requires: mod:os class WorkDir(object): '''A context manager for changing to a different working directory. The original working directory is restored upon exiting the context.''' def __init__(self, path): '''Initialize a context for changing t...
m = stream self.attributes = { "deps": [], } def preprocess(self): if
self.stream: write = self.stream.write else: write = lambda s: None s = load_file(self.filename) with WorkDir(os.path.dirname(self.filename)): write(self._process_directives(s)) def bench(self): self.attributes["bench"] = True def public(self...
b3j0f/sync
b3j0f/sync/accessor/filter.py
Python
mit
315
0
NOT = ['!', '$not'] IN = ['$in'] NIN = ['$nin'] AND = ['&&', '$and'] OR = ['||', '$or'] NOR = ['!||', '$nor'] EQ = ['=', '$eq']
LT = ['<', '$lt'] GT = ['>', '$gt'] LTE = ['<=', '$lte'] GTE = ['>=', '$gte'] NEQ = ['!=', '$neq'] LIKE = ['%%', '$re'] EXISTS = ['$ex'] TYPE = ['$t'] MOD = ['%', '$mod'] SIZE
= ['$len']
spcui/autotest
client/deps/mysql/mysql.py
Python
gpl-2.0
997
0.004012
#!/usr/bin/python import os from autotest.client import utils version = 3 def setup(tarball, topdir): srcdir = os.path.join(topdir, 'src') if not os.path.exists(tarball): utils.get_file('http://downloads.mysql.com/archives/mysql-5.0/mysql-5.0.45.tar.gz', tarball) utils.extract_tarball_to_dir(tarb...
b' % topdir) os.chdir(topdir) pwd = os.getcwd() tarball = os.path.join(pwd, 'mysql-5.0.45.tar.gz') utils.updat
e_version(pwd+'/src', False, version, setup, tarball, pwd)