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
EricMuller/mynotes-backend
requirements/twisted/Twisted-17.1.0/src/twisted/web/test/test_wsgi.py
Python
mit
74,813
0.002045
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Tests for L{twisted.web.wsgi}. """ __metaclass__ = type from sys import exc_info import tempfile import traceback import warnings from zope.interface.verify import verifyObject from twisted.python.compat import intToBytes, urlquote, _PY3 f...
and stops resource traversal. """ verifyObject(IResource, self.resource) self.assertTrue(self.resource.isLeaf) def test_unsupported(self): """ A L{WSGIResource} cannot have L{IResource} children. Its C{getChildWithDefault} and C{putChild} methods raise L{RuntimeErr...
r, self.resource.getChildWithDefault, b"foo", Request(DummyChannel(), False)) self.assertRaises( RuntimeError, self.resource.putChild, b"foo", Resource()) class WSGITestsMixin: """ @ivar channelFactory: A no-argument callable which will be in...
microwaveabletoaster/dunces-and-dungeons
dunces-and-dungeons.py
Python
gpl-3.0
5,516
0.033539
from dungeon.dungeon import Dungeon, Hub from entity.player.players import Player, Party import entity.item.items as items import sys, os import base import web.server try: import dill except: dill = None PARTY = Party() class Manager: def __init__(self): self.checked = False def get_current_release(self): ...
_/\| (____/\/\____) | (______/ (_______)|/ )_)(_______/(_______/\_______) _______ _ ______ ( ___ )( ( /|( __ \\ | ( ) || \ ( || ( \ ) | (___) || \ | || | ) | | ___ || (\ \) || | | | | ( ) || | \ || | ) | | ) ( || ) \ || (__/ ) |/ \||/ )_)(______/ ______ _ ...
( || \ ( || ( \/| ( \/| ( ) || \ ( || ( \/ | | ) || | | || \ | || | | (__ | | | || \ | || (_____ | | | || | | || (\ \) || | ____ | __) | | | || (\ \) |(_____ ) | | ) || | | || | \ || | \_ )| ( | | | || | \ | ) | | (__/ )| (___) || ) \ || (___) || (___...
EmanueleCannizzaro/scons
test/toolpath/VariantDir.py
Python
mit
2,582
0.000387
#!/usr/bin/env python # # Copyright (c) 2001 - 2016 The SCons Foundation # # 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 us...
# NONINFR
INGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "test/toolpath/VariantDir.p...
orangain/jenkins-docker-sample
tests.py
Python
mit
681
0.003008
# coding: utf-8 import unittest from config_reader import ConfigReader class TestConfigReader(unittest.TestCase): def setUp(self): self.config = ConfigReader(""" <root> <person> <name>山田</name> <age>15</age> </person> ...
<age>43</age> </person> </root>
""") def test_get_names(self): self.assertEqual(self.config.get_names(), ['山田', '佐藤']) def test_get_ages(self): self.assertEqual(self.config.get_ages(), ['15', '43'])
SpamExperts/SpamPAD
tests/functional/test_plugins/test_uri_eval.py
Python
gpl-2.0
31,989
0.003064
"""Functional tests for URIEval Plugin""" from __future__ import absolute_import import random import sys import unittest from string import ascii_letters from string import digits import tests.util # Load plugin and report matched RULES and SCORE PRE_CONFIG = """ loadplugin oa.plugins.uri_eval.URIEvalPlugin repor...
def test_check_for_http_redirector_links_combined(self): email = """From: sender@example.com \nhttp://utility.baidu.com/t
raf/click.php?id=215&urlhttps://log0.wordpress.com""" self.setup_conf(config=CONFIG, pre_config=PRE_CONFIG) result = self.check_pad(email) self.check_report(result, 1, ['CHECK_FOR_HTTP_REDIRECTOR']) def test_check_for_http_redirector_no_http(self): email = """From: sender@example...
levilucio/SyVOLT
UMLRT2Kiltera_MM/Properties/from_thesis/HMM4_then1_IsolatedLHS.py
Python
mit
2,493
0.01083
from core.himesis import Himesis, HimesisPreConditionPatternLHS import uuid class HMM4_then1_IsolatedLHS(HimesisPreConditionPatternLHS): def __init__(self): """ Creates the himesis graph representing the AToM3 model HMM4_then1_IsolatedLHS. """ # Flag this instanc...
after the nodes in the LHS have been matched. # You can access a matched node labelled n by: PreNode('n'). # To access attribute x of node n, use: PreNode('n')['x']. # The given constraint must evaluate to a boolean expression: # returning True enables the rule to be applied, # returning False forbids the rule f...
========================================================================= return True """ self["name"] = """""" self["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'MM4_then1') # Set the node attributes # Add the attribute equations ...
deepmind/xmanager
xmanager/cli/cli.py
Python
apache-2.0
2,310
0.005195
# Copyright 2021 DeepMind Technologies Limited # # 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 agr...
raise app.UsageError( f'Subcommand `{cmd} {subcmd}` is not a supported subcommand') else: raise app.UsageError(f'Command `{cmd}` is not a supported command') def entrypoint(): app.run(main) if __na
me__ == '__main__': app.run(main)
surajssd/kuma
kuma/wiki/views/misc.py
Python
mpl-2.0
6,940
0.000144
# -*- coding: utf-8 -*- import newrelic.agent from tower import ugettext_lazy as _lazy, ugettext as _ from django.contrib import messages from django.db.models import Q from django.http import HttpResponseBadRequest, JsonResponse from django.shortcuts import get_object_or_404, redirect, render from django.views.decora...
lowed_tags': ' '.join(ALLOWED_TAGS), } return render(request, 'wiki/ckeditor_config.js', context, content_type='application/x-javascript
') @block_user_agents @require_GET @allow_CORS_GET @newrelic.agent.function_trace() def autosuggest_documents(request): """ Returns the closest title matches for front-end autosuggests """ partial_title = request.GET.get('term', '') locale = request.GET.get('locale', False) current_locale = re...
bparzella/secsgem
secsgem/secs/functions/s12f18.py
Python
lgpl-2.1
2,601
0
##################################################################### # s12f18.py # # (c) Copyright 2021, Benjamin Parzella. All rights reserved. # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Fou...
>>> secsgem.secs.func
tions.SecsS12F18 { MID: A/B[80] IDTYP: B[1] DATA: [ { XYPOS: I1/I2/I4/I8[2] BINLT: U1/A } ... ] } **Example**:: >>> import secsgem.secs >>> secsge...
pdxwebdev/yadapy
yada/lib/python2.7/site-packages/py/_code/_py2traceback.py
Python
gpl-3.0
2,765
0.001808
# copied from python-2.7.3's traceback.py # CHANGES: # - some_str is replaced, trying to create unicode strings # import types def format_exception_only(etype, value): """Format the exception part of a traceback. The arguments are the exception type and value such as given by sys.last_type and sys.last_va...
sage indicating which exception occurred is always the last string in the list. """ # An instance should not have a meaningful value parameter, but # sometimes does, particularly for string exceptions, such as # >>> raise string1, string2 # deprecated # # Clear these out first because iss...
problem. if (isinstance(etype, BaseException) or isinstance(etype, types.InstanceType) or etype is None or type(etype) is str): return [_format_final_exc_line(etype, value)] stype = etype.__name__ if not issubclass(etype, SyntaxError): return [_format_final_exc_line(stype, ...
lifemapper/core
LmWebServer/common/lmconstants.py
Python
gpl-3.0
13,281
0.000753
"""This module contains constants used by the Lifemapper web services """ import os from LmServer.base.utilities import get_mjd_time_from_iso_8601 from LmServer.common.lmconstants import SESSION_DIR from LmServer.common.localconstants import SCRATCH_PATH, APP_PATH from LmWebServer.common.localconstants import PACKAGIN...
try: # Try processing a string str_val = param.lower().strip() if str_val == 'false' or str_val == 'no': return False if str_val == 'true' or str_val == 'yes':
return True except Exception: pass # Return default if we can't figure it out return default # This constant is used for processing query parameters. If no 'processIn' # key, just take the parameter as it comes in # Note: The dictionary keys are the .lower() version of the...
corydodt/SupperFeed
supperfeed/spoon.py
Python
mit
595
0.001681
from twisted.python import usage fro
m txpx import runner from supperfeed.build import Build class Options(usage.Options): subCommands = [ ("build", None, Build, Build.__doc__), ] def opt_version(self): print 'SupperFeed server v???' return usage.Options
.opt_version(self) def postOptions(self): """Recommended if there are subcommands:""" if self.subCommand is None: self.synopsis = "spoon <subcommand>" raise usage.UsageError("** Please specify a subcommand (see \"Commands\").") run = runner(Options)
andyrgtz/Proyecto-Triples
computer_equipment_control/model/__init__.py
Python
apache-2.0
146
0
fr
om . import usuario from . import equipo_cambio from . import equipo_computo from . import sucursales from . import
depto from . import usuario
chouseknecht/ansible
lib/ansible/modules/cloud/vmware_httpapi/vmware_appliance_health_info.py
Python
gpl-3.0
4,064
0.001476
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2019, Paul Knight <paul.knight@delaware.gov> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = { 'metadata_...
ribute: description: facts about the specified health attribute returned: always type: dict sample: { "value": true } ''' from ansible.module_utils.vmware_httpapi.VmwareRestModule i
mport API, VmwareRestModule SLUG = dict( applmgmt='/health/applmgmt', databasestorage='/health/database-storage', load='/health/load', mem='/health/mem', softwarepackages='/health/software-packages', storage='/health/storage', swap='/health/swap', system='/health/system', lastcheck...
krukmat/docker-rest-django
website/urls.py
Python
cc0-1.0
1,192
0.001678
"""composeexample URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Cl...
ickets_calendar.views import EventDiscoveryViewSet router = routers.DefaultRouter() router.register(r'event_discovery', EventDiscoveryViewSet) # Wire up our API using autom
atic URL routing. # Additionally, we include login URLs for the browsable API. urlpatterns = [ url(r'^', include(router.urls)), url(r'^admin/', admin.site.urls), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) ]
zepheira/pybibframe
lib/reader/marcxml.py
Python
apache-2.0
7,428
0.006058
''' For processing MARC/XML Uses SAX for streaming process Notice however, po
ssible security vulnerabilities: https://docs.python.org/3/library/xml.html#xml-vulnerabilities ''' import re from collections import defaultdict, OrderedDict import unicodedata import warnings import xml.parsers.expat from versa import I, VERSA_BASEIR
I, ORIGIN, RELATIONSHIP, TARGET, ATTRIBUTES from versa import util from bibframe.reader import marc MARCXML_NS = marc.MARCXML_NS # valid subfield codes VALID_SUBFIELD_PAT = re.compile(r'[a-zA-Z0-9\-]$') # validates tags in URL form IS_VALID_TAG = lambda t: len(t.rsplit('/',1)[-1]) == 3 NSSEP = ' ' class expat_cal...
nharraud/b2share
invenio/b2share/b2share_api.py
Python
gpl-2.0
10,207
0.002351
# -*- coding: utf-8 -*- # B2SHARE2.api.py from __future__ import absolute_import # The current user is implicitly used throughout the API from flask.login import current_user # TODO: # - versioning of community, schema, records: # - schemas change to new schemas with new ids # - records change to new v...
_state are not changeable. Automatically creates a new record version.""" pass def change_state(self, new_state, reason): """ Changes the i
nternal record_status field and triggers other events accordingly: if submitted inform the admin for review, if rejected inform the owner. Automatically creates a new record version.""" pass def get_reference_list(self): """Returns a ReferenceList object describi...
louispotok/pandas
pandas/tests/io/json/test_ujson.py
Python
bsd-3-clause
56,148
0.000232
# -*- coding: utf-8 -*- try: import json except ImportError: import simplejson as json import math import pytz import pytest import time import datetime import calendar import re import decimal import dateutil from functools import partial from pandas.compat import range, zip, StringIO, u import pandas._libs.j...
output = ujson.encode(input, **encode_kwargs) assert input == json.loads(output) assert output == e
xpected_output assert input == ujson.decode(output) # Default behavior assumes encode_html_chars=False. helper(not_html_encoded, ensure_ascii=True) helper(not_html_encoded, ensure_ascii=False) # Make sure explicit encode_html_chars=False works. helper(not_html_encod...
BrandonYates/sherlock
Python/Clue/Room.py
Python
gpl-3.0
1,517
0.010547
#/usr/bin/python class Room(Card): _roomId = None def __init__(self, ID, label, roomId): self._id = ID self._label = label self.cardType = CardType(CardType.room) self._roomId = RoomName(roomId) def __str__(self): return ''.join(( "id: ", se...
try: index = int(name) except ValueError: index = getRoomNameIndex(name) if index > 0 and index
< 3: self._roomName = _names.get(index) return True else: return False @staticmethod def getRoomNameIndex(x): return { "HALL" : 0, "LOUNGE" : 1, "DININGROOM" : 2, "KITCHEN" : 3, "BALLROOM" :...
jonparrott/gcloud-python
dlp/noxfile.py
Python
apache-2.0
3,018
0.000331
# Copyright 2017, Google 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/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
x.session(python=['2.7'
, '3.5', '3.6', '3.7']) def unit(session): """Run the unit test suite.""" default(session) @nox.session(python=['2.7', '3.6']) def system(session): """Run the system test suite.""" if not os.environ.get('GOOGLE_APPLICATION_CREDENTIALS', ''): session.skip('Credentials must be set via environm...
Xinglab/rPGA
src/rPGA/scripts/splicing.py
Python
gpl-2.0
42,017
0.03927
#!/python # Copyright (C) 2015 University of California, Los Angeles (UCLA) # Shayna R. Stein, Emad Bahrami-Samani, Yi Xing # # Authors: Shayna R. Stein, Emad Bahrami-Samani, Yi Xing # # This program is free software: you can redistribute it and/or modify it under # the terms of the GNU General Public License as publi...
# get effective lengths tS = int(ele[5]); tE = int(ele[6]
); ## target exon coord uS = int(ele[7]); uE = int(ele[8]); ## upstream exon coord dS = int(ele[9]); dE = int(ele[10]); ## downstream exon coord tLen=min(tE-tS,self.junctionLength/2); ## target exon length uLen=min(uE-uS,self.junctionLength/2); ## upstream exon length dLen=min(dE-dS,self....
morelab/c4a_data_repository
RestApiInterface/src/packActivityRecognition/pattern_model_matching.py
Python
gpl-3.0
29,421
0.008838
# -*- coding: utf-8 -*- import sys, getopt import time, datetime import logging import numpy as np import pandas as pd import json import itertools from expert_activity_model import ExpertActivityModel from Pattern import Pattern from Cluster import Cluster from LogReader import LogReader from ad_pattern_filter impo...
rn and cluster lists self.patternlist = [] self.clusterlist = [] # Attribute to store a dict of eam indices and all their possible combinations self.eamcombinations = {} # For the maximization problem, build already all the combinations of EAM # indices e...
for i in eamindex: # eams = list(itertools.combinations(eamindex, i)) self.eamcombinations[i] = list(itertools.combinations(eamindex, i + 1)) # print i # print self.eamcombinations[i] # print '-----------------------------------' # TODO consider to...
iaddict/mercurial.rb
vendor/mercurial/hgext/gpg.py
Python
mit
9,365
0.001708
# Copyright 2005, 2006 Benoit Boissinot <benoit.boissinot@ens-lyon.org> # # This software may be used and distributed according to the terms of the # GNU General Public License version 2 or any later version. '''commands to sign and verify changesets''' import os, tempfile, binascii from mercurial import util, comman...
rimary key fingerprint = l.split()[10] elif (l.startswith("GOODSIG") or
l.startswith("EXPSIG") or l.startswith("EXPKEYSIG") or l.startswith("BADSIG")): if key is not None: keys.append(key + [fingerprint]) key = l.split(" ", 2) fingerprint = None if err: return ...
rehandalal/therapist
therapist/messages.py
Python
mpl-2.0
2,098
0.003813
NOT_GIT_REPO_MSG =
"#{red}Not a git repository (or any of the parent directories)" HOOK_ALREADY_INSTALLED_MSG = "The pre-commit hook has already been installed." EXISTING_HOOK_MSG = ( "#{yellow}There is an existing pre-commit hook.\n" "#{reset_all}Therapist can preserve this legacy hook and run it before the Therapist " "p...
VE_LEGACY_HOOK_MSG = "Would you like to preserve this legacy hook?" COPYING_HOOK_MSG = "Copying `pre-commit` to `pre-commit.legacy`...\t" DONE_COPYING_HOOK_MSG = "#{green}#{bright}DONE" CONFIRM_REPLACE_HOOK_MSG = "Do you want to replace this hook?" INSTALL_ABORTED_MSG = "Installation aborted." INSTALLING_HOOK_MSG ...
KamilKwiatkowski123/Repozytorium
recipe-580709-1.py
Python
gpl-3.0
4,433
0.001128
#! /usr/bin/env python # -*- coding: utf-8 -*- # <https://code.activestate.com/recipes/580709-lines-of-code-loc/> # Basic Lines-Of-Code counter in Python source files, rep
orting the # number of blank, comment and source code lines and total number of # lines in all Python files scanned. # Usage example:
# % python locs.py -rec ~/Projects # 8691 *.py files: 365038 blank (14.0%), 212100 comment (8.1%), # 2030198 source (77.9%), 2607336 total lines # (2.739 secs, 951872 lines/sec) # % python3 locs.py -rec ~/Projects # 8691 *.py files: 365037 blank (14.0%), 212100 comment (8.1%), # ...
Mariusz1970/enigma2
Navigation.py
Python
gpl-2.0
12,222
0.024464
from time import time from os import path from enigma import eServiceCenter, eServiceReference, eTimer, pNavigation, getBestPlayableServiceReference, iPlayableService from Components.ParentalControl import parentalControl from Components.config import config from Tools.BoundFunction import boundFunction from Tools.StbH...
rint"[NAVIGATION] timediff=%s" % abs(self.PowerTimer.getNextPowerManagerTime() - time()) f = open("/tmp/was_powertimer_wakeup", "w") f.write('1') f.close()
self.gotostandby() else: if self.syncCount <= 24 and time() <= 31536000: # max 2 mins or when time is in sync self.timesynctimer.start(5000, True) else: print"[NAVIGATION] No Recordings/PowerTimers found, end work-around" if self.nextRecordTimerAfterEventActionAuto: print"[NAVIGATION] wasTimerWa...
elastic-coders/aiohttp
tests/test_urldispatch.py
Python
apache-2.0
36,992
0.000108
import asyncio import os import pathlib import re import unittest from collections.abc import Sized, Container, Iterable, Mapping, MutableMapping from unittest import mock from urllib.parse import unquote from multidict import CIMultiDict import aiohttp.web from aiohttp import hdrs from aiohttp.web import (UrlDispatche...
_until_complete(self.router.resolve(req)) self.assertIsNotNone(info1) self.assertIs(route, info1.route) req = self.make_request('POST', '/') info2 = self.loop.run_until_complete(self.router.resolve(req))
self.assertIsNotNone(info2) self.assertIs(info1.route, info2.route) def test_match_second_result_in_table(self): handler1 = self.make_handler() handler2 = self.make_handler() self.router.add_route('GET', '/h1', handler1) self.router.add_route('POST', '/h2', handler2) ...
alberts/check_mk
web/htdocs/bi.py
Python
gpl-2.0
76,013
0.00717
#!/usr/bin/python # -*- encoding: utf-8; py-indent-offset: 4 -*- # +------------------------------------------------------------------+ # | ____ _ _ __ __ _ __ | # | / ___| |__ ___ ___| | __ | \/ | |/ / | # | | | | '_ \ / _ \/ __| |/ /...
else: group_names.add(a[0]) group_names = list(group_names) else
: # classic mode: precompile all and display only groups with members compile_forest(config.user_id) group_names = list(set([ group for group, trees in g_user_cache["forest"].items() if trees ])) return sorted(group_names, cmp = lambda a,b: cmp(a.lower(), b.lower())) def log(s): if com...
MuckRock/muckrock
muckrock/core/autocomplete.py
Python
agpl-3.0
1,730
0
"""Customized autocomplete widgets""" # Standard Library import re # Third Party from dal import autocomplete # MuckRock from muckrock.jurisdiction.models import Jurisdiction class MRSelect2Mixin:
"""MuckRock Model Select2 mixin""" def __init__(self, *args, **kwargs): attrs = { "data-html": True, "data-dropdown-css-class": "select2-dropdown", "data-width": "100%", } attrs.update(kwargs.pop("attrs", {})) super().__init__(*args, attrs=attr...
er(self, selected_choices): """Filter out non-numeric choices""" selected_choices = [c for c in selected_choices if c.isdecimal()] return super().filter_choices_to_render(selected_choices) class ModelSelect2(MRSelect2Mixin, autocomplete.ModelSelect2): """MuckRock Model Select2""" class M...
ghowland/rpg
rpg_operation.py
Python
mit
2,007
0.017439
#!/usr/bin/env python """ RPG: Operation These are any operations we want to carry out from our YAML files. Operations are strings that are tied to Python code, to carry out things that arent possible to easily make YAML tags for directly. """ from rpg_log import Log import rpg_combat def HandleOp...
peration, data): """Handle the operation. Args: game: Game object operation: string, name of the operation to look up data: dict, data at the level the operation was specified in, which may contain information the operation needs to operat
e. Operation specific. """ # Pay for a room's night sleep if operation == 'RoomSleepPay': Log('RoomSleepPay: You are rested!') # Max up the player's current health #NOTE(g): Uses a percentage based increase from the game data. If not # present, assume full recovery. modifier ...
bluegenes/MakeMyTranscriptome
scripts/tasks_v2.py
Python
bsd-3-clause
26,656
0.002026
import os import sys import time import signal import subprocess import warnings import platform def time_to_hms(delta): ''' Convert some time in seconds to a tuple of (hours, minutes, seconds). ''' m, s = divmod(delta, 60) h, m = divmod(m, 60) return (h, m, s) def check_foregro...
f, command, dependencies=[], targets=[], cpu=1, name='Anonymous_Task', stderr=None, stdout=None, error_check=not_zero, max_wall_time=float('inf')): ''' The __init__ for the Task object has nine parameters described below: command - a string representation of the cmd line co...
a list containing Task objects, Supervisor objects, or unit functions. A call to self.checkDependencies will return True if and only if all Task objects in dependencies are finished, all Supervisor objects in dependencies are finished, and all unit f...
rezoo/chainer
tests/chainer_tests/functions_tests/math_tests/test_logarithm_1p.py
Python
mit
1,946
0
import unittest import numpy import chainer from chainer.backends import cuda import chainer.functions as F from chainer import gradient_check from chainer import testing from chainer.testing import attr @testing.parameterize(*testing.product({ 'shape': [(), (3, 2)], })) class Log1pFunctionTest(unittest.TestCas...
shape).astype(numpy.float32) def check_forward(self, x_data): x = chainer.Variable(x_data) y = F.log1p(x) testing.assert_allclose( numpy.log1p(self.x), y.data, atol=1e-7, rtol=1e-7) def test_log1p_forward_cpu(self): self.check_forward(self.x) @attr.gpu def ...
elf): self.check_forward(cuda.to_gpu(self.x)) def check_backward(self, x_data, y_grad): gradient_check.check_backward(F.log1p, x_data, y_grad, dtype='d') def test_log1p_backward_cpu(self): self.check_backward(self.x, self.gy) @attr.gpu def test_log1p_backward_gpu(self): ...
ResilientScience/wot
setup.py
Python
bsd-2-clause
720
0.001389
from pip.req import parse_requirements try: from setuptools import setup except ImportError: from distutils.core import se
tup # parse_requirements() returns generator of pip.req.InstallRequirement objects install_reqs = parse_requirements("requirements.txt") # reqs is a list of requirement reqs = [str(ir.req) for ir
in install_reqs] setup(name="wot", description="generating context-free grammars of content", author="Resilient Science, Inc.", author_email="info@resilientscience.com", url="http://resilientscience.github.io/wot/", version="0.1", scripts=[], packages=["wot", "wot.sequitur", ...
jericks/geoscript-py
geoscript/style/label.py
Python
mit
4,163
0.013452
from geoscript.style import util from geoscript.style.expression import Expression from geoscript.style.font import Font from geoscript.style.fill import Fill from geoscript.style.halo import Halo from geoscript.style.color import Color from geoscript.style.property import Property from geoscript.style.symbolizer impor...
on(offset).expr) lp.setAligned(align) #lp.setRepeated(repeat) if gap: lp.setGap(Expression(gap).expr) if igap: lp.setInitialGap(Expression(igap).expr) self._placement = lp self.options = {'followLi
ne': follow, 'group': group} if displace: self.options['maxDisplacement'] = displace if repeat: self.options['repeat'] = repeat return self def _prepare(self, rule): syms = util.symbolizers(rule, TextSymbolizer) for sym in syms: self._apply(sym) def _apply(self, sym): Sym...
baklanovp/pystella
pystella/rf/star.py
Python
mit
7,789
0.00077
import numpy as np from pystella.rf import Band from pystella.rf.rad_func import Flux2MagAB from pystella.util.phys_var import phys __author__ = 'bakl' class Star: def __init__(self, name, spec=None, is_flux_eq_luminosity=False): """Creates a Star with Spectrum instance. Required parameters: name.""" ...
p - band_o.zp return kcor @staticmethod def flux_to_redshift(flux, z): if z <= 0.: return flux flux_z = flux * (1.+z) # flux_z = flux / (1.+z) # flux_z = flux # flux_z = np.interp(freq / (1.
+ z), freq[::-1], flux[::-1]) return flux_z
alekseik1/python_mipt_study_1-2
2sem/great_control_work/F.py
Python
gpl-3.0
285
0.035088
n = int(input()) l = [[] for x in range(n)] for i in range(n): l[i] = [int(x) for x in input().split()] if n == 3 and l == [[0,0,1],[0,0,1],[1,0,0]]: print('NO') exit(0) for i in range(n): if l[i][n-i-1] != l[n-i-1][i]
: print('NO') exit(
0) print('YES')
pra85/calibre
src/calibre/ebooks/docx/names.py
Python
gpl-3.0
4,127
0.007996
#!/usr/bin/env python # vim:fileencoding=utf-8 from __future__ import (unicode_literals, division, absolute_import, print_function) __license__ = 'GPL v3' __copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>' import re from lxml.etree import XPath as X from calibre.utils.filenames im...
, attr, default=None): return x.attrib.get(expand(attr), default) def ancestor(elem, name): try: return XPath('ancestor::%s[1]' % name)(elem)[0] except IndexError: return None def generate_anchor(name, existing): x = y = 'id_' + re.sub(r'[^0-9a-zA-Z_]', '', ascii_text(name)).lstrip('_'...
:%s' % a for a in args))(elem) def descendants(elem, *args): return XPath('|'.join('descendant::%s' % a for a in args))(elem)
abdesslem/malwareHunter
web/controller/beaker/crypto/pycrypto.py
Python
gpl-2.0
970
0.001031
"""Encryption module that uses pycryptopp or pycrypto""" try: # Pycryptopp is preferred over Crypto because Crypto has had # various periods of not being maintained, and
pycryptopp uses # the Crypto++ library which is generally considered the 'gold standard' # of crypto implementations from pycryptopp.cipher import aes def aesEncrypt(data, key): cipher = aes.AES(key) return cipher.process(data) # magic. aesDecrypt = aesEncrypt except ImportEr...
counter=Counter.new(128, initial_value=0)) return cipher.encrypt(data) def aesDecrypt(data, key): cipher = AES.new(key, AES.MODE_CTR, counter=Counter.new(128, initial_value=0)) return cipher.decrypt(data) def getKeyLength(): return 32
carsongee/edx-platform
common/lib/xmodule/xmodule/open_ended_grading_classes/self_assessment_module.py
Python
agpl-3.0
11,892
0.001766
import json import logging from lxml import etree from xmodule.capa_module import ComplexEncoder from xmodule.progress import Progress from xmodule.stringify import stringify_children import openendedchild from .combined_open_ended_rubric import CombinedOpenEndedRubric log = logging.getLogger("edx.courseware") cla...
ent>
""" TEMPLATE_DIR = "combinedopenended/selfassessment" # states INITIAL = 'initial' ASSESSING = 'assessing' REQUEST_HINT = 'request_hint' DONE = 'done' def setup_response(self, system, location, definition, descriptor): """ Sets up the module @param system: Modul...
amwelch/a10sdk-python
a10sdk/core/vlan/vlan_global.py
Python
apache-2.0
1,226
0.009788
from a10sdk.common.A10BaseClass import A10BaseClass class VlanGlobal(A10BaseClass): """Class Description:: Configure global options for vlan. Class vlan-global supports CRUD Operations and inherits from `common/A10BaseClass`. This class is the `"PARENT"` class for this module.` :param l3_vl...
xy for REST operations and session handling. Refer to `common/device_proxy.py` URL for this object:: `https://<Hostname|Ip address>//axapi/v3/vlan-global`. """ def __init__(self,
**kwargs): self.ERROR_MSG = "" self.required=[] self.b_key = "vlan-global" self.a10_url="/axapi/v3/vlan-global" self.DeviceProxy = "" self.l3_vlan_fwd_disable = "" self.enable_def_vlan_l2_forwarding = "" for keys, value in kwargs.items(): set...
pwong-mapr/private-hue
tools/app_reg/build.py
Python
apache-2.0
1,864
0.013948
#!/usr/bin/env python # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you ma...
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 O
R CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Helpers to build the apps """ import logging import os import subprocess import common LOG = logging.getLogger(__name__) def runcmd(cmdv, additional_env=No...
google/google-ctf
third_party/edk2/AppPkg/Applications/Python/Python-2.7.2/Tools/scripts/ifdef.py
Python
apache-2.0
3,829
0.003656
#! /usr/bin/env python # Selectively preprocess #ifdef / #ifndef statements. # Usage: # ifdef [-Dname] ... [-Uname] ... [file] ... # # This scans the file(s), looking for #ifdef and #ifndef preprocessor # commands that test for one of the names mentioned in the -D and -U # options. On standard output it write...
) == 2: if keyword == 'ifdef': ko = 1 else: ko = 0 word = words[1] if word in defs: stack.append((ok, ko, word)) if not ko: ok = 0 elif word in undefs: stack.append((ok, ...
-1, word)) if ok: fpo.write(line) elif keyword == 'if': stack.append((ok, -1, '')) if ok: fpo.write(line) elif keyword == 'else' and stack: s_ok, s_ko, s_word = stack[-1] if s_ko < 0: if ok: fpo.write(line) ...
open-machine-learning/mldata
repository/views/publication.py
Python
gpl-3.0
2,214
0.001807
from django.core import serializers from django.core.urlresolvers import reverse from django.db import transaction from django.http import HttpResponse from django.http import HttpResponseRedirect from repository.forms import * from repository.models import * @transaction.commit_on_success def edit(request): """E...
orm(request.POST) else: form = PublicationForm(request.POST) if form.is_valid(): if not pub: pub = Publication() pub.content = form.cleaned_data['content'] pub.title = form.cleaned_data['title'] pub.save() return Ht...
pResponseRedirect(reverse('repository_index')) def get(request, id): """AJAX: Get publication specified by id. @param request: request data @type request: Django request @param id: id of item to edit @type id: integer @return: publication content in response page @rtype: Django response ...
wwright2/dcim3-angstrom1
sources/openembedded-core/scripts/lib/wic/3rdparty/pykickstart/commands/partition.py
Python
mit
11,515
0.001911
# # Chris Lumens <clumens@redhat.com> # # Copyright 2005, 2006, 2007, 2008 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, modify, # copy, or redistribute it subject to the terms and conditions of the GNU # General Public License v.2. This program is distributed in the hope that...
self, *args, **kwargs) self.bytesPerInode = kwargs.get("by
tesPerInode", 4096) self.fsopts = kwargs.get("fsopts", "") self.label = kwargs.get("label", "") def _getArgsAsStr(self): retval = FC3_PartData._getArgsAsStr(self) if hasattr(self, "bytesPerInode") and self.bytesPerInode != 0: retval += " --bytes-per-inode=%d" % self.byt...
leiyangyou/Arpeggio
tests/unit/regressions/issue_20/test_issue_20.py
Python
mit
827
0.003636
# -*- coding: utf-8 -*- ####################################################################### # Name: test_optional_in_choice # Purpose: Optional matches
always succeds but should not stop alternative # probing on failed match. # Author: Igor R. Dejanović <igor DOT dejanovic AT gmail DOT com> # Copyright: (c) 2015 Igor R. Dejanović <igor DOT dejanovic AT gmail DOT com> # License: MIT License #####################################################################...
ammar from arpeggio import ParserPython, Optional, EOF def g(): return [Optional('first'), Optional('second'), Optional('third')], EOF def test_optional_in_choice(): parser = ParserPython(g) input_str = "second" parse_tree = parser.parse(input_str) assert parse_tree is not None
elopezga/ErrorRate
ErrorRate/crosstalkpacketloss.py
Python
mit
2,801
0.042842
#Packetloss measurement with the FPGA + OSA crosstalk reading on new switch from structureFiling import * import LivePCAPReader as PCAPReader from sys import argv script, filename = argv; def main(): #now time to read in some of the initial configurations #might not need this since we can save the configurati...
n.diconGP700("TCPIP::192.168.1.201::gpib0,3::INST
R")#this is the dicon switch Oscope = DataCollector_agilentDSA91304A("TCPIP::192.168.1.202::INSTR", directory) #oscope #Now to set the configurations #Osa.driver._write('*RCL setup.set') #this needs to be changed to the name of the config settings #Oscop.driver._write(':disk:load snapshot.set') #will also ne...
appknox/xysec_adb
xysec_adb/pylib/device/adb_wrapper_test.py
Python
apache-2.0
2,716
0.006996
# Copyright 2013 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. """Tests for the AdbWrapper class.""" import os import tempfile import time import unittest from pylib.device import adb_wrapper from pylib.device import d...
...' while 'package:' not in self._adb.Shell('pm path android'): time.sleep(1) def testRootRemount(self): self._adb.Root() while True: try: self._
adb.Shell('start') break except device_errors.AdbCommandFailedError: time.sleep(1) self._adb.Remount() if __name__ == '__main__': unittest.main()
adaptive-learning/flocs-web
practice/permissions.py
Python
gpl-3.0
567
0.001764
from rest_framework import permissions class IsAdminOrOwnerPostAnyone(permissions.BasePermission): def has_object_permissio
n(self, request, view, obj): """ Limit access to exact instances, owners can access only their instances. """ if not request.user: return False elif request.user.is_staff: return True elif hasattr(obj, 'user'): return request.user == ob...
return False
nfsli926/stock
python/com/nfs/helloworld.py
Python
apache-2.0
3,988
0.019184
# coding=utf-8 __author__ = 'litao' # -*- coding:utf-8 -*- import urllib import urllib2 import re import thread import time class QSBK: def __init__(self): self.pageIndex = 1 self.user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' self.headers = { 'User-Agent' : self.user_age...
able = True #先加载一页内容 self.loadPage() #局部变量,控制当前读到了第几页 nowPage = 0 while self.enable
: if len(self.stories)>0: #从全局list中获取一页的段子 pageStories = self.stories[0] #当前读到的页数加一 nowPage += 1 #将全局list中第一个元素删除,因为已经取出 del self.stories[0] #输出该页的段子 self.getOneStory(pageStories,n...
zachpodbielniak/PodNet
Linux/Python/CClock.py
Python
gpl-3.0
4,740
0.010338
''' ____ _ _ _ _ _ ____ ___ | _ \ ___ __| | \ | | ___| |_ / \ | _ \_ _| | |_) / _ \ / _` | \| |/ _ \ __| / _ \ | |_) | | | __/ (_) | (_| | |\ | __/ |_ / ___ \| __/| | |_| \___/ \__,_|_| \_|\___|\__| /_/ \_\_| |___| File: CClock.py Author: Zach Podbieln...
GLONG(x) return PodNetLib.ClockAndGetSeconds(byref(s)) def ClockAndGetSecondsFloat(x): s = ULONGLONG(x)
return PodNetLib.ClockAndGetSecondsFloat(byref(s)) def CreateTimeSpec(MilliSeconds): s = TIMESPEC() PodNetLib.CreateTimeSpec(byref(s), MilliSeconds) return s def CreateTimeSpecNano(NanoSeconds): s = TIMESPEC() PodNetLib.CreateTimeSpecNano(byref(s), NanoSeconds) re...
mxtthias/mcomix
mcomix/thumbbar.py
Python
gpl-2.0
15,561
0.002313
"""thumbbar.py - Thumbnail sidebar for main window.""" import urllib import Queue import gtk import gobject import threading from mcomix.preferences import prefs from mcomix import image_tools from mcomix import tools from mcomix import constants from mcomix imp
ort callback class ThumbnailSidebar(gtk.HBox): """A thumbnail sidebar including scrollbar for the main window.""" def __init__(self
, window): gtk.HBox.__init__(self, False, 0) self._window = window # Cache/thumbnail load status self._loaded = False self._is_loading = False self._stop_cacheing = False # Caching threads self._cache_threads = None self._currently_selected_page ...
ivanalejandro0/keymanager
src/leap/keymanager/__init__.py
Python
gpl-3.0
16,455
0.000122
# -*- coding: utf-8 -*- # __init__.py # Copyright (C) 2013 LEAP # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Th...
d_private} is True, then the private key is
encrypted with C{password} and sent to server in the same request, together with a hash string of user's address and password. The encrypted private key will be saved in the server in a way it is publicly retrievable through the hash string. :param ktype: The type of the key. ...
prometheanfire/openstack-guest-agents-unix
nova-agent.py
Python
apache-2.0
1,284
0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright (c) 2011 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 co
py 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 # Li...
GlauberGoncalves/Python
Lista PythonBrasil/exer08.py
Python
mit
378
0.005391
#
Faça um Programa que pergunte quanto você ganha por hora # e o número de horas trabalhadas no mês. Calcule e mostre o # total do seu salário no referido mês. salarioXhoras = float(input('Quanto voce ganha por hora? ')) hor
as = float(input('Quantas horas trabalhadas? ')) salario = horas * salarioXhoras print('Voce ganhará %2.f de salario esse mes' %(salario))
google/init2winit
init2winit/dataset_lib/ogbg_molpcba.py
Python
apache-2.0
8,040
0.00709
# coding=utf-8 # Copyright 2022 The init2winit 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 la...
iplier, hps.max_edges_multiplier), num_batches) def valid_epoch(num_batches=None): return itertools.islice( _get_batch_iterator( iter(valid_ds), eval_batch_size, hps.max_nodes_multiplier, hps.max_edges_multiplier), num_batches) def test_epoch(num_batches=None):
return itertools.islice( _get_batch_iterator( iter(test_ds), eval_batch_size, hps.max_nodes_multiplier, hps.max_edges_multiplier), num_batches) return Dataset(train_iterator_fn, eval_train_epoch, valid_epoch, test_epoch)
mahim97/zulip
zerver/tornado/exceptions.py
Python
apache-2.0
447
0.002237
from typing import Text from django.utils.translation import ugettext as _ from zerver.lib.exceptions import ErrorCode, JsonableError class BadEventQueueI
dError(JsonableError): code = ErrorCode.BAD_EVENT_QUEUE_ID data_fields = ['queue_id'] def __init__(self, queue_id: Text) -> None: self.queue_id = queue_id # type: Text @staticmethod def msg_format() -
> Text: return _("Bad event queue id: {queue_id}")
jhermann/cookiecutter
cookiecutter/main.py
Python
bsd-3-clause
3,903
0
#!/usr/bin/env python # -*- coding: utf-8 -*- """ cookiecutter.main ----------------- Main entry point for the `cookiecutter` command. The code in this module is also a good example of how to use Cookiecutter as a library rather than a script. """ from __future__ import unicode_literals import logging import os fro...
(context
, no_input) # Add some system values, especially for use by hook scripts now = datetime.now() context.update(extra_globals or {}) context.update(dict( version=cookiecutter_version, repo_dir=os.path.abspath(repo_dir), context_file=os.path.abspath(context_file), current_ye...
Dejust/flask-base
app/models/common.py
Python
gpl-3.0
155
0
""" Здесь могут быть определены любые модели SQLAlchemy """ from fla
sk_sqlalchemy import
SQLAlchemy DB = SQLAlchemy()
KDE/printer-applet
debug.py
Python
gpl-2.0
1,703
0.024075
#!/usr/bin/env python ## Copyright (C) 2008 Red Hat, Inc. ## Copyright (C) 2008 Tim Waugh <twaugh@redhat.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 of the License...
gprint ("Caught %s exception. Traceback:" % type) (type, value, tb) = sys.exc_info () tblast = traceback.extract_tb (tb, limit=None) if len (tblast): tblast =
tblast[:len (tblast) - 1] extxt = traceback.format_exception_only (type, value) for line in traceback.format_tb(tb): debugprint (line.strip ()) debugprint (extxt[0].strip ()) debugprint (end) set_debugging (d)
laurentb/weboob
modules/humanis/__init__.py
Python
lgpl-3.0
885
0
# -*- coding: utf-8 -*- # Copyright(C) 2017 Jean Walrave # # This file is part of a weboob module. # # This weboob module is free software: you can redistribute it and/or m
odify # it under th
e terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This weboob module is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANT...
pybuilder/pybuilder
samples/pybuilder_external_plugin_demo/build.py
Python
apache-2.0
1,076
0
# -*- coding: utf-8 -*- # # This file is part of PyBuilder # # Copyright 2011-2020 PyBuilder Team # # 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...
lugin("python.coverage") use_plugin("python.distutils") name = "pybuilder-extern
al-plugin-demo" version = "1.0" default_task = "publish" @init def set_properties(project): project.set_property("coverage_break_build", False)
cristian99garcia/xjoy
xevents/Xlib/ext/xfixes.py
Python
gpl-3.0
2,944
0.00034
# Xlib.ext.xfixes -- XFIXES extension module # # Copyright (C) 2010-2011 Outpost Embedded, LLC # Forest Bond <forest.bond@rapidrollout.com> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public License # as published by the Free Software F...
m Xlib.protocol import rq extname = 'XFIXES' class QueryVersion(rq.ReplyRequest): _reque
st = rq.Struct(rq.Card8('opcode'), rq.Opcode(0), rq.RequestLength(), rq.Card32('major_version'), rq.Card32('minor_version') ) _reply = rq.Struct(rq.ReplyCode(), rq.Pad(...
juan-cb/django-cookie-law
cookielaw/tests.py
Python
bsd-2-clause
1,857
0.001616
import time from django.test import LiveServerTestCase from django.utils.translation import ugettext as _ from selenium import webdriver from selenium.common.exceptions import * class FunctionalTest(LiveServerTestCase): def setUp(self): self.browser = webdriver.Chrome() self.browser.implicitly_w...
ocalhost:8081/') cookielaw_banner = self.browser.find_element_by_id('CookielawBanner') # contains header, paragraph and agree button self.assertIn(_('COOKIE_INFO_HEADER'), cookielaw_banner.text) self.assertIn(_('COOKIE_INFO_PARA'), cookielaw_banner.text) self.assertIn(_('COOK
IE_INFO_OK'), cookielaw_banner.text) # on click of the button, cookie set and banner hidden cookielaw_banner.find_element_by_class_name('btn').click() self.assertFalse(cookielaw_banner.is_displayed()) self.assertEqual(self.browser.get_cookie('cookielaw_accepted')['value'], '1') ...
calancha/DIRAC
Core/Utilities/List.py
Python
gpl-3.0
3,974
0.037494
########################################################################################### # $HeadURL$ ########################################################################################### """Collection of DIRAC useful list related modules. By default on Error they return None. """ __RCSID__ = "$Id$" from t...
List.append( anObject ) def fromChar( inputString, sepChar = "," ): """Generates a list splitting a string by the required character(s) resulting string items are stripped and empty items are removed. :param string inputString: list serialised to string :param string sepChar: separator :retu
rn: list of strings or None if sepChar has a wrong type """ if not ( type( inputString ) in StringTypes and type( sepChar ) in StringTypes and sepChar ): # to prevent getting an empty String as argument return None return [ fieldString.strip() for fieldString in inputString.split( sepCh...
vuolter/pyload
src/pyload/core/datatypes/pypackage.py
Python
agpl-3.0
1,788
0.001119
# -*- coding: utf-8 -*- from ..managers.event_manager import UpdateEvent from ..utils.old import safepath class PyPackage: """ Represents a package object at runtime. """ def __init__(self, manager, id, name, folder, site, password, queue, order): self.m = self.manager = manager sel...
""" return { self.id: { "id": self.id, "name": self.name, "folder": self.folder, "site": self.site, "password": self.password, "queue": self.queue, "order": self.order, "l...
tion about contained links. """ return self.m.get_package_data(self.id)["links"] def sync(self): """ sync with db. """ self.m.update_package(self) def release(self): """ sync and delete from cache. """ self.sync() self.m.r...
iwm911/plaso
plaso/parsers/olecf_plugins/summary.py
Python
apache-2.0
14,885
0.006248
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2014 The Plaso Project Authors. # Please see the AUTHORS file for details on individual 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 L...
reation_time
self._root_modification_time = root_modification_time self._events = [] self.attributes = {} self._InitFromPropertySet(olecf_item.set) def _InitFromPropertySet(self, property_set): """Initializes the object from a property set. Args: property_set: The OLECF property set (pyolecf.property_...
bowlofstew/changes
tests/changes/jobs/test_cleanup_tasks.py
Python
apache-2.0
1,422
0
from __future__ import absolute_import from mock import patch from datetime import datetime from uuid import uuid4 from changes.constants import Status from changes.jobs.cleanup_tasks import cleanup_tasks, CHECK_TIME from changes.models import Task from changes.testutils import TestCase class CleanupTasksTest(Test...
oo': 'bar'}}, ) self.create_task( task_name='cleanup_tasks', task_id=uuid4(), date_created=now, status=Status.finished, ) self.create_task(
task_name='cleanup_tasks', task_id=uuid4(), date_created=old_dt, status=Status.finished, ) cleanup_tasks() mock_delay.assert_called_once_with( 'cleanup_tasks', countdown=5, kwargs={ 'task_id': task.task_i...
tridvaodin/Assignments-Valya-Maskaliova
LPTHW/ex31.py
Python
gpl-2.0
1,470
0.002721
print "You enter a dark room with three doors. Do you go through door #1, door #2 or door #3?" door = raw_input("> ") if door == "1": print "There's a giant bear here eating
a cheese cake. What do you do?" print "1. Take the cake." print "2. Scream at the bear." bear = raw_input("> ") if bear =
= "1": print "The bear eats your face off. Good job!" elif bear == "2": print "The bear eats your legs off. Good job!" else: print "Well, doing %s is probably better. Bear runs away." % bear elif door == "2": print "You stare into the endless abyss at Cthulhu's retina." print...
kyclark/metagenomics-book
python/map/gematria2.py
Python
gpl-3.0
301
0
#!/usr/bin/env python3 """docstring""" import os import sys args = s
ys.argv[1:] if len(args) != 1: print('Usage: {} WORD'.format(os.path.basename(sys.argv[0]))) sys.exit(1) word = args[0] number = 0 for letter in word: number
+= ord(letter) print('"{}" = "{}"'.format(word, number))
mozaiques/zombase
tests/test_worker.py
Python
mit
1,539
0
# -*- coding: utf-8 -*- import unittest from zombase import worker class FakeDbSession(object): def __init__(self): self.has_been_committed = False def commit(self): self.has_been_committed = True class FakeForeman(object): def __init__(self): self._dbsession = FakeDbSession()...
: foreman = FakeForeman() worker.MappingManagingWorker( foreman, managed_sqla_map=FakeMapping, managed_sqla_map_name='fake', ) def test__get(self): foreman = FakeForeman()
a_worker = worker.MappingManagingWorker( foreman, managed_sqla_map=FakeMapping, managed_sqla_map_name='fake', ) a_worker._get(sqla_obj=FakeMapping())
dooferlad/need-input
puke/templatetags/__init__.py
Python
gpl-3.0
25
0
__author__ =
'doof
erlad'
jsjohnst/tornado
tornado/test/websocket_test.py
Python
apache-2.0
14,750
0.000271
from __future__ import absolute_import, division, print_function, with_statement import traceback from tornado.concurrent import Future from tornado import gen from tornado.httpclient import HTTPError, HTTPRequest from tornado.log import gen_log, app_log from tornado.testing import AsyncHTTPTestCase, gen_test, bind_u...
assertEqual(cm.exception.code, 404) @gen_test def test_websocket_http_success(self): with self.assertRaises(WebSocketError)
: yield self.ws_connect('/non_ws') @gen_test def test_websocket_network_fail(self): sock, port = bind_unused_port() sock.close() with self.assertRaises(IOError): with ExpectLog(gen_log, ".*"): yield websocket_connect( 'ws://127...
sdague/home-assistant
tests/components/sensor/test_device_trigger.py
Python
apache-2.0
14,830
0.001146
"""The test for sensor device automation.""" from datetime import timedelta import pytest import homeassistant.components.automation as automation from homeassistant.components.sensor import DOMAIN from homeassistant.components.sensor.device_trigger import ENTITY_TRIGGERS from homeassistant.const import CONF_PLATFORM...
atform.ENTITIES["battery"] assert await async_setup_component( hass, automation.DOMAIN, { automation.DOMAIN: [ { "trigger": { "platform": "device", "domain": DOMAIN, "devi...
vice": "test.automation"}, } ] }, ) assert "must contain at least one of below, above" in caplog.text async def test_if_fires_on_state_above(hass, calls): """Test for value triggers firing.""" platform = getattr(hass.components, f"test.{DOMAIN}") platform.init()...
simonpessemesse/seguinus
programmesStandaloneUtilitaires/ajoutFourniture.py
Python
gpl-2.0
509
0.001965
# coding: utf-8 import configureEnvironne
ment configureEnvironnement.setup() from restaurant.models import Fourniture, Fournisseur fs = Fournisseur.objects.all() for f in fs: print(f.id, ") " + f.nom) res =
input("Entrez le num fournisseur: ") idee = int(res) print(idee) f = Fournisseur.objects.get(id=idee) print(("Choisi: " + f.nom)) res = input("Entrez le prod: ") while len(res) > 2: fourN = Fourniture(nom=res, note=15, fournisseur=f) fourN.save() res = input("Entrez Le prod: ")
PKU-Dragon-Team/Datalab-Utilities
__init__.py
Python
mit
672
0
import json import numpy as np import pandas as pd import numbers class NumpyAndPandasEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, (np.ndarray, np.matrix)): return [self.default(x) for x in obj] if isinstance(obj, pd.DataFrame): return [self.default...
terrows()] if isinstance(obj, pd.Series): return [self.default(val) for _, val in obj.iteritems()] if isinstance(obj, numbers.Integral): return int(obj) if isinstance(obj, (numbers.Real, numbers.Rational)): return float(obj) return s
uper().default(obj)
timothyclemans/checklistsforglass
checklistsforglass/settings.py
Python
apache-2.0
6,341
0.002523
# Django settings for checklistsforglass project. DEBUG = True TEMPLATE_DEBUG = DEBUG import os; os.environ['LANG'] = 'en_US.UTF-8' ADMINS = ( # ('Your Name', 'your_email@example.com'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.
backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': '/home/tim/checklistsforglass/dev.db', # Or path to database file if using sqlite3. 'USER': '',
# Not used with sqlite3. 'PASSWORD': '', # Not used with sqlite3. 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } } # Loc...
sorenh/cc
vendor/Twisted-10.0.0/twisted/scripts/twistd.py
Python
apache-2.0
721
0
# -*- test-case-name: twisted.test.test_twistd -*- # Copyright (c) 2001-2008 Twisted Matrix Laboratories. # See LICENSE for details. """ The Twisted Daemon: platfor
m-independent interface. @author: Christopher Armstrong """ from twisted.application import app from twisted.python.runtime import platformType if platformType == "win32": from twisted.scripts._twistw import ServerOptions, \ WindowsApplicatio
nRunner as _SomeApplicationRunner else: from twisted.scripts._twistd_unix import ServerOptions, \ UnixApplicationRunner as _SomeApplicationRunner def runApp(config): _SomeApplicationRunner(config).run() def run(): app.run(runApp, ServerOptions) __all__ = ['run', 'runApp']
Pharaoh00/Pharaoh-Toolkit
oldVersions/testPass.py
Python
mit
363
0.030303
import random, string import sys print("Password Generator\n") userInput = input("Qual o tamanho da sua senha? ") def passGen(x): if us
erInput.isdigit(): specialsChar =".-_+*&#$@!%" letterStore = strin
g.ascii_letters + string.digits + specialsChar print("".join(random.sample(letterStore, int(x) ))) else: print("Somente numeros") passGen(userInput)
Azure/azure-sdk-for-python
sdk/databoxedge/azure-mgmt-databoxedge/azure/mgmt/databoxedge/v2019_08_01/aio/operations/_jobs_operations.py
Python
mit
4,734
0.004014
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
/Data Box Gateway device. Get
s the details of a specified job on a Data Box Edge/Data Box Gateway device. :param device_name: The device name. :type device_name: str :param name: The job name. :type name: str :param resource_group_name: The resource group name. :type resource_group_name: str ...
knuu/competitive-programming
atcoder/abc/abc154_f.py
Python
mit
558
0
mod = 10 ** 9+7 def inv(x): return pow(x, mod - 2, mod) r1, c1, r2, c2 = map(int, input().split()) fact, inv_fact = [1, 1], [1, 1] for i in range(2, r2+c2+3): fact.append
(fact[-1] * i % mod) inv_fact.append(inv(fact[-1])) def nCr(n, r): return fact[n] * inv_fact[r] * inv_fact[n-r] % mod def path_sum_sum(r, c): return ((r + 2) * nCr(c+r+2, r+2) % mod + mod - c - 1) * inv(c + 1)
% mod ans = (path_sum_sum(r2, c2) + mod - path_sum_sum(r2, c1-1) + mod - path_sum_sum(r1-1, c2) + path_sum_sum(r1-1, c1-1)) print(ans % mod)
mvaled/sentry
src/sentry/snuba/models.py
Python
bsd-3-clause
903
0
from __future__ import absolute_import from
enum import
Enum from django.db import models from django.utils import timezone from sentry.db.models import FlexibleForeignKey, Model class QueryAggregations(Enum): TOTAL = 0 UNIQUE_USERS = 1 class QueryDatasets(Enum): EVENTS = "events" class QuerySubscription(Model): __core__ = True project = Flexib...
masayuko/nikola
nikola/plugins/template/jinja.py
Python
mit
4,861
0.000412
# -*- coding: utf-8 -*- # Copyright © 2012-2015 Roberto Alsina and others. # 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 t...
f self.dependency_cache.get(template_name) is None: # Use a breadth-first search to find all templates this one # depends on. queue = deque([template_name]) visited_templates =
set([template_name]) deps = [] while len(queue) > 0: curr = queue.popleft() source, filename = self.lookup.loader.get_source(self.lookup, curr)[:2] deps.append(filename) ...
janeen666/mi-instrument
mi/dataset/driver/dosta_ln/wfp/dosta_ln_wfp_driver.py
Python
bsd-2-clause
1,413
0.006369
#!/usr/bin/env python """ @package mi.dataset.driver.dosta_ln.wfp @file marine-integrations/mi/dataset/driver/dosta_ln/wfp/dosta_ln_wfp.py @author Tapana Gupta @brief Driver for the dosta_ln_wfp instrument Release notes: Initial Release """ from mi.core.log import get_logger from mi.dataset.parser.WFP_E_file_commo...
{DataSetDriverConfigKeys.PARTICLE_MODULE: 'mi.dataset.parser.dosta_ln_wfp', DataSetDriverConfigKeys.PARTICLE_CLASS: 'DostaLnWfpInstrumentParserDataParticle'}, {StateKey.POSITION: 0}, stream_handle, lambda state, ingested: None, lambda data: None, ...
ler) driver.processFileStream() return particle_data_handler
YUNZHONGTAN/MY_Python_script
test/socket_server.py
Python
gpl-3.0
694
0.012121
#!/usr/bin/python #coding:utf-8 import socket HOST,PORT = '',8888 #初始化 listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # 绑定 listen_socket.bind((HOST, PORT)) #监听 listen_socket.listen(1) print 'Se
rving HTTP on port %s ...'% PORT while True: #接受请求 client_connection, client_address = listen_socket.accept() # 通信 request = client_connection.recv(1024) print request http_response = ''' HTTP/1.1 200 OK Hello
, World! ''' client_connection.sendall(http_response) # 关闭链接 client_connection.close()
lorddex/unibopoly
python_kp/smart_m3/discovery.py
Python
lgpl-3.0
5,827
0.008066
import threading import select import time import socket pyb_present = False try: import pybonjour pyb_present = True except ImportError: pyb_present = False TIMEOUT = 5 discovered_lock = threading.Semaphore() discovered = [] discovered_event = threading.Event() discovery_running = False def discover(t...
t = raw_input("SmartSpace Port >" ) print ssname, ip, port rtuple = ( ssname, ("TCP",
(ip,int(port)) )) return rtuple def discover_mDNS(name = None, reg_type = "_kspace._tcp"): global discovery_running if not discovery_running: # print "Starting mDNS discovery" d = mDNS_Discovery(reg_type) d.start() discovery_running = True if not name: d...
Julian/mkenv
venvs/_config.py
Python
mit
6,178
0
import json import os import subprocess import sys try: from functools import lru_cache except ImportError: from functools32 import lru_cache from pyrsistent import freeze, pmap, pvector, thaw import attr import filesystems.exceptions import tomlkit class DuplicatedLinks(Exception): pass def _empty():...
attr.ib(default=pvector()) requirements = attr.ib(default=pvector()) link = attr.ib(default=pmap()) link_module = attr.ib(default=pmap()) post_commands = attr.ib(default=pvector()) @classmethod def from_dict(cls, name, config_dict, bundles): # tomlkit's data structures are
broken in at least one way, # see sdipater/tomlkit#49, but I don't trust them not to be # broken in other ways given that they inherit from dict requirements = _interpolated(config_dict.get("requirements", [])) install = list(_interpolated(config_dict.get("install", []))) for b...
jcooky/jandy
jandy-python/tests/a.py
Python
gpl-3.0
457
0
# import re, os # from ja
ndy.profiler import Profiler # # # class Base: # def __init__(self): # print('init call') # # def compile(self, str): # re.compile(str) # # # # p = Profiler("12K", "localhost:3000", 1) # try: # p.start() # b = Base() # b.compile("foo|bar") # print("Hello W
orld!!\n") # finally: # p.done() # # # #try: # # b.print_usage() # #except e.MyException as e: # # raise ValueError('failed')
sukeesh/Jarvis
jarviscli/plugins/calories.py
Python
mit
6,664
0
from colorama import Fore from plugin import plugin @plugin("calories") class calories: """ calculates recommended daily calorie intake,calories for weight add and loss. The calculating method is based on gender, age, height and weight. since it uses the Miffin-St Jeor Equation as it is considered...
take that preserves one's weight, the one to lose weight and the intake to gain more weight. """ if gender.lower == "m": gender_no = 5 else: # A constant value based on gender gender_no = -161
brm = float(10 * weight + 6.25 * height - 5 * age + gender_no) * self.exercise_level(workout_level) # The calculation of the intake to lose weight brm_loss = brm - 500.0 # The calculation of the intake to gain weight brm_put_on = brm + 500.0 return brm, br...
annoviko/pyclustering
pyclustering/cluster/tests/integration/it_rock.py
Python
gpl-3.0
2,770
0.016606
"""! @brief Integration-tests for ROCK algorithm. @authors Andrei Novikov (pyclustering@yandex.ru) @date 2014-2020 @copyright BSD-3-Clause """ import unittest; import matplotlib; matplotlib.use('Agg'); from pyclustering.cluster.tests.rock_templates import RockTestTemplates; from pyclustering.clu...
MPLES.SAMPLE_SIMPLE4, 1, 5, 0.5, [15, 15, 15, 15, 15], True); RockTestTemplates.templateLengthProcessData(SIMPLE_SAMPLES.SAMPLE_SIMPLE4, 1.5, 5, 0.5, [15, 15, 15, 15, 15], True); RockTestTemplates.templateLengthProcessData(SIMPLE_SAMPLES.SAMPLE_SIMPLE5, 1, 4, 0.5, [15, 15, 15, 15], True); def ...
15, 15, 15, 15, 15], True); def testClusterTheSameData1ByCore(self): RockTestTemplates.templateLengthProcessData(SIMPLE_SAMPLES.SAMPLE_SIMPLE9, 1, 2, 0.5, [10, 20], True); def testClusterTheSameData2ByCore(self): RockTestTemplates.templateLengthProcessData(SIMPLE_SAMPLES.SAMPLE_SIMPLE12,...
mlflow/mlflow
mlflow/store/tracking/dbmodels/models.py
Python
apache-2.0
14,421
0.00319
import time from sqlalchemy.orm import relationship, backref import sqlalchemy as sa from sqlalchemy import ( Column, String, ForeignKey, Integer, CheckConstraint, BigInteger, PrimaryKeyConstraint, Boolean, ) from mlflow.entities import ( Experiment, RunTag, Metric, Param...
into ``experiment`` table. """ experiment = relationship("SqlExperiment", backref=backref("runs", cascade="all")) """ SQLAlchemy relationship (many:one) with :py:class:`mlflow.store.dbmodels.models.SqlExperiment`. """ __table_args__ = ( CheckConstraint(source_type.in_(SourceTypes), nam...
n_(RunStatusTypes), name="status"), CheckConstraint( lifecycle_stage.in_(LifecycleStage.view_type_to_stages(ViewType.ALL)), name="runs_lifecycle_stage", ), PrimaryKeyConstraint("run_uuid", name="run_pk"), ) @staticmethod def get_attribute_name(mlflow_attribut...
WeKeyPedia/toolkit-python
wekeypedia/metrics/__init__.py
Python
mit
19
0
f
rom .lsm import *
avanzosc/odoo-addons
account_headquarter/models/account_group.py
Python
agpl-3.0
1,098
0
# Copyright 2021 Alfredo de la Fuente - AvanzOSC # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo import models, fields, api class AccountGroup(models.Mode
l): _inherit = 'account.group' length_account = fields.Integer( string='Length account', compute='_compute_length_account', store=True) without_headquarter = fields.Boolean( string='Without headquarter in invoices and accounting entries', default=True) @api.depends('cod...
len(group.code_prefix_start) def _find_account_group_headquarter(self): found = False group = self while not found: if not group.parent_id: found = True without_headquarter_control = group.without_headquarter else: con...
gocept/zodb.py3migrate
doc/conf.py
Python
mit
284
0
import gocept.package.sphinxconf _year_started = 2016 html_theme = '
alabaster' html_theme_path = [] html_sidebars = {'**': ['globaltoc.html', 'searchbox.html']} html_logo = 'zodb.png' autosummary_generate = [] gocept.package.sphinxconf.set_defaults() # htm
l_sidebars['**'].pop(0)
steveniemitz/scales
test/scales/util/mocks.py
Python
mit
4,542
0.010568
import gevent from scales.asynchronous import AsyncResult from scales.constants import ChannelState, SinkProperties from scales.core import ScalesUriParser from scales.message import (MethodReturnMessage, FailedFastError) from scales.loadbalancer.serverset import ServerSetProvider from scales.sink import (ClientMessag...
lted.Set() class MockSinkProvider(SinkProviderBase): def __init__(self): super(MockSinkProvider, self).__init__() self.ProcessRequest = None self.ProcessResponse = None self.sinks_created = [] def CreateSink(self, properties): ms = MockSink(properties) ms.ProcessRequest = self.ProcessRequ...
MockSink class MockServerSetProvider(ServerSetProvider): def __init__(self): self._servers = set() self._on_leave = None self._on_join = None def Initialize(self, on_join, on_leave): self._on_join = on_join self._on_leave = on_leave def Close(self): pass def AddServer(self, host, p...
APTrust/EarthDiver
dpnode/dpn/data/migrations/0001_initial.py
Python
apache-2.0
8,635
0.004401
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.Create...
blank=True, max_length=64)),
('created_on', models.DateTimeField(auto_now_add=True)), ('updated_on', models.DateTimeField(auto_now=True, auto_now_add=True)), ('published', models.BooleanField(default=False)), ('brightening_objects', models.ManyToManyField(null=True, blank=True, to='data.RegistryEnt...
partofthething/home-assistant
homeassistant/components/aws/notify.py
Python
apache-2.0
7,412
0.000405
"""AWS platform for notify component.""" import asyncio import base64 import json import logging import aiobotocore from homeassistant.components.notify import ( ATTR_TARGET, ATTR_TITLE, ATTR_TITLE_DEFAULT, BaseNotificationService, ) from homeassistant.const import ( CONF_NAME, CONF_PLATFORM, ...
if session is None: _LOGGER.warning("No available aws session for %s", credential_name) del aws_config[CONF_CREDENTIAL_NAME] if session is None: profile = aws_config.get(CONF_PROFILE_NAME) if profile is not None: session = aiobotocore.AioSession(profile=profi...
CitizenScienceInAstronomyWorkshop/pyIBCC
attic/create_pi.py
Python
mit
409
0.04401
from random import random def ran_pi(): dim=[2,3]
out=[] for i in range(dim[0]): temp=[] for j in range(dim[1]): temp.append(random()) sm=sum(temp) out.append([temp[i]/sm for i in range(dim[1])]) return out pi={i:[[1.0,0.0],[0.0,1.0]] for i in range(5)} temp={i:
[[0.0,1.0],[1.0,0.0]] for i in range(5,10)} pi.update(temp)
adamsherman/pytrademonster
pytrademonster/services/quotesService.py
Python
mit
6,582
0.003191
from collections import OrderedDict __author__ = 'adam' from pytrademonster.constants import TradeMonsterConstants from pytrademonster.objects import QuoteChain, QuoteOptionItem, QuoteItem import xmltodict class QuoteRequests(object): ''' Create payload items for quote requests ''' def createOptionCh...
pend to the option dictionary
for strike in allStrikes: strikeVal = strike['strike'] callOption = self.createQuoteOptionItem(strike['call'], TradeMonsterConstants.CALL_PUT.CALL) putOption = self.createQuoteOptionItem(strike['put'], TradeMonsterConstants.CALL_PUT.PUT) callKey = (strik...
vuolter/pyload
src/pyload/plugins/accounts/FreakshareCom.py
Python
agpl-3.0
1,452
0.001377
# -*- coding: utf-8 -*- import re import time from ..base.account import BaseAccount class FreakshareCom(BaseAccount
): __name__ = "FreakshareCom" __type__ = "account" __version__ = "0.21" __status__ = "testing" __description__ = """Freakshare.com account plugin""" __license__ = "GPLv3" __authors__ = [("RaNaN", "RaNaN@pyload.net")] d
ef grab_info(self, user, password, data): premium = False validuntil = None trafficleft = None html = self.load("http://freakshare.com/") try: m = re.search(r"ltig bis:</td>\s*<td><b>([\d.:\-]+)</b></td>", html, re.M) validuntil = time.mktime(time.strpti...
imbo/imboclient-js
docs/conf.py
Python
mit
8,014
0.007736
# -*- coding: utf-8 -*- # # imboclient-js documentation build configuration file, created by # sphinx-quickstart on Wed Feb 12 20:38:51 2014. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. #...
o document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absol
ute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extension...