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
connectIOT/iottoolkit
iottoolkit/core/Agent.py
Python
apache-2.0
6,297
0.015245
''' Created on Sep 15, 2012 Agent classes. Contains references to instances of classes containing observer handlers and code Agent Instances are created automatically. Create a named Handler instance under the Agent, as an instance of the desired handler class, by create (POST) of a JSON object containing a dicti...
Elements = linkPath.split('/') for pathElement in self._pathElements[:-1] : # all but the last, which should be the endpoint self._currentDict = self._currentDict[pathElement].resources self._resource = self._currentDict[self._pathElements[-1]
] self._linkCache.update({ self._linkPath : self._resource }) return self._resource def getByLink(self, linkPath): return self.linkToRef(linkPath).get() def setByLink(self, linkPath, newValue): self.linkToRef(linkPath).set(newValue) class addHandler(Handler): # an exa...
coderbone/SickRage-alt
sickbeard/providers/bitcannon.py
Python
gpl-3.0
5,147
0.002137
# coding=utf-8 # Author: Dustyn Gibson <miigotu@gmail.com> # # URL: https://sickchill.github.io # # This file is part of SickChill. # # SickChill 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 ...
(title, seeders, leechers), logger.DEBUG) continue size = convert_size(result.pop("size", -1)) or -1 item = {'title': title, 'link': download_url, 'size': size, 'seeders': seeders, 'leechers': leechers, 'hash': ''} ...
(title, seeders, leechers), logger.DEBUG) items.append(item) except (AttributeError, TypeError, KeyError, ValueError): continue # For each search mode sort all the items by seeders if available items.sort(key=lambda d:...
astyl/wxPlotLab
mplotlab/models/projections.py
Python
mit
920
0.031522
# -*-coding:Utf-8 -* from abcmodels import AModel from mplotlab.utils.abctypes import FLOAT,LIST,STRING,BOOL,RegisterType class AProjection(AModel): parametersInfo = list(AModel.paramet
ersInfo) parametersInfo.extend([ ("plotmodels",LIST,lambda:[],"plotModels"), ("title", STRING,lambda:"title","axes title"), ("xlabel", STRING,lambda:"","axes xlabel"), ("ylabel", STRING,lambda:"","axes ylabel"), ]) class Projection2D(AProjection): parametersInfo = ...
FLOAT,lambda:0.0,"axes xmin"), ("xmax", FLOAT,lambda:1.0,"axes xmax"), ("ymin", FLOAT,lambda:0.0,"axes ymin"), ("ymax", FLOAT,lambda:1.0,"axes ymax"), ]) RegisterType(AProjection) RegisterType(Projection2D)
radekp/qt
util/local_database/qlocalexml2cpp.py
Python
lgpl-2.1
18,286
0.004812
#!/usr/bin/env python ############################################################################# ## ## Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ## All rights reserved. ## Contact: Nokia Corporation (qt-info@nokia.com) ## ## This file is part of the test suite of the Qt Toolkit. ## ## $QT_BEG...
bling, name): sib = sibling.nextSibling while sib: if sib.nodeType == sibling.ELEMENT_NODE \ and (not name or sib.nodeName == name): return sib sib = sib.nextSibling return False def eltText(elt): result = "" child = elt.f
irstChild while child: if child.nodeType == elt.TEXT_NODE: if result: result += " " result += child.nodeValue child = child.nextSibling return result def loadLanguageMap(doc): result = {} language_list_elt = firstChildElt(doc.documentElement, "la...
mic4ael/indico
indico/util/roles.py
Python
mit
3,193
0.003445
# This file is part of Indico. # Copyright (C) 2002 - 2020 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from __future__ import unicode_literals import csv from flask import flash, session from indico.core.er...
s: {email}').format(row=num_row, email=email)) if email in emails: raise UserValueError(_('Row {}: email address is not unique').format(num_row)) emails.add(email) users = set(User.query.filter(~User.is_deleted, User.all_emails.in_(emails))) users_emails = {user....
new_members = users - self.role.members return new_members, users, unknown_emails def _process(self): form = ImportMembersCSVForm() if form.validate_on_submit(): new_members, users, unknown_emails = self.import_members_from_csv(form.source_file.data) if form.remov...
openstack-packages/delorean
dlrn/migrations/versions/7fbd3a18502f_extra_tables_for_votes_on_aggregates.py
Python
apache-2.0
2,153
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...
entifiers, used by Alembic. revision = '7fbd3a18502f' down_revision = '00a31f1f39c0' branch_labels = None depends_on = None def upgrade(): # Since SQLite3 does not allow ALTER TABLE statements, we need to do a # batch operation: http://alembic.zzzcomputing.com/en/latest/batch.html with op.batch_alter_tabl...
4), nullable=True)) op.create_table('civotes_agg', sa.Column('id', sa.Integer(), nullable=False), sa.Column('ref_hash', sa.String(64), nullable=False), sa.Column('ci_name', sa.String(256), nullable=True), ...
Alan-Jairo/topgeo
doc.py
Python
mit
103
0.009709
def topgeo ('topgeo'): """ Esta libreria funciona para realizar ca
lculos topografico
s. """
RihanWu/vocabtool
database.py
Python
mit
323
0
# -*- coding: utf-8 -*- """VocabTool database module This is the database module of 'VocabTool'. It connects the program with external database
""" # Standard library import sqlite3 # TODO: Implement function:add_to_database <RihanW> def add_to_database
(word): """Add the current word to local database""" pass
jongyeob/swpy
swpy/dscovr/__init__.py
Python
gpl-2.0
102
0.009804
from swpy.dscovr.clients import
DscovrC
lient, DscovrRTClient from swpy.dscovr.graph import DscovrGraph
neurodata/ndstore
scripts/ingest/mitra/jp2kakadu.py
Python
apache-2.0
1,931
0.016572
# Copyright 2014 NeuroData (http://neurodata.io) # # 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...
-1: subfile = 'F/' elif name.find('IHC') != -1: subfile = 'IHC/' elif name.find('N') != -1: subfile = 'N/' # Determine the write location of the file. This was /mnt on datascopes writelocation = result.location+subfile+name.split(result.path)[1].split('_')[3].split('.')[0] # Call...
ocation) ] ) if __name__ == "__main__": main()
euccas/CodingPuzzles-Python
leet/source/binarysearch/find_k_closest_elements.py
Python
mit
4,030
0.005955
class Solution(): def kClosestNumbers(A, target, k): if A is None or len(A) == 0 or target is None or k is None or k == 0: return [] start, end = 0, len(A) - 1 closest = 0 while (start + 1 < end): mid = start + (end - start)//2 if target == A[mid]...
is None: return []
# find the number closest to x idx = self.find_closest_index(arr, x) return self.find_k(arr, k, x, idx) def find_closest_index(self, arr, x): start, end = 0, len(arr) - 1 while start + 1 < end: mid = start + (end - start) // 2 if arr[mid] == x: ...
etherkit/OpenBeacon2
macos/venv/lib/python3.8/site-packages/_pyinstaller_hooks_contrib/tests/conftest.py
Python
gpl-3.0
524
0
# ------------------------------------------------------------------ # Copyright (c) 2020 PyInstaller Development Team. # # This file i
s distributed under the terms of the GNU General Public # License (version 2.0 or later). # # The full license is available in LICENSE.GPL.txt, distributed with # this software. # # SPDX-License-Identifier: GPL-2.0-or-later # ------------------------------------------------------------------ # Import all fixtures from ...
aller.utils.conftest import *
zhengfish/examples
python3/ftp/ftpmirror.py
Python
gpl-2.0
13,096
0.0042
#! /usr/bin/env python # # @refer # http://svn.python.org/projects/python/trunk/Tools/scripts/ftpmirror.py # @note # """ Mirror a remote ftp subtree into a local directory tree. usage: ftpmirror [-v] [-q] [-i] [-m] [-n] [-r] [-s pat] [-l username [-p passwd [-a account]]] hostname[:...
xit(2) verbose = 1 # 0 for -q, 2 for -v interactive = 0 mac = 0 rmok = 0 nologin = 0 skippats = ['.', '..', '.mirrorinfo'] # Main program: parse command line and start processing def main(): global verbose, interactive, mac, rmok, nologin try: opts, args = getopt.getopt(sys.argv[1:], 'a:bil:mnp:qrs:v'...
t = '' if not args: usage('hostname missing') host = args[0] port = 0 if ':' in host: host, port = host.split(':', 1) port = int(port) try: auth = netrc.netrc().authenticators(host) if auth is not None: login, account, passwd = auth except (netrc.Netrc...
kostyll/usb-flash-network-monitor
server/utils.py
Python
mit
246
0.012195
# -*- coding:utf-8 -*- # from __future__ import unicode_literals def clean_up_double_spaces(line): while line.find(' ') >-1: line = line.replace(' ',' ') return line # in futur
e will be gettext function def _(x):
return x
sychsergiy/DocFlow
doc_flow/settings/base.py
Python
bsd-3-clause
3,695
0.001624
import os import sys # PATH vars BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) root = lambda *x: os.path.join(BASE_DIR, *x) sys.path.insert(0, root('apps')) # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'CHANGE THIS!!!' # SECURITY WARNING: don't run with ...
s', ] SITE_ID = 1 PROJECT_APPS = [ 'accounts', 'filters', 'documents', ] INSTALLED_APPS += PROJECT_APPS MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.mi...
are.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'doc_flow.apps.accounts.middleware.LoginRequiredMiddleware', ] ROOT_URLCONF = 'doc_flow.urls' # Python dotted path to the WSGI application used by Django'...
andredalton/bcc
2014/MAC0242/miniep3/miniep3.py
Python
apache-2.0
5,396
0.004872
#! /usr/bin/env python3 import sys import re def uso(): """Imprime instruções de uso do programa.""" uso = """ Este programa gera a ordem correta de inclusão em um banco de dados. Passe o nome dos arquivos na linha de comando. Caso queira imprimir ocorrências de referência circular ou inexistente ...
le]: dic[table].remove(key) procura(dic, ordem, verb) def procedencia(lst, verb): """Gera uma lista de procedencia para cada tabela.
Inicialmente a função iria trabalhar com o arquivo separado por linhas, mas como o arquivo pode ser inteiro feito em apenas uma linha modifiquei a estratégia para uma varredura de estados. Não me preocupei com erros de sintaxe. Lista de estados: 0: Procurando por uma instrução CREATE ...
nop33/indico
indico/modules/events/contributions/operations.py
Python
gpl-3.0
9,065
0.002978
# This file is part of Indico. # Copyright (C) 2002 - 2017 European Organization for Nuclear Research (CERN). # # Indico 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 (a...
db.session.flush() signals.event.subcontribution_deleted.send(subcontrib) logger.info('Subcontribution %s deleted by %s',
subcontrib, session.user) subcontrib.event.log(EventLogRealm.management, EventLogKind.negative, 'Subcontributions', 'Subcontribution "{}" has been deleted'.format(subcontrib.title), session.user) @no_autoflush def create_contribution_from_abstract(abstract, contrib_session=None): even...
valmynd/MediaFetcher
src/main.py
Python
gpl-3.0
9,141
0.021879
#!/usr/bin/env python3 from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * from models.settingsmodel import SettingsModel from views.clipboardview import ClipBoardView from views.downloadview import DownloadView from views.settingsview import SettingsDialog, SettingsToolBar, Configurabl...
elf.mainWindow.tabBar.setCurrentWidget(self.mainWindow.downloadView) self.mainWindow.downloadView.model().start() class MainWindow(QMainWindow): aboutToQuit = pyqtSignal() def __init__(self): QMainWindow.__init__(self) self.setWindowTitle("Media Fetcher") self.setWindowIcon(QIcon("../img/icon.png")) sel...
olutePath() self.settingsModel = SettingsModel(self.settings) self.settingsDialog = SettingsDialog(self, self.settingsModel) self.statusBar = SettingsToolBar(self, self.settingsModel) self.addToolBar(Qt.BottomToolBarArea, self.statusBar) self.toolBar = MainToolBar(self) self.addToolBar(Qt.TopToolBarArea, se...
bgmerrell/desmod
tests/test_queue.py
Python
mit
1,789
0
from desmod.queue import Queue, PriorityQueue def test_mq(env): queue = Queue(env, capacity=2) def producer(msg, wait): yield env.timeout(wait) yield queue.put(msg) def consumer(expected_msg, wait): yield env.timeout(wait) msg = yield queue.get() assert msg == exp...
for i in range(5): yield queue.put(i) yield env.timeout(1) def consumer(env): yield env.timeout(5) for i in range(3): msg = yield queue.get() assert msg == i def full_waiter(env): yield queue.when_full() result.append('full'...
ny() assert env.now == 1 result.append('any') env.process(producer(env)) env.process(consumer(env)) env.process(full_waiter(env)) env.process(any_waiter(env)) env.process(any_waiter(env)) env.run() assert queue.items assert queue.is_full assert 'full' in result a...
xuewei4d/scikit-learn
asv_benchmarks/benchmarks/ensemble.py
Python
bsd-3-clause
3,520
0
from sklearn.experimental import enable_hist_gradient_boosting # noqa from sklearn.ensemble import (RandomForestClassifier, GradientBoostingClassifier, HistGradientBoostingClassifier) from .common import Benchmark, Estimator, Predictor from .datasets import ...
param_names = ['representation', 'n_jobs'] params = (['dense', 'sp
arse'], Benchmark.n_jobs_vals) def setup_cache(self): super().setup_cache() def make_data(self, params): representation, n_jobs = params if representation == 'sparse': data = _20newsgroups_highdim_dataset() else: data = _20newsgroups_lowdim_dataset() ...
SergeySatskiy/ttkiosk
src/ui/1440x900/Logo.py
Python
gpl-2.0
3,995
0.009512
# # ttkiosk - table tennis club touch screen based kiosk. # Copyright (C) 2009 Sergey Satskiy # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your op...
__init__( self, firstLabel ): QtGui.QLabel.__init__( self, firstLabel ) def mouseReleaseEvent( self, event ): """ go home """ ui.navigateHome() if GlobalD
ata().isAdmin: ui.hideForm( 'TopBar' ) ui.showForm( 'AdminTopBar' ) return class Ui_Logo(ui.FormBaseClass): def setupUi(self, Logo, path): ui.FormBaseClass.__init__(self) Logo.setObjectName("Logo") Logo.resize(400, 300) self.gridLayoutWidget = QtGui...
rmaceissoft/django-photologue
photologue/views.py
Python
bsd-3-clause
5,802
0.003792
import warnings from django.views.generic.dates import ArchiveIndexView, DateDetailView, DayArchiveView, MonthArchiveView, \ YearArchiveView from django.views.generic.detail import DetailView from django.views.generic.list import ListView from django.views.generic.base import RedirectView from django.core.urlresol...
'slug': kwargs['slug'
]}) class PhotoDayArchiveOldView(DeprecatedMonthMixin, RedirectView): permanent = True def get_redirect_url(self, *args, **kwargs): super(PhotoDayArchiveOldView, self).get_redirect_url(*args, **kwargs) return reverse('photologue:photo-archive-day', kwargs={'year': kwargs['year'], ...
fs714/drfilter
tools/novasetup.py
Python
apache-2.0
995
0
# Still some problems... import time import shutil from configobj import ConfigObj NOVA_API_CONF = "/etc/nova/api-paste.ini" OS_API_SEC = "composite:openstack_compute_api_v2" DR_FILTER_TARGET_KEY = "keystone_nolimit" DR_FILTER_TARGET_KEY_VALUE = "compute_req_id faultwrap sizelimit " \ "au...
_VALUE conf.write() for sec in conf: print(sec) for key in conf[se
c]: print("\t" + key + " = " + conf[sec][key])
rfhk/awo-custom
sale_line_quant_extended/models/__init__.py
Python
lgpl-3.0
208
0
# -*- coding: utf-8 -*- from
. import sale_order from . import sale_order_line from . import procurement from . import stock_quant from . import stock_move from . import
stock_picking from . import purchase
ksamuel/smit
vessels/crawler/wamp_client.py
Python
mit
4,286
0.001633
import os import sys import asyncio from pathlib import Path import pendulum sys.path.append(str(Path(__file__).absolute().parent.parent.parent)) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings") from django.core.wsgi import get_wsgi_application # noqa application = get_wsgi_application() from a...
tivity.vessel
log.info(f'Update vessel "{vessel.id}" helico to "{helico}"') vessel.helico = helico or None vessel.save() return activity.to_dict( timezone="Europe/Paris", include_vessel=True ) activity = await loop.run_in_executor(Non...
amirgeva/py2d
tools/combine_tiles.py
Python
bsd-2-clause
1,330
0
import sys import glob from PIL import Image import cv2 import numpy as
np import cmdline as cmd gap = 0 output =
'tiles.png' def set_gap(param): global gap gap = int(param) def set_output(param): global output output = param def main(): cmd.flag('gap', True, set_gap) cmd.flag('out', True, set_output) cmd.parse() print(f"Combining images with gap {gap}") x = gap y = gap rects = {} ...
Captain-Coder/tribler
Tribler/Core/Utilities/install_dir.py
Python
lgpl-3.0
1,960
0.002041
""" install_dir. Author(s): Elric Milon """ from __future__ import absolute_import import os.path import sys from six import text_type import Tribler from Tribler.Core.osutils import is_android def is_frozen(): """ Return whether we are running in a frozen environment """ try: # PyInstaller...
This function is used from tribler.py too, but can't be there as tribler.py gets frozen into an exe on windows. def determine_install_dir(): # Niels, 2011-03-03: Working dir sometimes set to a browsers working dir # only seen on windows # apply trick to obtain the executable location # see http://www.p...
indows # TODO(emilon): tribler_main.py is not frozen, so I think the special # treatment for windows could be removed (Needs to be tested) if sys.platform == 'win32': return get_base_path() elif sys.platform == 'darwin': return get_base_path() elif is_android(): return os.pa...
dana-i2cat/felix
modules/resource/manager/stitching-entity/src/delegate/geni/v3/models/sdn_resource_table.py
Python
apache-2.0
1,820
0.004396
import pymongo class Ports(object): def __init__(self): self.__ports = [] def get(self): return self.__ports def add(self, name, num): port = {'name': name, 'num': num} self.__ports.append(port) class SDNDatapathResourceTable(object): def __in...
d, 'component_manager_id': component_manager_id, 'dpid': dpid, 'ports': ports} # Return the ID of the new entry return self.table.insert(row) def delete(self, rm_uuid,
component_id, component_manager_id, dpid): row = {'rm_uuid': rm_uuid, 'component_id': component_id, 'component_manager_id': component_manager_id, 'dpid': dpid} self.table.remove(row) class SDNLinkResourceTable(object): def __init__(self): self.ta...
sony/nnabla
python/test/function/test_where.py
Python
apache-2.0
1,821
0
# Copyright 2019,2020,2021 Sony Corporation. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed...
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 pytest import numpy as np import nnabla.functions as F fr...
est_utils import list_context ctxs = list_context('Where') @pytest.mark.parametrize("ctx, func_name", ctxs) @pytest.mark.parametrize("seed", [313]) def test_where_forward_backward(seed, ctx, func_name): from nbla_test_utils import function_tester rng = np.random.RandomState(seed) inshape = (2, 3, 4) ...
mrbox/django
django/test/utils.py
Python
bsd-3-clause
21,134
0.000284
import logging import re import sys import time import warnings from contextlib import contextmanager from functools import wraps from unittest import skipIf, skipUnless from xml.dom.minidom import Node, parseString from django.apps import apps from django.conf import UserSettingsHolder, settings from django.core impo...
keys |= set(dict.keys()) return keys def instrumented_test_render(self, context): """ An instrumented Template render method, providing a signal that can be intercepted by the test system Client """ template_rendered.send(sender=self, template=self, context=context) return...
e-test setup. This involves: - Installing the instrumented test renderer - Set the email backend to the locmem email backend. - Setting the active locale to match the LANGUAGE_CODE setting. """ Template._original_render = Template._render Template._render = instrumented_test_render ...
sputnick-dev/weboob
modules/bred/bred/browser.py
Python
agpl-3.0
5,970
0.002345
# -*- coding: utf-8 -*- # Copyright(C) 2014 Romain Bignon # # This file is part of weboob. # # weboob is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your opti...
) except BrowserHTTPError: self.do_login(self.login, self.password) retu
rn super(BredBrowser, self).open(*args, **kwargs) def get_accounts_list(self): r = self.api_open('/transactionnel/services/rest/Account/accounts') for content in r.json()['content']: if self.accnum != '00000000000' and content['numero'] != self.accnum: continue ...
jstarc/nli_generation
hierarchical_softmax.py
Python
mit
2,566
0.010912
from keras import backend as K from keras import initializations from keras.backend.common import _EPSILON from keras.engine.topology import Layer from keras.engine import InputSpec from theano.tensor.nnet import h_softmax import theano.tensor as T class HierarchicalSoftmax(Layer): def __init__(self, output...
.shape(x)[0], self.output_dim, self.n_classes, self.n_outputs_per_class, self.W1, self.b1, self.W2, self.b2, target) output_dim = 1 if self.trainable else self.output_dim input_length = K.shape(X[0])[1] y = K.resha...
e(Y, (-1, input_length, output_dim)) return y def get_config(self): config = {'output_dim': self.output_dim, 'init': self.init.__name__} base_config = super(HierarchicalSoftmax, self).get_config() return dict(list(base_config.items()) + list(config.it...
indevgr/django
django/core/management/commands/migrate.py
Python
bsd-3-clause
13,610
0.002425
# -*- coding: utf-8 -*- from __future__ import unicode_literals import time from collections import OrderedDict from importlib import import_module from django.apps import apps from django.core.checks import Tags, run_checks from django.core.management.base import BaseCommand, CommandError from django.core.management...
) raise CommandError( "Conflicting migrations detected; multiple leaf nodes in the " "migration graph: (%s).\nTo fix them run " "'python manage.py makemigrations --merge'" % name_str ) # If they supplied command line arguments, work ou...
ptions['migration_name'] if app_label not in executor.loader.migrated_apps: raise CommandError( "App '%s' does not have migrations." % app_label ) if migration_name == "zero": targets = [(app_label, None)] else: ...
google-research/google-research
alx/batching_utils.py
Python
apache-2.0
19,361
0.009245
# coding=utf-8 # Copyright 2022 The Google Research 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 applicab...
histories and ground truth into multiple examples and pads any extra space with -1. This function assumes that no user history is large enou
gh to overfill the space in a single batch i.e. all user histories <= batch_size * seq_len. Args: xs: list of examples. (row_id, history, ground_truth) if is_test if True, (row_id, history) otherwise. batch_size: size of the batch. num_rows_per_batch: fixed number of rows per batch. We keep this ...
trehn/teamvault
teamvault/apps/secrets/migrations/0020_auto_20180220_1356.py
Python
gpl-3.0
752
0
# Generated by Django 2.0 on 2018-02-20 13:56 from django.db import migrations def copy_owner_data(apps, schema_editor): Secret = apps.get_model('secrets', 'Secret') for secret in Secret.objects.all(): secret.allowed_groups.add(*list(secret.owner_groups.all())) secret.allowed_users.add(*list(...
(): secret.notify_on_access_request.add(*list(group.user_set.all())) class Migration(migrations.Migration): dependencies = [ ('secrets', '0019_secret_notify_on_access_request'), ] operations = [ migrat
ions.RunPython(copy_owner_data), ]
Parisson/TimeSide
timeside/server/management/commands/timeside-save-items.py
Python
agpl-3.0
346
0
from django.core.management.base import BaseCommand from timeside.server
.models import Item class Command(BaseCommand): help = """ Save all Items to populate ext
ernal id, sha1, mime type, samplerate and audio duration """ def handle(self, *args, **options): for item in Item.objects.all(): item.save()
yongwen/makahiki
makahiki/apps/managers/challenge_mgr/tests.py
Python
mit
2,099
0.002382
"""Tests the challenge_mgr module.""" import datetime from django.contrib.auth.models import User from django.test import TransactionTestCase from django.core.urlresolvers import reverse from apps.managers.challenge_mgr import challenge_mgr from apps.managers.challenge_mgr.models import RoundSetting from apps.utils ...
test_utils.set_competition_round() current = challenge_mgr.get_round_name() self.assertEqual(current, current_round, "Test that the current round is returned.") start = datetime.datetime.today() + datetime.timedelta(days=1) end = start + datetime.timedelta(days=7) r...
rt = start rounds.end = end rounds.save() challenge_mgr.init() current_round = challenge_mgr.get_round_name() self.assertTrue(current_round is None, "Test that there is no current round.")
antoinecarme/pyaf
tests/model_control/detailed/transf_None/model_control_one_enabled_None_MovingMedian_Seasonal_DayOfMonth_SVR.py
Python
bsd-3-clause
160
0.05
import tests.
model_control.test_ozone_custom_models_enabled as testmod testmod.build_model( ['None'] , ['Mov
ingMedian'] , ['Seasonal_DayOfMonth'] , ['SVR'] );
alpatania/MapperTools
setup.py
Python
gpl-3.0
791
0.003793
from setuptools import setup def readme(): with open('README.rst') as f: return f.read() setup(name='MapperTools', packages=['MapperTools'], version='0.1', description='A
python 2.7 implementation of Mapper algorithm for Topological Data Analysis', keywords='mapper TDA python', long_description=readme(), url='http://github.com/alpatania', author='Alice Patania', author_email='alice.patania@gmail.com', license='MIT', classifiers=['Development St...
'pandas', 'collections'], include_package_data=True, zip_safe=False)
labsland/labmanager
labmanager/rlms/ext/rest.py
Python
bsd-2-clause
9,234
0.010613
# -*-*- encoding: utf-8 -*-*- # # gateway4labs is free software: you can redistribute it and/or modify # it under the terms of the BSD 2-Clause License # gateway4labs 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. import sys import json import requests import traceback from flask import current_app from flask.ext.wtf import TextField, Required, URL, PasswordField, SelectField from labmanager.forms import AddForm, RetrospectiveForm, GenericPermissionForm from labmanager.rlms import registe...
aseFormCreator, Versions, Capabilities def get_module(version): return sys.modules[__name__] class HttpAddForm(AddForm): base_url = TextField("Base URL", validators = [Required(), URL(False) ]) login = TextField("Login", validators = [Required() ]) password = PasswordField("Password", val...
akosiaris/transliterate
src/transliterate/contrib/languages/hi/translit_language_pack.py
Python
gpl-2.0
1,416
0.005376
# -
*- coding: utf-8 -*- __title__ = 'transliterate.contrib.languages.hi.translit_language_pack' __author__ = 'Artur Barseghyan' __copyright__ = 'Copyright (c) 2013 Artur Barseghyan' __license__ = 'GPL 2.0/LGPL 2.1' __all__ = ('HindiLanguagePack',) from transliterate.base import TranslitLanguagePack, registry class Hind...
guagePack(TranslitLanguagePack): """ Language pack for Hindi language. See `http://en.wikipedia.org/wiki/Hindi` for details. """ language_code = "hi" language_name = "Hindi" character_ranges = ((0x0900, 0x097f),) # Fill this in mapping = ( u"aeof", #AEOF u"अइओफ", ...
Ajapaik/ajapaik-web
ajapaik/ajapaik/management/commands/refresh_albums.py
Python
gpl-3.0
1,895
0.003694
from random import randint import time from django.contrib.gis.geos import Point from django.core.management.base import BaseCommand from ajapaik.ajapaik.models import Album class Command(BaseComm
and): help = 'Refresh albums' def handle(self, *args, **options): albums = Album.objects.exclude(atype__in=[Album.AUTO, Album.FAVORITES]) for a in albums: historic_photo_qs = a.get_historic_photos_queryset_with_subalbums() if not historic_photo_qs.exists(): ...
oto_qs = a.get_geotagged_historic_photo_queryset_with_subalbums() a.photo_count_with_subalbums = historic_photo_qs.count() a.geotagged_photo_count_with_subalbums = geotagged_photo_qs.count() a.rephoto_count_with_subalbums = a.get_rephotos_queryset_with_subalbums().count() ...
hkpeprah/git-achievements
app/services/views.py
Python
gpl-2.0
2,967
0.002359
import json import re from django.conf import settings from django.http import HttpResponse from django.template import RequestContext from django.views.decorators.csrf import csrf_exempt from django.views.decorators.http import require_http_methods from django.shortcuts import render_to_response from django.contrib.a...
al web service request. @param: HttpRequest @return: HttpResponse """ data = json.loads(request.body) data = check_for_unlocked_achievements(data.get('event'), data.get('payload')) return HttpResponse(json.dumps(data), status=200, content_type="application/js
on")
krafczyk/spack
var/spack/repos/builtin/packages/lammps/package.py
Python
lgpl-2.1
5,249
0.000572
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
user-netcdf') depends_on('blas', when='+user-atc') depends_on('lapack', when='+user-atc') depends_on('latte@1.0.1', when='@:20180222+latte') depends_on('latte@1.1.1:', when='@20180316:20180628+latte') depends_on('latte@1.2.1:', when='@20180629:+latte') depends_on('blas', when='+latte') depen...
python', when='+python') depends_on('mpi', when='+user-lb') depends_on('mpi', when='+user-h5md') depends_on('hdf5', when='+user-h5md') conflicts('+body', when='+poems@:20180628') conflicts('+latte', when='@:20170921') conflicts('+python', when='~lib') conflicts('+qeq', when='~manybody') ...
vollov/lotad
content/apps.py
Python
mit
182
0
from __future__ import
unicode_literals from django.apps import AppConfig class ContentCo
nfig(AppConfig): """ Module to manage i18n contents """ name = 'content'
nemanja-d/odoo_project_extensions
project_task_forecasts/models/milestone_template.py
Python
gpl-3.0
1,778
0.003937
# -*- coding: utf-8 -*- import logging from openerp import models, fields, api, exceptions as ex _logger = logging.ge
tLogger(__name__) class MilestoneTemplate(models.Model): _name = 'project.milestone.template' _inherit = ['mail.thread',
'ir.needaction_mixin'] name = fields.Char('Name', required=True, track_visibility='onchange') line_ids = fields.One2many('project.milestone.template.line', 'milestone_template_id', string='Milestones') project_id = fields.Many2one('project.project', 'Project', required=True, track_visibility='onchange') ...
jcoady9/youtube-dl
youtube_dl/extractor/twitter.py
Python
unlicense
15,024
0.002067
# coding: utf-8 from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import ( determine_ext, float_or_none, xpath_text, remove_end, int_or_none, ExtractorError, ) class TwitterBaseIE(InfoExtractor): def _get_vmap_video_url(self, vmap_url, video...
9', 'info_dict': { 'id': 'iBb2x00UVlv', 'ext': 'mp4', 'upload_date': '20151113', 'uploader_id': '1189339351084113920', 'uploader': 'ArsenalTerje', 'title': 'Vine by ArsenalTerje', }, 'add_...
425449b59049d', 'info_dict': { 'id': '705235433198714880', 'ext': 'mp4', 'title': 'Twitter web player', 'thumbnail': 're:^https?://.*\.jpg', }, }, ] def _real_extract(self, url): video_id = self._match_id(ur...
codehacken/Athena
src/vision_opencv/cv_bridge/python/cv_bridge/__init__.py
Python
gpl-2.0
42
0
f
rom .core import CvBridge, CvBridg
eError
AthenaYe/UFLDL_Tutorial
Chap1_Supervised_Learning_and_Optimization/logistic_regression.py
Python
gpl-2.0
1,696
0.004127
#!/usr/bin/env python2.7 # -*- coding:utf-8 -*- import sklearn.datasets as skds import numpy as np import random import theano.tensor as T import theano import matplotlib.pyplot as plt import math #I don't know what the jesus 'housing.data' means so I used self-generated dataset x = np.arange(-50., 50., 1) y = np.arr...
a = theano.shared(np.random.uniform(-0.1, 0.1)) X = T.dscalar('X') Y = T.dscalar('Y') #functions prediction = 1/(1 + T.exp(-omega * X + theta)) loss1 = -Y * T.log(prediction) loss2 = 1/2.0 * (prediction - Y) ** 2 predict = t
heano.function([X], prediction) calculate_loss = theano.function([X, Y], loss2) print predict(1.0) #derivatives dX = T.grad(loss2, X) dtheta = T.grad(loss2, theta) domega = T.grad(loss2, omega) epsilon = .01 #gradient function gradient_step = theano.function( [X, Y], updates=((omega, omega - e...
RazvanRotari/iaP
services/uploaders/nytimes.py
Python
mit
1,016
0.001969
#!/usr/bin/env python3 import requests import xmltodict import upload import model RSS_ENDPOINT = "http://rss.nytimes.com/services/xml/rss/nyt/HomePage.xml" def get_rss(): response = requests.get(RSS_ENDPOINT) return xmltodict.parse(response.text)["rss"] def main(): data = get_rss() for item in data[...
del.NewsItem(item["guid"]["#text"]) newsItem.title = item["title"] newsItem.provenance = "http://rss.nytimes.com" newsItem.author = item["dc:creator"] newsItem.timestamp = item["pubDate"] if "category" in item: print("\n\n\n") print(item["category"]) ...
categories = [x["#text"] for x in item["category"]] else: newsItem.categories = [item["category"]["#text"]] newsItem.description = item["description"] upload.upload_model(newsItem) if __name__ == "__main__": main()
danmichaelo/UKBot
ukbot/revision.py
Python
mit
7,012
0.002567
# encoding=utf-8 # vim: fenc=utf-8 et sw=4 ts=4 sts=4 ai import weakref import re import urllib from collections import OrderedDict from datetime import datetime import logging import pytz from mwtemplates import TemplateEditor from mwtextextractor import get_body_text from .common import _ logger = logging.getLogger(...
self.username = v[0].upper() + v[1:] elif k
== 'parsedcomment': self.parsedcomment = v elif k == 'text': if v is not None: self.text = v elif k == 'parenttext': if v is not None: self.parenttext = v else: raise Exception('a...
tehmaze/parser
parser/symbol.py
Python
mit
977
0.002047
# Crude symbol based top down operator presedence parser, as originally # implemented by Vaughan Pratt[1] and Douglas Crockford[2]. # # [1]: http://doi.acm.org/10.1145/512927.512931 # [2]: http://javascript.crockford.com/tdop/tdop.html import re class SymbolBase(object): ident = None value = None first = ...
r method in ['advance', 'expression']: setattr(self, method, getattr(self.parser, method)) def nud(self): ''' Null declaration, is used when a token appears at the beginning of a language construct. ''' raise SyntaxError('Syntax error %r' % (self.ident,)) de...
''' raise SyntaxError('Unknown operator %r' % (self.ident,))
lebabouin/CouchPotatoServer-develop
couchpotato/core/providers/trailer/vftrailers/youtube_dl/extractor/brightcove.py
Python
gpl-3.0
5,375
0.003539
# encoding: latin-1 import re import json import xml.etree.ElementTree from .common import InfoExtractor from ..utils import ( compat_urllib_parse, find_xpath_attr, compat_urlparse, ExtractorError, ) class BrightcoveIE(InfoExtractor): _VALID_URL = r'https?://.*brightcove\.com/(services|viewer).*...
act(self, url): mobj = re.match(self._VALID_URL, url) query_str = mobj.group('query') query = compat_urlparse.parse_qs(query_str) videoPlayer = query.get('@videoPlayer') if videoPlayer: retu
rn self._get_video_info(videoPlayer[0], query_str) else: player_key = query['playerKey'] return self._get_playlist_info(player_key[0]) def _get_video_info(self, video_id, query): request_url = self._FEDERATED_URL_TEMPLATE % query webpage = self._download_webpage(requ...
wangjiezhe/FetchNovels
novel/sources/sto.py
Python
gpl-3.0
2,128
0.004008
#!/usr/bin/env python # -*- coding: utf-8 -*- import re from pyquery import PyQuery from novel import serial, utils BASE_URL = 'http://www.sto.cc/{}-1/' PAGE_URL = 'http://www.sto.cc/{}-{}/' class StoTool(utils.Tool): def __init__(self): super().__init__() word_list = ( 's思s兔s網s文...
'││', '//', '\$\$', ) symbols = '|'.join(symbol_list).join(('(.|', ')')) pats = (symbols.join(w.split('s')) for w in word_list) symbol_extras = ('',) self.remove_extras.extend( (re.compile(pat) for pat in pats)
) self.remove_extras.extend( (re.compile(pat) for pat in symbol_extras) ) class Sto(serial.SerialNovel): def __init__(self, tid): super().__init__(utils.base_to_url(BASE_URL, tid), '#BookContent', tid=tid) self.tool = StoTool def get_title...
makersauce/ConstructSecur
Overlord/host.py
Python
mit
8,573
0.011781
##TODO: # #getLog(day) FInish it #machines new #machines mod # import os import datetime from flask import Flask, jsonify, render_template, request, redirect, url_for from dblayer import DBlayer db = DBlayer(DEBUG=True) app = Flask(__name__, static_folder='web/static', static_url_path='') app.template_folder = "web"...
().sort('lastupdated', -1)[n] print result return jsonify(name=result['name'],description=result['description'],handle=result['twitterhandle'],tid=result['twitterid'],updated=result['lastupdated'],geo=result['lastgeo'],category=result['category']) ##END MAP ##ADMIN PAGE @app.route('/admin/_add_merchant'...
t.args.get('name', 0, type=str) tline = request.args.get('tagline', 0, type=str) handle = request.args.get('twitterhandle', 0, type=str) category = request.args.get('category',type=str) new = {'name': name, 'category': category, 'twitterhandle': handle, 'description': tline} print new added = db...
ARL-UTEP-OC/emubox
workshop-manager/bin/RequestHandler/client_updater.py
Python
gpl-2.0
2,004
0.000998
import sys import time import logging from socketio import socketio_manage from socketio.mixins import BroadcastMixin from socketio.namespace import BaseNamespace from DataAggregation.webdata_aggregator import getAvailableWorkshops logger = logging.getLogger(__name__) std_out_logger = logging.StreamHandler(sys.stdo...
st_msg(server, ns_name, event, *args): pkt = dict(type="event", name=event, args=args, endpoint=ns_name) for sessid, socket in server.sockets.iteritems(): socket.send_packet(pkt) def workshops_monitor(server): sizes = [] workshops = getAvailableWor...
tmp = [w.workshopName, w.q.qsize()] sizes.append(tmp) broadcast_msg(server, '', "sizes", tmp) while True: logger.info("Participants viewing frontend:" + str(len(server.sockets))) workshops_available = [] curr_workshops = getAvailableWorkshops() for w in curr_w...
matt-oak/Project_Euler
17_number_letter_counts.py
Python
mit
3,740
0.04893
# imports import sys import math # main function def main(argv): summation = 0 #one ... ninety nine for i in range(1, 100): summation = summation + to_words(i)
#854 characers for 1 - 99 #print summation #one hundred and ... one_hundreds = (13
*99)+summation+10 two_hundreds = (13*99)+summation+10 three_hundreds = (15*99)+summation+12 four_hundreds = (14*99)+summation+11 five_hundreds = (14*99)+summation+11 six_hundreds = (13*99)+summation+10 seven_hundreds = (15*99)+summation+12 eight_hundreds = (15*99)+summation+12 nine_hundreds = (14*99)+summation+...
hackerpals/Python-Tutorials
Kids-Pthon-Workshops/guessing-game/ex2/call-op.py
Python
gpl-3.0
591
0.011844
#!/usr/bin/env python3 """ Call Operators in Python """ #Setup our variables num1 = 1 num2 = 2 var1 = 'a' var2 = 'b' ''' + / Additions / Can combine strings or numbes ''' totalNum = num1 + num2 totalVar = var1 + var2 print(totalNum, totalVar ) ''' - / Subtraction ''' totalNum = num1 - num2 ''' * / Multiplica...
/ / Division ''' ''' % / Remainder(Modulo) ''' ''' ** / Powe
r ''' ''' = / Assignment ''' ''' == / Equality ''' ''' != / Not Equal ''' ''' > / Greater than ''' ''' < / Less than ''' ''' &(or and) / and ''' ''' | or / or '''
Elchi3/kuma
kuma/attachments/tests/conftest.py
Python
mpl-2.0
809
0
import datetime import pytest from django.core.files.base import ContentFile from kuma.attachments.models import Attachment, AttachmentRevision @pytest.fixture def file_attachment(db, wiki_user): file_id = 97 filename = "test.txt" title = "Test text file" attachment = Attachment(title=title, mindto...
evision = AttachmentRevision( title=title, is_approved=True, attachment=attachment, mime_type="text/plain", description="Initial upload", created=datetime.datetime.now(), ) revision.creator = wiki_user revision.file.save(filename, ContentFile(b"This is only a ...
n.make_current() return dict(attachment=attachment, file=dict(id=file_id, name=filename),)
mmottahedi/neuralnilm_prototype
scripts/e234.py
Python
mit
4,812
0.004572
from __future__ import print_function, division import matplotlib matplotlib.use('Agg') # Must be before importing matplotlib.pyplot or pylab! from neuralnilm import Net, RealApplianceSource, BLSTMLayer, DimshuffleLayer from lasagne.nonlinearities import sigmoid, rectify from lasagne.objectives import crossentropy, mse...
turePoolLayer from lasagne.updates import nesterov_momentum from functools import partial import os from neuralnilm.source import standardise, discretize, fdiff, power_and_fdiff from neuralnilm.experiment import run_experiment from neuralnilm.net import TrainingError import __main__ NAME = os.path.splitext(os.path.spl...
ATH = "/homes/dk3810/workspace/python/neuralnilm/figures" SAVE_PLOT_INTERVAL = 250 GRADIENT_STEPS = 100 """ e233 based on e131c but with: * lag=32 * pool e234 * init final layer and conv layer """ def exp_a(name): # global source # source = RealApplianceSource( # filename='/data/dk3810/ukdale.h5', ...
eseraygun/python-entities
tests/field.py
Python
bsd-3-clause
5,621
0
import unittest from entities import * class TestField(unittest.TestCase): def test_make_default(self): field = Field(default=None, null=True) self.assertEqual(field.make_default(), None) field = Field(default=lambda: 1, null=True) self.assertEqual(field.make_default(), 1) ...
self.assertRaises(ValueError, field.make_default) def test_full_name(self): class Foo(Entity): field = ListField(DynamicField()) self.assertEqual(Foo.field.full_name(), 'field') self.assertEqual(Foo.field.item_field.full_name(), 'field.<item>') def test_validate(self): ...
True) self.assertEqual(field.validate(None), None) field = DynamicField(IntegerField, null=True) self.assertEqual(field.validate(None), None) field = DynamicField(IntegerField, null=False) self.assertRaises(ValidationError, lambda: field.validate(None)) self.assertRaise...
leilihh/novaha
nova/cert/manager.py
Python
apache-2.0
2,464
0.000406
# Copyright 2012 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 t
he 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 # License for the specific language governing permissions and limitations # under the License. """ Cert manager manages x509 certificates. **Related Flags** :cert_topic: What :mod:`rpc` topic to listen to...
grandquista/ReQL-Core
setup.py
Python
apache-2.0
1,701
0
from setuptools import setup, Extension with open('README.md') as istream: long_description = istream.read() tests_require = ['pytest'] libReQL = Extension( 'libReQL', include_dirs=['src'], sources=[ 'src/Python/connection.c', 'src/Python/cursor.c', 'src/Python/query.c', ...
, 'src/reql/cursor.c', 'src/reql/decode.c', 'src/reql/encode.c', 'src/reql/error.c', 'src/reql/query.c' ] ) setup( author='Adam Grandquist', author_email='grandquista@gmail.com', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience ...
h', 'Operating System :: MacOS :: MacOS X', 'Programming Language :: C', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Py...
levilucio/SyVOLT
UML2ER/transformation/H02Package2ERModel.py
Python
mit
1,402
0.03709
from core.himesis import Himesis import uuid class H02Package2ERModel(H
imesis): def __init__(self): """ Creates the himesis graph representing the DSLTrans rule 02Package2ERModel. """ # Flag this instance as compiled now self.is_compiled = True super(H02Package2ERModel, self).__init__(name='H02Package2ERModel', num_nodes=0, edges=[]) # Set the graph attributes self["mm_...
(uuid.NAMESPACE_DNS,'02Package2ERModel') # match model. We only support one match model self.add_node() self.vs[0]["mm__"] = """MatchModel""" # apply model node self.add_node() self.vs[1]["mm__"] = """ApplyModel""" # paired with relation between match and apply models self.add_node() self.vs[2]["mm...
titasakgm/brc-stock
openerp/addons/base_report/__openerp__.py
Python
agpl-3.0
1,858
0.011841
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2013 Cubic ERP - Teradata SAC (<http://cubicerp.com>). # # This program is free software: you can redistribute it and/or modify # it under the...
for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { "name": "Base Report to Improve the Reports", "version"...
on ir.actions.report.xml object in order to support many kinds of reports engines. Next the improves: * Add a text field to edit and customize the report on the fly. * Add a check field to push the report on the toolbar window """, "author": "Cubic ERP", "website": "http://cubicERP.com", "category": "R...
eviljeff/zamboni
mkt/submit/tests/test_views.py
Python
bsd-3-clause
38,831
0
# -*- coding: utf-8 -*- import datetime import json import os import shutil from django.conf import settings from django.core.files.storage import default_storage as storage from django.core.urlresolvers import reverse import mock from nose.tools import eq_, ok_ from pyquery import PyQuery as pq import mkt from mkt....
def test_page(self): r = self.client.get(self.url)
eq_(r.status_code, 200) doc = pq(r.content)('#submit-terms') eq_(doc.length, 1) eq_(doc.find('input[name=newsletter]').siblings('label').length, 1, 'Missing its <label>!') def test_progress_display(self): self._test_progress_display([], 'terms') @mock.patch('...
ojengwa/sympy
sympy/core/tests/test_expr.py
Python
bsd-3-clause
54,290
0.000682
from __future__ import division from sympy import (Add, Basic, S, Symbol, Wild, Float, Integer, Rational, I, sin, cos, tan, exp, log, nan, oo, sqrt, symbols, Integral, sympify, WildFunction, Poly, Function, Derivative, Number, pi, NumberSymbol, zoo, Piecewise, Mul, Pow, nsimplify, ratsimp, trigsimp, radsim...
isinstance(a, (int, float)): return a ** self.number return NotImplemented def __pow__(self, a): if isinstance(a, (int, float, DummyNumber)): return self.number ** a return NotImplemented def __pos__
(self): return self.number def __neg__(self): return - self.number class I5(DummyNumber): number = 5 def __int__(self): return self.number class F1_1(DummyNumber): number = 1.1 def __float__(self): return self.number i5 = I5() f1_1 = F1_1() # basic sympy obje...
huajiahen/hotspot
backend/Busy/BusyJpush.py
Python
mit
3,607
0.019324
# -*- coding:utf-8 -*- import copy import urllib, urllib2 import json import logging import hashlib import time logger = logging.getLogger('jpush_py') SEND_MSG_URL = 'http://api.jpush.cn:8800/sendmsg/v2/sendmsg' REQUIRED_KEYS = set(('receiver_type', 'msg_type', 'msg_content','platform')) class JPushPy(object): '...
g): if params['msg_type'] == 1: v = dict( n_content = v ) if isinstance(v,dict): new_params[k] = json.dumps(v) elif isinstance(v,unicode): new_params[k] = v.encode('utf-8') ...
f.generate_verification_code(new_params) def send_msg(self, params, timeout = None): ''' 发送消息 ''' #Debug logger.debug('params: '+repr(params)) if len(REQUIRED_KEYS & set(params.keys())) != len(REQUIRED_KEYS): return dict( sendno = params....
stgeorges/pythonscripts
object_names_No_occurrences.py
Python
unlicense
2,663
0.010139
#*******************************************************************************************# #********* Object names and its number of occurrences **************************************# #********* by Djordje Spasic ***************************************************************# #********* issworld2000@yahoo.com 08-F...
sColumnU[i] message += " %s - %i\n" % (mergedL[i][1], mergedL[i][0]) rs.MessageBox(message, 0, "Results") else: filename = rs.SaveFileName("Save csv file","*.csv||", None, "ObjectNamesOccurrences", "csv") file = open(filename, 'w') ...
name = mergedL[i][1] occ = mergedL[i][0] line = "%s,%i \n" %(name, occ) file.write(line) file.close() print "Done" else: print "You do not have named objects. Function terminated" ...
jjhelmus/berryconda
recipes/faker/run_test.py
Python
bsd-3-clause
7,740
0
import faker import faker.providers import faker.providers.address import faker.providers.address.cs_CZ import faker.providers.address.de_DE import faker.providers.address.el_GR import faker.providers.address.en import faker.providers.address.en_AU import faker.providers.address.en_CA import faker.providers.address.en_...
mport faker.providers.job.pl_PL import faker.providers.job.ru_RU import faker.providers.job.uk_UA import faker.providers.job.zh_TW import faker.providers.lorem import faker.providers.lorem.el_GR import faker
.providers.lorem.la import faker.providers.lorem.ru_RU import faker.providers.misc import faker.providers.misc.en_US import faker.providers.person import faker.providers.person.bg_BG import faker.providers.person.cs_CZ import faker.providers.person.de_AT import faker.providers.person.de_DE import faker.providers.person...
OpenTreeOfLife/opentree
custom_import.py
Python
bsd-2-clause
7,868
0.001398
#!/usr/bin/env python # -*- coding: utf-8 -*- """ ***************************** NOTE that this is a modified version from web2py 2.8.2. For full details on what has changed, see https://github.com/OpenTreeOfLife/opentree/commits/master/custom_import.py This file was patched (by jimallman, on 10/10/2017) to restore w...
new_date = os.path.getmtime(file) except:
self._import_dates.pop(file, None) # Clean up # Handle module changing in package and #package changing in module: if file.endswith(".py"): # Get path without file ext: file = os.path.splitext(file)[0] ...
LuqueDaniel/pybooru
pybooru/exceptions.py
Python
mit
1,211
0
# -*- coding: utf-8 -*- """pybooru.exceptions This module contains Pybooru exceptions. Classes: * PybooruError -- Main Pybooru exception class. * PybooruHTTPError -- Manages HTTP status errors. * PybooruAPIError -- Manages all API errors. """ # __furute__ imports from __future__ import absolute_import ...
o catch Pybooru error message.""" pass class PybooruHTTPError(PybooruError): """Class to catch HTTP error message.""" def __init__(self, msg, http_code, url): """Initialize PybooruHTTPError. Keyword arguments: msg (str): The error message. http_code (int): The HTT...
status code. url (str): The URL. """ super(PybooruHTTPError, self).__init__(msg, http_code, url) self._msg = "{0}: {1} - {2}, {3} - URL: {4}".format( msg, http_code, HTTP_STATUS_CODE[http_code][0], HTTP_STATUS_CODE[http_code][1], url) def __str__(self): ...
lociii/symcon-index
heroku/urls.py
Python
mit
376
0
# -*- coding: UTF-8 -*- from django.conf.urls import url, include from django.contrib import admin from django.contrib.staticfiles.urls impor
t staticfiles_urlpatterns urlpatterns = [ url(r'^', include('symcon.urls'
)), url(r'^pages/', include('django.contrib.flatpages.urls')), url(r'^admin/', include(admin.site.urls)), ] urlpatterns += staticfiles_urlpatterns()
zymtech/Scrapiders
jd_51job/jd_51job/spiders/jd.py
Python
mit
3,113
0.00771
# -*- coding : uft-8 -*- import scrapy import urllib from jd_51job.items import Jd51JobItem from scrapy.http import Request from scrapy.exceptions import IgnoreRequest import os import datetime import re class Jd51JobSpider(scrapy.Spider): name = "jd_51job" allowed_domain = ["51job.com"] datafile = os....
bsearch/search_result.php?" urls = [] for kw in keywords: url = start_url + 'keyword=' + urllib.quote(keyword) urls.append(ur
l) def start_requests(self): for url in self.urls: yield scrapy.http.Request(url, callback=self.parse0, errback=self.errback) def parse0(self, response): print response.url pagestr = response.xpath('//div[@class="dw_page"]//span[@class="td"]/text()').extract()[0] pa...
Jorge-Rodriguez/ansible
lib/ansible/modules/network/f5/bigip_apm_policy_fetch.py
Python
gpl-3.0
15,623
0.001088
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright: (c) 2018, F5 Networks Inc. # GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', ...
e from library.module_utils.network.f5.icontrol import download_file from library.module_utils.network.f5.icontrol import
tmos_version from library.module_utils.network.f5.icontrol import module_provisioned except ImportError: from ansible.module_utils.network.f5.bigip import F5RestClient from ansible.module_utils.network.f5.common import F5ModuleError from ansible.module_utils.network.f5.common import AnsibleF5Parameters ...
blueburningcoder/nupic
tests/swarming/nupic/swarming/experiments/spatial_classification/description.py
Python
agpl-3.0
15,433
0.002592
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2013, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This progra...
# 0: silent; >=1: some info; >=2: more info; 'spVerbosity' : 0, 'globalInhibition': 1, # Number of cell columns in the cortical region (same number for # SP and TP) # (see
also tpNCellsPerCol) 'columnCount': 2048, 'inputWidth': 0, # SP inhibition control (absolute value); # Maximum number of active columns in the SP region's output (when # there are more, the weaker ones are suppressed) 'numActiveColumnsPerInhArea...
hellolintong/LinDouFm
resource/channel.py
Python
mit
1,825
0.000548
#!/usr/bin/env python # encoding: utf-8 from flask.ext.restful import Resource, fields, marshal_with, marshal from .base import BaseArgs, LengthField, ChannelKey from database.channel.channel_model import get_channel_status, get_channel, update_channel, delete_channel class ChannelQueryArgs(BaseArgs): def rules(...
return marshal(get_channel_status(), channel_status_fields) ret_channels = get_channel(**args) return marshal(ret_channels, channel_fields) """ class ChannelResource(
Resource): @authenticated('admin') @marshal_with(channel_fields) def patch(self, key): args = ChannelPatchArgs().args channel = get_channel(key=key)[0] update_channel(channel, **args) channel = get_channel(key=key)[0] return channel @authenticated('admin') de...
TD22057/T-Home
python/tHome/sma/Header.py
Python
bsd-2-clause
2,886
0.033264
#=========================================================================== # # Common data packet structures. Used for requests and replies. # #=========================================================================== from .. import util #===========================================================================...
ed class. That # allows this to compute the correct packet length and encode it. packetLen = len( self.struct ) - self._hdrSize self.packetHi = ( packetLen >> 8 ) & 0xFF self.packetLo = packetLen & 0xFF self.wordLen = int( packetLen / 4 ) # Any destination -
we send to a specific IP address so this # isn't important. self.destId = 0xFFFF self.destSerial = 0xFFFFFFFF self.destCtrl = 0x00 self.srcId = 0x7d # TODO change this? self.srcSerial = 0x334657B0 # TODO change this? self.srcCtrl = 0x00 self.error = 0 self.fragmen...
solvo/organilab
src/laboratory/migrations/0035_auto_20180621_0020.py
Python
gpl-3.0
694
0.001441
# -*- coding: utf-8 -*- # Generated by Django 1.11.13 on 2018-06-21 06:20 from __future__ import unicode_literals from django.db import migrations import django.db.models.deletion import mptt.fields class Migration(migrations.Migration): dependencies = [ ('laboratory', '0034_group_perms'), ] op...
model
_name='laboratory', name='organization', field=mptt.fields.TreeForeignKey(on_delete=django.db.models.deletion.CASCADE, to='laboratory.OrganizationStructure'), ), ]
WoLpH/python-utils
_python_utils_tests/test_python_utils.py
Python
bsd-3-clause
272
0.003676
fr
om python_utils import __about__ def test_definitions(): # The setup.py requires this so we better make sure they exist :) assert __about__.__version__ assert __about__.__author__ assert __about__.__author_email__ assert __about
__.__description__
liavkoren/djangoDev
tests/i18n/test_compilation.py
Python
bsd-3-clause
4,924
0.002031
import os import stat import unittest from django.core.management import call_command, CommandError from django.core.management.utils import find_command from django.test import SimpleTestCase from django.test import override_settings from django.utils import translation from django.utils._os import upath from django....
StringIO()) self.assertTrue(os.path.exists(self.MO_FILE_HR)) def test_multiple_locales(self): call_command('compilemessages', locale=['hr', 'fr'], stdout=StringIO()) self.assertTrue(os.path.exists(self.MO_FILE_HR)) self.assertTrue(os.path.exists(self.MO_FILE_FR)) class Compilati...
def setUp(self): super(CompilationErrorHandling, self).setUp() self.addCleanup(self.rmfile, os.path.join(test_dir, self.MO_FILE)) def test_error_reported_by_msgfmt(self): with self.assertRaises(CommandError): call_command('compilemessages', locale=[self.LOCALE], stdout=StringI...
asimshankar/tensorflow
tensorflow/contrib/distribute/python/combinations.py
Python
apache-2.0
15,137
0.005748
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
import division from __future__
import print_function from collections import OrderedDict import sys import types import unittest from absl.testing import parameterized import six from tensorflow.contrib.cluster_resolver import TPUClusterResolver from tensorflow.contrib.distribute.python import mirrored_strategy as mirrored_lib from tensorflow.cont...
noslenfa/tdjangorest
uw/lib/python2.7/site-packages/rest_framework/tests/test_serializer.py
Python
apache-2.0
65,306
0.001348
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from django.db.models.fields import BLANK_CHOICE_DASH from django.test import TestCase from django.utils.datastructures import MultiValueDict from django.utils.translation import ugettext_lazy as _ from rest_framework import se...
eate_partial_nested(self):
"""Test a serializer with nested data which has missing fields.""" names = {'first': 'John'} data = {'ssn': '1234567890', 'names': names} serializer = PersonIdentifierSerializer(data=data) expected_names = {'first': 'John', 'last': '', 'initials': ''} data['names'] = expec...
huggingface/transformers
tests/longformer/test_modeling_longformer.py
Python
apache-2.0
29,819
0.003622
# coding=utf-8 # Copyright 2020 The HuggingFace Team. 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 requir...
ion_mask) result = model(input_ids, global_attention_mask=global_attention_mask) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, self.hidden_size)) def create...
ken_type_ids, input_mask, sequence_labels, token_labels, choice_labels ): model = LongformerForMaskedLM(config=config) model.to(torch_device) model.eval() result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels) self.parent.asse...
CHT5/program-y
bots/y-bot/src/test/extensions/banking/test_balance.py
Python
mit
467
0.004283
import unittest from extensions.banking.balance import BankingBalanceExtension class
BankBalanceExtensionTests(unittest.TestCase): def setUp(self): self.bot = None self.clientid = "testid" def test_balance(self): balance = BankingBalanceExtension() self.assertIsNo
tNone(balance) result = balance.execute(self.bot, self.clientid, "NOW") self.assertIsNotNone(result) self.assertEqual("0.00", result)
notapresent/rtrss
tests/test_storage_util.py
Python
apache-2.0
4,598
0.000217
import unittest import os from testfixtures import TempDirectory from mock import MagicMock, patch, call import requests import httplib2 import googleapiclient.errors from tests import AttrDict from rtrss.storage import util class HttpUtilTestCase(unittest.TestCase): def test_is_retryable_returns_false_on_rando...
ath, self.filename) def tearDown(self): self.tempdir.cleanup()
def test_returns_file_object(self): with util.locked_open(self.filepath, util.M_WRITE) as f: self.assertIsInstance(f, file) def test_concurrent_read(self): self.tempdir.write(self.filename, self.test_data) with util.locked_open(self.filepath, util.M_READ) as f1: with...
wen96/django-boilerplate
my_project/settings/wsgi.py
Python
mit
393
0
""" WSGI config for my_project project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/ """ import os from dja
ngo.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings.config"
) application = get_wsgi_application()
bondar-pavel/infoblox-client
infoblox_client/tests/base.py
Python
apache-2.0
105
0
import
unittest class TestCase(unittest.TestCase): """Test case base class f
or all unit tests."""
memo/tensorflow
tensorflow/python/summary/text_summary_test.py
Python
apache-2.0
2,226
0.005391
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
ry class TextPluginTest(test_util.TensorFlowTestCase): """Test the Text Summary API. These tests are focused on testing the API design of the text_summary method. It doesn't test the PluginAsset and tensors registry functionality, because that is better tested by the text_plugin test that actually consumes t...
with self.assertRaises(ValueError): num = array_ops.constant(1) text_summary.text_summary("foo", num) # The API accepts vectors. arr = array_ops.constant(["one", "two", "three"]) summ = text_summary.text_summary("foo", arr) self.assertEqual(summ.op.type, "TensorSummary") ...
GMDSP-Linked-Data/RDF-work-in-progress
salford/gmdspconverters/streetlighting.py
Python
mit
2,324
0.006454
__author__ = 'jond' import csv import re from rdflib import URIRef, Literal, Namespace, RDF from gmdspconverters import utils STREETLIGHT = Namespace('http://data.gmdsp.org.uk/id/salford/streetlighting/') STREETLIGHT_ONT = Namespace('http://data.gmdsp.org.uk/def/council/streetlighting/') def convert(graph, input_...
((vcard, utils.RDFS['label'], Literal("Address of streetlight with ID " + row["Feature ID"]))) graph.add((vcard, utils.VCARD['street-address'], Literal(row["RoadName"]))) #graph.add((vcard, utils.VCARD['postal-code'], Literal(row["POSTCODE"]))) #graph.ad
d((vcard, utils.POST['postcode'], URIRef(utils.convertpostcodeto_osuri(row["POSTCODE"])))) # location information graph.add((sl, utils.OS["northing"], Literal(row["Northing"]))) graph.add((sl, utils.OS["easting"], Literal(row["Easting"]))) # add conversion for lat/long ...
argivaitv/argivaitv
plugin.video.salts/scrapers/local_scraper.py
Python
gpl-2.0
7,215
0.003881
""" SALTS XBMC Addon Copyright (C) 2014 tknorris 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...
": "title", "operator": "contains", "value": "%s"}' % (title) if year: filter_str = '{"and": [%s, {"field": "year", "operator": "is", "value": "%s"}]}' % (filter_str, year) if video_type == VIDEO_TYPES.MOVIE: cmd = '{"jsonrpc": "2.0", "method": "VideoLibrary.GetMo
vies", "params": { "filter": %s, "limits": { "start" : 0, "end": 25 }, "properties" : ["title", "year", "file", "streamdetails"], \ "sort": { "order": "ascending", "method": "label", "ignorearticle": true } }, "id": "libMovies"}' result_key = 'movies' id_key = 'movieid' else:...
CodyKochmann/generators
generators/chain.py
Python
mit
1,291
0.002324
# -*- coding: utf-8 -*- # @Author: Cody Kochmann # @Date: 2017-09-09 14:58:43 # @Last Modified by: Cody Kochmann # @Last Modified time: 2017-12-09 10:27:36 from functools import partial from strict_functions import strict_globals @strict_globals(partial=partial) def chain(*args): """itertools.chain, just bett...
print('-'*30)
print(tuple(generator)) print('-'*30) show(chain()) # this is a generator of generators g = (iter(range(10)) for i in range(10)) show(chain(g)) # doing this in itertools would do this g = (iter(range(10)) for i in range(10)) show(itr.chain(g))
amolborcar/learnpythonthehardway
ex17.py
Python
mit
649
0.003082
from sys import argv from os.path import exists script, from_file, to_file = argv print "Copying from %s to %s..." % (from_file, to_file) # we could do these two on one line, how? # in_file = open(from_file) # indata = in_file.read() # like this! indata = open(from_file).read() print "The input file is %d bytes lo...
t "Does the output file exist? %r" % exists(to_file) print "Ready, hit RETURN to continue, CTRL-C to abort." raw_input("> ") out_file = open(to_file, "w") out_file.write(indata) print "Alright, all done!" out_file.close() # in_file.close() # this line isn't necessary since in_file is no longer a thi
ng
rspavel/spack
var/spack/repos/builtin/packages/py-websocket-client/package.py
Python
lgpl-2.1
997
0.005015
# 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) class PyWebsocketClient(PythonPackage): """WebSocket client for P
ython. hybi13 is supported.""" homepage = "https://g
ithub.com/websocket-client/websocket-client.git" url = "https://pypi.io/packages/source/w/websocket_client/websocket_client-0.57.0.tar.gz" version('0.57.0', sha256='d735b91d6d1692a6a181f2a8c9e0238e5f6373356f561bb9dc4c7af36f452010') version('0.56.0', sha256='1fd5520878b68b84b5748bb30e592b10d0a91529d538...
fsys/js.lesscss
js/lesscss/script.py
Python
bsd-3-clause
67
0.014925
# -*- coding: utf-8 -*- import subprocess import shutil import
os
partofthething/home-assistant
tests/components/homekit_controller/test_config_flow.py
Python
apache-2.0
22,205
0.001531
"""Tests for homekit_controller config flow.""" from unittest import mock import unittest.mock from unittest.mock import patch import aiohomekit from aiohomekit.model import Accessories, Accessory from aiohomekit.model.characteristics import CharacteristicsTypes from aiohomekit.model.services import ServicesTypes impo...
_info["properties"]["id"] # Device is discovered result = await hass.config_entries.flow.async_init( "homekit_controller", context={"source": "zeroconf"}, data=discovery_info ) assert result["type"] == "abort
" assert result["reason"] == "invalid_properties" async def test_discovery_ignored_model(hass, controller): """Already paired.""" device = setup_mock_accessory(controller) discovery_info = get_device_discovery_info(device) discovery_info["properties"]["id"] = "AA:BB:CC:DD:EE:FF" discovery_info...
cprogrammer1994/ModernGL
examples/old-examples/GLWindow/particle_system.py
Python
mit
1,710
0.022807
import math import random import struct import GLWindow import ModernGL # Window & Context wnd = GLWindow.create_window() ctx = ModernGL.create_context() tvert = ctx.vertex_shader(''' #version 330 uniform vec2 acc; in vec2 in_pos; in vec2 in_prev; out vec2 out_pos; out vec2 out_prev; ...
rticle(): a = random.uniform(0.0, math.pi * 2.0) r = random.uniform(0.0, 0.001) return struct.pack('
2f2f', 0.0, 0.0, math.cos(a) * r - 0.003, math.sin(a) * r - 0.008) vbo1 = ctx.buffer(b''.join(particle() for i in range(1024))) vbo2 = ctx.buffer(reserve=vbo1.size) vao1 = ctx.simple_vertex_array(transform, vbo1, ['in_pos', 'in_prev']) vao2 = ctx.simple_vertex_array(transform, vbo2, ['in_pos', 'in_prev']) render_va...
linsalrob/EdwardsLab
matplotlib graphs/kde.py
Python
mit
1,377
0.003631
import matplotlib.pyplot as plt import numpy as np from scipy.stats import gaussian_kde from scipy.stats.distributions import norm from sklearn.grid_search import GridSearchCV from sklearn.neighbors import KernelDensity data = [1.5] * 7 + [2.5] * 2 + [3.5] * 8 + [4.5] * 3 + [5.5] * 1 + [6.5] * 8 density = gaussian_kde...
h=bandwidth) kde_skl.fit(x[:, np.newaxis]) # score_samples() returns the log-likelihood of the samples log_pdf = kde_skl.score_samples(x_grid[:, np.newaxis]) print(
log_pdf[0:10]) density = np.exp(log_pdf) plt.plot(x_grid, density, color='blue', alpha=0.5, lw=3) #plt.show() grid = GridSearchCV(KernelDensity(), {'bandwidth': np.linspace(0.1, 1.0, 30)}, cv=20) # 20-fold cross-validation # print(x[:, None]) grid.fit(x[:, None]) # print gri...
evanbiederstedt/RRBSfun
scripts/repeat_finder_scripts/repeat_finder_RRBS_NormalBCD19pCD27pcell23_44_CTCTCTAC.G.py
Python
mit
706
0.009915
import glob impor
t numpy as np import pandas as pd from numpy import nan import os os.chdir("/gpfs/commons/home/biederstedte-934/evan_projects/RRBS_anno_clean") repeats = pd.read_csv("repeats_hg19.csv") annofiles = glob.glob("RRBS_NormalBCD19pCD27pcell23_44_CTCTCTAC.G*") def between_range(row): subset = repeats.loc[(row["chr"] =...
urn np.nan return subset.repeat_class #newdf1 = pd.DataFrame() for filename in annofiles: df = pd.read_table(filename) df["hg19_repeats"] = df.apply(between_range, axis = 1) df.to_csv(str("repeatregions_") + filename + ".csv", index=False)
Stargrazer82301/CAAPR
CAAPR/CAAPR_AstroMagic/PTS/pts/do/evolve/reference.py
Python
mit
4,813
0.005195
#!/usr/bin/env python # -*- coding: utf8 -*- # ***************************************************************** # ** PTS -- Python Toolkit for working with SKIRT ** # ** © Astronomical Observatory, Ghent University ** # ***************************************************************** ##...
n a * x + b # ----------------------------------------------------------------- def chi_squared_function(chromosome): """ This function calculates the chi-squared value for a certain set of parameters
(chromosome) :param chromosome: :return: """ chi_squared = 0.0 for i in range(len(test_data_x)): x = test_data_x[i] y = test_data_y[i] chromosome_y = fit_function(x, chromosome[0], chromosome[1]) chi_squared += (y - chromosome_y) ** 2. chi_squared /= 2.0 return chi_squared ...