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
li-xirong/jingwei
util/simpleknn/bigfile.py
Python
mit
3,569
0.009526
import os, sys, array import numpy as np class BigFile: def __init__(self, datadir): self.nr_of_images, self.ndims = map(int, open(os.path.join(datadir,'shape.txt')).readline().split()) id_file = os.path.join(datadir, "id.txt") self.names = open(id_file).read().strip().split() asse...
re.bin") print ("[%s] %dx%d instances loaded from %s" % (self.__class__.__name__, self.nr_of_images, self.ndims, datadir)) self.fr = None self.current = 0 def open(self): self.fr = open(os.path.join(self.feat_dir,'feature.bin'), 'rb') self.current = 0 def close(sel...
return self def next(self): if self.current >= self.nr_of_images: self.close() raise StopIteration else: res = array.array('f') res.fromfile(self.fr, self.ndims) _id = self.names[self.current] self.current += 1 ...
jlcarmic/producthunt_simulator
venv/lib/python2.7/site-packages/scipy/sparse/csgraph/tests/test_traversal.py
Python
mit
2,390
0
from __future__ import division, print_function, absolute_import import numpy as np from numpy.testing import assert_array_almost_equal from scipy.sparse.csgraph import breadth_first_tree, depth_first_tree,\ csgraph_to_dense, csgraph_from_dense def test_graph_breadth_first(): csgraph = np.array([[0, 1, 2, 0,...
aph, 0, directed) assert_array_almost_equal(csgraph_to_dense(dfirst_test), dfirst) def test_graph_breadth_first_trivial_graph(): csgraph = np.array([[0]]) csgraph = csgraph_from_dense(csgraph, null_value=0) bfirst = np.array([[0]]) for directed in [True, Fal...
first_tree(csgraph, 0, directed) assert_array_almost_equal(csgraph_to_dense(bfirst_test), bfirst) def test_graph_depth_first_trivial_graph(): csgraph = np.array([[0]]) csgraph = csgraph_from_dense(csgraph, null_value=0) bfirst = np.array([[0]]) for directed ...
TeamADEA/Hunger_Games
HG_Driver.py
Python
mit
1,353
0.01626
from HG_Code.HG_Test import UnitTest as UT from HG_Code import Model as mo from HG_Code.Visualize import Visualizer from HG_Code.SimManager import sim_manager from HG_Code.Hunger_Grid import hunger_grid from HG_Code.Kat import Kat from HG_Code import hg_settings from HG_Code import Mutate as mu unitTest = UT.Run_Unit_...
3, 'Lava World', -1) #mo.run_model(.2,.2,.05,.01, 10, 50, 33, 33, 'Nuclear Wasteland') #mo.run_model(.02,.5,.05,.5, 10, 10, 33, 33, 'Berry World') #mo.run_model(.00,.00,.1,.1, 10, 10, 33, 33, "No Lava") #mo.run_model(.1,.1,0.0,0.0, 10, 10, 33, 33, "No Berries") #mo.run_model(.1,.1,.1
,.1,10,10,33,33,"Lava & Berries")
theolind/pymysensors
mysensors/cli/gateway_tcp.py
Python
mit
1,102
0
"""Start a tcp gateway.""" import click from mysensors.cli.helper import ( common_gateway_options, handle_msg, run_async_gateway, run_gateway, ) from mysensors.gateway_tcp import AsyncTCPGateway, TCPGateway def common_t
cp_options(func): """Supply common tcp gateway options.""" func = click.option( "-p", "--port", default=5003, show_default=True,
type=int, help="TCP port of the connection.", )(func) func = click.option( "-H", "--host", required=True, help="TCP address of the gateway." )(func) return func @click.command(options_metavar="<options>") @common_tcp_options @common_gateway_options def tcp_gateway(**kwargs): ...
sunfishcode/cretonne
lib/cretonne/meta/cdsl/typevar.py
Python
apache-2.0
30,326
0.000132
""" Type variables for Parametric polymorphism. Cretonne instructions and instruction transformations can be specified to be polymorphic by using type variables. """ from __future__ import absolute_import import math from . import types, is_power_of_two from copy import copy try: from typing import Tuple, Union, ...
turn intv if intv: return full_range else: return (default, default) def interval_to_set(intv): # type: (Interval) -> Set if is_empty(intv): return set() (lo, hi) = intv assert is_power_of_two(lo) assert is_power_of_two(hi) assert lo <= hi return set([2**i...
rue iff bits is a legal bit width for a bool type. bits == 1 || bits \in { 8, 16, .. MAX_BITS } """ return bits == 1 or \ (bits >= 8 and bits <= MAX_BITS and is_power_of_two(bits)) class TypeSet(object): """ A set of types. We don't allow arbitrary subsets of types, but use a parametr...
amife/carpool
service/src/call2ride/interface.py
Python
gpl-3.0
62,939
0.018145
""" Open CarPool is a free and open source carpooling/dynamic ride sharing system, open to be connected to other car pools and public transport. Copyright (C) 2009-2014 Julian Rath, Oliver Pintat This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License...
e.time(timeplus.hour, timeplus.minute) resu
ltdate = datetime.datetime.combine(date, time) ## Check Datetime, if in the past use tomorrow if (timeplus2 > time or force) and start_date_bool: if checkonly: return True aday = datetime.timedelta(days=1) resultdate = resultdate + aday if checkonly: return False resultd...
scls19fr/openchrono
openchrono/databuffer.py
Python
gpl-3.0
1,914
0.009404
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function, absolute_import CSV_DEFAULT_SEP = ',' CSV_DEFAULT_LF = '\n' def append_same_length(columns, data): if columns != []: return len(columns) == len(data) return True class DataBuffer(object): def __init__(self, csv_...
, "b", "c"] data.append(1, 2.5, 3) data.append(4, 5, 6) data.append(7, 8, 9) data.close() def main_with_context_manager(): """ Using a context manager (with ...) will automatically
close file descriptor """ with DataBuffer("data.csv") as data: data.columns = ["a", "b", "c"] data.append(1, 2.5, 3) data.append(4, 5, 6) data.append(7, 8, 9) if __name__ == '__main__': main_with_context_manager()
OSSOS/MOP
src/ossos/core/ossos/pipeline/update_astrometry.py
Python
gpl-3.0
19,113
0.006017
#!python """ Update the astrometric and photometric measurements of an mpc observation based on the header contents of the observation. """ from copy import deepcopy import time from astropy import units import os import math import numpy import logging import re import mp_ephem from ossos import storage, wcs, astrom f...
wcs.xy2sky(x, y, usepv=True) new_sep = mpc_in.coordinate.separation(new_coordinate) if new_sep < TOLERANCE*2: mpc_obs.coordinate = new_coordinate mpc_obs.comment.x = x mpc_obs.comment.y = y sep = new_sep if sep > TOLERANCE: ...
-> large offset when using comment line X/Y to compute RA/DEC") if reset_pixel_coordinates: logging.warn("Using RA/DEC and original WCS to compute X/Y and replacing X/Y in comment.".format(sep)) header2 = _connection_error_wrapper(storage.get_astheader, expnum, ccd) image_wcs = ...
cowboysmall/rosalind
src/textbook/rosalind_ba4l.py
Python
mit
569
0.015817
import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), '../tools')) import files import table import genetics def main(argv): int_mass = table.integer_mass(argv[0]) lines = files.r
ead_lines(argv[1]) leaderboard = [([int_mass[p] for p in peptide], peptide) for peptide in lines[0].split()] spectrum
= [int(m) for m in lines[1].split()] N = int(lines[2]) print ' '.join(leader[1] for leader in genetics.trim_leaderboard(leaderboard, spectrum, N)) if __name__ == "__main__": main(sys.argv[1:])
fsxfreak/club-suite
clubsuite/suite/models/__init__.py
Python
mit
216
0
from .mdl_user import * from .mdl_club import * from .mdl_event import * from .mdl_receipt import * from .mdl_budget import * from .mdl
_division import * from .mdl_eventsignin import * from .mdl_joinrequest import *
fabricehong/zim-desktop
zim/__init__.py
Python
gpl-2.0
7,256
0.008131
# -*- coding: utf-8 -*- # Copyright 2008-2014 Jaap Karssenberg <jaap.karssenberg@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 2 of the License, or # (at your optio...
later version. This program is distributed in the hope that it will b
e useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ''' import os import sys import gettext import logging import locale logger = logging.getLogger('zim') #: This parameter can be set by ./setup.py, can be e.g. "maemo" PLATFORM = None ####...
crepererum/intbitset
tests/test_intbitset.py
Python
gpl-2.0
24,902
0.002972
# -*- coding: utf-8 -*- ## ## This file is part of intbitset. ## Copyright (C) 2007, 2008, 2009, 2010, 2011, 2013, 2014 CERN. ## ## intbitset 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 ...
0], [10, 20, 60, 70], [10, 40, 60, 80], [1000], [10000], [23, 45, 67, 89, 110, 130, 174, 1002, 2132, 23434], [700,
2000], list(range(1000, 1100)), [30], [31], [32], [33], [62], [63], [64], [65], [126], [127], [128], [129] ] self.fncs_list = [ (intbitset.__and__, set.__and__, int.__and__, False), (intbitset.__or__, set.__or__, int.__or__, False),...
GreatFruitOmsk/nativeconfig
nativeconfig/configs/registry_config.py
Python
mit
5,235
0.004585
import logging import winreg from nativeconfig.configs.base_config import BaseConfig LOG = logging.getLogger('nativeconfig') ERROR_NO_MORE_ITEMS = 259 ERROR_NO_MORE_FILES = 18 def traverse_registry_key(key, sub_key): """ Traverse registry key and yield one by one. @raise WindowsError: If key cannot b...
winreg.REG_MULTI_SZ: raise ValueErro
r("value must be a REG_MULTI_SZ") return value except: self.LOG.info("Unable to get array \"%s\" from the registry:", name, exc_info=True) return None def set_array_value_cache_free(self, name, value): try: if value is not None: with...
ychen820/microblog
y/google-cloud-sdk/platform/gsutil/third_party/oauth2client/oauth2client/tools.py
Python
bsd-3-clause
8,468
0.006731
# 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 by applicable law or ...
un() function returns new credentials. The new credentials are also stored in the Storage argument, which updates the file associated with the Storage object. It presumes it is run from a command-line application and supports the following flags: --auth_host_name: Host name to use when running a local web...
horization. (default: 'localhost') --auth_host_port: Port to use when running a local web server to handle redirects during OAuth authorization.; repeat this option to specify a list of values (default: '[8080, 8090]') (an integer) --[no]auth_local_webserver: Run a local web serv...
mass-project/mass_server
mass_flask_config/app.py
Python
mit
2,133
0.002344
import os import subprocess from pymongo import MongoClient from flask import Flask, redirect, url_for, request, flash from flask_bootstrap import Bootstrap from flask_mongoengine import MongoEngine from flask_modular_auth import AuthManager, current_authenticated_entity, SessionBasedAuthProvide
r, KeyBasedAuthProvider from .reverse_proxy import ReverseProxied # Initialize app app = Flask(__name__) app.wsgi_app = ReverseProxied(app.wsgi_app) # Generate or
load secret key BASE_DIR = os.path.dirname(os.path.dirname(__file__)) SECRET_FILE = os.path.join(BASE_DIR, 'secret.txt') try: app.secret_key = open(SECRET_FILE).read().strip() except IOError: try: import random app.secret_key = ''.join([random.SystemRandom().choice('abcdefghijklmnopqrstuvwxyz012...
ferchault/iago
docs/conf.py
Python
mit
8,700
0.006897
# -*- coding: utf-8 -*- # # iago documentation build configuration file, created by # sphinx-quickstart on Wed Sep 28 18:57:03 2016. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All ...
fault.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation. #html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entitie...
malmiron/incubator-airflow
tests/operators/test_http_operator.py
Python
apache-2.0
1,793
0
# -*- coding: utf-8 -*- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed wi
th this work
for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unle...
sakura-internet/saklient.python
saklient/cloud/models/model_routerplan.py
Python
mit
3,430
0.0117
# -*- coding:utf-8 -*- # This code is automatically transpiled by Saklient Translator import six from ..client import Client from .model import Model from ..resources.resource import Resource from ..resources.routerplan import RouterPlan from ...util import Util import saklient str = six.text_type # module saklient....
count): Util.validate_type(count, "int") return self._limit(count) ## Web APIのフィルタリング設定を直接指定します。 # # @param {str} key キー # @param {any} value 値 # @param {bool} multiple=False valueに配列を与え、OR条件で完全一致検索する場合にtrueを指定します。通常、valueはスカラ値であいまい検索されます。 # @return {saklient.cloud.models....
terPlan} def filter_by(self, key, value, multiple=False): Util.validate_type(key, "str") Util.validate_type(multiple, "bool") return self._filter_by(key, value, multiple) ## 次のリクエストのために設定されているステートをすべて破棄します。 # # @return {saklient.cloud.models.model_routerplan.Model_RouterPla...
lipk/pyzertz
pyzertz/table_view.py
Python
apache-2.0
3,483
0.014643
from tile_view import * from table import * from game_state import * from circ_button import * class TableView: GREY = (100,100,100) BLACK = (0,0,0) WHITE = (255,255,255) BGCOLOR = (60,60,100) TILE_COLOR = (90, 255, 90) TILE_RADIUS = 30 TABLE_POS = (245, 90) # table : Table # pl1,...
(surface,state.t.get(tile.col, tile.row)) self.pl1_view.draw(surface, state.pl1) self.pl2_view.draw(surface, state.pl2) for i in range(len(state.t.marbles)): btn = self.marble_stack[i] btn.text = str(state.t.marbles[i]) btn.draw_button(surface) def get_pr...
sed_marble(self, pos): for (i,marble) in enumerate(self.marble_stack): if marble.pressed(pos): return i return None class PlayerView: def __init__(self, pl: Player, pos: (int, int)): self.pos = pos r = int(TableView.TILE_RADIUS/2) self.buttons =...
carcinogoy/MemeRepo
MemeRepo/delete.py
Python
mit
517
0.009671
import flask import MemeRepo.db as db import MemeRepo.funcs as fnc from MemeRepo.config import config def handle(code, uri): result = db.get_file(uri) if result
== None: return flask.render_template("error.html", msg="That file does not exist", code="400"), 400 else: if result['owner'] == code: db.delete_file(uri) return 'deleted' else: return flask.render_template("error.html", msg="You d
o not own that file", code="403"), 403
sxjscience/tvm
apps/topi_recipe/gemm/android_gemm_square.py
Python
apache-2.0
4,440
0.00045
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
= "android" # Change target configuration. # Run `adb shell cat /proc/cpuinfo` to find the arch. arch = "arm64" target = "llvm -mtriple=%s-linux-android" % arch def ngflops(N): return 2.0 * f
loat(N * N * N) / (10 ** 9) dtype = "float32" def evaluate(func, ctx, N, times): a_np = np.random.uniform(size=(N, N)).astype(dtype) b_np = np.random.uniform(size=(N, N)).astype(dtype) a = tvm.nd.array(a_np, ctx) b = tvm.nd.array(b_np, ctx) c = tvm.nd.array(np.zeros((N, N), dtype=dtype), ctx) ...
warrieka/portal4argis_tools
portal/csvportal.py
Python
mit
4,761
0.018694
import arcpy, os, json, csv from portal import additem, shareItem, generateToken, getUserContent, updateItem, getGroupID, deleteItem, getGroupContent from metadata import metadata from ESRImapservice import ESRImapservice class csvportal(object): def __init__(self, user, password, portal, worksspace, group...
n csv_reader: line = [unicode(cell, 'latin-1') for cell in row] name, ds, url = (line[nameCol], line[pathCol], line[urlCol]) if self.ws and os.path.dirname(ds).endswith('.sde'): ds = os.path.join(self.ws , os.path.basename(ds) ) ...
#generate new token every 50 uses if not nr%50 : self.token = generateToken(self.user, self.password, self.portal) nr += 1 ##TODO: DELETE layers in group and not in csv def addLyr(self, dataSource, name, serviceUrl, groupIDs=[]): """Add *da...
kenshay/ImageScript
ProgramData/SystemFiles/Python/Lib/site-packages/win32com/gen_py/C866CA3A-32F7-11D2-9602-00C04F8EE628x0x5x4.py
Python
gpl-3.0
308,803
0.056677
# -*- coding: mbcs -*- # Created by makepy.py version 0.5.01 # By python version 2.7.9 (default, Dec 10 2014, 12:28:03) [MSC v.1500 64 bit (AMD64)] # From type library '{C866CA3A-32F7-11D2-9602-00C04F8EE628}' # On Fri Jun 30 10:48:37 2017 'Microsoft Speech Object Library' makepy_version = '0.5.01' python_version = 0x20...
1 # from enum DISPID_SpeechAudioBufferInfo DISPID_SAFGetWaveFormatEx =3 # from enum DISPID_SpeechAudi
oFormat DISPID_SAFGuid =2 # from enum DISPID_SpeechAudioFormat DISPID_SAFSetWaveFormatEx =4 # from enum DISPID_SpeechAudioFormat DISPID_SAFType =1 # from enum DISPID_SpeechAudioFormat DISPID_SASCurrentDevicePosition=5 # from enum DISPID_SpeechAud...
ovresko/erpnext
erpnext/setup/doctype/supplier_group/supplier_group.py
Python
gpl-3.0
639
0.017214
# -*- coding: utf-8 -*- # Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe.utils.nestedset import NestedSet, get_root_of class SupplierGroup(NestedSet): nsm_parent_field = 'parent_sup...
parent_supplier_group
: self.parent_supplier_group = get_root_of("Supplier Group") def on_update(self): NestedSet.on_update(self) self.validate_one_root() def on_trash(self): NestedSet.validate_if_child_exists(self) frappe.utils.nestedset.update_nsm(self)
bottero/IMCMCrun
examples/Synthetic1/createSyntheticRandomProfile.py
Python
mit
6,749
0.017188
# -*- coding: utf-8 -*- """ Created on Wed Dec 9 21:31:53 2015 Create random synthetic velocity profile + linear first guesses @author: alex """ import random import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D def savitzky_golay(y, window_size, order, deriv=0, rate=1): r...
ordX)+" "+str(coordY)+" "+str(coordZ)+"\n") # Close opened file fo.close() fig = plt.figure() ax = fig.gca(projection='3d') #Axes3D(fig) ax.hold(True) ax.scatter(Xstats,Ystats,Zstats,zdir='z',s=20,c='b') if (len(coordShotsX) > 3): ax.scat
ter(Xshots,Yshots,Zshots,zdir='z',s=20,c='r',marker='^') else: ax.scatter(Xshots,Yshots,Zshots,zdir='z',s=200,c='r',marker='^') ax.set_xlim3d(min(min(Xshots),min(Xstats))-100,max(max(Xshots),max(Xstats))+100) ax.set_ylim3d(min(min(Yshots),min(Ystats))-100,max(max(Yshots),max(Ystats))+100) ax.set_zlim3d(min(min(Zsho...
mfherbst/spack
lib/spack/spack/repo.py
Python
lgpl-2.1
42,050
0.000143
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
# # This program 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 terms and # conditions of the GNU Lesser General Public License for more details. # # You should have received a copy of th...
ion, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ############################################################################## import collections import os import stat import shutil import errno import sys import inspect import imp import re import traceback import tempfile import json from contextlib ...
ytsapras/robonet_site
scripts/reception_data.py
Python
gpl-2.0
34,418
0.014614
import glob import operational_instruments from astropy.io import fits from numpy.fft import fft2, ifft2 import sewpy from astropy import wcs from astropy.table import Table from astropy.io import ascii from astropy.time import Time import pytz import numpy as np import os import time import log_utilities...
logger.info('Loaded the BANZAI catalogue') except : pass except: logger.error('I cannot load the image!') # self.data = science_image.data # self.header
= science_image.header # self.oldheader = science_image.header.copy() self.camera = None self.sky_level = None self.sky_level_std = None self.sky_minimum_level = None self.sky_maximum_level = None self.number_of_stars = None self.ellipticity = None...
wandsdn/RheaFlow
RheaFlow/NetlinkProcessor.py
Python
apache-2.0
6,275
0.000478
#!/usr/bin/env python #-*- coding:utf-8 -*- # # Copyright (C) 2016 Oladimeji Fayomi, University of Waikato. # # 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/licens...
self.notify(['ifaceTable', self.ifaceTable(ipdb)]) if action is 'RTM_NEWADDR': log.info("RTM_NEWADDR happened at %s", str(datetime.now())) self.notify(['ifaceTable', self.ifaceTable(ipdb)]) if action is 'RTM_DELADDR': log.info("RTM_DELADDR happened at %s", s...
Table', self.ifaceTable(ipdb)]) def add_neighbour(self, msg): attributes = msg['attrs'] ip_addr = attributes[0][1] if attributes[1][0] is 'NDA_LLADDR': mac_addr = attributes[1][1] iface_index = msg['ifindex'] host = {'ipaddr': ip_addr, 'mac_addr': mac_add...
erudit/eruditorg
eruditorg/apps/public/auth/urls.py
Python
gpl-3.0
2,483
0.003222
# -*- coding: utf-8 -*- from django.urls import re_path from django.contrib.auth import views as auth_views from django.utils.translation import gettext_lazy as _ from django.urls import reverse_lazy from . import forms from . import views app_name = "auth" urlpatterns = [ # Sign in / sign out re_path( ...
icationForm ), name="login", ), re_path(_(r"^deconnexion/$"), auth_views.LogoutView.as_view(next_page="/"), name="logout"), re_path(_(r"^bienvenue/$"), views.UserLoginLandingRedirectView.as_view(), name="landing"), # Parameters & personal data re_path( _(r"^donnees-personnell...
/$"), views.UserParametersUpdateView.as_view(), name="parameters"), # Password change re_path(_(r"^mot-de-passe/$"), views.UserPasswordChangeView.as_view(), name="password_change"), # Password reset re_path( _(r"^mot-de-passe/reinitialisation/$"), auth_views.PasswordResetView.as_view( ...
mjdarby/RogueDetective
dialogue.py
Python
gpl-2.0
2,401
0.016243
# This stores all the dialogue related stuff import screen class Dialogue(object): """Stores the dialogue tree for an individual NPC""" def __init__(self, npc): super(Dialogue, self).__init__() self.npc = npc self.game = npc.game self.root = None self.currentNode = None def setRootNode(self...
predicate(): availableChoices.append((choice, child)) else: availableChoices.append((choice, child)) npcName = None if self.game.player.notebook.isNpcKnown(self.n
pc): npcName = self.npc.firstName + " " + self.npc.lastName choiceTexts = [choice.choiceText for (choice, child) in availableChoices] screen.printDialogueChoices(self.game.screen, self.game.player, choiceTexts, npcName) choiceIdx = self.game.getDialogueChoic...
uniflex/uniflex
uniflex/core/timer.py
Python
mit
1,583
0
import threading __author__ = "Piotr Gawlowicz" __copyright__ = "Copyright (c) 2015, Technische Universitat Berlin" __version__ = "0.1.0" __email__ = "gawlowicz@tkn.tu-berlin.de" class Timer(object): def __init__(self, handler_): assert callable(handler_) super().__init__() self._handler ...
l): # Avoid cancellation during execution of self._callable() cancel = self._event.wait(interval) if cancel: return self._handler() class TimerEventSender(Timer): # timeout handler is called by timer thread context. # So in order to actual execution context to a
pplication's event thread, # post the event to the application def __init__(self, app, ev_cls): super(TimerEventSender, self).__init__(self._timeout) self._app = app self._ev_cls = ev_cls def _timeout(self): self._app.send_event(self._ev_cls())
tommyp1ckles/hippocrates
server.py
Python
mit
742
0.006739
from flask import Flask from flask import render_template import euclid import queue_constant
s import ast import redis import threading REDIS_ADDRESS = "localhost" REDIS_PORT = 6379 REDIS_DB = 0 app = Flask(__na
me__) @app.route("/") def monitor(): queue = redis.StrictRedis(host=REDIS_ADDRESS, port=REDIS_PORT, db=REDIS_DB) nstatus = [] status = ast.literal_eval(queue.get(queue_constants.NODE_KEY).decode()) for s in status: nstatus.append({"name":s, "status":status[s]["status"]}) return render_templ...
interactiveaudiolab/nussl
nussl/core/__init__.py
Python
mit
1,293
0.000773
""" Core ==== AudioSignals ------------ .. autoclass:: nussl.core.AudioSignal :members: :autosummary: Masks ----- .. automodule:: nussl.core.masks :members: :autosummary: Constants ------------ .. automodule:: nussl.core.constants :members: :autosummary: External File Zoo ----------------- ....
s from . import constants from . import efz_utils from . import play_utils from . import utils from . import mixing from . import masks __all__ = [ 'AudioSi
gnal', 'STFTParams', 'constants', 'efz_utils', 'play_utils', 'utils', 'mixing' 'masks', ]
KyoHS/Python
SingleThreadPortScan.py
Python
gpl-2.0
1,536
0.009115
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Author: S.H. Version: 0.1 Date: 2015-01-17
Description: Scan ip: 74.125.131.0/24 74.125.131.99-125 74.125.131.201 Only three format above. Read ip form a ip.txt, and scan all port(or a list port). """ import os import io import socket fileOpen = open("ip.txt", 'r') fileTemp = open("temp.txt", 'a') for line in fileOpen.readlines(): if li...
for i in range(ip[3], b+1): fileTemp.write(str(ip[0])+"."+str(ip[1])+"."+str(ip[2])+"."+str(i)+"\n") elif line.find("/") != -1: list = line[:line.index("/")] ip = [int(a) for a in list.split(".")] for i in range(256): fileTemp.write(str(ip[0])+"."+str(ip[1])+"."+str(ip[2])+"."+str(i)+"\n"...
chrsrds/scikit-learn
sklearn/covariance/empirical_covariance_.py
Python
bsd-3-clause
9,848
0
""" Maximum likelihood covariance estimator. """ # Author: Alexandre Gramfort <alexandre.gramfort@inria.fr> # Gael Varoquaux <gael.varoquaux@normalesup.org> # Virgile Fritsch <virgile.fritsch@inria.fr> # # License: BSD 3 clause # avoid division truncation import warnings import numpy as np from scipy...
atures) Estimated covariance matrix to be stored, and from which precision is computed. """ covariance = check_array(covariance) # set covariance self.covariance_ =
covariance # set precision if self.store_precision: self.precision_ = linalg.pinvh(covariance) else: self.precision_ = None def get_precision(self): """Getter for the precision matrix. Returns ------- precision_ : array-like ...
RedHatInsights/insights-core
insights/parsers/ls_var_run.py
Python
apache-2.0
1,120
0
""" LsVarRun - command ``ls -lnL /var/run`` ======================================= The ``ls -lnL /var/run`` command provides information for the listing of the ``/var/run`` directory. Sample input is shown in t
he Examples. See ``FileListing`` class for additional information. Sample directory list:: total 20 drwx--x---. 2 0 984 40 May 15 09:29 openvpn drwxr-xr-x. 2 0 0 40 May 15 09:30 plymouth drwxr-xr-x. 2 0 0 40 May 15 09:29 ppp drwxr-xr-x. 2 75 75 40 May 15 09:29 radvd -rw...
drwx------. 2 32 32 40 May 15 09:29 rpcbind -r--r--r--. 1 0 0 0 May 17 16:26 rpcbind.lock Examples: >>> "rhnsd.pid" in ls_var_run False >>> "/var/run" in ls_var_run True >>> ls_var_run.dir_entry('/var/run', 'openvpn')['type'] 'd' """ from insights.specs import Specs from ....
cryptobanana/ansible
docs/bin/plugin_formatter.py
Python
gpl-3.0
26,677
0.002774
#!/usr/bin/env python # (c) 2012, Jan-Piet Mens <jpmens () gmail.com> # (c) 2012-2014, Michael DeHaan <michael@ansible.com> and others # (c) 2017 Ansible Project # # 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...
) with open(fname, 'wb') as f: f.write(to_bytes(text)) else: print(text) def get_plugin_info(module_dir, limit_to=No
ne, verbose=False): ''' Returns information about plugins and the categories that they belong to :arg module_dir: file system path to the top of the plugin directory :kwarg limit_to: If given, this is a list of plugin names to generate information for. All other plugins will be ignored. :r...
menpo/vrml97
vrml/weaktuple.py
Python
bsd-3-clause
4,708
0.015718
"""tuple sub-class which holds weak references to objects""" import weakref class WeakTuple( tuple ): """tuple sub-class holding weakrefs to items The weak reference tuple is intended to allow you to store references to a list of objects without needing to manage weak references directly. For th...
(>=)""" return list(self) >= sequence def __gt__( self, sequence ): """Compare the tuple to another (>)""" return list(self) > sequence def __le__( self, sequence ): """Compare the tuple to another (<=)"""
return list(self) <= sequence def __lt__( self, sequence ): """Compare the tuple to another (<)""" return list(self) < sequence def __ne__( self, sequence ): """Compare the tuple to another (!=)""" return list(self) != sequence def __repr__( self ): """Return a ...
igor-toga/local-snat
neutron/api/v2/base.py
Python
apache-2.0
33,385
0.00012
# Copyright (c) 2012 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...
ctions = member_actions self._primary_key = self._get_primary_key() if self._allow_pagination and self._native_pagination: # Native pagination need native sorting support if not self._native_sorting: raise exceptions.Invalid( _("Native paginati...
not self._allow_sorting: LOG.info(_LI("Allow sorting is enabled because native " "pagination requires native sorting")) self._allow_sorting = True self.parent = parent if parent: self._parent_id_name = '%s_id' % parent['member_nam...
mazvv/travelcrm
travelcrm/forms/leads_offers.py
Python
gpl-3.0
1,762
0
# -*-coding: utf-8 -*- import colander from . import ( SelectInteger, ResourceSchema, BaseForm, BaseSearchForm, ) from ..resources.leads_offers import LeadsOffersResource from ..models.lead_offer import LeadOffer from ..models.currency import Currency from ..models.supplier import Supplier from ..mode...
) supplier_id = colander.SchemaNode( SelectInteger(Supplier), ) currency_id = colander.SchemaNode( SelectInteger(Currency), ) price = colander.SchemaNode( colander.Money(), ) status = colander.SchemaNode( colander.String(), ) descr = colander.Sche...
eadOfferForm(BaseForm): _schema = _LeadOfferSchema def submit(self, lead_offer=None): if not lead_offer: lead_offer = LeadOffer( resource=LeadsOffersResource.create_resource( get_auth_employee(self.request) ) ) lead_of...
Yelp/kafka-utils
tests/acceptance/steps/common.py
Python
apache-2.0
2,265
0
# -*- coding: utf-8 -*- # Copyright 2016 Yelp Inc. # # Licensed under the Apache License, Version 2.0
(the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica
ble law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_...
MrYevral/YevBot
Alternate/MasterBot.py
Python
gpl-3.0
586
0.020478
'''This gile will take arguments from the command line, if none are found it will look
for a .bot file, if that isn't found it will promt the user for auth tokens :- with this information the masterbot will connect to its own twitch channel and await a !connect command''' #Author MrYevral #check for .bot file in current directory import os import sys def getBotInfo(): if len(sys.argv) > 2: if sys.argv...
ot" '''for file in os.listdir("."): if file.endswith(".bot"): print file'''
caioserra/apiAdwords
examples/adspygoogle/dfp/v201306/deactivate_placements.py
Python
apache-2.0
2,253
0.003107
#!/usr/bin/python # # Copyright 2013 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...
'key': 'status', 'value': { 'xsi_type': 'TextValue', 'value': 'ACTIVE' } }] query = 'WHERE status = :status' # Get placements by statement. placements = DfpUtils.GetAllEntitiesByStatementWithService( placement_service, query=query, bind_vars=values) for placement in placements: print ('P...
t['status'])) print 'Number of placements to be deactivated: %s' % len(placements) # Perform action. result = placement_service.PerformPlacementAction( {'type': 'DeactivatePlacements'}, {'query': query, 'values': values})[0] # Display results. if result and int(result['numChanges']) > 0: print 'Number of placem...
mammadori/asteroids
game/ship.py
Python
bsd-3-clause
3,293
0.004555
# -*- coding: utf-8 *-* from pyglet.window import key from pyglet import clock from . import util, physicalobject from . import resources class Ship(physicalobject.PhysicalObject): """A class for the player""" def __init__(self, thrust_image=None, *args, **kwargs): super().__init__(*args, **kwargs) ...
def turn(self, clockwise): self.rotation_speed = clockwise * self.rotate_speed def shoot(self): resources.bullet_sound.play() forward = util.angle_to_vector(self.rotation) bullet_pos = [self.x + self.radius * forward[0], self.y + self.radius * forward[1]] bullet_vel...
d[1]] bullet = physicalobject.PhysicalObject(lifespan=self.bullet_duration, vel=bullet_vel, x=bullet_pos[0], y=bullet_pos[1], img=resources.shot_image, batch=self.batch, group=self.group, screensize=self.screensize) self.bullets.add(bullet) def destroy(self): # check invulnerabi...
zepheira/freemix
freemix/exhibit/admin.py
Python
apache-2.0
632
0.011076
from django.contrib import admin from freemix.exhibit import models class CanvasAdmin(admin.ModelAdmin): list_display = ('title', 'description') search_fields = ('title', 'descriptio
n',) admin.site.register(models.Canvas, CanvasAdmin) class ExhibitAdmin(admin.ModelAdmin): list_display = ('slug', 'owner',) search_fie
lds = ('slug', 'title', 'description', 'owner__username') admin.site.register(models.Exhibit, ExhibitAdmin) class ThemeAdmin(admin.ModelAdmin): list_display = ('title', 'description') search_fields = ('title', 'description',) admin.site.register(models.Theme, ThemeAdmin)
laserkelvin/FTSpecViewer
setup.py
Python
gpl-3.0
214
0
import os req
uirements = ["numpy", "scipy", "pandas", "matplotlib", "peakutils", "uncertainties", "pyqtgraph"] for package in requirements: os.system("pip install " + packag
e)
NetworkAutomation/jaide
jaide/core.py
Python
gpl-2.0
43,240
0.000046
""" This core.py module is part of the Jaide (Junos Aide) package. It is free software for use in manipulating junos devices. To immediately get started, take a look at the example files for implementation guidelines. More information can be found at the github page found here: https://github.com/NetworkAutomation/ja...
connection to the device via a NCClient manager object. | > **NOTE:** The connect
parameter should be ignored under most | > circumstances. Changing it only affects how Jaide first | > connects to the device. The decorator function | > @check_instance will handle moving between session | > types for you. @param host: The IP or host...
simonsmiley/iliasCorrector
iliasCorrector/models.py
Python
mit
2,030
0.002463
from iliasCorrector import db def _split_ident(ident): data = ident.split('_') matr = int(data[-1]) last = data[0] first = ' '.join(data[1:-2]) return first, last, matr class Exercise(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80), unique=True) p...
return '<Exercise {}>'.format(self.name) class Submission(db.Model): id = db.Column(db.Integer, primary_key=True) grade = db.Column(
db.Float) exercise_id = db.Column(db.Integer, db.ForeignKey('exercise.id')) student_ident = db.Column(db.String(256)) files = db.relationship('File', backref='submission', lazy='dynamic') remarks = db.Column(db.Text) def __repr__(self): return '<Submission of {} for exercise {}>'.format(sel...
alexvlis/shape
nnmath.py
Python
gpl-3.0
518
0.021236
import numpy as np tansig = lambda n: 2 / (1 + np.exp(-2 * n)) - 1 sigmoid = lambda n: 1 / (1 + np.exp(
-n)) hardlim = lambda n: 1 if n >= 0 else 0 purelin = lambda n: n relu = lambda n: np.fmax(0, n) square_error = lambda x, y: np.sum(0.5 * (x - y)**2) sig_prime = lambda z: sigmoid(z) * (1 - sigmoid(z)) relu_prime = lambda z: relu(z) * (1 - relu(z)) softmax = lambda n: np.exp(n
)/np.sum(np.exp(n)) softmax_prime = lambda n: softmax(n) * (1 - softmax(n)) cross_entropy = lambda x, y: -np.dot(x, np.log(y))
jskksj/cv2stuff
cv2stuff/tests/test_exception.py
Python
isc
307
0.006515
import pytest def
test_zero_division(): with pytest.raises(ZeroDivisionError): 1 / 0 def test_recursion_depth(): with pytest.raises(RuntimeError) as excinfo: def f(): f() f() assert 'maximum recursi
on depth exceeded' in str(excinfo.value)
bath-hacker/binny
binny/collector/models.py
Python
mit
297
0.006734
from
__future__ import unicode_literals from django.db import models from db.models import Bin class CollectionEntry(models.Model): bin_obj = models.ForeignKey(Bin, related_name='requested_bins') fullness = models.IntegerField() date_added = models.Dat
eTimeField(auto_now_add=True)
weso/CWR-DataApi
tests/grammar/config/test_options.py
Python
mit
919
0
# -*- coding: utf-8 -*- import unittest from cwr.grammar.factory.config import rule_options __author__ = 'Bernardo Martínez Garrido' __license__ = 'MIT' __status__ = 'Development' class TestConfigOptions(unittest.TestCase): def setUp(self): self._rule = rule_options def test_zero_options(self): ...
(result)) self.assertEqual(
'option2', result[0]) def test_two_options(self): line = '(option1, option2)' result = self._rule.parseString(line) self.assertEqual(2, len(result)) self.assertEqual('option1', result[0]) self.assertEqual('option2', result[1])
dagnelies/restfs
old/restfs.py
Python
mit
4,068
0.004916
""" Operations: P - login G - list - list the dir's content G - read - reads a file G - info - infos about a file P - write - writes a file P - mkdir - makes a dir P - copy - to=... P - move - to=... P - delete - DELETE P - logout """ import canister import bottle import os.path import json imp...
open(os.path.join(fpath, name), mode='w') file.write(up)
file.close() elif cmd == 'mkdir': # os.mkdir # build dirs recursively os.makedirs(fpath, exist_ok=True) elif cmd == 'move': if not to: raise Exception('Missing destination ("to=...")') fto = fullpath(to) shutil.move(fpath, fto) elif c...
ducandu/aiopening
aiopening/misc/special.py
Python
mit
1,167
0.003428
""" ------------------------------------------------------------------------- AIOpening - special.py useful functions created: 2017/09/01 in PyCharm (c) 2017 Sven - ducandu GmbH ------------------------------------------------------------------------- """ import numpy as np import tensorflow as tf def we...
the weighting defined by weights (which must sum to 1). """ # An array of the weights, cumulatively summed. cs = np.cumsum(weights) # Find the index of the first weight over a random value. idx = sum(cs < np.random.rand()) return objects[min(idx, len(objects) - 1)] def to_one_hot(ind, dim): ...
ge(len(inds)), inds] = 1 return ret def from_one_hot(v): return np.nonzero(v)[0][0] def from_one_hot_batch(v): if len(v) == 0: return [] return np.nonzero(v)[1] def new_tensor(name, n_dim, dtype): return tf.placeholder(dtype=dtype, shape=[None] * n_dim, name=name)
rbtcollins/lmirror
l_mirror/tests/commands/test_commands.py
Python
gpl-3.0
1,692
0.004728
# # LMirror is Copyright (C) 2010 Robert Collins <robertc@robertcollins.net> # # LMirror is free software: you can redistribute it and/or modify it under the # terms of the GNU General Public License as published by the Fr
ee Software # Foundation, either version 3 of the License, or (at your option) any later # version. # # This program 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 Lic...
# # You should have received a copy of the GNU General Public License along with # this program. If not, see <http://www.gnu.org/licenses/>. # # In the LMirror source tree the file COPYING.txt contains the GNU General Public # License version 3. # """Tests for the commands command.""" from l_mirror.commands impor...
Incogniiito/Chrononaut
my/tensorflow/rnn_cell.py
Python
apache-2.0
9,075
0.003857
import tensorflow as tf from tensorflow.python.ops.rnn_cell import DropoutWrapper, RNNCell, LSTMStateTuple from my.tensorflow import exp_mask, flatten from my.tensorflow.nn import linear, softsel, double_linear_logits class SwitchableDropoutWrapper(DropoutWrapper): def __init__(self, cell, is_train, inpu...
or each in state]
else: tiled_states = [tf.tile(tf.expand_dims(state, 1), [1, _memory_size, 1])] # [N, M, d] in_ = tf.concat(2, [tiled_inputs] + tiled_states + [memory]) out = linear(in_, 1, bias, squeeze=True, input_keep_prob=input_keep_prob, is_train=is_train) ...
rcbops/nova-buildpackage
nova/image/fake.py
Python
apache-2.0
9,011
0.008323
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 Justin Santa Barbara # 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.apach...
image data for the given name.""" images = copy.deepcopy(self.imag
es.values()) for image in images: if name == image.get('name'): return image raise exception.ImageNotFound(image_id=name) def create(self, context, metadata, data=None): """Store the image data and return the new image id. :raises: Duplicate if the image...
holys/ledis-py
ledis/_compat.py
Python
mit
2,327
0.006446
"""Internal module for Python 2 backwards compatibility.""" import sys if sys.version_info[0] < 3: from urlparse import parse_qs, urlparse from itertools import imap, izip from string import letters as ascii_letters from Queue import Queue try: from cStringIO import StringIO as BytesIO ...
d the core # methods to aid implementating different queue organisations. class LifoQueue(Queue): "Override queue methods to implement a last-in first-out queue." def _init(self, maxsize): sel
f.maxsize = maxsize self.queue = [] def _qsize(self, len=len): return len(self.queue) def _put(self, item): self.queue.append(item) def _get(self): return self.queue.pop()
cbrentharris/bricklayer
bricklayer/utils/downloader.py
Python
mit
951
0.005258
import platform import urllib import subprocess from progressbar import ProgressBar class Downloader(object): WINDOWS_DOWNLOAD_URL = "http://cache.lego.com/downloads/ldd2.0/installer/setupLDD-PC-4_3_8.exe" MAC_DOWNLOAD_URL = "http://cache.lego.com/
downloads/ldd2.0/installer/setupLDD-MAC-4_3_8.zip" PB = None @classmethod def download_ldd(cls): if platform.system() == "D
arwin": urllib.urlretrieve(cls.MAC_DOWNLOAD_URL, "ldd.zip", reporthook=cls.download_progress) elif platform.system() == "Windows": urllib.urlretrieve(cls.WINDOWS_DOWNLOAD_URL, "ldd.exe") # subprocess.Popen("ldd.exe") @classmethod def download_progress(cls, count, blo...
m8ttyB/socorro
socorro/unittest/cron/jobs/test_upload_crash_report_json_schema.py
Python
mpl-2.0
1,523
0
# 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 mock from nose.tools import ok_ from crontabber.app import CronTabber from socorro.unittest.cron.jobs.base impo...
tionTestBase from socorro.unittest.cron.setup_configman import ( get_config_manager_for_crontabber, ) from socorro.schemas import CRASH_REPORT_JSON_SCHEMA_AS_STRING class TestUploadCrashReportJSONSchemaCronApp(IntegrationTestBase): def _setup_config_manager(self): return get_config_manager_for_cront...
jobs.upload_crash_report_json_schema.' 'UploadCrashReportJSONSchemaCronApp|30d', ) @mock.patch('boto.connect_s3') def test_run(self, connect_s3): key = mock.MagicMock() connect_s3().get_bucket().get_key.return_value = None connect_s3().get_bucket().new_key.retu...
Gnurou/glmark2
waflib/Logs.py
Python
gpl-3.0
5,584
0.068947
#! /usr/bin/env python # encoding: utf-8 # WARNING! Do not edit! https://waf.io/book/index.html#_obtaining_the_waf_file import os,re,traceback,sys from waflib import Utils,ansiterm if not os.environ.get('NOSYNC',False): if sys.stdout.isatty()and id(sys.stdout)==id(sys.__stdout__): sys.stdout=ansiterm.AnsiTerm(sys.s...
global
log log=logging.getLogger('waflib') log.handlers=[] log.filters=[] hdlr=log_handler() hdlr.setFormatter(formatter()) log.addHandler(hdlr) log.addFilter(log_filter()) log.setLevel(logging.DEBUG) def make_logger(path,name): logger=logging.getLogger(name) hdlr=logging.FileHandler(path,'w') formatter=logging.For...
atmark-techno/atmark-dist
user/bind/contrib/queryperf/utils/gen-data-queryperf.py
Python
gpl-2.0
2,783
0.004671
#!/usr/bin/python # # $Id: gen-data-queryperf.py,v 1.1.10.1 2003/05/15 05:07:21 marka Exp $ # # Contributed by Stephane B
ortzmeyer <bortzmeyer@nic.fr> # # "A small tool which may be useful with contrib/queryperf. This script # can generate files of queries, both with random names (to test the # behaviour with NXdomain) and with d
omains from a real zone file." # import sys import getopt import random import re ldh = [] # Letters for i in range(97, 122): ldh.append(chr(i)) # Digits for i in range(48, 57): ldh.append(chr(i)) # Hyphen ldh.append('-') maxsize=10 tld='org' num=4 percent_random = 0.3 gen = None zone_file = None domains = {...
qsnake/gpaw
gpaw/scf.py
Python
gpl-3.0
2,689
0.002975
import numpy as np from gpaw import KohnShamConvergenceError class SCF
Loop: """Self-consistent field loop. converged: Do we have a self-consistent solution? """ def __init__(self, eigenstates=0.1, energy=0.1, density=0.1, maxiter=100, fixdensity=False, niter_fixdensity=None): self.max_eigenstates_error = max(eigenstates, 1e-20) s...
if niter_fixdensity is None: niter_fixdensity = 2 self.niter_fixdensity = niter_fixdensity if fixdensity: self.fix_density() self.reset() def fix_density(self): self.fixdensity = True self.niter_fixdensity = 10000000 se...
rafaelsilvag/pyNFRouter
test/teste.py
Python
gpl-2.0
798
0.012531
from netfilterqueue import NetfilterQueue from dpkt import ip, icmp, tcp, udp from scapy.all import * import socket def print_and_accept(pkt): data=pkt.get_payload() res = ip.IP(data) res2 = IP(data) i = ICMP(data) t = TCP(data) u = UDP(data) print "SOURCE IP: %s\tDESTINATION IP: %s" % (soc...
resp.dst eth = Ether(src=eth_src, dst=eth_dst) eth.type = 2048 sendp(eth/res2/res2,iface="eth0") pkt.accept() nfqueue = NetfilterQueue() nfqueue.bind(6, print_and_accept) try: nfqueue.run() except KeyboardInterrupt, ex: p
rint ex
unmrds/cc-python
.ipynb_checkpoints/eggs-checkpoint.py
Python
apache-2.0
1,783
0.00673
#!/usr/bin/env python import csv # create an empty list that will be filled with the rows of data from the CSV as dictionaries csv_content = [] # open and loop through each line of the csv file to populate our data file
with open('aaj1945_DataS1_Egg_shape_by_species_v2.csv') as csv_file: csv_reader = csv.DictReader(csv_file) lineNo = 0 for row in csv_reader: # process each row of the csv file csv_content.append(row) if lineNo < 3: # print o
ut a few lines of data for our inspection print(row) lineNo += 1 # create some empty lists that we will fill with values for each column of data order = [] family = [] species = [] asymmetry = [] ellipticity = [] avglength = [] # for each row of data in our dataset write a set of values in...
satnet-project/propagators
output_predict.py
Python
apache-2.0
2,281
0.003069
################################################################################ # Copyright 2015 Samuel Gongora Garcia (s.gongoragarcia@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 Founda...
g with this program. If not, see <http://www.gnu.org/licenses/>. # ###########################################################################
##### # Author: s.gongoragarcia[at]gmail.com ################################################################################ class Read_predict_data: def __init__(self, index_satellite): from os import getcwd, chdir index_satellite = index_satellite + 1 directorio_script = getcwd() ...
SequencingDOTcom/App-Market-API-integration
python/bootstrap/urls.py
Python
mit
231
0
from django.conf.urls import include, url from django.contrib import ad
min urlpat
terns = [ url(r'^admin/', include(admin.site.urls)), url(r'^external/', include('external.urls')), url(r'^dev/', include('dev.urls')), ]
mongodb/motor
test/test_environment.py
Python
apache-2.0
11,605
0.001034
# Copyright 2012-2015 MongoDB, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writin...
= True try: import tornado except ImportError: HAVE_TORNADO = False tornado = None HAVE_ASYNCIO = True try: import asyncio except ImportError: HAVE_ASYNCIO = False asyncio = None HAVE_AIOHTTP = True try:
import aiohttp except ImportError: HAVE_AIOHTTP = False aiohttp = None # Copied from PyMongo. def partition_node(node): """Split a host:port string into (host, int(port)) pair.""" host = node port = 27017 idx = node.rfind(":") if idx != -1: host, port = node[:idx], int(node[idx...
SamR1/FitTrackee
e2e/utils.py
Python
agpl-3.0
2,863
0
import os import random import st
ring from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait TEST_APP_URL = os.get
env('TEST_APP_URL') TEST_CLIENT_URL = os.getenv('TEST_CLIENT_URL') E2E_ARGS = os.getenv('E2E_ARGS') TEST_URL = TEST_CLIENT_URL if E2E_ARGS == 'client' else TEST_APP_URL def random_string(length=8): return ''.join(random.choice(string.ascii_letters) for x in range(length)) def register(selenium, user): selen...
RagtagOpen/bidwire
bidwire/scrapers/massgov/url_scraper_dict.py
Python
mit
1,717
0.008154
UL_CATEGORY_LI = '//ul[@class="category
"]/li' H2_A_TITLELINK = './h2/a[@class="titlelink"]' SPAN_A_TITLELINK = './span/a[@class="titlelink"]' DIV_BODYFIELD_P = '//div[contains(@class,"bodyfield"
)]/p' CATEGORY_H2_XPATH = [ UL_CATEGORY_LI, H2_A_TITLELINK ] BODYFIELD_SPAN_XPATH = [ DIV_BODYFIELD_P, SPAN_A_TITLELINK ] """Mapping of relative URL (for EOPSS pages) to the xpath needed to extract documents (1st xpath for section, 2nd xpath for document link) """ MASSGOV_DICT = { 'homeland-sec/grants/do...
graingert/sqlalchemy
lib/sqlalchemy/orm/loading.py
Python
mit
36,424
0
# orm/loading.py # Copyright (C) 2005-2020 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 """private module containing functions used to convert database rows into object inst...
] result = [] keys = [ent._label_name for ent in query._entities] keyed_tuple = result_tuple( keys, [ent.entities for ent in query._entities] ) for row in iterator: newrow = list(row) for i in mapped_en...
ewrow[i] = session._merge( attributes.instance_state(newrow[i]), attributes.instance_dict(newrow[i]), load=load, _recursive={}, _resolve_conflict_map={}, ) ...
pkimber/booking
booking/tests/scenario.py
Python
apache-2.0
2,769
0.001083
# -*- encoding: utf-8 -*- from __future__ import unicode_literals from datetime import ( datetime, timedelta, ) from dateutil.relativedelta import relativedelta from base.tests.model_maker import clean_and_save from booking.models import ( Booking, Category, Location, ) def get_alpe_d_huez(): ...
head = weekday - d.weekday() if days_ahead <= 0: # Target day already happened this week days_ahead += 7 return d + timedelta(days_ahead) def demo_data(): # set-up some dates today = datetime.today().date() # 1st week last month starting Saturday first_prev_month = today + relativedelt...
') # 2nd week last month make_booking_in_past(end_date, end_date + timedelta(days=7), 'Meribel') # 1st week this month starting Saturday first_this_month = today + relativedelta(day=1) start_date = next_weekday(first_this_month, 5) make_booking_in_past(start_date, start_date + timedelta(days=3),...
alzeih/ava
ava_core/integration/integration_ldap/test_data.py
Python
gpl-3.0
6,603
0.001212
# Rest Imports from rest_framework import status # Local Imports from ava_core.abstract.test_data import AvaCoreTestData from ava_core.integration.integration_ldap.models import LDAPIntegrationAdapter # Implementation class LDAPIntegrationAdapterTestData(AvaCoreTestData): """ Test data for LDAPIntegrationAdap...
: 'unique_char', 'salt': 'unique_char', 'd
ump_dn': 'unique_char', 'ldap_user': 'unique_char', 'ldap_integration_history': '/example/2/', 'integrationadapter_ptr': 'default', 'server': 'unique_char', } missing_ldap_password = { 'salt': 'standard_char', 'dump_dn': 'standard_char', 'ldap_user': 'sta...
aiden0z/snippets
leetcode/049_group_anagrams.py
Python
mit
1,315
0.00076
"""Group Anagrams Given an array of strings, group anagrams together. Example: Input: ["eat", "tea", "tan", "ate", "nat", "bat"] Output: [ ["ate","eat","tea"], ["nat","tan"], ["bat"] ] Note: All inputs will be in lowercase. The order of y...
key in store: store[key].append(item) else: store[key] = [item] return store.values() if __name__ == '__main__': cases = [ ( ["eat", "tea", "tan", "ate", "nat", "bat"], [ ["ate", "eat", "tea"], ["...
ms(case[0]) for l in case[1]: for item in l: found = False for ll in result: if item in ll: found = True assert found
galihmelon/sendgrid-python
sendgrid/helpers/mail/content.py
Python
mit
735
0
class Content(object): def __init__(self, type_=None, value=None): self._type = None
self._value = None if type_ is not None: self.type = type_ if value is not None: self.value = value @property def type(self): return self._type @type.setter def type(self, value):
self._type = value @property def value(self): return self._value @value.setter def value(self, value): self._value = value def get(self): content = {} if self.type is not None: content["type"] = self.type if self.value is not None: ...
hugovk/diff-cover
diff_cover/tool.py
Python
agpl-3.0
6,230
0.000482
""" Implement the command-line tool interface. """ from __future__ import unicode_literals import argparse import os import sys import diff_cover from diff_cover.diff_reporter import GitDiffReporter from diff_cover.git_diff import GitDiffTool from diff_cover.git_path import GitPathTool from diff_cover.violations_report...
t load '{0}'".format(path)) try: reporter = reporter_class(tool, input_reports, user_options=user_options) generate_quality_report( reporter, arg_dict['compare_branch'], arg_dict['html_report'] ) ...
# Close any reports we opened finally: for file_handle in input_reports: file_handle.close() else: LOGGER.error("Quality tool not recognized: '{0}'".format(tool)) exit(1) if __name__ == "__main__": main()
mikaelboman/home-assistant
homeassistant/components/device_tracker/owntracks.py
Python
mit
7,427
0
""" Support the OwnTracks platform. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/device_tracker.owntracks/ """ import json import logging import threading from collections import defaultdict import homeassistant.components.mqtt as mqtt from homeassist...
if location not in beacons: beacons.append(location) _LOGGER.info("Added beacon %s", location) else: # Normal region regions = REGIONS_ENTERED[dev_id] if location not in regions: ...
cation) _LOGGER.info("Enter region %s", location) _set_gps_from_zone(kwargs, location, zone) see(**kwargs) see_beacons(dev_id, kwargs) def leave_event(): """Execute leave event.""" with LOCK: region...
bkpathak/Algorithms-collections
src/DP/coin_play.py
Python
apache-2.0
2,084
0.024952
# Consider a row of n coins of values v1 . . . vn, where n is even. # We play a game against an opponent by alternating turns. In each turn, # a player selects either the first or last coin from the row, removes it # from the row permanently, and receives the value of the coin. Determine the # maximum possible amount o...
efinitely win if we move first. # Note: The opponent is as clever as the user. # http://www.geeksforgeeks.org/dynamic-programming-set-31-optimal-strategy-for-a-game/ def find_max_val_recur(coins,l,r): if l + 1 == r: return max(coins[l],coins[r]) if l == r: return coins[i] left_choose = co...
right_choose = coins[r] + min(find_max_val_recur(coins,l + 1,r-1),find_max_val_recur(coins,l,r-2)) return max(left_choose,right_choose) coin_map = {} def find_max_val_memo(coins,l,r): if l + 1 == r: return max(coins[l],coins[r]) if l == r: return coins[i] if (l,r) in coin_map: ...
lorenzogil/yith-library-server
yithlibraryserver/views.py
Python
agpl-3.0
4,160
0
# Yith Library Server is a password storage server. # Copyright (C) 2012-2013 Yaco Sistemas # Copyright (C) 2012-2013 Alejandro Blanco Escudero <alejandro.b.e@gmail.com> # Copyright (C) 2012-2015 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com> # # This file is part of Yith Library Server. # # Yith Library Server is...
rer='templates/home.pt') def home(request): return {} @view_config(route_name='contact', renderer='templates/contact.pt') def contact(request): button1 = Button('submit', _('Send message')) button1.css_class = 'btn-primary' button2 = Button('cancel', _('Cancel')) button2.css_class = 'btn-default' ...
buttons=(button1, button2)) if 'submit' in request.POST: controls = request.POST.items() try: appstruct = form.validate(controls) except ValidationFailure as e: return {'form': e.render()} context = {'link': request.route_url('contact')} context.upda...
manterd/myPhyloDB
database/migrations/0021_auto_20190305_1458.py
Python
gpl-3.0
1,211
0.001652
# -*- coding: utf-8 -*- # Generated by Django
1.11.12 on 2019-03-05 14:58 from __future__ import unicode_literals from django.conf
import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('database', '0020_daymetdata'), ] operations = [ migrations.CreateModel( name='PublicProjects', fields=[ ...
wooga/airflow
airflow/providers/papermill/operators/papermill.py
Python
apache-2.0
2,587
0.000773
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
iance # 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 perm...
ity/pants
src/python/pants/pantsd/pants_daemon.py
Python
apache-2.0
6,887
0.009438
# coding=utf-8 # Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import logging impor...
ial deadlocks if pre-fork # threads have any locks acquired at the time of fork. logging._lock = threading.RLock() if logging.thread else None for handler in logging.getLogger(
).handlers: handler.createLock() # Invoke a global teardown for all logging handlers created before now. logging.shutdown() # Reinitialize logging for the daemon context. setup_logging(log_level, console_stream=None, log_dir=self._log_dir, log_name=self.LOG_NAME) # Close out pre-fork file d...
nirenzang/Serpent-Pyethereum-Tutorial
pyethereum/ethereum/meta.py
Python
gpl-3.0
2,865
0.00349
from ethereum.slogging import get_logger log = get_logger('eth.block_creation') from ethereum.block import Block, BlockHeader from ethereum.common import mk_block_from_prevstate, validate_header, \ verify_execution_results, validate_transaction_tree, \ set_execution_results, add_transactions, post_finalize from...
timestamp=None, coinbase='\x35'*20, extra_data='moo ha ha says the laughing cow.', min_gasprice=0): log.info('Cr
eating head candidate') if parent is None: temp_state = State.from_snapshot(chain.state.to_snapshot(root_only=True), chain.env) else: temp_state = chain.mk_poststate_of_blockhash(parent.hash) cs = get_consensus_strategy(chain.env.config) # Initialize a block with the given parent and va...
smokeyfeet/smokeyfeet-registration
src/smokeyfeet/registration/forms.py
Python
mit
2,149
0
from django import forms from .models import PassType, Registration class SignupForm(forms.ModelForm): pass_type = forms.ModelChoiceField( queryset=PassType.objects.filter(active=True), widget=forms.widgets.RadioSelect(), ) class Meta: model = Registration fields = ( ...
el = None def clean_workshop_partner_email(self): """ Take care of uniqueness constraint ourselves """ email = self.cleaned_data.get("workshop_partner_email") qs = Registration.objects.filter(workshop_partner_email=email).exists(
) if email and qs: raise forms.ValidationError("Workshop parter already taken.") return email def clean_agree_to_terms(self): data = self.cleaned_data["agree_to_terms"] if data is False: raise forms.ValidationError("You must agree to the terms.") ret...
jmankiewicz/odooAddons
hr_attendance_new_check/__openerp__.py
Python
agpl-3.0
958
0.003135
# -*- coding: utf-8 -*- { 'name': "Better validation for Attendance", 'summary': """ Short (1 phrase/line) summary of the module's purpose, used as subtitle on modules listing or apps.openerp.com""", 'description': """ Long description of module's purpose """, 'author':
"Jörn Mankiewicz", 'website': "http://www.yourcompany.com", # Categories can be used to filter modules in modules listing # Check https://github.com/odoo/odoo/blob/master/openerp/addons/base/module/module_data.xml # for the full list 'category': 'Uncategorized', 'version': '8.0.0.1', # an...
# always loaded 'data': [ # 'security/ir.model.access.csv', 'views/hr_attendance.xml', ], # only loaded in demonstration mode 'demo': [ 'demo.xml', ], }
sebwink/deregnet
graphs/kegg/keggtranslator/bin/make_graphml_igraph_readable.py
Python
bsd-3-clause
169
0.011834
import sys import networkx as nx def main(graphml): g = nx.read_graphml(graphml) nx.write_graphml(g, graphml) if __nam
e__ == '__main__': main(sys.argv[
1])
kmova/bootstrap
docker/py2docker/numpy-sum.py
Python
apache-2.0
323
0.009288
import numpy as np # Example taken from : http://cs231n.github.io/python-numpy-tutorial/#numpy x = np.array([[1,2],[3,4]]) print np.sum(x) # Compute sum of all elements; prints "10" prin
t np.sum(x, axis=0) # Compute sum of each column; pr
ints "[4 6]" print np.sum(x, axis=1) # Compute sum of each row; prints "[3 7]"
dpaleino/bootchart2
pybootchartgui/batch.py
Python
gpl-3.0
1,604
0.006858
# This file is part of pybootchartgui. # pybootchartgui 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. # pybootchartgui is dis...
# along with pybootchartgui. If not, see <http://www.gnu.or
g/licenses/>. import cairo import draw def render(writer, res, options, filename): handlers = { "png": (lambda w, h: cairo.ImageSurface(cairo.FORMAT_ARGB32, w, h), \ lambda sfc: sfc.write_to_png(filename)), "pdf": (lambda w, h: cairo.PDFSurface(filename, w, h), lambda sfc: 0), ...
lmEshoo/st2contrib
packs/sensu/etc/st2_handler.py
Python
apache-2.0
4,880
0.002459
#!/usr/bin/env python import httplib try: import simplejson as json except ImportError: import json import os import sys from urlparse import urljoin try: import requests except ImportError: raise ImportError('Missing dependency "requests". Do ``pip install requests``.') try: import yaml except I...
body['payload'] = json.loads(sys.stdin.read().strip()) _post_event_to_st2(_get_st2_webhooks_url(), body) if __name__ == '__main__': try: if not os.path.exists(ST2_CONFIG_FILE): sys.stderr.write('Configuration file not found. Exiting.\n') sys.exit(1
) with open(ST2_CONFIG_FILE) as f: config = yaml.safe_load(f) ST2_USERNAME = config['st2_username'] ST2_PASSWORD = config['st2_password'] ST2_API_BASE_URL = config['st2_api_base_url'] ST2_AUTH_BASE_URL = config['st2_auth_base_url'] if not REG...
ykaneko/ryu
ryu/tests/unit/ofproto/test_ofproto_common.py
Python
apache-2.0
1,111
0
# Copyright (C) 2012 Nippon Telegraph and Telephone 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 required by appli...
ions under the License. # vim: tabstop=4 shiftwidth=4 softtabstop=4 import unittes
t import logging from nose.tools import eq_ from ryu.ofproto.ofproto_common import * LOG = logging.getLogger('test_ofproto_common') class TestOfprotCommon(unittest.TestCase): """ Test case for ofprotp_common """ def test_struct_ofp_header(self): eq_(OFP_HEADER_PACK_STR, '!BBHI') eq_(OFP...
ErickMurillo/ciat_plataforma
ficha_granos_basicos/views.py
Python
mit
17,583
0.05029
# -*- coding: utf-8 -*- from django.shortcuts import render from .models import * from .forms import * from comunicacion.lugar.models import * from mapeo.models import * from django.http import HttpResponse from django.db.models import Sum, Count, Avg import collections import numpy as np # Create your views here. def...
ESCOLARIDAD_CHOICES: madre = filtro.filter(productor__composicionfamiliar__familia = '2', productor__composicionfamiliar__escolaridad = obj[0]).distinct('productor
__composicionfamiliar').count() padre = filtro.filter(productor__composicionfamiliar__familia = '1', productor__composicionfamiliar__escolaridad = obj[0]).distinct('productor__composicionfamiliar').count() #hijos-------------------- hijos_5_12 = filtro.filter(productor__composicionfamiliar_...
stvstnfrd/edx-platform
openedx/core/djangoapps/embargo/tests/test_models.py
Python
agpl-3.0
12,890
0.001164
"""Tes
t of models for embargo app""" import json import pytest import six from django.db.utils import IntegrityError from django.test import TestCase from opaque_keys.edx.locator import CourseLocator from openedx.core.djangolib.testing.utils import CacheIsolationTestCase from ..models import ( Country, CountryAcc...
EmbargoedCourse, EmbargoedState, IPFilter, RestrictedCourse ) class EmbargoModelsTest(CacheIsolationTestCase): """Test each of the 3 models in embargo.models""" ENABLED_CACHES = ['default'] def test_course_embargo(self): course_id = CourseLocator('abc', '123', 'doremi') # Tes...
antoinecarme/pyaf
tests/artificial/transf_Anscombe/trend_Lag1Trend/cycle_7/ar_/test_artificial_32_Anscombe_Lag1Trend_7__100.py
Python
bsd-3-clause
263
0.087452
i
mport pyaf.Bench.TS_datasets as tsds import tests.artificial.process_artific
ial_dataset as art art.process_dataset(N = 32 , FREQ = 'D', seed = 0, trendtype = "Lag1Trend", cycle_length = 7, transform = "Anscombe", sigma = 0.0, exog_count = 100, ar_order = 0);
theopak/storytellingbot
Extrapolate/Extrapolate.py
Python
mit
7,576
0.005148
#!/usr/bin/python3 #import nltk #import pattern.en from nltk import word_tokenize from nltk import pos_tag from nltk.corpus import wordnet #import nltk.fuf.linearizer from nltk.stem.wordnet import WordNetLemmatizer as wnl from re import sub import string import random from .genderPredictor import genderPredictor #nlt...
self.sent_syns = synonyms search_sent = [] # creates a list of similar sentences to search for for idx, item in enumerate(tag_list): # looks for synonyms at the corresponding index for s in synonyms[idx]: temp = sub(r"\b%s\b" %item[0], s, sent) ...
# will get rid of duplicates once i make it hashable search_sent = list(set(search_sent)) # print("\nSample list of synonymous sentences:") # for i in range(min(len(search_sent), 20)): # print(search_sent[i]) return search_sent if __name__ == '__main__': #list of p...
martyone/sailfish-qtcreator
tests/system/suite_SCOM/tst_SCOM01/test.py
Python
lgpl-2.1
3,047
0.009846
############################################################################# ## ## Copyright (C) 2015 The Qt Company Ltd. ## Contact: http://www.qt.io/licensing ## ## This file is part of Qt Creator. ## ## Commercial License Usage ## Licensees holding valid commercial Qt licenses may use this file in ## accordance wit...
U Lesser General Public License Usage ## Alternatively, this file may be used under the terms of the GNU Lesser ## General Public License version 2.1 or version 3 as published by the Free ## Software Foundation and appearing in the file LICENSE.LGPLv21 and ## LICENSE.LGPLv3 included in the packaging of this file. Plea...
ic License ## requirements will be met: https://www.gnu.org/licenses/lgpl.html and ## http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ## ## In addition, as a special exception, The Qt Company gives you certain additional ## rights. These rights are described in The Qt Company LGPL Exception ## version 1.1, inc...
vphill/eot-cdx-analysis
code/cdx_extract_date.py
Python
cc0-1.0
524
0
from __future__ import print_function import fileinput from datetime import datetime for line in fileinp
ut.input(): line = line.rstrip() # This condition removes CDX header lines if line[0] is ' ': continue # Extract just the timestamp from line timestamp = line.split(' ', 2)[1] # Datetiem format in CDX is 20121125005312 date_object = datetime.strptime(timestamp, '%Y%m%d%H%M%S') ...
) print(date_object.strftime('%Y-%m-%d %H:%M:%S'))
uliwebext/uliweb-redbreast
test/test_core_utils.py
Python
bsd-2-clause
2,255
0.010643
from redbreast.core.utils import * import pytest from uliweb import manage, functions import os def test_import(): a = CommonUtils.get_class('redbreast.core.spec.TaskSpec') assert str(a)
== "<class 'redbreast.core.spec.task.TaskSpec'>" def test_import_not_exist(): a = CommonUtils.get_class('redbreast.core.spec.NotExistSpec') assert str(a) == 'None' def test_import_error(): with pytest.raises(ImportError): a = CommonUtils.get_class('not.exist.mod
ule.NotExistSpec') class TestUtilInProject(object): def setup(self): locate_dir = os.path.dirname(__file__) os.chdir(locate_dir) os.chdir('test_project') import shutil shutil.rmtree('database.db', ignore_errors=True) manage.call('uliweb syncdb') ...
jniediek/mne-python
mne/viz/tests/test_evoked.py
Python
bsd-3-clause
7,380
0.000136
# Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # Denis Engemann <denis.engemann@gmail.com> # Martin Luessi <mluessi@nmr.mgh.harvard.edu> # Eric Larson <larson.eric.d@gmail.com> # Cathy Nangini <cnangini@gmail.com> # Mainak Jas <mainak@neuro.hut.fi> #...
arnings.simplefilter('always') # enable b/c these tests throw warnings base_dir = op.join(op.dirname(__file__), '..', '..', 'io', 'tests', 'data') evoked_fname = op.join(base_dir, 'test
-ave.fif') raw_fname = op.join(base_dir, 'test_raw.fif') cov_fname = op.join(base_dir, 'test-cov.fif') event_name = op.join(base_dir, 'test-eve.fif') event_id, tmin, tmax = 1, -0.1, 0.1 n_chan = 6 layout = read_layout('Vectorview-all') def _get_raw(): """Get raw data.""" return read_raw_fif(raw_fname, preload...
hippke/TTV-TDV-exomoons
create_figures/system_22.py
Python
mit
7,952
0.005659
"""n-body simulator to derive TDV+TTV diagrams of planet-moon configurations. Credit for part of the source is given to https://github.com/akuchling/50-examples/blob/master/gravity.rst Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License """ import numpy import math import matplotlib.pylab as plt...
ddle_point) ttv_array = numpy.divide(ttv_array, 1000) # km/s # Compensate for barycenter offset of planet at start of simulation: planet.px = 0.5 * (gravity_firstmoon + gravity_secondmoon) stretch_factor = 1 / ((planet.px / 1000) / numpy.amax(ttv_arra
y)) ttv_array = numpy.divide(ttv_array, stretch_factor) # Convert to time units, TTV ttv_array = numpy.divide(ttv_array, R_star) ttv_array = numpy.multiply(ttv_array, transit_duration * 60 * 24) # minutes # Convert to time units, TDV oldspeed = (2 * R_star / transit_duration) * 1000 / 24 / 60...
schreiberx/sweet
mule/platforms/50_ppeixoto_usp_gnu/JobPlatform.py
Python
mit
4,663
0.016299
import platform import socket import sys from mule_local.JobGeneration import * from mule.JobPlatformResources import * from . import JobPlatformAutodetect import multiprocessing # Underscore defines symbols to be private _job_id = None def _whoami(depth=1): """ String of function name to recycle code ...
""" Returns ------- bool True if current platform matches, otherwise False """ return JobPlatformAutodetect.autodetect() def get_platform_id(): """ Return platform ID Returns ------- string unique ID of platform """ return "ppeixoto_usp_gnu" def get_...
ount() h.num_nodes = 1 # TODO: So far, we only assume a single socket system as a fallback h.num_cores_per_socket = h.num_cores_per_node return h def jobscript_setup(jg : JobGeneration): """ Setup data to generate job script """ global _job_id _job_id = jg.runtime.getUniqueID(j...