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
v-samodelkin/TowerDefence
MapObjects/Enemy.py
Python
mit
2,746
0
# -*- coding: utf8 -*- import MapModel as Mm from MapObjects.MovingObject import MovingObject import Statistic class Enemy(MovingObject): dx = [0, 1, 0, -1] dy = [1, 0, -1, 0] def __init__(self, health, width, height): super().__init__() self.gold = 2 self.able_to_go = {Mm.Player,...
}\n".format(self.health) info += "Урон: {0}\n".format(self.damage) return info def collision_init(self): # noinspection PyUnusedLocal @self.collide_registrar(Mm.Ground) def ground_collide(obj, ground): return None, obj @sel
f.collide_registrar(Mm.HeartStone) def heartstone_collide(obj, heartstone): heartstone.attack(obj.damage * (obj.health / heartstone.defence)) return None, heartstone @self.collide_registrar(Mm.Arrow) def arrow_collide(obj, arrow): obj.health -= arrow.damage ...
smiley325/accounter
ref/edmunds.py
Python
epl-1.0
1,537
0.001952
import os, requests, time import mydropbox edmunds = mydropbox.get_keys('edmunds') api_key = edmunds['api_key'] api_secret = edmunds['api_secret'] vin = mydropbox.read_dropbox_file(os.path.join('Records', 'Financials', 'Car', 'VIN')).strip() r = requests.get("https://api.edmunds.com/api/vehicle/v2/vins/%s?&fmt=json&a...
ionid: "&optionid=%s" % optionid, optionids)) + ''.join(map(lambda colorid: "&colorid=%s" % colorid, colorids)) + "&condition=%s" % condition + "&mileage=%s" % mileage + "&zip=%s" % zipcode + "&fmt=json&api_key=%s" % api_key ) data = r.json() totalWithOptions = data['tmv']['totalWithOptions'] disp...
('Used TMV Retail', 'usedTmvRetail') ] total = 0.0 for label, key in disp: total += totalWithOptions[key] print("%s: %f" % (label, totalWithOptions[key])) total /= 3 print("Average: %f" % total)
mcallistersean/b2-issue-tracker
toucan/user_profile/notifications/email.py
Python
mit
561
0.005348
from django.template.loader import get_template from . import BaseNotification class EmailNotification(BaseNotification): def get_message(self): template = get_template('user_profile/notification/email/issue.txt') return template.render({ 'issue': self.issue, 'notification...
ification }) def send_issue_notification(self): self.notification.user.email_user( 'New Issue #%s created: %s' % (self.issue.pk, self.issue.title), self.
get_message() )
naegi/dotfiles
home/spotify_status.py
Python
unlicense
3,414
0.003515
#!/usr/bin/env python3 import sys import dbus import argparse parser = argparse.ArgumentParser() parser.add_argument( '-t', '--trunclen', type=int, metavar='trunclen' ) parser.add_argument( '-f', '--format', type=str, metavar='custom format', dest='custom_format' ) parser.add_argum...
dest='play_pause' ) parser.add_argument( '-d', '--default', type=str, metavar='string to return when spotify is off', dest='default') parser.add_argument( '--font', type=str, metavar='the index of
the font to use for the main label', dest='font' ) parser.add_argument( '--playpause-font', type=str, metavar='the index of the font to use to display the playpause indicator', dest='play_pause_font' ) args = parser.parse_args() def fix_string(string): # corrects encoding for the python versi...
tuturto/pyherc
src/pyherc/test/unit/test_itemadder.py
Python
mit
5,532
0.009219
# -*- coding: utf-8 -*- # Copyright (c) 2010-2017 Tuukka Turto # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy,...
les = [EffectHandle( trigger = 'on drink', effect = 'cure medium wounds', parameters = None, charges = 1)])) self.item_generator = Item...
em_generator, self.configuration, self.rng) self.item_adder.add_items(self.level) def test_adding_items(self): """ Test basic case of adding items on the level """ assert_that(list(get_items(self.level)...
scommab/can-opener
cans/gmail.py
Python
apache-2.0
1,364
0.026393
from threading import Thread import sys import imaplib import time class Can(Thread): def __init__(self, id, config, opener, key): Thread.__init__(self) self.key = key self.config = config self.id = id self.opener = opener self.running = True pass def run(self): try: user = ...
ject = data.split('"')[3] if str(self.key) in subject: r, body = m.fetch(uid, '(BODY[TEXT])') body = body[0][1].strip() #print subject #print body self.opener(self
.id, body) m.logout() time.sleep(15) def stop(self): self.running = False def setKey(self, key): self.key = key if __name__ == "__main__": cans = {} def opener(id, ans): if id not in cans: return if ans == "quit": cans[id].stop() c = Can(1, opener, "non-real") ca...
ESOedX/edx-platform
common/test/acceptance/pages/lms/peer_grade.py
Python
agpl-3.0
1,101
0.000908
""" Students grade peer submissions. """ from __future__ import absolute_import from bok_choy.page_object import PageObject from bok_choy.promise import Promise class PeerGradePage(PageObject): """ Students grade peer submissions. """ url = None def is_browser_on_page(self): def _is_co...
(): is_present = ( self.q(css='div.peer-grading-tools').present or self.q(css='div.grading-panel.current-state').present ) return is_present, is_present return Promise(_is_correct_page, 'On the peer grading page.').fulfill() @property ...
(self, problem_name): """ Choose the problem with `problem_name` to start grading or calibrating. """ index = self.problem_list.index(problem_name) + 1 self.q(css='a.problem-button:nth-of-type({})'.format(index)).first.click()
seokjunbing/cs75
src/data_processing/read_data.py
Python
gpl-3.0
22,577
0.00186
import os, re, sys import read_dicts from collections import Counter import pandas as pd import numpy as np import operator import random sys.path.append('.') ENABLE_WRITE = 1 INDEX_NAMES_FILES = '../../data/aaindex/list_of_indices.txt' def getscores(d, aalist, seq): score_list = list() char_freq = dict()...
: if c in char_freq: char_freq[c] += 1 else:
char_freq[c] = 1 for aa in aalist: score = 0 for k in d[aa].iterkeys(): try: freq = char_freq[k] except KeyError: freq = 0 score += d[aa][k] * freq score_list.append(str(score)) return '|'.join(score_list) d...
google-research/federated
utils/keras_metrics.py
Python
apache-2.0
2,516
0.004769
# 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing...
for the specific language governing permissions and # limitations under the License. """Libraries of Keras metrics.""" import tensorflow as tf def _apply_mask(y_true, sample_weight, masked_tokens, dtype): if sample_weight is None: sample_weight = tf.ones_like(y_true, dtype)
else: sample_weight = tf.cast(sample_weight, dtype) for token in masked_tokens: mask = tf.cast(tf.not_equal(y_true, token), dtype) sample_weight = sample_weight * mask return sample_weight class NumTokensCounter(tf.keras.metrics.Sum): """A `tf.keras.metrics.Metric` that counts tokens seen after m...
dsaldana/roomba_sensor_network
roomba_sensor/src/roomba_sensor/util/geo.py
Python
gpl-3.0
268
0.003731
from math import sqrt def euclidean_distance(p1, p2): """ Compu
te euclidean distance for two points :param p1: :param p2: :return: """ dx, dy = p2[0] - p1[0], p2[1] - p1[1] # Magnitude. Coulomb law.
return sqrt(dx ** 2 + dy ** 2)
aleju/ImageAugmenter
test/augmentables/test_bbs.py
Python
mit
85,736
0.000105
from __future__ import print_function, division, absolute_import import warnings import sys # unittest only added in 3.4 self.subTest() if sys.version_info[0] < 3 or sys.version_info[1] < 4: import unittest2 as unittest else: import unittest # unittest.mock is not available in 2.7 (though unittest2 might conta...
lf): bb = ia.BoundingBox(y1=10, x1=20, y2=30, x2=40) bb2 = self._func(bb, (10, 10), (20, 10)) assert np.isclose(bb2.y1, 10*2) assert np.isclose(bb2.x1, 20*1) assert np.iscl
ose(bb2.y2, 30*2) assert np.isclose(bb2.x2, 40*1) def test_inplaceness(self): bb = ia.BoundingBox(y1=10, x1=20, y2=30, x2=40) bb2 = self._func(bb, (10, 10), (10, 10)) if self._is_inplace: assert bb2 is bb else: assert bb2 is not bb class TestBound...
vinodchitrali/pbspro
test/fw/ptl/lib/pbs_testlib.py
Python
agpl-3.0
502,834
0.00042
# coding: utf-8 # Copyright (C) 1994-2016 Altair Engineering, Inc. # For more information, contact Altair at www.altair.com. # # This file is part of the PBS Professional ("PBS Pro") software. # # Open Source License Information: # # PBS Pro is free software. You can redistribute it and/or modify it under the # terms ...
'PTL_RSH_CMD': 'ssh', 'PTL_CP_CMD': 'scp -p', 'PTL_EXPECT_MAX_ATTEMPTS': 60, 'PTL_EXPECT_INTERVAL': 0.5, 'PTL_UPDATE_ATTRIBUTES': True, } self
.handlers = { 'PTL_SUDO_CMD': DshUtils.set_sudo_cmd, 'PTL_RSH_CMD': DshUtils.set_rsh_cmd, 'PTL_CP_CMD': DshUtils.set_copy_cmd, 'PTL_EXPECT_MAX_ATTEMPTS': Server.set_expect_max_attempts, 'PTL_EXPECT_INTERVAL': Server.set_expect_interval, 'PTL_UPDATE...
mrquim/mrquimrepo
script.module.nanscrapers/lib/nanscrapers/scraperplugins/yesmovies.py
Python
gpl-2.0
5,703
0.01543
import re import requests import threading from ..common import clean_title,clean_search import xbmc from ..scraper import Scraper sources = [] class scrape_thread(threading.Thread): def __init__(self,m,match,qual): self.m = m self.match = match self.qual = qual threading.Thread.__i...
craper): domains = ['yesmovies.to'] name = "yesmovies" def __init__(self): self.base_link = 'https://yesmovies.to' self.search_link = '/search/' def scrape_episode(self, title, show_year, year, season, episode, imdb, tvdb, debrid = False): try: start_url = self.base...
itle.replace(' ','+')+'.html' html = requests.get(start_url).content match = re.compile('<div class="ml-item">.+?<a href="(.+?)".+?title="(.+?)"',re.DOTALL).findall(html) for url,name in match: if clean_title(title)+'season'+season == clean_title(name): ...
wujuguang/sqlalchemy
test/orm/test_query.py
Python
mit
183,302
0.000005
import contextlib import sqlalchemy as sa from sqlalchemy import and_ from sqlalchemy import between from sqlalchemy import bindparam from sqlalchemy import Boolean from sqlalchemy import cast from sqlalchemy import collate from sqlalchemy import column from sqlalchemy import desc from sqlalchemy import distinct from ...
"expr": user_alias, "entity": user_alias, }, ],
), ( sess.query(user_alias.id), [ { "name": "id", "type": users.c.id.type, "aliased": True, "expr": user_alias.id, "entity": ...
HackingHabits/PersonalPasswordManager
packages/Flask/examples/minitwit/minitwit.py
Python
mit
8,424
0.00095
# -*- coding: utf-8 -*- """ MiniTwit ~~~~~~~~ A microblogging application written with Flask and sqlite3. :copyright: (c) 2010 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ from __future__ import with_statement import time from sqlite3 import dbapi2 as sqlite3 from hashlib im...
[session['user_id'], whom_id]) g.db.commit() flash('You are no longer following "%s"' % username) return redirect(url_for('user_timeline', username=username)) @app.route('/add_message', methods=['POST']) def add_message(): """Registers a new message for the user.""" if 'user_id' not in...
lues (?, ?, ?)''', (session['user_id'], request.form['text'], int(time.time()))) g.db.commit() flash('Your message was recorded') return redirect(url_for('timeline')) @app.route('/login', methods=['GET', 'POST']) def login(): """Logs the user in.""" if g.u...
htem/CATMAID
django/applications/catmaid/control/common.py
Python
agpl-3.0
8,243
0.002669
import string import random import json from collections import defaultdict from django.http import HttpResponse from django.shortcuts import render_to_response from django.template.context import RequestContext from catmaid.fields import Double3D from catmaid.models import Log, NeuronSearch, CELL_BODY_CHOICES, \ ...
nloop.com/blog/2008/may/10/getting-requestcontext-your-templates/ # Required because we need a RequestContext, not just a Context - the # former looks at TEMPLATE_CONTEXT_PROCESSORS, while the latter doesn't. def my_render_to_response(req, *args, **kwargs): kwargs['context_instance'] = RequestContext(req) retu...
message. This is a helper method to return such a structure: """ return HttpResponse(json.dumps({'error': message}), content_type='text/json') def order_neurons(neurons, order_by=None): column, reverse = 'name', False if order_by and (order_by in SORT_ORDERS_DICT): ...
hicknhack-software/buildbot-inplace-config
buildbot_inplace/config.py
Python
apache-2.0
5,400
0.002222
""" Buildbot inplace config (C) Copyright 2015 HicknHack Software GmbH The original code can be found at: https://github.com/hicknhack-software/buildbot-inplace-config 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...
project): return [ _project_profile_trigger_name(project.name, profile) for profile in project.inplace.profiles if self.project_profile_worker_names(profile)] def _pr
oject_profile_trigger_name(project_name, profile): return "_".join([project_name, profile.platform, profile.name, "Trigger"])
theoneandonly-vector/LaZagne
Windows/src/LaZagne/config/constant.py
Python
lgpl-3.0
416
0.057692
class constant(): folder_name = 'results' MAX_HELP_POSITION = 27 CURRENT_VERSION = '0.9.1'
output = None file_logger = None
# jitsi options jitsi_masterpass = None # mozilla options manually = None path = None bruteforce = None specific_path = None mozilla_software = '' # ie options ie_historic = None # total password found nbPasswordFound = 0 passwordFound = []
antoinecarme/sklearn2sql_heroku
tests/regression/freidman1/ws_freidman1_SVR_rbf_db2_code_gen.py
Python
bsd-3-clause
121
0.016529
from sklearn2sql_
heroku.tests.regression import generic as reg_gen
reg_gen.test_model("SVR_rbf" , "freidman1" , "db2")
Perlmint/Yuzuki
resource/util.py
Python
mit
66
0.015152
# -*- codin
g: utf-8 -*- from helper.resource import Yuzuki
Resource
DineshRaghu/dstc6-track1
src/data_utils.py
Python
gpl-3.0
14,089
0.013273
from __future__ import absolute_import import os import re import numpy as np import tensorflow as tf stop_words=set(["a","an","the"]) def load_candidates(data_dir, task_id): assert task_id > 0 and task_id < 6 candidates=[] candidates_f=None candid_dic={} #candidates_f='candidates.txt' candid...
nd((context[:],u[:],candid_dic[' '.join(r)])) data.append((context[:],u[:],a,dialog_id)) u.append('$u') u.append('#'+str(n
id)) r.append('$r') r.append('#'+str(nid)) context.append(u) context.append(r) else: r=tokenize(line) r.append('$r') r.append('#'+str(nid)) context.append(r) else: ...
joakim-hove/ert
tests/utils.py
Python
gpl-3.0
582
0
from pathlib import Path def source_dir(): src
= Path("@CMAKE_CURRENT_SOURCE_DIR@/../..") if src.is_dir(): return src.relative_to(Path.cwd()) # If the file was not correctly configured by cmake, look for the source # folder, assuming the build folder is inside the source folder. current_path = Path(__file__) while current_path != Path("...
nt_path current_path = current_path.parent raise RuntimeError("Cannot find the source folder") SOURCE_DIR = source_dir()
yausern/stlab
devices/TritonDaemon/TritonDaemon.py
Python
gpl-3.0
4,577
0.007428
"""Triton Daemon - Communication server for Oxford Triton system The Triton fridge already has communication capacity to directly control and read both the temperatures and other elements of the fridge (pressure sensors, valves, compressor, ...). However, the Triton logging uses binary format files that can only be o...
w') ff.write('#' + ', '.join(varline)+'\n') ''' logfolder = input('Enter BF log folder location (default "{}"):\n'.format(LOGFOLDER)) if logfolder == '': logfolder = LOGFOLDER tritonaddr = input('Enter address of Triton instrument (default "{}"):\n'.format(TRITONADDR)) if trit...
andler, args=(commandq,tritonaddr)) myhandler.daemon = True myhandler.start() loggerthread = Thread(target=logger, args=(commandq,logfolder)) loggerthread.start() # create an INET, STREAMing socket serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # bind the socket to a publ...
themadinventor/esptool
espefuse.py
Python
gpl-2.0
42,922
0.004497
#!/usr/bin/env python # ESP32 efuse get/set utility # https://github.com/themadinventor/esptool # # Copyright (C) 2016 Espressif Systems (Shanghai) PTE LTD # # 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 # ...
, None, "int", "Efuse read disablemask"), ('FLASH_CRYPT_CNT', "security", 0, 0, 0x07F00000, 2, None, "bitcount", "Flash encryption mode counter"), ('MAC', "identity", 0, 1, 0xFFFFFFFF, 3, None, "mac", "Factory MAC Address"), ('XPD_SDIO_FORCE', "config", 0, 4, 1 << 16, 5, ...
XPD_SDIO_REG', "config", 0, 4, 1 << 14, 5, None, "flag", "If XPD_SDIO_FORCE, enable VDD_SDIO reg on reset"), ('XPD_SDIO_TIEH', "config", 0, 4, 1 << 15, 5, None, "flag", "If XPD_SDIO_FORCE & XPD_SDIO_REG, 1=3.3V 0=1.8V"), ('CLK8M_FREQ', "config", 0, 4, 0xFF, None, None,...
mistermatti/plugz
plugz/plugz.py
Python
bsd-3-clause
373
0.002681
import abc class PluginTypeBase(object): """ Baseclass for plugin types. This needs to be derived from in order for plugin types to be accepted by p
lugz.
""" __metaclass__ = abc.ABCMeta plugintype = None @staticmethod def is_valid_file(file): """ Accept or reject files as valid plugins. """ return file.endswith('.py')
arg-hya/taxiCab
Plots/TrajectoryPlot/TrajectoryPlot.py
Python
gpl-3.0
1,224
0.013072
import pycrs import mpl_toolkits.basemap.pyproj as pyproj # Import the pyproj module import shapefile as shp import matplotlib.pyplot as plt shpFilePath = r"taxi_zones\taxi_zones" sf = shp.Reader(shpFilePath) records = sf.records() plt.figure() for shape in sf.shapeRecords(): x = [i[0] for i in shape...
oat(strings[1]) x2,y2 = pyproj.transform(wgs84,isn2004 ,co1,co2) lat.append(x2) lon.append(y2) # if i == 14450: # break if i == 1169120: break x1 = lat y1 = lon plt.plot(x1, y1, 'o', color='blue', markersize=7, markeredgewidth=0.0) pl...
w()
JiscPER/jper
service/dao.py
Python
apache-2.0
3,957
0.006318
""" This module contains all the Data Access Objects for models which are persisted to Elasticsearch at some point in their lifecycle. Each DAO is an extension of the octopus ESDAO utility class which provides all of the ES-level heavy lifting, so these DAOs mostly just provide information on where to persist the data...
aximum number to return (defaults to 10) """ self.notification_id = notification_id self.size = size def query(self): """ generate the query as a python dictionary object :return: a python dictionary containing the ES query, ready for JSON serialisation """ ...
"query" : { "term" : {"notification.exact" : self.notification_id} }, "size" : self.size } class RetrievalRecordDAO(dao.ESDAO): """ DAO for RetrievalRecord """ __type__ = "retrieval" """ The index type to use to store these objects """ class Ac...
DMIAlumni/pydrone-game
pydrone/utils/matrix_generator.py
Python
bsd-2-clause
1,291
0.001549
import math import fpformat import os from pydrone.utils.data_structures import Graph def world_generator(size, x_end, y_end, knowledge): # Controllo se si richiede un mondo con il knowledge degli stati o meno if knowledge: world = Graph(x_end, y_end) for i in range(size): for j i...
matrix = [[0 for i in range(size)] for j in range(size)] for i in range(size): for j in range(size): matrix[i][j] = float(fpformat.fix(math.sqrt(math.fabs(pow((x_end - i), 2) + pow((y_end - j), 2))), 3)) matrix[x_end][y_end] = -1 return matrix def matrix_genera...
e)] return matrix def print_matrix(matrix): os.system("clear") size = len(matrix[0]) for j in range(size): for i in range(size): value = matrix[i][j] if value > 0: print "", "*", else: print "", "-", print
metjush/decision_tree
setup.py
Python
mit
734
0.042234
from setuptools import setup setup(name='decision_tree', version='0.04', description='Practice implementation of a classification decision tree', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python
:: 2.7', 'Topic :: Scientific/Engineering :: Artificial Intelligence', ], keywords='classification decision tree machine learning random forest', url='https://github.com/metjush/decision_tree', author='metjush', author_email='metjush@gmail.com', license='MIT', packages=['decision_tre...
uires=[ 'numpy', 'sklearn' ], include_package_data=True, zip_safe=False)
lehinevych/cfme_tests
cfme/tests/configure/test_docs.py
Python
gpl-2.0
5,548
0.001802
# -*- coding: utf-8 -*- import pytest import re import requests try: # Faster, C-ext from cStringIO import StringIO except ImportErro
r: # Slower, pure python from StringIO import StringIO from pdfminer.converter import TextConverter from pdfminer.layout import LAParams from pdfminer.pdfpage import PDFPage from pdfminer.pdfinterp import PDFPageInterpreter, PDFResourceManager from cfme.configure.about import product_assistance as about from ...
= StringIO() manager = PDFResourceManager() laparams = LAParams(all_texts=True, detect_vertical=True) converter = TextConverter(manager, output, laparams=laparams) interpreter = PDFPageInterpreter(manager, converter) for page in PDFPage.get_pages(file_obj, page_nums): interpreter.process_pa...
congrieb/yikBot
start.py
Python
mit
469
0.004264
import pyak import yikbot import time # Latitude and Longitude of location whe
re bot should
be localized yLocation = pyak.Location("42.270340", "-83.742224") yb = yikbot.YikBot("yikBot", yLocation) print "DEBUG: Registered yikBot with handle %s and id %s" % (yb.handle, yb.id) print "DEBUG: Going to sleep, new yakkers must wait ~90 seconds before they can act" time.sleep(90) print "DEBUG: yikBot instance 90...
viswimmer1/PythonGenerator
data/python_files/29179833/tests.py
Python
gpl-2.0
3,436
0.009604
import unittest import warnings import datetime from django.core.urlresolvers import reverse from django.test import TestCase from incuna.utils import find from articles.models import Article class ArticleAccessTests(TestCase): fixtures = ['articles_data.json',] def test_article_index(self): response ...
_date', Article._meta.local_fields)
) \ and bool(find(lambda f: f.name == 'publication_end_date', Article._meta.local_fields)): self.skip = False else: warnings.warn("Skipping datepublisher tests. Extension not registered") self.skip = True def test_publication_date(self): if self.skip:...
graalvm/mx
mx.py
Python
gpl-2.0
772,837
0.003661
# # ---------------------------------------------------------------------------------------------------- # # Copyright (c) 2007, 2021, Oracle and/or its affiliates. All rights reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # # This code is free software; you can redistribute it and/or modify ...
BILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License # version 2 for more details (a copy is included in the LICENSE file that # accompanied this code). # # You should have received a copy of the GNU General Public License version
# 2 along with this work; if not, write to the Free Software Foundation, # Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. # # Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA # or visit www.oracle.com if you need additional information or have any # questions. # # -----------------...
Shir0kamii/mongofollow
mongofollow.py
Python
mit
1,092
0
"""Tail any mongodb collection""" from time import sleep from bson import ObjectId __version__ = "1.1.0" def fetch(collection, filter, last_oid_generation_time=None): if last_oid_generation_time is not None: last_oid = ObjectId.from_da
tetime(last_oid_generation_time) filter.update({"_id": {"$gte": last_oid}}) return collection.find(filter) def filter_duplicates(cursor, ids): for doc in cursor: if doc["_id"] not in ids: yield doc def mongofollow(collection, filter=None, sleep_du
ration=0.1): if filter is None: filter = {} last_oid_generation_time = None last_oids = set() while True: cursor = fetch(collection, filter, last_oid_generation_time) for doc in filter_duplicates(cursor, last_oids): oid = doc["_id"] last_oid_generation_tim...
Healdb/altcointip
src/ctb/ctb_coin.py
Python
gpl-2.0
8,785
0.006602
""" This file is part of ALTcointip. ALTcointip 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. ALTcointip is distr...
]: raise Exception("CtbCoin::verify_user(): _user wrong type (%s) or empty (%s)", type(_user), _user) return str(_user.lower()) def verify_addr(self, _addr = None): """ Verify and return coin address """ if not _addr or not type(_addr) in [str, unicode]: ...
dr),_addr) return re.escape(str(_addr)) def verify_amount(self, _amount = None): """ Verify and return amount
xxxIsaacPeralxxx/anim-studio-tools
grenade/tests/unit/test_translators/test_sequence.py
Python
gpl-3.0
3,110
0.018328
# # Copyright 2010 Dr D Studios Pty Limited (ACN 127 184 954) (Dr. D Studios), its # affiliates and/or its licensors. # from ..helpers.translators import verify_translate from grenade.translators.sequence import SequenceTranslator from probe.fixtures.mock_shotgun import MockShotgun class TestSequenceTranslator(objec...
{'id':3, 'type':'Note'}, {'id':4, 'type':'Scene'}, {'id':5, 'type':'Shot'}, {'id':6, 'type':'Task'}] self.session = MockShotgun(schema=[], data=self.shotgun_data) self.translator = SequenceTranslator(...
"" pass def test_translate(self): """ Test that the translator converts the supplied test data as expected. .. versionadded:: v00_04_00 """ verify_translate(self.translator, 'project', {'id':1, 'type':'Project'}, 'hf2', 'mm4') verify_translate(se...
zadgroup/edx-platform
common/djangoapps/embargo/forms.py
Python
agpl-3.0
3,061
0.000327
""" Defines forms for providing validation of embargo admin details. """ from django import forms from django.utils.translation import ugettext as _ import ipaddr from xmodule.modulestore.django import modulestore from opaque_keys import InvalidKeyError from opaque_keys.edx.keys import CourseKey from embargo.models...
course_key = CourseKey.from_string(cleaned_id) except InvalidKeyError: raise forms.ValidationError(error_msg) if not modulestore().has_course(course_key): raise forms.ValidationError(error_msg) return course_key class IPFilterForm(forms.ModelForm)
: # pylint: disable=incomplete-protocol """Form validating entry of IP addresses""" class Meta: # pylint: disable=missing-docstring model = IPFilter def _is_valid_ip(self, address): """Whether or not address is a valid ipv4 address or ipv6 address""" try: # Is this an...
mrjmad/gnu_linux_mag_drf
hall_of_cards/cardsgame/migrations/0003_card_modified.py
Python
mit
465
0.002151
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('cardsgame', '000
2_card_mana_cost'), ] operations = [ migrations.AddField( model_name='card', name=
'modified', field=models.PositiveIntegerField(null=True, verbose_name='Modified'), preserve_default=True, ), ]
Buggaarde/youtube-dl
youtube_dl/extractor/yahoo.py
Python
unlicense
13,867
0.002323
# coding: utf-8 from __future__ import unicode_literals import itertools import json import re from .common import InfoExtractor, SearchInfoExtractor from ..compat import ( compat_urllib_parse, compat_urlparse, ) from ..utils import ( clean_html, unescapeHTML, ExtractorError, int_or_none, ...
ll-154609075.html', 'md5': '226a895aae7e21b0129e2a2006fe9690', 'info_dict': { 'id': 'e624c4bc-3389-34de-9d
fc-025f74943409', 'ext': 'mp4', 'title': '\'The Interview\' TV Spot: War', 'description': 'The Interview', 'duration': 30, } }, { 'url': 'http://news.yahoo.com/video/china-moses-crazy-blues-104538833.html', 'md5'...
junbochen/pylearn2
pylearn2/testing/datasets.py
Python
bsd-3-clause
2,822
0
""" Simple datasets to be used for unit tests. """ __authors__ = "Ian Goodfellow" __copyright__ = "Copyright 2010-2012, Universite de Montreal" __credits__ = ["Ian Goodfellow"] __license__ = "3-clause BSD" __maintainer__ = "LISA Lab" __email__ = "pylearn-dev@googlegroups" import numpy as np from theano.compat.six.move...
channels, axes, num_classes):
dims = {'b': num_examples, 'c': channels} for i, dim in enumerate(shape): dims[i] = dim shape = [dims[axis] for axis in axes] X = rng.randn(*shape) idx = rng.randint(0, num_classes, (num_examples,)) Y = np.zeros((num_examples, num_classes)) for i in xrange(num_examples): ...
lemenkov/sippy
sippy/SipReplaces.py
Python
gpl-2.0
2,867
0.011161
# Copyright (c) 2005 Maxim Sobolev. All rights reserved. # Copyright (c) 2006-2007 Sippy Software, Inc. All rights reserved. # # This file is part of SIPPY, a free RFC3261 SIP stack and B2BUA. # # SIPPY is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as pub...
arams = None): SipGenericHF.__init__(self, body) if body != None: return self.parsed = True self.params = [] self.call_id = call_id self.from_tag = from_tag self.to_tag = to_tag self.early_only = early_only if params != None: ...
params = [] params = self.body.split(';') self.call_id = params.pop(0) for param in params: if param.startswith('from-tag='): self.from_tag = param[len('from-tag='):] elif param.startswith('to-tag='): self.to_tag = param[len('to-tag='):] ...
nathanielvarona/airflow
airflow/contrib/sensors/sagemaker_tuning_sensor.py
Python
apache-2.0
1,201
0.001665
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
ed. See the License for the # specific language governing permissions and limitations # under the License. """This module is deprecated. Please use :mod:`airflow.providers.amazon.aws.sensors.sagemaker_tuning`.""" import warnings # pylint: disable=unused-import from airflow.providers.amazon.aws.sensors.sagemaker_tuni...
viders.amazon.aws.sensors.sagemaker_tuning`.", DeprecationWarning, stacklevel=2, )
razor-x/scipy-data_fitting
examples/wave.py
Python
mit
1,252
0.002417
import os import sympy from example_helper import save_example_fit from scipy_data_fitting import Data, Model, Fit # # Example of a fit to a sine wave with error bars. # name = 'wave' # Load data from a csv file. data = Data(name) data.path = os.path.join('examples','data', 'wave.csv') data.genfromtxt_args['skip_he...
.expression = 'wave' fit.independent = {'symbol': 't', 'name': 'Time', 'units': 's'} fit.dependent = {'name': 'Voltage', 'prefix': 'kilo', 'units': 'kV'} fit.parameters = [ {'symbol': 'A', 'value': 0.3, 'prefix': 'kilo', 'units': 'kV'}, {'symbol': 'ω', 'guess': 1, '
units': 'Hz'}, {'symbol': 'δ', 'guess': 1}, ] fit.quantities = [ {'expression': 'frequency', 'name': 'Frequency', 'units': 'Hz'}, {'expression': 1 / model.expressions['frequency'] , 'name': 'Period', 'units': 's'}, ] # Save the fit to disk. save_example_fit(fit)
guillemborrell/gtable
tests/test_records.py
Python
bsd-3-clause
1,282
0.00078
from gtable import Table import numpy as np def test_records(): t = Table({'a': [1, 2, 3], 'b': np.array([4, 5, 6])}) t1 =
Table({'a': [1, 2, 3], 'd': np.array([4, 5, 6])}) t.stack(t1) records = [r for r in t.records()] assert records == [ {'a': 1, 'b': 4}, {'a': 2, 'b': 5}, {'a': 3, 'b': 6}, {'a': 1, 'd': 4}, {'a': 2, 'd': 5}, {'a': 3, 'd': 6}] records = [r for r in t.reco...
d': np.nan}, {'a': 3, 'b': 6, 'd': np.nan}, {'a': 1, 'b': np.nan, 'd': 4}, {'a': 2, 'b': np.nan, 'd': 5}, {'a': 3, 'b': np.nan, 'd': 6}] def test_first_record(): t = Table({'a': [1, 2, 3], 'b': np.array([4, 5, 6])}) t1 = Table({'a': [1, 2, 3], 'd': np.array([4, 5, 6])}) t.s...
unnikrishnankgs/va
venv/lib/python3.5/site-packages/tensorflow/contrib/distributions/python/ops/bijectors/affine_linear_operator.py
Python
bsd-2-clause
1,182
0.000846
# Copyright 2016 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 applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissi...
Operator bijector.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # go/tf-wildcard-import # pylint: disable=wildcard-import from tensorflow.contrib.distributions.python.ops.bijectors.affine_linear_operator_impl import * # pylint: enable=wildcard-import ...
botify-labs/moto
moto/iam/aws_managed_policies.py
Python
apache-2.0
495,649
0.000176
# Imported via `make aws_managed_policies` aws_managed_policies_data = """ { "AWSAccountActivityAccess": { "Arn": "arn:aws:iam::aws:policy/AWSAccountActivityAccess", "AttachmentCount": 0, "CreateDate": "2015-02-06T18:41:18+00:00", "DefaultVersionId": "v1", "Document": { ...
"Action": [ "SNS:Publish" ], "Effect": "Allow", "Resource": "arn:aws:sns:*:*:metrics-sns-topic-f
or-*" }, { "Action": [ "Discovery:*" ], "Effect": "Allow", "Resource": "*", "Sid": "Discovery" }, { "Action": [ ...
dr0pz0ne/sibble
lib/ansible/parsing/splitter.py
Python
gpl-3.0
10,657
0.002721
# (c) 2014 James Cammarata, <jcammarata@ansible.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any late...
eral Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # Make coding more python3-ish from __future__ import (absolute_
import, division, print_function) __metaclass__ = type import re import codecs from ansible.errors import AnsibleParserError from ansible.parsing.quoting import unquote # Decode escapes adapted from rspeer's answer here: # http://stackoverflow.com/questions/4020539/process-escape-sequences-in-a-string-in-python _HEX...
wohllab/milkyway_proteomics
galaxy_milkyway_files/tools/wohl-proteomics/MSGFcrux/percolator_output_modifier_fractionated.py
Python
mit
10,590
0.011143
#!/usr/bin/python import sys, copy, tarfile """ - Splits Percolator output into decoy and target files. - Extracts unique PSM/peptides/proteins out of a Percolator output file. - Merges Percolator output files Usage: python percolator_output_modifier.py command psm/peptides/proteins [score] infile outfile...
continue for feat in feattree[0]: # It's actually faster to loop through the feat's children, # but this is 2-line code and still readable. featscore = float(feat.xpath('xmlns:%s' % scores[score], namespaces=ns)[0].text) seq = fea...
try: # psm seqs are parsed here seq = seq[0].attrib['seq'] except Exception: ## caught when parsing peptide seqs (different format) seq = str(seq[0]) if seq not in filtered[filt_el]: filter...
onecloud/neutron
neutron/plugins/cisco/common/cisco_constants.py
Python
apache-2.0
2,838
0.000352
# Copyright 2011 Cisco Systems, Inc. All rights reserved. # # Licensed under the Apache
License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is...
ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # # @author: Sumit Naiksatam, Cisco Systems, Inc. # Attachment attributes INSTANCE_ID = 'instance_id' TENANT_ID = 'tenant_id' TENANT_NAME = 'tenant_name' HOST_NAME = 'host...
hasgeek/funnel
migrations/versions/e679554261b2_main_label_index.py
Python
agpl-3.0
452
0.004425
"""Main label index. Revision ID: e679554261b2 Revises: e2be4ab896d3 Create Date: 2019-05-09 18
:55:24.472216 """ # revision identifiers, used by Alembic. revision = 'e679554261b2' down_revision = 'e2be4ab896d3' from alembic import op def upgrade(): op.create_index( op.f('ix_label_main_label_id'), 'label', ['main_label_id'], unique=False ) def downgrade(): op.drop_index(op.f('ix_label_m...
'label')
luizdepra/sketch_n_hit
app/assets.py
Python
mit
984
0.003049
from flask.ext.assets import Bundle from . import wa js_libs = Bundle('js/libs/jquery.min.js', 'js/libs/bootstrap.min.js', 'js/libs/lodash.min.js', #filters='jsmin', output='js/libs.js')
js_board = Bundle('js/libs/drawingboard.min.js', #filters='jsmin', output='js/board.js') js_main = Bundle('js/main.js', #filters='jsmin', output='js/snh.js') css_main = Bundle('css/bootstrap.min.css', 'css/font-awesome.min.css', ...
output='css/snh.css') css_board = Bundle('css/drawingboard.min.css', filters='cssmin', output='css/board.css') wa.register('js_libs', js_libs) wa.register('js_board', js_board) wa.register('js_main', js_main) wa.register('css_main', css_main) wa.register('css_board', css...
fedallah/dsperf
pytest_2.py
Python
mit
1,084
0.057196
#!/usr/bin/env python3 import csv import sqlite3 # requires python3 # requires sqlite3 # sqldb = sqlite3.connect(':memory:') def main: while True: input_location = input("Please provide the pathname of the file you wish to extract data from. Enter a blank line when you are done.") if input_location = False: ...
csvread = csv.rader( csvfile, delimiter=',' quotechar='' ) class perfitem_group(inputfile): def __init__(self) def class perfitem(perfitem_group): def __init__(self) def mkdict class row(inputfile): def init(self): self = with open( inputfile.self.location, newline='' ) as csvfile: csvre...
ow allfiles = False while True: # while allfiles <> "":
jrichte43/ProjectEuler
Problem-0442/solutions.py
Python
gpl-3.0
936
0.00641
__problem_title__ = "Eleven-free integers" __problem_url___ = "http
s://projecteuler.net/problem=442" __problem_description__ = "An integer is called if its decimal expansion does not contain any " \ "substring representing a power of 11 except 1. For example, 2404 and " \ "13431 are eleven-f
ree, while 911 and 4121331 are not. Let E( ) be the " \ "th positive eleven-free integer. For example, E(3) = 3, E(200) = 213 " \ "and E(500 000) = 531563. Find E(10 )." import timeit class Solution(): @staticmethod def solution1(): pass @stat...
r-stein/sublime-text-caret-jump
caret_jump.py
Python
mit
2,134
0
import sublime import sublime_plugin OPTIONS_LAST_REGEX = "jump_caret_last_regex" class CaretJumpCommand(sublime_plugin.TextCommand): def run(self, edit, jump=True, jump_to=None, repeat_previous_jump=False): view = self.view def get_next_sels(user_input): new_sels = [] fo...
if jump and new_sels: view.sel().clear() view.sel().add_all(new_sels) def input_changed(user
_input): new_sels = get_next_sels(user_input) view.add_regions("caret_jump_preview", new_sels, "source, text", "dot", sublime.DRAW_OUTLINED) def input_canceled(): ...
dmitrystu/svd_editor
modules/tview.py
Python
apache-2.0
7,250
0.001517
import wx import svd import my class View(wx.Panel): def __init__(self, parent, data=None): wx.Panel.__init__(self, parent) self.data = {} self.tree = wx.TreeCtrl(self) self.tree.AddRoot('FROM_RUSSIA_WITH_LOVE') self.Bind(wx.EVT_SIZE, self.onResize) self.Bind(wx.EV...
data[p] = pi for r in p.registers: ri = tree.AppendItem(pi, r.name) tree.SetPyData(ri, r) self.data[r] = ri tree.UnselectAll() tree.Expand(root) tree.Selec
tItem(root) tree.Thaw() def AddItem(self, obj): pass def DelItem(self, obj): if obj == self.tree: item = self.tree.GetSelection() if item.IsOk(): data = self.tree.GetPyData(item) if isinstance(data, svd.device): ...
t0mk/ansible
lib/ansible/modules/network/nxos/nxos_vlan.py
Python
gpl-3.0
13,902
0.001511
#!/usr/bin/python # # 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 distribut...
s(): if param == 'mapped_vni' and value == 'default': command = 'no vn-segment' else: command = VLAN_ARGS.get(param).format(vlan.g
et(param)) if command: commands.append(command) commands.insert(0, 'vlan ' + vid) commands.append('exit') return commands def get_list_of_vlans(module): body = run_commands(module, ['show vlan | json']) vlan_list = [] vlan_table = body[0].get('TABLE_vlanbrief')['ROW_vlanb...
flavour/rgims_as_diff
private/templates/RGIMS/controllers.py
Python
mit
9,573
0.011804
# -*- coding: utf-8 -*- from os import path from gluon import current from gluon.html import * from s3 import s3_represent_facilities, s3_register_validation # ============================================================================= class index(): """ Custom Home Page """ def __call__(self): ...
#_disabled = "disabled", _id = "manage_facility_btn",
_class = "action-btn" ), _id = "manage_facility_box", _class = "menu_box fleft") s3.jquery_ready.append( '''$('#manage_facility_select').change(f...
utkbansal/kuma
vendor/packages/translate/convert/test_po2dtd.py
Python
mpl-2.0
22,788
0.001668
#!/usr/bin/env python # -*- coding: utf-8 -*- import warnings import pytest from translate.convert import dtd2po, po2dtd, test_convert from translate.misc import wStringIO from translate.storage import dtd, po class TestPO2DTD: def setup_method(self, method): warnings.resetwarnings() def teardown...
simpledtd = simpledtd_template % (label, accesskey) dtdfile = self.merge2dtd(simpledtd, simplepo) dtdfile.makeindex() assert dtd.unquotefromdtd(dtdfile.id_index["simple.%s" %
accesskey].definition) == "a" def test_ampersandfix(self): """tests that invalid ampersands are fixed in the dtd""" simplestring = '''#: simple.string\nmsgid "Simple String"\nmsgstr "Dimpled &Ring"\n''' dtdfile = self.po2dtd(simplestring) dtdsource = str(dtdfile) assert "Di...
efforia/django-shipping
shipping/providers/default.py
Python
lgpl-3.0
5,966
0.008213
#!/usr/bin/python # # This file is part of django-ship project. # # Copyright (C) 2011-2020 William Oliveira de Lagos <william.lagos@icloud.com> # # Shipping is free software: you can redistribute it and/or modify # it under the terms of the Lesser GNU General Public License as published by # the Free Software ...
s not None: user_postcode = form.cleaned_data['shipping_detail_postcode'] else: user_postcode = settings.STORE_POSTCODE user_postcode = form.cleaned_data['shipping_detail_postcode'] shippingservice = FreteFacilShippingService() cart = Cart.objects.from_request(request) delivery_value = 0.0 ...
if len(properties) > 0: props = properties[0] deliverable = shippingservice.create_deliverable(settings.STORE_POSTCODE, user_postcode, props.width,...
jmaidens/Codility
MaxCounters.py
Python
mit
951
0.005258
# Solution to exercise MaxCounters # http://www.codility.com/train/ def solution(N, A): counters
= [0 for _ in range(N)] last_max_counter = 0 current_max_counter = 0 # Iterate through A. At each step, the value of counter i is # last_max_counter or counters[i], whichever is greater for a in A: if a == N+1: last_max_counter = current_max_counter elif counter...
ter + 1 current_max_counter = max(current_max_counter, counters[a-1]) else: counters[a-1] += 1 current_max_counter = max(current_max_counter, counters[a-1]) # Make a pass through counters to update the ones that # have not changed since the last max_counter opperatio...
ctenix/pytheway
imooc_requests_urllib.py
Python
gpl-3.0
978
0.011579
#__*__coding:utf-8__*__ import urllib import urllib2 URL_IP = 'http://127.0.0.1:8000/ip' URL_GET = 'http://127.0.0.1:8000/get' def use_simple_urllib2(): response = urllib2.urlopen(URL_IP) print '>>>>Response Headers:' print response.info() print '>>>>Response Body:' print ''.join([line for line i...
print '>>>>Response Body:' print ''.join([line for line in response.readlines()]) if __name__== '__main
__': print '>>>Use simple urllib2:' use_simple_urllib2() print print '>>>Use params urllib2:' use_params_urllib2()
antoinecarme/sklearn2sql_heroku
tests/classification/FourClass_500/ws_FourClass_500_GaussianNB_sqlite_code_gen.py
Python
bsd-3-clause
139
0.014388
from sklearn2sql_heroku
.tests.classification import generic as class_gen class_gen.test_model("Gau
ssianNB" , "FourClass_500" , "sqlite")
Lenusik/python
fixture/contact.py
Python
gpl-2.0
2,909
0.003438
__author__ = 'Lenusik' from model.contact import Contact import re class ContactHelper: def __init__(self, app): self.app = app contact_cache = None def get_contact_list(self): if self.contact_cache is None: driver = self.app.driver self.app.open_home_page() ...
er.find_el
ement_by_name("work").get_attribute("value") mobilephone = driver.find_element_by_name("mobile").get_attribute("value") secondaryphone = driver.find_element_by_name("phone2").get_attribute("value") return Contact(firstname=firstname, lastname=lastname, id=id, homephone=hom...
asekretenko/yandex-tank
tests/Autostop_Test.py
Python
lgpl-2.1
3,041
0.007892
from yandextank.plugins.Aggregator import SecondAggregateData from yandextank.plugins.Autostop import AutostopPlugin from Tank_Test import TankTestCase import tempfile import unittest class AutostopTestCase(TankTestCase): def setUp(self): core = self.get_core() core.load_configs(['config/autostop....
foo.end_test(0) def test_run_false_trigger_bug(self): data = SecondAggregateData() data.overall.http_codes = {} self.foo.core.set_option(self.foo.SECTION, "autostop", "http (5xx, 100%, 1)") self.foo.configure() self.foo.prepare_test() self.foo.start...
o.aggregate_second(data) if self.foo.is_test_finished() >= 0: raise RuntimeError() self.foo.end_test(0) if __name__ == '__main__': unittest.main()
Kotaimen/stonemason
stonemason/service/tileserver/themes/views.py
Python
mit
1,132
0.000883
# -*- encoding: utf-8 -*- __author__ = 'ray' __date__ = '2/27/15' from flask import jsonify, abort from flask.views import MethodView from ..models import ThemeModel class ThemeView(MethodView): """ Theme View Retrieve description of a list of available themes. :param theme_model: A theme model that ...
. :type theme_model: :class:`~stonema
son.service.models.ThemeModel` """ def __init__(self, theme_model): assert isinstance(theme_model, ThemeModel) self._theme_model = theme_model def get(self, tag): """Return description of the theme. Raise :http:statuscode:`404` if not found. :param name: Name of a...
maxplanck-ie/HiCExplorer
hicexplorer/test/long_run/test_hicBuildMatrix.py
Python
gpl-2.0
9,095
0.002969
import warnings warnings.simplefilter(action="ignore", category=RuntimeWarning) warnings.simplefilter(action="ignore", category=PendingDeprecationWarning) from hicexplorer import hicBuildMatrix, hicInfo from hicmatrix import HiCMatrix as hm from tempfile import NamedTemporaryFile, mkdtemp import shutil import os import...
_R2_unsorted.bam" dpnii_file = ROOT + "DpnII.bed" def are_files_equal(file1, file2, delta=None): equal = True if delta: mismatches = 0 with open(file1) as textfile1, open
(file2) as textfile2: for x, y in zip(textfile1, textfile2): if x.startswith('File'): continue if x != y: if delta: mismatches += 1 if mismatches > delta: equal = False ...
sinotradition/meridian
meridian/tst/acupoints/test_zuwuli233.py
Python
apache-2.0
299
0.006689
#!/usr/bin/python #coding=utf-8 ''' @author: sheng @license: ''' import unittest from meridian.acupoints import zuwuli233 class TestZuwuli233Functions(unittest.TestCase): def setUp(self): pass def test_xxx(sel
f): pass if __name__ == '__
main__': unittest.main()
willingc/oh-mainline
vendor/packages/scrapy/scrapy/tests/test_cmdline/__init__.py
Python
agpl-3.0
1,166
0.008576
import sys import os from subprocess import Popen, PIPE import unittest class CmdlineTest(unittest.TestCase): def setUp(self): self.env = os.environ.copy() if 'PYTHONPATH' in os.environ: self.env['PYTHONPATH'] = os.environ['PYTHONPATH'] self.env['SCRAPY_SETTINGS_MODULE'] = 'scr...
ted') def test_override_settings_using_set_arg(self): self.assertEqual(self._execute('settings', '--get', 'TEST1', '-s',
'TEST1=override'), \ 'override + loaded + started') def test_override_settings_using_envvar(self): self.env['SCRAPY_TEST1'] = 'override' self.assertEqual(self._execute('settings', '--get', 'TEST1'), \ 'override + loaded + started')
openstack/octavia
octavia/tests/unit/common/test_base_taskflow.py
Python
apache-2.0
5,974
0
# Copyright 2015 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 applicable law...
mock.MagicMock() job1.wait.side_effect = [False, True] job2 = mock.MagicMock() job2.wait.side_effect = [False, True] job3 = mock.MagicMock() job3.wait.return_value = True job_board = mock.MagicMock() job_board.iterjobs.side_effect = [ [job1, j
ob2, job3], [job1, job2] ] self.service_controller._wait_for_job(job_board) job1.extend_expiry.assert_called_once() job2.extend_expiry.assert_called_once() job3.extend_expiry.assert_not_called() @mock.patch('octavia.common.base_taskflow.RedisDynamicLoggingConduc...
hiidef/hiispider
legacy/evaluateboolean.py
Python
mit
650
0.004615
from unicodeconverter import convertToUnicode def evaluateBoolean(b): if isinstance(b, bool): return b if isinstance(b, str): b = convertToUnicode(b) if isinstance(b, unicode): if b.lower() == u"false": return False elif b.l
ower() == u"true": return True elif b.lower() == u"no": return False elif b.lower() == u"yes": return True else: try: return bool(int(b)) except:
return True else: try: return bool(int(b)) except: return True
CptSpaceToaster/memegen
memegen/stores/image.py
Python
mit
275
0
import os
class ImageStore: def __init__(self, root): self.root = root def exists(self, image): image.root = self.root return os.path.isfile(image.path) def create(self, image): image.root = self.root
image.generate()
unioslo/cerebrum
Cerebrum/modules/no/hia/OrgLDIF.py
Python
gpl-2.0
4,715
0
# -*- coding: utf-8 -*- # # Copyright 2004-2020 University of Oslo, Norway # # This file is part of Cerebrum. # # Cerebrum 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 # ...
source_system=source_system,
convert=self.attr2syntax[attr][0], verify=self.attr2syntax[attr][1], normalize=self.attr2syntax[attr][2])) for attr, source_system, contact_type in ( ('telephoneNumber', manual, self.const.contact_phone), ...
smmribeiro/intellij-community
plugins/hg4idea/testData/bin/mercurial/thirdparty/selectors2.py
Python
apache-2.0
27,478
0.000619
""" Back-ported, durable, and portable selectors """ # MIT License # # Copyright (c) 2017 Seth Michael Larson # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including...
e rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: #
# The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE ...
tombs/Water-Billing-System
waterbilling/core/models.py
Python
agpl-3.0
53,833
0.009529
# -*- coding: utf-8 -*- from __future__ import unicode_literals from datetime import timedelta from decimal import Decimal from django.db import models from django.db import transaction from django.utils.timezone import now from django.db.models import Sum, Max, F from audit_log.models.managers import AuditLog cla...
y
def bills(self): return self.bill_set.all() @property def notices(self): return self.notice_set.all() @property def meterreads(self): return self.meterread_set.all() @property def adjustments(self): return self.adjustment_set.all() @property def meters...
kronenthaler/mod-pbxproj
pbxproj/pbxsections/XCConfigurationList.py
Python
mit
821
0.002436
from pbxproj import PBXGenericObject class XCConfigurationList(PBXGenericObject): def _get_comment(self): info = self._get_section() return f'Build configuration list for {info[0]} "{info[1]}"' def _get_section(self): objects = self.ge
t_parent() target_id = self.get_id() for obj in objects.get_objects_in_section('PBXNativeTarget', 'PBXAggregateTarget'): if target_id in obj.buildConfigurationList: return obj.isa, obj.name projects = filter(la
mbda o: target_id in o.buildConfigurationList, objects.get_objects_in_section('PBXProject')) project = projects.__next__() target = objects[project.targets[0]] name = target.name if hasattr(target, 'name') else target.productName return project.isa, name
sander76/home-assistant
homeassistant/components/climacell/__init__.py
Python
apache-2.0
11,985
0.000834
"""The ClimaCell integration.""" from __future__ import annotations from datetime import timedelta import logging from math import ceil from typing import Any from pyclimacell import ClimaCellV3, ClimaCellV4 from pyclimacell.const import CURRENT, DAILY, FORECASTS, HOURLY, NOWCAST from pyclimacell.exceptions import ( ...
clientsession from homeassistant.helpers.entity import DeviceInfo from homeassistant.helpers.update_coordinat
or import ( CoordinatorEntity, DataUpdateCoordinator, UpdateFailed, ) from .const import ( ATTRIBUTION, CC_ATTR_CLOUD_COVER, CC_ATTR_CONDITION, CC_ATTR_HUMIDITY, CC_ATTR_OZONE, CC_ATTR_PRECIPITATION, CC_ATTR_PRECIPITATION_PROBABILITY, CC_ATTR_PRECIPITATION_TYPE, CC_ATTR_...
xingyepei/edx-platform
common/test/acceptance/pages/studio/settings_advanced.py
Python
agpl-3.0
7,464
0.001742
""" Course Advanced Settings page """ from bok_choy.promise import EmptyPromise from .course_page import CoursePage from .utils import press_the_notification_button, type_in_codemirror, get_codemirror_value KEY_CSS = '.key h3.title' UNDO_BUTTON_SELECTOR = ".action-item .action-undo" MANUAL_BUTTON_SELECTOR = ".action...
'no_grade', 'display_coursenumber', 'display_organization', 'catalog_visibility', 'chrome', 'days_early_for_beta', 'default_tab'
, 'disable_progress_graph', 'discussion_blackouts', 'discussion_sort_alpha', 'discussion_topics', 'due', 'due_date_display_format', 'edxnotes', 'use_latex_compiler', 'video_speed_optimizations', 'enro...
alex-Symbroson/BotScript
BotScript/res/calibrate.py
Python
mit
4,128
0.004845
from RaspiBot import Methods, sleep # represents btn color and action on press in a state class Btn: def __init__(self, red, green, nextid = None): self.red = red self.green = green self.next = nextid # represents one menu state with message, button and own action class State: de...
ate[id] = State(*StateArgs) self.states += 1 return self.states # run machine def run(self, id): while id != None: id = self.state[id].run() # navigate through menu def select(state): while True: if Methods.isBtnPressed(1): Methods.waitForBtnRelease(1) ...
].next if Methods.isBtnPressed(3): Methods.waitForBtnRelease(3) return state.btns[2].next sleep(0.1) # measure sharp values def cal_sharps(state): i = 0 sharp = 1 while True: # measure left sharp if Methods.isBtnPressed(1): sharp = 1 ...
wenxiaomao1023/wenxiaomao
article/migrations/0002_auto_20160921_1518.py
Python
mit
587
0
# -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-09-21 15:18 from __f
uture__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('article', '0001_initial'), ] operations = [ migrations.AlterField( model_name='article', name='content', field=models.Te...
sc', field=models.TextField(blank=True), ), ]
nikkitricky/nikbuzz
score.py
Python
mit
5,706
0.006484
""" @author: Nikhith !! """ from pycricbuzz import Cricbuzz import json import sys """ Writing a CLI for Live score """ try: cric_obj = Cricbuzz() # cric_obj contains object instance of Cricbuzz Class matches = cric_obj.matches() except: print "Connection dobhindhi bey!" sys.exit(0) ...
print "Batting:" try: print " " + str(batobj['batsman'][0]['name']) + " : " + str(batobj['batsman'][0]['runs']) + " (" + str(batobj['batsman'][0]['balls']) + ")" print " " + str(batobj['batsman'][1]['name']) + " : " +
str(batobj['batsman'][1]['runs']) + " (" + str(batobj['batsman'][1]['balls']) + ")" except: print "Wicket!!!!" print "Bowling:" print " " + str(bowlobj['bowler'][0]['name']) + " : " + str(bowlobj['bowler'][0]['runs']) + " /" + str(bowlobj['bowler'][0]['wickets']) + " (" + str(...
cliffton/localsecrets
offers/views.py
Python
mit
3,993
0.001002
# Create your views here. from rest_framework import viewsets from offers.models import Offer, OfferHistory, OfferReview from offers.serializers import ( OfferSerializer, OfferHistorySerializer, OfferReviewSerializer ) from shops.serializers import ShopSerializer from rest_framework import status from rest_...
= OfferSerializer def list(s
elf, request): params = request.query_params offers = [] if params: ulat = float(params['lat']) ulon = float(params['lon']) for offer in Offer.objects.select_related('shop').all(): olat = float(offer.shop.latitude) olon = float(...
skomendera/PyMyTools
providers/value.py
Python
mit
359
0
def represe
nts_int(value): try: int(value) return True except ValueError: return False def bytes_to_gib(byte_value, round_digits=2): return round(byte_value / 1024 / 1024 / float(1024), round_digits) def count_to_millions(count_value, round_digits=3): return round(count_value / fl...
its)
betterlife/psi
psi/app/models/__init__.py
Python
mit
875
0.001143
from .image import Image from .product_category import ProductCategory from .supplier import Supplier, PaymentMethod from .product import Product from .product import ProductImage from .enum_values import EnumValues from .re
lated_values import RelatedValues from .customer import Customer from .expense import Expense from .incoming import Incoming from
.shipping import Shipping, ShippingLine from .receiving import Receiving, ReceivingLine from .inventory_transaction import InventoryTransaction, InventoryTransactionLine from .purchase_order import PurchaseOrder, PurchaseOrderLine from .sales_order import SalesOrder, SalesOrderLine from .user import User from .role imp...
deepmind/dm_control
dm_control/locomotion/arenas/bowl.py
Python
apache-2.0
4,927
0.008119
# Copyright 2020 The dm_control Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
hfield).adr physics.model.hfield_data[start_idx:start_idx+res**2] = terrain.ravel() # If we have a rendering context, we need to re-upload the modified # heightfield data. if physics.contexts: with physics.contexts.gl.make_current() as ctx:
ctx.call(mjlib.mjr_uploadHField, physics.model.ptr, physics.contexts.mujoco.ptr, physics.bind(self._hfield).element_id) @property def ground_geoms(self): return (self._terrain_geom, self._ground_geom)
Danielhiversen/home-assistant
tests/components/template/test_binary_sensor.py
Python
apache-2.0
27,103
0.001107
"""The tests for the Template Binary sensor platform.""" from datetime import timedelta import logging from unittest.mock import patch import pytest from homeassistant import setup from homeassistant.components import binary_sensor from homeassistant.const import ( ATTR_DEVICE_CLASS, EVENT_HOMEASSISTANT_START...
ry_sensor": { "platform": "template", "sensors": { "test_template_sensor": { "value_template": "{{ states.sensor.xyz.state }}", "entity_picture_template": "{% if " "states.binary_sensor.test_state...
, }, ], ) async def test_entity_picture_template(hass, start_ha): """Test entity_picture template.""" state = hass.states.get("binary_sensor.test_template_sensor") assert state.attributes.get("entity_picture") == "" hass.states.async_set("binary_sensor.test_state", "Works") await hass.a...
rokuz/omim
kml/pykmlib/bindings_test.py
Python
apache-2.0
4,094
0.004272
import unittest import datetime import pykmlib class PyKmlibAdsTest(unittest.TestCase): def test_smoke(self): classificator_file_str = '' with open('./data/classificator.txt', 'r') as classificator_file: classificator_file_str = classificator_file.read() types_file_str = '' ...
['12345', '54321', '98765']) track.properties.set_dict({'tr_property1':'value1', 'tr_property2':'value2'}) file_data = pykmlib.FileData() f
ile_data.server_id = 'AAAA-BBBB-CCCC-DDDD' file_data.category = category file_data.bookmarks.append(bookmark) file_data.tracks.append(track) s = pykmlib.export_kml(file_data) imported_file_data = pykmlib.import_kml(s) self.assertEqual(file_data, imported_file_data) if ...
vipmunot/HackerRank
Algorithms/Viral Advertising.py
Python
mit
81
0.012346
m = [2] for i in range(int(input())-1): m.ap
pend(in
t(3*m[i]/2)) print(sum(m))
lizardsystem/lizard-fewsapi
lizard_fewsapi/collect.py
Python
gpl-3.0
1,482
0
# (c) Nelen & Schuurmans. GPL licensed, see LICENSE.rst. # -*- coding: utf-8 -*- from __future__ import unicode_literals from __future__ import print_function import logging import requests logger = logging.getLogger(__name__) def collect_filters(url): """Return filters from FEWS, cleaned and ready for storing...
url) # TODO return from_fews def _download(url): r = requests.get(url) r.raise_for_status() # Only raises an error when not succesful. return r.json() def _process_filter_dict(filter_dict): # {'filter': {name, childfilters, etc} content = filter_dict['filter'] name = content['name']...
t['description'] if name == description: # Description is only interesting if it is different from the name. # Often it is the same, so we've got to filter it out. description = '' children = [_process_filter_dict(child_filter_dict) for child_filter_dict in content.get('c...
epmatsw/FootballBot
fxns/8ball.py
Python
cc0-1.0
986
0.037525
if dest.lower()=='footballbot': dest=origin par=' '.join(params).lower() if len(par) < 10 and par.count('is') == 0 and par.count('?') == 0 and par.count('will') == 0 and par.count('should') == 0 and par.count('could') == 0 and par.count('do') == 0 and par.count('has') == 0 and par.count('does') == 0 and par.count('when...
who') == 0: db['msgqueue'].append([origin+': That\'s not a question!',dest]) else: if par.count(' or ') == 1: opt1=par[par.find(' or ')+4:].strip() if opt1.count(' ') != 0: opt1=opt1[:opt1.find(' ')].strip()
opt2=par[::-1] opt2=opt2[opt2.find(' ro ')+4:].strip() if opt2.count(' ') != 0: opt2=opt2[:opt2.find(' ')].strip() opt1=opt1.replace('?','') opt2=opt2.replace('?','') opt2=opt2[::-1] db['msgqueue'].append([origin+': '+random.choice(db['language']['verbs'])+'ing '+random.choice([opt1,opt2]),dest]) else: db...
junmin-zhu/chromium-rivertrail
tools/chrome_remote_control/chrome_remote_control/page_runner.py
Python
bsd-3-clause
6,385
0.01112
# 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. import logging import os import time import traceback import urlparse import random import csv from chrome_remote_control import page_test from chrome_re...
t_shuffle_order_file.') def Run(self, options, possible_browser, test, results): archive_path = os.path.abspath(os.path.join(self.page_set.base_dir, self.page_set.archive_path)) if options.wpr_mode == wpr_modes.WPR_OFF: if os.path.isfile(archive_path): ...
e: possible_browser.options.wpr_mode = wpr_modes.WPR_OFF logging.warning(""" The page set archive %s does not exist, benchmarking against live sites! Results won't be repeatable or comparable. To fix this, either add svn-internal to your .gclient using http://goto/read-src-internal, or create a new arc...
start-jsk/jsk_apc
demos/instance_occlsegm/tests/image_tests/test_resize.py
Python
bsd-3-clause
1,334
0
import cv2 import skimage.data import instance_occlsegm_lib def test_resize(): for interpolation in [cv2.INTER_NEAREST, cv2.INTER_LINEAR]: _test_resize(interpolation) def _test_resize(interpolation): img = skimage.data.astronaut() H_dst, W_dst = 480, 640 ret = instance_occlsegm_lib.image.r...
mg, height=H_dst, width=W_dst, interpolation=interpolation) assert ret.dtype == img.dtype assert r
et.shape == (H_dst, W_dst, 3) ret = instance_occlsegm_lib.image.resize( img, height=H_dst, interpolation=interpolation) hw_ratio = 1. * img.shape[1] / img.shape[0] W_expected = int(round(1 / hw_ratio * H_dst)) assert ret.dtype == img.dtype assert ret.shape == (H_dst, W_expected, 3) sca...
denz/swarm-crawler
swarm_crawler/text.py
Python
bsd-3-clause
2,172
0.005525
BREADABILITY_AVAILABLE = True try: from breadability.readable import Article, prep_article, check_siblings except ImportError: BREADABILITY_AVAILABLE = False Article = object from operator import attrgetter from werkzeug.utils import cached_property import re from lxml.etree import tounicode, tostring ...
e ImportError('breadability is not available') super(PageText, self).__init__(*args, **kwargs) def __unicode__(self): return self.winner() def stripped(self, text): for replacement, whitespace in self.WHITESPACE.items():
text = re.sub(whitespace, replacement, text) return text def slice(self, before=1, reverse=True): if self.candidates: # cleanup by removing the should_drop we spotted. [n.drop_tree() for n in self._should_drop if n.getparent() is not None] ...
gorgias/apispec
tests/test_core.py
Python
mit
13,849
0.000939
# -*- coding: utf-8 -*- import pytest import mock from apispec import APISpec, Path from apispec.exceptions import PluginError, APISpecError description = 'This is a sample Petstore server. You can find out more ' 'about Swagger at <a href=\"http://swagger.wordnik.com\">http://swagger.wordnik.com</a> ' 'or on irc.f...
dd_path_with_no_path_raises_error(self, spec): with pytest.raises(APISpecError) as excinfo: spec.add_path() assert 'Path template is not specified' in str(excinfo)
def test_add_path_strips_base_path(self, spec): spec.options['basePath'] = '/v1' spec.add_path('/v1/pets') assert '/pets' in spec._paths assert '/v1/pets' not in spec._paths def test_add_path_accepts_path(self, spec): route = '/pet/{petId}' route_spec = self.pa...
csunny/blog_project
source/libs/spider/common.py
Python
mit
694
0.001441
#!usr/bin/env python # -*- coding: utf-8 -*- """ @author magic """ import ur
llib2 def download(url, user_agent='wswp', num_retries=2): print 'Downloading:', url headers = {'User-Agent': user_agent} request = urllib2.Request(url, headers=headers) try: html = urllib2.urlopen(request).read() except urllib2.URLError, e: print 'Download error:', e.reason ...
html = download(url, user_agent, num_retries-1) return html if __name__ == '__main__': pass # download('http://blog.csdn.net/column/details/datamining.html')
ceph/calamari-clients
utils/urls.py
Python
mit
3,135
0.00319
from django.conf.urls import patterns, include, url from settings import STATIC_ROOT, GRAPHITE_API_PREFIX, CONTENT_DIR # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() urlpatterns = patterns( '', # These views are needed for
the django-rest-framework debug interface # to be able to log in and out. The URL path doesn't matter, rest_framework # finds the views by name. url(r'^api/rest_framework/', include('rest_framework.urls', namespace='rest_framework')), url(r'^$', 'calamari_web.views.home'), url(r'^api/v1/', includ...
t': '%s/admin/' % STATIC_ROOT}), url(r'^manage/(?P<path>.*)$', 'calamari_web.views.serve_dir_or_index', {'document_root': '%s/manage/' % STATIC_ROOT}), url(r'^login/$', 'django.views.static.serve', {'document_root': '%s/login/' % STATIC_ROOT, 'path': "index.html"}), url(r'^login/(?P<path>...
makinacorpus/django
django/test/testcases.py
Python
bsd-3-clause
49,061
0.002242
from __future__ import unicode_literals from copy import copy import difflib import errno from functools import wraps import json import os import re import sys import select import socket import threading import unittest from unittest import skipIf # Imported here for backward compatibility from unittest.util...
empty list if value is None. """ if value is None: value = [] elif not isinstance(value, list): value = [value] return value real_commit = transaction.commit real_rollback = transaction.rollback real_enter_transaction_management = transaction.enter_transaction_management real_leave_tra...
nsaction_methods(): transaction.commit = nop transaction.rollback = nop transaction.enter_transaction_management = nop transaction.leave_transaction_management = nop transaction.abort = nop def restore_transaction_methods(): transaction.commit = real_commit transaction.rollback = real_rollb...
hgiemza/DIRAC
ConfigurationSystem/Client/Helpers/Resources.py
Python
gpl-3.0
10,846
0.043426
""" Helper for the CS Resources section """ import re from distutils.version import LooseVersion #pylint: disable=no-name-in-module,import-error from DIRAC import S_OK, S_ERROR, gConfig from DIRAC.ConfigurationSystem.Client.Helpers.Path import cfgPath from DIRAC.Core...
ues' % (
grid, site, ce ) ) if not result['OK']: continue queues = result['Value'] for queue in queues: if community: comList = gConfig.getValue( '/Resources/Sites/%s/%s/CEs/%s/Queues/%s/VO' % ( grid, site, ce, queue ), [] ) if comList and not community in com...
staceytay/workabroad-scraper
workabroad/items.py
Python
mit
490
0.004082
# Define here the models for your scraped items # # See documentation in: # http://doc.scrapy.org/en/latest/topics/items.html from scrapy.item import Item, Field class WorkabroadItem(Item): # define the fields for your item here like: # name = Field() pass class PostItem(Item): href = Field()
id = Field() title = Field() location = Field() expiry = Field() agency = Field() qualifications = Field() info = Field() requirements = Fi
eld()
Simocracy/simocraPy
simocracy/ldhost.py
Python
gpl-2.0
2,714
0.006275
#!/bin/env python3.4 # -*- coding: UTF-8 -*- import simocracy.wiki as wiki import re ## config ## #Möglichkeit zur Simulation des Vorgangs simulation = False #Loglevel: schreibe nur geänderte Zeilen ("line") oder # ganze geänderte Artikel ("article") auf stdin oder # gar nicht ("none") loglevel = "...
newLine = replaceAll(el.groupdict()['link'], replacement, newLine) newLine = replaceAll(doubleRepl, replacement, newLine) text = text + newLine #logging if simulation and loglevel == "line": logs = logs + "\n- " + line.decode('utf-8') + "+ " + newLine + "\n" ...
int(text) else: raise Exception("config kaputt") #Schreiben if not simulation: wiki.edit_article(article, text, opener) print("Done: "+article) print("========================================================\n") if __name__ == "__main__": ...
dsoprea/PyInotify
tests/test_inotify.py
Python
gpl-2.0
17,960
0.003905
# -*- coding: utf-8 -*- import os import unittest import inotify.constants import inotify.calls import inotify.adapters import inotify.test_support try: unicode except NameError: _HAS_PYTHON2_UNICODE_SUPPORT = False else: _HAS_PYTHON2_UNICODE_SUPPORT = True class TestInotify(unittest.TestCase): def...
INOTIFY_EVENT(wd=1, mask=256, cookie=0, len=16), ['IN_CREATE'], inner_path, u'filen
ame料夾'), (inotify.adapters._INOTIFY_EVENT(wd=1, mask=32, cookie=0, len=16), ['IN_OPEN'], inner_path, u'filename料夾'), (inotify.adapters._INOTIFY_EVENT(wd=1, mask=8, cookie=0, len=16), ['IN_CLOSE_WRITE'], inner_path, u'filename料夾'), ] self.assertEquals(events, expe...