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
Eric89GXL/scipy
scipy/_lib/_ccallback.py
Python
bsd-3-clause
6,196
0.001453
from . import _ccallback_c import ctypes PyCFuncPtr = ctypes.CFUNCTYPE(ctypes.c_void_p).__bases__[0] ffi = None class CData(object): pass def _import_cffi(): global ffi, CData if ffi is not None: return try: import cffi ffi = cffi.FFI() CData = ffi.CData except...
function : {PyCapsule, ctypes function pointer, cffi function pointer}
Low-level callback function. user_data : {PyCapsule, ctypes void pointer, cffi void pointer} User data to pass on to the callback function. signature : str, optional Signature of the function. If omitted, determined from *function*, if possible. Attributes ---------- functi...
QuantiModo/QuantiModo-SDK-Python
SwaggerPetstore/models/json_error_response.py
Python
gpl-2.0
1,773
0.00564
#!/usr/bin/env python # coding: utf-8 """ Copyright 2015 SmartBear Software Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unle...
on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ class JsonErrorResponse(object): """ NOTE: This class is auto generated by the swagger code generator...
class manually. """ def __init__(self): """ Swagger model :param dict swaggerTypes: The key is attribute name and the value is attribute type. :param dict attributeMap: The key is attribute name and the value is json key in definition. """ self.swagger_types = {...
BlueHouseLab/sms-openapi
python-requests/conf.py
Python
apache-2.0
324
0.003521
# -*- coding: utf-8 -*- appid = 'example' apikey = 'c5dd7e7dkjp27377l903c42c032b413b' sender = '01000000000'
# FIXME - MUST BE CHANGED AS REAL PHONE NUMBER receivers = ['01000000000', ] # FIXME - MUST BE CHANGED AS REAL PHONE NU
MBERS content = u'나는 유리를 먹을 수 있어요. 그래도 아프지 않아요'
ULHPC/easybuild-easyblocks
easybuild/easyblocks/generic/cmakemake.py
Python
gpl-2.0
4,702
0.002552
## # Copyright 2009-2017 Ghent University # # This file is part of EasyBuild, # originally created by the HPC team of Ghent University (http://ugent.be/hpc/en), # with support of Ghent University (http://ugent.be/hpc), # the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be), # Flemish Research Foundation (F...
if builddir is not None: self.log.nosupport("CMakeMake.configure_step: named argument
'builddir' (should be 'srcdir')", "2.0") # Set the search paths for CMake include_paths = os.pathsep.join(self.toolchain.get_variable("CPPFLAGS", list)) library_paths = os.pathsep.join(self.toolchain.get_variable("LDFLAGS", list)) setvar("CMAKE_INCLUDE_PATH", include_paths) set...
asiroliu/MyTools
MyArgparse.py
Python
gpl-2.0
2,738
0.004018
# coding=utf-8 from __future__ import unicode_literals """ Name: MyArgparse Author: Andy Liu Email : andy.liu.ud@hotmail.com Created: 3/26/2015 Copyright: All rights reserved. Licence: This program is free software: you can redistribute it and/or modify it under the te...
help='Add different values to list') args = parser.parse_args() logging.debug('NoPre = %r' % args.NoPre) logging.debug('simple_value = %r' % args.simple_value) logging.debug('constant_value = %r' % args.constant_value) logging.debug('boolean_switch = %r' % args.boolean...
llection) logging.debug('const_collection = %r' % args.const_collection) return args if __name__ == '__main__': from MyLog import init_logger logger = init_logger() parse_command_line()
chrigu6/vocabulary
vocabulary/trainer/admin.py
Python
gpl-3.0
195
0
from django.contrib import admin from trai
ner.models import Language, Word, Card, Set admin.site.register(Language) admin.site.register(Word) admin.site.register(Card) admin.site.regist
er(Set)
tomashaber/raiden
raiden/network/protocol.py
Python
mit
24,753
0.000485
# -*- coding: utf-8 -*- import logging import random from collections import ( namedtuple, defaultdict, ) from itertools import repeat import cachetools import gevent from gevent.event import ( _AbstractLinkable, AsyncResult, Event, ) from ethereum import slogging from raiden.exceptions import ( ...
out of values. Returns: bool: True if the message was acknowledged, False otherwise. """ async_result = protocol.send_raw_with_result( data, receiver_address, ) event_quit = event_first_of( asyn
c_result, event_stop, ) for timeout in timeout_backoff: if event_quit.wait(timeout=timeout) is True: break protocol.send_raw_with_result( data, receiver_address, ) return async_result.ready() def wait_recovery(event_stop, event_health...
kernsuite-debian/lofar
SAS/ResourceAssignment/ResourceAssignmentEditor/config/default.py
Python
gpl-3.0
967
0
# Copyright (C) 2012-2015 ASTRON (Netherlands Institute for Radio Astronomy) # P.O. Box 2, 7990 AA Dwingeloo, The Netherlands # # This file is part of the LOFAR software suite. # The LOFAR software suite is free software: you can redistribute it and/or # modify it under the terms of the GNU General Public License as p...
he LOFAR software suite is distributed in the hope that it will b
e 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 the GNU General Public License along # with the LOFAR software suite. If not, see <http://www.g...
mediafactory/yats
modules/yats/caldav/storage.py
Python
mit
12,605
0.002697
# -*- coding: utf-8 -*- import json import logging import vobject from datetime import datetime from contextlib import contextmanager from radicale import ical from yats.shortcuts import get_ticket_model, build_ticket_search_ext, touch_ticket, remember_changes, mail_ticket, jabber_ticket, check_references, add_histo...
NENT') and settings.KEEP_IT_SIMPLE_DEFAULT_COMPONENT: tic.component_id = settings.KEEP_IT_SIMPLE_DEFAULT_COMPONENT tic.show_start = cd['show_start'] tic.uuid = cal.vtodo.uid.value tic.save(user=request.user) ...
for ele in form.changed_data: form.initial[ele] = '' remember_changes(request, form, tic) touch_ticket(request.user, tic.pk) mail_ticket(request, tic.pk, form, rcpt=settings.TICKET_NEW_MAIL_RCPT, is_api=True) ja...
our-city-app/oca-backend
src/rogerthat/bizz/payment/to.py
Python
apache-2.0
1,164
0.000859
# -*- coding: utf-8 -*- # Copyright 2020 Green Valley Belgium NV # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance
with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in
writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # @@license_version:1.7@@ from mcfw.properties import...
laurent-george/weboob
modules/cmso/__init__.py
Python
agpl-3.0
788
0
# -*- coding: utf-8 -*- #
Copyright(C) 2012 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 option) any later version. # # weboob 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 PARTIC...
pculture/mirocommunity
localtv/models.py
Python
agpl-3.0
55,425
0.000902
import datetime import itertools import re import urllib2 import mimetypes import operator import logging import sys import traceback import warnings import tagging import tagging.models import vidscraper from bs4 import BeautifulSoup from django.conf import settings from django.contrib.auth.models import User from dj...
ing) return True class WidgetSettingsManager(SiteRelatedManager): def _new_entry(self, site, using): ws = super(WidgetSettingsManager, self)._new_entry(site, using) try: site_settings = SiteS
ettings.objects.get_cached(site, using) except SiteSettings.DoesNotExist: pass else: if site_settings.logo: site_settings.logo.open() ws.icon = site_settings.logo ws.save() return ws class WidgetSettings(Thumbnailable): ...
caseyrollins/osf.io
api/base/versioning.py
Python
apache-2.0
5,741
0.003135
from rest_framework import exceptions as drf_exceptions from rest_framework import versioning as drf_versioning from rest_framework.compat import unicode_http_header from res
t_framework.utils.mediatypes import _MediaType from api.base import exceptions from api.base import utils from api.base.renderers import BrowsableAPIRendererNoForms from api.base.settings import LATEST_VERSIONS def get_major_version(version): ret
urn int(version.split('.')[0]) def url_path_version_to_decimal(url_path_version): # 'v2' --> '2.0' return str(float(url_path_version.split('v')[1])) def decimal_version_to_url_path(decimal_version): # '2.0' --> 'v2' return 'v{}'.format(get_major_version(decimal_version)) def get_latest_sub_version...
Guidobelix/pyload
module/plugins/accounts/FilerioCom.py
Python
gpl-3.0
407
0.014742
# -*- coding: utf-8 -*- from module.plugins.internal.XFSAccount import XFSAccount class FilerioCom(XFSAccount):
__name__ = "FilerioCom" __type__ = "account" __version__ = "0.07" __status__ = "testing" __description__ = """FileRio.in account plugin""" __license__ = "GPLv3" __authors__ = [("zoidberg", "zoidberg@mujmail.cz")] PLUGIN_
DOMAIN = "filerio.in"
ray-project/ray
python/ray/train/tests/test_results_preprocessors.py
Python
apache-2.0
7,269
0.001238
import pytest from ray.train.callbacks.results_preprocessors import ( ExcludedKeysResultsPreprocessor, IndexedResultsPreprocessor, SequentialResultsPreprocessor, AverageResultsPreprocessor, MaxResultsPreprocessor, WeightedAverageResultsPreprocessor, ) def test_excluded_keys_results_preprocess...
results_preprocessor1 = WeightedAverageResultsPreprocessor(["a"], "b") expected1 = deepcopy(results1) for res in expected1: res.update({"weight_avg_b(a)": 2.5}) assert results_preprocessor1.p
reprocess(results1) == expected1 assert ( "Averaging weight `b` is not reported by all workers in `train.report()`." in caplog.text ) assert "Use equal weight instead." in caplog.text # test case 2: metric key `a` (to be averaged) is not reported from all workers results_preprocesso...
g2p/tranquil
tranquil/__init__.py
Python
bsd-3-clause
1,717
0.041351
import re from django.core.exceptions import ImproperlyConfigured from sqlalchemy import create_engine, MetaData from sqlalchemy.orm import sessionmaker from tranquil.models import Importer __all__ = ( 'engine', 'meta', 'Session', ) class EngineCache(object): __shared_state = dict( engine = None, meta = None, ...
raise ImproperlyConfigured( 'Unknown database engine: %s' % settings.DATABASE_ENGINE ) url = '{protocol}://{user}:{pass}@{host}{port}/{name}' for p in options: if p == 'port' and len( options[p] ) > 0: url = re.sub( '{%s}' % p, ':%s' % options[p], url ) else: url = re.sub( '{%s}' % p, options[...
) self.Session = sessionmaker( bind=self.engine, autoflush=True, autocommit=False ) self.importer = Importer(self.meta) cache = EngineCache() engine = cache.engine meta = cache.meta Session = cache.Session
jku/telepathy-gabble
tests/twisted/jingle/initial-audio-video.py
Python
lgpl-2.1
7,213
0.004298
""" Tests outgoing calls created with InitialAudio and/or InitialVideo, and exposing the initial contents of incoming calls as values of InitialAudio and InitialVideo """ import operator from servicetest import ( assertContains, assertEquals, assertLength, wrap_channel, EventPattern, call_async, make_channel_...
EL_TYPE_STREAMED_MEDIA ] assertLength(1, media_classes) fixed, allowed = media_classes[0] assertContains(cs.INITIAL_AU
DIO, allowed) assertContains(cs.INITIAL_VIDEO, allowed) check_neither(q, conn, bus, stream, remote_handle) check_iav(jt, q, conn, bus, stream, remote_handle, True, False) check_iav(jt, q, conn, bus, stream, remote_handle, False, True) check_iav(jt, q, conn, bus, stream, remote_handle, True, True) ...
markflyhigh/incubator-beam
sdks/python/apache_beam/io/textio_test.py
Python
apache-2.0
43,198
0.006898
# # 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 us...
datetime import glob import gzip import logging import os import shutil import sys import tempfile import unittest import zlib from builtins import range import apache_beam as beam import apache_beam.io.source_test_utils as source_test_utils from apache_beam import coders from apach
e_beam.io import ReadAllFromText from apache_beam.io import iobase from apache_beam.io.filesystem import CompressionTypes from apache_beam.io.textio import _TextSink as TextSink from apache_beam.io.textio import _TextSource as TextSource # Importing following private classes for testing. from apache_beam.io.textio impo...
awg24/pretix
src/pretix/plugins/paypal/signals.py
Python
apache-2.0
267
0
from django.dispatch import receiver from pretix.base.signals import register_payment_providers @receiver(reg
ister_payment_providers, dispatch_uid="payment_paypal") def register_payment_provider(sender, **kwargs): from .payment import Paypal return
Paypal
idlesign/django-admirarchy
admirarchy/tests/testapp/models.py
Python
bsd-3-clause
633
0.00158
from django.db import models class AdjacencyListModel(models.Model): title = models.CharField(max_length=100) parent = models.ForeignKey( 'self', related_name='%(class)s_parent', on_delete=models.CASCADE, db_index=True, null=True, blank=True) def __str__(self): return 'adjacencylistmode...
SetModel(models.Model): title =
models.CharField(max_length=100) lft = models.IntegerField(db_index=True) rgt = models.IntegerField(db_index=True) level = models.IntegerField(db_index=True) def __str__(self): return 'nestedsetmodel_%s' % self.title
lkmhaqer/gtools-python
netdevice/migrations/0007_auto_20190410_0358.py
Python
mit
567
0
# -*- coding: utf-8 -*- # Generated by Django 1.11.13 on 2019-04-10 03:58 from __future__
import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('netdevice', '0006_auto_20190409_0325'), ] operations = [ migrations.RenameField( model_name='vrf', old_name='vrf_name',
new_name='name', ), migrations.RenameField( model_name='vrf', old_name='vrf_target', new_name='target', ), ]
doffm/dbuf
src/dbuf/util.py
Python
bsd-3-clause
3,108
0.026705
from functools import reduce class ScopedString (object): def __init__ (self): self._stack = [] def push (self, frame): self._stack.append (frame) def pop (s
elf): frame = self._stack.pop() return frame def __str__
(self): return '.'.join (self._stack) class ScopedList (object): def __init__ (self, stack=None): if stack: self._stack = stack else: self._stack = [] self.push() def push (self): ...
ebilionis/py-best
best/random/_student_t_likelihood_function.py
Python
lgpl-3.0
2,586
0.001933
"""A likelihood function representing a Student-t distribution. Author: Ilias Bilionis Date: 1/21/2013 """ __all__ = ['StudentTLikelihoodFunction'] import numpy as np import scipy import math from . import GaussianLikelihoodFunction class StudentTLikelihoodFunction(GaussianLikelihoodFunction): """An...
The data or a proper mean_funciton is preassumed. name --- A name for the likelihood function. """ self.nu = nu super(StudentTLikelihoodFunction, self).__init__(num_input=num_input, ...
data=data, mean_function=mean_function, cov=cov, name=name) def __call__(self, x): """Evaluate the function at x.""" mu = s...
Azure/azure-sdk-for-python
sdk/search/azure-search-documents/samples/async_samples/sample_index_crud_operations_async.py
Python
mit
3,884
0.00309
# 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. # --------------------------------------------------------------------...
ame="state", type=SearchFieldDataType.String), ], collection=True) ] cors_options = CorsOptions(allowed_origins=["*"], max_age_in_seconds=60) scoring_profile = ScoringProfile( name="MyProfile" ) scoring_profiles = [] scoring_profiles.append(scoring_profile) index = SearchInd...
fields=fields, scoring_profiles=scoring_profiles, cors_options=cors_options) result = await client.create_or_update_index(index=index) # [END update_index_async] async def delete_index(): # [START delete_index_async] name = "hotels" await client.delete_index(name) # [END delet...
bohdon/maya-pulse
src/pulse/scripts/pulse/colors.py
Python
mit
381
0
def RGB01ToHex(rgb): """ Return an RGB color value as a hex color string. """ return '#%02x%02x%02x' % tuple([int(x * 255) for x in rgb]) def hexToRGB01(hexColor): """ Return a hex color string as an RGB tuple of floats in the
range 0..1 """ h = hexColor.lstrip('#') return tuple([x / 255.0 for x in [int(h[i:i + 2], 16)
for i in (0, 2, 4)]])
arenadata/ambari
ambari-server/src/main/resources/stacks/HDP/2.3.ECS/services/ECS/package/scripts/service_check.py
Python
apache-2.0
1,514
0.004624
""" 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 use this ...
import params env.set_params(params) # run fs list command to make sure ECS client can talk to ECS backend list_command = format("fs -ls /") if params.security_enabled: Execute(forma
t("{kinit_path_local} -kt {hdfs_user_keytab} {hdfs_principal_name}"), user=params.hdfs_user ) ExecuteHadoop(list_command, user=params.hdfs_user, logoutput=True, conf_dir=params.hadoop_conf_dir, try_sleep=3, trie...
abo-abo/edx-platform
common/djangoapps/mitxmako/middleware.py
Python
agpl-3.0
1,006
0
# Copyright (c) 2008 Mikeal Rogers # # Licensed under the Apache License, Version 2.0 (the "Licen
se"); #
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 # distribuetd under the License is distributed on an "AS IS" BASIS, # WITHOUT W...
maciejkula/spotlight
spotlight/cross_validation.py
Python
mit
6,519
0
""" Module with functionality for splitting and shuffling datasets. """ import numpy as np from sklearn.utils import murmurhash3_32 from spotlight.interactions import Interactions def _index_or_none(array, shuffle_index): if array is None: return None else: return array[shuffle_index] de...
d for the shuffle. Returns ------- interactions: :class:`spotlight.interactions.Interactions` The shuffled interactions. """ if random_state is None: random_state = np.random.RandomState() shuffle_indices = np.arange(len(interactions.user_ids)) random_state.shuffle(shuffl...
nteractions.ratings, shuffle_indices), timestamps=_index_or_none(interactions.timestamps, shuffle_indices), weights=_index_or_none(interactions.weights, ...
alirizakeles/memopol-core
memopol/meps/migrations/0017_auto__del_field_mep_stg_office.py
Python
gpl-3.0
12,677
0.008046
# encoding: utf-8 from south.db import db from south.v2 import SchemaMigration class Migration(SchemaMigration): def forwards(self, orm): # Deleting field 'MEP.stg_office' db.delete_column('meps_mep', 'stg_office') def backwards(self, orm): # User chose to not deal...
'False'}), 'countries': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['meps.Country']", 'through': "orm['meps.CountryMEP']", 'symmetrical': 'False'}), 'delegations': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['meps.Delegation']", 'through': "orm['m...
onRole']", 'symmetrical': 'False'}), 'ep_debates': ('django.db.models.fields.URLField', [], {'max_length': '200'}), 'ep_declarations': ('django.db.models.fields.URLField', [], {'max_length': '200'}), 'ep_id': ('django.db.models.fields.IntegerField', [], {'unique': 'True'}), ...
SqueezeStudioAnimation/dpAutoRigSystem
dpAutoRigSystem/Scripts/dpArm.py
Python
gpl-2.0
3,972
0.007301
# importing libraries: import maya.cmds as cmds import maya.mel as mel # global variables to this module: CLASS_NAME = "Arm" TITLE = "m028_arm" DESCRIPTION = "m029_armDesc" ICON = "/Icons/dp_arm.png" def Arm(dpAutoRigInst): """ This function will create all guides needed to compose an arm. """ # chec...
RigInst.guide.Finger.editUserName(ringFingerInstance, checkText=dpAutoRigInst.langDic[dpAutoRigInst.langName]['m034_ring']) pinkFingerInstance = dpAutoRigInst.initGuide('dpFinge
r', guideDir) dpAutoRigInst.guide.Finger.editUserName(pinkFingerInstance, checkText=dpAutoRigInst.langDic[dpAutoRigInst.langName]['m035_pink']) thumbFingerInstance = dpAutoRigInst.initGuide('dpFinger', guideDir) dpAutoRigInst.guide.Finger.editUserName(thumbFingerInstance, checkText=dpAutoRigIns...
madprime/genevieve
genevieve_client/migrations/0004_auto_20160328_1526.py
Python
mit
1,731
0.001733
# -*- coding: utf-8 -*- # Generated by Django 1.9.4 on 2016-03-28 15:26 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependen...
s.CharField(blank=True, max_length=30)), ('refresh_token', models.CharField(blank=True, max_length=30)), ('token_expiration', models.DateTimeField(null=True)),
('connected_id', models.CharField(max_length=30, unique=True)), ('openhumans_username', models.CharField(blank=True, max_length=30)), ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], options={ ...
dr-bigfatnoob/quirk
language/functions.py
Python
unlicense
1,698
0.009423
from __future__ import print_function, division import sys import os sys.path.append(os.path.abspath(".")) sys.dont_write_bytecode = True from distribution import * import operator as o from utils.lib import gt, lt, gte, lte, neq, eq __author__ = "bigfatnoob" def sample(values, size=100): return np.random.choice(v...
"normalCI": NormalCI, "uniform": Uniform, "random": Random, "exp": Exponential, "binomial": Binomial, "geometric": Geometric, "triangular": Triangular }
operations = { "+": o.add, "-": o.sub, "*": o.mul, "/": o.div, "|": max, "&": o.mul, ">": to_int(gt), "<": to_int(lt), ">=": to_int(gte), "<=": to_int(lte), "==": to_int(eq), "!=": to_int(neq) }
timohtey/mediadrop_copy
mediacore_env/Lib/site-packages/distribute-0.7.3/setup.py
Python
gpl-3.0
1,879
0.000532
#!/usr/bin/env python """Distutils setup file, used to install or test 'setuptools'""" import textwrap import sys try: import setuptools except ImportError: sys.stderr.write("Distribute 0.7 may only upgrade an existing " "Distribute 0.6 installation")
raise SystemExit(1) long_description = textwrap.dedent(""" Distribute - legacy package This package is a simple c
ompatibility layer that installs Setuptools 0.7+. """).lstrip() setup_params = dict( name="distribute", version='0.7.3', description="distribute legacy wrapper", author="The fellowship of the packaging", author_email="distutils-sig@python.org", license="PSF or ZPL", long_description=lon...
shazadan/mood-map
tweets/management/commands/stream.py
Python
gpl-2.0
361
0.00554
from django.core.mana
gement.base import BaseCommand, CommandError from tweets.tasks import stream
#The class must be named Command, and subclass BaseCommand class Command(BaseCommand): # Show this when the user types help help = "My twitter stream command" # A command must define handle() def handle(self, *args, **options): stream()
yytang2012/novels-crawler
novelsCrawler/spiders/piaotian.py
Python
mit
1,931
0.000518
#!/usr/bin/env python # coding=utf-8 """ Created on April 15 2017 @author: yytang """ from scrapy import Selector from libs.misc import get_spider_name_from_domain from libs.polish import polish_title, polish_subtitle, polish_content from novelsCrawler.spiders.novelSpider import NovelSpider class PiaotianSpider(No...
ngs = { # 'DOWNLOAD_DELAY': 0.3, # } def parse_title(self, response): sel = Selector(response) title = sel.xpath('//h1/text()').extract()[0] title = polish_title(title, self.name) return title def parse_episodes(self, response): sel = Selector(response) ...
e(subtitle_selectors): subtitle_url = subtitle_selector.xpath('@href').extract()[0] subtitle_url = response.urljoin(subtitle_url.strip()) subtitle_name = subtitle_selector.xpath('text()').extract()[0] subtitle_name = polish_subtitle(subtitle_name) episodes.app...
signed/intellij-community
python/testData/inspections/PyTupleAssignmentBalanceInspectionTest/unpackNonePy3.py
Python
apache-2.0
65
0.076923
a, b = <warning d
escr="Need more values to unpa
ck">None</warning>
dhoomakethu/apocalypse
apocalypse/server/__init__.py
Python
mit
86
0.011628
""" @author: dhoomakethu """ from __futur
e__ import absolute_import, u
nicode_literals
rokubun/android_rinex
setup.py
Python
bsd-2-clause
547
0.007313
#!/usr/env/bin/ python3 from setuptools import setup, Extension # #CXX_FLAGS = "-O3 -std=gnu
++11 -Wall -Wno-comment" # ## List of C/C++ sources that will conform the library #sources = [ # # "andrnx/clib/android.c", # #] setup(name="andrnx", version="0.1", description="Package to convert from GNSS logger to Rinex files", author='Miquel Garcia', author_ema
il='info@rokubun.cat', url='https://www.rokubun.cat', packages=['andrnx'], test_suite="andrnx.test", scripts=['bin/gnsslogger_to_rnx'])
ulikoehler/FreeCAD_drawing_dimensioning
InitGui.py
Python
gpl-3.0
3,832
0.008351
class DrawingDimensioningWorkbench (Workbench): # Icon generated using by converting linearDimension.svg to xpm format using Gimp Icon = ''' /* XPM */ static char * linearDimension_xpm[] = { "32 32 10 1", " c None", ". c #000000", "+ c #0008FF", "@ c #0009FF", "# c #000AFF", "$ c ...
.", ". .", ". .", ". .", ". .", ".
.", ". .", ". ."}; ''' MenuText = 'Drawing Dimensioning' def Initialize(self): import importlib, os from dimensioning import __dir__, debugPrint, iconPath import linearDimension import linearDimension_stack ...
gilshwartz/tortoisehg-caja
tortoisehg/hgqt/filelistmodel.py
Python
gpl-2.0
7,732
0.002069
# Copyright (c) 2009-2010 LOGILAB S.A. (Paris, FRANCE). # http://www.logilab.fr/ -- mailto:contact@logilab.fr # # 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, o...
stype in _subrepoType2IcoMap: ic = geticon(_subrepoType2IcoMap[stype]) ic = getoverlaidicon(ic, icOverlay) subrepoIcoDict[stype] = ic return subrepoIcoDict class HgFileListModel(QAbstractTableModel): """ Model used for listing (modi
fied) files of a given Hg revision """ showMessage = pyqtSignal(QString) def __init__(self, parent): QAbstractTableModel.__init__(self, parent) self._boldfont = parent.font() self._boldfont.setBold(True) self._ctx = None self._files = [] self._filesdict = {} ...
pyblish/pyblish-mindbender
mindbender/maya/pythonpath/userSetup.py
Python
mit
488
0
"""Maya initialis
ation for Mindbender pipeline""" from maya import cmds def setup(): assert __import__("pyblish_maya").is_setup(), ( "pyblish-mindbender depends on pyblish_maya which has not " "yet been setup. Run pyblish_maya.setup()") from pyblish import api api.register_gui("pyblish_lite") from m...
import api, maya api.install(maya) # Allow time for dependencies (e.g. pyblish-maya) # to be installed first. cmds.evalDeferred(setup)
balancehero/kinsumer
kinsumer/checkpointer.py
Python
mit
1,882
0.000531
""":mod:`kinsumer.checkpointer` --- Persisting positions for Kinesis shards ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """ import abc import json import os.path from typing import Optional, Dict class Checkpointer(abc.ABC, object): """Checkpointer is the interface for persisting ...
d] = sequence def get_checkpoint(self, shard_id: str) -> Optional[str]: return self._checkpoints.get(shard_id) class FileCheckpointer(InMemoryCheckpointer): def __init__(self, file: str) -> None:
super().__init__() self.file = os.path.expanduser(file) if os.path.exists(self.file): with open(self.file, 'rb') as f: self._checkpoints = json.load(f) def checkpoint(self, shard_id: str, sequence: str) -> None: super().checkpoint(shard_id, sequence) ...
gribvirus74/Bee-per
Error.py
Python
gpl-3.0
534
0.035581
class ParametrizedError(Exception): def __i
nit__(self, problem, invalid): self.problem = str(problem) self.invalid = str(invalid) def __str__(self): print('--- Error: {0}\n--- Caused by: {1}'.format(self.problem, self.invalid)) class InvalidToken(ParametrizedError): pass class ToneError(ParametrizedError): pass class IntervalError(Para...
etrizedError): pass
F5Networks/f5-common-python
f5/bigip/tm/cm/test/functional/test_failover_status.py
Python
apache-2.0
1,104
0.000906
# Copyright 2016 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...
software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # class TestFailoverStatus(object): def test_get_status(se...
m/failover-status/") failover_status.refresh() des =\ (failover_status.entries['https://localhost/mgmt/tm/cm/failover-status/0'] ['nestedStats'] ['entries'] ['status'] ['description']) assert des == "ACTIVE"
OpenMined/PySyft
tests/integration/smpc/tensor/share_tensor_test.py
Python
apache-2.0
975
0
# third party # third party import numpy as np import pytest # syft absolute # absolute from syft.core.tensor.smpc.share_tensor import ShareTensor @pytest.mark.smpc def test_bit_extraction() -> None: share = ShareTensor(rank=0, parties_info=[], ring_size=2**32) data = np
.array([[21, 32], [-54, 89]], dtype=np.int32) share.child = data exp_res1 = np.array([[False, False], [True, False]], dtype=np.bool_) res = share.bit_extraction(31).child assert (res == exp_res1).all() exp_res2 = np.array([[True, False], [False, False]], dtype=np.bool_)
res = share.bit_extraction(2).child assert (res == exp_res2).all() @pytest.mark.smpc def test_bit_extraction_exception() -> None: share = ShareTensor(rank=0, parties_info=[], ring_size=2**32) data = np.array([[21, 32], [-54, 89]], dtype=np.int32) share.child = data with pytest.raises(Exception):...
nsalomonis/BAM-to-Junction-BED
multiBAMtoBED.py
Python
apache-2.0
19,040
0.024685
### hierarchical_clustering.py #Author Nathan Salomonis - nsalomonis@gmail.com #Permission is hereby granted, free of charge, to any person obtaining a copy #of this software and associated documentation files (the "Software"), to deal #in the Software without restriction, including without limitation the rights #t...
ir,destination_file)) except Exception: pass ### If a single BAM file is indicated
if bam_file != None: output_filename = string.replace(bam_file,'.bam','') output_filename = string.replace(output_filename,'=','_') destination_file = output_filename+'__exon.bed' paths_to_run = [(bam_file,refExonCoordinateFile,bed_reference_dir,destination_file)] if 'reference'...
kagenZhao/cnBeta
CnbetaApi/CnbetaApis/views.py
Python
mit
3,183
0.002513
#!/usr/bin/env python3 from django.shortcuts import render # Create your views here. from CnbetaApis.datas.Models import * from CnbetaApis.datas.get_letv_json import get_letv_json from CnbetaApis.datas.get_youku_json import get_youku_json from django.views.decorators.csrf import csrf_exempt from django.http import...
.GET.get('limit') or 20 session = DBSession() datas = None if lastID: datas = session.query(Article).order_by(desc(
Article.id)).filter(and_(Article.introduction != None, Article.id < lastID)).limit(limit).all() else: datas = session.query(Article).order_by(desc(Article.id)).limit(limit).all() values = [] for data in datas: values.append({ 'id': data.id, 'title': data.title, ...
fbradyirl/home-assistant
tests/components/google/test_calendar.py
Python
apache-2.0
11,260
0.000977
"""The tests for the google calendar platform.""" import copy from unittest.mock import Mock, patch import httplib2 import pytest from homeassistant.components.google import ( CONF_CAL_ID, CONF_CLIENT_ID, CONF_CLIENT_SECRET, CONF_DEVICE_ID, CONF_ENTITIES, CONF_NAME, CONF_TRACK, DEVICE_...
_of_event + dt_util.dt.timedelta(minutes=60) start = middle_of_event.isoformat() end = end_event.isoformat() event = copy.deepcopy(TEST_EVENT) event["start"]["dateTime"] = start event["end"]["dateTime"] = end mock_next_event.return_value.event = event assert await async_setup_component(hass...
}) await hass.async_block_till_done() state = hass.states.get(TEST_ENTITY) assert state.name == TEST_ENTITY_NAME assert state.state == STATE_ON assert dict(state.attributes) == { "friendly_name": TEST_ENTITY_NAME, "message": event["summary"], "all_day": False, "offse...
capoe/espressopp.soap
src/Int3D.py
Python
gpl-3.0
3,721
0.017468
# Copyright (C) 2012,2013 # Max Planck Institute for Polymer Research # Copyright (C) 2008,2009,2010,2011 # Max-Planck-Institute for Polymer Research & Fraunhofer SCAI # # This file is part of ESPResSo++. # # ESPResSo++ is free software: you can redistr
ibute it and/or modify # it under th
e 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. # # ESPResSo++ is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY ...
areeda/gwpy
gwpy/plot/tests/test_segments.py
Python
gpl-3.0
5,755
0
# -*- coding: utf-8 -*- # Copyright (C) Duncan Macleod (2018-2020) # # This file is part of GWpy. # # GWpy 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)...
re details. # # You should have received a copy of the GNU General Public License # along with GWpy. If not, see <http://www.gnu.org/licenses/>. """Tests for `gwpy.plot.segments` """ import pytest import numpy from matplotlib import rcParams from matplotlib.colo
rs import ColorConverter from matplotlib.collections import PatchCollection from ...segments import (Segment, SegmentList, SegmentListDict, DataQualityFlag, DataQualityDict) from ...time import to_gps from .. import SegmentAxes from ..segments import SegmentRectangle from .test_axes import Tes...
kumar303/rockit
vendor-local/boto/mturk/qualification.py
Python
bsd-3-clause
6,761
0.005177
# Copyright (c) 2008 Chris Moyer http://coredumped.org/ # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, ...
accepted. The value is an integer between 0 and 100. """ def __init__(self, comparator, integer_value, required_to_preview=False): Requirement.__init__(self, qualification_type_id="00000000000000000070", comparator=comparator, integer_value=integer_value, required_to_preview=required_to_preview) class...
dRequirement(Requirement): """ The percentage of assignments the Worker has returned, over all assignments the Worker has accepted. The value is an integer between 0 and 100. """ def __init__(self, comparator, integer_value, required_to_preview=False): Requirement.__init__(self, qualification_t...
ammzen/SolveLeetCode
9PalindromeNumber.py
Python
mit
727
0.008253
# Determine whether an integer is a palindrome. Do this without extra space. class Solution: # @return a boolean def isPalindrome1(self, x): if x < 0 or x % 10 == 0 and x: return False xhalf = 0 while x > xhalf: xhalf = xhalf
* 10 + x % 10 x /= 10 return (x == xhalf or x == xhalf/10 ) def isPalindrome(self, x): if x < 0: return False size, xreverse = x, 0 while size: xreverse = xreverse * 10 + size % 10 si
ze = (size - (size % 10)) / 10 return True if xreverse==x else False if __name__ == '__main__': s = Solution() print s.isPalindrome1(0)
Trinak/PyHopeEngine
src/pyHopeEngine/event/guiEvents.py
Python
gpl-3.0
550
0.007273
''' Created o
n Aug 27, 2013 @author: Devon Define gui events ''' from pyHopeEngine import BaseEvent class Event_ButtonPressed(BaseEvent): '''Sent when a button is pressed''' eventType = "ButtonPressed" def __init__(self, value): '''Contains a value identifying the button''' self.value = value ...
self.height = height
gandalf-the-white/foundation
amaryl/scripts/initdatabase.py
Python
mit
1,705
0.021114
#!/usr/bin/env python # -*- coding: utf-8 -*- import mysql.connector import time import datetime conn = mysql.connector.connect(host="localhost",user="spike",password="valentine", database="drupal
") cann = mysql.connector.connect(host="localhost",user="spike",password="valentine", database="content_delivery_weather") cursor = conn.cursor() cursar = cann.cursor() cursor.execute("""SELECT uid, mail FROM users""") rows = cursor.fetchall() for row in rows: if row[0] != 0: p
rint('{0} : {1} '.format(row[0], row[1])) #print('UPDATE new_v4_users_probes_edit SET email = {0} WHERE uid = {1}'.format(row[1], row[0])) cursar.execute("""UPDATE new_v4_users_probes_edit SET email = %s WHERE userid = %s""",(row[1], row[0])) cursar.execute("""SELECT probename, probeid FROM new_v4_sonde"...
marchdf/dotfiles
mypython/mypython/mytermcolor.py
Python
mit
5,928
0.000337
# I made some modifications to termcolor so you can pass HEX colors to # the colored function. It then chooses the nearest xterm 256 color to # that HEX color. This requires some color functions that I have added # in my python path. # # 2015/02/16 # # # coding: utf-8 # Copyright (c) 2008-2011 Volvox Development Team ...
ue, magenta, cyan, white. Available text highlights: on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan, on_white. Available attributes:
bold, dark, underline, blink, reverse, concealed. Example: colored('Hello, World!', 'red', 'on_grey', ['blue', 'blink']) colored('Hello, World!', 'green') """ if os.getenv("ANSI_COLORS_DISABLED") is None: fmt_str = "\033[%dm%s" if color is not None: if "#" in ...
shub0/algorithm-data-structure
python/find_minimum.py
Python
bsd-3-clause
1,730
0.004046
#! /usr/bin/python ''' Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). Find the minimum element. ''' class Solution: # @param num, a list of integer # @return an integer # You may assume no duplicate exists in the array. def fi...
2**32) size = len(num) if size == 0: return INT_MIN_VALUE elif size == 1: return num[0] low_index = 0 high_index = size - 1 while (low_index < high_index - 1): mid_index = low_index + (high_index - low_index) / 2 if (num[mid...
high_index -= 1 return min(num[low_index], num[high_index]) if __name__ == '__main__': solution = Solution() print solution.findMinDuplicate([3,3,1,2,2])
elliterate/capybara.py
capybara/tests/session/test_has_selector.py
Python
mit
7,185
0.004454
import pytest import re import capybara class TestHasSelector: @pytest.fixture(autouse=True) def setup_session(self, session): session.visit("/with_html") def test_is_true_if_the_given_selector_is_on_the_page(self, session): assert session.has_selector("xpath", "//p") assert sess...
tor("id", "h2one", exact_text="Header Class Test One") assert session.has_no_selector("id", "h2one", exact_text="Header Class Test") def test_only_matches_elements_that_do_not_match_exactly_when_exact_text_true(self, session): assert not session.has_no_selector("id", "h2one", text="Header Class Tes...
_text=True) assert session.has_no_selector("id", "h2one", text="Header Class Test", exact_text=True) def test_does_not_match_substrings_when_exact_text_false(self, session): assert not session.has_no_selector("id", "h2one", text="Header Class Test One", ex...
anetasie/sherpa
sherpa/astro/sim/tests/test_astro_sim_unit.py
Python
gpl-3.0
1,513
0
# # Copyright (C) 2017 Smithsonian Astrophysical Observatory # # # 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. #...
on sherpa/sim/tests_sim_unit.py. """ from sherpa.astro import sim # This is part of #397 # def test_list_samplers(): """Ensure list_samplers returns a list.""" mcmc = sim.MCMC() samplers = mcmc.list_samplers() assert isinstance(samplers, list) assert len(samplers) > 0 def test_list_samplers_...
ce these are the only values. This is # a slightly-different return list to the non-astro version. # samplers = sim.MCMC().list_samplers() for expected in ['mh', 'metropolismh', 'pragbayes', 'fullbayes']: assert expected in samplers
lukius/wifi-deauth
attack/builder.py
Python
mit
2,286
0.010499
from impl import FixedClientDeauthAttack,\ SniffedClientDeauthAttack,\ GlobalDisassociationAttack class WiFiDeauthAttackBuilder(object): '''This object finds the appropriate attack for the options supplied by the user.''' @classmethod def build_from(cls, opt...
thod def handles(cls, options): return len(options.client) == 0 and not options.should_sniff def _get_attack_implementor(self): interface = self.options.interface bssid = self.options.bssid return GlobalDisassociationAttack(interface, bssid) class SniffedClient...
dles(cls, options): return len(options.client) == 0 and options.should_sniff def _get_attack_implementor(self): interface = self.options.interface bssid = self.options.bssid timeout = self.options.timeout return SniffedClientDeauthAttack(interface, bssid, timeout)
huggingface/pytorch-transformers
tests/test_modeling_flax_gpt2.py
Python
apache-2.0
14,464
0.00401
# Copyright 2021 The HuggingFace Team. 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 applicabl...
n_positions=self.max_position_embeddings, n_ctx=self.max_position_embeddings, use_cache=False, bos_token_id=self.bos_token_id, eos_token_id=self.eos_token_id, pad_token_id=self.pad_token_id, gradient_checkpointing=gradient_checkpointing, ) ...
def prepare_config_and_inputs_for_common(self): config_and_inputs = self.prepare_config_and_inputs() config, input_ids, attention_mask = config_and_inputs inputs_dict = {"input_ids": input_ids, "attention_mask": attention_mask} return config, inputs_dict def check_use_cache_forw...
codetojoy/gists
python/pipenv_jun_2020/tests/test_location.py
Python
apache-2.0
257
0.007782
from xyz.location import build_location def test_build_location_simple(): # test Location = build_locatio
n() location = Location("Canada", "Charlottetown") assert location.country == "Canada" assert location.city =
= "Charlottetown"
Haynie-Research-and-Development/jarvis
deps/lib/python3.4/site-packages/Cryptodome/Hash/SHA224.py
Python
gpl-2.0
6,132
0.001794
# -*- coding: utf-8 -*- # # =================================================================== # The contents of this file are dedicated to the public domain. To # the extent that dedication to the public domain is not available, # everyone is granted a worldwide, perpetual, royalty-free, # non-exclusive license to e...
tion of all the arguments. In other words: >>> m.update(a); m.update(b) is equivalent to: >>> m.update(a+b) :Para
meters: data : byte string The next chunk of the message being hashed. """ expect_byte_string(data) result = _raw_sha224_lib.SHA224_update(self._state.get(), data, c_size_t(len(da...
kunaltyagi/nsiqcppstyle
rules/RULE_4_5_A_braces_for_type_definition_should_be_located_in_seperate_line.py
Python
gpl-2.0
3,220
0.001242
""" Braces for type definition(class / struct / union / enum) should be located in the seperate line. == Violation == class K() { <== ERROR } struct K { <== ERROR } == Good == struct A() { <== CORRECT } class K() { <== CORRECT public : void Hello...
) { <== Don't care. It's a function definition. } } """ from nsiqunittest.nsiqcppstyle_unittestbase import * from nsiqcppstyle_rulehelper import * from nsiqcppstyle_repor
ter import * from nsiqcppstyle_rulemanager import * def RunRule(lexer, currentType, fullName, decl, contextStack, typeContext): if not decl and currentType != "NAMESPACE" and typeContext is not None: t = lexer.GetNextTokenInType("LBRACE", False, True) if t is not None: t2 = typ...
quimaguirre/diana
diana/toolbox/parse_uniprot.py
Python
mit
9,091
0.0055
######################################################################### # Uniprot XML parser to parse phosphorylation info of proteins # # eg 29/07/2009 ######################################################################### #from xml.etree.ElementTree import ElementTree from xml.etree.ElementTree import iterparse...
pos = pos_elm.get("position") desc = elem.get("description") vals = desc.split(";") type = vals[0] kinase = vals[1][vals[1].find("by")+2:].strip() if (len(vals
) > 1) else None if self.psiteDesc_to_psiteChar.has_key(type): type = self.psiteDesc_to_psiteChar[type] current_element.add_psite(pos, type, kinase) else: ignored_modification_types.add(type) ...
porduna/appcomposer
alembic/versions/73b63ad41d3_add_autoincrement.py
Python
bsd-2-clause
446
0.008969
"""Add autoincrement Revision ID: 73b63ad41d3 Revises: 331f2c45f5a Create Date: 2017-07-25 17:09:55.204538 """ # revision identifiers, used by Alembic. revision = '73b63ad41d3' down_revision = '331f2c45f5a' from alembic import op from sqlalchemy import Integer import sqlalchemy as sa def upgrade(): op.alter_c...
ble=False) def downgrade(): pass
googleapis/python-certificate-manager
samples/generated_samples/certificatemanager_v1_generated_certificate_manager_update_dns_authorization_async.py
Python
apache-2.0
1,818
0.00165
# -*- 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...
ager_v1_generated_CertificateManager_UpdateDnsAuthorization_async] from google.cloud import certificate_manager_v1 async def sample_update_dns_authorization(): # Create a client client = certif
icate_manager_v1.CertificateManagerAsyncClient() # Initialize request argument(s) dns_authorization = certificate_manager_v1.DnsAuthorization() dns_authorization.domain = "domain_value" request = certificate_manager_v1.UpdateDnsAuthorizationRequest( dns_authorization=dns_authorization, ) ...
grepcook/blog
blog/handlers.py
Python
mit
1,071
0.013072
#!/usr/bin/env python #---coding=utf8--- from HomeHandler import HomeHandler from LoginHandler import LoginHandler from LogoutHandler import LogoutHandler from ArchivesHandler import ArchivesHandler from CategoryHandler import CategoryHandler from TagHandler import TagHandler from PageHandler import PageHandler from Se...
r), (r"/admin/",AdminHome), (r"/list/post",ListPost), (r"/edit/post",EditPost),
(r"/list/comment",ListComment), (r"/list/tag",ListTag), (r"/list/category",ListCategory), (r"/list/html",ListHtml), ]
jackrzhang/zulip
zerver/lib/user_groups.py
Python
apache-2.0
3,997
0.005504
from __future__ import absolute_import from collections import defaultdict from django.db import transaction from django.utils.translation import ugettext as _ from zerver.lib.exceptions import JsonableError from zerver.models import UserProfile, Realm, UserGroupMembership, UserGroup from typing import Dict, Iterable,...
up(user_profile, user_group) return bool(num_deleted) except Exception: return False def create_user_group(name: str, members: List[UserProfile], realm: Realm, description: str='') -> UserGroup: with transaction.atomic(): user_group = UserGroup.objects.create(name=...
roupMembership.objects.bulk_create([ UserGroupMembership(user_profile=member, user_group=user_group) for member in members ]) return user_group def get_user_group_members(user_group: UserGroup) -> List[UserProfile]: members = UserGroupMembership.objects.filter(user_group=use...
mzweilin/HashTag-Understanding
test/test_bing_search.py
Python
apache-2.0
529
0.015123
from bing_search_api import BingSearchAPI my_key = "MEL5FOrb1H5G1E78YY
8N5mkfcvUK2hNBYsZl1aAEEbE" def query(query_string): bing = BingSearchAPI(my_key) params = {'ImageFilters':'"Face:Face"', '$format': 'json', '$top': 10, '$skip': 0} results = bing.search('web',query_string,params).json() # requests 1.0+ return [result['Url'] f...
query(query_string)
ProjectFacet/facet
project/editorial/migrations/0063_assignment_complete.py
Python
mit
453
0.002208
# -*- coding: utf-8 -*- from __future__ import unicode_l
iterals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('editorial', '0062_auto_20171202_1413'),
] operations = [ migrations.AddField( model_name='assignment', name='complete', field=models.BooleanField(default=False, help_text=b'Is the assignment complete?'), ), ]
xhair/TopOdoo_Addons
ToproERP_WeChat_GLD/controllers/wechat_gld.py
Python
agpl-3.0
43,140
0.004475
# -*- coding: utf-8 -*- # © <2016> <ToproERP liujing> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from json import * import logging import string import hashlib import urllib2 from openerp import http from openerp.http import request import Cookie import base64 import pytz import datetime from...
gld = request.env['syt.oa.gld'].sudo().search([('name', '=', gld_name)]) message = request.env['
mail.message'].sudo().search([('res_id', '=', gld.id), ('model', '=', 'syt.oa.gld')]) if message: for value in message: temp_item = {} employee = request.env['hr.employee'].sudo().search([('user_id', '=', int(value.create_uid))]) # temp_item['operator'...
sangh/LaserShow
pyglet-hg/examples/window_platform_event.py
Python
bsd-3-clause
3,351
0.001492
#!/usr/bin/env python # ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are ...
# * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLU...
ONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC...
Paul-Ezell/cinder-1
cinder/volume/drivers/huawei/huawei_driver.py
Python
apache-2.0
49,899
0
# Copyright (c) 2015 Huawei Technologies Co., Ltd. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # ...
t__(self, *args, **kwargs): super(HuaweiBaseDriver, self).__init__(*args, **kwargs)
self.configuration = kwargs.get('configuration') if not self.configuration: msg = _('_instantiate_driver: configuration not found.') raise exception.InvalidInput(reason=msg) self.configuration.append_config_values(huawei_opts) self.xml_file_path = self.configuration...
Donearm/PyImagedownloader
pyimagedownloader/tests/imgchili_test.py
Python
gpl-3.0
12,411
0.005076
#!/usr/bin/env python2 # -*- coding: utf-8 -*- import unittest import imgchili import lxml.html from os.path import join, getsize, isfile class TestImgchili(unittest.TestCase): def setUp(self): self.basedir = '/mnt/d/Maidens/Uploads/' self.url = 'http://imgchili.com/show/2765/2765317_9.jpg' ...
<p><label>Username:&nbsp;</label><input name="username" class="textfield" type="text" /></p> <p><label>Password:&nbsp;</label><input name="password" class="textfield" type="password" /></p> <br /><br /><p><a href="javascript:void(0);" onclick="toggl...
it" value="Log In" class="button1" /></p> </form> </div> </div> </div> <div class="logo_cell"> <a href="./" style="float: left;" class="logo"></a> <div style=""><img src="./theme/images/blank.gif" height="0" width="0" alt="blank" /></div> ...
soumyaslab/pythonlab
py2/excel_example/test_planner_extended_filters.py
Python
gpl-2.0
83,909
0.017841
from audioop import reverse from time import sleep import pytest import requests from utils import * from conftest import file_dir as test_home from conftest import ref_version import json import datetime class TestsortMajor: def test_sort_with_reminderState_1(self): filter_response = call_ref_url("get", make_book...
def test_sort_with_recordingContentState_12(self): filter_response = call_ref_url("get", make_booking_filter_url("sort=title&recordingContentState=partial,complete")) assert filter_response.status_code == 200 def test_sort_with_downloadContentState_13(self): filter_response = call_re
f_url("get", make_booking_filter_url("sort=title&downloadContentState=partial")) assert filter_response.status_code == 200 def test_sort_with_downloadContentState_14(self): filter_response = call_ref_url("get", make_booking_filter_url("sort=title&downloadContentState=complete")) assert filter_response.status_co...
unnikrishnankgs/va
venv/lib/python3.5/site-packages/tensorflow/models/object_detection/exporter.py
Python
bsd-2-clause
13,779
0.006387
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
f = freeze_graph_with_def_protos( input_graph_def=inference_graph_def, input_saver_def=saver.as_saver_def(), input_checkpoint=input_checkpoint, output_node_names=output_node_names, restore_op_name='save/restore
_all', filename_tensor_name='save/Const:0', clear_devices=True, initializer_nodes='') return frozen_graph_def # TODO: Support batch tf example inputs. def _tf_example_input_placeholder(): tf_example_placeholder = tf.placeholder( tf.string, shape=[], name='tf_example') tensor_dict = tf_ex...
doylew/detectionsc
format_py/ngram_nskip.py
Python
mit
6,042
0.015227
import os import glob ###################################################
## ######Init the files################################## ##################################################### os.remove("a0.txt") os.remove("a1.txt") os.remove("a2.txt") os.remove("a3.txt") os.remove("a4.txt") os.remove("a5.txt") os.remove("a6.txt") os.remove("a7.txt") os.remove("a8.txt") os.remove("a9.txt") os.remo...
txt") os.remove("n3.txt") os.remove("n4.txt") os.remove("n5.txt") os.remove("n6.txt") os.remove("n7.txt") os.remove("n8.txt") os.remove("n9.txt") os.remove("v0.txt") os.remove("v1.txt") os.remove("v2.txt") os.remove("v3.txt") os.remove("v4.txt") os.remove("v5.txt") os.remove("v6.txt") os.remove("v7.txt") os.remove("v8...
tddv/readthedocs.org
readthedocs/donate/signals.py
Python
mit
6,234
0.000642
import random from django.dispatch import receiver from django.conf import settings from readthedocs.restapi.signals import footer_response from readthedocs.donate.models import SupporterPromo from readthedocs.donate.constants import INCLUDE, EXCLUDE from readthedocs.donate.utils import offer_promo PROMO_GEO_PATH =...
= [] for obj in promo_queryset: # Break out if we aren't meant to show to this language if obj.programming_language and not show_to_programming_language(obj, programming_language): continue # Break out if we aren't meant to show to this country if country_code and not sh...
# If we haven't bailed because of language or country, possibly show the promo filtered_promos.append(obj) promo_obj = choose_promo(filtered_promos) # Show a random house ad if we don't have anything else if not promo_obj: house_promo = SupporterPromo.objects.filter(live=True, ...
home-assistant/home-assistant
homeassistant/components/opnsense/device_tracker.py
Python
apache-2.0
2,172
0
"""Device tracker support for OPNSense routers.""" from homeassistant.components.device_tracker import DeviceScanner from . import CONF_TRACKER_INTERFACE, OPNSENSE_DATA async def async_get_scanner(hass, config, discovery_info=None): """Configure the OPNSense device_tracker.""" interface_client = hass.data[OP...
class OPNSenseDeviceScanner(DeviceScanner): """This class queries a router running OPNsense.""" def __init__(self, client, interfaces): """Initialize the scanner.""" self.last_results = {} self.client = client self.interfaces = interfaces def _get_mac_addrs(self, devices...
es.""" out_devices = {} for device in devices: if not self.interfaces: out_devices[device["mac"]] = device elif device["intf_description"] in self.interfaces: out_devices[device["mac"]] = device return out_devices def scan_devices(self...
johnnovak/polylinize.py
polylinize.py
Python
mit
6,224
0.002731
#!/usr/bin/env python # Convert line elements with overlapping endpoints into polylines in an # SVG file. import os import sys try: from lxml import etree except ImportError: import xml.etree.ElementTree as etree from collections import defaultdict from optparse import OptionParser SVG_NS = 'http://www.w...
svg): lines = [] for l in svg.getroot().iter('{%s}line' % SVG_NS): lines.append(Line(l)) return lines def align_lines(l1, l2): if ( l1.x1 == l2.x1 and l1.y1 == l2.y1 or l1.x2 == l2.x2 and l1.y2 == l2.y2): l2.reverse() def connect_lines(lines, endpoint_hash, line, direction,...
endpoint_hash.pop_connected_line(line, key) if connected_line: if direction == START: poly.insert(0, connected_line) else: poly.append(connected_line) align_lines(line, connected_line) lines.remove(connected_line) line =...
LukeMurphey/splunk-google-drive
src/bin/google_drive_app/urllib3/connectionpool.py
Python
apache-2.0
36,488
0.000658
from __future__ import absolute_import import errno import logging import sys import warnings from socket import error as SocketError, timeout as SocketTimeout import socket from .exceptions import ( ClosedPoolError, ProtocolError, EmptyPoolError, HeaderParsingError, HostChangedError, Locatio...
Seconds to wait before giving up and raising :class:`urllib3.exceptions.EmptyPoolError` if the pool is empty and :prop:`.block` is ``True``. """ conn = None try:
conn = self.pool.get(block=self.block, timeout=timeout) except AttributeError: # self.pool is None raise ClosedPoolError(self, "Pool is closed.") except queue.Empty: if self.block: raise EmptyPoolError( self, "P...
UK992/servo
tests/wpt/web-platform-tests/tools/wptrunner/wptrunner/tests/__init__.py
Python
mpl-2.0
193
0
import os impor
t sys here = os.path.abspath(os.path.split(__file__)[0]) sys.path.insert(0, os.path.join(here, os.pardir, os.p
ardir, os.pardir)) import localpaths as _localpaths # noqa: F401
leiferikb/bitpop-private
bitpop_specific/extensions/bittorrent_surf/app/lib/falcon-api/python/falcon_api/test/classic.py
Python
bsd-3-clause
2,962
0.015868
import sys import time import json import logging import random import tornado.options from tornado.options import define, options from tornado import gen define('srp_root',default='http://192.168.56.1') #define('srp_root',default='https://remote-staging.utorrent.com') #define('srp_root',default='https://remote.utorre...
for _ in range(1): client = Client(username, password) client.sync() yield gen.Task( asyncsleep, 1 ) #client.add_url(torrent) client.stop() tasks = [] for hash, torrent in client.torrents.items(): if torrent.get('progress') == 1000:
tasks.append( gen.Task( torrent.fetch_files ) ) tasks.append( gen.Task( torrent.fetch_metadata ) ) responses = yield gen.Multi( tasks ) logging.info('responses %s' % [r.code for r in responses]) tasks = [] for hash, torrent in client.torrents.items(): if torrent.get('progr...
beernarrd/gramps
gramps/gen/filters/rules/_matchessourcefilterbase.py
Python
gpl-2.0
2,456
0.0057
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2010 Benny Malengier # Copyright (C) 2011 Tim G L Lyons # # 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 versio...
tion = "Matches objects with sources that match the " \ "specified source filter name" category = _('Citation/source filters') # we want to have this filter show source filters namespace = 'Source' def prepare(self, db, user): MatchesFilterBase.prepare(self, db, user) ...
s None : return False for citation_handle in object.get_citation_list(): citation = db.get_citation_from_handle(citation_handle) sourcehandle = citation.get_reference_handle() if self.MSF_filt.check(db, sourcehandle): return True return Fa...
mxm/incubator-beam
sdks/python/apache_beam/runners/test/__init__.py
Python
apache-2.0
1,360
0.002941
# # 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 us...
ng-import-
order, wrong-import-position from __future__ import absolute_import try: from apache_beam.runners.dataflow.test_dataflow_runner import TestDataflowRunner from apache_beam.runners.direct.test_direct_runner import TestDirectRunner except ImportError: pass # pylint: enable=wrong-import-order, wrong-import-position
mozman/ezdxf
profiling/construct.py
Python
mit
3,719
0.000269
# Copyright (c) 2020, Manfred Moitzi # License: MIT License import sys import time from datetime import datetime from pathlib import Path from ezdxf.acc import USE_C_EXT from ezdxf.render.forms import ellipse if USE_C_EXT is False: print("C-extension disabled or not available.") sys.exit(1) from ezdxf.math._...
log_file.close() def profile1(func, *args) -> float: t0 = time.perf_counter() func(*args) t1 = time.perf_counter() return t1 - t0 def profile(text, log_name, pyfunc, cyfunc, *args): pytime = profile1(pyfunc, *args) cytime = profile1(cyfunc, *args) ratio = pytime / cytime print(f"Pyt...
ratio:.1f}x") log(log_name, pytime, cytime) def profile_py_has_clockwise_orientation(vertices, count): for _ in range(count): py_has_clockwise_orientation(vertices) def profile_cy_has_clockwise_orientation(vertices, count): for _ in range(count): cy_has_clockwise_orientation(vertices) ...
JuliaPackageMirrors/DCEMRI.jl
test/q6/prep6.py
Python
mit
2,599
0.014236
from pylab import * from scipy.io import loadmat, savemat import time
import dicom Rel
= 4.5 # assumed Relaxivity of Gd-DTPA at 3 T [s^-1 [mmol Gd-DTPA]^{-1}] flip_angle = 30 * pi / 180.0 # rad TR = 5e-3 # sec nx = 80 ny = 50 nt = 1321 noise_sigma = 0.2 random_seed = 1337 seed(random_seed) dx = 1 deltat = 1 data_dir = 'DICOM/' file_ext = 'QIBA_v06_Tofts_beta1' outfile_base = 'qiba6' data_dicom = ze...
4shadoww/usploit
modules/apache_users.py
Python
mit
1,754
0.005137
# Copyright (C) 2015 – 2021 Noa-Emil Nissinen (4shadoww) from core.hakkuframework import * from core import getpath import http.client import socket conf = { "name": "apache_users", # Module's name (should be same as file's name) "version": "1.1", # Module version "shortdesc": "scan directory of apache us...
pen(getpath.db()+'apache_users.txt', 'r') paths = [] for line in f: paths.append(line.replace('\n', '')) f.close() try: paths_found = [] for path in paths: path = path.replace("\n", "") conn = http.client.HTTPConnection(variables['target'][0]) ...
res = conn.getresponse() if(res.status==200): print_success("[%s] ... [%s %s]" % (path, res.status, res.reason)) paths_found.append(path) else: print_warning("[%s] ... [%s %s]" % (path, res.status, res.reason)) return paths_found ...
zeqing-guo/SPAKeyManager
MergeServer/apps.py
Python
gpl-3.0
138
0
from __future__ import unicode_literals from django.apps import AppConfig
class MergeserverConfig(AppConfig):
name = 'MergeServer'
ULHPC/modules
easybuild/easybuild-easyblocks/easybuild/easyblocks/f/fastqc.py
Python
mit
1,735
0.002882
## # Copyright 2009-2013 Ghent University # # This file is part of EasyBuild, # originally created by the HPC team of Ghent University (http://ugent.be/hpc/en), # with support of Ghent University (http://ugent.be/hpc), # the Flemish Supercomputer Centre (VSC) (https://vscentrum.be/nl/en), # the Hercules foundation (htt...
ils. # # You should have rece
ived a copy of the GNU General Public License # along with EasyBuild. If not, see <http://www.gnu.org/licenses/>. ## """ General EasyBuild support for installing FastQC @author: Emilio Palumbo """ import os import stat from easybuild.tools.filetools import run_cmd from easybuild.easyblocks.generic.packedbinary impor...
dougthor42/douglib
douglib/plotting.py
Python
mit
1,474
0.000678
# -*- coding: utf-8 -*- """ plotting.py Part of douglib. Used for general data plotting. Created on Tue June 06 08:44:12 2014 @author: dthor """ # --------------------------------------------------------------------------- ### Imports # ----------------------------------------------------------------------...
n rcd_list: x_data.append(rc_to_radius((rcd[0], rcd[1]), die_xy, center_rc)) y_data.append(rcd[2]) pyplot.figure() pyplot.plot(x_data, y_data, 'bo') pyplot.xlabel("Radius") pyplot.ylabel("Value") pyplot.show() def main(): """ Runs only when module is called di...
center_rc = (24, 31.5) fake_rcd_list = [] for row in range(30): for col in range(54): value = (random.normalvariate(10, 5) + rc_to_radius((row, col), die_xy, center_rc)) fake_rcd_list.append([row, col, value]) radius_plot(fake_rcd_list, die_xy, ...
elijah513/ice
scripts/TestController.py
Python
gpl-2.0
3,512
0.008827
#!/usr/bin/env python # ********************************************************************** # # Copyright (c) 2003-2015 ZeroC, Inc. All rights reserved. # # This copy of Ice is licensed to you under the terms described in the # ICE_LICENSE file included in this distribution. # # *************************************...
== 0: sys.stdout.write("removing trust settings for the HTTP server certificate... ") sys.stdout.flush() if os.system("security remove-trusted-cert " + serverCert) != 0: print("\nerror: couldn't remove trust settings for the HTTP server certificate") else:
print("ok") else: print("trust settings already removed") # # On OS X, provide an option to allow removing the trust settings # if TestUtil.isDarwin(): try: opts, args = getopt.getopt(sys.argv[1:], "", ["clean"]) if ("--clean", "") in opts: removeTrustSettings() ...
goodmami/xigt
xigt/mixins.py
Python
mit
9,014
0.000888
import warnings from xigt.consts import ( ID, TYPE, ALIGNMENT, CONTENT, SEGMENTATION ) from xigt.errors import ( XigtError, XigtStructureError ) from xigt.ref import id_re # list.clear() doesn't exist in Python2, but del list[:] has other problems try: [].clear except AttributeError: ...
def insert(self, i, obj): self._assert_type(obj) obj._parent = self._container self._create_id_mapping(obj) list.insert(self, i, obj) def
extend(self, objs): for obj in objs: self.append(obj) def remove(self, obj): # NOTE: this method is destructive. check for broken refs here? if obj.id is not None: del self._dict[obj.id] list.remove(self, obj) def clear(self): self._dict.clear() ...
ai-se/Tree-Learner
_imports/where2.py
Python
unlicense
11,309
0.02131
""" # A Better Where WHERE2 is a near-linear time top-down clustering alogithm. WHERE2 updated an older where with new Python tricks. ## Standard Header Stuff """ from __future__ import division, print_function from pdb import set_trace import sys import types from demos import * from libWhere import * from nas...
. |.. |.. 11 |.. |.. |.. |.. 5. |.. |.. |.. |.. 6. |.. |.. |.. 12 |.. |.. |.. |.. 6. |.. |.. |.. |.. 6.
|.. 47 |.. |.. 23 |.. |.. |.. 11 |.. |.. |.. |.. 5. |.. |.. |.. |.. 6. |.. |.. |.. 12 |.. |.. |.. |.. 6. |.. |.. |.. |.. 6. |.. |.. 24 |.. |.. |.. 12 |.. |.. |.. |.. 6. |.. |.. |.. |.. 6. |.. |.. |.. 12 |.. |.. |.. |.. 6. |.. |.. |.. |.. 6. WHERE2 returns c...
paulcarroty/Learn-Python-The-Hard-Way
ex16.py
Python
gpl-3.0
740
0
# Exercise 16: Reading and Writing Files from sys import argv script, filename = argv print "We're going to erase %r." % filename print "If you don't want that, hit CTRL-C
(^C)." print "If you do want that, hit RETURN." raw_input("?") print "Opening the file..." target = open(filename, 'w') print "Truncating the file. Goodbye!" target.truncate() print "Now I'm going to ask you for three lines." line1 = raw_input("line 1: ") line2 = raw_input("line 2: ") line3 = raw_input("line 3: "...
nt "I'm going to write these to the file." target.write(line1) target.write("\n") target.write(line2) target.write("\n") target.write(line3) target.write("\n") print "And finally, we close it." target.close() # $ python ex16.py test.txt
yland/coala
tests/parsing/StringProcessing/StringProcessingTestBase.py
Python
agpl-3.0
5,848
0.000171
import unittest class StringProcessingTestBase(unittest.TestCase): # The backslash character. Needed since there are limitations when # using backslashes at the end of raw-strings in front of the # terminating " or '. bs = "\\" # Basic test strings all StringProcessing functions should test. ...
, r"1|\+"] # Test strings for the remo
ve_empty_matches feature (alias auto-trim). auto_trim_test_pattern = r";" auto_trim_test_strings = [r";;;;;;;;;;;;;;;;", r"\\;\\\\\;\\#;\\\';;\;\\\\;+ios;;", r"1;2;3;4;5;6;", r"1;2;3;4;5;6;7", ...
dreamsxin/kbengine
assets/scripts/base/kbemain.py
Python
lgpl-3.0
2,796
0.051105
# -*- coding: utf-8 -*- import os import KBEngine from KBEDebug import * def onBaseAppReady(isBootstrap): """ KBEngine method. baseapp已经准备好了 @param isBootstrap: 是否为第一个启动的baseapp @type isBootstrap: BOOL """ INFO_MSG('onBaseAppReady: isBootstrap=%s, appID=%s, bootstrapGroupIndex=%s, bootstrapGlobalIndex=%s' % \ ...
dyForLogin(isBootstrap): """ KBEngine method. 如果返回值大于等于1.0则初始化全部完成, 否则返回准备的进度值0.0~1.0。 在此可以确保脚本层全部初始化完成之后才开放登录。 @param isBootstrap
: 是否为第一个启动的baseapp @type isBootstrap: BOOL """ return 1.0 def onReadyForShutDown(): """ KBEngine method. 进程询问脚本层:我要shutdown了,脚本是否准备好了? 如果返回True,则进程会进入shutdown的流程,其它值会使得进程在过一段时间后再次询问。 用户可以在收到消息时进行脚本层的数据清理工作,以让脚本层的工作成果不会因为shutdown而丢失。 """ INFO_MSG('onReadyForShutDown()') return True def onBaseAppShutDown(sta...
pablosuau/pyBacklogger
controllers/filter_games_controller.py
Python
gpl-2.0
7,069
0.002405
''' This module controls the dialog to set filter criteria ''' from PyQt5 import QtCore, Qt, QtWidgets from views.filter_dialog import Ui_FilterDialog class FilterGamesController(QtWidgets.QDialog): ''' Controller object for the filter games dialog. ''' def __init__(self, table, parent=None): ...
connect( lambda: select_all(self.user_interface.listSystem)) self.user_interface.pushButtonDeselectAllSystem.clicked.connect( lambda: deselect_all(self.user_interface.listSystem)) self.user_interface.pushButtonSelectAllStatus.clicked.connect( lambda: select_all(self.u...
istStatus)) self.user_interface.pushButtonDeselectAllStatus.clicked.connect( lambda: deselect_all(self.user_interface.listStatus)) self.user_interface.pushButtonSelectAllLabel.clicked.connect( lambda: select_all(self.user_interface.listLabel)) self.user_interface.pushButt...
KaiAPaulhus/GifExtract
src/alpha.py
Python
mit
1,716
0.003497
from interface.design.ui_screen import Ui_wnd_gifextract from PyQt5 import QtWidgets import sys import listener import config import ffmpeg import queue import interface.menus.Frame_CreateGif import interface.menus.Frame_ExtractFrames import interface.menus.Frame_Queue class Screen(QtWidgets.QMainWindow): def ...
self.ui.setupUi(self) self.slots = listener.Slots(self)
self.createLinks() setupConfig() setupTabs() setupFFMpeg() setupQueue() def createLinks(self): self.ui.actionPreferences.triggered.connect(self.openOptions) def openOptions(self): import interface.menus.ConfigMenu options = interface.menus.Co...
miurahr/translate
translate/convert/ical2po.py
Python
gpl-2.0
4,527
0.000884
# # Copyright 2007 Zuza Software Foundation # # This file is part of translate. # # translate 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 ve...
self.convert_store() else: self.merge_stores() if self.extraction_msg: self.target_st
ore.header().addnote(self.extraction_msg, "developer") self.target_store.removeduplicates(self.duplicate_style) if self.target_store.isempty(): return 0 self.target_store.serialize(self.output_file) return 1 def run_converter( input_file, output_file, template_file=N...