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
AunShiLord/sympy
sympy/logic/boolalg.py
Python
bsd-3-clause
49,069
0.000346
""" Boolean algebra module for SymPy """ from __future__ import print_function, division from collections import defaultdict from itertools import combinations, product from sympy.core.basic import Basic from sympy.core.cache import cacheit from sympy.core.core import C from sympy.core.numbers import Number from symp...
lean values to True or False using ==. # Yes: if greeting: # No: if greeting == True: # Worse: if greeting is True: class BooleanAtom(Boolean): """ Base class of BooleanTrue and BooleanFalse. """ @property
def canonical(self): return self class BooleanTrue(with_metaclass(Singleton, BooleanAtom)): """ SymPy version of True, a singleton that can be accessed via S.true. This is the SymPy version of True, for use in the logic module. The primary advantage of using true instead of True is that short...
eunchong/build
scripts/slave/recipe_modules/auto_bisect/config_validation.py
Python
bsd-3-clause
3,647
0.007952
# Copyright 2016 The Chromium Au
thors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import re # Note: this module is tested by a unit test config_validation_test.py, # rather than recipe simulation tests. _BISECT_CONFIG_SCHEMA = { 'command': {'type': 'string', 'requi...
ion', 'required': True}, 'bisect_bot': {'type': 'string'}, 'metric': {'type': 'string'}, 'bug_id': {'type': 'integer'}, 'repeat_count': {'type': 'integer'}, 'max_time_minutes': {'type': 'integer'}, 'bisect_mode': {'type': 'string', 'choices': ['mean', 'return_code', 'std_dev'...
LyzardKing/ubuntu-make
umake/frameworks/dart.py
Python
gpl-3.0
5,057
0.002768
# -*- coding: utf-8 -*- # Copyright (C) 2014 Canonical # # Authors: # Didier Roche # # 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 3. # # This program is distributed in the hope that ...
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # detail
s. # # 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 """Dartlang module""" from contextlib import suppress from gettext import gettext as _ import logging i...
niksoc/srmconnect
app/migrations/0018_auto_20160822_1047.py
Python
gpl-3.0
4,536
0
# -*- coding: utf-8 -*- # Generated by Django 1.10 on 2016-08-22 10:47 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('app', '0017_auto_20160821_1833'), ] operations = [ migrations.AlterField( ...
le', name='created', field=models.DateTimeField(auto_now_add=True), ), migrations.AlterField( model_name='comment_available', name='modified', field=models.D
ateTimeField(blank=True), ), migrations.AlterField( model_name='comment_event', name='created', field=models.DateTimeField(auto_now_add=True), ), migrations.AlterField( model_name='comment_event', name='modified', fi...
ProfessorX/Config
.PyCharm30/system/python_stubs/-1247971765/PyKDE4/kio/KUrlComboBox.py
Python
gpl-2.0
1,586
0.010719
# encoding: utf-8 # module PyKDE4.kio # from /usr/lib/python3/dist-packages/PyKDE4/kio.cpython-34m-x86_64-linux-gnu.so # by generator 1.135 # no doc # imports import PyKDE4.kdeui as __PyKDE4_kdeui import PyQt4.QtCore as __PyQt4_QtCore import PyQt4.QtGui as __PyQt4_QtGui class KUrl
ComboBox(__PyKDE4_kdeui.KComboBox): # no doc def addDefaultUrl(self, *args, **kwargs): # real signatu
re unknown pass def maxItems(self, *args, **kwargs): # real signature unknown pass def mouseMoveEvent(self, *args, **kwargs): # real signature unknown pass def mousePressEvent(self, *args, **kwargs): # real signature unknown pass def removeUrl(self, *args, **kwargs): ...
jvkersch/hsmmlearn
hsmmlearn/tests/test_hsmm_wrappers.py
Python
gpl-3.0
1,757
0
import unittest import numpy as np from ..emissions import GaussianEmissions, MultinomialEmissions from ..hsmm import GaussianHSMM, MultinomialHSMM class TestHSMMWrappers(unittest.TestCase): def setUp(self): # Exact values don't matter self.tmat = np.eye(3) self.durations = np.eye(3) ...
ans = np.array([1.0, 2.0, 3.0]) scales = np.array([0.5, 0.4, 0.3]) hsmm = GaussianHSMM(means, scales, self.durations, self.tmat) # Test property getters np.testing.assert_array_equal(hsmm.means, means) np.testing.assert_array_equal(hsmm.scales, scales) # Now updat
e properties and check that the value changed on the # emissions. new_means = np.array([5.0, 5.0, 5.0]) new_scales = np.array([1.0, 1.0, 1.0]) hsmm.means = new_means hsmm.scales = new_scales emissions = hsmm.emissions np.testing.assert_array_equal(emissions.mean...
LLNL/spack
var/spack/repos/builtin/packages/r-prodlim/package.py
Python
lgpl-2.1
1,415
0.003534
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class RProdlim(RPackage): """Product-Limit Estimation for Censored Event History Analysis P...
256='4b22b54fdf712439309be0ff74f63cde9080464667b00e19823372ac0fc254ab') version('1.6.1', sha256='3f2665257118a3db8682731a500b1ae4d669af344672dc2037f987bee3cca154') versio
n('1.5.9', sha256='853644886c57102e7f6dd26b6e03e54bf3f9e126f54c76f8d63a3324811f7b42') depends_on('r@2.9.0:', type=('build', 'run')) depends_on('r-rcpp@0.11.5:', type=('build', 'run')) depends_on('r-survival', type=('build', 'run')) depends_on('r-kernsmooth', type=('build', 'run')) depends_on('r-lav...
YuxuanLing/trunk
trunk/code/study/python/Fluent-Python-example-code/09-pythonic-obj/vector2d_v3_slots.py
Python
gpl-3.0
3,560
0.000281
""" A 2-dimensional vector class >>> v1 = Vector2d(3, 4) >>> print(v1.x, v1.y) 3.0 4.0 >>> x, y = v1 >>> x, y (3.0, 4.0) >>> v1 Vector2d(3.0, 4.0) >>> v1_clone = eval(repr(v1)) >>> v1 == v1_clone True >>> print(v1) (3.0, 4.0) >>> octets = bytes(v1...
me = type(self).__name__ return '{}({!r}, {!r})'.format(class_name, *self) def __str__(self): return str(tuple(self)) def __bytes__(self): return (bytes([ord(self.typecode)]) + bytes(array(self.typecode, self))) def __eq__(self, other): return tu...
^ hash(self.y) def __abs__(self): return math.hypot(self.x, self.y) def __bool__(self): return bool(abs(self)) def angle(self): return math.atan2(self.y, self.x) def __format__(self, fmt_spec=''): if fmt_spec.endswith('p'): fmt_spec = fmt_spe...
plugaai/pytrthree
tools/request_sender.py
Python
mit
2,685
0.003724
#!/usr/bin/env python import argparse import datetime import pandas as pd import yaml from pytrthree import TRTH from pytrthree.utils import retry def make_request(daterange, criteria): request = api.factory.LargeRequestSpec(**template) short_dates = sorted([x.replace('-', '') for x in daterange.values()]) ...
nge'] = daterange if 'fields' in criteria: request['messageTypeList']['messageType'][0]['fieldList']['string'] = criteria['fields'] return request def parse_daterange(s): return dict(start=str(s.iloc[0].date()), end=str(s.iloc[-1].date())) if __name__ == '__main__': parser = argparse.Argumen...
parser.add_argument('--config', action='store', type=argparse.FileType('r'), required=True, help='TRTH API configuration (YAML file)') parser.add_argument('--template', action='store', type=argparse.FileType('r'), required=True, help='Base template for the request...
mitsuhiko/zine
zine/docs/builder.py
Python
bsd-3-clause
2,947
0.001018
# -*- coding: utf-8 -*- """ zine.docs.builder ~~~~~~~~~~~~~~~~~~~~~~ The documentation building system. This is only used by the documentation building script. :copyright: (c) 2010 by the Zine Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ import re impor...
content, lineno, content_offset, block_text, state, state_machine): return [nodes.comment('', 'PLUGIN_LINKS')] plugin_links_directive.arguments = (0, 0, 0) plugin_links_directive.content = 1 directives.register_directi
ve('plugin_links', plugin_links_directive) def is_relative_uri(uri): if uri.startswith('/'): return False # there is no uri parser, but the url parser works mostly return not urlparse(uri)[0] class Translator(html4css1.HTMLTranslator): pass class DocumentationWriter(html4css1.Writer): ...
leylabmpi/pyTecanFluent
tests/test_Utils.py
Python
mit
1,127
0.022183
#!/usr/bin/env python # -*- coding: utf-8 -*- # import ## batteries import os import sys import pytest ## 3rd party import pandas as pd ## package from pyTecanFluent import Utils # data dir test_dir = os.path.join(os.path.dirname(__file__)) data_dir = os.path.join(test_dir, 'data') # tests def test_make_range(): ...
_index=True) x = Utils.make_range('1,2,5', set_zero_index=True) assert x == [0,1,4] x = Utils.make_range('1,2,5
-6', set_zero_index=True) assert x == [0,1,4,5] def test_check_gwl(): gwl_file = os.path.join(data_dir, 'multi_dispense.gwl') ret = Utils.check_gwl(gwl_file) assert ret is None
mudbungie/carrieocoyle
gallery/migrations/0006_auto_20151027_1101.py
Python
mit
404
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration):
dependencies = [ ('gallery', '0005_piece_medium'), ] operations = [ migrations.AlterField( model_name='medium', name='medium_name',
field=models.TextField(default='Medium'), ), ]
johannfaouzi/pyts
pyts/datasets/uea.py
Python
bsd-3-clause
9,597
0
""" Utility functions for the UEA multivariate time series classification archive. """ # Author: Johann Faouzi <johann.faouzi@gmail.com> # License: BSD-3-Clause import numpy as np import os import pickle from scipy.io.arff import loadarff from sklearn.utils import Bunch from urllib.request import urlretrieve import z...
) if data_home is None: import pyts home = '/'.join(pyts.__file__.split('/')[:-2]) + '/' relative_path = 'pyts/datasets/cached_datasets/UEA/' path = home + relative_path else: path = data_home if not os.path.exists(path): os.makedirs(path) correct_d...
et = _correct_uea_name_download(dataset) if use_cache and os.path.exists(path + correct_dataset): bunch = _load_uea_dataset(correct_dataset, path) else: url = ("http://www.timeseriesclassification.com/Downloads/{0}.zip" .format(correct_dataset)) filename = 'temp_{}'.format...
frappe/frappe
frappe/patches/v10_0/refactor_social_login_keys.py
Python
mit
4,935
0.024924
import frappe from frappe.utils import cstr def execute(): # Update Social Logins in User run_patch() # Create Social Login Key(s) from Social Login Keys frappe.reload_doc("integrations", "doctype", "social_login_key", force=True) if not frappe.db.exists('DocType', 'Social Login Keys'): return social_login_...
ient_secret") if not (github_login_key.client_secret and github_login_key.client_id): github_login_key.enable_social_login = 0 github_login_key.save() if social_login_keys.get("google_client_id") or social_login_keys.get("google_client_secret"): google_login_key = frappe.new_doc("Social Login Key") google_...
_login_keys.get("google_client_id") google_login_key.client_secret = social_login_keys.get("google_client_secret") if not (google_login_key.client_secret and google_login_key.client_id): google_login_key.enable_social_login = 0 google_login_key.save() frappe.delete_doc("DocType", "Social Login Keys") def ru...
CxAalto/gtfspy
gtfspy/spreading/heap.py
Python
mit
2,529
0.001977
from heapq import heappush, heappop import numpy as np from gtfspy.route_types import WALK from .event import Event class EventHeap: """ EventHeap represents a container for the event heap to run time-dependent Dijkstra for public transport routing objects. """ def __init__(self, pd_df=None): ...
tart_time_ut+max_duration_ut: continue te = Event(transfer_arr_time, e.arr_time_ut, e.to_stop_I, transfe
r_to_stop_I, WALK) self.add_event(te)
OpenNetworkingFoundation/PIF-Open-Intermediate-Representation
pif_ir/meta_ir/validate.py
Python
apache-2.0
4,103
0.006581
""" @file @brief Validator for MetaIR Does semantic validation of the MetaIR instance """ from common import * def meta_ir_validate_parser(instance): """ @brief Semantic validation of an MetaIR instance @param instance The MetaIR instance map @returns Boolean, True if instance is valid. The inst...
n of an MetaIR instance @param instance The MetaIR in
stance map @returns Boolean, True if instance is valid. The instance is assumed to be a syntactically valid instance. This routine calls the object specific validators: parser tables The Parser: Each edge connects two declared states In so doing, the validator gene...
alvason/probability-insighter
code/mutation-drift-selection.py
Python
gpl-2.0
11,460
0.006457
# -*- coding: utf-8 -*- # <nbformat>3.0</nbformat> # <headingcell level=1> # Wright-Fisher model of mutation, selection and random genetic drift # <markdowncell> # A Wright-Fisher model has a fixed population size *N* and discrete non-overlapping generations. Each generation, each individual has a random number of ...
hts = [x / total for x in weights] return list(np.random.multinomial(pop_size, weights)) # <codecell> get_offspring_counts() # <codecell> def offspring_step(): counts = get_offspring_counts() for (haplotype, count) in zip(pop.keys(), counts): if (count > 0): pop[haplotype] = count ...
eadingcell level=3> # Combine and iterate # <codecell> def time_step(): mutation_step() offspring_step() # <codecell> generations = 5 # <codecell> def simulate(): for i in range(generations): time_step() # <headingcell level=3> # Record # <markdowncell> # We want to keep a record of past ...
colobas/gerador-horarios
bs4/builder/_html5lib.py
Python
mit
6,730
0.027637
__all__ = [ 'HTML5TreeBuilder', ] import warnings from bs4.builder import ( PERMISSIVE, HTML, HTML_5, HTMLTreeBuilder, ) from bs4.element import NamespacedAttribute import html5lib from html5lib.constants import namespaces from bs4.element import ( Comment, Doctype, NavigableString, Tag, ) class HTML5Tree...
, namespaces["html"])) else: newParent.appendChild( TextNode(child, self.soup)) def cloneNode(self): tag = self.soup.new_tag(self.element.name, self.namespace) node = Element(tag, self.soup, self.namespa
ce) for key,value in self.attributes: node.attributes[key] = value return node def hasContent(self): return self.element.contents def getNameTuple(self): if self.namespace == None: return namespaces["html"], self.name else: return self.namespace, self.name nameTuple = property(getNameTuple) cl...
erickeller/edi
tests/lib/test_playbookrunner.py
Python
lgpl-3.0
2,684
0.000373
# -*- coding: utf-8 -*- # Copyright (C) 2016 Matthias Luescher # # Authors: # Matthias Luescher # # This file is part of edi. # # edi is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of...
in_file: parser = ConfigurationParser(main_file) runner = PlaybookRunner(parser, "fake-container", "lxd") playbooks = runner.run_all() expected_playbooks = ['10_base_system', '20_networking', '30_foo'] assert playbooks == expected_playbook
s
RemuTeam/Remu
project/tests/GUI/PopUps/test_remove_presentations_pop_up.py
Python
mit
1,094
0.002742
import unittest from GUI.PopUps.RemovePresentationsPopUp import RemovePresentationsPopUp class TestBindPresentat
ionToSlavePopup(unittest.TestCase): def setUp(self): self.presentations = ["Slave1", "Slave2"] self.remove_popup = RemovePresentationsPopUp(self.presentations, None) def test_init_setups_properly(self): self.assertEquals(len(self.remove_popup.selected_presentations), 0) self.as...
elf.assertEqual(len(self.remove_popup.ids.presentation_list.children), 2) def test_selected_presentations_is_empty_at_first(self): self.assertEqual(len(self.remove_popup.selected_presentations), 0) # # def test_checkbox_selects(self): # self.bind_popup.on_checkbox_active(self.bind_popup.ch...
undefinedv/Jingubang
sqlmap/lib/utils/crawler.py
Python
gpl-3.0
8,802
0.002272
#!/usr/bin/env python """ Copyright (c) 2006-2016 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ import httplib import os import re import urlparse import tempfile import time from lib.core.common import clearConsoleLine from lib.core.common import dataToStdout from lib....
_ = red
uce(lambda x, y: x == y, map(lambda x: urlparse.urlparse(x).netloc.split(':')[0], (url, target))) if conf.scope: if not re.search(conf.scope, url, re.I): continue elif not _: ...
anhaidgroup/py_entitymatching
py_entitymatching/dask/dask_black_box_blocker.py
Python
bsd-3-clause
22,385
0.00344
from collections import OrderedDict import logging import time import sys import pandas as pd import numpy as np import pyprind import dask from dask import delayed from dask.diagnostics import ProgressBar import cloudpickle as cp import pickle from py_entitymatching.blocker.blocker import Blocker import py_entitym...
er.warning( "WARNING THIS BLOCKER IS EXPERIMENTAL AND NOT TESTED. USE AT
YOUR OWN " "RISK.") super(Blocker, self).__init__(*args, **kwargs) self.black_box_function = None def set_black_box_function(self, function): """Sets black box function to be used for blocking. Args: function (function): the black box function to be...
ppizarror/korektor
bin/easyprocess/examples/log.py
Python
gpl-2.0
447
0
from easyprocess import EasyPro
cess # @UnresolvedImport import logging # turn on logging logging.basicConfig(level=logging.DEBUG) EasyProcess('python --version').call() EasyProcess('ping localhost').start().sleep(1).stop() EasyProcess('python --version').check() try: EasyProcess('bad_command').check() except Exception, detail: print detai
l try: EasyProcess('sh -c bad_command').check() except Exception, detail: print detail
SnowOnion/ero
acfunh.py
Python
mit
353
0.002882
#!/usr/bin/python2 #coding=utf8 import httplib import urllib im
port urllib2 import json req = urllib2.Request('http://h.acfun.tv/综合版1.json') res = urllib2.urlopen(req) json_str = res.read() json_dic = json.loads(json_str) print json.dumps(json_dic, indent=4, encoding='utf-8') # print json.dumps(json_dic['data']['replys']
.items()[0], indent=4)
klavinslab/coral
tests/tests/test_design/test_gibson.py
Python
mit
2,083
0
'''Test gibson design module.''' from nose.tools import assert_equal, assert_raises from coral import design, DNA, Primer def test_gibson_primers(): '''Test gibson_primers function.''' # Fuse tdh3 promoter sequence to yfp (trimmed for readability) tdh3_3prime = DNA('aaccagttccctgaaattattcccctacttgactaataa...
rev = DNA('CCTTGCTCACCAT') # Design primers - with homology all on left side, right side, or mixed # All on the 'right' - i.e. fwd primer right = design.gibson_primers(tdh3_3prime, yfp_nterm, 'right') right_rev = Primer(rev_anneal, tm=rev_tm, overhang=all_right) right_fwd = Primer(fwd_anneal, tm=fwd...
ert_equal(right, (right_rev, right_fwd)) # All on the 'left' - i.e. rev primer left = design.gibson_primers(tdh3_3prime, yfp_nterm, 'left') left_rev = Primer(rev_anneal, tm=rev_tm) left_fwd = Primer(fwd_anneal, tm=fwd_tm, overhang=all_left) assert_equal(left, (left_rev, left_fwd)) # On both prim...
aewallin/allantools
tests/functional_tests/test_noise.py
Python
lgpl-3.0
556
0.01259
#!/usr/bin/python import sys sys.path.append("..") from allantools import noise import numpy import pytest def test_noise(): N = 500 #rate = 1.0 w = noise.white(N) b = noise.brown(N) v = noise.violet(N) p = noise.pink(N) # check output length assert len(w) == N assert len(b...
== N # check output type for x in [w, b, v, p]: assert type(x)
== numpy.ndarray, "%s is not numpy.ndarray" % (type(x)) if __name__ == "__main__": test_noise()
Hastu/educ_plateform
educ/authentification/admin.py
Python
mit
152
0.006579
from django.contrib import admin from forum.models import * admin.site.reg
ister(Student) admi
n.site.register(Professor) admin.site.register(Classroom)
Tackitt/flask-apispec
examples/petstore.py
Python
mit
2,262
0.007515
# -*- coding: utf-8 -*- import six import marshmallow as ma from flask_apispec import ResourceMeta, Ref, doc, marshal_with, use_kwargs class Pet: def __init__(self, name, type): self.name = name self.type = type class PetSchema(ma.Schema): name = ma.fields.Str() type = ma.fields.Str() c...
ith_metaclass(ResourceMeta)): schema = None @marshal_with(Ref('schema'), code=200) def get(self, id): pass
@marshal_with(Ref('schema'), code=200) @marshal_with(Ref('schema'), code=201) def post(self): pass @marshal_with(Ref('schema'), code=200) def put(self, id): pass @marshal_with(None, code=204) def delete(self, id): pass class PetResource(CrudResource): schema = P...
yebrahim/pydatalab
datalab/utils/_gcp_job.py
Python
apache-2.0
1,521
0.006575
# Copyright 2016 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except # in compliance with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed ...
context = datalab.context.Context.default() self._context = context self._api = self._create_api(context) def _create_api(self, context): raise Exception('_create_api must be defined in a derived class') def __repr__(self): """Returns a representation for the job for showing in the notebook....
(self._context.project_id, self._job_id, self.state)
jfrancis71/TensorFlowApps
CZFaceDetection.py
Python
mit
9,947
0.036594
# # The weights for this model come from training in a neural network library called CognitoNet which is now retired. # # That training session used images from the Face Scrub data set: # http: http://vintage.winklerbros.net/facescrub.html # H.-W. Ng, S. Winkler. # A data-driven approach to cleaning large fac...
) image = pilImage.resize( ( int(width), int(height) ) ) objs = CZSingleScaleDetectObjects( image, tfGraph, threshold ) scale = pilImage.width / image.width for obj in objs: objRet.append( ( obj[0], ( scale*(16 + obj[1]
-16), scale*(16 + obj[2]-16) ), ( scale*(16 + obj[1]+16), scale*(16 + obj[2]+16) ) ) ) return objRet def CZIntersection( a, b ): xa=max(a[0][0],b[0][0]) ya=max(a[0][1],b[0][1]) xb=min(a[1][0],b[1][0]) yb=min(a[1][1],b[1][1]), if ( xa>xb or ya>yb ): ans = 0 else: ans = (xb-x...
michielkauwatjoe/Meta
meta/rgb.py
Python
mit
524
0.009542
#!/usr/bin/env python3 ''' bm = sd.Bitmap(Width,Height) for x in xrange(Height*Width): j= x // Width i= x % Width col = Color[x] bm.SetPixel(i,j,col) bm.Save(PathWrite,sd.Imaging.ImageFormat.Bmp) ''' from PIL import Image w = h = 255 img = Image.new( 'RGB', (w, h), "black") # Create a new black image...
load() # Create the pixel map for i in range(img.size[0]): # For every pixel:
for j in range(img.size[1]): pixels[i,j] = (i, j, 100) # Set the colour accordingly img.show()
rx2130/Leetcode
python/7 Reverse Integer.py
Python
apache-2.0
710
0.002817
class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ # Op1: isNegative = False if x < 0: isNegative = True x *= -1 x = int(str(x)[::-1]) if isNegative: x *= -1 return x if ab...
sign = -1 x *= -1 num = 0 while x: if abs(num) > 214748364: return 0 num = num * 10 + x % 10
x //= 10 return num * sign test = Solution() print(test.reverse(1000000003)) print(test.reverse2(-1000000003))
mathemage/h2o-3
h2o-py/h2o/expr.py
Python
apache-2.0
15,701
0.004204
# -*- encoding: utf-8 -*- """ Rapids expressions. These are helper classes for H2OFrame. :copyright: (c) 2016 H2O.ai :license: Apache License Version 2.0 (see LICENSE for details) """ from __future__ import division, print_function, absolute_import, unicode_literals import collections import copy import gc import m...
tion on the evaluated object. Examples might be: lazy # dataset time parse vs changing the global timezone. Global timezone change # is eager, so the time parse as to occur in the correct order relative to # the timezone change, so cannot be lazy. # def _get_ast_str(self, top): if not self...
return str(self._cache._data) if self._cache.is_scalar() else self._cache._id if self._cache._id is not None: return self._cache._id # Data already computed under ID, but not cached # assert isinstance(self._children,tuple) exec_str = "({} {})".format(self._op, " ".join([E...
itoijala/pyfeyner
tests/test-bend90a.py
Python
gpl-2.0
1,085
0.000922
# # pyfeyner - a simple Python interface for making Fey
nman diagrams. # Copyright (C) 2005-2010 Andy Buckley, Georg von Hippel # Copyright (C) 2013 Ismo Toijala # # pyfeyner 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 ...
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 pyfeyner; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # ...
coolcooldool/tencent-weibo-exporter
loginver4/tencent_util.py
Python
apache-2.0
10,110
0.006012
# -*- coding: utf-8 -*- ''' Created on 2017/09/14 @author: yuyang ''' import os import urllib import uuid import re import docx_ext from docx.shared import Pt from docx.shared import RGBColor from docx.shared import Inches JPEG_EXTENSION = '.jpg' PNG_EXTENSION = '.png' GIF_EXTENSION = '.gif' SPLIT_STRING = '///' T...
rgb = RGBColor(0x08, 0x08, 0x08) def add_picture(document, story): filenames = analyze_pic(story) for filename
in filenames: try: document.add_picture(filename, width=Inches(5)) except: print '插入图片出错:' + filename def add_time(document, time): para = document.add_paragraph() run = para.add_run(time) font = run.font font.italic = True #font.name = 'Microsoft YaHei' ...
stack-of-tasks/rbdlpy
tutorial/lib/python2.7/site-packages/OpenGL/GLES2/NV/read_depth_stencil.py
Python
lgpl-3.0
785
0.008917
'''OpenGL extension NV.read_depth_stencil This module customises the behaviour of the OpenGL.raw.GLES2.NV.read_depth_stencil to provide a more Python-friendly API The official definition of this extension is available here: http://www.opengl.org/registry/specs/NV/read_depth_stencil.txt ''' from OpenGL import platfo...
ead_depth_stencil import * from OpenGL.raw.GLES2.NV.read_depth_stencil import _EXTENSION_NAME def glInitReadDepthStencilNV(): '''R
eturn boolean indicating whether this extension is available''' from OpenGL import extensions return extensions.hasGLExtension( _EXTENSION_NAME ) ### END AUTOGENERATED SECTION
TimeSynth/TimeSynth
timesynth/signals/car.py
Python
mit
1,472
0.001359
import numpy as np from .base_signal import BaseSignal __all__ = ['CAR'] class CAR(BaseSignal): """Signal generatpr for continuously autoregressive (CAR) signals. Parameters ---------- ar_param : number (default 1.0) Parameter of the AR(1) process
sigma
: number (default 1.0) Standard deviation of the signal start_value : number (default 0.0) Starting value of the AR process """ def __init__(self, ar_param=1.0, sigma=0.5, start_value=0.01): self.vectorizable = False self.ar_param = ar_param self.sigma = si...
jhgg/discord.py
discord/colour.py
Python
mit
6,401
0.003749
# -*- coding: utf-8 -*- """ The MIT License (MIT) Copyright (c) 2015-2016 Rapptz 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 u...
ctory method that returns a :class:`Colour` with a value of ``0x1f8b4c``.""" ret
urn cls(0x1f8b4c) @classmethod def blue(cls): """A factory method that returns a :class:`Colour` with a value of ``0x3498db``.""" return cls(0x3498db) @classmethod def dark_blue(cls): """A factory method that returns a :class:`Colour` with a value of ``0x206694``.""" re...
enigmampc/catalyst
catalyst/finance/performance/position.py
Python
apache-2.0
7,850
0.000127
# # Copyright 2016 Quantopian, 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 wr...
unt': np.floor( self.amount * float(stock_dividend.ratio) ) } @expect_types(asset=Asset) def handle_split(self, asset, ratio): """ Update the position by
the split ratio, and return the resulting fractional share that will be converted into cash. Returns the unused cash. """ if self.asset != asset: raise Exception("updating split with the wrong asset!") # adjust the # of shares by the ratio # (if we had 100 ...
dalimatt/Instastalk
dependencies/workflow/background.py
Python
mit
7,361
0.001359
#!/usr/bin/env python # encoding: utf-8 # # Copyright © 2014 deanishe@deanishe.net # # MIT Licence. See http://opensource.org/licenses/MIT # # Created on 2014-04-06 # """ Run background tasks """ from __future__ import print_function, unicode_literals import sys import os import subprocess import pickle from workfl...
rn immediately and will not run the specified command. """ if is_running(name): wf().logger.info('Task `{0}` is already running'.format(name)) ret
urn argcache = _arg_cache(name) # Cache arguments with open(argcache, 'wb') as file_obj: pickle.dump({'args': args, 'kwargs': kwargs}, file_obj) wf().logger.debug('Command arguments cached to `{0}`'.format(argcache)) # Call this script cmd = ['/usr/bin/python', __file__, name, str...
tinkerinestudio/Tinkerine-Suite
TinkerineSuite/python/Lib/power/__init__.py
Python
agpl-3.0
1,441
0.002776
# coding=utf-8 """ Provides crossplatform checking of current power source, battery warning level and battery time remaining estimate. Allows you to add observer for power notifications if platform supports it. Usage: from power import PowerManagement, PowerManagementObserver # Automatically imports platform-speci...
error=str(e), platform=platform)) from power.common import PowerManagemen
tNoop as PowerManagement
nirvaris/nirvaris-dictionary
dictionary/migrations/0012_auto_20160521_1234.py
Python
mit
887
0.002255
# -*- coding: utf-8 -*- # Generated by Django 1.9 on 2016-
05-21 12:34 from __future__ import unicode_literals import dictionary.models from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('dictionary'
, '0011_auto_20160503_1535'), ] operations = [ migrations.RenameField( model_name='picture', old_name='image', new_name='full', ), migrations.AddField( model_name='picture', name='small', field=models.ImageField(max...
savi-dev/horizon
horizon/views/auth_forms.py
Python
apache-2.0
8,511
0.000587
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Copyright 2012 Nebula, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # no...
on, create a # new,
empty session if the existing session # corresponds to a different authenticated user. request.session.flush() # Always cycle the session key when viewing the login form to # prevent session fixation request.session.cycle_key() # For now we'll allow fallb...
maxive/erp
addons/lunch/models/lunch.py
Python
agpl-3.0
14,593
0.003358
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from collections import OrderedDict import json import datetime from odoo import api, fields, models, _ from odoo.exceptions import AccessError, ValidationError from odoo.addons import decimal_precision as dp class L...
'currency_id': line.currency_id.id, }
# sort the old lunch orders by (date, id) lunch_data = OrderedDict(sorted(lunch_data.items(), key=lambda t: (t[1]['date'], t[0]), reverse=True)) self.previous_order_widget = json.dumps(lunch_data) @api.one @api.depends('user_id') def _compute_cash_move_balance(self): ...
abelectronicsuk/ABElectronics_Python_Libraries
IOPi/tests/get_bus_pullups.py
Python
gpl-2.0
1,397
0
#!/usr/bin/env python """ ================================================ ABElectronics IO Pi Tests | test get_bus_pullups function Requires python smbus to be installed For Python 2 install with: sudo apt-get install python-smbus For Python 3 install with: sudo apt-get install python3-smbus run with: python3 get_b...
if x != a: passed = False break iopi.set_bus_pullups(a) x = iopi.get_bus_pullups()
if x != a: passed = False break if passed is False: print("Test Failed") else: print("Test Passed") if __name__ == "__main__": main()
quattor/aquilon
lib/aquilon/worker/commands/show_realm_all.py
Python
apache-2.0
1,108
0
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2012,2014,2016 C
ontributor # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distrib...
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. """Contains the logic for `aq show realm --all`.""" from aquilon.aqdb.model import Realm from aquilon.worker.broker import BrokerC...
edx-solutions/edx-platform
lms/djangoapps/courseware/tests/test_lti_integration.py
Python
agpl-3.0
9,264
0.002807
"""LTI integration tests""" import json from collections import OrderedDict import mock import oauthlib import six from django.conf import settings from django.urls import reverse from six import text_type from lms.djangoapps.courseware.tests.helpers import BaseTestXmodule from lms.djangoapps.courseware.views.views...
'element_id': self.item_descriptor.location.html_id(), 'launch_url': u'http://www.example.com', # default value 'open_in_a_new_page': Tr
ue, 'form_url': self.item_descriptor.xmodule_runtime.handler_url(self.item_descriptor, 'preview_handler').rstrip('/?'), 'hide_launch': False, 'has_score': False, 'module_score': None, 'co...
narrowmark/engelbart
note_entry.py
Python
mit
4,157
0.006495
import time import wx import xapian from threading import Thread from stop_words import stop_words class NoteEntryFrame(wx.Frame): def __init__(self, parent): wx.Frame.__init__(self, None, title="Note Entry", size=(300, 300)) self.db_path = "db" self.InitUI() def InitUI(self): panel = wx.Panel(se...
wx.BoxSizer(wx.HORIZONTAL) sizer = wx.FlexGridSizer(3, 2, 9, 25) subject = wx.StaticText(panel, label='Subject') note = wx.StaticText(panel, label='Note') self.subject_text = wx.TextCtrl(panel) self.note_text = wx.TextCtrl(panel, style=wx.TE_MULTILINE) sizer.AddMany([(subject), (self.subjec...
lf.note_text, 1, wx.EXPAND)]) sizer.AddGrowableRow(1, 1) sizer.AddGrowableCol(1, 1) hbox.Add(sizer, proportion=1, flag=wx.ALL|wx.EXPAND, border=15) panel.SetSizer(hbox) # Accelerator features save = wx.NewId() open = wx.NewId() self.Bind(wx.EVT_MENU, self.onCtrlS, id=save) self.Bi...
rew4332/tensorflow
tensorflow/contrib/slim/python/slim/evaluation.py
Python
apache-2.0
12,824
0.002963
# Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agree...
oop method: # Create model and obtain the predictions: images, labels = LoadData(...) predictions = MyModel(images)
# Choose the metrics to compute: names_to_values, names_to_updates = slim.metrics.aggregate_metric_map({ "accuracy": slim.metrics.accuracy(predictions, labels), "mse": slim.metrics.mean_squared_error(predictions, labels), }) # Define the summaries to write: for metric_name, metric_value in metri...
cjaymes/pyscap
src/scap/model/oval_5/defs/linux/SystemDUnitDependencyStateElement.py
Python
gpl-3.0
1,172
0.00256
# Copyright 2016 Casey Jaymes # This file is part of PySCAP. # # PySCAP 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. # # PySCAP is ...
URPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with PySCAP. If not, see <http://www.gnu.org/licenses/>. import logging from scap.model.oval_5.defs.linux.StateType import StateType logger = logging.getLogger(__name__) clas...
'elements': [ {'tag_name': 'unit', 'class': 'scap.model.oval_5.defs.EntityStateType', 'min': 0, 'max': 1}, {'tag_name': 'dependency', 'class': 'scap.model.oval_5.defs.EntityStateType', 'min': 0, 'max': 1}, ], }
OxPython/Python_float_round
src/digit_precision_float.py
Python
epl-1.0
432
0.006977
#!/usr/bin/env
python # -*- coding: utf-8 -*- ''' Created on Jul 16, 2014 @author: anroco How to define the number of decimal digits of a float in Python? ¿Cómo definir la cantidad de digitos decimales de
un float en Python? ''' #crate a float number f = 13.9497389867 print(f) #this method rounded to the number of digits defined after the decimal point. print(round(f, 2)) #define 4 digits of precision print(round(f, 4))
IllinoisRoboticsInSpace/Arduino_Control
RemoteControl/Move.py
Python
mit
675
0.056296
from ArduinoSerial import sendData, beginTransmission import serial import time import atexit ser = serial.Serial("/dev/ttyACM0",115200) ser.flushInput() #The next five lines allow the motors to stop once the ctrl+c command is given to abort the program. def exit_handler(): sendData(ser,1,0) sendData(ser,2,0) atex...
ter(exit_handler) if ser.is_open: beginTransmission(ser) else: print("Serial Closed") square = [(100,100),(100,-100),(100,100),(100,-100),(100,100),(100,-100),(100,100),(100,-100),(0,0)] #This should create a square for cmd in squ
are: sendData(ser, 1, cmd[0]) #This sends the commands to arduino, for each motor sendData(ser, 2, cmd[1])
zouzhberk/ambaridemo
demo-server/src/main/resources/stacks/HDP/2.1.GlusterFS/services/YARN/package/scripts/application_timeline_server.py
Python
apache-2.0
1,573
0.006357
""" 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 use this ...
elf, env): import params env.set_params(params) yarn() def start(self, env): import params env.set_params(params) self.configure(env) # FOR SECURITY service('historyserver', action='start') def stop(self, env): import params env.set_params(params) service('historyserver', a...
_historyserver_pid_file) if __name__ == "__main__": ApplicationTimelineServer().execute()
yourlabs/django-cities-light
src/cities_light/tests/test_update.py
Python
mit
5,691
0
"""Tests for update records.""" import unittest from dbdiff.fixture import Fixture from .base import TestImportBase, FixtureDir class TestUpdate(TestImportBase): """Tests update procedure.""" def test_update_fields(self): """Test all fields are updated.""" fixture_dir = FixtureDir('update') ...
self.import_data( fixture_dir, 'initial_country', 'initial_region', 'initial_subregion', 'initial_city', 'initial_translations' ) self.import_data( fixture_dir, 'add_country', 'add_region...
Fixture( fixture_dir.get_file_path('add_records.json') ).assertNoDiff() def test_noinsert(self): """Test --noinsert option.""" fixture_dir = FixtureDir('update') self.import_data( fixture_dir, 'initial_country', 'initial_region',...
brain461/ar_too
ar_too/__init__.py
Python
apache-2.0
197
0.005076
# -*- coding: utf-8 -*- from .api import get_artifactory_config_from_url
, update_ldapSettings_from_
dict, update_artifactory_config, cr_repository, update_password, get_repo_configs, get_repo_list
kevin-coder/tensorflow-fork
tensorflow/python/compiler/tensorrt/test/batch_matmul_test.py
Python
apache-2.0
3,185
0.002826
# 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...
lute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.python.compiler.tensorrt.test import tf_trt_integration_test_base as trt_test from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.f...
ow.python.ops import array_ops from tensorflow.python.ops import gen_array_ops from tensorflow.python.ops import math_ops from tensorflow.python.platform import test class BatchMatMulTest(trt_test.TfTrtIntegrationTestBase): def GetParams(self): """Testing conversion of BatchMatMul in TF-TRT conversion.""" ...
pr2git/e2openplugin-OpenWebif
plugin/__init__.py
Python
gpl-3.0
509
0.011788
# -*- c
oding: utf-8 -*- from Components.Language import language from Tools.Directories import resolveFilename, SCOPE_PLUGINS import gettext PluginLanguageDomain = "OpenWebif" PluginLanguagePath = "Extensions/OpenWebif/locale" def localeInit(): gettext.bindtextdomain(PluginLanguageDomain, resolveFilename(SCOPE_PLUGINS, P...
addCallback(localeInit)
rapirent/toc_project
kuoteng_bot/kuoteng_bot/urls.py
Python
mit
972
0.002058
"""kuoteng_bot URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include...
dmin from django.conf import settings #from telegram_bot.views import _set_webhook urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^bot/', include('telegram_bot.urls')), url(r'^', include('django_telegrambot.urls')), ] #_set_webhook()
Peter-Collins/NormalForm
src/py/CoordinateChange.py
Python
gpl-2.0
3,820
0.003141
""" AUTHOR: Dr. Andrew David Burbanks, 2005 This software is Copyright (C) 2004-2008 Bristol University and is released under the GNU General Public License version 2. MODULE: CoordinateChange PURPOSE: Compute the coo
rdinate changes relating complex diagonal to complex nor
mal form coordinates. NOTES: For parallel computation, one can specify for which variable index we want to compute the coordinate change. """ # parallel; we specify the index that we wish to compute. from Polynomial import Polynomial from IsogradeInnerTaylorCoeffs import IsogradeInnerTaylorCoeffs from Utility impo...
google-research/episodic-curiosity
third_party/gym/ant_wrapper_test.py
Python
apache-2.0
2,294
0.001308
# coding=utf-8 # The MIT License # # Copyright (c) 2016 OpenAI (https://openai.com) # Copyright (c) 2018 The TF-Agents Authors. # Copyright (c) 2018 Google LLC (http://google.com) # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the ...
d to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLI
ED, 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 CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWIS, ARISING FROM, # OUT OF OR IN CONNECT...
ActivisionGameScience/assertpy
tests/test_same_as.py
Python
bsd-3-clause
2,899
0.008624
# Copyright (c) 2015-2019, Activision Publishing, 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: # # 1. Redistributions of source code must retain the above copyright notice, this # list of ...
ote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMIT
ED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOOD...
sebrandon1/neutron
neutron/extensions/providernet.py
Python
apache-2.0
3,608
0
# Copyright (c) 2012 OpenStack Foundation. # All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless...
dernet(extensions.ExtensionDescriptor): """Extension class supporting provider networks. This class is used by neutron's extension framework to make metadata about the provider network extension available to clients. No new resources are defined by this extension. Instead, the existing network reso...
so include provider attributes. """ @classmethod def get_name(cls): return "Provider Network" @classmethod def get_alias(cls): return "provider" @classmethod def get_description(cls): return "Expose mapping of virtual networks to physical networks" @classm...
thdb-theo/Zombie-Survival
src/pickup.py
Python
mit
3,543
0.001411
from functools import partial from random import random, randint, choice import pygame import init as _ from baseclass import BaseClass from options import Options try: from cython_ import collide except ImportError: from python_ import collide from miscellaneous import further_than, scale from t...
_tile) @classmethod def spawn(cls, survivor): _further_than = partial(further_than, survivor=survivor, min_dist=150) pos_spawn_tiles = list(filter(_further_than, cls.spawn_tiles)) if not pos_spa
wn_tiles: # If no pick-up spawn is far enough away if not cls.spawn_tiles: # If all pick-up spawns are occupied, don"t spawn return pos_spawn_tiles.extend(cls.spawn_tiles) cls.left_round -= 1 type_ = random() spawn_tile = choice(pos_spawn_tiles) ...
alexwlchan/python-taskpaper
test/test_item.py
Python
mit
3,541
0
# -*- encoding: utf-8 -*- from hypothesis import given from hypothesis.strategies import integers, lists import pytest from taskpaper import TaskPaperItem, TaskPaperError from utils import taskpaper_item_strategy @given(integers()) def test_setting_tab_size(tab_size): """We can set the tab size on TaskPaperIte...
Create an item with a parent, then set the parent to None. Check the child is removed from the list of its previous parents' children. """ item_p = TaskPaperItem('parent') item_c = TaskPaperItem('child', parent=
item_p) item_c.parent = None assert item_c.parent is None assert item_p.children == [] def test_detect_item_cannot_be_its_parents_parent(self): """ An item cannot be the parent of its own parent. """ item_p = TaskPaperItem('parent') item_c = TaskPape...
mkmeral/TevitolApplication
application/backend/application/views.py
Python
gpl-3.0
2,676
0.00299
from rest_framework.decorators import api_view from rest_framework.response import Response from django.contrib.auth.models import User from application.serializers import UserSerializer, ApplicationSerializer, ApplicationListSerializer from rest_framework import viewsets, status from application.models import Applicat...
except Application.DoesNotExist: raise Http404 def get(self, request, pk, form
at=None): applications = self.get_object(pk) serializer = ApplicationSerializer(applications) return Response(serializer.data) def put(self, request, pk, format=None): application = self.get_object(pk) serializer = ApplicationSerializer(application, data=request.data) ...
Xinglab/rmats2sashimiplot
src/MISO/misopy/test_miso.py
Python
gpl-2.0
7,024
0.002847
#!/usr/bin/env python import os import sys import unittest import pysam import sam_utils class TestMISO(unittest.TestCase): """ Test MISO functionality. """ def setUp(self): # Find out the current directory self.miso_path = \ os.path.dirname(os.path.abspath(os.path.expandus...
"+read must match +target under fr-firstrand
." assert(sam_utils.read_matches_strand(f_read, minus_target_strand, "fr-firststrand") == False), \ "+read must match +target under fr-firststrand." # test -read assert(sam_utils.read_matches_st...
vamst/COSMOS2
cosmos/web/admin.py
Python
gpl-3.0
358
0.002793
# from .. import Workflow, Stage, Tas
k, TaskFile # # from flask.ext import admin # from flask.ext.admin.contrib import sqla # # # def add_cosmos_admin(flask_app, session): # adm = admin.Admin(flask_app, 'Flask Admin', base_template="admin_layout.html") # f
or m in [Workflow, Stage, Task, TaskFile]: # adm.add_view(sqla.ModelView(m, session))
jamiefolsom/edx-platform
lms/djangoapps/instructor_task/tests/test_tasks_helper.py
Python
agpl-3.0
61,734
0.003193
# -*- coding: utf-8 -*- """ Unit tests for LMS instructor-initiated background tasks helper functions. Tests that CSV grade report generation works with unicode emails. """ import ddt from mock import Mock, patch import tempfile from openedx.core.djangoapps.course_groups import cohorts import unicodecsv from django....
ls import override_settings from capa.tests.response_xml_factory import MultipleChoiceResponseXMLFactory from certificates.models import CertificateStatuses from certificates.tests.factories import GeneratedCertificateFactory, CertificateWhitelistFactory from course_modes.models import CourseMode from courseware.tests...
estCase, TestReportMixin, InstructorTaskModuleTestCase from openedx.core.djangoapps.course_groups.models import CourseUserGroupPartitionGroup from openedx.core.djangoapps.course_groups.tests.helpers import CohortFactory import openedx.core.djangoapps.user_api.course_tag.api as course_tag_api from openedx.core.djangoapp...
noironetworks/group-based-policy
gbpservice/nfp/common/constants.py
Python
apache-2.0
4,212
0.000237
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # d...
neutron_port" GBP_PORT = "gbp_policy_target" NEUTRON_NETWORK = "neutron_network" GBP_NETWORK = "gbp_group" PROVIDER = "provider" CONSUMER = "consumer" STITCHING = "stitching" MANAGEMENT = "management" MONITOR = "monitoring" GATEWAY_TYPE = "gateway" ENDPOINT_TYPE = "endpoint" CREATE = "create" UPDATE = "update" DELET...
E_PORT = "ACTIVE" STANDBY_PORT = "STANDBY" MASTER_PORT = "MASTER" STANDALONE_PORT = "STANDALONE" ACTIVE = "ACTIVE" # REVISIT(ashu) - Merge to have single BUILD state PENDING_CREATE = "PENDING_CREATE" PENDING_UPDATE = "PENDING_UPDATE" PENDING_DELETE = "PENDING_DELETE" ERROR = "ERROR" BUILD = "BUILD" NFP_STATUS = [ACTI...
nextgenusfs/ufits
amptk/install.py
Python
bsd-2-clause
3,232
0.008045
#!/usr/bin/env python from __future__ import (absolute_import, division, print_function, unicode_literals) import sys import os import argparse import tarfile import gzip import json import requests import shutil from amptk import amptklib try: from urllib.request import urlopen except Impo...
tabase` command.") sys.exit(1) #download if not x in URL: if args.force: continue print("%s not valid, choices are ITS, 16S, LSU, COI" % x)
sys.exit(1) print("Downloading %s pre-formatted database" % x) address = URL.get(x) if not os.path.isfile(x+'.amptk.tar.gz'): amptklib.download(address, x+'.amptk.tar.gz') tfile = tarfile.open(x+'.amptk.tar.gz', 'r:gz') tfile.extractall(x) for file ...
resmio/django-sendgrid
sendgrid/tests/test_signals.py
Python
bsd-2-clause
3,625
0
from django.test import TestCase, Client from sendgrid import utils, signals import json class SignalTestCase(TestCase): def setUp(self): self.client = Client() self.email_data = {'subject': 'Test Subject', 'body': 'Hi, I am a test body', 'fr...
l self.assertEqual(len(data), 2) self.assertEqual(data[1][0].ev
ent, 'processed') self.assertEqual(data[1][0].uuid, message.uuid) self.assertEqual(response.status_code, 200) def test_dupe_signals(self): """ Test handling of duplicate signals. """ data = [] def email_event_handler(sender, signal): data.append((sender...
gem/oq-engine
openquake/hazardlib/source/non_parametric.py
Python
agpl-3.0
10,119
0
# The Hazard Library # Copyright (C) 2013-2022 GEM Foundation # # 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. #...
ot None: assert len(weights) == len(data) for (rup, pmf), weight in zip(data, weights): rup.weight = weight def iter_ruptures(self, **kwargs): """ Get a generator object that yields probabilistic ruptures the source consists of. :returns: ...
zardlib.source. rupture.NonParametricProbabilisticRupture`. """ for rup, pmf in self.data: if rup.mag >= self.min_mag: yield NonParametricProbabilisticRupture( rup.mag, rup.rake, self.tectonic_region_type, rup.hypocenter, ru...
radman404/Who-s-attacking-me-now--
wamnclient.py
Python
gpl-2.0
2,126
0.024929
#!/usr/bin/python import pygeoip import json from logsparser.lognormalizer import LogNormalizer as LN import gzip import glob import socket import urllib2 IP = 'IP.Of,Your.Server' normalizer = LN('/usr/local/share/logsparser/normalizers') gi = pygeoip.GeoIP('../GeoLiteCity.dat') def complete(text, state): return (gl...
newd
ata = data newjson = json.dumps(newdata) print json.loads(newjson) send(newjson) def send(data): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('Ip.Of.Your.Server', 9999)) s.sendall(data) s.close() try: sshcheck() except KeyboardInterrupt: print '\nCtrl+C Exiting...' exit(0)
markroxor/gensim
gensim/corpora/indexedcorpus.py
Python
lgpl-2.1
5,378
0.002789
#!/usr/bin/env python # -*- codi
ng: utf-8 -*- # # Copyright (C) 2010 Radim Rehurek <radimrehurek@seznam.cz> # Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html """ Indexed corpus is a mechanism for random-accessing corpora. While the standard corpus interface in gensim allows iterating over corpus with `for doc in corpus: pa...
the same as the corpus file plus '.index' suffix) that stores the byte offset of the beginning of each document. """ import logging import six import numpy from gensim import interfaces, utils logger = logging.getLogger('gensim.corpora.indexedcorpus') class IndexedCorpus(interfaces.CorpusABC): def __init__(se...
leschzinerlab/ISAC
ISAC.py
Python
mit
8,169
0.045048
#!/usr/bin/env python import optparse from sys import * import os,sys,re from optparse import OptionParser import glob import subprocess from os import system import linecache import time #========================= def setupParserOptions(): parser = optparse.OptionParser() parser.set_usage("%prog -i <...
ult=1, help="Number of generations. (Default=1)") parser.add_option("--queue",dest="queue",type="string", metavar="STRING",default='condo', help="Queue for job submission. (Default=condo)") parser.add_option("--nodes",dest="nodes",type="int", metavar="INT",default=20, h...
threads per node to run. (Default=8)") parser.add_option("--walltime",dest="walltime",type="int", metavar="INT",default=8, help="Walltime for job (estimated run time, in hours). (Default=8)") parser.add_option("-d", action="store_true",dest="debug",default=False, help="debug") ...
lociii/googleads-python-lib
examples/adspygoogle/dfp/v201306/creative_service/get_creatives_by_statement.py
Python
apache-2.0
2,090
0.002871
#!/usr/bin/python # # Copyright 2013 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required b...
= {'query': 'WHERE creativeType = :creativeType LIMIT 500', 'values': values} # Get creatives by statement. response = creative_service.GetCreativesByStatement(filter_statement)[0] creatives = [] if 'results' in response: creatives = response['results'] # Display results
. for creative in creatives: print ('Creative with id \'%s\', name \'%s\', and type \'%s\' was found.' % (creative['id'], creative['name'], creative['Creative_Type'])) print print 'Number of results found: %s' % len(creatives)
nicholasserra/sentry
src/sentry/api/endpoints/project_details.py
Python
bsd-3-clause
8,377
0.002029
from __future__ import absolute_import import logging from datetime import timedelta from django.utils import timezone from rest_framework import serializers, status from rest_framework.response import Response from sentry.api.base import DocSection from sentry.api.bases.project import ProjectEndpoint from sentry.ap...
et_option('sentry:resolve_age', 0)), 'sentry:scrub_data': bool(project.get_option('sentry:scrub_data', True)), 'sentry:scrub_defaults': bool(project.get_option('sentry:scrub_defaults', True)), 'sentry:sensitive_fields': project.get_option('sentry:sensitive_fields', [
]), } data['activePlugins'] = active_plugins data['team'] = serialize(project.team, request.user) data['organization'] = serialize(project.organization, request.user) include = set(filter(bool, request.GET.get('include', '').split(','))) if 'stats' in include: ...
opennode/nodeconductor-assembly-waldur
src/waldur_core/core/tests/test_authentication.py
Python
mit
7,832
0.002937
from django.conf import settings from django.contrib.auth import get_user_model from django.core.cache import cache from django.urls import reverse from django.utils import timezone from freezegun import freeze_time from rest_framework import status, test from rest_framework.authtoken.models import Token from . import...
token_in_a_year = response.data['token']
self.assertEqual(original_token, token_in_a_year) def test_token_created_date_is_refreshed_even_if_token_lifetime_is_none(self): response = self.client.post( self.auth_url, data={'username': self.username, 'password': self.password} ) self.assertEqual(response.status_code, s...
ayseyo/oclapi
django-nonrel/ocl/integration_tests/tests/openmrs_mapping_validation.py
Python
mpl-2.0
1,429
0.003499
from django.core.urlresolvers import reverse from mappings.tests import MappingBaseTest from mappings.validation_messages import OPENMRS_SINGLE_MAPPING_BETWEEN_TWO_CONCEPTS from oclapi.models import CUSTOM_VALIDATION_SCHEMA_OPENMRS from test_helper.base import create_user, create_source, create_concept class OpenMRS...
user1, source=source) self.client.login(username='user1
', password='user1') kwargs = { 'source': source.mnemonic } mapping1 = { 'from_concept_url': concept1.url, 'to_concept_url': concept2.url, 'map_type': 'Same As' } mapping2 = { 'from_concept_url': concept1.url, ...
Trust-Code/python-cnab
tests/test_registro.py
Python
mit
4,409
0.000454
import unittest from unittest import skip from decimal import Decimal from cnab240 import errors from cnab240.bancos import itau from tests.data import get_itau_data_from_file class TestRegistro(unittest.TestCase): def setUp(self): itau_data = get_itau_data_from_file() self.header_arquivo = it...
0.00')) def test_escrita_campo_num_decimal(self): # aceitar s
omente tipo Decimal with self.assertRaises(errors.TipoError): self.seg_p.valor_titulo = 10.0 with self.assertRaises(errors.TipoError): self.seg_p.valor_titulo = '' # Testa se as casas decimais estao sendo verificadas with self.assertRaises(errors.NumDecimaisError...
Microvellum/Fluid-Designer
win64-vc/2.78/python/lib/asyncio/selector_events.py
Python
gpl-3.0
39,441
0.000076
"""Event loop using a selector and related classes. A selector is a "notify-when-ready" multiplexer. For a subclass which also includes support for signal handling, see the unix_events sub-module. """ __all__ = ['BaseSelectorEventLoop'] import collections import errno import functools import socket import warnings ...
continue except BlockingIOError: break def _write_to_self(self): # This may be called from a different thread, possibly after # _close_self_pipe() has been called or even while it is # running. Guard for self._csock being None or closed. When # a so...
th errno set to # EBADF, but let's not rely on the exact error code). csock = self._csock if csock is not None: try: csock.send(b'\0') except OSError: if self._debug: logger.debug("Fail to write a null byte into the " ...
quartzmo/gcloud-ruby
google-cloud-bigquery-data_transfer/synth.py
Python
apache-2.0
3,453
0.001448
# Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, s...
ydatatransfer', config_path='artman_bigquerydatatransfer.yaml' ) s.copy(v1_library / 'acceptance') s.copy(v1_library / 'lib') s.copy(v1_library / 'test') s.copy(v1_library / 'README.md') s.copy(v1_library / 'LICENSE') s.copy(v1_library / '.gitignore') s.copy(v1_library / '.yardopts') s.copy(v1_library / 'google-clo...
mspec) # PERMANENT: Use custom credentials env variable names s.replace( 'lib/google/cloud/bigquery/data_transfer/v1/credentials.rb', 'BIGQUERYDATATRANSFER_KEYFILE', 'DATA_TRANSFER_KEYFILE') s.replace( 'lib/google/cloud/bigquery/data_transfer/v1/credentials.rb', 'BIGQUERYDATATRANSFER_CREDENTIALS', 'DAT...
coxley/trigger
trigger/utils/notifications/events.py
Python
bsd-3-clause
4,682
0.001495
# -*- coding: utf-8 -*- """ Event objects for the notification system. These are intended to be used within event handlers such as `~trigger.utils.notifications.handlers.email_handler()`. If not customized within :setting:`NOTIFICATION_HANDLERS`, the default notification type is an `~trigger.utils.notification.event...
ger.utils.notifications i
mport send_email try: # This should return True upon successfully sending email e = self return send_email(addresses=e.recipients, subject=e.title, body=e.message, sender=e.sender, mailhost=e.mailhost) except...
allenlavoie/tensorflow
tensorflow/contrib/model_pruning/python/pruning_test.py
Python
apache-2.0
9,014
0.006989
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
) self.assertEqual(p._sparsity.eval(), p_copy._sparsity.eval()) class PruningTest(test.TestCase): def setUp(self): super(PruningTest, self).setUp() self.global_step = training_util.get_or_create_global_step() def testCreateMask2D(self): width = 10 height = 20 with self.test_session(): ...
hts = variables.Variable( random_ops.random_normal([width, height], stddev=1), name="weights") masked_weights = pruning.apply_mask(weights, variable_scope.get_variable_scope()) variables.global_variables_initializer().run() weights_val = weights.eval...
kfcpaladin/sze-the-game
renpy/display/joystick.py
Python
mit
1,793
0.001673
# Copyright 2004-2017 Tom Rothamel <pytom@bishoujo.us> # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation files # (the "Software"), to deal in the Software without restriction, # including without limitation the rights to use, copy, modify, m...
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 CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISI...
ave for a few compatibility functions. import renpy.display import pygame_sdl2 # Do we have a joystick enabled? enabled = False class JoyBehavior(renpy.display.layout.Null): """ This is a behavior intended for joystick calibration. If a joystick event occurs, this returns it as a string. """ pa...
rdo-management/neutron
neutron/openstack/common/eventlet_backdoor.py
Python
apache-2.0
4,859
0
# Copyright (c) 2012 OpenStack Foundation. # Administrator of the National Aeronautics and Space Administration. # 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 a...
or(port_range, ex, help_for_backdoor_port) def _listen(host, start_port, end_port, listen_fu
nc): try_port = start_port while True: try: return listen_func((host, try_port)) except socket.error as exc: if (exc.errno != errno.EADDRINUSE or try_port >= end_port): raise try_port += 1 def initialize_if_enabled(): backd...
mindbody/API-Examples
SDKs/Python/test/test_custom_payment_method.py
Python
bsd-2-clause
980
0
# coding: utf-8 """ MINDBODY Public API No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501 OpenAPI spec version: v6 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import impo...
ittest import swagger_client from swag
ger_client.models.custom_payment_method import CustomPaymentMethod # noqa: E501 from swagger_client.rest import ApiException class TestCustomPaymentMethod(unittest.TestCase): """CustomPaymentMethod unit test stubs""" def setUp(self): pass def tearDown(self): pass def testCustomPaym...
SymbiFlow/prjxray
fuzzers/031-cmt-mmcm/generate.py
Python
isc
3,572
0.00056
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright (C) 2017-2020 The Project X-Ray Authors. # # Use of this source code is governed by a ISC-style # license that can be found in the LICENSE file or at # https://opensource.org/licenses/ISC # # SPDX-License-Identifier: ISC import json from prjxray.segmaker i...
"{0:011b}"
.format(paramadj)[::-1]] for i in range(10): segmk.add_site_tag(site, '%s[%u]' % (param, i), bitstr[i]) for param, bits in [ ('CLKOUT0_DIVIDE_F', 7), ('CLKOUT1_DIVIDE', 7), ('CLKOUT2_DIVIDE', 7), ('CLKOUT3_DIVIDE', 7), ('CLKOUT4_DIVIDE', 7), ('CL...
EnTeQuAk/dotfiles
sublime-text-3/Packages/Search in Project/searchengines/grep.py
Python
unlicense
953
0.018888
### Start of fixing import paths import os, sys, inspect # realpath() with make your script run, even if you symlink it :) cmd_folder = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile( inspect.currentframe() ))[0])) if cmd_folder not in sys.path: sys.path.insert(0, cmd_folder) # use this if you want...
n different ways on Windows # __file__ fails if someone does os.chdir() before # sys.argv[0] also fails because i
t doesn't not always contains the path ### End of fixing import paths import base class Grep (base.Base): pass engine_class = Grep
yaukwankiu/armor
tests/imageToDataTest4.py
Python
cc0-1.0
5,132
0.01286
# attempting the classify the charts, after armo
r/tests/imageToDataTest3.py # Plan: 1. compute features and store them # 2. classify # 3. display # #sleepTime= 140000 sleepTime =0 import time print time.asctime() print 'sleeping now for ', sleepTime, 'seconds' time.sleep(sleepTime) import os import time import pickle import numpy as np from...
rn.plt inputFolder = dp.defaultImageDataFolder + 'charts2-allinone-/' imageFolder = dp.root + 'labLogs2/charts2_extracted/' outputFolder = dp.root + 'labLogs2/charts2_features/' try: os.makedirs(outputFolder) except: print outputFolder, 'exists' N = 500 L = os.listdir(inputFolder) L = [v for v in L if...
Pulgama/supriya
supriya/nonrealtime/NodeTransition.py
Python
mit
4,163
0.001441
import supriya.commands import supriya.realtime from supriya.system.SupriyaValueObject import SupriyaValueObject class NodeTransition(SupriyaValueObject): """ A non-realtime state transition. """ ### CLASS VARIABLES ### __documentation_section__ = "Session Internals" __slots__ = ("_source",...
ts) parent = nodes_to_parents.get(node, None) if node in nodes_to_children: del nodes_to_children[node]
if node in nodes_to_parents: del nodes_to_parents[node] if not parent: return children = list(nodes_to_children[parent]) children.remove(node) nodes_to_children[parent] = tuple(children) or None def _move_node(self, nodes_to_children, nodes_to_parents): ...
siddhantgoel/streaming-form-data
examples/tornado/stream_request_body.py
Python
mit
1,487
0
import os.path import tempfile from time import time from streaming_form_data import StreamingFormDataParser from streaming_form_data.targets import FileTarget, ValueTarget
from tornado.ioloop import IOLoop from tornado.web import Application,
RequestHandler, stream_request_body one_hundred_gb = 100 * 1024 * 1024 * 1024 @stream_request_body class UploadHandler(RequestHandler): def prepare(self): self.request.connection.set_max_body_size(one_hundred_gb) name = 'uploaded-file-tornado-{}.dat'.format(int(time())) self.value = V...
kevgraham7/toolbox
python/samples/git-tools/util/log_setup.py
Python
apache-2.0
1,033
0.001936
import logging class BorgSingleton: _shared_state = {} def __init__(self): self.__dict__ = self._shared_state class LoggerSetup(BorgSingleton): """Logger setup convenience class""" DEFAULT_FORMAT = '%(asctime)s - %(name)s - %(levelname)s - %(message)s' def __init__(self, logger_name, ...
if log_file: self.add_log_file(log_file, log_level, log_format) def add_log_file(self, log_file, level=logging.INFO, log_format=DEFAULT_FORMAT): file_handler
= logging.FileHandler(log_file) file_handler.setLevel(level) file_handler.setFormatter(logging.Formatter(log_format)) logging.getLogger(self.__logger_name).addHandler(file_handler) def get_logger(self): return logging.getLogger(self.__logger_name)
nitely/Spirit
spirit/comment/bookmark/urls.py
Python
mit
273
0
# -*- coding: utf-8 -
*- from django.conf.urls import re_path from . import views app_name = 'bookmark' urlpatterns = [ re_path(r'^(?P<topic_id>[0-9]+)/create/$', views.create, name='cre
ate'), re_path(r'^(?P<topic_id>[0-9]+)/find/$', views.find, name='find'), ]
verma-varsha/zulip
zerver/management/commands/enqueue_digest_emails.py
Python
apache-2.0
728
0.002747
from __future__ import absolute_import import datetime from typing import Any, List from django.conf import settings from django.core.management.base import BaseCommand from django.utils.timezone import now as timezone_now fr
om zerver.lib.digest import enqueue_emails, DIGEST_CUTOFF from zerver.lib.logging_util import create_logger ## Logging setup ## logger = create_logger(__name__, settings.DIGEST_LOG_PATH, 'DEBUG') class Command(BaseCommand): help = """Enqueue digest emails for users that haven't checked the app in a while. """ ...
cutoff = timezone_now() - datetime.timedelta(days=DIGEST_CUTOFF) enqueue_emails(cutoff)
obi-two/Rebelion
data/scripts/templates/object/mobile/shared_space_rebel_tier3_ezkiel.py
Python
mit
452
0.04646
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATION
S MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Creature() result.template = "object/mobile/shared_space_rebel_tier3_ezkiel.iff" result.attribute_template_id = 9 result.stfName("npc_name","ishi_tib_base_male") ##...
N MODIFICATIONS #### #### END MODIFICATIONS #### return result
renzon/fatec-script
backend/appengine/pythonicos.py
Python
mit
1,283
0.003118
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from random import shuffle class Carta(): def __init__(self, numero, naipe): self.numero = numero self.naipe = naipe def __repr__(self): return '%s de %s' % (self.numero, self.naipe) class Baralho(): ...
elf._cartas = [Carta(numero, naipe) for numero in 'As 1 2 3 4 5 6 7 8 9 10 Q J K'.split() for naipe in 'Ouros Espadas Copas Paus'.split()] def __getitem__(self, index): return self._cartas[index] def __setitem__(self, key, value): self._cartas[key] = value def __le...
aus') baralho = Baralho() baralho[55] = Carta('As', 'Paus') shuffle(baralho) for carta in baralho: print carta print baralho[0] class Vetor(): def __init__(self, x, y): self.y = y self.x = x def __repr__(self): return '(%s, %s)' % (self.x, self.y) def __add__(self, other): ...
tensorflow/federated
tensorflow_federated/python/learning/model.py
Python
apache-2.0
12,401
0.002903
# Copyright 2018, The TensorFlow Federated 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 o...
ases this method will be called from `forward_pass` to produce the predictions, and `forward_pass` will further compute loss and metrics updates. Note that this im
plies `batch_input` will have a *different* signature for `predict_on_batch` than for `forward_pass`; see the args section of this documentation for a specification of the relationship. Args: batch_input: A nested structure of tensors that holds the prediction inputs for the model. The struct...
utn-frm-si/reservas
app_reservas/urls.py
Python
mit
4,160
0
# coding=utf-8 from djan
go.conf.urls import url from .views import ( AliTemplateView, AliVideoconferenciasDetailView, AreaDetailView, AulaD
etailView, CuerpoDetailView, IndexView, LaboratorioDetailView, LaboratorioInformaticoDetailView, LaboratorioInformaticoListView, NivelDetailView, recurso_eventos_json, RecursoAliDetailView, SolicitudAliReclamosSugerencias, SolicitudAulaView, SolicitudInstalacionSoftwareView, ...
mitodl/open-discussions
course_catalog/management/commands/print_course_duplicates_yaml.py
Python
bsd-3-clause
397
0
"""Management command for uploading master json data for OCW courses""" from django.core.management import BaseComm
and from course_catalog.etl.deduplication import generate_duplicates_yaml class Command(BaseCommand): """Print course duplicates yaml""" help = "Print course
duplicates yaml" def handle(self, *args, **options): self.stdout.write(generate_duplicates_yaml())