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
Fillll/reddit2telegram
reddit2telegram/channels/~inactive/r_jacksepticeye/app.py
Python
mit
149
0.006711
#encoding:utf-8 subreddit = 'jacksepticeye' t_channel = '@r_jackseptice
ye' def send_post(subm
ission, r2t): return r2t.send_simple(submission)
ininex/geofire-python
resource/lib/python2.7/site-packages/gcloud/streaming/buffered_stream.py
Python
mit
2,444
0
"""Small helper class to provide a small slice of a stream. This class reads ahead to detect if we are at the end of the stream. """ class BufferedStream(object): """Buffers a stream, reading ahead to determine if we're at the end. :type stream: readable file-like object :param stream: the stream to b...
read into the buffer :rtype: integer """ return self._end_pos @property def _bytes_remaining(self): """Bytes remaining to be read from the buffer :rtype: integer """ return len(self._buffered_data) - self._buffer_pos def read(self, size=None): ...
bytes to read (defaults to all remaining bytes). """ if size is None or size < 0: raise ValueError( 'Illegal read of size %s requested on BufferedStream. ' 'Wrapped stream %s is at position %s-%s, ' '%s bytes remaining.' % (siz...
lsaffre/timtools
timtools/sdoc/barcodes.py
Python
bsd-2-clause
4,217
0.030828
## Copyright 2003-2009 Luc Saffre ## This file is part of the TimTools project. ## TimTools 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 v...
.line(x,bottom,x,top) class BarcodeFlowable(Flowable): '''A barcode symbol as flowable. Works only with EAN13.''' def __init__(self, barCodeSymbol): Flowable.__init__(self) assert hasattr(barCodeSymbol,'font') "name of font to use for printing human-readable text" a...
deSymbol,'bits') """string of 0,1 and L characters. each character stands for one "bit" or "module". 0 means white, 1 means black, L means long black""" assert hasattr(barCodeSymbol,'moduleHeight') "module height in points" assert hasattr(barCodeSymbol,'patternWi...
wavesoft/LiveQ
liveq-common/liveq/utils/FLAT.py
Python
gpl-2.0
3,333
0.031203
################################################################ # LiveQ - An interactive volunteering computing batch system # Copyright (C) 2013 Ioannis Charalampidis # # 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 ...
line: # Empty line pass elif "# BEGIN " in line: # Ignore labels found some times in AIDA files dat = line.split(" ") section = dat[2] sectiontype = 0 # Get additional section title title = "" if len(dat) > 3: title = " ".join(dat[3:]) # Allocate section record activesection ...
: sections[section] = activesection else: activesection['n'] = section sections.append(activesection) section = None elif line.startswith("#") or line.startswith(";"): # Comment pass elif section: # Data inside section # "SPECIAL" section is not parsable here if section == "SPECI...
8l/beri
cheritest/trunk/tests/mt/test_ipc.py
Python
apache-2.0
1,772
0.004515
#- # Copyright (c) 2014 Robert M. Norton # All rights reserved. # # @BERI_LICENSE_HEADER_START@ # # Licensed to BERI Open Systems C.I.C. (BERI) under one or more contributor # license agreements. See the NOTICE file distributed with this work for # additional information regarding copyright ownership. BERI licenses t...
NSE_HEADER_END@ # from beritest_tools import BaseBERITestCase from nose.plugins.attrib import attr @attr('mt') class test_ipc(BaseBERITestCase): def test_cause_t0(self): self.assertRegisterEqual(s
elf.MIPS.threads[0].s0 & 0xffff, 0x800, "Thread 0 cause register not interrupt on IP3") def test_epc_t0(self): expected_epc=self.MIPS.threads[0].s2 self.assertRegisterInRange(self.MIPS.threads[0].s1, expected_epc, expected_epc + 4, "Thread 0 epc register not expected_epc") def test_cause_t1(se...
erickpeirson/django-ncbi
ncbi/ncbi/wsgi.py
Python
gpl-3.0
385
0
""" WSGI config for ncbi project. It exposes the WSG
I callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ncbi.settings") application = get_wsgi_ap...
ion()
espdev/readthedocs.org
readthedocs/rtd_tests/tests/test_footer.py
Python
mit
3,568
0.003363
import json import mock from django.test import TestCase from django.test.client import RequestFactory from readthedocs.core.middleware import FooterNoSessionMiddleware from readthedocs.rtd_tests.mocks.paths import fake_paths_by_regex from readthedocs.projects.models import Project class Testmaker(TestCase): f...
assertE
qual(resp['version_supported'], True) self.assertEqual(r.context['main_project'], self.pip) self.assertEqual(r.status_code, 200) self.latest.active = False self.latest.save() r = self.client.get('/api/v2/footer_html/?project=pip&version=latest&page=index', {}) resp = jso...
ChristianSch/crime-stats-nlp
conf.py
Python
mit
8,233
0.006195
# -*- coding: utf-8 -*- # # crime-nlp-cfgi documentation build configuration file, created by # sphinx-quickstart on Mon Jan 19 17:51:24 2015. # # 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 # autogenerated file...
ative to source directory, that
match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true...
zhinaonet/sqlmap-z
lib/core/agent.py
Python
gpl-3.0
50,858
0.004031
#!/usr/bin/env python """ Copyright (c) 2006-2017 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ import re from lib.core.common import Backend from lib.core.common import extractRegexResult from lib.core.common import getSQLSnippet from lib.core.common import getUnicode ...
_ = "%s%s" % (origValue, kb.customInjectionMark) if kb.postHint == POST_HINT.JSON and not isNumber(newValue) and not '"%s"' % _ in paramString: newValue = '"%s"' % newValue elif kb.postHint == POST_HINT.JSON_LIKE and not isNumber(newValue) and not "'%s'" % _ in paramString: ...
retVal = paramString.replace(_, self.addPayloadDelimiters(newValue)) retVal = retVal.replace(kb.customInjectionMark, "").replace(REPLACEMENT_MARKER, kb.customInjectionMark) elif BOUNDED_INJECTION_MARKER in paramDict[parameter]: _ = "%s%s" % (origValue, BOUNDED_INJECTION_MARKER) ...
jopamer/swift
utils/incrparse/incr_transfer_tree.py
Python
apache-2.0
3,699
0.002974
#!/usr/bin/env python from __future__ import print_function import argparse import os import subprocess import sys from test_util import TestFailedError, run_command, \ serializeIncrParseMarkupFile def main(): parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, ...
that contains the expected incrementally ' 'transferred syntax tree') args = parser.parse_args(sys.argv[1:]) test_file = args.file.name test_file_name = os.path.basename(test_file) test_case = ar
gs.test_case temp_dir = args.temp_dir swift_syntax_test = args.swift_syntax_test expected_syntax_tree_file = args.expected_incremental_syntax_tree if not os.path.exists(temp_dir): os.makedirs(temp_dir) incremental_serialized_file = temp_dir + '/' + test_file_name + '.' \ + test_cas...
mkuiack/tkp
tkp/telescope/lofar/beam.py
Python
bsd-2-clause
1,207
0.004143
""" Beam characterization calculations. For more information and the math behind this code go to the `LOFAR imaging capabilities page <http://www.astron.nl/radio-observatory/astronomers/lofar-imaging-capabilities-sensitivity/lofar-imaging-capabilities/lofa>`_. """ import math def fwhm(lambda_, d, alpha1=1.3): ""...
and any additional tapering which may be used to form the station beam. No electronic tapering is presently applied to LOFAR station beamforming. For a uniformly illuminated circular aperture, alpha1 takes the value of 1.02, and the value increases ...
""" The Field of View (FoV) of a LOFAR station :param fwhm: nominal Full Width Half Maximum, caulculated with :func:`fwhm`. """ return math.pi * ((fwhm / 2) ** 2)
guaix-ucm/pyemir
emirdrp/tools/merge_bounddict_files.py
Python
gpl-3.0
3,275
0.000611
# # Copyright 2008-2018 Universidad Complutense de Madrid # # This file is part of PyEmir # # PyEmir 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 l...
buted 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 General Public License # along with PyEmir. If not, se...
datetime import datetime import json import os import sys from uuid import uuid4 from numina.tools.arg_file_is_new import arg_file_is_new from emirdrp.core import EMIR_NBARS def main(args=None): # parse command-line options parser = argparse.ArgumentParser() # positional arguments parser.add_argum...
sbuss/voteswap
users/migrations/0014_signuplog.py
Python
mit
928
0.002155
# -*- coding: utf-8 -*- # Generated by Django 1.9.9 on 2016-10-03 02:38 from __future__
import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(m
igrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('users', '0013_auto_20161002_0504'), ] operations = [ migrations.CreateModel( name='SignUpLog', fields=[ ('id', models.AutoField(auto_created=T...
zmap/ztag
ztag/annotations/FtpLacie.py
Python
apache-2.0
3,497
0.002574
import re from ztag.annotation import Annotation from ztag.annotation import OperatingSystem from ztag.annotation import Type from ztag.annotation import Manufacturer from ztag import protocols import ztag.test class FtpLacie(Annotation): protocol = protocols.FTP subprotocol = protocols.FTP.BANNER port = ...
eta.global_metadata.manufacturer = Manufacturer.LACIE meta.global_metadata.product = product return meta """ Tests "220 NetworkSpace2 FTP Server [10.0.1.50]\r\n" "220 LaCie-CloudBox FTP Serve
r [192.168.0.16]\r\n" "220 LaCie-CloudBox FTP Server [192.168.0.21]\r\n" "220 LaCie-CloudBox FTP Server [192.168.1.197]\r\n" "220 NetworkSpace2 FTP Server [192.168.100.17]\r\n" "220 LaCie-CloudBox FTP Server [192.168.1.11]\r\n" "220 NetworkSpace2 FTP Server [192.168.0.26]\r\n" "220 LaCie-CloudBo...
tropp/acq4
acq4/devices/SutterMP285/SutterMP285.py
Python
mit
18,485
0.011577
# -*- coding: utf-8 -*- from __future__ import with_statement from acq4.devices.Device import * from acq4.devices.OptomechDevice import * #import serial, struct from acq4.drivers.SutterMP285 import * from acq4.drivers.SutterMP285 import SutterMP285 as SutterMP285Driver ## name collision with device class from acq4.uti...
ith values in meters. speed will be set before moving unless speed=None """ with self.driverLock: if speed is not None: self.mp285.setSpeed(speed, fine) self.mp285
.setPos(pos, block=block, timeout = timeout) self.getPosition(refresh=True) class SMP285Interface(QtGui.QWidget): def __init__(self, dev, win): QtGui.QWidget.__init__(self) self.ui = devTemplate.Ui_Form() self.ui.setupUi(self) self.win = win self.dev = dev ...
BlessedAndy/Programming-Foundations-with-Python
Programming Foundations with Python/src/cn/careerwinner/sap/report_scheduler.py
Python
apache-2.0
55
0
''' C
reated on Jul 18, 2017 @author: I310003 '''
mddenton/Projects-my
Games/blackjack.py
Python
mit
1,541
0.009734
# python v. 3.3.2 import random def genSuit(): suit = random.randint(1, 4) if suit == 1: return "Clubs" if suit == 2: return "Diamonds" if suit == 3: return "Hearts" if suit == 4: return "Spades" return "Whoops!" def genRank(): rank = random.randint(1, 13) ...
ion = card.find(" ") rank = card[0: position]
# print(rank) if rank == "Ace": return 11 if rank == "King" or rank == "Queen" or rank == "Jack": return 10 return int(rank) def hand(): card1 = drawCard() card2 = drawCard() drawTwo = value(card1) + value(card2) print ("first card: ", card1, ", second card: ", card2, sep...
tethysplatform/tethys
tests/unit_tests/test_tethys_gizmos/test_gizmo_options/test_base.py
Python
bsd-2-clause
1,994
0
""" ******************************************************************************** * Name: base.py * Author: nswain * Created On: July 23, 2018 * Copyright: (c) Aquaveo 2018 ******************************************************************************** """ import unittest import tethys_gizmos.gizmo_options.base as ...
t_get_tethys_gizmos_css(self): result = basetest.TethysGizmoOptions.get_tethys_gizmos_css() self.assertIn('tethys_gizmos.css', result[0])
self.assertNotIn('.js', result[0]) def test_get_vendor_js(self): result = basetest.TethysGizmoOptions.get_vendor_js() self.assertFalse(result) def test_get_gizmo_js(self): result = basetest.TethysGizmoOptions.get_gizmo_js() self.assertFalse(result) def test_get_ven...
azafred/fredlibs
tests/test_advanced.py
Python
bsd-2-clause
271
0
# -*- coding: utf-8 -*- from .context import fredlibs import unittest class
AdvancedTestSuite(unittest.TestCase): """Advanced test cases.""" def test_thoughts(self): self.assertIsNone(fredlibs.main(
)) if __name__ == '__main__': unittest.main()
ttm/sonhos
scripts/exwn.py
Python
cc0-1.0
203
0.019704
import nltk as k #ss=k.corpus.wordnet.synset("thumb") aa=k.corp
us.wordnet.synsets("word") print("hypernyms: ", aa[0].hypernyms(),"\nhyponyms:
", aa[0].hyponyms()) print("\n\nall methods:", dir(aa[0]))
Tendrl/commons
tendrl/commons/tests/utils/test_event_utils.py
Python
lgpl-2.1
676
0
import __builtin__ import maps from tendrl.commons.utils.event_utils import emit_event def test_emit_event(): setattr(__builtin__, "NS", maps.NamedDict()) NS.publisher_id = 0 NS.node_context = maps.NamedDict(fqdn="test",
node_id="0") NS.tendrl_context = maps.NamedDict(integration_id="", cluster_name="", sds_name="") emit_event("test", "test", "test", "test", "test", tags=maps.NamedDict(entity_type="brick"))...
ict(entity_type="volume"))
teoreteetik/api-snippets
monitor/events/instance-get-example-phone-number/instance-get-example-phone-number.6.x.py
Python
mit
370
0
# Download the Python helper library from twilio.com/docs/python/install from twilio.rest import Client # Your Account Sid and Auth Token
from twi
lio.com/user/account account_sid = "ACCOUNT_SID" auth_token = "your_auth_token" client = Client(account_sid, auth_token) event = client.monitor.events("AE21f24380625e4aa4abec76e39b14458d").fetch() print(event.description)
cyncyncyn/evette
languagefiles/language_us_1.3.2.py
Python
gpl-2.0
68,624
0.041691
#!/usr/bin/python # -*- coding: UTF-8 -*- #Copyright (C) 2007 Adam Spencer - Free Veterinary
Management Suite #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 version. #This program is distributed in the hope that it will be...
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 Floor, Boston, MA 02110-1301, USA. ##Contact: evetteproject@dsl.pipex.com ####US English#### def GetDictionary(): ...
eduNEXT/edx-platform
lms/djangoapps/coursewarehistoryextended/tests.py
Python
agpl-3.0
4,269
0.002577
""" Tests for coursewarehistoryextended Many aspects of this app are covered by the courseware tests, but these are specific to the new storage model with multiple backend tables. """ import json from unittest import skipUnless from unittest.mock import patch from django.conf import settings from django.db import co...
y, StudentModule, StudentModuleHistory from lms.djangoapps.courseware.tests.factories import COURSE_KEY from lms.djangoapps.courseware.tests.factories import LOCATION from lms.djangoapps.courseware.tests.factories import StudentModuleFactory @skipUnless(settings.FEATURES["ENABLE_CSMH_EXTENDED"], "CSMH Extended needs ...
s TestStudentModuleHistoryBackends(TestCase): """ Tests of data in CSMH and CSMHE """ # Tell Django to clean out all databases, not just default databases = set(connections) def setUp(self): super().setUp() for record in (1, 2, 3): # This will store into CSMHE via the post_s...
lento/cortex
test/IECoreMaya/PluginLoadUnload.py
Python
bsd-3-clause
2,870
0.032404
########################################################################## # # Copyright (c) 2008, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source
and binary forms, with or without # modification, ar
e permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright # notice, this list of condition...
src053/PythonComputerScience
chap8/syracuse.py
Python
cc0-1.0
606
0.049505
#a Program that finds the syracuse sequence #function to call the even calculation def even(n): return n/2 #function to call the odd calculation def odd(n): return 3 * n + 1 def main(): #get
the natural number from user n = eval(input("Please enter a natural number: ")) #iterate until the n var is 1 while n > 1: #if n var is evenly divisible by two then run the even function if n % 2 == 0: #for trouble shooting print("even function will be ran") n = even(n) #print the value of n prin...
main()
supasate/word_prediction
Chapter4/4-7-even-solution.py
Python
gpl-2.0
193
0.00885
# จงเขียนโปรแกรมแสดงเลขคู่ในช่วง 0 ถึง 10 (รวม 10 ด้วย) for i in range(11): if (i % 2 == 0)
: print(
i)
drussell393/ConfidenceMon
modules/zabbix.py
Python
mit
5,988
0.009185
import json import logging import re import urllib2 import base64 class _NullHandler(logging.Handler): """ Null Handler class for Logger """ def emit(self, record): pass logger = logging.getLogger(__name__) logger.addHandler(_NullHandler()) class ZabbixAPIException(Exception): """ ZabbixAPI exceptio...
elf.url = url + '/api_jsonrpc.php' self.__log
in(user, password) logger.debug("JSON-PRC Server: %s", self.url) def __getattr__(self, attr): """ Dynamically create an object class (ie: host) """ return ZabbixAPIObjectClass(attr, self) def __login(self, user='', password=''): """ Do login to zabbix server Attributes: user...
sfu-discourse-lab/SFU_Comment_Extractor
Source_Code/data_cleanup/repair_gnm_article_text.py
Python
mit
1,779
0.033165
from bs4 import BeautifulSoup import requests import os import re import time import dbm import csv import pandas as pd def _count_words(s): """count the number of words in a paragraph Args: [String] s Return: [INT] number of words in the string """ return len(s.split(" ")) def get_page(url): ""
"get the page information Args: [String] URL: the URL to the page we
try to parse Return: [Data Structure] page: the request response from the page """ print(url) page = '' while page == '': try: time.sleep(1) page = requests.get(url) except: print("Connection refused by the server..") print("Let me sleep for 5 seconds") print("ZZzzzz...") time.sleep(5) ...
locaweb/leela
try/src/try_leela/helpers.py
Python
apache-2.0
1,592
0.010678
# -*- coding: utf-8 -*- import sys import time def make(session): session.execute("make (%(rnd_name.0)s)") a_guid = session.message()[1][-1] assert(session.message() is None) return(a_guid) def link(session, a, l, b): session.execute("make %s -[%s]> %s" % (a, l, b)) assert(s
ession.message() is None) def kill(session, a, l, b=None): if (b is None): session.execute("kill %s -[%s]> ()" % (a, l)) else: session.execute("kill %s -[%s]> %s" % (a, l, b)) assert(session.message() is None) def kattr_put(session, a, name, value, ttl=None): if (ttl is None): ...
s \"%s\" %s%s" % (a, name, value, ttl)) assert(session.message() is None) def tattr_put(session, a, name, time, value, ttl=None): if (ttl is None): ttl = "" else: ttl = " with ttl:%d" % (ttl,) session.execute("attr put %s \"%s\" [%s] %s%s" % (a, name, time, value, ttl)) assert(sessi...
alexm92/sentry
src/sentry/models/commit.py
Python
bsd-3-clause
1,338
0
from __future__ import absolute_import, print_function from django.db import models from django.utils import timezone from sentry.db.models import ( BoundedPositiveIntegerField, FlexibleForeignKey, Model, sane_repr ) from sentry.utils.cache import memoize class Commit(Model): __core__ = False organizat...
ct is referenced (and thus created) author = FlexibleForeignKey('sentry.CommitAuthor', null=True) message = models.TextField
(null=True) class Meta: app_label = 'sentry' db_table = 'sentry_commit' index_together = ( ('repository_id', 'date_added'), ) unique_together = ( ('repository_id', 'key'), ) __repr__ = sane_repr('organization_id', 'repository_id', 'key') ...
gaftech/fmanalyser
fmanalyser/commands/fmlogger.py
Python
mit
4,946
0.00647
#!/usr/bin/env python # -*- coding: utf-8 -*- from ..client import MODE_CHOICES from ..client.tasks import ReadChannelValues, WriteChannelValue from ..client.worker import Worker from ..utils.command import BaseCommand from ..values.channel import Channel from ..values.signals import ValueChangeEvent from optparse impo...
.wait(blocking=False, timeout=2) time.sleep(self.options.sleep) def make_channel(self): channel = Channel() for variable in channel.get_variables(): enabled = getattr(self.options, variable.descriptor.key) variable.enabled = enabled return channel de...
lf, sender, event): message = self.format_event(event) self.log_data(message) def format_event(self, event): descriptor = event.sender.descriptor return '%s: %s' % (descriptor.key, descriptor.format_value(event.new_value)) def log_data(self, message): self.datalogg...
antonyr/django-haystack
haystack/management/commands/rebuild_index.py
Python
bsd-3-clause
1,324
0.003776
# encoding: utf-8 from __future__ import absolute_import, division, print_function, unicode_literals from django.core.management import ca
ll_command from django.core.management.base import BaseCommand class Command(BaseCommand): help = "Completely rebuilds the search index by removing th
e old data and then updating." def add_arguments(self, parser): parser.add_argument( '--noinput', action='store_false', dest='interactive', default=True, help='If provided, no prompts will be issued to the user and the data will be wiped out.' ) parser.add_argument( ...
apache/incubator-airflow
docs/exts/docs_build/docs_builder.py
Python
apache-2.0
12,386
0.002018
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
IR}/_doctrees/docs/{self.package_name}" @property def _inventory_cache_dir(self) -> str: return f"{DOCS_DIR}/_inventory_cache" @property def is_versioned(self): """Is current documentation package versioned?""" # Disable versioning. This documentation does not apply to any rele...
ate # it as needed, i.e. with each new package of providers. return self.package_name not in ('apache-airflow-providers', 'docker-stack') @property def _build_dir(self) -> str: if self.is_versioned: version = "stable" if self.for_production else "latest" return f...
mangaki/mangaki
mangaki/mangaki/management/commands/anilist_tags_to_json.py
Python
agpl-3.0
3,990
0.002514
# SPDX-FileCopyrightText: 2014, Mangaki Authors # SPDX-License-Identifier: AGPL-3.0-only from time import sleep import json from django.core.management.base import BaseCommand from mangaki.wrappers.anilist import AniList from mangaki.models import Work MAX_ATTEMPTS = 5 BACKOFF_DELAY = 2 class Command(BaseCommand)...
self.stdout.write('Number of works : '+str(count)+'\n\n') for work in works: title_display = work.title.encode('utf8') if self.stdout.encoding is not None: title_display = title_display.decode(self.stdout.encoding) anilist_result = None # Try...
tch data from AniList with an exponential backoff for tries in range(MAX_ATTEMPTS): try: # Search the work by title on AniList anilist_result = client.get_work(search_title=work.title) break except Exception as err: ...
jmartinm/invenio
modules/miscutil/lib/plotextractor_converter.py
Python
gpl-2.0
8,021
0.003117
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2010, 2011 CERN. ## ## Invenio 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 opt...
d_file = os.path.join(sdir, extracted_file) # Add to full list of ext
racted files file_list.append(extracted_file) dummy1, cmd_out, dummy2 = run_shell_command('file %s', (extracted_file,)) # is it TeX? if cmd_out.find(tex_output_contains) > -1: might_be_tex.append(extracted_file) # is it an image? elif cmd_out.lower().find(i...
lakshmisampath/searchlight
searchlight/elasticsearch/plugins/glance/metadefs.py
Python
apache-2.0
5,700
0
# Copyright 2015 Intel Corporation # 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 require...
te", "metadef_object.create", "metadef_object.update", "metadef_object.delete", "metadef_property.create", "metadef_property.update", "metadef_property.delete", "metadef_tag.create", "metadef_tag.update", "metade...
etadef_namespace.delete_objects", "metadef_namespace.delete_tags" ]
nibrahim/PlasTeX
plasTeX/Base/LaTeX/Bibliography.py
Python
mit
4,545
0.00418
#!/usr/bin/env python """ C.11.3 Bibliography and Citation (p208) """ import plasTeX, codecs from plasTeX.Base.LaTeX.Sectioning import chapter, section from plasTeX import Command, Environment from Lists import List log = plasTeX.Logging.getLogger() class bibliography(chapter): args = 'files:str' linkType ...
doc.userdata.setPath('bibliography/bibcites', bibcites) return res @property def id(self): return self.attributes['key'] @property def bibcite(self): doc = self.ownerDocument res = doc.createDocumentFr
agment() bibcites = doc.userdata.getPath('bibliography/bibcites', {}) res.extend(bibcites.get(self.attributes['key'])) return res def digest(self, tokens): if self.macroMode == Command.MODE_END: return for tok in tokens: if not isinstance(...
iPlantCollaborativeOpenSource/libcloud
libcloud/loadbalancer/drivers/elb.py
Python
apache-2.0
12,957
0
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use ...
turn balancer._members def ex_list_balancer_policies(self, balancer): """ Return a list of policy description string. :rtype: ``list`` of ``str`` """ params = { 'Action': 'DescribeLoadBalancerPolicies',
'LoadBalancerName': balancer.id } data = self.connection.request(ROOT, params=params).object return self._to_policies(data) def ex_list_balancer_policy_types(self): """ Return a list of policy type description string. :rtype: ``list`` of ``str`` """ ...
seibert-media/Highton
highton/fields/object_field.py
Python
apache-2.0
933
0.002144
from highton.fields import Field class ObjectField(Field): """ The ObjectFIeld parses the init_class object :ivar init_class: a Highton model "
"" def __init__(self, name, init_class): super().__init__(name) self.init_class = init_class def encode(self): """ Just encode the object you have as value :return: the parsed element :rtype: xml.etree.ElementTree.Element """ return self....
def decode(self, element): return self.init_class.decode(element) def to_serializable_value(self): """ Run through all fields of the object and parse the values :return: :rtype: dict """ return { name: field.to_serializable_value() ...
eggsandbeer/scheduler
tests/test_site_yearly_aggregator.py
Python
bsd-3-clause
1,460
0.008219
__author__ = 'Bohdan Mushkevych' import unittest from settings import enable_test_mode enable_test_mode() from db.model.raw_data import DOMAIN_NAME, TIMEPERIOD from
constants import PROCESS_SITE_YEARLY from tests import monthly_fixtures from tests import yearly_fixtures from tests.test_abstract_worker import AbstractWorkerUnitTest from workers.site_yearly_aggregator import SiteYearlyAggregator class SiteYearlyAggregatorUnitTest(AbstractWorkerUnitTest): def virtual_set_up(sel...
super(SiteYearlyAggregatorUnitTest, self).constructor(baseclass=SiteYearlyAggregator, process_name=PROCESS_SITE_YEARLY, output_prefix='EXPECTED_SITE_YEARLY', ...
ixc/django-fluent-contents
fluent_contents/plugins/commentsarea/appsettings.py
Python
apache-2.0
862
0.00348
""" Settings for the markup part. """ from django.conf import settings from django.core.exceptions import ImproperlyConfigured COMMENTS_APP = getattr(settings, 'COMMENTS_APP', 'comments') FLUEN
T_COMMENTSAREA_THREADEDCOMMENTS = 'threadedcomments' in settings.INSTALLED_APPS # Test threadedcomments support if FLUENT_COMMENTSAREA_THREADEDCOMMENTS: try: from threadedcomments.templatetags import threadedcomments_tags except ImportError: raise ImportError("The 'threadedcomments' package is...
MMENTS_APP setting. if not COMMENTS_APP or COMMENTS_APP == 'comments': raise ImproperlyConfigured("To use 'threadedcomments', specify the COMMENTS_APP as well")
payal97/portal
systers_portal/common/tests/selenium/test_admin_actions.py
Python
gpl-2.0
4,015
0.000249
from common.tests.selenium.base import SeleniumTestCase from selenium.webdriver.support.ui import Select, WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By class TestAdminActions(SeleniumTestCase): """ Automated visual tests admin action...
admin() self.browser.get(self.live_server_url) self.browser.add_cookie(self.create_session_cookie()) self.browser.refresh() self.browser.get('{}{}'.format(self.live_server_url, '/meetup/add/')) name = self.browser.find_element_by_id("id_name") slug = self.browser.find_ele...
nt_by_id("id_location")) email = self.browser.find_element_by_id("id_email") name.send_keys("Foo Community") slug.send_keys("foo-community") email.send_keys("foo.community@systers.org") location.select_by_index(1) # Locate the CKE iframe for description descriptio...
ContinuumIO/chaco
chaco/overlays/simple_inspector_overlay.py
Python
bsd-3-clause
6,043
0.00182
"""A simple inspector overlay for plots This module provides the SimpleInspectorOverlay for displaying information gathered from an inspector tool in a TextGrid. By default it is configured to work with a SimpleInspectorTool. The module also provides some helper factory functions for creating text formatters for dic...
asic_formatter('y', 2)]] def _new_value_updated(self, event): if event is None: self.text_grid = array() if self.visibility == "auto": self.visibility = False elif self.visibility == "auto"
: self.visible = True if self.tooltip_mode: self.alternate_position = self.inspector.last_mouse_position d = event text = [] self.text_grid.string_array = array([[formatter(**d) for formatter in row] for row in self.field_formatters]) self.t...
rg3915/spark
spark/feeds/views.py
Python
mit
6,435
0
import json from django.contrib.auth.decorators import login_required from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator from django.http import (HttpResponse, HttpResponseBadRequest, HttpResponseForbidden) from django.shortcuts import get_object_or_404, render from djang...
like = Activity(activity_type=Activity.LIKE, feed=feed_id, user=user) like.save() user.profile.notify_liked(feed) return HttpResponse(feed.calculate_likes()) @login_required @ajax_required def comment(request): if request.method == 'POST': feed_id = request.POST['feed'] ...
) post = request.POST['post'] post = post.strip() if len(post) > 0: post = post[:255] user = request.user feed.comment(user=user, post=post) user.profile.notify_commented(feed) user.profile.notify_also_commented(feed) return ren...
timj/scons
src/engine/SCons/Tool/msvc.py
Python
mit
11,390
0.004829
"""engine.SCons.Tool.msvc Tool-specific initialization for Microsoft Visual C/C++. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # __COPYRIGHT__ # # Permission is hereby granted, free of charge, to any p...
t+source pairs that use the same action, defined by the same environment, and have the same target and source directories, will be batched. Returning None specifies that the specified target+source should not be batched with other compilations. """ # Fixi
ng MSVC_BATCH mode. Previous if did not work when MSVC_BATCH # was set to False. This new version should work better. # Note we need to do the env.subst so $MSVC_BATCH can be a reference to # another construction variable, which is why we test for False and 0 # as strings. if not 'MSVC_BATCH' in env...
gltn/stdm
stdm/third_party/sqlalchemy/util/_collections.py
Python
gpl-2.0
29,219
0.000068
# util/_collections.py # Copyright (C) 2005-2020 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """Collection classes and helpers.""" from __future__ import absolute_import ...
lf): return [self[key] for key in self._list] def items(self): return [(key, self[key]) for key in self._list] if
beagles/sosreport-neutron
sos/plugins/ata.py
Python
gpl-2.0
1,452
0.008953
### 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 version. ## This program is distributed in the hope that it will be useful,...
lic License ## along with this program; if not, write to the Free Software ## Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. from sos.plugins import Plugin, RedHatPlugin, UbuntuPlugin, DebianPlugin import os class Ata(Plugin, RedHatPlugin, UbuntuPlugin, DebianPlugin): """ ATA and IDE related informatio...
) def setup(self): dev_path = '/dev' sys_block = '/sys/block' self.add_copy_spec('/proc/ide') if os.path.isdir(sys_block): for disk in os.listdir(sys_block): if disk.startswith("sd") or disk.startswith("hd"): disk_path = os.path.join(d...
streamr/marvin
migrations/versions/19b7fe1331be_.py
Python
mit
665
0.010526
"""Add number_of_streams to movies. Revision ID: 19b7fe1331be Revises: 2c76677d803f Create Date: 2013-11-16 22:11:44.560000 """ # revision identifiers, used by Alembic. revision = '19b7fe1331be' down_revision = '2
c76677d803f' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - please adjust! ### op.add_column('movie', sa.Column('number_of_streams', sa.Integer(), nullable=False, server_default='0')) ### end Alembic commands ### def d
owngrade(): ### commands auto generated by Alembic - please adjust! ### op.drop_column('movie', 'number_of_streams') ### end Alembic commands ###
ICGC-TCGA-PanCancer/pcawg-central-index
pcawg_metadata_parser/pcawg_summary.loader.py
Python
gpl-2.0
955
0.013613
#!/usr/bin/env python import sys import json from elasticsearch1 import Elasticsearch def init_es(es_host, es_index): es = Elasticsearch([ es_host ]) es.indices.delete( es_index, ignore=[400, 404] ) es.indices.create( es_index, ignore=400 ) # create mappings with open('pcawg_summa
ry.mapping.json', 'r') as m: es_mapping = m.read() es.indices.put_mapping(index=es_index, doc_type='donor', body=es_mapping) return es def main(argv=None): if argv is None: argv = sys.argv else: sys.argv.extend(argv) es_host = 'localhost:9200' es_index = 'pcawg_su...
doc = json.loads(entity) es.index(index=es_index, doc_type='donor', id=doc['donor_unique_id'], \ body=doc, timeout=90 ) if __name__ == "__main__": sys.exit(main())
jamielennox/keystone
keystone/tests/unit/test_v2_keystoneclient.py
Python
apache-2.0
58,102
0
# Copyright 2012 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in...
nant_id(self): client = self.get_client() token = client.auth_token self.assertRaises(client_exceptions.Unauthorized, self._client, token=token, tenant_id=uuid.uuid4().hex) def test_authenticate_token_invalid_tenant_name(self): cli...
tenant_name=uuid.uuid4().hex) def test_authenticate_token_tenant_name(self): client = self.get_client() token = client.auth_token token_client = self._client(token=token, tenant_name='BAR') tenants = token_client.tenants.list() self.assertEqual(self.tenant_bar['id'],...
batermj/algorithm-challenger
code-analysis/programming_anguage/python/source_codes/Python3.8.0/Python-3.8.0/Doc/includes/sqlite3/simple_tableprinter.py
Python
apache-2.0
731
0.002736
import sqlite3 FIELD_MAX_WIDTH = 20 TABLE_NAME = 'people' SELECT = 'select * from %s order by age, name_last' % TABLE_NAME con = sqlite3.connect("mydb") cur = con.cursor() cur.execute(SELECT) # Print a header. for fieldDesc in cur.description:
print(fieldDesc[0].ljust(FIELD_MAX_WIDTH), end=' ') print() # Finish the header with a newline. print('-' * 78) # For each row, print the value of each field left-justified within # the maximum possible width of that field. fieldIndices = range(len(cur.descript
ion)) for row in cur: for fieldIndex in fieldIndices: fieldValue = str(row[fieldIndex]) print(fieldValue.ljust(FIELD_MAX_WIDTH), end=' ') print() # Finish the row with a newline. con.close()
SUSE/azure-sdk-for-python
azure-mgmt-servermanager/azure/mgmt/servermanager/models/session_parameters.py
Python
mit
2,307
0.002167
# 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 generate
d by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from msrest.serialization import Model class SessionParameters(Model): """Parameter col
lection for creation and other operations on sessions. :param user_name: Encrypted User name to be used to connect to node. :type user_name: str :param password: Encrypted Password associated with user name. :type password: str :param retention_period: Session retention period. Possible values ...
cbertinato/pandas
pandas/tests/tseries/offsets/test_fiscal.py
Python
bsd-3-clause
29,268
0
""" Tests for Fiscal Year and Fiscal Quarter offset classes """ from datetime import datetime from dateutil.relativedelta import relativedelta import pytest from pandas._libs.tslibs.frequencies import INVALID_FREQ_ERR_MSG from pandas import Timestamp from pandas.tseries.frequencies import get_offset from pandas.tse...
gMonth=12, qtr_with_extra_week=3)), ("REQ-N-DEC-MON-3", makeFY5253NearestEndMonthQuarter(weekday=0, startingMonth=12, qtr_with_extra_week=3))] for name, expected in pairs: ...
r (actual: %r)" % (name, expected, offset)) class TestFY5253LastOfMonth(Base): offset_lom_sat_aug = makeFY5253LastOfMonth(1, startingMonth=8, weekday=WeekDay.SAT) offset_lom_sat_sep = makeFY5253LastOfMonth(1, startingMonth=9, ...
enthought/etsproxy
enthought/blocks/compiler_/ast/deep_equality.py
Python
bsd-3-clause
113
0
# p
roxy module from __future__ imp
ort absolute_import from codetools.blocks.compiler_.ast.deep_equality import *
idlesign/torrt
tests/rpc/test_transmission.py
Python
bsd-3-clause
2,194
0.002279
import pytest from torrt.rpc.transmission import TransmissionRPC, TransmissionRPCException @pytest.fixture def transmission(): rpc = TransmissionRPC() return rpc def test_auth(response_mock): transmission = TransmissionRPC(user='wrong', password='wrongwrong') with response_mock( f'POST {t...
Unauthorized</h1>Unauthorized
User', bypass=False ): with pytest.raises(TransmissionRPCException): transmission.method_get_version() def test_get_version(response_mock, transmission): with response_mock( f'POST {transmission.url} -> 200:' '{"arguments":{"rpc-version":15,"rpc-version-minimum":1,...
lmaag182/nupic_physical
online.py
Python
agpl-3.0
994
0.009054
try: import serial # Python2 except ImportError: from serial3 import * # Python3 from nupic.frameworks.opf.modelfactory import
ModelFactory import os,sys ser = serial.Serial('/dev/ttyACM0', 9600) def get_online(number_of_records=20):# 0 means forever model = ModelFactory.loadFromCheckpoint(os.getcwd() + "/model_save") count=0 ser.flushInput() while (count < number_of_records) or (number_of_records == 0): count = cou...
)[0]), "s2": float(text.split(",")[1]), "s3": float(text.split(",")[2]), "s4": float(text.split(",")[3]) }) prediction = int(result.inferences['multiStepBestPredictions'][4]) sys.stdout.write("\r"+ str(prediction)) sys.stdou...
monikagrabowska/osf.io
addons/base/views.py
Python
apache-2.0
27,063
0.001626
import datetime import httplib import os import uuid import markupsafe from django.utils import timezone from flask import make_response from flask import redirect from flask import request import furl import jwe import jwt from django.db import transaction from modularodm import Q from modularodm.exceptions import N...
raise UNAUTHORIZED for registrations that have not been archived yet if action == 'copyfrom' or (action == 'copyto' and node.is_registration): parent = node.parent_node while parent: if parent.can_edit(auth): return True parent = parent.parent_node # User...
d be allowed to download files # from prereg challenge draft registrations. try: prereg_schema = MetaSchema.find_one( Q('name', 'eq', 'Prereg Challenge') & Q('schema_version', 'eq', 2) ) allowed_nodes = [node] + node.parents prereg_draft_registration = Dra...
glandium/git-cinnabar
cinnabar/cmd/bundle.py
Python
gpl-2.0
3,371
0
from __future__ import absolute_import, unicode_literals import logging from cinnabar.cmd.util import CLI from cinnabar.git import ( Git, GitProcess, InvalidConfig, ) from cinnabar.githg import GitHgStore from cinnabar.helper import GitHgHelper from cinnabar.hg.bundle import
( create_bundle, PushStore, ) from cinnabar.hg.repo import ( BundleApplier, get_bundle, get_clonebundle, get_repo, Remote, unbundle20, unbundler, ) from cinnabar.util import fsencode @CLI.subcommand @CLI.argument('--version', choices=(1, 2), type=int, default=2 if unb...
on') @CLI.argument('path', help='path of the bundle') @CLI.argument('rev', nargs='+', help='git revision range (see the Specifying Ranges' ' section of gitrevisions(7))') def bundle(args): '''create a mercurial bundle''' revs = [fsencode(r) for r in args.rev] bundle_commits...
idstudiolab/imagestore
src/imagestore/tests.py
Python
lgpl-2.1
4,153
0.00313
import unittest import re from lxml import etree from zope.testing import doctest, cleanup import zope.component.eventtesting from imagestore.xml import XMLValidationError, local_file class ValidationTests(unittest.TestCase): relaxng = etree.RelaxNG(file=local_file('rng', 'imagestore.rng')) def validat...
/imagestore"> <sessions href="sessions"> </sessions> </imagestore> ''' self.validate(etree.XML(xml)) def test_attributes_illegal(self): xml = ''' <imagestore xmlns="http://studiolab.io.tudelft.nl/ns/imagestore"> <sessions name="sessions">
</sessions> </imagestore> ''' self.assertRaises(XMLValidationError, self.validate, etree.XML(xml)) def test_extended(self): xml = ''' <imagestore xmlns="http://studiolab.io.tudelft.nl/ns/imagestore"> <sessions> <session href="sessions/foo" nam...
PuZheng/lejian-backend
lejian/config/views.py
Python
mit
2,153
0.000477
# -*- coding: UTF-8 -*- from flask import jsonify from sqlalchemy.orm.exc import NoResultFound from flask.ext.databrowser import ModelView, col_spec, sa from flask.ext.databrowser.action import DeleteAction from flask.ext.babel import lazy_gettext, gettext as _ from genuine_ap.config import config_ws from genuine_ap.mo...
ec.InputColSpec('type_', _('type')), col_spe
c.InputColSpec('brief', _('brief')), col_spec.InputColSpec('value', _('value'), doc=u'若是布尔类型,应当填写1(真)或0(假)'), ] def get_actions(self, processed_objs=None): return [DeleteAction(_("remove"))] config_model_view = ConfigModelView(sa.SAModell(Config, db, ...
pearpai/TensorFlow-action
deep_learning_with_tensorFlow/Chapter07/p176.py
Python
apache-2.0
1,084
0.000988
# coding=utf-8 import matplotlib.pyplot as plt import tensorflow as
tf import numpy as np from PIL import Image path = "../datasets/demo_picture/cat.jpg" img = Image.open(path) # 获取长宽 print img.size image_raw_data = tf.gfile.FastGFile("../datasets/demo_picture/cat.jpg", 'r').read() img_data = tf.image.decode_jpeg(image_raw_data) with tf.Sess
ion() as sess: croped = tf.image.resize_image_with_crop_or_pad(img_data, 1000, 1000) padded = tf.image.resize_image_with_crop_or_pad(img_data, 3000, 3000) print 'croped ', croped.get_shape() print 'padded ', croped.get_shape() # TensorFlow的函数处理图片后存储的数据是float32格式的,需要转换成uint8才能正确打印图片。 # plt.imsh...
valuesandvalue/valuesandvalue
vavs_project/fbdata/views.py
Python
mit
3,902
0.004357
# fbdata.views # DJANGO from django.contrib import messages from django.contrib.auth.models import User #from django.db.models import Max #from django.db.models import Q from django.http import HttpResponseRedirect, HttpResponse, Http404 from django.shortcuts import get_object_or_404 from django.views.generic.base imp...
pager = None return self.render_to_response({
'user': user, 'username': username, 'fbuser': fbuser, 'participant': participant, 'start': start, 'end': end, 'pager': pager}) class InteractionData(LoginRequired...
lavalamp-/ws-backend-community
lib/wsregex.py
Python
gpl-3.0
3,414
0.022847
# -*- coding: utf-8 -*- from __future__ import absolute_import import re class RegexLib(object): """ A class containing all regular expressions used throughout the DataHound application. """ # Class Members # Potentially better email regex # "([A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{...
][0-9]|3[0-2]))$", flags=re.IGNORECASE ) last_name_regex = re.compile("^[A-Za-z\-']{1,32}$") log_entry_stub_regex = re.compile("\[(.*?)\]") mime_string_regex = re.compile("^[a-z\-]+/[a-z\.\-_0-9]+(;(\s?[\w=\.\-]+)+)?$", flags=re.IGNORECASE) order_name_regex = re.compile("^[A-Za-z-_0-9]+$") ...
egex = re.compile( "^([\\\\\w\-!@\$%\^\*\(\)_`~+\[\]{}|;'\",<>]+=([\\\\\w\-!@\$%\^\*\(\)_`~+\[\]{}|;'\",<>]*)?(&[\\\\\w\-!@\$%\^\*\(\)_`~+\[\]{}|;'\",<>]+=([\\\\\w\-!@\$%\^\*\(\)_`~+\[\]{}|;'\",<>]*)?)*)$", flags=re.IGNORECASE, ) url_port_regex = re.compile(".+:([1-9]([0-9]{1,10})?)$", flags=re....
bhupennewalkar1337/erpnext
erpnext/schools/doctype/discussion/test_discussion.py
Python
gpl-3.0
263
0.007605
# -*- coding: utf-8 -*- # Cop
yright (c) 2015, Frappe and Contributors # See license.txt from __future__ import unicode_literals import frappe import unittest # test_records = frappe.get_test_records('Di
scussion') class TestDiscussion(unittest.TestCase): pass
FluidityStokes/fluidity
tools/vtu2ensight.py
Python
lgpl-2.1
5,350
0.011589
#!/usr/bin/env python3 import sys import argparse import glob import re import vtk import vtktools def parse_args(argv): parser = argparse.ArgumentParser( prog="vtu2ensight", description="""This converts a vtu file to a ensight file. If applied to checkpointed files, use rename_checkpoint ...
ensight
format): ug = addblockid(reader.ugrid) # check/remove ghostlevel array: ug = removeghostlevel(reader, ug) # write data: writedata(writer, ug, i) # write case file: writecase(writer, len(vtus)) if __name__ == "__main__": # get arguments: args = parse_args(sys.argv...
grani/grpc
src/python/grpcio_health_checking/grpc_health/v1/health.py
Python
bsd-3-clause
2,629
0
# Copyright 2015, Google 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 and the f...
tus = self._server_status.get(request.service) if status is None: context.set_code(grpc.StatusCode.NOT_FOUND) return health_pb2.HealthCheckResponse() else: return health_pb2.HealthCheckResponse(status=status) def set(self, service, status): ...
NOTE, '' must be set. status: HealthCheckResponse.status enum value indicating the status of the service """ with self._server_status_lock: self._server_status[service] = status
nirmeshk/oh-mainline
mysite/profile/migrations/0097_auto__chg_field_unsubscribetoken_modified_date__del_field_citation_dis.py
Python
agpl-3.0
17,952
0.008021
# -*- 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 'UnsubscribeToken.modified_date' db.alter_column(u'prof...
self.gf('django.db.models.fields.IntegerField')(null=True), keep_default=False) models = { u'auth.group': { 'Meta': {'object_name': 'Group'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('djan...
ield', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, u'auth.permission': { 'Meta': {'ordering': "(u'content_type__app_label', u'con...
vasyarv/edx-ora2
openassessment/xblock/test/test_grade.py
Python
agpl-3.0
20,558
0.002636
# -*- coding: utf-8 -*- """ Tests for grade handlers in Open Assessment XBlock. """ import copy import ddt import json import mock from django.test.utils import override_settings from submissions import api as sub_api from openassessment.workflow import api as workflow_api from openassessment.assessment.api import peer...
def test_render_grade_feedback_only_criterion(self, xblock): #
Add in per-criterion feedback for the feedback-only criterion peer_assessments = copy.deepcopy(self.ASSESSMENTS) for asmnt in peer_assessments: asmnt['criterion_feedback'] = { u'𝖋𝖊𝖊𝖉𝖇𝖆𝖈𝖐 𝖔𝖓𝖑𝖞': u"Ṫḧïṡ ïṡ ṡöṁë ḟëëḋḅäċḳ." } self_assessment = cop...
XiaoxiaoLiu/morphology_analysis
IVSCC/morph_clustering_on_bbp_features_old_example.py
Python
gpl-3.0
37,767
0.013319
__author__ = 'xiaoxiaol' import numpy as np import pylab as pl import scipy import pandas as pd import seaborn as sns import os import sys, getopt from scipy.cluster import hierarchy import platform from scipy.stats.stats import pearsonr import scipy.stats as stats from PIL import Image import glob from sklearn.metri...
e(len(xnames)) tick_marksy = np.arange(len(ynames)) pl.xticks(tick_mark
sx, xnames) pl.yticks(tick_marksy, ynames) pl.tight_layout() pl.ylabel(ylabel) pl.xlabel(xlabel) def heatmap_plot_zscore_ivscc(df_zscore_features, df_all, output_dir, title=None): # Create a custom palette for dendrite_type colors dendrite_types = [np.nan, 'aspiny', 'sparsely spiny', 'spiny']...
cjaymes/pyscap
src/scap/model/oval_5/sc/linux/SystemDUnitDependencyItemElement.py
Python
gpl-3.0
1,135
0.002643
# Copyright 2016 Casey Jaymes # This file is part of PySCAP. # # PySCAP 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. # # PySCAP is ...
PySCAP. If not, see <http://www.gnu.org/licenses/>. import logging from scap.Model import Model from scap.model.oval_5.sc.ItemType import ItemType logger = logging.getLogger(__name__) class SystemDUnitDependencyItemElement(ItemType):
MODEL_MAP = { 'elements': [ {'tag_name': 'unit', 'class': 'scap.model.oval_5.sc.EntityItemType', 'min': 0, 'max': 1}, {'tag_name': 'dependency', 'class': 'scap.model.oval_5.sc.EntityItemType', 'min': 0, 'max': None}, ], }
jayGattusoNLNZ/DROID_comparer
DROID_export_comparer.py
Python
mit
1,579
0.019633
import csv import os #### make sure these file names are the same as the ones on your system baseline_csv = r"baseline.csv" new_csv = r"cleaned_csv.csv" ########### do not edit below this line ################# baseline_as_rows = [] new_as_rows = [] if not os.path.exists(baseline_csv): quit("The basel...
v: baseline_as_rows.append(row) with open(n
ew_csv) as new_data: new_rows = csv.reader(new_data) for row in new_rows: new_as_rows.append(row) if len(baseline_as_rows) != len(new_as_rows): quit("Your csv log file '{}' does not have the same number of rows as the baseline log '{}'.".format(new_csv, baseline_csv)) else: print "Your csv log...
jinverar/crits
crits/relationships/views.py
Python
mit
13,325
0.005854
import json from django.contrib.auth.decorators import user_passes_test from django.http import HttpResponse from django.shortcuts import render_to_response from django.template.loader import render_to_string from django.template import RequestContext from crits.core.user_tools import user_can_view_data from crits.re...
message': message} else: message = "Error adding relationship: %s" % results['me
ssage'] result = {'success': False, 'message': message} else: message = "Invalid Form: %s" % form.errors form = form.as_table() result = {'success': False, 'form': form, 'message': message} return HttpResponse(json.dumps(result), mimetype="application/...
longwosion/GitBundler
gitbundler/server.py
Python
bsd-2-clause
7,538
0.006235
#! /usr/bin/env python #coding=utf-8 import os from gitcmd import GitCmd from config import GitBundlerConfig class GitBundlerServer(object): def __init__(self): config = GitBundlerConfig() self.url = config.get('server.upload.url', verbose=False) self.user = config.get('serv...
http import register_openers import urllib2 register_openers() if os.path.exists(file): print " Uploading File:: %s" % file print " Server:: %s" % self.url
file = open(file, "rb") params = {'fileName': file} datagen, headers = multipart_encode(params) headers['gitbundler-user'] = self.user headers['gitbundler-password'] = self.password request = urllib2.Request(self.url, datagen, headers) re...
VIVEKLUCKY1848/gedit-plugins-1
plugins/synctex/synctex/__init__.py
Python
gpl-2.0
219
0.004566
import gi gi.r
equire_version('Gedit', '3.0') gi.require_version('Gtk', '3.0') gi.require_version('Peas', '1.0') gi.require_version('PeasGtk', '1.0') from .synctex import SynctexApp
Activatable, SynctexWindowActivatable
FXIhub/condor
examples/scripts/rotations/example.py
Python
bsd-2-clause
6,922
0.014447
import numpy try: import matplotlib.pyplot as pypl plotting = True except: plotting = False import os, shutil this_dir = os.path.dirname(os.path.realpath(__file__)) import condor import logging logger = logging.getLogger('condor') logger.setLevel("INFO") #logger.setLevel("DEBUG") out_dir = this_dir + "...
mpy.fft.fftshift(res["entry_1"]["data_1"]["data_fourier"]))) fourier_space = res["entry_1"]["data_1"]["data_fourier"] vmin = numpy.log10(res["entry_1"]["data_1"]["data"].max()/10000.) pypl.imsave(out_dir + "/%s_%2.2f.png
" % (s,angle_d), numpy.log10(res["entry_1"]["data_1"]["data"]), vmin=vmin) pypl.imsave(out_dir + "/%s_%2.2f_phases.png" % (s,angle_d), numpy.angle(fourier_space)%(2*numpy.pi)) pypl.imsave(out_dir + "/%s_rs_%2.2f.png" % (s,angle_d), abs(real_space))
gercordero/va_de_vuelta
src/resumen.py
Python
gpl-3.0
166
0.042169
import
pilas from aplicacion import App pilas.iniciar(ancho = 1280, alto = 800, titulo = "Aplicadion para Docente") pilas.cambiar_escen
a(App()) pilas.ejecutar()
leifos/treconomics
treconomics_project/treconomics/experiment_configuration.py
Python
mit
8,405
0.009756
__author__ = 'leif' import os import socket import logging import logging.config import logging.handlers from autocomplete_trie import AutocompleteTrie from ifind.search.engines.whooshtrec import Whooshtrec from experiment_setup import ExperimentSetup work_dir = os.getcwd() # when deployed this needs to match up with...
ttask/3/', 'taskspacer', 'snippetpretask/4/','taskspacerwithdetails/4/', 'search/4/', 'diversityposttask/4/','systemdiversityposttask/4/', 'taskspacer', 'diversityexitsurvey/', 'diversityperformance/', 'endexperiment/', 'logout/' ] jaana_flow = [ 'startexperiment/', 'preexperiment/UK/', 'de...
er2/0/', 'search/0/', 'postpracticetask/0/', 'taskspacer', 'snippetpretask/1/','taskspacer2/1/', 'search/1/', 'posttaskquestions/1/', 'taskspacer', 'snippetpretask/2/', 'taskspacer2/2/','search/2/', 'posttaskquestions/2/', 'taskspacer', 'performance/', 'endexperiment/', 'logout/' ] ...
spilkjir/CTGViewer
src/PyQwtNavigationPlot.py
Python
gpl-3.0
7,973
0.001255
# -*- coding: utf-8 -*- # # Created on Oct 15, 2013 # @authors: Jiri Spilka # http://people.ciirc.cvut.cz/~spilkjir # @2015, CIIRC, Czech Technical University in Prague # # Licensed under the terms of the GNU GENERAL PUBLIC LICENSE # (see CTGViewer.py for details) """ PyQwtNavigationPlot -------------------- The navi...
200) # the -1 is because of UCs with all zero values # self.setYMinMax(0, 300) self.canvasPicker = PyQwtCanvasPicker(self) self.canvasPicker.signal_point_clicked.connect(self.set_selected_point) self._step = 300*self.get_sampling_freq() # 300 = 5 minutes / for left-rigth arrow move ...
ared.connect(self.reinit) self.reinit() def reinit(self): # self._selected_point = 0 navplothighlight = PyQwtNavigationPlotHighlight(self) navplothighlight.attach(self) # cm = self.canvasMap(QwtPlot.xBottom) # self._pointFmin = self.invTransform(QwtPlot.xBottom, cm...
wittrup/crap
python/kal.py
Python
mit
1,302
0.004608
cmd = r"C:\Users\wittr\sdr\kalibrate-win-release\kal.exe" import os, re from subprocess import Popen, PIPE pattern_band = r'\s*band to scan\s*\((.+)\)' pattern_chan = r'(chan).+?(\d+).+?([\d.]+)(\w+).+?([\d.]+)(\w+).+?(\w+).+?([\d.]+)' process = Popen(cmd + ' -h', shell=True, stdout=P
IPE) # To use a pipe with the subprocess module, you have to pass shell=True (result, err) = process.communicate() process.wait() # Wait for p
rocess to finish result = str(result, encoding='ascii') matches = re.findall(pattern_band, result) results = {} for match in matches: bands = match.split(', ') for band in bands: process = Popen(cmd + ' -s ' + band, shell=True, stdout=PIPE, stderr=PIPE) # To use a pipe with the subprocess module, you...
danieljf24/cmrf
relevanceFusion.py
Python
mit
1,905
0.007874
import os import sys import numpy as np from basic.common import checkToSkip def process(options): overwrite = options.overwrite inputeFile = options.inputeFile weightFile = options.weightFile resultFile = options.resultFile weightFile = os.path.join('result', weightFile) weight...
re from different methods") parser.add_option("--weightFile", default='optimized_wights.txt', type="string", help="optimized wight will be written in the file") parser.add_option("--resultFile", default='fianl.result.txt', type="string", help="final score after relevance fusion") (options, args) = pars...
__main__": sys.exit(main())
karllessard/tensorflow
tensorflow/python/kernel_tests/lookup_ops_test.py
Python
apache-2.0
145,826
0.008771
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
-1, dtypes.int64) keys = constant_op.constant(["brain", "salad", "surgery"]) values = constant_op.constant([0, 1, 2], dtypes.int64) table = self.getHashTable()( lookup_ops.KeyValueTensorInitializer(keys, values), default_val) self.initialize_table(table) sp_indices = [[0, 0], [0, 1], [1, 0]...
tensor = sparse_tensor.SparseTensor( constant_op.constant(sp_indices, dtypes.int64), constant_op.constant(["brain", "salad", "tank"]), constant_op.constant(sp_shape, dtypes.int64)) output = table.lookup(input_tensor) out_indices, out_values, out_shape = self.evaluate(output)
tunegoon/asteria
manage.py
Python
mit
250
0
#!/usr/bin/env python import os import sys
if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "asteria.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
weaponsjtu/neteye
urls.py
Python
gpl-2.0
1,514
0.023118
from django.conf.urls.defaults import * #from pinax.apps.account import urls from django.conf import settings # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() from wangji.sharesite.models import Onesite info_dict = { 'queryset': Onesite.objects.all(), } url...
'wangji.sharesite.option.siteinfo'), (r'^$', 'wangji.sharesite.views.index'), (r'^snooker/$', 'wangji.sharesite.snooker.snooker'), (r'^sjtu/$', 'wangji.sharesite.snooker.index'), (r'^invite/$', 'wangji.sharesite.snooker.invite'), (r'^snooker/about/$', 'wangji.s
haresite.snooker.about'), (r'^snooker/players/$', 'wangji.sharesite.snooker.players'), (r'^snooker/clubs/$', 'wangji.sharesite.snooker.clubs'), (r'^snooker/voice/$', 'wangji.sharesite.snooker.voice'), # Uncomment the admin/doc line below to enable admin documentation: # (r'^admin/doc/', include('django.cont...
michsien/Learning_python
exercises _1-44/ex41.py
Python
mit
2,013
0.03378
import random from urllib import urlopen import sys WORD_URL = "http://learncodethehardway.org/words.txt" WORDS = [] PHRASES = { "class %%%(%%%):": "Make a class named %%% that is-a %%%.", "class %%%(object):\n\tdef __init__(self, ***)" : "class %%% has-a __init__ that takes self and *** parameters.", "class %...
urlopen(WORD_URL).readlines(): WORDS.append(word.strip()) def convert(snippet, phrase): class_names = [w.capitalize() for w in random.sample(WORDS, snippet.count("%%%"))] other_names = random.sample(WORDS, snippet.count("***")) results = [] param_names = [] for i in range(0, snippet.count("@@@")): para...
in snippet, phrase: result = sentence[:] #fake class names for word in class_names: result = result.replace("%%%", word, 1) #fake other names for word in other_names: result = result.replace("***", word, 1) #fake parameter lists for word in param_names: result = result.replace("@@@", word, 1...
rohitranjan1991/home-assistant
tests/components/homeassistant/test_scene.py
Python
mit
10,833
0.000831
"""Test Home Assistant scenes.""" from unittest.mock import patch import pytest import voluptuous as vol from homeassistant.components.homeassistant import scene as ha_scene from homeassistant.components.homeassistant.scene import EVENT_SCENE_RELOADED from homeassistant.const import STATE_UNKNOWN from homeassistant.s...
lo") is None assert await hass.services.async_call( "scene", "create", {"scene_id": "hallo", "snapshot_entities": ["light.my_light"]},
blocking=True, ) await hass.async_block_till_done() scene = hass.states.get("scene.hallo") assert scene is not None assert scene.attributes.get("entity_id") == ["light.my_light"] hass.states.async_set("light.my_light", "off", {"hs_color": (123, 45)}) turn_on_calls = async_mock_service(hass,...
yukihirai0505/tutorial-program
programming/python/machine-learning/ch02/and_gate01.py
Python
mit
198
0
def AND(x1, x2):
w1, w2, theta = 0.5, 0.5, 0
.7 tmp = x1 * w1 + x2 * w2 if tmp <= theta: print(0) elif tmp > theta: print(1) AND(0, 0) AND(1, 0) AND(0, 1) AND(1, 1)
chubbymaggie/datasketch
benchmark/lsh_benchmark.py
Python
mit
3,795
0.004743
import time, argparse, sys, json from sklearn.datasets import fetch_20newsgroups import numpy as np import scipy.stats from datasketch import MinHashLSH, MinHash from lshforest_benchmark import bootstrap_data, _compute_jaccard def benchmark_lsh(num_perm, threshold, index_data, query_data): print("Building LSH ind...
224, 256] output = {
"num_perms" : num_perms, "lsh_times" : [], "lsh_results" : [], "linearscan_times" : [], "linearscan_results" : [], "ground_truth_times" : None, "ground_truth_results" : None} index_data, query_data = bootstrap_data(num_perms, 1000, 500, scipy.stats.randint(10,...
RudolfCardinal/crate
crate_anon/nlp_manager/number.py
Python
gpl-3.0
1,874
0
#!/usr/bin/env python """ crate_anon/nlp_manager/number.py =============================================================================== Copyright (C) 2015-2021 Rudolf Cardinal (rudolf@pobox.com). This file is part of CRATE. CRATE is free software: you can redistribute it and/or modify it under t...
pt (TypeError, ValueError): return None def to_pos_float(s: str) -> Optional[float]: """ Converts a string to a positive f
loat, by using :func:`to_float` followed by :func:`abs`. Returns ``None`` on failure. """ try: return abs(to_float(s)) except TypeError: # to_float() returned None return None
moxuanchen/BMS
core/utils/vcode.py
Python
apache-2.0
1,445
0
# -*- coding: utf-8 -*- import hashlib import random import requests from flask import current_app class Vcode(object): @staticmethod def random_verification_code(): return ''.join(random.choice('0123456789') for i in range(6)) @staticmethod def generate_vcode_sign(data): SMS_SECRET...
URL'].format( sign=Vcode.generate_vcode_sign(data)), data=data) if resp.status_code == 200 and resp.json()['code'] == 0: return True else: print 'error:', str(resp), str(resp.json()) return False
@staticmethod def save_vcode_and_phone(phone, vcode): current_app.redis.set(phone, vcode) current_app.redis.expire(phone, 5 * 60) @staticmethod def get_vcode_by_phone(phone): return current_app.redis.get(phone)
gvlproject/libcloudbridge
cloudbridge/providers/aws/services.py
Python
mit
63,632
0
"""Services
implemented by the AWS provider.""" import ipaddress import logging import string import uuid from botocore.exceptions import ClientError import tenacity import cloudbridge.base.helpers as cb_helpers from cloudbridge.base.middleware import dispatch from cloudbridge.base.resources import ClientPagedResultList from cl...
m cloudbridge.base.services import BaseBucketService from cloudbridge.base.services import BaseComputeService from cloudbridge.base.services import BaseDnsRecordService from cloudbridge.base.services import BaseDnsService from cloudbridge.base.services import BaseDnsZoneService from cloudbridge.base.services import Bas...
codesmythe/gnucash
bindings/python/example_scripts/priceDB_test.py
Python
gpl-2.0
1,772
0.009594
#!/usr/bin/env python3 # Test file for price database stuff # To update the price database call # $PATH/gnucash --add-price-quotes $PATHTOFILE # before running this. # Adding to a calling bash script would be better # Although calling it from here would be even better! # OR: export PYTHONPATH=<path-to-gnucash-inst-d...
rom gnucash import Session # FILE should be the path to your existing gnucash file/database # For a file, simply pass the pathname, for a database you can use # these forms: # mysql://user:password@host/dbname # postgres://user:passw
ord@host[:port]/dbname (the port is optional) # FILE = "PATH_TO_YOUR_TEST_FILE" ## Fail is not saved but use a copy anyway session = Session(FILE, True, False, False) root = session.book.get_root_account() book = session.book pdb = book.get_price_db() comm_table = book.get_table() gbp = comm_table.lookup("CURRENCY",...
chenjun0210/tensorflow
tensorflow/contrib/learn/python/learn/estimators/state_saving_rnn_estimator_test.py
Python
apache-2.0
26,488
0.002303
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
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. # ============================================================================== """Tests for learn.estimators...
nsorflow.contrib import lookup from tensorflow.contrib.layers.python.layers import feature_column from tensorflow.contrib.layers.python.layers import target_column as target_column_lib from tensorflow.contrib.learn.python.learn.estimators import constants from tensorflow.contrib.learn.python.learn.estimators import mod...
rhinstaller/blivet-gui
tests/blivetgui_tests/utils_test.py
Python
gpl-2.0
5,595
0.003932
# -*- coding: utf-8 -*- import unittest from unittest.mock import MagicMock, patch from blivetgui.blivet_utils import BlivetUtils, FreeSpaceDevice from blivetgui.i18n import _ from blivet.size import Size class FreeSpaceDeviceTest(unittest.TestCase): def test_free_basic(self): free = FreeSpaceDevice(f...
=True, format=MagicMock(type=None)) free = FreeSpaceDevice(free_size=Size("8 GiB"), dev_id=0, start=0, end=1, parents=[disk]) self.assertEqual(free.disk, disk) # free space in a vg parent = MagicMock(type="lvmvg", children=[], is_disk=False, format=MagicMock
(type=None), parents=[MagicMock(type="partition", children=[MagicMock()], is_disk=False, parents=[disk], format=MagicMock(type="lvmpv"))]) free = FreeSpaceDevice(free_size=Size("8 GiB"), dev_id=0, start=0, end=1, parents=[parent]) self.asser...
thomas-sterrenburg/fingerprinting-python
src/main.py
Python
mit
16,603
0.002831
# Copyright 2017 Thomas Sterrenburg # # Licensed under the MIT License (the License); you may not # use this file except in compliance with the License. You may obtain a copy # of the License at https://opensource.org/licenses/MIT# import glob import re import sys import time from src.io.storage import get_request_i...
s('MALFORMED_' + ('000' + str(index))[-3:], response, fingerprint, host, host_index) def get_malformed_methods(): activities = 'GET', 'HEAD', 'POST', 'PUT' malformed_methods_list = [] for activity in a
ctivities: malformed_methods = ( activity, activity + '/', activity + '/1.0', activity + ' / HTTP/123.45', activity + ' / HTTP/999.99', activity + ' / HTP/1.0', activity + ' / HTT/1.0', activity + ' / HTTP/7.Q', ...
RajShahCrazy/youtube-dl
youtube_dl/__main__.py
Python
unlicense
390
0.002564
#!/usr/bin/env python # Execute with # $ python youtube_dl/__main__.py (2.6+) # $ pytho
n -m youtube_dl (2.7+) import sys if __package__ is None and not hasattr(sys, "frozen"): # direct call of __main__.py import os.path sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import youtube_dl if __name__ == '__main__': youtube_dl.
main()
MichaelAquilina/numpy
numpy/core/tests/test_multiarray.py
Python
bsd-3-clause
220,691
0.001137
from __future__ import division, absolute_import, print_function import collections import tempfile import sys import shutil import warnings import operator import io import itertools if sys.version_info[0] >= 3: import builtins else: import __builtin__ as builtins from decimal import Decimal import numpy as...
size, 20) assert_equal(self.two.nbytes, 20*num) assert_equal(self.two.itemsize, self.two.dtype.itemsize) assert_equal(self.two.base, np.arange(20)) def test_dtypeattr(self): assert_equal(self.one.dtype, np.dtype(np.int_)) assert_equal(self.three.dtype, np.dtype(np.float_)) ...
r, 'd') self.assertTrue(self.three.dtype.str[0] in '<>') assert_equal(self.one.dtype.str[1], 'i') assert_equal(self.three.dtype.str[1], 'f') def test_int_subclassing(self): # Regression test for https://github.com/numpy/numpy/pull/3526 numpy_int = np.int_(0) if sys...
jan-huiskes/Project
data/csv2json.py
Python
gpl-3.0
1,876
0.002665
# Jan Huiskes # 10740929 import csv import json import sys reload(sys) sys.setdefaultencoding('utf8') js
onfile = open('data.json', 'w') csvfile3 = open('data.csv', 'r') def p2f(x): return float(x.strip('%')) jsonfile.write('{"data" : {') jsonfile.write('\n') i = 0 for row in csvfile3: row = row.split() if len(row) == 12: j = 1 else: j = 0 jsonfile.write('"' + row[10 + j] + '": {') ...
write('\n') jsonfile.write('"kiesman": ' + row[7 + j] + ',') elif int(row[7 + j]) == 0: jsonfile.write('"fillKey": "democrat",') jsonfile.write('\n') jsonfile.write('"kiesman": ' + row[4 + j] + ',') else: jsonfile.write('"fillKey": "tot",') jsonfile.write('\n') ...
rbnvrw/FRAPalyzer
test.py
Python
mit
258
0.003876
import nose from
os import path file_path = path.abspath(__file__) tests_path = path.join(path.abspath(path.dirname(file_path)), "tests") nose.main(argv=[path.abspath(__file__), "--with-coverage", "--cover-erase", "--cover-packa
ge=frapalyzer", tests_path])
asifr/pmquery
pmquery.py
Python
mit
6,143
0.030288
# -*- coding: utf-8 -*- #!/usr/bin/env python ''' pmquery - Query PubMed and download results to text files ## Requirements If you don't have the pip utility first install it with: > easy_install pip Install all the mandatory dependencies by typing: > pip install -r requirements.txt ## Usage Before running the scri...
0, '') issue = journalIssue.getElementsByTagName('Issue') issue = parse_xml(issue, 0, '') pages = xmldoc.getElementsByTagName('MedlinePgn') pages = parse_xml(pages, 0, '') jsonout.append({ 'pmid':pmid, 'title':title, 'authors':authorlist, 'journal':j
ournal, 'year':year, 'volume':volume, 'issue':issue, 'pages':pages, 'abstract':abstract }) return json.dumps(jsonout) # Prepare to query E-Search utilsparams = { 'db':database, 'tool':tool, 'email':email, 'term':term, 'usehistory':'y', 'retmax':retmax, 'retstart':retstart } url = ...