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
ruipgpinheiro/subuser
logic/subuserlib/classes/subuserSubmodules/run/runReadyImage.py
Python
lgpl-3.0
2,881
0.012843
#!/usr/bin/env python # This file should be compatible with both Python 2 and 3. # If it is not, please file a bug report. """ Contains code that prepairs a subuser's image to be run. """ #external imports import os #internal imports from subuserlib.classes.userOwnedObject import UserOwnedObject class RunReadyImage(...
rfileContents += "RUN (umask 337; echo \""+self.getUser().getEndUser().name+" ALL=(ALL) NOPASSWD: ALL\" > /etc/sudoers.d/allowsudo )\n" return dockerfileContents def build(self): """ Returns the Id of the Docker image to be run. """ return self.getUser().getDockerDaemon().build(None,quietClient=T...
,forceRm=True,rm=True,dockerfile=self.generateImagePreparationDockerfile())
nyu-dl/dl4mt-simul-trans
policy.py
Python
bsd-3-clause
23,644
0.007867
""" -- Policy Network for decision making [more general] """ from nmt_uni import * from layers import _p import os import time, datetime import cPickle as pkl # hyper params TINY = 1e-7 PI = numpy.pi E = numpy.e A = 0.2 B = 1 class Controller(object): def __init__(self, trng, option...
= 128 self.n_in = n_in self.n_out = n_out if self.options.get('layernorm', True): self.rec = 'lngru' else:
self.rec = 'gru' if not n_in: self.n_in = options['readout_dim'] if not n_out: if self.type == 'categorical': self.n_out = 2 # initially it is a WAIT/COMMIT action. elif self.type == 'gaussian': self.n_out = 100 ...
mrrrgn/releasetasks
releasetasks/__init__.py
Python
mpl-2.0
1,546
0.001294
# -*- coding: utf-8 -*- from os import path import yaml import arrow from chunkify import chunkify from jinja2 import Environment, FileSystemLoader, StrictUndefined from taskcluster.utils import stableSlugId DEFAULT_TEMPLATE_DIR = path.join(path.dirname(__file__), "templates") def make_task_graph(root_template="...
plate_
kwargs) return yaml.safe_load(template.render(**template_vars))
lutris/website
common/management/commands/anon_db.py
Python
agpl-3.0
2,839
0
"""Remove any personally identifying information from the database""" from django.core.management.base import BaseCommand from django.conf import settings from django.contrib.admin.models import LogEntry from django_openid_auth.models import UserOpenID from rest_framework.authtoken.models import Token from reversion.mo...
rint("Updated %s uploads" % res) res = News.objects.all().update(user=user) print("Updated %s news" % res) res = Revision.objects.all().update(user=user) print("Updated %s revisions" % res) res = User.objects.exclude(pk=user.id).delete() print("Deleted %s users" % res[...
lt_password) user.username = "lutris" user.email = "root@localhost" user.website = "" user.steamid = "" user.save() print("Password for user %s is now %s" % (user, default_password))
shayneholmes/plover
plover/logger.py
Python
gpl-2.0
1,566
0.000639
# Copyright (c) 2013 Hesky Fisher # See LICENSE.txt for details. """A module to handle logging.""" import logging from logging.handlers import RotatingFileHandler LOGGER_NAME = 'plover_logger' LOG_FOR
MAT = '%(asctime)s %(message)s' LOG_MAX_BYTES = 10000000 LOG_COUNT = 9 class Logger(object): def __init__(self): self._logger = logging
.getLogger(LOGGER_NAME) self._logger.setLevel(logging.DEBUG) self._handler = None self._log_strokes = False self._log_translations = False def set_filename(self, filename): if self._handler: self._logger.removeHandler(self._handler) handler = None ...
frenetic-lang/netcore-1.0
examples/Campus.py
Python
bsd-3-clause
1,239
0.026634
#!/usr/bin/python from mininet.topo import Topo, Node class CampusTopo( Topo ): "A simple example of a small campus network." def __init__(self, enable_all = True): " Create a campus topology." super( CampusTopo, self).__init__() # Add switches and hosts. switches = [1, 2, 3]...
tches[2] ) self.add_edge( switches[1], switches[2] ) for host in trustedUsers: self.add_edge( host, switches[0] ) for host in secureServers: self.add_edge( host, switches[1] ) for host in untrustedUsers: self.add_edge( host, switches[2] ) # Co...
) # Let mininet run this topo from the command line. topos = { 'campus' : ( lambda: CampusTopo() ) }
timgilbert/how-you-been
src/howyoubeen/Foursquare.py
Python
mit
3,878
0.009025
import string, urllib, urllib2, logging from webapp2_extras import json import Handlers, Config class FoursquareException(Exception): def __init__(self, message, value): super(self, Exception).__init__(message) self.value = value class FoursquareApiException(FoursquareException): pass class Four...
ccess_token']) else: raise FoursquareException(result) self.setCookie(self.OAUTH_COOKIE, access_token) def getFoursquareCheckins(self, accessToke
n): """Get the list of the signed-in user's checkins, per https://developer.foursquare.com/docs/users/checkins""" return self.getFoursquareApi('users/self/checkins', accessToken) def foursquareApiUrl(self, apiPath, accessToken): """Return a complete URL to the relevant foursqua...
sbesson/zeroc-ice
java/test/Ice/operations/run.py
Python
gpl-2.0
1,426
0.011921
#!/usr/bin/env python # ********************************************************************** # # Copyright (c) 2003-2013 ZeroC, Inc. All rights reserved. # # This copy of Ice is licensed to you under the terms described in the # ICE_LICENSE file included in this distribution. # # *************************************...
n(head, p) for p in path] path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ] if len(path) == 0: raise Runti
meError("can't find toplevel directory!") sys.path.append(os.path.join(path[0], "scripts")) import TestUtil print("tests with regular server.") TestUtil.clientServerTest(additionalClientOptions = "--Ice.Warn.AMICallback=0") print("tests with AMD server.") TestUtil.clientServerTest(additionalClientOptions = "--Ice.War...
fregaham/manaclash
cost.py
Python
gpl-3.0
8,669
0.006575
# Copyright 2011 Marek Schmidt # # This file is part of ManaClash # # ManaClash 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. # # Ma...
mp1 = mana_parse(m1) mp2 = mana_parse(m2) ret = {} excess = 0 for c in "WGRUB": ret[c] = mp1[c] - mp2[c] if mp1[None] >= mp2[None]: ret[None] = mp1[None] - mp2[None] else: ret[None] = 0 x = mp2[None] - mp1[None] for c in "WGRUB": if ret...
x = 0 else: x -= ret[c] ret[c] = 0 assert x == 0 return mana_format(ret) class ManaCost(Cost): def __init__ (self, manacost): Cost.__init__(self) self.manacost = manacost def get_text(self, game, obj, player): return "...
mjball/Singularity
scripts/logfetch/logfetch_base.py
Python
apache-2.0
2,462
0.017059
import os import sys import gzip from datetime import datetime from termcolor import colored from singularity_request import get_json_response BASE_URI_FORMAT = '{0}{1}' REQUEST_TASKS_FORMAT = '/history/request/{0}/tasks' ACTIVE_TASKS_FORMAT = '/history/request/{0}/tasks/active' def unpack_logs(logs): for zipped_fi...
://")) else "http://" uri = BASE_URI_FORMAT.format(uri_prefix, args.singularity_uri_base) return uri def tasks_for_request(args): if args.requestId and args.deployId: tasks = [task["taskId"]["id"] for task i
n all_tasks_for_request(args) if (task["taskId"]["deployId"] == args.deployId)] else: tasks = [task["taskId"]["id"] for task in all_tasks_for_request(args)] if hasattr(args, 'task_count'): tasks = tasks[0:args.task_count] return tasks def all_tasks_for_request(args): uri = '{0}{1}'.format(bas...
cako/notorius
src/image_label.py
Python
gpl-3.0
15,994
0.004627
#!/usr/bin/python # -*- coding: UTF-8 -*- #==============================================================================# # # # Copyright 2011 Carlos Alberto da Costa Filho # # ...
re.pyqtSignal(int) show_search_trigger = QtCore.pyqtSignal() hide_search_trigger = QtCore.pyqtSignal() def __init__(self, parent = None): super(ImageLabel, self).__init__() self.parent = parent self.preamble = PREAMBLE self.note_pos = QtCore.QPointF() self.note_icon_...
re.QPoint() self.current_uid = 0 self.closest_id = 0 self.notes = {} self.move = False self.drag = False self.overscroll = 0 self.control = False self.noteImage = QtGui.QImage(':img/note22.png') self.rubber_band = QtGui.QRubberBand( QtGui.QRubberBa...
ibc/MediaSoup
worker/deps/catch/.conan/build.py
Python
isc
3,044
0.001643
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import re from cpt.packager import ConanMultiPackager from cpt.ci_manager import CIManager from cpt.printer import Printer class BuilderSettings(object): @property def username(self): """ Set catchorg as package's owner """ retur...
le: result = pattern.search(line) if result: version = result.group(1) return version @property d
ef _branch(self): """ Get branch name from CI manager """ printer = Printer(None) ci_manager = CIManager(printer) return ci_manager.get_branch() if __name__ == "__main__": settings = BuilderSettings() builder = ConanMultiPackager( reference=settings.reference, ...
d-e-e-p/generate_nametags_with_barcodes
generate_nametags_with_barcodes.py
Python
gpl-3.0
22,514
0.014302
#!/usr/bin/python # # generate_nametags_with_barcodes.py # Copyright (C) 2016 Sandeep M # # every year an elementary school in california runs a festival where families # sign up for parties and events, as well as bid for auctions and donations. # each family is issued some stickers with unique barcode to make...
: label number #str4 = str(data['index']+1) + "/" + str(data['number_of_stick
ers'] ) str4 = " " return (num1, str1, str2, str3, str4) #---------------------------------------------------------------------- # http://stackoverflow.com/questions/21217846/python-join-list-of-strings-with-comma-but-with-some-conditions-code-refractor #------------------------------------------------------...
RiccardoRossi/pyKratos
stokes_ex/square_cavity.py
Python
bsd-2-clause
4,711
0.011675
from __future__ import print_function, absolute_import, division import sys sys.path.append("..") print(sys.path) from numpy import * from pyKratos import * #example = "cavity" #example = "gravity" #example = "shear_x" example = "inlet" # add variables to be allocated from the list in variables.py solution_step_va...
) node.Fix(VELOCITY_Y) for node in right_nodes: node.Fix(VELOCITY_X) node.Fix(VELOCITY_Y) for node in top_nodes: node.Fix(VELOCITY_X) node.Fix(VELOCITY_Y) node.SetSolutionStepValue(VELOCITY_X,0,1.0) #fixing the node at the ce
nter of the bottom face model_part.Nodes[int(nx/2)+1].Fix(PRESSURE) elif example=="gravity": for node in bottom_nodes: node.Fix(VELOCITY_X) node.Fix(VELOCITY_Y) for node in left_nodes: node.Fix(VELOCITY_X) node.Fix(VELOCITY_Y) for node in right_nodes: ...
bomjacob/htxaarhuslan
main/migrations/0022_auto_20161208_2216.py
Python
mit
679
0.001473
# -*- coding: utf-8 -*- # Generated by Django 1.10.2 on 2016-12-08 21:16 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main', '0021_auto_20161208_1214'), ] operations = [ migrations.AlterField( ...
entteam', name='name', field=models.CharField(max_length=255, verbose_name='holdnavn'), ), migrations.AlterField( model_name='tournamentteam', name='profiles', field=models.ManyToManyField(to='main.Profile', verbose_name='medlemmer
'), ), ]
windyuuy/opera
chromium/src/chrome/common/extensions/docs/server2/chained_compiled_file_system.py
Python
bsd-3-clause
3,233
0.007733
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from compiled_file_system import CompiledFileSystem from file_system import FileNotFoundError class ChainedCompiledFileSystem(object): ''' A CompiledFileS...
mpiled file system is read in the reverse order (the last one is read first). If the version matches, return the data. Otherwise, read from the previous compiled file system until the first one is read. It is used to chain compiled file systems whose underlying file systems are slightly different. This...
is shared by them. ''' class Factory(CompiledFileSystem.Factory): def __init__(self, factory_and_fs_chain): self._factory_and_fs_chain = factory_and_fs_chain def Create(self, populate_function, cls, category=None): return ChainedCompiledFileSystem( [(factory.Create(p...
breuleux/bugland
bugland/premade.py
Python
bsd-3-clause
796
0.028894
from gen import * from dataset import * # TETROMINO tetromino_gen = lambda w, h: TwoGroups("tetrisi/tetriso/tetrist/tetrisl/tetrisj/tetriss/tetrisz",
1010, w, h, n1 = 1, n2 = 2, rot =
True, task = 1) tetromino = lambda w, h: BugPlacer(tetromino_gen(w, h), True) tetromino10x10 = tetromino(10, 10) tetromino16x16 = tetromino(16, 16) # PENTOMINO pentomino_gen = lambda w, h: TwoGroups("pentl/pentn/pentp/pentf/penty/pentj/pentn2/pentq/pentf2/penty2", 2020, w, h, ...
jiayuzhou/pyProxSolver
org/jiayu/optimization/smooth.py
Python
gpl-2.0
563
0.039076
''' A set of (smooth) loss functions. Created on Oct 2, 2014 @author: jiayu.zhou ''' import numpy as np; def least_squa
res(w, X, y): ''' least squares loss. MATLAB verified function. f(x) = 1/2 * ||X * w - y||_F^2. Parameters ---------- w: np.matrix X: np.matrix y: np.matrix Returns ---------- ''' Xw_y = np.dot(X, w) - y; f = 0.5 * np.linalg.norm(Xw_y,...
= np.dot(X.T, Xw_y); g = g.reshape(g.shape[0] * g.shape[1] , 1, order = 'F'); return [f, g];
Brocade-OpenSource/OpenStack-DNRM-Neutron
neutron/db/migration/alembic_migrations/versions/3b54bf9e29f7_nec_plugin_sharednet.py
Python
apache-2.0
2,645
0.001134
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright 2013 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE...
ullable=False), sa.PrimaryKeyConstraint('quantum_id'), sa.UniqueConstraint('ofc_id') ) op.create_table( 'ofcfiltermappings', sa.Column('ofc_id', sa.String(length=255), nullable=False), sa.Column('quantum_id', sa.String(length=36), nullable=False),
sa.PrimaryKeyConstraint('quantum_id'), sa.UniqueConstraint('ofc_id') ) def downgrade(active_plugin=None, options=None): if not migration.should_run(active_plugin, migration_for_plugins): return op.drop_table('ofcfiltermappings') op.drop_table('ofcportmappings') op.drop_table('ofc...
cokelaer/spectrum
test/test_correlog.py
Python
bsd-3-clause
1,904
0.006828
from spectrum import CORRELOGRAMPSD, CORRELATION, pcorrelogram, marple_data from spectrum import data_two_freqs from pylab import log10, plot, savefig, linspace from numpy.testing import assert_array_almost_equal, assert_almost_equal def test_correlog(): psd = CORRELOGRAMPSD(marple_data, marple_data, lag=15) ...
d='xcorr') assert_array_almost_equal(psd1, psd2) def test_pcorrelogram_class(): p = pcorrelogram(marple_data, lag=16) p() print(p) p = pcorrelogram(data_two_freqs(), lag=16) p.plot() print(p) def test_CORRELOGRAMPSD_others(): p = CORRELOGRAMPSD(marple_data, marple_data, lag=16, NFFT=No...
) savefig('psd_corr.png') if __name__ == "__main__": create_figure()
gale320/newfies-dialer
newfies/appointment/templatetags/appointment_tags.py
Python
mpl-2.0
1,283
0.002338
# # Newfies-Dialer License # http://www.newfies-dialer.org # # 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/. # # Copyright (C) 2011-2014 Star2Billing S.L. # # The Initia...
rm_status') def alarm_status(value): """Alarm Status Templatetag""" if not value: return '' STATUS = dict(ALARM_STATUS) try: return ST
ATUS[value].encode('utf-8') except: return '' @register.filter(name='alarm_method') def alarm_method(value): """Alarm Method Templatetag""" if not value: return '' METHOD = dict(ALARM_METHOD) try: return METHOD[value].encode('utf-8') except: return ''
clchiou/garage
py/g1/bases/g1/bases/times.py
Python
mit
364
0
__all__ = [ 'Units', 'convert', ] import enum class Units(enum.Enum): SECONDS = 0
MILLISECONDS = -3 MICROSECONDS = -6 NANOSECONDS = -9 def convert(source_unit, target_unit, time): """Convert time between units.""" if source_unit is target_unit: return time return time * 10**(sourc
e_unit.value - target_unit.value)
alejandro-mc/BDM-DDD
value_noisecomplaints/getLoudMusicComp.py
Python
mit
2,652
0.019985
import pyspark
import operator import sys #311 call 2010 to present csv #0 Unique Key,Created Date,Closed Date,Agency,Agency Name, #5 Compla
int Type,Descriptor,Location Type,Incident Zip,Incident Address, #10 Street Name,Cross Street 1,Cross Street 2,Intersection Street 1, #14 Intersection Street 2,Address Type,City,Landmark,Facility Type,Status, #20 Due Date,Resolution Description,Resolution Action Updated Date, #23 Community Board,Borough,X Coordinate (S...
JeffHoogland/bodhi3packages
python3-efl-i386/usr/lib/python3.4/dist-packages/efl/__init__.py
Python
bsd-3-clause
56
0.035714
_
_version__ = "1.12.0" __version_inf
o__ = ( 1, 12, 0 )
aerospike/aerospike-admin
test/e2e/util.py
Python
apache-2.0
6,156
0.000975
# Copyright 2013-2021 Aerospike, 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 writ...
separated_stdout = get_separate_output(actual_stdout) result = parse_output(separated_stdout[0]) return result def get_merged_header(*lines): h = [[_f for _f in _h.split(" ") if _f] for _h in lines] header = [] if len(h) == 0 or any(len(h[i]) != len(h[i + 1]) for i in range(len(h) - 1)): ...
h[jdx + 1][idx] == ".": break header_i += " " + h[jdx + 1][idx] header.append(header_i) return header def check_for_subset(actual_list, expected_sub_list): if not expected_sub_list: return True if not actual_list: return False for i in expected_sub_...
ocelot-collab/ocelot
ocelot/cpbd/coord_transform.py
Python
gpl-3.0
3,359
0.002679
""" S.Tomin and I.Zagorodnov, 2017, DESY/XFEL """ from ocelot.common.globals import * import logging logger = logging.getLogger(__name__) try: import numexpr as ne ne_flag = True except: logger.debug("coord_transform.py: module NUMEXPR
is not installed. Install it to speed up calculation") ne_flag = False def xp_2_xxstg_mad(xp, xxstg, gamref): # to mad format N = xp.shape[1] pref = m_e_eV * np.sqrt(gamref ** 2 - 1) betaref = np.sqrt(1 - gamref ** -2) u = np.c_[xp[3], xp[4], xp[5]] if ne_flag: sum_u2 = ne.evaluate...
sqrt(1 + np.sum(u * u, 1) / m_e_eV ** 2) beta = np.sqrt(1 - gamma ** -2) if np.__version__ > "1.8": p0 = np.linalg.norm(u, 2, 1).reshape((N, 1)) else: p0 = np.sqrt(u[:, 0] ** 2 + u[:, 1] ** 2 + u[:, 2] ** 2).reshape((N, 1)) u = u / p0 u0 = u[:, 0] u1 = u[:, 1] u2 = u[:, ...
rizkidoank/awsu
awsu/config.py
Python
gpl-3.0
11,653
0.000944
""" configuration module for awsu, contains two objects """ import boto3 import sqlite3 import logging import getpass import datetime import configparser import uuid import requests import json from dateutil.tz import tzutc from urllib.parse import urlencode, quote_plus from os import environ from bs4 import BeautifulS...
profile, 'provider', provider) config_file.set(profile, 'durations', google.duration_seconds) with open(environ.get('HOME') + '/.aws/config', 'w+') as f: try:
config_file.write(f) finally: f.close() print("Assuming " + config_file.get(profile, 'role_arn')) sts = boto3.client('sts') res = sts.assume_role_with_saml( RoleArn=config_file.get(profile, 'role_arn'), ...
SEL-Columbia/commcare-hq
corehq/util/zip_utils.py
Python
bsd-3-clause
1,577
0
import os import tempfile from wsgiref.util import FileWrapper import zipfile from django.http import HttpResponse from django.views.generic import View from corehq.util.view_utils import set_file_download def make_zip_tempfile(files, compress=True): compression = zipfile.ZIP_DEFLATED if compress else zipfile.ZIP...
elf): raise NotImplementedError() def check_before_zipping(self): raise NotImplementedError() def get(self, request, *args, **kwargs): error_response = sel
f.check_before_zipping() if error_response: return error_response files, errors = self.iter_files() fpath = make_zip_tempfile(files, compress=self.compress_zip) if errors: self.log_errors(errors) wrapper = FileWrapper(open(fpath)) response = Http...
HaroldMills/Vesper
scripts/old_bird_detector_eval/annotate_old_bird_calls.py
Python
mit
6,952
0.005898
""" Annotates Old Bird call detections in the BirdVox-70k archive. The annotations classify clips detected by the Old Bird Tseep and Thrush detectors according to the archive's ground truth call clips. This script must be run from the archive directory. """ from django.db.models import F from django.db.utils import...
# Annotate Old Bird clip call center index. model_utils.annotate_clip( old_bird_clip, center_index_annotation_info, str(call_center_index), creating_user=user) # Get ground truth clip call center frequen...
otations[CENTER_FREQ_ANNOTATION_NAME] # Annotate Old Bird clip call center frequency. model_utils.annotate_clip( old_bird_clip, center_freq_annotation_info, call_center_freq, creating_user=user) ...
osroom/osroom
apps/modules/category/apis/theme_category.py
Python
bsd-2-clause
2,262
0.000982
#!/usr/bin/env python # -*-coding:utf-8-*- # @Time : 2017/11/1 ~ 2019/9/1 # @Author : Allen Woo from flask import request from apps.core.flask.login_manager import osr_login_required from apps.configs.sys_config import METHOD_WARNING from apps.core.blueprint import api from apps.core.flask.permission import permission_...
dit, \ category_delete, get_category_type @api.route('/admin/content/theme-category', methods=['GET', 'POST', 'PUT', 'DELETE']) @osr_login_required @permission_required(use_default=False) def api_theme_category(): """ GET: action:<str>, 可以为get_category, get_category_type, 默认get_category 1...
action:<str>, 为get_category type:<str>, 你设置的那几个类别中的类别,在config.py文件中category, 可在网站管理端设置的 theme_name:<str> 2. 获取所有的type: config.py文件中category的所有CATEGORY TYPE action:<str>, 为get_category_type theme_name:<str> 解释: 在分类中(category)又...
shogun-toolbox/shogun
examples/undocumented/python/kernel_wave.py
Python
bsd-3-clause
846
0.030733
#!/usr/bin/env python from tools.load import LoadMatrix from numpy import where import shogun as sg lm=LoadMatrix() traindat = lm.load_numbers('../data/fm_train_real.dat') testdat = lm.load_numbers('../data/fm_test_real.dat') parameter_list=[[traindat,testdat, 1.0],[traindat,testdat, 10.0]] def kernel_wave (fm_train...
e_features(fm_test_real) distance = sg.create_distance('EuclideanDistance') kernel = sg.create_kernel('WaveKernel', theta=theta, distance=distance) kernel.init(feats_train, feats_train) km_train=kernel.get_kernel_matrix() kernel.init(feats_train, feats_test) km_test=kernel.get_kernel_matrix() return km_train,...
__name__=='__main__': print('Wave') kernel_wave(*parameter_list[0])
spulec/moto
moto/organizations/exceptions.py
Python
apache-2.0
2,748
0.00182
from moto.core.exceptions import JsonRESTError class AccountAlreadyRegisteredException(JsonRESTError): code = 400 def __init__(self): super().__init__( "AccountAlreadyRegisteredException", "The provided account is already a delegated administrator for your organization.", ...
ion(JsonRESTError): code = 400 def __init__(self): super().__init__( "RootNotFoundException", "You specified a root that doesn't exist." ) class TargetNotFoundException(JsonRESTError): code = 400 def __init__(self): super().__init__( "TargetNotFou
ndException", "You specified a target that doesn't exist." )
mikeing2001/LoopDetection
pox/web/webcore.py
Python
gpl-3.0
15,662
0.01443
# Copyright 2011,2012 James McCauley # # This file is part of POX. # # POX 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. # # POX is d...
thod = getattr(handler, mname) return method() def log_request (self, code = '-', size = '-'): weblog.debug(self
.prefix + (':"%s" %s %s' % (self.requestline, str(code), str(size)))) def log_error (self, fmt, *args): weblog.error(self.prefix + ':' + (fmt % args)) def log_message (self, fmt, *args): weblog.info(self.prefix + ':' + (fmt % args)) _favicon = ("47494638396110001000c206006a5797927bc18f83ad...
zooko/egtp
common/mencode_unittests.py
Python
agpl-3.0
13,498
0.004075
#!/usr/bin/env python # # Copyright (c) 2001 Autonomous Zone Industries # Copyright (c) 2002 Bryce "Zooko" Wilcox-O'Hearn # This file is licensed under the # GNU Lesser General Public License v2.1. # See the file COPYING or visit http://www.gnu.org/ for details. # __cvsid = '$Id: mencode_unittests.py,v 1.1 200...
ecode" except MencodeError: return
def test_rej_dict_with_float(self): try: s = mencode({'foo': 0.9873}) assert 0, "You can't encode floats! Anyway, the result: %s, is probably not what we meant." % humanreadable.hr(s) except MencodeError, le: try: # print "got exce1: %s" % humanr...
metachris/py2app
py2app_tests/basic_app_with_encoding/package1/subpackage/module.py
Python
mit
29
0
"package1.subpackage.module"
xvorenda/DAENA
py/alarm.py
Python
gpl-3.0
62,009
0.004919
#!/usr/bin/env python from __future__ import division import time import sys import MySQLdb as mdb import smtplib import re import bz2 import alarm # Alarm Levels: # Temperature Alarms # 0 - No alarm, freezer is in a normal state # 1 - freezer is in a high temp range, and has been for 30 min # 2 - freezer is in a high...
if alarmLevel == self.CRITICAL_TEMP_ALARM_SILENCED: #print "alarmLevel self.CRITICAL_TEMP_ALARM_SILENCED", alarmLevel
pass # constant reminder alarm every 60min elif alarmLevel == self.CRITICAL_TEMP_ALARM: #check to see if it has been > 60 min since the last alarm # Reminder 3 > Alarm 3 (1 hour) if alarmTime < (((time.time())-(self.SIXTY_SECONDS * self....
drphilmarshall/Music
beatbox/universe.py
Python
mit
38,369
0.013188
import numpy as np import matplotlib import matplotlib.pylab as plt import healpy as hp import string import yt import os import glob from PIL import Image as PIL_Image from images2gif import writeGif from scipy.special import sph_harm,sph_jn import beatbox from beatbox.multiverse import Multiverse # ===============...
s of R_yn for i in lms:
l = i[0] m = i[1] trigpart = np.cos(np.pi*l/2.0) B = np.asarray([A[ki][l] for ki in range(len(k))]) R_long[y,:NN/2] = 4.0 * np.pi * sph_harm(m,l,theta,phi).reshape(NN/2)*B.reshape(NN/2) * trigpart trigpart = np.sin(np.pi*l/2.0) R_long[y,NN/2:] = 4.0 * np.pi * ...
datapythonista/pandas
pandas/tests/io/xml/test_xml.py
Python
bsd-3-clause
34,008
0.000265
from io import ( BytesIO, StringIO, ) import os from typing import Union from urllib.error import HTTPError import numpy as np import pytest from pandas.compat import PY38 import pandas.util._test_decorators as td from pandas import DataFrame import pandas._testing as tm from pandas.io.xml import read_xml ...
es>3</sides> </row> </data>""" xml_prefix_nmsp = """\ <?xml version='1.0' encoding='utf-8'?> <doc:data xmlns:doc="http://example.com"> <doc:row> <doc:shape>square</doc:shape> <doc:degrees>360</doc:degrees> <doc:sides>4.0</doc:sides> </doc:row> <doc:row> <doc:shape>circle</doc:shape> <doc:de...
<doc:row> <doc:shape>triangle</doc:shape> <doc:degrees>180</doc:degrees> <doc:sides>3.0</doc:sides> </doc:row> </doc:data>""" df_kml = DataFrame( { "id": { 0: "ID_00001", 1: "ID_00002", 2: "ID_00003", 3: "ID_00004", 4: "ID_00005", ...
hfp/tensorflow-xsmm
tensorflow/python/saved_model/model_utils/__init__.py
Python
apache-2.0
1,544
0.003886
# Copyright 2018 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...
_outputs from tensorflow.python.saved_
model.model_utils.export_utils import get_temp_export_dir from tensorflow.python.saved_model.model_utils.export_utils import get_timestamped_export_dir # pylint: enable=wildcard-import
katyushacccp/ISN_projet_final
final 0.0/modules/affichage.py
Python
cc0-1.0
2,709
0.068291
from tkinter import * from modules.gestionnaire import * def couleurAffiche(couleur): if couleur == "red": return "#CC0000" elif couleur == "green": return "#006600" elif couleur == "blue": return "#0000CC" elif couleur == "orange": return "#FF4500" elif couleur == "yellow": return "#FFD500...
.create_rectangle(390,177,480,190,width=1,fill=couleurAffiche(cube[4][4])) can.create_rectangle(390,360,480,373,width=1,fill=couleurAffiche(cube[5][4])) can.create_rectangle(550,177,640,190,width=1,fill=couleurAffiche(cube[4][4])) can.create_rectangle(550,360,640,373,width=1,fi
ll=couleurAffiche(cube[5][4])) can.create_rectangle(230,17,320,30,width=1,fill=couleurAffiche(cube[3][4])) can.create_rectangle(230,520,320,533,width=1,fill=couleurAffiche(cube[3][4])) can.create_rectangle(17,230,30,320,width=1,fill=couleurAffiche(cube[3][4])) can.create_rectangle(693,230,680,320,width=1,fill=c...
agamdua/hamster-core
hamster/jobs/models.py
Python
mit
209
0.004785
from django.db imp
ort models class Job(models.Model): job_name = models.CharField(max_length=80) disabled = m
odels.BooleanField(default=False) def __unicode__(self): return self.job_name
flinz/eatnit
eatnit/apps/food/urls.py
Python
gpl-2.0
482
0.006224
from
django.conf.urls import patterns, url from eatnit.apps.food import views urlpatterns = patterns('', url(r'^$', views.index, name='eatnit_index'), # url(r'^meals/$', views.meal_index, name='meal_index'), # url(r'^meals/(?P<meal_id>\d+)/$', views.meal_detail, name='meal_detail'), # url(r'^restaurants/$'...
ws.restaurant_detail, name='restaurant_detail'), )
edwinsteele/visual-commute
vcapp/migrations/0002_initial.py
Python
cc0-1.0
5,957
0.006211
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Station' db.create_table('vcapp_station', ( ('id', self.gf('django.db.models.fie...
'station': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['vcapp.Station']"}) }, 'vcapp.line': { 'Meta': {'object_name': 'Line'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'line_name': ('django.db.models.fiel...
top': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'arrival_point'", 'to': "orm['vcapp.TripStop']"}), 'departure_tripstop': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'departure_point'", 'to': "orm['vcapp.TripStop']"}), 'id': ('django.db.models.f...
colinbrislawn/scikit-bio
skbio/sequence/_iupac_sequence.py
Python
bsd-3-clause
16,530
0.00006
# ---------------------------------------------------------------------------- # Copyright (c) 2013--, scikit-bio development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. # --------------------------------------------...
f): """Determine if the sequence contains one or more gap characters. Returns ------- bool Indicates whether there are one or more occurrences of gap characters in the biological sequence. Examples -------- >>> from skbio import DNA ...
_gaps() True """ # TODO use count, there aren't that many gap chars # TODO: cache results return bool(self.gaps().any()) @stable(as_of='0.4.0') def degenerates(self): """Find positions containing degenerate characters in the sequence. Returns --...
googleads/google-ads-python
google/ads/googleads/v10/enums/types/webpage_condition_operator.py
Python
apache-2.0
1,199
0.000834
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
class WebpageConditionOperatorEnum(proto.Message): r"""Container for enum describing webpage condition operator
in webpage criterion. """ class WebpageConditionOperator(proto.Enum): r"""The webpage condition operator in webpage criterion.""" UNSPECIFIED = 0 UNKNOWN = 1 EQUALS = 2 CONTAINS = 3 __all__ = tuple(sorted(__protobuf__.manifest))
tchellomello/home-assistant
homeassistant/components/nello/lock.py
Python
apache-2.0
2,961
0.001013
"""Nello.io lock platform.""" from itertools import filterfalse import logging from pynello.private import Nello import voluptuous as vol from homeassistant.components.lock import PLATFORM_SCHEMA, LockEntity from homeassistant.const import CONF_PASSWORD, CONF_USERNAME import homeassistant.helpers.config_validation as...
__) ATTR_ADDRESS = "address" ATTR_LOCATION_ID = "location_id" EVENT_DOOR_BELL = "nello_bell_ring" PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( {vol.Required(CONF_USERN
AME): cv.string, vol.Required(CONF_PASSWORD): cv.string} ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Nello lock platform.""" nello = Nello(config.get(CONF_USERNAME), config.get(CONF_PASSWORD)) add_entities([NelloLock(lock) for lock in nello.locations], True) cla...
CloudBrewery/duplicity-swiftkeys
duplicity/backends/hsibackend.py
Python
gpl-2.0
2,186
0.004575
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*- # # Copyright 2002 Ben Escoto <ben@emerose.org> # Copyright 2007 Kenneth Loafman <kenneth@loafman.com> # # This file is part of duplicity. # # Duplicity is free software; you can redistribute it and/or modify it # under the ter
ms 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. # # Duplicity 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 License for more details. # # You should have received a copy of the GN...
pycam/python-functions-and-modules
my_first_module.py
Python
unlicense
51
0
de
f say_hello(user): print('Hello', user,
'!')
kaarl/pyload
module/plugins/internal/Account.py
Python
gpl-3.0
12,347
0.007208
# -*- coding: utf-8 -*- import random import re import threading import time from module.plugins.internal.Plugin import Plugin, Skip from module.plugins.internal.misc import Periodical, compare_time, decode, isiterable, lock, parse_size class Account(Plugin): __name__ = "Account" __type__ = "account" ...
counts.clear() for user, info in accounts.items(): self.add(user, info['password'], info['options']) @lock def getAccountData(self, user, force=False): if force:
self.accounts[user]['plugin'].get_info() return self.accounts[user] @lock def getAllAccounts(self, force=False): if force: self.init_accounts() #@TODO: Recheck in 0.4.10 return [self.getAccountData(user, force) for user in self.accounts] #@TODO: Remove in 0.4.10 ...
mgraupe/acq4
acq4/devices/Laser/taskTemplate.py
Python
mit
6,745
0.001927
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file '.\taskTemplate.ui' # # Created: Thu Oct 08 16:48:34 2015 # by: PyQt4 UI code generator 4.10.4 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except...
Gui.QApplication.translate(context, text, disambig) class Ui_Form(object): def setupUi(self, Form): Form.setObjectName(_fromUtf8("Form")) Form.resize(218, 236) self.gridLayout_2 = QtGui.QGridLayout(Form) self.gridLayout_2.setObjectName(_fromUtf8("gridLayout_2")) self.group
Box = QtGui.QGroupBox(Form) self.groupBox.setObjectName(_fromUtf8("groupBox")) self.gridLayout = QtGui.QGridLayout(self.groupBox) self.gridLayout.setSpacing(0) self.gridLayout.setContentsMargins(3, 0, 3, 3) self.gridLayout.setObjectName(_fromUtf8("gridLayout")) self.power...
LAUDATIO-Repository/Version1.1
app/webroot/js/creativecommons/license_xsl/licensexsl_tools/makerdf.py
Python
gpl-3.0
2,716
0.004786
""" makerdf.py Assemble RDF describing all available CC licenses using licenses.xml as a source for all canonical license URIs. Requires RDFlib (http://rdflib.net), lxml (http://codespeak.net/lxml). (c) 2005-2006, Nathan R. Yergler, Creative Commons. """ __version__ = 0.5 from rdflib.Graph import Graph import rdfl...
tring", dest="licenses_xml", help="Use the specified licenses file.", default="licenses.xml"), make_option("-o", "--output", action="store", type="string", dest="output_rdf", help="Write the RDF to the specified file.", ...
ser = OptionParser(usage=usage, version="%%prog %s" % __version__, option_list = option_list) return parser def assembleRDF(instream, outstream, verbose=False): licenses = lxml.etree.parse(instream) graph = Graph('default',"http://crea...
johnson1228/pymatgen
pymatgen/analysis/pourbaix/tests/test_maker.py
Python
mit
1,116
0.005376
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. from __future__ import unicode_literals import unittest import os from pymatgen.analysis.pourbaix.maker import PourbaixDiagram from pymatgen.analysis.pourbaix.entry import PourbaixEntryIO class TestPourbaix...
ZnO2(s)", "Zn[2+]", "ZnHO2[-]", "ZnO2[2-]", "Zn(s)"] def test_pourbaix_diagram(self): self.assertEqual(len(self._pd.facets), 6, "Incorrect number of facets") self.assertEqual(set([e.name for e in self._pd.stable_entries]), set(self.list_of_stable_entries), "List
of stable entries does not match") if __name__ == '__main__': unittest.main()
halfline/gedit
plugins/externaltools/tools/windowactivatable.py
Python
gpl-2.0
7,385
0.002844
# -*- coding: UTF-8 -*- # Gedit External Tools plugin # Copyright (C) 2005-2006 Steve Frécinaux <steve@istique.net> # # 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 versi...
age_tools") action.connect("activate", lambda action, parameter: self.open_dialog()) self.window.add_action(action) self.gear_menu = self.extend_gear_menu("ext9") item = Gio.MenuItem.new(_("Manage _External Tools..."), "win.manage_tools") self.gear_menu.append_menu_item(item) ...
ools"), external_tools_submenu) self.gear_menu.append_menu_item(item) external_tools_submenu_section = Gio.Menu() external_tools_submenu.append_section(None, external_tools_submenu_section) # Create output console self._output_buffer = OutputPanel(self.plugin_info.get_data_dir()...
zedshaw/learn-python3-thw-code
ex4.py
Python
mit
566
0.001767
cars = 100 space_in_a_car = 4.0 drivers = 30 passengers = 90 cars_not_driven = cars - drivers cars_driven = drivers carpool_capacity = cars_driven * space_in_a_car average_passe
ngers_per_car = passengers / cars_driven print("There are", cars, "cars available.") print("There are only", drivers, "driver
s available.") print("There will be", cars_not_driven, "empty cars today.") print("We can transport", carpool_capacity, "people today.") print("We have", passengers, "to carpool today.") print("We need to put about", average_passengers_per_car, "in each car.")
AleksNeStu/ggrc-core
test/integration/ggrc/converters/test_import_assessments.py
Python
apache-2.0
19,212
0.001457
# Copyright (C) 2017 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # pylint: disable=maybe-no-member, invalid-name """Test request import and updates.""" import csv from collections import OrderedDict from cStringIO import StringIO from itertools import izip from flask....
ignore_lines="22", ), }, "row_warnings": { errors.UNKNOWN_OBJECT.format( line=19, object_type="Audit",
slug="not existing" ), errors.WRONG_VALUE_DEFAULT.format( line=20, column_name="State", value="open", ), }, } } self._check_csv_response(response, expected_errors) def test_mappin...
kerel-fs/skylines
skylines/api/views/errors.py
Python
agpl-3.0
1,466
0
from werkzeug.exceptions import HTTPException, InternalServerError from .json import jsonify def register(app): """ Register error handlers on the given app :type app: flask.Flask """ @app.errorhandler(400) @app.erro
rhandler(401) @app.errorhandler(403) @app.errorhandler(404) @app.errorhandler(405) @app.errorhandler(500) def handle_http_error(e): if not isinstance(e, HTTPException): e = InternalServerError() data = getattr(e, 'data', None) if data: message = data[...
essage': message, }, status=e.code) @app.errorhandler(422) def handle_bad_request(err): # webargs attaches additional metadata to the `data` attribute data = getattr(err, 'data') if data: # Get validations from the ValidationError object messages = data['...
piglei/uwsgi-sloth
uwsgi_sloth/template.py
Python
apache-2.0
1,040
0.002885
# -*- coding: utf-8 -*- """Template shortcut & filters""" import os import datetime from jinja2 import Environment, FileSystemLoader from uwsgi_sloth.settings import ROOT from uwsgi_sloth import settings, __VERSION__ template_path = os.path.join(ROOT, 'templates') env = Environment(loader=FileSystemLoader(template_pa...
mins = divmod(mins, 60) if hours: return '%dh%dm%ds' % (hours, mins, secs) elif mins: return '%dm%ds' % (mins, secs) elif secs: return '%ds%dms' % (secs, msecs) else: return '%.2fms' % msecs env.filters['friendly_time'] = friendly_time def render_template(template_name...
now=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), version='.'.join(map(str, __VERSION__))) return template.render(**context)
wrboyce/ec2hashcat
ec2hashcat/aws/s3.py
Python
apache-2.0
5,740
0.002265
""" Copyright 2015 Will Boyce """ from __future__ import print_function import os import re from boto3.session import Session from ec2hashcat import exceptions class S3Bucket(object): types = ('hashlists', 'dumps', 'wordlists', 'rules') def __init__(self, cfg): self.cfg = cfg aws = Session...
attr.append(groups[key]) attr = '_'.join(attr) return self.__getattribute__(attr)(groups['type']) raise AttributeError("'{}' object has no attribute '{}'".format( self.__class__.__name__, name)) def __dir__(self): funcs = [ ...
'put_object'] func_templates = ('delete_{}', 'download_{}', 'get_{}', 'get_{}s', 'get_{}_objects', '{}_exists', 'put_{}') obj_types = [t[:-1] for t in self.types] func_matrix = zip(sorted(func_templates * len(obj_types)), obj_types * len(func_templates)) for func_template, o...
arubertoson/piemenu
piemenu/menusystem/node.py
Python
gpl-2.0
4,177
0
#! usr/bin/env python2 from PySide import QtGui, QtCore from PySide.QtCore import Qt from settings import Icon class Node(object): Command, Form, Separator = 'command', 'form', 'separator' @classmethod def from_type(cls, type_, **kw): cls = Command if kw['type'] == cls.Command ...
ut = ['\t' for i in range(level)] output.append(self._label if self._parent is not None else 'Root') output.append('\n') output.extend([item.log(level) for item in self._items]) level -= 1 return ''.join(output) class Command(Node): def __init__(self, **kw): ...
self._icon = kw.get('icon', '') self._command = kw.get('command', '') self._sub_command = kw.get('sub_command', '') self._label = 'Untitled Command' if self._label == '' else self._label def icon(self): return self._icon def command(self): return self._comman...
freedesktop-unofficial-mirror/papyon
papyon/service/AddressBook/scenario/contacts/messenger_contact_add.py
Python
gpl-2.0
3,036
0.002306
# -*- coding: utf-8 -*- # # Copyright (C) 2007 Johann Prieur <johann.prieur@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 option) an...
self.contact_info['contact_type'] = self.contact_type self.contact_info['is_messenger_user'] = True elif self.network_id == NetworkID.EXTERNAL: self.contact_info.setdefault('email', {})[ContactEmailType.EXTERNAL] = self.account self.contact_info['capability'] = se...
self._ab.ContactAdd(self._callback, self._errback, self._scenario, self.contact_info, invite_info, self.auto_manage_allow_list)
googleapis/python-tpu
google/cloud/tpu_v2alpha1/services/tpu/async_client.py
Python
apache-2.0
54,857
0.001367
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
ator_type_path) parse_accelerator_type_path = staticmethod(TpuClient.parse_accelerator_type_path) node_path = staticmethod(TpuClient.node_path) parse_node_path = staticmethod(TpuClient.parse_node_path) runtime_version_path = staticmethod(TpuClient.runtime_version_path) parse_runtime_version_path = s...
common_billing_account_path = staticmethod( TpuClient.parse_common_billing_account_path ) common_folder_path = staticmethod(TpuClient.common_folder_path) parse_common_folder_path = staticmethod(TpuClient.parse_common_folder_path) common_organization_path = staticmethod(TpuClient.common_organizat...
npinchot/djangocon_2015_talk
manage.py
Python
mit
274
0.00365
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault
("DJANGO_SETTINGS_MODULE", "e_commerce_with_django_at_scale.settings") from django.core.management imp
ort execute_from_command_line execute_from_command_line(sys.argv)
joopert/home-assistant
tests/components/jewish_calendar/test_sensor.py
Python
apache-2.0
19,613
0.000982
"""The tests for the Jewish calendar sensors.""" from datetime import timedelta from datetime import datetime as dt import pytest import homeassistant.util.dt as dt_util from homeassistant.setup import async_setup_component from homeassistant.components import jewish_calendar from tests.common import async_fire_time_...
vua": "Ki Tavo", "hebrew_parshat_hashavua": "כי תבוא", }, havdalah_offset=50, ), make_nyc_test_params( dt(2018, 9, 1, 20, 0), { "english_upcoming_shabbat_candle_lighting": dt(2018, 8, 31, 19, 15), "english_upcoming_shabbat_havdalah": dt(2018, 9...
h_parshat_hashavua": "Ki Tavo", "hebrew_parshat_hashavua": "כי תבוא", }, ), make_nyc_test_params( dt(2018, 9, 1, 20, 21), { "english_upcoming_candle_lighting": dt(2018, 9, 7, 19, 4), "english_upcoming_havdalah": dt(2018, 9, 8, 20, 2), "engl...
FireballDWF/cloud-custodian
tools/c7n_mailer/c7n_mailer/datadog_delivery.py
Python
apache-2.0
4,461
0.000897
# Copyright 2017 Capital One Services, 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...
if sqs_message and sqs_message.get( 'action', False) and sqs_message['action'].get('to', False): for to in sqs_message['action']['to']: if to.startswith('datadog://'): parsed = urlparse(to) metric_config_map.app
end(dict(parse_qsl(parsed.query))) return metric_config_map
Jumpscale/web
pythonlib/flask_admin/base.py
Python
apache-2.0
16,504
0.001636
from functools import wraps from flask import Blueprint, render_template, abort, g from flask.ext.admin import babel from flask.ext.admin._compat import with_metaclass from flask.ext.admin import helpers as h # For compatibility reasons import MenuLink from flask.ext.admin.menu import MenuCategory, MenuView, MenuLink...
""" # Store self as
admin_view kwargs['admin_view'] = self kwargs['admin_base_template'] = self.admin.base_template # Provid
LLNL/spack
var/spack/repos/builtin/packages/r-maps/package.py
Python
lgpl-2.1
902
0.004435
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Ap
ache-2.0 OR MIT) from spack import * class RMaps(RPackage): """Display of maps. Projection code and larger maps are in separate packages ('m
approj' and 'mapdata').""" homepage = "https://cloud.r-project.org/package=maps" url = "https://cloud.r-project.org/src/contrib/maps_3.1.1.tar.gz" list_url = "https://cloud.r-project.org/src/contrib/Archive/maps" version('3.3.0', sha256='199afe19a4edcef966ae79ef802f5dcc15a022f9c357fcb8cae8925fe8b...
trsheph/SynBioStandardizer
SynColi2/SyGS_v2.py
Python
bsd-2-clause
3,078
0.01462
#!/usr/bin/env python ##### # # Synthetic Biology Gene Standardizer # Copyright (c) 2015, Tyson R. Shepherd, PhD # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source co...
*2+1)].rstrip()); fIn.close() genes=[]; # # Start your engines # stnds = ['N','BioB','BglB','MoClo','GB','Chi'] SynthRecs = [] q = 0 for p in geneSeqIn: # # Look for: non-ATG start codons, non-TAA stop codons, # NdeI: NdeI # BioBrick: EcoRI, SpeI, XbaI, PstI, mfeI, avrII, NheI, NsiI, SbfI,...
BbsI, BsaI, MlyI # GoldenBraid: BsmI, BtgZI # Chi sites # Then makes non-conflicting point mutations to highest allowed codon usage # tmpGeneSeqOut=genestand2.refactor(geneName[q], p, stnds, 1) geneSeqOut.append(genestand2.mutatePromoters(geneName[q], tmpGeneSeqOut)) q=q+1 # print(str(q)+'/'+s...
leyyin/stk-stats
maint_graphics.py
Python
mit
651
0.004608
#!/usr/bin/env python import os import time import django from userreport import maint os.environ['DJANGO_SETTINGS_MODULE'] = 'userreport.settings' django.setup() start_time = time.time() remove_time, get_time, save_time = maint.refresh_data() total_time = time
.time() - start_time print("--- Remove Time: {:>5.2f} seconds, {:>5.2%} ---".format(remove_time, remove_time / total_time)) print("--- Get Time: {:>5.2f} seconds, {:>5.2%} ---".format(get_time, get_time / total_time)) print("--- Save Time: {:>5.2f} seconds, {:>5.2%} ---"
.format(save_time, save_time / total_time)) print("--- Total Time: {:>5.2f} seconds ---".format(total_time))
leonardbinet/Transilien-Api-ETL
api_etl/extract_schedule.py
Python
mit
5,949
0.001513
""" Module used to download from SNCF website trains schedules and save it in the right format in different databases (Dynamo or relational database) """ from os import path, makedirs import zipfile from urllib.request import urlretrieve import logging import pandas as pd from api_etl.settings import __GTFS_FOLDER_P...
rl %s", self.schedule_url) gtfs_links = pd.read_csv(self.schedule_url) # Create data folder if n
ecessary if not path.exists(self.gtfs_folder): makedirs(self.gtfs_folder) # Download and unzip all files # Check if one is "gtfs-lines-last" gtfs_lines_last_present = False for link in gtfs_links["file"].values: logger.info("Download of %s", link) ...
kret0s/gnuhealth-live
tryton/server/trytond-3.8.3/trytond/modules/sale_promotion/tests/test_sale_promotion.py
Python
gpl-3.0
824
0.002427
# This file is part of Tryton. The COPYRIGHT file at the top level of # this repository contains the full copyright notices and license terms. import unittest import doctest import trytond.tests.test_tryton from trytond.tests.test_tryton import ModuleTestCase from trytond.tests.test_tryton import doctest_setup, doctes...
onTestCase(ModuleTestCase): 'Test Sale Promotion module' module = 'sale_promotion' def suite(): suite = trytond.tests.test_tryton.suite() suite.addTests(unittest.TestLoader().loadTestsFromTestCase( SalePromotionTestCase)) suite.addTests(doctest.DocFileSuite('scenario_sale_promotion.rst...
doctest_setup, tearDown=doctest_teardown, encoding='utf-8', optionflags=doctest.REPORT_ONLY_FIRST_FAILURE)) return suite
wathen/PhD
MHD/FEniCS/MHD/Stabilised/SaddlePointForm/Test/SplitMatrix/ScottTest/Lshaped/Dominik/NS.py
Python
mit
11,453
0.021304
#!/usr/bin/python # interpolate scalar gradient onto nedelec space im
port petsc4py import sys petsc4py.init(sys.argv) from petsc4py import PETSc from dolfin import * import mshr Print = PETSc.Sys.Print # from MatrixOperations import * import numpy as np import PETScIO as IO import common import scipy import scipy.io import time import BiLinear as forms import IterOperation
s as Iter import MatrixOperations as MO import CheckPetsc4py as CP import ExactSol import Solver as S import MHDmatrixPrecondSetup as PrecondSetup import NSprecondSetup import MHDprec as MHDpreconditioner import memory_profiler import gc import MHDmulti import MHDmatrixSetup as MHDsetup import Lshaped import NSprecondi...
sgarrity/bedrock
bedrock/releasenotes/views.py
Python
mpl-2.0
8,074
0.001362
# 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 re from copy import copy from operator import attrgetter from django.conf import settings from django.http import...
f note.id in notes: continue if note.is_public and note.tag: note.link = '%s#note-%s' % (link, note.id) note.version = release.version notes[note.id] = note # Sort by date in descending order notes = sorted(notes.values(), key=attrget...
erse=True) return l10n_utils.render(request, 'firefox/releases/nightly-feed.xml', {'notes': notes}, content_type='application/atom+xml')
code-google-com/cortex-vfx
test/IECore/LensDistortOpTest.py
Python
bsd-3-clause
2,750
0.019636
########################################################################## # # Copyright (c) 2013, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistribu...
OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY O...
############################################################## from IECore import * import sys import unittest class LensDistortOpTest(unittest.TestCase): def testDistortOpWithStandardLensModel(self): # The lens model and parameters to use. o = CompoundObject() o["lensModel"] = StringData( "StandardRadial...
agry/NGECore2
scripts/object/tangible/wearables/ring/item_ring_set_commando_utility_b_01_01.py
Python
lgpl-3.0
1,084
0.020295
import sys def setup(core, object): object.setAttachment('radial_filename', 'ring/unity') object.setAttachment('objType', 'ring') object.setStfFilename('static_item_n') object.setStfName('item_ring_set_commando_utility_b_01_01') object.setDetailFilename('static_item_d') object.setDetailName('item_ring_set_comman...
mod_bonus.@stat_n:strength_modified', 15) object.setIntAttribute('cat_skill_mod_bonus.@stat_n:expertise_devastation_bonus',
5) object.setStringAttribute('@set_bonus:piece_bonus_count_3', '@set_bonus:set_bonus_commando_utility_b_1') object.setStringAttribute('@set_bonus:piece_bonus_count_4', '@set_bonus:set_bonus_commando_utility_b_2') object.setStringAttribute('@set_bonus:piece_bonus_count_5', '@set_bonus:set_bonus_commando_utility_b_3')...
eswartz/panda3d-stuff
programs/dynamic-geometry/draw_path_tris.py
Python
mit
10,950
0.010594
''' Draw a tunnel with keyboard movement, create it and its collision geometry, and walk through it. Created on Feb 25, 2015 Released Feb 4, 2016 @author: ejs ''' from panda3d.core import loadPrcFile, loadPrcFileData # @UnusedImport loadPrcFile("./myconfig.prc") # loadPrcFileData("", "load-display p3tinydisplay\nba...
{4}".format(int(pos.x*1
00)/100., int(pos.y*100)/100., int(pos.z)/100., self.fpscamera.getHeading(), self.fpscamera.getLookAngle())) prevPos = self.prevPos if not prevPos: self.prevPos = pos elif (pos - prevPos...
dedoogong/asrada
HandPose_Detector/FingerPosition.py
Python
apache-2.0
1,202
0.002496
from enum import IntEnum class FingerPosition(IntEnum): VerticalUp = 0 VerticalDown = 1 HorizontalLeft = 2 HorizontalRight = 3 DiagonalUpRigh
t = 4 DiagonalUpLeft = 5 DiagonalDownRight = 6 DiagonalDownLeft = 7 @staticmethod def get_finger_position_name(finger_position): if finger_position == FingerPosition.VerticalUp: finger_type = 'Vertical Up' elif finger_position == FingerPosition.VerticalDown: ...
elif finger_position == FingerPosition.HorizontalLeft: finger_type = 'Horizontal Left' elif finger_position == FingerPosition.HorizontalRight: finger_type = 'Horizontal Right' elif finger_position == FingerPosition.DiagonalUpRight: finger_type = 'Diagonal Up Right' ...
radicalbit/ambari
contrib/management-packs/odpi-ambari-mpack/src/main/resources/stacks/ODPi/2.0/services/HIVE/package/scripts/hcat_client.py
Python
apache-2.0
2,941
0.00578
#!/usr/bin/env python """ Licensed to the Apache Software Foundation (ASF) under one or more contributor l
icense agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Th
e 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 Unless required by applicable law or agreed to in writing, software distribute...
glaudsonml/kurgan-ai
tools/sqlmap/waf/modsecurity.py
Python
apache-2.0
777
0.003861
#!/usr/bin/env python """ Copyright (c) 2006-2016 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copyi
ng permission """ import re from lib.core.enums import HTTP_HEADER from lib.core.settings import WAF_ATTACK_VECTORS __product__ = "ModSecurity: Open Source Web Application Firewall (Trustwave)" def detect(get_page): retval = False for vector in WAF_ATTACK_VECTORS: page, headers, code = get_page(get...
retval = code == 501 and re.search(r"Reference #[0-9A-Fa-f.]+", page, re.I) is None retval |= re.search(r"Mod_Security|NOYB", headers.get(HTTP_HEADER.SERVER, ""), re.I) is not None retval |= "This error was generated by Mod_Security" in page if retval: break return retva...
htlcnn/pyrevitscripts
HTL.tab/Test.panel/Test.pushbutton/keyman/keyman/keyman/settings.py
Python
mit
3,109
0.001287
""" Django settings for keyman project. Generated by 'django-admin startproject' using Django 1.11.7. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ import os ...
on.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValida...
True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.11/howto/static-files/ STATIC_URL = '/static/'
googleapis/python-aiplatform
google/cloud/aiplatform_v1/types/tensorboard.py
Python
apache-2.0
4,087
0.001223
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
, message=timestamp_pb2.Timestamp,) update_time = proto.Field(proto.MESSAGE, number=7, message=timestamp_pb2.Timestamp,) labels = proto.MapField(pro
to.STRING, proto.STRING, number=8,) etag = proto.Field(proto.STRING, number=9,) __all__ = tuple(sorted(__protobuf__.manifest))
bzz/kythe
.ycm_extra_conf.py
Python
apache-2.0
9,245
0.008329
#!/usr/bin/python # Copyright 2017 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 ap...
AST_INIT_FAILURE_TIME = None # If this many seconds have passed since the last failure, then try to generate # the compilation database again. RETRY_TIMEOUT_SECONDS = 120 HEADER_EXTENSIONS = ['.h', '.hpp', '.hh', '.hxx'] SOURCE_EXT
ENSIONS = ['.cc', '.cpp', '.c', '.m', '.mm', '.cxx'] NORMALIZE_PATH = 1 REMOVE = 2 # List of clang options and what to do with them. Use the '-foo' form for flags # that could be used as '-foo <arg>' and '-foo=<arg>' forms, and use '-foo=' for # flags that can only be used as '-foo=<arg>'. # # Mapping a flag to NORMA...
JoePelz/SAM
spec/python/pages/test_rules.py
Python
gpl-3.0
19,920
0.001908
# coding=utf-8 from spec.python import db_connection import operator import pytest from datetime import datetime from sam.pages.rules
import Rules, RulesApply, RulesEdit, RulesNew from sam.models.security import rules, rule_template, ruling_process from sam import errors db = db_connection.db sub_id = db_connection.default_sub ds_full = db_connection.dsid_default def reset_dummy_rules(): r = rules.Rules(db, sub_id) r.clear() r.add_rul...
esc3', {}) r.add_rule("suspicious.yml", 'suspicious traffic', 'desc4', {}) all_rules = r.get_all_rules() ids = [rule.id for rule in all_rules] # enable all but portscan.yml r.edit_rule(ids[0], {'active': True}) r.edit_rule(ids[1], {'active': True}) r.edit_rule(ids[3], {'active': True}) def...
EmreAtes/spack
var/spack/repos/builtin/packages/libiconv/package.py
Python
lgpl-2.1
2,156
0.000464
############################################################################## # 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...
RPOSE. See the terms and # conditions of the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ##########...
nv provides an implementation of the iconv() function and the iconv program for character set conversion.""" homepage = "https://www.gnu.org/software/libiconv/" url = "http://ftp.gnu.org/pub/gnu/libiconv/libiconv-1.15.tar.gz" version('1.15', 'ace8b5f2db42f7b3b3057585e80d9808') version('1.14',...
ClockworkOrigins/m2etis
configurator/configurator/NedGenerator.py
Python
apache-2.0
6,119
0.001471
__author__ = 'sianwahl' from string import Template class NedGenerator: def __init__(self, number_of_channels): self.number_of_channels = number_of_channels def generate(self): return self._generate_tuplefeeder_ned(), self._generate_m2etis_ned() def _generate_tuplefeeder_ned(self): ...
input trace_in; // gate for trace file commands input udpIn; output udpOut; input tcpIn; output tcpOut; submodules: tupleFeeder: TupleFeeder; connections allowunconnected: from_lowerTier --> tupleFeeder.from_lowerTier; to_lowerTie
r <-- tupleFeeder.to_lowerTier; trace_in --> tupleFeeder.trace_in; udpIn --> tupleFeeder.udpIn; udpOut <-- tupleFeeder.udpOut; } """ channel_specific_parameters = "" for i in range(0, self.number_of_channels): channel_specific_parameters += "int numToSend_" + ...
tongpa/pypollmanage
pypollmanage/service/questionservice.py
Python
apache-2.0
1,641
0.014016
# -*- coding: utf-8 -*- import json from tg import request from tgext.pluggable import app_model from tgext.pyutilservice import Utility from surveyobject import QuestionObject class QuestionService(object): def __init__(self): self.utility = Utility() pass def create(self, **question...
.question ) question
.id_question = self.utility.setIfEmpty(question.id_question) self.questionProject = app_model.QuestionProject.getId(question.id_question_project) questionLang = self.questionObject.questionLang questionLang.id_language = self.questionProject.id_language if question.id_question : ...
JulyKikuAkita/PythonPrac
cs15211/MinimumWindowSubstring.py
Python
apache-2.0
7,107
0.001688
__source__ = 'https://leetcode.com/problems/minimum-window-substring/' # https://github.com/kamyu104/LeetCode/blob/master/Python/minimum-window-substring.py # Time: O(n) # Space: O(k), k is the number of different characters # Hashtable # # Description: Leetcode # 76. Minimum Window Substring # # Given a string S and ...
th(); ++i) { if(--count[s.charAt(i)] >= 0) { windowSize++; } if (windowSize == t.length()) { while (++count[s.charAt(left)] <= 0) { left++; } if (i - left < end - start) { start = ...
return start == -1 ? "" : s.substring(start, end + 1); } } '''
breunigs/livestreamer
src/livestreamer/plugins/filmon_us.py
Python
bsd-2-clause
3,678
0.002719
import re import requests from livestreamer.compat import urlparse from livestreamer.exceptions import PluginError, NoStreamsError from livestreamer.plugin import Plugin from livestreamer.stream import RTMPStream, HTTPStream from livestreamer.utils import urlget, urlresolve, prepend_www RTMP_URL = "rtmp://204.107.26....
07.26.75/streamer" SWF_URL = "http://www.filmon.us/application/themes/base/flash/broadcast/VideoChatECCDN_debug_withoutCenteredOwner.swf" SWF_UPLOAD_URL = "http://www.battlecam.com/application/themes/base/flash/MediaPlayer.swf" class Filmon_us(Plugin): @classmethod def can_handle_url(self, url): retur...
s not usable and required by Filmon_us plugin") streams = {} try: # history video if "filmon.us/history" in self.url or "filmon.us/video/history/hid" in self.url: streams['default'] = self._get_history() # uploaded video elif "filmon.us/v...
rec/BiblioPixel
bibliopixel/control/rest/decorator.py
Python
mit
2,062
0.00097
import flask, functools, traceback, urllib from .. import editor NO_PROJECT_ERROR = 'No Project is currently loaded' BAD_ADDRESS_ERROR = 'Bad address {address}' BAD_GETTER_ERROR = 'Couldn\'t get address {address}' BAD_SETTER_ERROR = 'Couldn\'t set value {value} at address {address}' def single(method): """Decora...
error = BAD_SETTER_ERROR result = method(self, ed, value) result = {'value': result} except Except
ion as e: traceback.print_exc() msg = '%s\n%s' % (error.format(**locals()), e) result = {'error': msg} return flask.jsonify(result) return single def multi(method): """Decorator for RestServer methods that take multiple addresses""" @functools.wraps(method) ...
tburrows13/Game-of-Life
tools.py
Python
mit
771
0
import time def import_grid(file_to_open): grid = [] print(file_to_open) with open(file_to_open) as file: for i, line in enumerate(file):
if i == 0: iterations = int(line.split(" ")[0]) delay = float(line.split(" ")[1]) else: grid.append([]) line = line.strip() for item in line: grid[i-1].append(int(
item)) return grid, iterations, delay def save_grid(file, grid): with open(file, 'w') as file: for line in grid: file.write(line + "\n") def check_time(prev_time, freq): if time.time() - prev_time > freq: return True else: return False
pyrocko/pyrocko
src/apps/colosseo.py
Python
gpl-3.0
7,525
0
from __future__ import print_function # http://pyrocko.org - GPLv3 # # The Pyrocko Developers, 21st Century # ---|P------/S----------~Lg---------- import sys import logging import os.path as op from optparse import OptionParser from pyrocko import util, scenario, guts, gf from pyrocko import __version__ logger = lo...
se('map', args) if len(args) == 0: args.append('.') fn = get_scenario_yml(args[0]) if not fn: parser.print_help() sys.exit(1) project_dir = args[0] gf_stores_path = op.join(project_dir, 'gf_stores') engine = get_engine([gf_stores_path]) try: sc = guts.lo...
sc.make_map(op.join(project_dir, 'map.pdf')) except scenario.ScenarioError as e: die(str(e)) def command_snuffle(args): from pyrocko.gui import snuffler parser, options, args = cl_parse('map', args) if len(args) == 0: args.append('.') fn = get_scenario_yml(args[0]) i...
ECP-CANDLE/Supervisor
workflows/async-search/python/utils.py
Python
mit
594
0.001684
from string import Template import re import os import sys import time import json import math import os import subprocess import csv def saveResults(resultsList, json_fname, csv_fname): print(resultsList) print(json.dumps(resultsList, indent=4, sort_keys=True)) with open(json_fname, 'w') as outfile: ...
utfile, indent=4, sort_keys=True) keys = resultsList[0].keys() with open(csv_fname, 'w') as output_file:
dict_writer = csv.DictWriter(output_file, keys) dict_writer.writeheader() dict_writer.writerows(resultsList)
billiob/papyon
papyon/util/odict.py
Python
gpl-2.0
1,321
0.006056
from UserDict import UserDict class odict(UserDict): def __init__(self, dict = None): self._keys = [] UserDict.__init__(self, dict) def __delitem__(self, key): UserDict.__delitem__(self, key) self._keys.remove(key) def __setitem__(self, key, item): UserDict.__setit...
ict.clear(self) self._keys = [] def copy(self): dict = UserDict.copy(self) dict._keys = self._keys[:] return dict def items(self): return map(lambda key: (key, self[key]), self._keys) def keys(self): return self._keys[:] def popitem(self): try:...
-1] except IndexError: raise KeyError('dictionary is empty') val = self[key] del self[key] return (key, val) def setdefault(self, key, failobj = None): if key not in self._keys: self._keys.append(key) return UserDict.setdefault(self, key, failobj) ...
albertfxwang/grizli
grizli/multifit.py
Python
mit
180,455
0.010662
"""Functionality for manipulating multiple grism exposures simultaneously """ import os import time import glob from collections import OrderedDict import multiprocessing as mp import scipy.ndimage as nd import numpy as np import matplotlib.pyplot as plt from astropy.table import Table import astropy.io.fits as pyfi...
ocal i
mports from . import utils from . import model #from . import stack from .fitting import GroupFitter from .utils_c import disperse from .utils_c import interp from .utils import GRISM_COLORS, GRISM_MAJOR, GRISM_LIMITS, DEFAULT_LINE_LIST def test(): import glob from grizlidev import utils import griz...
not-na/peng3d
docs/pyglet/graphics/vertexdomain.py
Python
gpl-2.0
851
0.008226
#!/usr/bin/env python # -*- coding: utf-8 -*- # # vertexdomain.py # # Copyright 2016 notna <notna@apparat.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 ...
your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOU
T 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 this program; if not, write to the Free Software # Foundation, Inc...
nburn42/tensorflow
tensorflow/python/ops/linalg_grad.py
Python
apache-2.0
14,666
0.009
# Copyright 2015 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...
A*X = B. """ a = op.inputs[0] b = op.inputs[1] l2_regularizer = math_ops.cast(op.inputs[2], a.dtype.base_dtype) # pylint: disable=protected-access chol = linalg_ops._RegularizedGramianCholesky( a, l2_regularizer=l2_regularizer, first_kind=False) # pylint: enable=protected-access ...
ops.cholesky_solve(chol, math_ops.matmul(a, grad)) # Temporary tmp = (A * A^T + lambda * I)^{-1} * B. tmp = linalg_ops.cholesky_solve(chol, b) a1 = math_ops.matmul(tmp, a, adjoint_a=True) a1 = -math_ops.matmul(grad_b, a1) a2 = grad - math_ops.matmul(a, grad_b, adjoint_a=True) a2 = math_ops.matmu...
jplusplus/dystopia-tracker
app/core/migrations/0001_initial.py
Python
lgpl-3.0
9,322
0.008904
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Category' db.create_table(u'core_category', ( ...
d', [], {'max_length': '75'}) }, u'core.prediction': { 'Meta': {'object_name': 'Prediction'}, 'category': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['core.Category']"}),
'creation_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'description_D': ('django.db.models.fields.TextField', [], {'max_length': '300'}), 'description_E': ('django.db.models.fields.TextField', [], {'max_length': '300'}), ...
raspibo/Livello1
var/www/cgi-bin/valori2csv_search_date.py
Python
mit
2,996
0.010013
#!/usr/bin/env python3 """ The MIT License (MIT) Copyright (c) 2016 davide Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, co...
ribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in al
l copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY...
lukereding/mateChoiceTracking
low_light_tracker.py
Python
apache-2.0
17,260
0.025203
import numpy as np import cv2, csv, os, re, sys, time, argparse, datetime ''' started 25 August 2015 31 August 2015: modifying script so that it queries frames from a video taken with ffmpeg 10 Nov 2015 modifying for use in low light LCD tank (filters over the four flourescent light) assumes there are four 'parts'...
her the right or lefthand side of the tank to be declared side bias. defaults to 0.75",nargs='?',default=0.75) args = ap.parse_args() # print arguments to the screen print("\n\n\tinput path: {}".format(args.pathToVideo)) print("\tname of trial: {}".format(args.videoName)) print("\tfps of video: {}".format(args.fps)) ...
d 1") # calculate the time that the program should start the main loop start_time = time.time() lower = np.array([0,0,0]) upper = np.array([255,255,20]) counter = 0 # output to csv file where the results will be written name = args["videoName"] print "name of csv file: " + str(name) + ".csv" myfile = open(name+".csv...
bertrandvidal/stuff
djangoprojects/django_rest_framework/tutorial/snippets/urls.py
Python
unlicense
568
0.001761
from django.conf.urls import url, include from snippets import views
from rest_framework.routers import DefaultRouter # Create a router and register our viewsets with it. router = DefaultRouter() router.register(r'snippets', views.SnippetViewSet) router.register(r'users', views.UserViewSet) # The API URLs
are now determined automatically by the router. # Additionally, we include the login URLs for the browsable API. urlpatterns = [ url(r'^', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) ]
dufferzafar/mitmproxy
netlib/http/multipart.py
Python
mit
898
0.001114
import re from netlib.http import headers def decode(hdrs, content): """ Takes a mul
tipart boundary encoded string and returns list of (key, value) tuples. """ v = hdrs.get("content-type") if v: v = headers.parse_content_type(v) if not v: return [] try: boundary = v[2]["boundary"].encode("ascii") except (KeyError, UnicodeError): ...
s() if len(parts) > 1 and parts[0][0:2] != b"--": match = rx.search(parts[1]) if match: key = match.group(1) value = b"".join(parts[3 + parts[2:].index(b""):]) r.append((key, value)) return r return []