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
atados/api
atados_core/migrations/0016_auto_20151208_2014.py
Python
mit
702
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('atados_core', '0015_subscription_card_id'), ] operations = [ migrations.RemoveField( model_na
me='subscription', name='cardholder_name', ), migrations.RemoveField( model_name='subscription', name='cvv', ), migrations.RemoveField( mo
del_name='subscription', name='exp_month', ), migrations.RemoveField( model_name='subscription', name='exp_year', ), ]
akappy7/ChromeOS_EC_LED_Diagnostics
test/tpm_test/subcmd.py
Python
bsd-3-clause
318
0
#!/usr/b
in/python # Copyright 2015 The
Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Subcommand codes that specify the crypto module.""" # Keep these codes in sync with include/extension.h. AES = 0 HASH = 1 RSA = 2
sunlightlabs/read_FEC
fecreader/formdata/migrations/0005_auto__add_field_skede_effective_date__add_field_skede_dissemination_da.py
Python
bsd-3-clause
36,890
0.0074
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'SkedE.effective_date' db.add_column(u'formdata_skede', 'effective_date', ...
gth': '34', 'null': 'True', 'blank': 'True'}), 'contributor_suffix': ('django.db.models.fields.CharField', [], {'max_length': '10', 'null': 'True', 'blank': 'True'}), 'contributor_zip': (
'django.db.models.fields.CharField', [], {'max_length': '9', 'null': 'True', 'blank': 'True'}), 'donor_candidate_district': ('django.db.models.fields.CharField', [], {'max_length': '2', 'null': 'True', 'blank': 'True'}), 'donor_candidate_fec_id': ('django.db.models.fields.CharField', [], {'max_l...
spaceone/httoop
httoop/semantic/__init__.py
Python
mit
181
0
# -*- coding: utf-8 -*- f
rom httoop.semantic.request import ComposedRequest from httoop.semantic.response import ComposedResponse __all__ = ('ComposedReq
uest', 'ComposedResponse')
orvi2014/kitsune
kitsune/tags/forms.py
Python
bsd-3-clause
6,116
0
import json from django.forms import Widget, MultipleChoiceField from django.forms.util import flatatt from django.utils.datastructures import MultiValueDict, MergeDict from django.utils.encoding import force_unicode from django.utils.html import escape from django.utils.safestring import mark_safe from taggit.models...
RLs without hitting the network. async_urls = () # make_link should be a function that takes a tag slug and returns some # kind of meaningful link. Ignored if async_urls is (). def make_link(self, slug): return '#' # Allow adding new tags to the vocab: can_create_tags = False # TO...
# responsible for routing to those and doing the calls to remove/add # the tag. def _render_tag_list_items(self, control_name, tag_names): """Represent applied tags and render controls to allow removal.""" def render_one(tag): output = u'<li class="tag">' # Hidden in...
reedstrm/Pyrseas
tests/functional/test_autodoc_dir.py
Python
bsd-3-clause
2,782
0
# -*- coding: utf-8 -*- """Test dbtoyaml and yamltodb using autodoc schema but I/O to/from a directory Same as test_autodoc.py but with directory tree instead of a single YAML file. See http://cvs.pgfoundry.org/cgi-bin/cvsweb.cgi/~checkout~/autodoc/autodoc/ regressdatabase.sql?rev=1.2 """ from pyrseas.testutils import...
elf): # Create the source schema self.execute_script(__file__, 'autodoc-schema.sql') # Run pg_dump against source database srcdump = self.tempfile_path('autodoc-src.dump') self.run_pg_dump(srcdump, True) # Create source YAML file and directory tree # Note: the s...
aml(srcyaml, True) self.create_yaml(None, True) # Migrate the target database targsql = self.tempfile_path('autodoc.sql') self.migrate_target(None, targsql) # Run pg_dump against target database targdump = self.tempfile_path('autodoc.dump') self.run_pg_dump(targ...
eicher31/compassion-modules
hr_planning/models/hr_planning_day_move_request.py
Python
agpl-3.0
6,277
0
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2014 Compassion CH (http://www.compassion.ch) # Releasing children from poverty in Jesus' name # @author: David Coninckx <david@coninckx.com> # # The licence is in the file __manifest__.p...
ions.UserError( _(u'{} does not work this day : {}').format( employee_name, vals['old_date']) ) # Add request else: vals['old_date'] = False return super(
HrPlanningDayMoveRequest, self).create(vals) @api.multi def write(self, vals): if 'type' in vals: if vals['type'] == 'add': vals['old_date'] = False return super(HrPlanningDayMoveRequest, self).write(vals) # Delete a request @api.multi def unlink(self): ...
clld/clldutils
tests/test_markup.py
Python
apache-2.0
1,781
0.001123
import io from operator import itemgetter import pytest from clldutils.markup import Table, iter_markdown_tables, iter_markdown_sections def test_Table(): t = Table() assert t.render() == '' t = Table('a', 'b', rows=[[1, 2], [3, 4]]) assert t.render() == \ '| a | b |\n|----:|----:|\n| 1 | 2...
ys.readouterr() assert out == ' a b\n--- ----\n 1 2.35\n' f = io.StringIO() with Table('a', 'b',
tablefmt='simple', file=f) as t: t.append([1, 2.345]) assert f.getvalue() == ' a b\n--- ----\n 1 2.35\n' def test_iter_markdown_tables(): header, rows = ['a', 'b'], [[1, 2], [3, 4]] text = Table(*header, **dict(rows=rows)).render() + '\nabcd' assert list(iter_markdown_tables(text))[0] ...
ryos36/polyphony-tutorial
Tutorial_1/false/cubic_root_false.py
Python
mit
740
0.012162
from polyphony import testbench def cube(x): return x * x * x def abs(x): if x <
0 : return -x e
lse: return x def cubic_root(x): ans = 0 for ans in range(0, abs(x) + 1): if cube(ans) >= abs(x): break print("ans is ", ans) if cube(ans) != abs(x): return False else: print("2:ans is ", ans) if x < 0 : ans = -ans return ans ...
jabber-at/gajim
src/command_system/framework.py
Python
gpl-3.0
12,291
0.000895
# Copyright (C) 2009-2010 Alexander Cherniuk <ts33kr@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # T...
ation(self): """ Extract handler's documentation which is a doc-string and transform it to a usable forma
t. """ return getdoc(self.handler) def extract_description(self): """ Extract handler's description (which is a first line of the documentation). Try to keep them simple yet meaningful. """ documentation = self.extract_documentation() return documenta...
colincsl/pyKinectTools
pyKinectTools/algs/SkeletonBeliefPropagation.py
Python
bsd-2-clause
4,811
0.036791
import numpy as np ''' Belief Propagation on tree''' class Node: children = [] parent = -1 pos = -1 index = -1 depth = 0 msgsDown = {} msgUp = -1 psi = -1 belief = -1 def __init__(self, parent_=-1, index_=-1, children_=[], pos_=-1, depth_=0): self.index = index_ self.pos = pos_ self.parent = parent...
ief = -1 def getLeaves(self, leaves=set()): if self.children == []: leaves.add(self) else: for c in self.children: l = c.getLeaves(leaves) if self.parent == -1: return list(leaves) else: return leaves def calcPsi(self, hypothesis): #psi is the unary potentials/messages # hypothesis = g...
pothesis)[0]]) for i in xrange(np.shape(hypothesis)[0]): self.psi[i] = np.sqrt(np.sum((hypothesis[i] - self.pos)**2)) # print '1', self.psi self.psi = (np.sum(self.psi) - self.psi)/np.sum(self.psi) self.psi /= np.sum(self.psi) # print '4', self.psi def setPsi(self, psi): pass def calcMessageUp(self):...
LSSTDESC/LSSTDarkMatter
nanolensing/test.py
Python
mit
2,880
0.0125
import numpy as np import scipy.interpolate import pylab pylab.ion() ########## #s = 128 # 2**7 s = 2**8 n, m = np.meshgrid(np.fft.fftshift(np.fft.fftfreq(s)) * s, np.fft.fftshift(np.fft.fftfreq(s)) * s) kappa = np.zeros([s, s]) kappa[int(s / 2.), int(s / 2.)] = 100. kappa[int(s / 4.), int(s / 4.)] = 100. #r = np...
phi, axis=1), axis=1)) #rho += (np.sum(kappa) - np.sum(rho)) / s**2 pylab.figure() #pylab.pcolor(np.gradient(phi, axis=0), cmap='binary') #pylab.contourf(n, m, np.gradient(phi, axis=0), 100, cmap='binary') pylab.contourf(
n, m, rho, 100, cmap='binary') pylab.colorbar() #pylab.xlim(0., s) #pylab.ylim(0., s) pylab.xlim(-s / 2, s / 2) pylab.ylim(-s / 2, s / 2) # Now do the ray-tracing n_trace = 10000000 x = np.random.uniform(-s / 2, s / 2, n_trace) y = np.random.uniform(-s / 2, s / 2, n_trace) #x = np.random.uniform(-10., 10., n_trace) ...
ActiveState/code
recipes/Python/286155_Entering_accented_characters_Tkinter/recipe-286155.py
Python
mit
3,210
0.001558
from Tkinter import * from ScrolledText import Sc
rolledText from unicodedata import loo
kup import os class Diacritical: """Mix-in class that adds keyboard bindings for accented characters, plus other common functionality. An inheriting class must define a select_all method that will respond to Ctrl-A.""" accents = (('acute', "'"), ('grave', '`'), ('circumflex', '^'), ...
jstoja/TsinghuaMailSystem
src/com/mailsystem/services/UserService.py
Python
mit
1,800
0.009444
from sqlalchemy.orm import eagerload_all from src.com.mailsystem.orm import User class UserService: @staticmethod def listAll(db_users): s = db_users.session() ret = s.query(User).all() s.close() return ret @staticmethod def selectById(db_users, iduserthu): s = ...
ret = s.query(User)
.options(eagerload_all('addresses')).get(iduserthu) s.close() return ret @staticmethod def selectByStudentnumber(db_users, studentnumber): s = db_users.session() ret = s.query(User).options(eagerload_all('addresses')).filter(User.__table__.c.studentnumber == studentnumber).one()...
jacquesqiao/Paddle
python/paddle/fluid/tests/unittests/test_dist_transpiler.py
Python
apache-2.0
20,013
0.0003
# Copyright (c) 2018 PaddlePaddle 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 app...
["listen_and_serv"]) # block1~2: optimize pass self.assertEqual([op.type for op in pserver.blocks[1].ops], ["sum", "scale", "sgd"]) # confirm startup program self.assertEqual([op.type for op in startup.global_block().ops], [...
be split into two blocks fc_w_var = startup2.global_block().var("fc_w") self.assertEqual(fc_w_var.shape, (1000L, 1000L)) # all parameters should be optimized on pserver pserver_params = [] for prog in [pserver, pserver2]: for blk in prog.blocks: for o...
demisto/content
Packs/EWS/Integrations/EWSv2/EWSv2_test.py
Python
mit
10,212
0.00284
import datetime import EWSv2 import logging import dateparser import pytest from exchangelib import Message from EWSv2 import fetch_last_emails from exchangelib import EWSDateTime, EWSTimeZone class TestNormalCommands: """ """ class MockClient: class MockAccount: def __init__(self...
lass MockInbox: class parent: def __init__(self): self.children = "" def __init__(self): self.parent = self.parent() def get_folder_by_path(self, path, account=None,
is_public=False): return "" def test_keys_to_camel_case(): assert EWSv2.keys_to_camel_case('this_is_a_test') == 'thisIsATest' # assert keys_to_camel_case(('this_is_a_test', 'another_one')) == ('thisIsATest', 'anotherOne') obj = {} obj['this_is_a_value'] = 'the_value' obj['this_is_a_lis...
hedvig/project-config
jenkins/scripts/project-requirements-change.py
Python
apache-2.0
10,166
0.00059
#! /usr/bin/env python # Copyright (C) 2011 OpenStack, LLC. # Copyright (c) 2013 Hewlett-Packard Development Company, L.P. # Copyright (c) 2013 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the
License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-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...
rse import collections import contextlib import os import shlex import shutil import subprocess import sys import tempfile requirement = None project = None def run_command(cmd): print(cmd) cmd_list = shlex.split(str(cmd)) p = subprocess.Popen(cmd_list, stdout=subprocess.PIPE, s...
RedHatInsights/insights-core
insights/core/dr.py
Python
apache-2.0
32,029
0.000781
""" This module implements an inversion of control framework. It allows dependencies among functions and classes to be declared with decorators and the resulting dependency graphs to be executed. A decorator used to declare dependencies is called a :class:`ComponentType`, a decorated function or class is called a comp...
t) DEPENDENTS = defaultdict(set) COMPONENTS = defaultdict(lambda: defaultdict(set)) DELEGATES = {} HIDDEN = set() IGNORE = defaultdict(set) ENABLED = defaultdict(lambda: True) def set_enabled(component, enabled=True): """ Enable a component for evaluation. If set to False, the component is skipped, and a...
f the callable object itself, the component's module is loaded as a side effect of calling this function. Args: component (str or callable): fully qualified name of the component or the component object itself. enabled (bool): whether the component is enabled for evaluation. Re...
ffu/DSA-3.2.2
grc/base/Port.py
Python
gpl-3.0
2,557
0.024638
""" Copyright 2008, 2009 Free Software Foundation, Inc. This file is part of GNU Radio GNU Radio Companion 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 ...
type(self): return self.get_parent().resolve_dependencies(self._type) def get_connections(self): """ Get all connections that use this port. @return a list of connection objects """ connections = self.get_parent().get_parent().get_connections() connections = filter(lambda c: c.get_source() is self or c.ge...
def get_enabled_connections(self): """ Get all enabled connections that use this port. @return a list of connection objects """ return filter(lambda c: c.get_enabled(), self.get_connections())
aaronkhoo/aws-config-rules
python/ec2_require_tags_with_valid_values.py
Python
cc0-1.0
3,341
0.003292
# # This file made available under CC0 1.0 Universal (https://creativecommons.org/publicdomain/zero/1.0/legalcode) # # Ensure that resources have required tags, and that tags have valid values. # # Trigger Type: Change Triggered # Scope of Changes: EC2:Instance # Accepted Parameters: requiredTagKey1, requiredTagValues1...
if not tag["value"] in required_tags["requiredTagValues"+str(x)].split(','): return "Tag '"
+ required_tags["requiredTagKey"+str(x)] + "' value '" + tag["value"] + "' is not a valid value." if not tag_present: return "Tag '" + required_tags["requiredTagKey"+str(x)] + "' is not present." return None def evaluate_compliance(configuration_item, rule_parameters): if configuration_ite...
NoUsername/samsungremote
autodiscover.py
Python
mit
2,377
0.011359
import logging import socket from six.moves import http_client from six.moves.urllib import parse from six import BytesIO from six import b, u class SSDPResponse(object): class _FakeSocket(BytesIO): def makefile(self, *args, **kw): return self def __init__(self, response): r = http...
("st") self.cache = r.getheader("cache-control").split("=")[1] def __repr__(self): return "<SSDPResponse({location}, {st}, {usn})>".format(**self.__dict__) def discover(service, localIp, timeout=2, retries=1): group = ("239.255.255.250", 1900) messag
e = "\r\n".join([ 'M-SEARCH * HTTP/1.1', 'HOST: {0}:{1}', 'MAN: "ssdp:discover"', 'ST: {st}','MX: 3','','']) socket.setdefaulttimeout(timeout) responses = {} for _ in range(retries): sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) #...
rchaudhari/hadoop_learning
wc_streaming/reducer.py
Python
unlicense
1,158
0.002591
#!/usr/bin/env python #This example is original obtained from # http://www.michael-noll.com/tutorials/writing-an-hadoop-mapreduce-program-in-python/ from operator import itemgetter import sys current_word = None current_count = 0 word = None # input comes from STDIN for line in sys.stdin: # remove leading and...
# ignore/discard this line continue # this IF-switch only works because Hadoop sorts map output # by key (here: word) before
it is passed to the reducer if current_word == word: current_count += count else: if current_word: # write result to STDOUT print '%s\t%s' % (current_word, current_count) current_count = count current_word = word # do not forget to output the last word i...
DailyActie/Surrogate-Model
01-codes/scikit-learn-master/sklearn/utils/tests/test_validation.py
Python
mit
18,596
0.000376
"""Tests for input validation functions""" import warnings from itertools import product from tempfile import NamedTemporaryFile import numpy as np import scipy.sparse as sp from nose.tools import assert_raises, assert_true, assert_false, assert_equal from numpy.testing import assert_array_equal from sklearn.datasets...
e(4).reshape(2, 2).astype(np.float) X_inf[0, 0] = np.inf assert_raises(ValueE
rror, check_array, X_inf) check_array(X_inf, force_all_finite=False) # no raise # nan check X_nan = np.arange(4).reshape(2, 2).astype(np.float) X_nan[0, 0] = np.nan assert_raises(ValueError, check_array, X_nan) check_array(X_inf, force_all_finite=False) # no raise # dtype and order enforc...
davemerwin/django-oneforty
setup.py
Python
bsd-3-clause
1,060
0.003774
from setuptools import setup, find_packages setup( name='django-oneforty', version=__import__('oneforty').__version__, description='django-oneforty is designed to be a simple, lightweight status/update engine.', long_descri
ption=open('README.txt').read(), author='Pure Blue Inc', author_email='dave@purebluedesign.com', url='http://github.com/davemerwin/django-oneforty/tree/master', download_url='http://github.com/davemerwin/django-oneforty/archives/master', license='BSD', packages=find_packages(exclude=['ez_setup']...
us :: 1 - Beta', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Librari...
sb1992/NETL-Automatic-Topic-Labelling-
training/doc2vectrain.py
Python
apache-2.0
3,504
0.014269
""" Author: Shraey Bhatia Date: October 2016 File: doc2vectrain.py Gives a trained document vectors model (also known as Doc2VecModel). The input format are documents extrated using wiki extractor and tokenized using stanford tokenizer stored in a directory Output would be a trained doc2ve...
doc" not in line: #</doc tells us end of document, till not reached it is same document
for word in line.split(" "): values.append(word.strip()) if "</doc" in line: if found!= "": yield LabeledSentence(words = values, tags = [found]) ...
nicholas-moreles/blaspy
bp_unit_tests/level_1/unit_test_dot.py
Python
bsd-3-clause
6,815
0.000147
""" Copyright (c) 2014-2015, The University of Texas at Austin. All rights reserved. This file is part of BLASpy and is available under the 3-Clause BSD License, which can be found in the LICENSE file at the top-level directory or at http://opensource.org/licenses/BSD-3-Clause """ from blaspy im...
_for_y_raises_ValueError(self): x = array([[1.]]) y = 2. self.assertRaises(ValueError, dot, x, y) def test_not_2
d_numpy_with_1d_for_x_raises_ValueError(self): x = array([1., 2., 3.]) y = array([[3., 2., 1.]]) self.assertRaises(ValueError, dot, x, y) def test_not_2d_numpy_with_1d_for_y_raises_ValueError(self): x = array([[1., 2., 3.]]) y = array([3., 2., 1.]) self.assertRaises(...
MahjongRepository/mahjong
mahjong/hand_calculating/yaku_list/daburu_open_riichi.py
Python
mit
494
0
from mahjong.hand_calculating.yaku import Yaku class DaburuOpenRiichi(Yaku): """ Yaku situation """ def __init__(self, yaku_id): super(DaburuOpenRiichi, self).__
init__(yaku_id) def set_attributes(self): self.name = "Double Open Riichi" self.han_open = None self.han_closed =
3 self.is_yakuman = False def is_condition_met(self, hand, *args): # was it here or not is controlling by superior code return True
calroc/AVRV
instructions.py
Python
gpl-3.0
6,667
0.022199
from util import A, B, B_reversed, C, D, E, F, G, H, instr, spec, spec_reversed _mark = set(dir()) ; _mark.add('_mark') @A def jmp(address): ''' 1001 010k kkkk 110k kkkk kkkk kkkk kkkk ''' def cli(): return 16, 0b1001010011111000 @B def ldi(register, immediate): ''' 1110 KKKK dddd KKKK ''' @C ...
d rrrr ''' @A def brsh(address): ''' 1111 01kk kkkk k000 ''' @D def movw(Rd, Rr): ''' 0000 0001 dddd rrrr ''' @B def andi(register, immediate): ''' 0111 KKKK dddd KKKK ''' @H def sbis(register,
bit): ''' 1001 1011 AAAA Abbb ''' @G def clr(Rd): ''' 0010 01dd dddd dddd ''' @F def push(Rr): ''' 1001 001r rrrr 1111 ''' @G def pop(Rd): ''' 1001 000d dddd 1111 ''' @D def or_(Rd, Rr): ''' 0010 10rd dddd rrrr ''' @G def swap(Rd): ''' 1001 010d dddd 0010 ''' @B def adiw...
boegel/easybuild-easyblocks
easybuild/easyblocks/s/samcef.py
Python
gpl-2.0
4,106
0.003166
## # Copyright 2015-2021 Ghent University # # This file is part of EasyBuild, # originally created by the HPC team of Ghent University (http://ugent.be/hpc/en), # with support of Ghent University (http://ugent.be/hpc), # the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be), # Flemish Research Foundation (F...
tment of Economy, Science and Innovation (EWI) (http://www.ewi-vlaanderen.be/en). # # https://github.com/easybuilders/easybuild # # EasyBuild 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 v2. # # EasyBuild is...
R PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with EasyBuild. If not, see <http://www.gnu.org/licenses/>. ## """ EasyBuild support for building and installing Samcef, implemented as an easyblock @author: Kenneth Hoste (...
poojavade/Genomics_Docker
Dockerfiles/gedlab-khmer-filter-abund/pymodules/python2.7/lib/python/ipython-2.2.0-py2.7.egg/IPython/html/services/notebooks/filenbmanager.py
Python
apache-2.0
18,231
0.004278
"""A notebook manager that uses the local file system for storage. Authors: * Brian Granger * Zach Sailer """ #----------------------------------------------------------------------------- # Copyright (C) 2011 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is in...
tebook dir and path.""" path = path.strip('/') if not os.path.isdir(self._get_os_path(path=path)): raise
web.HTTPError(404, 'Directory not found: ' + path) names = glob.glob(self._get_os_path('*'+self.filename_ext, path)) names = [os.path.basename(name) for name in names] return names def path_exists(self, path): """Does the API-style path (directory) actually exist? ...
dentaku65/plugin.video.sod
channels/leserietv.py
Python
gpl-3.0
12,830
0.002495
# -*- coding: utf-8 -*- # ------------------------------------------------------------ # streamondemand.- XBMC Plugin # Canal para itafilmtv # http://blog.tvalacarta.info/plugin-xbmc/streamondemand. # By Costaplus # ------------------------------------------------------------ import re import urlparse impor...
ovità") itemlist = [] data = scrapertools.cache_page(item.url) patron = '<div class="video-item-cover"[^<]+<a href="(.*?)">[^<]+<img src="(.*?)" alt="(.*?)">' matches = re.compile(patron, re.DOTALL).findall(data) scrapertools.printMatches(matches) for scrapedurl, scrapedthumbnail, sc...
if (DEBUG): logger.info( "title=[" + scrapedtitle + "], url=[" + scrapedurl + "], thumbnail=[" + scrapedthumbnail + "]") itemlist.append(infoSod( Item(channel=__channel__, action="episodi", title="[COLOR azure]" + scrapedtitle + "[/COLOR]", ...
marcosgabarda/django-belt
belt/files.py
Python
mit
1,514
0.001982
import hashlib import os import random import time from django.utils.deconstruct import deconstructible from django.utils.text import slugify
@deconstructible class UploadToDir(object): """Generates a function to give to ``upload
_to`` parameter in models.Fields, that generates an name for uploaded files based on ``populate_from`` attribute. """ def __init__(self, path, populate_from=None, prefix=None, random_name=False): self.path = path self.populate_from = populate_from self.random_name = random_name ...
dknlght/dkodi
src/plugin.video.animehere/servers/depositfiles.py
Python
gpl-2.0
2,041
0.020598
# -*- coding: utf-8 -*- #------------------------------------------------------------ # pelisalacarta - XBMC Plugin # Conector para depositfiles # http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/ #------------------------------------------------------------ import urlparse,urllib2,urllib,re import os from core ...
er.info("[depositfiles.py] test_video_exists(page_url='%s')" % page_url) # Existe: http://depositfiles.com/files/vmhjug6t7 # No existe: data = scrapertools.
cache_page(page_url) patron = 'Nombre del Archivo: <b title="([^"]+)">([^<]+)</b>' matches = re.compile(patron,re.DOTALL).findall(data) if len(matches)>0: return True,"" else: patron = '<div class="no_download_msg">([^<]+)<' matches = re.compile(patron,re.DOTALL).findall(d...
hipsterware/scoreline
toys/corpscore.py
Python
agpl-3.0
2,066
0.005324
#!/usr/bin/env python import csv import json import sys import click def score(company, sexbiases): """ Given a company record with board of directors and executive names, return our guess of the % of governance that is male. Since names are not always unambiguous determinants of sex, we also r...
})
sys.stdout.flush() if __name__ == '__main__': corpscore()
wbyne/QGIS
python/plugins/processing/algs/help/__init__.py
Python
gpl-2.0
2,053
0.000487
# -*- coding: utf-8
-*- """ *************************************************************************** __init__.py --------------------- Date : January 2016 Copyrigh
t : (C) 2016 by Victor Olaya Email : volayaf at gmail dot com *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * ...
ctrlaltdel/neutrinator
vendor/openstack/tests/unit/compute/v2/test_service.py
Python
gpl-3.0
3,503
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 writing, software # distributed under t...
s.put.assert_called_with( url, json=body) def test_enable(self): sot = service.Service(**EXAMPLE) res = sot.enable(self.sess, 'host1', 'nova-compute') self.assertIsNone(res.body) url = 'os-services/enable' body = { 'binary': 'nova-compute', ...
disable(self.sess, 'host1', 'nova-compute') self.assertIsNone(res.body) url = 'os-services/disable' body = { 'binary': 'nova-compute', 'host': 'host1', } self.sess.put.assert_called_with( url, json=body) def test_disable_with_reason(self)...
bmwachajr/bucketlist
application/resource_urls.py
Python
mit
733
0.002729
from flask_restful import Api from application import app from application.resources.v1.auth import Login, Register from application.resources.v1.bucketlists import Bucketlists, BucketlistResource from application.resources.v1.items import Items, ItemResource def load_urls(api): api.add_resource(Login, "/auth/log...
lists, "/bucketlists/") api.add_resource(Bucketl
istResource, "/bucketlists/<int:id>") api.add_resource(Items, "/bucketlists/<int:id>/items/") api.add_resource(ItemResource, "/bucketlists/<int:id>/items/<int:item_id>") @app.errorhandler(404) def page_not_found(e): return "Not found, Please check your request", 404
anthropo-lab/XP
privacy_project/privacy_value/pages.py
Python
gpl-3.0
3,067
0.002934
from otree.api import Currency as c, currency_range from ._builtin import Page, WaitPage from .models import Constants import time ################################################# ################################################# class GeneralInstructions(Page): timeout_seconds = 120 form_model = 'player' ...
# Manage the javascript time_out: Don't fill any data pass else: # Set the last activity time_stamp self.player.participant.vars['active_flag'] = time.time() class Choice_2(Page): timeout_seconds = 180 form_model = 'player' form_fields = ['response_1',...
_9', 'response_10', 'response_11', 'response_12', 'response_13', 'response_14', 'response_15', 'response_16', 'response_17', 'response_18', 'response_19'] def is_displayed(self): return (self.player.agreement == "accord") & (self.player.treatment == Constants.c_treatme...
koljonen/pgcli
release.py
Python
bsd-3-clause
2,731
0
#!/usr/bin/env python from __future__ import print_function import re import ast import subprocess import sys from optparse import OptionParser DEBUG = False CONFIRM_STEPS = False DRY_RUN = False def skip_step(): """ Asks for user's response whether to run a step. Default is yes. :return: boolean """...
sion_re = re.compile(r'__version__\s+=\s+(.*)') with open(version_file, 'rb') as f: ver =
str(ast.literal_eval(_version_re.search( f.read().decode('utf-8')).group(1))) return ver def commit_for_release(version_file, ver): run_step('git', 'reset') run_step('git', 'add', version_file) run_step('git', 'commit', '--message', 'Releasing version %s' % ver) def create_git_tag(tag_...
ksuarz/mongo-monary-driver
timing/profile.py
Python
apache-2.0
429
0.009324
# Monary - Copyright 2011-2013 David J. C. Beach # Please see the included LICENSE.TXT and NOTICE.TXT for licensing information. from t
ime import time class profile(object): def __init__(self, name): self._name = name def __enter__(self): self._start = time() def __exit__(self, *args): stop = t
ime() print "%s took %6.2f s" % (self._name, stop - self._start)
gpmidi/MCEdit-Unified
editortools/editortool.py
Python
isc
8,663
0.001501
from OpenGL import GL import numpy from depths import DepthOffset from pymclevel import BoundingBox from config import config from albow.translate import _ class EditorTool(object): surfaceBuild = False panel = None optionsPanel = None toolIconName = None worldTooltipText = None previewRendere...
nt=1, blocksOnly=F
alse): pass def flip(self, amount=1, blocksOnly=False): pass def mirror(self, amount=1, blocksOnly=False): pass def swap(self, amount=1): pass def mouseDown(self, evt, pos, direction): '''pos is the coordinates of the block under the cursor, direction ...
pombredanne/SourceForge-Allura
ForgeBlog/forgeblog/tests/unit/__init__.py
Python
apache-2.0
1,126
0.008881
from pylons import c from ming.orm.ormsession import ThreadLocalORMSession from allura.websetup import bootstrap from allura.lib import helpers as h from allura.lib import plugin from allura import model as M from alluratest.controller import setup_basic_test def setUp(): setup_basic_test() class BlogTestWithMo...
oogle_analytics = False)) project_reg.register_neighborhood_project(neighborhood, [c.user]) c.project = neighborhood.register_project('test', c.user) c.project.install_app('Blog', 'blog') ThreadLocalORMSession.flush_all() h.set_context('test', 'blog', neighborhood='Projects') ...
sion.close_all()
Joshuaalbert/IonoTomo
src/ionotomo/tests/test_turbulent_realisation.py
Python
apache-2.0
5,260
0.042966
from ionotomo import * import numpy as np import pylab as plt def test_turbulent_realisation(plot=True): xvec = np.linspace(-100,100,100) zvec = np.linspace(0,1000,1000) M = np.zeros([100,100,1000]) TCI = TriCubic(xvec,xvec,zvec,M) print("Matern 1/2 kernel") cov_obj = Covariance(tci=TCI) si...
,j,k] = 1. stencil /= (dx*dy*dz)**(2./3.) lap = ndimage.convolve(phi,stencil,mode='wrap') phih -= 2/corr*lap laplap = ndimage.convolve(lap,stencil,mode='wrap') phih += corr*laplap phih /= 8*np.pi*sigma**2 if plot: f = plt.figure(figsize=(12,12)) ...
,3,2) ax.set_title("FFT based") im = plt.imshow(phihat[50,:,:],extent=(z[0],z[-1],x[0],x[-1])) plt.colorbar(im) ax = f.add_subplot(3,3,3) ax.set_title("Analytic") im = plt.imshow(phih[50,:,:],extent=(y[0],y[-1],x[0],x[-1])) plt.colorbar(im) ax = f.a...
gyang/horizon
horizon/dashboards/nova/images_and_snapshots/snapshots/forms.py
Python
apache-2.0
2,323
0.00043
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 United States Government as represented by the # Administrator of the National Aeronautics a
nd Space Administration. # A
ll Rights Reserved. # # Copyright 2012 Nebula, 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 a...
updatengine/updatengine-server
configuration/migrations/0003_auto__add_field_deployconfig_activate_time_deploy__add_field_deploycon.py
Python
gpl-2.0
2,136
0.004682
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'deployconfig.activate_time_deploy' db.add_column('configuration_deployconfig', 'activate_tim...
b.delete_column('configuration_deployconfig', 'start_time') # Deleting field 'deployconfig.end_time' db.delete_column('configuration_deployconfig', 'end_time') models = { 'configuration.deployconfig': { 'Meta': {'object_name': 'deployconfig'},
'activate_deploy': ('django.db.models.fields.CharField', [], {'default': "'yes'", 'max_length': '3'}), 'activate_time_deploy': ('django.db.models.fields.CharField', [], {'default': "'yes'", 'max_length': '3'}), 'end_time': ('django.db.models.fields.TimeField', [], {}), 'id...
jsirois/pants
src/python/pants/core/goals/test_test.py
Python
apache-2.0
11,226
0.001069
# Copyright 2018 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from abc import ABCMeta, abstractmethod from dataclasses import dataclass from functools import partial from textwrap import dedent from typing import List, Optional, Tuple, Type import p...
) def test_debug_target(rule_runner: RuleRunner) -> None: exit_code, _ = run_test_rule( rule_runner, field_set=SuccessfulFieldSet, targets=[make_target()], debug=True, ) assert exit_code == 0 def test_coverage(rule_runner: RuleRunner) -> None: addr1 = Address("", ta...
rr = run_test_rule( rule_runner,
pacoqueen/ginn
ginn/formularios/confirmings.py
Python
gpl-2.0
54,543
0.013784
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### # Copyright (C) 2005-2008 Francisco José Rodríguez Bogado, # # Diego Muñoz Escalante. # # (pacoqueen@users.sourceforge.ne...
else: self.ir_a(objeto) gtk.main() # --------------- Funciones auxiliares ------------------------------ def dividir_confirming(self, boton): """ Divide el confirming actual creando uno idéntico pero haciendo corresponder a cada uno de ellos la mitad del importe ...
imientos asociados dividiendo el importe en 2. """ if utils.dialogo(titulo = "¿DIVIDIR CONFIRMING?", texto = "Se procederá a dividir el confirming actual" " en dos.\nAmbos serán idénticos y tendrán c" "o...
Morphux/installer
pythondialog/dialog.py
Python
apache-2.0
155,394
0.000792
# dialog.py --- A Python interface to the ncurses-based "dialog" utility # -*- coding: utf-8 -*- # # Copyright (C) 2002-2004, 2009-2010, 2013-2016 Florent Rougon # Copyright (C) 2004 Peter Åstrand # Copyright (C) 2000 Robb Shecter, Sultanbek Tezadov # # This library is free software; you can redistribute it and/or #...
ld have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foun
dation, Inc., 51 Franklin St, Fifth Floor, Boston, # MA 02110-1301 USA. """Python interface to :program:`dialog`-like programs. This module provides a Python interface to :program:`dialog`-like programs such as :program:`dialog` and :program:`Xdialog`. It provides a :class:`Dialog` class that retains some parameter...
MediaMath/t1-python
tests/test_budgetflights.py
Python
apache-2.0
3,209
0.002493
from __future__ import absolute_import import unittest import responses import requests from .requests_patch import patched_extract_cookies_to_jar from terminalone import T1 mock_credentials = { 'username': 'user', 'password': 'password', 'api_key': 'api_key', } API_BASE = 'api.mediamath.com' requests.se...
sts/fixtures/json/budgetflight_array_single.json') as f: fixture = f.read() with open('tests/fixtures/json/budgetflight_single.json') as f: singlefixture = f.read() responses.add(responses.GET, 'https://api.mediamath.com/api/v2.0/campaigns/11111/budget_flights', ...
igns/11111/budget_flights/12345', body=singlefixture, content_type='application/json') bfs = self.t1.get('campaigns', 11111, 'budget_flights') bf = next(bfs) bf.total_budget = 101 bf.save() self.assertTrue('total_budget=101.0' in respon...
lshuo/WC2014_bet
src/set_zhihu_point_table.py
Python
apache-2.0
2,291
0.035356
import cPickle point_table = {} point_table[( 4, 4)] = 400. point_table[( 3, 4)] = 270. point_table[( 2, 4)] = 170. point_table[( 1, 4)] = 100. point_table[( 0, 4)] = 0. point_table[(-1, 4)] = 0. point_table[(-2, 4)] = 0. point_table[(-3, 4)] = 0. point_table[(-4, 4)] = 0. point_table[( 4, 3)] = 240. point_table[( 3,...
e[( 0,-2)] = 10. point_table[(-1,-2)] = 160. point_table[(-2,-2)] = 240. point_table[(-3,-2)] = 180. point_table[(-4,-2)] = 140. point_table[( 4,-3)] = 0. point_table[( 3,-3)] = 0. point_table[( 2,-3)] = 0. point_table[( 1,-3)] = 0. point_table[( 0,-3)] = 0. point_table[(-1,-3)] = 120. point_table[(-2,-3)] = 200. poin...
table[( 3,-4)] = 0. point_table[( 2,-4)] = 0. point_table[( 1,-4)] = 0. point_table[( 0,-4)] = 0. point_table[(-1,-4)] = 100. point_table[(-2,-4)] = 170. point_table[(-3,-4)] = 270. point_table[(-4,-4)] = 400. cPickle.dump(point_table, open('../data/point_table.cpickle', 'wb'))
NUinfolab/context
web/stakeholders.py
Python
mit
5,364
0.002983
import copy import re import string from connection import _cached_users from context.nlp.entities import name_tokens, best_matches from context.nlp.util import tokenize from context.services import discover_twitter_users_via_bing from context.services.twitter import get_timeline, discover_users ALNUM_PAT = re.compil...
eyetv' 'larrygallup', 'latimes', 'latvives', 'newsweek', 'nytimes', 'obamainaugural', 'reuters', 'sam_schaefer', 'tpm', 'washingtonpost', ) UNAMBIGUOUS_MEDIA_NAME_TOKENS = ( 'bb
c', 'bloomberg', 'cnn', 'herald', 'nbc', 'news', 'nytimes', 'reuters', 'telegram', 'tribune', 'tv', ) SKIP_TOKENS = \ [l for l in string.ascii_lowercase] + \ ['mr', 'mrs', 'miss', 'ms', 'dr', 'rev', 'reverend', 'sir', 'sr', 'jr', 'mayor', 'president', 'chief', 'gov',...
ULHPC/easybuild-easyblocks
easybuild/easyblocks/b/binutils.py
Python
gpl-2.0
8,639
0.003936
## # Copyright 2009-2017 Ghent University # # This file is part of EasyBuild, # originally created by the HPC team of Ghent University (http://ugent.be/hpc/en), # with support of Ghent University (http://ugent.be/hpc), # the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be), # Flemish Research Foundation (F...
run_cmd from easybuild.tools.systemtools import get_shared_lib_ext from easybuild.tools.toolchain import DUMMY_TOOLCHAIN_NAME class EB_binutil
s(ConfigureMake): """Support for building/installing binutils.""" @staticmethod def extra_options(extra_vars=None): """Extra easyconfig parameters specific to the binutils easyblock.""" extra_vars = ConfigureMake.extra_options(extra_vars=extra_vars) extra_vars.update({ '...
skyoo/jumpserver
apps/users/migrations/0025_auto_20200206_1216.py
Python
gpl-2.0
534
0.001873
# Generated by Django 2.2.10 on 2020-02-06 04:16 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('users', '0024_au
to_20191118_1612'), ] operations = [ migrations.AlterField( model_name='user', name='source', field=models.CharField(choices=[('local', 'Local'), ('ldap', 'LDAP/AD')
, ('openid', 'OpenID'), ('radius', 'Radius'), ('cas', 'CAS')], default='local', max_length=30, verbose_name='Source'), ), ]
MostlyOpen/odoo_addons_jcafb
myo_annotation_cst/models/annotation_seq.py
Python
agpl-3.0
1,352
0.002219
# -*- coding: utf-8 -*- ############################################################################### # # Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol # # 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 #...
############################ from openerp import models, fields class Annotation(models.Model): _inherit = 'myo.annotation' # code = fields.Char('Code', index=True, required=False, readonly=False, default=False, # help='Use "/" to get an automatic new Annotation Code.') code = fie...
an automatic new Annotation Code.')
raincoatrun/basemap
examples/barb_demo.py
Python
gpl-2.0
2,853
0.044515
from mpl_toolkits.basemap import Basemap import numpy as np import matplotlib.pyplot as plt # read in data. file = open('fcover.dat','r') ul=[];vl=[];pl=[] nlons=73; nlats=73 dellat = 2.5; dellon = 5. for line in file.readlines(): l = line.replace('\n','').split() ul.append(float(l[0])) vl.append(float(l[1]))...
hic projection. m = Basemap(width=10000000,height=10000000,lon_0=-90,lat_0=45.,lat_ts=45, resolution='l',projection='stere') x,y = m(lons,lats) # transform from spherical to map projection coordinates (rotation # and
interpolation). nxv = 25; nyv = 25 udat, vdat, xv, yv = m.transform_vector(u,v,lons1,lats1,nxv,nyv,returnxy=True) # create a figure, add an axes. fig=plt.figure(figsize=(8,6)) ax = fig.add_axes([0.1,0.1,0.8,0.8]) # plot color-filled contours over map levs = np.arange(960,1051,4) cs1 = m.contour(x,y,p,levs,colors='k',li...
wuhengzhi/chromium-crosswalk
content/test/gpu/gpu_tests/context_lost_expectations.py
Python
bsd-3-clause
1,984
0.001512
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from gpu_tests.gpu_test_expectations import GpuTestExpectations # See the GpuTestExpectations class for documentation. class ContextLostExpectations(GpuTes...
omplete self.Fail('ContextLost.WebGLContextLostFromLoseContextExtension', ['android', ('qualcomm', 'Adreno (TM) 420')], bug=611906) self.Fail(
'ContextLost.WebGLContextLostFromQuantity', ['android', ('qualcomm', 'Adreno (TM) 420')], bug=611906)
bb111189/CryptoKnocker
CryptoKnocker/CryptoKnocker/urls.py
Python
mit
970
0.005155
from django.conf.urls import patterns, include, url from django.contrib import admin from django.conf import settings admin.autodiscover() urlpatterns = patterns
('', # Examples: # url(r'^$', 'CryptoKnocker.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admi
n.site.urls)), url(r'^$', include("mainpage.urls")), url(r"^login/$", "mainpage.views.login_form"), url(r'^management/$', "management.views.index"), url(r'^management/login$', "management.views.user_login"), url(r'^logout/$', "management.views.user_logout"), url(r'^management/registration/$', "m...
ellxc/piperbot
plugins/weather.py
Python
gpl-2.0
8,113
0.009501
# Get weather data from various online sources # -*- coding: utf-8 -*- import requests from wrappers import * @plugin class yweather: @command("weather") def weather(self, message): """Get the current condition in a given location, from the Yahoo! Weather Service """ w = self.get_yaho...
nits']['temperature']) forecast = [] for pred in channel['item']['forecast']: c = {"day": pred['day'], "condition": pred['text'],
"high": "{0}°{1}".format(pred['high'], channel['units']['temperature']), "low": "{0}°{1}".format(pred['low'], channel['units']['temperature'])} forecast.append(c) return {"city":city, "country":country, "region":region, "hi...
OCA/business-requirement
business_requirement_sale/models/__init__.py
Python
agpl-3.0
156
0
# License AGPL-3.0 or later (https://www.gnu.org/licenses/ag
pl). from . import business_requirement from . import sale_order_
line from . import sale_order
feist/pcs
pcs/common/file.py
Python
gpl-2.0
6,496
0.000154
from collections import namedtuple import fcntl import os import shutil from pcs.common.tools import format_os_error # TODO add logging (logger / debug reports ?) to the RawFile class; be aware # the class is used both in pcs.cli and pcs.lib packages FileMetadata = namedtuple( "FileMetadata", [ "file...
lf.metadata.path, self.metadata.owner_user_name, self.metadata.owner_group_name, ) except LookupError as e: raise RawFileError( self.metadata, RawFileError.ACTION_CHOWN...
awFileError( self.metadata, RawFileError.ACTION_CHOWN, format_os_error(e), ) from e if self.metadata.permissions is not None: try: os.chmod(my_file.fil...
hhkaos/reiniciador
members/middleware/__init__.py
Python
gpl-2.0
752
0
# myapp/middleware/__init__.py from django.core.exceptions import SuspiciousOperation from django.views.defaults import server_error class SquashInvalidHostMiddleware(object): """ Middleware class to squash errors due to suspicious Host: headers.
""" def process_request(self, request): """ Check for denied Hosts. """ try: # Attempt to obtain Host: from http header. This may elicit a # SuspiciousOperation if Host: doesn't match ALLOWED_HOSTS. # Unceremoniously squash these errors to p...
server_error(request)
awni/tensorflow
tensorflow/contrib/skflow/python/skflow/models.py
Python
apache-2.0
11,426
0.00175
"""Various high level TF models.""" # Copyright 2015-present The Scikit Flow 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/lice...
"_BW"): tmp, state_bw = tf.nn.rnn(cell_bw, _reverse_se
q(inputs, sequence_length), initial_state_bw, dtype, sequence_length) output_bw = _reverse_seq(tmp, sequence_length) # Concat each of the forward/backward outputs outputs = [
Blackflappybird/droneapi-python
setup.py
Python
apache-2.0
1,271
0.01967
from setuptools import setup, Extension import numpy as np import platform version = '0.1.3' ext_modules = [] setup (name = 'droneapi', zip_safe=True, version = version, description = 'Python language bindings for the DroneApi', long_description = '''Python language bindings for the Drone...
hub.com/diydrones/droneapi-python', author = '3D Robotics', install_requires = [ 'pymavlink', 'MAVProxy
>= 1.3.1', 'protobuf >= 2.5.0' ], author_email = 'kevinh@geeksville.com', classifiers=['Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: Ap...
haum/hms_twitter
hms_twitter/tests/test_twitter.py
Python
mit
130
0
import unittest
class FakeTests(unittest.TestCase): def test_trueness(self): self.assertEquals(True a
nd True, True)
timtadh/gitolite-manager
gitolite_manager/views/user.py
Python
agpl-3.0
7,934
0.00731
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' gitolite-manager Author: Tim Henderson Contact: tim.tadh@gmail.com, tadh@case.edu Copyright: 2013 All Rights Reserved, see LICENSE ''' import urllib, re import cgi from logging import getLogger log = getLogger('gm:view:user') from pyramid.view import view_config fro...
'user_name' : user, 'errors': err, }) try: key_controller.rm_key(db, session.user, int(match['keyid'])) except Exception, e: return tvars(request, { 'TITLE' : 'remove key for %s' % user, 'user_name' : user, 'errors': [str(e)], }...
artners', request_method=['GET'], renderer='templates/add-partner.html' ) def partners(request): db = request.environ['db.session'] session = request.environ['gm_session'] if session.user is None: return HTTPFound(request.application_url) email = session.user.email user = email[:ema...
emmuchira/kps_erp
erpnext/config/stock.py
Python
gpl-3.0
7,192
0.045884
from __future__ import unicode_literals from frappe import _ def get_data(): return [ { "label": _("Stock Transactions"), "items": [ { "type": "doctype", "name": "Stock Entry", "description": _("Record item movement."), }, { "type": "doctype", "name": "Delivery Note", ...
"fa fa-facetime-video", "items": [ { "type": "help", "label": _("Items and Pricing"), "youtube_id": "qXaEwld4_Ps" }, { "type": "help", "label": _("Item Variants"), "youtube_i
d": "OGBETlCzU5o" }, { "type": "help", "label": _("Opening Stock Balance"), "youtube_id": "0yPgrtfeCTs" }, { "type": "help", "label": _("Making Stock Entries"), "youtube_id": "Njt107hlY3I" }, { "type": "help", "label": _("Serialized Inventory"), "yout...
jakelever/knowledgediscovery
analysis/separate/jaccard.py
Python
mit
2,061
0.043668
import argparse from collections import defaultdict def calculateJaccardIndex(x,z,neighbours): shared = neighbours[x].intersection(neighbours[z]) combined = neighbours[x].union(neighbours[z]) return len(shared)/float(len(combined)) if __name__ == '__main__': parser = argparse.ArgumentParser(description='Calculate...
scores for a set of scores') parser.add_argument('--cooccurrenceFile',type=str,required=True,help='File containing cooccurrences') parser.add_argument('--occurrenceFile',type=str,required=True,help='File containing occurrences') parser.add_argument('--sentenceCount',type=str,required=True,help='File containing sente...
taining the raw ANNI vector data') parser.add_argument('--anniVectorsIndex',type=str,help='File containing the index for the ANNI vector data') parser.add_argument('--outFile',type=str,required=True,help='File to output scores to') args = parser.parse_args() print "Loading relationsToScore" relationsToScore = []...
Wireless-Innovation-Forum/Spectrum-Access-System
src/harness/reference_models/geo/zones_test.py
Python
apache-2.0
4,052
0.004195
# Copyright 2018 SAS Project 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 requ...
ers, 30) self.assertEqual(z['BATH'].minAzimuthDeg, 0) self.assertEqual(z['BATH'].maxAzimuthDeg, 360) self.assertEqual(z['BATH'].catBNeighborhoodDistanceKm, 240) def test_read_urban_areas(self)
: z = zones.GetUrbanAreas() exp_area = 275000 approx_area = z.area * 110**2 * np.cos(44*np.pi/180) self.assertTrue(z.is_valid) self.assertTrue(approx_area > exp_area * 0.9 and approx_area < exp_area * 1.1) def test_read_usborder(self): z = zones.GetUsBorder() self.asse...
timsavage/funktion-generator
utils/wave-editor/wave_editor/_ui/about_dialog.py
Python
bsd-3-clause
2,661
0.00451
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'resources/about_dialog.ui' # # Created: Sat Apr 8 00:53:02 2017 # by: pyside-uic 0.2.15 running on PySide 1.2.2 # # WARNING! All changes made in this file will be lost! from PySide import QtCore, QtGui class Ui_AboutDialog(object): ...
Layout = QtGui.QGridLayout(AboutDialog) self.gridLayout.setObjectName("gridLayout") self.label = QtGui.QLabel(AboutDialog) font = QtGui.QFont() font.setPointSize(14) font.setWeight(75) font.setBold(True) self.label.setFont(font) self.label.setTextFormat(Qt...
) self.label_2 = QtGui.QLabel(AboutDialog) self.label_2.setAlignment(QtCore.Qt.AlignBottom|QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft) self.label_2.setObjectName("label_2") self.gridLayout.addWidget(self.label_2, 2, 0, 1, 1) self.label_3 = QtGui.QLabel(AboutDialog) font =...
gynvael/zrozumiec-programowanie-cwiczenia
INT-int-to-negabinary-python/int-to-negabinary-coverter.py
Python
mit
1,451
0.004824
# The MIT License (MIT) # Copyright (c) 2017 Kinga Makowiecka # # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation file # (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify,...
ION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import mat
h import sys base = -2.0 result = "" number = int(sys.argv[1]) print "converting number " + str(number) + " to negabinary value:" while number != 0: ceilOfDivision = int(math.ceil(number / base)) reminder = int(number % base) result = result + str(int(math.fabs(reminder))) number = ceilOfDivision print...
iulian787/spack
var/spack/repos/builtin/packages/wps/package.py
Python
lgpl-2.1
3,952
0.000759
# Copyright 2013-2018 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 * import glob import tempfile class Wps(Package): """The Weather Research and Forecasting Pre-Pro...
" homepage = "https://www.mmm.ucar.edu/weather-research-and-forecasting-model" url = "https://git
hub.com/wrf-model/WPS/archive/v4.2.tar.gz" maintainers = ['MichaelLaufer'] version('4.2', sha256='3e175d033355d3e7638be75bc7c0bc0de6da299ebd175a9bbc1b7a121acd0168') # Serial variant recommended in WRF/WPS docs variant('build_type', default='serial', values=('serial', 'serial_NO_GRIB2', 'dm...
parksandwildlife/wastd
occurrence/serializers.py
Python
mit
14,367
0.001879
from django.apps import apps from rest_framework.serializers import SlugRelatedField, ModelSerializer, ValidationError from rest_framework_gis.serializers import GeoFeatureModelSerializer from rest_polymorphic.serializers import PolymorphicSerializer from taxonomy.models import Community, Taxon from occurrence.models ...
s_html", "source", "source_id", "status", "encountered_on", "encountered_by", "area_type", "accuracy", "northern_extent", ) geo_field = "point" class OccurrenceTaxonAreaEncounterPolyInlineSerializer(GeoFeatureModelSerializer): """Serializer
for Occurrence TaxonAreaEncounter to be used inline in TaxonSerializer. """ class Meta: exclude = ("taxon", ) model = TaxonAreaEncounter id_field = "id" geo_field = "geom" class OccurrenceTaxonAreaEncounterPolySerializer(GeoFeatureModelSerializer): """Serializer for Occurre...
dpniel/snapcraft
integration_tests/test_parts.py
Python
gpl-3.0
4,131
0
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*- # # Copyright (C) 2016-2017 Canonical Ltd # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in ...
"Description: A tool and a library (usable from many languages) " "for client side URL transfers, supporting FTP, FTPS, HTTP, " "HTTPS, TELNET, DICT, FILE and LDAP.\n\n") self.assertThat(output, Contains(expected_prefix)) idx = output.index(expected_prefix) + len(expe...
"curl": { "plugin": "autotools", "source": "http://curl.haxx.se/download/curl-7.44.0.tar.bz2", "source-type": "tar", "configflags": [ "--enable-static", "--enable-shared", "--disable-manu...
FibercorpLabs/FibercorpDevops
cisco/aci/createRoutedOutside.py
Python
gpl-3.0
3,646
0.003291
from cobra.model.l3ext import Out, RsEctx from cobra.model.bgp import ExtP as bgpExtP from cobra.model.ospf import ExtP as ospfExtP from cobra.model.tag import Inst from createMo import * DEFAULT_NONE = '' DEFAULT_NO = 'no' DEFAULT_OSPF_AREA_ID = 'None' CHOICES = [] def input_key_args(msg='\nPlease Specify Routed...
s.keys() else args l3ext_out = Out(fv_tenant, routed_outside_name) if 'private_network' in args.keys(): l3ext_rsectx = RsEctx(l3ext_out, tnFvCtx
Name=args['private_network']) if 'bgp' in args.keys() and args['bgp']: bgp_extp = bgpExtP(l3ext_out) if 'ospf' in args.keys() and args['ospf']: ospf_extp = ospfExtP(l3ext_out, areaId='0.0.0.' + str(get_value(args, 'ospf_area_id', '1'))) if 'tags' in args.keys() and is_valid(args['tags']): ...
ruffsl/ros_buildfarm
ros_buildfarm/status_page.py
Python
apache-2.0
38,413
0.000911
# Copyright 2014-2016 Open Source Robotics Foundation, 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 applicabl...
get_release_view_name from .common import get_short_arch from .common import Target from .config import get_index as get_config_index from .config import get_release_build_files from .debian_rep
o import get_debian_repo_data from .status_page_input import get_rosdistro_info from .status_page_input import RosPackage from .templates import expand_template from .templates import get_template_path def build_release_status_page( config_url, rosdistro_name, release_build_name, cache_dir, output_dir...
Havate/havate-openstack
proto-build/gui/horizon/Horizon_GUI/horizon/workflows/base.py
Python
apache-2.0
33,334
0.00012
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 Nebula, 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 # # ...
er the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See t
he # License for the specific language governing permissions and limitations # under the License. import copy import inspect import logging from django.core import urlresolvers from django import forms from django.forms.forms import NON_FIELD_ERRORS # noqa from django import template from django.template.defau...
apache/cloudstack-ec2stack
ec2stack/__init__.py
Python
apache-2.0
4,934
0.000203
#!/usr/bin/env python # encoding: utf-8 # # 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 Licens...
gister_blueprint(default_controller) return app def _generate_args(): """ Generate command line arguments for ec2stack-configure. @return: args. """ parser = argparse.ArgumentParser() parser.add_argument( '-p', '--profile', required=False, help='The profi...
l', default='initial' ) parser.add_argument( '-d', '--debug', required=False, help='Turn debug on for application', default=False ) args = parser.parse_args() return vars(args) def _load_config_file(): """ Checks that the user's configurat...
Alwnikrotikz/pebl-project
src/pebl/taskcontroller/xgrid.py
Python
mit
3,271
0.005809
import time import os.path import shutil import tempfile import cPickle try: import xg except: xg = False from pebl import config, result from pebl.taskcontroller.base import _BaseSubmittingController, DeferredResult class XgridDeferredResult(DeferredResult): def __init__(self, grid, task): ...
'Id of the grid to use at the Xgrid controller.', default='0' ), config.FloatParameter( 'xgrid.pollinterval', 'Time (in secs) to wait between polling the Xgrid controller.',
default=60.0 ), config.StringParameter( 'xgrid.peblpath', 'Full path to the pebl script on Xgrid agents.', default='pebl' ) ) def __init__(self, **options): """Create a XGridController. Any config param for 'xgrid' can be passe...
Yuriy-Leonov/nova
nova/virt/fake.py
Python
apache-2.0
16,557
0.000121
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # Copyright (c) 2010 Citrix Systems, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you m...
nova import block
_device from nova.compute import power_state from nova.compute import task_states from nova import db from nova import exception from nova.openstack.common.gettextutils import _ from nova.openstack.common import log as logging from nova.virt import driver from nova.virt import virtapi CONF = cfg.CONF CONF.import_opt('...
mfauvel/GrasslandsSympa
Codes/cluster_grasslands.py
Python
gpl-3.0
1,580
0.022152
import scipy as sp import hdda from multiprocessing import Pool import pickle import muesli_functions as mf # Convenient function def ClusterGrasslands(id_,DB,bands,C): # Read samples X = mf.readSamplesId(DB,id_,bands) # L1 Normalization X /= X.sum(axis=1)[:,sp.newaxis] print("Process Grasslands ...
0001,'random_state':rep,'C':C} model_ = hdda.HDGMM(model='M4') conv = model_.fit(X,param=param) if conv == 1: models.append(model_) icl.append(model_.icl) model_ = [] # Select the model with the highest ICL t = sp.argmax(icl) model = models[t] # Save ...
pickle.dump(model,output) if __name__ == '__main__': # Parameters DB = "../Data/grassland_id_2m.sqlite" data = sp.loadtxt("/media/Data/Data/MUESLI/spectresPrairies/Res/nc_grasslands.csv",delimiter=',',dtype=sp.int16) bands = 'band_0' for b in xrange(1,221): bands += ", band_{}".for...
Fokko/incubator-airflow
docs/exts/exampleinclude.py
Python
apache-2.0
9,331
0.000965
# -*- coding: utf-8 -*- # flake8: noqa # Disable Flake8 because of all the sphinx imports # # 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 licens...
ou 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 distributed under the License is distribut...
fw1121/Pandoras-Toolbox-for-Bioinformatics
src/SPAdes/ext/src/python_libs/joblib2/hashing.py
Python
gpl-3.0
6,526
0.000306
##############################################################
############## # Copyright (c) 2011-2014 Saint-Petersburg Academic University # All Rights Reserved # See file LICENSE for details. ############################################################################ """ Fast cryptographic hash of Python objects, with a special case for fast hashing of numpy arrays. """ # Au...
t normalesup dot org> # Copyright (c) 2009 Gael Varoquaux # License: BSD Style, 3 clauses. import pickle try: from hashlib import md5 except ImportError: from md5 import md5 import sys import types import struct if sys.version_info[0] == 3: # in python3, StringIO does not accept binary data # see http...
flav-io/flavio
flavio/physics/higgs/signalstrength.py
Python
mit
3,003
0.000666
r"""Functions for Higgs signal strengths.""" import flavio from . import production from . import decay from . import width prod_modes = { 'ggF': { 'desc': 'gluon fusion production', 'tex': 'gg', 'str': 'gg', }, 'hw': { 'desc': '$W$ boson associated production', 't...
ss': r'h\to ff', }, 'h_ww': { 'tex': r'W^+W^-', 'str': 'WW', 'tex_class': r'h\to VV', }, 'h_zz': { 'tex': r'ZZ', 'str': 'ZZ', 'tex_class': r'h\to VV', }, 'h_vv': { 'tex': r'VV', 'str': 'VV', 'tex_class': r'h\to VV', }, ...
ex_class': r'h\to VV', }, 'h_gaga': { 'tex': r'\gamma\gamma', 'str': 'gammagamma', 'tex_class': r'h\to VV', }, } def higgs_signalstrength(wc_obj, par, name_prod, name_dec): scale = flavio.config['renormalization scale']['hdecays'] C = wc_obj.get_wcxf(sector='all', scale=sca...
glciampaglia/pymulator
pymulator/sim.py
Python
gpl-3.0
3,607
0.000832
""" Pymulator simulation objects """ import json import datetime from .serialize import PandasNumpyEncoderMixIn, hook def importmodel(s): """ Import model from string s specifying a callable. The string has the following structure: package[.package]*.model[:function] For example: ...
_setmodel(self, f_or_str): if isinstance(f_or_str, str): self._modelstr = f_or_str self._f = importmodel(f_or_str) elif callable(f_or_str): self._modelstr = funstr(f_or_str)
self._f = f_or_str else: raise ValueError('Neither a callable nor a string: {}'.format(f_or_str)) def _delmodel(self): del self._f del self._modelstr model = property(_getmodel, _setmodel, _delmodel, "Simulation model") def _setoutputs(self, outputs): ...
tridc/django_local_library
catalog/urls.py
Python
gpl-3.0
1,232
0.008117
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^books/$', views.BookListView.as_view(), name='books'), url(r'^books/(?P<pk>\d+)$', views.BookDetailView.as_view(), name='book-detail'), url(r'^books/(?P<pk>[-\w]+)/renew/$', views.renew_b...
s.AuthorCreate.as_view(), name='author-create'), url(r'^authors/(?P<pk>\d+)/update/$', views.AuthorUpdate.as_view(), name='author-update'), url(r'^authors/(?P<pk>\d+)/delete/$', views.AuthorDelete.as_view(
), name='author-delete'), url(r'^mybooks/$', views.LoanedBooksByUserListView.as_view(), name='my-borrowed'), url(r'^borrowed/$', views.BorrowedBooksListView.as_view(), name='books-borrowed'), ]
BlackSmith/GreenTea
apps/core/migrations/0015_auto_20160509_1446.py
Python
gpl-2.0
1,599
0.005003
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models def set_default_data(apps, schema_editor): #removed_duplicated(apps, schema_editor) FileLog = apps.get_model("core", "FileLog") for it in FileLog.objects.exclude(path=""): it.url=it.path ...
name='to_removed', field=models.BooleanField(default=False), ), migrations.AddField( model_name='filelog', name='url', field=models.CharField(max_length=256, null=True), ),
migrations.AlterField( model_name='filelog', name='path', field=models.CharField(max_length=256, null=True), ), migrations.RunPython(set_default_data, unset_default_data), ]
lantip/sms-komunitas
medkom/member/serializers.py
Python
gpl-3.0
1,693
0.008269
from member.models import Person, Family, Handphone, KeluargaGangguan, JenisDifable, StatusRumah from member.models import Lantai, Dinding, Atap, JamsosDiterima, SumberAirMinum, StatusListrik from member.models import DayaListrik, JadwalRonda, ProgramKB, Agama, StatusPerkawinan, HubunganKeluarga from member.models impo...
fields = '__all__' class GolonganDarahSerializer(serializers.ModelSerializer): class Meta: model = GolonganDarah fields = '__all__' class AgamaSerializer(serializers.ModelSerializer): class Meta: model = Agama fields = '__all__' class UsiaSerializer(serializers.ModelSerialize...
class LargeResultsSetPagination(PageNumberPagination): page_size = 100 page_size_query_param = 'page_size' max_page_size = 1000 class StandardResultsSetPagination(PageNumberPagination): page_size = 10 page_size_query_param = 'page_size' max_page_size = 100
alimanfoo/numcodecs
docs/conf.py
Python
mit
10,126
0.005629
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # numcodecs documentation build configuration file, created by # sphinx-quickstart on Mon May 2 21:40:09 2016. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # ...
ions available for each theme, see the # documentati
on. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. # "<project> v<release> documentation" by default. #html_title = 'numcodecs v@@' # A shorter title for the navigation bar. Default is the same ...
markfinger/django-node
tests/tests.py
Python
mit
8,492
0.002591
import os import shutil import unittest from django.utils import six from django_node import node, npm from django_node.node_server import NodeServer from django_node.server import server from django_node.base_service import BaseService from django_node.exceptions import ( OutdatedDependency, MalformedVersionInput,...
se) self.assertTrue(server.test()) def test_node_server_config_is_as_expected(self): config = server.get_config() self.assertEqual(config['address'], server.address) self.assertEqual(config['port'], server.port) self.assertEqual(config['startup_output'], server.get_startup_o...
s = (EchoService, ErrorService, TimeoutService) self.assertEqual(len(config['services']), len(services)) service_names = [obj['name'] for obj in config['services']] service_sources = [obj['path_to_source'] for obj in config['services']] for service in services: self.assertIn...
KlubJagiellonski/pola-backend
pola/tests/commands/test_send_ai_pics_stats.py
Python
bsd-3-clause
197
0
from unittest i
mport TestCase from django.core.management import call_command class SendAiPicsStatsTestCase(TestCase): def test_run_comman
d(self): call_command('send_ai_pics_stats')
VUIIS/dax
dax/tests/unit_test_processor_graph.py
Python
mit
7,266
0.002615
from unittest import TestCase from dax.processor_graph import ProcessorGraph from dax import yaml_doc from dax.tests import unit_test_common_processor_yamls as yamls from dax.tests import unit_test_entity_common as common from dax.processors import AutoProcessor class TestLog: def __init__(self): self.w...
scription, log) print(actual) def test_processor_inputs_from_sources(self): print((ProcessorGraph.processor_inputs_
from_sources( ProcessorGraphUnitTests.__getabcdscenario() ))) def test_ordering_from_sources(self): log = TestLog() print((ProcessorGraph.order_from_inputs( ProcessorGraph.processor_inputs_from_sources( ProcessorGraphUnitTests.__getabcdscenario() ...
antoinecarme/pyaf
tests/artificial/transf_None/trend_MovingMedian/cycle_12/ar_12/test_artificial_128_None_MovingMedian_12_12_100.py
Python
bsd-3-clause
265
0.086792
import pyaf.Bench.TS_datasets as tsds import tests.artificial.process_artificial_dataset as art art.process_dataset(N = 128 , FREQ = 'D', seed = 0, trendtype = "MovingMedian", cycle_length = 12, transform = "None", sigma = 0.0, exog_count = 100, ar_or
der = 12);
SanDisk-Open-Source/desmod
desmod/progress.py
Python
mit
12,418
0.000564
from contextlib import contextmanager from datetime import datetime, timedelta from queue import Queue from typing import IO, TYPE_CHECKING, Dict, Generator, List, Optional, Set, Tuple, Union import sys import timeit import simpy from desmod.config import ConfigDict from desmod.timescale import TimeValue, parse_time,...
get_multi_progress_manager(progress_queue: Optional['Queue[ProgressTuple]']): @contextmanager def progress_producer(env): if progress_queue: period_s = _get_interval_period_s(env.config) env.process(_progress_enqueue_process(env, period_s, progress_queue)) try: ...
progress_queue.put((env.sim_index, env.now, env.now, env.timescale)) else: yield None return progress_producer def _progress_enqueue_process( env: 'SimEnvironment', period_s: Union[int, float], progress_queue: 'Queue[ProgressTuple]', ) -> Generator[simpy.Timeout, None, None]...
saltstack/salt
tests/pytests/unit/modules/test_modjk.py
Python
apache-2.0
5,541
0.002707
""" :codeauthor: Jayesh Kariya <jayeshk@saltstack.com> """ import pytest import salt.modules.modjk as modjk from tests.support.mock import patch @pytest.fixture def configure_loader_modules(): return {modjk: {}} def test_version(): """ Test for return the modjk version """ with patch.object...
turn_value={"worker.result.type": "OK"}): assert modjk.bulk_activate(["node1", "node2", "node3"], "loadbalancer1") def test_bulk_disable(): """ Test for disab
le all the given workers in the specific load balancer """ with patch.object(modjk, "_do_http", return_value={"worker.result.type": "OK"}): assert modjk.bulk_disable(["node1", "node2", "node3"], "loadbalancer1") def test_bulk_recover(): """ Test for recover all the given workers in the specifi...
cmptrgeekken/evething
thing/views/assets.py
Python
bsd-2-clause
17,736
0.001466
# ------------------------------------------------------------------------------ # Copyright (c) 2010-2013, EVEthing team # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # Redistributions of...
p = {} for corporation in corporations: corporation_ids.app
end(corporation.id) corporation_map[corporation.id] = corporation # apply our initial set of filters assets = Asset.objects.filter( Q(character__in=character_ids, corporation_id=0) | Q(corporation_id__in=corporation_ids) ) assets = assets.prefetch_related('item__item_gro...
USGSDenverPychron/pychron
pychron/pipeline/plot/editors/isochron_editor.py
Python
apache-2.0
3,053
0.000328
# =============================================================================== # Copyright 2013 Jake Ross # # 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...
======= # ============= enthought library imports ======================= # ============= standard library imports ======================== # ============= local library imports ========================== from __future__ import absolute_import from pychron.pipeline.plot.editors.figure_editor import FigureEditor from ...
ochronModel class IsochronEditor(FigureEditor): pass class InverseIsochronEditor(FigureEditor): # plotter_options_manager = Instance(InverseIsochronOptionsManager, ()) basename = "isochron" figure_model_klass = InverseIsochronModel pickle_path = "isochron" # parent_editor = None # #...
chuchiperriman/cloud-services-notifications
src/cloudsn/ui/window.py
Python
gpl-3.0
17,147
0.00659
# -*- mode: python; tab-width: 4; indent-tabs-mode: nil -*- from gi.repository import Gtk import os import shutil import gettext from cloudsn.core import config, provider, account, indicator, keyring from cloudsn import logger import cloudsn.core.utils as coreutils STOP_RESPONSE = 1 class MainWindow: __default =...
elect_provider_combo (self, providers_combo, name): #Select the provider and disable item i=0 for row in providers_combo.get_model(): if
row[1] == name: providers_combo.set_active (i) break i += 1 def load_window(self): from cloudsn.core.controller import Controller self.builder=Gtk.Builder() self.builder.set_translation_domain("cloudsn") self.builder.add_from_file(config...
ESS-LLP/erpnext-healthcare
erpnext/hr/doctype/employee_onboarding/test_employee_onboarding.py
Python
gpl-3.0
2,742
0.022247
# -*- coding: utf-8 -*- # Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and Contributors # See license.txt from __future__ import unicode_literals import frappe import unittest from frappe.utils import nowdate from erpnext.hr.doctype.employee_onboarding.employee_onboarding import make_employee from erpnext.hr.doct...
'role': 'HR User' }) onboarding.status = 'Pending' onboarding.insert() onboarding.submit() self.assertEqual(onboarding.project, 'Em
ployee Onboarding : Test Researcher - test@researcher.com') # don't allow making employee if onboarding is not complete self.assertRaises(IncompleteTaskError, make_employee, onboarding.name) # complete the task project = frappe.get_doc('Project', onboarding.project) project.tasks[0].status = 'Closed' proj...
Brahimbaz/venom-xbmc-addons-beta
plugin.video.vstream/resources/lib/config.py
Python
gpl-2.0
6,593
0.014713
import os import sys import xbmc import xbmcplugin import xbmcgui class cConfig(): COUNT = 0 ERROR = [] def __check(self): try: import xbmcaddon self.__bIsDharma = True except ImportError: self.__bIsDharma = False def __init...
: if (self.__bIsDh
arma == False): return if (iSeconds == 0): iSeconds = 1000 else: iSeconds = iSeconds * 1000 xbmc.executebuiltin("Notification(%s,%s,%s,%s)" % (str(sTitle), (str(sDescription)), iSeconds, self.__sIcon)) def update(self): x...
sani-coop/tinjaca
addons/recepcion/models/__init__.py
Python
gpl-2.0
48
0
# -*
- coding: utf-8 -*- import model_recepcion