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
ultmaster/eoj3
contest/views.py
Python
mit
11,433
0.010408
from datetime import timedelta, datetime from django.contrib import messages from django.contrib.contenttypes.models import ContentType from django.core.cache import cache from django.db import transaction from django.http import Http404 from django.http import HttpResponse from django.shortcuts import get_object_or_4...
em.avg_score / 100 * problem.weight, 1) data['authors'] = self.contest.authors.all() # color settings data['level_colors'] = ["", "green", "teal", "blue", "orange", "red"] retur
n data class ContestProblemDetail(BaseContestMixin, TemplateView): template_name = 'contest/problem.jinja2' def get_context_data(self, **kwargs): data = super(ContestProblemDetail, self).get_context_data(**kwargs) data['contest_problem'] = get_object_or_404(ContestProblem, ...
Glyfina-Fernando/pymtl
pisa/pisa_encoding.py
Python
bsd-3-clause
22,637
0.03428
#========================================================================= # pisa_encoding #========================================================================= # This module encapsulates the encoding of PISA and includes # assembly/disassembly functions. We first define a PISA encoding table # which includes inst...
k, and opcode match. The instructino template should start # with the instruction name and a list of field tags deliminted by # whitespace, commas, and/or parentheses. The field tags should map to # assemble_field and disasm_field functions below. The instruction # template is used both for assembly and disassembly. Th...
on is tested against each entry in the table by first applying # the mask and then checking for a match. pisa_encoding_table = \ [ # Basic instructions [ "mfc0 rt, rc0", 0xffe007ff, 0x40000000 ], [ "mtc0 rt, rc0", 0xffe007ff, 0x40800000 ], [ "nop", 0xffffffff, 0x000...
CarlFK/wafer
wafer/schedule/south_migrations/0004_auto__add_field_scheduleitem_css_class.py
Python
isc
9,737
0.007805
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'ScheduleItem.css_class' db.add_column(u'schedule_schedule...
tetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'Fal...
ique': 'True', 'max_length': '30'}) }, u'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max...
gdsfactory/gdsfactory
fixme/netlist.py
Python
mit
766
0
import gdsfactory as gf yaml = """ instances: mmi1: component: mmi1x2 settings: width_mmi: 4.5 length_mmi: 10 mmi2: component: mmi1x2 settings: width_mmi: 4.5 length_mmi:
5 straight: component: straight placements: mmi2: x: 100 mirror: True straight: x: 40 y: 40 routes: route_name1: links: mmi1,o3: mmi2,o3 route_name2: links: mmi1,o2: straight,o1 route_name3: links: ...
,o1 o2: mmi2,o1 """ if __name__ == "__main__": """FIXME""" mzi = gf.read.from_yaml(yaml) n = mzi.get_netlist() # mzi.show() # mzi.plot()
mikefeneley/topcoder
src/SRM-701/square_free_string.py
Python
mit
340
0.002941
class SquareFr
eeString: def isSquareFree(self, s): for i in range(0, len(s)): for length in range(1, len(s)): first = s[i:length + i] second = s[i+length:i+length+length] if second == first: return "not square-free" return "sq
uare-free"
Succeed-Together/bakfu
classify/base.py
Python
bsd-3-clause
1,167
0.004284
"""Base classes for classifiers""" from ..core.classes import Processor class BaseClassifier(Processor): ''' The base class for classifiers. ''' def __init__(self, *args, **kwargs): super(BaseClassifier, self).__init__(*args, **kwargs) self.classifier = None class SklearnClassifier(B...
''' self.classifier = self.
classifier_class(*args, **kwargs) def run_classifier(self, caller, *args, **kwargs): pass def run(self, caller, *args, **kwargs): return self.run_classifier(caller, *args, **kwargs) def __getattr__(self, attr): '''Propagate attribute search to the clusterizer.''' try: ...
mindriot101/bokeh
sphinx/source/conf.py
Python
bsd-3-clause
9,540
0.004403
# -*- coding: utf-8 -*- from __future__ import unicode_literals from os.path import abspath, dirname, join # # Bokeh documentation build configuration file, created by # sphinx-quickstart on Sat Oct 12 23:43:03 2013. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not a...
('Twitter', '//twitter.com/BokehPlots'),
), 'NAV_DOCS': ( ('Installation', 'installation'), ('User Guide', 'user_guide'), ('Gallery', 'gallery'), ('Tutorial', 'https://mybinder.org/v2/gh/bokeh/bokeh-notebooks/master?filepath=tutorial%2F00%20-%20Introduction%20and%20Setup.ipynb'), ('Reference', 'reference'), ...
deepmind/dm_fast_mapping
examples/human_agent.py
Python
apache-2.0
4,270
0.00726
# Copyright 2019 DeepMind Technologies Limited. 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 a...
FE_LEFT_RIGHT': 0, 'LOOK_LEFT_RIGHT': 0, 'LOOK_DOWN_UP': 0, 'HAND_GRIP': 0, } def main(_): pygame.init() try: pygame.mixer.quit() except NotImplementedError: pass pygame.display.set_caption('Fast Language Learning Tasks Human Agent
') if 'with_distractors' in FLAGS.level_name: # for the tasks from the HTM paper episode_length_seconds = 450.0 else: episode_length_seconds = 120.0 env_settings = dm_fast_mapping.EnvironmentSettings( seed=FLAGS.seed, level_name=FLAGS.level_name, episode_length_seconds=episode_length_seconds...
franklingu/leetcode-solutions
questions/russian-doll-envelopes/Solution.py
Python
mit
1,024
0.010742
""" You have a number of envelopes with widths and heights given as a pair of integers (w, h). One envelope can fit into another if and only if both the width and height of one envelope is greater than the width and height of the other envelope. What is the maximum number of envelopes can you Russi
an doll? (put one inside other) Note: Rotation is not allowed. Example: Input: [[5,4],[6,4],[6,7],[2,3]] Output: 3 Explanation: The maximum number of envelopes you can Russian doll is 3 ([2,3] => [5,4] => [6,7]). """ import bisect class Solution(object): def maxEnvelopes(self, envelopes):
""" :type envelopes: List[List[int]] :rtype: int """ if not envelopes: return 0 envelopes.sort(key=lambda x:(x[0],-x[1])) h=[] for i, e in enumerate(envelopes,0): j = bisect.bisect_left(h, e[1]) if j < len(h): ...
philgyford/django-ditto
ditto/flickr/migrations/0024_auto_20201119_1539.py
Python
mit
1,708
0
# Generated by Django 3.1.3 on 2020-11-19 15:39 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('flickr', '0023_auto_20180104_1457'), ] operations = [ migrations.AddField( model_name='photo', name='x_large_3k_heig...
sitiveSmallIntegerField(blank=True, null=True), ), migrations.AddField( model_name='photo', name='x_large_4k_height', field=models.PositiveSmallIntegerField(blank=True, null=True), ), migrations.AddField( model_name='photo', nam...
name='x_large_5k_height', field=models.PositiveSmallIntegerField(blank=True, null=True), ), migrations.AddField( model_name='photo', name='x_large_5k_width', field=models.PositiveSmallIntegerField(blank=True, null=True), ), migr...
limifly/ntpserver
ntpserver.py
Python
mit
9,482
0.0058
import datetime import socket import struct import time import Queue import mutex import threading import select taskQueue = Queue.Queue() stopFlag = False def system_to_ntp_time(timestamp): """Convert a system time to a NTP time. Parameters: timestamp -- timestamp in system time Returns: corres...
metric active", 2: "symmetric passive", 3: "client", 4: "server", 5: "broadcast", 6: "reserved for NTP control messages", 7: "reserved for private use", } """mode table""" LEAP_TABLE = { 0: "no warning", 1: "last minute has 61 seconds", ...
nds", 3: "alarm condition (clock not synchronized)", } """leap indicator table""" class NTPPacket: """NTP packet class. This represents an NTP packet. """ _PACKET_FORMAT = "!B B B b 11I" """packet format to pack/unpack""" def __init__(self, version=2, mode=3, tx_timestamp...
josecasares/UWS
OPCPLCModule.py
Python
gpl-3.0
6,469
0.015831
"""Gestión de controlador con comunicación OPC UA. """ __author__="José A. Casares" __date__="2016-02-14" __version__="1.3" from threading import Thread from TagModule import * import time from opcua import ua, Client class OPCPLC(PLC): """PLC con comunicación OPC UA. Args:: address (str): Dirección I...
e),OPCPLC.opctype[self.type])) if self.type>=2 and self.type<=9: self.node.set_value(ua.Variant(int(value),OPCPLC.opctype[self.type])) if self.type>=10 and self.type<=11: self.node.set_value(ua.Variant(float(value),OPCP
LC.opctype[self.type])) if self.type==12: self.node.set_value(ua.Variant(str(value),OPCPLC.opctype[self.type])) if self.type==13: self.node.set_value(ua.Variant(datetime.strptime(value,"%Y-%m-%d %H:%M:%S"),OPCPLC.opctype[self.type])...
mbrenig/SheetSync
setup.py
Python
mit
800
0.00125
from setuptools import setup import os execfile(os.path.join('sheetsync','version.py')) with open('README.rst') as fh: long_description = fh.read() with open('requi
rements.txt') as fh: requirements = [line.strip() for line in fh.readlines()] setup( name='sheetsync', version=__version__, description="Synchronize rows of data with a google spreadsheet", long_description=long_description, author='Mark Brenig-Jones', author_email='markbrenigjones@gmail.co...
opment Status :: 4 - Beta", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 2.7", ], )
Mariatta/pythondotorg
jobs/migrations/0001_initial.py
Python
apache-2.0
6,405
0.004059
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import markupfield.fields import django.utils.timezone from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODE...
ions.AddField( model_name='job', name='job_types', field=models.ManyToManyField(to='jobs.JobType', verbose_name='Job technologies', related_name='jobs', blank=True), preserve_default=True,
), migrations.AddField( model_name='job', name='last_modified_by', field=models.ForeignKey(null=True, to=settings.AUTH_USER_MODEL, related_name='jobs_job_modified', blank=True, on_delete=models.CASCADE), preserve_default=True, ), ]
hbrunn/server-tools
__unported__/import_odbc/import_odbc.py
Python
agpl-3.0
10,315
0.004653
# -*- coding: utf-8 -*- ############################################################################## # # Daniel Reis # 2011 # # 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 ...
sync." "\n
Later changes on the source may not be replicated on the destination"), 'start_run': fields.datetime('Time started', readonly=True), 'last_run': fields.datetime('Time ended', readonly=True), 'last_record_count': fields.integer('Last record count', readonly=True), 'last_error_count': ...
mvwicky/ScotusScraper
logger.py
Python
mit
2,583
0.000774
import os import sys from datetime import datetime class Logger(object): """class that logs output to a log file and stdout""" def __init__(self, name, save_dir=None, attr=None, ovrw=False): """Constructor name: the name for the log file attr: an optional additional name for the...
ath, log_name) if ovrw: os.unlink(self.log_path) self.__call__('Log Overwritten') def name(self): return os.path.split(self.log_path)[1] def __call__(self, msg, ex=False, exit_code=-1): """ writes to log file and stdout msg: message to log
ex: whether or not to exit exit_code: the exit code to emit, unused if not exiting """ msg = ''.join([str(msg), '\n']) sys.stdout.write(msg) sys.stdout.flush() now = datetime.now().strftime("%X") with open(self.log_path, 'a') as log: log.write('...
takeflight/wagtail
wagtail/admin/edit_handlers.py
Python
bsd-3-clause
29,420
0.0017
import functools import re from django import forms from django.core.exceptions import FieldDoesNotExist, ImproperlyConfigured from django.db.models.fields import CharField, TextField from django.forms.formsets import DELETION_FIELD_NAME, ORDERING_FIELD_NAME from django.forms.models import fields_for_model from django...
mfield_callback=formfield_for_dbfield) for field_name, field in fields.items(): try: panel
_class = field.widget.get_panel() except AttributeError: panel_class = FieldPanel panel = panel_class(field_name) panels.append(panel) return panels class EditHandler: """ Abstract class providing sensible default behaviours for objects implementing the EditHandle...
Digilent/u-boot-digilent
tools/binman/fdt_test.py
Python
gpl-2.0
2,920
0.000342
# SPDX-License-Identifier: GPL-2.0+ # Copyright (c) 2016 Google, Inc # Written by Simon Glass <sjg@chromium.org> # # Test for the fdt modules import os import sys import tempfile import unittest from dtoc import fdt from dtoc import fdt_util from dtoc.fdt import FdtScan from patman import tools class TestFdt(unittes...
tEquals(fdt.TYPE_BYTE, prop.type) self.assertEquals(chr(8), prop.value) prop = node.props['bytearray'] self.assertEquals(fdt.TYPE_BYTE, prop.type) self.assertEquals(list, type(prop.value)) self.assertEquals(str, type(prop.value[0])) self.assertEquals(3, len(prop.value)) ...
als(0x090a0b0c, fdt_util.GetInt(node, 'longbytearray')) prop = node.props['stringval'] self.assertEquals(fdt.TYPE_STRING, prop.type) self.assertEquals('message2', fdt_util.GetString(node, 'stringval')) prop = node.props['stringarray'] self.assertEquals(fdt.TYPE_STRING, prop.typ...
tgenin/botstral
tweet_analyzer.py
Python
gpl-2.0
3,517
0.001138
#!/usr/bin/env python # -*- coding: utf-8 -*- # Botstral - a bot # Copyright (C) 2014 Thomas Génin # # This file is part of Botstral. # # Botstral 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...
weet_log' def retweet_log(tweet): name = tweet.user.screen_name rt_num = tweet.retweet_count f_num = tweet.user.friends_count rt_ratio = 0
if f_num == 0 else float(rt_num) / f_num try: logger.info('<{}> {} ({} - {})'.format(name, tweet.text, rt_num, rt_ratio)) logger.info('http://twitter.com/{}/status/{}'.format( tweet.user.screen_name, tweet.id)) except Exception as e: logger.info('Error in logging re...
phodal/iot-code
chapter5/test-post.py
Python
mit
160
0.0125
import re
quests import time while 1: r = requests.put("http://localhost:3000/api/4", data={"temperature": 24, "led": 1}) print r.
text time.sleep(1)
MrP01/SymbolWorte
Progress.py
Python
gpl-3.0
2,678
0
from PySide6.QtCore import QObject, Signal, QThread, QEventLoop from PySide6.QtWidgets import QWidget, QProgressBar, QPushButton, QHBoxLayout class Calculator(QObject): calculationDone = Signal(object) def __init__(self): QObject.__init__(self) self.progress = Progress() def main(self, a...
) class ProgressView(QWidget): def __init__(self, progress=None, parent=None): QWidget.__init__(self, parent) self.progressBar = QProgressBar() self.abortButton = QPushButton() layout = QHBoxLayout() layout.addWidget(self.progressBar) layout.addWidget(self.abortBut...
if progress: self.setProgress(progress) def setProgress(self, progress): self.progress = progress self.progress.progressSetup.connect(self.progressBar.setMaximum) self.progress.progressNotified.connect(self.progressBar.setValue) self.progress.progressCompleted.conn...
sebdelsol/pyload
module/plugins/hooks/MyfastfileCom.py
Python
gpl-3.0
1,045
0.007656
# -*- coding: utf-8 -*- from module.common.json_l
ayer import json_loads from module.network.RequestFactory import getURL from module.plugins.internal.MultiHoster import MultiHoster class MyfastfileCom(MultiHoster): __name__ = "MyfastfileCom" __type__ = "hook" __version__ = "0.02" __conf
ig__ = [("hosterListMode", "all;listed;unlisted", "Use for hosters (if supported)", "all"), ("hosterList", "str", "Hoster list (comma separated)", ""), ("unloadFailing", "bool", "Revert to standard download if download fails", False), ("interval", "int", "Reload int...
LeoLiangZhang/Picocenter
worker/netfilter.py
Python
mit
4,059
0.000246
import sys import threading from netfilterqueue import NetfilterQueue import dpkt import socket import config logger = config.logger class FlowControlQueue: ''' The class creates a NetfilterQueue that blocks/releases IP packets of given types. ''' def __init__(self, worker, queue_num=config.WorkerCo...
, proto): bname = self._block_name(dip, dport, proto) with self.lck: if bname not in self.block_table: self.block_table[bname] = [] self.worker_already_informed[bname] = False self._debug("block {0}".format(bname)) def release(self, dip, dport, pr...
h self.lck: if bname in self.block_table: blocked_pkts = self.block_table[bname] del self.block_table[bname] del self.worker_already_informed[bname] n = len(blocked_pkts) for pkt in blocked_pkts: pkt.accept() self._debug("re...
enriclluelles/troposphere_sugar
troposphere_sugar/runner.py
Python
mit
2,590
0.002317
from __future__ import print_function import boto3 import sys import time import botocore.exceptions class Runner(object): def __init__(self, template, stack_name, params=[], iam_capability=False, session=None): self.stack_name = stack_name self.iam_capability = iam_capability self.params =...
on_args()) def update(self): try:
self.client.update_stack(**self.stack_operation_args()) except botocore.exceptions.ClientError as e: if "No updates are to be performed" not in str(e): raise def wait(self): stack_status = "" count = 0 while stack_status not in ["UPDATE_COMPLETE", "CREAT...
tylertian/Openstack
openstack F/nova/nova/scheduler/filters/extra_specs_ops.py
Python
apache-2.0
2,088
0
# Copyright (c) 2011 OpenStack, LLC. # 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 requi...
x: <or> v1 <or> v2 <or> v3
while True: if words.pop(0) == value: return True if not words: break op = words.pop(0) # remove a keyword <or> if not words: break return False if words and method(value, words[0]): return True...
FallenWarrior2k/cardinal.py
src/cardinal/db/migrations/versions/52d93745fa71_index_muted_until_column_for_use_in_.py
Python
mit
743
0.001346
"""Index muted_until column for use in filters Revision ID: 52d93745fa71 Revises: dc0db050f230 Create Date: 2018-12-13 13:53:58.895770 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '52d93745fa71' down_revision = 'dc0db050f230' branch_labels = None depends_on ...
p.create_index(op.f('ix_mute_users_muted_until'), 'mute_users', ['muted_until'], unique=False) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_index(
op.f('ix_mute_users_muted_until'), table_name='mute_users') # ### end Alembic commands ###
ChuanleiGuo/AlgorithmsPlayground
LeetCodeSolutions/python/554_Brick_Wall.py
Python
mit
498
0.002008
class Solution(object): def leastBricks(self, wall): """ :type wall: List[List[int]] :rtype: int """ if len(wall) == 0: return 0 count = 0 hash_map = {} for row in wall: length = 0 for brick
in row[:-1]: length += brick hash_map[length] = hash_map.get(length, 0) +
1 count = max(count, hash_map[length]) return len(wall) - count
elaeon/dsignature
creacion_firma/migrations/0022_userdocumentsign_xml_pkcs7.py
Python
gpl-3.0
478
0
# -*- coding: ut
f-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [
('creacion_firma', '0021_auto_20150618_1457'), ] operations = [ migrations.AddField( model_name='userdocumentsign', name='xml_pkcs7', field=models.FileField(null=True, upload_to=b'', blank=True), preserve_default=True, ), ]
Sohojoe/damon
damon1/templates/blank.py
Python
apache-2.0
5,739
0.003136
# -*- coding: utf-8 -*- # opts.py """blank.py Generic template for importing modules needed to write Damon scripts. Copyright (c) 2009 - 2011, [Developer Name] for [Company Name]. Purpose: Damon Version: Python Version: Numpy Version: License ------- Licensed under the Apache License, Version 2.0 (the "License"); ...
d.wright_map() => Plot person and item distributions d.bank() => Save row/column coordinates in "bank" file d.export() => Export specified outputs as files """ import os import sys import warnings warnings.simplefilter('ignore') # matplotlib produces ann...
otlib.pyplot as plt except ImportError: pass # If damon1 is not stored in your Python's site-packages folder, specify path damon1_path = '/Users/markhmoulton/Google Drive/my_python' if damon1_path: sys.path.append(damon1_path) import damon1 as damon1 import damon1.core as dmn import damon1.tools as dmnt # S...
oso/qgis-etri
tests/test_table_pt.py
Python
gpl-3.0
4,538
0.005509
#!/usr/bin/python import sys sys.path.insert(0, "..") from qgis.PyQt import QtCore from qgis.PyQt import QtGui from qgis.PyQt import QtWidgets from qgis_etri.mcda.types import Alternatives, AlternativePerformances, Criteria, PerformanceTable from qgis_etri.table import qt_performance_table from xml.etree import Element...
rn str(fname) def save_to_xmcda(): if not pt_table: return fname = save_dialog_box() if fname: root = ElementTree.Element('{http
://www.decision-deck.org/2009/XMCDA-2.1.0}XMCDA') pt_xmcda = pt.to_xmcda() criteria_xmcda = c.to_xmcda() alternatives_xmcda = a.to_xmcda() root.append(pt_xmcda) root.append(criteria_xmcda) root.append(alternatives_xmcda) indent(root) ElementTree.dump(root)...
TangentMicroServices/LibraryService
libraryservice/settings.py
Python
mit
3,615
0.002213
""" Django settings for libraryservice project. For more information on this file, see https://docs.djangoproject.com/en/1.7/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.7/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...
, 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.
contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'libraryservice.urls' WSGI_APPLICATION = 'libraryservice...
Molecular-Image-Recognition/Molecular-Image-Recognition
code/rmgpy/data/kinetics/groups.py
Python
mit
27,577
0.010661
#!/usr/bin/python # -*- coding: utf-8 -*- ################################################################################ # # RMG - Reaction Mechanism Generator # # Copyright (c) 2002-2017 Prof. William H. Green (whgreen@mit.edu), # Prof. Richard H. West (r.west@neu.edu) and the RMG Team (rmg_dev@mit.edu) # # ...
ithout restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, subli
cense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDE...
luizpericolo/alc-2014-3
movie_base.py
Python
gpl-3.0
3,879
0.004898
#coding: utf-8 import numpy as np class MovieBase(): def read_from_csv(self, file_path): f = open(file_path, 'r') self.matrix = np.loadtxt(f, delimiter=',') self.shape = self.matrix.shape f.close() def get_user_unseen_films(self, user_idx): if user_idx >= self.shape[...
rediction) # l_r_appr = np.zeros(self.shape) # for i in range(k): # l_r_appr += self._S[i] * np.dot(self.U.transpose()[i], self.V_t[:,i]) # print l_r_appr # Uk, _Sk, Vk_t = np.linalg.svd(l_r_appr, ful
l_matrices=True) # print "Uk: {}".format(Uk) # print "_Sk: {}".format(_Sk) # print "Vk_t: {}".format(Vk_t)
diogenesfilho/Estadio
Estádio/projeto_orientado/app/Complex.py
Python
gpl-2.0
45,005
0.018979
# -*- coding: utf-8 -*- from gi.overrides.keysyms import musicalflat from OpenGL.GL import * from OpenGL.GLU import * from OpenGL.GLUT import * from PIL import Image from pygame.mixer import music class BancoReserva: def __init__(self): self.textura1 = glGenTextures(1) self.obj = GLuint() def...
R) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glTexImage2D( GL_TEX
TURE_2D, 0, 3, ix, iy, 0, GL_RGBA, GL_UNSIGNED_BYTE, image ) def desenhar(self): self.obj = glGenLists(3) glNewList(self.obj,GL_COMPILE) glPushMatrix() glTranslatef(10, -.15, 5) glScale(.05,.05,.05) glRotate(35, 0, 1, 0) #Coluna Esq ...
MrLeeh/jsonwatchqt
jsonwatchqt/mainwindow.py
Python
mit
19,071
0.00021
#! python3 """ GUI for Ultrasonic Temperature Controller Copyright (c) 2015 by Stefan Lehmann """ import os import datetime import logging import json import serial from qtpy.QtWidgets import QAction, QDialog, QMainWindow, QMessageBox, \ QDockWidget, QLabel, QFileDialog, QApplication from qtpy.QtGui imp...
# record widget self.recordWidget = RecordWidget(self.rootnode, self) self.recordDockWidget = QDockWidget(self.tr("data recording"), self)
self.recordDockWidget.setObjectName("record_dockwidget") self.recordDockWidget.setWidget(self.recordWidget) # actions and menus self._init_actions() self._init_menus() # statusbar statusbar = self.statusBar() statusbar.setVisible(True) self.conne...
mjuric/duplicity
duplicity/backends/hsibackend.py
Python
gpl-2.0
2,314
0.002593
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*- # # Copyright 2002 Ben Escoto <ben@emerose.org> # Copyright 2007 Kenneth Loafman <kenneth@loafman.com> # # This file is part of duplicity. # # Duplicity is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License...
option) any later version. # # Duplicity 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 # General Public License for more details. # # You should have received a copy of the GNU Gene...
city; if not, write to the Free Software Foundation, # Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA import os import duplicity.backend hsi_command = "hsi" class HSIBackend(duplicity.backend.Backend): def __init__(self, parsed_url): duplicity.backend.Backend.__init__(self, parsed_url) ...
osrf/rosbook
teleop_bot/keys_to_twist_with_ramps.py
Python
apache-2.0
2,634
0.02164
#!/us
r/bin/env python # BEGIN ALL import rospy import math from std_msgs.msg import String from geometry_msgs.msg import Twist key_mapping = { 'w':
[ 0, 1], 'x': [ 0, -1], 'a': [ 1, 0], 'd': [-1, 0], 's': [ 0, 0] } g_twist_pub = None g_target_twist = None g_last_twist = None g_last_send_time = None g_vel_scales = [0.1, 0.1] # default to very slow g_vel_ramps = [1, 1] # units: meters per second^2 # BEGIN RAMP def ramped_vel(v_p...
agoose77/hivesystem
manual/movingpanda/panda-finalweb.py
Python
bsd-2-clause
1,591
0.002514
import spyder import movingpanda_datamodel import Spyder pandadict = {} # First panda class a = Spyder.AxisSystem() a *= 0.005 data = "models/panda-model", "egg", [("walk", "models/panda-walk4", "egg")], a box = Spyder.Box2D(50, 470, 96, 96) image = "pandaicon.png", True hivemap = "pandawalk.web" pandadict["pandaclas...
els/panda-walk4", "egg")], a box = Spyder.Box2
D(200, 500, 48, 48) image = "pandaicon.png", True hivemap = "pandawalk2.web" pandadict["pandaclass2"] = ("actor", data, box, image, hivemap) #Third panda class a = Spyder.AxisSystem() a *= 0.3 data = "models/panda", "egg", [], a box = Spyder.Box2D(280, 480, 144, 112) image = "pandaicon2.png", True hivemap = "pandajump...
sauloal/cnidaria
scripts/venv/lib/python2.7/site-packages/ete2/_ph.py
Python
mit
4,356
0.011708
# #START_LICENSE########################################################### # # # This file is part of the Environment for Tree Exploration program # (ETE). http://etetoolkit.org # # ETE is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # t...
cific methods implemented in # the toolkit may be available in the documentation. # # More info at http://etetoolkit.org. Contact: huerta@embl.de # # # #END_LICENSE############################################################# ''' I use this module to check for newer versions of ETE ''' import urllib2 as url try...
__ except ImportError: __VERSION__ = "Unknown" def call(): print " == Calling home...", try: f = url.urlopen('http://etetoolkit.org/et_phone_home.php?VERSION=%s&ID=%s' %(__VERSION__, __ETEID__)) except: print "No answer :(" else: print "Got answer!" ...
answerrrrrrrrr/myflask
migrations/versions/02ccb3e6a553_.py
Python
mit
2,065
0.013075
"""empty message Revision ID: 02ccb3e6a553 Revises: None Create Date: 2016-05-17 22:15:03.881575 """ # revision identifiers, used by Alembic. revision = '02ccb3e6a553' down_revision = None from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - please adjust! ###...
umn('name', sa.String(length=64), nullable=True), sa.Column('default', sa.Boolean(), nullable=True), sa.Column('permissions', sa.Integer(), nullable=True), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('name') ) op.create_index(op.f('ix_roles_default'), 'roles', ['default'], unique=False) ...
.Column('username', sa.String(length=64), nullable=True), sa.Column('role_id', sa.Integer(), nullable=True), sa.Column('password_hash', sa.String(length=128), nullable=True), sa.Column('confirmed', sa.Boolean(), nullable=True), sa.Column('name', sa.String(length=64), nullable=True), sa.Column('locat...
SolaWing/ycmd
ycmd/tests/clang/flags_test.py
Python
gpl-3.0
50,631
0.03014
# Copyright (C) 2011-2019 ycmd contributors # # This file is part of ycmd. # # ycmd 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. # #...
Public License for more details. # # You should have received a copy of the GNU General Public License # along with ycmd. If not, see <http://w
ww.gnu.org/licenses/>. from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import # Not installing aliases from python-future; it's unreliable and slow. from builtins import * # noqa import contextlib import os from hamcrest im...
jamesbeebop/evennia
evennia/web/website/tests.py
Python
bsd-3-clause
9,576
0.001462
from django.conf import settings from django.utils.text import slugify from django.test import Client, override_settings from django.urls import reverse from evennia.utils import class_from_module from evennia.utils.test_resources import EvenniaTest class EvenniaWebTest(EvenniaTest): # Use the same classes the v...
et_kwargs()), follow=True) self.assertEqual(response.status_code, self.authenticated_response) # ------------------------------------------------------------------------------ class AdminTest(EvenniaWebTest)
: url_name = "django_admin" unauthenticated_response = 302 class IndexTest(EvenniaWebTest): url_name = "index" class RegisterTest(EvenniaWebTest): url_name = "register" class LoginTest(EvenniaWebTest): url_name = "login" class LogoutTest(EvenniaWebTest): url_name = "logout" class Passw...
matthrice/MarkeTouch-TTS
src/executer.py
Python
apache-2.0
5,222
0.035236
import subprocess import requests import os import wave URL = 'WATSON_URL' PASSWORD = 'WATSON_PASSWORD' USERNAME = 'WATSON_USERNAME' CHUNK_SIZE = 1024 def download(text, filename, path): #requests gets response using parameters for authorization and audio format #stream=True allows it to be streamed as well #ve...
"Spanish": voice = "es-US_SofiaVoice" #checks if no language change, if so leaves off count if len(stringList) == 1: #downloads file, also appends to fileList f = download(b, filename + extension, path) fileList.append(f)
else: f = download(b, filename + str(count) + extension, path) fileList.append(f) #creates an english file elif a == "English": voice = english #checks if no language change, if so leaves off count if len(stringList) == 1: f = download(b, filename + extension, path) fileList.appen...
meteoswiss-mdr/monti-pytroll
scripts/plot_hrw.py
Python
lgpl-3.0
12,338
0.017507
from __future__ import division from __future__ import print_function from datetime import datetime import sys, string, os import logging sys.path.insert(0, "/home/lom/users/cll/pytroll/install/lib/python2.6/site-packages") from mpop.satellites import GeostationaryFactory from mpop.projector import get_area_def from m...
+'_HRW_'+area+'/' #output_dir='/data/cinesat/out/' output_dir='./pics/' if not exists(output_dir): print('... create output directory: ' + output_dir) makedirs(output_dir) image_type ='.png' # preparation for adding the title if add_title: # get font for title fontsize=18 font = ImageFont.truety...
** plot detailed winds") detailed_str = 'detailed' # hrw_channels=None, min_correlation=None, cloud_type=None, style='barbs' detailed_char = 'd' else: print("*** plot basic winds") detailed_str = 'basic' detailed_char = 'b' # read HRW wind vectors p...
cedricbonhomme/c-dric-on-mange-o-midi
refuge/__init__.py
Python
agpl-3.0
1,267
0.004736
#! /usr/bin/env python # -*- coding: utf-8 -*- import os import json fr
om flask import Flask app = Flask(__name__) app.config.from_object(__name__) # Loads the restaurants RESTAURANTS = {} with open('./refuge/var/restaurants.json', 'r') as f: RESTAURANTS = json.load(f) AREAS = { "Kirchberg": [49.6383, 6.1349, 49.6228,
6.1785], "Gare": [49.6088, 6.1206, 49.5953, 6.1472], "Esch-sur-Alzette": [49.5532, 5.8868, 49.4896, 5.9991], "Sierck-Les-Bains": [49.4770, 6.3202, 49.4154, 6.4342], "Sarreguemines": [49.3323, 6.5286, 48.9274, 7.5157] } jc_decaux_api_key = os.environ.get('JCDecaux...
mblayman/markwiki
markwiki/storage/fs/__init__.py
Python
bsd-2-clause
97
0
# Copyright (c
) 2016, Matt Layman '''Storage services which use the file system to stor
e data'''
Mistobaan/tensorflow
tensorflow/contrib/distributions/python/kernel_tests/mvn_diag_test.py
Python
apache-2.0
11,359
0.008804
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the A
pache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may
obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for ...
fgaudin/aemanager
notification/migrations/0001_initial.py
Python
agpl-3.0
4,760
0.008193
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def
forwards(self, orm): # Adding model 'Notification' db.create_table('notification_notification', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('user', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['auth.User'], unique=True)), ...
gf('django.db.models.fields.BooleanField')(default=False)), ('notify_invoices_to_send', self.gf('django.db.models.fields.BooleanField')(default=False)), ('notify_bug_comments', self.gf('django.db.models.fields.BooleanField')(default=False)), )) db.send_create_signal('notification...
cjcardinale/climlab
climlab/process/process.py
Python
mit
34,601
0.003266
#============================================================================== # Principles of the new `climlab` API design: # # * `climlab.Process` object has several iterable dictionaries of named, # gridded variables: # # * `process.state` # # * state variables, usually time-dependent...
cess.process.Process` :param array la
t: latitudinal points (optional) :param lev: altitudinal points (optional) :param int num_lat: number of latitudional points (optional) :param int num_levels: number of altitudinal points (optional) :param dict input: collection of input quantities :param bool verb...
ProfessorX/Config
.PyCharm30/system/python_stubs/-1247971765/PyKDE4/kdecore/KGlobal.py
Python
gpl-2.0
2,143
0.011666
# encoding: utf-8 # module PyKDE4.kdecore # from /usr/lib/python3/dist-packages/PyKDE4/kdecore.cpython-34m-x86_64-linux-gnu.so # by generator 1.135 # no doc # imports import PyQt4.QtCore as __PyQt4_QtCore import PyQt4.QtNetwork as __PyQt4_QtNetwork class KGlobal(): # skipped bases: <class 'sip.wrapper'> # no doc...
signature unknown pass def setActiveComponent(self, *args, **kwargs): # real signature unknow
n pass def setAllowQuit(self, *args, **kwargs): # real signature unknown pass def setLocale(self, *args, **kwargs): # real signature unknown pass def staticQString(self, *args, **kwargs): # real signature unknown pass def umask(self, *args, **kwargs): # real signature...
LumPenPacK/NetworkExtractionFromImages
win_build/nefi2_win_amd64_msvc_2015/site-packages/networkx/algorithms/bipartite/tests/test_cluster.py
Python
bsd-2-clause
2,709
0.042451
import networkx as nx from nose.tools import * from networkx.algorithms.bipartite.cluster import cc_dot,cc_min,cc_max import networkx.algorithms.bipartite as bipartite def test_pairwise_bipartite_cc_functions(): # Test functions for different kinds of bipartite clustering coefficients # between pairs of nodes ...
),answer) def test_average_path_graph(): G=nx.path_graph(4) assert_equal(bipartite.average_clustering(G,mode='dot'),0.5) assert_equal(bipartite.average_clustering(G,mode='max'),0.5) assert_equal(bipartite.average_clustering(
G,mode='min'),1) def test_ra_clustering_davis(): G = nx.davis_southern_women_graph() cc4 = round(bipartite.robins_alexander_clustering(G), 3) assert_equal(cc4, 0.468) def test_ra_clustering_square(): G = nx.path_graph(4) G.add_edge(0, 3) assert_equal(bipartite.robins_alexander_clustering(G), 1...
H0w13/WebGrabber
website/handlers/fund.py
Python
mit
193
0.005181
from handlers.base import BaseHandler import logging logger = logging.getLogger('boilerplate.' + __name__)
class FundHandler(BaseHandler): def g
et(self): self.render("fund.html")
ahelsing/geni-ch
plugins/csrm/CredentialStore.py
Python
mit
11,171
0.005819
#---------------------------------------------------------------------- # Copyright (c) 2011-2015 Raytheon BBN Technologies # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and/or hardware specification (the "Work") to # deal in the Work without restriction, including ...
esponse.append((str(row[0]), str(row[1]))) else: response.append((str(row[0]), None)) return self._successReturn(response) # Return row.context if it has, otherwise None def get_context(self, row): if hasattr(row, 'context'):
return str(row.context) return None def get_permissions(self, client_cert, principal, credentials, options, session): q = session.query(self.db.CS_ACTION_TABLE.c.name, self.db.CS_ACTION_TABLE.c.context_type, self.d...
frossigneux/kwstandby
kwstandby/openstack/common/policy.py
Python
apache-2.0
25,233
0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (c) 2012 OpenStack Foundation. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www....
requested rule is not found')), ] CONF = cfg.CONF CONF.register_opts(policy_opts) LOG = logging.getLogger(__name__) _checks = {} class PolicyNotAuthorized(Exception): def __init__(self, rule): msg = _("Policy doesn't allow %s to be performed.") % rule super(PolicyNotAuthorized, self).__init__...
ding of JSON rule data.""" # Suck in the JSON data and parse the rules rules = dict((k, parse_rule(v)) for k, v in jsonutils.loads(data).items()) return cls(rules, default_rule) def __init__(self, rules=None, default_rule=None): """Initialize the Rules store."...
a25kk/mitr
src/mitr.sitetheme/mitr/sitetheme/testing.py
Python
mit
1,948
0
# -*- coding: utf-8 -*- """Base module for unittesting.""" from plone.app.testing import applyProfile from plone.app.testing imp
ort FunctionalTesting from plone.app.testing import IntegrationTesting from plone.app.testing import login from plone.app.testing import PLONE_FIXTURE from plone.app.testing import PloneSandboxLayer from plone.app.testing import setRoles from plone.app.testing import TEST_USER_ID from plone.app.testing import TEST_USER...
NE_FIXTURE,) def setUpZope(self, app, configurationContext): """Set up Zope.""" # Load ZCML import mitr.sitetheme self.loadZCML(package=mitr.sitetheme) z2.installProduct(app, 'mitr.sitetheme') def setUpPloneSite(self, portal): """Set up Plone.""" # Insta...
dimagi/commcare-hq
corehq/apps/cleanup/management/commands/delete_duplicate_users.py
Python
bsd-3-clause
4,468
0.001343
import itertools from collections import defaultdict from django.contrib.auth.models import User from django.core.management import BaseCommand from corehq.apps.es import FormES from corehq.apps.users.dbaccessors import ( get_all_user_id_username_pairs_by_domain, ) from corehq.apps.users.models import CommCareUse...
licates_to_delete): all_usernames = {u.username for u in all_users} duplicates_usernames = {u.username for u in duplicates_to_delete} assert len(all_usernames) == 1 assert len(all_usernames
& duplicates_usernames) == 1 print(f'Deleting {len(duplicates_to_delete)} users for {all_users[0].username}') for user_to_delete in duplicates_to_delete: print(f' Deleting {user_to_delete.user_id}') # CommCareUser.delete from corehq.apps.ota.utils import delete_demo_restore_for_user...
kennethreitz/pipenv
pipenv/vendor/plette/__init__.py
Python
mit
151
0
__all__ = [ "__version__", "Lockfile", "Pipfile", ] __ver
sion__
= '0.2.4.dev0' from .lockfiles import Lockfile from .pipfiles import Pipfile
bokeh/bokeh
sphinx/source/docs/user_guide/examples/styling_title.py
Python
bsd-3-clause
289
0
from
bokeh.plotting import figure, output_file, show output_file("title.html") p = figure(width=400, height=400, title="Some Title") p.title.text_color = "olive" p.title.text_font = "times" p.title.text_font_style = "italic"
p.circle([1, 2, 3, 4, 5], [2, 5, 8, 2, 7], size=10) show(p)
caimmy/prehistory
utils/url_helper.py
Python
gpl-3.0
581
0.003591
# _*_ coding:utf-8 _*_ __author__ = 'caimiao' __date__ = '15-6-7' import base64
from flask import url_for from utils.encode_helper import ensure_bytes def makeTipsPageUrl(_title, _content, _theme='info', _jumpurl=''): """ 构造提示信息页的跳转参数 :param url: :param _title: :param _content: :param _jumpto: :param _theme: :return: """ return url_for("TipsPage", title=bas...
(ensure_bytes(_content)), theme=_theme, jumpUrl=_jumpurl)
cyanfish/heltour
heltour/tournament/tests/test_api.py
Python
mit
1,289
0.003879
import json from django.test import TestCase, Client from heltour.tournament.models import * def createCommonAPIData(): team_count = 4 round_count = 3 board_count = 2 league = League.objects.create(name='Team League', tag='team', competitor_type='team') season
= Season.objects.create(league=league, name='Team Season', tag='team', rounds=round_count, boards=board_count) league2 = League.objects.create(name='Lone League', tag='lone') season2 = Season.objects.create(league=league2, name='Lone Season', tag='lone', ...
eam = Team.objects.create(season=season, number=n, name='Team %s' % n) TeamScore.objects.create(team=team) for b in range(1, board_count + 1): player = Player.objects.create(lichess_username='Player%d' % player_num) player_num += 1 TeamMember.objects.create(team=team,...
codelucas/uci-web-extraction-workshop
basic.py
Python
mit
1,190
0
# -*- coding: utf-8 -*- import urllib2 from BeautifulSoup import BeautifulSoup # Download the HTML request = urllib2.Request('http://www.uci.edu') response = urllib2.urlopen(request) print '\r\n\r\n' # Verify that everything went ok. # Error codes: 200 == good, 404, 500 == ba
d print 'The error code is:', response.code print '\r\n\r\n' html = response.read() # Parse the HTML into a dom object via our BS library. dom = Beautifu
lSoup(html) # Extract out the <div> tag containing our news. news_tag = dom.find('div', {'id': 'news'}) # See what the extracted HTML looks like. print 'The extracted news div HTML looks like:' print '====================================' print news_tag print '\r\n\r\n' # Further extract out a list of the actual new...
chelnak/vRAAPIClient
examples/reservation/createReservations/createReservation.py
Python
mit
379
0
#!/usr/bin/python import getpass import json from globalco
nfig import passwd, url, usr from vraapiclient import reservation client = reservation.ReservationClie
nt(url, usr, passwd) with open('reservationTemplate.json') as json_data: payload = json.load(json_data) reservation = client.createReservation(payload) print "Reservation created: {id}".format(id=reservation)
RasaHQ/rasa_nlu
stubs/redis/__init__.py
Python
apache-2.0
1,588
0.001259
from typing import Text, List, overload, Optional, Union, Mapping, Literal from redis import ConnectionPool from typing_extensions import Protocol # We should switch to https://pypi.org/project/types-redis/ once # https://github.com/python/typeshed/issues/5065 is fixed. class StrictRedis(Protocol): @overload ...
iteral[False] = ..., retry_on_timeout: bool = ..., ssl: bool = ..., ssl_keyfile: Optional[Text] = ..., ssl_certfile: Optional[Text] = ..., ssl_cert_reqs: Optional[Union[str, int]] = ..., ssl_ca_certs: Optional[Text] = ..., ssl_check_hostname: bool = ..., m...
val: float = ..., client_name: Optional[Text] = ..., username: Optional[Text] = ..., ) -> None: ... def keys(self, pattern: Text) -> List[Text]: ...
terryyin/linkchecker
tests/checker/test_telnet.py
Python
gpl-2.0
1,953
0.001024
# -*- coding: iso-8859-1 -*- # Copyright (C) 2004-2012 Bastian Kleineidam # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later versi...
e the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License a
long # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. """ Test telnet checking. """ from .telnetserver import TelnetServerTest class TestTelnet (TelnetServerTest): """Test telnet: link checking.""" def test_telnet_error (s...
matthewdeanmartin/kata-python
kata/count_by/test.py
Python
gpl-3.0
124
0.008065
import unittest im
port kata.count_by.main as cb class Tests(unittest.TestCase): def test_main(self):
cb.run()
gtrichards/PHYS_T480
code/sklearn_ex1.py
Python
mit
1,063
0.003763
# G. Richards 2016, based on sgd_separator.py by Jake Vanderplas import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import SGDClassifier from sklearn.datasets.samples_generator import make_blobs # we create 50 separable points X, Y = make_blobs(n_samples=50, centers=2, random_state=0, cluste...
.60) # fit the model clf = SGDClassifier(loss="hinge", alpha=0.01, n_iter=200, fit_intercept=True) clf.fit(X, Y) # plot the line, the points, and the nearest vectors to the plane xx = np.linspace(-1, 5, 10) yy = np.linspace(-1, 5, 10)
X1, X2 = np.meshgrid(xx, yy) Z = np.empty(X1.shape) for (i, j), val in np.ndenumerate(X1): x1 = val x2 = X2[i, j] #p = clf.decision_function([x1, x2]) p = clf.decision_function(np.array([x1,x2]).reshape(1,-1)) Z[i, j] = p[0] levels = [-1.0, 0.0, 1.0] linestyles = ['dashed', 'solid', 'dashed'] colo...
endlessm/chromium-browser
third_party/catapult/third_party/WebOb/setup.py
Python
bsd-3-clause
2,154
0.001857
from setuptools import setup version = '1.5.0a0' testing_extras = ['nose', 'coverage'] docs_extras = ['Sphinx'] setup( name='WebOb', version=version, description="WSGI request and response object", long_description="""\ WebOb provides wrappers around the WSGI request environment, and an object to he...
"Topic :: Internet :: WWW/HTTP :: WSGI :: Application", "Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware", "Programming Language :: Python :: 2.6", "Programming Language :: Pyt
hon :: 2.7", "Programming Language :: Python :: 3.2", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", ], keywords='...
daviddoria/itkHoughTransform
Utilities/Maintenance/UpdateCopyrightStatementsInITK.py
Python
apache-2.0
6,444
0.019243
#!/usr/bin/python #========================================================================== # # Copyright Insight Software Consortium # # 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...
istributed 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. * *=========================================================================*/ """ NewVTKDependantCopyrightNotice="""/*========================================================================= * * Portions of this file a...
lablup/sorna-manager
src/ai/backend/manager/defs.py
Python
lgpl-3.0
262
0
""" Common definitions/constants used throughout the manager. """ from typing import Final from ai.backend.common.types import SlotName, SlotTypes INTRINSIC_SLOTS: Final = { SlotName('cpu'): SlotTypes('c
ount'), SlotName('mem'): SlotTypes('bytes'), }
sephalon/python-ivi
ivi/agilent/agilentDSOX4024A.py
Python
mit
1,689
0.004737
""" Python Interchangeable Virtual Instrument Library Copyright (c) 2014 Alex Forencich Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the righ...
IN THE SOFTWARE. """ from .agilent4000A import * class agilentDSOX4024A(agilent4000A): "Agilent InfiniiVision DSOX4024A IVI oscilloscope driver" def __init__(self, *args, **kwargs): self.__dict__.setdefault('_instrument_id', 'DSO-X 4024A') super(agilentDSOX4024A, self).__init__...
self._channel_count = self._analog_channel_count + self._digital_channel_count self._bandwidth = 200e6 self._init_channels()
fujy/ROS-Project
src/rbx2/rbx2_vision/nodes/unused/motion_history_demo.py
Python
mit
6,836
0.011264
#!/usr/bin/env python """ motion_history_demo.py - Version 1.0 2013-06-26 Based on the OpenCV motempl.py sample code Extends the ros2opencv2.py script which takes care of user input and image display Created for the Pi Robot Project: http://www.pirobot.org Copyright (c) 2013 Patrick Goebel. ...
s, (x, y), (x+w, y+h), (0, 255, 0)) r = min(w/2, h/2) cx, cy = x+w/2, y+h/2 angle = angle*np.pi/180 cv2.circle(vis, (cx, cy), r, color, 3) cv2.line(vis, (cx, cy), (int(cx+np.cos(angle)*r), int(cy+np.sin(angle)*r)), color, 3) def trunc(f, n): '''Truncates/pads a float f to n decimal plac...
g''' slen = len('%.*f' % (n, f)) return float(str(f)[:slen]) if __name__ == '__main__': try: node_name = "motion_history" MotionHistory(node_name) rospy.spin() except KeyboardInterrupt: print "Shutting down motion history node." cv2.destroyAllWindows()
qbahn/grortir
grortir/main/pso/swarm.py
Python
mit
2,603
0
"""Represents swarm.""" import numpy as np from grortir.main.pso.particle import Particle class Swarm(object): """Class which represent swarm.""" def __init__(self, process, stages, number_of_particles): self.stages = stages self.process = process self.number_of_particles = number_o...
ost() stage.final_quality
= stage.get_quality( stage.input_vector, best_control_params[stage]) def _post_process_not_run_stages(self): for stage in self.stages: successors = self.process.successors(stage) for successor in successors: successor.input_vector = None s...
nirvn/QGIS
python/plugins/processing/algs/gdal/GridDataMetrics.py
Python
gpl-2.0
9,332
0.003751
# -*- coding: utf-8 -*- """ *************************************************************************** GridDataMetrics.py --------------------- Date : October 2013 Copyright : (C) 2013 by Alexander Bruy Email : alexander dot bruy at gmail dot com *********...
rocessing.TypeVectorPoint])) z_field_param = QgsProcessingParameterField(self.Z_FIELD, self.tr('Z value from field'), None, self.INPUT, ...
tFlags(z_field_param.flags() | QgsProcessingParameterDefinition.FlagAdvanced) self.addParameter(z_field_param) self.addParameter(QgsProcessingParameterEnum(self.METRIC, self.tr('Data metric to use'), ...
Kentoseth/rangoapp
tango_with_django_project/tango_with_django_project/settings.py
Python
mit
6,169
0.002594
# Django settings for tango_with_django_project project. import os PROJECT_PATH = os.getcwd() TEMPLATE_PATH = os.path.join(PROJECT_PATH, 'templates') STATIC_PATH = os.path.join(PROJECT_PATH, 'static') DATABASE_PATH = os.path.join(PROJECT_PATH, 'rango.db') #MEDIA_URL = '/media/' #code shouldn't be here!!! #MEDIA_RO...
qlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'DATABASE_PATH', # Or path to database file if using sqlite3. # The following settings are not
used with sqlite3: # 'USER': '', # 'PASSWORD': '', # 'HOST': '', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP. # 'PORT': '', # Set to empty string for default. } } # Hosts/domain names that are valid for ...
phihag/adhocracy
src/adhocracy/migration/versions/001_Initial.py
Python
agpl-3.0
10,657
0.002815
from datetime import datetime from sqlalchemy import * from migrate import * meta = MetaData() user_table = Table('user', meta, Column('id', Integer, primary_key=True), Column('user_name', Unicode(255), nullable=False, unique=True, index=True), Column('display_name', Unicode(255), nullable=True, index=Tr...
Column('reply_id', Integer, ForeignKey('comment.id'), nullable=True) ) instance_table = Table('instance', meta, Column('id', Integer, primary_key=True), Column('key', Unicode(20), nullable=False, unique=True), Column('label', Unicode(255), nullable=False), Column('description
', UnicodeText(), nullable=True), Column('required_majority', Float, nullable=False), Column('activation_delay', Integer, nullable=False), Column('create_time', DateTime, default=func.now()), Column('access_time', DateTime, default=func.now(), onupdate=func.now()), Column('delete_time', DateTime, nu...
Pingmin/linux
tools/perf/scripts/python/exported-sql-viewer.py
Python
gpl-2.0
159,347
0.027669
#!/usr/bin/env python # SPDX-License-Identifier: GPL-2.0 # exported-sql-viewer.py: view data from sql database # Copyright (c) 2014-2018, Intel Corporation. # To use this script you will need to have exported data using either the # export-to-sqlite.py or the export-to-postgresql.py script. Refer to those # scripts f...
ide2.QtCore import * from PySide2.QtGui import * from PySide2.QtSql import * from PySide2.QtWidgets import * pyside_version_1 = False e
xcept: pass if pyside_version_1: from PySide.QtCore import * from PySide.QtGui import * from PySide.QtSql import * from decimal import * from ctypes import * from multiprocessing import Process, Array,
OriHoch/pysiogame
classes/logoimg.py
Python
gpl-3.0
3,434
0.006698
# -*- coding: utf-8 -*- import pygame import os from game_boards import game000 class LogoImg(pygame.sprite.Sprite): 'holds the logo in top left corner' def __init__(self, mainloop): # Call the parent's constructor pygame.sprite.Sprite.__init__(self) self.mainloop = mainloop se...
] is not None: self.mainloop.mouse_over[0].on_mouse_out() self.mainloop.mouse_over[0] = self if self.mainloop.mouse_over[1] is not None: self.mainloop.mouse_over[1].on_mouse_out() self.mainloop.mouse_over[1]
= None if self.mainloop.mouse_over[2] is not None: self.mainloop.mouse_over[2].on_mouse_out() self.mainloop.mouse_over[2] = None if self.state != 2: self.state = 1 self.mouse_over = True self.update() #print("enter (in logoimg.py)") self....
chenyyx/scikit-learn-doc-zh
examples/zh/cluster/plot_face_compress.py
Python
gpl-3.0
2,198
0.001821
#!/usr/bin/python # -*- coding: utf-8 -*- """ ========================================================= Vector Quantization Example ========================================================= Face, a 1024 x 768 size image of a raccoon face, is used here to illustrate how `k`-means is used for vector quantization. """ ...
eze() labels = k_means.labels_ # create an array from labels and values face_compressed = np.choose(labels, values) face_compressed.shape = face.shape vmin = face.min() vmax = face.max() # original face plt.figure(1, figsize=(3, 2.2)) plt.imshow(face, cmap=plt.cm.gray, vmin=vmin, vmax=256) # compressed face plt.fig...
2.2)) plt.imshow(face_compressed, cmap=plt.cm.gray, vmin=vmin, vmax=vmax) # equal bins face regular_values = np.linspace(0, 256, n_clusters + 1) regular_labels = np.searchsorted(regular_values, face) - 1 regular_values = .5 * (regular_values[1:] + regular_values[:-1]) # mean regular_face = np.choose(regular_labels.r...
opendaylight/opendove
odcs/data_handler/python/dcs_objects/DPSNodeStatistics.py
Python
epl-1.0
26,790
0.005487
''' @copyright (c) 2010-2013 IBM Corporation All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 which accompanies this distribution, and is available at http://www.eclipse.org/legal/epl-v10.html @author: Amitabha Biswas ''' imp...
''' # The CPU utilization values are stored in a circular array with 2 rows. # The current index of the row represents the latest values. In the example # below row 1 (with the latest) time is the current index. # The values in the row represents the number of operations between # Time Start and...
e reason we need 2 rows is because when a row moves forward e.g. from # array index 0 --> 1, the values in that new row are 0s, so for some time # we still need the old row 0 to compute the values. # -------------------------------------------------------------- # | Index | Time Start | Time End | Upd...
MonicaHsu/truvaluation
venv/lib/python2.7/site-packages/pymysql/tests/test_connection.py
Python
mit
2,580
0.000388
import pymysql import time from pymysql.tests import base class TestConnection(base.PyMySQLTestCase): def test_utf8mb4(self): """This test requires MySQL >= 5.5""" arg = self.databases[0].copy() arg['charset'] = 'utf8mb4' conn = pymysql.connect(**arg) def test_largedata(self):...
e()') self.assertEqual(cur.fetchone()[0], current_db) con.select_db(other_db) cur.execute('SELECT databa
se()') self.assertEqual(cur.fetchone()[0], other_db) def test_connection_gone_away(self): """ http://dev.mysql.com/doc/refman/5.0/en/gone-away.html http://dev.mysql.com/doc/refman/5.0/en/error-messages-client.html#error_cr_server_gone_error """ con = self.connections...
jr55662003/Diabetic-Retinopathy-website
website/diabetics/forms.py
Python
mit
178
0.011236
from django import forms class ImageUploadForm(forms.Form): '''Image upload form.''' image = forms.ImageF
ield(widget=forms.ClearableFileInput(attrs={'multiple':
True}))
bcoca/ansible-modules-extras
notification/grove.py
Python
gpl-3.0
3,463
0.006353
#!/usr/bin/python # -*- coding: utf-8 -*- # # This file is part of Ansible # # Ansible 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. ...
e: grove version_added: 1.4 short_description: Sends a notification to a grove.io channel description: - The M(grove) module sends a message for a service to a Grove.io channel. options: channel_token: description: - Token of the channel to post to. required: true service: description:...
- Message content required: true url: description: - Service URL for the web client required: false icon_url: description: - Icon for the service required: false validate_certs: description: - If C(no), SSL certificates will not be validated. This should only be used ...
AaronZhangL/az-AIchart-AIML-py
aiml/Utils.py
Python
gpl-2.0
1,169
0.017964
#!/usr/bin/env python # -*- coding: utf-8 -*- from LangSupport import splitChinese """This file contains assorted general utility functions used by other modules in the PyAIML package. """ # TODO: andelf, add chinese sentence support def sentences(s): """Split the string s into a list of sentences."...
the entire input string. if len(sentenceList) == 0: sentenceList.append(s) # auto convert chinese return map(lambda s: u' '.join(splitChinese(s)), sentenceList) # Self test if __name__ == "__main__": # sentences sents = sentences("First. Second, stil
l? Third and Final! Well, not really") assert(len(sents) == 4)
ymero/PyCrawler
test/test_handler.py
Python
mit
996
0.002008
__author__ = 'mengpeng' import os from unittest import TestCase from pycrawler.scraper import DefaultScraper from pycrawler.handler import Handler from pycrawler.utils.tools import gethash from test_scraper import SpiderTest class TestTempHandler(TestCase): def test_setargs(self): h = Handler.get('TempHan...
se('conent', 'testurl1') self.assertTrue(os.path.exists(h._tmpfilename('testurl1'))) def test__tmpfilename(self): h = Handler.get('T
empHandler')(SpiderTest('testspider')) self.assertEqual('./tmp/testspider/' + str(gethash('sample')) + '.html', h._tmpfilename('sample')) self.assertTrue(os.path.exists('./tmp/'))
pombredanne/sortinghat
sortinghat/matching/__init__.py
Python
gpl-3.0
1,244
0.002414
# -*- coding: utf-8 -*- # # Copyright (C) 2014-2015 Biter
gia # # 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. # # This program is distributed in the hope that it will be useful...
See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # # Authors: # Santiago Dueñas <sduenas@bitergia.co...
michaelkirk/QGIS
python/user.py
Python
gpl-2.0
2,327
0.005157
import os import
sys import glob import traceback from PyQt4.QtCore import QCoreApplicati
on from qgis.core import QgsApplication, QgsMessageLog def load_user_expressions(path): """ Load all user expressions from the given paths """ #Loop all py files and import them modules = glob.glob(path + "/*.py") names = [os.path.basename(f)[:-3] for f in modules] for name in names: ...
Netuitive/netuitive-diamond
src/collectors/elasticsearch/elasticsearch.py
Python
mit
18,479
0.000595
# coding=utf-8 """ Collect the elasticsearch stats for the local node. Supports multiple instances. When using the 'instances' parameter the instance alias will be appended to the 'path' parameter. #### Dependencies * urlib2 """ import urllib2 import ssl import re from diamond.collector import str_to_bool try: ...
return self._set_or_sum_metric(metrics, metric_path, current_item) def _set_or_sum_metric(self, metrics, metric_path, value): """If we already have a datapoint for this metric, lets add the value. This is used when the logstash mode is enabled.""" if metric_path in metrics...
= self._get(scheme, host, port, '_cluster/health') if not result: return
v-iam/azure-sdk-for-python
azure-servicefabric/azure/servicefabric/models/stateful_service_info.py
Python
mit
2,711
0.001107
# 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 may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from .service_info import ServiceInfo class StatefulServiceInfo(S...
pe id: str :param name: Full hierarchical name of the service in URI format starting with `fabric:`. :type name: str :param type_name: The name of the service type as specified in the service manifest. :type type_name: str :param manifest_version: The version of the service manifest. :...
mathstuf/tangelo
tangelo/tangelo/__init__.py
Python
apache-2.0
9,092
0.00121
import cherrypy import copy import functools import inspect import os.path import sys from types import StringTypes import tangelo.util def content_type(t=None): r = cherrypy.response.headers['Content-type'] if t is not None: cherrypy.response.headers['Content-type'] = t return r def header(h...
= typefuncs return typed_func return wrap def return_type(retty
pe): """ Decorate a function to automatically convert its return type to a string using a custom func
aarticianpc/greenpointtrees
src/paypal/standard/pdt/south_migrations/0004_auto__chg_field_paypalpdt_ipaddress.py
Python
mit
15,085
0.007955
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Changing field 'PayPalPDT.ipaddress' db.alter_column('paypal_pdt', 'ip...
': 'PayPalPDT', 'db_table': "'paypal_pdt'"}, 'address_city': ('django.db.models.fields.CharField', [], {'max_length': '40', 'blank': 'True'}), 'address_country': ('django.db.models.fields.CharField', [], {'max_length': '64', 'blank': 'True'}), 'address_country_code': ('django.db.mode...
.fields.CharField', [], {'max_length': '64', 'blank': 'True'}), 'address_name': ('django.db.models.fields.CharField', [], {'max_length': '128', 'blank': 'True'}), 'address_state': ('django.db.models.fields.CharField', [], {'max_length': '40', 'blank': 'True'}), 'address_status': ('dj...
varlib1/servermall
supervisord/check.py
Python
bsd-3-clause
6,952
0.000863
# (C) Datadog, Inc. 2010-2016 # All rights reserved # Licensed under Simplified BSD License (see LICENSE) # stdlib from collections import defaultdict import itertools import re import socket import time import xmlrpclib # 3p import supervisor.xmlrpc # project from checks import AgentCheck DEFAULT_HOST = 'localhost...
le: %(stderr_logfile)s Stdout log file: %(stdout_logfile)s Log file: %(logfile)s State: %(statename)s Start time: %(start_str)s Stop time: %
(stop_str)s Exit Status: %(exitstatus)s""" % proc
Sorsly/subtle
google-cloud-sdk/lib/surface/compute/url_maps/list_cdn_cache_invalidations.py
Python
mit
3,298
0.004548
# Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
tp=self.http, batch_url=self.batch_url, errors=new_errors)) errors.extend(new_errors) if new_errors: utils.RaiseToolException( errors, error_message='Could not fetch resource:') urlmap_id = objects[0].id filter_expr = ('(operationType
eq invalidateCache) (targetId eq ' '{urlmap_id})').format(urlmap_id=urlmap_id) max_results = args.limit or constants.MAX_RESULTS_PER_PAGE project = self.project requests = [ (self.global_service, 'AggregatedList', self.global_service.GetRequestType('AggregatedList')( ...
random-toto/funcMatrix
fMatrices.py
Python
gpl-3.0
11,526
0.007314
#!/usr/bin/python3 #-*- coding: utf-8 -*- def absMat(matrice): '''Renvoie la matrice avec la valeur absolue de tous ses coefficients. Renvoie False si échec. - matrice - complexe ''' if type(matrice) is not list: raise Exception("absMat : Pas une matrice.") #~ return False if no...
eturn M def zeros(entier = 1): ''' ''' try: entier = int(entier) except: raise Exception("zeros : Pas un réel") L = [0 for i in range(entier)] M = [] for i in range(entier): M.append(L) return M def idMat(entier = 1): ''' ''' try: entier = ...
Pas un réel") e = 0 M = [] for i in range(entier): L = [1 if i == e else 0 for i in range(entier)] M.append(L) e +=1 return M print(idMat(5)) def det2Mat(matrice): '''Renvoie le déterminant d'une matrice 2*2. False en cas d'échec - matrice - complexe - 2*2 ...
dutradda/myreco
setup.py
Python
mit
3,551
0.001971
# Copyright 2016 Diogo Dutra # 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, sof...
seller'\ ' swagger openapi falconframework falcon framework', install_requires=install_requires, tests_require=tests_require, setup_requires=setup_requires, classifiers=[ 'License :: OSI Approv
ed :: MIT License', 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Natural Language :: English', 'Programming Language :: Python :: 3.5', 'Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware', 'Topic :: Software Development :: Libraries :: Python Mo...
abuchanan/go_data
go_data/__init__.py
Python
mit
2,074
0.001446
from __future__ import absolute_import from collections import defaultdict import rdflib from go_data import goa def load_gene_terms(goa_path, go_owl_path): """ Load GO information related to a certain gene annotation. A GO annotation file describes the GO terms related to each gene in a specific ...
about the associated GO term. A GO OWL file describes a GO ontology. Given a path to a GO annotation file, and a path to a GO ontology file, th
is function loads the records from the annotation file, and the GO term description from the ontology file. Note, currently this only loads the term description from the ontology. GO ontologies are complex, and this function is only loading a very minimum amount of data. """ genes_terms = defa...
ActiveState/code
recipes/Python/141934_Merging_sorted_sequences/recipe-141934.py
Python
mit
1,380
0.033333
def xmerge(*ln): """ Iterator version of merge. Assuming l1, l2, l3...ln sorted sequences, return an iterator that yield all the items of l1, l2, l3...ln in ascending order. Input values doesn't need to be lists: any iterable sequence can
be used. """ pqueue = [] for i in map(iter, ln): try: pqueue.append((i.next(), i.next)) except StopIteration: pass pqueue.sort() pqueue.reverse() X = max(0, len(pqueue) - 1) while X: d,f =
pqueue.pop() yield d try: # Insort in reverse order to avoid pop(0) lo, hi, d = 0, X, f() while lo < hi: mid = (lo+hi)//2 if d > pqueue[mid][0]: hi = mid else: lo = mid+1 pqueue.insert(lo, (d,f)) ...
dtroyer/osc-lib
osc_lib/tests/api/test_utils.py
Python
apache-2.0
3,383
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 # distrib...
props', ) self.assertEqual(self.input_list, output) output = api_utils.simple_filter( copy.deepcopy(self.input_list), attr='status', property_field='props', ) self.assertEqual(self.input_list, output) def test_simple_f
ilter_prop_attr_value(self): output = api_utils.simple_filter( copy.deepcopy(self.input_list), attr='b', value=2, property_field='props', ) self.assertEqual( [api_fakes.RESP_ITEM_1, api_fakes.RESP_ITEM_2], output, ) ...
BirkbeckCTP/janeway
src/utils/management/commands/run_upgrade.py
Python
agpl-3.0
1,613
0.00124
import os from importlib import import_module from django.core.management.base import BaseCommand from django.utils import translation from django.conf import settings def get_modules(): path = os.path.join(settings.BASE_DIR, 'utils', 'upgrade') root, dirs, files = next(os.walk(path)) return files clas...
ts to Django's management command-line parser. :param parser: the parser to which the required arguments will be added :return: None """ parser.add_argument('--path', required=False) def handle(self, *args, **options): if not options.ge
t('path'): print('No upgrade selected. Available upgrade paths: ') for file in get_modules(): module_name = file.split('.')[0] print('- {module_name}'.format(module_name=module_name)) print('To run an upgrade use the following: `python3 manage.py r...
andyraib/data-storage
python_scripts/env/lib/python3.6/site-packages/pandas/stats/tests/test_fama_macbeth.py
Python
apache-2.0
2,484
0.001208
# flake8: noqa from pandas import DataFrame, Panel from pandas.stats.api import fama_macbeth from .common import assert_almost_equal, BaseTest from pandas.compat import range from pandas import compat import pandas.util.testing as tm import numpy as np class TestFamaMacBeth(BaseTest): def testFamaMacBethRollin...
eta=2) def checkFamaMacBethExtended(self, window_type, x, y, **kwds): window = 25 with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): result = fama_macbeth(y=y, x=x, window_type=window_type, window=window, **kwds) self._chec...
len(index) for i in range(time - window + 1): if window_type == 'rolling': start = index[i] else: start = index[0] end = index[i + window - 1] x2 = {} for k, v in x.iteritems(): x2[k] = v.truncate(sta...
ygenc/onlineLDA
onlineldavb_new/build/scipy/scipy/special/basic.py
Python
gpl-3.0
27,910
0.016267
# # Author: Travis Oliphant, 2002 # from numpy import pi, asarray, floor, isscalar, iscomplex, real, imag, sqrt, \ where, mgrid, cos, sin, exp, place, seterr, issubdtype, extract, \ complexfloating, less, vectorize, inexact, nan, zeros, sometrue from _cephes import ellipkm1, mathieu_a, mathieu_b, iv, ...
J(v,z), Y(v,z), H1(v,z), H2(v,z), phase = -1 # L(v,z) = I(v,z) or exp(v*pi*i)K(v,z), phase = 1 # For K, you can pull out the exp((v-k)*pi*i
) into the caller p = 1.0 s = L(v-n, z) for i in xrange(1, n+1): p = phase * (p * (n-i+1)) / i # = choose(k, i) s += p*L(v-n + i*2, z) return s / (2.**n) def jvp(v,z,n=1): """Return the nth derivative of Jv(z) with respect to z. """ if not isinstance(n,types.IntType) or (n...