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
compas-dev/compas
src/compas/data/coercion.py
Python
mit
1,742
0
from __future__ import print_function from __future__ import absolute_import from __future__ import division from .validators import is_item_iterable def coerce_sequence_of_tuple(sequence): """Make sure all items of a sequence are of type tuple. Parameters ---------- sequence : sequence A se...
tance(item, list): if not is_item_iterable(item): item = [item]
else: item = list(item) items.append(item) return items
dcolish/Presentations
speedy_c.py
Python
bsd-3-clause
44
0
import speedyc
print speedyc.crunit(
10**6)
gcallah/Indra
models/bacteria.py
Python
gpl-3.0
5,141
0
""" This is the model that stimulates the behavior of bacterias according to toxin and nutrients level. """ import sys from random import randint from indra.agent import Agent from indra.composite import Composite from indra.display_methods import BLUE, GREEN, RED from indra.env import Env from registry.registry impo...
= sys.maxsize * (-1) if agent["prev_nutricity"] is not None
: nutrient_change = nutrient_level - agent["prev_nutricity"] else: nutrient_change = sys.maxsize * (-1) threshold = DEF_THRESHOLD agent["prev_toxicity"] = toxin_level agent["prev_nutricity"] = nutrient_level if (toxin_change > nutrient_change) or (threshold >= toxin_level): ...
hgascon/pulsar
pulsar/core/sippy/SipCCDiversion.py
Python
bsd-3-clause
1,314
0.002283
# Copyright (c) 2003-2005 Maxim Sobolev. All rights reserved. # Copyright (c) 2006-2007 Sippy Software, Inc. All rights reserved. # # This file is part of SIPPY, a free RFC3261 SIP stack and B2BUA. # # SIPPY is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
other than those described here, or to purchase support for this # software, please contact Sippy Software, Inc. by e-mail at the # following addresses: sales@sippysoft.com. # # SIPPY is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or...
c License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. from .SipAddressHF import SipAddressHF class SipCCDiversion(SipAddressHF): hf...
kjedruczyk/phabricator-tools
py/phl/phlgit_diff.py
Python
apache-2.0
5,562
0.00018
"""Wrapper around 'git diff'.""" # ============================================================================= # CONTENTS # ----------------------------------------------------------------------------- # phlgit_diff # # Public Functions: # raw_diff_range_to_here # raw_diff_range # no_index # create_add_file #...
guage governing permissions and # limitations under the License. #
------------------------------ END-OF-FILE ----------------------------------
mpillar/codeeval
1-moderate/sort-martix-columns/main.py
Python
unlicense
1,201
0.004163
import sys def row_matrix_to_col_matrix(row_matrix): col_matrix = [] for c in range(len(row_matrix)): col_matrix.append([]) for r in range(len(row_matrix)): for c in range(len(row_matrix)): col_matrix[c].append(row_matrix[r][c]) return col_matrix def col_matrix_to_row_matrix(col_...
urn row_matrix def matrix_compare(a, b): length = min(len(a), len(b)) index = 0 while index < length: if a[index] != b[index]: return a[index] - b[index] index += 1 return 0 def main(): test_cases = open(sys.argv[1], 'r') for test
in test_cases: test = test.strip() if len(test) == 0: continue m = row_matrix_to_col_matrix([[int(i) for i in s.strip().split(' ')] for s in test.split('|')]) print(' | '.join([' '.join([str(e) for e in r]) for r in col_matrix_to_row_matrix(sorted(m, cmp=matrix_compare))])) test_case...
priyankarani/nereid
nereid/wrappers.py
Python
gpl-3.0
4,148
0
# This file is part of Tryton & Nereid. The COPYRIGHT file at the top level of # this repository contains the full copyright notices and license terms. import warnings from werkzeug._internal import _missing from flask.wrappers import Request as RequestBase, Response as ResponseBase from flask.ext.login import current...
def is_json(self): """Indicates if this request is JSON or not. By default a request is considered to include JSON data if the mimetype is ``application/json`` or ``application/*+json``. This feature is forward ported from flask 0.11. When flask
is released this will be removed from nereid code .. versionadded:: 3.0.4.0 """ mt = self.mimetype if mt == 'application/json': return True if mt.startswith('application/') and mt.endswith('+json'): return True return False class Respon...
hanlind/nova
nova/virt/libvirt/blockinfo.py
Python
apache-2.0
22,853
0.000131
# Copyright (C) 2012-2013 Red Hat, 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 la...
'disk.rescue' -> disk_info 'disk.local' -> disk_info 'disk.swap' -> disk_info 'disk.config' -> d
isk_info If any of the default disks are overridden by the block device info mappings, the hash value will be None For any ephemeral device there will also be a dict entry 'disk.eph$NUM' -> disk_info For any volume device there will also be a dict entry: $path -> disk_info Finally a sp...
CSD-Public/stonix
src/tests/rules/unit_tests/zzzTestRuleConfigurePasswordPolicy.py
Python
gpl-2.0
7,397
0.002839
#!/usr/bin/env python3 ############################################################################### # # # Copyright 2019. Triad National Security, LLC. All rights reserved. # # This program was produced
under U.S. Government contract 89233218CNA000001 # # for Los Alamos National Laboratory (LANL), which is operated by Triad # # National Security, LLC for the U.S. Department of Energy/National Nuclear # # Security Administration. # # ...
gram are reserved by Triad National Security, LLC, and # # the U.S. Department of Energy/National Nuclear Security Administration. The # # Government is granted for itself and others acting on its behalf a # # nonexclusive, paid-up, irrevocable worldwide license in this material to # # reproduce, prepare de...
jpaasen/cos
framework/beamformer/capon/RealTimeCapon/profile/prof.py
Python
mit
13,692
0.045209
import sys, re from subprocess import Popen, PIPE import framework.mynumpy as np info = {} QUIET=True ONLY_TIME=True USE_CODE_COUNTERS=True import framework.beamformer.capon.getCaponCUDA as getCaponCUDA #sys.path.append('/home/me/Work/UiO/Phd/Code/Profile') def getTimings(app_name='testEfficiency_default', ...
PIPE) output, error = prof.communicate() if error == '': if verbose: print output return output else: print output raise Exception(error) events='' profiler_output = run(M,L) lines = re.split("\n+", profiler_output)...
f re.search(".+%s.+"%function, l): timings = re.sub("^\s*", '', l) timings = re.sub("[\sa-zA-Z]*%s.+"%function, '', timings) columns = re.split("\s+", timings) if not entered_once: entered_once = True runtim...
bbenligiray/keras_models
test.py
Python
mit
801
0.013733
import model_loader from ker
as.utils import plot_model model_names = ['ResNet50', 'VGG19'] stages = ['5', 'final'] for model_name in model_names: for stage in stages: full_model = model_loader.load_full_model(model_name, random_weights=False, no_cats=2, weight_decay=0, activation='softmax') tail_model = model_loader.load_tail_model(model_n...
_model(model_name, random_weights=False, no_cats=2, weight_decay=0, activation='softmax', stage=stage) plot_model(full_model, to_file=model_name + '_' + stage + '_' + 'full.png') plot_model(tail_model, to_file=model_name + '_' + stage + '_' + 'tail.png') plot_model(head_model, to_file=model_name + '_' + stage + ...
google-research/tensor2robot
utils/__init__.py
Python
apache-2.0
605
0.001653
# coding=utf-8 # Copyright 2022 The Tensor2Robot Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # #
http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, softw
are # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
Goldmund-Wyldebeast-Wunderliebe/raven-python
raven/contrib/django/client.py
Python
bsd-3-clause
6,779
0.001475
""" raven.contrib.django.client ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import import logging from django.conf import settings from django.core.exceptions import Suspicio...
update(self.
get_data_from_request(request)) if kwargs.get('exc_info'): exc_value = kwargs['exc_info'][1] # As of r16833 (Django) all exceptions may contain a ``django_template_source`` attribute (rather than the # legacy ``TemplateSyntaxError.source`` check) which describes template inf...
qalhata/Python-Scripts-Repo-on-Data-Science
HTTP_Request_using_Requests.py
Python
gpl-3.0
821
0.002436
# -*- coding: utf-8 -*- """ Created on Sun Jan 15 23:32:44 2017 @author: Shabaka """ """ Import the package requests. Assign the URL of interest to the variable url. Package the request to the URL, send the request and catch the response with a single function requests.get(), assigning ...
bject r to return the HTML of the webpage as a string; store the result in a variable text. Hit submit to print the HTML of the webpage. """ # Import package import requests # Specify the url: url url = "http://docs.datacamp.com/teach/" # Packages the request, send the request and catch the respon...
= r.text # Print the html print(text)
lpenz/ansible-playbooks
roles/user-x/files/scripts/warnd.py
Python
apache-2.0
1,987
0
#!/usr/bin/env python3 import getopt import sys import os Options = { 'daemon': False, 'fifo': os.environ['HOME'] + '/warnd_fifo', 'log': [], 'time': 2, 'size': 54, 'wrap': 0, } State = { 'currentlog': 0, } USAGE = '\n'.join([ 'Usage: %s' % sys.argv[0], ' Warns the user about so...
' -l, --log LOG1,LOG2,... Where to log the messages. ' 'Userfull with root-tail. Default: no log.', ]) def usage(): print(USAGE) def loga(lines): if len(Options['log']) == 0: return log = Options['log'][State['currentlog']] hoje = os.popen("date +%b\\
%e\\ %H:%M:%S", 'r') line = hoje.read()[:-1] + ' ' + os.environ['USER'] + ' ' + "".join(lines) hoje.close() log.write(line + "\n") print(line) log.flush() State['currentlog'] = (State['currentlog'] + 1) % len(Options['log']) def doline(lines): loga(lines) os.system("xkbbell") def ma...
ceteri/intro_spark
src/02.wc.py
Python
cc0-1.0
167
0
from operator import add f = s
c.textFile("data/README.md") wc = f.flatMap(
lambda x: x.split(' ')).map(lambda x: (x, 1)).reduceByKey(add) wc.saveAsTextFile("wc_out")
apache/bloodhound
trac/trac/db/api.py
Python
apache-2.0
13,510
0.000666
# -*- coding: utf-8 -*- # # Copyright (C)2005-2009 Edgewall Software # Copyright (C) 2005 Christopher Lenz <cmlenz@gmx.de> # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at http://trac.e...
n_local.wdb = None
except: _transaction_local.wdb = None ldb.rollback() ldb = None raise return transaction_wrapper class DbContextManager(object): """Database Context Manager The outermost `DbContextManager` will close the connection. """ ...
tfroehlich82/EventGhost
plugins/CyberlinkUniversalRemote/__init__.py
Python
gpl-2.0
4,075
0.004664
# -*- coding: utf-8 -*- # # This file is a plugin for EventGhost. # Copyright © 2005-2020 EventGhost Project <http://www.eventghost.net/> # # EventGhost 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 v...
elf, data): if self.last_data != data: # print data if data in KEY_CODES_1: self.TriggerEnduringEvent(KEY_CODES_1[data]) self.last_data = data
elif data in KEY_CODES_2: self.TriggerEnduringEvent(KEY_CODES_2[data]) self.last_data = data elif data[:3] in KEY_CODES_3: self.TriggerEnduringEvent(KEY_CODES_3[data[:3]]) self.last_data = data elif data[:2] in KEY_CODES_4: ...
baixuexue123/note
python/others/aes_test.py
Python
bsd-2-clause
2,519
0.000825
#!/usr/bin/env python # -*- coding: utf-8 -*- import binascii import base64 import hashlib from Crypto import Random from Crypto.Cipher import AES # binascii.unhexlify # binascii.hexlify # 填充方式 # PKCS#5 和 PKCS#7 唯一的区别就是前者规定了数据块大小是 64 比特(8 字节) # 而 AES 中数据块大小是 128 比特(16字节), 因此在 AES 中, PKCS#5 和 PKCS#7 没有区别. BS = 16
def pad(s): return s + (BS - len(s) % BS) * chr(BS - len(s) % BS) def unpad
(s): return s[0:-ord(s[-1])] def encrypt(key, raw): raw = pad(raw) iv = Random.new().read(AES.block_size) cipher = AES.new(key, AES.MODE_CBC, iv) return iv + cipher.encrypt(raw) def decrypt(key, enc): iv = enc[:16] enc = enc[16:] cipher = AES.new(key, AES.MODE_CBC, iv) return unp...
gdementen/larray
larray/inout/pandas.py
Python
gpl-3.0
15,402
0.00448
from itertools import product import numpy as np import pandas as pd from larray.core.array import Array from larray.core.axis import Axis, AxisCollection from larray.core.constants import nan from larray.util.misc import unique_list def decode(s, encoding='utf-8', errors='strict'): if isinstance(s, bytes): ...
s to False. fill_value : scalar, optional Value used to fill cells corresponding to label combinations which are not present in the input Series. Defaults to NaN. meta : list of pairs or dict or OrderedDict or Metadata, optional Metadata (title, description, author, creation_date, ...) a...
array. Keys must be strings. Values must be of type string, int, float, date, time or datetime. Returns ------- Array See Also -------- Array.to_series Examples -------- >>> from larray import ndtest >>> s = ndtest((2, 2, 2), dtype=float).to_series() >>> s ...
wakatime/wakatime
wakatime/dependencies/haxe.py
Python
bsd-3-clause
1,199
0
# -*- co
ding: utf-8 -*- """ wakatime.dependencies.haxe ~~~~~~~~~~~~~~~~~~~~~~~~~~ Parse dependencies from Haxe code. :copyright: (c) 2018 Alan Hamlett. :license: BSD, see LICENSE for more details. """ from . import TokenParser class HaxeParser(TokenParser): exclude = [ r'^haxe$', ] ...
ken, content in self.tokens: self._process_token(token, content) return self.dependencies def _process_token(self, token, content): if self.partial(token) == 'Namespace': self._process_namespace(token, content) elif self.partial(token) == 'Text': self._pr...
rahulunair/nova
nova/tests/functional/db/api/test_migrations.py
Python
apache-2.0
32,181
0.001492
# 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...
nistic testing you need to set up db's named 'openstack_citest' with user 'openstack_citest' and password 'openstack_citest' on localhost. The test will then use that db and u/p combo to run the tests. For postgres on Ubuntu this can be done with the following commands:: | sudo -u postgres psql | postgres=# create us...
citest with owner openstack_citest; """ import os from migrate.versioning import repository import mock from oslo_db.sqlalchemy import enginefacade from oslo_db.sqlalchemy import test_fixtures from oslo_db.sqlalchemy import test_migrations from oslo_db.sqlalchemy import utils as db_utils from oslo_serialization impo...
joshzarrabi/e-mission-server
emission/net/int_service/giles/store_existing_stats.py
Python
bsd-3-clause
1,854
0.033981
import pandas from emission.net.api.stats import storeClientEntry, storeServerEntry, storeResultEntry def loadEntries(fname): df = pandas.read_csv(fname) entries = [] for c in range(len(df)): entry = {} for key in df.keys(): entry[key] = df[key][c] entries.append(entry) return entries def storeClientEn...
) #print(df['reading'][c] == 'None') print(df['reading'][c] == 'None') def storeServerEntries(fname): df = pandas.read_csv(fname) for c in range(len(df)): try: user = df['user'][c] stat = df['stat'][c] ts = int(df['ts'][c]) reading = float(df['reading'][c]) storeServerEntry(user, stat, ts, re...
] ts = int(df['ts'][c]) reading = float(df['reading'][c]) storeResultEntry(user, stat, ts, reading) except Exception as e: print(e) if __name__ == '__main__': storeClientEntries("client_stats.csv") storeResultEntries("result_stats.csv") storeServerEntries("server_stats.csv") #storeResultEntries("emi...
cwaldbieser/txcas
txcas/jinja_view_provider.py
Python
gpl-3.0
6,278
0.000956
# Standard library import cgi import itertools import json import sys from textwrap import dedent import urlparse # Application modules from txcas.constants import VIEW_LOGIN, VIEW_LOGIN_SUCCESS, VIEW_LOGOUT, \ VIEW_INVALID_SERVICE, VIEW_ERROR_5XX, VIEW_NOT_FOUND from txcas.exceptions import V...
failed=failed, request=request) d = self._getServiceEntry(service) d.addCallback(render, login_ticket, service, failed, request) return
d def renderLoginSuccess(self, avatar, request): """ """ return self._renderTemplate( VIEW_LOGIN_SUCCESS, avatar=avatar, request=request) def renderLogout(self, request): """ """ return self...
julianwang/cinder
cinder/volume/drivers/rbd.py
Python
apache-2.0
40,525
0.000025
# Copyright 2013 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable l...
LE("error opening rbd image %s"), name) driver._disconnect_from_rados(client, ioctx) raise self.driver = driver self.client = client self.ioctx = ioctx def __enter__(self): return self def __exit__(self, type_
, value, traceback): try: self.volume.close() finally: self.driver._disconnect_from_rados(self.client, self.ioctx) def __getattr__(self, attrib): return getattr(self.volume, attrib) class RADOSClient(object): """Context manager to simplify error handling for co...
mauroalberti/gsf
pygsf/geometries/shapes/space3d.py
Python
gpl-3.0
95,789
0.001733
import abc from typing import Optional, Callable from math import fabs import itertools from copy import copy import numbers from array import array from .space2d import Point2D, Segment2D from ...orientations.orientations import * from ...mathematics.statistics import * from ...mathematics.quaternions import * ...
def to2d(self) -> Point2D: """ Projection on the x-y plane as a 2D point. Examples: >>> Point3D(2, 3, 4).to2d() Point2D(2.0000, 3.0000) """ return Point2D( x=self.x, y=se
lf.y ) def pXY(self) -> 'Point3D': """ Projection on the x-y plane :return: projected object instance Examples: >>> Point3D(2, 3, 4).pXY() Point3D(2.0000, 3.0000, 0.0000) """ return Point3D(self.x, self.y, 0.0) def pXZ(self) -> 'Po...
shagabutdinov/sublime-named-mark
commands.py
Python
mit
2,443
0.022923
import sublime import sublime_plugin class GotoNamedMark(sublime_plugin.TextCommand): def run(self, edit, name = 'user', unset = True, set = False, set_name = None, set_icon = 'dot'): selelctions = [] for sel_item in self.view.sel(): selelctions.append([sel_item.a, sel_item.b]) regions = self...
self.view.sel().add_all(regions) if unset: self.view.erase_regions(name) if len(self.view.sel()) == 1: self.view.show(self.view.sel()[0].a) if set: self.view.run_command('set_named_mark', { "name": set_name or name, "icon": set_icon, "sel": selelctions, })
class DeleteToNamedMark(sublime_plugin.TextCommand): def run(self, edit, name = 'user', reset = True): regions = self.view.get_regions(name) if len(regions) == 0: return start_sel = self.view.sel()[0] start = min(start_sel.a, start_sel.b) end_sel = regions[0] end = max(end_sel.a, end...
plotly/plotly.py
packages/python/plotly/plotly/validators/heatmap/colorbar/_showticklabels.py
Python
mit
446
0.002242
import _plotly_utils.basevalidators class Showticklabels
Validator(_plotly_utils.basevalidators.BooleanValidator): def __init__( self, plotly_name="showticklabels", parent_name="heatmap.colorbar", **kwargs ): super(ShowticklabelsValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=k...
**kwargs )
hsaputra/tensorflow
tensorflow/python/keras/_impl/keras/layers/embeddings_test.py
Python
apache-2.0
2,384
0.002517
# Copyright 2016 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...
kwargs={'output_dim': 4, 'input_dim': 10, 'mask_zero': True}, input_shape=(3, 4, 2), input_dtype='int32', expected_output_dtype='float32') with self.test_session(): testing_utils.layer_test( keras.layers.Embedding, kwarg...
': 4, 'input_dim': 10, 'mask_zero': True, 'input_length': (None, 2)}, input_shape=(3, 4, 2), input_dtype='int32', expected_output_dtype='float32') if __name__ == '__main__': test.main()
noslenfa/tdjangorest
uw/lib/python2.7/site-packages/IPython/lib/display.py
Python
apache-2.0
13,061
0.002833
"""Various display related classes. Authors : MinRK, gregcaporaso, dannystaple """ from os.path import exists, isfile, splitext, abspath, join, isdir from os import walk, sep class IFrame(object): """ Generic class to embed an iframe in an IPython notebook """ iframe = """ <iframe ...
= included_suffixes # remove trailing slashs for more consistent output formatting path = path.rstrip('/') self.path =
path self.url_prefix = url_prefix self.result_html_prefix = result_html_prefix self.result_html_suffix = result_html_suffix self.notebook_display_formatter = \ notebook_display_formatter or self._get_notebook_display_formatter() self.terminal_display_formatter = \ ...
crosick/zhishu
app/auth/views.py
Python
mit
1,613
0.001278
#-*- coding:utf-8 -*- from flask import render_template, redirect, request, url_for, flash from flask.ext.login import login_user, logout_user, login_required, \ current_user from . import auth from .. import db from ..models import User from .forms import LoginForm, RegistrationForm @auth.before_app_request def ...
ent_user.is_authenticated(): current_user.ping() @auth.route('/login', methods=['GET', 'POST']) def login(): """登录""" form = LoginForm() if form.validate_on_submit(): user = User.query.filter_by(email=form.email.data).first() if user is not None and user.verify_password(form.pa...
direct(request.args.get('next') or url_for('main.index')) flash('Invalid username or password.') return render_template('auth/login.html', form=form) @auth.route('/logout') @login_required def logout(): """登出""" logout_user() flash('You have been logged out.') return redirect(url_for('main...
d7415/merlin
Arthur/loadable.py
Python
gpl-2.0
7,668
0.006781
# This file is part of Merlin/Arthur. # Merlin/Arthur is the Copyright (C)2009,2010 of Elliot Rosemarine. # Individual portions may be copyright by individual contributors, and # are included in this collective work with permission of the copyright # owners. # This program is free software; you can redistribute it an...
wargs) def authenticate(self, request): request.session = None request.user =
None key = request.COOKIES.get(SESSION_KEY) if key: auth = Arthur.load(key, datetime.now()) if auth is None: raise UserError("Your session has expired, please login again.") if request.path == LOGOUT: session.delete(auth) ...
calvinleenyc/zulip
analytics/management/commands/client_activity.py
Python
apache-2.0
3,040
0.001316
from __future__ import absolute_import from __future__ import print_function from typing import Any from argparse import ArgumentParser from django.core.management.base import BaseCommand from django.db.models import Count, QuerySet from zerver.models import UserActivity, UserProfile, Realm, \ get_realm, get_use...
ous clients; think of it as telling you # approximately how many people from a group have used a particular # client recently. For example, this might be useful to get a sense of # how popular different versions of a desktop client are. # # Importantly, this does
NOT tell you anything about the relative # volumes of requests from clients. threshold = datetime.datetime.now() - datetime.timedelta(days=7) client_counts = user_activity_objects.filter( last_visit__gt=threshold).values("client__name").annotate( count=Count('client__nam...
malkavi/Flexget
flexget/components/bittorrent/torrent_alive.py
Python
mit
10,086
0.001884
import binascii import itertools import socket import struct import threading from http.client import BadStatusLine from random import randrange from urllib.error import URLError from urllib.parse import quote, urlparse, urlsplit, urlunsplit from loguru import logger from requests impor
t Re
questException from flexget import plugin from flexget.event import event from flexget.utils import requests from flexget.utils.bittorrent import bdecode logger = logger.bind(name='torrent_alive') class TorrentAliveThread(threading.Thread): _counter = itertools.count() def __init__(self, tracker, info_hash...
RENCI/xDCIShare
hs_app_timeseries/migrations/0001_initial.py
Python
bsd-3-clause
9,652
0.003937
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings import hs_core.models class Migration(migrations.Migration): dependencies = [ ('auth', '0001_initial'), ('pages', '__first__'), migrations.swappable_d...
r_editable_hs_app_timeseries_timeseriesresource', null=True, to=settings.AUTH_USER_MODEL, blank=True)), ('last_changed_by', models.ForeignKey(related_name='last_changed_hs_app_timeseries_timeseriesresource', to=settings.AUTH_USER_MODEL, help_text=b'The person who last changed the resourc
e', null=True)), ('owners', models.ManyToManyField(help_text=b'The person who has total ownership of the resource', related_name='owns_hs_app_timeseries_timeseriesresource', to=settings.AUTH_USER_MODEL)), ('user', models.ForeignKey(related_name='timeseriesresources', verbose_name='Author...
msupino/alerta-contrib
integrations/supervisor/evlistener.py
Python
mit
2,514
0.000796
#!/usr/bin/env python import sys import json import platform from alertaclient.api import ApiClient from alertaclient.alert import Alert from alertaclient.heartbeat import Heartbeat class Listener(object): def wait(self): data = sys.stdin.readline() headers = dict([x.split(':') for x in data.sp...
erity=severity, origin=headers['server'], text='State changed from %s to %s.' % (body['from_state'], event),
raw_data='%s\n\n%s' % (json.dumps(headers), json.dumps(body)) ) try: api.send(supervisorAlert) except Exception as e: listener.log_stderr(e) listener.send_cmd('RESULT 4\nFAIL') else: listener.send_cmd('RESULT 2\nOK') if __name_...
gasman/wagtail
wagtail/admin/localization.py
Python
bsd-3-clause
4,210
0.000951
import pytz from django.conf import settings from django.utils.dates import MONTHS, WEEKDAYS, WEEKDAYS_ABBR from django.utils.translation import gettext as _ # Wagtail languages with >=90% coverage # This list is manually maintained WAGTAILADMIN_PROVIDED_LANGUAGES = [ ('ar', 'Arabic'), ('ca', 'Catalan'), ...
azilian Portuguese'), ('pt-pt', 'Portuguese'), ('ro', 'Romanian'), ('ru', 'Russian'), ('sv', 'Swedish'), ('sk-sk', 'Slovak'), ('th', 'Thai'), ('tr', 'Turkish'), ('uk', 'Ukrainian'), ('zh-hans', 'Chinese (Simplified)'), ('zh-hant', 'Chinese (Traditional)'), ] # Translatable stri...
ect def get_js_translation_strings(): return { 'DELETE': _('Delete'), 'EDIT': _('Edit'), 'PAGE': _('Page'), 'PAGES': _('Pages'), 'LOADING': _('Loading…'), 'NO_RESULTS': _('No results'), 'SERVER_ERROR': _('Server Error'), 'SEE_ALL': _('See all'), ...
2947721120/django-material
tests/test_base_layout.py
Python
bsd-3-clause
1,031
0.00097
from django import forms from django.test.utils import override_settings from django_webtest import WebTest from material import Layout, Row, Column from . import build_test_urls class LayoutForm(forms.Form): test_field1 = forms.CharField() test_field2 = forms.CharField() test_field3 = forms.CharField() ...
', 'test_field2'), Row('test_field3', Column('test_field4', 'test_field5'))) @override_settings(ROOT_URLCONF=__name__) class Test(WebTest): default_form = LayoutForm def test_fie
ld_part_override(self): """ Issue #19 """ response = self.app.get(self.test_field_part_override.url) self.assertIn('NO FIELD', response.content.decode('utf-8')) test_field_part_override.template = """ {% form %} {% part form.test_field1 %}NO FIELD{% endp...
pcu4dros/pandora-core
workspace/lib/python3.5/site-packages/jsonschema/_version.py
Python
mit
122
0
# This file is automatically generated by setup.py. __version__ = '2.6.0' __sha__ = 'gd16713a' __
revision_
_ = 'gd16713a'
arifgursel/rauth
tests/test_session.py
Python
mit
5,224
0
# -*- coding: utf-8 -*- ''' rauth.test_session ------------------ Test suite for rauth.session. ''' from base import RauthTestCase from rauth.session import OAuth1Session, OAuth2Session, OflySession from mock import patch import requests import json class RequestMixin(object): def assert_ok(self,...
onTestCase, self).test_request(user_id='123') @patch.object(requests.Session, 'request') def test_request_with_header_auth(self, mock_request): mock_request.return_value = self.response r = self.session.request('GET', 'http://example.com/', ...
ssert_ok(r) @patch.object(requests.Session, 'request') def test_request_with_md5(self, mock_request): mock_request.return_value = self.response r = self.session.request('GET', 'http://example.com/', user_id='123', ...
Scalsol/XMU_bkxk_Captcha
captcha_recognition.py
Python
apache-2.0
4,092
0.005621
__author__ = 'Scalsol' from PIL import Image import numpy as np import pytesseract import os rows = 100 cols = 210 dx = np.array([0, 0, -1, 1]) dy = np.array([-1, 1, 0, 0]) save_dir = "D:\\\Python\\Small_Contribution\\image" def get_point(ncol): global rows for row in range(rows): i...
, narry): k
1 = (up_r1 - up_l1) / (cols - 11) b1 = up_l1 k2 = (up_r2 - up_l2) / (cols - 11) b2 = up_l2 narr = np.ones((100, 210), dtype = np.int32) * 255 for i in range(cols): uu = round(k1 * i + b1) narr[(uu - 1) : (uu + 5), i] = 0 uu = round(k2 * i + b2) narr[(uu - 1) ...
KevinHanson/google-python
basic/list1.py
Python
apache-2.0
3,962
0.022968
#!/usr/bin/python -tt # Copyright 2010 Google Inc. # Licensed under the Apache License, Version 2.0 # http://www.apache.org/licenses/LICENSE-2.0 # Google's Python Class # http://code.google.com/edu/languages/google-python-class/ # Basic list exercises # Fill in the code for the functions below. main() is already set ...
ef wordsover3() #sorted(a, key=) i = 0 for s in words: #print s #print len(s) #i = i + 1 #print 'i=' + str(i) #if the length of s is greater than or equal to 2 then add one to i #(bob == 10 or bob > 10)
if (len(s) == 2 or len(s) > 2): if (s[0] == s[-1]): i = i + 1 #print 'i=' + str(i) return i # B. front_x # Given a list of strings, return a list with the strings # in sorted order, except group all the strings that begin with 'x' first. # e.g. ['mix', 'xyz', 'apple', 'xanadu', 'aardvark'] yields # ['xan...
teffalump/rentport
common/forms.py
Python
gpl-3.0
6,442
0.01661
#### FORMS from flask import current_app from flask.ext.wtf import Form from flask.ext.security.forms import RegisterForm, LoginForm, RegisterFormMixin from wtforms import (SelectField, StringField, SubmitField, TextAreaField, HiddenField, FileField, RadioField, SelectField, IntegerField, ValidationErr...
unique_user_username]) password=Passwo
rdField('Password', [DataRequired(), good_enough_password]) class ChangePasswordForm(Form): password=PasswordField('New password', [DataRequired(), good_enough_password]) submit=SubmitField('Update') class ExtendedLoginForm(LoginForm): email=StringField('Log...
vinu76jsr/librarymanagementsystem
librarymanagementsystem/settings.py
Python
apache-2.0
3,254
0
""" Django settings for librarymanagementsystem project. For more information on this file, see https://docs.djangoproject.com/en/1.6/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.6/ref/settings/ """ # Build paths inside the project like this: os.path.join(B...
.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contri
b.staticfiles', 'social.apps.django_app.default', 'django_extensions', 'djangosecure', 'mainapp', ) AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'social.backends.google.GoogleOpenId', ) SECURE_FRAME_DENY = True MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.m...
TheLazyHase/dragon_dice_simulator
business/dice/face/standard/group_id.py
Python
gpl-3.0
1,018
0.003929
# -*- coding: utf-8 *-* # Copyright (c) 2013 Tisserant Pierre # # This file is part of Dragon dice simulator. # # Dragon dice simulator 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 Softwa
re Foundation, either version 3 of the License, or #
(at your option) any later version. # # Dragon dice simulator is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You ...
cherishing78/BSVer
Yintest/noloop.py
Python
bsd-3-clause
3,693
0.069862
import numpy as np def Initial_diag(dim): conv=np.diag(np.random.rand(dim)) return conv def Convergence(matrix): delta=(np.abs(matrix).max(axis=0)).max(axis=0) return delta def Train(trainingset,label): (imagenum,dim)=trainingset.shape #Each column vector stands for a image. dataset=np.transpose(trainingset) ...
e the constant term for e[i,j]. constant=0 for j in range(m_index,m_index+m[i]): constant+=np.dot(Se,np.dot(G_class[m[i]-1],dataset[:,j])) #Compute the Su_new and Se_new for j in range(m_index,m_index+m[i]): u+=np.dot(Su,np.dot((F+(m[i]+1)*G_class[m[i]-1]),dataset[:,j])) eij=np.dot(Se,dataset[:,...
Se_new+=np.dot(eij,np.transpose(eij))/m[i]/peoplenum Su_new+=np.dot(u,np.transpose(u))/peoplenum #Pointer move on. m_index+=m[i] Delta_Su=Su_new.__sub__(Su) Delta_Se=Se_new.__sub__(Se) Delta=max(Convergence(Delta_Su),Convergence(Delta_Se)) Su=Su_new Se=Se_new print '------ %dth iteration acco...
schleichdi2/openpli-e2
skin.py
Python
gpl-2.0
35,598
0.03576
from Tools.Profile import profile profile("LOAD:ElementTree") import xml.etree.cElementTree import os profile("LOAD:enigma_skin") from enigma import eSize, ePoint, eRect, gFont, eWindow, eLabel, ePixmap, eWindowStyleManager, \ addFont, gRGB, eWindowStyleSkinned, getDesktop from Components.config import ConfigSubsecti...
: take the center point of parent size/width # % : take given percentag of parent size/width # w : multiply by current font width # h : multiply by current font height # def parseCoordinate(s, e, size=0, font=None): s = s.strip() if s == "center": # for speed, can be common...
(e - size)/2 elif s == '*': return None else: try: val = int(s) # for speed except: if 't' in s: s = s.replace("center", str((e-size)/2.0)) if 'e' in s: s = s.replace("e", str(e)) if 'c' in s: s = s.replace("c", str(e/2.0)) if 'w' in s: s = s.replace("w", "*" + str(fonts[font][3])...
gwu-libraries/loggins
loggins/ui/management/commands/map_network_hosts.py
Python
mit
2,508
0.002392
from django.core.exceptions import ObjectDoesNotExist from django.core.management.base import BaseCommand, CommandError from django.conf import settings from ui.models import Location from pysnmp.entity.rfc3413.oneliner import cmdgen class Command(BaseCommand): help = '''Capture network status of all the hosts ...
'1.3.6.1.4.1.25071.1.1.2.1.1.3',) if errorIndication: print(str(ip_address) + ': ' + str(errorIndication)) else: if errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), ...
try: location = Location.objects.get(hostname__iexact=hostname) if location.ip_address != ip_address: location.ip_address = ip_address location.save() ...
lakshmi-kannan/matra
openstack/common/rpc/impl_qpid.py
Python
apache-2.0
26,196
0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 OpenStack Foundation # Copyright 2011 - 2012, Red Hat, 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 # # ...
"durable": False, "auto-delete": True, "exclusive": False, }, }, } addr_opts["node"]["x-declare"].update(node_opts) addr_opts["link"]["x-declare"].update(link_opts) self.address = "%s ; %s" % (node_name, jsonut...
econnect(self, session): """Re-declare the receiver after a qpid reconnect.""" self._declare_receiver(session) def _declare_receiver(self, session): self.session = session self.receiver = session.receiver(self.address) self.receiver.capacity = 1 def _unpack_json_msg(sel...
zerolab/wagtail
wagtail/admin/forms/__init__.py
Python
bsd-3-clause
285
0
# definitions wh
ich are not being deprecated from wagtail.admin.forms from .models import ( # NOQA DIRECT_FORM_FIELD_OVERRIDES, FORM_FIELD_OVERRIDES, WagtailAdminModelForm, WagtailAdminModelFormMetaclass, formfield_for_dbfield) from .pages import WagtailAdminPageForm
# NOQA
tomasjames/citsciportal
app/agentex/migrations/0015_datapoint_sorttimestamp.py
Python
gpl-3.0
431
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('agentex', '0014_remove_dec
ision_datacollect'), ] operations = [ migrat
ions.AddField( model_name='datapoint', name='sorttimestamp', field=models.DateTimeField(null=True, blank=True), ), ]
pydoit/doit
doit/loader.py
Python
mit
15,129
0.001983
"""Loads dodo file (a python module) and convert them to 'tasks' """ import os import sys import copy import inspect import importlib from collections import OrderedDict from .exceptions import InvalidTask, InvalidCommand, InvalidDodoFile from .task import DelayedLoader, Task, dict_to_task from .cmdparse import TaskP...
None) if creator_params is not None: parser = TaskParse([CmdOption(opt) for opt in creator_params]) # Add task options from config, if present if config: task_stanza = 'task:' + name
if task_stanza in config: parser.overwrite_defaults(config[task_stanza]) # if relevant command line defaults are available parse those if name in arg_pos: creator_kwargs, _ = parser.parse(args[arg_pos[name]+1:]) else: ...
astrobin/astrobin
astrobin_apps_json_api/i18n/views/__init__.py
Python
agpl-3.0
35
0
from .messages
import I18nMessag
es
ryankanno/py-utilities
tests/text/test_string_utilities.py
Python
mit
904
0
#!/usr/bin/env python # -*- coding: utf-8 -*- from nose.tools import ok_ from nose.tools import raises from py_utilities.text.string_utilities import str_to_bool import unittest class TestStringUtilities(unittest.TestCase): def test_str_to_bool(self): ok_(str_to_bool("yes")) ok_(str_to_bool("y")...
bool("no"))
ok_(not str_to_bool("n")) ok_(not str_to_bool("false")) ok_(not str_to_bool("f")) ok_(not str_to_bool("0")) ok_(not str_to_bool("0.0")) ok_(not str_to_bool("")) ok_(not str_to_bool("none")) ok_(not str_to_bool("[]")) ok_(not str_to_bool("{}")) ...
sunqm/pyscf
pyscf/mp/test/test_f12.py
Python
apache-2.0
2,137
0.007019
#!/usr/bin/env python # Copyright 2014-2018 The PySCF Developers. 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 # # U...
ss required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import un...
cf import gto from pyscf import lo from pyscf import scf from pyscf.mp import mp2f12_slow as mp2f12 from pyscf import mp mol = gto.Mole() mol.verbose = 0 mol.output = None mol.atom = [ [8 , (0. , 0. , 0.)], [1 , (0. , -0.757 , 0.587)], [1 , (0. , 0.757 , 0.587)]] mol.basis = 'ccpvdz' mol.build() def...
nekohayo/meld
meld/vc/svk.py
Python
gpl-2.0
2,215
0.01219
### Copyright (C) 2009 Vincent Legoll <vincent.legoll@gmail.com> ### 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...
can ask to create its repository, we # don't want that to happen, so provide the right answer with `text="n"` status = misc.cmdout([self.CMD, "info"], cwd=location, stdout=misc.NULL, stderr=misc.NULL, text='n')[1] # SVK does evil things to
the real stdin, even when having its input # stream redirected to a newly created pipe, restore sanity manually misc.cmdout(['stty', 'sane'], stdout=misc.NULL, stderr=misc.NULL, stdin=None) except OSError: raise ValueError() if status != 0: raise ValueErro...
hvy/chainer
tests/chainermn_tests/datasets_tests/test_empty_dataset.py
Python
mit
1,128
0
import unittest import numpy as np from chainermn.datasets import create_empty_dataset import chainerx as chx class TestEmptyDataset(unittest.TestCase): def setUp(self): pass def check_create_empty_dataset(self, original_dataset): empty_dataset = create_empty_dataset(original_dataset) ...
n = 10 self.check_create_empty_dataset([]) self.check_create_empty_dataset([0]) self.check_create_empty_dataset(list(range(n))) self.check_create_empty_dataset(list(range(n * 5 - 1))) self.check_create_empty_dataset(xp.array([])) self.check_create_empty_dataset(xp...
.check_create_empty_dataset(xp.arange(n * 5 - 1))
dreibh/planetlab-lxc-plcapi
cache_utils/decorators.py
Python
bsd-3-clause
2,006
0.001994
#coding: utf-8 from django.core.cache import cache from django.utils.functional import wraps from cache_utils.utils import _cache_key, _func_info, _func_type def cached(timeout, group=None): """ Caching decorator. Can be applied to function, method or classmethod. Supports bulk cache invalidation and invalidat...
lidation is not supported. Wrapped callable gets `invalidate` methods. Call `invalidate` with same arguments as f
unction and the result for these arguments will be invalidated. """ backend_kwargs = {'group': group} if group else {} def _cached(func): func_type = _func_type(func) @wraps(func) def wrapper(*args, **kwargs): # full name is stored as attribute on first call ...
iulian787/spack
var/spack/repos/builtin/packages/xfsprogs/package.py
Python
lgpl-2.1
1,290
0.004651
# Copyright 2013-2020 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 i
mport * class Xfsprogs(AutotoolsPackage): """XFS User Tools.""" homepag
e = "http://oss.sgi.com/projects/xfs/" url = "http://kernel.org/pub/linux/utils/fs/xfs/xfsprogs/xfsprogs-4.17.0.tar.xz" version('5.8.0', sha256='8ef46ed9e6bb927f407f541dc4324857c908ddf1374265edc910d23724048c6b') version('5.7.0', sha256='8f2348a68a686a3f4491dda5d62dd32d885fbc52d32875edd41e2c296e7b4f35'...
Comunitea/CMNT_004_15
project-addons/stock_deposit/wizard/stock_return_deposit.py
Python
agpl-3.0
6,171
0.002593
############################################################################## # # Copyright (C) 2015 Pexego All Rights Reserved # $Jesús Ventosinos Mayor <jesus@pexego.es>$ # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License...
y of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from odoo import models, fields, api, exceptions, _ from odoo.exceptions import ValidationError class StockReturnDeposi...
_name = 'stock.return.deposit' @api.multi def _get_active_deposits(self): wiz_lines = [] deposit_obj = self.env['stock.deposit'] deposit_ids = self.env.context.get('active_ids', []) deposits = deposit_obj.search([('id', 'in', deposit_ids), ('state', '=', 'draft')]) for...
smymc/Maya-Python
kmAnimImpExp.py
Python
gpl-2.0
3,967
0.04445
# -*- coding: utf-8 -*- ############################################################################### ## # @file kmAnimImpExp.py
# @brief AnimファイルとSelectファイル同時書き出し # @version 1.0.1 # @date 2016/04/23 # @note - edit # - cleanup # @todo # ############################################################################### import os import maya.cmds as mc import maya.mel as mm ##############################################################...
########## if not mc.pluginInfo("animImportExport",q=True,loaded=True): mc.loadPlugin( 'animImportExport' ) mc.pluginInfo( 'animImportExport', edit=True, autoload=True ) ############################################################################### def main(): mc.python('from kmAnimImpExp import *') if mc.window(...
crs4/hl7apy
hl7apy/v2_3_1/messages.py
Python
mit
47,596
0.002122
from .groups import GROUPS from .segments import SEGMENTS MESSAGES = { 'ACK': ('sequence', (('MSH', SEGMENTS['MSH'], (1, 1), 'SEG'), ('MSA', SEGMENTS['MSA'], (1, 1), 'SEG'), ('ERR', SEGMENTS['ERR'], (0, 1), 'SEG'),)), 'ADR_A19': ('sequence', (('MSH', SEGMEN...
('DB1', SEGMENTS['DB1'], (0, -1), 'SEG'), ('OBX', SEGMENTS['OBX'], (0, -1), 'SEG'),)),
'ADT_A18': ('sequence', (('MSH', SEGMENTS['MSH'], (1, 1), 'SEG'), ('EVN', SEGMENTS['EVN'], (1, 1), 'SEG'), ('PID', SEGMENTS['PID'], (1, 1), 'SEG'), ('PD1', SEGMENTS['PD1'], (0, 1), 'SEG'), ('MRG', SEGMENTS['MRG'], (0, 1), 'SEG'), ...
mousebrains/kayak
scripts/old2new_info.py
Python
gpl-3.0
14,013
0.007707
#! /usr/bin/env python3 # # Copy from old style levels_information database to new style in levels_nuevo # import mysql.connector from mysql.connector.errors import Error import MyLogger import logging import MyDB import re import argparse from int2hash import int2hash from stateAbbreviations import state2code def co...
] is None and row['calcID'] is None: return None if row['merged_dbs'] is not None: if row['calcID'] is not None: for key in sorted(row): logger.error('row[%s] = %s', key, row[key])
raise Exception('Both merged_dbs and calcID are defined') for name in row['merged_dbs'].split(): if name in name2url: mkSource(tgt, row, name, name2url[name], None, logger) else: logger.warning('merged db name=%s not known', name) elif row[...
nesdis/djongo
tests/django_tests/tests/v21/tests/contenttypes_tests/test_models.py
Python
agpl-3.0
11,130
0.001977
from django.contrib.contenttypes.models import ContentType, ContentTypeManager from django.contrib.contenttypes.views import shortcut from django.contrib.sites.shortcuts import get_current_site from django.http import Http404, HttpRequest from django.test import TestCase, override_settings from .models import ( Au...
) def test_get_for_models_creation(self): ContentType.objects.all().delete() with self.assertNumQueries(4): cts = ContentType.objects.get_for_models(ContentType, FooWithUrl, ProxyModel, ConcreteModel) self.assertEqual(cts, { ContentType: ContentType.objects.get_for_m...
(ProxyModel), ConcreteModel: ContentType.objects.get_for_model(ConcreteModel), }) def test_get_for_models_empty_cache(self): # Empty cache. with self.assertNumQueries(1): cts = ContentType.objects.get_for_models(ContentType, FooWithUrl, ProxyModel, ConcreteModel) ...
AversivePlusPlus/AversivePlusPlus
modules/hal/stream-hal/conanfile.py
Python
bsd-3-clause
318
0.006289
from conans import ConanFile, CMake class Aversi
vePlusPlusModuleConan(ConanFile): name = "stream-hal" version = "0.1" exports = "*.
hpp" requires = "stream/0.1@AversivePlusPlus/dev", "hal-switch/0.1@AversivePlusPlus/dev" def package(self): self.copy("*.hpp", src="include", dst="include")
washort/zamboni
mkt/api/tests/test_handlers.py
Python
bsd-3-clause
37,545
0
# -*- coding: utf-8 -*- import json import os import tempfile import urllib from decimal import Decimal from StringIO import StringIO from django.core.urlresolvers import reverse from django.test.client import RequestFactory from mock import patch from nose.tools import eq_ from rest_framework.request import Request ...
device_type=mkt.DEVICE_DESKTOP.id) res = self.client.get(self.get_url) eq_(res.status_code, 200) content = json.loads(res.content) eq_(content['device_types'], [u'desktop']) def test_not_public(self): self.create_app() res = self.anon.get(self.get_url) ...
app.update(status=mkt.STATUS_PUBLIC) res = self.anon.get(self.get_url) eq_(res.status_code, 200) def test_get_previews(self): app = self.create_app() res = self.client.get(self.get_url) eq_(len(json.loads(res.content)['previews']), 0) Preview.objects.create(addon=app...
jimbotonic/df_nlp
step3/graphs2b.py
Python
gpl-2.0
1,385
0.01444
# # This file is part of DF. # # DF 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. # # Latassan is distributed in the hope that it ...
@gmail.com> # from __future__ import division import sys from utils import * from igraph import Graph import cPickle as pickle import logging as log import scipy.sparse as sps if __name__ == '__main__': log.basicConfig(level=log.DEBUG, format='%(asctime)s:%(levelname)s:%(message)s') matrix_file_...
= GraphUtils.get_graph_from_matrix(umat,density,ignore_weights=iw) log.info('#vertices, #edges: ' + str(len(g.vs)) + ', ' + str(len(g.es))) pickle.dump(g, open(graph_file_name, 'wb'))
ychen820/microblog
y/google-cloud-sdk/platform/google_appengine/lib/django-1.3/django/middleware/cache.py
Python
bsd-3-clause
9,078
0.002093
""" Cache middleware. If enabled, each Django-powered page will be cached based on URL. The canonical way to enable cache middleware is to set ``UpdateCacheMiddleware`` as your first piece of middleware, and ``FetchFromCacheMiddleware`` as the last:: MIDDLEWARE_CLASSES = [ 'django.middleware.cache.UpdateCa...
esses middleware top-down. The single-class ``CacheMiddleware`` can be used for some simple sites. However, if any other piece of middleware needs to affect the cache key, you'll need to use the two-part ``UpdateCacheMiddleware`` and ``FetchFromCacheMiddleware``. This'll most often happen when you're using Django's ``...
The number of seconds each page is stored for is set by the "max-age" section of the response's "Cache-Control" header, falling back to the CACHE_MIDDLEWARE_SECONDS setting if the section was not found. * If CACHE_MIDDLEWARE_ANONYMOUS_ONLY is set to True, only anonymous requests (i.e., those not made by a logged...
bitesandbytes/upgraded-system
src/simple_5_lstm.py
Python
mit
26,400
0.004962
# TODO: # 1. Fix broken functions # 2. Network architecture changed, but functions need to use mask differently # 3. Evaluation function from __future__ import print_function import cPickle as pickle import sys import time from collections import OrderedDict import numpy import theano import theano.tensor as tensor ...
atch_start + minibatch_size]) minibatch_start += minibatch_size if (minibatch_start != n): # Make a minibatch out of what is left minibatches.append(idx_list[minibatch_start:]) return zip(range(len(minibatches)), minibatches) def zipp(params, tparams): """ When we reload the ...
lue(vv) def unzip(zipped): """ When we pickle the model. Needed for the GPU stuff. """ new_params = OrderedDict() for kk, vv in zipped.items(): new_params[kk] = vv.get_value() return new_params def dropout_layer(state_before, use_noise, trng): proj = tensor.switch(use_noise, ...
redhat-openstack/glance
glance/tests/unit/test_quota.py
Python
apache-2.0
28,856
0.000035
# Copyright 2013, Red Hat, 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...
on]) pre_add_locations.extend([new_location]) self.assertEqual(image.locations, pre_add_locations) def test_iadd_location(self):
new_location = {'url': 'file:///a/path', 'metadata': {}, 'status': 'active'} image = self._get_image() pre_add_locations = image.locations[:] image.locations += [new_location] pre_add_locations += [new_location] self.assertEqual(image.locations, pre_add_l...
Fillll/reddit2telegram
reddit2telegram/channels/r_tupac/app.py
Python
mit
163
0.006135
#encoding:utf-8 subreddit = 'tupac'
t_channel = '@r_tupac' submissions_ranking = 'new' def send_post(submission, r2t): return r2t.send_
simple(submission)
v4l3r10/goingxincoin
contrib/bitrpc/bitrpc.py
Python
gpl-3.0
7,843
0.038251
from jsonrpc import ServiceProxy import sys import string # ===== BEGIN USER SETTINGS ===== # if you do not set these you will be prompted for a password for every command rpcuser = "" rpcpass = "" # ====== END USER SETTINGS ====== if rpcpass == "": access = ServiceProxy("http://127.0.0.1:8332") else: access = Ser...
ss.gettransaction(txid) except: print "\n---An error occurred---\n" elif cmd == "getwork": try: data = raw_input("Data (optional): ") try: print access.gettransaction(data) except: print access.gettransaction() except: print "\n---An error occurred---\n" elif cmd == "help": try: cmd = raw_input(...
pt: print "\n---An error occurred---\n" elif cmd == "listaccounts": try: mc = raw_input("Minimum confirmations (optional): ") try: print access.listaccounts(mc) except: print access.listaccounts() except: print "\n---An error occurred---\n" elif cmd == "listreceivedbyaccount": try: mc = raw_input...
ViktorMarinov/get-a-room
get_a_room/rooms/room_serializers.py
Python
mit
505
0
from rooms.models import Room from rest_framework import serializers class RoomSerializer(serializers.HyperlinkedModelSerializer): """ Serializer for Room model with all fields. """
class Meta: model = Room fields = ('url', 'number', 'capacity', 'is_computer_room') class SimpleRoomSerializer(serializers.ModelSerializer): """ Another serializer for Room model with fewer fields. """ class Meta: model = Room
fields = ('url', 'number')
EmreAtes/spack
var/spack/repos/builtin/packages/py-bsddb3/package.py
Python
lgpl-2.1
1,821
0.000549
###################################################
########################### # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-647188 # # For details, see htt
ps://github.com/spack/spack # Please also see the NOTICE and LICENSE files for our notice and the LGPL. # # This program 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) version 2.1, February 1999. # # ...
google/distla_core
distla/struc_pack/single-host/struc_pack_wrapper.py
Python
apache-2.0
3,236
0.00309
# Copyright 2021 The Distla 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 applicable ...
f electrons in the system. """ r_task = ctypes.c_int(0) para_mode = ctypes.c_int(0) n_basis = ctypes.c_int(0) n_elec = ctypes.c_double(0.0) n_lrow = ctypes.c_int(0) n_lcol = ctypes.c_int(0) path_buffer = path.encode('ASCII') self._libstruc_pack.c_struc_pack_init_rw( byref(self...
_mode, n_basis, n_elec) self._libstruc_pack.c_struc_pack_read_mat_dim( self.rh, path_buffer, byref(n_elec), byref(n_basis), byref(n_lrow), byref(n_lcol)) matrix = np.zeros([n_basis.value, n_basis.value], dtype='double') pointer_to_matrix = matrix.ctypes.data_as(ctypes.POINTER(ctypes.c_double)) ...
LLNL/spack
lib/spack/spack/cmd/compiler.py
Python
lgpl-2.1
7,261
0.000413
# 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 __future__ import print_function import argparse import sys from six import iteritems import llnl.util.tty as tty ...
-scope', choices=scopes, metavar=scopes_metavar, default=spack.config.default_modify_scope('compilers'), help="configuration scope to modify") # Remove remove_parser = sp.add_parser( 'remove', aliases=['rm'], help='remove compiler by spec') remove_parser.add_argument( '-
a', '--all', action='store_true', help='remove ALL compilers that match spec') remove_parser.add_argument('compiler_spec') remove_parser.add_argument( '--scope', choices=scopes, metavar=scopes_metavar, default=spack.config.default_modify_scope('compilers'), help="configuration sc...
howard/p1tr-tng
p1tr/logwrap.py
Python
mit
5,616
0.003561
""" Provides convenience functions for logging. Wraps around Python's logging module. A word about the logging functions (debug, info, warning, error, critical): The first parameter is the message to be logged. Additional to that, a number of keyword arguments is supported: * server - If only this is set, the message ...
hat when logging to a channel, the severity is not displayed. """ import logging import os.path # Constants DEBUG = logging.DEBUG INFO = logging.INFO WARNING = logging.WARNING ERROR = logging.ERROR
CRITICAL = logging.CRITICAL _logdir = 'log' _loglevel = logging.ERROR _to_stderr = True _loggers = dict() _default_format = logging.Formatter('%(asctime)s %(levelname)s\t%(message)s') _channel_format = logging.Formatter('%(asctime)s %(message)s') def _clear_loggers(): """ Terminates the existing loggers, so...
sigurdga/maps
tests/test_example.py
Python
gpl-3.0
1,448
0.01105
#!/usr/bin/python # -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*- ### BEGIN LICENSE # Copyright (C) 2012 Sigurd Gartmann sigurdga-ubuntu@sigurdga.no # 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 pub...
General Public License along # with this program. If not, see <http://
www.gnu.org/licenses/>. ### END LICENSE import sys import os.path import unittest sys.path.insert(0, os.path.realpath(os.path.join(os.path.dirname(__file__), ".."))) from maps import AboutMapsDialog class TestExample(unittest.TestCase): def setUp(self): self.AboutMapsDialog_members = [ 'AboutDial...
gencer/python-phonenumbers
python/phonenumbers/data/region_VA.py
Python
apache-2.0
1,604
0.006858
"""Auto-generated file, do not edit by hand. VA metadata""
" from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata PHONE_METADATA_VA = PhoneMetadata(id='VA', country_code=39, international_prefix='00', general_desc=PhoneNumberDesc(national_number_pattern='(?:0(?:878\\d{5}|6698\\d{5})|[1589]\\d{5,10}|3(?:[12457-9]\\d{8}|[36]\\d{7,9}))', possible_length=(...
11)), fixed_line=PhoneNumberDesc(national_number_pattern='06698\\d{5}', example_number='0669812345', possible_length=(10,)), mobile=PhoneNumberDesc(national_number_pattern='3(?:[12457-9]\\d{8}|6\\d{7,8}|3\\d{7,9})', example_number='3123456789', possible_length=(9, 10, 11)), toll_free=PhoneNumberDesc(nation...
DESHRAJ/django-organizations
organizations/app_settings.py
Python
bsd-2-clause
1,816
0.002753
# -*- coding: utf-8 -*- # Copyright (c) 2012-2015, Ben Lopatin and contributors # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # Redistri
butions of sou
rce code must retain the above copyright notice, this # list of conditions and the following disclaimer. Redistributions in binary # form must reproduce the above copyright notice, this list of conditions and the # following disclaimer in the documentation and/or other materials provided with # the distribution # # TH...
thatneat/dotfiles
other_applications/sublime-text-3/Packages/SublimeLinter-contrib-eslint/linter.py
Python
mit
3,189
0.001881
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by roadhump # Copyright (c) 2014 roadhump # # License: MIT # """This module exports the ESLint plugin class.""" import sublime import os import re from SublimeLinter.lint import NodeLinter class ESLint(NodeLinter): ...
"Error", "", match.group(0), None)] match = self.crash_regex.match(output) if match: msg = "ESLint crashed: %s" % match.group(1) return [(match, 0, None, "Error", "", msg, None)] return super().find_errors(output) def split_match(self, match): """ E...
s. """ v1message = 'File ignored because of your .eslintignore file. Use --no-ignore to override.' v2message = 'File ignored because of a matching ignore pattern. Use --no-ignore to override.' match, line, col, error, warning, message, near = super().split_match(match) if messa...
you21979/mysql_batch
bin/partition_create.py
Python
apache-2.0
3,384
0.008274
#!/usr/bin/python """ Copyright 2013 yuki akiyama (you2197901 at gmail.com) 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 ...
1) strname = pname.strftime('p%Y%m%d') strrange = prange.strftime('%Y-%m-%d') return "".join(("PARTITION ", strname, " VALUES LESS THAN (TO_DAYS('", strrange, "'))
ENGINE=InnoDB")) def partition_create_by_range(baseday, count): list = [] for i in range(count): list.append(partition_create_by_day(baseday + datetime.timedelta(i))) return list def partition_make_create_sql(tablename, list): sql = "" head = "ALTER TABLE " + tablename + " REORGANIZE PARTITI...
alanjds/drf-nested-routers
rest_framework_nested/runtests/runtests.py
Python
apache-2.0
1,379
0.004351
#!/usr/bin/env python # http://ericholscher.com/blog/2009/jun/29/enable-setuppy-test-your-django-apps/ # http://www.travisswicegood.com/2010/01/17/django-virtualenv-pip-and-fabric/ # http://code.djangoproject.com/svn/django/trunk/tests/runtests.py import os import sys # fix sys path so we don't need to setup PYTHONPA...
tTestClass` you want to test. Append a method name if you only want to test a specific method of that class. """ def main(): TestRunner = get_runner(settings) import ipdb ipdb.set_trace() test_runner = TestRunner() if len(sys.argv) == 2: test_case = '.' + sys.argv[1] el
if len(sys.argv) == 1: test_case = '' else: print(usage()) sys.exit(1) test_module_name = 'rest_framework_nested.tests' if django.VERSION[0] == 1 and django.VERSION[1] < 6: test_module_name = 'tests' failures = test_runner.run_tests([test_module_name + test_case]) s...
Eficode/robotframework-imagehorizonlibrary
tests/utest/test_screenshot.py
Python
mit
2,185
0
# -*- coding: utf-8 -*- from os import getcwd, listdir from os.path import abspath, dirname, isdir, join as path_join from shutil import rmtree from sys import exc_info from tempfile import mkdtemp from unittest import TestCase from mock import patch, MagicMock from robot.libraries.BuiltIn import BuiltIn CURDIR = abs...
with( path_join(folder, expected_filename % i)) self.mock.reset_mock() def test_take_a_screenshot(self): self._take_screenshot_many_times('ImageHorizon-screenshot-%d.png') def test_take_a_screenshot_inside_robot(self): with patch.object(BuiltIn, 'get_variable_value'...
valid_folder(self): from ImageHorizonLibrary import ScreenshotFolderException for index, invalid_folder in enumerate((None, 0, False), 1): self.lib.screenshot_folder = invalid_folder expected = path_join(getcwd(), 'ImageHorizon-screenshot-%d.png'...
tensorflow/tensorflow
tensorflow/python/keras/layers/pooling_test.py
Python
apache-2.0
13,742
0.002183
# Copyright 2016 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...
ut_shape=(3, 4, 5), expected_output_shape=(None, 1, 5)) testing_utils.layer_test( keras.layers.pooling.GlobalM
axPooling1D, kwargs={'data_format': 'channels_first', 'keepdims': True}, input_shape=(3, 4, 5), expected_output_shape=(None, 4, 1)) testing_utils.layer_test( keras.layers.pooling.GlobalAveragePooling1D, kwargs={'keepdims': True}, input_shape=(3, 4, 5), expecte...
mwernerds/giscup2015
python/setup.py
Python
gpl-2.0
465
0.027957
from setuptools import setup, Extension #from distutils.core import setup, Ex
tension module1 = Extension('giscup15', sources = ['giscup15.cpp'], extra_compile_args=['-std=c++11'], libraries=['shp']) setup (name = 'giscup15', version = '1.0', description = 'This is a wrapper around the shortest path engine from GIS Cup 2...
module1])
XMLPro/ManagementSystem
system/admin.py
Python
mit
414
0
from django.contrib import admin from .
models import CustomUser, Equipment, Search, TagManagement from .models import Reserved, Request, Vote, Log, Tag admin.site.register(CustomUser) admin.site.register(Equipment) admin.site.register(Search) admin.site.register(Reserved) admin.site.register(Request) admin.site.register(Vote) admin.site.register(Log) admin...
n.site.register(Tag)
JaviMerino/trappy
trappy/devfreq_power.py
Python
apache-2.0
2,302
0.001738
# Copyright 2015-2016 ARM Limited # # 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 w...
rt Base from trappy.dynamic import register_ftrace_parser class DevfreqInPower(Base): """P
rocess de devfreq cooling device data regarding get_power in an FTrace dump""" name = "devfreq_in_power" """The name of the :mod:`pandas.DataFrame` member that will be created in a :mod:`trappy.ftrace.FTrace` object""" unique_word="thermal_power_devfreq_get_power:" """The event name in the trace""...
rero/reroils-app
tests/api/acq_orders/test_acq_orders_permissions.py
Python
gpl-2.0
7,056
0
# -*- coding: utf-8 -*- # # RERO ILS # Copyright (C) 2020 RERO # Copyright (C) 2020 UCLouvain # # 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, version 3 of the License. # # This program ...
sert data['update']['can'] assert data['delete']['can'] res = client.get(acq_order_saxon_permission_url) assert res.status_code == 200 data = get_json(res) assert not data['r
ead']['can'] assert data['list']['can'] assert not data['update']['can'] assert not data['delete']['can'] res = client.get(acq_order_sion_permission_url) assert res.status_code == 200 data = get_json(res) assert not data['read']['can'] assert data['list']['can'] assert not data['upd...
0--key/lib
portfolio/Python/scrapy/topgeartrading/4x4tyrescouk.py
Python
apache-2.0
2,085
0.004317
import re from scrapy.spider import BaseSpider from scrapy.selector import HtmlXPathSelector from scrapy.http import Request, FormRequest, HtmlResponse from scrapy.utils.response import get_base_url from scrapy.utils.url import urljoin_rfc from product_spiders.items import Product, ProductLoader class TyresCoUk(Base...
): if not isinstance(response, HtmlResponse): return hxs
= HtmlXPathSelector(response) # categories category_urls = hxs.select(u'//div[@id="categoryTab"]//a/@href').extract() for url in category_urls: yield Request(url) # subcategories subcategories_urls = hxs.select(u'//div[@id="thecategories"]//a/@href').extract() ...
AlexStarov/Shop
applications/comment/admin.py
Python
apache-2.0
2,151
0.006708
# coding=utf-8 __author__ = 'Админ' from django.contrib import admin from applications.comment.models import Comment class CommentAdmin(admin.ModelAdmin, ): list_display = ['pk', 'record_parent', 'serial_number', 'is_active', 'name', 'created_at', 'updated_at', ] list_display_links = ['pk', 'record_parent',...
antity', 'price', ] # list_display_lin
ks = ['pk', 'object_id', 'product', 'quantity', 'price', ] #admin.site.register(Product, ProductAdmin, )
bd-j/bsfh
prospect/utils/plotting.py
Python
gpl-2.0
9,476
0.000739
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np try: import matplotlib.pyplot as pl except(ImportError): pass __all__ = ["get_best", "get_truths", "get_percentiles", "get_stats", "posterior_samples", "hist_samples", "joint_pdf", "compute_sigma_level", "trim_walkers", "fi...
_labels" keys. :param nsample: Number of random samples to draw. :param **kwargs: Extra keywords are passed to ``hist_samples``. :returns thetas: A list of parameter vectors pulled at random from the chain, of same length as ``samples``. """ flatchain, pnames = his...
s) weights = res.get("weights", None) ns = flatchain.shape[0] if nsample is None: nsample = ns s = np.random.choice(ns, p=weights, size=nsample) thetas = flatchain[s, :] return thetas def hist_samples(res, showpars=None, start=0, thin=1, return_lnprob=False, **extras):...
Pinecast/pinecast
analytics/views_podcast.py
Python
apache-2.0
6,182
0.003235
from django.utils.translation import ugettext import accounts.payment_plans as plans from . import query from .constants import SOURCE_MAP from .formatter import Format from .util import country_code_map, restrict, specific_location_timeframe from accounts.models import UserSettings from pinecast.helpers import revers...
.last_thirty() .group('country')) return f.driver.format_country(label=ugettext('Listens')) @restrict(plans.PLAN_PRO) def podcast_listener_locations_specific_source(req, pod):
return [ {'label': country_code_map[x], 'value': x} for x in Format(req, 'listen-country') .select(v='count') .where(podcast=str(pod.id)) .during('sixmonth') .group('country') .driver.get_resulting_groups() if x is not None...
SUSE/azure-sdk-for-python
azure-mgmt-recoveryservicesbackup/azure/mgmt/recoveryservicesbackup/models/mab_protection_policy.py
Python
mit
1,955
0.002046
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
tionPolicy, self).__init__(protected_items_count=protected_items_count) self.schedule_policy = schedule_policy self.retention_policy = retention_poli
cy self.backup_management_type = 'MAB'
biocyberman/bcbio-nextgen
tests/unit/pipeline/test_rnaseq.py
Python
mit
976
0
import pytest from bcbio.pipeline import rnaseq @pytest.yield_fixture def ericscript_run(mocker): yield mocker.patch('bcbio.pipeline.rnaseq.ericscript.run', autospec=True) @pytest.fixture def sample(): return { 'config': { 'algorithm': { 'fusion_mode': True, ...
def test_detect_fusion_callers
_calls_for_each_sample(ericscript_run, sample): samples = [[sample], [sample]] rnaseq.detect_fusions(samples) assert ericscript_run.call_count == len(samples) def test_detect_fusions_returns_updated_samples(ericscript_run, sample): samples = [[sample]] result = rnaseq.detect_fusions(samples) a...
pcabido/socorro
socorro/external/http/correlations.py
Python
mpl-2.0
6,839
0.000731
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import datetime import os import re import stat import tempfile import time import requests from socorro.lib import ex...
break elif on: try: this_signature = line.split('|')[-2].strip() if this_signature == signature: if signature_found: break signature_found = True ...
p() count = int(COUNT_REGEX.findall(rest)[0]) continue except IndexError: pass if signature_found: if not line.strip(): break else: ...
jresendiz27/EvolutionaryComputing
practices/first/evolutionaryStrategies/functions.py
Python
apache-2.0
1,490
0.010738
"""-0.75/(1+x**2)-(0.65*x*math.atan(1/x))+0.65 (-4* x**2 - 20*x - 100) + (1 - x)**4 3*x**2+ 12/(x**3) - 5 3*x**4 + x**2 - 2*x + 1 10+x**3-2*x-5*(np.finfo(float).eps)**x x**2- 10*(np.finfo(float).eps)**(0.1*x) (10*x**3+3*x**2+5)**2 0.5/math.sqrt(1+x**2)- math.sqrt(1+x**2)*(1-0.5/(1+x**2))+x (np.finfo(float).eps)**x-x**3...
4 #4 variables x[0]**2+x[1]**2+x[2]**2 #3 variables 100*(x[0]**2-x[1])**2+(1-x[0])**2 math.floor(x[0])+math.floor(
x[1])+math.floor(x[2])+math.floor(x[3])+math.floor(x[4]) #5 variables #23 - 30 variables suma = 0 for i in range(1,30): suma+= i*x[i-1]**4 return suma + random.gauss(0,1) #24 a = [[-32,-16,0,16,32,-32,-16,0,16,32,-32,-16,0,16,32,-32,-16,0,16,32,-32,-16,0,16,32], [-32,-32,-32,-32,-32,-16,-16,-16,-16,-16,0,0,0,0,0,16,16...
googleads/google-ads-python
google/ads/googleads/oauth2.py
Python
apache-2.0
4,658
0.000215
# Copyright 2019 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
get("client_secret"), config_data.get("refresh_token"), http_proxy=config_data.
get("http_proxy"), ) elif all(key in config_data for key in required_service_account_keys): # Using the Service Account Flow return get_service_account_credentials( config_data.get("json_key_file_path"), config_data.get("impersonated_email"), http_proxy=co...
amunozf/legibilidad
legibilidad.py
Python
gpl-3.0
8,040
0.008123
# Legibilidad 2 (beta) # Averigua la legibilidad de un texto # Spanish readability calculations # © 2016 Alejandro Muñoz Fernández #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 ...
word = re.sub(r'\W+', '', word) syllables = separasilabas.silabizer() return len(syllables(word)) def count_all_sy
llables(text): ''' The whole text syllable count ''' text = ''.join(filter(lambda x: not x.isdigit(), text)) clean = re.compile('\W+') text = clean.sub(' ', text).strip() text = text.split() text = filter(None, text) total = 0 for word in text: total += count_syllabl...
jnimmo/pyIntesisHome
examples/cli_example.py
Python
mit
2,243
0
import argparse import asyncio import logging import sys from pyintesishome import IntesisHome, IntesisHomeLocal from pyintesishome.const import ( DEVICE_AIRCONWITHME, DEVICE_ANYWAIR, DEVICE_INTESISHOME, DEVICE_INTESISHOME_LOCAL, ) _LOGGER = logging.getLogger("pyintesishome") async def main(loop): ...
intesishome.com", metavar="PASSWORD", default=None, ) parser.add_argument( "--device", type=str, dest="device", help="Select API to connect to", choices=[ DEVI
CE_INTESISHOME, DEVICE_AIRCONWITHME, DEVICE_ANYWAIR, DEVICE_INTESISHOME_LOCAL, ], default=DEVICE_INTESISHOME, ) parser.add_argument( "--host", type=str, dest="host", help="Host IP or name when using device intesishome_local", ...