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
Code4SA/mma-dexter
dexter/analysis/base.py
Python
apache-2.0
3,167
0.001895
from math import sqrt from datetime import datetime from dexter.models import db, Document, Person from sqlalchemy.sql import func from sqlalchemy.orm import joinedload class BaseAnalyser(object): """ Base for analyser objects that handles a collection of documents to analyse, based on either document i...
self.start_date = row[0].date() self.end_date = row[1].date() else: self.start_date = self.end_date = datetime.utcnow() self.days = max((self.end_date - self.start_date).days, 1) def _fetch_doc_ids(self): if self.doc_
ids is None: rows = db.session.query(Document.id)\ .filter(Document.published_at >= self.start_date.strftime('%Y-%m-%d 00:00:00'))\ .filter(Document.published_at <= self.end_date.strftime('%Y-%m-%d 23:59:59'))\ .all() self.doc_ids = [r[0] for r in ...
pepitogithub/PythonScripts
Crucigrammer.py
Python
gpl-2.0
16,271
0.022187
import Aplicacion import random import os import time from Generales import Generales from Letras import Letras from Menu import * from Variable import * from validador import * #------------------------------------------------ #--------------- TODO --------------------------- #------------------------------...
archivo = open(self.vars["filesPath"].valor + "\\" +self.grillaCrucigrama,"w") for x in range(0, len(self.grilla)): for y in range(0, len(self.grilla[0])): archivo.write(self.grilla[x][y]) archivo.write("\n")
archivo.close() def escribirPalabra(self,palabra,x,y,dir): i = 0 for letra in palabra: self.grilla[x + (dir[0]*i)][y + (dir[1]*i)] = letra i+=1 def iterarPalabras(self): self.resultado = [] startTime = time.time(...
wright-group/WrightData
2011-11 Yurs/workup.py
Python
cc0-1.0
4,760
0.004412
''' First Created 2016/05/05 by Blaise Thompson Last Edited 2016/08/08 by Blaise Thompson Contributors: Blaise Thompson ''' ### import #################################################################### import os import sys import importlib import collections import WrightTools as wt ### define ##############...
ict() ### download ################################################################## bypass_download = True if __name__ == '__main__' and not bypass_download: shared_module.download(key, directory) ### absorbance ################################################################ # TODO: ### 2D frequency p...
################################# raw_pickle_path = os.path.join(directory, 'on diagonal 2D delay.p') processed_pickle_path = raw_pickle_path def workup(): folder = os.path.join(directory, 'on diagonal 2D delay') files = wt.kit.glob_handler('', folder=folder) data = wt.data.from_KENT(files, name='PbSe') ...
johnstonskj/guernsey
guernsey/entities.py
Python
bsd-3-clause
4,713
0.00191
# # Guernsey REST client package, based on the Java Jersey client. # Copyright (c) 2011 Simon Johnston (simon@johnstonshome.org) # See LICENSE.txt included in this distribution or more details. # import logging try: import json except: json = None from xml.etree.ElementTree import fromstring, _ElementInterfac...
return True return False def read(self, raw_entity, content_type): if raw_entity is None: return None logger.debug('Parsing input as XML') return fromstring(raw_entity) class XmlWriter(EntityWriter): """ Write Python objects into ``application/xml``. """ d...
with('/xml') or content_type.endswith('+xml'): if isinstance(object, _ElementInterface) or isinstance(object, ElementTree): return True return False def write(self, object, content_type, to_file): if isinstance(object, _ElementInterface): tree = ElementTree(o...
damianmoore/photo-manager
photonix/photos/utils/organise.py
Python
agpl-3.0
6,846
0.001315
import os import shutil from hashlib import md5 from io import StringIO from PIL im
port Image
from photonix.photos.models import LibraryPath from photonix.photos.utils.db import record_photo from photonix.photos.utils.fs import (determine_destination, find_new_file_name, mkdir_p) from photonix.photos.utils.metadata import get_datetime SYNOLOGY_THUMBNAILS_DIR_NAME = '/@eaD...
mfortner/MyPythonKoans
python2/koans/about_strings.py
Python
mit
5,911
0.005075
#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * class AboutStrings(Koan): def test_double_quoted_strings_are_strings(self): string = "Hello, world." self.assertEqual(True, isinstance(string, basestring)) def test_single_quoted_strings_are_also_strings(self): ...
self.assertEqual(True, (a == b)) def test_use_backslash_at_the_end_
of_a_line_to_continue_onto_the_next_line(self): string = "It was the best of times,\n\ It was the worst of times." self.assertEqual(52, len(string)) def test_triple_quoted_strings_can_span_lines(self): string = """ Howdy, world! """ self.assertEqual(15, len(string)) ...
iberben/django-press-links
press_links/models.py
Python
bsd-3-clause
2,904
0.001377
from django.db import models from django.contrib.auth.models import User from django.contrib.sites.models import Site from django.utils.translation import ugettext_lazy as _ from press_links.enums import STATUS_CHOICES, LIVE_STATUS, DRAFT_STATUS from django.utils import tim
ezone from parler.models import TranslatableModel, TranslatedFields from parler.managers import TranslatableQuerySet class EntryManager(models.Manager): def get_queryset(self): return EntryQuerySet(self.model) def live(self): """ Returns a list of all published entries. :rty...
urrent()) class EntryQuerySet(TranslatableQuerySet): pass class Entry(TranslatableModel): author = models.ForeignKey(User, verbose_name=_('author'), related_name='%(app_label)s_%(class)s_related') slug = models.SlugField(max_length=255, unique_for_date='pub_date', ...
kbaseapps/kb_STAR
test/STAR_server_test.py
Python
mit
35,670
0.002916
# -*- coding: utf-8 -*- import unittest import os # noqa: F401 import os.path import json # noqa: F401 import time import shutil from os import environ try: from ConfigParser import ConfigParser # py2 except: from configparser import ConfigParser # py3 from pprint import pprint, pformat # noqa: F401 from...
during tests) def loadPairedEndReads(self): if hasattr(self.__class__, 'pairedEndLibInfo'): return self.__class__.pairedEndLibInfo # 1) upload files to shock shared_dir = "/kb/module/work/tmp" forward_data_file = '../work/testReads/small.forward.fq' forward_file =...
ta_file, forward_file) reverse_data_file = '../work/testReads/small.reverse.fq' reverse_file = os.path.join(shared_dir, os.path.basename(reverse_data_file)) shutil.copy(reverse_data_file, reverse_file) ru = ReadsUtils(os.environ['SDK_CALLBACK_URL']) pe_reads_ref = ru.upload_read...
Megaverse/FindInDictionary
defn.py
Python
mit
1,253
0.004789
#! python3 # Author: Shuvam Shah import requests, bs4, sys def findMeaning(word): baseURL = 'http://www.dictionary.com/browse/' missSpellingBaseURL = 'http://www.dictionary.com/misspeling?term=' # Download the specific word page. res = requests.get('%s%s?s=t' % (baseURL, word)) try: re...
for i in range(len(sections)): header = sections[i].select('header span')[0].getText() meanings = sections[i].select('div.def-set div.def-content') print('%s' % header) for j in range(len(meanings)):
print('%s. %s' % (j + 1, meanings[j].getText())) print('\n') print('\n') print('That\'s all for %s' % word) word = str(' '.join(sys.argv[1:])) findMeaning(word)
xesscorp/skidl
tests/test_erc.py
Python
mit
6,637
0.002109
# -*- coding: utf-8 -*- # The MIT License (MIT) - Copyright (c) 2016-2021 Dave Vandenbout. import pytest from skidl import ( ERC, POWER, SKIDL, TEMPLATE, Net, Part, Pin, erc_assert, erc_logger, package, subcircuit, ) from .setup_teardown import setup_function, teardown_fu...
="R", dest=TEMPLATE, pins=[Pin(num=1, func=Pin.types.PULLUP), Pin(num=2, func=Pin.types.PULLDN)], ) r1 = res() r1[1] += r1[2] ERC() assert erc_logger.warning.count == 0 assert erc_logger.error.count == 1 def test_pull_2(): res = Part( tool=SKIDL, name="res"...
, dest=TEMPLATE, pins=[Pin(num=1, func=Pin.types.PULLUP), Pin(num=2, func=Pin.types.PULLUP)], ) r1 = res() r1[1] += r1[2] ERC() assert erc_logger.warning.count == 1 assert erc_logger.error.count == 0 def test_pull_3(): res = Part( tool=SKIDL, name="res", ...
tdlong/YeastRobot
UserPrograms/ASE/Mon_Wash_3_temp.py
Python
gpl-3.0
1,361
0.031594
import sys # where RobotControl.py, etc lives sys.path.append('/home/pi/Desktop/ADL/YeastRobot/PythonLibrary') from RobotControl import * ################################# ### Define Deck Layout ################################# deck="""\ DW96W DW96W DW96W BLANK BLANK BLANK BLANK DW96W DW96W DW96W BLANK BLANK B...
LANK BLANK BLANK BLANK BLANK BLANK BLANK """ # 2 3 4 5 6 # note the 1st user defined column is "2" not zero or one,
since tips are at 0 & 1 ################################## OffsetDict={0: 'UL', 1: 'UR', 2: 'LL', 3: 'LR'} # read in deck, etc DefineDeck(deck) printDeck() InitializeRobot() CurrentTipPosition = 2 # eventually row in 0,1,2,3 for row in [0,1,2]: for offset in [0,1,2,3]: # get tips CurrentTipPosition = retrieve...
polyaxon/polyaxon
core/polyaxon/utils/humanize.py
Python
apache-2.0
2,827
0.000354
#!/usr/bin/python # # Copyright 2018-2021 Polyaxon, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable ...
differences on different app server machines if delta.total_seconds() < 0: return "a few seconds ago" num_yea
rs = delta.days // 365 if num_years > 0: return "{} year{} ago".format( *((num_years, "s") if num_years > 1 else (num_years, "")) ) num_weeks = delta.days // 7 if num_weeks > 0: return "{} week{} ago".format( *((num_weeks, "s") if num_weeks > 1 else (num_week...
ET-CS/python-patterns
examples/python2/fun/rot13.py
Python
apache-2.0
85
0
#!/usr/b
in/env python # -*- coding: rot13 -*- cevag "Uryyb TvgUho!".rapbqr("rot13"
)
iw/mirage-jekyll
fabfile.py
Python
mit
6,415
0
from datetime import datetime import os import sys import time import boto.ec2 from fabric.api import cd, env, prefix, put, run, settings, sudo, task env.user = 'vagrant' env.hosts = ['127.0.0.1:2222'] key_fname = os.path.join('~', '.vagrant.d', 'insecure_private_key') env.key_filename = os.path.expanduser(key_fnam...
directory is required') with cd(build_dir): with prefix('eval `opam config env`'): run('env NET=socket FS=crunch mirage configure --unix') run('make') @task def build_xen_unikernel(build_dir=None): """Produce a Mirage unikernel capable of running on Amazon EC2. Args: ...
with cd(build_dir): with prefix('eval `opam config env`'): run('env DHCP=true FS=crunch mirage configure --xen') run('make') @task def build_mirage_ami(access_key=None, secret_key=None, region='eu-west-1', availability_...
LLNL/spack
var/spack/repos/builtin/packages/blast-legacy/package.py
Python
lgpl-2.1
1,292
0.002322
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from os import symlink from spack import * class BlastLegacy(Package): """Legacy NCBI BLAST distribution -- no long...
tp.ncbi.nlm.nih.gov/blast/executables/legacy.NOTSUPPORTED/2.2.26/ncbi.tar.gz" version('2.2.26', sha256='d8fffac25efc8ca894c707c840a4797a8a949ae6fd983d2f91c9972f788efb7d', deprecated=True) depends_on('tcsh', type='build') def install(self, spec, prefix): filter_file('/bin/csh -f', '/usr/bin/e
nv tcsh', 'make/ln-if-absent', string=True) symlink(self.stage.source_path, '../ncbi') tcsh = which('tcsh') with working_dir('..'): tcsh('./ncbi/make/makedis.csh') # depends on local data in the source tree install_path = join_path(prefix, 'usr/l...
sander76/home-assistant
tests/components/rituals_perfume_genie/test_sensor.py
Python
apache-2.0
3,099
0.000968
"""Tests for the Rituals Perfume Genie sensor platform.""" from homeassistant.components.rituals_perfume_genie.sensor import ( BATTERY_SUFFIX, FILL_SUFFIX, PERFUME_SUFFIX, WIFI_SUFFIX, ) from homeassistant.const import ( ATTR_DEVICE_CLASS, ATTR_ICON, ATTR_UNIT_OF_MEASUREMENT, DEVICE_CLAS...
try = registry.async_get("sensor.genie_battery") assert entry assert entry.unique_id == f"{hublot}{BATTERY_SUFFIX}" state = hass.states.get("sensor.genie_wifi") assert state assert state.state == str(diffuser.wif
i_percentage) assert state.attributes.get(ATTR_DEVICE_CLASS) == DEVICE_CLASS_SIGNAL_STRENGTH assert state.attributes.get(ATTR_UNIT_OF_MEASUREMENT) == PERCENTAGE entry = registry.async_get("sensor.genie_wifi") assert entry assert entry.unique_id == f"{hublot}{WIFI_SUFFIX}" async def test_sensors_d...
desarrollogt-frm-utn/reservas
app_reservas/admin/tipoRecursoAli.py
Python
mit
487
0.002066
# coding=utf-8 fro
m django.contrib import admin from ..models import TipoRecursoAli @admin.register(TipoRecursoAli) class TipoRecursoAliAdmin(admin.ModelAdmin): """ Especificación de la representación de TipoRecursoAli en la interfaz de administración. """ list_display = ( 'nombre', 'nombre_plural', ...
list_filter = ( 'is_visible_navbar', )
timabbott/zulip
zerver/webhooks/pagerduty/tests.py
Python
apache-2.0
4,489
0.005569
from zerver.lib.test_classes import WebhookTestCase class PagerDutyHookTests(WebhookTestCase): STREAM_NAME = 'pagerduty' URL_TEMPLATE = "/api/v1/external/pagerduty?api_key={api_key}&stream={stream}" FIXTURE_DIR_NAME = 'pagerduty' def test_trigger(self) -> None: expected_message = 'Incident [3...
com/incidents/PRORDTY) acknowledged by [Laura Haley](https://webdemo.pagerduty.com/users/P553OPV):\n\n
``` quote\nMy new incident\n```' self.send_and_test_stream_message('acknowledge_v2', 'Incident 33', expected_message) def test_incident_assigned_v2(self) -> None: expected_message = 'Incident [33](https://webdemo.pagerduty.com/incidents/PRORDTY) assigned to [Wiley Jacobson](https://webdemo.pagerdut...
HaliteChallenge/Halite-II
apiserver/apiserver/model.py
Python
mit
10,268
0.001461
import enum import google.cloud.storage as gcloud_storage import sqlalchemy from . import config class CompileStatus(enum.Enum): """The compilation status of a bot.""" UPLOADED = "Uploaded" IN_PROGRESS = "InProgress" SUCCESSFUL = "Successful" FAILED = "Failed" DISABLED = "Disabled" class C...
unt(sqlalchemy.distinct(bots.c.user_id)) ]).select_from(bots).where(bot
s.c.games_played > 0) def hackathon_total_ranked_users_query(hackathon_id): """Build a query counting all users in a hackathon.""" return sqlalchemy.sql.select([ _func.count(sqlalchemy.distinct(bots.c.user_id)) ]).select_from( bots.join( hackathon_participants, (bot...
jstaffans/django-cljs-loader
examples/simple/app/settings-prod.py
Python
mit
100
0
fr
om .settings import * CLJS_LOADER['FIGWHEEL'] = False CLJS_LOADER['CLJS_BUILD']
= Keyword('min')
dhowland/EasyAVR
keymapper/easykeymap/boards/sigma.py
Python
gpl-2.0
9,214
0.017473
# Easy AVR USB Keyboard Firmware Keymapper # Copyright (C) 2013-2016 David Howland # # 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 la...
111 ), # REF_PORTD ( 0b00000000 , 0b00000000 ), # REF_PORTE ( 0b11110011 , 0b00000000 ) # REF_PORTF ] matrix_strobe = [ # REF_PORTB REF_PORTC REF_PORTD REF_PORTE
REF_PORTF ( 0b10000000 , 0b00000000 , 0b00000000 , 0b00000000, 0b00000000 ), ( 0b10000000 , 0b00000000 , 0b00000001 , 0b00000000, 0b00000000 ), ( 0b10000000 , 0b00000000 , 0b00000010 , 0b00000000, 0b00000000 ), ( 0b10000000 , 0b00000000 , 0b00000011 , 0b00000000, 0b00000000 ), ( 0b10000000 , 0b00000...
DStauffman/dstauffman
dstauffman/matlab.py
Python
lgpl-3.0
4,465
0.002912
r""" Functions that make it easier to deal with Matlab data. Notes ----- #. Written by David C. Stauffer in December 2018. """ #%% Imports from __future__ import annotations import doctest from pathlib import Path from typing import Any, Dict, List, Optional, Set, Tuple, Union import unittest from dstauffman.consta...
>>> print(out['row_nums'][1]) 2.2 """ def _load( file: h5py.Group, varlist: Optional[Union[List[str], Set[str], Tuple[str]]], squeeze: bool, enums: Optional[Dict[str, Any]], ) -> Dict[str, Any]: r"""Wrapped subfunction so it can be called recursively.""" ...
s that are not in the given varlist if varlist is not None and key not in varlist: continue # if no varlist (thus loading every key), still skip those that start with # if varlist is None and key in {'#refs#', '#subsystem#'}: continue # ali...
lmazuel/azure-sdk-for-python
azure-mgmt-network/azure/mgmt/network/v2017_11_01/models/application_gateway_redirect_configuration_py3.py
Python
mit
3,957
0.005054
# 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 ...
mt.network.v2017_11_01.models.SubResource] :param path_rules: Path rules specifying redirect configuratio
n. :type path_rules: list[~azure.mgmt.network.v2017_11_01.models.SubResource] :param name: Name of the resource that is unique within a resource group. This name can be used to access the resource. :type name: str :param etag: A unique read-only string that changes whenever the resource is upd...
timmygee/investorservitude
investorservitude/core/views.py
Python
mit
710
0.001408
from django.contrib.auth.models import User from rest_framework im
port viewsets, response from .serializers import HoldingSerializer, UserSerializer from .models import Holding class HoldingViewSet(viewsets.ModelViewSet): queryset = Holding.objects.order_by('created') serializer_class = HoldingSerializer pagination_class = None
class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer def retrieve(self, request, pk=None): if pk == 'i': serialized = UserSerializer(request.user, context={'request': request}) return response.Response(serialized.data) ...
bruderstein/PythonScript
PythonLib/full/http/__init__.py
Python
gpl-2.0
6,733
0.006981
from enum import IntEnum __all__ = ['HTTPStatus'] class HTTPStatus(IntEnum): """HTTP status codes and reason phrases Status codes from the following RFCs are all observed: * RFC 7231: Hypertext Transfer Protocol (HTTP/1.1), obsoletes 2616 * RFC 6585: Additional HTTP Status Codes * R...
lable in preferred format') PROXY_AUTHENTICATION_REQUIRED = (407, 'Proxy Authentication Required', 'You must authenticate with this proxy before proceeding') REQUEST_TIMEOUT = (408, 'Request Timeout', 'Request timed out; try again later') CONFLICT = 409
, 'Conflict', 'Request conflict' GONE = (410, 'Gone', 'URI no longer exists and has been permanently removed') LENGTH_REQUIRED = (411, 'Length Required', 'Client must specify Content-Length') PRECONDITION_FAILED = (412, 'Precondition Failed', 'Precondition in headers is false') R...
anomen-s/programming-challenges
tools/wordcount/wordcount.py
Python
gpl-2.0
462
0.032468
#!/usr/bin/python3 import re from sys import argv if (len(argv) < 2): print("Missing argument") exit(1); counts = {} with open(argv[1]) as f: for line in f: for word in re.split(r'\W+', line): if word != '': word = word.lower() c = counts.get(word, 0); c += 1
counts[word] = c sortedcount = list(counts.items()); sortedcount.sort(key=lambda x:-x[1
]) for (w,c) in sortedcount: print('%i\t%s' % (c, w))
adw0rd/lettuce-py3
tests/unit/test_feature_parser.py
Python
gpl-3.0
27,374
0.001096
# -*- coding: utf-8 -*- # <Lettuce - Behaviour Driven Development for python> # Copyright (C) <2010-2012> Gabriel Falcão <gabriel@nacaolivre.org> # # 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 Foundatio...
'Mary Doe' rents 'Matrix Revolutions' Then she nee
ds to pay 6 bucks Scenario: Renting two movies allows client to take one more without charge Given I have the following movies in my database | Name | Rating | New | Available | | A night at the museum 2 | 3 stars | yes | 9 | | Matrix Revolutions...
okin/nikola
setup.py
Python
mit
5,175
0.00058
#!/usr/bin/env python import os import sys import shutil from setuptools import setup, find_packages from setuptools.command.install import install with open('requirements.txt', 'r') as fh: dependencies = [l.strip().split("#")[0] for l in fh] extras = {} with open('requirements-extras.txt', 'r') as fh: ext...
e = os.path.join(self.install_lib, 'nikola') try: shutil.rmtree(tree, ignore_errors=True) except Exception: pass class nikola_install(install): def run(self): expands_symlinks_for_windows()
remove_old_files(self) install.run(self) setup(name='Nikola', version='8.0.3', description='A modular, fast, simple, static website and blog generator', long_description=long_description, author='Roberto Alsina and others', author_email='ralsina@netmanagers.com.ar', url='h...
point97/hapifis
server/apps/survey/migrations/0020_auto__add_field_question_order.py
Python
gpl-3.0
4,857
0.007206
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Question.order' db.add_column(u'survey_question', 'order', self.gf('dj...
ax_length': '254'}), 'responses': ('django.db.models.fields
.related.ManyToManyField', [], {'related_name': "'responses'", 'symmetrical': 'False', 'to': u"orm['survey.Response']"}), 'survey': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['survey.Survey']"}), 'ts': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datet...
lrocheWB/navitia
source/jormungandr/jormungandr/scenarios/tests/qualifier_tests.py
Python
agpl-3.0
13,540
0.001551
# Copyright (c) 2001-2014, Canal TP and/or its affiliates. All rights reserved. # # This file is part of Navitia, # the software to build cool stuff with public transport. # # Hope you'll enjoy and contribute to this project, # powered by Canal TP (www.canaltp.fr). # Help us simplify mobility and open public tr...
= response_pb2.Bike foot_journey.sections[2].street_network.mode = response_pb2.Bss assert(not qualifier.has_car(foot_journey)) foot_journey.sections.add() foot_journey.sections[3].type = resp
onse_pb2.STREET_NETWORK foot_journey.sections[3].street_network.mode = response_pb2.Car assert(qualifier.has_car(foot_journey)) def standard_choice_test(): journeys = [] #the first is the worst one journey_worst = response_pb2.Journey() journey_worst.arrival_date_time = str_to_time_stamp("2013...
tonymke/testrattingcapitals.com
server/testrattingcapitals/schema.py
Python
agpl-3.0
5,558
0.001799
""" Copyright (c) 2016-2017 Tony Lechner and contributors testrattingcapitals.com is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later ve...
www.gnu.org/licenses/>. """ import datetime import json from sqlalchemy import Column, DateTime, Float, Index, Integer, String, \ Text from sqlalchemy.ext.declarative import declarative_base, DeclarativeMeta MARSHAL_IGNORE_FIELDS = { 'to_json', 'from_json', 'alliance_name', 'ship_name', 'character_name', ...
ONEncoder(json.JSONEncoder): """ JSONEncoder for SQLalchemy declarative objects """ def default(self, obj): if isinstance(obj, datetime.datetime): return obj.isoformat() """ This bit shamelessly jacked from a Stack Overflow response by user Sasha B. Since there'...
rajmani1995/TicTacToe-Automated
tictactoe.py
Python
mit
3,660
0.025956
'''Automation of Game TicTacToe on android device Moto G3 for Game on Google play store (https://play.google.com/store/apps/details?id=com.pinkpointer.tictactoe) Environments Opencv for python adb tool for debugging Author: Rajmani Arya ''' class Game: def __init__(self): self.board = [ 0 for i in ra...
(294, 992), (533, 992)] import cv2 from os import system from random import randint from time import sleep
## Computer is 'X' <-> 2 and mobile is 'O' <-> 1 game = Game() pos = randint(0,8) system("adb shell screencap -p /sdcard/tictac.png") system("adb pull /sdcard/tictac.png") img = cv2.imread('tictac.png') for i,v in enumerate(positions): if game.get_cell_value(i) == 0 and img[v[1]][v[0]][2] == 248: game.m...
dask/dask
dask/array/tests/test_cupy_gufunc.py
Python
bsd-3-clause
532
0.007519
import
numpy as np import pytest pytestmark = pytest.mark.gpu import dask.array as da from dask.array.gufunc import apply_gufunc from dask.array.utils import assert_eq cupy = pytest.importorskip("cupy") def test_apply_gufunc_axis(): def mydiff(x): return np.diff(x) a = cupy.random.randn(3, 6, 4) da_ ...
rray=False) m = np.diff(a, axis=1) dm = apply_gufunc( mydiff, "(i)->(i)", da_, axis=1, output_sizes={"i": 5}, allow_rechunk=True ) assert_eq(m, dm)
amwelch/a10sdk-python
a10sdk/core/A10_file/file_wsdl.py
Python
apache-2.0
1,901
0.007891
from a10sdk.common.A10BaseClass import A10BaseClass class Wsdl(A10BaseClass): """ :param action: {"optional": true, "enum": ["create", "import", "export", "copy", "rename", "check", "replace", "delete"], "type": "string", "description": "'create': create; 'import': import; 'export': export; 'copy': copy; ...
ximum": 2147483647, "minimum": 0, "optional": true} :param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py` Class Description:: WSDL file information and management commands. Class wsd
l supports CRUD Operations and inherits from `common/A10BaseClass`. This class is the `"PARENT"` class for this module.` URL for this object:: `https://<Hostname|Ip address>//axapi/v3/file/wsdl`. """ def __init__(self, **kwargs): self.ERROR_MSG = "" self.required=[...
fake-name/ReadableWebProxy
WebMirror/management/rss_parser_funcs/feed_parse_extractTranslatinotakuCf.py
Python
bsd-3-clause
2,627
0.023619
def extractTranslatinotakuCf(item): ''' Parser for 'translatinotaku.cf' ''' vol, chp, frag, postf
ix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None tagmap = [ ('Hokage Ryos Path',
'Hokage: Ryo\'s Path', 'translated'), ('The Strongest Hokage', 'The Strongest Hokage', 'translated'), ('God of Soul System', 'God Of Soul System', 'translated'), ('Harry Potter and the Secret Treas...
libranwizard/projecteuler
euler3.py
Python
gpl-3.0
344
0.002907
import time start = time.time() def prime_factors(n): l = [] i = 2 while n != 1: if n % i == 0: l.append(i) while n % i == 0: n = n // i i += 1 return l print(prime_factors(60085
1475143)[-1]) elapsed =
time.time() - start print("time elapsed:", elapsed, "seconds")
materialsproject/pymatgen
dev_scripts/chemenv/explicit_permutations_plane_algorithm.py
Python
mit
5,857
0.003244
# Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. """ Development script of the ChemEnv utility to get the explicit permutations for coordination environments identified with the separation plane algorithms (typically with coordination numbers >= 6) """ import itertools impo...
_csm_separation_plane( coordination_geometry=cg, sepplane=sepplanealgo,
local_plane=local_plane, plane_separations=[], dist_tolerances=[0.05, 0.1, 0.2, 0.3], testing=True, points_perfect=points_perfect, ) print(cgsm) if cgsm[0] is None: print("IS NONE !") input() continue ...
JordanReiter/sorl-thumbnail
sorl/thumbnail/engines/convert_engine.py
Python
bsd-3-clause
6,419
0.000935
from __future__ import unicode_literals, with_statement import re import os import subprocess from collections import OrderedDict from django.utils.encoding import smart_str from django.core.files.temp import NamedTemporaryFile from sorl.thumbnail.base import EXTENSIONS from sorl.thumbnail.compat import b from sorl.t...
tings.THUMBNAIL_FLATTEN and not flatten == "off": args.append('-flatten') suffix = '.%s' % EXTENSIONS[options['format']] with NamedTemporaryFile(suffix=suffix, mode='rb') as
fp: args.append(fp.name) args = map(smart_str, args) p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) p.wait() out, err = p.communicate() if err: raise Exception(err) thumbnail.write(fp.read()...
sisl/CustomerSim
src/vs_simulate.py
Python
apache-2.0
8,125
0.023877
# VS SIMULATE from shared_functions import * from net_designs import * import pandas as ps import json import numpy as np import pickle import networkx as nx import scipy.stats as sct from scipy import stats as sc import random import h5py import os from copy import deepcopy from scipy import stats as sc def...
1,2,3,4] cols_A = [5,6,7] cols_Y = 8 cols_Z = 9 # LOAD AVG PRICES PER CATEGORY print('Loading avg. prices') prices = load('../kaggle_valued_shoppers/vs_cat_avg_prices.p') # PREPARE TEST DATA print('Preparing data') random.seed(RANDOM_SEED) np.random.seed(RANDOM_SEED) rand_ind = np.random.permutation(da
ta.shape[0]) test_customers = rand_ind[216000:217000] # 1000 customers from test set test_data = data[test_customers].T del data # EXTRACT ARRAYS WITH ORIGINAL DATA orig_S = test_data[cols_S].T orig_A = test_data[cols_A].T orig_Q = test_data[cols_Y].T orig_P = test_data[cols_Z].T * orig_Q del test_data orig_S = np...
adv-tsk/Course-Se-Python
php4dvd/pages/movie.py
Python
apache-2.0
5,067
0.001925
# -*- coding: utf-8 -*- import allure from selenium.webdriver.common.by import By from .base import BasePage from .elements import SimpleInput, SimpleText from .blocks.nav import NavBlock class BrowseMoviePageLocators(ob
ject): """Локаторы страницы просмотра информации о фильме""" TITLE_LOCATOR = (By.CSS_SELECTOR, '#movie h2') COUNTRY_LOCATOR = (By.NAME, 'country') DIRECTOR_LOCATOR = (By.NAME, 'director') WRITER_LOCATOR = (By.NAME, 'writer') PRODUCER_LOCATOR = (By.NAME, 'prod
ucer') EDIT_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Edit"]') REMOVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Remove"]') class BrowseMoviePage(BasePage): """Страница просмотра информации о фильме""" def __init__(self, driver): super(BrowseMoviePage, self).__init__(driver) ...
ging/horizon
horizon/test/tests/templatetags.py
Python
apache-2.0
5,342
0
# Copyright 2012 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Copyright 2012 Nebula, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except
in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable la
w or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import re from django.co...
sajuptpm/neutron-ipam
neutron/plugins/cisco/nexus/cisco_nexus_snippets.py
Python
apache-2.0
4,813
0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright 2011 Cisco Systems, 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...
NT_VLAN_TRAILER = """ </vlan> </allowed> </trunk> </switchport> </__XML__MODE_if-ethernet-switch> </%s> </interface> """ CMD_INT_VLAN_SNIPPET = (CMD_INT_VLAN_HEADER + CMD_VLAN_ID + ...
_SNIPPET = (CMD_INT_VLAN_HEADER + CMD_VLAN_ADD_ID + CMD_INT_VLAN_TRAILER) CMD_NO_VLAN_INT_SNIPPET = """ <interface> <%s> <interface>%s</interface> <__XML__MODE_if-ethernet-switch> <switchport></swi...
RalfBarkow/Zettelkasten
venv/lib/python3.9/site-packages/setuptools/command/egg_info.py
Python
gpl-3.0
25,495
0
"""setuptools.command.egg_info Create a distribution's .egg-info directory and contents""" from distutils.filelist import FileList as _FileList from distutils.errors import DistutilsInternalError from distutils.util import convert_path from distutils import log import distutils.errors import distutils.filelist import...
version += time.strftime("-%Y%m%d") return version vtags = property(tags) class egg_info(InfoCommon, Command): description = "create a distribution's .egg-info directory" user_options = [ ('egg-base=', 'e', "directory containing .egg-info directories" ...
number"), ('no-date', 'D', "Don't include date stamp [default]"), ] boolean_options = ['tag-date'] negative_opt = { 'no-date': 'tag-date', } def initialize_options(self): self.egg_base = None self.egg_name = None self.egg_info = None self.egg_versio...
nthuion/nthuion-backend
nthuion/utils.py
Python
bsd-2-clause
437
0
from contextlib import contextmanager from pyramid.httpexceptions import HTTPBadRequest, HTTPNotFound from sqlalchemy.orm.exc imp
ort NoResultFound @contextmanager def keyerror_is_bad_request(): try: yield except KeyError as exc: raise HTTPBadRequest('missing required key {}'.format(exc)) @contextmanage
r def noresultfound_is_404(): try: yield except NoResultFound: raise HTTPNotFound
dencold/blt
blt/test/test_aws.py
Python
mit
2,431
0.010695
import pytest from mock import patch, call, Mock, MagicMock from blt.tools import aws @pytest.fixture def cmds(): config = { "aws": { "AWS_ACCESS_KEY_ID": "JLKSNLBNLSKDFJWOEI" , "AWS_SECRET_ACCESS_KEY": "JFvnwoaifeIOJFnegoiwfaqEF" , "AWS_BUCKET_NAME": "matter-developers" ...
aws.AmazonCommands(config) @pytest.fixture def source_hashes(): return { 'images/same_hash.jpg': {'hash': '7f7b682a6da0ffb6f40811ffba10ade3'},
'images/diff_hash.jpg': {'hash': 'bdba7bf1340ceddb3e3c3aa3cd7d0ad6'}, 'images/dne.jpg': {'hash': 'b68a0e1dd8afc98bc883c3cf11b73526'} } @pytest.fixture def target_hashes(): return { 'images/same_hash.jpg': {'hash': '7f7b682a6da0ffb6f40811ffba10ade3'}, 'images/diff_hash.jpg': {'hash':...
emprovements/binwalk
src/binwalk/plugins/compressd.py
Python
mit
1,413
0.031847
#import binwalk.core.C #import binwalk.core.plugin #from binwalk.core.common import * #class CompressdPlugin(binwalk.core.plugin.Plugin): # ''' # Searches for and validates compress'd data. # ''' #MODULES = [] #READ_SIZE = 64 #COMPRESS42 = "compress42" #COMPRESS42_FUNCTIONS = [ # bin...
t(self): #self.comp = binwalk.core.C.Library(self.COMPRESS42, self.COMPRESS42_FUNCTIONS) # This plugin is currently disabled due to the need to move away from supporting C # libraries and i
nto a pure Python project, for cross-platform support and ease of # installation / package maintenance. A Python implementation will likely need to # be custom developed in the future, but for now, since this compression format is # not very common, especially in firmware, simply disable it. ...
hazelnusse/sympy-old
sympy/core/add.py
Python
bsd-3-clause
15,623
0.003072
from basic import Basic, S, C from operations import AssocOp from cache import cacheit from symbol import Symbol class Add(AssocOp): __slots__ = [] is_Add = True @classmethod def flatten(cls, seq): """ Takes the sequence "seq" of nested Adds and returns a flatten list. Retur...
t.is_irrational if a: return True if a is None: return return False def _eval_is_positive(self): c = self.args[0] r = Add(*self.args[1:]) if c.is_positive and r.is_positive: return True if c.is_unbounded: if r.is_unbounded: ...
return c.is_positive elif r.is_unbounded: return r.is_positive if c.is_nonnegative and r.is_positive: return True if r.is_nonnegative and c.is_positive: return True if c.is_nonpositive and r.is_nonpositive: return False def _...
rg3915/orcamentos
orcamentos/crm/migrations/0002_auto_20161126_0030.py
Python
mit
1,108
0.001808
# -*- coding: utf-8 -*- # Generated by Django 1.9.6 on 2016-11-26 02:30 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('crm', '0001_initial'), ] operations = [ migrations.AlterField( m...
Engª.'), ('p', 'Prof.'), ('pa', 'Profa.'), ('sr', 'Sr.'), ('sra', 'Sra.'), ('srta', 'Srta.')], max_length=4, null=True, verbose
_name='tratamento'), ), ]
BIT-SYS/gem5-spm-module
src/mem/ruby/system/DirectoryMemory.py
Python
bsd-3-clause
2,226
0.000449
# Copyright (c) 2009 Advanced Micro Devices, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: redistributions of source code must retain the above copyright # notice, this list of conditions...
RRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SE
RVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # Authors: S...
smartlinux/nsxapitest
nat/case45_nsx_static_nat_list_script.py
Python
gpl-3.0
1,488
0.008868
#!/usr/bin/python # -*- coding: utf-8 -*- # # Test script for NAT function. # Static NAT: 仅用address来映射,不用port来映射 import sys import datetime import libxml2 sys.path.append("..") import rest from nsx_basic_input import * from nsx_basic_script import isSingleIp, isIpRange from case45_nsx_static_nat_list_input import * ...
ginalPort")[0].getContent() transPort = xp.xpat
hEval("translatedPort")[0].getContent() if origPort=='any' and transPort=='any': outputStr += (rule.serialize('UTF-8', 1)+'\n') output(outputStr) def output(msg): f = file(datetime.datetime.now().strftime("../log/" + caseName + "_output_20%y%m%d%H%M%S.log"), "w") f.write(msg) f.cl...
Senbjorn/mipt_lab_2016
test_on_python/task_5.py
Python
gpl-3.0
168
0.047619
#task_5
def y1(x): return 1 + x * x def y2(x): return -2 - x * x x, y = tuple(map(float, input().split())) if y1(x) < y or y2(x)
> y: print('YES') else: print('NO')
codercold/Veil-Evasion
modules/payloads/python/shellcode_inject/base64_substitution.py
Python
gpl-3.0
14,562
0.004601
""" This payload receives the msfvenom shellcode, base64 encodes it, and stores it within the payload. At runtime, the executable decodes the shellcode and executes it in memory. module by @christruncer """ import base64 from datetime import date from datetime import timedelta from modules.common import shellcod...
e Using msfvenom Shellcode = self.shellcode.generate() # Base64 Encode Shellcode EncodedShellcode = base64.b64encode(Shellcode) # Generate Random Variable Names ShellcodeVaria
bleName = helpers.randomString() RandPtr = helpers.randomString() RandBuf = helpers.randomString() RandHt = helpers.randomString() RandT = helpers.randomString() HeapVar = helpers.randomString() PayloadCode = 'import ctypes...
paulsoh/moxie
moxie/moxie/settings/partials/static.py
Python
mit
2,938
0
# Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.9/howto/static-files/ from .application import * STATIC_URL = '/static/' MEDIA_URL = '/media/' STATIC_ROOT = os.path.join(PROJECT_BASE_DIR, 'dist', 'static') MEDIA_ROOT = os.path.join(PROJECT_BASE_DIR, 'dist', 'media') STATICFILES_STORAG...
ss/moxie.css', }, }, 'JAVASCRIPT': { 'vendor': { 'source_filenames': ( 'js/vendor/jquery-1.12.2.min.js', ), 'output_filename': 'js/vendor.js', }, 'react': {
'source_filenames': ( 'js/vendor/react.js', 'js/vendor/react-dom.js', 'js/vendor/browser.min.js', ), 'output_filename': 'js/react.js', }, 'react_myApp': { 'source_filenames': ( 'js/comment.js', ...
tajkhan/pluto-pocc
annotations/module/align/unparser.py
Python
gpl-3.0
2,012
0.006461
# # Contain unparsing procedures. # import sys #------------------------------------------- def unparseToC(vars, annot_body_code, indent, extra_indent): '''Unparse to C/C++ code''' if len(vars) == 0: return annot_body_code s = '\n' s += indent + '#pragma disjoint (' for i, v in enumerat...
v.dimensions) s += ') \n' s += indent + 'if (((' for i, v in enumerate(vars): if i > 0: s += '|' s += '(int)(' + __printAddressC(v.var_name, v.dimensions) + ')' s += ') & 0xF) == 0) {\n' for v in vars: s += indent + ext
ra_indent s += '__alignx(16,' + __printAddressC(v.var_name, v.dimensions) + ');\n' s += annot_body_code.replace('\n', '\n' + extra_indent) s += '\n' s += indent + '} else {\n' s += annot_body_code.replace('\n', '\n' + extra_indent) s += '\n' s += indent + '}\n' s += indent retur...
PayettePeople/SkinDesigner
src/SkinDesigner_System-CurtainWall.py
Python
gpl-3.0
12,231
0.014553
# SkinDesigner: A Plugin for Building Skin Design (GPL) started by Santiago Garay # This file is part of SkinDesigner. # # Copyright (c) 2017, Santiago Garay <sgaray1970@gmail.com> # SkinDesigner is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as publis...
hickness: A floating point value that indicates in scene units the cap thickness of all panel and window mullions. Default value is 0.25m (1 inch). Alternatively a list of three floating point values can be indicated to specify mullion properties at each of the th
ree mullion pieces(below/left of window, at window, above/right of window) windowThickness: A floating point value that indicates in scene units the thickness of window mullions. Overrides overal 'thickness' parameter Default value uses 'thickness' value specified. Alternatively a list of three floating...
jameshiew/dj-stripe
djstripe/migrations/0003_auto_20150128_0800.py
Python
mit
948
0.00211
# -*- coding: utf-8 -*- from __future__ import ( absolute_import, division, print_function, unicode_literals ) import django.db.models.deletion from django.conf import settings from django.db import migrations, models # Can't use the callable because the app registry i
s not ready yet. # Really trusting users here... bad idea? probably. DJSTRIPE_UNSAFE_SUBSCRIBER_MODEL = getattr(settings, "DJSTRIPE_SUBSCRIBER_MODEL", settings.AUTH_USER_MODEL) class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(DJSTRIPE_
UNSAFE_SUBSCRIBER_MODEL), ('djstripe', '0002_auto_20150122_2000'), ] operations = [ migrations.AlterField( model_name='customer', name='subscriber', field=models.OneToOneField(null=True, on_delete=django.db.models.deletion.CASCADE, to=DJSTRIPE_UNSAFE_SUBSCRIB...
cpennington/edx-platform
common/test/acceptance/pages/lms/login.py
Python
agpl-3.0
1,477
0.001354
""" Login page for the LMS. """ from bok_choy.page_object import PageObject from bok_choy.promise import EmptyPromise from common.test.acceptance.pages.lms import BASE_URL from common.test.acceptance.pages.lms.dashboard import DashboardPage class LoginPage(PageObject): """ Login page for the LMS. """ ...
s_present, "Click ready").fulfill() EmptyPromise(self.q(css='input#password').is_present, "Click ready").fulfill() self.q(css='input#email').fill(email) self.q(css='input#password').fill(password) self.wait_for_ajax() def submit(self): """ Submit registration info t...
ashboard = DashboardPage(self.browser) dashboard.wait_for_page() return dashboard
IfcOpenShell/IfcOpenShell
src/ifcopenshell-python/ifcopenshell/api/sequence/assign_process.py
Python
lgpl-3.0
2,464
0.001218
# IfcOpenShell - IFC toolkit and geometry engine # Copyright (C) 2021 Dion Moult <dion@thinkmoult.com> # # This file is part of IfcOpenShell. # # IfcOpenShell is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundat...
ments: if ( assignment.is_a("IfclRelAssignsToProcess") and assignment.RelatingProcess == self.settings["relating_process"] ): re
turn operates_on = None if self.settings["relating_process"].OperatesOn: operates_on = self.settings["relating_process"].OperatesOn[0] if operates_on: related_objects = list(operates_on.RelatedObjects) related_objects.append(self.settings["related_object"]) ...
chrismeyersfsu/ansible
lib/ansible/modules/cloud/profitbricks/profitbricks_datacenter.py
Python
gpl-3.0
7,988
0.00338
#!/usr/bin/python # 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. # # Ansible is distributed...
'1.0'} DOCUMENTATION = ''' --- module: profitbricks_datacenter short_description: Create or destroy a ProfitBricks Virtual Datacenter. description: - This is a simple module that
supports creating or removing vDCs. A vDC is required before you can create servers. This module has a dependency on profitbricks >= 1.0.0 version_added: "2.0" options: name: description: - The name of the virtual datacenter. required: true description: description: - The description of the...
eyalev/timee
docs/conf.py
Python
mit
8,353
0.005387
#!/usr/bin/env python # -*- coding: utf-8 -*- # # timee documentation build configuration file, created by # sphinx-quickstart on Tue Jul 9 22:26:36 2013. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autog...
HTML output ------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a # theme further. For a list of options available for each them...
here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as # html_title. #html_short_title = None # The name of an image file...
jerkos/cobrapy
cobra/solvers/glpk_solver_java.py
Python
lgpl-2.1
14,112
0.005244
##cobra.solvers.glpk_solver #This script provides wrappers for libglpk-java 1.0.22 and pyglpk 0.3 from warnings import warn from copy import deepcopy ###solver specific parameters from .parameters import status_dict, variable_kind_dict, \ sense_dict, parameter_mappings, parameter_defaults, \ objective_senses,...
ults = parameter_defaults['%s_%s'%(solver_name, __name)] class Problem(): """Create a more pythonesqe class to wrap the key features of the libglpk-java functions. """ def __init__(self): """the attributes g, lp, mip should be made private ...
= GLPK self._lp= GLPK.glp_create_prob() self._simplex_parameters = glp_smcp() self._mip_parameters = None self._g.glp_init_smcp(self._simplex_parameters) self.status = self.objective_value = None self._mip = False def set_name(self, name=''): self._g.glp_set_p...
tensorflow/similarity
tensorflow_similarity/api/__init__.py
Python
apache-2.0
4,454
0.001797
# Copyright 2021 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to ...
pose or further training / evaluation. The default implementation can scale up to medium deployment (1M-10M+ points) easily, provided the computers have enough memory. For very large scale deployments you will need to sublcass the compoments to match your own architetctue. See FIXME colab to see how to deploy TensorFl...
n. """ # The file is used to list the public API for document generation purpose. from tensorflow_similarity import architectures # noqa from tensorflow_similarity import evaluators # noqa from tensorflow_similarity import layers # noqa from tensorflow_similarity import losses # noqa from tensorflow_similarity imp...
lucidbard/NewsBlur
vendor/oauth2client/appengine.py
Python
mit
19,989
0.006253
# Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writ...
nstance (%s)' % (self.name, value)) return super(FlowProperty, self).validate(value) def empty(self, value): return not value class CredentialsProperty(db.Property): """App Engine datastore Property for Credentials. Utility property that allows easy storage and retrieval of ...
at the user type is. data_type = Credentials # For writing to datastore. def get_value_for_datastore(self, model_instance): logger.info("get: Got type " + str(type(model_instance))) cred = super(CredentialsProperty, self).get_value_for_datastore(model_instance) if cred is None: ...
vicalloy/dj-scaffold
dj_scaffold/conf/prj/sites/settings/production.py
Python
bsd-3-clause
33
0.030303
from
bas
e import * DEBUG = False
stinkydan/lemur
lemur/migrations/versions/4dc5ddd111b8_.py
Python
apache-2.0
960
0.0125
"""Creating a one-to-many relationship for notifications Revision ID: 4dc5ddd111b8 Revises: 4c8915e461b3 Create Date: 2015-07-24 15:02:04.3
98262 """ # revision identifiers, used by Alembic. revision = '4dc5ddd111b8' down_revision = '4c8915e461b3' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - please adjust! ### op.create_table('certificate_notification_associations', sa.Column('notif...
lable=True), sa.Column('certificate_id', sa.Integer(), nullable=True), sa.ForeignKeyConstraint(['certificate_id'], ['certificates.id'], ondelete='cascade'), sa.ForeignKeyConstraint(['notification_id'], ['notifications.id'], ondelete='cascade') ) ### end Alembic commands ### def downgrade(): ##...
uber/clusto-query
test/test_lexer.py
Python
isc
3,315
0.00181
import unittest import clusto_query.lexer from clusto_query.exceptions import StringParseError class LexerTest(unittest.TestCase): def test_consume(self): self.assertEqual(clusto_query.lexer.consume('nom', 'nomnomnom'), 'nomnom') def test_lex_string_inner_quoted_basic(self): ...
lex_string('1K and'), (1024, ' and')) self.assertEqual(clusto_query.lexer.lex_string('1.5T and'), (1649267441664.0, ' and')) def test_lex_string_invalid_size(self): self.assertEqual(clusto_query.lexer.lex_string('1.1.1.1K and'), ...
elf): self.assertEqual(clusto_query.lexer.lex('pool = production and (attr haproxy.enabled = 1)'), ['pool', '=', 'production', 'and', '(', 'attr', 'haproxy.enabled', '=', 1, ')'])
obi-two/Rebelion
data/scripts/templates/object/tangible/ship/crafted/weapon/missile/shared_wpn_seismic_missile_mk1.py
Python
mit
494
0.044534
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS
MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Tangible() result.template = "object/tangible/ship/crafted/weapon/missile/shared_wpn_seismic_missile_mk1.iff" result.attribute_template_id = 8 result.stfName("space_craft...
IONS #### #### END MODIFICATIONS #### return result
5g-empower/empower-runtime
empower/managers/alertsmanager/alertshandler.py
Python
apache-2.0
2,382
0
#!/usr/bin/env python3 # # Copyright (c) 2022 Roberto Riggio # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicabl...
nager as apimanager # pylint: disable=W0223 class AlertsHandler(apimanager.APIHandler): """Alerts handler""" URLS = [r"/api/v1/alerts/?", r"/api/v1/alerts/([a-zA-Z0-9-]*)/?"] @apimanager.validate(min_args=0, max_args=1) def get(self, *args, **kwargs): """Lists all the alerts. ...
3d9ada26 """ return self.service.alerts \ if not args else self.service.alerts[uuid.UUID(args[0])] @apimanager.validate(returncode=201, min_args=0, max_args=1) def post(self, *args, **kwargs): """Create a new alert. Args: [0], the alert id (optional) ...
euske/pdfminer
tools/latin2ascii.py
Python
mit
2,305
0.006508
#!/usr/bin/env python # # latin2ascii.py - converts latin1 characters into ascii. # import sys """ Mappings from Latin-1 characters to ASCII. This is an in-house mapping table for some Latin-1 characters (acutes, umlauts, etc.) to ASCII strings. """ LATIN2ASCII = { #0x00a0: '', #0x00a7: '', # iso-8859-1 0...
d(c),c) for c in s ) def main(argv): import getopt, fileinput def usage(): print('usage: %s [-c codec] file ...' % argv[0]) return 100 try: (opts, args) = getopt.getopt(argv[1:], 'c') except getopt.GetoptError: return usage() if not args: return usage() codec = ...
c = v for line in fileinput.input(args): line = latin2ascii(unicode(line, codec, 'ignore')) sys.stdout.write(line.encode('ascii', 'replace')) return if __name__ == '__main__': sys.exit(main(sys.argv))
SpaceVim/SpaceVim
bundle/vim-hug-neovim-rpc/pythonx/neovim_rpc_methods.py
Python
gpl-3.0
3,743
0
# vim:set et sw=4 ts=8: import vim # vim's python binding doesn't have the `call` method, wrap it here def nvim_call_function(method, args): vim.vars['_neovim_rpc_tmp_args'] = args # vim.eval('getcurpos()') return an array of string, it should be an array # of int. Use json_encode to workaround this ...
im_buf_set_lines(buffer, start, end, err, lines): if start < 0: start = len(buffer) + 1 + start if end < 0: end = len(buffer) + 1 + end buffer[start:end] = lines if nvim_call_function('bufwinnr', [buffer.number]) != -1: # vim needs' redraw to update the screen, it seems to be a ...
r_line_count(buffer): return len(buffer) def nvim_buf_line_count(buffer): return len(buffer) def nvim_get_option(name): return vim.options[name] def nvim_buf_get_option(buf, name): return buf.options[name] def nvim_set_option(name, val): vim.options[name] = val def nvim_buf_set_option(buf,...
PhillipTaylor/ReactionBot
src/plugins/reaction.py
Python
mit
3,083
0.001946
# -*- coding: utf-8 import datetime from random import choice from zope.interface import implements from core.plugins.interface import IActionHandler, IFinalize, IPeriodic from core.plugins.manager import plugin_manager SPEAK_INTERVAL = 3 * 60 # only speak every 3 minutes. make it more valuable! RELOAD_INTERVAL = 1...
it('=') if (len(parsed) > 1): match_string = ' '.join(parsed[:-1]).strip() urls = parsed[-1].strip() self.image_dictionary[match_string] = urls.split(' ')
logfile.close() self.last_reload = datetime.datetime.now() print "%d images available" % len(self.image_dictionary) def accepts_action(self, action): return action in ['privmsg', 'login', 'quit', 'exit'] def handle_action(self, protocol, action, user, message): nick = us...
harvardinformatics/jobTree
batchSystems/parasol.py
Python
mit
11,029
0.011152
#!/usr/bin/env python #Copyright (C) 2011 by Benedict Paten (benedictpaten@gmail.com) # #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 rig...
assert self.usedCpus >= 0 self.outputQueue1.task_done() #Now keep going
while True: #time.sleep(0.1) #Sleep to let parasol catch up #Apparently unnecessary line = popenParasolCommand(parasolCommand)[1][0] match = pattern.match(line) if match != None: #This is because parasol add job will return success, even if the job was not properly i...
rdppathak/DataStructuresPython
BinaryTree/TreeTraversal.py
Python
apache-2.0
1,537
0.040338
import Queue class Graph: def __init__(self, number_of_vertices): self.number_of_vertices = number_of_vertices self.vertex_details = {} self.visited = {} def add_edge(self, vertex_label, edge): if self.vertex_details.has_key(vertex_label): self.vertex_details[vertex_label].append(edge) else: self....
ting_vert
ex): print "Starting breath first search from vertex: ", starting_vertex bfs_queue = Queue.Queue() bfs_trace = [] bfs_queue.put(starting_vertex) self.visited[starting_vertex] = 1 while(not bfs_queue.empty()): current_vertex = bfs_queue.get() bfs_trace.append(current_vertex) adjacent_vertices = se...
habnabit/pip
tests/functional/test_install.py
Python
mit
25,668
0
import os import textwrap import glob from os.path import join, curdir, pardir import pytest from pip.utils import appdirs, rmtree from tests.lib import (pyversion, pyversion_tuple, _create_test_package, _create_svn_repo, path_to_url) from tests.lib.local_repos import local_checkout from test...
assert (script.site_packages / 'initools') in result.files_created, ( str(result.stdout) ) def _test_install_editable_from_git(script, tmpdir, wheel): """Test cloning from Git.""" if wheel: script.pip('install', 'wheel') pkg_path = _create_test_package(script, n
ame='testpackage', vcs='git') args = ['install', '-e', 'git+%s#egg=testpackage' % path_to_url(pkg_path)] result = script.pip(*args, **{"expect_error": True}) result.assert_installed('testpackage', with_files=['.git']) def test_install_editable_from_git(script, tmpdir): _test_install_editable_from_git(...
pme1123/pyroots
pyroots/tennant_measurement.py
Python
apache-2.0
5,145
0.011079
""" Author: Patrick Ewing Date: May 23, 2018 Functions for tenant segmentation. Mostly for validation purposes to compare manual length estimates with pyroots segmentation. Contents -------- tennant_on_segmented draw_fishnet """ from scipy import ndimage import numpy as np from skimage import color, img_as_...
############################ ####### ###### ####### Draw Fishnet ###### ####### ###### ##########
########################################### ##################################################### def draw_fishnet(image_in, size=100, grid_color = (200, 0, 0), weight = 1): """ Draw a square mesh grid over an image. The size of the grid is in pixels. Colo...
rwl/PyCIM
CIM14/ENTSOE/Equipment/Core/Curve.py
Python
mit
4,106
0.002923
# Copyright (C) 2010-2011 Richard Lincoln # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish...
t to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY
OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARIS...
Robpol86/FlashAirMusic
tests/test_configuration.py
Python
mit
12,904
0.001162
"""Test flash_air_music.configuration functions/classes.""" import pytest from flash_air_music import configuration, exceptions from flash_air_music.__main__ import __doc__ as doc def common_init(monkeypatch, tmpdir, skip_ffmpeg=False): """Perform common test setup. :param monkeypatch: pytest fixture. ...
erm': tmpdir.join('music').chmod(0o444) # Run. if mode ==
'good': configuration.initialize_config(doc) assert config['--music-source'] == str(tmpdir.join('music')) return elif mode == 'default': configuration.initialize_config(doc) assert config['--music-source'] == str(tmpdir.join('fam_music_source')) return # Run. ...
davharris/retriever
try_install_all.py
Python
mit
1,795
0.001114
"""Attempt to install all datasets into all database management systems This module, when run, attempts to install datasets from all Retriever scripts in the /scripts folder (except for those listed in IGNORE), for each engine in ENGINE_LIST() from __init__.py. In other words, it runs trys to install using all possibl...
does not check the values in the database. """ import os import sys from retriever.lib.tools import choose_engine from retriever import MODULE_LIST, ENGINE_LIST, SCRIPT_LIST MODULE_LIST = MODULE_LIST() ENGINE_LIST = ENGINE_LIST() if len(sys.argv) > 1: ENGINE_LIST = [e for e in ENGINE_LIST if ...
sys.argv[1:] or e.abbreviation in sys.argv[1:]] SCRIPT_LIST = SCRIPT_LIST() TEST_ENGINES = {} IGNORE = ["AvianBodyMass", "FIA"] for engine in ENGINE_LIST: opts = {} print "** %s **" % engine.name opts["engine"] = engine.abbreviation try: TEST_ENGINES[engine.abbreviation] = ...
ccxt/ccxt
python/ccxt/async_support/ndax.py
Python
mit
95,533
0.001706
# -*- coding: utf-8 -*- # PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN: # https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code from ccxt.async_support.base.exchange import Exchange import json from ccxt.base.errors import ExchangeError from ccxt.base.errors import A...
'GetWithdrawTemplateTypes', 'GetWithdrawTicket', 'GetWithdrawTickets', ], 'post': [ 'AddUserAffiliateTag', 'CancelUserReport', 'RegisterNewDevice', ...
'GenerateTradeActivityReport', 'GenerateTransactionActivityReport', 'GenerateTreasuryActivityReport', 'ScheduleTradeActivityReport', 'ScheduleTransactionActivityReport', 'ScheduleTreasuryAc...
joeflack4/pma-api
pma_api/models/api_base.py
Python
mit
5,645
0
"""Abstract base model.""" from datetime import datetime from pma_api.config import IGNORE_FIELD_PREFIX from pma_api.models import db from pma_api.models.string import EnglishString def prune_ignored_fields(kwargs): """Prune ignored fields. Args: kwargs (dict): Keyword arguments. """ to_pop ...
Optio
nal index to append after the prefix. This is to handle situations where a field has one or more sibling fields that represent essentially the same variable, e.g. "characteristic1", "characteristic2". Returns: dict: Namespace formatted dictionary. """ ...
tornadoalert/kmcoffice
attendance/admin.py
Python
gpl-3.0
1,936
0.019112
from django.contrib import admin from .models import Batch, Event, PreClaim, Claim, Department, Student from
django.contrib.admin.models import LogEntry # Register your models here. def js_approve(modeladmin, request, queryset): queryset.update(js_approved = True) js_approve.short_description = 'Joint Sec Approves' def dean_approve(modeladmin,request, queryset): queryset.update(dean_approved = True) dean_approve.s...
admin,request, queryset): queryset.update(sis_approved = True) sis_approve.short_description = 'SIS Approves' @admin.register(PreClaim) class PreClaimAdmin(admin.ModelAdmin): exclude = ('students','dean_approved') list_display = ('event','dean_approved') actions = [dean_approve,] def get_action...
bkaganyildiz/StreamBasedNotification
StreamBasedNotifs/capture/consumer.py
Python
gpl-3.0
1,668
0.001799
from channels.auth import channel_session_user_from_http from .models import Stream, Notification import redis import ast from .task import sendNotifications, send_not
ifications from channels import Group import json redis_con = re
dis.Redis('demo.scorebeyond.com', 8007) subs = redis_con.pubsub() subs.subscribe('test') @channel_session_user_from_http def ws_connect(message): '''Capture redis stream and save it into database''' Group('stream').add(message.reply_channel) for message in subs.listen(): if message['type'] == "mess...
mikekaram/SMS_python
example_6dof.py
Python
mit
905
0
import SMSLibrary as sms import time as t sms.init(0) motorId = [4, 5, 6, 7, 8, 9] t.sleep(0.02) sms.broadcastStop() t.sleep(0.02) sms.broadcastStart() # sms.start(motorId) for i in motorId: sms.resetErrors(i) # print(sms
.getPosition(i)) t.sleep(0.02) for i in motorId: # sms.setProfiledVelocitySetpoint(i, 128) print(sms.getAbsolutePosition(i)[1])
t.sleep(1) # sms.broadcastDoMove() t.sleep(1) # print(sms.getPIDgainP(motorId)) # print(sms.getPIDgainI(motorId)) # print(sms.getPIDgainD(motorId)) # sms.profiledMoveToRelativePosition(motorId, 10000) # t.sleep(5) # print(float(sms.getPosition(motorId)[1])) # sms.moveToRelativePosition(motorId, -16384) # t.sleep(...
aouyar/pybackup
pybackup/plugins/mysql.py
Python
gpl-3.0
4,714
0.00594
"""pybackup - Backup Plugin for MySQL Database """ import os from pybackup import errors from pybackup import utils from pybackup.logmgr import logger from pybackup.plugins import BackupPluginBase from pysysinfo.mysql import MySQLinfo __author__ = "Ali Onur Uyar" __copyright__ = "Copyright 2011, Ali Onur Uyar" __cr...
"Error Message: %s" % str(e)) logger.info("Starting dump of %d MySQL Databases.", len(self._conf['db_list'])) for db in self._conf['db_list']: self.dumpDatabase(db, False) self.dumpDatabase(db, True) logger.info("Finished dump of MySQL Databases.") ...
ump_full', PluginMySQL, 'dumpFull'), ('mysql_dump_databases', PluginMySQL, 'dumpDatabases'),)
zaproxy/zap-api-python
src/zapv2/authentication.py
Python
apache-2.0
3,748
0.003735
# Zed Attack Proxy (ZAP) and its related class files. # # ZAP is an HTTP/HTTPS proxy for assessing web application security. # # Copyright 2022 the ZAP development team # # 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...
""" return six.next(six.itervalues(self.zap._request(self.zap.base + 'authentication/view/getAuthenticationMethod/', {'contextId': contextid}))) def get_logged_in_indicator(self, contextid): """ Gets the logged in indicator for the context with the given ID. """
return six.next(six.itervalues(self.zap._request(self.zap.base + 'authentication/view/getLoggedInIndicator/', {'contextId': contextid}))) def get_logged_out_indicator(self, contextid): """ Gets the logged out indicator for the context with the given ID. """ return six.next(...
beproud/bpssl
setup.py
Python
bsd-3-clause
1,131
0.001768
#!/usr/bin/env python #:coding=utf-8: from setuptools import setup, find_packages import sys extra = {} if sys.version_info >= (3,): extra['use_2to3'] = True setup( name='bpssl', version='1.0.3', description='SSL/HTTPS for Django', long_description=open('README.rst').read() + '\n' + open('CHANGES...
'Topic :: Software Development :: Libraries :: Python Modules', ], packages=find_packages(), namespace_packages=[ 'beproud', 'beproud.django', ], install_requires=[ 'Django>=1.2', ], test_
suite='tests.main', **extra )
BeATz-UnKNoWN/python-for-android
python3-alpha/python3-src/Lib/test/test_nntplib.py
Python
apache-2.0
49,704
0.000865
import io import datetime import textwrap import unittest import functools import contextlib import collections from test import support from nntplib import NNTP, GroupInfo, _have_ssl import nntplib if _have_ssl: import ssl TIMEOUT = 30 # TODO: # - test the `file` arg to more commands # - test error conditions # ...
AME) start = last - 10 # The "start-" article range form resp, lines = self.server.over((start, None)) art_num, art
_dict = lines[0] self._check_art_dict(art_dict) # The "start-end" article range form resp, lines = self.server.over((start, last)) art_num, art_dict = lines[-1] # The 'last' article is not necessarily part of the output (cancelled?) self.assertGreaterEqual(art_num, start)...
pattisdr/osf.io
api/actions/permissions.py
Python
apache-2.0
2,521
0.002777
# -*- coding: utf-8 -*- from __future__ import unicode_literals from rest_framework import permissions as drf_permissions from api.base.utils import get_user_auth from osf.models.action import ReviewAction from osf.models.mixins import ReviewableMixin, ReviewProviderMixin from osf.utils.workflows import ReviewTrigger...
) if request.method in drf_permissions.SAFE_METHODS: # Moderators and node contributors can view actions is_node_contributor = target is not None and target.has_permission(auth.user, osf_permissions.READ)
return is_node_contributor or auth.user.has_perm('view_actions', provider) else: # Moderators and node admins can trigger state changes. is_node_admin = target is not None and target.has_permission(auth.user, osf_permissions.ADMIN) if not (is_node_admin or auth.u...
DavideCanton/Python3
num/collatz/main.py
Python
gpl-3.0
326
0.009202
__author__ = 'Davide' import random from collatz import collatz_len def main(): R = [random.randint(10 ** 0, 10 ** 10) for _ in range(1000
000)] lenghts = [(x, collatz_len(x)) for x in R] lenghts.sort(key
=lambda x: x[1]) for (x, c) in lenghts[-10:]: print(c, x) if __name__ == "__main__": main()
Skruf90/FriendlyTorrent
src/tornado/BitTornado/BT1/Rerequester.py
Python
apache-2.0
15,296
0.009283
# Written by Bram Cohen # modified for multitracker operation by John Hoffman # see LICENSE.txt for license information from BitTornado.zurllib import urlopen, quote from urlparse import urlparse, urlunparse from socket import gethostbyname from btformats import check_peers from BitTornado.bencode import bdecode from ...
self.url += "&port=" else: self.url += "&port=0&cryptoport=" self.url += str(port) seed_id = config.get('dedicated_seed_id') if seed_id: self.url += '&seed_id='+quote(seed_id) if self.seededfunc: self.url += '&check_seeded=1' ...
st_failed = True self.never_succeeded = True self.errorcodes = {} self.lock = SuccessLock() self.special = None self.stopped = False def start(self): self.sched(self.c, self.interval/2) self.d(0) def c(self): if self.stopped: return ...
egtaonline/GameAnalysis
gameanalysis/reduction/_common.py
Python
apache-2.0
5,610
0.000713
"""Common routines for reductions""" import numpy as np from gameanalysis import utils def reduce_profiles(sarr, reduced_players, profiles): # pylint: disable=too-many-locals """Hierarchically reduces several role symmetric array profiles This returns the reduced profiles, and a boolean mask showing which o...
st be two dimensional.""" full_players = np.add.reduceat(profiles, sarr.role_starts, 1) utils.check( np.all(full_players >= reduced_players), 'full_players must be at least reduced_players') utils.check(
np.all((reduced_players > 0) | ((full_players == 0) & (reduced_players == 0))), 'reduced players must be greater than 0') rep_red_players = reduced_players.repeat(sarr.num_role_strats, 1) rep_full_players = np.maximum( full_players, 1).repeat(sarr.num_rol...
baroquebobcat/pants
tests/python/pants_test/backend/codegen/antlr/java/test_antlr_java_gen.py
Python
apache-2.0
7,533
0.007965
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache
License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os import re import time from textwrap import dedent from twitter.common.dirutil.fileset
import Fileset from pants.backend.codegen.antlr.java.antlr_java_gen import AntlrJavaGen from pants.backend.codegen.antlr.java.java_antlr_library import JavaAntlrLibrary from pants.base.exceptions import TaskError from pants.build_graph.build_file_aliases import BuildFileAliases from pants.invalidation.build_invalidat...
alviano/wasp
tests/asp/cautious/solitaire14.cautious.asp.test.py
Python
apache-2.0
40,390
0.000149
input = """ 1 2 0 0 1 3 0 0 1 4 0 0 1 5 0 0 1 6 0 0 1 7 0 0 1 8 0 0 1 9 0 0 1 10 0 0 1 11 0 0 1 12 0 0 1 13 0 0 1 14 0 0 1 15 0 0 1 16 0 0 1 17 0 0 1 18 0 0 1 19 0 0 1 20 0 0 1 21 0 0 1 22 0 0 1 23 0 0 1 24 0 0 1 25 0 0 1 26 0 0 1 27 0 0 1 28 0 0 1 29 0 0 1 30 0 0 1 31 0 0 1 32 0 0 1 33 0 0 1 34 0 0 1 35 0 0 1 36 0 0 1...
38 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 1 1 2 1 190 189 2 191 132 0 2 57 58 59 60 61 62 63 64 65 66 67 68 69 70
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 1...
xzturn/caffe2
caffe2/python/cnn.py
Python
apache-2.0
7,639
0.000262
## @package cnn # Module caffe2.python.cnn from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import brew from caffe2.python.model_helper import ModelHelper from caffe2.proto import caffe2_pb2 import lo...
lf, *args, **kwargs): return brew.dropout( self, *args, order=self.order, use_cudnn=self.use_cudnn, **kwargs ) def LRN(self, *args, **kwargs): return brew.lrn( self, *args, order=self.order, use_cudnn=self.use_cudnn, **kwargs ) def Softmax(self, *args, *...
w.softmax(self, *args, use_cudnn=self.use_cudnn, **kwargs) def SpatialBN(self, *args, **kwargs): return brew.spatial_bn(self, *args, order=self.order, **kwargs) def InstanceNorm(self, *args, **kwargs): return brew.instance_norm(self, *args, order=self.order, **kwargs) def Relu(self, *args...
jopohl/urh
src/urh/ui/painting/FFTSceneManager.py
Python
gpl-3.0
1,960
0.002041
import numpy as np from PyQt5.QtGui import QPainterPath, QPen from PyQt5.QtWidgets import QGraphicsPathItem from urh import settings from urh.cythonext import path_creator from urh.ui.painting.GridScene import GridScene from urh.ui.painting.SceneManager import SceneManager class FFTSceneManager(SceneManager): de...
f len(self.peak) < self.num_samples else np.maximum(self.peak, self.plot_data) self.scene.setSceneRect(0, -5, self.num_samples, 10) def clear_path(self): for item in self.scene.items(): if isinstance(item, QGraphicsPathIte
m) and item != self.peak_item: self.scene.removeItem(item) item.setParentItem(None) del item def clear_peak(self): self.peak = [] if self.peak_item: self.peak_item.setPath(QPainterPath()) def eliminate(self): super().eliminate...
wooyek/glosuj-w-lomiankach
src/flask_multi_view/actions.py
Python
mit
7,581
0.001584
# coding=utf-8 # # Copyright 2010 Brave Labs sp. z o.o. # All rights reserved. # # This source code and all resulting intermediate files are CONFIDENTIAL and # PROPRIETY TRADE SECRETS of Brave Labs sp. z o.o. # Use is subject to license terms. See NOTICE file of this project for details. import inspect from ...
fn): def decorator(view_class): view_class.decorate_actions(fn) return view_class return decorator class Base
ActionView(object): """Base controller configuring routes for actions defined by a subclass You must implement other actions:: ButlerControler(BaseActionView): def hello(self, name): return 'Hello {}}!'.format(name) def greting(self, name): ...
fboers/jumeg
examples/connectivity/plot_degree_circle.py
Python
bsd-3-clause
694
0.001441
#!/usr/bin/env python ''' Plot degree values for a given set of nodes in a simple circle plot. ''' import numpy as np import matplotlib.pyplot as plt import mne from jumeg import get_jumeg_path from jumeg.connectivity import plot_degree_circle import bct orig_labels_fname = get_jumeg_path() + '/data/desikan_label_...
n_ = con[0, :, :, 2] + con[0, :, :, 2].T # compute the degree degrees = mne.connectivity.degree(con_,
threshold_prop=0.2) fig, ax = plot_degree_circle(degrees, yaml_fname, orig_labels_fname)
rigatoni/linguine-python
test/transaction_test.py
Python
mit
1,437
0.011134
import unittest import sys import os from pymongo import MongoClient from bson.objectid import ObjectId from linguine.transaction import Transaction class TransactionTest(unittest.TestCase): def setUp(self): self.trans = Transaction('test') self.test_data = {} def test_parse_json(self):
#set up test data db = 'linguine-test' corpora = MongoClient()[db].corpus test_contents_id = corpora.insert({ "title": "A Tale of Two Cities", "contents" : "it was the best of times it was the worst of times it was the age of whatever it was the age of whatever", "tags": [] }) se...
t_data = '{"transaction_id":"1", "operation":"NoOp", "library":"no_library", "corpora_ids":["' + str(test_contents_id) + '"]}' #clean up corpora.remove(test_contents_id) def test_run(self): #set up test data db = 'linguine-test' corpora = MongoClient()[db].corpus te...
joaduo/python-simplerpc
simplerpc/common/abstract/FrameworkObject.py
Python
bsd-3-clause
383
0.002611
# -*- coding: utf-8 -*- ''' Copyright (c) 2013, LastSeal S.A. Copyright
(c) 2011-2012, Joaquin G. Duo All rights reserved. This code is distributed under BSD 3-clause License. For details check the LICENSE file in the root of the project. ''
' class FrameworkObject(object): pass def smokeTestModule(): FrameworkObject() if __name__ == '__main__': smokeTestModule()
cmars/pystdf
pystdf/OoHelpers.py
Python
gpl-2.0
955
0.00733
# # PySTDF - The Pythonic STDF Parser # Copyright (C) 2006 Casey Marshall # # 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 ve
rsion 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without ev
en 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 General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Flo...