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
andela-ijubril/book-search
booker/bookstore/tests/test_views.py
Python
mit
1,271
0.003147
from django.test import TestCase, Client from bookstore.models import Book, Category from django.core.urlresolvers import reverse class BookStoreViewTestCase(TestCase): def setUp(self): self.client = Client() self.catego
ry = Category.objects.create(name="programming", description="for the geeks") self.book = Book.objects.create(name="elastic search", description="An intro", author="jubril", category=self.category) def tearDown
(self): Category.objects.all().delete() Book.objects.all().delete() def test_home_page_view(self): response = self.client.get('/') self.assertTemplateUsed(response, 'bookstore/index.html') def test_user_can_search_by_category(self): data = {'bookerOptions': 'category', ...
aperigault/ansible
lib/ansible/modules/cloud/openstack/os_ironic_node.py
Python
gpl-3.0
12,322
0.000325
#!/usr/bin/python # coding: utf-8 -*- # (c) 2015, Hewlett-Packard Development Company, L.P. # 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_version': '1.1'...
"openstack" uuid: "d44666e1-35b3-4f6b-acb0-88ab7052da69" state: present power: pre
sent deploy: True maintenance: False config_drive: "http://192.168.1.1/host-configdrive.iso" instance_info: image_source: "http://192.168.1.1/deploy_image.img" image_checksum: "356a6b55ecc511a20c33c946c4e678af" image_disk_format: "qcow" delegate_to: localhost ''' from ansible.module_utils.basic i...
kermitfr/kermit-webui
src/webui/index/forms.py
Python
gpl-3.0
2,043
0.001958
from django import forms from django.forms import ModelForm from django.contrib.auth.models import User from django.utils.translation import ugettext_lazy as _ from django.contrib.auth import authenticate class AuthenticationForm(forms.Form): """ Base class for authenticating users. Extend this to get a form ...
ername=username, password=password) if self.user_cache is None: raise forms.ValidationError(_("Please enter a correct username and password. Note that both fields are case-sensitive.")) elif not self.user_cache.is_active: ra
ise forms.ValidationError(_("This account is inactive.")) # TODO: determine whether this should move to its own method. if self.request: if not self.request.session.test_cookie_worked(): raise forms.ValidationError(_("Your Web browser doesn't appear to have cookies enabled. ...
Mirantis/bareon-api
bareon_api/cli.py
Python
apache-2.0
904
0.002212
import os import sys import requests from paste import deploy from paste import httpserver from bareon_api.common.config import CONF from bareon_api.data_sync import sync_all_nodes current_dir = os.path.dirname(__file__) def data_sync(): resp = requests.post('http://{host}:{port}/v1/actions/sync_all'.format( ...
onse code {0}'.format(resp.status_code)) print(resp.text) def run(): sync_all_nodes() paste_conf = os.path.join(os.sep, 'etc', 'bareon-api', 'bareon-api-paste.ini') if not os.path.lexists(paste_conf): paste_conf = os.path.join(current_dir, '..', 'etc', 'bareon', 'bareon-api-paste.ini') ap...
(application, host=CONF.host_ip, port=CONF.port)
haystack/eyebrowse-server
notifications/management/commands/emit_notices.py
Python
mit
342
0
import logging from django.core.management.base import BaseCommand from notifications.engine import send_all class Command(BaseCommand): help = "Emit queued notices." def handle(self, *args, **options
): logging.basicConfig(level=logging.DEBUG, format="%(message)s") logging.
info("-" * 72) send_all(*args)
ProjectSWGCore/NGECore2
scripts/mobiles/lairs/dantooine_voritor_hunter_lair_1.py
Python
lgpl-3.0
224
0.022321
import sys from java.util import V
ector def addTemplate(core): core.spawnService.addLairTe
mplate('dantooine_voritor_hunter_lair_2', 'slinking_voritor_hunter', 15, 'object/tangible/lair/base/poi_all_lair_bones.iff') return
hoatle/django-celery
project/settings/common.py
Python
bsd-3-clause
752
0
""" common specific project settings """ from settings.common import * # noqa from heroku_env import env, cast_bool INSTALLED_APPS += ( 'userena', 'guardian', 'easy_thumbnails', 'accounts', 'djcelery_email', ) AUTHENTICATION_BACKENDS = ( 'userena.backends.UserenaAuthenticationBackend', ...
ends.ObjectPermissionBackend', 'django.contrib.auth.backends.ModelBackend', ) ANONYMOUS_USER_ID = -1 AUTH_PROFILE_MODULE = 'accounts.MyProfile' MIGRATION_MODULES = { 'userena': 'userena_patch.migrations' } USERENA_SIGNIN_REDIRECT_URL = '/accounts/%(username)s/' LOGIN_URL = '/accounts/signin/' LOGOUT_URL
= '/accounts/signout/' USERENA_USE_HTTPS = env('USERENA_USE_HTTPS', cast=cast_bool, default=False)
icoxfog417/pykintone
pykintone/comment_result.py
Python
apache-2.0
1,085
0
from pykintone.result import
Result from pykintone.comment import RecordComment, Mention class CreateCommentResult(Result): def __init__(self, response): super(CreateCommentResult, self).__init__(response) self.comment_id = -1 if self.ok: serialized = response.json() if "id" in serialized: ...
t, self).__init__(response) self.raw_comments = [] self.older = False self.newer = False if self.ok: serialized = response.json() if "comments" in serialized: self.raw_comments = serialized["comments"] self.older = serialized["older...
stuti-rastogi/leetcodesolutions
150_reversePolishNotation.py
Python
apache-2.0
602
0.001661
class Solution: def evalRPN(self, to
kens: List[str]) -> int: stack = [] result = 0 for c in tokens: if c in ['+', '-', '*', '/']: op2 = stack.pop() op1 = stack.pop() if c == '+':
stack.append(op1+op2) elif c == '-': stack.append(op1-op2) elif c == '*': stack.append(op1*op2) else: stack.append(int(op1/op2)) else: stack.append(int(c)) return stack[...
Fat-Zer/FreeCAD_sf_master
src/Mod/Path/PathScripts/PathDressupDogbone.py
Python
lgpl-2.1
49,208
0.002134
# -*- coding: utf-8 -*- # *************************************************************************** # * Copyright (c) 2014 Yorik van Havre <yorik@uncreated.net> * # * * # * This program is free software; you can redistribute it a...
lf, x, y, z): return self.moveTo(self.End + FreeCAD.
Vector(x, y, z)) def move(self, distance, angle): dx = distance * math.cos(angle) dy = distance * math.sin(angle) return self.moveBy(dx, dy, 0) def asVector(self): return self.End - self.Start def asDirection(self): return self.asVector().normalize() def asLin...
asascience-open/metadown
metadown/collectors/geonetwork.py
Python
gpl-3.0
2,788
0.002152
import os import csv import tempfile import codecs from urlparse import urlsplit from shutil import abspath import requests from metadown.utils.etree import etree namespaces = { "gmx": "http://www.isotc211.org/2005/gmx", "gsr": "http://www.isotc211.org/2005/gsr", "gss": "http://www.isotc211.org/2005/gss"...
oot.xpath( '/gmd:MD_Metadata/gmd:fileIdentifier/gco:CharacterString', namespaces=namespaces ) uuid = "GeoNet
work-" + x_res[0].text + ".xml" return uuid @staticmethod def modifier(url, **kwargs): # translate ISO19139 to ISO19115 gmi_ns = "http://www.isotc211.org/2005/gmi" etree.register_namespace("gmi",gmi_ns) new_root = etree.Element("{%s}MI_Metadata" % gmi_ns) old_r...
Jamlum/pytomo
pytomo/translation_cache_url.py
Python
gpl-2.0
4,763
0.00189
#!/usr/bin/env python '''Translate new cache url format into human readable airport codes based on Maurizio M. Munafo perl code: $name =~ tr/0-9a-z/uzpkfa50vqlgb61wrmhc72xsnid83ytoje94/; ''' import re from string import maketrans, lowercase import sys import os import logging from optparse import OptionParser, SU...
gv=None): 'Program wrapper' if argv is None: argv = sys.argv[1:] usage = '%prog [-v] url_input_files' parser = OptionParser(usage=usage) parser.add_option('--debug', action='store_true', dest='debug'
, default=False, help=SUPPRESS_HELP) parser.add_option('-v', '--verbose', action='store_true', dest='verbose', default=False, help='run in verbose mode') (options, args) = parser.parse_args(argv) if options.verbose: config_pytomo.LOG.setLevel(logging.INFO)...
StuntsPT/pyRona
pyRona/pyRona.py
Python
gpl-3.0
8,988
0
#!/usr/bin/python3 # Copyright 2016-2018 Francisco Pina Martins <f.pinamartins@gmail.com> # This file is part of pyRona. # pyRona 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...
r each covar """ POP_NAMES = [] def __init__(self, covar): self.name = covar self.pop_ronas = defaultdict(list) self.corr_coef = {} self.avg_ronas = [] self.stderr_ronas = [] def basic_stats(self, use_weights): """ Gets the average RONA and stde...
ovariate. Stores the values in variables inside the class instance. """ if len(self.pop_ronas) > 1: # Sort markers: markers = sorted(list(self.corr_coef.keys())) list_of_marker_values = np.array([self.pop_ronas[x] for x in ...
dwcaraway/podserve
start.py
Python
agpl-3.0
223
0.004484
from podserve import create_app __author__ = 'dwcaraway' if __name__ == '__main__
':
import logging import sys logging.basicConfig(stream=sys.stderr, level=logging.DEBUG) app = create_app() app.run()
valkyriesavage/invenio
modules/bibharvest/lib/oai_harvest_admin.py
Python
gpl-2.0
65,264
0.012871
## Administrator interface for BibIndex ## This file is part of Invenio. ## Copyright (C) 2009, 2010, 2011 CERN. ## ## Invenio 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 ## Licen...
{'ln': ln, 'oai_src_id': str(oai_src_id)} edit_link = create_html_link(urlbase=oai_harvest_admin_url + \ "/editsource", urlargd=default_link_argd, link_label=_("edit")) del_link = create_...
"/delsource", urlargd=default_link_argd, link_label=_("delete")) test_link = create_html_link(urlbase=oai_harvest_admin_url + \ "/testsource", urlargd=default_link_argd, ...
Endika/odoo-saas-tools
saas_client/__openerp__.py
Python
gpl-3.0
506
0.001976
{ 'name': 'SaaS Client',
'version': '1.0.0', 'author': 'Ivan Yelizariev', 'license': 'GPL-3', 'category': 'SaaS', 'website': 'https://it-projects.info', 'depends': ['auth_oauth', 'auth_oauth_check_client_id', 'saas_utils', 'mail'], 'data': [ 'views/saas_client.xml', 'security/rules.xml', 'se...
'installable': True, }
pybursa/homeworks
e_tverdokhleboff/hw3/3.4.py
Python
gpl-2.0
52
0.019231
import os
import sys print help(sys
) print help(os)
georglind/babusca
examples/context.py
Python
mit
209
0.028708
# for
accessing babusca library. import os import sys sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
import smatrix import scattering import g1 import g2 import generators
ajmendez/python-fsps
fsps/__init__.py
Python
mit
2,187
0.000914
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import (division, print_function, absolute_import, unicode_literals) __version__ = "0.1.1" import os import re import subprocess import warnings def run_command(cmd): """ Open a child process, and return its exit status an...
from the setup script. try: __FSPS_SETUP__ except NameError: __FSPS_SETUP__ = F
alse if not __FSPS_SETUP__: __all__ = ["StellarPopulation", "find_filter", "get_filter", "list_filters"] from .fsps import StellarPopulation from .filters import find_filter, get_filter, list_filters
ZhongxingPeng/simple_neural_network
search_param.py
Python
mit
6,378
0.005801
"""Search initial values of parameters in our simple neural network""" import math import random import numpy as np class SimpleNeuralNetwork(object): """Simple neural network""" def __init__(self): self.lamb = np.random.randn() # pylint: disable = no-member self.bias = np.random.randn() # p...
lf.lamb * 2 * temp_u2 nabla_weight = nabla_bias * coordinate_x return (nabla_lamb, nabla_bias, nabla_weight) def evaluate(self, test_data): """Evaluate the neural network""" num_correct_predict = 0 test_results = [(self.feedforward(x, y), label) for (x, y, label) in test_d...
_prob, label in test_results: if abs(label - predict_prob) < 0.5: num_correct_predict += 1 return num_correct_predict def sigmoid(weighted_z): """Compute sigmoid function""" return 1.0/(1.0+np.exp(- weighted_z)) # pylint: disable = no-member if __name__ == '__main__': ...
Bloombox/bloombox-client
Python/bloombox/api/__init__.py
Python
apache-2.0
80
0
# -*
- coding: utf-8 -*- __doc__ = """ bloo
mbox: API clients for Python """
rmgorman/django-guardian
guardian/utils.py
Python
bsd-2-clause
7,292
0.000686
""" django-guardian helper functions. Functions defined within this module should be considered as django-guardian's internal functionality. They are **not** guaranteed to be stable - which means they actual input parameters/output type may change in future releases. """ from __future__ import unicode_literals import...
None) if (model and issubclass(model, base_cls) and
model is not generic_cls and getattr(model, 'enabled', True)): # if model is generic one it would be returned anyway if not model.objects.is_generic(): # make sure that content_object's content_type is same as # the one of given obj fk = ...
jan-rybizki/Chempy
Chempy/time_integration.py
Python
mit
14,641
0.035175
import numpy as np class ABUNDANCE_MATRIX(object): ''' This class contains all information necessary to characterize the chemical evolution of the open-box one-zone Chempy model. It calculates the mass flow between the different components. And can advance the chemical evolution when the enrichment from the SSP ...
cosmic_inflow = self.sfr[0] * self.sfr_factor_for_cosmic_accretion self.gas_reservoir['gas'][0] = cosmic_inflow for i,item in enumerate(self.cosmic_accretion_elements): self.gas_reservoir[item][0] = self.cosmic_accretion_element_fractions[i] * cosmic_inflow starting_gas = sum(self.sfr) * gas_reservoir_mas...
ll_symbols): self.gas_reservoir[item][0] += self.infall_fractions[i] * starting_gas for i,item in enumerate(self.elements): if item not in ['H','He']: self.cube['Z'][0] += self.cube[item][0] self.gas_reservoir['Z'][0] += self.gas_reservoir[item][0] self.cube['Z'][0] = self.cube['Z'][0] / self.cube[...
moopet/django-flatpage-meta
setup.py
Python
mit
607
0
from setuptools import setup, find_packages setup( name='django-flatpage-meta', version='0.0.2', description='A simple app to add meta tag support to flatpages', author="Ben Sinclair", packages=find_packages(), classifiers=[ 'Development Status :: 1 - Alpha', 'Enviro
nment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ], include_package_data=True, zip_safe=False,
)
ashwch/CrossTab
app/forms.py
Python
mit
1,236
0.001618
import logging from django import forms from django.conf import settings from django.forms import ModelForm from app.models import ExtendedUser, UserFiles logger = logging.getLogger(__name__) class ExtendedUserForm(ModelForm): first_name = forms.CharField(required=False, max_length=100) last_name = forms.C...
nfo('Content-type was fine.'
) return uploaded_file class Meta: model = UserFiles fields = ['userid', 'uploaded_file']
F5Networks/f5-common-python
f5/bigip/tm/ltm/test/unit/test_cipher.py
Python
apache-2.0
1,877
0
# Copyright 2021 F5 Networks Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writi...
ND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import mock import pytest from f5.bigip import ManagementRoot from f5.bigip.tm.ltm.cipher import Group from f5.bigip.tm.ltm.cipher import Rule from f5.sdk_exception import MissingReq...
jbrowne/UCSBsketch
linux/Bin/DirectedLine.py
Python
bsd-3-clause
3,540
0.014124
""" filename: EqualsObserver.py description: This module looks for equal signs Doctest Examples: >>> t = TextMarker() """ #------------------------------------- import pdb import math from Utils import Logger from Utils import GeomUtils from Observers import CircleObserver from Observers import LineObserver ...
er.__init__(self, board) self.getBoard().AddBoardObserver( self, [H_LineAnnotation, V_LineAnnotation, TB_LineAnnotation, BT_L
ineAnnotation] ) self.getBoard().RegisterForAnnotation( LineObserver.LineAnnotation, self ) def onAnnotationAdded( self, strokes, annotation ): threshold = 10 d_threshold = 15 a = annotation.angle l = annotation.linearity sp = annotation.start_point ...
IQSS/miniverse
dv_apps/metrics/stats_util_dataverses.py
Python
mit
15,410
0.005581
""" Create metrics for Dataverses. This may be used for APIs, views with visualizations, etc. """ from collections import OrderedDict from django.db import models from dv_apps.utils.date_helper import get_month_name_abbreviation,\ get_month_name from dv_apps.dataverses.models import Dataverse, DATAVERSE_TYPE_UNCA...
ning_total += d['count'] rec_fmt['running_total'] = running_total # d['month_year'] = d['yyyy_mm'].strftime('%Y-%m') # Add year and month numbers rec_fmt['year_num'] = d['yyyy_mm'].year rec_fmt['month_num'] = d['yyyy_mm'].month # Add month name ...
ame_found, rec_fmt['month_name'] = get_month_name(d['yyyy_mm'].month) rec_fmt['month_name_short'] = month_name_short else: # Log it!!!!!! pass # Add formatted record formatted_records.append(rec_fmt) data_dict = OrderedDict() ...
Twangist/log_calls
tests/set_reset_defaults/global_defaults.py
Python
mit
211
0
__author__ = 'bria
noneill' from log_calls import log_calls global_settings = dict( log_call_numbers=True, log_exit=False, log_retval=True, ) log_calls.set_defaults(global_settings
, args_sep=' $ ')
osgee/keychainserver
keychain/views/web/userview.py
Python
apache-2.0
10,760
0.001394
import datetime import json import math import re import time import uuid from django import forms from django.http import HttpResponseRedirect from django.shortcuts import render from django.utils import timezone from keychain import captcha as captcha_generator from keychain import cryptool from keychain.models imp...
d(): user_name = user_form.cleaned_data['user_name'] user_password = user_form.cleaned_data['password'] captcha = user_form.cleaned_data['captcha'].lower() if 'captcha' in request.session and request.session['captcha'] == captcha: del request.session['capt...
user = User(user_password=user_password) account_type = get_account_type(user_name) if account_type == account_type_user_name: user.user_name = user_name elif account_type == account_type_user_email: user.user_email = user_nam...
paulcwatts/dominion
dominion/base.py
Python
bsd-3-clause
1,060
0
class Requirement(object): """ Requirements are the basis for Dominion. They define what needs to exist on a host/role, or perhaps what *mustn't* exist. Requirements are defined on Roles. """ creation_counter = 0 "Th
e base class for requirements." def __init__(self, required=True, ensure=None, depends=None, post=None): self.required = required self.ensure = ensure or "exists" self.depends = depends or () if self.ensure == "removed": self.required = False self.post = post or (...
creation_counter = Requirement.creation_counter Requirement.creation_counter += 1 def __call__(self): self.apply() def apply(self): if self.ensure == "exists" or self.required: if hasattr(self, 'install'): return self.install() if self.ensure == "rem...
lochiiconnectivity/exabgp
lib/exabgp/bgp/timer.py
Python
bsd-3-clause
1,586
0.035309
# encoding: utf-8 """ timer.py Created by Thomas Mangin on 2012-07-21. Copyright (c) 2009-2015 Exa Networks. All rights reserved. """ import time from exabgp.logger import Logger from exabgp.bgp.message.nop import _NOP from exabgp.bgp.message.keepalive import KeepAlive from exabgp.bgp.message.notification import Not...
elif message.TYPE == KeepAlive.TYPE: raise Notify(2,6,'Negotiated holdtime was zero, it was invalid to send us a keepalive messages') class SendTimer (object): def
__init__ (self,me,holdtime): self.logger = Logger() self.me = me self.keepalive = holdtime.keepalive() self.last_sent = int(time.time()) def need_ka (self): if not self.keepalive: return False now = int(time.time()) left = self.last_sent + self.keepalive - now if now != self.last_sent: self...
getredash/redash
migrations/versions/65fc9ede4746_add_is_draft_status_to_queries_and_.py
Python
bsd-2-clause
1,370
0.00292
"""Add is_draft status to queries and dashboards Revision ID: 65fc9ede4746 Revises: Create Date: 2016-12-07 18:08:13.395586 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. from sqlalchemy.exc import ProgrammingError revision = "65fc9ede4746" down_revision = None branch_l...
if you ran the old migrations. if 'column "is_dra
ft" of relation "queries" already exists' in str(e): print( "Can't run this migration as you already have is_draft columns, please run:" ) print( "./manage.py db stamp {} # you might need to alter the command to match your environment.".format( ...
veger/ansible
lib/ansible/modules/cloud/azure/azure_rm_dnsrecordset_facts.py
Python
gpl-3.0
6,511
0.002765
#!/usr/bin/python # # Copyright (c) 2017 Obezimnaka Boms, <t-ozboms@microsoft.com> # # 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_version': '1.1', ...
urceGroups/testing/providers/Microsoft.Network/dnszones/newzone.com/A/servera", "name": "servera", "properties": { "ARecords": [ { "ipv4Address": "10.4.5.7" }, { ...
"ipv4Address": "2.4.5.8" } ], "TTL": 12900 }, "type": "Microsoft.Network/dnszones/A" } ] ''' from ansible.module_utils.azure_rm_common import AzureRMModuleBase try: from msrestazure.azu...
googlefonts/nototools
nototools/collect_cldr_punct.py
Python
apache-2.0
4,670
0.000642
#!/usr/bin/env python # # 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 require...
currencies.add(tag.text) return currencies def _get_cldr_files(cldr_dirs): files = set() for cldr_dir in cldr_dirs: search = path.join(CLDR_DIR, "common", cldr_dir, "*.xml") files.update(glob.glob(search)) return files def _collect_script_to_punct(files): """Builds s...
scripts. Adds ASCII single and double quotes if corresponding quotes are in the punct.""" script_to_punct = collections.defaultdict(set) curly_quotes_to_standard = [ (frozenset([unichr(0x2018), unichr(0x2019)]), frozenset(["'"])), (frozenset([unichr(0x201C), unichr(0x201D)]), frozenset(['...
deepmind/dm_robotics
py/vision/types.py
Python
apache-2.0
3,974
0.006039
# Copyright 2020 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 ag...
fic language governing permissions and # limitations under the License. """Common types used in DeepMind Robotics vision package. This file is maintained for simplifying data creation and manipulation as well as facilitating type hints
. """ import dataclasses from typing import Mapping, Optional, Sequence, Tuple import numpy as np MaskPoints = Sequence[Sequence[Tuple[int, int]]] Centers = Mapping[str, Optional[np.ndarray]] Detections = Mapping[str, Optional[np.ndarray]] @dataclasses.dataclass(frozen=True) class Intrinsics: """Camera intrinsic...
ganeshgore/myremolab
server/launch/sample_unixsocket/main_machine/main_instance/login/server_config.py
Python
bsd-2-clause
459
0.015251
weblab_db_username = 'weblab' weblab_db_password = 'weblab' ############################## # RemoteFacade configuration # ############################## login_facade_soap_bind = '' login_facade_soap_port = 10623
login_facade_soap_service_name = '/weblab/login/soap/' login_facade_xmlrpc_bind = '' login_facade_xmlrpc_port = 19645 login_facade_json_bind = '' login_facade_json_port = 18645 login_web_facade_port =
18745
arlolra/stem
stem/util/connection.py
Python
lgpl-3.0
8,605
0.009994
# Copyright 2012-2013, Damian Johnson # See LICENSE for licensing information """ Connection and networking based utility functions. This will likely be expanded later to have all of `arm's functions <https://gitweb.torproject.org/arm.git/blob/HEAD:/src/util/connections.py>`_, but for now just moving the parts we need...
not enough groups and none are collapsed elif address.count("::")
> 1 or ":::" in address: return False # multiple groupings of zeros can't be collapsed for entry in address.split(":"): if not re.match("^[0-9a-fA-f]{0,4}$", entry): return False return True def is_valid_port(entry, allow_zero = False): """ Checks if a string or int is a valid port number. ...
metagriffin/iniget
setup.py
Python
gpl-3.0
3,162
0.022454
#!/usr/bin/env python # -*- coding: utf-8 -*- #------------------------------------------------------------------------------ # file: $Id$ # auth: metagriffin <mg.github@metagriffin.net> # date: 2013/04/27 # copy: (C) Copyright 2014-EOT metagriffin -- see LICENSE.txt #---------------------------------------------------...
R A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see http://www.gnu.org/licenses/. #------------------------------------------------------------------------------ import os, sys, setup...
require python 2.7+ if sys.hexversion < 0x02070000: raise RuntimeError('This package requires python 2.7 or better') heredir = os.path.abspath(os.path.dirname(__file__)) def read(*parts, **kw): try: return open(os.path.join(heredir, *parts)).read() except: return kw.get('default', '') test_dependencies = [ ...
cbitstech/Purple-Robot-Django
management/commands/extractors/builtin_pressureprobe.py
Python
gpl-3.0
7,463
0.003886
# pylint: disable=line-too-long import datetime import psycopg2 import pytz CREATE_PROBE_TABLE_SQL = 'CREATE TABLE builtin_pressureprobe(id SERIAL PRIMARY KEY, user_id TEXT, guid TEXT, timestamp DOUBLE PRECISION, utc_logged TIMESTAMP, sensor_vendor TEXT, sensor_name TEXT, sensor_power DOUBLE PRECISION, sensor_type BI...
\ 'pressure, ' + \ 'alti
tude, ' + \ 'accuracy) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s);' values = [user_id, reading_id, datetime.datetime.fromtimestamp(reading['TIMESTAMP'], tz=pytz.utc)] values.append(reading['EVENT_TIMESTAMP'][i]) ...
fgrsnau/sipa
sipa/utils/exceptions.py
Python
mit
316
0
# -*- coding: utf-8 -*- """ Custom exceptions for sipa Operational
Error for MySQL and SERVER_DOWN for LDAP are global app handlers! """ class UserNotFound(Exception): pass class PasswordInvalid(Exception): pass class DBQueryEmpty(Exception): pass cl
ass LDAPConnectionError(Exception): pass
mihailim/Sigil
src/Resource_Files/plugin_launchers/python/sigil_gumbo_bs4_adapter.py
Python
gpl-3.0
7,056
0.001559
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab # Copyright 2012 Google Inc. All Rights Reserved. # Modifications to use BeautifulSoup4 # Copyright 2015-2020 Kevin B. Hendricks, Stratford, Ontario, Canada # Licensed under the Apache License, Version 2.0 (the "License"...
node.contents) def _add_next_prev_pointers(soup): def _traverse(node): # .findAll requires the .next pointer, which is what we're trying to add
# when we call this, and so we manually supply a generator to yield the # nodes in DOM order. yield node try: for child in node.contents: for descendant in _traverse(child): yield descendant except AttributeError: # Not...
jcchoiling/learningPython
treehouse/pythonSeries/diary.py
Python
gpl-3.0
2,264
0.002208
from collections import OrderedDict import datetime import os import sys from peewee import * db = SqliteDatabase('diary.db') class Entry(Model): content = TextField() timestamp = DateTimeField(default=datetime.datetime.now) class Meta: database = db def initialize(): """Create a table i...
ies""" entries = Entry.select().order_by(Entry.timestamp.desc()) if search_query: entries = entries.where(Entry.content.contains(search_query)) for entry in entries: timestamp = entry.timestamp.strftime('%A %B %d, %Y %I:%M%p') clear() print(tim
estamp) print('=' * len(timestamp)) print(entry.content) print('N) next entry') print('d) delete entry') print('q) return to main menu') next_action = input('Action: [Ndq] ').lower().strip() if next_action == 'q': break elif next_action == 'd'...
qkitgroup/qkit
qkit/services/qsurveilkit/data_class.py
Python
gpl-2.0
8,469
0.012634
# DATA class v1.0 written by HR,JB@KIT 2011, 2016 ''' DATA exchange class, also holds global variables for thread management. Generalized version based on TIP. ''' # 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...
f_lib.Data(self.fname, mode='a') self.hdf_t = self.hf.add_coordinate('timestamps') self.hdf_v = self.hf.add_value_vector('values', x = self.hdf_t) self.url_timestamps = '/entry/data0/timestamps' self.url_values = '/entry/data0/values' view = self.hf.add_view('...
d_to_log(self): with self.log_lock: self.hdf_t.append(float(self.get_timestamp())) self.hdf_v.append(float(self.get_last_value())) def close_logfile(self): self.hf.close_file() def schedule(self): ''' S...
SpamExperts/pyzor
tests/unit/test_config.py
Python
gpl-2.0
9,903
0.000404
import os import logging import unittest try: import configparser as ConfigParser except ImportError: import ConfigParser try: from unittest.mock import patch, Mock except ImportError: from mock import patch, Mock import pyzor.config from tests.util import mock_open class MockData(list): def c...
nfig.load_passwd_file(fp) def tearDown(self): super(TestPasswdLoad, self).tearDown() patch.stopall() def test_nothing(self): result = self.get_passwd() self.assertEqual(result, {}) def test_default(self): result = self.get_passwd("foobar") self.assertEqual(...
ult, {}) def test_passwd(self): self.data.append("alice : %s\n" % self.alice_key) self.data.append("bob : %s\n" % self.bob_key) result = self.get_passwd() self.assertEqual(result, {"alice": self.alice_key, "bob": self.bob_key}) def test_invalid...
tschijnmo/ccpoviz
ccpoviz/renderpov.py
Python
mit
2,302
0
""" Pov-ray template rendering ========================== This is a driver module that renders the pov-ray template for the given molecule and user configuration based on the several other modules for transforming molecular information into more and more primtive pov-ray objects. """ import pystache import pkg_resou...
t draw_atms from .drawbonds import draw_bonds from .drawaxes import draw_axes def gen_render_dict(structure, ops_dict): """Generates the dictionary for rendering the template""" render_dict = {} cam_dict, cam_loc, cam_foc = gen_camera_ops(ops_dict, structure) render_dict['camera'] = cam_dict l...
cam_foc, ops_dict) render_dict.update(lightsouce_dict) atms_list = draw_atms(structure, ops_dict) render_dict['atoms'] = atms_list bonds_list = draw_bonds(structure, cam_loc, ops_dict) render_dict['bonds'] = bonds_list bkg_colour = ops_dict['background-colour'] if bkg_colour == '': ...
tuskar/tuskar-ui
openstack_dashboard/dashboards/admin/networks/subnets/tables.py
Python
apache-2.0
2,757
0.000363
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 NEC Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #...
e(tables.DataTable): name = tables.Column("name", verbose_name=_("Name"), link='horizon:admin:networks:subnets:detail') cidr = tables.Column("cidr", verbose_name=_("CIDR")) ip_version = tables.Column("ipver_str", verbose_name=_("IP Version")) gateway_ip = tables.Column("gateway_...
) table_actions = (CreateSubnet, DeleteSubnet) row_actions = (UpdateSubnet, DeleteSubnet,)
kevelbreh/betternet
betternet/command/privmsg.py
Python
apache-2.0
3,895
0.000513
from twisted.words.protocols.irc import ERR_NORECIPIENT, ERR_NOTEXTTOSEND, ERR_NOSUCHNICK class Command(object): """ PRIVMSG is used to send private messages between users, as well as to send messages to channels. <msgtarget> is u
sually the nickname of the recipient of the message, or a channel name. The <msgtarget> parameter may also be a host mask (#<mask>) or server mask ($<mask>). In both cases the server will only send the PRIVM
SG to those who have a server or host matching the mask. The mask MUST have at least 1 (one) "." in it and no wildcards following the last ".". This requirement exists to prevent people sending messages to "#*" or "$*", which would broadcast to all users. Wildcards are the '*' and '?' characters...
tolstoyevsky/pieman
pieman/setup.py
Python
gpl-3.0
1,517
0
""" Script for building the Pieman package. """ from setuptools import setup try: import pypandoc LONG_DESCRIPTION = pypandoc.convert('README.md', 'rst') except (ImportError, OSError): # OSError is raised when pandoc is not installed. LONG_DESCRIPTION = ('Utilities written in Python which are used by ...
aintainer='Evgeny Golyshev', maintainer_email='eugulixes@gmail.com', license='https://gnu.org/licenses/gpl-3.0.txt', scripts=[ 'bin/apk_tools_version.py', 'bin/bsc.py', 'bin/bscd.py', 'bin/check_mutually_exclusive_params.py', 'bin/check_redis.py', ...
render.py', 'bin/wget.py', ], packages=['pieman'], include_package_data=True, data_files=[ ('', ['requirements.txt']), ('pieman', ['pieman/build_status_codes']), ], install_requires=REQUIREMENTS_LIST)
magicicada-bot/magicicada-server
magicicada/u1sync/scan.py
Python
agpl-3.0
2,968
0
# Copyright 2009 Canonical Ltd. # Copyright 2015-2018 Chicharreros (https://launchpad.net/~chicharreros) # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distribu...
_target = None child_names = None try: link_target = os.readlink(path) except OSError as e: if e.errno != EINVAL: raise try: child_names = os.listdir(path) except OSError as e: if e.errno != ENOT
DIR: raise if link_target is not None: # symlink sum = hashlib.sha1() sum.update(link_target) content_hash = "sha1:%s" % sum.hexdigest() return MergeNode(node_type=SYMLINK, content_hash=content_hash) elif child_names is not None: # directory ...
jgeewax/gcloud-python
runtimeconfig/google/cloud/runtimeconfig/_helpers.py
Python
apache-2.0
2,925
0
# Copyright 2016 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
me`` and is returned as the ``name`` field of a variable resource. See: https://cloud.google.co
m/deployment-manager/runtime-configurator/reference/rest/v1beta1/projects.configs.variables :rtype: str :returns: The variable's short name, given its full resource name. :raises: :class:`ValueError` if ``full_name`` is not the expected format """ projects, _, configs, _, variables, result = full_n...
GustavoVS/timtec
accounts/models.py
Python
agpl-3.0
4,252
0.001646
# -*- coding: utf-8 -*- from django.db import models from django.utils.translation import ugettext_lazy as _ from django.core import validators from django.core.mail import send_mail from django.conf import settings from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, UserManager, Group from djan...
import re class AbstractTimtecUser(AbstractBaseUser, PermissionsMixin): USERNAME_REGEXP = re.compile('^[\w.+-]+$') username = models.CharField( _('Username'), max_length=30, unique=True, help_text=_('Required. 30 characters or fewer. Letters, numbe
rs and ' './+/-/_ characters'), validators=[ validators.RegexValidator(USERNAME_REGEXP, _('Enter a valid username.'), 'invalid') ]) first_name = models.CharField(_('First name'), max_length=30, blank=True) last_name = models.CharField(_('Last name'), max_length=3...
infobloxopen/infoblox-netmri
infoblox_netmri/api/remote/models/device_flow_filter_cfg_remote.py
Python
apache-2.0
4,190
0.004296
from ..remote import RemoteModel from infoblox_netmri.utils.utils import check_api_availability class DeviceFlowFilterCfgRemote(RemoteModel): """ Network traffic flow configuration, definition of a path of ip flow to rule | ``DeviceFlowFilterCfgID:`` The internal NetMRI identifier for this ip packet fl...
``attribute type:`` string """ properties = ("DeviceFlowFilterCfgID", "DeviceID", "FfcFirstSeenTime", "SrcDeviceZoneID", "DestDeviceZoneID", "FfcType", "FfcDisplayText", "FfcConfigTex...
"FfcProvisionData", "DataSourceID", "FfcStartTime", "FfcEndTime", "FfcTimestamp", "FfcChangedCols", "FfcName", "FfcData", ) @property @check_api_availability ...
DevynCJohnson/Pybooster
pylib/code_interpreter.py
Python
lgpl-3.0
5,388
0.001114
#!/usr/bin/env python3 # -*- coding: utf-8; Mode: Python; indent-tabs-mode: nil; tab-width: 4 -*- # vim: set fileencoding=utf-8 filetype=python syntax=python.doxygen fileformat=unix tabstop=4 expandtab : # kate: encoding utf-8; bom off; syntax python; indent-mode python; eol unix; replace-tabs off; indent-width 4; tab-...
{r'exit', r'quit'}: break stdout.write(getoutput('perl -e \'' + _input + '\'') + '\n') # PHP # def execphp(_code: str) -> str: """Execute PHP code given as a str and return the output as a str.""" return getoutput('php -r \'' + _code.replace('\'', '\\\'') + '\'') def execphpfile(_file...
ipt given as a str and return the output as a str.""" return getoutput(r'php -f ' + _filename) # RUBY # def execruby(_code: str) -> str: """Execute Ruby code given as a str and return the output as a str.""" return getoutput('ruby -e \'' + _code.replace('\'', '\\\'') + '\'') def execrubyfile(_filename...
marcosschroh/youtube-audio-downloader
sound_downloader/conf_manager.py
Python
gpl-3.0
990
0
import sys import yaml import collections Conf = collections.namedtuple( 'Conf', 'links audio_formats show_download_progress overrride_audios' ) class ConfManager(object): DEFAULT_AUDIO_FORMATS = ['mp4', 'mp3', 'webm', 'm4a', 'ogg', 'wma'] @classmethod def get_conf(cls, file_path
): with open(file_path, 'r'
) as stream: try: conf = yaml.load(stream) except yaml.YAMLError as exc: sys.exit(exc) links = conf.get('youtube-links', []) audio_formats = conf.get( 'audio-formats-priority', cls.DEFAULT_AUDIO_FORMATS ) sh...
lucashmorais/x-Bench
mozmill-env/python/Lib/site-packages/mozdevice/adb_android.py
Python
mit
16,605
0.000903
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at http://mozilla.org/MPL/2.0/. import os import re import time from adb import ADBDevice, ADBError from distutils.version import StrictVersion class...
tion management methods def install_app(self, apk_path, timeout=None): """Installs an app on the device. :param apk_path: string containing the apk file name to be installed. :param timeout: optional integer specifying the maximum time in seconds for any spawned adb...
throwing an ADBTimeoutError. This timeout is per adb call. The total time spent may exceed this value. If it is not specified, the value set in the ADB constructor is used. :raises: * ADBTimeoutError * ADBError """ data = self.com...
Freso/picard
picard/ui/edittagdialog.py
Python
gpl-2.0
7,337
0.001227
# -*- coding: utf-8 -*- # # Picard, the next-generation MusicBrainz tagger # Copyright (C) 2011 Michael Wiencek # # 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 Licens...
at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of th...
USA. from PyQt4 import QtCore, QtGui from picard.util.tags import TAG_NAMES from picard.ui import PicardDialog from picard.ui.ui_edittagdialog import Ui_EditTagDialog class EditTagDialog(PicardDialog): def __init__(self, window, tag): PicardDialog.__init__(self, window) self.ui = Ui_EditTagDial...
kawamon/hue
desktop/core/ext-py/openpyxl-2.6.4/openpyxl/chart/plotarea.py
Python
apache-2.0
5,861
0.001536
from __future__ import absolute_import # Copyright (c) 2010-2019 openpyxl from openpyxl.descriptors.serialisa
ble import Serialisable from openpyxl.descriptors import ( Typed, Alias, ) from openpyxl.descriptors.excel import ( ExtensionList, ) from openpyxl.descriptors.sequence import ( MultiSequence, MultiSequencePart, ) from openpyxl.descriptors.nested import ( NestedBool, ) from ._3d import _3DBase f...
ne_chart import LineChart, LineChart3D from .pie_chart import PieChart, PieChart3D, ProjectedPieChart, DoughnutChart from .radar_chart import RadarChart from .scatter_chart import ScatterChart from .stock_chart import StockChart from .surface_chart import SurfaceChart, SurfaceChart3D from .layout import Layout from .sh...
google/retiming
models/kp2uv_model.py
Python
apache-2.0
2,722
0.001837
# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
pred_id, pred_uv = output _, pred_id_class = pred_id.max(1) pred_id_class = pred_id_class.unsqueeze(1) # extract UV from pred_uv (48 channels); select based on class ID selected_uv = -1 * torch.ones(pred_uv.shape[0], 2, pred_uv.shape[2], pred_uv.shape[3], device=pred_uv.device) ...
_uv += mask * pred_uv[:, (partid - 1) * 2:(partid - 1) * 2 + 2] pred_uv = selected_uv rgb = torch.cat([pred_id_class.float() * 10 / 255. * 2 - 1, pred_uv], 1) return rgb def optimize_parameters(self): pass
sunlightlabs/read_FEC
fecreader/formdata/testing/mptest.py
Python
bsd-3-clause
818
0.018337
# example adapted from http://stackoverflow.com/a/9039979 # need multiprocessing: 'pip install multiprocessing' from multiprocessing import Pool, Process, Queue class Worker(Process): def __init__(self, queue, id): super(Wor
ker, self).__init__() self.queue= queue self.id = id def run(self): print 'Worker started with id %s' % (self.id)
# do some initialization here for data in iter( self.queue.get, None ): # Use data print data, self.id the_real_source = range(1,200) request_queue = Queue() for i in range(4): Worker( request_queue, i ).start() for data in the_real_source: request_queue.pu...
GbalsaC/bitnamiP
venv/lib/python2.7/site-packages/sympy/mpmath/functions/hypergeometric.py
Python
agpl-3.0
51,556
0.00997
from ..libmp.backend import xrange from .functions import defun, defun_wrapped def _check_need_perturb(ctx, terms, prec, discard_known_zeros): perturb = recompute = False extraprec = 0 discard = [] for term_index, term in enumerate(terms): w_s, c_s, alpha_s, beta_s, a_s, b_s, z = term h...
if verbose: print() print(" Evaluating term %i/%i : %iF%i" % \ (term_index+1, len(terms), len(a_s), len(b_s))) print(" powers", ctx.nstr(w_s), ctx.nstr(c_s)) print(" gamma", ctx.nstr(alpha_s), ctx.ns...
z, **kwargs) #for a in alpha_s: v *= ctx.gamma(a) #for b in beta_s: v *= ctx.rgamma(b) #for w, c in zip(w_s, c_s): v *= ctx.power(w, c) v = ctx.fprod([ctx.hyper(a_s, b_s, z, **kwargs)] + \ [ctx.gamma(a) for a in alpha_s] + \ ...
reedessick/event_supervisor2
dq/dq.py
Python
mit
3,882
0.014168
description = "a module housing checks of DQ summary page functionality" author = "reed.essick@ligo.org" #--------------------------------------------------------------------------------------------------- import eventSupervisor.eventSupervisorUtils as esUtils #--------------------------------------------------...
ks tasks = [lldqReportCheck( timeout,
emailOnSuccess=emailOnSuccess, emailOnFailure=emailOnFailure, emailOnException=emailOnException, logDir=logDir, logTag='%s.%s'%(logTag, self.name), ), ] ### wrap up instantiation ...
sn6uv/gmpy_cffi
tests/test_version.py
Python
bsd-3-clause
629
0
import re import pytest from gmpy_cffi import version, mp_version, mpfr_version,
mpc_version class TestVersion: def test_version(self): s = version() assert isinstance(s, str) assert re.match(r'\d\.\d\.\d', s) def test_mp_version(self): s = mp_version() assert isinstance(s, str) assert s.startswith('GMP ') def test_mpfr_version(self):...
def test_mpc_version(self): s = mpc_version() assert isinstance(s, str) assert s.startswith('MPC ')
TheWardoctor/Wardoctors-repo
script.module.urlresolver/lib/urlresolver/plugins/vivosx.py
Python
apache-2.0
1,584
0.003157
''' vivo.sx urlresolver plugin Copyright (C) 2015 y2000j This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distr...
: name = "vivosx" domains = ["vivo.sx"] pattern = '(?://|\.)(vivo\.sx)/([0-9a-zA-Z]+)' def __init__(self): self.net = common.Net() def get_media_url(self, host, media_id): web_url = self.get_url(host, media_id) # get landing page resp = self.net.http_GET(web_url, h...
ders={'Referer': web_url}) html = resp.content r = re.search(r'Core\.InitializeStream \(\'(.*?)\'\)', html) if not r: raise ResolverError('page structure changed') b = base64.b64decode(r.group(1)) j = json.loads(b) if len(j) == 0: raise ResolverError('video not found')...
ColdMatter/EDMSuite
EDMScripts/OldScripts/AquireWithWait.py
Python
mit
689
0.033382
# MapLoop - asks ScanMaster to make a series of scans with one of the pg # parameters incremented scan to scan from DAQ.Environment import * def aquireWithEFlip(numScans): # setup fileSystem = Environs.FileSystem file = \
fileSystem.GetDataDirectory(\ fileSystem.Paths["scanMasterDataPath"])\ + fileSystem.GenerateNextDataFileName() print("Saving as " + file + "_*.zip") print("") # start looping r = range(numScans) for i in range(len(r)): print "Scan Number: " + str(r[i]) #raw_input("unplug the rf cable") sm.AcquireAnd...
ireWithEFlip(numScans)"
stefanseefeld/numba
numba/types/abstract.py
Python
bsd-2-clause
9,786
0.000511
from __future__ import print_function, division, absolute_import from abc import ABCMeta, abstractmethod, abstractproperty import itertools import weakref import numpy as np from ..six import add_metaclass from ..utils import cached_property # Types are added to a global registry (_typecache) in order to assign # ...
he[wr] = wr return inst def __call__(cls, *args, **kwargs): """ Instantiate *cls* (a Type subclass, presumably) and intern it. If an interned instance already exists, it is returned, otherwise the new instance is returned. """ inst = type.__call__(cls, *a...
def _type_reconstructor(reconstructor, reconstructor_args, state): """ Rebuild function for unpickling types. """ obj = reconstructor(*reconstructor_args) if state: obj.__dict__.update(state) return type(obj)._intern(obj) @add_metaclass(_TypeMetaclass) class Type(object): """ ...
multidadosti-erp/multidadosti-addons
hr_timesheet_to_invoice/models/account_analytic_line_to_invoice.py
Python
agpl-3.0
313
0
from odoo import fields, models class AccountAnalyticLineToInvoice(models.
Model): _name = 'account.analytic.line.to.invoice' name = fields.Char(string='Name', required=True) factor = fields.Float(string='Discount (%)', required=True) billable = fields.
Boolean(string='Billable', default=True)
coala-analyzer/coala-bears
bears/vhdl/VHDLLintBear.py
Python
agpl-3.0
2,011
0
from shutil import which from coalib.bearlib.abstractions.Linter import linter from dependency_management.requirements.DistributionRequirement import ( DistributionRequirement) @linter(executable='perl', output_format='regex', output_regex=r'.+:(?P<line>\d+):(?P<severity>.*) - (?P<message>.*)') c...
es.html#tp46> and ' 'put it into your PATH.') else: return True @staticmethod def create_argumen
ts(filename, file, config_file): return which('bakalint.pl'), '--input', filename
prologic/mio
test_parser.py
Python
mit
282
0
#!/usr/bin/python -i import sys from mio import lexer from mio import parser from mio import runtime from mio.main import parse_args opts,
args = parse_args(sys.argv) runtime.init(args, opts) eval = runtime.state.ev
al def parse(s): return parser.parse(lexer.tokenize(s))
54Pany/pupy
pupy/genpayload.py
Python
bsd-3-clause
3,991
0.028564
#!/usr/bin/env python # -*- coding: UTF8 -*- # --------------------------------------------------------------- # Copyright (c) 2015, Nicolas VERDIER (contact@n1nj4.eu) # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following c...
.type=="dll_x64": binary=get_edit_binary(os.path.join("payloads","pupyx64.dll"), args.host, args.port) outpath="pupyx64.dll" if args.output: outpath=args.output with open(outpath, 'wb') as w: w.write(binary) elif args.type=="dll_x86": binary=get_edit
_binary(os.path.join("payloads","pupyx86.dll"), args.host, args.port) outpath="pupyx86.dll" if args.output: outpath=args.output with open(outpath, 'wb') as w: w.write(binary) else: exit("Type %s is invalid."%(args.type)) print "binary generated to %s with HOST=%s"%(outpath,(args.host, args.port))
arbrandes/edx-platform
lms/djangoapps/mobile_api/users/tests.py
Python
agpl-3.0
26,677
0.003186
""" Tests for users API """ import datetime from unittest.mock import patch from urllib.parse import parse_qs import ddt import pytz from completion.test_utils import CompletionWaffleTestMixin, submit_completions_for_testing from django.conf import settings from django.db import transaction from django.template impo...
es/{self.course.id}/about' in found_course['course_about'] assert f'course_info/{self.course.id}/updates' in found_course['course_updates'] assert f'course_info/{self.course.id}/handouts' in found_course['course_handouts'] assert found_course['id'] == str(self.course.id) assert courses[0...
_url(self.course) assert expected_course_image_url is not None assert expected_course_image_url in found_course['course_image'] assert expected_course_image_url in found_course['media']['course_image']['uri'] def verify_failure(self, response, error_type=None): assert response.statu...
schleichdi2/OPENNFR-6.1-CORE
opennfr-openembedded-core/meta/lib/oeqa/selftest/prservice.py
Python
gpl-2.0
5,821
0.00481
import unittest import os import logging import re import shutil import datetime import oeqa.utils.ftools as ftools from oeqa.selftest.base import oeSelfTest from oeqa.utils.commands import runCmd, bitbake, get_bb_var from oeqa.utils.decorators import testcase from oeqa.utils.network import get_free_port class Bitbak...
s = [] for stamp in os.listdir(package_stamps_path): find_stamp = re.match("%s\.%s\.([a-z0-9]{32})" % (re.escape(prefix), recipe_task), stamp) if fi
nd_stamp: stamps.append(find_stamp.group(1)) self.assertFalse(len(stamps) == 0, msg="Cound not find stamp for task %s for recipe %s" % (recipe_task, package_name)) self.assertFalse(len(stamps) > 1, msg="Found multiple %s stamps for the %s recipe in the %s directory." % (recipe_task, pack...
huiyiqun/check_mk
tests/git/test_find_debug_code_web.py
Python
gpl-2.0
620
0.006452
#!/usr/bin/python # encoding: utf-8 import os import glob import pytest from testlib
import cmk_path, cmc_path def test_find_debug_code(): scanned = 0 for base_path in [ cmk_path(), cmc_path() ]: for dirpath, dirnames, filenames in os.walk("%s/web" % base_path)
: scanned += 1 for filename in filenames: path = "%s/%s" % (dirpath, filename) for line in open(path): l = line.lstrip() assert not l.startswith("html.debug("), \ "Found \"html.debug(...)\" call" ...
marcosgabarda/django-belt
tests/app/managers.py
Python
mit
406
0
from django.db import models from django.db.models import Count from belt.managers import Sear
chQuerySetMixin class PostQuerySet(SearchQuer
ySetMixin, models.QuerySet): pass class CategoryQuerySet(SearchQuerySetMixin, models.QuerySet): pass class BlogQuerySet(SearchQuerySetMixin, models.QuerySet): def annotate_total_posts(self): return self.annotate(total_posts=Count("posts"))
frew/simpleproto
scons-local-1.1.0/SCons/Warnings.py
Python
bsd-2-clause
5,241
0.005152
# # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 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...
PythonVersionWarning(DeprecatedWarning): pass class ReservedVariableWarning(Warning): pass class StackSizeWarning(Warning): pass class FortranCxxMixWarning(LinkWarning): pass _warningAsException = 0 # The below is a list of 2-tuples. The first element is a class object. # The second element is tr...
d. _enabled = [] _warningOut = None def suppressWarningClass(clazz): """Suppresses all warnings that are of type clazz or derived from clazz.""" _enabled.insert(0, (clazz, 0)) def enableWarningClass(clazz): """Suppresses all warnings that are of type clazz or derived from clazz.""" _enabled.i...
DigitalGlobe/gbdxtools
tests/unit/moto_test_data.py
Python
mit
1,017
0
""" These functions are written assuming the under a moto call stack. TODO add check is a fake bucket? """ import boto3 def pre_load_s3_data(bucket_name, prefix, region='us-east-1'): s3 = boto3.client('s3', region_name=region) res = s3.create_bucket(Bucket=bucket_name) default_kwargs = {"Body": b"Fake da...
es = s3.put_object(Key="{}/images/myimage{}.tif".format(prefix, i), **default_kwargs) for i, _ in enumerate(range(400)): s3.put_object(Key="{}/scripts/myscripts{}.py".format(prefix, i), **default_kwargs) for i, _ in enumerate(range(110)): s3.pu...
t( Key="{}/scripts/subdir/otherscripts{}.sh".format(prefix, i), **default_kwargs)
yhaddad/Heppi
tests/__init__.py
Python
mit
110
0.027273
# -*- coding
: utf-8 -*- __author__ = 'Yacine Haddad' __email__ = 'yhaddad@cern.ch' __version__ = '2.0.0'
ProgVal/Limnoria-test
plugins/Plugin/__init__.py
Python
bsd-3-clause
2,763
0.000362
### # Copyright (c) 2005, Jeremiah Fincher # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this list of conditi...
ERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWA
RE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. ### """ This plugin handles various plugin-related things, such as getting help for a plugin, getting a list of the loaded plugins, and searching and downloading plugins from supybot.com. """ import supybot import supybot.world as world # Use this for the vers...
ngannguyen/aimseqtk
src/geneusage/geneusage.py
Python
mit
13,077
0.002829
#Copyright (C) 2013 by Ngan Nguyen # #Released under the MIT license, see LICENSE.txt '''Gene Usage Distribution V, J, D, VJ, VDJ ttests ''' import os import sys import gzip import cPickle as pickle from optparse import OptionGroup import numpy as np import mdp from jobTree.scriptTree.target import Target from sonLi...
as statcommon import aimseqtk.src.geneusage.geneusage_plot as guplot class GeneUsageStat(SampleStat): '''Contain geneusage stats of a specific sample ''' def __init__(self): SampleStat.__init__(self) self.type2gene2clones = {} self.type2gene2reads = {} types = ['v', 'd', 'j...
[type] = {} self.type2gene2reads[type] = {} def set_stats(self, type2gene2clones, type2gene2reads): self.type2gene2clones = type2gene2clones self.type2gene2reads = type2gene2reads def sample_geneusage_stat(sample, samdir, args=None): # gene usage of a specific number # initiali...
anish/buildbot
master/buildbot/test/unit/test_steps_trigger.py
Python
gpl-2.0
28,334
0.001588
# This file is part of Buildbot. Buildbot 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, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without eve...
iggerable(name='c')
m.scheduler_manager.namedServices = dict(a=a, b=b, c=c) a.brids = {77: 11} b.brids = {78: 22} c.brids = {79: 33, 80: 44} def make_fake_br(brid, builderid): return fakedb.BuildRequest( id=brid, buildsetid=BRID_TO_BSID(brid), builderid=builderid) ...
febert/DeepRL
q_learning_sarsa/qnn.py
Python
gpl-3.0
36,944
0.009257
from __future__ import print_function from __future__ import division import tensorflow as tf import numpy as np from collections import deque class qnn: def __init__(self, size_input, size_output, discount=0.99, size_hidden = [300,400,400], ...
te initialization. Larger than zero to avoid dead ReLUs """ # if fan_in_size > 0: # if act
is None: # std=1.0/np.sqrt(fan_in_size) # elif act is tf.nn.relu: # print('relu!!!!') # std=np.sqrt(2.0)/np.sqrt(fan_in_size) # elif fan_in_size == 0: # std=0.0 std=0.0 print('bias std =', std...
mpavezb/memoria
informe/code/python/ltm_smach_sample.py
Python
agpl-3.0
811
0.007398
#!/usr/bin/env python import rospy import smach import ltm_addons.smach as ltm class SampleState(smach.State): def __init__(self, text=""): smach.State.__init__(self, outcomes=['succeeded']) ltm.register_state(self, ["sample_tag"]) def execute(self, userdata): return 'succeeded...
ltm.register_state(sm, ["a_tag", "other_tag"]) with sm: smach.StateMachine.add('FOO', SampleState(), transitions={'succeeded': 'BAR'}) smach.StateMachine.add('BAR', SampleState(),
transitions={'succeeded': 'succeeded'}) # Setup LTM callbacks ltm.setup(sm) # RUN sm.execute()
dhuang/incubator-airflow
airflow/migrations/versions/8646922c8a04_change_default_pool_slots_to_1.py
Python
apache-2.0
3,222
0.000931
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
ession.query(TaskInstance).filter(TaskInstance.pool_slots.is_(None)).update( {TaskInstance.pool_slots: 1}, synchronize_session=False ) session.commit() with op.batch_alter_table("task_instance", schema=None) as batch_op: batch_op.alter_column("pool_slots", existing_type=sa.Integer, nullable...
hema=None) as batch_op: batch_op.alter_column("pool_slots", existing_type=sa.Integer, nullable=True)
ekasitk/sahara
sahara/service/edp/oozie/engine.py
Python
apache-2.0
11,739
0
# Copyright (c) 2014 OpenStack Foundation # # 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 ...
ahara.utils import xmlutils as x CONF = cfg.CONF conductor = c.API @six.add_metaclass(abc.ABCMeta) class OozieJobEngine(base_engine.JobEngine): def __init__(self, cluster): self.cluster = cluster self.plugin = job_utils.get_plugin(self.cluster) def _get_client(self): return o.Oozi...
f.cluster), self.get_oozie_server(self.cluster)) def _get_oozie_job_params(self, hdfs_user, path_to_workflow, oozie_params, use_hbase_lib): app_path = "oozie.wf.application.path" oozie_libpath_key = "oozie.libpath" oozie_libpath = "...
reignofmiracle/RM_Torrent
TorrentPython/TorrentPython/Downloader.py
Python
mit
1,176
0.001701
import pykka from rx.subjects import * from TorrentPython.DownloadManager import * from TorrentPython.RoutingTable import * class DownloaderActor(pykka.ThreadingActor): def __init__(self, downloader): super(Downloa
derActor, self).__init__() self.downloader = downloader self.download_manager = DownloadManager(downloader) def on_receive(self, message): return message.get('func')(self) def from_start(self): pass def from_stop(self): pass
class Downloader(Subject): def __init__(self, client_id, metainfo, path, routing_table=None): super(Downloader, self).__init__() self.client_id = client_id self.metainfo = metainfo self.path = path self.routing_table = routing_table or RoutingTable.INITIAL_ROUTING_TABLE ...
yyy1394/redis-monitor
src/api/controller/SlowlogController.py
Python
mit
685
0.029197
from Base
Controller import BaseController import datetime import redis class SlowlogController(BaseCont
roller): def get(self): data={} data['data']=[] server = self.get_argument("server").split(':') connection = redis.Redis(host=server[0], port=(int)(server[1]), db=0,socket_timeout=1) logs = connection.execute_command('slowlog','get','128') for lid,timeticks,run_micro...
qusp/orange3
Orange/widgets/data/owmergedata.py
Python
bsd-2-clause
8,896
0.000337
import math import itertools from collections import defaultdict from PyQt4 import QtGui, QtCore import numpy import Orange from Orange.widgets import widget from Orange.widgets import gui from Orange.widgets.utils import itemmodels class OWMergeData(widget.OWWidget): name = "Merge Data" description = "Mer...
e): key = [inst[a] for a in key_vars] if exclude_unknown and any(math.isnan(k) for k in key): continue key = tuple([str(k) for k in key]) groups[key].append(i) return groups def left_join_indices(table1, table2, vars1, vars2): key_map1 = group_table_in
dices(table1, vars1) key_map2 = group_table_indices(table2, vars2) indices = [] for i, inst in enumerate(table1): key = tuple([str(inst[v]) for v in vars1]) if key in key_map1 and key in key_map2: for j in key_map2[key]: indices.append((i, j)) else: ...
jmaas/zenossctl
docs/conf.py
Python
gpl-2.0
7,813
0.007555
# -*- coding: utf-8 -*- # # Cobbler documentation build configuration file, created by # sphinx-quickstart on Sat Aug 23 06:59:22 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. # # All...
encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'zenossctl' copyright = u'2014-2015, Jörgen Maas' # The version info for the project you're documenting, acts as replacement for # |version| and |release|,...
rt X.Y version. version = '1.2' # The full version, including alpha/beta/rc tags. release = '1.2.0' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false ...
her001/tmdrv
tmdrv.py
Python
gpl-3.0
3,992
0.0248
#!/usr/bin/env python3 # Copyright 2016, 2017 Andrew Conrad # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This ...
ets for initialization for m in device.control: try: _control_init( device.idVendor, device.idProduct[m[
'step'] - 1], m['request_type'], m['request'], m['value'], m['index'], m['data'], ) except usb1.USBErrorNotFound: print('Error getting handle for device {:0=4x}:{:0=4x} ({} Step {}).'.format(device.idVendor, device.idProduct[m['step']-1], device.name, m['step'])) raise except usb1.USBEr...
marclr/passwordGenerator
Multipass.py
Python
mit
8,642
0.003009
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'Multipass.ui' # # Created: Tue Feb 04 23:58:25 2014 # by: PyQt4 UI code generator 4.10.3 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except Attr...
self.username_label.setGeometry(QtCore.QRect(20, 16, 151, 20)) font = QtGui.QFont() font.setFamily(_fromUtf8("Consolas")) font.setPointSize(12) self.username_label.setFont(font) self.username_label.setLocale(QtCore.QLocale(QtC
ore.QLocale.English, QtCore.QLocale.UnitedStates)) self.username_label.setObjectName(_fromUtf8("username_label")) self.domain_label = QtGui.QLabel(self.widget) self.domain_label.setGeometry(QtCore.QRect(210, 16, 161, 20)) font = QtGui.QFont() font.setFamily(_fromUtf8("Consolas"))...
koct9i/linux
scripts/gdb/linux/tasks.py
Python
gpl-2.0
3,545
0
# # gdb helper commands and functions for Linux kernel debugging # # task & thread tools # # Copyright (c) Siemens AG, 2011-2013 # # Authors: # Jan Kiszka <jan.kiszka@siemens.com> # # This work is licensed under the terms of the GNU GPL version 2. # import gdb from linux import utils task_type = utils.CachedType(...
task_ptr_type, "thread_group") if t == g: break t = g = utils.container_of(g['tasks']['next'], task_ptr_type, "tasks") if t == init_task: return def get_task_b
y_pid(pid): for task in task_lists(): if int(task['pid']) == pid: return task return None class LxTaskByPidFunc(gdb.Function): """Find Linux task by PID and return the task_struct variable. $lx_task_by_pid(PID): Given PID, iterate over all tasks of the target and return that task_stru...
induktio/LamaTrainer
falib/RegexParser.py
Python
gpl-3.0
6,711
0.00909
from NfaBuilder import NfaBuilder def enum(**enums): return type('Enum', (), enums) nodeTypes = enum(CHARACTER = 1, STAR = 2, QUESTION = 3, ALTER = 4, CONCAT = 5, PLUS = 6) specialTransitions = enum(EPSILON = -1) class ParseError( Exception ): pass class ParseNode(): """ Represents a node in the result...
f.next] if self.next < len(self.data) el
se 0 def pop(self): """ Pops character from regex string Returns: Popped character """ nextChar = self.peek() if self.next < len(self.data): self.next += 1 return nextChar def current_position(self): """ ...
pbmanis/acq4
acq4/modules/TaskRunner/analysisModules/AnalysisModule.py
Python
mit
1,578
0.006971
# -*- coding: utf-8 -*- from __future__ import print_function from acq4.util import Qt from acq4.pyqtgraph.WidgetGroup import WidgetGroup class AnalysisModule(Qt.QWidget): def __init__(self, taskRunner): Qt.QWidget.__init__(self) self.pr = taskRunner self.pr.sigNewFrame.connect(self.newFram...
ed) self.pr.sigTaskFinished.connect(self.taskFinished) def postGuiInit(self): self.stateGroup = WidgetGroup(self) def newFrame(self, *args): pass #print "NEW FRAME!" #print args def taskStarted(self, *args): pass #print "taskStarted!" d...
pass #print "taskStarted!" def saveState(self): return self.stateGroup.state() def restoreState(self, state): self.stateGroup.setState(state) def quit(self): try: self.pr.sigNewFrame.disconnect(self.newFrame) except TypeErro...
lzkelley/zcode
zcode/math/tests/test_math_core.py
Python
mit
31,267
0.001055
"""Test methods for `zcode/math/math_core.py`. Can be run with: $ nosetests math/tests/test_math_core.py $ nosetests math/tests/test_math_core.py:TestMathCore.test_around $ python math/tests/test_math_core.py """ from __future__ import absolute_import, division, print_function, unicode_literals import nu...
power(10.0, 0.0), np.power(10.0, 2.5)], scale='log', num=20) assert_true(np.allclose(ref2, spc2)) # Automatically selects appropriate Range ref3 = np.logspace(1.0, 2.0, num=13) spc3 = spacing([-10.0, 100.0, 0.0, 10.0], scale='log', num=13) assert_true(np.allclose(ref3, spc3)) ...
, -2.5, -5.0, 0.0], scale='lin', num=27, filter='<') assert_true(np.allclose(ref4, spc4)) # Only integral (whole number) values # log spacing vals = [2.34, 365.23] res = np.array([2., 3., 4., 5., 6., 7., 8., 9., 10., 20., 30., 40., 50., 60., 70., 80., 90....
rupak0577/ginga
ginga/web/pgw/PgHelp.py
Python
bsd-3-clause
6,284
0.00175
# # PgHelp.py -- web application threading help routines. # # Eric Jeschke (eric@naoj.org) # # Copyright (c) Eric R. Jeschke. All rights reserved. # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. # import tornado.web import tornado.websocket import tornado.tem...
efault_interval = 10 ConfigEvent = namedtuple("ConfigEvent", ["type", "id", "width", "height"]) InputEvent = namedtuple("InputEvent", ["type",
"id", "x", "y", "button", "delta", "alt_key", "ctrl_key", "meta_key", "shift_key", "key_code"]) GestureEvent = namedtuple("GestureEvent", ["type", "id", "x", "y", "dx", "dy", "distance", ...
scupid-admin/morph-python-sdk
morph/action.py
Python
mit
1,819
0.001649
""" Your code basically returns a list of actions. This is the goal of your code. There are 3 type of Actions that you can add. 1) GoToFlow - Used for jumping to a conversation 2) SetVariable - Used for setting an attribute 3) Publish - Used to reply back to the user Actions are executed in the order that you send th...
riable_title, variable): Action.__init__(self, name="setVariableAction") self.variable_scope = variable_scope self.variable_title = variable_title self.variable = variable def to_json(self): attr = {'name': self.name, 'variableScope': self.variable_s
cope, 'variableTitle': self.variable_title, 'variable': self.variable.to_json()} return attr class Publish(Action): def __init__(self): Action.__init__(self, name="publish") self.messages = [] def add_message(self, message): self.messages.append(message) d...
jabesq/home-assistant
homeassistant/components/homekit_controller/config_flow.py
Python
apache-2.0
13,073
0
"""Config flow to configure homekit_controller.""" import os import json import logging import voluptuous as vol from homeassistant import config_entries from homeassistant.core import callback from .const import DOMAIN, KNOWN_DEVICES from .connection import get_bridge_information, get_accessory_name HOMEKIT_IGNOR...
"HomeKit device %s: c# not exposed, in violation of spec", hkid) config_num = None if paired: if hkid in self.hass.data.get(KNOWN_DEVICES, {}):
# The device is already paired and known to us # According to spec we should monitor c# (config_num) for # changes. If it changes, we check for new entities conn = self.hass.data[KNOWN_DEVICES][hkid] if conn.config_num != config_num: ...
ogajduse/spacewalk
backend/server/test/unit-test/rhnSQL/misc_functions.py
Python
gpl-2.0
15,041
0.000864
#!/usr/bin/python # # Copyright (c) 2008--2016 Red Hat, Inc. # # This software is licensed to you under the GNU General Public License, # version 2 (GPLv2). There is NO WARRANTY for this software, express or # implied, including the implied warranties of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. You should...
s.set_name(name) s.set_description(description) s.save() rhnSQL.commit() return s def create_server_group(params): "Create a server group from a dictionary with the params" return _create_server_group(*(), **params) def fetch_server_group(org_id, name)
: "Load a server group object from the org id and name" s = rhnServerGroup.ServerGroup() s.load(org_id, name) return s _query_fetch_server_groups = rhnSQL.Statement(""" select sgm.server_group_id from rhnServerGroupMembers sgm, rhnServerGroup sg where sgm.server_id = :server_i...
mattcongy/movie-converter
mconverter/__init__.py
Python
mit
9,117
0.000658
#!/usr/bin/python import os from mconverter.avcodecs import video_codec_list, audio_codec_list, subtitle_codec_list from mconverter.formats import format_list from mconverter.ffmpeg import FFMpeg, FFMpegError, FFMpegConvertError class ConverterError(Exception): pass class Converter(object): """ Conver...
erError('Source file has no audio or video streams') if info.video and 'video' in options: options = options.copy() v = options['video'] = options['video'].copy() v['src_width'] = info.video.video_width
v['src_height'] = info.video.video_height if info.format.duration < 0.01: raise ConverterError('Zero-length media') if twopass: optlist1 = self.parse_options(options, 1) for timecode in self.ffmpeg.convert(infile, outfile, optlist1, ...
romanoved/nanomsg-python
_nanomsg_ctypes/__init__.py
Python
mit
8,282
0.000604
from __future__ import division, absolute_import, print_function,\ unicode_literals import ctypes import platform import sys if sys.platform in ('win32', 'cygwin'): _functype = ctypes.WINFUNCTYPE _lib = ctypes.windll.nanomsg else: _functype = ctypes.CFUNCTYPE _lib = ctypes.cdll.LoadLibrary('libnanoms...
anomsg_cpy.Message size %d, address 0x%x >' % ( self._len, self._address ) def __str__(self): return bytes(buffer(self)) def __del__(self): _nn_freemsg(self._address) self._len = 0 self._address = 0 return...
sage.from_address(address) def nn_allocmsg(size, type): "allocate a message" pointer = _nn_allocmsg(size, type) if pointer is None: return None return _create_message(pointer, size) def nn_recv(socket, *args): "receive a message" if len(args) == 1: flags, = args point...