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
RagaiAhmed/PSP
src/tasks.py
Python
apache-2.0
1,617
0.005566
import src.game_utils.function_proxy as check from src.basic_functions import * """ This file is the one you'll be working on read the documentation of the functions to know what it must be able to do. """ def move_snake(): """ This function controls how the snake moves Uses an edited v...
cube an so on def frame_logic(): """ Controls Frame Logic """ snake = get_snake() snake.move() body = snake.body if body[0] == get_food_position(): # if the snake ate a food food_location(body) # calls a function to change food location taking care of not spawning on snake bo...
ten itself or out of screen game_over() def food_location(body): """ :param body: Snake body to avoid :return: None """ rnd_pnt = random_point() while rnd_pnt in body: rnd_pnt = random_point() change_food_location(rnd_pnt) def submit_your_functions(): check.proto...
UKTradeInvestment/export-wins-data
fdi/tests/util.py
Python
gpl-3.0
706
0
f
rom collections import UserDict class PathDict(UserDict): def __normalize_key(self, key): tkey = key if isinstance(key, str) and '.' in key: tkey = tuple(key.split('.')) return tkey def __setitem__(self, key, value): tkey = self.__normalize_key(key) return...
em__(self, item): tkey = self.__normalize_key(item) return super().__getitem__(tkey) def __delitem__(self, key): tkey = self.__normalize_key(key) return super().__delitem__(tkey)
toymachine/venster
venster/windows.py
Python
mit
23,583
0.018318
## Copyright (c) 2003 Henk Punt ## 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, #...
_pack_ = 2 _fields_ = [ ("style", DWORD), ("exStyle", DWORD), ("x", c_short), ("y", c_short), ("cx", c_short), ("cy", c_short), ("id", WORD) ] class COPYDATASTRUCT(Structure): _f
ields_ = [ ("dwData", ULONG_PTR), ("cbData", DWORD), ("lpData", PVOID)] def LOWORD(dword): return dword & 0x0000ffff def HIWORD(dword): return dword >> 16 TRUE = 1 FALSE = 0 NULL = 0 IDI_APPLICATION = 32512 SW_SHOW = 5 SW_SHOWNORMAL = 1 SW_HIDE = 0 EN_CHANGE = 768 MSGS = [('WM...
nastya/droidbot
droidbot/adapter/adb.py
Python
mit
13,744
0.003783
# This is the interface for adb import subprocess import logging import re from adapter import Adapter import time import sys import os class ADBException(Exception): """ Exception in ADB connection """ pass class ADB(Adapter): """ interface of ADB send adb commands via this, see: ht...
RO_DEBUGGABLE_PROPERTY = 'ro.debuggable' def __init__(self, device=None): """ initi
ate a ADB connection from serial no the serial no should be in output of `adb devices` :param device: instance of Device :return: """ self.logger = logging.getLogger(self.__class__.__name__) if device is None: from droidbot.device import Device dev...
andrewjylee/omniplay
logdb/pydot.py
Python
bsd-2-clause
60,152
0.01694
# -*- coding: Latin-1 -*- """Graphviz's dot language Python interface. This module provides with a full interface to create handle modify and process graphs in Graphviz's dot language. References: pydot Homepage: http://code.google.com/p/pydot/ Graphviz: http://www.graphviz.org/ DOT Language: http://www.grap...
' + s + '"' return s def graph_from_dot_data(data): """Load graph as defined by data in DOT format. The data is assumed to b
e in DOT format. It will be parsed and a Dot class will be returned, representing the graph. """ return dot_parser.parse_dot_data(data) def graph_from_dot_file(path): """Load graph as defined by a DOT file. The file is assumed to be in DOT format. It will be loaded, parsed and a...
jaredlunde/cargo-orm
unit_tests/aio/AioPostgresPool.py
Python
mit
5,680
0
#!/usr/bin/python3 -S # -*- coding: utf-8 -*- """ `Unit tests for cargo.clients.AioPostgresPool` --·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·--·-- 2016 Jared Lunde © The MIT License (MIT) http://github.com/jaredlunde """ import unittest import psycopg2 from cargo.cursors import...
tion: self.assertIs(connection.autocommit, pool.autocommit) self.assertIs(connection._dsn, pool._dsn) self.assertIs(connection._schema, pool._schema) self.assertIs(connection.encoding, pool.enco
ding) self.assertIs(connection.minconn, pool.minconn) self.assertIs(connection.maxconn, pool.maxconn) self.assertIs(connection.cursor_factory, pool.cursor_factory) def test_put(self): with AioPostgresPool(1, 2) as pool: conn = pool.get() ...
akiokio/centralfitestoque
src/.pycharm_helpers/pydev/pydevd_xml.py
Python
bsd-2-clause
6,287
0.009384
import pydev_log import traceback import pydevd_resolver from pydevd_constants import * #@UnusedWildImport from types import * #@UnusedWildImport try: from urllib import quote except: from urllib.parse import quote #@UnresolvedImport try: from xml.sax.saxutils import escape def makeValidXmlValue(s): ...
g.python.core.InitModule return 'Unable to get Type', 'Unable to get Type', None try: if type_name
== 'org.python.core.PyJavaInstance': return type_object, type_name, pydevd_resolver.instanceResolver if type_name == 'org.python.core.PyArray': return type_object, type_name, pydevd_resolver.jyArrayResolver for t in typeMap: if isinstance(o, t[0]): ...
jarped/QGIS
python/plugins/processing/algs/lidar/lastools/lasduplicate.py
Python
gpl-2.0
3,468
0.001442
# -*- coding: utf-8 -*- """ *************************************************************************** lasduplicate.py --------------------- Date : September 2013 Copyright : (C) 2013 by Martin Isenburg Email : martin near rapidlasso point com ************...
ls import LAStoolsUtils from LAStoolsAlgorithm import LAStoolsAlgorithm from processing.core.parameters import ParameterBoolean from processing.core.parameters import ParameterFile class lasduplicate(LAStoolsAlgorithm): LOWEST_Z = "LOWEST_Z" UN
IQUE_XYZ = "UNIQUE_XYZ" SINGLE_RETURNS = "SINGLE_RETURNS" RECORD_REMOVED = "RECORD_REMOVED" def defineCharacteristics(self): self.name, self.i18n_name = self.trAlgorithm('lasduplicate') self.group, self.i18n_group = self.trAlgorithm('LAStools') self.addParametersVerboseGUI() ...
rdmorganiser/rdmo
rdmo/views/migrations/0015_remove_null_true.py
Python
apache-2.0
4,097
0.003661
# -*- coding: utf-8 -*- # Generated by Django 1.11.16 on 2019-03-13 11:54 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('views', '0014_data_migration'), ] operations = [ migrations.AlterField( ...
ame='view', name='uri', field=models.URLField(blank=True, help_text='The Uniform Resource Identifier of this view (auto-generated).', max_length=640, verbose_name='URI'), ), migrations.AlterField( model_name='view', name='uri_prefix',
field=models.URLField(blank=True, help_text='The prefix for the URI of this view.', max_length=256, verbose_name='URI Prefix'), ), ]
NuAge-Solutions/NW
oj.py
Python
gpl-3.0
292
0
#!/usr/bin/env python import sys
from imp import load_source from os import path src_path
= path.abspath(path.dirname(__file__)) oj_path = path.join(src_path, 'dependencies', 'oj') sys.path.append(oj_path) oj = load_source('oj', path.join(oj_path, 'utils', 'run.py')) oj.run(src_path)
dmsuehir/spark-tk
regression-tests/sparktkregtests/testcases/frames/frame_group_by_test.py
Python
apache-2.0
10,492
0.000096
# vim: set encoding=utf-8 # Copyright (c) 2016 Intel Corporation  # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # #       http://www.apache.org/licenses/LICENSE-2.0 # # Unless require...
rror on non-numeric column""" with self.assertRaises(Exception): self.frame.group_by('colors', {'colors': self.context.agg.var}) def test_invalid_column_name(self): """Aggregate on non-existant column errors""" with self.assertRaises(Exception): self.frame.group_by( ...
xt.agg.var}) def test_group_int32_standard(self): """Test groupby on 1 column, int32""" stats = self.frame.group_by(['Int32_0_15'], {'Int32_0_31': self.aggs}) self._validate(stats, 'Int32_0_31', ['Int32_0_15']) def test_group_float32_standard(self): """Test groupby on 1 column,...
sgarrity/bedrock
bedrock/pocketfeed/api.py
Python
mpl-2.0
1,744
0.00172
import datetime import re import requests from django.conf import settings from django.utils.timezone import make_aware, utc from raven.contrib.django.raven_compat.models import client as sentry_client def get_articles_data(count=8): payload = { 'consumer_key': settings.POCKET_CONSUMER_KEY, 'acce...
s_data(articles): for _, article in articles: # id from API should be moved to pocket_id to not conflict w/DB's id article['pocket_id'] = article['id'] # convert time_shared from unix timestamp to datetime a
rticle['time_shared'] = make_aware(datetime.datetime.fromtimestamp(int(article['time_shared'])), utc) # remove data points we don't need del article['comment'] del article['excerpt'] del article['id'] del article['quote'] check_article_image(article) def check_article...
bellowsj/aiopogo
aiopogo/pogoprotos/networking/requests/messages/evolve_pokemon_message_pb2.py
Python
mit
3,240
0.008025
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: pogoprotos/networking/requests/messages/evolve_pokemon_message.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _m...
has_default_value=False, default_value
=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=154,...
pylessard/python-udsoncan
test/test_stubbed_isotpsock.py
Python
mit
2,233
0.000896
from test.UdsTest import UdsTest from test.stub import StubbedIsoTPSocket from udsoncan.exceptions import * import socket class TestStubbedIsoTPSocket(UdsTest): def test_open(self): tpsock = StubbedIsoTPSocket() self.assertFalse(tpsock.bound) tpsock.bind(interface='vcan0', rxid=0x100, txid=...
nterface='vcan0', rxid=0x401, txid=0x400) with self
.assertRaises(socket.timeout): tpsock2.recv()
jinzekid/codehub
python/test_web_speed.py
Python
gpl-3.0
1,603
0.022163
import io,pycurl,sys,os,time class idctest: def __init__(self): self.contents = '' def body_callback(self,buf): self.contents = self.contents + buf def test_gzip(input_url): t = idctest() #gzip_test = file("gzip_test.txt", 'w') c = pycurl.Curl() c.setopt(pycurl.WRITEFUNCT...
_url = sys.argv[1] test
_gzip(input_url)
hustodemon/spacewalk
backend/wsgi/__init__.py
Python
gpl-2.0
609
0
# # Copyright (c) 2010 Red Hat, Inc. # # This software is licensed to you under the GNU General Public License, # version 2 (GPLv2). There is NO WARRANTY for this software, express or # implied, including the implied warranties of MERCHANTABILITY or FITNE
SS # FOR A PARTICULAR PURPOSE. You
should have received a copy of GPLv2 # along with this software; if not, see # http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. # # Red Hat trademarks are not licensed under GPLv2. No permission is # granted to use or replicate Red Hat trademarks that are incorporated # in this software or its documentation. # #
diogenes1oliveira/mathbind
mathbind/types/basicvaluetype.py
Python
mit
3,498
0.002287
#!/usr/bin/env python3 from mathbind.types import BasicType class BasicValueType(BasicType): """ Represents a basic pure type that can be passed by value, thus excluding arrays and pointers. Attributes: - typename (str): basic C typename (int, long long, unsi
gned, bool, etc) - c_math_name (str): corresponding Mathematica C type - math_name (str): corresponding Mathematica type (Integer, Real) - c_name (str): corresponding C type (int, long long, float). """ def __init__(self, typename
): self.typename = typename type_parts = set(typename.split()) self.c_name = typename if not type_parts: raise ValueError elif {'float', 'double'} & type_parts: self.c_math_name = 'mreal' self.math_name = 'Real' elif 'bool' in type_p...
jijeshmohan/webdriver-rb
firefox/src/py/firefox_profile.py
Python
apache-2.0
11,601
0.003017
# Copyright 2008-2009 WebDriver committers # Copyright 2008-2009 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 requ...
st in profiles.ini" return os.path.join(utils.get_firefox_app_data_dir(), self.profile_ini.get(section, "Path")) @staticmethod def _refresh_ini(): FirefoxProfile.profile_ini = get_profile_ini() def _launch_in_silent(self): os.environ["XRE_PROFILE_PATH"] ...
rofile_dir subprocess.Popen([utils.get_firefox_start_c
mahak/cinder
cinder/tests/unit/image/test_accelerator.py
Python
apache-2.0
3,676
0.002176
# # 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 # ...
@mock.patch('cinder.image.accelerator.ImageAccel._get_engine') @mock.patch('cinder.image.accelerator.ImageAccel.is_engine_ready', re
turn_value = True) def test_decompress_img_engine_ready(self, mock_accel_engine_ready, mock_get_engine): source = mock.sentinel.source dest = mock.sentinel.dest run_as_root = mock.sentinel.run_as_root mock_engine = mock.Mock(spec=fakeEngine)...
glennlive/gnuradio-wg-grc
grc/gui/MainWindow.py
Python
gpl-3.0
13,903
0.006258
""" Copyright 2008, 2009, 2011 Free Software Foundation, Inc. This file is part of GNU Radio GNU Radio Companion 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...
# Report Window ############################################################ def add_report_lin
e(self, line): """ Place line at the end of the text buffer, then scroll its window all the way down. Args: line: the new text """ self.text_display.insert(line) ############################################################ # Pages: create and close #####...
Azure/azure-sdk-for-python
sdk/appplatform/azure-mgmt-appplatform/azure/mgmt/appplatform/v2020_11_01_preview/aio/operations/_monitoring_settings_operations.py
Python
mit
16,766
0.005189
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
rialized _update_put_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/monitoringSettings/default'} # type: igno
re @distributed_trace_async async def begin_update_put( self, resource_group_name: str, service_name: str, monitoring_setting_resource: "_models.MonitoringSettingResource", **kwargs: Any ) -> AsyncLROPoller["_models.MonitoringSettingResource"]: """Update the...
mrcatacroquer/Bridge
migrations/versions/2356a38169ea_followers.py
Python
mit
941
0.012752
"""followers Revision ID: 2356a38169ea Revises: 288cd3dc5a8 Create Date: 2013-12-31 16:10:34.500006 """ # revision identifiers, used by Alembic. revision = '2356a38169ea' down_revision = '288cd3dc5a8' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by...
p.create_table('follows',
sa.Column('follower_id', sa.Integer(), nullable=False), sa.Column('followed_id', sa.Integer(), nullable=False), sa.Column('timestamp', sa.DateTime(), nullable=True), sa.ForeignKeyConstraint(['followed_id'], ['users.id'], ), sa.ForeignKeyConstraint(['follower_id'], ['users.id'], ), sa.Prima...
superdesk/Live-Blog
plugins/media-archive-image/superdesk/media_archive/impl/image_data.py
Python
agpl-3.0
1,525
0.007213
''' Created on Apr 19, 2012 @package: superdesk media archive @copyright: 2012 Sourcefabric o.p.s. @license: http://www.gnu.org/licenses/gpl-3.0.txt @author: Gabriel Nistor SQL Alchemy based implementation for the image data API. ''' from ally.cdm.spec import ICDM from ally.container import wire from ally.container...
ted @setup(IImageDataService, name='imageDataService') class ImageDataServiceAlchemy(MetaDataServiceBaseAlchemy, IMetaDataReferencer, IImageDataService): ''' @see: IImageDataService ''' cdmArchiveImage = ICDM; wire.entity('cdmArchiveImage') thumbnailManager = IThumbnailManager; wire.entity('thumbna...
er') def __init__(self): assert isinstance(self.cdmArchiveImage, ICDM), 'Invalid archive CDM %s' % self.cdmArchiveImage assert isinstance(self.thumbnailManager, IThumbnailManager), 'Invalid thumbnail manager %s' % self.thumbnailManager MetaDataServiceBaseAlchemy.__init__(self, Image...
kd0kfo/pi_lcd_controller
python/picontroller/button_listener.py
Python
gpl-3.0
1,373
0.00437
#!/usr/bin/env python from time import sleep class ButtonListener(): """ Service that polls the button status device and calls a callback funtion for each button pressed. Callback function should return a boolean to show whether or not the listening should continue. """ def __init__(se...
self.last_state = {"0": 0} def listen(self): while True: raw_state = [ord(ch) for ch in self
.button_device.read(self.num_buttons)] state = dict(zip(range(0, len(raw_state)), raw_state)) for (button, isup) in state.iteritems(): if isup: state[button] = 1 else: state[button] = 0 if not isup and button...
ActiveState/code
recipes/Python/577680_Multithreaded_Mandelbrot_Fractal/recipe-577680.py
Python
mit
1,749
0.009148
# Multi-threaded Mandelbrot Fractal (Do not run using IDLE!) # FB - 201104306 import threading from PIL import Image w = 512 # image width h = 512 # image height image = Image.new("RGB", (w, h)) wh = w * h maxIt = 256 # max number of iterations allowed # drawing region (
xa < xb & ya < yb) xa = -2.0 xb = 1.0 ya = -1.5 yb = 1.5 xd = xb - xa yd = yb - ya numThr = 5 # number of threads to run # lock = threading.Lock() class ManFrThread(threading.Thread): def __init__ (self, k)
: self.k = k threading.Thread.__init__(self) def run(self): # each thread only calculates its own share of pixels for i in range(k, wh, numThr): kx = i % w ky = int(i / w) a = xa + xd * kx / (w - 1.0) b = ya + yd * ky / (h - 1.0) ...
tyndare/osmose-backend
analysers/analyser_osmosis_highway_turn_lanes.py
Python
gpl-3.0
4,965
0.006448
#!/usr/bin/env python #-*- coding: utf-8 -*- ########################################################################### ## ## ## Copyrights Frédéric Rodrigo 2016 ## ## ...
>'turn:lanes', '|'), 1) WHEN tags->'highway'
IN ('motorway', 'trunk') THEN 2 ELSE 1 END) AS lanes, SUM(array_length(string_to_array(tags->'turn:lanes', 'slight_'), 1) - 1) AS lanes_slight, SUM(array_length(string_to_array(tags->'turn:lanes', 'merge_to_'), 1) - 1) AS lanes_merge_to FROM turn_lanes_steps GROUP BY nid, start_end HAVING BOOL_AND(ta...
oesteban/preprocessing-workflow
fmriprep/cli/sample_openfmri_tasks_list.py
Python
bsd-3-clause
3,643
0.000549
# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """ A tool to generate a tasks_list.sh file for running fmriprep on subjects downloaded with datalad with sample_openfmri.py """ import os import glob CMDLINE = """\ {fmriprep_cm...
if opts.tasks_filter: cmdline += '-t %s' % ' '.join(opts.tasks
_filter) fmriprep_cmd = 'fmriprep' if opts.cmd_call is None: singularity_dir = os.getenv('SINGULARITY_BIN') singularity_img = sorted( glob.glob(os.path.join(singularity_dir, 'poldracklab_fmriprep_*'))) if singularity_img: fmriprep_cmd = 'singularity run %s' % sin...
mr-ninja-snow/Self-Updating-Python-Program
setup.py
Python
gpl-3.0
334
0.005988
fro
m distutils.core import setup from program_version import RELEASE setup(name='program', version=RELEASE, description='A self updating program example', author='Mr Snow', author_email='ninja@snow.com', url='https://github.com/mr-ni
nja-snow/Self-Updating-Python-Program.git', packages=[], )
dario-chiappetta/Due
due/agent.py
Python
gpl-3.0
7,123
0.026534
""" Due is a learning, modular, action-oriented dialogue agent. `Agents` are the entities that can take part in Episodes (:mod:`due.episode`), receiving and issuing Events (:mod:`due.event`). """ import uuid from abc import ABCMeta, abstractmethod from datetime import datetime from due.event import Event from due impo...
= self.leave_callback(episode) if not result: result = [] return result @abstractmethod def utterance_callback(self, episode): """ This is a callback method that is invoked whenever a new Utterance Event is acted in an Episode.
:param episode: the Episode where the Utterance was acted :type episode: `due.episode.Episode` :return: A list of response Events :rtype: `list` of :class:`due.event.Event` """ pass @abstractmethod def action_callback(self, episode): """ This is a callback method that is invoked whenever a new Action...
DemocracyFoundation/Epitome
Agora/forms.py
Python
agpl-3.0
40
0.025
from d
jango import f
orms # future use
mindbaffle/ATF
Test/FunctionalTests/DomTreeEditorTestScripts/AddAllItems.py
Python
apache-2.0
20,874
0.007857
#Copyright (c) 2014 Sony Computer Entertainment America LLC. See License.txt. import sys sys.path.append("./CommonTestScripts") import Test doc = atfDocService.OpenNewDocument(editor) #===================== 0: root ================================== Test.Equal(0, Test.GetEnumerableCount(treeLister.TreeView.GetChil...
root child count does not increase when adding a sprite") editingContext.Insert[UITextItem](DomNode(UISchema.UITextItemType.Type), treeLister.TreeView.DomNode) Test.Equal(1, Test.GetEnumerableCount(treeLister.TreeView.GetChildren(treeLister.TreeView.DomNode)), "Verify root child count does not increase when adding a te...
ext.Insert[UIAnimation](DomNode(UISchema.UIAnimationType.Type), treeLister.TreeView.DomNode) Test.Equal(1, Test.GetEnumerableCount(treeLister.TreeView.GetChildren(treeLister.TreeView.DomNode)), "Verify root child count does not increase when adding an animation") #===================== 1: Package ====================...
thunderhoser/GewitterGefahr
gewittergefahr/prediction_paper_2019/make_predictor_figure.py
Python
mit
17,810
0.000842
"""Makes figure with GridRad and MYRORSS predictors.""" import argparse import numpy import matplotlib matplotlib.use('agg') import matplotlib.pyplot as pyplot from gewittergefahr.gg_utils import soundings from gewittergefahr.gg_utils import radar_utils from gewittergefahr.gg_utils import time_conversion from gewitter...
ergefahr.plotting import imagemagick_utils from gewittergefahr.scripts import plot_input_examples as plot_examples SEPARATOR_STRING = '\n\n' + '*' * 50 + '\n\n' MINOR_SEPARATOR_STRING = '\n\n' + '-' * 50 + '\n\n' TIME_FORMAT = '%Y-%m-%d-%H%M%S' DUMMY_TARGET_NAME = 'tornado_lead-time=0000-3600sec_distance=00000-10000m...
soundings.U_WIND_NAME, soundings.V_WIND_NAME, soundings.TEMPERATURE_NAME, soundings.SPECIFIC_HUMIDITY_NAME, soundings.PRESSURE_NAME ] SOUNDING_HEIGHTS_M_AGL = soundings.DEFAULT_HEIGHT_LEVELS_M_AGL NUM_GRIDRAD_ROWS = 32 NUM_GRIDRAD_COLUMNS = 32 RADAR_HEIGHTS_M_AGL = numpy.array([3000], dtype=int) GRIDRAD_FIEL...
staute/shinken_deb
shinken/util.py
Python
agpl-3.0
24,533
0.001141
# -*- coding: utf-8 -*- # Copyright (C) 2009-2014: # Gabes Jean, naparuba@gmail.com # Gerhard Lausser, Gerhard.Lausser@consol.de # Gregory Starck, g.starck@gmail.com # Hartmut Goebel, h.goebel@goebel-consult.de # # This file is part of Shinken. # # Shinken is free software: you can redistribute it and/...
), t return res # ################################## TIME ################################## # @memoized def get_end_of_day(
year, month_id, day): end_time = (year, month_id, day, 23, 59, 59, 0, 0, -1) end_time_epoch = time.mktime(end_time) return end_time_epoch # @memoized def print_date(t): return time.asctime(time.localtime(t)) # @memoized def get_day(t): return int(t - get_sec_from_morning(t)) # Same but for wee...
mgraupe/acq4
acq4/modules/DataManager/FileDataView.py
Python
mit
3,567
0.00841
# -*- coding: utf-8 -*- from PyQt4 import QtCore, QtGui from acq4.util.DataManager import * #import acq4.Manager as Manager import acq4.pyqtgraph as pg #from acq4.pyqtgraph.MultiPlotWidget import MultiPlotWidget #from acq4.pyqtgraph.ImageView import ImageView from acq4.util.DictView import * import acq4.util.metaarray...
self.widgets[0].setImage(data, autoRange=False) except: print "widget types:", map(type, self.widgets) raise else: self.clear() w = pg.ImageView(self) #print "add...
Image(data) self.widgets.append(w) self.currentType = 'image' else: self.clear() w = pg.MultiPlotWidget(self) self.addWidget(w) w.plot(data) self.currentType = 'plot' self.widg...
Jcing95/iop-hd
test/functional/mining.py
Python
mit
5,574
0.002153
#!/usr/bin/env python3 # Copyright (c) 2014-2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test mining RPCs - getmininginfo - getblocktemplate proposal mode - submitblock""" import copy from b...
inal') self.log.info("getblocktemplate: Test bad tx count") # The tx count is immediately after the block header TX_COUNT_OFFSET = 80 bad_block_sn = bytearray(block.serialize()) assert_equal(bad_block_sn[TX_COUNT_OFFSET], 1) bad_block_sn[TX_COUNT_OFFSET] += 1 ass...
a': b2x(bad_block_sn), 'mode': 'proposal'}) self.log.info("getblocktemplate: Test bad bits") bad_block = copy.deepcopy(block) bad_block.nBits = 469762303 # impossible in the real world assert_template(node, bad_block, 'bad-diffbits') self.log.info("getblocktemplate: Test bad m...
makhidkarun/py_tools
lib/ship_crew.py
Python
gpl-3.0
852
0.026995
""" ship_crew.py Generates a minimal ship crew based on tonnage. python crew -s 400 """ from __future__ import print_function import random import sys sys.path.append(".") from character import Character import character_tools def get_career(): return random.choice(['Scouts', 'Navy', 'Merchants'
]) def create_crew(size): for c in range(int(size/400)): create_crewman("Pilot") create_crewman("Navg") for c in range(int(size/300)): create_crewman("Eng") def create_crewman(role): if role == "Eng": skill = "Engineering" elif role == "Navg": skill = "Navgigation" elif role == "Helm"...
") crew.display() print("")
Ledoux/ShareYourSystem
Pythonlogy/draft/Noders/Grouper/Drafts/__init__ copy.py
Python
mit
4,755
0.04837
# -*- coding: utf-8 -*- """ <DefineSource> @Date : Fri Nov 14 13:20:38 2014 \n @Author : Erwan Ledoux \n\n </DefineSource> A Grouper establishes a group of parenting nodes for which each level is setted in equivalent hdf5 structure. """ #<DefineAugmentation> import ShareYourSystem as SYS BaseModuleStr="ShareYour...
): #Definition RepresentingKeyStrsList=[ 'GroupedParentVariable', 'GroupedInt', 'GroupedKeyStr', 'GroupedDeriveParentersList', 'GroupedPathStrsList', 'GroupedPathStr' ]
#@Hooker.HookerClass(**{'HookingAfterVariablesList':[{'CallingVariable':BaseClass.__init__}]}) def default_init( self, _GroupedParentVariable=None, _GroupedInt=-1, _GroupedKeyStr="", _GroupedDeriveParentersList=None, _GroupedPathStrsList=None, _GroupedPathStr="/", **_KwargVariablesDi...
sysadminmatmoz/odoo-clearcorp
account_exchange_rates_adjustment/__init__.py
Python
agpl-3.0
1,086
0
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Addons modules by CLEARCORP S.A. # Copyright (C) 2009-TODAY CLEARCORP S.A. (<http://clearcorp.co.cr>). # # This program is free software: you can redistribute...
ived a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ##############################
################################################ import account_exchange_rates_adjustment import wizard
legoktm/pywikipedia-rewrite
scripts/i18n/isbn.py
Python
mit
10,492
0.047954
# -*- coding: utf-8 -*- msg = { 'en': { 'isbn-formatting': u'Robot: Formatting ISBN', }, # Author: Csisc # Author: Lloffiwr # Author: Xqt 'qqq': { 'isbn-formatting': u'Edit summary when the bot fixes [http://en.wikipedia.org/wiki/International_Standard_Book_Number ISBN] number formatting.', }, # Author: Csi...
'it': { 'isbn-formatting': u'Bot: Formatto ISBN', }, # Author: Fryed-peach # Author: Shirayuki 'ja': { 'isbn-formatting': u'ロボットによる: ISBN の整形', }, # Author: NoiX180
'jv': { 'isbn-formatting': u'Bot: Mormat ISBN', }, # Author: 아라 'ko': { 'isbn-formatting': u'로봇: ISBN 형식 지정', }, # Author: Purodha 'ksh': { 'isbn-formatting': u'Bot: ISBN zerääsch jemaat.', }, # Author: George Animal 'ku': { 'isbn-formatting': u'Robot:ISBN\'ê format bike', }, # Author: Robby 'lb':...
alexanderfefelov/nav
python/nav/web/portadmin/views.py
Python
gpl-2.0
20,814
0
# # Copyright 2010 (C) Norwegian University of Science and Technology # # This file is part of Network Administration Visualized (NAV). # # NAV is free software: you can redistribute it and/or modify it under # the terms of the GNU General Public License version 2 as published by # the Free Software Foundation. # # Thi...
ndex'))] if additional_paths: navpath += additional_paths form = form if form else SearchForm() return { 'header': {'name': 'PortAdmin', 'description': 'Configure interfaces on ip devices'}, 'navpath': navpath, 'title': create_title(navpat
h), 'form': form } def index(request): """View for showing main page""" netboxes = [] interfaces = [] if 'query' in request.GET: form = SearchForm(request.GET) if form.is_valid(): netboxes, interfaces = search(form.cleaned_data['query']) if len(netbo...
Tatsh-ansible/ansible
lib/ansible/plugins/action/include_vars.py
Python
gpl-3.0
10,206
0.001372
# (c) 2016, Allen Sanabria <asanabria@linuxdynasty.org> # # This file is part of Ansible # # Ansible 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. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public Licens...
tylereaves/26md
setlist/migrations/0013_show2.py
Python
bsd-3-clause
970
0.002062
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('setlist', '0012_remove_show_leg'), ] operations = [ migrations.CreateModel( name='Show2', fields=[ ...
eld(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('venue', models.ForeignKey(to='setlist.Venue', to_field='id')), ('tour', models.ForeignKey(to='setlist.Tour', to_field='id')), ('date', models.DateField(db_in
dex=True)), ('setlist', models.TextField(default=b'', blank=True)), ('notes', models.TextField(default=b'', blank=True)), ('source', models.TextField(default=b'', blank=True)), ], options={ }, bases=(models.Model,), ...
sio2project/oioioi
oioioi/disqualification/urls.py
Python
gpl-3.0
139
0
#
Force loading views from oioioi.disqualification.views import disqualification_fragment app_name = 'disqualification' urlpatterns =
()
etalab/cowbots
email_changes.py
Python
agpl-3.0
16,025
0.016047
#! /usr/bin/env python # -*- coding: utf-8 -*- # CowBots -- Error detection bots for CKAN-of-Worms # By: Emmanuel Raviart <emmanuel@raviart.com> # # Copyright (C) 2013 Etalab # http://github.com/etalab/cowbots # # This file is part of CowBots. # # CowBots is free software; you can redistribute it and/or modify # it u...
conv.not_none, ), }, default = 'drop', ), conv.not_none, ))(dict(config_parser.items('CowBots-Email-Changes')), conv.def
ault_state) cache_dir = os.path.join(app_dir, 'cache') if not os.path.exists(cache_dir): os.makedirs(cache_dir) global headers headers = { 'User-Agent': conf['user_agent'],
Foris/darwined-core-python-clients
darwined_core_python_clients/physical/buildings.py
Python
mit
2,117
0
import json import requests class Building(): """Building Client.""" # Service Setup config = { 'schema': 'http', 'host': 'localhost', 'port': '9202', 'endpoint': 'api/v1/buildings' } @classmethod def base_url(cls): """Form the base url for the service...
None @classmethod def create(cls, attrs): """Create an building with the attributes passed in attrs dict.""" r = requests.post(cls.base_url(), data=json.dumps(attrs)) if r.status_code == 200: return r.json() else: return None @classmethod def upd...
+ code, data=json.dumps(attrs)) if r.status_code == 200: return r.json() else: return None @classmethod def delete(cls, code): """Delete the building identified by code.""" r = requests.delete(cls.base_url() + '/' + code) return r.status_code == 2...
CrazyDaiDai/learningPython
hellow.py
Python
gpl-3.0
1,589
0.019119
#!/usr/bin/env python3 #定义一个变量a a = 100 #判断a是否大于等于0 if a >= 100: # 如果大于等于0执行这里边的内容 print('a为正 a =',a) else: # 反之执行这段代码 print('a为负 a =',a) # #转义字符 # print("I'm OK") print('I\'m OK') print('I\'m\tlearning\nPython') # 使用 r'' 来使 '' 里边的字符串不需要转 // 但是这样不行 --> print(r'I'm OK') print(r'\\n\\') # 如果有很多换行的地方可以使用 ...
3 > 2 and 1 > 2 -->",3 > 2 and 1 > 2
) print("2 > 3 and 1 > 2 -->",2 > 3 and 1 > 2) # or 只要一个为真 则真 反之假 print("3 > 2 or 2 > 1 -->",3 > 2 or 2 > 1) print("3 > 2 or 1 > 2 -->",3 > 2 or 1 > 2) print("2 > 3 or 1 > 2 -->",2 > 3 or 1 > 2) # not 取反 print("not 3 > 2 -->",not 3 > 2) print("not 2 > 3 -->",not 2 > 3) # None 在Python里边是一个特殊的值,None不能理解为0 因为0是有意义的,而None...
netkicorp/wns-api-server
netki/util/__init__.py
Python
bsd-3-clause
23
0.043478
__author__ = 'md
avid
'
Omrigan/diseases
diseases/migrations/0001_initial.py
Python
mit
1,149
0.003481
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Case', fields=[ ('id', models.AutoField(primary...
], ), migrations.CreateModel( name='Disease', fields=[ ('id', models.AutoField(primary_key=True, serialize=False, auto_created=True, verbose_name='ID')), ('title', models.CharField(max_length=1000)), ('dateCreation', models....
('description', models.CharField(max_length=4000)), ], ), ]
helfertool/helfertool
src/badges/migrations/0004_auto_20160306_1424.py
Python
agpl-3.0
638
0.001567
# -*- coding: utf-8 -*- # Generated by Django 1.9.4 on 2016-03-06 13:24 from __future__ import unicode_literals import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('badges', '0003_badgedesign_bg_color'), ] operations = ...
[django.core.validators.RegexValidator('^#[a-fA-F0-9]{6}$')], verbose_name='Background color'), ),
]
sadnoodles/chromeremote
examples/xssbot.py
Python
gpl-3.0
2,168
0
# coding=utf-8 ''' xssbot 必须具有以下功能 1.可对指定url进行访问 2.拦截alert等框框 3.拦截页内跳转 4.锁定设定cookies(未实现) 在EditThisCookie的chrome扩展中使用扩展特有的接口实现 chrome.cookies.onChanged.addListener 但在https://chromedevtools.github.io/devtools-protocol/文档中并没有相关类似功能、 ''' from chromeremote import ChromeTabThread as ChromeTab ...
(ChromeTab): # 一个页面允许运行10秒 TAB_TIMEOUT = 10 def __init__(self, url, host, port): super(XssbotTab, self).__init__(host, port) self.opened = False self.url = url self.ini
tjs = ''' window.alert =function(){}; window.confirm =function(){}; window.prompt = function(){}; window.open= function(){}; ''' def run(self): def processNavigation(para): # 仅处理第一次我们跳转,其他禁止跳转 if self.opened: response = 'CancelAndIgnore' else:...
NejcZupec/ggrc-core
src/ggrc/models/category.py
Python
apache-2.0
1,823
0.013165
# Copyright (C) 2016 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> from ggrc import db from sqlalchemy.ext.associationproxy import association_proxy from sqlalchemy.orm import validates from .categorization import Categorization from .mixins import deferred, Base, Hierarch...
e='all, delete-orphan', ) @validates('type') def validates_type(self, key, value): return self.__class__.__name__
# REST properties _publish_attrs = [ 'name', 'type', 'required', #'scope_id', ] _sanitize_html = [ 'name', ] @classmethod def eager_query(cls): from sqlalchemy import orm query = super(CategoryBase, cls).eager_query() return query.options()
azaghal/ansible
test/support/integration/plugins/modules/openssl_csr.py
Python
gpl-3.0
53,940
0.004301
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyrigt: (c) 2017, Yanis Guenane <yanis+ansible@guenane.org> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_ve...
separated string' or a YAML list. - Values must be prefixed by their options. (i.e., C(email), C(URI), C(DNS), C(RID), C(IP), C(dirName), C(otherName) and the ones specific to your CA) - Note that if no SAN is specified, but a common name, the common name will be add...
ls.ietf.org/html/rfc5280#section-4.2.1.6). type: list elements: str aliases: [ subjectAltName ] subject_alt_name_critical: description: - Should the subjectAltName extension be considered as critical. type: bool aliases: [ subjectAltName_critical ] use...
greysondn/gamesolutions
twilioquest/python/codepath/functions.py
Python
mit
644
0.006211
# TwilioQuest version 3.1.26
# Works in: # 3.1.26 # bog standard main function def main(): print("functions") hail_friend() print("function arguments") hail_friend("Operator") print("function return values") print(f"{add_numbers(45, -1)}") # functions the tasks demand def add_numbers(num1, num2): return num1 + nu...
tion challenge if (None == name): print("Hail, friend!") else: # use given value to pass argument challenge print(f"Hail, {name}!") # standard main guard if ("__main__" == __name__): main()
adapteva/epiphany-gdb
gdb/copyright.py
Python
gpl-2.0
11,525
0.000954
#! /usr/bin/env python # Copyright (C) 2011-2012 Free Software Foundation, Inc. # # This file is part of GDB. # # 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, ...
c", "sim/arm/bag.c", "sim/arm/armvirt.c", "sim/arm/main.c", "sim/arm/bag.h", "sim/arm/communicate.c", "sim/arm/gdbhost.h", "sim/arm/armfpe.h", "sim/arm/arminit.c", "sim/common/cgen-fpu.c",
"sim/common/cgen-fpu.h", "sim/common/cgen-fpu.h", "sim/common/cgen-accfp.c", "s
tedlaz/pyted
tests/pysqlqt/src/classes/json_data.py
Python
gpl-3.0
4,956
0
""" @file @brief This file loads and saves settings (as JSON) @author Ted Lazaros <tedlaz@gmail.com> @section LICENSE """ try: import json except ImportError: import simplejson as json import copy from classes.logger import log class JsonDataStore: """ This class which allow...
object is a dictionary (i.e. project data) for key in default: if key not in user: # Add missing key to user dictionary user[key] = default[key] # Return merged dictionary return user def read_fro
m_file(self, file_path): """ Load JSON settings from a file """ # log.debug("loading {}".format(file_path)) try: with open(file_path.encode('UTF-8'), 'r') as f: contents = f.read() if contents: # log.debug("loaded", contents)...
a143753/AOJ
1576.py
Python
apache-2.0
497
0.026157
[m,n]
= map(int,input().split()) def find(v,cs): for c in cities: if v in c: return (True,c) return (False,set([v])) cities = [] for _ in range(n): [a,b] = map(int,input().split()) (ra,fa) = find(a,cities) (rb,fb) = find(b,cities) mg = fa | fb if ra: cities.remove...
cities)))
zneak/capstone
bindings/python/setup.py
Python
bsd-3-clause
6,134
0.001304
#!/usr/bin/env python import glob import os import platform import shutil import stat import sys from distutils import log from distutils import dir_util from distutils.command.build_clib import build_clib from distutils.command.sdist import sdist from distutils.core import setup from distutils.sysconfig import get_py...
os.system("nmake") os.chdir("..") SETUP_DATA_FILES.append("src/build/capstone.dll") elif SYSTEM == "cygwin": os.chmod("make.sh", stat.S_IREAD|stat.S_IEXEC) if is_64bits: os.system("CAPSTONE_BU...
else: os.system("CAPSTONE_BUILD_CORE_ONLY=yes ./make.sh cygwin-mingw32") SETUP_DATA_FILES.append("src/capstone.dll") else: # Unix os.chmod("make.sh", stat.S_IREAD|stat.S_IEXEC) os.system("CAPSTONE_BUILD_CORE_ON...
jimkmc/micropython
tools/make-frozen.py
Python
mit
1,041
0.000961
#!/usr/bin/env python3 # # Create frozen modules structure for MicroPython. # # Usage: # # Have a directory with modules to be frozen (only modules, not packages # supported so far): # # frozen/foo.py # frozen/bar.py # # Run script, passing path to the directory above: # # ./make-frozen.py frozen > frozen.c # # Include...
ame(f): return f[:-len(".py")] modules = [] for dirpath, dirnames, filenames in os.walk(sys.argv[1]): for f in filenames: st = os.stat(dirpath + "/" + f) modules.append((f, st)) print("#include <stdint.h>") print("const uint16_t mp_frozen_sizes[] = {") for f, st in modules: print("%d," %...
e) print("0};") print("const char mp_frozen_content[] = {") for f, st in modules: m = module_name(f) print('"%s\\0"' % m) data = open(sys.argv[1] + "/" + f).read() data = repr(data)[1:-1] data = data.replace('"', '\\"') print('"%s"' % data) print("};")
Ingenico-ePayments/connect-sdk-python2
ingenico/connect/sdk/meta_data_provider.py
Python
mit
5,912
0.001522
import platform from base64 import b64encode import re from ingenico.connect.sdk.data_object import DataObject from ingenico.connect.sdk.defaultimpl.default_marshaller import \ DefaultMarshaller from ingenico.connect.sdk.domain.metadata.shopping_cart_extension import ShoppingCartExtension from request_header impor...
sion is not N
one: dictionary['shoppingCartExtension'] = self.shopping_cart_extension.to_dictionary() return dictionary def from_dictionary(self, dictionary): super(MetaDataProvider.ServerMetaInfo, self).from_dictionary(dictionary) if 'platformIdentifier' in dictionary: ...
zeldin/libsigrokdecode
decoders/timing/pd.py
Python
gpl-3.0
4,356
0.005282
## ## This file is part of the libsigrokdecode project. ## ## Copyright (C) 2014 Torsten Duwe <duwe@suse.de> ## Copyright (C) 2014 Sebastien Bourdelin <sebastien.bourdelin@savoirfairelinux.com> ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public Lic...
, 'desc': 'Data line'}, ) annotations = ( ('time', 'Time'), ('average', 'Average'), ) annotation_rows = ( ('time', 'Time', (0,)), ('average', 'Average', (1,)), ) options = ( { 'id': 'avg_period', 'desc': 'Averaging period', 'default': 100 }, ) def...
que() self.chunks = 0 def metadata(self, key, value): if key == srd.SRD_CONF_SAMPLERATE: self.samplerate = value def start(self): self.out_ann = self.register(srd.OUTPUT_ANN) self.initial_pins = [0] def decode(self): if not self.samplerate: ...
creative-workflow/pi-setup
lib/piservices/policies.py
Python
mit
867
0.023068
import sys, os, fabric class PiServicePolicies: @staticmethod def is_local(): return (not fabric.api.env.hosts or fabric.api.env.hosts[0] in ['localhost', '127.0.0.1', '::1']) @staticmethod def is_pi(): return os.path.isdir('/home/pi') @staticmethod def check_local_or_exit(): if not PiService...
able on localhost!!!" sys.exit(-1) @staticmethod def check_remote_or_exit(): if PiServicePolicies.is_local(): print "...only callable on remote host!!!" sys.exit(-1) def check_installed_or_exit(self): if not PiServicePolicies.installed(self): print "...first you have to install t...
t: print self.name+' not installed' return ret
superdyzio/PWR-Stuff
AIR-ARR/Projekt Zespołowy/catkin_ws/devel/lib/python2.7/dist-packages/geographic_msgs/srv/_GetGeographicMap.py
Python
mit
33,019
0.015385
"""autogenerated by genpy from geographic_msgs/GetGeographicMapRequest.msg. Do not edit.""" import sys python3 = True if sys.hexversion > 0x03000000 else False import genpy import struct import geographic_msgs.msg class GetGeographicMapRequest(genpy.Message): _md5sum = "505cc89008cb1745810d2ee4ea646d6e" _type = "...
self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(_x)))) except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(_x)))
) def deserialize(self, str): """ unpack serialized message in str into this message instance :param str: byte array of serialized message, ``str`` """ try: if self.bounds is None: self.bounds = geographic_msgs.msg.BoundingBox() end = 0 start = end end += 4 (...
CodeLionX/CommentSearchEngine
cse/reader/ArticleMappingReader.py
Python
mit
1,729
0.009254
import csv import os class ArticleMappingReader(object): def __init__(self, arcticlesFilepath, delimiter=','): self.__delimiter = delimiter self.__articlesFilepath = arcticlesFilepath self.__articlesFile = None self.__articlesReader = None self.__currentArticleData = None...
) return self def close(self): self.__articlesFile.close() def currentArticleId(self): return self.__currentArticleData[0] def currentArticleUrl(self): return self.__currentArticleData[1] def __parseIterRow(self, row): articleId = int(row[0]) artic...
self.__articlesFile.seek(0) iter(self.__articlesReader) # skip csv header in iteration mode: next(self.__articlesReader) return self def __next__(self): self.__currentArticleData = self.__parseIterRow(next(self.__articlesReader)) return self.__currentArticleDa...
mneary1/YGOPricesAPI
prices.py
Python
mit
2,551
0.000784
import requests class YGOPricesAPI(): def __init__(self): self.url = "http://yugiohprices.com/api" def __make_request(self, url): """Request a resource from api""" request = requests.get(url) if request.status_code != 200: status_code = request.status_code ...
reason}') return request.json() def get_price_by_name(self, name): """Retrieves price data for every version of a card using its name""" url = f"{self
.url}/get_card_prices/{name}" return self.__make_request(url) def get_price_by_tag(self, tag, rarity=None): """Retrieve price data for a specific version of a card using its print tag""" if rarity: url = f"{self.url}/price_history/{tag}?rarity={rarity}" else: ...
openstack/compute-hyperv
compute_hyperv/nova/imagecache.py
Python
apache-2.0
11,925
0
# Copyright 2013 Cloudbase Solutions Srl # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless r...
rue, lock_path=base_image_dir) def fetch_image_if_not_existing(): fetched = False image_path = No
ne for format_ext in ['vhd', 'vhdx', 'iso']: test_path = base_image_path + '.' + format_ext if self._pathutils.exists(test_path): image_path = test_path self._update_image_timestamp(image_id) break if no...
lmazuel/azure-sdk-for-python
azure-mgmt-logic/azure/mgmt/logic/models/integration_account_map_paged.py
Python
mit
926
0.00108
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
IntegrationAccountMap object """ _attribute_map = { 'next_link': {'key': 'nextLink', 'type': 'str'}, 'current_page': {'key': 'value', 'type': '[Int
egrationAccountMap]'} } def __init__(self, *args, **kwargs): super(IntegrationAccountMapPaged, self).__init__(*args, **kwargs)
buchwj/xvector
client/xVClient/ui/LoginWidgetUI.py
Python
gpl-3.0
11,829
0.004734
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'LoginWidget.ui' # # Created: Wed Jul 13 22:46:23 2011 # by: PyQt4 UI code generator 4.8.3 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except Att...
etHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(LoginWidget.sizePolicy().hasHeightForWidth(
)) LoginWidget.setSizePolicy(sizePolicy) self.verticalLayout = QtGui.QVBoxLayout(LoginWidget) self.verticalLayout.setObjectName(_fromUtf8("verticalLayout")) self.formTabs = QtGui.QTabWidget(LoginWidget) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy...
kvar/ansible
lib/ansible/modules/network/fortios/fortios_system_replacemsg_traffic_quota.py
Python
gpl-3.0
10,207
0.001568
#!/usr/bin/python from __future__ import (absolute_import, division, print_function) # Copyright 2019 Fortinet, Inc. # # 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 Lic...
else: fos.https('on') fos.login(host, username, password, verify=ssl_verify) def filter_system_replacemsg_traffic_quota_data(json): option_list = ['buffer', 'format', 'header', 'msg_type'] dictionary = {} for attribute in option_list: if attribute in json and ...
urn dictionary def underscore_to_hyphen(data): if isinstance(data, list): for elem in data: elem = underscore_to_hyphen(elem) elif isinstance(data, dict): new_data = {} for k, v in data.items(): new_data[k.replace('_', '-')] = underscore_to_hyphen(v) dat...
thierry1985/project-1022
domains/driverlogshift/readsetting.py
Python
mit
965
0.048705
#!/usr/bin/python import re,os def compare_file(x,y): dr = re.compile(r"[\S]+?([0-9]+)[\S]+") orderx = -1 ordery = -1 m = dr.match(x) if m: orderx = int(m.group(1)) m = dr.match(y) if m: ordery = int(m.group(1)) if orderx == -1 or ordery== -1: return 0 if orderx>ordery: return 1 elif orderx==ordery: ...
.strip() l = line.split("-")[0] l.strip() if "truck" in t:
print "truck ", l.count("truck"), elif "driver" in t: print "driver", l.count("driver"), elif "obj" in t: print "Object ", l.count("package"), print "--- ",f
guilhermefloriani/signature-recognition
network.py
Python
mit
4,512
0.005319
import numpy as np import random class NeuralNetwork(): def __init__(self, sizes): # sizes is an array with the number of units in each layer # [2,3,1] means w neurons of input, 3 in the hidden layer and 1 as output self.num_layers = len(sizes) self.sizes = sizes # the syn...
e_variable return [training_data[i:i + batch_size] for i in r
ange(0, n, batch_size)] def update_batches(self, batches, alpha): for batch in batches: nabla_b = [np.zeros(b.shape) for b in self.biases] nabla_w = [np.zeros(w.shape) for w in self.weights] m = len(batch) # x is a array of length 901 # y is a s...
ASCIT/donut-python
donut/modules/calendar/permissions.py
Python
mit
251
0
import enum class calendar_permissions(enum.IntEnum): ASCIT = 21 AVERY = 22 BECHTEL = 23 BLACKER = 24 DABNEY = 25 FLEMING = 2
6 LLOYD = 27 PAGE = 28 RICKETTS = 29 RUDDOCK = 30 OTHER = 31
ATHLETICS = 32
selimnairb/2014-02-25-swctest
lessons/thw-python-debugging/basic_exceptions/syntax_error.py
Python
bsd-2-clause
223
0.008969
#!/usr/bin/env python """ SyntaxError -
There's something wrong with how you wrote the surrounding code. Check your parentheses, and make sure there are colons where nee
ded. """ while True print "Where's the colon at?"
rahulunair/nova
nova/tests/functional/api_sample_tests/test_instance_actions.py
Python
apache-2.0
5,930
0
# Copyright 2012 Nebula, Inc. # Copyright 2013 IBM Corp. # # 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...
_version': 'v2.1'})] class ServerActionsV251NonAdminSampleJsonTest(ServerAc
tionsSampleJsonTest): """Tests the 2.51 microversion for the os-instance-actions API. The 2.51 microversion allows non-admins to see instance action event details *except* for the traceback field. The tests in this class are run as a non-admin user so all fields except for the ``traceback`` field ...
nickraptis/fidibot
src/modules/help.py
Python
bsd-2-clause
2,615
0.000765
# Author: Nick Raptis <airscorp@gmail.com> """ Module for listing commands and help. """ from basemodule import BaseModule, BaseCommandContext from alternatives import _ class HelpContext(BaseCommandContext): def cmd_list(self, argument): """List commands""" arg = argument.lower() index ...
lf.send(target, _("No help for %s"), args[0]) else: args.append("") cmd = args.pop(0)
cmd_type = args.pop(0) if 'pu' in cmd_type or self.target.startswith('#'): cmd_type = 'public' elif 'pr' in cmd_type or not self.target.startswith('#'): cmd_type = 'private' else: # we shouldn't be here self.lo...
stefwalter/cockpit
test/common/cdp.py
Python
lgpl-2.1
9,003
0.002777
# -*- coding: utf-8 -*- import fcntl import glob import json import os import random import shutil import socket import subprocess import sys import tempfile import time TEST_DIR = os.path.normpath(os.path.dirname(os.path.realpath(os.path.join(__file__, "..")))) def browser_path(headless=True): """Return path t...
s.check_output("which chromium-browser || which chromium || which google-chrome || true", shell=True).strip() if p: return p p = os.path.join(os.path.dirname(TEST_DIR), "node_modules/chromium/lib/chromium/chrome-linux/chrome") if os.access(p, os.X_OK): return p return None def jsquote...
elpers=[]): self.lang = lang self.timeout = 60 self.valid = False self.headless = headless self.verbose = verbose self.trace = trace self.inject_helpers = inject_helpers self._driver = None self._browser = None self._browser_home = None ...
vahtras/loprop
tests/test_bond.py
Python
gpl-3.0
7,956
0.005279
import numpy as np STR_NOBOND = """AU 3 1 2 1 1 0.00000000 0.00000000 0.00000000 -0.66387672 0.00000000 -0.00000000 0.34509720 3.78326969 -0.00000000 -0.00000000 3.96610412 0.00000000 3.52668267 0.00000000 -0.00000000 -2.98430053 0.00000000 -0.00000000 ...
: 0.45 (cpu) 0.11 (wall) """ STR_BOND = """AU 5 1 22 1 1 0.00
000000 0.00000000 0.00000000 -0.66387672 0.00000000 -0.00000000 0.41788500 1.19165567 0.00000000 0.00000000 2.74891057 0.00000000 1.33653383 0.00000000 0.00000000 4.18425484 0.00000000 -0.00000000 -0.00000000 -0.00000000 0.19037387 0.0000000...
fanglinfang/myuw
myuw/test/cache.py
Python
apache-2.0
5,375
0
from django.test import TestCase from restclients.mock_http import MockHTTP from myuw.util.cache_implementation import MyUWCache from restclients.models import CacheEntryTimed from datetime import timedelta CACHE = 'myuw.util.cache_implementation.MyUWCache' class TestCustomCachePolicy(TestCase): def test_sws_de...
cache
_entry.time_saved = (orig_time_saved - timedelta(minutes=(60 * 4)+1)) cache_entry.save() response = cache.getCache('sws', '/student/myuwcachetest1', {}) self.assertEquals(response, None) def test_sws_term_policy(self): with self.set...
MieRobot/Blogs
Blog_LinearRegression.py
Python
gpl-3.0
1,518
0.009223
# coding: utf-8 # In[2]: # Import and read the datset import numpy as np from sklearn import linear_model import matplotlib.pyplot as plt import pandas as pd dataset = pd.read_csv("C://Users//Koyel//Desktop/MieRobotAdvert.csv") dataset.head() # In[3]: dataset.describe() # In[4]: dataset.columns # In[5]: i...
rn.model_selection import train_test_split # In[10]: X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=101) # In[11]: from sklearn.linear_model import LinearRegression # In[12]: lm = LinearRegression() # In[13]: lm.fit(X_train,y_train) # In[14]: print(lm.intercept_) ...
redict(X_test) # In[26]: plt.ylabel("likes predicted") plt.title("Likes predicated for MieRobot.com blogs",color='r') plt.scatter(y_test,predictions) # In[23]: print (lm.score) # In[19]: sns.distplot((y_test-predictions),bins=50); # In[20]: from sklearn import metrics print('MAE:', metrics.mean_absolute_err...
dprog-philippe-docourt/django-qr-code
qr_code/qrcode/utils.py
Python
bsd-3-clause
30,602
0.003171
"""Utility classes and functions for configuring and setting up the content and the look of a QR code.""" import datetime import decimal from collections import namedtuple from dataclasses import dataclass, asdict from datetime import date from typing import Optional, Any, Union, Sequence from django.utils.html import...
ult is *'M'*.
:param bool boost_error: Tells whether the QR code encoding engine tries to increase the error correction level if it does not affect the version. Error correction level is not increased when it impacts the version of the code. :param bool micro: Indicates if a Micro QR Code should be c...
jumpstarter-io/horizon
openstack_dashboard/dashboards/admin/images/properties/forms.py
Python
apache-2.0
3,269
0.000612
# 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 # d...
cept Exception: msg = _('Unable to create image custom ' 'property "%s".') % data['key'] exceptions.handle(request, msg) class EditProperty(forms.SelfHandlingForm): key = forms.CharField(widget=forms.wid
gets.HiddenInput) value = forms.CharField(label=_("Value")) def handle(self, request, data): try: api.glance.image_update_properties(request, self.initial['image_id'], **{data['key']: convert_value(data['key'], data['value'])}) msg = _('Saved cust...
souravbadami/oppia
schema_utils_test.py
Python
apache-2.0
25,162
0.000318
# coding: utf-8 # # Copyright 2014 The Oppia Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requi...
}] }, 'coding_mode': { 'type': SCHEMA_TYPE_UNICODE, 'choices': ['none', 'python', 'coffee
script'], }, 'placeholder': { 'type': SCHEMA_TYPE_UNICODE, }, }, } # Schemas for validators for the various types. VALIDATOR_SPECS = { SCHEMA_TYPE_BOOL: {}, SCHEMA_TYPE_DICT: {}, SCHEMA_TYPE_FLOAT: { 'is_at_least': { 'min_value': { ...
hainm/elyxer
src/elyxer/gen/layout.py
Python
gpl-3.0
10,103
0.010792
#! /usr/bin/env python # -*- coding: utf-8 -*- # eLyXer -- convert LyX source files to HTML output. # # Copyright (C) 2009 Alex Fernández # # 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 Foundat...
TaggedText().complete(self.contents, 'span
class="List-contents"') self.contents = [first, second] class PlainLayout(Layout): "A plain layout" def process(self): "Output just as contents." self.output = ContentsOutput() self.type = 'Plain' def makevisible(self): "Make the layout visible, output as tagged text." self.output = Tag...
tkuriyama/jsonutils
jsonutils/lws/test/test_lws_logger.py
Python
mit
3,990
0
"""Test cases for JSON lws_logger module, assumes Pytest.""" from jsonutils.lws import lws_logger class TestDictToTreeHelpers: """Test the helper functions for dict_to_tree.""" def test_flatten_list(self): """Test flattening of nested lists.""" f = lws_logger.flatten_list nested = [1...
lws_logger.filter_keys errors = {'key': 99, 'key_str': 'key error', 'val': -99,
'val_str': 'val error'} pairs = [('a', 'hi'), ('a', 99), ('b', 'hi')] filtered = [('a', 'hi'), ('b', 'hi')] assert f(pairs, errors) == filtered def test_filter_errors_multiple(self): """Test list error term filtering, multiple errors.""" f = lws_logger.filter_keys ...
Tusky/DjangoSample
blog/views.py
Python
mit
2,273
0.00088
from django.contrib import messages from django.contrib.auth.decorators import login_required from django.db.models import Q from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404 from django.urls import reverse from django.utils.decorators import method_decorator from django.views....
e == 'user': qs = qs.filter(posted_by__user
name=self.kwargs.get('slug', '')) elif type_of_page == 'category': qs = qs.filter(categories__slug=self.kwargs.get('slug', '')) if search_query: qs = qs.filter(Q(title__icontains=search_query) | Q(content__icontains=search_query)) return qs class SinglePost(DetailView):...
lidavidm/mathics-heroku
venv/lib/python2.7/site-packages/sympy/printing/gtk.py
Python
gpl-3.0
510
0.003922
from __future__ import with_statement from sympy.printin
g.mathml import mathml import tempfile import os def print_gtk(x, start_viewer=True): """Print to Gtkmathview, a gtk widget capable of rendering Ma
thML. Needs libgtkmathview-bin""" from sympy.utilities.mathml import c2p tmp = tempfile.mktemp() # create a temp file to store the result with open(tmp, 'wb') as file: file.write( c2p(mathml(x), simple=True) ) if start_viewer: os.system("mathmlviewer " + tmp)
thebachchaoproject/bachchao-server
pahera/PythonModules/CheckIfUserExists_mod.py
Python
mit
1,431
0.004892
from pahera.models import Person from django.db import connection, transaction from pahera.Utilities import DictFetchAll # To check whether there exists a user with same email or phone no before registering the new user..!!! def VerifyTheUser(data): cursor = connection.cursor() email = data['email'] phone ...
hone_no'] == phone: if post['id'] == person.id: return True else: return False else:
return True else: return True
kogaki/pqkmeans
test/clustering/test_pqkmeans.py
Python
mit
2,918
0.004798
import unittest import pqkmeans import numpy import collections import pickle class TestPQKMeans(unittest.TestCase): def data_source(self, n: int): for i in range(n): yield [i * 100] * 6 def setUp(self): # Train PQ encoder self.encoder = pqkmeans.encoder.PQEncoder(num_subd...
redict(codes) self.assertTrue((fit_predicted == predicted).all()) # Reconstruct the o
riginal vectors codes_decoded = self.encoder.inverse_transform(codes) cluster_centers_decoded = self.encoder.inverse_transform(cluster_centers) for cluster, code_decoded in zip(predicted, codes_decoded): other_cluster = (cluster + 1) % max(predicted) self.assertLessEqual...
praus/shapy
shapy/framework/commands/qdisc.py
Python
mit
537
0.001862
HTBRootQdisc = """\ tc qdisc add dev {interface!s} root handle 1: \ htb default {default_c
lass!s}\ """ HTBQdisc = """\ tc qdisc add dev {interface!s} parent {parent!s} handle {handle!s} \ htb default {default_class!s}\ """ NetemDelayQdisc = """\ tc qdisc add dev {interface!s} parent {parent!s} handle
{handle!s} \ netem delay {delay!s}ms\ """ IngressQdisc = "tc qdisc add dev {interface!s} ingress" PRIOQdisc = "tc qdisc add dev {interface!s} root handle 1: prio" pfifoQdisc = "tc qdisc add dev {interface!s} root handle 1: pfifo"
twilio/twilio-python
tests/unit/jwt/test_jwt.py
Python
mit
9,331
0.002251
import time as real_time import unittest import jwt as jwt_lib from mock import patch from twilio.jwt import Jwt, JwtDecodeError class DummyJwt(Jwt): """Jwt implementation that allows setting arbitrary payload and headers for testing.""" ALGORITHM = 'HS256' def __init__(self, secret_key, issuer, subje...
self.assertJwtsEqual( jwt.to_jwt(), 'secret_key', expected_headers={'typ': 'JWT', 'alg': 'HS256', 'yes': 'oui'}, expected_payload={'iss': 'issuer', 'exp': 3600, 'nbf': 0, 'pay': 'me'}, ) def test_encode_no_key_fails(self)
: jwt = DummyJwt(None, 'issuer') self.assertRaises(ValueError, jwt.to_jwt) def test_encode_decode(self): test_start = self.now() jwt = DummyJwt('secret_key', 'issuer', subject='hey', payload={'sick': 'sick'}) decoded_jwt = Jwt.from_jwt(jwt.to_jwt(), 'secret_key') s...
thaim/ansible
lib/ansible/plugins/doc_fragments/openstack.py
Python
mit
3,726
0.001074
# -*- coding: utf-8 -*- # Copyright: (c) 2014, Hewlett-Packard Development Company, L.P. # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) class ModuleDocFragment(object): # Standard openstack documentation fragment DOCUMENTATION = r''' options: cloud: descri...
oud or cloud config to operate against. If I(cloud) is a string, it references a named cloud config as defined in an OpenStack clouds.yaml file. Provides default values for I(auth) and I(auth_type). This parameter is not needed if I(auth) is provided or if OpenStack OS_* environment vari...
a dict, it contains a complete cloud configuration like would be in a section of clouds.yaml. type: raw auth: description: - Dictionary containing auth information as needed by the cloud's auth plugin strategy. For the default I(password) plugin, this would contain I(auth_url), ...
googleapis/python-oslogin
google/cloud/oslogin_v1/types/__init__.py
Python
apache-2.0
1,116
0
# -*- 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 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 permis...
leRequest, GetSshPublicKeyRequest, ImportSshPublicKeyRequest, ImportSshPublicKeyResponse, LoginProfile, UpdateSshPublicKeyRequest, ) __all__ = ( "DeletePosixAccountRequest", "DeleteSshPublicKeyRequest", "GetLoginProfileRequest", "GetSshPublicKeyRequest", "ImportSshPublicKeyReque...
chaos-soft/chocola
files/apps.py
Python
mit
164
0
from django.apps import AppConfig class File
sConfig(AppConfig): name = 'files' verbose_name = 'Files' def
ready(self): from . import signals
trehn/django-installer
django_installer/installer/forms.py
Python
isc
2,440
0.00041
try: from configparser import NoSectionError, NoOptionError except ImportError: from ConfigParser import NoSectionError, NoOptionError from django import forms from django.utils.translation import ugettext as _ def get_opti
on(settings, section, option): try: return settings.get(section, option) except NoSectionError: return "" except NoOptionError: return "" class BaseURLForm(forms.Form): title = _("Base URL") url = forms.URLField( help_text=_("The absolute URL this application will ...
def populate_from_settings(self, settings): self.data['url'] = get_option(settings, "base_url", "url") def populate_settings(self, settings): settings.add_section("base_url") settings.set("base_url", "url", self.cleaned_data['url']) class DatabaseForm(forms.Form): title = _("Dat...
LunacyZeus/Tao-ni
web/Taoni/manage.py
Python
gpl-3.0
803
0
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Taoni.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the ...
"Couldn't import Django. Are you sure i
t's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv)
kaedroho/wagtail
wagtail/contrib/postgres_search/tests/test_backend.py
Python
bsd-3-clause
7,353
0.000272
from django.test import TestCase from wagtail.search.tests.test_backends import BackendTests from wagtail.tests.search import models from ..utils import BOOSTS_WEIGHTS, WEIGHTS_VALUES, determine_boosts_weights, get_weight class TestPostgresSearchBackend(BackendTests, TestCase): backend_path = 'wagtail.contrib.p...
, 'B'), (-1, 'C'), (-1, 'D')]) self.assertListEqual(determine_boosts_weights([-1, 1, 2]), [(2, 'A'), (1, 'B'), (-1, 'C'), (-1, 'D')]) self.assertListEqual(determine_boosts_weights([0, 1, 2, 3]), [(3, 'A'), (2, 'B'), (1, 'C'), (0, 'D')]) s...
[(1.5, 'A'), (1, 'B'), (0.5, 'C'), (0, 'D')]) self.assertListEqual(determine_boosts_weights([0, 1, 2, 3, 4, 5, 6]), [(6, 'A'), (4, 'B'), (2, 'C'), (0, 'D')]) self.assertListEqual(determine_boosts_weights([-2, -1, 0, 1, 2, 3, 4]), ...
rafaeljusto/shelter
testing/scan_querier/scan_querier.input.py
Python
gpl-2.0
3,451
0.019994
#!/usr/bin/env python # Copyright 2014 Rafael Dantas Justo. All rights reserved. # Use of this source code is governed by a GPL # license that can be found in the LICENSE file. import getopt import sys import subprocess import urllib.request class NS: def __init__(self): self.name = "" self.type = "NS" ...
print(line) continue if lineParts[3] == "NS" and len(lineParts) == 5: ns = NS() ns.name = lineParts[0] ns.namserver = lineParts[4] zone.append(ns)
elif lineParts[3] == "A" and len(lineParts) == 5: a = A() a.name = lineParts[0] a.address = lineParts[4] zone.append(a) elif lineParts[3] == "AAAA" and len(lineParts) == 5: aaaa = AAAA() aaaa.name = lineParts[0] aaaa.address = lineParts[4] zone.append(aaaa) elif...
cpieloth/CppMath
tools/PackBacker/packbacker/job.py
Python
apache-2.0
2,389
0.000837
__author__ = 'Christof Pieloth' import logging from packbacker.errors import ParameterError from packbacker.installers import installer_prototypes from packbacker.utils import UtilsUI class Job(object): log = logging.getLogger(__name__) def __init__(self): self._installers = [] def add_instal...
append(installer) def execute(self): errors = 0 for i in self._installers: if not UtilsUI.ask_for_execute('Install ' + i.label): continue
try: if i.install(): Job.log.info(i.name + ' executed.') else: errors += 1 Job.log.error('Error on executing ' + i.name + '!') except Exception as ex: errors += 1 Job.log....
anjsimmo/simple-ml-pipeline
learners/traveltime_baserate.py
Python
mit
1,292
0.00387
import json import pickle import numpy as np import pandas as pd import numpy as np import datatables.traveltime def write_model(baserate, model_file): """ Write model to file baserate -- average travel time output_file -- file """ model_params = { 'baserate': baserate } mo
del_str = json.dumps(model_params) with open(model_file, 'w') as out_f: out_f.write(model_str) def load_model(mo
del_file): """ Load linear model from file model_file -- file returns -- baserate """ with open(model_file, 'r') as model_f: model_str = model_f.read() model_params = json.loads(model_str) return model_params['baserate'] def train(train_data_file, model_file): data = datatab...
TissueMAPS/TmLibrary
tmlib/submission.py
Python
agpl-3.0
1,761
0.000568
import logging import tmlib.models as tm class SubmissionManager(object): '''Mixin class for submission and monitoring of computational tasks.''' def __init__(self, experiment_id, program_name): ''' Parameters ---------- experiment_id: int ID of the processed expe...
Parameters ---------- user_id: int, optional ID of submitting user (if not the user who owns the experiment) Returns ------- Tuple[int, str] ID of the submission and the name of the submitting user Warning ------- Ensure that the ...
bmitted, i.e. added to a running `GC3Pie` engine. To this end, use the ::meth:`tmlib.workflow.api.update_submission` method. See also -------- :class:`tmlib.models.submission.Submission` ''' with tm.utils.MainSession() as session: if user_id is None: ...
openweave/happy
happy/ReturnMsg.py
Python
apache-2.0
1,604
0
#!/usr/bin/env python3 # # Copyright (c) 2015-2017 Nest Labs, Inc. # All rights reserved. # # Licensed under the Apache License, Version 2.0 (the
"License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" ...
guage governing permissions and # limitations under the License. # ## # @file # Implements ReturnMsg class. # # ReturnMsg is used to return not only numerical status of # success or fail, but allows to return any data structure as well. # class ReturnMsg: def __init__(self, value=None, da...