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
yro/openveda
openveda/config.py
Python
gpl-3.0
6,037
0.00265
import os import sys import json import yaml import getpass import boto """ Configure VDC instance, or read config'd settings into class This will read a default yaml file and output to a instance-specific file, to be read by processes as needed """ from reporting import ErrorObject from global_vars import * cla...
aml', os.path.join( os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'instance_config.yaml' ) ) self.settings_dict = {} self.encode_library = None def run(self
): if self.configure is True: self._configure() if self.configure is False: self._read_settings() self._initiate_environment() def _initiate_environment(self): """ Do the necessaries """ try: self.settings_dict['workdi...
ray-project/ray
python/ray/tune/examples/sigopt_example.py
Python
apache-2.0
2,215
0
"""This example demonstrates the usage of SigOpt with Ray Tune. It also checks that it is usable with a separate scheduler. """ import sys import time from ray import tune from ray.tune.schedulers import AsyncHyperBandScheduler from ray.tune.suggest.sigopt import SigOptSearch def evaluate(step, width, height): ...
"environment variable." ) space = [ { "name": "width", "type": "int", "bounds": {"min": 0, "max": 20}, }, { "name": "height", "type": "int",
"bounds": {"min": -100, "max": 100}, }, ] algo = SigOptSearch( space, name="SigOpt Example Experiment", max_concurrent=1, metric="mean_loss", mode="min", ) scheduler = AsyncHyperBandScheduler(metric="mean_loss", mode="min") analysis = tune.run( ...
NeuralProsthesisLab/unlock
unlock/view/test/test_pyglet_text.py
Python
bsd-3-clause
997
0.011033
from unlock import PygletTextLabel, BellRingTextLabelDecorator from unlock import
PygletWindow, Canvas, UnlockController, AlternatingBinaryStateModel import unittest import pyglet import multiprocessing as mp class PygletTextTests(unittest
.TestCase): def testPygletText(self): window = PygletWindow(fullscreen=False, show_fps=True) canvas = Canvas.create(window.width, window.height) model = AlternatingBinaryStateModel() pos = PositionMixin() text_label = PygletTextLabel(model, canvas, 'the text', canvas.w...
Iwan-Zotow/Fiducial
CADhelpers.py
Python
mit
9,989
0.002803
# -*- coding: utf-8 -*- import sys from typing import List import OCC.TopoDS import aocutils.display.topology from XcMath import utils from point3d import point3d from point2d import point2d # http://opencascade.blogspot.com/2009/02/topology-and-geometry-in-open-cascade_12.html r"""This module ...
99:
return None if V1 > 2e99 or V1 < -2e99: return None if V2 > 2e99 or V2 < -2e99: return None stepu = (U2 - U1) / float(Nu) stepv = (V2 - V1) / float(Nv) pt = OCC.gp.gp_Pnt() blocks = list() for ku in range(0, Nu+1): u = utils.clamp(U1 + float(ku)*stepu, U1, U2) ...
weigj/django-multidb
tests/regressiontests/queries/models.py
Python
bsd-3-clause
36,069
0.001913
""" Various complex queries that have been problematic in the past. """ import datetime import pickle import sys from django.conf import settings from django.db import models from django.db.models.query import Q, ITER_CHUNK_SIZE # Python 2.3 doesn't have sorted() try: sorted except NameError: from django.uti...
25, 0) >>> time4 = datetime.datetime(2007, 12, 20, 21, 0, 0) >>> i1 = Item.objects.create(name='one', created=time1, modified=time1, creator=a1, note=n3) >>> i1.tags = [t1, t2] >>>
i2 = Item.objects.create(name='two', created=time2, creator=a2, note=n2) >>> i2.tags = [t1, t3] >>> i3 = Item.objects.create(name='three', created=time3, creator=a2, note=n3) >>> i4 = Item.objects.create(name='four', created=time4, creator=a4, note=n3) >>> i4.tags = [t4] >>> r1 = Report.objects.create(name='r1', crea...
hwong/samplesubmod
__init__.py
Python
mit
51
0
__version__ = "0.0.2" from .samplesubmod import
*
harikishen/addons-server
tests/ui/pages/desktop/collections.py
Python
bsd-3-clause
779
0
from pypom import Region from selenium.webdriver.common.by import By from base import Base class Collections(Base
): """Collecti
ons page.""" _item_locator = (By.CSS_SELECTOR, '.item') def wait_for_page_to_load(self): self.wait.until(lambda _: len(self.collections) > 0 and self.collections[0].name) return self @property def collections(self): collections = self.find_elements(*self...
yfdyh000/pontoon
pontoon/base/apps.py
Python
bsd-3-clause
1,388
0
from django.apps import AppConfig from django.contrib import admin from django.contrib.admin.sites import AdminSite import session_csrf from session_csrf import anonymous_csrf class BaseConfig(AppConfig): name = 'pontoon.base' verbose_name = 'Base' _has_patched = False def ready(self): supe...
ls. from pontoon.base import signals # NOQA def monkeypatch(self)
: # Only patch once, ever. if BaseConfig._has_patched: return # Monkey-patch Django's csrf_protect decorator to use # session-based CSRF tokens: session_csrf.monkeypatch() admin.site = SessionCsrfAdminSite() BaseConfig._has_patched = True class Ses...
sdss/marvin
tests/api/test_modelcube.py
Python
bsd-3-clause
2,893
0.005876
# !usr/bin/env python2 # -*- coding: utf-8 -*- # # Licensed under a 3-clause BSD license. # # @Author: Brian Cherinka # @Date: 2017-05-19 17:00:49 # @Last modified by: Brian Cherinka # @Last Modified time: 2017-07-30 19:23:16 from __future__ import print_function, division, absolute_import from tests.api.conftest ...
def test_modelcube_failures(self, galaxy, page, params, name, missing, errmsg, bintype, template): params.update({'name': name, 'bintype': bintype, 'template': template}) if name is None: page.route_no_valid_params(page.url, missing, reqtype='post', errmsg=errmsg) el
se: url = page.url.format(**params) url = url.replace('None/', '') if missing in ['bintype', 'template'] else url page.route_no_valid_params(url, missing, reqtype='post', params=params, errmsg=errmsg)
realms-team/solmanager
libs/smartmeshsdk-REL-1.3.0.1/app/Simple/SimpleIPPing.py
Python
bsd-3-clause
4,066
0.014511
#!/usr/bin/python #============================ adjust path ===================================== import sys import os if __name__ == "__main__": here = sys.path[0] sys.path.insert(0, os.path.join(here, '..', '..','libs')) sys.path.insert(0, os.path.join(here, '..', '..','external_libs')) #==============...
# get list of operational motes macs = {} currentMac = (0,0,0,0,0,0,0,0) # start getMoteConfig() iteration with the 0 MAC address continueAsking = True while continueAsking: try: res = connector.dn_getMoteConfig(currentMac,True) except APIError: ...
dress currentMac = res.macAddress # print list of operational motes print '\nmoteId MAC' for (id,mac) in macs.items(): print '{0:<6} {1}'.format(id,FormatUtils.formatMacString(mac)) print '\n================ Step 2. Ping a mote' goOn = True while goOn: ...
anhstudios/swganh
data/scripts/templates/object/tangible/wearables/backpack/shared_backpack_s01.py
Python
mit
462
0.045455
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE D
OCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Tangible() result.template = "object/tangible/wearables/backpack/shared_back
pack_s01.iff" result.attribute_template_id = 11 result.stfName("wearables_name","backpack_s01") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
jjgomera/pychemqt
lib/EoS/Cubic/PR.py
Python
gpl-3.0
12,880
0.000466
#!/usr/bin/python3 # -*- coding: utf-8 -*- r"""Pychemqt, Chemical Engineering Process simulator Copyright (C) 2009-2017, Juan José Gómez Romera <jjgomera@gmail.com> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Softwa...
# Eq 9 else: alfa = (1+m*(1-(T/cmp.Tc)**0.5))**2 # Eq 17 return m, alfa def _GEOS(self, xi): am, bm = self._mixture("PR", xi,
[self.ai, self.bi]) delta = 2*bm epsilon = -bm**2 return am, bm, delta, epsilon def _da(self, tau, x): """Calculate the derivatives of α, this procedure is used for Helmholtz energy formulation of EoS for calculation of properties, alternate alfa formulation must d...
nearai/program_synthesis
program_synthesis/common/tools/reporter.py
Python
apache-2.0
3,368
0
"""Tools to simplify PyTorch reporting and integrate with TensorBoard.""" import collections import six import sys import time try: from tensorflow import summary as tb_summary except ImportError: tb_summary = None class TensorBoardWriter(object): """Write events in TensorBoard format.""" def __ini...
sec)" % elapsed_secs if self._writer: elapsed_steps = float( self._last_step - self._last_reported_step)
self._writer.add( self._last_step, 'step/sec', elapsed_steps / elapsed_secs) line = u"Step {}: {}".format(self._last_step, metrics) if stdout: stdout.write(line) else: print(line) sel...
jpigree/config
sys/__init__.py
Python
unlicense
2,239
0
#!/usr/bin/env python # -*- coding: utf-8 -*- import imp import logging from os import walk from os.path import realpath, dirname, join, isdir, isfile from getpass import getuser from sys import exit WORKDIR = realpath(join(dirname(__file__))) PACKAGES = "packages" def build_cli(parent_subparser): sys_choices ...
=sys_choices) install_parser.add_argument( '--no-pacman-refresh', action='store_true', help='Disable pacman refresh' ) # No remove command, too dangerous def available_sys_types(): for element in next(walk(WORKDIR))[1]: if isdir(join(WORKDIR, element)) and not element...
", "_"]: yield element def install(tools_module, args): if not getuser() == "root": tools_module.error_print("Need to be executed with sudo!!!") exit(1) if not args.no_pacman_refresh: tools_module.pacman_refresh() if args.TYPE == "all": for type in [sys_type f...
JuBra/GEMEditor
GEMEditor/model/classes/reference.py
Python
gpl-3.0
4,310
0.00116
from collections import namedtuple from uuid import uuid4 from GEMEditor.model.classes.annotation import Annotation class Reference: """ ReferenceItem contains the information a pubmed or similar literature reference Authors are saved as author instances """ def __init__(self, id=None, pmid="", pmc="", d...
. Parameters ---------- reference: GEMEditor.model.classes.base.ReferenceLink reciprocal: bool """ self._linked_items.add(item) if reciprocal: item.add_reference(self, reciprocal=False) def remove_link(self, item, reciprocal=True): """ Re...
k reciprocal: bool """ self._linked_items.discard(item) if reciprocal: item.remove_reference(self, reciprocal=False) def remove_all_links(self): """ Remove all reference links """ for item in self.linked_items: self.remove_link(item, reciproc...
xgds/xgds_basalt
apps/basaltApp/scripts/setReplicationFilters.py
Python
apache-2.0
4,119
0.005584
#!/usr/bin/env python import optparse from os import system class ReplicationData: tableList = [{'database':'xgds_basalt', 'tables':[ 'xgds_video_videosegment', 'xgds_video_videoepisode', 'xgds_core_constant', ...
/irg/tungsten/tungsten/tools/tpm update --skip-validation-check=MySQLMyISAMCheck --skip-validation-check=MySQLUnsupportedDataTypesCheck --hosts=%s,%s --repl-svc-applier-filters=delay,replicate --property=replicator.filter.delay.delay=%s --property=replicator.filter.replicate.ignore=" def getTableListString(self): ...
for ti in self.tableList: dbName = ti['database'] for tname in ti['tables']: tableFullNameList.append("%s.%s" % (dbName, tname)) tableListString = ",".join(tableFullNameList) return tableListString def buildReplicationCommand(self, delayTimeSecs=0, remoteHos...
project-icp/bee-pollinator-app
src/icp/apps/beekeepers/migrations/0013_update_queen_source_options.py
Python
apache-2.0
778
0.001285
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migra
tions, models class Migration(migrations.Migration): dependencies = [ ('beekeepers', '0012_add_new_survey_fields'), ] operations = [ migrations.AlterField( model_name='monthlysurvey', name='queen_source', field=models.CharField(blank=True, max_length=2...
from?', choices=[('NON_LOCAL_COMMERCIAL', 'Non-local commercial breeder'), ('LOCAL_COMMERCIAL', 'Local commercial breeder'), ('LOCAL_NON_COMMERCIAL', 'Local, non-commercial or reared on site'), ('REQUEENED', 'Colony requeened itself'), ('PACKAGE', 'Package'), ('FERAL', 'Feral colony or swarm')]), ), ]
wangyixiaohuihui/spark2-annotation
python/pyspark/shuffle.py
Python
apache-2.0
28,525
0.000386
# # 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 n...
and load them partition by partition again. `data` and `pdata` are used to hold the merged items in memory. At first, all the data are merged into `data`. Once the used memory goes over limit, the items in `data` are dumped into disks, `data` will be cleared, all rest of i
tems will be merged into `pdata` and then dumped into disks. Before returning, all the items in `pdata` will be dumped into disks. Finally, if any items were spilled into disks, each partition will be merged into `data` and be yielded, then cleared. >>> agg = SimpleAggregator(lambda x, y: x...
DedMemez/ODS-August-2017
hood/CogHood.py
Python
apache-2.0
2,990
0.004013
# Fuck you Disyer. Stealing my fucking paypal. GET FUCKED: toontown.hood.CogHood from panda3d.core import Lens from direct.fsm import ClassicFSM, State from toontown.toonbase import ToontownGlobals from toontown.hood.Hood import Hood class CogHood(Hood): notify = directNotify.newCategory('CogHood') ID ...
atus) def exitCogHQLoader(self): self.ignore(self.loaderDoneEvent) self.loader.exit() self.loader.unload() del self.loader def handleCogHQLoaderDone(self): doneStatus = self.loader.getDoneStatus() if self.isSameHood(doneStatus): self.fsm.r...
messenger.send(self.doneEvent) def exit(self): base.localAvatar.setCameraFov(settings['fov']) base.camLens.setNearFar(ToontownGlobals.DefaultCameraNear, ToontownGlobals.DefaultCameraFar) Hood.exit(self)
albatros69/monit-pi
monit/monit.py
Python
gpl-2.0
946
0.005285
#! /usr/bin/python # vim: set fileencoding=utf-8 sw=4 ts=4 et: import rrdtool, os from def_rrds import rrds import def_metrics from def_metrics import metrics for m in metrics: if isinstance(metrics[m]['
rrd'], list): # multiples rrds for i,f in enumerate(metrics[m]['rrd']): if not os.path.isfile(f): rrdtool.create(f, rrds[m][i]) else: if not os.path.isfile(metrics[m]['rrd']): rrdt
ool.create(metrics[m]['rrd'], rrds[m]) values = getattr(def_metrics, '_get_'+m)() #print(m, repr(values)) if isinstance(metrics[m]['rrd'], list): # multiples rrds for i,f in enumerate(metrics[m]['rrd']): rrdtool.update(f, 'N:'+':'.join(values[i])) else: if isinstance...
nanocell/lsync
python/boto/dynamodb/__init__.py
Python
gpl-3.0
2,701
0
# Copyright (c) 2011 Mitch Garnaat http://garnaat.org/ # Copyright (c) 2011 Amazon.com, Inc. or its affiliates. All Rights Reserved # # 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 ...
egionInfo(name='us-west-1', endpoint='dynamodb.us-west-1.amazonaws.com', connection_cls=boto.dynamodb.layer2.Layer2), RegionInfo(name='us-west-2', endpoint='dynamodb.us-west-2.amazonaws.com', connection_cls=boto.dyna...
m', connection_cls=boto.dynamodb.layer2.Layer2), RegionInfo(name='ap-southeast-1', endpoint='dynamodb.ap-southeast-1.amazonaws.com', connection_cls=boto.dynamodb.layer2.Layer2), RegionInfo(name='eu-west-1', ...
plotly/plotly.py
packages/python/plotly/plotly/validators/heatmapgl/hoverlabel/_font.py
Python
mit
1,875
0
import _plotly_utils.basevalidators class FontValidator(_plotly_utils.basevalidators.CompoundValidator): def __init__( self, plotly_name="font", parent_name="heatmapgl.hoverlabel", **kwargs ): super(FontValidator, self).__init__( plotly_name=plotly_name, parent_name=par...
.pop("data_class_str", "Font"), data_docs=kwargs.pop( "data_docs", """ color colorsrc Sets the source reference on Chart Studio Cloud for `color`. family HTML font family - the typeface that ...
available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The Chart Studio Cloud (at https://chart-studio...
Cat5TV/nems-migrator
data/1.6/argonone/test.py
Python
gpl-3.0
199
0.01005
#!/usr/bin/python fr
om datetime import datetime dateTimeObj = datetime.now() with open("/var/log/nems/argonone.log","a") as text_file: text_file.write("{0} Test was run.\r\n".format(dateTimeObj))
zerodb/zerodb
zerodb/crypto/exceptions.py
Python
agpl-3.0
41
0
class Wro
ngKeyError(E
xception): pass
rahulunair/nova
nova/virt/disk/mount/api.py
Python
apache-2.0
10,966
0.000091
# Copyright 2011 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, so...
ied. See the # License for the specific language governing permissions and limitations # under the License. """Support for mounting virtual image files.""" import os import time from oslo_log import log as logging from oslo_service import loopingcall from oslo_utils import importutils from nova import exception from...
a.i18n import _ import nova.privsep.fs from nova.virt.image import model as imgmodel LOG = logging.getLogger(__name__) MAX_DEVICE_WAIT = 30 MAX_FILE_CHECKS = 6 FILE_CHECK_INTERVAL = 0.25 class Mount(object): """Standard mounting operations, that can be overridden by subclasses. The basic device operations ...
AndreaOrru/Gilgamesh
gilgamesh/utils/signed_types.py
Python
bsd-2-clause
153
0
from ctypes import c_byte, c_short def s8(byte: int) -> int:
return c_byte(byte).value def s16(
word: int) -> int: return c_short(word).value
cocreature/pytracer
__init__.py
Python
mit
204
0
import pytracer.color import pytracer.mat
erials import pytracer.camera import pytracer.scene import pytracer.objects import pytracer.vector import pytracer.main import pytracer.lights import pytracer.
ray
sloede/config
vim/vim/AutomaticTexPlugin_12.1/ftplugin/ATP_files/latextags.py
Python
unlicense
14,763
0.014292
#!/usr/bin/python # -*- coding: utf-8 -*- # Author: Marcin Szamotulski # http://atp-vim.sourceforge.net # # Copyright Statement: # This file is a part of Automatic Tex Plugin for Vim. # # Automatic Tex Plugin for Vim is free software: you can redistribute it # and/or modify it under the terms of the GNU Ge...
)?{.*}\s*%s{%s}' % (pat, match), line): tag_type="section" elif re.search('\\\\subsection(?:\[.*\])?{.*}\s*%s{%s}' % (pat, match), line): tag_type="subsection" elif re.search('\\\\subsubsection(?:\[.*\])?{.*}\s*%s{%s}' % (pat, match), line): tag_type="subsubsection" elif re.search('\...
h), line): tag_type="paragraph" elif re.search('\\\\subparagraph(?:\[.*\])?{.*}\s*%s{%s}' % (pat, match), line): tag_type="subparagraph" elif re.search('\\\\begin{[^}]*}', line): # \label command must be in the same line, # To do: I should add searching in next line too. ...
mmihaltz/pysettrie
tests/test_settrie.py
Python
lgpl-3.0
15,405
0.010128
#!/usr/bin/env python3 # coding: utf8 """ Unit tests for module PySetTrie (see settrie.py). Author: Márton Miháltz https://sites.google.com/site/mmihaltz/ """ import unittest from settrie import SetTrie, SetTrieMap, SetTrieMultiMap class TestSetTrie(unittest.TestCase): """ UnitTest for SetTrie class """ d...
.t.subsets({1, 3, 5, 111}), [{1, 3}, {1, 3, 5}])
self.assertEqual(self.t.subsets({1, 4, 8}), [{1, 4}]) self.assertEqual(self.t.subsets({2, 3, 4, 5}), [{2, 3, 5}, {2, 4}]) self.assertEqual(self.t.subsets({2, 3, 5, 6}), [{2, 3, 5}]) class TestSetTrieMap(unittest.TestCase): """ UnitTest for SetTrieMap class """ def setUp(self): self.t = SetTrieMap...
biomodels/MODEL1006230031
setup.py
Python
cc0-1.0
377
0.005305
from setuptools import setup, find_pac
kages setup(name='MODEL1006230031', version=20140916, description='MODEL1006230031 from BioModels', url='http://www.ebi.ac.uk/biomodel
s-main/MODEL1006230031', maintainer='Stanley Gu', maintainer_url='stanleygu@gmail.com', packages=find_packages(), package_data={'': ['*.xml', 'README.md']}, )
ducthangho/imdb
test.py
Python
apache-2.0
5,282
0.008141
#!/usr/bin/env python3 # # This file is open source software, licensed to you under the terms # of the Apache License, Version 2.0 (the "License"). See the NOTICE file # distributed with this work for additional information regarding copyright # ownership. You may not use this file except in compliance with the Licen...
tream_test', 'httpd', ] other_tests = [ 'smp_test', ] last_len = 0 def print_status_short(msg): global last_len print('\r' + ' '*last_len, end='') last_len = len(msg) print('\r' + msg, end='') print_status_verbose = print class Alarm(Exception): pass def alarm_handler(signum,
frame): raise Alarm if __name__ == "__main__": all_modes = ['debug', 'release'] parser = argparse.ArgumentParser(description="Seastar test runner") parser.add_argument('--fast', action="store_true", help="Run only fast tests") parser.add_argument('--name', action="store", help="Run only test who...
nielsbuwen/ilastik
tests/test_applets/objectClassification/testPrediction.py
Python
gpl-3.0
15,423
0.012514
############################################################################### # ilastik: interactive learning and segmentation toolkit # # Copyright (C) 2011-2014, the ilastik developers # <team@ilastik.org> # # This program is free software; you can redistribute it and/or # mod...
dicted_labels[23]==1 assert predicted_labels[2]==2 assert predicted_labels[18]==2 assert predicted_labels[24]==2 assert predicted_labels[26]==2 #Predict by neighborhood color selFeatures = {"Standard Object Features": {"Mean in neighborhood":{"margin": (5...
t() predicted_labels = predictions[0] assert predicted_labels[0]==0 assert predicted_labels[1]==1 assert predicted_labels[8]==1 assert predicted_labels[24]==1 assert predicted_labels[28]==1 assert predicted_labels[9]==2 assert predicted_labels[14]==2 ...
gem/oq-hazardlib
openquake/hazardlib/geo/__init__.py
Python
agpl-3.0
1,848
0
# -*- coding: utf-8 -*- # vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright (C) 2012-2017 GEM Foundation # # OpenQuake 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 Licen...
# # You should have received a copy of the GNU Affero General Public License # along with OpenQuake. If not, see <http://www.gnu.org/licenses/>. """ Package :mod:`openquake.hazardlib.geo` contains implementations of different geographical primitives, such as :class:`~openquake.hazardlib.geo.point.Point`, :class:`~ope...
zardlib.geo.polygon.Polygon` and :class:`~openquake.hazardlib.geo.mesh.Mesh`, as well as different :mod:`surface <openquake.hazardlib.geo.surface>` implementations and utility class :class:`~openquake.hazardlib.geo.nodalplane.NodalPlane`. """ from openquake.hazardlib.geo.point import Point from openquake.hazardlib.geo....
brettchien/LeetCode
125_ValidPalindrome.py
Python
mit
1,516
0.004617
class Solution: # @param {string} s # @return {boolean} def isPalindrome(self, s): s = s.lower() if len(s) in [0, 1]:
return True else: start = 0 end = len(s) - 1 while end - start > 0: while not self.isAlphanumeric(s[start]): if start < end: start += 1 else: break ...
if end > start: end -= 1 else: break if start == end: break # print start, end if s[start] != s[end]: return False else: ...
KrzysztofStachanczyk/Sensors-WWW-website
www/env/lib/python2.7/site-packages/django/conf/locale/es_CO/formats.py
Python
gpl-3.0
767
0
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django pack
age. # from __future__ import unicode_literals DATE_FORMAT = r'j \d\e F \d\e Y' TIME_FORMAT = 'H:i' DATETIME_FORMAT = r'j \d\e F \d\
e Y \a \l\a\s H:i' YEAR_MONTH_FORMAT = r'F \d\e Y' MONTH_DAY_FORMAT = r'j \d\e F' SHORT_DATE_FORMAT = 'd/m/Y' SHORT_DATETIME_FORMAT = 'd/m/Y H:i' FIRST_DAY_OF_WEEK = 1 DATE_INPUT_FORMATS = [ '%d/%m/%Y', '%d/%m/%y', # '25/10/2006', '25/10/06' '%Y%m%d', # '20061025' ] DATETIME_INPUT_FORMATS = [ ...
CalebBell/thermo
tests/test_electrochem.py
Python
mit
36,985
0.004569
# -*- coding: utf-8 -*- '''Chemical Engineering Design Library (ChEDL). Utilities for process modeling. Copyright (C) 2016, 2017 Caleb Bell <Caleb.Andrew.Bell@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...
_capacity_w(T+273.15), rtol=1e-5) @pytest.mark.slow def test_dissociation_reactions(): # Check there's only one dissociation reaction for each product assert len(df['Electrolyte Formula']) == len(set(df['Electrolyte Formula'].values.tolist())) # Check the chemicals match up with the...
assert CAS_from_any(CAS) == CAS assert pubchem_db.search_CAS(CAS).formula == serialize_formula(formula) # Check the anions match up with the database for formula, CAS, charge in zip(df['Anion formula'], df['Anion CAS'], df['Anion charge']): assert CAS_from_any(CAS) == CAS assert CAS_f...
dcrankshaw/clipper
clipper_admin/clipper_admin/deployers/pyspark.py
Python
apache-2.0
10,541
0.002941
from __future__ import print_function, with_statement, absolute_import import shutil import pyspark import logging import re import os import json from ..version import __version__ from ..clipper_admin import ClipperException from .deployer_utils import save_python_function logger = logging.getLogger(__name__) def ...
labels : list(str), optional
A list of strings annotating the model. These are ignored by Clipper and used purely for user annotations. registry : str, optional The Docker container registry to push the freshly built model to. Note that if you are running Clipper on Kubernetes, this registry must be accesible ...
ManagementCenterInnsbruck/Flying-PCB
Software/LARIX Flightcontroller/MATLAB_HIL_ARMGCC/RPI_Software/V002_20062017/project_interface.py
Python
gpl-3.0
4,745
0.014542
__author__ = "Markus Lechner" __license__ = "GPL" __version__ = "0.0.2" __maintainer__ = "Markus Lechner" __email__ = "markus.lechner@technikum-wien.at" __status__ = "Production" import sys import time import logging from app_status import Thread_Application_Status from spi_com import SPI_Communication from uart_com...
tus_thread() spi_frame = [] #It is necessary to send 0.0 as controller value for the very #first time, due to sensor data are not available at
the beginning #of the data transmission self.int_spi.send_spi_frame(0.0) spi_frame = self.int_spi.receive_spi_frame(self.SPI_DATA_IND) self.controller_proc.set_controller_param(spi_frame) while True: #Get controlled values ctrl_data =...
rio-group/trabalho-ai-pacman
graphicsDisplay.py
Python
unlicense
24,882
0.017201
# graphicsDisplay.py # ------------------ # Licensing Information: Please do not distribute or publish solutions to this # project. You are
free to use and extend these projects for educational # purposes. The Pacman AI projects were developed at UC Berkeley, primarily by # John DeNero (denero@cs.berkeley.edu) and Dan Klein (kle
in@cs.berkeley.edu). # For more info, see http://inst.eecs.berkeley.edu/~cs188/sp09/pacman.html from graphicsUtils import * import math, time from game import Directions ########################### # GRAPHICS DISPLAY CODE # ########################### # Most code by Dan Klein and John Denero written or rewritten f...
JackDanger/sentry
src/sentry/south_migrations/0086_auto__add_field_team_date_added.py
Python
bsd-3-clause
23,507
0.00821
# -*- coding: 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 field 'Team.date_add
ed' db.add_column('sentry_team', 'date_added', self.gf('django.db.models.fields.DateTimeField')(default=datetime.datetime.now, null=True), keep_default=False) def backwards(self, orm): # Deleting field 'Team.date_added' db.delete_column('sentry_t...
models = { 'sentry.user': { 'Meta': {'object_name': 'User', 'db_table': "'auth_user'"}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'...
divio/django-cms
cms/toolbar/items.py
Python
bsd-3-clause
16,937
0.00183
import json from abc import ABCMeta from collections import defaultdict from django.template.loader import render_to_string from django.utils.encoding import force_str from django.utils.functional import Promise from cms.constants import RIGHT, LEFT, REFRESH_PAGE, URL_CHANGE class ItemSearchResult: def __init__...
if self.extra_context: return self.extra_context return {} class SubMenu(ToolbarAPIMixin, BaseItem): template = "cms/toolbar/items/menu.html" sub_level = True active = False def __init__(self, name, csrf_token, disabled=False, side=LEFT): ToolbarAPIMixin.__init__(self) ...
:%s>' % force_str(self.name) def add_break(self, identifier=None, position=None): item = Break(identifier) self.add_item(item, position=position) return item def get_items(self): items = self.items for item in items: item.toolbar = self.toolbar i...
infoINGenieria/Zweb
z_web/registro/migrations/0016_auto_20151230_0957.py
Python
gpl-2.0
1,002
0.003003
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('registro', '0015_auto_20151220_1216'), ] operations = [ migrations.AlterField( model_name='certificacion', ...
field=models.ForeignKey(to='core.Obras', related_name='certificaciones_obras'), ), migration
s.AlterField( model_name='certificacion', name='periodo', field=models.ForeignKey(related_name='certificaciones_periodo', verbose_name='Periodo', to='parametros.Periodo'), ), migrations.AlterField( model_name='registro', name='dia', ...
abhishek-sehgal954/Inkscape_extensions_for_halftone_filters
SVG_to_SVG/svg_to_svg_ordered_dithering.py
Python
gpl-2.0
7,450
0.012752
"""Copyright (c) 2017 abhishek-sehgal954 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 version. This prog...
def draw_circle(self,(x, y), r, color, parent, id_): style = {'stroke': 'none', 'stroke-width': '1', 'fill': color,"mix-blend-mode" : "multiply"} attribs = {'style': simplestyle.formatStyle(style), 'cx': str(x), 'cy': str(y), 'r': str(r)} if id_ is not None: attribs.update...
: style = {'stroke': 'none', 'stroke-width': '1', 'fill': color,"mix-blend-mode" : "multiply"} if(transform == 1.5): attribs = {'style': simplestyle.formatStyle(style), 'cx': str(x), 'cy': str(y), 'rx': str(r1), 'ry': str(r2)} elif(transform == 3): attribs = {'st...
miing/mci_migo
api/v10/handlers.py
Python
agpl-3.0
14,587
0.000206
# Copyright 2010-2012 Canonical Ltd. This software is licensed under the # GNU Affero General Public License version 3 (see the file LICENSE). import logging import json from datetime import datetime, timedelta from django.conf import settings from django.core.exceptions import ValidationError from django.core.seria...
GET', 'POST')
response = {} baseurl = settings.SSO_ROOT_URL.strip('/') def __init__(self): self.response = self.response.copy() for key, value in self.response.items(): if key.endswith('_link'): self.response[key] = value % self.baseurl def read(self, request): if...
zvolsky/platby
controllers/jednoduche.py
Python
agpl-3.0
3,803
0.022877
# coding: utf8 from mz_wkasa_platby import Uc_sa, zpatky, aliases @auth.requires_membership('vedeni') def bu2(): response.view = 'jednoduche/pohyby.html' md, dal, org = aliases(db) return dict(sledovany=Uc_sa.bezny, pohyby=db((db.pohyb.datum>=zpatky(60))&( (db.pohyb.iddal=...
d.on(md.id==db.pohyb.idma_dati), dal.on(dal.id==db.pohyb.iddal)), orderby=~db.pohyb.datum)) @auth.requires_membership('vedeni') def bu(): response.view = 'jednoduche/pohyby.html' md, dal, org = aliases(db) return dict(sledovany=Uc_sa.bezny, pohyby=db((db.pohyb.idda...
(db.pohyb.idma_dati==Uc_sa.bezny)).select( db.pohyb.ALL, db.auth_user.nick, org.nick, md.zkratka, dal.zkratka, left=(db.auth_user.on(db.auth_user.id==db.pohyb.idauth_user), org.on(org.id==db.pohyb.idorganizator), md.on(md.id==db.pohyb...
modelblocks/modelblocks-release
resource-incrsem/scripts/unkword.py
Python
gpl-3.0
1,388
0.016571
import sys import re import storestate UNKCOUNT = int(sys.argv[1]) WordCount = { } for line in open(sys.argv[2]): count,word = line.split() WordCount[word] = int(count) for line in sys.stdin: wordlist = re.findall('(?<= )[^\(\) ]+',line) for word in wordlist: ## if word not in WordCount: ## sys.std...
word)+'(?=[\(\) \n])',storestate.getUnkWord(word),line) sys.stdout.write( line ) ''' import sys import codecs import collections import storestate MINCOUNT = 2 Items = [ ] WCount = collections.defaultdict(int) for line in codecs.getreader('utf-8')(sys.stdin): cond = line.partition(' : ')[0] w = line.partiti...
if WCount[w]>=MINCOUNT else\ storestate.getUnkWord(w)) ) # otherwise # 'unk+'+('ing' if w.endswith('ing') else\ # 'ed' if w.endswith('ed') else\ # 's' if w.endswith('s') else\...
Signiant/maestro-core
maestro/tools/path.py
Python
mit
3,383
0.005616
import os, platform, re, shutil def get_tree_size(path = '.'): """ get_tree_size will return the total size of a directory tree """ if not os.path.exists(path): raise OSError("Path " + str(path) + " does not exist!") total_size = 0 for dirpath, dirnames, filenames in os.walk(str(path))...
e of the inputted path. Returns the absolute path if found (with correct casing) or None. """ if os.path.exists(path): return path elif platform.system() == "Windows": return None path_elements = full_split(path) path_root = None drive, path = os.path.splitdrive(path) if no...
ot = os.path.abspath(os.path.normpath("./")) else: path_root = os.path.abspath(os.path.normpath("/")) else: path_root = os.path.abspath(os.path.normpath(drive)) if not os.path.exists(path_root): raise OSError("Unable to locate path root: " + str(path_root)) #Build the f...
miso-belica/sumy
tests/test_models/test_tf.py
Python
apache-2.0
4,023
0.001491
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals import pytest from sumy.models import TfDocumentModel from sumy.nlp.tokenizers import Tokenizer def test_no_tokenizer_with_string(): with pytest.raises(ValueError): TfDocumentModel("text without t...
WB", "wB", "WA")) terms = tuple(sorted(model.terms)) assert terms == ("wa", "wb") def test_pretokenized_words_frequencies(): model = TfDocumentModel(("wC", "wC", "WC", "wA", "WB", "wB")) assert model.term_
frequency("wa") == 1 assert model.term_frequency("wb") == 2 assert model.term_frequency("wc") == 3 assert model.term_frequency("wd") == 0 assert model.most_frequent_terms() == ("wc", "wb", "wa") def test_magnitude(): tokenizer = Tokenizer("english") text = "wA wB wC wD" model = TfDocument...
ungarj/mapchete
test/testdata/geojson_test.py
Python
mit
717
0
"""Example process file.""" from mapchete.errors import MapcheteNodataTile from shapely.geometry import shape def execute(mp): """User defined process.""" # Reading and writing data works like this: with mp.open("file1") as vector_file: if vector_file.is_empty(): raise MapcheteNodataT...
properties=dict( name=feature["properties"].get("NAME_0", None), id=feature["properties"].get("ID_0", None), area=shape(feature["geometry"]).area, ), ) for feature
in vector_file.read() ]
dneiter/exabgp
lib/exabgp/reactor/loop.py
Python
bsd-3-clause
15,137
0.031314
# encoding: utf-8 """ reactor/loop.py Created by Thomas Mangin on 2012-06-10. Copyright (c) 2009-2015 Exa Networks. All rights reserved. """ import os import re import sys import time import signal import select from collections import deque from exabgp.protocol.ip import IP from exabgp.reactor.daemon import Daemo...
e keys.discard(key) if not self.schedule() and not keys: ready = self.ready(ios.keys() + self.processes.fds(),end-time.time()) for io in ready: if io in ios: keys.add(ios[io]) del ios[io] if not keys: reload_completed = True # RFC state that we MU...
cause the session to drop if self.listener: for connection in self.listener.connected(): # found # * False, not peer found for this TCP connection # * True, peer found # * None, conflict found for this TCP connections found = False for key in self.peers: pee...
guillaume-havard/test_cherrypy
src/tut3.py
Python
mit
345
0.005797
import random import string import cherrypy class StringGenerator(object): @cherrypy.expose def index(self):
return "Hello wo
rld!" @cherrypy.expose def generate(self, length=8): return ''.join(random.sample(string.hexdigits, int(length))) if __name__ == '__main__': cherrypy.quickstart(StringGenerator())
treyhunner/django-appconf
tests/tests.py
Python
bsd-3-clause
5,628
0
from __future__ import absolute_import from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.test import TestCase from .models import (AppConf, TestConf, PrefixConf, YetAnotherPrefixConf, SeparateConf, ProxyConf, CustomHolderConf,...
self): class RequirementConf(AppConf): SIMPLE_VALUE = Tr
ue class Meta: required = ['SIMPLE_VALUE'] def test_missing(self): self.assertRaises(ImproperlyConfigured, self.create_invalid_conf)
asgordon/DPLL
cnf.py
Python
bsd-2-clause
5,803
0.005859
# Homework 2 solution, part 1: cnf.py # Andrew Gordon # Feb 18, 2015 # Revised June 19, 2015 for better input/output and implies->if import sys import fileinput def biconditionalElimination(s): if type(s) is str: return s elif type(s) is list and s[0] == "iff": return(["and", [...
rn result else: return([s[0]] + [andAssociativity1(i) for i in s[1:]]) def orAssociativity(s): revision = orAssociativity1(s) if revision == s: return s else: return orAssociativity(revision) def orAssociativity1(s): if type(s) is str: return s elif type(s) is l...
f type(i) is list and i[0] == "or": result = result + i[1:] else: result.append(i) return result else: return([s[0]] + [orAssociativity1(i) for i in s[1:]]) def removeDuplicateLiterals(s): if type(s) is str: return s if s[0] == "not": ...
chipx86/reviewboard
reviewboard/reviews/managers.py
Python
mit
28,564
0
from __future__ import unicode_literals import logging from django.contrib.auth.models import User from django.core.exceptions import ObjectDoesNotExist from django.db import connections, router, transaction from django.db.models import Manager, Q from django.db.models.query import QuerySet from django.utils import s...
if show_all_local_sites: assert local_site is None else: qs = qs.filter(local_site=local_site) if distinct: qs = qs.distinct() return qs def accessible_ids(self, *args, **kwargs): """Return IDs of groups that are accessible by the given...
d: 3.0.24: In prior versions, the order was not specified, but was generally numeric order. This should still be true, but officially, we no longer guarantee any order of results. Args: *args (tuple): Positional arguments to pass to :p...
JohnyEngine/CNC
heekscnc/nc/nc.py
Python
apache-2.0
20,018
0.014987
################################################################################ # nc.py # # Base class for NC code creation # And global functions for calling current creator # # Hirutso Enni, 2009-01-13 # altered by Dan Falck 2010-08-04 # added tap() arguments Michael Haberler 2010-10-07 #############################...
coordinates(self): """Set machine coordinates""" pass ####################
######################################################## ## Cutter radius compensation def use_CRC(self): """CRC""" return False ############################################################################ ## Cycles def pattern(self): """Simple pattern eg. ci...
snakeleon/YouCompleteMe-x86
third_party/ycmd/third_party/requests/setup.py
Python
gpl-3.0
2,080
0
#!/usr/bin/env python import os import re import sys from codecs import open try: from setuptools import setup except ImportError: from distutils.core import setup if sys.argv[-1] == 'publish': os.system('python setup.py sdist upload') sys.exit() packages = [ 'requests', 'requests.packages'...
__.py', 'r') as fd: version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1) if not version: raise RuntimeError('Cannot find version information') with open('README.rst', 'r', 'utf-8') as f: readme = f.read() with open('HISTORY.rst', 'r', 'ut...
history, author='Kenneth Reitz', author_email='me@kennethreitz.com', url='http://python-requests.org', packages=packages, package_data={'': ['LICENSE', 'NOTICE'], 'requests': ['*.pem']}, package_dir={'requests': 'requests'}, include_package_data=True, install_requires=requires, lice...
Quintin-Z/rt-thread
bsp/lpc824/rtconfig.py
Python
gpl-2.0
3,324
0.006017
import os # toolchains options ARCH='arm' CPU='cortex-m0' CROSS_TOOL='keil' if os.getenv('RTT_CC'): CROSS_TOOL = os.getenv('RTT_CC') # cross_tool provides the cross compiler # EXEC_PATH is the compiler execute path, for example, CodeSourcery, Keil MDK, IAR if CROSS_TOOL == 'gcc': print '================ERROR==...
_PATH = os.getenv('RTT_EXEC_PATH') #BUILD = 'debug' BUILD = 'release' if PLATFORM == 'gcc': # toolchains PREFIX = 'arm-none-eabi-' CC = PREFIX + 'gcc' AS = PREFIX + 'gcc' AR = PREFIX + 'ar' LINK = PREFIX + 'gcc' TARGET_EXT = 'axf' SIZE = PREFI
X + 'size' OBJDUMP = PREFIX + 'objdump' OBJCPY = PREFIX + 'objcopy' DEVICE = ' -mcpu=cortex-m0 -mthumb -ffunction-sections -fdata-sections' CFLAGS = DEVICE AFLAGS = ' -c' + DEVICE + ' -x assembler-with-cpp' LFLAGS = DEVICE + ' -Wl,--gc-sections,-Map=rtthread-lpc824.map,-cref,-u,Reset_Handler -T...
valdergallo/raidmanager
player/migrations/0002_auto_20160403_1645.py
Python
mit
2,163
0.003236
# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-04-03 16:45 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('player', '0001_initial'), ] operations = [ ...
migrations.DeleteModel( name='Faction', ), migrations.DeleteModel( name='Game', ), migrations.DeleteModel( name='Server', ), migrations.De
leteModel( name='SpecType', ), migrations.AddField( model_name='playerfeedback', name='owner', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='owner', to='player.Player'), ), migrations.AddField( ...
ignatenkobrain/dnf
tests/test_base.py
Python
gpl-2.0
9,603
0.001666
# Copyright (C) 2012-2013 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) any later version. # This program is distributed in the hope that it will...
mdb = support.MockYumDB() pkg, = base.sack.query().installed().filter(name='pepper') base.yumdb.get_package(pkg).get = {'reason': 'user', 'from_repo': 'anakonda'}.get iterator = base.iter_userinstalled() self.assertRaises(StopIteration, next, iterator) def test_iter_us
erinstalled_badreason(self): """Test iter_userinstalled with a package installed for a wrong reason.""" base = dnf.Base() base._sack = support.mock_sack('main') base._yumdb = support.MockYumDB() pkg, = base.sack.query().installed().filter(name='pepper') base.yumdb.get_pa...
ArcherSys/ArcherSys
skulpt/src/lib/getopt.py
Python
mit
69
0
raise
NotImplementedError("getopt is not yet impl
emented in Skulpt")
showa-yojyo/bin
twmods/commands/geo.py
Python
mit
4,854
0.001648
"""geo.py: Implementation of class AbstractTwitterGeoCommand and its subclasses. """ from argparse import ArgumentParser from . import (AbstractTwitterCommand, call_decorator) from ..parsers import (filter_args, cache) # GET geo/id/:place_id # POST geo/place DEPRECATED # GET geo/reverse_geocode # GET geo/search GEO...
elf.args), 'lat', 'long', 'accuracy', 'granularity', 'max_results', 'query', 'ip', 'contained_within', 'street_address') return kwargs, self.twhandler.geo.search def make_commands(manager):
"""Prototype""" # pylint: disable=no-member return (cmd_t(manager) for cmd_t in AbstractTwitterGeoCommand.__subclasses__()) CHOICES = ('poi', 'neighborhood', 'city', 'admin', 'country') @cache def parser_geo_common(): """Return the parser for common arguments.""" parser = ArgumentPa...
aristanetworks/arista-ovs-quantum
quantum/plugins/cisco/tests/unit/v2/ucs/test_ucs_inventory_v2.py
Python
apache-2.0
4,700
0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 Cisco Systems, Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache....
ntory, cmd)([]) self.assertEqual(results[const.DEVICE_IP], self.inventory.keys()) LOG.de
bug("test_%s - END", cmd) def _test_with_port_creation(self, cmd, params=None): """Tests commands that requires a port to exist""" LOG.debug("test_%s - START", cmd) net_uuid = uuidutils.generate_uuid() device_params = self._ucs_inventory.create_port(tenant, net_uuid, ...
itkvideo/ITK
Utilities/Maintenance/FindRedundantHeaderIncludes.py
Python
apache-2.0
6,011
0.024455
#!/usr/bin/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...
ing {0} from {1}".format(line,self.filePathBaseDirs[filename]+"/"+filename)) else: outfile.write(line) ff.close() outfile.close() os.rename(self.filePathBaseDirs[filename]+"/"+filename+"_cleaned
",self.filePathBaseDirs[filename]+"/"+filename) def proc_children(self,node,dupcandidate,starting_child): ## Pocess all children isdone=donenode.get((starting_child,dupcandidate),None) if isdone != None: #print "found {0} {1}".format(starting_child,dupcandidate) return F...
ironman5366/W.I.L.L
will.py
Python
mit
3,781
0.002116
# External imports from flask import Flask from flask_socketio import SocketIO import dataset # Builtin imports import logging import sys try: import Queue except ImportError: import queue as Queue import os import json from logging.handlers import RotatingFileHandler import datetime import atexit import signa...
se: ch.setLevel(logging.INFO) handler = RotatingFileHandler(logfile, maxBytes=10000000, backupCount=5) handler.setLevel(logging.DEBUG) self.app.logger.addHandler(handler) global log log = self.app.logger
self.socketio = SocketIO(app) web.socketio = self.socketio self.socketio.on(web.disconnect_session, 'disconnect') self.socketio.on(web.get_updates, "get_updates") signal.signal(signal.SIGTERM, self.dump_events) self.start() self.socketio.run( app, host=...
MapofLife/MOL
earthengine/google-api-python-client/samples/searchforshopping/fulltextsearch.py
Python
bsd-3-clause
1,222
0.005728
#!/usr/bin/python2.4 # -*- coding: utf-8 -*- # # Copyright 2010 Google Inc. All Rights Reserved. """Full text search query against the shopping search API""" import pprint from apiclient.discovery import build SHOPPING_API_VERSION = 'v1' DEVELOPER_KEY = 'AIzaSyACZJW4JwcWwz5taR2gjIMNQrtgDLfILPc' def main(): """...
operator can be used to search for alternative search terms, for example: q = 'banana|apple' will search for bana
nas or apples. Search phrases such as those containing spaces can be specified by surrounding them with double quotes, for example q='"mp3 player"'. This can be useful when combining with the "|" operator such as q = '"mp3 player"|ipod'. """ client = build('shopping', SHOPPING_API_VERSION, developerKey=DEV...
jonparrott/gcloud-python
dlp/google/cloud/dlp_v2/gapic/dlp_service_client_config.py
Python
apache-2.0
7,062
0
config = { "interfaces": { "google.privacy.dlp.v2.DlpService": { "retry_codes": { "idempotent": ["DEADLINE_EXCEEDED", "UNAVAILABLE"], "non_idempotent": [] }, "retry_params": { "default": { "initial_retry_...
"retry_codes_name": "non_idempotent", "retry_params_name": "default" }, "UpdateDeidentifyTemplate": { "timeout_millis": 300000, "retry_codes_name": "non_idempotent", "retry_params_name": "default" ...
"timeout_millis": 300000, "retry_codes_name": "idempotent", "retry_params_name": "default" }, "ListDeidentifyTemplates": { "timeout_millis": 300000, "retry_codes_name": "idempotent", ...
tinloaf/home-assistant
homeassistant/components/media_player/mpd.py
Python
apache-2.0
10,700
0
""" Support to interact with a Music Player Daemon. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/media_player.mpd/ """ from datetime import timedelta import logging import os import voluptuous as vol from homeassistant.components.media_player import ...
tus['state'] == 'stop': return STATE_OFF return
STATE_OFF @property def is_volume_muted(self): """Boolean if volume is currently muted.""" return self._muted @property def media_content_id(self): """Return the content ID of current playing media.""" return self._currentsong.get('file') @property def media_co...
jerivas/mezzanine
mezzanine/forms/admin.py
Python
bsd-2-clause
7,520
0.000665
from copy import deepcopy from csv import writer from datetime import datetime from io import BytesIO, StringIO from mimetypes import guess_type from os.path import join from django.conf.urls import url from django.contrib import admin from django.contrib.messages import info from django.core.files.storage import File...
me].widget.attrs["class"] = css_class class Meta: model = Field exclude = inline_field_excludes class FieldAdmin(TabularDynamicInlineAdmin): """ Admin class for the form field. Inherits from TabularDynamicInlineAdmin to add dynamic "Add another" link and drag/drop ordering. """ ...
""" Admin class for the Form model. Includes the urls & views for exporting form entries as CSV and downloading files uploaded via the forms app. """ class Media: css = {"all": (static("mezzanine/css/admin/form.css"),)} inlines = (FieldAdmin,) list_display = ( "title", ...
vmthunder/virtman
virtman/utils/__init__.py
Python
apache-2.0
23
0
__author__ = 'xin
cafe'
OpenPOWER-BigData/HDP-falcon
src/bin/prism_stop.py
Python
apache-2.0
848
0
# # 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 # limitat...
under the License. See accompanying LICENSE file. # import os import sys import falcon_config as fc import subprocess cmd = sys.argv[0] prg, base_dir = fc.resolve_sym_link(os.path.abspath(cmd)) service_stop_cmd = os.path.join(base_dir, 'bin', 'service_stop.py') subprocess.call(['python', service_stop_cmd, 'prism'])
Nitrate/Nitrate
src/tcms/xmlrpc/api/testrun.py
Python
gpl-2.0
23,617
0.000593
# -*- coding: utf-8 -*- import logging from operator import methodcaller from typing import List from django.core.exceptions import ObjectDoesNotExist from kobo.django.xmlrpc.decorators import user_passes_test from tcms.issuetracker.models import Issue from tcms.management.models import TCMSEnvValue, TestTag from tc...
un.add_cases('1, 2', '10, 20') """ trs = TestRun.objects.filter(run_id__in=pre_process_ids(run_ids)) tcs = TestCase.objects.filter(case_id__in=pre_process_ids(case_ids)) for tr in trs.iterator(): for tc in tcs.iterator(): tr.add_case_run(case=tc) @log_call(namespace=__xmlrpc_names...
r("has_perm", "testruns.delete_testcaserun")) def remove_cases(request, run_ids, case_ids): """Remove one or more cases from the selected test runs. :param run_ids: give one or more run IDs. It could be an integer, a string containing comma separated IDs, or a list of int each of them is a run ...
okfn/jsontableschema-py
tableschema/schema.py
Python
mit
10,197
0.000392
# -*- coding: utf-8 -*- from __future__ import division from __future__ import print_function from __future__ import absolute_import from __future__ import unicode_literals import io import six import json from copy import deepcopy from .profile import Profile from .field import Field from . import exceptions from . i...
https://github.com/frictionlessda
ta/tableschema-py#schema """ return [field.name for field in self.fields] def get_field(self, name): """https://github.com/frictionlessdata/tableschema-py#schema """ for field in self.fields: if field.name == name: return field return None...
stormi/tsunami
src/secondaires/navigation/equipage/volontes/relacher_rames.py
Python
bsd-3-clause
3,392
0.000592
# -*-coding:Utf-8 -* # Copyright (c) 2013 LE GOFF Vincent # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # lis...
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """Fichier contenant la volonté RelacherRames""" import re from secondaires.navigation.equipage.ordres.relacher_rames import \ Rela
cherRames as OrdreRelacherRames from secondaires.navigation.equipage.ordres.long_deplacer import LongDeplacer from secondaires.navigation.equipage.volonte import Volonte class RelacherRames(Volonte): """Classe représentant une volonté. Cette volonté demande à ceux qui tiennent les rames de les lâcher. "...
amishb/youtube-dl
youtube_dl/extractor/eagleplatform.py
Python
unlicense
3,435
0.001758
# coding: utf-8 from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import ( ExtractorError, int_or_none, ) class EaglePlatformIE(InfoExtractor): _VALID_URL = r'''(?x) (?: eagleplatform:(?P<custom_host>[^/]+):| ...
'thumbnail': 're:^https?://.*\.jpg$', 'duration': 87, 'view_count': int, 'age_limit': 0, }, }, { # http://muz-tv.ru/play/7129/ # http://media.clipyou.ru/index/player?record_id=12820&width=730&height=415&autoplay=true 'url': 'eagleplatform:...
'md5': '6c2ebeab03b739597ce8d86339d5a905', 'info_dict': { 'id': '12820', 'ext': 'mp4', 'title': "'O Sole Mio", 'thumbnail': 're:^https?://.*\.jpg$', 'duration': 216, 'view_count': int, }, }] def _handle_error(self, resp...
Jolopy/GimpHub
runPeriodic.py
Python
gpl-2.0
1,892
0.008457
import threading from .app.crawl import getArticle, rucrawler import pymongo INTERVAL_SECONDS = 30*60 MONGO_HOST = '52.54.134.145' MONGO_PORT = 27017 MONGO_DATABASE = 'mizzychan' def get_db(): connection = pymongo.MongoClient(MONGO_HOST, MONGO_PORT) database = getattr(connection, MONGO_DATABASE) return co...
#articles += rucrawler.getBusiness() #articles += rucrawler.getEntertainment() articles = rucrawler.getMemes() #articles
+= rucrawler.getSports() #articles += rucrawler.getTech() #articles += rucrawler.getUSNews() #articles += rucrawler.getWorldNews() conn, db = get_db() for article in articles: try: if 'title' not in article or not article['title'] or article['title'].isspace(): ar...
brainwane/zulip
zerver/management/commands/create_large_indexes.py
Python
apache-2.0
3,096
0.002261
from typing import Any from django.db import connection from zerver.lib.management import ZulipBaseCommand def create_indexes() -> None: # Creating concurrent indexes is kind of a pain with current versions # of Django/postgres, because you will get this error with seemingly # reasonable code: # ...
.") cursor.execute(''' CREATE INDEX IF NOT EXISTS zerver_usermessage_active_mobile_push_notification_id ON zerver_usermessage (user_profile_id, message_id) WHERE (flags & 4096) != 0; ''') print("Finished.") class Command(ZulipBaseComma
nd): help = """Create concurrent indexes for large tables.""" def handle(self, *args: Any, **options: str) -> None: create_indexes()
Kegbot/kegbot-server
pykeg/contrib/twitter/plugin.py
Python
gpl-2.0
12,130
0.002308
"""Twitter plugin for Kegbot.""" from pykeg.plugin import plugin from pykeg.plugin import util from pykeg.core.models import KegbotSite from pykeg.core.util import SuppressTaskErrors from . import forms from . import tasks from . import views from .client import TwitterClient from unicodedata import normalize KEY_...
.update_status(contents) d
ef truncate_tweet(tweet, max_len=TWEET_MAX_LEN, truncate_str=TRUNCATE_STR): if len(tweet) <= max_len: return tweet words = tweet.strip().split() while True: tweet = " ".join(words) candidate = normalize("NFC", tweet + truncate_str) if not tweet or len(candidate) <= max_len: ...
citrix-openstack-build/oslo.cache
oslo_cache/exception.py
Python
apache-2.0
770
0
# Copyright 2012 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License
at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to 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 gover...
configured correctly.""" class QueueEmpty(Exception): """Raised when a connection cannot be acquired."""
kushG/osf.io
scripts/osfstorage/files_audit.py
Python
apache-2.0
4,698
0.002341
#!/usr/bin/env python # encoding: utf-8 """Verify that all OSF Storage files have Glacier backups and parity files, creating any missing backups. TODO: Add check against Glacier inventory Note: Must have par2 installed to run """ import os import logging impo
rt pyrax from boto.glacier.layer2 import Layer2 from pyrax.exceptions import NoSuchObject from modularodm import Q from website.app im
port init_app from website.addons.osfstorage import model from scripts import utils as scripts_utils from scripts.osfstorage import utils as storage_utils from scripts.osfstorage import settings as storage_settings container_primary = None container_parity = None vault = None logger = logging.getLogger(__name__) lo...
BRiAl/BRiAl
sage-brial/brial/intersect.py
Python
gpl-2.0
1,354
0.003693
# # intersect.py # PolyBoRi # # Created by Michael Brickenstein on 2008-09-24. # Copyright 2008 The PolyBoRi Team # from .gbcore import groebner_basis from .statistics import used_vars_set from itertools import chain def intersect(i, j, **gb_opts): """ This functions intersects two ideals. The first ring...
used_vars_set(j) t = next(iter(i)).ring().variable(0) if uv.reducible_by(t): raise ValueError("First ring variable has to be reserved as helper variable t") if not t > uv: raise ValueError("need elimination ordering for first ring variable") gb = groebner_basis(list(chain((t * p for p i...
if __name__ == "__main__": _test()
xbmc/atv2
xbmc/lib/libPython/Python/Lib/test/test_pyclbr.py
Python
gpl-2.0
7,102
0.003098
''' Test cases for pyclbr.py Nick Mathewson ''' from test.test_support import run_unittest import unittest, sys from types import ClassType, FunctionType, MethodType, BuiltinFunctionType import pyclbr from unittest import TestCase StaticMethodType = type(staticmethod(lambda: None)) ClassMethodType = type(classme...
ngest modules cm('random', ignore=('Random',)) # from _random import Random as CoreGenerator cm('cgi', ignore=('log',)) # set with = in module cm('mhlib') cm('urllib', ignore=('getproxies_registry', 'open_https', 'getproxies...
'dump',)) # from sre_constants import * cm('pdb') cm('pydoc') # Tests for modules inside packages cm('email.Parser') cm('test.test_pyclbr') def test_main(): run_unittest(PyclbrTest) if __name__ == "__main__": test_main()
aababilov/python-marconiclient
marconiclient/common/apiclient/auth/response.py
Python
apache-2.0
6,051
0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 Nebula, Inc. # Copyright 2013 Alessio Ababilov # Copyright 2013 Grid Dynamics # Copyright 2013 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in complia...
Unless required by applic
able 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. import logging fr...
L-yCoyote/web-quest
site/text_data.py
Python
mit
9,734
0.029709
place_time = { "1" : "United Kingdom, London, MI6 / fri 28 august, 3:50 a.m.", "2" : "London, agent Harry's House / fri 28 august, 3:55 a.m.", "3" : "Ireland, Dublin, agent Patrick's House / fri 28 august, 9:45 a.m.", "4" : "Ireland, Dublin, agent Patrick's House / fri 28 august, 11:30 a.m.", "5" : "Ireland, Dubli...
з собственного дома в Дублине был похищен агент Патрик.", "1_2": "был похищен агент Патрик.", "2"
: "ДОПОЛНИТЕЛЬНО: В настоящий момент агенты Чарльз и Колин находятся на задании в Северной Америки, агент Шарлотта погибла при исполнение долга год назад. Остальные агенты в данный момент не задействованы в операциях MI6. Ожидайте в ближайший час дополнительную информацию о местоположении перечисленных агентов." } mi...
mcs07/mongodb-chemistry
mchem/postgres.py
Python
mit
6,525
0.003831
# -*- coding: utf-8 -*- """ mchem.postgres ~~~~~~~~~~~~~~ Functions to build and benchmark PostgreSQL database for comparison. :copyright: Copyright 2014 by Matt Swain. :license: MIT, see LICENSE file for more details. """ from __future__ import print_function from __future__ import unicode_literals from __future__ ...
()[0] #cur.execute("select m from rdk.mols where molregno = %s", (molregno,)) #smiles = cur.fetcho
ne()[0] cur.execute("select %s from rdk.fps where molregno = %s", (AsIs(fp), molregno,)) qfp = cur.fetchone()[0] log.debug(mol_id) start = time.time() cur.execute("select molregno from rdk.fps where %s%%%s", (AsIs(fp), qfp,)) #cur.execute("select molregno from rdk.fps whe...
googleapis/python-dialogflow
samples/generated_samples/dialogflow_v2_generated_conversation_profiles_update_conversation_profile_async.py
Python
apache-2.0
1,721
0.001743
# -*- 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...
# Initialize request argument(s) conversation_profile = dialogflow_v2.ConversationProfile() conversation_profile.display_name = "display_name_value" request = dialogflow_v2.UpdateConversationProfileRequest( conversation_profile=conversation_profile, ) # Make the request response = awa...
e the response print(response) # [END dialogflow_v2_generated_ConversationProfiles_UpdateConversationProfile_async]
smacleod/reviewboard-persona
reviewboard_persona/admin_urls.py
Python
mit
190
0.005263
from djan
go.conf.urls.defaults import patterns, url from reviewboard_persona.extension import RBPersona urlpatterns = patterns('reviewboard_persona.views',
url(r'^$', 'configure'), )
roghu/py3_projects
tests/Numbers/test_credit_card_validator.py
Python
mit
1,051
0
import pytest from src.Numbers.credit_card_validator import CardValidator, CardError class TestCreditCard: def test_valiator_success(self): card = CardValidator(4556821195558787) assert card.__str__() == "************8787" assert card.__repr__() == "<Credit Card: ************8787>" d...
st.raises(CardError) as ex: CardValidator(4000) assert "'Card is invalid.'" in str(ex.value) def test_luhn_number_failure(self): with p
ytest.raises(CardError) as ex: CardValidator(4123456789012345) assert "'Card is invalid.'" in str(ex.value) def test_number_prefix_failure(self): with pytest.raises(CardError) as ex: CardValidator(1000000000000000) assert "'Card is invalid.'" in str(ex.value)
ljschumacher/tierpsy-tracker
tierpsy/helper/params/read_attrs.py
Python
mit
7,845
0.008413
import tables import numpy as np import json import os def single_db_microns_per_pixel(file_name): #this is used in the single worm case, but it would be deprecated. I want to use this argument when I read the data from original additional files with tables.File(file_name, 'r') as fid: microns_per_pixe...
ase reader = AttrReader(fname) ventral_side = reader.ventral_side print(ventral_side) return ventral_side def read_fps(fname, dflt=1): assert isinstance(fname, str) reader = AttrReader(fname, dflt) return reader.fps def read_microns_per_pixel(fname, dflt=1): reader = AttrReader(fna...
reader = AttrReader(fname, dflt) fps_out = reader.get_fps() microns_per_pixel_out = reader.get_microns_per_pixel() is_light_background = reader._read_attr('is_light_background', 1) print(fps_out, microns_per_pixel_out, is_light_background) return fps_out, microns_per_pixel_out, is_light...
wavefrontHQ/python-client
test/test_alert_source.py
Python
apache-2.0
1,258
0
# coding: utf-8 """ Wavefront REST API <p>The Wavefront REST API enables you to interact with Wavefront servers using standard REST API tools. You can use the REST API to automate commonly executed operations such as automaticall
y tagging sources.</p><p>When you make REST API calls outside the Wavefront REST API documentation
you must add the header \"Authorization: Bearer &lt;&lt;API-TOKEN&gt;&gt;\" to your HTTP requests.</p> # noqa: E501 OpenAPI spec version: v2 Contact: chitimba@wavefront.com Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import unittest impor...
srgblnch/LinacDS
LinacAttrs/LinacFeatures/__init__.py
Python
gpl-3.0
1,254
0
# ##### 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 3 # of the License, or (at your option) any later version. # # This program is distrib...
CHANTABILITY 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 this program; If not, see <http://www.gnu.org/licenses/>. # # ##### END GPL LICENSE BLOCK ##### from .buffers import CircularBu...
mport Events, EventCtr from .feature import _LinacFeature from .formulas import Formula from .interlockreset import InterlockReset from .memorised import Memorised from .qualities import QualityInterpreter from .toofarcondition import TooFarCondition __author__ = "Lothar Krause and Sergi Blanch-Torne" __maintainer__ =...
couchbase/cbagent
cbagent/collectors/ps.py
Python
apache-2.0
1,640
0.00061
from cbagent.collectors.libstats.psstats import PSStats from cbagent.collectors import Collector class PS(Collector): COLLECTOR = "atop" # Legacy KNOWN_PROCESSES = ("beam.smp", "memcached", "indexer", "projector", "cbq-engine", "sync_gateway") def __init__(self, settings): ...
for node in self.nodes: self.mc.add
_server(node) def sample(self): for process in self.KNOWN_PROCESSES: for node, stats in self.ps.get_samples(process).items(): if stats: self.update_metric_metadata(stats.keys(), server=node) self.store.append(stats, ...
ChantyTaguan/zds-site
zds/notification/management/commands/uniquify_subscriptions.py
Python
gpl-3.0
1,008
0.000992
from django.core.management import BaseCommand from django.db.models import Count from zds.notification.models import Subscription class Command(BaseCommand): help = "Delete all but la
st duplicate subscriptions" def handle(self, *args, **options): self.stdout.write("Start
ing uniquifying subscriptions") count = 0 # Find all duplicates duplicates = ( Subscription.objects.values("user", "content_type", "object_id") .annotate(Count("id")) .filter(id__count__gt=1) ) for sub in duplicates: del sub["id__c...
frankjdelgado/wiki-history-extractor
query_handler/query_handler.py
Python
mit
8,093
0.021253
from db_connector import RevisionDB import datetime class QueryHandler(object): data={} #function which get the quantity of revisions #tested @classmethod def filter_by_user(self,values): #values is a list composed by 1 value, the user name to filter by data={'user':values[0]} ...
until the date. # If the integer is 1: It will return the revisions made from the date until the last revision. # the strptime convert the stri
ng arguments into datetime datatype if len(values) == 1: date_i=datetime.datetime.strptime(values[0],date_format) #it is used 2 dates to extract the revision for the whole day, from 0:0 to 23:59 date_f=date_i.replace(hour=23,minute=59,second=59) data={'timestamp':...
codedsk/hubcheck
hubcheck/pageobjects/po_generic_page.py
Python
mit
3,505
0.00913
from hubcheck.pageobjects.basepageobject import BasePageObject from hubcheck.pageobjects.basepageelement import Link from selenium.common.exceptions import NoSuchElementException class GenericPage(BasePageObject): """Generic Page with just a header and footer""" def __init__(
self,browser,catalog): super(GenericPage,self).__init__(browser,catalog) self.path = '/' # load hub's classes GenericPage_Locators = self.load_class('GenericPage_Locators') NeedHelpForm = self.load_class('NeedHelpForm') Header = self.load_class('Header') Footer =...
rs # setup page object's components self.needhelpform = NeedHelpForm(self,{},self.__refreshCaptchaCB) self.needhelplink = Link(self,{'base':'needhelplink'}) self.header = Header(self) # self.footer = Footer(self) def __refreshCaptchaCB(self): self._bro...
huligagn/hello
generate_dataset.py
Python
apache-2.0
1,785
0.02409
import os import shutil import yaml from time import ctime import cv2 print ctime() datasetPath = '/home/huligang/data/myVoc/' dataset_new = 'dataset/' if os.path.exists(dataset_new): shutil.rmtree(dataset_new) os.system('mkdir ' + dataset_new) Annotations = datasetPath + 'Annotations/' JPEGImages = datasetPath + '...
]) xmax = int(obj['bndbox']['xmax']) ymax = int(obj['bndbox']['ymax']) assert(xmin < xmax) assert(ymin < ymax) if not os.path.exists(dataset_new + obj['name']): os.system('mkdir ' + dataset_new + obj['name']) cv2.imwrite(dataset_new + obj['name'] + '/' + str(count) + '.jpg', ...
j['bndbox']['xmin']) ymin = int(obj['bndbox']['ymin']) xmax = int(obj['bndbox']['xmax']) ymax = int(obj['bndbox']['ymax']) assert(xmin < xmax) assert(ymin < ymax) if not os.path.exists(dataset_new + obj['name']): os.system('mkdir ' + dataset_new + obj['name']) cv2.imwrite(dataset_new ...
fos/fos-legacy
scratch/very_scratch/old_core/picking_test.py
Python
bsd-3-clause
4,325
0.028902
#!/usr/bin/python import sys import numpy as np try: import OpenGL.GL as gl import OpenGL.GLUT as glut import OpenGL.GLU as glu except ImportError: ImportError('PyOpenGL is not installed') import mouse # objects SELECT_BUFFER_SIZE=100 def drawLines(mode): pass def drawRects(m...
glut init glut.glutInit(sys.argv) glut.glutInitDisplayMode (glut.GLUT_DOUBLE | glut.GLUT_RGB) glut.glutInitWindowSize (w, h) glut.glutInitWindowPosition (px, py) glut.glutCreateWindow (title) def init(color=(0.,0.,0.)): #add objects #origin() gl.glClearColor (color[0], color[1], ...
y,year,zdist if key == chr(27): sys.exit(0) if key == 'a': glut.glutIdleFunc(spin) if key == 'p' or key == 'P': # picking viewport=gl.glGetIntegerv(gl.GL_VIEWPORT) #print viewport w=viewport[2]-viewport[0] h=viewport[3]-viewp...
yabirgb/maths-books
p_scrap/merger.py
Python
mit
245
0.004082
import
json read_files = ["data_" + str(x) + ".json" for x in range(700)] with open("libros.json", "w") as outfile: dic = {} for f in read_files: dic.upda
te( json.loads(open(f, "r",).read())) outfile.write(json.dumps(dic))
purduerov/X9-Core
rov/camera/camera.py
Python
mit
2,803
0.002141
import os import signal import subprocess class Camera(object): # In order to run mjpg-streamer through Python, make sure # mjpg-streamer-experimental is installed so the .so objects # and mjpg-streamer are all on defualt PATH so we don't have # to specify path (was getting a lot of errors resulting ...
utput = 'output_http.so -p {port} {web}'.format( port=self.port, web='-w /usr/local/www' ) self.status = "killed" # framerate shouldn't be changed: keep at 30, allows for a good image while # reserving valuable processing power for other devices. Device is formatted as ...
here you want to output image # to: change as needed # open video feed for an instance of Camera def start(self): self.process = subprocess.Popen(['mjpg_streamer', '-i', self.input, '-o', self.output]) if self.is_alive(): self.status = 'active' # closes video feed for an i...
litui/openparliament
parliament/committees/migrations/0001_initial.py
Python
agpl-3.0
5,619
0.002492
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migrat
ion): dependencies = [ ('hansards', '0001_initia
l'), ('core', '0001_initial'), ] operations = [ migrations.CreateModel( name='Committee', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name_en', models.TextField()), ...
mbayon/TFG-MachineLearning
venv/lib/python3.6/site-packages/numpy/core/tests/test_records.py
Python
mit
15,635
0.002239
from __future__ import division, absolute_import, print_function import sys import collections import pickle import warnings from os import path import numpy as np from numpy.testing import ( TestCase, run_module_suite, assert_, assert_equal, assert_array_equal, assert_array_almost_equal, assert_raises, asser...
qual(type(arr2), type(arr)) def test_recarray_repr(self): # make sure non-structured dtypes also show up as rec.array a = np.array(np.ones(4, dtype='f8')) assert_(repr(np.rec.array(a)).startswith('rec.array')) # check that the 'np.record' part of the dtype isn't shown a = n...
ert_equal(repr(a).find('numpy.record'), -1) a = np.rec.array(np.ones(3, dtype='i4'))