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
Parsl/parsl
parsl/tests/test_python_apps/test_memoize_1.py
Python
apache-2.0
976
0
import argparse import parsl from parsl.app.app import python_app from parsl.tests.configs.local_threads import config @python_app(cache=True) def random_uuid(x, cache=True): import uuid return str(uuid.uuid4()) def test_python_memoization(n=2): """Testing python memoization disable """ x = ran...
n__': parsl.clear() parsl.load(config) parser = argparse.ArgumentParser() parser.add_argument("-c", "--count", default="10", help="Count of apps to launch") parser.add_argument("-d", "--debug", action='store_true', help="Count of apps to launch") ...
stream_logger() x = test_python_memoization(n=4)
jiquintana/proxy-final
db_model/db_layer.py
Python
gpl-3.0
30,743
0.009791
#!/usr/bin/python # -*- coding: utf-8 -*- # vim: ts=4:sw=4:sts=4:ai:et:fileencoding=utf-8:number import sys if sys.version_info < (3, 0): python_OldVersion = True else: python_OldVersion = False import pprint from sqlalchemy import Column, ForeignKey, Integer, String, Boolean, Table, or_, CHAR, Enum ...
00000, # 07.
xxh mask 'H08_M' : 0b000000000000000100000000, # 08.xxh mask 'H09_M' : 0b000000000000001000000000, # 09.xxh mask 'H10_M' : 0b000000000000010000000000, # 10.xxh mask 'H11_M' : 0b000000000000100000000000, # 11.xxh mask 'H12_M' : 0b000000000001000000000000, # 12.xxh mask 'H13_M' : 0b0000...
piotroxp/scibibscan
scib/lib/python3.5/site-packages/astropy/wcs/tests/extension/test_extension.py
Python
mit
2,891
0.001038
# Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import absolute_import, division, print_function, unicod
e_literals import os import subprocess import sys from ....tests.helper import pytest def test_wcsapi_extension(tmpdir): # Test that we can build a simple C extension with the astropy.wcs C API setup_path = os.path.dirname(__file__) astropy_path = os.path.abspath( os.path.join(setup_path, '..',...
THONPATH')] = str(os.pathsep.join(paths)) # Build the extension # This used to use subprocess.check_call, but on Python 3.4 there was # a mysterious Heisenbug causing this to fail with a non-zero exit code # *unless* the output is redirected. This bug also did not occur in an # interactive session...
elijah74/django-url-shortener
base/conf/urls/all.py
Python
bsd-3-clause
915
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals """shortener URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a...
.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^shortener/', include('shortener.urls', namespace='short
ener')), ]
koodaamo/asynciohelpers
asynciohelpers/service.py
Python
gpl-3.0
6,449
0.021244
from contextlib import suppress import asyncio from concurrent.futures import CancelledError from .exceptions import SetupException class AsyncioRunning: "base runner class that sets up and runs the loop & payload" RESTART_DELAY = 15 # seconds until waiter & runner are restarted # these three required per ...
s" %
(type(exc), exc)) else: self._protocol.is_closed.add_done_callback(self._reconnect) break await asyncio.sleep(self.RECONNECT_DELAY, loop=self._loop) def _reconnect(self, future): if not self._closing: self._logger.warn("connection lost, reconnecting") ...
sialm/par_king
client/ParKingClient.py
Python
mit
11,117
0.004408
# from i2clibraries import i2c_hmc58831 from socket import socket from socket import AF_INET from socket import SOCK_STREAM from socket import error as socket_error from time import sleep from time import time from struct import pack from datetime import datetime from threading import Thread import config import ParKin...
or_1() self.z_base_line_1 = z self.last_z_signal_1 = 0 if not config.ONE_SENSOR: (x, y, z) = self.read_from_sensor_2() self.z_base_line_2 = z self.last_z_signal_2 = 0 def create_logs(self): """ Create
s a unique log file per session :return: log file """ try: file_name = 'log_file' log_file = open(file_name, 'w') return log_file except Exception as e: print('Log file error, shutting down.') self.tear_down() def create_da...
stvstnfrd/edx-platform
openedx/core/djangoapps/xblock/learning_context/manager.py
Python
agpl-3.0
1,895
0.001583
""" Helper methods for working with learning contexts """ from edx_django_utils.plugins import PluginManager from opaque_keys import OpaqueKey from opaque_keys.edx.keys import LearningContextKey, UsageKeyV2 from openedx.core.djangoapps.xblock.apps import get_xblock_app_config class LearningContextPluginManager(Plugi...
e installed. """ if isinstance(key, LearningContextKey): context_type
= key.CANONICAL_NAMESPACE # e.g. 'lib' elif isinstance(key, UsageKeyV2): context_type = key.context_key.CANONICAL_NAMESPACE elif isinstance(key, OpaqueKey): # Maybe this is an older modulestore key etc. raise TypeError("Opaque key {} does not have a learning context.".format(key)) ...
dejlek/pulsar
examples/philosophers/tests.py
Python
bsd-3-clause
1,021
0
import unittest import asyncio from pulsar import send from pulsar.apps.test import test_timeout from .manage import DiningPhilosophers class TestPhylosophers(unittest.TestCase): app_cfg = None concurrency = 'thread' @classmethod @asyncio.coroutine def setUpClass(cls)
: app = DiningPhilosophers(name='plato', concurrency=cls.concurrency) cls.app_cfg = yield from send('arbiter', 'run', app) @test_timeout(30) @asyncio.coroutine def test_info(self): while True: yield from asyncio.sleep(0.5) inf...
if p: all.append(p) if len(all) == 5: break @classmethod def tearDownClass(cls): if cls.app_cfg is not None: return send('arbiter', 'kill_actor', cls.app_cfg.name)
KITPraktomatTeam/Praktomat
src/utilities/file_operations.py
Python
gpl-2.0
3,099
0.002259
# -*- coding: utf-8 -*- import os import grp import tempfile from django.conf import settings from utilities import encoding import shutil import zipfile gid = None if (settings.USEPRAKTOMATTESTER): gid = grp.getgrnam('praktomat').gr_gid def makedirs(path): if os.path.exists(path): return else: ...
erwrites an existing file, with the name of the file in the archive as the parameter. The file_cb is called for every file, after extracting it. """ if not zipfile.is_zipfile(zipfilename): raise InvalidZipFile("File %s is not a zipfile." % zipfilename) zip = zipfile.ZipFile(zipfilename, 'r'...
l would not protect against ..-paths, # it would do so from python 2.7.4 on. for finfo in zip.infolist(): dest = os.path.join(to_path, finfo.filename) # This check is from http://stackoverflow.com/a/10077309/946226 if not os.path.realpath(os.path.abspath(dest)).startswith(to_path): ...
RuthAngus/LSST-max
code/soft/regions.py
Python
mit
5,812
0.025292
import numpy as np import matplotlib.pyplot as plt import time def regions(seed=0, randspots, activityrate=1, cyclelength=1, cycleoverlap=0, maxlat=70, minlat=0, tsim=1000, tstart=0, dir="."): """ inputs activityrate - number of bipoles (1= solar) cyclelength - length of cycle in years ...
radians) phneg= phi of negative pole (radians) width= width of each pole (radians) bmax = maximum flux density (Gauss) According to Schrijver and Harvey (1994), the number of active regions
emerging with areas in the range [A,A+dA] in a time dt is given by n(A,t) dA dt = a(t) A^(-2) dA dt , where A is the "initial" area of a bipole in square degrees, and t is the time in days; a(t) varies from 1.23 at cycle minimum to 10 at cycle maximum. The bipole area is the area within the 25-Ga...
tylertian/Openstack
openstack F/python-novaclient/novaclient/tests/v1_1/test_security_group_rules.py
Python
apache-2.0
2,485
0.002414
from novaclient import exceptions from novaclient.v1_1 import security_group_rules from novaclient.tests import utils from novaclient.tests.v1_1 import fakes cs = fakes.FakeClient() class SecurityGroupRulesTest(utils.TestCase): def test_delete_security_group_rule(self): cs.security_group_rules.delete(1)...
rule(self): sg = cs.security_group_rules.create(1, "tcp", 1, 65535, "10.0.0.0/16", 101) body = { "security_group_rule": { "ip_protocol": "tcp", "from_port": 1, "to_port": 65535, "cidr...
d": 101, "parent_group_id": 1, } } cs.assert_called('POST', '/os-security-group-rules', body) self.assertTrue(isinstance(sg, security_group_rules.SecurityGroupRule)) def test_invalid_parameters_create(self): self.assertRaises(exceptions.CommandError, ...
erdc-cm/air-water-vv
3d/dambreak_Ubbink/dambreak_Ubbink_medium/ls_consrv_n.py
Python
mit
982
0.01222
from proteus import * from dambreak_Ubbink_medium import * from ls_consrv_p import * timeIntegrator = ForwardIntegrator timeIntegration = NoInte
gration femSpaces = {0:basis} subgridError = None massLumping = False numericalFluxType = DoNothing conservativeFlux = None shockCapturing = None fullNewtonFlag = True multilevelNonlinearSolver = Newton levelNonlinearSolver = Newt
on nonlinearSmoother = None linearSmoother = None matrix = SparseMatrix if useOldPETSc: multilevelLinearSolver = PETSc levelLinearSolver = PETSc else: multilevelLinearSolver = KSP_petsc4py levelLinearSolver = KSP_petsc4py if useSuperlu: multilevelLinearSolver = LU levelLinearSol...
chaserhkj/musicbox
setup.py
Python
mit
1,899
0.003686
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author: omi # @Date: 2014-08-24 22:08:33 # @Last Modified by: omi # @Last Modified time: 2015-03-30 23:36:21 ''' __ ___________________________________________ | \ ||______ | |______|_____||______|______ | \_||______ | |______| |______||______ ...
to music by omi | | | + ------------------------------------------ + ''' from setuptools import setup, find_packages setup( name='NetEase-MusicBox', version='0.1.9.6', packages=find_packages(), include_package_data=True, install_requires=[ ...
], }, author='omi', author_email='4399.omi@gmail.com', url='https://github.com/darknessomi/musicbox', description='A sexy command line interface musicbox', keywords=['music', 'netease', 'cli', 'player'], zip_safe=False, )
MyRookie/SentimentAnalyse
venv/lib/python2.7/site-packages/nltk/corpus/reader/semcor.py
Python
mit
11,106
0.005312
# Natural Language Toolkit: SemCor Corpus Reader # # Copyright (C) 2001-2015 NLTK Project # Author: Nathan Schneider <nschneid@cs.cmu.edu> # URL: <http://nltk.org/> # For license information, see LICENSE.TXT """ Corpus reader for the SemCor Corpus. """ from __future__ import absolute_import, unicode_literals...
the complete XML data structure, use the ``xml()``
method. For access to simple word lists and tagged word lists, use ``words()``, ``sents()``, ``tagged_words()``, and ``tagged_sents()``. """ def __init__(self, root, fileids, wordnet, lazy=True): XMLCorpusReader.__init__(self, root, fileids) self._lazy = lazy self._wordne...
kramwens/order_bot
venv/lib/python2.7/site-packages/twilio/rest/resources/trunking/credential_lists.py
Python
mit
1,709
0
from .. import NextGenInstanceResource, NextGenListResource class CredentialList(NextGenInstanceResource): """ A Credential List Resource. See the `SIP Trunking API reference <https://www.twilio.com/docs/sip-trunking/rest/credential-lists>_` for more information. .. attribute:: sid T...
Disassociates a Credential List from the Trunk. :param credentia
l_list_sid: A human readable Credential list sid. """ return self.delete_instance(credential_list_sid)
ruijie/quantum
quantum/tests/unit/test_linux_dhcp.py
Python
apache-2.0
23,666
0.000085
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 OpenStack LLC # 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/l...
ntf.assert_has_calls(expected) chmod.assert_called_once_with('/baz', 0644) rename.assert_called_once_with('/baz', '/foo') def test_resta
rt(self): class SubClass(dhcp.DhcpBase): def __init__(self): dhcp.DhcpBase.__init__(self, None, None, None) self.called = [] def enable(self): self.called.append('enable') def disable(self, retain_port=False): ...
iamhuy/rumour-veracity-verification
src/data/make_interim.py
Python
mit
7,273
0.0044
# -*- coding: utf-8 -*- import os import logging from dotenv import find_dotenv, load_dotenv from constants import * import json from utils import json_from_file, merge_json import shutil from settings import * def prepare_train_data(): """ Runs data processing scripts to turn traning raw data from (../raw) into ...
lies # read structure structure_file = open(os.path.join(source_
tweet_folder_path, 'structure.json'), "r") structure_content = structure_file.read() structure_file.close() structure = json.loads(structure_content) source_tweet['structure'] = structure source_tweet['veracity'] = veracity_labels[source_tweet['id_str']] source_tweet['s...
smalls12/django_helpcenter
helpcenter/api/tests/test_serializers.py
Python
mit
6,657
0
import json from django.test import TestCase from rest_framework.test import APIRequestFactory from helpcenter import models from helpcenter.api import serializers from helpcenter.api.testing_utils import full_url from helpcenter.testing_utils import create_article, create_category class TestArticleSerializer(Test...
msg='\nExpected: {}\n Actual: {}'.format( expected, serializer.data)) def test_update(self): """ Test updating an existing Category. If data is passed to an existing Category, it should update the existing instance's data. """ category = create_category() ...
a = { 'title': 'Better Title' } serializer = serializers.CategorySerializer( category, data=data, partial=True) self.assertTrue(serializer.is_valid()) updated = serializer.save() self.assertEqual(1, models.Category.objects.count()) self.assertEq...
gavinfish/leetcode-share
python/201 Bitwise AND of Numbers Range.py
Python
mit
541
0.005545
''' Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive. For example, given the range [5, 7], you should return 4. ''' c
lass Solution(object): def rangeBitwiseAnd(self, m, n): """ :type m: int :type n: int :rtype: int """
while n > m: n &= n - 1 return n if __name__ == "__main__": assert Solution().rangeBitwiseAnd(5, 7) == 4 assert Solution().rangeBitwiseAnd(7, 15) == 0
xionluhnis/decnet-scripts
test.py
Python
mit
1,462
0.008208
#!/usr/bin/env python ## path configuration caffe_root = './caffe' script_path = '.' caffe_model = script_path + '/soccer.prototxt' caffe_weight = script_path + '/snapshot/superlatefusion_iter_15000.caffemodel' caffe_inference_weight = script_path + '/superlatefusion_inference.caffemodel' ### start generate caffemode...
as np import sys sys.path.append(caffe_root+'/python') import caffe from caffe.proto import caffe_pb2 import cv2 net = caffe.Net(caffe_model, caffe_weight) net.set_mode_cpu() net.set_phase_test() def forward_once(net): start_ind = 0 end_ind = len(net.layers) - 1 net._forward(start_ind, end_ind) re...
res = forward_once(net) layers = ['data', 'data2', 'seg-label', 'input', 'conv1', 'conv2', 'conv3', 'seg-score'] import os # debug output for name in layers: if not os.path.exists('debug/%s' % name): os.mkdir('debug/%s' % name) blob = net.blobs[name] for b in range(0, 16): for c in range(...
offbye/PiBoat
pyboat/piboat.py
Python
apache-2.0
2,413
0.003374
#!/usr/bin/python # -*- encoding: UTF-8 -*- # SockBoatServer created on 15/8/30 下午3:49 # Copyright 2014 offbye@gmail.com """ """ __author__ = ['"Xitao":<offbye@gmail.com>'] from SocketServer import ThreadingTCPServer, StreamRequestHandler import traceback import threading import os,sys from pi_pwm import PiPWM ...
data == "gps": self.wfile.write(get_gps()) elif data ==
"reboot": os.system('reboot') sys.exit() elif data == "halt": os.system("shutdown -r -t 5 now") sys.exit() elif data == "rtsp": os.system("raspivid -o - -w 640 -h 360 -t 9999999 |cvlc -vvv...
mkaplenko/mobilmoney_sms
client.py
Python
gpl-2.0
1,933
0.001046
# -*- coding: utf-8 -*- __author__ = 'mkaplenko' import httplib import time class MobilMoneySms(object): def __init__(self, phone_to, message): self.phone_to = phone_to self.message = message self.sync = int(time.time()*100) class MobilMoneySmsClient(object): connection_host = 'gate....
st_body()) self.response = connection.getresponse() @property def answer(self): return self.response.read() if self.response else None if __name__ == '__main__': sms = MobilMoneySms('+79151
234567', u'Привет мир! Я тестирую смс!') client = MobilMoneySmsClient('my_login', 'my_password', 'my_originator_name') client.register_sms(sms) client.send_sms() print(client.answer)
emgirardin/compassion-modules
sbc_compassion/tools/zbar_wrapper.py
Python
agpl-3.0
2,203
0
# -*- encoding: utf-8 -*- ############################################################################## # # Copyright (C) 2014 Compassion CH (http://www.compassion.ch) # Releasing children from poverty in Jesus' name # @author: Emmanuel Girardin <emmanuel.girardin@outlook.com> # # The licence is in the fil...
library. When no ZBar is detected, it apply a few filter on the input image and try the scanning agai
n. This technique reduces the number of false negative.""" import zbar import cv2 # we use openCV to repair broken QRCodes. from PIL import Image def scan_qrcode(filename): qrdata = None result = _decode(filename) # map the resulting object to a dictionary compatible with our software if result: ...
t3dev/odoo
addons/digest/models/digest_tip.py
Python
gpl-3.0
784
0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models from odoo.tools.translate import html_translate class DigestTip(models.Model): _name = 'digest.tip' _description = 'Digest T
ips' _order = 'sequence' sequence = fields.Integer( 'Sequence', default=1, help='Used to display digest tip in email template base on order') user_ids = fields.Many2many( 'res.users', string='Recipients', help='Users having already received this tip') tip_description = f...
te=html_translate) group_id = fields.Many2one( 'res.groups', string='Authorized Group', default=lambda self: self.env.ref('base.group_user'))
CarlFK/veyepar
dj/main/models.py
Python
mit
22,252
0.011639
# models.py import os import socket import datetime import random import re from django import forms from django import urls from django.db import models from django.db.models.signals import pre_save from .unique_slugify import u
nique_slugify from .titlecase import titlecase from functools import reduce def time2s(time): """ given 's.s' or 'h:m:s.s' returns s.s """ if time: sec = reduce(lambda x, i: x*60 + i, list(map(float, time.split(':')))) else: sec = 0.0 return sec class Client(models.Model)...
t=1) active = models.BooleanField(default=True, help_text="Turn off to hide from UI.") name = models.CharField(max_length=135) slug = models.CharField(max_length=135, blank=True, null=False, help_text="dir name to store input files", ) contacts = models.CharField(max_length=300, ...
xybydy/kirilim
utils.py
Python
gpl-2.0
934
0
import sys from time import sleep from colored import stylize, fg, attr def flush(msg, err=None, fast=None, wait=0, code='reg'): codes = dict( error=fg('red') + attr('bold'), reg=fg(28) + attr('bold'), blue=fg('blue') ) if err: if fast: print(stylize('\n[-] {0...
', codes['error'])) for char in msg: sys.stdout.write(stylize('%s' %
char, codes['error'])) sys.stdout.flush() sleep(wait) else: if fast: print(stylize('\n[+] {0}'.format(msg), codes[code]), end='') else: print(stylize('\n[+] ', codes[code]), end='') for char in msg: sys.stdout.write(...
Ruide/angr-dev
angr-management/angrmanagement/ui/widgets/qstring_table.py
Python
bsd-2-clause
3,604
0.001942
from PySide.QtGui import QTableWidget, QTableWidgetItem, QColor, QAbstractItemView from PySide.QtCore import Qt from angr.analyses.cfg.cfg_fast import MemoryData from ...utils import filter_string_for_display class QStringTableItem(QTableWidgetItem): def __init__(self, mem_data, *args, **kwargs): supe...
if irsb_addr in self._function.block_addrs_set: self.items.append(QStringTableItem(f)) break items_count = len(sel
f.items) self.setRowCount(items_count) for idx, item in enumerate(self.items): for i, it in enumerate(item.widgets()): self.setItem(idx, i, it) if 0 <= current_row < len(self.items): self.setCurrentCell(current_row, 0) self.setVisible(False) ...
hanipcode/norinproject
build/bdist.win-amd64/winexe/temp/wx._gdi_.py
Python
mit
358
0.011173
def __load(): import imp, os, sys try: dirname = os.path.dirname(__loader__.archive) except NameError: dirname = sys.prefix path = os.path.join(dirname, 'wx._gdi_.pyd') #print "py2exe extension module", __name__, "->", path mod = imp.load_dynamic(__n
ame__, path) ## mod.frozen = 1
__load() del __load
terrence2/OpenActuator
OpenActuator/app_a/diagnostic_led.py
Python
gpl-3.0
838
0.002387
import machine import time DIAGNOSTIC_LED = None try: with open('config/diagnostic_led.pin', 'r') as fp: invert = False value = int(fp.read()) if value < 0: value = -value invert = True DIAGNOSTIC_LED
= machine.Signal(value, machine.Pin.OUT, invert=invert) DIAGNOST
IC_LED.off() except: pass def blink_forever(cycle_period_ms): while True: blink_once(cycle_period_ms) def blink_n(cycle_period_ms, count): i = 0 while i < count: blink_once(cycle_period_ms) i += 1 def blink_once(cycle_period_ms): half_period = cycle_period_ms // 2 ...
ideascube/ideascube
ideascube/tests/test_tags_command.py
Python
agpl-3.0
4,017
0.000747
from django.core.management import call_command import pytest from ideascube.mediacenter.tests.factories import DocumentFactory from taggit.models import Tag pytestmark = pytest.mark.django_db def test_count_should_count_usage(capsys): DocumentFactory.create_batch(size=4, tags=['tag1']) call_command('tags'...
Bar_, half_clean1, half_clean2]) doc5 = DocumentFactory(tags=[Foo, foo, bar_, Bar]) doc6 = DocumentFactory(tags=[Foo, foo, Bar_, tag_to_delete]) call_command('tags', 'sanitize') all_tag_names = list(Tag.objects.all().order_by('name') .values_list('name', flat=True)
) assert all_tag_names == ['bar', 'foo', 'other', 'other:foo'] assert sorted(doc1.tags.names()) == ['bar', 'foo', 'other'] assert sorted(doc2.tags.names()) == ['bar', 'foo', 'other', 'other:foo'] assert sorted(doc3.tags.names()) == ['bar', 'foo'] assert sorted(doc4.tags.names()) == ['bar', 'foo', 'o...
guker/spear
config/grid/para_training_local.py
Python
gpl-3.0
1,092
0.032051
#!/usr/bin/env python # setup of the grid parameters # default queue used for training training_queue = { 'queue':'q1dm', 'memfree':'16G', 'pe_opt':'pe_mth 2', 'hvmem':'8G', 'io_big':True } # the queue that is used solely for the final ISV training step isv_training_queue = { 'queue':'q1wm', 'memfree':'32G', 'pe_opt...
hould enroll number_of_models_per_enrol_job = 20 enrol_queue = { 'queue':'q1d', 'memfree':'4G', 'io_big':True } # number of models that one score job should process number_of_models_per_score_job = 20 score_queue = { 'queue':'q1d', 'memfree':'4G', 'io_big':True } grid_type = 'local'
# on Idiap grid
ir0nb8t/tutorials
automateTheBoringStuff/vailidateInput.py
Python
gpl-3.0
344
0
while True: pr
int('Enter your age:') age = input() if age.isdecimal(): break print('Please enter a number for your age.') while True: print('Select a new password (letters and numbers only):') password = input() if password.isalnum(): break print('Passwords can onl
y have letters and numbers.')
aepifanov/mos_mu
modules/pkgs_verify_md5.py
Python
apache-2.0
4,932
0.003447
#!/usr/bin/env python from ansible.module_utils.basic import AnsibleModule from subprocess import Popen, PIPE from os import path import re import yaml def parse_verify_output(output_lines, pkg_name, pkg_ver=None, ex_re_list=None, cmd_md5sum=False): result = [] for line in output_lines...
('/var/lib/dpkg/info/%s.md
5sums' % pkg_name): md5_file = '/var/lib/dpkg/info/%s.md5sums' if md5_file: cmd = ('cd /; nice -n 19 ionice -c 3 md5sum --quiet -c ' '%s 2>&1') % md5_file cmd_md5sum = True else: # no md5 file, ski...
uclouvain/OSIS-Louvain
education_group/ddd/service/write/copy_training_service.py
Python
agpl-3.0
2,322
0.002154
############################################################################## # # OSIS stands for Open Student Information System. It's an application # designed to manage the core business of higher education institutions, # such as universities, faculties, institutes and professional schools. # The core ...
ion_group.ddd.domain.training import TrainingIdentity from ddd.logic.formation_catalogu
e.builder.training_builder import TrainingBuilder from education_group.ddd.repository import training as training_repository @transaction.atomic() def copy_training_to_next_year(copy_cmd: command.CopyTrainingToNextYearCommand) -> 'TrainingIdentity': # GIVEN repository = training_repository.TrainingRepository(...
ericmjl/bokeh
bokeh/core/validation/__init__.py
Python
bsd-3-clause
3,227
0.005888
#----------------------------------------------------------------------------- # Copyright (c) 2012 - 2020, Anaconda, Inc., and Bokeh Contributors. # All rights reserved. # # The full license is in the file LICENSE.txt, distributed with this software. #-------------------------------------------------------------------...
Imports #----------------------------------------------------------------------------- # Bokeh imports from .check import check_integrity, silence, silenced from .decorators import error, warning #----------------------------------------------------------------------------- # Globals and constants #-----------------...
--- # General API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Dev API #----------------------------------------------------------------------------- #----------------------------------------------------...
youlanhai/ExcelToCode
xl2code/writers/lua_writer.py
Python
mit
2,039
0.038744
# -*- coding: utf-8 -*- from base_writer import BaseWriter class LuaWriter(BaseWriter): def begin_write(self): super(LuaWriter, self).begin_write() self.output("module(...)", "\n\n") def write_sheet(self, name, sheet): self.write_value(name, sheet) if name == "main_sheet": self.write_value("main_length...
alue is None: return output("nil") tp = type(value) if tp == bool: output("true" if value else "false") elif tp == int: output("%d" % (value, )) elif tp == float: output("%g" % (value, )) elif tp == str: output('"%s"' %(value, )) elif tp == unicode: output('"%s"' % (value.encode("utf-...
tp == tuple or tp == list: output("{") for v in value: self.newline_indent(indent, max_indent) self.write(v, indent + 1, max_indent) output(", ") if len(value) > 0 and indent <= max_indent: output("\n") self._output(indent - 1, "}") else: output("}") elif tp == dict: output("...
e4p/dsub
dsub/providers/google.py
Python
apache-2.0
46,657
0.004479
# Copyright 2016 Google 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 a...
alized from object storage # output: files to de-localize to object storage # # script: any code that dsub writes (like the user script) # tmp: set TMPDIR in the environment to
point here # # workingdir: A workspace directory for user code. # This is also the explicit working directory set before the # user script runs. SCRIPT_DIR = '%s/script' % DATA_MOUNT_POINT TMP_DIR = '%s/tmp' % DATA_MOUNT_POINT WORKING_DIR = '%s/workingdir' % DATA_MOUNT_POINT MK_RUNTIME_...
ndokter/dsmr_parser
test/experiment_telegram.py
Python
mit
320
0
from dsmr_parser impor
t telegram_specifications from dsmr_parser.objects import Telegram from dsmr_parser.parsers import TelegramParser from example_telegrams import TELEGRAM_V4_2 parser = TelegramParser(telegram_specifications.V4) telegram = Telegram(TELEGRAM_V4_2, parser, telegram_spe
cifications.V4) print(telegram)
gamda/gameboard
gameboard/tests/unit_tests.py
Python
mit
14,863
0.010496
# Copyright (c) 2015 Daniel Garcia # # See the file LICENSE.txt for copying permission. import unittest import random from gameboard.gameboard import Gameboard, Direction from gameboard.coordinate import Coordinate class TestBoard(unittest.TestCase): def setUp(self): self.board = Gameboard() def tes...
m_right: Coordinate.d7, Direction.btm: Coordinate.c7, Direction.btm_left: Coordinate.b7, Direction.left: Coordinate.b8, Direction.top_left: None} self.assertEqual(n, correct) def test_neighbors_right(self): n = self.boa...
Direction.btm_right: None, Direction.btm: Coordinate.h6, Direction.btm_left: Coordinate.g6, Direction.left: Coordinate.g7, Direction.top_left: Coordinate.g8} self.assertEqual(n, correct) def test_neighbors_bottom(self): ...
IraKorshunova/kaggle-seizure-prediction
utils/data_splitter.py
Python
mit
4,982
0.004617
import random import numpy as np import itertools, copy def split_data_with_overlap(data_grouped_by_hour, valid_size, overlap_size, window_size, overlap_interictal=True, overlap_preictal=True, random_state=42): random.seed(random_state) number_of_test_interictal_hours = max(1, int...
idx not in set(valid_preictal_hours_indexes)] def fill_data_list(class_label, indexes): overlap = overlap
_preictal if class_label == 'preictal' else overlap_interictal x = [] for idx in indexes: data_hour = data_grouped_by_hour[class_label][idx] if overlap: data = np.concatenate(data_hour, axis=2) for i in xrange(divmod(data.shape[-1] - overlap_size, ...
piskvorky/smart_open
smart_open/smart_open_lib.py
Python
mit
15,002
0.001067
# -*- coding: utf-8 -*- # # Copyright (C) 2019 Radim Rehurek <me@radimrehurek.com> # # This code is distributed under the terms and conditions # from the MIT License (MIT). # """Implements the majority of smart_open's top-level API. The main functions are: * ``parse_uri()`` * ``open()`` """ import codecs impor...
port layer being used, smart_open will ignore that argument and log a warning message. smart_open/doctools.py magic goes here See Also -------- - `Standard library reference <https://docs.python.org/3.7/library/functions.html#open>`__ - `smart_open README.rst <https://github.com/RaRe-Tec...
should be a string') if transport_params is None: transport_params = {} fobj = _shortcut_open( uri, mode, ignore_ext=ignore_ext, buffering=buffering, encoding=encoding, errors=errors, ) if fobj is not None: return fobj # # This ...
biogeo/tinbergen
tinbergen.py
Python
mit
24,413
0.004956
#!/bin/python """ Main user interface and controller for Tinbergen. """ import sys import os import gobject import gtk import gst import tbdatamodel import string #import math NO_TIME = float('nan') if __name__ == '__main__': # Get the path to this script using sys.argv[0] script_dir = os.path.dirname(sys.a...
acketright'), 'speed x.5': gtk.gdk.keyval_from_name('bracketleft')} hotkey_list = [gtk.gdk.keyval_from_name(c) for c in string.ascii_letters+string.digits] def __init__(self, project): self.project = project self._cur_observer = None self._cur_video = None ...
ied = False # Load UI from Glade file: builder = gtk.Builder() builder.add_from_file(mainwin_gladefile) # Get references to relevant objects as attributes of self: ui_objects = ['main_win','observer_combo','file_nav','behavior_nav', 'video_area', 'play_butto...
croscon/fleaker
tests/marshmallow/test_extension.py
Python
bsd-3-clause
1,644
0.001217
# ~*~ coding: utf-8 ~*~ """ tests.marshmallow.test_extension ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Tests for the :class:`MarshmallowAwareApp` to ensure that it will properly register the extension and can be used, as well as testing the top level schema. """ import pytest from flask_marshmallow import fields from fleaker i...
te_app(): """Create the app for testing.""" app = MarshmallowAwareApp.create_app('tests.marshmallow') app.config['SERVER_NAME'] = SERVER_NAME @app.route('/test') def test(): """Test route for Flask URL generation.""" return b'test' return app def test_
marshmallow_extension_creation(): """Ensure creating the MM Aware app registers the extension.""" app = _create_app() # now check for the proper extension assert 'flask-marshmallow' in app.extensions assert app.extensions['flask-marshmallow'] is marsh def test_marshmallow_extension_url_for(): ...
roadmapper/ansible
lib/ansible/modules/cloud/google/gcp_compute_health_check.py
Python
gpl-3.0
47,123
0.004159
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2017 Google # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # ---------------------------------------------------------------------------- # # *** AUTO GENERATED CODE *** AUTO GENERATED CODE *** # ...
required: true type: str timeout_sec: description: - How long (in seconds) to wait before claiming failure. - The default value is 5 seconds
. It is invalid for timeoutSec to have greater value than checkIntervalSec. required: false default: '5' type: int aliases: - timeout_seconds unhealthy_threshold: description: - A so-far healthy instance will be marked unhealthy after this many consecutive failures. The default...
open-mmlab/mmdetection
configs/seesaw_loss/cascade_mask_rcnn_r101_fpn_random_seesaw_loss_mstrain_2x_lvis_v1.py
Python
apache-2.0
4,807
0
_base_ = [ '../_base_/models/cascade_mask_rcnn_r50_fpn.py', '../_base_/datasets/coco_instance.py', '../_base_/schedules/schedule_2x.py', '../_base_/default_runtime.py' ] model = dict( backbone=dict( depth=101, init_cfg=dict(type='Pretrained', checkpoint='torchvisio...
=1.0, loss_weight=1.0)) ], mask_head=dict(num_classes=1203)), test_cfg=dict( rcnn=dict( score_thr=0.0001, # LVIS allows up to 300 max_per_img=300))) img_norm_cfg = dict( mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb
=True) train_pipeline = [ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', with_bbox=True, with_mask=True), dict( type='Resize', img_scale=[(1333, 640), (1333, 672), (1333, 704), (1333, 736), (1333, 768), (1333, 800)], multiscale_mode='value', k...
alexmoratalla/yambopy
yambopy/units.py
Python
bsd-3-clause
2,898
0.007591
I = complex(0,1) ha2ev = 27.211396132 ev2cm1 = 8065.5440044136285 bohr2ang = 0.52917720859 atomic_mass = [ None, 1.00794, 4.002602, 6.941, 9.012182, 10.811, 12.0107, 14.0067, 15.9994, 18.9984032, 20.1797, 22.98976928, 24.305,26.9815386, 28.0855, ...
ne, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None] chemical_symbols = ['X', 'H', ...
'P', 'S', 'Cl', 'Ar', 'K', 'Ca', 'Sc', 'Ti', 'V', 'Cr', 'Mn', 'Fe', 'Co', 'Ni', 'Cu', 'Zn', 'Ga', 'Ge', 'As', 'Se', 'Br', 'Kr', 'Rb', 'Sr', 'Y', 'Zr', 'Nb', 'Mo', 'Tc', 'Ru', 'Rh', ...
tritoanst/ccxt
python/ccxt/bitstamp1.py
Python
mit
10,277
0.001946
# -*- coding: utf-8 -*- from ccxt.base.exchange import Exchange from ccxt.base.errors import ExchangeError from ccxt.base.errors import NotSupported class bitstamp1 (Exchange): def describe(self): return self.deep_extend(super(bitstamp1, self).describe(), { 'id': 'bitstamp1', 'na...
blicGetOrderBook(params) timestamp = int(orderbook['timestamp']) * 1000 return self.parse_order_book(orderbook, timestamp) def fetch_ticker(self, symbol, params={}): if symbol != 'BTC/USD': raise ExchangeError(self.id + ' ' + self.version + " fetchTicker doesn
't support " + symbol + ', use it for BTC/USD only') ticker = self.publicGetTicker(params) timestamp = int(ticker['timestamp']) * 1000 vwap = float(ticker['vwap']) baseVolume = float(ticker['volume']) quoteVolume = baseVolume * vwap return { 'symbol': symbol, ...
addition-it-solutions/project-all
addons/account_check_writing/report/check_print.py
Python
agpl-3.0
2,876
0.006259
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # 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 d
istributed 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License #...
caseydavenport/calico-docker
tests/st/policy/test_profile.py
Python
apache-2.0
15,579
0.000514
# Copyright 2015 Tigera, In
c # # 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 languag...
QubesOS/qubes-core-admin
qubes/tests/vm/appvm.py
Python
lgpl-2.1
7,275
0.001925
# -*- encoding: utf-8 -*- # # The Qubes OS Project, http://www.qubes-os.org # # Copyright (C) 2017 Marek Marczykowski-Górecki # <marmarek@invisiblethingslab.com> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public #...
pvm import qubes.vm.templatevm class TestApp(object): labels
= {1: qubes.Label(1, '0xcc0000', 'red')} def __init__(self): self.domains = {} class TestProp(object): # pylint: disable=too-few-public-methods __name__ = 'testprop' class TestVM(object): # pylint: disable=too-few-public-methods app = TestApp() def __init__(self, **kwargs): ...
sgiavasis/nipype
nipype/interfaces/afni/tests/test_auto_MaskTool.py
Python
bsd-3-clause
1,585
0.024606
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT from ....testing import assert_equal from ..preprocess import MaskTool def test_MaskTool_inputs(): input_map = dict(args=dict(argstr='%s', ), count=dict(argstr='-count', position=2, ), datum=dict(argstr='-datum %s', ), dilate_inputs...
ignore_exception=dict(nohash=True, usedefault=True, ), in_file=dict(argstr='-input %s', copyfile=False, mandatory=True, position=-1, ), inter=dict(argstr='-inter', ), out_file=dict(argstr='-prefix %s', name_source='in_file', name_template='%s_mask', ), outputtype...
MaskTool.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): yield assert_equal, getattr(inputs.traits()[key], metakey), value def test_MaskTool_outputs(): output_map = dict(out_file=dict(), ) outputs = MaskTool.output_spec() ...
deepak7mahto/ForensicsTool
ForensicsTool/ForensicsTool/Forensics_tool_redesigned_using_oops.py
Python
mit
14,272
0.007077
import os, colorama, random_functions, module1, module2, module3, module4, module5, module6, module7 class Main1(random_functions.random_functions_class): def tool_menu_front(self): try: colorama.init(autoreset=True) self.seperator() self.logo() se...
. |
/_\ /_\ /_\ /_\ /_\ | ...
Jelleas/CheckPy
checkpy/assertlib/__init__.py
Python
mit
38
0
from checkpy.assertlib.basic import
*
mrares/incubator-airflow
tests/utils/log/test_logging.py
Python
apache-2.0
4,229
0.000473
# -*- coding: utf-8 -*- # # 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 ...
('text', self.remote_log_location) self.hook_inst_mock.load_string.assert_called_once_with( 'content\ntext', key=self.remote_log_location, replace=True, encrypt=False, ) def test_write_raises(s
elf): self.hook_inst_mock.load_string.side_effect = Exception('error') handler = S3TaskHandler() with mock.patch.object(handler.log, 'error') as mock_error: handler.write('text', self.remote_log_location) msg = 'Could not write logs to %s' % self.remote_log_location ...
immo/pyTOM
df/df_interpreter.py
Python
gpl-3.0
1,707
0.018161
# coding: utf-8 # # drums-backend a simple interactive audio sampler that plays vorbis samples # Copyright (C) 2009 C.D. Immanuel Albrecht # # 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 Fou...
self.tracebacked = True return self.oldshowtraceback(*args) self.showtraceback = new_traceback def write(self,data): send = "PYTHON:" + data.replace("\n","\nPYTHON':")+"\n" self.vars["ui_out"].write(send) self.vars["ui_out"].flush() def hasTracebacked(self): if self...
ebacked = False return True else: return False
drewUCL/Automation-Station
mysite/mysite/settings.py
Python
mit
3,404
0.003231
""" Django settings for mysite project. Generated by 'django-admin startproject' using Django 1.9. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """ import os # Bu...
rib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ {
'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.co...
JeremyCCHsu/Python-Wrapper-for-World-Vocoder
pyworld/__init__.py
Python
mit
176
0
from __future__
import division, print_function, absolute_import import pkg_resources __version__ = pkg_resources.get_distribution('pyworld').version from .pyworld
import *
mikel-egana-aranguren/SADI-Galaxy-Docker
galaxy-dist/eggs/mercurial-2.2.3-py2.7-linux-x86_64-ucs4.egg/hgext/relink.py
Python
gpl-3.0
6,076
0.001317
# Mercurial extension to provide 'hg relink' command # # Copyright (C) 2007 Brendan Cully <brendan@kublai.com> # # This software may be used and distributed according to the terms of the # GNU General Public License version 2 or any later version. """recreates hardlinks between repository clones""" from mercurial imp...
remotelock.release() finally: locallock.release() def collect(src, ui): seplen = len(os.path.sep) candidates =
[] live = len(src['tip'].manifest()) # Your average repository has some files which were deleted before # the tip revision. We account for that by assuming that there are # 3 tracked files for every 2 live files as of the tip version of # the repository. # # mozilla-central as of 2010-06-10...
nZac/keg-elements
keg_elements/db/utils.py
Python
bsd-3-clause
2,393
0.001672
import math from sqlalchemy.sql import expression from sqlalchemy.ext.compiler import compiles from sqlalchemy.types import DateTime from bla
zeutils.strings import randchars from keg.db import db class utcnow(expression.FunctionElement): type = DateTime() @compiles(utcnow, 'postgresql') def _pg_utcnow(element, compiler, **kw): re
turn "TIMEZONE('utc', CURRENT_TIMESTAMP)" @compiles(utcnow, 'mssql') def _ms_utcnow(element, compiler, **kw): return "GETUTCDATE()" @compiles(utcnow, 'sqlite') def _sqlite_utcnow(element, compiler, **kw): return "CURRENT_TIMESTAMP" def validate_unique_exc(exc): return _validate_unique_msg(db.engine.di...
braceio/tags
tags/generator.py
Python
mit
7,669
0.002738
import os import sys import time import posixpath import threading if sys.version > '3': import urllib.parse from http.server import HTTPServer from http.server import SimpleHTTPRequestHandler else: import urllib from BaseHTTPServer import HTTPServer from SimpleHTTPServer import SimpleHTTPReque...
<li> <a href="/about.html"{% is about.html %} class="active"{% endis %}> about </a> </li> </ul>""" NEW_STYLE_STR = """.active {font-weight:bold;}""" NEW_SITE = { 'index.html': NEW_INDEX_STR, 'about.html': NEW_ABOUT_STR, '_partials/header.html': NEW_HEADER_STR, '_partials/nav....
msg = "Oops, there's already an index.html file in the source \n"+\ "folder. If you want to overwrite this folder with a new \n"+\ "site, use the --force option." print(msg) sys.exit(1) except OSError: pass print("Creating new site in '{...
openstack/cinder
cinder/tests/unit/volume/drivers/dell_emc/powermax/test_powermax_common.py
Python
apache-2.0
235,073
0.000009
# Copyright (c) 2020 Dell Inc. or its subsidiaries. # 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 # # ...
nfig_group', interval='10', retries='10', replication_device=None, powermax_port_group_name_template='portGroupName
') driver = fc.PowerMaxFCDriver(configuration=configuration) driver.common._get_attributes_from_config() self.assertEqual( 'portGroupName', driver.common.powermax_port_group_name_template) @mock.patch.object(common.PowerMaxCommon, '_gather_info') def t...
lupyuen/RaspberryPiImage
usr/share/pyshared/ajenti/plugins/supervisor/__init__.py
Python
apache-2.0
287
0
from ajenti.api import * from ajenti.plugins import * info = PluginInfo( title='Supervisor', icon='play', dependencies=[ PluginDe
pendency('main'), PluginDependency('services'), BinaryDependency('supervisord'), ], ) def init(): import
main
rdeheele/odoo
addons/website/models/ir_ui_view.py
Python
agpl-3.0
9,428
0.003076
# -*- coding: utf-8 -*- import copy from lxml import etree, html from openerp import SUPERUSER_ID, tools from openerp.addons.website.models import website from openerp.http import request from openerp.osv import osv, fields class view(osv.osv): _inherit = "ir.ui.view" _columns = { 'page': fields.bool...
elf._view_obj(cr, uid, child.get('t-call', child.get('t-call-assets')), context=context) except ValueError: continue if called_view not in result: result += self._views_ge
t(cr, uid, called_view, options=options, bundles=bundles, context=context) extensions = view.inherit_children_ids if not options: # only active children extensions = (v for v in view.inherit_children_ids if v.active) # Keep options in a deterministic order regardless of...
a-sk/alot
alot/db/utils.py
Python
gpl-3.0
15,380
0.001235
# Copyright (C) 2011-2012 Patrick Totzke <patricktotzke@gmail.com> # This file is released under the GNU GPL, version 3 or a later revision. # For further details see the COPYING file import os import email import tempfile import re from email.header import Header import email.charset as charset charset.add_charset('u...
TURE_MESSAGE_HEADER): m[k] = n[k] e
lse: # an encrypted message without signatures # should arouse some suspicion, better warn # the user add_signature_headers(m, [], 'no signature found') else: # 'Combined method', the sign...
Qwaz/solved-hacking-problem
SSCTF/2016/Crypto&Exploit/HeHeDa/Algorithm1-577265e1.py
Python
gpl-2.0
3,529
0.001133
def LShift(t, k): k %= 8 return ((t << k) | (t >> (8 - k))) & 0xff def encode(p): ret = "" for i in range(8): ret = ('|' if (p >> i) & 1 else 'O') + ret return ret A = [85, 128, 177, 163, 7, 242, 231, 69, 185, 1, 91, 89, 80, 156, 81, 9, 102, 221, 195, 33, 31, 131, 179, 246, 15, 139, 205,...
[179, 132, 74, 60, 94, 252, 166, 242, 208, 217, 117, 255, 20, 99, 225, 58, 54, 184, 243, 37, 96, 106, 64, 151, 148, 248, 44, 175, 152, 40, 171, 251, 210, 118, 56, 6, 138, 77, 45, 169, 209, 232, 68, 182, 91, 203, 9, 16, 172, 95, 154, 90, 164, 161, 231, 11, 21, 3, 97, 70, 34, 86, 124, 114, 119, 223, 123, 167, 47, 219, 19...
, 76, 121, 92, 153, 85, 100, 52, 109, 159, 112, 71, 62, 8, 244, 116, 245, 240, 215, 111, 134, 199, 214, 196, 213, 180, 189, 224, 101, 202, 201, 168, 32, 250, 59, 43, 27, 198, 239, 137, 238, 50, 149, 107, 247, 7, 220, 246, 204, 127, 83, 146, 147, 48, 17, 67, 23, 93, 115, 41, 191, 2, 227, 87, 173, 108, 82, 205, 49, ...
sabirmostofa/app-engine-facebook
lib/twitter.py
Python
lgpl-3.0
4,934
0.003445
from lib.oauth2 import Consumer as OAuthConsumer, Token, Request as OAuthRequest, \ SignatureMethod_HMAC_SHA1 from urllib2 import Request, urlopen from lib import simplejson import config # Twitter configuration TWITTER_SERVER = 'api.twitter.com' TWITTER_REQUEST_TOKEN_URL = 'https://%s/oauth/request...
ame = self.AUTH_BACKEND_NAME + 'association_data' if name in self.request.session: association_data = simplejson.loads(self.request.session[name])
del self.request.session[name] else: association_data = None return association_data def unauthorized_token(self): """Return request for unauthorized token (first stage)""" request = self.oauth_request(token=None, url=self.REQUEST_TOKEN_URL) respo...
D4TI3A/KhaeraTunnisa1144044
doc/Kuliah/Tugas2.py
Python
gpl-3.0
1,425
0.006316
graph = { 'Sarijadi': ['Jl.Surya Sumantri'], 'Jl.Surya Sumantri': ['Pasteur'], 'Pasteur': ['Jl.Dr.Djunjunan'], 'Jl.Dr.Djunjunan': ['Jl.Pajajaran'], 'Jl.Pajajaran': ['Bandara Husain Sastra Negara'], 'Bandara Husain Sastra Negara': ['Band...
if node not in jalur: newjalur = mencari_jalur_terpendek(graph, node, jalantujuan, jalur) if newjalur: if not jalurpendek or len(newjalur) < len(jalurpendek): jalurpendek = newjalur return jalurpendek print("Jalur Jalan ...
print("(Sarijadi, Jl.Surya Sumantri, Pasteur, Jl.Dr.Djunjunan, Jl.Pajajaran, Bandara Husain Sastra Negara)") print("(Khaera Tunnisa 1144044)") print("\n") jalanawal = raw_input("Masukan jalanawal : ") jalantujuan = raw_input("Masukan jalantujuan : ") hasil = mencari_jalur_terpendek(graph, jalanawal, jalantujuan, ...
anzev/hedwig
hedwig/learners/bottomup.py
Python
mit
2,529
0.001186
''' Main learner class. @author: anze.vavpetic@ijs.si ''' from collections import defaultdict from hedwig.core import UnaryPredicate, Rule, Example from hedwig.core.settings import logger from hedwig.stats.significance import is_redundant from hedwig.stats.scorefunctions import interesting class BottomUpLearner: ...
d: self.kb.n_members(pred) >= self.min_sup pruned_subclasses = {} for pred in self.kb.predicates:
subclasses = self.kb.get_subclasses(pred) pruned_subclasses[pred] = filter(min_sup, subclasses) return pruned_subclasses def _pruned_superclasses(self): min_sup = lambda pred: self.kb.n_members(pred) >= self.min_sup pruned_superclasses = {} for pred in self.kb.predi...
JamesChristie/minimax_kata
minimax_kata/interface/char_policy.py
Python
gpl-3.0
1,673
0.012552
from minimax_kata.ex
ecutioner import Executione
r from minimax_kata.interface import WALL_SPACE_CHAR from minimax_kata.interface import EMPTY_SPACE_CHAR from minimax_kata.interface import PLAYER_ONE_TRAIL_CHAR from minimax_kata.interface import PLAYER_TWO_TRAIL_CHAR from minimax_kata.interface import PLAYER_ONE_CHARS from minimax_kata.interface import PLAYER_TWO_CH...
mdmirabal/Parcial2-Prog3
main.py
Python
mit
1,078
0.042672
#!/usr/bin/python # -*- coding: utf-8 -*- from kivy.app import App from kivy.properties import ObjectProperty from kivy.uix.screenmanager import Screen from precios import Precio class Ventana(Screen): precio = ObjectProperty origen="" destino="" def Origen(self, origen): self.origen = origen print (origen)...
o): self.destino = destino print (destino) def CalcularPrecio(self): if self.origen != "" and self.destino != "": costo = ""+Precio(self.origen,self.destino) if costo == "null": self.precio.text ="No se pu...
self.precio.text = "El precio es de aproximadamente $"+costo else: self.precio.text = "POR FAVOR SELECCIONE UNA RUTA" class AplicacionApp(App): def build(self): return Ventana() def on_pause(self): return True if __name__ == '__main__': AplicacionApp().run()
aldian/tensorflow
tensorflow/python/training/tracking/tracking.py
Python
apache-2.0
12,398
0.005565
"""Dependency tracking for trackable objects.""" # 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/li...
elf._destruction_context(): self._destroy_resource() class CapturableResource(base.Trackable): """Holds a Tensor which a tf.function can capture. `CapturableResource`s are discovered by traversing the graph of object attributes, e.g. during `tf.saved_model.save`. They are excluded from the scope-base
d tracking of `TrackableResource`; generally things that require initialization should inherit from `TrackableResource` instead of `CapturableResource` directly. """ def __init__(self, device="", deleter=None): """Initialize the `CapturableResource`. Args: device: A string indicating a required ...
ddimensia/RaceCapture_App
autosportlabs/racecapture/views/configuration/rcp/wirelessconfigview.py
Python
gpl-3.0
3,591
0.005291
# # Race Capture App # # Copyright (C) 2014-2016 Autosport Labs # # This file is part of the Race Capture App # # This 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 ...
.append(wifi_view) if not self.rcp_capabilities or (self.rcp_capabi
lities and self.rcp_capabilities.has_cellular): cellular_view = CellularConfigView(self.base_dir, self.rcp_config) self.ids.wireless_settings.add_widget(cellular_view, index=0) self._views.append(cellular_view) def _attach_event_handlers(self): for view in self._views:...
codilime/cloudify-rest-client
cloudify_rest_client/blueprints.py
Python
apache-2.0
7,791
0
######## # Copyright (c) 2014 GigaSpaces Technologies Ltd. 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...
'/blueprints/{0}'.format(blueprint_id)) return Blueprint(response) def download(self, blueprint_id, output_file=None): """ Downloads a
previously uploaded blueprint from Cloudify's manager. :param blueprint_id: The Id of the blueprint to be downloaded. :param output_file: The file path of the downloaded blueprint file (optional) :return: The file path of the downloaded blueprint. """ uri = '/blueprints...
papedaniel/oioioi
oioioi/forum/views.py
Python
gpl-3.0
11,557
0.000865
from django.core.exceptions import PermissionDenied from django.core.urlresolvers import reverse from django.shortcuts import redirect, get_object_or_404 from django.template.response import TemplateResponse from django.utils.translation import ugettext_lazy as _ from django.views.decorators.http import require_POST fr...
{'forum': forum, 'category': category, 'thread': thread, 'form': form, 'msgs': msgs, 'is_locked': lock, 'post_set': post_set}) else: return TemplateResponse(request, 'forum/thread.html', {'forum': forum, 'category': category, 'thread': thread, ...
rce_condition(not_anonymous & contest_exists & can_enter_contest) @enforce_condition(forum_exists_and_visible & is_proper_forum & is_not_locked) def thread_add_view(request, category_id): category = get_object_or_404(Category, id=category_id) msgs = get_msgs(request) if request.method == 'POST': for...
xandmaga/migracao_py-upsert
postgres-list-table.py
Python
mit
6,300
0.012857
import psycopg2 import collections import json import sys def consulta(query): cursor.execute(query) return cursor.fetchall() def constroi_consulta_lista(lista_tabelas): tabelas = "" for tabela in lista_tabelas: tabelas = tabelas + "'" + tabela + "'," query = "SELECT distinct cl2.relname AS ref_table FROM ...
.cursor() cursor = pjesupcursor ''' #Conexao pjetst pjetstconn = psycopg2.connect("dbname=pj
e user=pjeadmin password=pj3adm1n-TJMG host=linbdpje-10 port=5432") pjetstcursor = pjetstconn.cursor() cursor = pjetstcursor ''' conexao pjetstcasa pje_local_conn = psycopg2.connect("dbname=pje user=postgres password=123456 host=localhost port=5432") pje_local_cursor = pje_local_conn.cursor() cursor = pje_local_curs...
buckinha/gravity
deprecated/test_script_optimizer2.py
Python
mpl-2.0
1,197
0.016708
from FireGirlOptimizer import * FGPO = FireGirlPolicyOptimizer() ###To create, uncomment the following two lines: FGPO.createFireGirlPathways(10,50) #FGPO.saveFireGirlPathways("FG_pathways_20x50.fgl") ###To load (already created data), uncomment the following line #FGPO.loadFireGirlPathways("FG_pathways_20x50.fgl") ...
GHTS_F_PRIME = False FGPO.AVERAGED_WEIGHTS_OBJ_FN = True FGPO.AVERAGED_WEIGHTS_F_PRIME = True print(" ") print("Initial Values") print("objfn: " + str(FGPO.calcObjFn())) print("fprme: " + str(FGPO.calcObjFPrime())) print("weights: " + str(FGPO.pathway_weights)) print("net values: " + str(FGPO.pathway_net_values)) #se...
the following print("Beginning Optimization Routine") FGPO.USE_AVE_PROB = False output=FGPO.optimizePolicy() FGPO.printOptOutput(output) print(" ") print("Final Values") print("objfn: " + str(FGPO.calcObjFn())) print("fprme: " + str(FGPO.calcObjFPrime())) print("weights: " + str(FGPO.pathway_weights)) print("net valu...
amolenaar/gaphor
gaphor/RAAML/fta/basicevent.py
Python
lgpl-2.1
1,914
0.000522
"""Basic Event item definition.""" from gaphas.geometry import Rectangle from gaphas.util import path_ellipse from gaphor.core.modeling import DrawContext from gaphor.diagram.presentation import ( Classified, ElementPresentation, from_package_str, ) from gaphor.diagram.shapes import Box, IconBox, Text, st...
"subject[NamedElement].namespace.name" ) def update_shapes(self
, event=None): self.shape = IconBox( Box( draw=draw_basic_event, ), Text( text=lambda: stereotypes_str(self.subject, ["BasicEvent"]), ), Text( text=lambda: self.subject.name or "", width=l...
yuchou/xblog
blog/templatetags/__init__.py
Python
mit
91
0.010989
#!/u
sr/bin/env python # -*- coding: utf-8 -*- """ @author: yuchou @time: 2017/8/7 1
0:28 """
PascualArroyo/Domotics
Raspberry/rele.py
Python
gpl-2.0
1,058
0.038752
#!/usr/bin/env python # -*- coding: utf-8 -*- import RPi.GPIO as GPIO import deviceConfig import time class Rele: #Rele valueRele = 0 def __init__(self):
GPIO.setup(deviceConfig.pinRele, GPIO.OUT) GPIO.setup(devi
ceConfig.pinReleLed, GPIO.OUT) GPIO.setup(deviceConfig.pinReleButton, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.add_event_detect(deviceConfig.pinReleButton, GPIO.FALLING, callback=self.buttonReleCallback, bouncetime=500) def getValue(self): return self.valueRele def setValue(self, value): self.valueRele ...
SKIRT/PTS
magic/tests/base.py
Python
agpl-3.0
22,419
0.003167
#!/usr/bin/env python # -*- coding: utf8 -*- # ***************************************************************** # ** PTS -- Python Toolkit for working with SKIRT ** # ** © Astronomical Observatory, Ghent University ** # ***************************************************************** # ...
ourcesTestBase, self).__init__(*args, **kwargs) # The remote self.remote = None # Paths self.data_path = None self.data_frames_path = None self.data_masks_path = None self.find_path = None self.find_paths = dict() self.extract_p
ath = None self.extract_paths = dict() # The coordinate systems self.coordinate_systems = CoordinateSystemList() # The frames self.frames = dict() # The dataset self.dataset = None # The catalog fetcher self.fetcher = CatalogFetcher() ...
dave-shawley/vetoes
tests/feature_flag_tests.py
Python
bsd-3-clause
751
0
import unittest import helper.config import mock from vetoes import config class FeatureFlagMixinTests(unittest.TestCase): def test_that_flags_are_processed_during_initialize(self): settings = helper.config.Data({ 'fe
atures': {'on': 'on', 'off': 'false'}
}) consumer = config.FeatureFlagMixin(settings, mock.Mock()) self.assertTrue(consumer.feature_flags['on']) self.assertFalse(consumer.feature_flags['off']) def test_that_invalid_flags_arg_ignored(self): settings = helper.config.Data({ 'features': {'one': 'not vali...
odrotleff/ROOTPWA
pyInterface/package/utils/_parseUtils.py
Python
gpl-3.0
3,290
0.029787
import glob import os import sys import pyRootPwa import pyRootPwa.utils def parseMassBinArgs(allMassBins, massBinArg): massBins = [] if massBinArg == "all": massBins = allMassBins elif ("-" in massBinArg) or ("," in massBinArg): rawMassBinIndices =
massBinArg.split(",") massBinIndices = [] for massBin
Index in rawMassBinIndices: if "-" in massBinIndex: (lb, tmp, ub) = massBinIndex.partition("-") try: lb = int(lb) ub = int(ub) except ValueError: return [] for i in range(lb, ub+1): massBinIndices.append(i) else: try: mbi = int(massBinIndex) except ValueError: ...
technige/py2neo
py2neo/cypher/queries.py
Python
apache-2.0
7,877
0.002158
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Copyright 2011-2021, Nigel Small # # 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 # # Unle...
am merge_key: tuple
of (rel_type, key1, key2...) :param start_node_key: :param end_node_key: :param keys: :param preserve: Collection of key names for values that should be protected should the relationship already exist. :return: (query, parameters) tuple """ return cypher_join("UNWIND $data AS...
ssaavedra/couchdb-python
couchdb/mapping.py
Python
bsd-3-clause
22,390
0.001385
# -*- coding: utf-8 -*- # # Copyright (C) 2007-2009 Christopher Lenz # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. """Mapping from raw JSON data structures to Python objects and vice versa. >>> from couchdb import ...
ass, and conveniently access all attributes: >>> person = Person.load(db, person.id) >>> old_rev = person.rev >>> person.name u'John Doe' >>> person.age 42 >>> person.added #doctest: +ELLIPSIS datetime.datetime(...) To update a document, si
mply set the attributes, and then call the ``store()`` method: >>> person.name = 'John R. Doe' >>> person.store(db) #doctest: +ELLIPSIS <Person ...> If you retrieve the document from the server again, you should be getting the updated data: >>> person = Person.load(db, person.id) >>> person.name u'John R....
tudennis/LeetCode---kamyu104-11-24-2015
Python/plus-one-linked-list.py
Python
mit
1,560
0
# Time: O(n) # Space: O(1) # Definition fo
r singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None #
Two pointers solution. class Solution(object): def plusOne(self, head): """ :type head: ListNode :rtype: ListNode """ if not head: return None dummy = ListNode(0) dummy.next = head left, right = dummy, head while right.next: ...
Robpol86/Flask-Large-Application-Example
tests/core/test_email.py
Python
mit
1,330
0.001504
from datetime import timedelta import time from pypi_portal.core.email import send_email, send_exception from pypi_portal.extensions import mail, redis def raise_and_send(): with mail.record_messages() as outbox: try: raise ValueError('Fake error.') except ValueError: send...
cord_messages() as outbox: send_email('Test Email', 'Message body.') assert 1 == len(outbox) assert 'Test Email' == outbox[0].subject with mail.record_messages() as outbox: send_email('Test Email2', 'Message bo
dy.', throttle=1) send_email('Test Email2', 'Message body.', throttle=timedelta(seconds=1)) send_email('Test Email9', 'Message body.', throttle=1) time.sleep(1.1) send_email('Test Email2', 'Message body.', throttle=1) assert 3 == len(outbox) assert ['Test Email2', 'Test Email9', ...
shuhaowu/projecto
projecto/utils.py
Python
apache-2.0
5,402
0.01666
import errno import os from flask import current_app, abort import ujson import werkzeug.utils def safe_mkdirs(path): if os.path.exists(path): return try: os.mkdir(path) except OSError as e: # Check for race conditions. If for some reason two threads/greenlets/whatever # tries to create the sam...
gin import current_user from .models import Project, User def hook_user_to_projects(user): for email in user.emails: for project in Project.index("unregistered_owners", email): project.unregistered_owners.remove(email) project.owners.append(user.key) project.save() for project in
Project.index("unregistered_collaborators", email): project.unregistered_collaborators.remove(email) project.collaborators.append(user.key) project.save() def project_access_required(fn): """This will allow anyone who is currently registered in that project to access the project. Denying the res...
Goodly/TextThresher
thresher_backend/storage.py
Python
apache-2.0
446
0.002242
from django.contrib.staticfiles import storage
# Configure the permissions used by ./manage.py collectstatic # See https://docs.djangoproject.com/en/1.10/ref/contrib/staticfiles/ class TTStaticFilesStorage(storage.StaticFilesStorage): def __init__(self, *args, **kwargs): kwargs['file_permissions_mode
'] = 0o644 kwargs['directory_permissions_mode'] = 0o755 super(TTStaticFilesStorage, self).__init__(*args, **kwargs)
CodingRobots/CodingRobots
robots/examples/Ninja.py
Python
gpl-3.0
2,216
0.000903
from robot import Robot class TheRobot(Robot): def initialize(self): # Try to get in to a corner self.forseconds(5, self.force, 50) self.forseconds(0.9, self.force, -10) self.forseconds(0.7, self.torque, 100) self.forseconds(6, self.force, 50) # Then look around and...
._turretdirect
ion = 1 self.turret(180) self._pingfoundrobot = None def scanfire(self): self.ping() sensors = self.sensors kind, angle, dist = sensors['PING'] tur = sensors['TUR'] if self._pingfoundrobot is not None: # has pinged a robot previously ...
AmandaMoen/AmandaMoen
students/KarlGentner/list_lab.py
Python
gpl-2.0
4,184
0.001195
#!/usr/bin/python import sys import copy # Create fruitlist fruitlist = [u"Apples", u"Pears", u"Oranges", u"Peaches"] # Display all fruit - helper method def displayAllFruit(fruitlist): sys.stdout.write("\nHere is the current list of fruit:\n") sys.stdout.write(", ".join(fruitlist)) sys.stdout.write(...
f.append(userInput) displayAllFruit(f) # User pick a fruit list index to display userInput = "" while isInt(userInput) is False or int(userInput) <= 0 or int(userInput) > len(f): userInput = raw_input("Pick a number between 1 and "
+ str(len(f)) + " to display the corresponding fruit.-->") sys.stdout.write("\nFruit #" + userInput + ": " + f[int(userInput)-1] + "\n") sys.stdout.write("\n") # Add to beginning of fruit list using "+" sys.stdout.write("...
ttsirkia/a-plus
course/migrations/0011_auto_20151215_1133.py
Python
gpl-3.0
624
0.001603
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('cou
rse', '0010_auto_20151214_1714'), ] operations = [ migrations.AddField( model_name='coursechapter', name='pare
nt', field=models.ForeignKey(to='course.CourseChapter', blank=True, null=True, related_name='children'), preserve_default=True, ), migrations.AlterUniqueTogether( name='coursechapter', unique_together=set([]), ), ]
amcw7777/python-exercises
cs177/project4/tetris.py
Python
apache-2.0
3,217
0.010258
import sys import pygame import time from tetris_window import * from tetrimino_factory import * # TASK 0: # # Enter your group information: # GROUP_ID = 0 AUTHOR1 = 'Sait Celebi' AUTHOR1_PURDUE_USERNAME = 'celebis' AUTHOR2 = 'John Doe' AUTHOR2_PURDUE_USERNAME = 'john123' AUTHOR3 = 'Donald Knuth' AUTHOR3_PURDUE_USERN...
.move_down() tetris_window.surface.fill( (0,0,0) ) # black bac
kground counter += 1 if counter == 5: current_tetrimino.move_down() counter = 0 current_tetrimino.draw_tetrimino() if current_tetrimino.has_landed(): tetris_window.add_tetrimino_to_landed_objects(current_tetrimino) tetris_win...
esitamon/django-skeleton
app/website/api.py
Python
gpl-3.0
840
0.00119
f
rom rest_framework import viewsets, permissions import models import serializers class PageViewSet(viewsets.ModelViewSet): """ This viewset automatically provides `list`, `create`, `retrieve`, `update` and `destroy` actions. """ queryset = models.Page.objects.all() serializer_class = serializ...
""" This viewset automatically provides `list`, `create`, `retrieve`, `update` and `destroy` actions. """ queryset = models.Post.objects.all() serializer_class = serializers.PostSerializer permission_classes = (permissions.IsAdminUser, ) def pre_save(self, obj): obj.owner = self....
itmages/itmages-service
itmagesd/common.py
Python
gpl-2.0
2,588
0.004637
# # -*- coding: utf-8 -*- # # Copyright 2011 Voldemar Khramtsov <harestomper@gmail.com> # # 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 o...
ts keys is required." class ActionType: IOMOD_RESPONSE = "iomodresponse" IOMOD
_PROGRESS = "iomodprogress" def echo (message, output="o"): if stat.verbose: if output == "e": std = sys.stderr else: std = sys.stdout std.write("%s\n" % message) ###
newmediamedicine/indivo_server_1_0
indivo/document_processing/idp_objs/equipmentscheduleitem.py
Python
gpl-3.0
3,298
0.014554
from indivo.lib import iso8601 from indivo.models import EquipmentScheduleItem XML = 'xml' DOM = 'dom' class IDP_Equipm
entScheduleItem: def post_data(self, name=None, name_type=None,
name_value=None, name_abbrev=None, scheduledBy=None, dateScheduled=None, dateStart=None, dateEnd=None, recurrenceRule_frequency=None, recurrenceRule...
pyroscope/pyrocore
src/pyrocore/torrent/queue.py
Python
gpl-2.0
6,987
0.00458
# -*- coding: utf-8 -*- # pylint: disable=I0011 """ rTorrent Queue Manager. Copyright (c) 2012 The PyroScope Project <pyroscope.project@gmail.com> """ # 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 Fo...
et: self.pr
oxy.log(xmlrpc.NOHASH, "%s: Started '%s' {%s}" % ( self.__class__.__name__, fmt.to_utf8(item.name), item.alias, )) def run(self): """ Queue manager job callback. """ try: self.proxy = config_ini.engine.open() # Get items ...
fake-name/ReadableWebProxy
WebMirror/management/rss_parser_funcs/feed_parse_extractNightskytlWordpressCom.py
Python
bsd-3-clause
560
0.033929
def extractNightskytlWordpressCom(item): ''' Parser for 'nightskytl.wordpress.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None tagmap = [ ('PRC', 'PRC', 'translated'), ('Loi...
rn buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=t
l_type) return False
UKN-DBVIS/SciBib
app/backend/db_controller/query/authors_publications.py
Python
apache-2.0
1,871
0.003207
# Copyright (C) 2020 University of Konstanz - Data Analysis and Visualization Group # This file is part of SciBib <https://github.com/dbvis-ukon/SciBib>. # # SciBib 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 Fo...
her version 3 of the License, or # (at your option) any later version. # # SciBib 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 Genera
l Public License for more details. # # You should have received a copy of the GNU General Public License # along with SciBib. If not, see <http://www.gnu.org/licenses/>. from backend.db_controller.db import SQLAlchemy from backend.db_controller.db import Authors_publications from backend.db_controller.helper impor...
wbsoft/frescobaldi
frescobaldi_app/snippet/import_export.py
Python
gpl-2.0
7,763
0.000902
# This file is part of the Frescobaldi project, http://www.frescobaldi.org/ # # Copyright (c) 2008 - 2014 by Wilbert Berendsen # # 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 ...
, Qt.Checked) dlg.setMessage(_("Choose which snippets you want to import:")) else: dlg.setMessage(_("There are no new or updated snippets in the file.")) unchanged.setExpanded(True) tree.setWhatsThis(_( "<p>Here the snippets from {filename} are displayed.</p>\n" "<p>If t...
r deselect " "them one by one, or all at once, using the checkbox of the group. " "Then click OK to import all the selected snippets.</p>\n" "<p>Existing, unchanged snippets can't be imported.</p>\n" ).format(filename=os.path.basename(filename))) qutil.saveDialogSize(dlg, "snippetto...
chrisnatali/networkx
networkx/classes/graph.py
Python
bsd-3-clause
55,144
0.000254
"""Base class for undirected graphs. The Graph class allows any hashable object as a node and can associate key/value attribute pairs with each undirected edge. Self-loops are allowed but multiple edges are not (see MultiGraph). For directed graphs see DiGraph and MultiDiGraph. """ # Copyright (C) 2004-2015 by # ...
ct (adjlist) represents the adjacency list and holds edge data keyed by neighbor. The inner dict (edge_attr) represents the edge data and holds edge attribute values keyed by attribute names. Each of these three dicts can be replaced by a user defined dict-like object. In general, the dict-like featur...
olding the factory for that dict-like structure. The variable names are node_dict_factory, adjlist_dict_factory and edge_attr_dict_factory. node_dict_factory : function, (default: dict) Factory function to be used to create the outer-most dict in the data structure that holds adjacency lists ke...