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
ardi69/pyload-0.4.10
pyload/plugin/hoster/LetitbitNet.py
Python
gpl-3.0
4,139
0.003866
# -*- coding: utf-8 -*- # # API Documentation: # http://api.letitbit.net/reg/static/api.pdf # # Test links: # http://letitbit.net/download/07874.0b5709a7d3beee2408bb1f2eefce/random.bin.html import re import urlparse from pyload.utils import json_loads, json_dumps from pyload.network.RequestFactory import getURL f...
response(url) if api_rep['status'] == 'OK': info = api_rep['data'][0] yield (info['name'], info['size'], 2, url) else: yield (url, 0, 1, url) class LetitbitNet(SimpleHoster): __name = "LetitbitNet" __type = "hoster" __version
= "0.30" __pattern = r'https?://(?:www\.)?(letitbit|shareflare)\.net/download/.+' __config = [("use_premium", "bool", "Use premium account if available", True)] __description = """Letitbit.net hoster plugin""" __license = "GPLv3" __authors = [("zoidberg", "zoidberg@mujmail.cz"), ...
xifle/home-assistant
tests/components/test_rfxtrx.py
Python
mit
5,523
0
"""The tests for the Rfxtrx component.""" # pylint: disable=protected-access import unittest import pytest from homeassistant.core import callback from homeassistant.bootstrap import setup_component from homeassistant.components import rfxtrx as rfxtrx from tests.common import get_test_home_assistant @pytest.mark.s...
valid_config(self): """Test configuration.""" self.assertFalse(setup_component(self.hass, 'rfxtrx', { 'rfxtrx': {} })) self.assertFalse(setup_component(self.hass, 'rfxtrx', { 'rfxtrx': { 'device': '/dev/serial/by-id/usb' +
'-RFXCOM_RFXtrx433_A1Y0NJGR-if00-port0', 'invalid_key': True}})) def test_fire_event(self): """Test fire event.""" self.assertTrue(setup_component(self.hass, 'rfxtrx', { 'rfxtrx': { 'device': '/dev/serial/by-id/usb' + ...
javnik36/ZTMtoGTFS
bugs_checker_osm.py
Python
mit
547
0.005484
import re osm
= open("stops.txt", 'r', encoding="utf-8") bugs = open("BAD-STOPS.txt", 'r', encoding="u
tf-8") still = open("BUGS-NOT-IN-OSM.txt", 'w') bugi = [] for line in bugs: line = line.split(' ') bugi.append(line[0]) print(len(bugi)) for line in osm: line = line.split(',') if line[0].isnumeric(): stop_nr = line[0] if stop_nr in bugi: bugi.remove(stop_nr) f...
marshmallow-code/marshmallow-jsonapi
tests/conftest.py
Python
mit
1,521
0
import pytest from tests.base import Author, Post, Comment, Keyword, fake def make_author(): return Author( id=fake.random_int(), first_name=fake.first_name(), last_name=fake.last_name(), twitter=fake.domain_word(), ) def make_post(with_comments=True, with_author=True, with_...
ne, comments=comments, keywords=keywords, ) def make_comment(with_author=True): author = make_author() if with_au
thor else None return Comment(id=fake.random_int(), body=fake.bs(), author=author) def make_keyword(): return Keyword(keyword=fake.domain_word()) @pytest.fixture() def author(): return make_author() @pytest.fixture() def authors(): return [make_author() for _ in range(3)] @pytest.fixture() def c...
jyejare/robottelo
pytest_plugins/testimony_markers.py
Python
gpl-3.0
5,447
0.002937
import inspect import re import pytest from robottelo.logging import collection_logger as logger IMPORTANCE_LEVELS = [] def pytest_addoption(parser): """Add CLI options related to Testimony token based mark collection""" parser.addoption( '--importance', help='Comma separated list of import...
nt', help='Comma separated list of component names to include in test collection', ) parser.addoption( '--assignee', help='Comma separated list of assignees to include in test collection', ) def pytest_configure(config): """Register markers related to testimony tokens""" fo...
timony token, use --importance to filter', 'component: Component testimony token, use --component to filter', 'assignee: Assignee testimony token, use --assignee to filter', ]: config.addinivalue_line("markers", marker) component_regex = re.compile( # To match :CaseComponent: FooBar ...
RPGOne/Skynet
scikit-learn-0.18.1/examples/neural_networks/plot_mlp_training_curves.py
Python
bsd-3-clause
3,692
0.001354
""" ======================================================== Compare Stochastic learning strategies for MLPClassifier ======================================================== This example visualizes some training loss curves for different stochastic learning strategies, including SGD and Adam. Because of time-constrai...
ning-rate", "inv-scaling with momentum", "inv-scaling with Nesterov's momentum", "adam"] plot_args = [{'c': 'red', 'linestyle': '-'}, {'c': 'green', 'linestyle': '-'}, {'c': 'blue', 'linestyle': '-'}, {'c': 'red', 'linestyle': '--'}, {'c': 'green', '
linestyle': '--'}, {'c': 'blue', 'linestyle': '--'}, {'c': 'black', 'linestyle': '-'}] def plot_on_dataset(X, y, ax, name): # for each dataset, plot learning for each learning strategy print("\nlearning on dataset %s" % name) ax.set_title(name) X = MinMaxScaler().fit_transfor...
mbayon/TFG-MachineLearning
venv/lib/python3.6/site-packages/scipy/misc/tests/test_doccer.py
Python
mit
3,171
0.002523
''' Some tests for the documenting decorator and support functions ''' from __future__ import division, print_function, absolute_import import sys import pytest from numpy.testing import assert_equal from scipy.misc import doccer # python -OO strips docstrings DOCSTRINGS_STRIPPED = sys.flags.optimize > 1 docstring...
def func(self): '''%(super)sABC''' return @doccer.inherit_docstring_from(Foo) def func2(self): # No docstring. return assert_equal(Bar.func.__doc__, Foo.func.__doc__ + 'ABC') assert_equal(Bar.func2.__doc__, Foo.func2.__doc_
_) bar = Bar() assert_equal(bar.func.__doc__, Foo.func.__doc__ + 'ABC') assert_equal(bar.func2.__doc__, Foo.func2.__doc__)
nicfit/vexmpp
vexmpp/stream.py
Python
mit
11,877
0.000168
import os import asyncio import logging from functools import partial from collections import deque from lxml import etree from . import stanzas from .stanzas import Iq from .parser import Parser from .utils import signalEvent from .utils import benchmark as timedWait from . import getLogger log = getLogger(__name_...
ric stream_wait_met = ValueMetric("stream:wait_time", type_=float) else: stream_wait_met = None _ENFORCE_TIMEOUTS = bool("VEX_ENFORCE_TIMEOUTS" in os.environ and int(os.environ["VEX_ENFORCE_TIMEOUTS"])) class QueuedStanza: def __init__(self, s): self.task_set = set() ...
super().__init__(self._run(), loop=loop) self._parser = Parser() self._data_queue = asyncio.Queue() self._stream = stream def parse(self, bytes_): self._data_queue.put_nowait(bytes_) def reset(self): self._parser.reset() async def _run(self): while T...
opennode/nodeconductor-assembly-waldur
src/waldur_mastermind/support/models.py
Python
mit
14,894
0.00141
import logging import re from django.conf import settings from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models from django.utils.translation import ugettext_lazy as _ from django_fsm import FSMIntegerField from model_ut...
(blank=True, null=True) template = models.ForeignKey( 'Template', related_name='issues', blank=True, null=
True, on_delete=models.PROTECT, ) feedback_request = models.BooleanField( blank=True, default=True, help_text='Request feedback from the issue creator after resolution of the issue', ) tracker = FieldTracker() def get_description(self): return self.descripti...
indevgr/django
django/views/debug.py
Python
bsd-3-clause
46,822
0.001474
from __future__ import unicode_literals import re import sys import types from django.conf import settings from django.http import HttpResponse, HttpResponseNotFound from django.template import Context, Engine, TemplateDoesNotExist from django.template.defaultfilters import force_escape, pprint from django.urls impor...
of the project's TEMPLATES setting. DEBUG_ENGINE = Engine(debug=True) HIDDEN_SETTINGS = re.compile('API|TOKEN|KEY|SECRET|PASS|SIGNATURE', flags=re.IGNORECASE) CLEANSED_SUBSTITUTE = '********************' class CallableSettingWrapper(object): """ Object to wrap callable appearing in settings * Not to call i...
to set attributes (#23070). """ def __init__(self, callable_setting): self._wrapped = callable_setting def __repr__(self): return repr(self._wrapped) def cleanse_setting(key, value): """Cleanse an individual setting key/value of sensitive content. If the value is a dictionary, r...
youfou/wxpy
wxpy/__init__.py
Python
mit
2,313
0.002017
#!/usr/bin/env python3 # coding: utf-8 """ 登陆微信:: # 导入模块 from wxpy import * # 初始化机器人,扫码登陆 bot = Bot() 找到好友:: # 搜索名称含有 "游否" 的男性深圳好友 my_friend = bot.friends().search('游否', sex=MALE, city="深圳")[0] 发送消息:: # 发送文本给好友 my_friend.send('Hello WeChat!') # 发送图片 my_friend.send_image('...
error, embed, ensure_one, mutual_friends __title__ = 'wxpy' __version__ = '0.3.9.8' __author__ = 'Youfou' __license__ = 'MIT' __copyright__ = '2017, Youfou' version_details = 'wxpy {ver} from
{path} (python {pv.major}.{pv.minor}.{pv.micro})'.format( ver=__version__, path=__path__[0], pv=sys.version_info) try: # Python 2.7+ from logging import NullHandler except ImportError: class NullHandler(logging.Handler): def emit(self, record): pass logging.getLogger(__name__).add...
Garrett-R/scikit-learn
doc/sphinxext/gen_rst.py
Python
bsd-3-clause
38,936
0.000719
""" Example generation for the scikit learn Generate the rst files for the examples by iterating over the python example files. Files that generate images should start with 'plot' """ from __future__ import division, print_function from time import time import ast import os import re import shutil import traceback i...
esp.headers.get('content-encoding', 'plain') data = resp.read() if encoding == 'pl
ain': pass elif encoding == 'gzip': data = StringIO(data) data = gzip.GzipFile(fileobj=data).read() else: raise RuntimeError('unknown encoding') else: with open(url, 'r') as fid: data = fid.read() fid.close() return dat...
ashwyn/eden-message_parser
modules/s3/s3import.py
Python
mit
123,322
0.002092
# -*- coding: utf-8 -*- """ Resource Import Tools @copyright: 2011-12 (c) Sahana Software Foundation @license: MIT 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 ...
s3_rest_controller(module, resourcename, csv_extra_fields=[ dict(label="ColumnLabelInTheCSV",
field=field_instance) ]) The Field instance "field" will be added to the upload form, and the user input will be added to each row of the CSV under the label as specified. If the "field" validator has options, the ...
acsone/mozaik
mozaik_communication/models/__init__.py
Python
agpl-3.0
178
0
# -*- coding: utf-8 -
*- # Copyright 2016 ACSONE SA/NV (<http://a
csone.eu>) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from . import mass_mailing_stats
apporc/nova
nova/scheduler/filters/disk_filter.py
Python
apache-2.0
3,099
0.001613
# Copyright (c) 2012 OpenStack Foundation # 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 ...
_allocation_ratio used_disk_mb = total_usable_disk_mb - free_disk_mb usable_disk_mb = disk_mb_limit - used_disk_mb if not usable_disk_mb >= requested_disk: LOG.debug
("%(host_state)s does not have %(requested_disk)s MB " "usable disk, it only has %(usable_disk_mb)s MB usable " "disk.", {'host_state': host_state, 'requested_disk': requested_disk, 'usable_disk_mb': usable_disk_mb}) ...
zlsun/XX-Net
code/default/launcher/simple_i18n.py
Python
bsd-2-clause
4,279
0.001168
import locale import os import subprocess import sys class SimpleI18N: def __init__(self, lang=None): if lang: self.lang = lang else: self.lang = self.get_os_language() if not self.lang: self.lang = "en_US" def get_os_language(self): try: ...
line = fp.readline() if not line:
break if line.startswith("\""): key += line[1:-2] elif line.startswith("msgstr "): value += line[8:-2] break else: break wh...
kaspermarstal/SimpleElastix
Examples/ImageGridManipulation/ImageGridManipulation.py
Python
apache-2.0
2,424
0.006601
#!/usr/bin/env python #========================================================================= # # Copyright Insight Software Consortium # # 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 ...
implied. # See the License for the s
pecific language governing permissions and # limitations under the License. # #========================================================================= from __future__ import print_function import SimpleITK as sitk import sys if len ( sys.argv ) < 3: print( "Usage: " +sys.argv[0]+ " <input-1> <input-2>" ) ...
RedHatInsights/insights-core
insights/parsers/package_provides_java.py
Python
apache-2.0
3,087
0.002915
""" PackageProvidesJava - command ``/bin/echo {java_command_package}`` ================================================================== .. warning:: This module is deprecated, please use :mod:`insights.parsers.package_provides` instead. This command reads the output of the pre-command: ``for jp in `/bin/p...
d the links between running_java_command and package which provi
des the java command. In ``ps aux`` output, we can only get what java command starts a java application, instead of java package. Through this way, when there is jdk bug, we can detect whether a running java application will be affected. Typical contents of the pre_command:: /usr/lib/jvm/jre/bin/java java-1.8.0-o...
airbnb/airflow
tests/test_utils/perf/perf_kit/sqlalchemy.py
Python
apache-2.0
8,062
0.001737
# 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 u...
whether many statements executed :return: """ total = time.monotonic() - conn.info["query_start_time"].pop() file_names = [ f"{f.filename}:{f.name}:{f.lineno}" for f in traceback.extract_stack() if "sqlalchemy" not in f.filename ] file...
f in traceback.extract_stack() if "sqlalchemy" not in f.filename] stack_info = " > ".join([f"{f.filename.rpartition('/')[-1]}:{f.name}:{f.lineno}" for f in stack][-7:]) conn.info.setdefault("query_start_time", []).append(time.monotonic()) output_parts = [] if self.display_num: ...
the-blue-alliance/the-blue-alliance
src/backend/common/consts/media_tag.py
Python
mit
1,026
0
import enum from typing import Dict, Optional, Set @enum.unique class MediaTag(enum.IntEnum): # ndb keys are based on these! Don't change! CHAIRMANS_VIDEO = 0 CHAIRMANS_PRESENTATION = 1 CHAIRMANS_ESSAY = 2 MEDIA_TAGS: Set[MediaTag] = {t for t in MediaTag}
TAG_NAMES: Dict[MediaTag, str] = { MediaTag.CHAIRMANS_VIDEO: "Chairman's Video", MediaTag.CHAIRMANS_PRESENTATION: "Chairman's Presentation", MediaTag.CHAIRMANS_ESSAY: "Chairman's Essay", } TAG_URL_NAMES: Dict[MediaTag, str] = { MediaTag.CHAIRMANS_VIDEO: "chairmans_video", MediaTag.CHAIRMANS_PRESENT...
diaTag.CHAIRMANS_PRESENTATION, MediaTag.CHAIRMANS_ESSAY, } def get_enum_from_url(url_name: str) -> Optional[MediaTag]: inversed = {v: k for k, v in TAG_URL_NAMES.items()} if url_name in inversed: return inversed[url_name] else: return None
magul/volontulo
backend/apps/volontulo/admin.py
Python
mit
315
0
# -*- coding: utf-8 -*- """ .. module:: admin """ from django.contrib import admin from apps.volontulo.models import Of
fer from apps.volontulo.models import Organization from apps.volontulo.models import UserProfile admin.site.register(Offer) admin.sit
e.register(Organization) admin.site.register(UserProfile)
sputnick-dev/weboob
weboob/browser/filters/standard.py
Python
agpl-3.0
24,256
0.00198
# -*- coding: utf-8 -*- # Copyright(C) 2014 Romain Bignon # # This file is part of weboob. # # weboob is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your opti...
e cell value from its name. For examp
le: >>> from weboob.capabilities.bank import Transaction >>> from weboob.browser.elements import TableElement, ItemElement >>> class table(TableElement): ... head_xpath = '//table/thead/th' ... item_xpath = '//table/tbody/tr' ... col_date = u'Date' ... col_label = [u'Na...
kaplun/Invenio-OpenAIRE
modules/bibexport/lib/bibexport_method_fieldexporter_webinterface.py
Python
gpl-2.0
22,858
0.012162
# -*- coding: utf-8 -*- ## $Id: webmessage_webinterface.py,v 1.13 2008/03/12 16:48:08 tibor Exp $ ## ## 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 t...
RL, ) _JOB_QUERIES_URL = "%s/exporter/job_queries" % (CFG_SITE_URL, ) _JOB_HISTORY_URL = "%s/exporter/history" % (CFG_SITE_URL, ) _NOT_AUTHORIZED_URL = "%s/exporter/not_authorized" % (CFG_SITE_URL, ) _LOGIN_URL = "%s/youraccount/login" % (CFG_SITE_SECURE_URL,) _NAVTRAIL_EXPORT = """<a href="/expor
ter" class="navtrail">Export</a>""" def index(self, req, form): """ The function called by default""" redirect_to_url(req, self._JOB_HISTORY_URL) __call__ = index def jobs(self, req, form): """Displays all the jobs of a given user and allows creation, deletion and executio...
QISKit/qiskit-sdk-py
qiskit/transpiler/fencedobjs.py
Python
apache-2.0
2,608
0.002301
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any...
ks if the attribute name is in the list of attributes to protect
. If so, raises TranspilerAccessError. Args: name (string): the attribute name to check Raises: TranspilerAccessError: when name is the list of attributes to protect. """ if name in object.__getattribute__(self, '_attributes_to_fence'): raise...
publica-io/django-publica-pages
pages/migrations/0001_initial.py
Python
bsd-3-clause
1,903
0.002627
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings import entropy.mixins class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('templates', '__firs...
b_index=True)), ('featured', models.BooleanField(default=False)), ('published_at', models.DateField(null=True)), ('created_by', models.ForeignKey(related_name='pages_page_created_by', blank=True, to=settings.AUTH_USER_MODEL, null=True)), ('modified_by', mo...
('preview_template', models.ForeignKey(related_name='pages_page_preview_templates', blank=True, to='templates.Template', null=True)), ('template', models.ForeignKey(related_name='pages_page_templates', blank=True, to='templates.Template', null=True)), ], options={ ...
be-cloud-be/horizon-addons
partner-contact/partner_contact_weight/models/res_partner.py
Python
agpl-3.0
534
0
# -*- coding: utf-8 -*- # Copyright 2016 Ursa Information Systems <http://ursainfosystems.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from openerp import fields, mo
dels class ResPartner(models.Model): _inherit = 'res.partner' weight = fields.Float("Weight") weight_uom = fields.Many2one( "product.uom", "Weight UoM", domain=lambda self: [('category_id', '=',
self.env.ref('product.product_uom_categ_kgm').id) ] )
MLAB-project/weewx
bin/weewx/drivers/ws23xx.py
Python
gpl-3.0
79,475
0.004328
#!usr/bin/env python # # Copyright 2013 Matthew Wall # See the file LICENSE.txt for your full rights. # # Thanks to Kenneth Lavrsen for the Open2300 implementation: # http://www.lavrsen.dk/foswiki/bin/view/Open2300/WebHome # description of the station communication interface: # http://www.lavrsen.dk/foswiki/bin/vie...
0xff) && (((x[2] & 0xf) == 0) || ((x[2] & 0xf) == 1)))) { sleep 10 } else { dir = x[2] >> 4 speed = ((((x[2] & 0xf) << 8) + (x[1])) / 10.0) dir0 = (x[2] >> 4) * 22.5 dir1 = (x[3] & 0xf) * 22.5 dir2 = (x[3] >> 4) *
22.5 dir3 = (x[4] & 0xf) * 22.5 dir4 = (x[4] >> 4) * 22.5 dir5 = (x[5] & 0xf) * 22.5 } ws2300.py 1.8 implementation: read 1 nibble starting at 0x527 read 1 nibble starting at 0x528 read 4 nibble starting at 0x529 read 3 nibble starting at 0x529 read 1 nibble starting at 0x52c read 1 nibble starting at 0x52d re...
jhs/strangle
test/testlibbind_ns_msg.py
Python
gpl-2.0
2,294
0.01918
#!/usr/bin/env python # # testlibbind_ns_msg.py - Unit tests for the libbind ns_msg wrapper # # This file is part of Strangle. # # Strangle 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 t...
Invalid(self): """Test whether the ns_msg type can handle bad data""" rng = testutils.rng for testNum in range(0, 50): packetLength = random.randrange(20, 80) packetVal = rng.read(packetLength) self.assertRaises(TypeError, libbind.ns_msg, packetVal) def testParseValidQuery(self): """Tes...
ype(n) is libbind.ns_msg) def testParseValidResponse(self): """Test whether ns_msg initialization parses valid NS queries""" packetData = file("data/www.company.example-response").read() n = libbind.ns_msg(packetData) assert(type(n) is libbind.ns_msg) def suite(): s = unittest.TestSuite() s.addTest( u...
ncoghlan/pip
pip/utils/__init__.py
Python
mit
25,452
0.000118
from __future__ import absolute_import from collections import deque import contextlib import errno import locale # we have a submodule named 'logging' which would shadow this if we used the # regular name: import logging as std_logging import re import os import posixpath import shutil import stat import subprocess i...
le 1: if os.environ.get('PIP_NO_INPUT'): raise Exception( 'No input was expected ($PIP_NO_INPUT set); question: %s' % message ) response = input(message) response = response.strip().lower() if response not in options: pr...
) ) else: return response def format_size(bytes): if bytes > 1000 * 1000: return '%.1fMB' % (bytes / 1000.0 / 1000) elif bytes > 10 * 1000: return '%ikB' % (bytes / 1000) elif bytes > 1000: return '%.1fkB' % (bytes / 1000.0) else: return ...
pytroll/pytroll-db
trolldb/hl_file.py
Python
gpl-3.0
7,220
0.00097
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2010, 2011, 2012, 2014, 2015. # Author(s): # Martin Raspaud <martin.raspaud@smhi.se> # This file is part of pytroll. # Pytroll is free software: you can redistribute it and/or modify it under the # terms of the GNU General Public License as published b...
parameter=p
_track) else: try: self.dbm.session.query(db.ParameterValue).join(db.Parameter).filter( db.ParameterValue.uid == self.uid).filter(db.Parameter.parameter_name == key).one().data_value except NoResultFound: self.dbm.create_parameter_valu...
CodigoSur/cyclope
cyclope/apps/feeds/migrations/0001_initial.py
Python
gpl-3.0
8,615
0.008358
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Feed' db.create_table('feeds_feed', ( ('id', self.gf('django.db.models.fields....
'user': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'comment_comments'", 'null': 'True', 'to': "orm['auth.User']"}), 'user_email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'user_name': ('django.db.mo...
: 'True'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), ...
enjaz/enjaz
niqati/migrations/0002_add_categories.py
Python
agpl-3.0
1,163
0.003484
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations def add_categories(apps, schema_editor): Category = apps.get_model('niqati', 'Category') # We are going to add categories only if none already exists. if not Category.objects.exists(): Category...
ints=3) Category.objects.create(label="Organizer", ar_label="تنظي
م", points=2) Category.objects.create(label="Participation", ar_label="مشاركة", points=1) def remove_categories(apps, schema_editor): Category = apps.get_model('niqati', 'Category') Category.objects.filter(l...
xiaoxq/apollo
modules/tools/restore_video_record/restore_video_record.py
Python
apache-2.0
9,788
0.002043
#!/usr/bin/env python3 ############################################################################### # Copyright 2019 The Apollo Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy...
code = os.system('{} --input_video={} --output_dir={}'.format( video_decoder_exe, self.video_file, self.image_dir)) if return_code != 0: logging.error('Failed to execute video2jpg for video {}'.format(self.video_file)) return False g
enerated_images = sorted(glob.glob('{}/*.jpg'.format(self.image_dir))) if len(generated_images) != len(self.image_ids): logging.error('Mismatch between original {} and generated frames {}'.format( len(self.image_ids), len(generated_images))) return False for idx i...
digwanderlust/pants
contrib/cpp/src/python/pants/contrib/cpp/tasks/cpp_compile.py
Python
apache-2.0
3,678
0.006797
# coding=utf-8 # Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os from pant...
elf): """Compile all sources in a given target to object files.""" def is_cc(source): _, ext = os.path.splitext(source) return ext[1:] in self.get_options().cc_exten
sions targets = self.context.targets(self.is_cpp) # Compile source files to objects. with self.invalidated(targets, invalidate_dependents=True) as invalidation_check: obj_mapping = self.context.products.get('objs') for vt in invalidation_check.all_vts: for source in vt.target.sources_r...
maxrbc/daedalus
scripts/make_features_quatification_table.py
Python
bsd-3-clause
1,805
0.060942
#!/usr/bin/env python from __future__ import division import argparse import os import shutil as sh import daedalus.lib.utils as du #make_quantification_table def parse_argument(): parser = argparse.ArgumentParser() parser.add_argument("-i",help = "",required = True , dest = "features_path" , ) pars
er.add_argument("-n",help = "total number of features from file to read",default = 99999, dest = "features" , type = int) parser.add_argument("--accuracy",help = "will stop reading features at this 'accuracy score'",default = 2,dest = "accuracy" , type = str) parser.add_argument("-o",help
= "The filename to where the results will be written to. ", default = ".", dest = "working_path", type = str) parser.add_argument("-f",help = "force override of the output files if they exist", action='store_true' , dest = "override") parser.add_argument("-v",help = " To run verbose form. Useful for debuging ", actio...
gollum23/oidoypaz
web/context_processors.py
Python
gpl-2.0
369
0
# -*- coding: utf-8 -*-
from .models import Slider, Category,
SoundLibrary def slider(request): slides = Slider.objects.all() return {'slider': slides} def category(request): categories = Category.objects.all() return {'category_menu': categories} def fonoteca(request): library = SoundLibrary.objects.all() return {'library': library}
su27/qcloud_cos_py3
docs/source/conf.py
Python
mit
9,669
0.006205
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Qcloud COS SDK for Python 3 documentation build configuration file, created by # cookiecutter pipproject # # 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 # autog...
html_extra_path = [] # If not None, a 'Last updated on:' timestamp is inserted at every page # bottom, using the given strftime format. # The empty string is equivalent to '%b %d, %Y'. #html_last_updated_fmt = None # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities....
s to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is s...
aerler/WRF-Projects
src/projects/GreatLakes/GRW_settings.py
Python
gpl-3.0
33,466
0.019841
''' Created on Sep 4, 2016 This module contains a meta data for HGS simulations for the GRW and a wrapper to load them. @author: Andre R. Erler, GPL v3 ''' import numpy as np from collections import OrderedDict from collections import namedtuple # internal imports import hgs.HGS as hgs # need to prevent name collisi...
targs['WRF T'] = dict(color='#E24B34') # red hgs_plotargs['WRF G'] = dict(color='#62A1C6') # blue hgs_plotargs['T Ensemble'] = dict(color='#E24B34') # red hgs_plotargs['G Ensemble'] =
dict(color='#62A1C6') # blue hgs_plotargs['ERAI-T'] = dict(color='#E24B34') # red hgs_plotargs['ERAI-G'] = dict(color='#62A1C6') # blue hgs_plotargs['T Mean'] = dict(color='red') # red hgs_plotargs['G Mean'] = dict(color=...
trawick/edurepo
src/edurepo/edurepo/settings.py
Python
apache-2.0
6,323
0.000949
""" Django settings for edurepo project. For more information on this file, see https://docs.djangoproject.com/en/1.6/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.6/ref/settings/ """ import logging # Build paths inside the project like this: os.path.join(BA...
ND': 'django.template.backend
s.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ...
tinybike/grapple
grapple/grapple.py
Python
mit
24,929
0.002166
#!/usr/bin/env python """Ripple ledger extractor. Grapple extracts the ledger from rippled via websocket. It starts at the current ledger index, and walks backwards until it reaches the genesis ledger. The genesis ledger index is set by default to 152370. If you have previously run Grapple, data will only be collect...
s pd import pandas.io.sql as psql import numpy as np import psycopg2 as db import psycopg2.extensions as ext # Python 3 compatibility from six.moves import xrange as range _IS_PYTHON_3 = sys.version_info[0] == 3 identity = lambda x : x
if _IS_PYTHON_3: u = identity else: import codecs def u(string): return codecs.unicode_escape_decode(string)[0] from config import * getcontext().rounding = ROUND_HALF_EVEN # Postgres connection if not os.environ.get("CONTINUOUS_INTEGRATION"): conn = db.connect(POSTGRES_CONNECTION_STRING) ...
factorlibre/stock-logistics-warehouse
stock_available/__openerp__.py
Python
agpl-3.0
483
0
# -*- coding: utf-8 -*- # © 2014 Numérigraphe SARL # License AGPL-3.0 or later (ht
tp://www.gnu.org/licenses/agpl.html). { 'name': 'Stock available to promise', 'version': '8.0.3.1.0', "author": u"Numérigraphe,Odoo Community Association (OCA)", 'category': 'Warehouse', 'depends': ['stock'], 'license': 'AGPL-3', 'data': [
'views/product_template_view.xml', 'views/product_product_view.xml', 'views/res_config_view.xml', ] }
Microvellum/Fluid-Designer
win64-vc/2.78/Python/bin/2.78/scripts/addons/rigify/rigs/pitchipoy/limbs/arm.py
Python
gpl-3.0
3,863
0.017085
#====================== BEGIN GPL LICENSE BLOCK ====================== # # 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, or (at your option) any later vers...
"' + ']' drv_modifier = cls.obj.animation_data.drivers[-1].modifier
s[0] drv_modifier.mode = 'POLYNOMIAL' drv_modifier.poly_order = 1 drv_modifier.coefficients[0] = 1.0 drv_modifier.coefficients[1] = -1.0 # Create hand widget create_hand_widget(cls.obj, ctrl, bone_transform_name=None) bones['ik']['ctrl']['terminal'] = [ ctrl ] ret...
lmazuel/azure-sdk-for-python
azure-mgmt-network/azure/mgmt/network/v2017_11_01/models/backend_address_pool_paged.py
Python
mit
982
0.001018
# 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 ...
A paging container for iterating over a list of :class:`BackendAddressPool <az
ure.mgmt.network.v2017_11_01.models.BackendAddressPool>` object """ _attribute_map = { 'next_link': {'key': 'nextLink', 'type': 'str'}, 'current_page': {'key': 'value', 'type': '[BackendAddressPool]'} } def __init__(self, *args, **kwargs): super(BackendAddressPoolPaged, self)....
Heufneutje/txircd
txircd/modules/rfc/pingpong.py
Python
bsd-3-clause
5,686
0.033415
from twisted.plugin import IPlugin from twisted.words.protocols import irc from txircd.module_interface import Command, ICommand, IModuleData, ModuleData from txircd.utils import now from zope.interface import implementer from typing import Any, Callable, Dict, List, Optional, Tuple @implementer(IPlugin, IModuleData) ...
ver {server.serverID} pinged out (last pong time '{pongTime}' was less than last ping time '{pingTime}' at the next ping interval)", server=server, pongTime=pongTime, pingTime=pingTime) server.disconnect("Ping timeout") return server.sendMessage("PING", self.ircd.serverID, server.serverID, prefix=self.ircd.serv...
) @implementer(ICommand) class UserPing(Command): resetsIdleTime = False forRegistered = None def __init__(self, ircd): self.ircd = ircd def parseParams(self, user: "IRCUser", params: List[str], prefix: str, tags: Dict[str, Optional[str]]) -> Optional[Dict[Any, Any]]: if not params: user.sendSingleError...
luotao1/Paddle
python/paddle/distributed/fleet/meta_parallel/tensor_parallel.py
Python
apache-2.0
1,803
0.000555
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
wargs) def _prepare_for_model(self): logger.info("start broadcast mp parameters") broadcast_mp_parameters(self._layers, self._hcg) if self._hcg.get_sharding_parallel_world_size() > 1: logger.info("start broadcast sharding parameters") broadcast_sharding_parameters(s...
oadcast_dp_parameters(self._layers, self._hcg) logger.info("mp's parameters is ready") def _pre_forward(self, *inputs, **kwargs): logger.debug("mp start broadcast input data") return broadcast_input_data(self._hcg, *inputs, **kwargs)
glymehrvrd/CppYCM
listeners/highlight_problems.py
Python
mit
902
0
import sublime import sublime_plugin import json from threading import Thread from ..lib.ycmd_handler import server from ..lib.utils import * from ..lib.msgs import MsgTemplates class CppYCMHighlightProblemsListener(sublime_plugin.EventListener): def on_selection_modified_async(self, view):
if not is_cpp(view) or view.is_scratch(): return # Not work in st3, output panel wouldn't call this callback # from ..commands.highlight_problems import output_panel # if output_panel and (view.id() == output_panel.id()): # sublime.message_dialog('match!') # upda...
s command if check_highlight_on_save(): view.window().run_command('cppycm_highlight_problems')
tabalinas/jsgrid-django
clients/urls.py
Python
mit
243
0.004115
from django.conf.urls import url from . import views from .views import Clients urlpatterns
= [ url(r'^$', v
iews.index, name='index'), url(r'^api/?$', Clients.as_view()), url(r'^api/(?P<client_id>[0-9]+)/?$', Clients.as_view()), ]
shl198/Pipeline
VariantCall/Human_GATK_RNA_vari_call.py
Python
mit
7,218
0.015517
""" this file does variant calling for RNAseq """ #============= import required packages ================= import os import sys import subprocess sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) # disable buffer from Modules.f00_Message import Message from Modules.f01_list_trim_fq import list_files_human,Trimmoma...
thread'] email = param['email'] startMessage = param['startMessage'] endMessage = param['endMessage'] ref_fa = param['refSequence'] file_path = param['filePath'] starDb = param['alignerDb'] trim = param['trim'] phred = param['phred'] picard = param['picard'] trimmomatic = param['trimmomatic'] trimmoAdapter = param['tr...
param['gatk'] read_group = param['readGroup'] organism = param['organism'] ##***************** Part 0. Build index file for bwa and GATK ****** ##***************** Part I. Preprocess ============================ #======== 1. map and dedupping ===================================== #======== (0) enter the directory...
rhyolight/nupic.son
app/soc/mapreduce/process_org_apps.py
Python
apache-2.0
2,473
0.007683
# Copyright 2011 the Melange authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wr...
port operation from melange.request import links from soc.logic import org_app as org_app_logic # MapReduce requires import of processed model classes. # pylint: disable=unused-import from soc.models.site import Site from soc.models.org_app_survey import OrgAppSurvey from soc.modules.gci.models.program import GCIPro...
am from soc.modules.gci.views.helper import url_names as gci_url_names # pylint: enable=unused-import class MapreduceRequestData(object): """Simple class to use for convenience with RequestData object""" def __init__(self, program, site): self.program = program self.site = site def process(org_app): ...
spreadflow/spreadflow-core
spreadflow_core/proc.py
Python
mit
2,588
0.000386
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals import copy from twisted.internet import defer, task from twisted.logger import Logger, LogLevel class SyntheticSource(object): def __init__(self, items): self.items = items def attach(sel...
def __init__(self, message='Item received: {item}', level='debug'): self.leve
l = LogLevel.levelWithName(level) self.message = message def __call__(self, item, send): self.log.emit(self.level, self.message, item=item) send(item, self) class Duplicator(object): """ A processor capable of sending messages to another flow. """ def __init__(self): ...
xtuyaowu/jtyd_python_spider
browser_interface/browser/BrowserFactory.py
Python
mit
225
0
# -*- coding: utf-8 -*- import sys sys.path.append('../browser_interface/browser') class BrowserFactory(object): def create(self, type, *args, **kwargs): return getattr(__import__(type), type)(*args,
**kwargs)
invisiblek/python-for-android
python3-alpha/python3-src/Lib/test/test_range.py
Python
apache-2.0
17,941
0.000334
# Python test set -- built-in functions import test.support, unittest import sys import pickle import itertools # pure Python implementations (3 args only), for comparison def pyrange(start, stop, step): if (start - stop) // step < 0: # replace stop with next element in the sequence of integers # ...
(OverflowError, len, x) self.assertEqual(_range_len(x), expected_len) self.assertEqual(x[0], a) idx = sys.maxsize+1 self.assertEqual(x[idx], a+(idx*c)) self.assertEqual(x[idx:idx+1][0], a+(idx*c)) with self.assertRaises(IndexError): x[-expected_len-1] ...
expected_len = 1 + (b - a) // c x = range(a, b, c) self.assertIn(a, x) self.assertNotIn(b, x) self.assertRaises(OverflowError, len, x) self.assertEqual(_range_len(x), expected_len) self.assertEqual(x[0], a) idx = sys.maxsize+1 self.assertEqual(x[idx], a+...
AunShiLord/Tensor-analysis
build/lib/tensor-analysis/arraypy.py
Python
mit
47,289
0.000508
# -*- coding: utf-8 -*- from sympy import Symbol from sympy.matrices import Matrix, MatrixSymbol from copy import copy from itertools import permutations from sympy.core.basic import Basic """ Module "arraypy" describes tensor and it's bases - Multidimentional arrays. Module consists of Arraypy class, TensorArray cla...
._dims.append(temp[k][1] - temp[k][0] + 1) k += 1 self._dims = tuple(self._dims) self._start_index = [temp[k][0] for k in range(self._rank)] self._end_index = [ temp[k][1] + 1 for k in r...
f._rank)] # a = Arraypy('Py') else: self._name = i # for list arguments if isinstance(i, (list)): # a = Arraypy( [2, 4, 1] ) # first list element - rank # second list element - length of every ...
tonghuashuai/42qu-notepad
lib/_tornado.py
Python
mit
3,187
0.00502
#!/usr/bin/env python # -*- coding: utf-8 -*- import Cookie import base64 import calendar import datetime import email.utils import functools import gzip import hashlib import hmac import httplib import logging import mimetypes import os.path import re import stat import sys import time import types import urllib impo...
timetuple()) expires = email.utils.formatdate( ti
mestamp, localtime=False, usegmt=True ) else: expires = 'Tue, 01 Jan 2030 00:00:00 GMT' morsel['expires'] = expires if path: morsel["path"] = path for k, v in kwargs.iteritems(): if k == 'max_age': k = 'max-age' morsel[k] = v web.RequestHandle...
LaetitiaPapaxanthos/UnionCom
PrimeDual.py
Python
mit
2,943
0.036357
# import os import random import torch import numpy as np def cor_pairs_match_Adam(Kx, Kz, N, params, p1, p2, epo, device): print("use device:", device) Kx = Kx / N Kz = Kz / N Kx = torch.from_numpy(Kx).float().to(device) Kz = torch.from_numpy(Kz).float().to(device) m = np.shape(Kx)[0] n = np.shape(Kz)[0] F =...
/(1-np.power(pho1,i)) hat_Snd_moment = Snd_moment/(1-np.power(pho2,i)) grad = hat_Fst_moment/(torch.sqrt(hat_Snd_moment)+delta) F_tmp = F - grad F_tmp[F_tmp<0]=0 F = (1-params.epsilon)*F + params.epsilon*F_tmp grad_s = Lambda + params.rho*(torch.mm(torch.t(F), Im) - In + S)
s_tmp = S - grad_s s_tmp[s_tmp<0]=0 S = (1-params.epsilon)*S + params.epsilon*s_tmp Mu = Mu + params.epsilon*(torch.mm(F,In) - Im) Lambda = Lambda + params.epsilon*(torch.mm(torch.t(F), Im) - In + S) #### if scaling factor a changes too fast, we can delay the update of speed. if i>=params.delay: # gr...
BrechtBa/mpcpy
examples/simple_space_heating_mpc.py
Python
gpl-3.0
11,279
0.006916
#!/usr/bin/env python ################################################################################ # Copyright 2015 Brecht Baeten # This file is part of mpcpy. # # mpcpy is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # th...
time = np.arange(starttime, stoptime+dt, dt, dtype=np.float) # initialize T_em = np.ones_like(time)*self.res['T_em'][-1] T_in = np.ones_like(time)*self.res['T_in'][-1] # interpolate inputs Q_flow_hp = np.interp(time, input['time'], input['Q_flow_hp']) Q_flow_so = np.in...
o']) T_am = np.interp(time, input['time'], input['T_am']) for i,t in enumerate(time[:-1]): # C_em dT_em/dt = Q_flow_hp - UA_em_in*(T_em-T_in) T_em[i+1] = T_em[i] + (Q_flow_hp[i] - self.parameters['UA_em_in']*(T_em[i]-T_in[i]))*dt/self.parameters['C_em'] # C_in ...
teoreteetik/api-snippets
sync/rest/maps/retrieve-map-item/retrieve-map-item.6.x.py
Python
mit
471
0
#
Download the Python helper library from twilio.com/docs/python/install from twilio.rest import Client # Your Account Sid and Auth Token from twilio.com/user/account account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" auth_token = "your_auth_token" client = Client(account_sid, auth_token) map_item = client.sync \ ....
curry") \ .fetch() print(map_item.data)
manasi24/tempest
tempest/scenario/test_large_ops.py
Python
apache-2.0
5,090
0.000393
# Copyright 2013 NEC Corporation # 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 ...
while cls._cleanup_resources: function
, args, kwargs = cls._cleanup_resources.pop(-1) try: function(*args, **kwargs) except lib_exc.NotFound: pass super(TestLargeOpsScenario, cls).resource_cleanup() @classmethod def addCleanupClass(cls, function, *arguments, **keywordArguments): ...
PuZZleDucK/pixelated-user-agent
service/test/functional/features/steps/attachments.py
Python
agpl-3.0
2,007
0.000997
# # Copyright (c) 2014 ThoughtWorks, Inc. # # Pixelated is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Pixelated is distrib...
Affero General Public License for more details. # # You should have received a copy of the GNU Affero General
Public License # along with Pixelated. If not, see <http://www.gnu.org/licenses/>. from email.mime.application import MIMEApplication from time import sleep from leap.mail.mail import Message from common import * from test.support.integration import MailBuilder from behave import given from crochet import wait_for from...
MAPSuio/spring-challenge16
frengers/generate.py
Python
mit
734
0.001362
from random import choice, shuffle names_fd = open('names.txt', 'ro') names = map(lambda name: name.strip(), names_fd.readlines()) events = [] for i in xrange(7): events.append("meet") for i in xrange(3): events.append("friends") names_fd.close() entries = set() while len(entries) < 8000: event = ...
case = event + " " + person_a + " " + person_b i
f case not in entries: equivalent = event + " " + person_b + " " + person_a if equivalent not in entries: entries.add(case) result = list(entries) shuffle(result) for entry in result: print entry
wette/netSLS
network_emulator/rpc_server.py
Python
apache-2.0
3,616
0.000553
""" Copyright 2015 Malte Splietker Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software ...
t()), transport.handle,
log=None) gevent.spawn(self._wsgi_server.serve_forever) self.__server = RPCServerGreenlets( transport, JSONRPCProtocol(), self.__dispatcher ) # register interface's public functions self.__dispatcher.register_instance(interface, "")...
bokunimowakaru/Wi-SUN_EnergyMeter
user_conf.py
Python
mit
486
0.005464
#
coding: UTF-8 # # user_conf.py # # スマート電力量メーター ユーザ設定 # # Copyright(C) 2016 pi@blue-black.ink # SEM_ROUTEB_ID = '00000000000000000000000000000000' SEM_PASSWORD = 'XXXXXXXXXXXX' SEM_INTERVAL = 20 # 瞬時電力取得間隔[s] SEM_DURATION = 6 # アクティブスキャンduration (通常は変更の必要なし) SOCK_UDP = '192.168.0.255' # UDPソケットIPアドレス SOC...
)
tstone2077/django-bases
site/main/views.py
Python
gpl-3.0
214
0.028037
from django.shortcuts import render_to_response from django.temp
late imp
ort RequestContext def about(request): return render_to_response('about.html',context_instance=RequestContext(request,{'active':'about'}))
hddn/studentsdb
students/signals.py
Python
mit
1,010
0.00297
# -*- coding: utf-8 -*- import logging from django.db.models.signals import post_save, post_delete from django.dispatch import rec
eiver from .models import Student @receiver(post_save, sender=Student) def log_student_updated_added_event(sender, **kwargs): """Writes info about updated or newly added student into log file""" logger = logging.getLogg
er(__name__) student = kwargs['instance'] if kwargs['created']: logger.info("Student added: {} {} (ID: {:d})".format(student.first_name, student.last_name, student.id)) else: logger.info("Student updated: {} {} (ID: {:d})".format(student.first_name, student.last_name, student.id)) @receiv...
winxos/python
cache_grab.py
Python
mit
1,468
0.042244
#!/usr/bin/env python # -*- coding: utf-8 -*- # grab cache file to user path # used for game factory, grab cached files # winxos 2014-02-22 import os,sys import fnmatch import getpass #get user name import shutil #copy from time import sleep rootdir = os.path.join('C:/Users',getpass.getuser(),'AppData\Local\Microsof...
flag=True if flag: print("grab files succ
essed.") return sleep(30) #延时 print("grab files failed.") from threading import Thread #grab files def grab_file(name,newpath): simplename,suffix=os.path.splitext(name) get_file=Thread(target=get_cachefile,args=(simplename+'*'+suffix,newpath))#parameter transin get_file.start() #异步抓...
sony/nnabla
python/test/utils/test_graph_converters/test_batch_normalization_folding.py
Python
apache-2.0
2,857
0.0014
# Copyright 2020,2021 Sony Corporation. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
rted in cuDNN context.') with nn.context_scope(ctx): # Random number np.random.seed(seed) rng = np.random.RandomState(seed) # Graph x_data = rng.randn(batch_size, 32, 32, 3) if
channel_last == True else rng.randn( batch_size, 3, 32, 32) x = nn.Variable.from_numpy_array(x_data) y_tgt = graph_act(x, test=test, w_bias=w_bias, channel_last=channel_last) # FunctionModifier modifiers = [] modifiers.append(GC.BatchNormal...
Kalimaha/fake_data_crud_service
test_data_crud_services/resources/test_book.py
Python
mit
338
0.002959
book_1 = { "ISBN": "0436203057", "authors": [ "Howard Marks" ], "genre": "non-fic
tion", "pages": 466, "title": "Mr. Nice" } book_
2 = { "ISBN": "0439708184", "authors": [ "J. K. Rowling" ], "genre": "fiction", "pages": 322, "title": "Harry Potter and the Sorcerer's Stone" }
jimmyraywv/cloud-custodian
tests/test_sqs.py
Python
apache-2.0
10,409
0.001537
# Copyright 2017 Capital One Services, 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...
ueName=name)['QueueUrl'] self.addCleanup(client.delete_queue, QueueUrl=queue_url) p = self.load_policy({ 'name': 'sqs-mark-for-op', 'resource': 'sqs', 'filters': [{'QueueUrl': queue_url}], 'actions': [ {'type': 'mark-for-op', ...
sion_factory=session_factory) resources = p.run() self.assertEqual(len(resources), 1) tags_after_run = client.list_queue_tags( QueueUrl=queue_url).get('Tags', {}) self.assertTrue("tag-for-op" in tags_after_run) @functional def test_sqs_tag(self): session_fac...
r0h4n/ceph-integration
tendrl/ceph_integration/objects/rbd/atoms/delete/__init__.py
Python
lgpl-2.1
2,691
0
from tendrl.ceph_integration.manager.exceptions import \ RequestStateError from tendrl.ceph_integration.manager.rbd_crud import RbdCrud from tendrl.ceph_integration.objects.rbd import Rbd from tendrl.commons.event import Event from tendrl.commons.message import Message from tendrl.commons import objects class Del...
" Error: %s" % (self.parameters['Rbd.name'], ex) }, job_id=self.parameters['job_id'], flow_id=self.parameters['flow_id'], cluster_id=NS.tendrl_context.integration_id, ...
return False NS._int.wclient.delete( "clusters/%s/Pools/%s/Rbds/%s" % ( NS.tendrl_context.integration_id, self.parameters['Rbd.pool_id'], self.parameters['Rbd.name'] ), recursive=True ) Event( ...
thombashi/typepy
typepy/checker/_nan.py
Python
mit
826
0.002421
""" .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from ._checker import CheckerFactory, TypeCheckerBase, TypeCheckerDelegator from ._common import isnan, isstring class NanTypeCheckerStrictLevel0(TypeCheckerBase): def is_instance(self): return isnan(self._value) def is_valid_af...
return isstring(self._value) _factory = CheckerFactory( checker_mapping={0: NanTypeCheckerStrictLevel0, 1: NanTypeCheckerStrictLevel1} ) class NanTypeChecker(TypeCheckerDelegator): def __init__(self, value, strict_level): super().__init__(value=value, checker_factory=_factory, strict_level=s
trict_level)
ttm/pnud4
flask/auxiliar.py
Python
unlicense
5,873
0.011588
#-*- coding: utf8 -*- from SPARQLWrapper import SPARQLWrapper, JSON from configuracao import * import string, networkx as x, nltk as k import __builtin__ stemmer = k.stem.RSLPStemmer() def fazRedeAmizades(): global SPARQLWrapper q="""SELECT ?a ?b ?aname ?bname WHERE { ?a foaf:knows ?b . ...
ql=SPARQLWrapper(URL_ENDPOINT_) sparql.setQuery(PREFIX+q) sparql.setReturnFormat(JSON) results = sparql.query().convert() msgs_=results["res
ults"]["bindings"] msgs=[mm for mm in msgs_ if ("titulo" not in mm.keys()) or (("teste de stress" not in mm["titulo"]["value"].lower()) or ("cbody" not in mm.keys() or ("comunidade de desenvolvedores e nesse caso, quanto mais" not in mm["cbody"]["value"].lower())))] textos1=[i...
gdsfactory/gdsfactory
gdsfactory/simulation/gtidy3d/tests/test_results.py
Python
mit
855
0
import gdsfactory as gf import gdsfactory.simulation.gtidy3d as gt from gdsfactory.config import CONFIG from gdsfactory.simulation.gtidy3d.get_results import get_results # def test_results_run(data_regression) -> None: # """Run simulations and checks local results.""" # component = gf.components.straight(leng...
ent, is_3d=False) # dirpath = CONFIG["sparameters"] # r = get_results(sim=sim, dirpath=dirpath, overwrite=True).result() # if data_regression: # data_regression.check(r.monitor_data) if __name__ == "__main__": # test_results_run(None) component = gf.components.straight(length=3) sim...
dirpath, overwrite=True).result()
Saldenisov/QY_itegrating_sphere
views/__init__.py
Python
mit
46
0.021739
from .ui import * from
.windows_views import
*
LLNL/spack
var/spack/repos/builtin/packages/py-sentry-sdk/package.py
Python
lgpl-2.1
1,517
0.000659
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class PySentrySdk(PythonPackage): """The new Python SDK for Sentry.io""" homepage = "https:...
un')) depends_on('py-bottle@0.12.13:', type=('build', 'run')) depends_on('py-falcon@1.4:', type=('build', 'run')) depends_on('py-django@1.8:', type=('build', 'run')) depends_on('py-sanic@0.8:', type=('build', 'run')) depends_on('py-celery@3:',
type=('build', 'run')) depends_on('py-apache-beam@2.12:', type=('build', 'run')) depends_on('py-rq@0.6:', type=('build', 'run')) depends_on('py-aiohttp@3.5:', type=('build', 'run')) depends_on('py-tornado@5:', type=('build', 'run')) depends_on('py-sqlalchemy@1.2:', type=('build', 'run')) depends...
Pyc0kw4k/djangocms-portfolio
djangocms_portfolio/models.py
Python
apache-2.0
2,018
0.002973
# coding: utf-8 # Django db from django.db import models # Fields (Requirements) from djangocms_text_ckeditor.fields import HTMLField #Filer (Requirements) from filer.fields.image import FilerImageField from filer.fields.folder import FilerFolderField # Taggit (Requirements) from taggit.managers import TaggableMana...
del): title = models.CharField(_('Title'), max_length=255) slug = models.SlugField() class Meta:
verbose_name = _('Category') verbose_name_plural = _('Categories') def __str__(self): return self.title class Work(models.Model): title = models.CharField(_('Title'), max_length=200) slug = models.SlugField() pub_date = models.DateTimeField(_('Published on'), auto_now_add=True)...
vienno/flashback
setup.py
Python
mit
515
0
from distutils.core import setup setup( name='flashback', packages=['flashback'], version='0.4', description='The handiest Flashback scraper in the game', author='Robin Linderborg', author_email='robin.linderborg@gmail.com',
install_requires=[ '
beautifulsoup4==4.4.1', 'requests==2.8.0' ], url='https://github.com/miroli/flashback', download_url='https://github.com/miroli/flashback/tarball/0.4', keywords=['flashback', 'scraping'], classifiers=[], )
didrocks/snapcraft
snapcraft/tests/test_config.py
Python
gpl-3.0
3,065
0
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*- # # Copyright (C) 2016 Canonical Ltd # # 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 distributed in the h...
new_conf.get('bar')) def test_clear_preserver_other_sections(self): create_config_from_string('''[keep_me]\nfoo=bar\n''') conf = config.Config() conf.set('bar', 'baz') self.assertEqual('b
az', conf.get('bar')) conf.clear() conf.save() new_conf = config.Config() self.assertEqual(None, new_conf.get('bar')) # Picking behind the curtains self.assertEqual('bar', new_conf.parser.get('keep_me', 'foo')) self.assertTrue(conf.is_empty()) class TestOptions(...
dwt/BayesianNetworks
fluent.py
Python
mit
46,253
0.014554
#!/usr/bin/env python3 # encoding: utf8 # license: ISC (MIT/BSD compatible) https://choosealicense.com/licenses/isc/ # This library is principally created for python 3. However python 2 support may be doable and is welcomed. """Use python in a more object oriented, saner and shorter way. # WARNING First: A word of w...
referrable and shorter alias `_`: >>> _(something) >>> # or >>> wrap(something) `wrap` is a factory function that returns a subclass of Wrapper, the basic and main object of this
library. This does two things: First it ensures that every attribute access, item access or method call off of the wrapped object will also return a wrapped object. This means that once you wrap something, unless you unwrap it explicitly via `.unwrap` or `._` it stays wrapped - pretty much no matter what you do wi...
emory-libraries/eulcommon
eulcommon/djangoextras/formfields.py
Python
apache-2.0
8,195
0.002318
# file eulcommon/djangoextras/formfields.py # # Copyright 2010,2011 Emory University Libraries # # 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...
elf, choices): self._choices = choices choices = property(_get_choices, _set_choices) class DynamicChoiceField(ChoiceField): '''A :class:`django.forms.ChoiceField` whose choices are not static, but instead generated dynamically when referenced. :param choices: callable; this will be called to...
they are referenced ''' widget = DynamicSelect def __init__(self, choices=None, widget=None, *args, **kwargs): # ChoiceField.__init__ tries to set static choices, which won't # work since our choices are dynamic, so we're going to have to skip # over it. # First normalize ...
googleapis/python-aiplatform
samples/snippets/feature_store_service/create_featurestore_sample.py
Python
apache-2.0
2,289
0.002184
# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
Featurestore.OnlineServingConfig( fixed_node_count=fixed_node_count, ), ), ) lro_response = client.create_featurestore(request=create_featurestore_request) print("Long running operation:", lro_response.operation.name) create_featurestore_response = lro_response.result...
ut) print("create_featurestore_response:", create_featurestore_response) # [END aiplatform_create_featurestore_sample]
odie5533/Python-RTSP
sdpp.py
Python
gpl-3.0
6,434
0.004352
# Pythonic SDP/SDPPLIN Parser # SDP = Session Description Protocol # # Copyright (C) 2008 David Bern # # 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 ...
edia_description
s = [] self.last_desc = None # Variables are provided for convenience self.protocol_version = None self.session_name = None self.session_desc = None self.start_time = None self.stop_time = None if data is None: return ...
MillerCMBLabUSC/lab_analysis
apps/4f_model/OldCode/thermo.py
Python
gpl-2.0
3,192
0.024436
import scipy.integrate as intg import numpy as np #Physical Constants #Everything is in MKS units #Planck constant [J/s] h = 6.6261e-34 #Boltzmann constant [J/K] kB = 1.3806e-23 #Speed of light [m/s] c = 299792458.0 #Pi PI = 3.14159265 #Vacuum Permitivity eps0 = 8.85e-12 #Resistivity of the mirror rho=2.417e-8 GHz = ...
- 1) if
callable(emis): e = emis(freq) else: e = emis return (2*e*h*freq**3)/(c**2)* occ #Calculates total black body power for a given temp and emis multiplied by the optical throughput. def weightedSpec(freq,temp,emis): AOmega = (c/freq)**2 return (AOmega*bbSpec(freq,temp,emis)) def bbPowe...
graphql-python/graphql-core
tests/utilities/test_type_from_ast.py
Python
mit
1,371
0
from pytest import raises from graphql.language import parse_type, TypeNode from graphql.type import GraphQLList, GraphQLNonNull, GraphQLObjectType from graphql.utilities import type_from_ast from ..validation.harness import test_schema def describe_type_from_ast(): def for_named_type_node(): node = par...
e("Cat") type_for_node = type_from_ast(test_schema, node) assert isinstance(type_for_node, GraphQLObjectType) assert type_for_node.name == "Cat" def for_list_type_node(): node = parse_type("[Cat]") type_for_node = type_from_ast(test_schema, node) assert
isinstance(type_for_node, GraphQLList) of_type = type_for_node.of_type assert isinstance(of_type, GraphQLObjectType) assert of_type.name == "Cat" def for_non_null_type_node(): node = parse_type("Cat!") type_for_node = type_from_ast(test_schema, node) assert isinstanc...
pFernbach/hpp-rbprm-corba
script/scenarios/sandbox/siggraph_asia/spiderman/down_spidey_interp.py
Python
lgpl-3.0
4,445
0.028796
from hpp.corbaserver.rbprm.rbprmbuilder import Builder from hpp.corbaserver.rbprm.rbprmfullbody import FullBody from hpp.gepetto import Viewer from hpp.gepetto import PathPlayer import down_spidey_path as path_planner #~ import hrp2_model as model import time tp = path_planner packageName = 'hpp-rbprm-corba' meshPa...
# CHEST HEAD 7-10 #~ 0.261799388, 0.174532925, 0.0, -0.523598776, 0.0, 0.0, 0.17, # LARM 11-17 #~ 0.261799388, -0.174532925, 0.0, -0.523598776, 0.0, 0.0, 0.17, # RARM 18-24 #~ 0.0, 0.0, -0.453785606, 0.872664626, -0.41887902, 0.0, #...
25-30 #~ 0.0, 0.0, -0.453785606, 0.872664626, -0.41887902, 0.0, # RLEG 31-36 #~ ]; r (q_init) fullBody.setCurrentConfig (q_goal) q_goal = fullBody.generateContacts(q_goal, [0,0,1]) q_init = fullBody.generateContacts(q_init, [0,0,1]) #~ fullBody.setStartState(q_init,[rLegId,lLegI...
woodymit/millstone_accidental_source
genome_designer/debug/2014_07_11_dep_mpileup_analysis.py
Python
mit
2,582
0.002711
""" ucript to manually bin alignments against position. The idea is to manually look for mutations that freebayes might miss because of the low probability of the events that we are dealing with. """ import os import sys # Setup Django environment. sys.path.append( os.path.join(os.path.dirname(os.path.realpat...
nviron['DJANGO_SETTINGS_MODULE'] = 'settings' from main.models
import * from utils import generate_safe_filename_prefix_from_label from utils.bam_utils import filter_bam_file_by_row from utils.samtools_utils import run_mpileup def get_pEVOL_bam_path(bam_path): return os.path.splitext(bam_path)[0] + '.pEVOL_only.bam' def filter_pEVOL_reads(): p = Project.objects.get(uid...
sonic182/libsasscompiler
test_djangoapp/django_app/settings.py
Python
mit
4,154
0.000963
""" Django settings for django_app project. Generated by 'django-admin startproject' using Django 1.11.2. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ import...
': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], ...
SES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:' } } # Password validation # https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSi...
Raulios/django-blog
core/migrations/0005_auto_20160120_1634.py
Python
mit
458
0
# -*- coding: utf-8 -*- # Generated by Django 1.9 on 2016-01-20 16:34 from __future__ import unicode_literals from django.db import migrations, mode
ls class Migration(migrations.Migration): dependencies = [ ('core', '0004_auto_20160120_1633'), ] operations = [ migrations.AlterField( model_name='post', name='categories', field=models.ManyToManyField(to='core.Category'), ), ]
jiangzhuo/kbengine
kbe/src/lib/python/Lib/test/test_codecs.py
Python
lgpl-3.0
111,483
0.001408
import codecs import contextlib import io import locale import sys import unittest import warnings import encodings from test import support if sys.platform == 'win32': VISTA_OR_LATER = (sys.getwindowsversion().major >= 6) else: VISTA_OR_LATER = False try: import ctypes except ImportError: ctypes = N...
lf._buffer[:size] self._buffer = self._buffer[size:] return s class MixInCheckStateHandling: def check_state_handling_decode(self, encoding, u, s): for i in range(len(s)+1): d = codecs.getincrementaldecoder(encoding)() part1 = d.decode(s[:i]) stat...
te() self.assertIsInstance(state[1], int) # Check that the condition stated in the documentation for # IncrementalDecoder.getstate() holds if not state[1]: # reset decoder to the default state without anything buffered d.setstate((state[0][...
luzfcb/cookiecutter_django_test
config/settings/local.py
Python
mit
2,250
0.000444
# -*- coding: utf-8 -*- """ Local settings - Run in Debug mode - Use console backend for emails - Add Django Debug Toolbar - Add django-extensions as app """ import socket import os from .common import * # noqa # DEBUG # ------------------------------------------------------------------------------ DEBUG = env.bo...
jango.core.mail.backends.console.EmailBackend') # CACHING # ------------------------------------------------------------------------------ CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'L
OCATION': '' } } # django-debug-toolbar # ------------------------------------------------------------------------------ MIDDLEWARE_CLASSES += ('debug_toolbar.middleware.DebugToolbarMiddleware',) INSTALLED_APPS += ('debug_toolbar', ) INTERNAL_IPS = ['127.0.0.1', '10.0.2.2', ] # tricks to have debug toolbar when d...
qsantos/spyce
gspyce/__main__.py
Python
gpl-3.0
73
0
#!/usr/bin/env python import gspyce.simulation gspyce.simulation.
main(
)
googleapis/python-dialogflow
samples/generated_samples/dialogflow_v2_generated_environments_delete_environment_async.py
Python
apache-2.0
1,441
0.000694
# -*- coding: utf-8 -*- # Copyright 2022 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...
overning permissions and # limitations under the License. # # Generated code. DO NOT EDIT! # # Snippet for DeleteEnvironment # NOTE: This snippet has been automatically generated for illustrative purposes only. # It may require modifications to work in your environment. # To install the latest published p
ackage dependency, execute the following: # python3 -m pip install google-cloud-dialogflow # [START dialogflow_v2_generated_Environments_DeleteEnvironment_async] from google.cloud import dialogflow_v2 async def sample_delete_environment(): # Create a client client = dialogflow_v2.EnvironmentsAsyncClient()...
kmoocdev2/edx-platform
openedx/core/djangoapps/auth_exchange/views.py
Python
agpl-3.0
8,123
0.002585
# -*- coding: utf-8 -*- """ Views to support exchange of authentication credentials. The following are currently implemented: 1. AccessTokenExchangeView: 3rd party (social-auth) OAuth 2.0 access token -> 1st party (open-edx) OAuth 2.0 access token 2. LoginWithAccessTokenView: 1st party (open-edx) ...
quest=request, oauth2_adapter=self.oauth2_adapter, data=request.POST) # pylint: disable=no-member if not form.is_valid(): return self.error_response(form.errors) # pylint: disable=no-member user = form.cleaned_data["user"] scope = form.cleaned_data["scope"] client = form.c...
return self.exchange_access_token(request, user, scope, client) def exchange_access_token(self, request, user, scope, client): """ Exchange third party credentials for an edx access token, and return a serialized access token response. """ if constants.SINGLE_ACCESS...
marcioweck/PSSLib
reference/deap/doc/code/tutorials/part_4/4_4_Using_Cpp_NSGA.py
Python
lgpl-3.0
4,997
0.005003
# This file is part of DEAP. # # DEAP 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 Foundation, either version 3 of # the License, or (at your option) any later version. # # DEAP is distributed ...
oolbox = base.Toolbox() # Gene initializer toolbox.register("network", genNetwork, dimension=INPUTS, mi
n_size=9, max_size=12) # Structure initializers toolbox.register("individual", tools.initIterate, creator.Individual, toolbox.network) toolbox.register("population", tools.initRepeat, list, toolbox.individual) toolbox.register("evaluate", evalEvoSN, dimension=INPUTS) toolbox.register("mate", tools.cxTwoPoint) toolbox...
mbohlool/client-python
kubernetes/test/test_v1_role_binding_list.py
Python
apache-2.0
971
0.004119
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.8.2 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import os import sys im...
netes.client.models.v1_role_binding_list import V1RoleBindingList class TestV1RoleBindingList(unittest.TestCase): """ V1RoleBindingList unit test stubs """ def setUp(self): pass def tearDown(self): pass def testV1RoleBindingList(self): """ Test V1RoleBindingList ...
oleBindingList() pass if __name__ == '__main__': unittest.main()
operasoftware/dragonfly-build-tools
df2/showconfig.py
Python
apache-2.0
486
0.026749
import sys i
mport json import os def showconfig(args): json.dump(args.config, sys.stdout, indent=1) def configdoc(args): with open(os.path.join(args.root_path, "CONFIGDOC"), "r") as f: print f.read() def setup_subparser(subparsers, config): subp = subpars
ers.add_parser('showconfig', help="Show the config file.") subp.set_defaults(func=showconfig) subp = subparsers.add_parser('configdoc', help="Show the config options.") subp.set_defaults(func=configdoc)
sebcourtois/pypeline-tool-devkit
pytaya/core/transform.py
Python
gpl-3.0
6,643
0.002559
import maya.cmds as mc import pymel.core as pm from pytd.util.logutils import logMsg from pytaya.util.sysutils import argsToPyNode def matchTransform(obj, target, **kwargs): logMsg(log='all') bPreserveChild = kwargs.pop('preserveChild', kwargs.pop('pc', Fa
lse)) sAttr = kwargs.pop('attributeToMatch', kwargs.pop('atm', 'trs')) bObjSpace = kwargs.get('objectSpace', kwargs.get('os', False)) (oObj, oTarget) = argsToPyNode(obj, target) oChildren = None if bPreserveChild: oChildren = oObj.getChildren(typ='transform') oParent = oObj.getPare...
, oParent) else: pm.parent(oChildren, world=True) sAttrList = list(sAttr) if sAttr == "trs": matchTRS(oObj, oTarget, **kwargs) elif sAttr == "rpvt": matchRotatePivot(oObj, oTarget, **kwargs) elif sAttr == "spvt": matchScalePivot(oObj, oTarget, **kwar...
comicxmz001/LeetCode
Python/35. Search Insert Position.py
Python
mit
973
0.045221
class Solution(object): def searchInsert(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int O(logn) """ low = 0 high = len(nums) - 1 if target <= nums[low]:
return low if target > nums[high]: return high+1 while low < high: mid = (low + high) // 2 # print low, high, mid if nums[mid] < target <= nums[mid+1]: return mid+1 if nums[mid] >= target: high = mid else: low = mid ...
:type nums: List[int] :type target: int :rtype: int 60ms O(n) """ index = 0 for num in nums: if num < target: index += 1 return index if __name__ == '__main__': target = 7 nums = [1,3,5,6] # nums = [1] print Solution().searchInsert(...
qedsoftware/commcare-hq
corehq/apps/accounting/migrations/0031_merge.py
Python
bsd-3-clause
324
0
# -*- coding: utf-8 -*- from __future__ import unic
ode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('accounting', '0027_more_prbac_bootstrap'), ('accounting', '0030
_remove_softwareplan_visibility_trial_internal'), ] operations = [ ]
zlsun/XX-Net
code/default/x_tunnel/local/heroku_front/check_ip.py
Python
bsd-2-clause
4,521
0.004424
#!/usr/bin/env python2 # coding:utf-8 import sys import os import threading current_path = os.path.dirname(os.path.abspath(__file__)) root_path = os.path.abspath( os.path.join(current_path, os.pardir, os.pardir, os.pardir)) data_path = os.path.abspath(os.path.join(root_path, os.pardir, os.pardir, 'data')) module_data...
d(target=self.checker).run() def check_all(): check = CheckAllIp() check.run() exit(0) def check_one(ip, top_domain, wait_time): config_path = os.path.join(module_data_path, "heroku_front.json") config = Config(config_path) openssl_context = SSLContext(logger) host_manager = HostManage...
ogger, config, connect_creator) res = check_ip.check_ip(ip, host=top_domain, wait_time=wait_time) if not res: print("connect fail") elif res.ok: print("success, domain:%s handshake:%d" % (res.domain, res.handshake_time)) else: print("not support") if __name__ == "__main__": ...
hh-italian-group/h-tautau
Studies/python/ttbarGenStudies_cfg.py
Python
gpl-2.0
8,374
0.019226
## @package patTuple # Configuration file to produce PAT-tuples and ROOT-tuples for X->HH->bbTauTau analysis. # # \author Claudio Caputo # # Copyright 2015 # # This file is part of X->HH->bbTauTau. # # X->HH->bbTauTau is free software: you can redistribute it and/or modify # it under the terms of the GNU General ...
) ##------------ #------------- # Output ROOT file #------------- process.TFileService = cms.Service("TFileService", fileName = cms.string("tree.root") ) process.p = cms.Path( # process.METSignificance* # process.eg
mGsfElectronIDSequence* # process.electronMVAValueMapProducer* process.bbttSkim* process.printTree* process.ttbarAnalyzer #(process.syncNtupler_mutau + process.syncNtupler_etau) ) process.out = cms.OutputModule("PoolOutputModule", compressi...