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
sangh/LaserShow
pyglet-hg/experimental/swigtypes/parse.py
Python
bsd-3-clause
12,636
0.002137
#!/usr/bin/env python ''' ''' __docformat__ = 'restructuredtext' __version__ = '$Id: $' import gzip import cPickle as marshal import optparse import os import sys import xml.sax def parse_type(type_string): '''Get a tuple of the type components for a SWIG-formatted type. For example, given the type "p.f(p....
push() # Push item elif c == ',': buf = flush() pop() # Pop item push() # Push item elif c == ')': buf = flush() pop() # Pop item
pop() # Pop param list else: buf += c flush() type_tuple = finalize(stack[0]) return type_tuple class SwigInterfaceHandler(object): def __init__(self): self.name = None self.cdecls = [] self.constants = [] def attribute(self...
LTS5/connectomeviewer
cviewer/plugins/cff2/ui/cnetwork_tree_node.py
Python
bsd-3-clause
2,792
0.011461
""" Specify the NetworkNode with its action, context-menus """ # Copyright (C) 2009-2010, Ecole Polytechnique Federale de Lausanne (EPFL) and # University Hospital Center and University of Lausanne (UNIL-CHUV) # # Modified BSD License # Standard library imports import os # Enthought library imports from traits.api im...
kw={'name': 'Edge Parameters', 'action': 'object._edge_parameters', 'tooltip': 'Thresholding and Change Attributes', 'enabled_when' : 'object.loaded == True'}, )
_RenderMatrixAction = Instance(Action, kw={'name': 'Connectome Matrix Viewer', 'action': 'object.invoke_matrix_viewer', 'tooltip':'View the connectivity matrices', 'enabled...
TomAugspurger/pandas
pandas/tests/arithmetic/test_datetime64.py
Python
bsd-3-clause
90,010
0.000644
# Arithmetic tests for DataFrame/Series/Index/Array classes that should # behave identically. # Specifically for datetime64 and datetime64tz dtypes from datetime import datetime, time, timedelta from itertools import product, starmap import operator import warnings import numpy as np import pytest import pytz from pa...
get_upcast_box, ) # ------------------------------------------------------------------ # Comparisons class TestDatetime64ArrayLikeComparisons: # Comparison tests for datetime64 vectors fully parametrized over # DataFrame/Series/DatetimeIndex/DatetimeArray. Ideally all comparison # tests will eventuall...
tz = tz_naive_fixture box = box_with_array xbox = box_with_array if box_with_array is not pd.Index else np.ndarray dti = date_range("20130101", periods=3, tz=tz) other = np.array(dti.to_numpy()[0]) dtarr = tm.box_expected(dti, box) result = dtarr <= other ...
111pontes/ydk-py
core/ydk/services/ietf_netconf.py
Python
apache-2.0
60,135
0.01485
""" ietf_netconf NETCONF Protocol Data Types and Protocol Operations. Copyright (c) 2011 IETF Trust and the persons identified as the document authors. All rights reserved. Redistribution and use in sour
ce and binary forms, with or without modification, is permitted pursuant to, and subject to the license terms contained in, the Simplified BSD License set forth in Section 4.c of the IETF Trust's Legal Provisions Relating to IETF Documents (http\://trustee.ietf.org/license\-info). This version of this YANG module is p...
legal notices. """ import re import collections from enum import Enum from ydk.types import Empty, YList, YLeafList, DELETE, Decimal64, FixedBitsDict from ydk.errors import YPYError, YPYModelError class EditOperationTypeEnum(Enum): """ EditOperationTypeEnum NETCONF 'operation' attribute values ...
ooblog/TSF1KEV
TSFpy/debug/sample_help.py
Python
mit
2,181
0.024759
#! /usr/bin/env python # -*- coding: UTF-8 -*- from __future__ import division,print_function,absolute_import,unicode_literals import sys import os os.chdir(sys.path[0]) sys.path.append('/mnt/sda2/github/TSF1KEV/TSFpy') from TSF_io import * #from TSF_Forth import * from TSF_shuffle import * from TSF_match import * fro...
"\t".join(["usage: ./TSF.py [command|file.tsf] [argv] ...", "commands:", " --help this commands view", " --about about TSF UTF-8 text (Japanese) view\" ", " --python TSF.tsf to Python.py view or save\" ", " --helloworld \"Hello world 1 #TSF_echoN\" sample", " --qui...
of Beer sample", " --fizzbuzz ([0]#3Z1~0)+([0]#5Z2~0) Fizz Buzz Fizz&Buzz sample", " --zundoko Zun Zun Zun Zun Doko VeronCho sample", " --fibonacci Fibonacci number 0,1,1,2,3,5,8,13,21,55... sample", " --prime prime numbers 2,3,5,7,11,13,17,19,23,29... sample", " --calcFX fr...
clay584/dns-updater
dns-updater.py
Python
apache-2.0
6,247
0.024972
#!/usr/bin/python # Import modules for CGI handling import cgi from IPy import parseAddress, IP import re from subprocess import Popen, PIPE # Create instance of FieldStorage form = cgi.FieldStorage() # Get data from fields ip_address = form.getvalue('ip_address') if form.getvalue('fqdn') == None: fqdn = 'blank' e...
t ' <tr>' print ' <td align="center">Hostname: <input placeholder=hostname type=text name=fqdn></td>' print ' </tr>' print ' <tr>' print ' <td align="center">IP Address: <input placeholder=10.0.0.1 type=text name=ip_address></td>' print ' </tr>' print ' <tr>' ...
rd></td>' print ' </tr>' print ' <tr>' print ' <td align="center" width="500"><input type=radio name=action value=delete> Delete <input type=radio name=action value=add /> Update</td>' print ' </tr>' print ' <td align="center">' if valid_form: print 'DNS Record Updated ...
Mo-Talha/Nomad
data/search/elastic.py
Python
mit
7,634
0.001703
from datetime import datetime import mongoengine import elasticsearch from elasticsearch import helpers from models.employer import Employer import models.term as Term import shared.secrets as secrets import shared.logger as logger COMPONENT = 'Search' elastic_instance = elasticsearch.Elasticsearch() def index_...
ex": "waterlooworks", "_type": "jobs", "_parent": employer.name, "_id": str(job.id), "_source": { "employer_name": employer.name, "job_title": job.title, "job_year": jo...
"job_keywords": [k.keyword for k in job.keywords], "job_locations": [location.name for location in job.location], "job_programs": job.programs, "job_levels": job.levels } } ...
nathanielvarona/airflow
airflow/migrations/versions/64a7d6477aae_fix_description_field_in_connection_to_.py
Python
apache-2.0
2,586
0.000387
# # 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...
e.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 permissions and limit...
s: f5b5ec089444 Create Date: 2020-11-25 08:56:11.866607 """ import sqlalchemy as sa # noqa from alembic import op # noqa # revision identifiers, used by Alembic. revision = '64a7d6477aae' down_revision = '61ec73d9401f' branch_labels = None depends_on = None def upgrade(): """Apply fix description field in co...
sparkslabs/kamaelia_
Sketches/RJL/Kamaelia/Community/RJL/Kamaelia/Protocol/HTTP/ErrorPages.py
Python
apache-2.0
3,275
0.011298
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1) # # (1) Kamaelia Contributors are listed in the AUTHORS file and at # http://www.kamaelia.org/AUTHORS - please extend this file, # not this notice. # # Licensed under the Apache License...
ributed 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. # ------------------------------------------------------------------------- """\...
======================== websiteErrorPage ======================== A simple HTTP request handler for HTTPServer. websiteErrorPage generates basic HTML error pages for an HTTP server. """ from Axon.Component import component def getErrorPage(errorcode, msg = ""): if errorcode == 400: return { "...
lindseypack/NIM
devices/migrations/0013_auto_20140925_1616.py
Python
mit
981
0.004077
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import m
odels, migrations class Migration(migrations.Migration): dependencies = [ ('devices', '0012_auto_20140925_1540'), ] operations = [ migrations.AlterField( model_name='ap', name='notes', field=models.TextField(default=b'', verbose_name=b'Notes', blank=Tr...
', verbose_name=b'Notes', blank=True), ), migrations.AlterField( model_name='switch', name='notes', field=models.TextField(default=b'', verbose_name=b'Notes', blank=True), ), migrations.AlterField( model_name='ups', name='notes'...
0111001101111010/open-health-inspection-api
venv/lib/python2.7/site-packages/pymongo/common.py
Python
gpl-2.0
23,408
0.000299
# Copyright 2011-2012 10gen, 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 writing...
idate_readable, 'ssl_certfile': validate_readable, 'ssl_cert_reqs': validate_cert_reqs, 'ssl_ca_certs': validate_readable, 'readpreference': validate_read
_preference, 'read_preference': validate_read_preference, 'tag_sets': validate_tag_sets, 'secondaryacceptablelatencyms': validate_positive_float, 'secondary_acceptable_latency_ms': validate_positive_float, 'auto_start_request': validate_boolean, 'use_greenlets': validate_boolean, 'authmechan...
endlessm/chromium-browser
tools/style_variable_generator/PRESUBMIT.py
Python
bsd-3-clause
746
0
# Copyright 2019 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. """Presubmit script for changes affecting tools/style_variable_generator/ See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for mor...
, whitelist=WHITELIST) def CheckChangeOnCommit(input_api, output_api):
return input_api.canned_checks.RunUnitTestsInDirectory( input_api, output_api, '.', whitelist=WHITELIST)
bdzimmer/handwriting
handwriting/improc.py
Python
bsd-3-clause
7,094
0.000846
# -*- coding: utf-8 -*- """ Image processing and feature extraction functions. """ import cv2 import numpy as np def pad_image(im, width, height, border=255): """pad char image in a larger image""" xoff = abs(int((im.shape[1] - width) / 2)) yoff = abs(int((im.shape[0] - height) / 2)) if width >= ...
feature vector from four downsampling amounts""" return downsample_multi(image, [0.4, 0.2, 0.1, 0.05]) def downsample_multi(image, scales): """create a feature vector from arbitrary downsampling amounts""" return np.hstack([np.rav
el(downsample(image, x)) for x in scales]) def max_pool(im): """perform 2x2 max pooling""" return np.max( np.stack( (im[0::2, 0::2], im[0::2, 1::2], im[1::2, 0::2], im[1::2, 1::2]), axis=-1), axis=-1) def max_pool_multi(image,...
kave/cfgov-refresh
cfgov/v1/admin.py
Python
cc0-1.0
143
0.013986
fr
om django.contrib import admin from models.snippets import Contact @admin.register(Contact) class ContactAdmin(admin.ModelAdmin): pas
s
NERC-CEH/jules-jasmin
majic/joj/services/dataset.py
Python
gpl-2.0
13,566
0.003096
""" # Majic # Copyright (C) 2014 CEH # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This pr...
filter(Dataset.dataset_type_id == dataset_type_id, or_(Dataset.viewable_by_user_id == user_id, Dataset.viewable_by_user_id == None),
Dataset.deleted == False).all() def get_dataset_types(self): """Returns all of the dataset types in the system""" with self.readonly_scope() as session: return session.query(DatasetType).all() def get_dataset_by_id(self, dataset_id, user_id=...
lem9/weblate
weblate/accounts/forms.py
Python
gpl-3.0
20,803
0
# -*- coding: utf-8 -*- # # Copyright © 2012 - 2017 Michal Čihař <michal@cihar.com> # # This file is part of Weblate <https://weblate.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, eith...
option( selected_choices, option_value, option_label ) ) return '\n'.join(output) class SortedSelectMultiple(SortedSelectMixin, forms.SelectMultiple): """Wrapper class to sort choices alphabetically.""" class SortedSelect(SortedSelectMixin, forms.Select): ...
fields = ( 'language', 'languages', 'secondary_languages', ) widgets = { 'language': SortedSelect, 'languages': SortedSelectMultiple, 'secondary_languages': SortedSelectMultiple, } def __init__(self, *args, **kwargs): ...
uclouvain/osis_louvain
assessments/templatetags/score_display.py
Python
agpl-3.0
1,668
0.0018
############################################################################## # # OSIS stands for Open Student Information System. It's an application # designed to manage the core business of higher education institutions, # such as universities, faculties, institutes and professional schools. # The core ...
if value is None or str(value) == '-': return "" else: try: if decimal_option: return "{0:.2f}".format(value)
else: return "{0:.0f}".format(value) except: return value
michaelhidalgo/7WCSQ
Tools/SQLMap/sqlmap/lib/core/enums.py
Python
apache-2.0
10,079
0.004465
#!/usr/bin/env python """ Copyright (c) 2006-2017 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ class PRIORITY: LOWEST = -100 LOWER = -50 LOW = -10 NORMAL = 0 HIGH = 10 HIGHER = 50 HIGHEST = 100 class SORT_ORDER: FIRST = 0 SECOND = 1 ...
}\Z' ORACLE = r'(?i)\As:[0-9a-f]{60}\Z' ORACLE_OLD = r'(?i)\A[01-9a-f]{16}\Z' MD5_GENERIC = r'(?i)\
A[0-9a-f]{32}\Z' SHA1_GENERIC = r'(?i)\A[0-9a-f]{40}\Z' SHA224_GENERIC = r'(?i)\A[0-9a-f]{28}\Z' SHA384_GENERIC = r'(?i)\A[0-9a-f]{48}\Z' SHA512_GENERIC = r'(?i)\A[0-9a-f]{64}\Z' CRYPT_GENERIC = r'(?i)\A(?!\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\Z)(?![0-9]+\Z)[./0-9A-Za-z]{13}\Z' WORDPRESS = r'(?i)\A...
ruchee/vimrc
vimfiles/bundle/vim-python/submodules/pylint/pylint/checkers/imports.py
Python
mit
38,570
0.001037
# Copyright (c) 2006-2015 LOGILAB S.A. (Paris, FRANCE) <contact@logilab.fr> # Copyright (c) 2012-2014 Google, Inc. # Copyright (c) 2013 buck@yelp.com <buck@yelp.com> # Copyright (c) 2014-2020 Claudiu Popa <pcmanticore@gmail.com> # Copyright (c) 2014 Brett Cannon <brett@python.org> # Copyright (c) 2014 Arun Persaud <aru...
pe: str):
"""generate a dependencies graph and add some information about it in the report's section """ outputfile = _dependencies_graph(filename, dep_info) sect.append(Paragraph(f"{gtype}imports graph has been written to {outputfile}")) # the import checker itself #########################################...
chrizel/onpsx
src/onpsx/core/migrations/0004_auto__add_field_userrole_order__add_field_userprofile_order.py
Python
gpl-3.0
5,858
0.008194
# encoding: 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 field 'UserRole.order' db.add_column('core_userrole', 'order', self.gf('django.db.models.fields.I...
: "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.perm
ission': { 'Meta': {'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentTy...
chipsecintel/chipsec
source/tool/chipsec/modules/tools/vmm/hv/define.py
Python
gpl-2.0
23,148
0.007776
#CHIPSEC: Platform Security Assessment Framework #Copyright (c) 2010-2016, Intel Corporation # #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; Version 2. # #This program is distributed in the hope...
treet, Fifth Floor, Boston, MA 02110-1301, USA. # #Contact information: #chipsec@intel.com # """ Hyper-V specific defines """ import re msrs = {
0x40000000: 'HV_X64_MSR_GUEST_OS_ID', 0x40000001: 'HV_X64_MSR_HYPERCALL', 0x40000002: 'HV_X64_MSR_VP_INDEX', 0x40000003: 'HV_X64_MSR_RESET', 0x40000010: 'HV_X64_MSR_VP_RUNTIME', 0x40000020: 'HV_X64_MSR_TIME_REF_COUNT', 0x40000021: 'HV_X64_MSR_REFERENCE_TSC', ...
ketch/effective_dispersion_RR
numerical_experiments/1D-propagation/FV_solution/sinusoidal/normal/write_slice.py
Python
bsd-2-clause
788
0.045685
from clawpack.petcl
aw.solution import Solution #from petclaw.io.petsc import read_petsc import matplotlib matplotlib.use('Agg') import matplotlib.pylab as pl from matplotlib import rc #rc('text', usetex=True) import numpy as np import os def write_slices(frame,fil
e_prefix,path,name): sol=Solution(frame,file_format='petsc',path=path,read_aux=False,file_prefix=file_prefix) x=sol.state.grid.x.centers; y=sol.state.grid.y.centers; my=len(y) q=sol.state.q f=open(name+'.txt','w') #f.writelines(str(xc)+" "+str(q[0,i,my/4])+" "+str(q[0,i,3*my/4])+"\n" for i,xc i...
nonZero/demos-python
src/examples/short/technology/grep.py
Python
gpl-3.0
459
0
#!/usr/bin/python2 ''' Implemting grep in python in less than 10 lines o
f code... ''' import re # for compile, finditer import sys # for argv # command line usage... if len(sys.argv) < 3: print('usage: grep.py [expr] [files...]') sys.exit(1) # first compile the regular expression... c = re.compile(sys.argv[1]) for filename in sys.argv[2:]: for num, l in enumerate(open(filen...
ICOS-Carbon-Portal/infrastructure
devops/roles/icos.jupyter/files/jusers.py
Python
gpl-3.0
11,637
0.001203
#!/opt/jusers/venv/bin/python3 import grp import os import pwd import random import spwd import subprocess import sys import click from concurrent.futures import ProcessPoolExecutor from ruamel.yaml import YAML PROJECT = '/project' DRY_RUN = False VERBOSE = False USERSDB = '/root/jusers.yml' PWDLENG = 10 # PLUGINS...
DRY_RUN: cmds = [l for g in gens for l in g] if len(cmds) == 0: return print("Everything is synced.") else: return print('\n'.join(cmds)) ncs = 0 for g in gens: cmds = init[:] for line in g: cmds.append(line) ncs += 1 ...
t.") sys.exit(1) if ncs == 0: print("Everything is synced.") # CLI @click.group() def cli(): pass @cli.command() @click.option('--force', '-f', is_flag=True, help="force restart") def restart_hub(force): """Restart the hub. All users are managed on the host system. The jupyter h...
mwisslead/vfp2py
testbed/test_lib.py
Python
mit
13,352
0.002097
# coding=utf-8 from __future__ import division, print_function import datetime as dt import math import os import random import faker from vfp2py import vfpfunc from vfp2py.vfpfunc import DB, Array, C, F, M, S, lparameters, parameters, vfpclass @lparameters() def MAIN(): pass @lparameters() def select_tests()...
assert len([w for w in S.cstring.split(',') if w]) == 3 assert len([w for w in S.cstring.split('.') if w]) == 1 assert vfpfunc.getwordnum(S.cstring, 2) == 'aaa,' assert vfpfunc.getwordnum(S.cstring, 2, ',') == ' BBB bbb' assert vfpfunc.getwordnum(S.cstring, 2
, '.') == '' assert vfpfunc.like('Ab*t.???', 'About.txt') assert not vfpfunc.like('Ab*t.???', 'about.txt') assert not ''[:1].isalpha() assert 'a123'[:1].isalpha() assert not '1abc'[:1].isalpha() assert not ''[:1].islower() assert 'test'[:1].islower() assert not 'Test'[:1].islower() a...
qPCR4vir/orange3
Orange/widgets/classify/owsvmclassification.py
Python
bsd-2-clause
7,592
0.000264
from collections import OrderedDict from PyQt4 import QtGui from PyQt4.QtCore import Qt from Orange.data import Table from Orange.classification.svm import SVMLearner, NuSVMLearner from Orange.widgets import settings, gui from Orange.widgets.utils.owlearnerwidget import OWBaseLearner class OWBaseSVM(OWBaseLearner):...
self._add_optimization_box() def _on_kernel_changed(self): enabled = [[False, False, False], # linear [True, True, True], # poly
[True, False, False], # rbf [True, True, False]] # sigmoid self.kernel_eq = self.kernels[self.kernel_type][1] mask = enabled[self.kernel_type] for spin, enabled in zip(self._kernel_params, mask): [spin.box.hide, spin.box.show][enabled]() self.set...
tomduijf/home-assistant
homeassistant/components/demo.py
Python
mit
5,021
0
""" homeassistant.components.demo ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Sets up a demo environment that mimics interaction with devices. """ import time import homeassistant.core as ha import homeassistant.bootstrap as bootstrap import homeassistant.loader as loader from homeassistant.const import ( CONF_PLATFORM, ATTR_E...
ponent('group') configurator = loader.get_component('configurator') config.setdefault(ha.DOMAIN, {}) config.setdefault(DOMAIN, {}) if config[DOMAIN].get('hide_demo_state') != 1: hass.states.set('a.Demo_Mode', 'Enabled') # Setup sun if not hass.config.latitude:
hass.config.latitude = 32.87336 if not hass.config.longitude: hass.config.longitude = 117.22743 bootstrap.setup_component(hass, 'sun') # Setup demo platforms for component in COMPONENTS_WITH_DEMO_PLATFORM: bootstrap.setup_component( hass, component, {component: {CONF_PLAT...
Ircam-Web/mezzanine-organization
organization/job/test/tests.py
Python
agpl-3.0
10,376
0.001157
# -*- coding: utf-8 -*- # # Copyright (c) 2016-2017 Ircam # Copyright (c) 2016-2017 Guillaume Pellerin # Copyright (c) 2016-2017 Emilie Zawadzki # This file is part of mezzanine-organization. # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public L...
name="dupont", email="jean@dupont.fr", message="I want this job", curriculum_vitae=self.file, cover_letter=self.file, job_offer=self.job_offer ) def test_job_offer_display_for_everyone(self): self.client.logout() response = self.cl...
esponse.status_code, 200) self.assertTemplateUsed(response, "job/job_offer_detail.html") self.client.login(username='user', password='test') response = self.client.get(self.job_offer.get_absolute_url()) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response,...
magenta/note-seq
note_seq/constants.py
Python
apache-2.0
2,620
0
# Copyright 2022 The Magenta Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in ...
ASIS, # 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. """Constants for music processing in Magenta.""" # Meter-related constants. DEFAULT_QUARTERS_PER_MINUTE = 120.0 DEFAULT_STEPS_PER_BAR ...
Default absolute quantization. DEFAULT_STEPS_PER_SECOND = 100 # Standard pulses per quarter. # https://en.wikipedia.org/wiki/Pulses_per_quarter_note STANDARD_PPQ = 220 # Special melody events. NUM_SPECIAL_MELODY_EVENTS = 2 MELODY_NOTE_OFF = -1 MELODY_NO_EVENT = -2 # Other melody-related constants. MIN_MELODY_EVENT ...
bambooom/OMOOC2py
_src/om2py5w/5wex0/client.py
Python
mit
2,054
0.039435
# -*- coding: utf-8 -*- # author: bambooom ''' My Diary Web App - CLI for client ''' import sys reload(sys) sys.setdefaultencoding('utf-8') import requests from bs4 import BeautifulSoup import re HELP = ''' Input h/help/? for help. Input q/quit to quit the process. Input s/sync to sync the diary log. Input lt/List...
gs) elif message in ['q','quit']: print 'Bye~' break elif message in ['lt','ListTags']: get_tags() elif message.startswith('st:'): tags = message[3:] elif message == 'FLUSH': delete_log() else: write_log(message,tags) if __name__ ==
'__main__': client()
SkyLothar/requests-aliyun
tests/test-utils.py
Python
apache-2.0
2,134
0
# -*- coding: utf8 -*- import base64 import hashlib import io import nose import requests import aliyunauth.utils import aliyunauth.consts def test_cal_b64md5(): s_data = b"foo" l_data = b"bar" * aliyunauth.consts.MD5_CHUNK_SIZE # normal data, None nose.tools.eq_(aliyunauth.utils.cal_b64md5(None), ...
size,
str nose.tools.eq_( aliyunauth.utils.cal_b64md5(io.StringIO(l_data.decode("utf8"))), b64md5(l_data) ) def test_to_bytes(): nose.tools.ok_(isinstance( aliyunauth.utils.to_bytes(u"foo"), requests.compat.bytes )) nose.tools.ok_(isinstance( aliyunauth.utils.to_b...
colinhiggs/pyramid-jsonapi
test_project/test_project/tests.py
Python
agpl-3.0
143,952
0.001765
from collections import namedtuple import configparser from functools import lru_cache import unittest from unittest.mock import patch, mock_open import transaction import testing.postgresql import webtest import datetime from pyramid.config import Configurator from pyramid.paster import get_app from sqlalchemy import ...
fg['app:main'].update(options or {}) config_path = '{}/tmp_testing.ini'.format(parent_dir) with open(config_path, 'w') as tmp_file: tmp_cfg.write(tmp_file) with warnings.catch_warnings(): # Suppress SAWarning: about Property _jsonapi_id being replaced by ...
ings.simplefilter( "ignore", category=SAWarning ) app = get_app(config_path) test_app = MyTestApp(app) test_app._pj_app = app if options: os.remove(config_path) return test_app def evaluate_filter(self, att_...
louyihua/edx-platform
lms/djangoapps/grades/tests/test_grades.py
Python
agpl-3.0
18,149
0.000937
""" Test grade calculation. """ import ddt from django.conf import settings from django.http import Http404 from django.test import TestCase from mock import patch, MagicMock from nose.plugins.attrib import attr from opaque_keys.edx.locations import SlashSeparatedCourseKey from opaque_keys.edx.locator import CourseLoc...
lf._gradesets_and_errors_for(self.course.id, self.students) student1, student2, student3, student4, student5 = self.students self.assertEqual( all_errors, { student3: "I don't like student3", student4: "I don't like student4" } ...
f.assertEqual(len(all_gradesets), 5) # Even though two will simply be empty self.assertFalse(all_gradesets[student3]) self.assertFalse(all_gradesets[student4]) # The rest will have grade information in them self.assertTrue(all_gradesets[student1]) self.assertTrue(all_gr...
jdavisp3/TigerShark
tigershark/parsers/M277U_4010_X070.py
Python
bsd-3-clause
49,720
0.052474
# # Generated by TigerShark.tools.convertPyX12 on 2012-07-10 16:29:58.682345 # from tigershark.X12.parse import Message, Loop, Segment, Composite, Element, Properties parsed_277U_HEADER = Loop( u'HEADER', Properties(looptype=u'wrapper',repeat=u'1',pos=u'015',req_sit=u'R',desc=u'Table 1 - Header'), Segment( u'BHT', Prop...
=u'R',repeat=u'1',pos=u'020',desc=u'Beginning of Hierarchical Transaction'), Element( u'BHT01', Properties(desc=u'Hierarchical Structure Code', req_sit=u'R', data_type=(u'ID',u'4',u'4'), position=1, codes=[u'0010'] ) ), Element( u'BHT02', Properties(desc=u'Transaction Set Purpose Code', req_s
it=u'R', data_type=(u'ID',u'2',u'2'), position=2, codes=[u'08'] ) ), Element( u'BHT03', Properties(desc=u'Reference Identification', req_sit=u'R', data_type=(u'AN',u'1',u'50'), position=3, codes=[] ) ), Element( u'BHT04', Properties(desc=u'Date', req_sit=u'R', data_type=(u'DT',u'8',u'8'), position=4, co...
tzpBingo/github-trending
codespace/python/telegram/poll.py
Python
mit
12,268
0.004239
#!/usr/bin/env python # pylint: disable=R0903 # # A library that provides a Python interface to the Telegram Bot API # Copyright (C) 2015-2022 # Leandro Toledo de Souza <devs@python-telegram-bot.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser Public L...
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 Lesser Public License for more details. # # You should have received
a copy of the GNU Lesser Public License # along with this program. If not, see [http://www.gnu.org/licenses/]. """This module contains an object that represents a Telegram Poll.""" import datetime import sys from typing import TYPE_CHECKING, Any, Dict, List, Optional, ClassVar from telegram import MessageEntity, Te...
apple/coremltools
coremltools/proto/Gazetteer_pb2.py
Python
bsd-3-clause
4,337
0.007148
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: Gazetteer.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _ref...
x00\x62\x06proto3') , dependencies=[DataStructures__pb2.DESCRIPTOR,], public_dependencies=[DataStructures__pb2.DESCRIPTOR,]) _GAZETTEER = _descriptor.Descriptor( name='Gazetteer', full_name='CoreML.Specification.CoreMLModels.Gazetteer', filename=None, file=DESCRIPTOR, containing_type=None, fields=...
13, cpp_type=3, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='language', full_name='CoreML.Specification.CoreMLModels.Gazetteer.lang...
kerel-fs/skylines
tests/data/users.py
Python
agpl-3.0
1,007
0
# -*- coding: utf-8 -*- """Setup the SkyLines application""" from faker import Faker from skylines.model import User def test_admin(): u = User() u.first_name = u'Example' u.last_name = u'Manager' u.email_address = u'manager@somedomain.com' u.password = u.original_password = u'managepass' u.a...
u1.original_password = u'test' u1.tracking_key = 123456 u1.tracking_delay = 2 return u1 def test_users(n=50): fake = Faker(locale='de_DE') fake.seed(42) users = [] for i in xrange(n): u = User() u.first_name =
fake.first_name() u.last_name = fake.last_name() u.email_address = fake.email() u.password = u.original_password = fake.password() u.tracking_key = fake.random_number(digits=6) users.append(u) return users
mobarski/sandbox
rsm/v9le/v5.py
Python
mit
8,419
0.049056
from common2 import * # NAME IDEA -> pooling/random/sparse/distributed hebbian/horde/crowd/fragment/sample memory # FEATURES: # + boost -- neurons with empty mem slots learn faster # + noise -- # + dropout -- temporal disabling of neurons # + decay -- remove from mem # + negatives -- learning to avoid detecting some...
neurons """ mem = self.mem tow = self.tow N = self.cfg['n'] M = self.cfg['m'] t = self.t scores = {} for j in mem: scores[j] = len(set(input) & mem[j]) if raw: return scores if noise: for j in mem: scores[j] += 0.9*random() if boost: for j in mem: scores[j] += 1+2*(...
len(mem[j])) if len(mem[j])<M else 0 # TODO boost also based on low win ratio / low tow if fatigue: for j in mem: dt = 1.0*min(fatigue,t - tow[j]) factor = dt / fatigue scores[j] *= factor if dropout: k = int(round(float(dropout)*N)) for j in combinations(N,k): scores[j] = -1 return sc...
firelab/viirs_ba
misc_utils/arcpy_functions.py
Python
cc0-1.0
4,645
0.010549
# This file contains the arcpy funcitons that export rasters and shape files # These were removed from the production script because they are not used. # I'm saving them here just in case.. # The function array2raster uses arcpy to output a raster from the VIIRS array. # This function DOES NOT handle the pixel size ...
"ActiveFire") # Output shapefile if ShapeOut == "y": print "Exporting to point shapefile:" if not os
.path.exists(ShapePath): os.makedirs(ShapePath) shp = ShapePath + '/' + 'fire_collection_point_' + datetime.datetime.now().strftime('%Y%m%d_%H%M%S') Pgsql2shpExe = os.path.join(PostBin, "pgsql2shp") query = '\"SELECT a.*, b.fid as col_id, b.active FROM fire_events a, fire_collect...
sqlalchemy/sqlalchemy
test/orm/test_scoping.py
Python
mit
7,276
0.000412
from unittest.mock import Mock import sqlalchemy as sa from sqlalchemy import ForeignKey from sqlalchemy import Integer from sqlalchemy import String from sqlalchemy import testing from sqlalchemy.orm import query from sqlalchemy.orm import relationship from sqlalchemy.orm import scoped_session from sqlalchemy.orm imp...
patch( "sqlalchemy.orm.session.object_session" ) as mock_object_session: sess.object_session("foo") eq_(mock_object_session.mock_calls, [mock.call("foo")]) @testing.combinations( "style1", "style2", "style3", "style4", ) def test_get_...
elf, style): """test #6285""" class MySession(Session): if style == "style1": def get_bind(self, mapper=None, **kwargs): return super().get_bind(mapper=mapper, **kwargs) elif style == "style2": # this was the workaround for #...
chiahaoliu/pdf_lib
pdf_lib/pdf_helper.py
Python
mit
3,994
0.017526
# helper functions import numpy as np import matplotlib.pyplot as plt import os import pandas as pd from diffpy.Structure import loadStructure from pyobjcryst.crystal import CreateCrystalFromC
IF from diffpy.srreal.bondcalculator import BondCalculator from diffpy.srreal.pdfcalculator import PDFCalculator from diffpy.srreal.pdfcalculator import DebyePDFCalculator #from pdf_lib.glbl import glbl from glbl import glbl def read_full_gr(f_name, rmin=glbl.r_min, rmax = glbl.r_max, skip_num=glbl.skip_row): '''...
to read .gr data generated from PDFgui''' read_in = np.loadtxt(str(f_name), skiprows = skip_num) raw_data = np.transpose(read_in) raw_data_list = raw_in.tolist() upper_ind = raw_list[0].index(rmax) lower_ind = raw_list[0].index(rmin) cut_data_list = np.asarray([raw_in[0][lower_ind:upper_ind], ...
savoirfairelinux/account-financial-tools
account_chart_update/wizard/wizard_chart_update.py
Python
agpl-3.0
67,528
0.001274
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (c) 2010 Zikzakmedia S.L. (http://www.zikzakmedia.com) # Copyright (c) 2010 Pexego Sistemas Informáticos S.L. (http://www.pexego.es) # @authors: Jordi Esteve (Zikzakmedia), Borja López Soilán (P...
tax codes, fiscal positions), " "the template name will be matched against the record name on this language." ), 'update_tax_code': fields.boolean( 'Update tax codes', help="Existing tax codes are updated." " Tax codes are searched by name." )...
help="Existing taxes are updated. Taxes are searched by name." ), 'update_account': fields.boolean( 'Update accounts', help="Existing accounts are updated. Accounts are searched by code." ), 'update_fiscal_position': fields.boolean( 'Update fiscal ...
guokr/asynx
asynx/asynx/__init__.py
Python
mit
194
0
from os imp
ort path from .taskqueue import TaskQueueClient __all__ = ['TaskQueueClient'] with open(path.join(path.dirname(__file__), 'version.txt'))
as fp: __version__ = fp.read().strip()
luofei98/qgis
python/plugins/processing/gui/ProcessingToolbox.py
Python
gpl-2.0
16,100
0.000683
# -*- coding: utf-8 -*- """ *************************************************************************** ProcessingToolbox.py --------------------- Date : August 2012 Copyright : (C) 2012 by Victor Olaya Email : volayaf at gmail dot com *********************...
if isinstance(item, TreeAlgorithmItem): alg = Processing.getAlgorithm(item.alg.comma
ndLineName()) message = alg.checkBeforeOpeningParametersDialog() if message: dlg = MissingDependencyDialog(message) dlg.exec_() return alg = alg.getCopy() dlg = alg.getCustomParametersDialog() if not dlg: ...
mcjlnrtwcz/Rekoder
rekoder.py
Python
mit
272
0
""" Execute this file to launch Rekoder. Refer to README.md for usage. """ # Rekoder m
odules from core.app import App if __name__ == '__main__': # Load configuration file and start application. app = App() app.load_json_config('config.json') app.start
()
riquito/fs-radar
tests/test_path_filter.py
Python
gpl-3.0
6,014
0
import pytest import unittest from fs_radar.path_filter import makePathFilter, makeDirFilter class MakePathFilterTest(unittest.TestCase): def test_empty_rules(self): f = makePathFilter([]) assert f('') is False assert f('foo.txt') is False def test_file_at_any_depth(self): ...
'a/b/' ]) assert f('a/bo') is False def test_just_asterisk(self): f = makePathFilter([ '*' ]) assert f('') is False assert f('foo.txt') assert f('a/b/') def test_start_with_asterisk(self): f = makeP
athFilter([ '*a', '*b/foo' ]) assert f('a') assert f('xyza') assert f('b') is False assert f('b/foo') assert f('xb/foo') def test_single_asterisk(self): f = makePathFilter([ 'a/*foo/a', 'b/bar*/b', ...
javierhuerta/unach-photo-server
tests/urls.py
Python
mit
296
0.003378
# -*-
coding: utf-8 from __future__ import unicode_literals, absolute_import from django.conf.urls import url, include from unach_photo_server.urls import urlpatterns as unach_photo_server_urls urlpatterns = [ url(r'^', include(unach_photo_server_urls, names
pace='unach_photo_server')), ]
xdevelsistemas/taiga-back-community
taiga/projects/attachments/__init__.py
Python
agpl-3.0
1,012
0
# -*- coding: utf-8 -*- # Copyright (C) 2014-2016 Andrey Antukh <niwi@niwi.nz> # Copyright (C) 2014-2016 Jesús Espino <jespinog@gmail.com> # Copyright (C) 2014-2016 David Barragán <bameda@dbarragan.com> # Copyright (C) 2014-2016 Alejandro Alonso <alejandro.alonso@kaleidos.net> # This program is free software: you can r...
# it under the terms of the GNU Affero General Public License as # published by the Free Sof
tware 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 Affero General Public Lic...
cea-hpc/shine
lib/Shine/Commands/Install.py
Python
gpl-2.0
4,458
0.001795
# Install.py -- File system installation commands # Copyright (C) 2007-2013 CEA # # This file is part of shine # # 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...
the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # from __future__ import print_function import sys from Shine.Configuration.Globals import Globals from Shine.FSUtils import create_lustrefs from Shine.Lustre.FileSystem import FSRemoteError from Shine.Commands.Base.Com...
ntHandler class Install(Command): """ shine install -m /path/to/model.lmf """ NAME = "install" DESCRIPTION = "Install a new file system." def execute(self): # Option sanity check self.forbidden(self.options.fsnames, "-f, see -m") self.forbidden(self.options.labels, "...
lfcnassif/MultiContentViewer
release/modules/ext/libreoffice/program/python-core-3.3.0/lib/email/iterators.py
Python
lgpl-3.0
2,205
0.002268
# Copyright (C) 2001-2006 Python Software Foundation # Author: Barry Warsaw # Contact: email-sig@python.org """Various types of useful iterators and generators.""" __all__ = [ 'body_line_iterator', 'typed_subpart_iterator', 'walk', # Do not include _structure() since it's part of the debugging API. ...
def _structure(msg, fp=None, level=0, includ
e_default=False): """A handy debugging aid""" if fp is None: fp = sys.stdout tab = ' ' * (level * 4) print(tab + msg.get_content_type(), end='', file=fp) if include_default: print(' [%s]' % msg.get_default_type(), file=fp) else: print(file=fp) if msg.is_multipart(): ...
aouerfelli/SuperDD-Python
res/Room.py
Python
mit
8,839
0.006788
from pygame import * from res import createImage, playSound class Room(): def __init__(self, levelSize, spritePath): self.level = Surface(levelSize) self.levelRect = self.level.get_rect() self.levelUnlocked = False self.levelCleared = False self.spike = crea...
self.bgFColor = 0x22373A self.bgBColor = 0x1B2821 self.tile = createImage("%sRegular/backdrop.png"%(spritePath)) self.startDoor = createImage("%sRegular/door_start.png"%(spritePath)) self.wallBlocks = { "top": createImage("%sRegular/border_top.png"...
tom": createImage("%sRegular/border_bottom.png"%(spritePath)), "left": createImage("%sRegular/border_left.png"%(spritePath)) } self.blockTypes = { "long": createImage("%sRegular/long_block.png"%(spritePath)), "short": createImage("%sRegular/short_block.png"%(spritePath...
tgquintela/pySpatialTools
pySpatialTools/utils/util_classes/__init__.py
Python
mit
266
0.007519
""" Ut
il classes ------------ Classes wh
ich represent data types useful for the package pySpatialTools. """ ## Spatial elements collectors from spatialelements import SpatialElementsCollection, Locations ## Membership relations from Membership import Membership
magnatronus/titanium-sac
titanium-sac.py
Python
mit
4,652
0.025795
# # ti-sac.py is a Titanium plug-in for Sublime Text 3 # # developed by Steve Rogers, SpiralArm Consulting Ltd (www.spiralarm.uk) # @sarmcon # # import sublime, sublime_plugin, os import Titanium.lib.tiutils as Ti # This will create a new Alloy Widget class sacAlloyWidgetCommand(sublime_plugin.WindowCommand): def ...
te project if os.path.exists(self.projectDir): sublime.error_message("Unable to create Titanium project, the directory already exists: %s " % self.projectDir) else: # Step 1 - Create Titanium skeleton project Ti.createClassicProject(projectName) # Step 2 - Now Create the sublime Project files Ti.co...
Ti.createSublimeProject(self.projectDir) # Step 3 Finally open the project (opens in a new sublime instance) os.system("open %s" % self.projectDir+".sublime-project") # Step 3a - possible add the project to the recent project list so it can be opened with Open Recent or Quick Project Switch #TODO:: # Th...
lablup/sorna-client
src/ai/backend/client/cli/admin/resource_policies.py
Python
lgpl-3.0
8,377
0.000716
import sys import click from tabulate import tabulate from . import admin from ...session import Session from ..pretty import print_error, print_fail @admin.command() @click.option('-n', '--name', type=str, default=None, help='Name of the resource policy.') def resource_policy(name): """ Show ...
um virtual folders allowed.') @click.option('--max-vfolder-size', type=int, default=0, help='Maximum virtual folder size (future plan).') @cli
ck.option('--idle-timeout', type=int, default=1800, help='The maximum period of time allowed for kernels to wait ' 'further requests.') # @click.option('--allowed-vfolder-hosts', type=click.Tuple(str), default=['local'], # help='Locations to create virtual folders.') @clic...
boedy1996/SPARC
geonode/geoserver/helpers.py
Python
gpl-3.0
54,697
0.000896
# -*- coding: utf-8 -*- ######################################################################### # # Copyright (C) 2012 OpenPlans # # 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 versio...
return None else: raise e if resource is None: # If there is no associated resource, # this method can not delete anything. # Let's return and make a note in the log. logger.deb
ug( 'cascading_delete was called with a non existent resource') return resource_name = resource.name ly
jmcnamara/XlsxWriter
xlsxwriter/test/comparison/test_chart_format23.py
Python
bsd-2-clause
1,541
0
############################################################################### # # Tests for XlsxWriter. # # SPDX-License-Identifier: BSD-2-Clause # Copyright (c), 2013-2022, John McNamara, jmcnamara@cpan.org # from ..excel_comparison_test import ExcelComparisonTest from ...workbook import Workbook class TestCompar...
d by Excel. """ def setUp(self): self.set_filename('chart_for
mat23.xlsx') def test_create_file(self): """Test the creation of an XlsxWriter file with chart formatting.""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() chart = workbook.add_chart({'type': 'column'}) chart.axis_ids = [108321024, 108328448]...
roshantha9/AbstractManycoreSim
src/libApplicationModel/SimpleBinaryTree.py
Python
gpl-3.0
2,226
0.014376
# simple binary tree # in this implementation, a node is inserted between an existing node and the root class BinaryTree(): def __init__(self,rootid): self.left = None self.right = None self.rootid = rootid def getLeftChild(self): return self.left def getRightChild(self):...
ree.e
ntry): if (tree.left != None): insert(item, tree.left) else: tree.left = Tree(item) else: if (tree.right != None): insert(item, tree.right) else: tree.right = Tree(item) ''' def printTree(tree): ...
mattliston/examples
example009.py
Python
mit
5,626
0.013686
# wget http://stuff.mit.edu/afs/sipb/contrib/pi/pi-billion.txt # THEANO_FLAGS=mode=FAST_RUN,device=gpu,floatX=float32 python example009.py from __future__ import division import numpy as np import theano import theano.tensor as T import lasagne as L import argparse import time from six.moves import cPickle np.set_print...
bjectives.categorical_crossentropy(prediction, target_var)
, mode='mean') params = L.layers.get_all_params(network, trainable=True) updates = L.updates.adam(loss, params, learning_rate=args.lr) scaled_grads,norm = L.updates.total_norm_constraint(T.grad(loss,params), np.inf, return_norm=True) train_fn = theano.function([input_var, target_var], [loss,norm], updates=updates) test...
jasonge27/picasso
python-package/doc/source/conf.py
Python
gpl-3.0
5,024
0.000796
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # pycasso documentation build configuration file, created by # sphinx-quickstart on Sun Sep 24 01:54:19 2017. # # 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 # au...
er', # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # # 'preamble': '', # Latex figure (float) alignment # # 'figu
re_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'pycasso.tex', 'pycasso Documentation', 'Haoming Jiang, Jian Ge', 'manual'), ] # -- Options f...
nis-sdn/odenos
apps/cli/producer.py
Python
apache-2.0
16,458
0.006744
# Copyright 2015 NEC 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 o...
urn self._generate_eport(cr_next) elif gen_type == 'link': return self._generate_link(cr_next) elif gen_type == 'slice': return self._generate_slice(cr_next) elif gen_type == 'slice_condition': if len(args) == 2: return self._generate_slice_con...
s) == 3: return self._generate_federation(cr_next, args[1], args[2]) else: raise Exception('Requires boundary_node and boundary_port') def _generate_node(self, cr_next): formatstr = self.formatstr if self.topo_type == 'fat_tree': CORE = To...
secret-transaction/RipOff9Gag
server/ripoff9gag/api.py
Python
apache-2.0
225
0.004444
import endpoints from api_user import UserAPI from api_posts import PostsAPI from api_comments import ReactionAPI from api_image import ImageA
PI APPLICATION = endpoints.api_server([PostsAPI, ReactionAPI, UserAPI, Ima
geAPI])
Jobava/zamboni
mkt/commonplace/views.py
Python
bsd-3-clause
6,014
0.000166
import json import os from urlparse import urlparse from django.conf import settings from django.core.files.storage import default_storage as storage from django.core.urlresolvers import resolve from django.http import Http404 from django.shortcuts import render from django.utils import translation from django.views.d...
75', 'https://localhost:8675', 'http://localhost', 'https://localhost', 'http://mp.dev', 'https://mp.dev', ]) if include_loop: # Include loop origins if necessary. allowed.extend([ 'https://hello.firefox.com', ...
'https://loop-webapp-dev.stage.mozaws.net', 'https://call.stage.mozaws.net', ]) return json.dumps(allowed) def get_build_id(repo): try: # Get the build ID from the database (bug 1083185). return DeployBuildId.objects.get(repo=repo).build_id except DeployBu...
sebastianffx/active_deep_segmentation
flickrsearch.py
Python
gpl-2.0
2,457
0.014652
""" Copyright (C) 2015 Sebastian Otalora This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the h...
the results imgs as dicts with ids, captions, urls and so forth for img_id in range(len(photos['photos']['photo'])): cur_img_id = photos['photos']['photo'][img_id] imgs_urls.append(cur_img_id['url_m']) #medium size #photoSizes = flickr.photos_getSizes(photo_id=cur_img_id['id']) #cur_img_...
ize'][0] contains the diferent sources of the img in diferent sizes: #{u'height': 75, # u'label': u'Square', # u'media': u'photo', # u'source': u'https://farm6.staticflickr.com/5836/22322409944_1498c04fb6_s.jpg', # u'url': u'https://www.flickr.com/photos/g20_turkey/22322409944/sizes/sq/', # u'wi...
addition-it-solutions/project-all
addons/account_budget/__openerp__.py
Python
agpl-3.0
3,013
0.003319
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
t greater/lower
than what he planned for this Budget. Each list of record can also be switched to a graphical view of it. Three reports are available: ---------------------------- 1. The first is available from a list of Budgets. It gives the spreading, for these Budgets, of the Analytic Accounts. 2. The second is...
tkwon/dj-stripe
djstripe/migrations/0021_auto_20170107_0813.py
Python
mit
865
0.001156
# -*- co
ding: utf-8 -*- # Generated by Django 1.10.5 on 2017-01-07 08:13 from __future__ import unicode_literals import django.core.validators from django.db import migrations import djstripe.fields class Migration(migrations.Migration): dependencies = [ ('djstripe', '0020_auto_20161229_0041'), ] opera...
ion_fee_percent', field=djstripe.fields.StripePercentField(decimal_places=2, help_text="A positive decimal that represents the fee percentage of the subscription invoice amount that will be transferred to the application owner's Stripe account each billing period.", max_digits=5, null=True, validators=[djan...
aayoubi/HNTwitter-bot
hnbot/test/test_hnbot.py
Python
gpl-3.0
306
0.022876
#!/usr/bin/env python # -*- coding: utf-8 -
*- import unittest import sys import os import hnbot class HnbotMessage(unittest.TestCase): def testTooLarge(s
elf): """test should fail if message size is bigger than 140 characters""" self.assertEqual(1,1) if __name__ == "__main__": unittest.main()
anilpai/leetcode
Codewars/BiggestSum.py
Python
mit
353
0.002833
''' Bigges
t Sum from Top left to Bottom Right ''' def find_sum(m): p = [0] * (len(m) + 1) for l in m: for i, v in enumerate(l, 1): p[i] = v + max(p[i-1], p[i]) return p[-1] matrix = [[20, 20, 10, 10], [10, 20, 10, 10], [10, 20
, 20, 20], [10, 10, 10, 20]] print(find_sum(matrix) == 140)
lrvick/kral
kral/services/twitter.py
Python
agpl-3.0
2,819
0.009933
# -*- coding: utf-8 -*- import base64 import time import simplejson as json from eventlet.green import urllib2 import urllib from kral import config def stream(queries, queue, kral_start_time): url = 'https://stream.twitter.com/1/statuses/filter.json' queries = [q.lower() for q in que
ries] quoted_queries = [urllib.quote(q) for q in quer
ies] query_post = 'track=' + ",".join(quoted_queries) request = urllib2.Request(url, query_post) auth = base64.b64encode('%s:%s' % (config.TWITTER['user'], config.TWITTER['password'])) request.add_header('Authorization', "basic %s" % auth) request.add_header('User-agent', config.USER_AGENT) ...
simonpessemesse/seguinus
chambres_chercheErreurDate.py
Python
gpl-2.0
361
0.01108
# coding: utf-8 import configureEnvironnement configureEnvironnement.setup() import django django.setup() from datetime import datetime, date, timedelta from chambres.models import Reservation, Client from chambres.views import OneDaySt
ats rs = Reservation.objects.all() for r in rs: if r.dateArrivee > r.dateDepart:
print(r, r.id, r.client.id)
opendatateam/udata
udata/commands/images.py
Python
agpl-3.0
2,037
0
import logging from collections import Counter from udata.commands import cli, header, success log = logging.getLogger(__name__) @cli.group('images') def grp(): '''Images related operations''' pass def render_or_skip(obj, attr): try: getattr(obj, attr).rerender() obj.save() re...
s: count['users'] += render_or_skip(user, 'avatar') posts = Post.objects(image__exists=True) total['posts'] = posts.count() log.info('P
rocessing {0} post images'.format(total['posts'])) for post in posts: count['posts'] += render_or_skip(post, 'image') reuses = Reuse.objects(image__exists=True) total['reuses'] = reuses.count() log.info('Processing {0} reuse images'.format(total['reuses'])) for reuse in reuses: coun...
daily-bruin/meow
meow/scheduler/migrations/0010_auto_20190716_1418.py
Python
agpl-3.0
382
0
# Generated by Django 2
.0.4 on 2019-07-16 21:18 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('scheduler', '0009_auto_2019
0607_1518'), ] operations = [ migrations.RenameField( model_name='smpost', old_name='post_instagram', new_name='post_newsletter', ), ]
lowRISC/opentitan
util/design/keccak_rc.py
Python
apache-2.0
1,923
0.00312
#!/usr/bin/env python3 # Copyright lowRISC contributors. # Licensed under the Apache License, Version 2.0, see LICENSE for details. # SPDX-License-Identifier: Apache-2.0 r"""Calculate Round Constant """ import argparse import bitarray as ba import logging as log def main(): parser = argparse.ArgumentParser( ...
e. Default is SHA3 Keccak round %(default)''') parser.add_argument('--verbose', '-v', action='store_true', help='Verbose') args = parser.parse_args() if (args.verbose): log.basicConfig(format="%(levelname)s: %(message)s", level=log.DEBUG) else: log.basicConfig(format="%(levelname)s: %(...
d be greater than 0") # Create 0..255 bit array rc = ba.bitarray(256) rc.setall(0) r = ba.bitarray('10000000') rc[0] = True # t%255 == 0 -> 1 for i in range(1, 256): # Update from t=1 to t=255 r_d = ba.bitarray('0') + r if r_d[8]: #Flip 0,4,5,6 ...
anhstudios/swganh
data/scripts/templates/object/tangible/ship/components/armor/shared_arm_mandal_enhanced_heavy_composite.py
Python
mit
514
0.042802
#### NOTICE
: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Tangible() result.template = "object/tangible/ship/components/armor/shared_arm_mandal_enhanced_heavy_composite.iff" result.a...
ICATIONS #### #### END MODIFICATIONS #### return result
avaitla/Haskell-to-C---Bridge
pygccxml-1.0.0/pygccxml/parser/directory_cache.py
Python
bsd-3-clause
18,986
0.003476
# Copyright 2004-2008 Roman Yakovenko. # Distributed under the Boost Software License, Version 1.0. (See # accompanying file LICENSE_1_0.txt or copy at # http://www.boost.org/LICENSE_1_0.txt) # # The initial version of the directory_cache_t class was written # by Matthias Baas (baas@ira.uka.de). """Directory c...
# Filename repository self.__filename_rep = filename_repository_t(self.__md5_sigs) # Index dictionary (Key is the value returned by _create_cache_key() # (which is based on the header file name) and value is an # index_entry_t object) self.__index = {} # Flag th...
flag = False # Check if dir refers to an existing file... if os.path.isfile(self.__dir): raise ValueError, "Cannot use %s as cache directory. There is already a file with that name."%self.__dir # Load the cache or create the cache directory... if os.path.isdir(self._...
PandaWei/avocado
avocado/utils/software_manager.py
Python
gpl-2.0
32,607
0.000123
#!/usr/bin/env python # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that ...
""" System inspector class. This may grow up to include more complete reports of
operating system and machine properties. """ def __init__(self): """ Probe system, and save information for future reference. """ self.distro = distro.detect().name def get_package_management(self): """ Determine the supported package management systems ...
stanleyz/pfsense-2.x-tools
pfsense-updateCRL.py
Python
gpl-2.0
2,863
0.008732
#!/usr/bin/env python import sys from pfsense_api import PfSenseAPI from datetime import datetime from pfsense_cmdline import PfSenseOptionParser from ConfigParser import ConfigParser from pfsense_logger import PfSenseLogger as logging import os.path parser = PfSenseOptionParser() parser.add_option("--id", dest="c...
emData = { 'id': parsed_options['crl_id'], 'act': 'editimported' }) api.logout() if rc == 302: logger.info('CRL Update successful for %s' % (section)) else: logger.info('CRL Update failed fo
r %s' % ( section))
chuckwired/ber-kit
setup.py
Python
gpl-3.0
1,036
0.007722
import multiprocessing from setuptools import setup, find_packages from ber_kit import __version__ setup(name='ber-kit', version= __version__, description='Toolkit to manage rolling upgrades on a Marathon cluster', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Deve...
License', 'Natural Language :: English', 'Topic :: System :: Systems Administration', ], keywords='marathon', url='http://bitbucket.org/connectedsolutions/ber-kit', author='Charles Rice, Cake Solutions', author_email='devops@cakesolutions.net', license='GNU GPLv3', packages=...
marathon>=0.8.6', ], entry_points = { 'console_scripts': [ 'ber-kit=ber_kit.main:main', ], }, test_suite='nose.collector', tests_require=[ 'nose', 'mock', 'coverage', ], zip_safe=False)
bitsanity/rateboard
moneroticker.py
Python
apache-2.0
2,777
0.022686
#!/usr/bin/python # -*- coding: utf-8 -*- import os import sys, traceback import threading import time import simplejson as json import urllib2 from PyQt4 import QtGui,QtCore from boardlet import Boardlet from modellet import Modellet class MoneroTicker(Boardlet): def __init__(self, parent, btcusd): super(Mon...
'ask: ' + "{:06.2f}".format(self.p_model.getBestAsk()) ) qp.setFont( self.p_timeFont ) qp.setPen
( self.p_grayPen ) qp.drawText( self.b_imgx(), self.b_row4y(), 'Refreshed: ' + self.p_model.getLastUpdated() ) qp.end() def periodicUpdate(self): while(True): st = self.getNextWaitTimeSeconds() time.sleep( st ) self.p_model.doRefresh() class Monero(Modellet): def __...
met-office-ocean/obsoper
benchmarks/bench_walk.py
Python
bsd-3-clause
551
0
"""Benchmark Walk algorithm""" import numpy as np import bench import obsoper.walk class BenchmarkWalk(bench.Suite): def setUp(self): longitudes, latitudes = np.meshgrid([1, 2, 3], [1, 2, 3], indexing="ij") sel...
self.fixture.detect((2.9, 2.9), i=0, j=0)
schleichdi2/OpenNfr_E2_Gui-6.0
lib/python/Components/SystemInfo.py
Python
gpl-2.0
3,888
0.010031
from boxbranding import getBoxType, getMachineProcModel, getMachineBuild from os import path from enigma import eDVBResourceManager, Misc_Options from Tools.Directories import fileExists, fileCheck from Tools.HardwareInfo import HardwareInfo SystemInfo = { } #FIXMEE... def getNumVideoDecoders(): idx = 0 while fi...
t in ('vuultimo', 'xpeedlx3', 'et10000', 'mutant2400', 'quadbox2400', 'atemionemesis') and fileExists("/dev/dbox/oled0") SystemInfo["DeepstandbySupport"] = HardwareInfo().has_deepstandby() SystemInfo["Fan"] = fileCheck("/proc/stb/fp/fan") SystemInfo["FanPWM"] = SystemInfo["Fan"] and fileCheck("/proc/stb/fp/fan_pwm") Sy...
power/standbyled") if getBoxType() in ('gbquad', 'gbquadplus','gb800ueplus', 'gb800seplus', 'gbipbox'): SystemInfo["WOL"] = False else: SystemInfo["WOL"] = fileCheck("/proc/stb/power/wol") or fileCheck("/proc/stb/fp/wol") SystemInfo["HDMICEC"] = (fileExists("/dev/hdmi_cec") or fileExists("/dev/misc/hdmi_cec0")) and f...
Loudr/pale
pale/fields/timestamp.py
Python
mit
189
0.005291
from pale.fields.string import StringFiel
d class TimestampField(StringField): """A field for timestamp st
rings.""" value_type = 'timestamp' # TODO - timestamp field rendering
jlongever/redfish-client-python
on_http_redfish_1_0/models/thermal_1_0_0_temperature.py
Python
apache-2.0
8,295
0.00217
# coding: utf-8 """ Copyright 2015 SmartBear Software 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...
al_context': 'Phy
sicalContext100PhysicalContext', 'related_item': 'list[Odata400IdRef]', 'related_itemodata_count': 'Odata400Count', 'related_itemodata_navigation_link': 'Odata400IdRef', 'status': 'ResourceStatus' } self.attribute_map = { 'member_id': 'MemberI...
cryptickp/heat
heat/engine/clients/os/keystone.py
Python
apache-2.0
5,676
0
# # 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 wr
iting, 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 keystoneclient import exceptions from h...
anhstudios/swganh
data/scripts/templates/object/static/naboo/shared_waterfall_naboo_falls_01.py
Python
mit
450
0.046667
#### NOTICE: THIS FILE IS AUTOGENERATED ##
## MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Static() result.template = "object/static/naboo/shared_wa
terfall_naboo_falls_01.iff" result.attribute_template_id = -1 result.stfName("obj_n","unknown_object") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
jart/tensorflow
tensorflow/contrib/autograph/core/errors.py
Python
apache-2.0
10,511
0.007326
# 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...
onstruction_error' not in f[3]: clea
ned_tb.append(f) return cleaned_tb def rewrite_graph_construction_error(source_map): """Rewrites errors raised by non-AG APIs inside AG generated code. Meant to be called from the try/except block inside each AutoGraph generated function. Only rewrites the traceback frames corresponding to the function th...
gem/sidd
utils/xml.py
Python
agpl-3.0
862
0.011601
# Copyright (c) 2011-2013, ImageCat Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is...
that it w
ill be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <...
kawamon/hue
desktop/core/ext-py/pyasn1-modules-0.2.6/tools/crldump.py
Python
apache-2.0
1,086
0.001842
#!/usr/bin/env python # # This file is part of pyasn1-modules software. # # Copyright (c) 2005-2019, Ilya Etingof <etingof@gmail.com> # License: http://snmplabs.com/pyasn1/license.html # # Read X.509 CRL on stdin, print them pretty and encode back into # original wire format. # CRL can be generated with "openssl opens...
"Usage: $ cat crl.pem | %s""" % sys.argv[0]) sys.exit(-1) asn1Spec = rfc2459.CertificateList() cnt = 0 while True: idx, substrate = pem.readPemBlocksFromFile(sys.stdin, ('-----BEGIN X509 CRL-----', '-----END X509 CRL-----')) if not substrate: break key, rest = decoder.decode(substrate, asn1S...
nt('*** %s CRL(s) re/serialized' % cnt)
linkcheck/linkchecker
linkcheck/htmlutil/__init__.py
Python
gpl-2.0
770
0
# Copyright (C) 2008-2014 Bastian Kleineidam # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distr...
n 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 Genera
l 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., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. """ HTML utils """
matk86/pymatgen
pymatgen/phonon/plotter.py
Python
mit
15,693
0.000828
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. from __future__ import division, unicode_literals, print_function import logging from collections import OrderedDict import numpy as np from monty.json import jsanitize from pymatgen.phonon.bandstructure impo...
the DOS for nicer looking plots. Defaults to None for no smearing. """ def __init__(self, stack=False, sigma=None): self.stack = stack self.sigma = sigma self._doses = OrderedDict() def add_dos(self, label, dos): """ Adds a dos for plotting. ...
label: label for the DOS. Must be unique. dos: PhononDos object """ densities = dos.get_smeared_densities(self.sigma) if self.sigma \ else dos.densities self._doses[label] = {'frequencies': dos.frequencies, 'densities': densitie...
aleontiev/django-cli
djay/blueprints/init/context.py
Python
mit
1,263
0.001584
import click import inflection import os def default(txt): return click.style(txt, fg="white", bold=True) def prompt(txt): return click.style(txt, fg="green") @click.command() @click.argument("name") @click.option("--description", prompt=prompt("Description"), default=default("N/A")) @click.option( "-...
me = click.unstyle(name) description = click.unstyle(description) email = click.unstyle(email) author = click.unstyle(author) version = click.unstyle(version) django_version = click.unstyle(django_version) return { "app": inflection.underscore(name), "description": description, ...
on": django_version, }
aronsky/home-assistant
tests/components/nut/util.py
Python
apache-2.0
1,446
0.002075
"""Tests for the nut integration.""" import json from unittest.mock import MagicMock, patch from homeassistant.components.nut.const import DOMAIN from homeassistant.const import CONF_HOST, CONF_PORT, CONF_RESOURCES from homeassistant.core import HomeAssistant from tests.common import MockConfigEntry, load_fixture ...
type(pynutclient).list_ups = MagicMock(return_value=list_ups) type(pynutclient).list_vars = MagicMock(return_valu
e=list_vars) return pynutclient async def async_init_integration( hass: HomeAssistant, ups_fixture: str, resources: list, add_options: bool = False ) -> MockConfigEntry: """Set up the nexia integration in Home Assistant.""" ups_fixture = f"nut/{ups_fixture}.json" list_vars = json.loads(load_fixtu...
Linhua-Sun/p4-phylogenetics
p4/STMcmc.py
Python
gpl-2.0
122,106
0.005135
# This is STMcmc, for super tree mcmc. # Started 18 March 2011, first commit 22 March 2011. import pf,func from Var import var import math,random,string,sys,time,copy,os,cPickle,types,glob import numpy as np from Glitch import Glitch from TreePartitions import TreePartitions from Constraints import Constraints from Tr...
sion (in log(result)) by at most 6.82e-13 for n up to 150, # over a wide range of beta (0.001 -- 1000) and cT (2 -- n/2) myLambda = cT/(2.0*n)
tester = 0.5 * math.log((n - 3.)/myLambda) epsilon = math.exp(-2. * beta) bigANEpsilon = 1 + (((2. * n) - 3.) * epsilon) + (2. * ((n * n) - (4. * n) - 6.) * epsilon * epsilon) termA = math.log(bigANEpsilon + 6 * cT * epsilon * epsilon) if beta < tester: termB = -(2. * beta) * (n - 3.) + (myLam...
toefl/pyotp
src/pyotp/hotp.py
Python
mit
1,325
0.000755
from pyotp.otp import OTP from pyotp import utils class HOTP(OTP): def at(self, count): """ Generates the OTP for the given count @param [Integer] count counter @returns [Integer] OTP """ return self.generate_otp(count) def verify(self, otp, counte...
initial_count starting counter value, defaults to 0
@param [String] the name of the OTP issuer; this will be the organization title of the OTP entry in Authenticator @return [String] provisioning uri """ return utils.build_uri( self.secret, name, initial_count=initial_count, ...
kraziegent/mysql-5.6
xtrabackup/test/kewpie/lib/server_mgmt/drizzled.py
Python
gpl-2.0
9,584
0.019825
#! /usr/bin/env python # -*- mode: python; indent-tabs-mode: nil; -*- # vim:expandtab:shiftwidth=2:tabstop=2:smarttab: # # Copyright (C) 2010,2011 Patrick Crews # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Soft...
# MySQL has a limitation of 107 characters for socket file path # we copy the mtr workaround of creating one in /tmp self.logging.verbose("Default socket file path: %s" %(self.socket_file)) self.socket_file = "/tmp/%s_%s.%s.sock" %(self.system_manager.uuid ...
f.name) self.logging.verbose("Changing to alternate: %s" %(self.socket_file)) self.timer_file = os.path.join(self.logdir,('timer')) # Do magic to create a config file for use with the slave # plugin self.slave_config_file = os.path.join(self.logdir,'slave.cnf') self....
sahiljain/catapult
dashboard/dashboard/services/issue_tracker_service.py
Python
bsd-3-clause
8,780
0.005353
# Copyright 2015 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. """Provides a layer of abstraction for the issue tracker API.""" import json import logging from apiclient import discovery from apiclient import errors _...
list, False otherwise. Returns: True if successful posted a comment or issue was deleted. False if making a comment failed unexpectedly. """ request = self._service.issues().comments().insert(
projectId='chromium', issueId=bug_id, sendEmail=send_email, body=body) try: if self._ExecuteRequest(request, ignore_error=False): return True except errors.HttpError as e: reason = _GetErrorReason(e) # Retry without owner if we cannot set owner to this issue....
CharLLCH/jianchi_alimobileR
ftrldata/TCReBuild/codes/mylibs/size.py
Python
gpl-2.0
65
0
item_id = 4986168 user_id =
20000 item_category =
9656 time = 31
Princeton-CDH/winthrop-django
winthrop/books/migrations/0004_unique_together_sort.py
Python
apache-2.0
1,351
0
# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2016-12-29 19:01 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('books', '0003_initial_subjects_languages_creatortypes'), ] operations = [ migration...
'name']}, ), migrations.AlterModelOptions( name='publisher', options={'ordering': ['name']}, ), migrations.AlterModelOptions( name='subject', options={'ordering': ['name']}, ), migrations.AlterUniqueTogether( nam...
r( name='booksubject', unique_together=set([('subject', 'book')]), ), ]
saddingtonbaynes/rez
src/rezplugins/shell/sh.py
Python
gpl-3.0
4,324
0.00185
""" SH shell """ import os import os.path import pipes import subprocess from rez.config import config from rez.utils.platform_ import platform_ from rez.shells import Shell, UnixShell from rez.rex import EscapedString class SH(UnixShell): norc_arg = '--noprofile' histfile = "~/.bash_history" histvar = "H...
is not None: cls._overruled_option('stdin', 'command', stdin) stdin = False return (rcf
ile, norc, stdin, command) @classmethod def get_startup_sequence(cls, rcfile, norc, stdin, command): _, norc, stdin, command = \ cls.startup_capabilities(rcfile, norc, stdin, command) envvar = None files = [] if not ((command is not None) or stdin): if ...
YeEmrick/learning
stanford-tensorflow/2017/assignments/exercises/e01_sol.py
Python
apache-2.0
4,765
0.004827
""" Solution to simple TensorFlow exercises For the problems """ import tensorflow as tf ############################################################################### # 1a: Create two random 0-d tensors x and y of any distribution. # Create a TensorFlow object that returns x + y if x > y, and x - y otherwise. # Hin...
######################## x = tf.constant([29.05088806, 27.61298943, 31.19073486, 29.35532951, 30.97266006, 26.67541885, 38.08450317, 20.74983215, 34.94445419, 34.45999146, 29.06485367, 36.01657104, 27.88236427, 20.56035233, 30.20379066, 29.51215172, 33.71149445, 28....
##################################################################### # 1e: Create a diagnoal 2-d tensor of size 6 x 6 with the diagonal values of 1, # 2, ..., 6 # Hint: Use tf.range() and tf.diag(). ############################################################################### values = tf.range(1, 7) out = tf.diag(v...
numpy/numpy
numpy/core/tests/test_ufunc.py
Python
bsd-3-clause
105,354
0.000816
import warnings import itertools import sys import pytest import numpy as np import numpy.core._umath_tests as umt import numpy.linalg._umath_linalg as uml import numpy.core._operand_flag_tests as opflag_tests import numpy.core._rational_tests as _rational_tests from numpy.testing import ( assert_, assert_equal, ...
s(TypeError, np.add, 1,
2, sigx='ii->i') assert_raises(TypeError, np.add, 1, 2, signaturex='ii->i') assert_raises(TypeError, np.add, 1, 2, subokx=False) assert_raises(TypeError, np.add, 1, 2, wherex=[True]) def test_sig_signature(self): assert_raises(TypeError, np.add, 1, 2, sig='ii->i', ...