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
markofu/scripts
nmap/nmap/zenmap/zenmapGUI/higwidgets/higspinner.py
Python
gpl-2.0
21,689
0.000277
#!/usr/bin/env python # -*- coding: utf-8 -*- # ***********************IMPORTANT NMAP LICENSE TERMS************************ # * * # * The Nmap Security Scanner is (C) 1996-2013 Insecure.Com LLC. Nmap is * # * also a registered trademark of Inse...
oftware is widely available for no charge. For the * # * purposes of this license, an installer is considered to include Covered * # * Software even if it
actually retrieves a copy of Covered Software from * # * another source during runtime (such as by downloading it from the * # * Internet). * # * * # * o Links (statically or dynam...
htwenhe/DJOA
env/Lib/site-packages/openpyxl/writer/workbook.py
Python
mit
5,683
0.003519
from __future__ import absolute_import # Copyright (c) 2010-2017 openpyxl """Write the workbook global settings to the archive.""" from copy import copy from openpyxl.utils import absolute_coordinate, quote_sheetname from openpyxl.xml.constants import ( ARC_APP, ARC_CORE, ARC_WORKBOOK, PKG_REL_NS, ...
.utils.datetime import CALENDAR_MAC_1904 def write_root_rels(workbook): """Write the relationships xml.""" rels = RelationshipList() rel = Relationship(type="officeDocument", Target=ARC_WORKBOOK) rels.append(rel) rel = Relationship(Target=ARC_CORE, Type="%s/metadata/core-properties" % PKG_REL_N...
is not None: # See if there was a customUI relation and reuse it xml = fromstring(workbook.vba_archive.read(ARC_ROOT_RELS)) root_rels = RelationshipList.from_tree(xml) for rel in root_rels.find(CUSTOMUI_NS): rels.append(rel) return tostring(rels.to_tree()) def get_acti...
amureki/lunch-with-channels
core/utils.py
Python
mit
2,997
0
import random from .exceptions import ClientError def catch_client_error(func): """ Decorator to catch the ClientError exception and translate it into a reply. """ def inner(message): try: return func(message) except ClientError as e: # If we catch a client er...
'Emma Fro
st', 'Black Panther', 'The Hulk', 'Thing', 'Galactus', 'Magneto', 'Spider-Man', 'Doctor Victor Von Doom', ] left = random.choice(adjective_list) right = random.choice(subject_list) name = '{} {}'.format(left, right) return name
xStream-Kodi/plugin.video.xstream
sites/animes-stream24_tv.py
Python
gpl-3.0
12,975
0.019352
# -*- coding: utf-8 -*- from resources.lib.gui.gui import cGui from resources.lib.gui.guiElement import cGuiElement from resources.lib.handler.requestHandler import cRequestHandler from resources.lib.parser import cParser from resources.lib.handler.ParameterHandler import ParameterHandler from resources.lib import logg...
return total = len(aResult[1]) for link, title, img, plot in aResult[1]: GuiElement = cGuiElement(title, SITE_IDENTIFIER, 'getHosters') GuiElement.setMediaType('movie' if isMovie else 'tvshow') GuiElement.setThumbnail(img) plot.replace('<b>', '') GuiElement.setDesc...
ode('iso-8859-1').encode('utf-8')) #GuiElement.setYear(year) params.setParam('siteUrl', link) params.setParam('sName', title) oGui.addFolder(GuiElement, params, False, total) if 'entry-title' in cRequestHandler(bResult[1][0]).request(): params.setParam('eUrl', bResult[1][0])...
luisgg/iteexe
exe/engine/parasabermasfpdidevice.py
Python
gpl-2.0
5,051
0.009114
#!/usr/bin/python # -*- coding: utf-8 -*- # =========================================================================== # iDevice Para Saber más creado para la FPD por José Ramón Jiménez Reyes # =========================================================================== """ Para Saber mas iDevice """ import logging fr...
.activityTextArea.content_w_resourcePaths = \ self.activityTextArea.MassageResourceDirsIntoContent( \ self.activityTextArea.content_wo_resourcePaths) self.activityTextArea.content = \ self.activityTextArea.content_w_resourcePaths def upgra...
0 to 1. """ log.debug(u"Upgrading iDevice") self.icon = u"activity" def upgradeToVersion2(self): """ Upgrades the node from 1 (v0.5) to 2 (v0.6). Old packages will loose their icons, but they will load. """ log.debug(u"Upgrading iDevice") # ...
iosonofabio/singlet
singlet/io/h5ad/__init__.py
Python
mit
1,069
0
# vim: fdm=indent # author: Fabio Zanini # date: 02/08/17 # content: Support module for filenames related to LOOM files. # Modules import numpy as np import pandas as pd from singlet.config import config # Parser def parse_dataset( path, obsm_keys=None, ): import anndata ...
, col in enumerate(array.T, 1): samplesheet[newkey+'_'+str(j)] = col featuresheet = adata.var.copy() count_mat = adata.X.toarray().T counts_table = pd.DataFrame( data=count_mat, index=featuresheet.index, columns=samplesheet.index, ) return { 'c...
, 'featuresheet': featuresheet, }
lamondlab/pyctk
tests/test_axeswidget.py
Python
apache-2.0
1,326
0.008296
# =========================================================================== # # Library: PyCTK # Filename: test_axeswidget.py # # Copyright (c) 2015 Lamond Lab # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may ...
== from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * from PyCTK.Widgets import ctkAxesWidget class Widget(QWidget): def __init__(self, parent=None, **kwargs): super().__init__(parent, **kwargs) l=QVBoxLayout(self) self._axesWidget=ctkAxesWidget(self)
l.addWidget(self._axesWidget) if __name__=="__main__": from sys import argv, exit a=QApplication(argv) w=Widget() w.show() w.raise_() exit(a.exec_())
dls-controls/pymalcolm
malcolm/modules/pva/controllers/pvaservercomms.py
Python
apache-2.0
14,734
0.000882
from typing import Any, Dict, List, Optional, Set from annotypes import add_call_types, stringify_error from cothread import cothread from p4p import Value from p4p.server import DynamicProvider, Server, ServerOperation from p4p.server.cothread import Handler, SharedPV from malcolm.core import ( APublished, B...
ery dotted field name # to the tree on the way up. This set will contain something like: # {"attr.value", "attr"} # Or for a table: #
{"table.value.colA", "table.value.colB", "table.value", "table"} # Or if self.field: # {"value"} changed_fields_inc_parents = op.value().changedSet(parents=True, expand=False) # Taking the intersection with all puttable paths should yield the # thing we want to change, so valu...
gotostack/neutron-lbaas
neutron_lbaas/tests/tempest/v2/api/base.py
Python
apache-2.0
14,152
0.000071
# Copyright 2015 Rackspace # # 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 t...
und: continue for listener in lb.get('listeners'): for pool in listener.get('pools'): hm = pool.get('healthmonitor') if hm: cls._try_delete_resource( cls.health_monitors_client.delete_...
_status(lb_id) cls._try_delete_resource(cls.pools_client.delete_pool, pool.get('id')) cls._wait_for_load_balancer_status(lb_id) health_monitor = pool.get('healthmonitor') if health_monitor: ...
kapilgarg1996/gmc
gmc/conf/global_settings.py
Python
mit
1,053
0.021842
DATASET_DIR = '/tmp' BRAIN_DIR = '/tmp' GENRES = [ 'blues', 'classical', 'country', 'disco', 'hiphop', 'jazz', 'metal', 'pop', 'reggae', 'rock' ] NUM_BEATS = 10 KEEP_FRAMES = 0 TRAIN_TEST_RATIO = [7, 3] MODE = 'nn' PCA = False FEATURES = ['mfcc', 'dwt', 'beat'] MFCC_EXTRA = ['delta', 'ddelta', 'energy'...
, 'DROPOUT_PROB' : 0.6 } CNN = { 'NUM_HIDDEN_LAYERS' : 2, 'NUM_DENSE_LAYERS' : 1, 'HIDDEN_FEATURES' : [32, 64], 'DENSE_INPUTS' : [128], 'INPUT_SHAPE' : [16, 17], 'PATCH_SIZE' : [5, 5], 'RANDOM' : False, 'STRIDES' : [1, 1, 1, 1], 'BATCH_SIZE' : 100, 'T
RAINING_CYCLES' : 1000, 'LEARNING_RATE' : 0.01, 'DROPOUT_PROB' : 0.6 }
jdilallo/jdilallo-test
examples/adwords/v201309/campaign_management/get_all_disapproved_ads_with_awql.py
Python
apache-2.0
1,927
0.008822
#!/usr/bin/python # # Copyright 2014 Google 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 b...
alize appropriate service. ad_group_ad_service = client.GetService('AdGroupAdService', version='v201309') # Construct query and get all ads for a given campaign. query = ('SELECT Id, AdGroupAdDisapprovalReasons ' 'WHERE CampaignId = %s AND ' 'AdGroupCreativeApprovalStatus = DISAPPROVED ' ...
Display results. if 'entries' in ads: for ad in ads['entries']: print ('Ad with id \'%s\' was disapproved for the following reasons: ' % (ad['ad']['id'])) if ad['ad'].get('disapprovalReasons'): for reason in ad['ad']['disapprovalReasons']: print '\t%s' % reason els...
carlsonp/kaggle-TrulyNative
scikit_generate_prediction2.py
Python
gpl-3.0
1,784
0.01065
from __future__ import print_function import pickle, os, sys, glob, hashlib from sklearn.ensemble import RandomForestClassifier import pandas as pd test_files = set(pd.read_csv('./data/sampleSubmission_v2.csv').file.values) train = pd.read_csv('./data/train_v2.csv') df_full = pickle.load(open( "df_full.p", "rb")) ...
, n_jobs=-1, random_state=0) train_data = df_full[df_full.sponsored.notnull()].fillna(0) test = df_full[df_full.sponsored.isnull() & df_full.file.isin(test_files)].fillna(0) clf.fit(train_data.drop(['file', 'sponsored'], 1), train_data.sponsored) #normalized value between 0 and 1 feature_importances = pd.Series(clf.fe...
with pd.option_context('display.max_rows', len(feature_importances), 'display.max_columns', 10): print(feature_importances) print('--- Create predictions and submission') submission = test[['file']].reset_index(drop=True) submission['sponsored'] = clf.predict_proba(test.drop(['file', 'sponsored'], 1))[:, 1] #make...
plotly/python-api
packages/python/plotly/plotly/graph_objs/scattermapbox/_textfont.py
Python
mit
8,586
0.000582
from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType import copy as _copy class Textfont(_BaseTraceHierarchyType): # class properties # -------------------- _parent_path_str = "scattermapbox" _path_str = "scattermapbox.textfont" _valid_props = {"color", "family", "si...
otly.com or on- premise) generates images on a server, where only a select number of fonts are installed and supported. These include "Arial", "Balto", "Courier New", "Droid Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas One", "Old Standard TT", "Open San...
pass", "PT Sans Narrow", "Raleway", "Times New Roman". size Returns ------- Textfont """ super(Textfont, self).__init__("textfont") if "_parent" in kwargs: self._parent = kwargs["_parent"] return # Validate arg ...
PhilHarnish/forge
src/puzzle/problems/crossword/_cryptic_nodes.py
Python
mit
437
0.011442
from typing import NamedTuple, List from data import crossword class Cl
ue(str): def __init__(self, value) -> None: super(Clue, self).__init__(value) self._tokens = crossword.tokenize_clue(value) class _Node(object): _clue: Clue _occupied: int def __init_
_(self, clue: Clue, occupied: int) -> None: self._clue = clue self._occupied = occupied class Parsed(List): pass # A list of nodes, initially Nulls
AnTAVR/aai2
src/modules/net/m_wifi.py
Python
gpl-2.0
517
0
import logging from ge
ttext import gettext as _ from .l_connector import ConnectorBase from .l_net import ModuleStrategyBase from .main import OptionsWIFI logger = logging.getLogger(__name__) # noinspection PyAbstractClass class Connector(ConnectorBase): opti_: OptionsWIFI class Module(ModuleStrategyBase): ID = 'net_wifi' ...
('WIFI')
ideaworld/FHIR_Tester
FHIR_Tester_backend/home/views.py
Python
mit
7,138
0.008826
from django.shortcuts import render from services.genomics_test_generator.fhir_genomics_test_gene import * from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponse, HttpResponseRedirect from django.template import RequestContext, loader import json from home.task_runner import perform_t...
list.append(item['name']) print resource_list if 'chosen_server' in req_json: #ser url and access token try: server_obj = server.objects.get(server_id=int(req_json['chosen_server'])) url = server_obj.server_url access_token = server_obj.access_token ...
n HttpResponse(json.dumps(result), content_type="application/json") else: access_token = req_json['access_token'] url = req_json['url'] token = None try: token = req_json['token'] except: pass username = None if token: username = auth.extract_username(toke...
apporc/cinder
cinder/volume/drivers/zfssa/zfssaiscsi.py
Python
apache-2.0
45,567
0.000044
# Copyright (c) 2014, 2015, Oracle and/or its affiliates. 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 ...
logbias=lcfg.zfssa_lun_logbias) if lcfg.zfssa_enable_local_cache: self.zfssa.create_project(lcfg.zfssa_pool, lcfg.zfssa_cache_proje
ct, compression=lcfg.zfssa_lun_compression, logbias=lcfg.zfssa_lun_logbias) schemas = [ {'property': 'image_id', 'description': 'OpenStack image ID', 'type': 'String'}, ...
Yukarumya/Yukarum-Redfoxes
browser/themes/preprocess-tab-svgs.py
Python
mpl-2.0
1,392
0.002874
#!/usr/bin/env python # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file,
You can obtain one at http://mozilla.org/MPL/2.0/. import buildconfig from mozbuild.preprocessor import preprocess # By default, the pre-processor used for jar.mn will use "%" as a marker # for ".css" files and "#" otherwise. This falls apart when a file using # one marker needs to include a file with the other mark...
so we invoke the pre- processor ourselves here with # the marker specified. The resulting SVG files will get packaged by the # processing of the jar file in the appropriate directory. def _do_preprocessing(output_svg, input_svg_file, additional_defines): additional_defines.update(buildconfig.defines) return pre...
hamogu/marxs
marxs/optics/multiLayerMirror.py
Python
gpl-3.0
7,308
0.004379
# Licensed under GPL version 3 - see LICENSE.rst import numpy as np from astropy.io import ascii from .base import FlatOpticalElement, FlatStack from ..math.utils import norm_vector, e2h, h2e class FlatBrewsterMirror(FlatOpticalElement): '''Flat mirror operated at the Brewster angle. Calculation of the Fres...
with varying layer thickness along one axis The distance between layers (and thus best reflected energy) changes along the local y axis. All reflectivity data is assumed to be for a single, desired angle. There is currently no way to enter varying reflecti
on that depends on the angle of incidence. Provide reflectivity data in a file with columns: - 'X(mm)' - position along the "changing" axis (local y axis) - 'Peak lambda' - wavelength with maximum reflection at a given position - 'Peak' - maximum reflection at a given position - 'FWHM(nm)' - f...
luac/django-argcache
src/argcache.py
Python
agpl-3.0
22,405
0.00308
""" Bulk-deletable cache objects. """ __author__ = "Individual contributors (see AUTHORS file)" __date__ = "$DATE$" __rev__ = "$REV$" __license__ = "AGPL v.3" __copyright__ = """ This file is part of ArgCache. Copyright (c) 2015 by the individual contributors (see AUTHORS file) This program is free s...
Really ought to depend on param signature. #self.global_token = ExternalToken(name=name, provided_params=(), external=hash(params)) self.global_token = Token(name=name, provided_
params=(), cache=self.cache) self.add_token(self.global_token) # Calling in the constructor to avoid duplicates if warn_if_loaded(): print "Dumping the cache out of paranoia..." self.delete_all() self.register() def _hit_hook(self, arg_list): ...
manankalra/Twitter-Sentiment-Analysis
demo/download.py
Python
mit
145
0.006897
#!/u
sr/bin/env python """ Download NLTK data """ __author__ = "Ma
nan Kalra" __email__ = "manankalr29@gmail.com" import nltk nltk.download()
olivierdalang/stdm
ui/ui_import_data.py
Python
gpl-2.0
14,198
0.002043
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui_import_data.ui' # # Created: Thu Nov 13 16:30:03 2014 # by: PyQt4 UI code generator 4.10.3 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fro...
.QGridLayout(self.destTable) self.gridLayout_2.setObjectName(_fromUtf8("gridLayout_2")) self.groupBox_3 = QtGui.QGroupBox(self.destTable)
self.groupBox_3.setObjectName(_fromUtf8("groupBox_3")) self.gridLayout = QtGui.QGridLayout(self.groupBox_3) self.gridLayout.setObjectName(_fromUtf8("gridLayout")) self.lstDestTables = QtGui.QListWidget(self.groupBox_3) self.lstDestTables.setObjectName(_fromUtf8("lstDestTables"...
duythanhphan/qt-creator
tests/system/suite_HELP/tst_HELP06/test.py
Python
lgpl-2.1
8,439
0.009835
############################################################################# ## ## Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ## Contact: http://www.qt-project.org/legal ## ## This file is part of Qt Creator. ## ## Commercial License Usage ## Licensees holding valid commercial Qt licenses may use this f...
der(view, item, "Rename Folder") replaceEditorContent(waitForObject(":Add Bookmark.treeView_QExpandingLineEdit"), newName) type(waitForObject(":Add Bookmark.treeView_QExpandingLineEdit"), "<Return>") return def invokeContextMenuItemOnBookmarkFolder(view, item, menuItem): aboveWidget = "{name='line' typ...
) activateItem(waitForObject("{aboveWidget=%s type='QMenu' unnamed='1' visible='1' " "window=':Add Bookmark_BookmarkDialog'}" % aboveWidget), menuItem) def getQModelIndexStr(textProperty, container): if (container.startswith(":")): container = "'%s'" % container retur...
hlin117/statsmodels
statsmodels/graphics/plottools.py
Python
bsd-3-clause
634
0.009464
import numpy as np def rainbow(n): """ Returns a list of colors sampled at equal intervals over the spectrum. Parameters ---------- n : int The number of colors to return Returns
------- R : (n,3) array An of rows of RGB color values Notes ----- Converts from HSV coordinates (0, 1, 1) to (1, 1, 1) to RGB. Based on the Sage function of the same name. """ from matplotlib import colors R = np.ones((1,n,3)) R[0,:,0] = np.linspace(0, 1, n, e
ndpoint=False) #Note: could iterate and use colorsys.hsv_to_rgb return colors.hsv_to_rgb(R).squeeze()
peheje/baselines
toy_examples/windy_gridworld/q_learning.py
Python
mit
1,351
0.00148
import time from copy import copy import numpy as np from gridworld import Gridworld, Position from utilities.utils import argmax_random_tie # START rows = 7 cols = 10 world = Gridworld(rows, cols) moveset = [ # Position(1, 1), # Position(1, -1), # Position(-1, -1), # Position(-1, 1), Position(1,...
isode % print_every == 0 and step < 30: print(world)
time.sleep(0.1) if found: print("found goal, epsilon {} in steps {}".format(e, step)) time.sleep(3)
jawilson/home-assistant
tests/components/greeneye_monitor/test_sensor.py
Python
apache-2.0
7,421
0.00283
"""Tests for greeneye_monitor sensors.""" from unittest.mock import AsyncMock, MagicMock from homeassistant.components.greeneye_monitor.sensor import ( DATA_PULSES, DATA_WATT_SECONDS, ) from homeassistant.const import STATE_UNKNOWN from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_...
etup_greeneye_monitor_component_with_config( hass, SINGLE_MONITOR_CONFIG_VOLTAGE_SENSORS ) mo
nitor = connect_monitor(monitors, SINGLE_MONITOR_SERIAL_NUMBER) assert_sensor_state(hass, "sensor.voltage_1", "120.0") monitor.voltage = 119.8 monitor.notify_all_listeners() assert_sensor_state(hass, "sensor.voltage_1", "119.8") async def test_power_sensor_initially_unknown( hass: HomeAssistant, ...
fake-name/ReadableWebProxy
WebMirror/management/rss_parser_funcs/feed_parse_extractFaelicyTumblrCom.py
Python
bsd-3-clause
674
0.02819
def extractFaelicyTumblrCom(item): ''' Parser for 'faelicy.tumblr.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in
item['title'].lower(): return None tagmap = [ ('the scum villain\'s self saving system', 'the scum villain\'s self saving system', 'translated'), ('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel'), ] for tagname, name, tl_typ...
rn False
conan-io/conan
conans/client/packager.py
Python
mit
1,979
0.002527
import os from conans.client.file_copier import FileCopier, report_copied_files from conans.model.manifest import FileTreeManifest from conans.paths import CONANINFO from conans.util.files import mkdir, save def export_pkg(conanfile, package_id, src_package_folder, hook_manager, conanfile_path, ref): # NOTE: Th...
ileCopier([src_package_folder], conanfile.package_folder) copier("*", symlinks=True) hook_manager.execute("post_package", conanfile=conanfile, conanfile_path=conanfile_path, reference=ref, pa
ckage_id=package_id) save(os.path.join(conanfile.package_folder, CONANINFO), conanfile.info.dumps()) manifest = FileTreeManifest.create(conanfile.package_folder) manifest.save(conanfile.package_folder) report_files_from_manifest(output, manifest) output.success("Package '%s' created" % package_id)...
notesoftware/notestudio
main.py
Python
gpl-2.0
8,246
0.02877
# coding: utf-8 #import pygame from Tkinter import * import ttk import time from PIL import ImageTk,Image from functools import partial import os import tkMessageBox from urllib2 import * from threading import Thread import urllib as u from window import * #############################################################...
B.buton["command"] = self.hakkinda cikisB = Window(master = self.pencere, no = 10, text = "Çıkış", pTitle = "Çıkış", pText = "Çıkış", pBilgi = "Çıkış") cikisB.buton["command"] = self.cik def ip(self): ipAdres = u.urlope...
= "NoteStudio 1.1" tkMessageBox.showinfo("NoteStudio",mesaj) def cik(self): self.pencere.destroy() sys.exit(0)
davogler/POSTv3
customers/migrations/0002_auto_20150405_1041.py
Python
mit
1,800
0.002778
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('customers', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='address', name='re...
s.AddField( model_name='recipient', name='city', field=models.CharField(max_length=50, blank=True),
preserve_default=True, ), migrations.AddField( model_name='recipient', name='country', field=models.CharField(max_length=40, verbose_name=b'Country', blank=True), preserve_default=True, ), migrations.AddField( model_name='recipi...
nschloe/quadpy
src/quadpy/s2/_kim_song/__init__.py
Python
mit
1,946
0
# ENH quadpy-optimize import pathlib from ...helpers import article from .._helpers import _read, register _source = article( authors=["KyoungJoong Kim", "ManSuk Song"], title="Symmetric quadrature formulas over a unit disk", journal="Korean J. Comp. & Appl. Math.", year="1997", volume="4", pa...
ng_04.json", _source) def kim_song_5(): return _read(this_dir / "kim_song_05.json", _source) def kim_song_6(): return _read(this_dir / "kim_song_06.json", _source) def kim_song_7(): return _read(this_dir / "kim_song_07.json", _source) # TODO find issue def kim_song_8():
return _read(this_dir / "kim_song_08.json", _source) def kim_song_9(): return _read(this_dir / "kim_song_09.json", _source) def kim_song_10(): return _read(this_dir / "kim_song_10.json", _source) def kim_song_11(): return _read(this_dir / "kim_song_11.json", _source) def kim_song_12(): return _r...
a301-teaching/a301_code
a301utils/a301_readfile.py
Python
mit
2,239
0.011166
""" download a file named filename from the atsc301 downloads directory and save it as a local file with the same name. command line example:: python -m a301utils.a301_readfile photon_data.csv module example:: from a3
01utils.a301_readfile import download download('photon_data.csv') """ import argparse import requests from pathlib import Path import sys import os import shutil def download(filename): """ copy file filename from http://clouds.eos.ubc.ca/~phil/courses/atsc301/down
loads to the local directory Parameters ---------- filename: string name of file to fetch from Returns ------- Side effect: Creates a copy of that file in the local directory """ url = 'https://clouds.eos.ubc.ca/~phil/courses/atsc301/downloads/{}'.format(filename) ...
MungoRae/home-assistant
homeassistant/components/sensor/knx.py
Python
apache-2.0
5,476
0
""" Sensors of a KNX Device. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/knx/ """ from enum import Enum import logging import voluptuous as vol from homeassistant.const import ( CONF_NAME, CONF_MAXIMUM, CONF_MINIMUM, CONF_TYPE, TEMP_CELSIUS ...
if not sensor_config: raise NotImplementedError() # set up the conversion function based on the address type address_type = sensor_config.get('address_type') if address_type == KNXAddressType.FLOAT: self.convert = convert_float elif address_type == KNXA...
else: raise NotImplementedError() # other settings self._unit_of_measurement = sensor_config.get('unit') default_min = float(sensor_config.get('default_minimum')) default_max = float(sensor_config.get('default_maximum')) self._minimum_value = config.config.get(C...
dshearer/jobber
platform_tests/keywords/testlib.py
Python
mit
27,023
0.001887
import subprocess as sp import os import stat import shutil import tempfile import pwd import time import json import yaml _NORMUSER = 'normuser' _RUNNER_LOG_FILE_FOR_ROOT = '/root/.jobber-log' _RUNNER_LOG_FILE_FOR_NORMUSER = '/home/{0}/.jobber-log'.\ format(_NORMUSER) _CONFIG_PATH = '/etc/jobber.conf' _OLD_CONFIG...
temDServiceCtl() elif program_exists(
'brew') and 'jobber ' in \ sp_check_output(['brew', 'services']): self._servicectl = BrewServiceCtl() elif program_exists('launchctl'): self._servicectl = LaunchctlServiceCtl() else: raise Exception("Cannot determine how to control Jobber service") ...
alfredgamulo/cloud-custodian
tools/c7n_azure/c7n_azure/session.py
Python
apache-2.0
14,857
0.001952
# Copyright The Cloud Custodian Authors. # SPDX-License-Identifier: Apache-2.0 import importlib import inspect import json import logging import os import sys import types from azure.common.credentials import BasicTokenAuthentication from azure.core.credentials import AccessToken from azure.identity import (AzureCliC...
except HTTPError as e:
e.message = 'Failed to retrieve SP credential ' \ 'from Key Vault with client id: {0}'.format(keyvault_client_id) raise self._credential = None if self._auth_params.get('access_token') is not None: auth_name = 'Access Token' pass el...
grimmjow8/ansible
lib/ansible/modules/commands/expect.py
Python
gpl-3.0
7,744
0.000646
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2015, Matt Martz <matt@sivel.net> # # 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, ...
be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/license...
s': ['preview'], 'supported_by': 'community', 'version': '1.0'} DOCUMENTATION = ''' --- module: expect version_added: 2.0 short_description: Executes a command and responds to prompts description: - The C(expect) module executes a command and responds to prompts - The ...
ichuang/sympy
sympy/physics/mechanics/kane.py
Python
bsd-3-clause
37,447
0.001762
__all__ = ['Kane'] from sympy import Symbol, zeros, Matrix, diff, solve_linear_system_LU, eye from sympy.utilities import default_sort_key from sympy.physics.mechanics.essential import ReferenceFrame, dynamicsymbols from sympy.physics.mechanics.particle import Particle from sympy.physics.mechanics.point
import Point from sympy.physics.mechanics.rigidbody import RigidBody class Kane(object): """Kane's method object. This object is used to do the "book-keeping" as you go through and form equations of motion in the way Kane presents in: Kane, T., Levinson, D. Dynamics Theory and Applications. 1985 McGra...
fault, to the advantage of smaller, simpler systems. If your system is large, it will lead to slowdowns; however turning it off might have negative implications in numerical evaluation. Care needs to be taken to appropriately reduce expressions generated with simp==False, as they might be too large ...
js0701/chromium-crosswalk
third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/controllers/manager.py
Python
bsd-3-clause
27,322
0.003221
# Copyright (C) 2010 Google Inc. All rights reserved. # Copyright (C) 2010 Gabor Rapcsanyi (rgabor@inf.u-szeged.hu), University of Szeged # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of so...
lf.INSPECTOR_SUBDIR = 'inspector' + port.TEST_PATH_SEPARATOR self.PERF_SUBDIR = 'perf' self.WEBSOCKET_SUBDIR = 'websocket' + port.TEST_PATH_SEPA
RATOR self.VIRTUAL_HTTP_SUBDIR = port.TEST_PATH_SEPARATOR.join([ 'virtual', 'stable', 'http']) self.LAYOUT_TESTS_DIRECTORY = 'LayoutTests' self.ARCHIVED_RESULTS_LIMIT = 25 self._http_server_started = False self._wptserve_started = False self._websockets_server...
pli3/enigma2-git
lib/python/Components/NimManager.py
Python
gpl-2.0
63,253
0.034623
from Tools.HardwareInfo import HardwareInfo from Tools.BoundFunction import boundFunction from config import config, ConfigSubsection, ConfigSelection, ConfigFloat, \ ConfigSatlist, ConfigYesNo, ConfigInteger, ConfigSubList, ConfigNothing, \ ConfigSubDict, ConfigOnOff, ConfigDateTime from enigma import eDVBSatellit...
for slot in nim_slots: if slot.type is not None: used_nim_slots.append((slot.slot, slot.description, slot.config.configMode.value != "nothing" and True or False, slot.isCompatible("DVB-S2"), slot.frontend_id is None and -1 or slot.frontend_id)) eDVBResourceManager.getInstance().se
tFrontendSlotInformations(used_nim_slots) for slot in nim_slots: if slot.frontend_id is not None: types = [type for type in ["DVB-T", "DVB-C", "DVB-S", "ATSC"] if eDVBResourceManager.getInstance().frontendIsCompatible(slot.frontend_id, type)] if len(types) > 1: slot.multi_type = {} for type in t...
AndrewPeelMV/Blender2.78c
2.78/scripts/startup/bl_ui/space_userpref.py
Python
gpl-2.0
50,089
0.001437
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distrib...
elf.layout split = layout.split()
row = split.row() row.label("") row = split.row() row.label("Interaction:") text = bpy.path.display_name(context.window_manager.keyconfigs.active.name) if not text: text = "Blender (default)" row.menu("USERPREF_MT_appconfigs", text=text) # only for addons ...
pombredanne/unuk
src/unuk/benchmarks/__init__.py
Python
bsd-3-clause
63
0
import http
benc
hmark from unuk.benchmarks.base import runtests
gloryofrobots/obin
arza/compile/compiler.py
Python
gpl-2.0
43,248
0.000694
__author__ = 'gloryofrobots' from arza.compile.code.opcode import * from arza.compile.parse import parser from arza.compile import simplify from arza.compile.parse import nodes from arza.compile.parse.basic import IMPORT_NODES from arza.compile.parse.nodes import (node_type, imported_name_to_s, ...
pe.add_scope_local(symbol) assert not platform.is_absent_index(idx) return idx def _declare_export(compiler, code, node): name = _get_symbol_name(compiler, node) scope = _current_scope(compiler) if sco
pe.has_export(name): compile_error(compiler, code, node, u"Name has already exported") scope.add_export(name) def _declare_import(compiler, name, func): assert space.issymbol(name) assert not api.isempty(name) scope = _current_scope(compiler) idx = scope.get_import_index(name) if not ...
de-vri-es/qtile
libqtile/widget/khal_calendar.py
Python
mit
5,419
0.000554
# -*- coding: utf-8 -*- ################################################################### # This widget will display the next appointment on your calendar in # the qtile status bar. Appointments within the "reminder" time will be # highlighted. Authentication credentials are stored on disk. # # This widget uses the k...
: data = 'No appointments in next ' + \ str(self.lookahead) + ' days' # get rid of any garbage in appointment added by khal data = ''.join(filter(lambda x: x in string.printable, data)) # colorize the event if it is within reminder time if (starttime ...
.foreground = self.default_foreground return data
BGmi/BGmi
tests/downloader/test_aria2.py
Python
mit
609
0
from unittest import mock from bgmi.downloader.aria2_rpc import Aria2DownloadRPC _token = "token:2333" @mock.patch("bgmi.config.ARIA2_RPC_URL", "https://uuu") @mock.patch("bgmi.config.ARIA2_RPC_TOKEN", "token:t") def test_use_config(): with mock.patch("xmlrpc.client.ServerPr
oxy") as m1: m1.return_value.aria2.getVersion.return_value = {"version
": "1.19.1"} Aria2DownloadRPC() m1.assert_has_calls( [ mock.call("https://uuu"), mock.call("https://uuu"), mock.call().aria2.getVersion("token:t"), ] )
Glottotopia/aagd
moin/local/moin/build/lib.linux-x86_64-2.6/MoinMoin/security/textcha.py
Python
mit
8,873
0.003043
# -*- coding: iso-8859-1 -*- """ MoinMoin - Text CAPTCHAs This is just asking some (admin configured) questions and checking if the answer is as expected. It is up to the wiki admin to setup questions that a bot can not easily answer, but humans can. It is recommended to setup SITE SPECIFIC ...
uage, like: textchas = { 'en': { 'some question': 'some answer', # ...
}, 'de': {}, # having no questions for 'de' means disabling textchas for 'de' # ... } """ return not not self.textchas # we don't want to return the dict def check_answer(self, given_answer, timestamp, signature): """ check if ...
skarra/PRS
libs/sqlalchemy/__init__.py
Python
agpl-3.0
4,621
0
# sqlalchemy/__init__.py # Copyright (C) 2005-2019 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php from . import util as _util # noqa from .inspection import inspect # noqa f...
rt BINARY # noqa from .types import Binary # noqa from .types import BLOB # noqa from .types import BOOLEAN # noqa fro
m .types import Boolean # noqa from .types import CHAR # noqa from .types import CLOB # noqa from .types import DATE # noqa from .types import Date # noqa from .types import DATETIME # noqa from .types import DateTime # noqa from .types import DECIMAL # noqa from .types import Enum # noqa from .types import FL...
electblake/python-lipsumation
lipsumation/engines/admin.py
Python
mit
119
0.008403
from django.
contrib import admin # Register your models here. from .models import Engine adm
in.site.register(Engine)
alexm92/sentry
src/sentry/web/frontend/account_notification.py
Python
bsd-3-clause
3,360
0.001488
from __future__ import absolute_import import itertools from django.contrib import messages from django.core.context_processors import csrf from django.db import transaction from django.http import HttpResponseRedirect from django.views.decorators.cache import never_cache from django.views.decorators.csrf import csrf...
els import ( Project, ProjectStatus ) from sentry.plugins import plugins from sentry.web.forms.accounts import ( ProjectEmailOptionsForm, NotificationSettingsForm, NotificationReportSettingsForm ) from sentry.web.decorators import login_required from sentry.web.frontend.base import BaseView from sentry.web....
y.utils.auth import get_auth_providers from sentry.utils.safe import safe_execute class AccountNotificationView(BaseView): notification_settings_form = NotificationSettingsForm @method_decorator(csrf_protect) @method_decorator(never_cache) @method_decorator(login_required) @method_decorator(sudo_...
antoinecarme/pyaf
tests/model_control/detailed/transf_Anscombe/model_control_one_enabled_Anscombe_MovingMedian_Seasonal_Minute_LSTM.py
Python
bsd-3-clause
161
0.049689
import tests.model_c
ontrol.test_o
zone_custom_models_enabled as testmod testmod.build_model( ['Anscombe'] , ['MovingMedian'] , ['Seasonal_Minute'] , ['LSTM'] );
pytroll/satpy
satpy/tests/reader_tests/test_avhrr_l0_hrpt.py
Python
gpl-3.0
8,951
0.001452
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2009-2021 Satpy developers # # This file is part of satpy. # # satpy 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 Licens...
n.""" del args, kwargs return data * 25.43 + 3 def fake_calibrate_therm
al(data, *args, **kwargs): """Fake calibration.""" del args, kwargs return data * 35.43 + 3 class CalibratorPatcher(PygacPatcher): """Patch pygac.""" def setUp(self) -> None: """Patch pygac's calibration.""" super().setUp() # Import things to patch here to make them patch...
Nurdok/pep257
setup.py
Python
mit
1,105
0
from __future__ import with_statement import os from setuptools import setup
# Do not update the version manually - it is mana
ged by `bumpversion`. version = '2.0.1rc' setup( name='pydocstyle', version=version, description="Python docstring style checker", long_description=open('README.rst').read(), license='MIT', author='Amir Rachum', author_email='amir@rachum.com', url='https://github.com/PyCQA/pydocstyle/',...
mzdaniel/oh-mainline
vendor/packages/kombu/funtests/tests/test_redis.py
Python
agpl-3.0
399
0
from funtests import transport class test_redis(transport.TransportCase): transport = "redis" prefix = "redis" def after_connect(self, connection): client = connection.channel().client client.info() def test_cant_connect_
raises_connection_error(self): conn = self.get_connection(port=65534) self.assertRaises(conn.connec
tion_errors, conn.connect)
82Flex/DCRM
suit/sortables.py
Python
agpl-3.0
6,638
0.000452
from copy import deepcopy, copy from django.contrib import admin from django.contrib.admin.views.main import ChangeList from django.contrib.contenttypes.admin import GenericTabularInline, GenericStackedInline from django.forms import ModelForm, NumberInput from django.db import models class SortableModelAdminBase(obj...
s def formfield_for_dbfield(self, db_field, **kwargs): if db_field.name == self.sortable: kwargs['widget'] =
deepcopy(SortableListForm.Meta.widgets['order']) kwargs['widget'].attrs['class'] += ' suit-sortable-stacked' kwargs['widget'].attrs['rowclass'] = ' suit-sortable-stacked-row' return super(SortableStackedInlineBase, self).formfield_for_dbfield(db_field, **kwargs) class SortableStackedI...
tensorflow/tensorflow
tensorflow/python/pywrap_dlopen_global_flags.py
Python
apache-2.0
1,919
0.003127
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
_pywrap_tensorflow.so. _use_rtld_global = (hasattr(sys, 'getdlopenflags') and hasattr(sys, 'setdlopenflags')) if _use_rtld_global: _default_dlopen_flags = sys.getdlopenflags() def set_dlopen_
flags(): if _use_rtld_global: sys.setdlopenflags(_default_dlopen_flags | ctypes.RTLD_GLOBAL) def reset_dlopen_flags(): if _use_rtld_global: sys.setdlopenflags(_default_dlopen_flags)
flaviogrossi/sockjs-cyclone
sockjs/cyclone/transports/htmlfile.py
Python
mit
2,041
0
from cyclone.web import asynchronous from sockjs.cyclone import proto from sockjs.cyclone.transports import streamingbase # HTMLFILE template HTMLFILE_HEAD = r''' <!doctype html> <html><head> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8...
ameter callback = self.get_argument('c', None) if not callback: self.write('"cal
lback" parameter required') self.set_status(500) self.finish() return self.write(HTMLFILE_HEAD % callback) self.flush() # Now try to attach to session if not self._attach_session(session_id): self.finish() return # Fl...
alxgu/ansible
lib/ansible/modules/database/postgresql/postgresql_membership.py
Python
gpl-3.0
12,662
0.002369
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2019, Andrew Klychkov (@Andersson007) <aaklychkov@mail.ru> # 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 =...
tError: HAS_PSYCOPG2 = False from ansible.module_utils.basic import AnsibleModule, missing_required_lib from ansible.module_utils.database import SQLParseError, pg_quote_identifier from ansible.module_util
s.postgres import connect_to_db, postgres_common_argument_spec from ansible.module_utils._text import to_native from ansible.module_utils.six import iteritems class PgMembership(object): def __init__(self, module, cursor, groups, target_roles, fail_on_role): self.module = module self.cursor = curs...
pombreda/ximenez
setup.py
Python
gpl-3.0
1,457
0
import os from setuptools import setup from setuptools import find_packages version_file = 'VERSION.txt' version = open(version_file).read().strip() description_file = 'README.txt' description = open(description_file).read().split('\n\n')[0].strip() description = description.replace('\n', ' ') long_description_file =...
, 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: System', 'Topic :: Utilities'], keywords='collector action plug-in plugin', url='http://code.noherring.com/ximenez', download_url='http://cheeseshop.python....
enez', )
rahul-c1/scrapy
scrapy/tests/test_djangoitem/__init__.py
Python
bsd-3-clause
2,978
0
import os from twisted.trial import unittest from scrapy.contrib.djangoitem import DjangoItem, Field from scrapy import optional_features os.environ['DJANGO_SETTINGS_MODULE'] = 'scrapy.tests.test_djangoitem.settings' if 'django' in optional_features: from .models import Person, IdentifiedPerson class BasePe...
obvious that "age" should be saved also, since it was # redefined in child class i['age'] = '22' person = i.save(commit=False) self.assertEqual(person.name, 'John') self.assertEqual(person.age, '22') def test_validation(self): long_name = 'z' * 300 i = Base...
al(set(i.errors), set(['age', 'name'])) i = BasePersonItem(name='John') self.assertTrue(i.is_valid(exclude=['age'])) self.assertEqual({}, i.errors) # once the item is validated, it does not validate again i['name'] = long_name self.assertTrue(i.is_valid()) def test_...
jermnelson/metadata-day-2013
web.py
Python
gpl-2.0
3,972
0.004532
""" Module for the Colorado Alliance of Research Libraries Metadata 2013 Presentation Copyright (C) 2013 Jeremy Nelson This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the Licens...
'rb')) SLIDES = PRESENTATION_INFO.get('slides') DEMO_REDIS = redis.StrictRedis() FLUP = False @route('/metadata-day-2013/assets/<type_of:path>/<filename:path>') def send_asset(type_of,filename): local_path = os.path.join(PROJECT_ROOT, "assets", type_...
filename) if os.path.exists(local_path): return static_file(filename, root=os.path.join(PROJECT_ROOT, "assets", type_of)) @route("/metadata-day-2013/bibframe.html") def bibframe(): return template('b...
CAB-LAB/cablab-core
esdl/providers/test_provider.py
Python
gpl-3.0
1,856
0.003233
import numpy as np from esdl.cube_provider import CubeSourceProvider from esdl.cube_config import CubeConfig class TestCubeSourceProvider(CubeSourceProvider): """ CubeSourceProvider implementation used for testing cube generation without any source files. The following usage generates a cube with two var...
ables ``test_1`` and ``test_2``: cube-gen -c ./myconf
.py ./mycube test:var=test_1 test:var=test_2 :param cube_config: Specifies the fixed layout and conventions used for the cube. :param name: The provider's registration name. Defaults to ``"test"``. :param var: Name of a (float32) variable which will be filled with random numbers. """ def __init__(...
google/dynamic-video-depth
loggers/html_template.py
Python
apache-2.0
2,786
0.001436
# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, s...
avascript" language="javascript" src="https://cdn.datatables.net/buttons/1.6.1/js/buttons.colVis.min.js"></scr
ipt> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css"> </link> <link rel="stylesheet" type="text/css" href="https://ztzhang.info/assets/css/buttons.dataTables.min.css"> </link> <link rel="stylesheet" type="text/css" href=...
MattBlack85/django-gruyere
gruyere/settings.py
Python
mit
1,620
0
import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) SECRET_KEY = '#zw#k0g76&a!ulj820of0+i#y(-y4%)sed3k-
3q9mw8kzn7)jf' DEBUG = True TEMPLATE_DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.
staticfiles', ) TEMPLATE_DIRS = ( os.path.join(BASE_DIR, 'templates/'), ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddlewar...
arcyfelix/ML-DL-AI
Supervised Learning/GANs/dcgan-tensorflayer/tensorlayer/nlp.py
Python
apache-2.0
32,641
0.00432
#! /usr/bin/python # -*- coding: utf8 -*- import tensorflow as tf import os from sys import platform as _platform import collections import random import numpy as np import warnings from six.moves import xrange from tensorflow.python.platform import gfile import re ## Iteration functions def generate_skip_gram_bat...
ex=
0) >>> print(batch) ... [2 2 3 3 4 4 5 5] >>> print(labels) ... [[3] ... [1] ... [4] ... [2] ... [5] ... [3] ... [4] ... [6]] References ----------- - `TensorFlow word2vec tutorial <https://www.tensorflow.org/versions/r0.9/tutorials/word2vec/index.html#vector-rep...
dyachan/django-usuario
setup.py
Python
mit
1,204
0.001661
import os from setuptools import setup with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme: README = readme.read() # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name='django-usuario', version='0.4', ...
include_package_data=True, license='MIT License', description='Extension to model User.', long_description=README, keywords = "django user", url='https://github.com/dyachan/django-usuario', author='Diego Yachan', author_email='diego.yachan@gmail.com', classifiers=[ 'Environment ...
rs', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language ::...
amitu/djangothis
djangothis/__init__.py
Python
bsd-3-clause
64
0
from djangothis.app import re
ad_
yaml, read_yaml_file, watchfile
pombredanne/pythran
website/support.py
Python
bsd-3-clause
1,151
0
#!/usr/bin/env python from pythran import tables TITLE = "Supported Modules and Functions" DEPTHS = '=*-+:~#.^"`' print(DEPTHS[0]*len(TITLE)) print(TITLE) print(DEPTHS[0]*len(TITLE)) print("") def format_name(name): if name.endswith('_') and not name.startswith('_'): name = name[:-1] return name ...
m) for k in sorted(sym_entries): dump_entry(format_name(k), entry_value[k], depth + 1) print("") for k in sorted(sub_entries): dump_entry(format_name(k), entry_value[k], depth + 1) print("") el
se: print(entry_name) for MODULE in sorted(tables.MODULES): if MODULE != '__dispatch__': dump_entry(format_name(MODULE), tables.MODULES[MODULE], 1)
adminq80/Interactive_estimation
game/round/migrations/0014_auto_20161102_2154.py
Python
mit
509
0.001965
# -*- coding: utf-8 -*- # Generated b
y Django 1.10.1 on 2016-11-02 21:54 from __future__ import unicode_literals from decimal import Decimal from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('round', '0013_plot_batch'), ] operations = [ migrations.AlterField( mode...
=Decimal('0'), max_digits=4), ), ]
botswana-harvard/ba-namotswe
ba_namotswe/tests/test_enrollment_model.py
Python
gpl-3.0
3,230
0.002786
from django.test.testcases import TestCase from django.utils import timezone from edc_visit_schedule.site_visit_schedules import site_visit_schedules from edc_visit_tracking.constants import SCHEDULED from ba_namotswe.models import Appointment, SubjectVisit, RequisitionMetadata, CrfMetadata, SubjectConsent, Registere...
nrollmentFactory() appointment = Appointment.objects.all().order_by('visit_code').first() SubjectVisit.objects.create( appointment=appointment,
report_datetime=timezone.now(), reason=SCHEDULED, ) schedule = site_visit_schedules.get_schedule(appointment.schedule_name) visit = schedule.get_visit(appointment.visit_code) self.assertGreater(CrfMetadata.objects.all().count(), 0) self.assertEqual(CrfMetadata.objects...
dilynfullerton/tr-A_dependence_plots
src/deprecated/nushellx_lpt/metafitter_abs.py
Python
cc0-1.0
4,879
0
"""nushellx_lpt/metafitter_abs.py Function definitions for an abstract *.lpt metafitter """ from __future__ import print_function, division, unicode_literals import numpy as np from deprecated.int.metafitter_abs import single_particle_metafit_int from constants import DPATH_SHELL_RESULTS, DPATH_PLOTS from deprecated....
urn: (x, y, const_list, const_dict), where const_list and const_dict contain exp, n, and zbt array """ x, y = map_to_arrays(me_map) zbt_list = list() x_arr, zbt_arr = map_to_arrays(mzbt_map) for xa, zbta, i in zip(x_arr, zbt_arr, range(len(
x_arr))): if xa in x: zbt_list.append(zbta) zbt_arr_fixed = np.array(zbt_list) const_list = [exp, n, np.array(zbt_arr_fixed)] const_dict = {'exp': exp, 'N': n, 'zbt_arr': zbt_arr_fixed} return x, y, const_list, const_dict # noinspection PyUnusedLocal def _get_plots_lpt(exp_list, da...
cindywang0728/adminset
setup/ansible.py
Python
apache-2.0
8,413
0.000713
#! /usr/bin/env python # -*- coding: utf-8 -*- from subprocess import Popen, PIPE from cmdb.models import Host, HostGroup from django.shortcuts import render from django.http import HttpResponse import os from config.views import get_dir from django.contrib.auth.decorators import login_required from accounts.permissio...
render(request, 'setup/result.html', locals()) @login_required() @permission_verify() def host_sync(request): group = HostGroup.objects.all() ansible_file = open(ansible_dir+"/hosts", "wb") all_host = Host.objects.all() for host in all_host: #gitlab ansible_host=10.100.1.76 host_name=gitlab ...
_file.write(host_item) for g in group: group_name = "["+g.name+"]"+"\n" ansible_file.write(group_name) members = Host.objects.filter(group__name=g) for m in members: group_item = m.hostname+"\n" ansible_file.write(group_item) ansible_file.close() loggi...
jrappen/sublime-distractionless
main.py
Python
isc
195
0
#!/usr/bin/env pyth
on # coding: utf-
8 from .src import * def plugin_loaded(): distractionless.plugin_loaded(reload=False) def plugin_unloaded(): distractionless.plugin_unloaded()
pvagner/orca
test/keystrokes/java/role_radio_button.py
Python
lgpl-2.1
16,318
0.003003
#!/usr/bin/python """Test of radio buttons in Java's SwingSet2.""" from macaroon.playback import * import utils sequence = MacroSequence() ########################################################################## # We wait for the demo to come up and for focus to be on the toggle button # #sequence.append(WaitForW...
tton Demo TabList Button Demo Page Radio Buttons TabList Radio Buttons Page Text Radio Buttons Panel Text Radio Buttons & y Radio One RadioButton'", " VISIBLE: '& y Radio One RadioButton', cursor=1", "SPEECH OUTPUT: 'Text Radio Buttons panel Radio One not selected radio button'"])) ##
###################################################################### # Expected output when radio button is selected. # # BRAILLE LINE: 'SwingSet2 Application SwingSet2 Frame RootPane LayeredPane Button Demo TabList Button Demo Radio Buttons TabList Radio Buttons Text Radio Buttons Panel &=y Radio One RadioButton'...
grlee77/scipy
scipy/linalg/tests/test_interpolative.py
Python
bsd-3-clause
8,973
0.000223
#****************************************************************************** # Copyright (C) 2013 Kenneth L. Ho # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # Redistributions of source code must retain the...
k(M, rank_tol) assert_(rank_est >= rank_np) assert_(rank_est <= rank_np + 10) def test_rank_estimates_lin_op(self, A): B = np.array([[1, 1, 0], [0, 0, 1], [0, 0, 1]], dtype=A.dtype) for M in [A, B]: ML = aslinearoperator(M) rank_tol = 1e-9 ...
rank_est = pymatrixid.estimate_rank(ML, rank_tol) assert_(rank_est >= rank_np - 4) assert_(rank_est <= rank_np + 4) def test_rand(self): pymatrixid.seed('default') assert_allclose(pymatrixid.rand(2), [0.8932059, 0.64500803], rtol=1e-4, atol...
JensRantil/cabot
app/celeryconfig.py
Python
mit
703
0
import os from datetime import timedelta BROKER_URL = os.environ['CELERY_BROKER_URL'] CELERY_IMPORTS
= ('app.cabotapp.tasks', ) CELERYBEAT_SCHEDULER = "djcelery.schedulers.DatabaseScheduler" CELERY_TASK_SERIALIZER = "json" CELERY_ACCEPT_CONTENT = ['json', 'msgpack', 'yaml'] CELERYBEAT_SCHEDULE = { 'run-all-checks': { 'task': 'app.cabotapp.tasks.run_all_checks', 'schedule': timedelta(seconds=60), ...
app.tasks.update_shifts', 'schedule': timedelta(seconds=1800), }, 'clean-db': { 'task': 'app.cabotapp.tasks.clean_db', 'schedule': timedelta(seconds=60*60*24), }, } CELERY_TIMEZONE = 'UTC'
germanop/sm
tests/test_SMBSR.py
Python
lgpl-2.1
3,181
0.006602
import unittest import mock import SMBSR import xs_errors import XenAPI import vhdutil import util import errno class FakeSMBSR(SMBSR.SMBSR): uuid = None sr_ref = None mountpoint = None linkpath = None path = None session = None remoteserver = None def __init__(self, srcmd, none): ...
password = 'aPassword'): srcmd = mock.Mock() srcmd.dconf = { 'server': server, 'serverpath': serverpath, 'username': username, 'password': password } srcmd.params = { 'command': 'some_command', 'device_config': {} ...
= FakeSMBSR(srcmd, None) smbsr.load(sr_uuid) return smbsr #Attach @mock.patch('SMBSR.SMBSR.checkmount') @mock.patch('SMBSR.SMBSR.mount') def test_attach_smbexception_raises_xenerror(self, mock_mount, mock_checkmount): smbsr = self.create_smbsr() mock_mount = mock.Mock(si...
xrg/openerp-server
bin/tools/amount_to_text.py
Python
agpl-3.0
7,774
0.012223
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the...
mod) return word def french_number(val): if val < 100: return _convert_nn_fr(val) if val < 1000: return _convert_nnn_fr(val) for (didx, dval) in ((v - 1, 1000 ** v) for v in range(len(denom_fr))): if dval > val: mod = 1000 ** didx l = val // mod ...
ret def amount_to_text_fr(number, currency): number = '%.2f' % number units_name = currency list = str(number).split('.') start_word = french_number(abs(int(list[0]))) end_word = french_number(int(list[1])) cents_number = int(list[1]) cents_name = (cents_number > 1) and ' Cents' or ' Cent'...
nicolaszein/chat
chat/models.py
Python
bsd-3-clause
2,028
0.00642
# -*- coding:utf-8 -*- from __future__ import unicode_literals from django.db import models from django.utils import timezone from django.utils.text import slugify from django.contrib.auth.models import User ROOM_TYPE = ( (1, u'Privado'), (2, u'Grupo'), ) class Room(models.Model): name = models.TextField(...
sage_user') message = models.TextField() timestamp = models.DateTimeField(default=timezone.now, db_index=True) def __unicode__(self): return '[{timestamp}] {handle}: {message}'.format(**self.as_dict()) @property def formatted_timestamp(self): return self.timestamp.strftime('%d/%m/%...
me()), 'message': self.message, 'timestamp': self.formatted_timestamp} SEXO = ( (1, u'Masculino'), (2, u'Feminino'), ) class UserProfile(models.Model): user = models.ForeignKey(User, verbose_name=u'Usuário', related_name='profile_user') avatar = models.ImageField(u'Foto', max_length=255, upload_to='us...
maximeolivier/pyCAF
pycaf/architecture/devices/__init__.py
Python
gpl-3.0
378
0
""" Import all modul
es and packages in the serverFeatures package ['account', 'connection', 'interface', 'package', 'process'] """ from pycaf.architecture.devices.server import Server from pycaf.architecture.devices.lists.serverList import ServerList from pycaf.architecture.devices.server_windows import ServerWindows import pycaf.archit...
tures.lists
BrainTech/openbci
obci/control/peer/configured_client.py
Python
gpl-3.0
3,186
0.003766
#!/usr/bin/python # -*- coding: utf-8 -*- from multiplexer.clients import connect_client from obci.control.peer.peer_control import PeerControl, ConfigNotReadyError import obci.control.common.config_message as cmsg from obci.utils.openbci_logging import get_logger, log_crash import sys class ConfiguredClient(object)...
lues()) @log_crash def get_param(self, param_name): return self.config.get_param(param_name) @log_crash def set_param(self, param_name, param_value): self.config.set_param
(param_name, param_value) @log_crash def ready(self): self.ready_to_work = True self.config.register_config(self.conn) self.config.send_peer_ready(self.conn) def validate_params(self, params): self.logger.info("VALIDATE PARAMS, {0}".format(params)) return True ...
matteoredaelli/scrapy_tyres
scrapy_tyres/spiders/auto-doc_it.py
Python
gpl-3.0
4,693
0.012785
# -*- coding: utf-8 -*- # scrapy_web # Copyright (C) 2016-2017 Matteo.Redaelli@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # ...
nr"]/text()').extract_first() description = "%s %s" % (product, size) p = re.compile(brand, re.IGNORECASE) product = re.sub(p,"", product, re.IGNORECASE) price = entry.xpath('.//p[@class="actual_price"]/text()').extract_first() picture_url = entry.xpath('.//im...
extract_first() eu_wet = entry.xpath('.//div[@class="eu_re"]//li[4]/img/@src').extract_first() eu_noise = entry.xpath('.//div[@class="eu_re"]//li[6]/text()').extract_first() if eu_fuel: m=re.match(".+-letter-(.+)\.png",eu_fuel) if m: ...
nasonfish/mammon
mammon/utility.py
Python
isc
7,875
0.002159
# mammon - utility/third-party stuff, each thing has it's own header and provenance # information. # CaseInsensitiveDict from requests. # # Copyright 2015 Kenneth Reitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may...
elf.max_age = max_age_seconds def __contains__(self, key): try: item = collections.OrderedDict.__getitem__(self, key.casefold()) if time.time() - item[1] < self.max_age: return True else: del self[key.casefold()] except KeyError: ...
e=None): item = collections.OrderedDict.__getitem__(self, key.casefold()) item_age = time.time() - item[1] if not max_age: max_age = self.max_age if item_age < max_age: if with_age: return item[0], item_age else: return ...
yaoyansi/mymagicbox
common/mymagicbox/AETemplateBase.py
Python
mit
2,176
0.011029
""" To create an Attribute Editor template using python, do the following: 1. create a subclass of `uitypes.AETemplate` 2. set its ``_nodeType`` class attribute to the name of the desired node type, or name the class using the convention ``AE<nodeType>Template`` 3. import the module AETemplates which do not meet o...
`AETemplate.nodeType()`` class method:: import AETemplates AETemplates.AEmib_amb_occlusionTemplate.nodeType() As a convenience, when pymel is imported it will automatically import the module ``AETemplates``, if it exists, thereby causing any AETemplates w
ithin it or its sub-modules to be registered. Be sure to import pymel or modules containing your ``AETemplate`` classes before opening the Atrribute Editor for the node types in question. To check which python templates are loaded:: from pymel.core.uitypes import AELoader print AELoader.loadedTemplates() The examp...
doublehou/BiliDan
bilidan.py
Python
mit
23,014
0.003825
#!/usr/bin/env python3 # Biligrab-Danmaku2ASS # # Author: Beining@ACICFG https://github.com/cnbeining # Author: StarBrilliant https://github.com/m13253 # # Biligrab is licensed under MIT licence # Permission has been granted for the use of Danmaku2ASS in Biligrab # # Copyright (c) 2014 # # Permission is hereby granted...
ment.bilibili.com/%(cid)s.xml' if source == 'overseas': url_get_media = 'http://interface.bil
ibili.com/v_cdn_play?' else: url_get_media = 'http://interface.bilibili.com/playurl?' def parse_url(url): '''Parse a bilibili.com URL Return value: (aid, pid) ''' regex = re.compile('http:/*[^/]+/video/av(\\d+)(/|/index.html|/index_(\\d+).html)?(\\?|#|$)') regex...
pylanglois/uwsa
uwsas/commands/command_manager.py
Python
bsd-3-clause
619
0.004847
#!/usr/bin/env python # coding=UTF-8 __author__ = "Pierre-Yves Langlois" __copyright__ = "https://github.com/pylanglois/uwsa/blob/master/LICENCE" __credits__ = ["Pierre-Yves Langlois"] __license__ = "BSD" __maintainer__ = "Pierre-Yves Langlois" from uwsas.common import * from uwsas.commands.abstract_command import A...
" Usage: uwsa cmd param where cmd in %s """) def get_log_name(self): return 'uwsas' cmanager = CommandManager()
superberny70/plugin.video.pelisalacarta-3-9X
pelisalacarta/channels/nolomires.py
Python
gpl-3.0
24,186
0.027578
# -*- coding: iso-8859-1 -*- #------------------------------------------------------------ # pelisalacarta - XBMC Plugin # Canal para nolomires.com by Bandavi # http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/ #------------------------------------------------------------ import urlparse,urllib2,urllib,re import o...
earch") buscador.salvar_busquedas(params,Url,category) Url = Url.replace(" ", "+") searchUrl = "http://www.nolomires.com/?s="+Url+"&x=1
5&y=19" listvideos(params,searchUrl,category) def search(params,Url,category): buscador.listar_busquedas(params,Url,category) def ListaCat(params,url,category): logger.info("[nolomires.py] ListaCat") xbmctools.addnewfolder( __channel__ ,"listvideos", category , "Acción","http://www.nol...
abilian/abilian-core
src/abilian/web/admin/panel.py
Python
lgpl-2.1
1,333
0.0015
"""""" from __future__ import annotations from typing import TYPE_CHECKING, Any, Callable, Dict if TYPE_CHECKING: from .extension import Admin class AdminPanel: """Base classe for admin panels. Currentl
y this class does nothing. It may be useful in the future either as just a marker interface (for automatic plugin discovery / registration), or to add some common functionnalities. Otherwise, it will be removed. """ id: str = "" label: str = "" icon: str = "" admin: Admin def url_v...
eprocess values for their views. This method is called only if the endpoint is for `get()`, `post()`, or one of the views installed with `install_additional_rules`. This is also the right place to add items to the breadcrumbs. """ def install_additional_rules(self, add_url_rule: C...
shlomif/PySolFC
pysollib/games/klondike.py
Python
gpl-3.0
55,884
0
#!/usr/bin/env python # -*- mode: python; coding: utf-8; -*- # ---------------------------------------------------------------------------## # # Copyright (C) 1998-2003 Markus Franz Xaver Johannes Oberhumer # Copyright (C) 2003 Mt. Hood Playing Card Co. # Copyright (C) 2005-2009 Skomoroh # # This program is free softwa...
eturn lay def startGame(self, flip=0, reverse=1): for i in range(1, len(self.s.rows)): self.s.talon.dealRow( rows=self.s.rows[i:], flip=flip, frames=0, reverse=reverse) self.startDealSample() self.s.talon.dealRow(reverse=reverse) if self.s.waste: ...
************************************************* # * Vegas Klondike # ************************************************************************ class VegasKlondike(Klondike): getGameScore = Game.getGameScoreCasino getGameBalance = Game.getGameScoreCasino def createGame(self, max_rounds=1): lay = K...
cmouse/buildbot
master/buildbot/steps/source/svn.py
Python
gpl-2.0
17,366
0.000921
# This file is part of Buildbot. Buildbot 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, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without eve...
rrors) @defer.inlineCallbacks def run_vc(self, branch, revision, patch): self.revision = revision self.method = self._getMethod() self.stdio_log = yield self.addLogForRemoteCommands("stdio") # if the version is new enough, and the password is set, then obfuscate # it ...
orkerVersionIsOlderThan('shell', '2.16'): self.password = ('obfuscated', self.password, 'XXXXXX') else: log.msg("Worker does not understand obfuscation; " "svn password will be logged") installed = yield self.checkSvn() if not installe...
mfcloud/python-zvm-sdk
sample/vlan/createvm_vlan_v1s2.py
Python
apache-2.0
4,094
0.005374
# Copyright 2017 IBM Corp. from zvmconnector import connector import os import time print("Setup client: client=connector.ZVMConnector('9.60.18.170', 8080)\n") client=connector.ZVMConnector('9.60.18.170', 8080) print("Test: send_request('vswitch_get_list')") list = client.send_request('vswitch_get_list') print("Resu...
FILE: %s" % GUEST_PROFILE) p
rint("GUEST_VCPUS: %s" % GUEST_VCPUS) print("GUEST_MEMORY: %s" % GUEST_MEMORY) print("DISK_POOL: %s" % DISK_POOL) print("IMAGE_PATH: %s" % IMAGE_PATH) print("IMAGE_OS_VERSION: %s" % IMAGE_OS_VERSION) print("image_name: %s" % image_name) print("url: %s" % url) print("network_info: %s" % network_info) print("------------...
alexquick/dokku
contrib/dokku-installer.py
Python
mit
13,390
0.002315
#!/usr/bin/env python2.7 import cgi import json import os import re import SimpleHTTPServer import SocketServer import subprocess import sys import threading VERSION = 'v0.14.6' hostname = '' try: command = "bash -c '[[ $(dig +short $HOSTNAME) ]] && echo $HOSTNAME || wget -q -O - icanhazip.com'" hostname = s...
ubprocess.Popen(command, shell=True, stdout=subprocess.PIPE) max_num = 0 exists = False for line in proc.stdout: m = pattern.search(line) if m: # User of the form `user` or `user#` exists exists = True max_num = max(max_num,...
ne def set_debconf_selection(debconf_type, key, value): found = False with open('/etc/os-release', 'r') as f: for line in f: if 'debian' in line: found = True if not found: return ps = subprocess.Popen(['echo', 'dokku dokku/{0} {1} {2}'.format( key...
cstipkovic/spidermonkey-research
python/mozbuild/mozbuild/test/test_mozconfig.py
Python
mpl-2.0
17,780
0.000675
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from __future__ import unicode_literals import os import unittest from shutil import rmtree from tempfile import ( ...
srcdir, relative_mozconfig) with open(path, 'w'): pass orig_dir = os.getcwd() try: os.chdir(curdir) self.assertEqual(os.path.realpath(loader.find_mozconfig()), os.path.realpath(path)) finally: os.chdir(orig_dir...
os.environ[b'MOZCONFIG'] = relative_mozconfig srcdir = self.get_temp_dir() curdir = self.get_temp_dir() dirs = [srcdir, curdir] loader = MozconfigLoader(srcdir) orig_dir = os.getcwd() try: os.chdir(curdir) with self.assertRaises(MozconfigFind...
karllessard/tensorflow
tensorflow/tools/ci_build/linux/mkl/set-build-env.py
Python
apache-2.0
12,236
0.007682
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache L
icense, 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, ...
step21/inkscape-osx-packaging-native
packaging/macosx/Inkscape.app/Contents/Resources/extensions/radiusrand.py
Python
lgpl-2.1
3,583
0.014792
#!/usr/bin/env python ''' Copyright (C) 2005 Aaron Spike, aaron@ekips.org This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Thi...
delta=randomize([0,0], self.options.radiusx, self.options.radiusy, self.options.norm) csp[0][0]+=delta[0] csp[0][1]+=delta[1] csp[1][0]+=delta[0] csp[1][1]+=delta[1] csp[2][0]...
andrey-yemelyanov/competitive-programming
cp-book/ch1/adhoc/time/12148_Electricity.py
Python
mit
1,212
0.005776
# Problem name: 12148 Electricity # Problem url: https://uva.onlinejudge.org/external/121/12148.pdf # Author: Andrey Yemelyanov import sys
import math import datetime def readline(): return sys.stdin.readline().strip() def main(): while True: n_readings = int(readline()) if n_readings == 0: break meter_readings = [] for i in range(n_read
ings): reading = [int(x) for x in readline().split()] date = datetime.date(reading[2], reading[1], reading[0]) consumption = reading[3] meter_readings.append((date, consumption)) c = get_daily_consumption(meter_readings) print(len(c), sum(c)) def get_dail...
Ecotrust/forestplanner
idb_import/treelive_summary/unpivoted/local_util_test_dbh_flexibility.py
Python
bsd-3-clause
3,275
0.00855
import os import sys from django.core.management import setup_environ thisdir = os.path.dirname(os.path.abspath(__file__)) appdir = os.path.realpath(os.path.join(thisdir, '..', '..', '..', 'lot')) sys.path.append(appdir) import settings setup_environ(settings) ############################## import pandas as pd from dj...
cursor.execute(sql) local_rows = dictfetchall(cursor) num_candidates = len(local_rows) print num_candidates if num_candidates < 10: # bail, use last known good query (ie don't assign local_rows to rows) break rows = loc
al_rows if num_candidates <= min_candidates or len(tpa_matches) == len(stand_list): keep_going = False else: tpa_matches.append(remaining.pop()) if rows: df = pd.DataFrame(rows) df.index = df['cond_id'] del df['cond_id'] print df[:25] els...
silenceli/nova
nova/api/openstack/compute/limits.py
Python
apache-2.0
15,344
0.000065
# Copyright 2011 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
s(limiter) # Parse the limits, if any are provided if limits is not None: limits = limiter.parse_limits(limits) self._l
imiter = limiter(limits or DEFAULT_LIMITS, **kwargs) @webob.dec.wsgify(RequestClass=wsgi.Request) def __call__(self, req): """Represents a single call through this middleware. We should record the request if we have a limit relevant to it. If no limit is relevan
sio2project/oioioi
oioioi/suspendjudge/tests.py
Python
gpl-3.0
3,682
0.000543
from celery.exceptions import Ignore from django.urls import reverse from oioioi.base.tests import TestCase from oioioi.contests.models import Contest, ProblemInstance, Submission from oioioi.evalmgr.tasks import create_environ from oioioi.programs.controllers import ProgrammingContestController from oioioi.suspendjud...
login_codes = {'test_user': 403, 'test_admin': 302, 'test_contest_admin': 302} views = [ 'suspend_all', 'resume_and_rejudge', 'suspend_all_but_init', 'resume_and_clear', ] self.client.get('/c/c/') # 'c' becomes the current contest f...
n_codes: for view in views: response = self._empty_post(login, view, problem_instance) self.assertEqual(response.status_code, login_codes[login]) class TestSuspending(TestSuspendjudgeSuper): fixtures = [ 'test_users', 'test_contest', 'test_full_p...
vlegoff/tsunami
src/secondaires/navigation/equipage/ordres/lever_ancre.py
Python
bsd-3-clause
2,720
0.000369
# -*-coding:Utf-8 -* # Copyright (c) 2010-2017 LE GOFF Vincent # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # ...
ment("ancre") if not ancre: return if not ancre.jetee: yield SignalInutile("l'ancre est déjà levée") else: ancre.lever(personnage) i = 0 while "ancre" in personnage.etats: i += 1 if i > 100:
yield SignalAbandonne("J'ai essayé trop longtemps.") elif personnage.stats.endurance < 40: yield SignalRelais("Je suis trop fatigué.") else: yield 2 yield SignalTermine()
googleinterns/lasertagger
tagging_converter_test.py
Python
apache-2.0
4,946
0.002431
# coding=utf-8 # Copyright 2019 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
'phrase_vocabulary': [',', 'and', ', and'], # Although, it would be possible to add ", and" and delete "And", this # shouldn't happen so that the tag
sequences are as simple as # possible. 'target_tags': ['KEEP', 'DELETE|,', 'KEEP', 'KEEP', 'KEEP'], }, # Test that necessary phrases are added. { 'input_texts': ['A . And B .'], 'target': 'A , and B .', 'phrase_vocabulary': [', and'], # Now w...
blond-admin/BLonD
unittests/beams/test_beam_object.py
Python
gpl-3.0
14,105
0.001347
# coding: utf-8 # Copyright 2017 CERN. This software is distributed under the # terms of the GNU General Public Licence version 3 (GPL Version 3), # copied verbatim in the file LICENCE.md. # In applying this licence, CERN does not waive the privileges and immunities # granted to it by virtue of its status as an Intergo...
ype(self.beam.dt[0]).__name__, msg='Beam: dt does not contain float') self.assertIn('float', type(self.beam.dE[0]).__name__, msg='Beam: dE does not contain float') def test_beam_statistic(self): sigma_dt = 1. sigma_dE = 1. self.beam.dt = ...
s) self.beam.dE = sigma_dE*numpy.random.randn(self.beam.n_macroparticles) self.beam.statistics() self.assertAlmostEqual(self.beam.sigma_dt, sigma_dt, delta=1e-2, msg='Beam: Failed statistic sigma_dt') self.assertAlmostEqual(self.beam.sigma_dE, sigma_dE, d...