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 |
|---|---|---|---|---|---|---|---|---|
GenericStudent/home-assistant | homeassistant/helpers/storage.py | Python | apache-2.0 | 8,036 | 0.000747 | """Helper to help store data."""
import asyncio
from json import JSONEncoder
import logging
import os
from typing import Any, Callable, Dict, List, Optional, Type, Union
from homeassistant.const import EVENT_HOMEASSISTANT_FINAL_WRITE
from homeassistant.core import CALLBACK_TYPE, CoreState, HomeAssistant, callback
from... | a is not None:
data = self._data
# If we didn't generate data yet, do it now.
if "data_func" in data:
data["data"] = data.pop("data_func")()
else:
data = await self.hass.async_add_executor_job(
json_util.load_json, self.path
... | if data["version"] == self.version:
stored = data["data"]
else:
_LOGGER.info(
"Migrating %s storage from %s to %s",
self.key,
data["version"],
self.version,
)
stored = await self._async_migrate_fun... |
rahulgayatri23/moose-core | python/libmumbl/nml_parser/MorphML.py | Python | gpl-3.0 | 32,632 | 0.006466 | """
Description: class MorphML for loading MorphML from file or xml element into
MOOSE.
NeuroML.py is the preferred interface. Use this only if NeuroML L1,L2,L3 files
are misnamed/scattered. Instantiate MorphML class, and thence use methods:
readMorphMLFromFile(...) to load a standalone MorphML from file OR
readMorp... | None
proximal = segment.find('./{'+self.m | ml+'}proximal')
if proximal is None:
# If proximal tag is not present, then parent attribute MUST be
# present in the segment tag! if proximal is not present, then
# by default the distal end of the parent is the proximal end
# of the child
... |
laurentb/weboob | modules/wordreference/pages.py | Python | lgpl-3.0 | 1,432 | 0 | # -*- coding: utf-8 -*-
# Copyright(C) 2012 Lucien Loiseau
#
# This file is part of a weboob module.
#
# This weboob module 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... | eful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this weboob module. If not, see <http://ww... |
from weboob.browser.pages import HTMLPage
from weboob.browser.elements import ItemElement, ListElement, method
from weboob.capabilities.translate import Translation
from weboob.browser.filters.standard import CleanText, Regexp, Env
class TranslatePage(HTMLPage):
@method
class get_translation(ListElement):
... |
iLoop2/ResInsight | ThirdParty/Ert/devel/python/python/ert/enkf/data/enkf_node.py | Python | gpl-3.0 | 3,730 | 0.006702 | # Copyright (C) 2012 Statoil ASA, Norway.
#
# The file 'enkf_node.py' is part of ERT - Ensemble based Reservoir Tool.
#
# ERT 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... | name(), node_id.iens, node_id.report_step))
def save(self, fs, node_id):
assert isinstance(fs, EnkfFs)
assert isinstance(node_id, NodeId)
EnkfNode.cNamespace().store(self, fs, True, node_id)
def free(self):
EnkfNode.cNamespace().free(self)
cwrapper = CWrapper(ENKF_LI... | = cwrapper.prototype("void enkf_node_free(enkf_node)")
EnkfNode.cNamespace().alloc = cwrapper.prototype("c_void_p enkf_node_alloc(enkf_node)")
EnkfNode.cNamespace().alloc_private = cwrapper.prototype("c_void_p enkf_node_alloc_private_container(enkf_node)")
EnkfNode.cNamespace().get_name = cwrapper.prototype("char* enkf... |
ifwe/wxpy | src/tests/test_notaskbar.py | Python | mit | 289 | 0.017301 | import wx
from testutil import main
def test_notaskbar():
f = lambda: wx.Frame(None, -1, style=wx.DEFAULT_FRAME_STYLE | wx.FRAME_NO_TASKBAR)
frames = [f() for x in x | range(10)]
for frame in frames:
frame.Destroy()
if __name__ == '__main__':
main(t | est_notaskbar) |
w1ll1am23/home-assistant | tests/components/waze_travel_time/test_config_flow.py | Python | apache-2.0 | 6,588 | 0.000152 | """Test the Waze Travel Time config flow."""
from homeassistant import config_entries, data_entry_flow
from homeassistant.components.waze_travel_time.const import (
CONF_AVOID_FERRIES,
CONF_AVOID_SUBSCRIPTION_ROADS,
CONF_AVOID_TOLL_ROADS,
CONF_DESTINATION,
CONF_EXCL_FILTER,
CONF_INCL_FILTER,
... | ,
CONF_AVOID_SUBSCRIPTION_ROADS: True,
CONF_AVOID_TOLL_ROADS: True,
CONF_EXCL_FILTER: "exclude",
CONF_INCL_FILTER: "include",
CONF_REALTIME: False,
CONF_UNITS: CONF_UNIT_SYSTEM_IMPERIAL,
CONF_VEHICLE_TYPE: "taxi",
},
)
a... | rue,
CONF_AVOID_SUBSCRIPTION_ROADS: True,
CONF_AVOID_TOLL_ROADS: True,
CONF_EXCL_FILTER: "exclude",
CONF_INCL_FILTER: "include",
CONF_REALTIME: False,
CONF_UNITS: CONF_UNIT_SYSTEM_IMPERIAL,
CONF_VEHICLE_TYPE: "taxi",
}
assert entry.options == {
CO... |
SarahBA/b2share | demo/b2share_demo/migration_cli.py | Python | gpl-2.0 | 15,061 | 0.00239 | # -*- coding: utf-8 -*-
#
# This file is part of EUDAT B2Share.
# Copyright (C) 2017 CERN, SurfsSara
#
# B2Share 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 o... | current_app.config['JSONSCHEMAS_HOST'],
current_app.config.get('APPLICATION_ROOT') or '', '', ''
))
for d in dirlist:
try:
process_v1_record(d, indexer, base_url, logfile)
except:
logfile.write("\n********************")
logfile.write("\nERROR: except... | ___\n"
.format(d))
logfile.write(traceback.format_exc())
logfile.write("\n********************")
logfile.close()
@migrate.command()
@with_appcontext
@click.option('-u', '--update', is_flag=True, default=False)
@click.argument('base_url')
def check_pids(update, ba... |
CiscoSystems/vespa | neutron/plugins/nec/agent/nec_neutron_agent.py | Python | apache-2.0 | 8,945 | 0.000112 | #!/usr/bin/env python
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2012 NEC Corporation.
# Based on ryu/openvswitch agents.
#
# Copyright 2012 Isaku Yamahata <yamahata at private email ne jp>
# Copyright 2011 Nicira Networks, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0... | :param integ_br: name of the integration bridge.
:param root_helper: utility to use when running shell cmds.
:param po | lling_interval: interval (secs) to check the bridge.
'''
self.int_br = ovs_lib.OVSBridge(integ_br, root_helper)
self.polling_interval = polling_interval
self.cur_ports = []
self.need_sync = True
self.datapath_id = "0x%s" % self.int_br.get_datapath_id()
self.agen... |
Soya93/Extract-Refactoring | python/helpers/py3only/docutils/languages/pt_br.py | Python | apache-2.0 | 1,948 | 0.001027 | # $Id: pt_br.py 5567 2008-06-03 01:11:03Z goodger $
# Author: David Goodger <goodger@python.org>
# Copyright: This module has been placed in the public domain.
# New language mappings are welcome. Before doing a new | translation, please
# read <http://docutils.sf.net/docs/howto/i18n.html>. Two files must be
# translated for each language: one in docutils/languages, the other in
# docutils/parsers/rst/languages.
"""
Brazilian Portuguese-language mappings for language-dependent features of Docutils.
"""
__docformat__ = 'reStructur... | # fixed: language-dependent
'author': 'Autor',
'authors': 'Autores',
'organization': 'Organiza\u00E7\u00E3o',
'address': 'Endere\u00E7o',
'contact': 'Contato',
'version': 'Vers\u00E3o',
'revision': 'Revis\u00E3o',
'status': 'Estado',
'date': 'Data',
'copyr... |
adviti/melange | thirdparty/google_appengine/google/storage/speckle/python/tool/google_sql.py | Python | apache-2.0 | 6,404 | 0.008588 | #!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | ives.
port: The TCP port to use when connecting. (UNUSED)
user: The user to use when connecting.
password: The password to use when connectin | g.
database: A DatabaseConfig instance containing the instance id and
database name.
Returns:
The DB API Connection object.
"""
dbi = self.get_import()
return dbi.connect(
host, database.instance, database=database.name, user=user,
password=password)
class Google... |
nakagami/reportlab | src/reportlab/lib/formatters.py | Python | bsd-3-clause | 3,887 | 0.019038 | #!/bin/env python
#Copyright ReportLab Europe Ltd. 2000-2012
#see license.txt for license details
#history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/lib/formatters.py
__all__=('Formatter','DecimalFormatter')
__version__=''' $Id: formatters.py 3959 2012-09-27 14:39:39Z robin $ '''
_... | es:
strInt, strFrac = strInt.split('.')
strFrac = sep + strFrac
if strip:
while strFrac and st | rFrac[-1] in ['0',sep]: strFrac = strFrac[:-1]
else:
strFrac = ''
if self.comma is not None:
strNew = ''
while strInt:
left, right = strInt[0:-3], strInt[-3:]
if left == '':
#strNew = self.comma + right + strNew
... |
1flow/1flow | oneflow/core/migrations/0098_auto__add_field_baseaccount_options.py | Python | agpl-3.0 | 54,756 | 0.007816 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as 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 'BaseAccount.options'
db.add_column(u'core_baseaccount', '... | k': 'True'}),
'content_type': ('django.db.models.fields.IntegerField', [], {'db_index': 'True', 'null': 'True', 'blank': 'True'}),
'excerpt': ('django.db.models.fiel | ds.TextField', [], {'null': 'True', 'blank': 'True'}),
'image_url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}),
'is_orphaned': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'publishers': ('django.db.models.fi... |
jiadaizhao/LeetCode | 1301-1400/1315-Sum of Nodes with Even-Valued Grandparent/1315-Sum of Nodes with Even-Valued Grandparent.py | Python | mit | 565 | 0.00531 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def sumEvenGrandparent(self, root: TreeNode) -> int:
total = 0
def dfs(root, p, gp): |
if root is None:
return
nonlocal total
if gp and (gp.val & 1) == 0:
total += root.val
dfs(root.left, root, p)
dfs(ro | ot.right, root, p)
dfs(root, None, None)
return total
|
bdmod/extreme-subversion | BinarySourcce/subversion-1.6.17/subversion/tests/cmdline/svntest/actions.py | Python | gpl-2.0 | 93,569 | 0.014043 | #
# actions.py: routines that actually run the svn client.
#
# Subversion is a tool for revision control.
# See http://subversion.tigris.org for more information.
#
# ====================================================================
# Copyright (c) 2000-2009 CollabNet. All rights reserved.
#
# This software is ... | ts at PATH, containing
nothing but the greek-tree at revision 1."""
if path == main.pristine_dir:
print("ERROR: attempt to overwrite the pristine repos! Aborting.")
sys.exit(1)
# copy the pristine repository to PATH.
main.safe_rmtree(path)
if main.copy_repos(main.pristine_dir, path, 1):
print(... | od_tree(path, 0666, 0666)
def run_and_verify_svnlook(message, expected_stdout,
expected_stderr, *varargs):
"""Like run_and_verify_svnlook2, but the expected exit code is
assumed to be 0 if no output is expected on stderr, and 1 otherwise."""
expected_exit = 0
if expected_stderr is ... |
BlogomaticProject/Blogomatic | opt/blog-o-matic/usr/lib/python/Bio/Clustalw/__init__.py | Python | gpl-2.0 | 21,060 | 0.004653 | # This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
"""Code for calling ClustalW and parsing its output (DEPRECATED).
This module has been superseded by the Bio.AlignIO framework for
alignment parsing, a... | lignment
o MultipleAlignCL"""
import Bio
import warnings
warnings.warn("Bio.Clustalw is deprecated. Please use the Bio.AlignIO framework for alignment parsing, and the ClustalW command line wrapper i | n Bio.Align.Applications for calling the tool. These are both described in the current version of the Biopython Tutorial and Cookbook.", Bio.BiopythonDeprecationWarning)
# standard library
import os
import sys
import subprocess
# biopython
from Bio import Alphabet
from Bio.Alphabet import IUPAC
from Bio.Align.Generic... |
jroivas/klapi | klapi-backend.py | Python | mit | 6,207 | 0.002578 | #!flask/bin/python
import zmq
import sys
import threading
import json
import settings
import utils
import os
from db import db
from images import images
from infra import infra
class KlapiServer(threading.Thread):
def __init__(self, sets):
threading.Thread.__init__(self)
self.port = 5555
s... | backend.recv_multipart()
server.send_multipart(data)
def run(self):
(context, server, backend) = self._init_connection()
workers = self.launch_workers(context)
self.serve(server, backend)
self._deinit_connection(context, server, backend)
for worker in self... | workers:
worker.join()
class KlapiWorker(threading.Thread):
def __init__(self, context, backend_name):
threading.Thread.__init__ (self)
self.context = context
self.backend_name = backend_name
self.running = False
def run(self):
worker = self.context.socket(z... |
xunxunzgq/open-hackathon-bak_01 | open-hackathon-server/src/hackathon/docker/hosted_docker.py | Python | mit | 24,562 | 0.003461 | # -*- coding: utf-8 -*-
#
# -----------------------------------------------------------------------------------
# Copyright (c) Microsoft Open Technologies (Shanghai) Co. Ltd. All rights reserved.
#
# The MIT License (MIT)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this softw... | name=container_name,
host_server_id=host_server.id,
vir | tual_environment=virtual_environment,
image=unit.get_image_with_tag())
self.db.add_object(container)
self.db.commit()
# port binding
ps = map(lambda p:
[p.port_from, p.port_to],
self.__assign_ports(experiment, host_se... |
ministryofjustice/cla_backend | cla_backend/apps/legalaid/admin_support/forms.py | Python | mit | 601 | 0.001664 | from django import forms
import markdown
from core.admin.fields import MarkdownAdminField
from ..models import Category
class CategoryModelForm(forms.ModelForm):
"" | "
Saves the field description as html version of the raw_description field.
"""
raw_description = MarkdownAdminField(label=u"Description", required=False)
class Meta(object):
model = Category
exclude = []
def save(self, *args, **kwargs):
self.instance.description = markdow... | |
mynlp/ccg2lambda | scripts/run_tests.py | Python | apache-2.0 | 3,569 | 0.007565 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# Copyright 2015 Pascual Martinez-Gomez
#
# 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
#
... | GetPremisesThatMatchConclusionArgsTestCase
from abduction_tools_test import GetTreePredArgsTestCase
from category_test import CategoryTestCase
from ccg2lambda_tools_test import AssignSemanticsToCCGTestCase
from ccg2lambda_tools_test | import AssignSemanticsToCCGWithFeatsTestCase
from ccg2lambda_tools_test import get_attributes_from_ccg_node_recursivelyTestCase
from ccg2lambda_tools_test import TypeRaiseTestCase
from knowledge_test import LexicalRelationsTestCase
from nltk2coq_test import Nltk2coqTestCase
from semantic_index_test import GetSemanticR... |
tridge/MAVProxy | MAVProxy/modules/mavproxy_map/__init__.py | Python | gpl-3.0 | 39,321 | 0.006078 | #!/usr/bin/env python
'''
map display module
Andrew Tridgell
June 2012
'''
import sys, os, math
import functools
import time
from MAVProxy.modules.mavproxy_map import mp_elevation
from MAVProxy.modules.lib import mp_util
from MAVProxy.modules.lib import mp_settings
from MAVProxy.modules.lib import mp_module
from MAVPr... | up, combine=True))
def show_position(self):
'''show map position click information'''
pos = self.mpstate.click_location
dms = (mp_util.degrees_to_dms(pos[0]) | , mp_util.degrees_to_dms(pos[1]))
msg = "Coordinates in WGS84\n"
msg += "Decimal: %.6f %.6f\n" % (pos[0], pos[1])
msg += "DMS: %s %s\n" % (dms[0], dms[1])
msg += "Grid: %s\n" % mp_util.latlon_to_grid(pos)
if self.logdir:
logf = open(os.path.join(self.logdir, "... |
newville/microprobe_docs | doc/macros/xrd.py | Python | bsd-2-clause | 7,656 | 0.003396 | """
Commands for X-ray Diffraction
Note that an XRD camera must be installed!
"""
def setup_epics_shutter(prefix='13MARCCD4:'):
"""
Setup Epics shutter for CCD camera
open /close pv = 13IDA:m70.VAL (SSA H WID)
open val = 0.080, close val = -0.020
"""
caput(prefix+'cam1:ShutterOpenEPICS.... | k()-t0 < timeout)):
sleep(0.25)
#endwhile
fname = caget(prefix+'cam1:FullFileName_RBV', as_string=True)
print('Acquire Done! %.3f sec' % (systime()-start_time))
print('Wrote %s' % fn | ame)
sleep(1.0)
caput(prefix+'cam1:ShutterControl', 1)
#enddef
def xrd_at(posname, t):
move_samplestage(posname, wait=True)
save_xrd(posname, t=t, ext=1)
#enddef
def xrd_bgr_marccd(prefix='13MARCCD4:', timeout=120.0):
"""
collect XRD Background for marccd
Parameters:
prefix (st... |
crs4/ProMort | promort/odin/views/reviewers_report.py | Python | mit | 9,771 | 0.00348 | # Copyright (c) 2019, CRS4
#
# 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, merge, publish, distribu... | views_status(self, reviewer):
roi_annotations = ROIsAnnotation.objects.filter(reviewer=reviewer)
clinical_annotations = ClinicalAnnotation.objects.filter(reviewer=rev | iewer)
return {
'roi_annotations': self._get_infos(roi_annotations),
'clinical_annotations': self._get_infos(clinical_annotations)
}
def _get_reviewers_by_group(self, group_name):
logger.info('Loading users for group %s', group_name)
group = Group.objects.get... |
onoga/wm | src/gnue/forms/GFObjects/GFTree.py | Python | gpl-2.0 | 25,780 | 0.03173 | #
# This file is part of GNU Enterprise.
#
# GNU Enterprise 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, or (at your option) any later version.
#
# GNU Enterprise is distributed in the h... | 'POST-FOCUSIN' : 'Post-FocusIn',
'ON-NEXT-ENTRY' : 'On-Next-Entry',
'ON-PREVIOUS-ENTRY': 'On-Previous-Entry',
'RECORD-ACTIVATED' : 'Record-Activated',
'RECORD-CHECKED' : 'Record-Checked',
'POST-REFRESH' : 'Post-Refresh',
}
self._triggerFunctions = {
'getBlock': {'funct... | lf.__trigger_getCheckedNodesData},
#'isVirtualRootChecked': {'function': self.__trigger_isVirtualRootChecked},
'getChildNodesData' : {'function': self.__trigger_getChildNodesData},
'setChildNodesData' : {'function': self.__trigger_setChildNodesData},
'checkAllNodes' : {'function': self.__trigger_chec... |
alekLukanen/pyDist | pyDist/comms/Logging.py | Python | mit | 516 | 0.003876 |
import logging
import sys
logging.getLogger("aiohttp").setLevel(logging.WARNING)
logging.getLogger("asyncio").setLevel(logging.WARNING)
l | ogging.getLogger("urllib3.connectionpool").setLevel(logging. | WARNING)
class Log(object):
def __init__(self, name):
self.name = name
logging.basicConfig(format='%(name)-12s:%(lineno)-3s | %(levelname)-8s | %(message)s'
, stream=sys.stdout, level=logging.DEBUG)
self.logger = logging.getLogger(self.name)
|
googleads/google-ads-python | google/ads/googleads/v8/services/services/extension_feed_item_service/client.py | Python | apache-2.0 | 25,315 | 0.001067 | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | hat is, the first one
# in the dictionary).
return next(iter(cls._transport_registry.values()))
class ExtensionFeedItemServiceClient(
metaclass=ExtensionFeedItemServiceClientMeta
):
"""Service to manage extension feed items."""
@staticmethod
def _get_default_mtls_endpoint(api_endpoint... | to mTLS endpoint.
Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to
"*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively.
Args:
api_endpoint (Optional[str]): the api endpoint to convert.
Returns:
str: converted mTLS api endpoint.
... |
plotly/python-api | packages/python/plotly/plotly/validators/choroplethmapbox/colorbar/_showticksuffix.py | Python | mit | 603 | 0.001658 | import _plotly_u | tils.basevalidators
class ShowticksuffixValidator(_plotly_utils.basevalidators.EnumeratedValidator):
def __init__(
self,
plotly_name="showticksuffix",
parent_name="choroplethmapbox.colorbar",
**kwargs
):
super(ShowticksuffixValidator, self).__init__(
plotly_... | edit_type=kwargs.pop("edit_type", "colorbars"),
role=kwargs.pop("role", "style"),
values=kwargs.pop("values", ["all", "first", "last", "none"]),
**kwargs
)
|
the-archer/ai-project | TrafficModel/main.py | Python | gpl-2.0 | 1,779 | 0.060146 | from roads import Roads
import csv
import qlearningAgents
def main(TimeToSimulate,TStep):
wrtFile1= open("road1.csv",'w')
wrtFile2= open("road2.csv",'w')
#specsFile1 = open("road1_specs.csv",'rb')
#specsFile2 = open("road2_specs.csv",'rb')
roads = Roads([[wrtFile1,TStep,500,"road1_specs.csv","Red"... | e))
print ("Penalty = " + str(penalty))
a.update(oldstate, action, newstate, penalty, ((itr)>=NumIterations*0.9))
action = a.getAction(newstate, algo = 1) |
print ("Action = " + str(action))
oldstate = newstate
penalty=0
timeToCallQL = action[1]
timetoCallQLorig=timeToCallQL
roads.updateSignals(action[0])
Time = itr*TStep
roads.UpdateRoads(Time)
penalty += (roads.getTotalDelay()*TStep/1000000)/timetoCallQLorig
#roads.Signa... |
jboro333/django_practice | django_practice/idjango_practice/migrations/0008_merge_20170616_1742.py | Python | gpl-3.0 | 357 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-06-16 17:42
from __future__ import unic | ode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('idjango_practice', '0005_merge_20170616_1612'),
('idjango_practice', '0007_auto_20 | 170616_1630'),
]
operations = [
]
|
LevinJ/Pedestrian-detection-and-tracking | src/doppia/tools/stixels_evaluation/stixels_evaluation.py | Python | apache-2.0 | 63,385 | 0.014089 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Main script for the stixel world evaluation.
"""
from __future__ import print_function
import sys
sys.path.append("..")
sys.path.append("../data_sequence")
sys.path.append("../helpers")
from stixels_pb2 import Stixels, Stixel
from data_sequence import DataSequence
... | detection_boxes.remove(detection_box)
#print("Match found")
break
else:
# no match
continue
#print(len(ground_truth_boxes), "unmatched ground_truth_boxes", ground_truth_boxes)
#print(len(detection_boxes), "unmatched de... | s
false_positives = len(detection_boxes)
false_negatives = len(ground_truth_boxes)
return false_positives, false_negatives
def recordings_stixels_data_sequences_generator(recordings):
stixel_data_dict = dict()
while True:
for name, value in recordi... |
joshuamckenty/yolo-octo-wookie | nova/endpoint/rackspace.py | Python | apache-2.0 | 7,526 | 0.000399 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compli... | inst['user_id'],
| inst['project_id'],
'default' # security group
)['bridge_name']
# key_data, key_name, ami_launch_index
# TODO(todd): key data or root password
inst.save()
return inst
def schedule_launch_of_instance(sel... |
oyam/pytorch-DPNs | dpn.py | Python | mit | 5,042 | 0.011503 | import torch
import torch.nn as nn
import torch.nn.functional as F
from collections import OrderedDict
__all__ = ['DPN', 'dpn92', 'dpn98', 'dpn131', 'dpn107', 'dpns']
def dpn92(num_classes=1000):
return DPN(num_init_features=64, k_R=96, G=32, k_sec=(3,4,20,3), inc_sec=(16,32,24,128), num_classes=num_classes)
d... | def dpn107(num_classes=1000):
return DPN(num_init_features=128, k_R=200, G=50, k_sec=(4,8,20,3), inc_sec=(20,64,64,128 | ), num_classes=num_classes)
dpns = {
'dpn92': dpn92,
'dpn98': dpn98,
'dpn107': dpn107,
'dpn131': dpn131,
}
class DualPathBlock(nn.Module):
def __init__(self, in_chs, num_1x1_a, num_3x3_b, num_1x1_c, inc, G, _type='normal'):
super(DualPathBlock, self).__init__()
self.num_1x1_c = n... |
mindcube/mindcube-django-cookiecutter | {{cookiecutter.repo_name}}/project/settings/local.py | Python | mit | 1,714 | 0.000583 | # -*- coding: utf-8 -*-
'''
Local settings
- Run in Debug mode
- Use console backend for emails
- Add Django Debug Toolbar
- Add django-extensions as app
'''
from .base import * # noqa
# DEBUG
# ------------------------------------------------------------------------------
DEBUG = env.bool('DJANGO_DEBUG', default=T... | t and testing.
SECRET_KEY = env("DJANGO_SECRET_KEY", default='CHANGEME!!!)z+y04z27*hk*i+m88pg2s5#_r0&@#8xq$q_*gh!2evub0)3)2')
# CACHING
# ---------------------------------------------- | --------------------------------
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'LOCATION': ''
}
}
# django-debug-toolbar
# ------------------------------------------------------------------------------
MIDDLEWARE_CLASSES += ('debug_toolbar.middleware.DebugT... |
deniszh/carbon | lib/carbon/tests/test_database.py | Python | apache-2.0 | 6,229 | 0.000963 | import os
from unittest import TestCase
from mock import patch
from os.path import exists
import shutil
from carbon.tests.util import TestSettings
from carbon.database import WhisperDatabase, CeresDatabase
class WhisperDatabaseTest(TestCase):
def setUp(self):
self._sep_patch = patch.object(os.path, 'sep... | sertEqual(
result,
'/tmp/_tagged/872/252/' + # nosec
'872252dcead671982862f82a3b440f02aa8f525dd6d0f2921de0dc2b3e874ad0')
result = database.exists(metric)
self.assertEqual(result, False)
def test_migrateTaggedFilesystemPathHashed(self):
metric = 'stats.e... | settings = TestSettings()
settings['LOCAL_DATA_DIR'] = '/tmp/'
settings['TAG_HASH_FILENAMES'] = False
database = CeresDatabase(settings)
result = database.exists(metric)
self.assertEqual(result, False)
old_path = database.getFilesystemPath(metric)
self.as... |
oberlin/pressgang | pressgang/actions/options/site/__init__.py | Python | bsd-3-clause | 2,352 | 0.023384 |
from django.template.loader import render_to_string
from django.utils.importlib import import_module
from pressgang.actions.options import Option, Options
from pressgan | g.utils.registry import create_registry
SiteOptionRegistry = create_registry('id')
class SiteOption(Option):
"""Base class for a single site option."""
__metaclass__ = SiteOptionRegistry
# The databse ID used by WordPress for the site option
wp_id = None
# A custom template to use to set the option, relative ... | one
# Whether the option is only available on multisite installations
multisite_only = False
def generate_code(self, blog, value):
"""Add code for a plugin to apply the WordPress option.
Arguments:
blog -- an instance of a Blog object
value -- the value of the option as a Python data type
"""
# If t... |
hectormartinez/rougexstem | taln2016/icsisumm-primary-sys34_v1/nltk/nltk-0.9.2/nltk/stem/api.py | Python | apache-2.0 | 715 | 0.002797 | # Natural Language Toolkit: Stemmer Interface
#
# Copyright (C) 2001-2008 University of Pennsylvania
# Auth | or: Trevor Cohn <tacohn@cs.mu.oz.au>
# | Edward Loper <edloper@gradient.cis.upenn.edu>
# Steven Bird <sb@csse.unimelb.edu.au>
# URL: <http://nltk.sf.net>
# For license information, see LICENSE.TXT
class StemmerI(object):
"""
A processing interface for removing morphological affixes from
words. This process is known as X{stemming}.
... |
jacekfh/PerfectHash | __init__.py | Python | unlicense | 63 | 0 | from PerfectH | ash import PerfectHash
__all__ = ['Perfe | ctHash']
|
HuaweiSNC/OpsDev | src/plugins/com.huawei.networkos.ops.python/templet/python/OpsDeviceManager.py | Python | apache-2.0 | 1,654 | 0.012092 | """
config of ops service, Control by OPS devices
@author: opsdev
"""
import httplib
import json
from OpsServiceConfig import OPS_SERVICE_CONFIG
class OpsDeviceManager():
def __init__(self,config):
self.server = config["server"]
self.port = config["port"]
self.addAction = "POST"
... | lf):
return self.restcall("/devices", "", self.getAction)
def restcal | l(self, opspath, data, action):
conn = httplib.HTTPConnection(self.server, self.port)
body = json.dumps(data)
if action == self.addAction:
conn.request(action, opspath, body)
elif action == self.getAction:
conn.request(action, opspath)
elif action == self.... |
nvoss12838/gpsFIT | plotFit.py | Python | mit | 111 | 0.027027 | import numpy as np
#python . | ./../ | ../../Modeling/modelData.py ../../../Costa_Rica.p bon2 ../bon2.fun
print 'a' |
anhstudios/swganh | data/scripts/templates/object/building/player/shared_player_city_bank_corellia_style_01.py | Python | mit | 446 | 0.049327 | #### NOTICE: THIS | FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Building()
result.template = "object/building/player/shared_player_city_bank_corellia_style_01.iff"
result.attribute_template_id = ... | sult |
theflorianmaas/dh | Python/dhproc/p_serial.py | Python | mit | 15,394 | 0.033714 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Ver 18 - 15 November 2017 -
import time
import serial
import string
import sys
import mysql.connector
from mysql.connector import errorcode, pooling
from db import *
import datetime
#from threading import Thread
import multiprocessing as mp
from multiprocessing import Queue... | umbers of parameters to build the string to send to the coordinator
# count the number of nodes
sql = "select count(*) as CNT from vwnodes WHERE nodetype != 0" #exclude external node
cur.execute(sql)
for (CNT) in cur:
nodeNum=parseint("{}".format(CNT))
INString = INString + str(nodeNum*pnum)
sql = "select c... | type = 2" #xbee nodes
cur.execute(sql)
for (CNT) in cur:
nodeNum=parseint("{}".format(CNT))
IXString = IXString + str(nodeNum)
# retrieve node data and buid initialization strings
sql = "select id, xbee_high_address, xbee_low_address, nodetype from vwnodes WHERE nodetype != 0 AND status = 1 order by id"
cur.e... |
harshilasu/LinkurApp | y/google-cloud-sdk/lib/googlecloudapis/compute/v1/compute_v1_messages.py | Python | gpl-3.0 | 211,698 | 0.007232 | """Generated message classes for compute version v1.
API for the Google Compute Engine service.
"""
from protorpc import messages
from googlecloudapis.apitools.base.py import encoding
package = 'compute'
class AccessConfig(messages.Message):
"""An access configuration attached to an instance's network interfac... | """A AddressesScopedList object.
Messages:
WarningValue: Informational warning which replaces the list of addresses
when the list is empty.
Fields:
addresses: List of addresses contained in this scope.
warning: Informational warning which replaces the list of addresses when
the list is e... | is empty.
Enums:
CodeValueValuesEnum: The warning type identifier for this warning.
Messages:
DataValueListEntry: A DataValueListEntry object.
Fields:
code: The warning type identifier for this warning.
data: Metadata for this warning in 'key: value' format.
message: Option... |
scollis/iris | lib/iris/analysis/calculus.py | Python | gpl-3.0 | 25,484 | 0.003453 | # (C) British Crown Copyright 2010 - 2014, Met Office
#
# This file is part of Iris.
#
# Iris is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation, either version 3 of the License, or
# (at your option) any l... | ons.CoordinateMultiDimError(coord)
circular = getattr(coord, 'circular', False)
if coord.shape == (1,) and not circular:
raise ValueError('Cannot take interval diffe | rences of a single valued coordinate.')
if circular:
circular_kwd = coord.units.modulus or True
else:
circular_kwd = False
if coord.bounds is not None:
bounds = iris.util.delta(coord.bounds, 0, circular=circular_kwd)
else:
bounds = None
points = iris.util.delta(coo... |
AnshulYADAV007/Lean | Algorithm.Python/VolumeWeightedAveragePriceExecutionModelRegressionAlgorithm.py | Python | apache-2.0 | 3,155 | 0.010149 | # QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the Lice... | ionAlgorithm(QCAlgorithmFramework):
'''Regression algorithm f | or the VolumeWeightedAveragePriceExecutionModel.
This algorithm shows how the execution model works to split up orders and
submit them only when the price is on the favorable side of the intraday VWAP.'''
def Initialize(self):
self.UniverseSettings.Resolution = Resolution.Minute
self.SetS... |
cmotc/Byzantium | captive_portal/captive_portal_test.py | Python | gpl-3.0 | 844 | 0.004739 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: set expandtab tabstop=4 shiftwidth=4 :
# Project Byzantium: http://wiki.hacdc.org/index.php/Byzantium
# Copyright (C) 2013 Project Byzantium
# This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as... | s207.github.com/flexmock
import unittest
import captive_portal
class CaptivePortalDetectorTest(unittest.TestCase):
def setUp(self):
self.detector = captive_por | tal.CaptivePortalDetector()
def test_index(self):
self.assertEqual("You shouldn't be seeing this, either.", self.detector.index())
if __name__ == '__main__':
unittest.main()
|
jelly/calibre | src/calibre/ebooks/metadata/rtf.py | Python | gpl-3.0 | 7,633 | 0.002751 | __license__ = 'GPL v3'
__copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>'
"""
Edit metadata in RTF files.
"""
import re, cStringIO, codecs
from calibre import force_unicode
from calibre.ebooks.metadata import MetaInformation, string_to_authors
title_pat = re.compile(r'\{\\info.*?\{\\title(.*?)(?<!\\)... | ategory', tags)
publisher = options.publisher
if publisher is not None:
publisher = encode(publisher)
pat = re.compile(base_pat.replace('name', 'manager'), re.DOTALL)
if pat.search(src):
src = pat.sub(r'{\\manager ' + publisher + r'}', src)
... | stream.truncate()
stream.write(src)
stream.write(after)
|
lez/stupidgit | stupidgit_gui/run.py | Python | mit | 492 | 0.006098 | #!/usr/bin/env python
# -*- coding: utf-8
import sys
import os
import os.path
import wx
from git import Repository
from MainWindow import *
de | f main():
# Parse arguments
repodir = sys.argv[1] if len(sys.argv) > 1 else os.getcwd()
# Show main window
try:
repo = Repository(repodir)
except GitError:
repo = None
app = wx.PySimpleApp()
win | = MainWindow(None, -1, repo)
win.Show(True)
app.MainLoop()
if __name__ == '__main__':
main()
|
gannetson/sportschooldeopenlucht | apps/statistics/migrations/0001_initial.py | Python | bsd-3-clause | 1,566 | 0.003831 | # -*- 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 model 'Statistic'
db.create_table(u'statistics_statistic', (
(u'id', self.gf('django.db... | rue'}),
'lives_changed': ( | 'django.db.models.fields.IntegerField', [], {}),
'projects': ('django.db.models.fields.IntegerField', [], {})
}
}
complete_apps = ['statistics'] |
simongibbons/numpy | numpy/core/tests/test_multiarray.py | Python | bsd-3-clause | 339,352 | 0.000949 | import collections.abc
import tempfile
import sys
import warnings
import operator
import io
import itertools
import functools
import ctypes
import os
import gc
import weakref
import pytest
from contextlib import contextmanager
from numpy.compat import pickle
import pathlib
import builtins
from decimal import Decimal
... | S4')] )
values = np.core.records.fromstring(data, types)
vals = values['vals']
assert_raises(ValueError, vals.setflags, writ | e=True)
def test_writeable_from_buffer(self):
data = bytearray(b'\x00' * 100)
vals = np.frombuffer(data, 'B')
assert_(vals.flags.writeable)
vals.setflags(write=False)
assert_(vals.flags.writeable is False)
vals.setflags(write=True)
assert_(vals.flags.writeabl... |
merlimat/pulsar | docker/pulsar/scripts/apply-config-from-env.py | Python | apache-2.0 | 2,339 | 0.00342 | #!/usr/bin/env python
#
# 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
# "Licens | e"); 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 WARRANTI... |
spencerkclark/aospy-obj-lib | aospy_user/runs/cases.py | Python | gpl-3.0 | 6,191 | 0 | from aospy import Run
am2_control = Run(
name='am2_control',
description=(
'Preindustrial control simulation.'
),
data_in_direc=('/archive/Yi.Ming/sm2.1_fixed/'
'SM2.1U_Control-1860_lm2_aie_rerun6.YIM/pp'),
data_in_dur=5,
data_in_start_date='0001-01-01',
data_in_e... | data_in_start_date='0001-01-01',
data_in_end_date='0080-12-31',
default_date_range=('0021-01-01', '0080-12-31'),
idealized=False
)
am2_extratropics = Run(
name='am2_extratropics',
descripti | on=(
'Anthropogenic sulfate aerosol forcing only in the'
' Northern Hemisphere extratropics (30N to Pole)'
),
data_in_direc=('/archive/Yi.Ming/sm2.1_fixed/'
'SM2.1U_Control-1860_lm2_aie2_extropical_rerun6.YIM/pp'),
data_in_dur=5,
data_in_start_date='0001-01-01',
da... |
dfm/ketu | ketu/k2/__init__.py | Python | mit | 345 | 0 | # -*- coding: utf-8 -*-
__all__ = ["photometry", "epic", "Data", "Inject", "Likelihood", "Summary",
"FP", "fit_traptransit"]
from . import photometry, epic
from .data import Data
from .inject impo | rt Inject
from .likelihood import Likelihood
from .summary import Su | mmary
from .fp import FP
from .traptransit import fit_traptransit
|
anodos-ru/catalog | updaters/axoft.py | Python | mit | 9,080 | 0.007759 | import catalog.runner
from catalog.models import *
class Runner(catalog.runner.Runner):
name = 'Axoft'
alias = 'axoft'
url = {'start': 'http://axoft.ru/',
'login': 'http://axoft.ru/',
'vendors': 'http://axoft.ru/vendors/',
'prefix': 'http://axoft.ru'}
word =... | (vendor_url)
# Добавляем в список ссылок на прайс-листы соответсвующие
for url in tree.xpath('//a/@href'):
if self.word['price'] in url:
if not self.url['prefix'] in url:
url = '{}{}'.format(self.url['prefix'], u... | prices.add(price)
return prices
def parse(self, data, vendor):
import xlrd
# Номера строк и столбцов
num = {
'header_line' : 3,
'first_line' : 5}
# Распознаваемые слова
word = {'party_article': 'AxoftSKU',
'product_ar... |
mhe/pynrrd | nrrd/errors.py | Python | mit | 74 | 0 | cla | ss NRRDError(Exception):
"""Exceptions for N | RRD class."""
pass
|
portableant/open-context-py | opencontext_py/apps/ocitems/obsmetadata/models.py | Python | gpl-3.0 | 628 | 0.001592 | from django.db import models
# Stores metadata about observation nodes to further annotate bundles o | f asserions
# an observation bundles assertions
class ObsMetadata(models.Model):
source_id = models.CharField(max_length=200, db_index=True)
project_uuid = models.CharField(max_length=50, db_index=True)
obs_num = models.IntegerField()
label = models.CharField(max_length=200)
obs_type = models.CharFi... | te = models.TextField()
class Meta:
db_table = 'oc_obsmetadata'
unique_together = (('source_id', 'obs_num'),)
|
alexliyu/CDMSYSTEM | firewall.py | Python | mit | 1,273 | 0.003273 | #!/usr/bin/python
# -*- coding:utf-8 -*-
"""
主程序入口
@author:alex
@date:15-2-13
@time:上午11:44
@contact:alexliyu2012@gmail.com
"""
__author__ = 'alex'
import sys
import os
import ConfigParser
import uuid
from subprocess import Popen, PIPE
from utils.heartbeat import HeartBeatManager
from ut | ils.tools import *
PROJECT_PATH = os.path.abspath(os.path.dirname(__file__))
def init(ini_file=None):
cf = ConfigParser.ConfigParser()
try:
if ini_file:
cf.read(ini_file)
else:
cf.read(os.path.join(PROJECT_PATH, "config.ini"))
redis_host = cf.get("REDIS", "IP"... | r_host = cf.get("LISTENING", "IP")
listener_port = cf.getint("LISTENING", "PORT")
except Exception, e:
print e
sys.exit(1)
print_info("REDIS端口 %s:%d" % (redis_host, redis_port))
print_info("监听心跳包端口 %s:%d" % (listener_host, listener_port))
print_info("开始运行白名单服务........")
se... |
pwnieexpress/pwn_plug_sources | src/voiper/sulley/impacket/dcerpc/transport.py | Python | gpl-3.0 | 11,565 | 0.009771 | # Copyright (c) 2003-2006 CORE Security Technologies
#
# This software is provided under under a slightly modified version
# of the Apache Software License. See the accompanying LICENSE file
# for more information.
#
# $Id: transport.py,v 1.5 2006/05/23 21:19:26 gera Exp $
#
# Description:
# Transport implementations... | rpc, dcerpc_v4
class DCERPCStringBinding:
parser = re.compile(r'(?:([a-fA-F0-9-]{8}(?:-[a-fA-F0-9-]{4}){3}-[a-fA- | F0-9-]{12})@)?' # UUID (opt.)
+'([_a-zA-Z0-9]*):' # Protocol Sequence
+'([^\[]*)' # Network Address (opt.)
+'(?:\[([^\]]*)\])?') # Endpoint and options (opt.)
def __init__(self, stringbinding):
match = DCERPCStringBinding.parser.match(... |
toby82/anvil | tools/endpoint-service-replace.py | Python | apache-2.0 | 3,065 | 0.003915 | #!/usr/bin/env python
from optparse import OptionParser
import getpass
import os
import sys
import yaml
possible_topdir = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]),
os.pardir,
os.pardir))
if os.path.exists(os.path.join(possible_t... | s', []),
'endpoints': contents.get('endpoints', []),
}
print("Regenerating with:")
print(utils.prettify_yaml(set_contents))
set_contents['users'] = []
set_contents['roles'] = []
set_contents['tenants'] = []
initer = keystone.Initializer( | token, options.keystone_uri)
initer.initialize(**set_contents)
def main():
parser = OptionParser()
parser.add_option("-k", '--keystone', dest='keystone_uri',
help='keystone endpoint uri to authenticate with', metavar='KEYSTONE')
parser.add_option("-f", '--file', dest='file',
... |
plotly/plotly.py | packages/python/plotly/plotly/validators/scatter3d/legendgrouptitle/font/_family.py | Python | mit | 554 | 0 | import _plotly_utils.basevalida | tors
class FamilyValidator(_plotly_utils.basevalidators.StringValidator):
def __init__(
self,
plotly_name="family",
parent_name="scatter3d.legendgrouptitl | e.font",
**kwargs
):
super(FamilyValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "style"),
no_blank=kwargs.pop("no_blank", True),
strict=kwargs.pop("strict", True),
... |
xi-studio/anime | music/train.py | Python | mit | 6,297 | 0.007146 | from __future__ import print_function
import argparse
import os
import random
import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
import torch.optim as optim
import torchvision.datasets as dset
import torchvision.transforms as transforms
import torchvision.utils as vutils
from torch.autograd import ... | 0]))
print('Time: %.4f' % (time.time() - nowtime | ))
########## Visualize #########
if(epoch % 1 == 0):
f_B = fake_B.cpu().data.numpy()
for n,pic in enumerate(f_B[0]):
misc.imsave('%s/%d_%d.png' % (opt.outf,epoch,n),pic)
if(epoch % 10 == 0):
print('save model:',epoch)
torch.save(netG.state_dict(), '%s/netG.pth' ... |
yisonPylkita/blace | Applications/Music_Player/getLibrary.py | Python | mit | 157 | 0.006369 | #!/usr/bin/ipy | thon
library_file = open('/srv/http/.config/cmus/lib.pl');
tracks = library_file.readlines()
for x in tracks:
print('<li>' + x + '</li>') | |
getpelican-plugins/pelican-flickr | pelican-flickr/models.py | Python | gpl-3.0 | 4,630 | 0.013823 | # codinf=utf-8
from pelican.utils import slugify
from .cached import FlickrCached
import main
import logging
logger = logging.getLogger(__name__)
class FlickrPhotoset(FlickrCached):
'''
Represents & Cache a Flickr Photoset
'''
primary = None
photos = []
def __init__(self, xml=None, id=None):
if xml i... | e))
def __unicode__(self):
return u"Flickr Photo %s '%s'" % (self.id, 'infos' in self.data and self.data['infos']['title'] or '-')
def __getattr__(self, name):
return self.__getitem__(name)
def __getitem__(self, name):
if name in self.data.get('infos', {}):
return self.data['infos'][name]
... | f.api.photos_getInfo(photo_id=self.id)
xml = xml.find('photo')
out = xml.attrib
out['title'] = xml.find('title').text
out['description'] = xml.find('description').text
out['dates'] = xml.find('dates').attrib
# Load urls
out['urls'] = {}
for url_xml in xml.find('urls').findall('url'):
... |
froststars/aws-cfn-templates | components/S3/LBLogBucketTemplate.py | Python | mit | 2,376 | 0 | # -*- encoding: utf-8 -*-
__author__ = 'kotaimen'
__date__ = '22/12/2016'
from troposphere import Retain, AWS_REGION, AWS_ACCOUNT_ID, AWS_NO_VALUE
from troposphere impor | t Parameter, Sub, Export, Equals, Not, Join, Condition
from troposphere import Template, Ref, Output, FindInMap, If, GetAtt
import troposphere.s3 as s3
import cfnutil
#
# Template
#
t = Template()
t.add_version()
t.add_description(
'Loadbalancer log bucket'
)
#
# Parameters
#
param_bucket_name = t.add_parameter... | # Condition
#
t.add_condition(
'HasBucketName',
Not(Equals(Ref(param_bucket_name), ''))
)
t.add_condition(
'ChinaRegionCondition',
Equals(Ref(AWS_REGION), 'cn-north-1')
)
#
# Mapping
#
t.add_mapping(
'ElbAccountId',
cfnutil.load_csv_as_mapping('mapping/elb-account-id.csv',
... |
danylaksono/inasafe | safe_qgis/impact_statistics/function_options_dialog.py | Python | gpl-3.0 | 9,302 | 0.000323 | # coding=utf-8
"""
InaSAFE Disaster risk assessment tool developed by AusAid -
**Impact Functions Dialog.**
Contact : ole.moller.nielsen@gmail.com
.. note:: 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 Soft... | ed are:') % im | pactFunctionName
myLabel = self.lblFunctionDescription
myLabel.setText(myText)
def parseInput(self, theInput):
"""Parse the input value of widget.
:param theInput: Dictionary that holds all |
lferr/charm | charm/test/toolbox/symcrypto_test.py | Python | lgpl-3.0 | 4,362 | 0.013984 | import unittest
from charm.toolbox.symcrypto import SymmetricCryptoAbstraction,AuthenticatedCryptoAbstraction, MessageAuthenticator
from charm.toolbox.pairinggroup import PairingGroup,GT
from charm.core.math.pairing import hashPair as sha1
class SymmetricCryptoAbstractionTest(unittest.TestCase):
def testAESCB... | b = AuthenticatedCryptoAbstraction(sha1(ran))
dmsg = b.decrypt(ct);
assert msg == dmsg , 'o: =>%s\nm: =>%s' % (msg, dmsg)
class MessageAuthenticatorTest(unittest.TestCase):
def testSelfVerify(self):
key = sha1(PairingGroup('SS512').random(GT))
m = MessageAuthenticator(key)
... | random(GT))
m = MessageAuthenticator(key)
a = m.mac('hello world')
m1 = MessageAuthenticator(key)
assert m1.verify(a), "expected message to verify";
def testTamperData(self):
key = sha1(PairingGroup('SS512').random(GT))
m = MessageAuthenticator(key)
a = m.ma... |
manuvarkey/cmbautomiser | cmbautomiser/openpyxl/xml/constants.py | Python | gpl-3.0 | 4,546 | 0.0022 | # Copyright (c) 2010-2021 openpyxl
"""Constants for fixed paths in a file and xml namespace urls."""
MIN_ROW = 0
MIN_COLUMN = 0
MAX_COLUMN = 16384
MAX_ROW = 1048576
# constants
PACKAGE_PROPS = 'docProps'
PACKAGE_XL = 'xl'
PACKAGE_RELS = '_rels'
PACKAGE_THEME = PACKAGE_XL + '/' + 'theme'
PACKAGE_WORKSHEETS = PACKAGE... | nxml | formats.org/drawingml/2006/chartDrawing"
CUSTOMUI_NS = 'http://schemas.microsoft.com/office/2006/relationships/ui/extensibility'
NAMESPACES = {
'cp': COREPROPS_NS,
'dc': DCORE_NS,
DCTERMS_PREFIX: DCTERMS_NS,
'dcmitype': 'http://purl.org/dc/dcmitype/',
'xsi': XSI_NS,
'vt': VTYPES_NS,
'xml'... |
plotly/plotly.py | packages/python/plotly/plotly/validators/scatter3d/line/colorbar/_dtick.py | Python | mit | 496 | 0.002016 | import _plotly_utils.basevalidators
class DtickValidator(_plotly_utils.basevalidators.AnyValidator):
def __init__(
self, plotly_name="dtick", parent_name | ="scatter3d.line.colorbar", **kwargs
):
super(Dt | ickValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "calc"),
implied_edits=kwargs.pop("implied_edits", {"tickmode": "linear"}),
**kwargs
)
|
dougwt/kartographer | kartographer/comparison/models.py | Python | gpl-2.0 | 8,723 | 0.000344 | """Django models for MK8 Kart Comparison Tool."""
from django.core.exceptions import ObjectDoesNotExist
from django.db import models
from django.templatetags.static import sta | tic
import re
import uuid
import logging
from ipware.ip import get_ip, get_real_ip
logger = logging.getLogger(__name__)
class KartComponent(models.Model):
"""Abstract model for all kart components."""
name = models.CharField(max_length=30, blank=True)
def __unicode__(self):
"""Return the compo... | return self.name
def file(self):
"""Return a lowercase form of the name used for image filenames."""
return re.sub(ur'[\W_]+', u'', self.name.lower(), flags=re.UNICODE)
class Meta:
abstract = True
ordering = ['pk']
class CommonStats(KartComponent):
"""Common stats acro... |
ros2/ci | ros2_batch_job/vendor/osrf_pycommon/tests/unit/test_process_utils/impl_aep_asyncio.py | Python | apache-2.0 | 505 | 0.00198 | from osrf_pycommon.process_utils import asyncio
from osrf_pyc | ommon.process_utils.async_execute_process import async_execute_process
from osrf_pycommon.process_utils import get_loop
from .impl_aep_protocol import create_protocol
loop = get_loop()
@asyncio.coroutine
def run(cmd, **kwargs):
transport, protocol = yield from async_execute_process(
create_protocol(), c... | etcode
|
Naoto-Imamachi/MIRAGE | scripts/module/analysis/motif_occurrence.py | Python | mit | 16,577 | 0.01086 | #!/usr/bin/env python
'''
motif_occurence.py:
Calculate probability of the miRNA-binding site occurence
<Methods>
(1)Binomial distribution
(2)Exact probability distribution
<Rules>
WC => Watson-Crick match
GU => G:U Wobble
-------------------------------
seed_length = 8
-------------------------------
... | eys()):
id_infor = x
targetrna_motif = tmp_dict[x][3] #NEED TO CHECK!!
motif_type = tmp_dict[x][5] #NEED TO CHECK!!
if motif_type == '8mer': #p1_p8_match, p2_p8_match, p1_p7_match, p2_p7_match, p3_p8_match
motif_ | type_need.append('p1_p8_match')
motif_type_dict['p1_p8_match'].append(utils.reverse_complement(targetrna_motif[0:8]))
motif_type_dict['p2_p8_match'].append(utils.reverse_complement(targetrna_motif[1:8]))
motif_type_dict['p1_p7_match'].append(utils.reverse_complement(targetrna_moti... |
filemakergarage/zeroclient | tests/local/test_random.py | Python | mit | 842 | 0 | from multiprocessing import Process, Value, Array
import time
import random
if __name__ == "__main__":
value_1 = Value('d', 0.0)
va | lue_2 = Value('d', 0.0)
v = {}
while True:
# y = random.randrange(14, 17, 1)
# m = format(random.randrange(1, 12, | 1), '02d')
# d = format(random.randrange(1, 31, 1), '02d')
# i1 = random.randrange(1, 99, 1)
# i2 = random.randrange(1, 10, 1)
v[0] = str(random.randrange(14, 17, 1))
v[1] = format(random.randrange(1, 12, 1), '02d')
v[2] = format(random.randrange(1, 31, 1), '02d')
... |
woodymit/millstone | genome_designer/pipeline/variant_calling/constants.py | Python | mit | 113 | 0 | """
C | onstants
"""
TOOL_FREEBAYES = 'freebayes'
TOOL_PINDEL = 'pindel'
TOOL_DELLY = 'delly'
TOOL_LUMPY = 'lu | mpy'
|
Willempie/Artificial_Intelligence_Cube | logic/handling/cube_storage.py | Python | apache-2.0 | 1,463 | 0.004101 | fr | om logic.rubiks_cube_converter import RubiksCubeConverter
from object_visual.v_rubiks_cube import VRubiksCube
class CubeStorage:
def __init__(self, display, cube_size):
self.cube_size = cube_size
self.current_cube = None
self._start_cube = VRubiksCube(self.cube_size, None, None, None, T... | ._start_cube.set_cube_visible(False)
#self.start_turn_cube =
self._result_cube = VRubiksCube(self.cube_size, None, None, None, True)
self._result_cube.set_cube_visible(False)
#self.result_turn_cube =
def load_from_xml_object(self, xml_object):
self._start_cube = RubiksCubeCo... |
tobi-wan-kenobi/bumblebee-status | bumblebee_status/modules/contrib/twmn.py | Python | mit | 1,236 | 0.001618 | # pylint: disable=C0111,R0903
"""Toggle twmn notifications.
Requires the following executable:
* systemctl
contributed by `Pseudonick47 <https://github.com/Pseudonick47>`_ - many thanks!
"""
import core.module
import core.widget
import core.input
import core.decorators
import util.cli
class Module(core.modul... |
self.__paused = False
# Make sure that twmn is currently not paused
util.cli.execute("killall -SIGUSR2 twmnd", ignore_errors=True)
core.input.register(self, button=core.input.LEFT_MOUSE, cmd=self.toggle_status)
def toggle_status(self, event):
self.__paused = not self.__paus... | wmnd")
except:
self.__paused = not self.__paused # toggling failed
def state(self, widget):
if self.__paused:
return ["muted"]
return ["unmuted"]
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
|
kytos/kytos-utils | kytos/__init__.py | Python | mit | 102 | 0 | """Kytos SDN Platform."""
from pkgutil import extend_path
__path__ = e | xtend_path(__path__, __n | ame__)
|
gdebure/cream | projects/models.py | Python | gpl-3.0 | 6,743 | 0.012164 | # -*- coding: utf-8 -*-
from datetime import date
from django.db import models
from django.core.exceptions import ValidationError
from django.core.urlresolvers import reverse
import reversion
from users.models import Employee
from services.models import Service
class ProjectStatus(models.Model):
id = model... | .toordinal()
date_volume_end = volume.date_end.toordinal()
volume_range = range(date_volume_start,date_volume_end+1)
days_volume = len(volume_range)
|
intersect = list(set(volume_range) & set(year_range))
days_intersect = len(intersect)
volume_price = round((volume.get_total_price()/days_volume)*days_intersect,2)
year_turnover += volume_price
return year_turnover
... |
seba-1511/randopt | examples/command_example.py | Python | apache-2.0 | 1,067 | 0.001874 | #!/usr/bin/env python3
import randopt as ro
@ro.cli
def test1(arg1=20, arg2='name', arg3=1.23):
print('test1')
print('arg1', arg1)
print('arg2', arg2)
print('arg3', arg3)
@ro.cli
def test2(arg1=20, arg2='name', arg3=1.23):
"""
The docstring serves as help when using the --help flag.
Ar... | ):
return x**2 | + y**2, {'additional': 'info'}
@ro.experiment('result_params_attachments')
def test_experiment3(x=2, y=3):
return x**2 + y**2, {'additional': 'info'}, {'attach': 'this sentence.'}
@ro.cli
def test_experiment4(x=2, y=4):
exp = ro.Experiment('params_from_def', params=ro.dict_to_constants(locals()))
exp.ad... |
AnsgarSchmidt/sensomatic | server/Pinger.py | Python | apache-2.0 | 2,983 | 0.002682 | import os
import time
import ping
import threading
import ConfigParser
import paho.mqtt.client as mqtt
class Pinger(threading.Thread):
def _readConfig(self):
update = False
if not os.path.isdir(self._homeDir):
print "Creating homeDir"
os.makedirs(self._homeDir)
i... | = ConfigParser.ConfigParser()
self._readConfig()
self._mqclient = mqtt.Client("Pinger", clean_session=True)
self._crew = {"ansi": False, "tiffy": Fals | e}
def run(self):
self._mqclient.connect(self._config.get("MQTT", "ServerAddress"), self._config.get("MQTT", "ServerPort"), 60)
self._mqclient.loop_start()
while True:
a = ping.quiet_ping(self._config.get("PINGER", "AnsiIP"), timeout=1, count=1)
if a[0] == 0:
... |
stevecassidy/hcsvlab_robochef | hcsvlab_robochef/monash/rdf.py | Python | gpl-3.0 | 1,426 | 0.007714 | '''
This module defines a method genrdf, which takes a metadata dictionary
as parameter and returns a rdflib Graph instance.
'''
from hcsvlab_robochef.rdf.map import *
# corpus identifier
MONASH = "MONASH"
def map_gender(prop, value):
"""Map gender (M or F) to FOAF.gender (male or female)"""
if value =... | erson descriptions
monashMap.add("SEX:", ignore=True)
monashMap.add("SCHOOL:", ignore=True)
monashMap.add("BIRTHPLACE:", ignore=T | rue)
monashMap.add("AGE:", ignore=True)
def map_genre(prop, value):
"""Generate the genre description, for Monash, this is
the same for every item"""
return ((AUSNC.mode, AUSNC.spoken),
(AUSNC.speech_style, AUSNC.spontaneous),
(AUSNC.interactivity, AUSNC.dialogue),
... |
ChristianFrisson/papermachines | chrome/content/papermachines/processors/mallet_lda_tags.py | Python | bsd-2-clause | 1,353 | 0.001478 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import os
import logging
import traceback
import mallet_lda
class MalletTagTopics(mallet_lda.MalletLDA):
"""
Topic modeling with separation based on tags
"""
def _basic_params(self):
self.name = 'mallet_lda_tags'
self.categorical ... | for filename in self.metadata.keys():
my_tags = [x for (x, y) in self.tags.iteritems()
| if int(self.metadata[filename]['itemID'
]) in y]
if len(my_tags) > 0:
self.metadata[filename]['label'] = my_tags[0]
else:
del self.metadata[filename]
self.files.remove(fil... |
CanonicalLtd/ubuntu-image | ubuntu_image/__init__.py | Python | gpl-3.0 | 690 | 0 | import os
from pkg_resources import resource_string as resource_bytes
# Try to get the version number, which will be different if we're living in a
# snap world or a deb. Actually, I'd prefer to not even have the -NubuntuY
# version string when we're running from | source, but that's trickier, so don't
# worry abo | ut it.
__version__ = os.environ.get('SNAP_VERSION')
if __version__ is None: # pragma: nocover
try:
__version__ = resource_bytes(
'ubuntu_image', 'version.txt').decode('utf-8')
except FileNotFoundError:
# Probably, setup.py hasn't been run yet to g... |
tanium/pytan | BUILD/build_api_examples.py | Python | mit | 16,361 | 0.0022 | #!/usr/bin/env python
# -*- mode: Python; tab-width: 4; indent-tabs-mode: nil; -*-
# ex: set tabstop=4
# Please do not change the two lines above. See PEP 8, PEP 263.
'''generates all of the examples from the test/ddt JSON files'''
__author__ = 'Jim Olsen (jim.olsen@tanium.com)'
__version__ = '2.1.4'
import os
import ... | , name): |
fn = name + '.rst'
return fn
def build_md_filename(self, name):
fn = name + '.md'
return fn
def build_py_filename(self, name):
fn = name + '.py'
return fn
def write_rst_file(self, name, out):
filename = self.build_rst_filename(name)
filepat... |
WaveBlocks/WaveBlocks | demos/demo_tunneling_spawning/demo_tunneling_spawn_propagation_norm_threshold.py | Python | bsd-3-clause | 517 | 0.007737 | algorithm = "spawn | ing_adiabatic"
#algorithm = "hagedorn"
potential = "eckart"
T = 70
dt = 0.005
eps = 0.0234218**0.5
basis_size = 300
parameters = [ (0.1935842258501978j, 5.1657101481699996, 0.0, 0.24788547371, -7.55890450883) ]
coefficients = [[(0, 1.0)]]
leading_component = 0
f = 9.0
ngn = 4096
write_nth = 20
spawn_method = "... | r' 0.32 usually not known apriori!
spawn_threshold = 0.32
|
codeif/crimg | crimg/bin.py | Python | mit | 1,481 | 0 | # -*- coding: utf-8 -*-
import sys
from io import BytesIO
import argparse
from PIL import Image
from .api import crop_resize
parser = argparse.ArgumentParser(
description='crop and resize an image without aspect ratio distortion.')
parser.add_argument('image')
parser.add_argument('-w', '-W', '--width', metavar='<... | rsed_args = parser.parse_args()
image = Image.open(parsed_args.image)
size = (parsed_args.width, parsed_args.height)
new_image = crop_resize(image, size, parsed_args.force)
if parsed_args.display:
new_image.show()
elif parsed_args.output:
new_image.save(parsed_args.output)
else:
... | except AttributeError:
stdout = sys.stdout
stdout.write(f.getvalue())
|
gnuradio/pybombs | pybombs/packagers/zypper.py | Python | gpl-3.0 | 6,420 | 0.00296 | #
# Copyright 2015-2016 Free Software Foundation, Inc.
#
# This file is part of PyBOMBS
#
# PyBOMBS 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, or (at your option)
# any later version.
#
... | self.packager = ExternalZypper(self.log)
def supported(self):
| """
Check if we can even run zypper.
Return True if so.
"""
return self.packager.command is not None
|
PortfolioEffect/jniusx | tests/test_enum.py | Python | mit | 522 | 0 | from __future__ import print_function
from __future__ import division
from | __future__ import absolute_import
import unittest
from jnius.reflect import autoclass
class SimpleEnum(unittest.TestCase):
def test_enum(self):
SimpleEnum = autoclass('org.jnius.SimpleEnum')
self.assertTrue(SimpleEnum)
def test_valu | e(self):
SimpleEnum = autoclass('org.jnius.SimpleEnum')
self.assertTrue(SimpleEnum.GOOD)
self.assertTrue(SimpleEnum.BAD)
self.assertTrue(SimpleEnum.UGLY)
|
bjura/EPlatform | spellerPuzzle.py | Python | gpl-3.0 | 24,523 | 0.047734 | #!/bin/env python2.7
# -*- coding: utf-8 -*-
# This file is part of AT-Platform.
#
# EPlatform 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 ... | ne[ :line.find('=')-1 ] == 'colorNiest':
| pass
elif line[ :line.find('=')-1 ] == 'ileLuk':
pass
#self.ileLuk= int(line[ line.rfind('=')+2:-1 ])
elif not line.isspace( ):
print 'Niewłaściwie opisane parametry'
print 'Błąd ... |
santoshmano/technical_interviews | coding_session/00_simple_sorts.py | Python | mit | 1,499 | 0.00467 |
"""
Problem: Sort array of integers using insertion, bubble and selection sort
input: array of integers, there may be duplicates
output: sorted array
"""
"""
insertion sort:
Return if array len is less than 2.
For every item from index 1 to end of string.
compare item with the left sorted array
if item is ... | insertion_sort, bubble_sort]
for sort in all_sorts:
lists = [[],
[3, 0],
[3, 2, 1],
[9, 5, 8, 2],
[-2, 4, 1, 1, 0, 8, 9]]
for list in li | sts:
print(sort(list), str(sort).sp)
|
g7/python-nala | setup.py | Python | gpl-3.0 | 1,120 | 0.017857 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# nala - file/directory watcher
# Copyright (C) 2013 Eugenio "g7" Paolantonio <me@medesimo.eu>
#
# 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, ... | eral Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from distutils.core import setup
setup(name='nala',
version='0.0.1',
description='file/directory watcher libraries',
author='Eugenio Paolantonio',
author_email='me@medesimo.eu',
url='https://github.com/g7/python-nala',
... |
)
|
lodemo/CATANA | src/data_collection/youtubeAPICrawler/filterChannelByCounts.py | Python | mit | 615 | 0.013008 | # -*- coding: utf-8 -*-
from youtubeAPICrawler.database import *
db = YTDatabase()
with db._session_scope(Tr | ue) as session:
# Get all channel historys with video counts zero
zch = session.query(ChannelHistory).filter( (ChannelHistory.videoCount <= 0) | (ChannelHistory.subscriberCount <= 0) |\
(ChannelHistory.viewCount <= 0) )
# Delete all channel item in th | e other table
for ch in zch:
print 'found'
session.query(Channel).filter(Channel.id == ch.channelID).delete(synchronize_session=False)
# Delete the history items
zch.delete(synchronize_session=False) |
hhursev/recipe-scraper | tests/test_innit.py | Python | mit | 3,331 | 0.0006 | from recipe_scrapers.innit import Innit
from tests import ScraperTest
class TestInnitScraper(ScraperTest):
scraper_class = Innit
def test_host(self):
self.assertEqual("innit.com", self.harvester_class.host())
def test_title(self):
self.assertEqual(
"Tofu Mixed Greens Salad w... | "1 1/3 tsp Kosher Salt",
"2/3 cup Olive Oil",
"2 pinches Black Pepper",
"1/4 cup Rice Wine Vinegar",
"1 cup Sunflo | wer Seeds",
],
self.harvester_class.ingredients(),
)
def test_nutrients(self):
self.assertEqual(
{
"sugarContent": "18 g",
"proteinContent": "32 g",
"fiberContent": "11 g",
"unsaturatedFatContent": "... |
pyannote/pyannote-audio | pyannote/audio/tasks/segmentation/speaker_tracking.py | Python | mit | 5,325 | 0.001315 | # MIT License
#
# Copyright (c) 2020-2021 CNRS
#
# 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, merge, pu... | OT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR | PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from typing import Lis... |
Azure/azure-sdk-for-python | sdk/synapse/azure-mgmt-synapse/azure/mgmt/synapse/aio/operations/_keys_operations.py | Python | mit | 13,131 | 0.004265 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reser | ved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# | Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
import functools
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar
im... |
Shebella/HIPPO | clc/tools/src/euca_admin/walruses.py | Python | gpl-3.0 | 2,284 | 0.029772 | import boto,sys,euca_admin
from boto.exception import EC2ResponseError
from euca_admin.generic import BooleanResponse
from euca_admin import EucaAdmin
from optparse import OptionParser
SERVICE_PATH = '/services/Configuration'
class Walrus():
def __init__(self, walrus_name=None, host_name=None, | port=None):
self.walrus_name = walrus_name
self.host_name = host_name
self.euca = EucaAdmin(path=SERVICE_PATH)
def __repr__(self):
| return 'WALRUS\t%s\t%s' % (self.walrus_name, self.host_name)
def startElement(self, name, attrs, connection):
return None
def endElement(self, name, value, connection):
if name == 'euca:detail':
self.host_name = value
elif name == 'euca:name':
self.walrus_name = value
else:
... |
ULHPC/easybuild-easyblocks | easybuild/easyblocks/i/impi.py | Python | gpl-2.0 | 9,563 | 0.00481 | # #
# 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 (... | edirs(tmpdir)
| except:
raise EasyBuildError("Directory %s can't be created", tmpdir)
cmd = "./install.sh --tmp-dir=%s --silent=%s" % (tmpdir, silentcfg)
run_cmd(cmd, log_all=True, simple=True)
def post_install_step(self):
"""Custom post install step for IMPI, fix broken e... |
simark/cyprj-to-makefile | setup.py | Python | gpl-3.0 | 576 | 0.053819 | from setuptools import setup, find_packages
setup(
name = "CyprjToMakefile",
version = "0.1",
author = "Simon Marchi",
author_email = "simon.marchi@polymtl.ca",
description = "Generate Makefiles from Cypress cyprj files.",
license = "GPLv3",
url = "https://github.com/simark/cyprj-to-makefil... | a2'],
package_data = {
'cyprj_to_makefile': ['Makefile.tpl'],
},
entry_points = {
'console_scripts': [
'cyprj-to-makefile = cyprj_to_makefile.cyprj_to | _makefile:main',
],
},
)
|
MingfeiPan/leetcode | array/39.py | Python | apache-2.0 | 691 | 0.008683 | #backtracking
class Solution:
def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
ret = []
candidates.sort()
self.backtrack(ret, [], candidates, target, 0)
retur | n ret
def backtrack(self, ret, temp, candidates, value, start):
if value < 0:
return
elif value == 0:
ret.append(temp)
return
else:
for i in range(start, len(candidates)):
self.backtrack(ret, temp + [candidates[i]], candida... | |
CodeRiderz/rojak | rojak-pantau/rojak_pantau/i18n/__init__.py | Python | bsd-3-clause | 31 | 0 | i | mport i18n as i
_ = i.i18n( | )
|
polyaxon/polyaxon | core/tests/test_init/test_init_code.py | Python | apache-2.0 | 2,535 | 0 | #!/usr/bin/python
#
# Copyright 2018-2021 Polyaxon, 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 ... | assert has_cred_access() is False
os.environ[POLYAXON_KEYS_GIT_CREDENTIALS] = "foo:bar"
assert has_cred_access() is True
del os.environ[POLYAXON_KEYS_GIT_CREDENTIALS]
def test_has_ssh_access(self):
assert has_ssh_access() is False
def test_get_clone_url(self):
url = "ht... | ert get_clone_url(url=url) == url
os.environ[POLYAXON_KEYS_GIT_CREDENTIALS] = "foo:bar"
assert get_clone_url(url=url) == "https://foo:bar@foo.com/test"
del os.environ[POLYAXON_KEYS_GIT_CREDENTIALS]
with patch("polyaxon.init.git.has_ssh_access") as ssh_access_mock:
ssh_access... |
OlegPshenichniy/RabbitMQ-Python | with_pika/2/durable/worker_durable_ack.py | Python | unlicense | 770 | 0.005195 | """
Worker which simulate hard work. Work with durable queue.
Using pika https://github.com/pika/pika.
"""
import time
import pika
def callback(channel, method, properties | , body):
print " [x] Received {0}".format(body)
time.sleep(float(body.count('second'))/20)
print " [x] Done"
channel.basic_ack(delivery_tag=method.delivery_tag)
params = pika.ConnectionParameters('localhost')
connection = pika.BlockingConnection(parameters=params)
#make channel
channel = connection.ch... | queue='sms')
print ' [*] Waiting for messages. To exit press CTRL+C'
channel.start_consuming()
|
seibert/blaze-core | samples/chunked/other_eval.py | Python | bsd-2-clause | 9,032 | 0.003764 | """ Provides the evaluator backends for Numexpr and the Python interpreter """
from expression_builder import Visitor
import blaze
import math
def evaluate(expression,
chunk_size,
vm='python',
out_flavor='blaze',
user_dict={},
**kwargs):
"""
... | s = operands
def eval(self, chunk_size=None):
chunk_size = (chunk_size
if chunk_size is not None
else self._infer_chunksize())
return evaluate(self.str_expr,
chunk_size,
vm='numexpr',
... | typesize = _per_element_size(self.operands)
vlen = _array_length(self.operands)
bsize = 2**20
bsize //= typesize
bsize = 2 ** (int(math.log(bsize,2)))
if vlen < 100*1000:
bsize //= 8
elif vlen < 1000*1000:
bsize //= 4
elif vlen < 10*1... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.