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
haandol/assemblyapi
main/views.py
Python
apache-2.0
215
0.013953
#coding: utf-8 from
django.http import HttpResponse from django.shortcuts import
render def index(request): return HttpResponse('UnderConstruction') def help(request): return render(request, 'help.html')
singingwolfboy/webhookdb
webhookdb/tasks/label.py
Python
agpl-3.0
4,696
0.000426
# coding=utf-8 from __future__ import unicode_literals, print_function from datetime import datetime from celery import group from urlobject import URLObject from webhookdb import db, celery from webhookdb.process import process_label from webhookdb.models import IssueLabel, Repository, Mutex from webhookdb.exceptions...
p( sync_page_of_labels.s( owner=owner, repo=repo, requestor_id=requestor_id, per_page=per_page
, page=page ) for page in xrange(1, last_page_num+1) ) finisher = labels_scanned.si( owner=owner, repo=repo, requestor_id=requestor_id, ) return (g | finisher).delay()
jiadaizhao/LeetCode
0301-0400/0394-Decode String/0394-Decode String.py
Python
mit
1,173
0.002558
class Solution: def decodeString(self, s: str) -> str: St = [] num = 0 curr = '' for c in s: if c.isdigit(): num = num*10 + int(c) elif c == '[': St.append([num, curr
]) num = 0 curr = '' elif c == ']': count, prev = St.pop() curr = prev + count*curr else: curr += c return curr class Solution2: def decodeString(self, s: str) -> str: i = 0 def decode(s)...
nlocal i result = [] while i < len(s) and s[i] != ']': if s[i].isdigit(): num = 0 while i < len(s) and s[i].isdigit(): num = num*10 + int(s[i]) i += 1 ...
SamiHiltunen/invenio-upgrader
invenio_upgrader/upgrades/invenio_2013_06_24_new_bibsched_status_table.py
Python
gpl-2.0
1,112
0
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2012 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 option) any later version. # # Invenio is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without
even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Invenio; if not, write to the Free Software Foundation, Inc., # 59 Temple Place, Suite 330, Bost...
gares/coq
doc/tools/coqrst/coqdomain.py
Python
lgpl-2.1
54,478
0.003572
########################################################################## ## # The Coq Proof Assistant / The Coq Development Team ## ## v # Copyright INRIA, CNRS and contributors ## ## <O___,, # (see version control and CREDITS file for authors & dates) ## ## \VV/ #########...
ons are numbered node['nowrap'] = nowrap nod
e['docname'] = docname node['number'] = None return node class CoqObject(ObjectDescription): """A generic Coq object for Sphinx; all Coq objects are subclasses of this. The fields and methods to override are listed at the top of this class' implementation. Each object supports the :name: option, ...
agustinhenze/nikola.debian
tests/test_rst_compiler.py
Python
mit
10,799
0.000556
# coding: utf8 # Author: Rodrigo Bistolfi # Date: 03/2013 """ Test cases for Nikola ReST extensions. A base class ReSTExtensionTestCase provides the tests basic behaivor. Subclasses must override the "sample" class attribute with the ReST markup. The sample will be rendered as HTML using publish_parts() by setUp(). O...
oundcloud.com" "/player/?url=http://" "api.soundcloud
.com/" "tracks/SID"), "height": "400", "width": "600"}) class VimeoTestCase(ReSTExtensionTestCase): """Vimeo test. Set Vimeo.request_size to False for avoiding querying the Vimeo api over the network """ ...
agoravoting/authapi
authapi/captcha/urls.py
Python
agpl-3.0
874
0.001144
# This file is part of authapi. # Copyright (C) 2014-2020 Agora Voting SL <[email protected]> # authapi is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public Lic
ense as published by # the Free Software Foundation, either version 3 of the License. # authapi is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for mo...
go.conf.urls import url from .decorators import captcha_required from captcha import views urlpatterns = [ url(r'^new/', views.new_captcha, name='new_captcha'), ]
SamHames/scikit-image
skimage/feature/texture.py
Python
bsd-3-clause
10,468
0.000287
""" Methods to characterize image textures. """ import numpy as np from ._texture import _glcm_loop, _local_binary_pattern def greycomatrix(image, distances, angles, levels=256, symmetric=False, normed=False): """Calculate the grey-level co-occurrence matrix. A grey level co-occurence matr...
result[:, :, 0, 3] array([[2, 0, 0, 0], [1, 1, 2, 0], [0, 0, 2, 1], [0, 0, 0, 0]], dtype=uint32) """
assert levels <= 256 image = np.ascontiguousarray(image) assert image.ndim == 2 assert image.min() >= 0 assert image.max() < levels image = image.astype(np.uint8) distances = np.ascontiguousarray(distances, dtype=np.float64) angles = np.ascontiguousarray(angles, dtype=np.float64) a...
Yelp/paasta
paasta_tools/setup_kubernetes_job.py
Python
apache-2.0
7,313
0.00082
#!/usr/bin/env python # Copyright 2015-2018 Yelp 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 ...
id(service_instance) except InvalidJobNameError: log.error( "Invalid service instance specified. Format is service%sinstance." % SPACER ) return Fals
e return True def setup_kube_deployments( kube_client: KubeClient, service_instances: Sequence[str], cluster: str, rate_limit: int = 0, soa_dir: str = DEFAULT_SOA_DIR, ) -> bool: if service_instances: existing_kube_deployments = set(list_all_deployments(kube_client)) existi...
sonya/eea
py/run_usa.py
Python
apache-2.0
111
0.027027
#!/usr/bin/python3 #import usa.matrices #import usa.total_energy import usa.emissions #imp
ort
usa.food_sector
os2webscanner/os2webscanner
django-os2webscanner/os2webscanner/__init__.py
Python
mpl-2.0
53
0
"""Django module for the
OS2datascanner project."
""
junhuac/MQUIC
src/tools/android/loading/user_satisfied_lens.py
Python
mit
5,080
0.006496
# Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Identifies key events related to user satisfaction. Several lenses are defined, for example FirstTextPaintLens and FirstSignificantPaintLens. """ import ...
rack.GetEvents() if e.Matches('blink.user_timing', 'firstContentfulPaint')] self._satisfied_msec = self._event_msec = \ self._ExtractFirstTiming(first_paints) class FirstSignificantPaintLens(_FirstEventLens): """Define satisfaction by the first paint after a big layout change. Our ...
e layout. Our event time is that of the next paint as that is the observable event. """ FIRST_LAYOUT_COUNTER = 'LayoutObjectsThatHadNeverHadLayout' def _CalculateTimes(self, tracing_track): sync_paint_times = [] layouts = [] # (layout item count, msec). for e in tracing_track.GetEvents(): # ...
Fokko/incubator-airflow
airflow/operators/pig_operator.py
Python
apache-2.0
2,775
0
# -*- coding: utf-8 -*- # # 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 #...
ating ${var} gets translated into jinja-type templating {{
var }}. Note that you may want to use this along with the ``DAG(user_defined_macros=myargs)`` parameter. View the DAG object documentation for more details. :type pigparams_jinja_translate: bool :param pig_opts: pig options, such as: -x tez, -useHCatalog, ... :type pig_opts: str ...
ProjexSoftware/projex
setup.py
Python
lgpl-3.0
2,436
0.004516
import os import re import subprocess from setuptools import setup, find_packages, Command try: with open('projex/_version.py', 'r') as f: content = f.read() major = re.search('__major__ = (\d+)', content).group(1) minor = re.search('__minor__ = (\d+)', content).group(1) rev = re.s...
, version=version, author='Eric Hulser', author_email='[email protected]', maintainer='Eric Hulser', maintainer_email='[email protected]', description='Library of useful utilities for Python.', license='MIT', keywords='', url='https://github.com/ProjexSoftware/projex', in...
ong_description='Library of useful utilities for Python.', classifiers=[], )
paninetworks/neutron
neutron/services/l3_router/brocade/mlx/l3_router_plugin.py
Python
apache-2.0
2,212
0
# Copyright 2015 Brocade Communications 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.org/licenses/LICENSE-2.0 # ...
he MLX switch')), cfg.StrOpt('username', default='admin', help=('The SSH username of the switch')), cfg.StrOpt('password', default='password', secret=True, help=('The SSH password of the switch')), cfg.StrOpt('physical_networks'...
h')), cfg.StrOpt('ports', default='', help=('Ports to be tagged in the VLAN being ' 'configured on the switch')), ] cfg.CONF.register_opts(SWITCHES, 'l3_brocade_mlx') cfg.CONF.register_opts(L3_BROCADE, 'L3_BROCADE_MLX_EXAMPLE') class ...
wujuguang/scrapy
tests/test_pipeline_files.py
Python
bsd-3-clause
16,352
0.00263
import os import random import time import hashlib import warnings from tempfile import mkdtemp from shutil import rmtree from six.moves.urllib.parse import urlparse from six import BytesIO from twisted.trial import unittest from twisted.internet import defer from scrapy.pipelines.files import FilesPipeline, FSFilesS...
self.assertEqual(file_path(Request("https://dev.mydeco.com/mydeco.pdf")), 'full/c9b564df929f4bc63
5bdd19fde4f3d4847c757c5.pdf') self.assertEqual(file_path(Request("http://www.maddiebrown.co.uk///catalogue-items//image_54642_12175_95307.txt")), 'full/4ce274dd83db0368bafd7e406f382ae088e39219.txt') self.assertEqual(file_path(Request("https://dev.mydeco.com/two/dirs/with%20space...
vitay/ANNarchy
ANNarchy/generator/Sanity.py
Python
gpl-2.0
13,045
0.006439
#=============================================================================== # # Sanity.py # # This file is part of ANNarchy. # # Copyright (C) 2013-2016 Julien Vitay <[email protected]>, # Helge Uelo Dinkelbach <[email protected]> # # This program is free software: you can redist...
d 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 thi...
==================================== import re from ANNarchy.core import Global from ANNarchy.core.PopulationView import PopulationView from ANNarchy.models.Synapses import DefaultSpikingSynapse, DefaultRateCodedSynapse # No variable can have these names reserved_variables = [ 't', 'dt', 't_pre', '...
umitproject/network-admin
netadmin/events/search_indexes.py
Python
agpl-3.0
1,285
0
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2011 Adriano Monteiro Marques # # Author: Piotrek Wasilewski <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of t
he GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even
the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from models import Event tr...
cmouse/buildbot
master/buildbot/reporters/words.py
Python
gpl-2.0
50,996
0.001452
# coding: utf-8 # This file is part of Buildbot. Buildbot 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, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRA...
import server from buildbot import util from buildbot import version from buildbot.data import resultspec from buildbot.plugins.db import get_plugins from buildbot.process.properties impo
rt Properties from buildbot.process.results import CANCELLED from buildbot.process.results import EXCEPTION from buildbot.process.results import FAILURE from buildbot.process.results import RETRY from buildbot.process.results import SKIPPED from buildbot.process.results import SUCCESS from buildbot.process.results impo...
dmlc/tvm
tests/python/relay/aot/aot_test_utils.py
Python
apache-2.0
30,132
0.002323
# 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...
erface valid_combinations = filter( lambda parameters: not (parameters[0] == "c" and not parameters[1]), all_combinations, ) # Only use reference system for C interface and unpacked API calls valid_combinations = filter( lambda parameters: not ( parameters[2] == AOT_...
valid_combinations, ) # Skip reference system tests if running in i386 container marked_combinations = map( lambda parameters: pytest.param(*parameters, marks=[skip_i386, requires_arm_eabi]) if parameters[2] == AOT_CORSTONE300_RUNNER else parameters, valid_combinatio...
dmnfarrell/smallrnaseq
smallrnaseq/config.py
Python
gpl-3.0
4,475
0.01676
#!/usr/bin/env python # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 3 # of the License, or (at your option) any later version. # # This program is distributed in the hope that ...
NTY; 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 this program; if not, write to the Free Software # Foundatio
n, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ Module for smallrnaseq configuration file. Used with command line app. Created Jan 2017 Copyright (C) Damien Farrell """ from __future__ import absolute_import, print_function import sys, os, string, time import types, re, subprocess, glob, shutil i...
jvrsantacruz/XlsxWriter
xlsxwriter/test/comparison/test_hyperlink14.py
Python
bsd-2-clause
1,222
0.000818
############################################################################### # # Tests for XlsxWriter. # # Copyright (c),
2013-2015, John McN
amara, [email protected] # from ..excel_comparsion_test import ExcelComparisonTest from ...workbook import Workbook class TestCompareXLSXFiles(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.maxDiff = None filena...
adhoc-dev/odoo-logistic
addons/logistic_x/__init__.py
Python
agpl-3.0
1,161
0
# -*- coding: utf-8 -*- ############################################################################## # # Ingenieria ADHOC - ADHOC SA # https://launchpad.net/~ingenieria-adhoc # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public Lice...
es_partner import waybill_expense import account_invoice
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
wolfstein9119/django-russian-fields
russian_fields/gender.py
Python
bsd-2-clause
975
0
from django.db import models from django.core.validators import MinLengthValidator from django.utils.translation import ugettext_lazy as _ class GENDERField(models.CharField): description = 'Gender' DEFAULT_MAX_LENGTH = DEFAULT_MIN_LENGTH =
1 GENDER_MALE = 'M' GENDER_FEMALE = 'F' GENDER_CHOICES = ( (GENDER_MALE, _('Male')), (GENDER_FEMALE, _('Female')), ) def __init__(self, *args, **kwargs): max_length = self.DEFAULT_MAX_LENGTH min_length = self.DEFAULT_MIN_LENGTH kwargs['max_length'] = max_le...
elf.GENDER_CHOICES super(GENDERField, self).__init__(*args, **kwargs) self.validators.extend([ MinLengthValidator(min_length), ]) def deconstruct(self): name, path, args, kwargs = super(GENDERField, self).deconstruct() del kwargs['max_length'] del kwargs[...
ForestClaw/forestclaw
applications/clawpack/advection/2d/swirl/p_00002.py
Python
bsd-2-clause
454
0.028634
# comment = "Torus example : eff. resolution = 2048 x 2048" import sys import os import subprocess import random np = 2 exec = "
swirl" arg_list = ["mpirun","-n",str(np),exec,"--inifile=timing.ini"] jobid = random.randint(1000,9999) outfile = "{:s}_0000{:d}.o{:d}".format(exec,np,jobid) f = open(outfile,'w') po = subprocess.Popen(arg_list,stdout=f) print("Starting process {:d} with jobid {:d} on {:d} processor(s).".format(po.pid,jobid,np)) #po.wa...
WhiteMagic/JoystickGremlin
container_plugins/double_tap/__init__.py
Python
gpl-3.0
13,349
0.000075
# -*- coding: utf-8; -*- # Copyright (C) 2015 - 2019 Lionel Ott # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # T...
ble-tap delay: </b>") ) self.delay_input = gremlin.ui.common.DynamicDoubleSpinBox() self.delay_input.setRange(0.1, 2.0)
self.delay_input.setSingleStep(0.1) self.delay_input.setValue(0.5) self.delay_input.setValue(self.profile_data.delay) self.delay_input.valueChanged.connect(self._delay_changed_cb) self.options_layout.addWidget(self.delay_input) self.options_layout.addStretch() # Act...
Aravinthu/odoo
addons/mail/controllers/bus.py
Python
agpl-3.0
3,026
0.003966
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import SUPERUSER_ID from odoo.http import request, route from odoo.addons.bus.controllers.main import BusController class MailChatController(BusController): def _default_request_uid(self): """ Fo...
id])]): channels.append((request.db, 'mail.channel', mail_channel.id)) # personal and needaction channel channels.append((request.db, 'res.partner', partner_id)) channels.append((request.db, 'ir.needaction', partner_id)) return super(MailChatCo...
----------- # Anonymous routes (Common Methods) # -------------------------- @route('/mail/chat_post', type="json", auth="none") def mail_chat_post(self, uuid, message_content, **kwargs): request_uid = self._default_request_uid() # find the author from the user session, which can be None...
IllusionRom-deprecated/android_platform_tools_idea
python/testData/formatter/continuationIndentForCallInStatementPart_after.py
Python
apache-2.0
108
0.009259
for item in really_long_name_of_the_function_wit
h_a_lot_of_pat
ams( param1, param2, param3): pass
toomoresuch/pysonengine
parts/gaeunit/test/HtmlTestCaseTest.py
Python
mit
3,299
0.003637
''' Created on May 5, 2009 @author: george ''' import unittest import gaeunit class Test(unittest.TestCase): tc = gaeunit.GAETestCase("run") def test_html_compare_ignorable_blank(self): html1 = """ <div> test text </div> """ html2 = """<div>test text</div>""" self...
result = self.tc._findHtmlDifference(html
1, html2) self.assertEqual(result, result_expected) def test_findHtmlDifference_long(self): html1 = "aaaaabbbbbcccccdddddeeeeefffffggggghhhhhiiiiijjjjjkkkkk" html2 = "aaaaabbbbbcccccdddddeeeeeeffffggggghhhhhiiiiijjjjjkkkkk" result_expected = "\n...bbbbbcccccdddddeeeeefffffggggghhhhh...
uiureo/demae
tests/test_util.py
Python
mit
245
0
from demae.util import split_size def test_split_size(): assert split_size(list(range(6)), 3) == [[0, 1], [2, 3], [4, 5]] assert spli
t_size(list(range(7)), 3) == [[0, 1], [2, 3], [4, 5,
6]] assert split_size([], 3) == [[], [], []]
cernbox/entf
IO_testing/payload_gen.py
Python
agpl-3.0
4,528
0.006405
#------------------------------------------------------------------------------- # Produce random files # Support file to generate content #------------------------------------------------------------------------------- #from PIL import Image import numpy import uuid import array import os import random, tempfile ...
2.0: break
else: break # got it! return fname ''' #------------------------------------------------------------------------------- # Produces a random text from the word_list given the size in bytes. # Returns exactly this amount of bytes, eventually truncating a word. #-------------------------...
alviano/wasp
tests/asp/cautious/count.example5.cautious.asp.test.py
Python
apache-2.0
418
0
input = """ 1 2 0 0 1 3 0 0
1 4 0 0 1 5 0 0 1 6 2 1 7 8 1 7 2 1 6 8 1 8 0 0 1 9 2 1 10 11 1 10 2 1 9 11 1 11 0 0 1 12 2 1 13 14 1 13 2 1 12 14 1 14 0 0 1 15 2 1 16 17 1 16 2 1 15 17 1 17 0 0 2 18 2 0 2 12 6 1 1 1 0 18 2 19 2 0 2 15 9 1 1 1 0 19 0 6 a(b,2) 9 a(b,1) 12 a(a,2) 15 a(a,1) 4 c(a) 5 c(b) 7 na(b,2) 10 na(b,1) 13 na(a,2) 16 na(a,1) 2 b(1...
)} """
Ruben0001/Mango
setup.py
Python
mit
1,060
0
import codecs import os from distutils.core import setup HERE = os.path.abspath(os.path.dirname(__file__)) def read(*parts): """ Build an absolute path from *parts* and and ret
urn the contents of the resulting file. Assume UTF-8 encoding. """ with codecs.open(os.path.join(HERE, *parts), "rb", "utf-8") as f: return f.read() setup( name='kik', version='1.2.0', packages=['kik', 'kik.messages'], package_dir={ 'kik': 'kik',
'kik.messages': 'kik/messages' }, author='kik', author_email='[email protected]', url='https://dev.kik.com', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Topic :: Software D...
aweisberg/cassandra-dtest
largecolumn_test.py
Python
apache-2.0
3,367
0.003861
import pytest import re import logging from dtest import Tester since = pytest.mark.since logg
er = logging.getLogger(__name__) @since('2.2') class TestLargeColumn(Tester): """ Check that inserting and reading large columns to the database doesn't cause off heap memory usage that is proportional to the size of the memory read/written. """ def stress_with_col_size(self, cluster, node, size)...
hema", "replication(factor=2)", "-col", "n=fixed(1)", "size=fixed(" + size + ")", "-rate", "threads=1"]) node.stress(['read', 'n=5', "no-warmup", "cl=ALL", "-pop", "seq=1...5", "-schema", "replication(factor=2)", "-col", "n=fixed(1)", "size=fixed(" + size + ")", "-rate", "threads=1"]) def directbytes(self,...
mandli/surge-examples
michael/setplot.py
Python
mit
11,195
0.002144
""" Set up the plot figures, axes, and items to be done for each frame. This module is imported by the plotting routines and then the function setplot is called to set the plot parameters. """ import os import numpy as np import matplotlib.pyplot as plt import datetime from clawpack.geoclaw.util import fetch...
============================================== # ========================================================================== # Loop over region specifications ploting both surface and speeds for re
gion in regions: name = region['name'] xlimits = region['limits'][0] ylimits = region['limits'][1] # ====================================================================== # Surface Elevations # ====================================================================== ...
Gaulois94/python-sfml
examples/spacial_music/spacial_music.py
Python
lgpl-3.0
3,151
0.025071
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # pySFML - Python bindings for SFML # Copyright 2012-2013, Jonathan De Wachter <[email protected]> # # This software is released under the LGPLv3 li
cense. # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import sfml as sf def main(song): window = sf.RenderWindow(sf.VideoMode(600, 600), "pySFML - Spacial Music") window.framerate_limit = 60 # load one font, one so...
try: font = sf.Font.from_file("data/sansation.ttf") music = sf.Music.from_file(song) texture = sf.Texture.from_file("data/speaker.gif") speaker = sf.Sprite(texture) speaker.position = -texture.size // 2 texture = sf.Texture.from_file("data/head_kid.png") hears = sf.Sprite(texture) hears.origin = tex...
antepsis/anteplahmacun
sympy/core/numbers.py
Python
bsd-3-clause
106,958
0.000524
from __future__ import print_function, division import decimal import fractions import math import re as regex from collections import defaultdict from .containers import Tuple from .sympify import converter, sympify, _sympify, SympifyError from .singleton import S, Singleton from .expr import Expr, AtomicExpr from ....
aching mechanism impleme
nted. Examples ======== >>> from sympy.core.numbers import igcd >>> igcd(2, 4) 2 >>> igcd(5, 10, 15) 5 """ if len(args) < 2: raise TypeError( 'igcd() takes at least 2 arguments (%s given)' % len(args)) if 1 in args: a = 1 k = 0 else: ...
FRC830/opencv-tools
camera.py
Python
mit
3,853
0.001557
from __future__ import division, print_function, unicode_literals import cv2 import os import threading import time import script try: # Python 3 import queue except ImportError: # Python 2 import Queue as queue class Camera(object): def __init__(self, id, fps=20, width=640, height=480): ...
v2.cv.CV_CAP_PROP_FRAME_WIDTH) height = capture_property('height', cv2.cv.CV_CAP_PROP_FRAME_HEIGHT) def __getattr__(self, attr): """ Fall back to CaptureThread attributes """ return getattr(self.cap_thread, attr) class CaptureThread(threading.Thread): _read_lock = threading.Lock() if ...
GE']) def __init__(self, camera): super(CaptureThread, self).__init__() self.parent_thread = threading.current_thread() self.camera = camera self._running = False self.cap = cv2.VideoCapture(camera.id) self.opt_queue = queue.Queue() self.image_lock = threadi...
fxstein/SentientHome
feed/feed.home.zillow.py
Python
apache-2.0
2,755
0.000363
#!/usr/local/bin/python3 -u """ Author: Oliver Ratzesberger <https://github.com/fxstein> Copyright: Copyright (C) 2016 Oliver Ratzesberger License: Apache License, Version 2.0 """ # Make sure we have access to SentientHome commons import os import sys try: sys.path.append(os.path.dirname(os.pat...
sd}zestimate'][ 'response']['zestimate'] local_data = data[ '{http://www.zillow.com/static/xsd/Zestimate.xsd}zestimate'][
'response']['localRealEstate'] event = [{ 'measurement': 'zillow', 'tags': { 'zpid': request_data['zpid'], 'region': local_data['region']['@name'], 'region_type': local_data['region']['@type'], }, 'fields': {...
jimmynl/hadafuna
tests/core/test_game.py
Python
mit
174
0
from unit
test2 import TestCase, main from hadafuna.core.game import KoikoiGame class KoikoiGameTest(TestCase): pass if __name__ == '__main__': main
(verbosity=2)
ovresko/erpnext
erpnext/setup/doctype/setup_progress/test_setup_progress.py
Python
gpl-3.0
219
0.009132
# -*- coding: utf-8 -*- # Copyright (c) 2017, Fra
ppe Technologies Pvt. Ltd. and Contributors # See license.txt from __future__ import unicode_literals import unittest class TestSetupProgres
s(unittest.TestCase): pass
kamal-gade/rockstor-core
manage.py
Python
gpl-3.0
251
0
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "RockStor.settings") from
django.core.management import execute_fr
om_command_line execute_from_command_line(sys.argv)
goptavares/aDDM-Toolbox
addm_toolbox/ddm_mla_test.py
Python
gpl-3.0
5,299
0.000189
#!/usr/bin/env python """ Copyright (C) 2017, California Institute of Technology This file is part of addm_toolbox. addm_toolbox 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, ...
for parameter sigma. trialsFileName: string, path of trial conditions file. numTrials: int, number of artificial data trials
to be generated per trial condition. numSimulations: int, number of simulations to be generated per trial condition, to be used in the RT histograms. binStep: int, size of the bin step to be used in the RT histograms. maxRT: int, maximum RT to be used in the RT histograms. n...
galileo-project/Galileo-dockyard
server/dockyard/driver/task/_model/__init__.py
Python
mit
137
0
from dockyard.utils.mongo im
port Mongo class Task(Mongo): """ channel msg receivers
expire """
seblefevre/testerman
plugins/probes/configurationfile/__init__.py
Python
gpl-2.0
30
0
impo
rt ConfigurationFilePro
be
stefanschramm/osm_oepnv_validator
rn.py
Python
gpl-3.0
4,325
0.024509
#!/usr/bin/env python # -*- coding: utf-8 -*- # rn.py - load network of routes from OSM # # Copyright (C) 2012, Stefan Schramm <[email protected]> # # 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 Fou...
): # callback: collect routes to validate for relation in relations: rid, tags, members = relation if self.relation_filter(relation): self.relations[rid] = relation for member in members: mid, typ, role = member if typ == "node": self.nodes[mid] = None if typ == "way": self....
lf.parents[(typ, mid)] = [("relation", rid)] else: self.parents[(typ, mid)].append(("relation", rid)) def ways_cb(self, ways): # callback: collect interesting ways for way in ways: wid, tags, nodes = way if wid in self.ways and self.ways[wid] == None: self.ways[wid] = way for nid in nodes...
silent1mezzo/jeeves-framework
jeeves/conf/project_template/bot.py
Python
isc
246
0
#!/usr/bin/env python import
os import sys if __name__ == "__main__": os.environ.setdefault("JEEVES_SETTINGS_MODULE", "settings")
from jeeves.core.management import execute_from_command_line execute_from_command_line(sys.argv[1:])
geometer/book_tools
encrypt.py
Python
mit
1,584
0.005051
#!/usr/bin/python import shutil, string, sy
s, tempfile from argparse import ArgumentParser f
rom fbreader.format.epub import EPub def verify_key(key, name): if len(key) != 32: raise Exception('Incorrect %s length %d, 32 expected' % (name, len(key))) for sym in key: if not sym in string.hexdigits: raise Exception('Incorrect character %s in %s' % (sym, name)) def parse_comma...
openstack/python-tackerclient
tackerclient/tacker/v1_0/nfvo/vim.py
Python
apache-2.0
4,822
0
# Copyright 2016 Brocade Communications 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.org/licenses/LICENSE-2.0 # ...
gument( '--is-default', type=strutils.bool_from_string, metavar='{True,False}', help=_('Indicate whether the VIM is used as default')) def args2body(self, parsed_args): body = {self.resource: {}} config_param = None # config arg passed as d
ata overrides config yaml when both args passed if parsed_args.config_file: with open(parsed_args.config_file) as f: config_yaml = f.read() try: config_param = yaml.load(config_yaml, Loader=yaml.SafeLoader) ...
gijs/solpy
solpy/summary.py
Python
lgpl-2.1
787
0.012706
"""summerize pv systems""" import argparse import pv import os import datetime parser = argpars
e.ArgumentParser() parser.add_argument('--verbose', '-v', action='count')
parser.add_argument('files', nargs='*') args = parser.parse_args() total_dc = 0 sdate = datetime.datetime(2014,6,16) for i in args.files: try: plant = pv.load_system(i) ctime = os.path.getmtime(i) cdt = datetime.datetime.fromtimestamp(ctime) if cdt > sdate: total_dc += ...
DailyActie/Surrogate-Model
surrogate/benchmarks/__init__.py
Python
mit
1,275
0.000784
# MIT License # # Copyright (c)
2016 Daily Actie # # 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, distribute, sublicense...
to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT...
guillaumebel/nibbles-clutter
glchess/src/lib/chess/pgn.py
Python
gpl-2.0
18,947
0.009659
# -*- coding: utf-8 -*- """ Implement a PGN reader/writer. See http://www.chessclub.com/help/PGN-spec """ __author__ = 'Robert Ancell <[email protected]>' __license__ = 'GNU General Public License Version 2' __copyright__ = 'Copyright 2005-2006 Robert Ancell' import re """ ; Example PGN file [Event "F/S...
else: raise Error('Unknown token %s in movetext' % (str(tokenType))) def parseToken(self, tokenType, data): """ """
# Ignore all comments at any time if tokenType is TOKEN_LINE_COMMENT or tokenType is TOKEN_COMMENT: if self.currentMoveNumber > 0: move = self.game.getMove(self.currentMoveNumber) move.comment = data[1:-1] return if self.state is self.STA...
Xowap/ansible
lib/ansible/constants.py
Python
gpl-3.0
16,541
0.013482
# (c) 2012-2014, Michael DeHaan <[email protected]> # # 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) an...
: if path is not None and os.path.exists(path): try: p.read(path) except configparser.Error as e:
raise AnsibleOptionsError("Error reading config file: \n{0}".format(e)) return p, path return None, '' def shell_expand_path(path): ''' shell_expand_path is needed as os.path.expanduser does not work when path is None, which is the default for ANSIBLE_PRIVATE_KEY_FILE ''' if...
christianmemije/kolibri
kolibri/auth/filters.py
Python
mit
10,993
0.005003
from six import string_types from django.db import models from django.db.models.query import F from .constants import collection_kinds from .errors import InvalidHierarchyRelationsArgument class HierarchyRelationsFilter(object): """ Helper class for efficiently making queries based on relations between mode...
archy` method on the `HierarchyRelationsFilter` instance, passing arguments fixing valu
es for models in the hierarchy structure, or linking them to fields on the base model being filtered (via F expressions). """ _role_extra = { "tables": [ '"{facilityuser_table}" AS "source_user"', '"{role_table}" AS "role"', ], "where": [ "role.us...
mark-burnett/filament-dynamics
actin_dynamics/primitives/__init__.py
Python
gpl-3.0
776
0
# Copyright (C) 2010 Mark Burnett # # This program is free soft
ware: you can redistribute it and/or modify # it under the term
s of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABIL...
pgaref/HTTP_Request_Randomizer
http_request_randomizer/requests/parsers/FreeProxyParser.py
Python
mit
3,551
0.003943
import logging import requests from bs4 import BeautifulSoup from http_request_randomizer.requests.parsers.UrlParser import UrlParser from http_request_randomizer.requests.proxy.ProxyObject import ProxyObject, AnonymityLevel, Protocol logger = logging.getLogger(__name__) __author__ = 'pgaref' class FreeProxyParser...
d: {}".format(self.get_url())) return [] content = response.content soup = BeautifulSoup(content, "html.parser") table = soup.find("table", attrs={"id": "proxylisttable"})
# The first tr contains the field names. headings = [th.get_text() for th in table.find("tr").find_all("th")] datasets = [] for row in table.find_all("tr")[1:-1]: dataset = zip(headings, (td.get_text() for td in row.find_all("td"))) if da...
NavarraBiomed/clips
studies_app/migrations/0006_auto_20161205_1225.py
Python
gpl-2.0
6,384
0.002193
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('studies_app', '0005_auto_20161205_1202'), ] operations = [ migrations.Remove
Field( model_name='observationalcase', name='clips_control_group', ), migrations.Rem
oveField( model_name='observationalcase', name='clips_exp_date', ), migrations.RemoveField( model_name='observationalcase', name='clips_n_lote', ), migrations.RemoveField( model_name='observationalcase', name='clips_...
tudennis/LeetCode---kamyu104-11-24-2015
Python/flip-game.py
Python
mit
1,018
0.005894
# Time: O(c * n + n) = O(n * (c+1)) # Space: O(n) # This solution compares only O(1) times for the two consecutive "+" class Solution(object): def generatePossibleNextMoves(self, s): """ :type s: str :rtype: List[str]
""" res = [] i, n = 0, len(s) - 1 while i < n: # O(n) time if s[i] =
= '+': while i < n and s[i+1] == '+': # O(c) time res.append(s[:i] + '--' + s[i+2:]) # O(n) time and space i += 1 i += 1 return res # Time: O(c * m * n + n) = O(c * n + n), where m = 2 in this question # Space: O(n) # This solution...
kmike/psd-tools
src/psd_tools/terminology.py
Python
mit
52,949
0
""" Constants for descriptor. This file is automaticaly generated by tools/extract_terminology.py """ from enum import Enum as _Enum class Klass(bytes, _Enum): """ Klass definitions extracted from PITerminology.h. See https://www.adobe.com/devnet/photoshop/sdk.html """ Action = b'Actn' Actio...
tDepth16 = b'BD16' BitDepth24 = b'BD24' BitDepth32 = b'BD32' BitDepth4 = b'BD4 ' BitDepth8 = b'BD8 ' BitDepthA1R5G5B5 = b'1565' BitDepthR5G6B5 = b'x565' BitDepthX4R4G4B4 = b'x444' BitDepthA4R4G4B4 = b'4444' BitDepthX8R8G8B8 = b'x888' Bitmap = b'Btmp' Black = b'Blck' Black...
Blocks = b'Blks' Blue = b'Bl ' Blues = b'Bls ' Bottom = b'Bttm' BrushDarkRough = b'BrDR' BrushesAppend = b'BrsA' BrushesDefine = b'BrsD' BrushesDelete = b'Brsf' BrushesLoad = b'Brsd' BrushesNew = b'BrsN' BrushesOptions = b'BrsO' BrushesReset = b'BrsR' BrushesSave = b...
chipx86/reviewboard
reviewboard/datagrids/sidebar.py
Python
mit
13,527
0
"""Sidebar item management for datagrids.""" from __future__ import unicode_literals from django.utils import six from django.utils.six.moves.urllib.parse import urlencode from djblets.util.compat.django.template.loader import render_to_string from reviewboard.site.urlresolvers import local_site_reverse class Base...
ional template context. By default, this is empty. """ return {} class BaseSidebarSection(BaseSidebarItem): """Base class for a section of items on the sidebar. Subclasses can override this to define a section and provide items listed in the section. Sections can optional...
play a count. """ template_name = 'datagrids/sidebar_section.html' def __init__(self, *args, **kwargs): """Initialize the section. Args: *args (tuple): Positional arguments to pass to the parent class. **kwargs (dict): Keyword argum...
nsmoooose/csp
csp/base/applog.py
Python
gpl-2.0
1,162
0.001721
# Copyright 2004 Mark Rose <[email protected]
ceforge.net> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Gene
ral 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, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR ...
ruchee/vimrc
vimfiles/bundle/vim-python/submodules/astroid/astroid/brain/brain_scipy_signal.py
Python
mit
2,437
0.00041
# Copyright (c) 2019 Valentin Valls <[email protected]> # Copyright (c) 2020-2021 hippo91 <guill
[email protected]> # Copyright (c) 2020 Claudiu Popa <[email protected]> # Copyright (c) 2021 Pierre Sassoulas <[email protected]> # Licensed under the LGPL: https://www.gnu.org/licenses/old-licen
ses/lgpl-2.1.en.html # For details: https://github.com/PyCQA/astroid/blob/master/LICENSE """Astroid hooks for scipy.signal module.""" import astroid def scipy_signal(): return astroid.parse( """ # different functions defined in scipy.signals def barthann(M, sym=True): re...
openlabs/trytond
trytond/tests/test_mixins.py
Python
gpl-3.0
1,711
0.005845
#!/usr/bin/env python # -*- coding: utf-8 -*- #This file is part of Tryton. The COPYRIGHT file at the top level of #this repository contains th
e full copyright
notices and license terms. import unittest import urllib from trytond.tests.test_tryton import (POOL, DB_NAME, USER, CONTEXT, install_module) from trytond.transaction import Transaction from trytond.url import HOSTNAME class UrlTestCase(unittest.TestCase): "Test URL generation" def setUp(self): ...
skoolkid/pyskool
pyskool/skoolsound.py
Python
gpl-3.0
18,865
0.004665
# -*- coding: utf-8 -*- # Copyright 2013, 2014 Richard Dymond ([email protected]) # # This file is part of Pyskool. # # Pyskool 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...
(60,154), # A2 (63,145), # B2 (71,129), # C2 (80,114), # D2 (86,107), # E2 ((90,101) in the original games, but unused) (95,96), # F2 (107,86), # G2 (not in the original games) ) def delays_to_samples(delays, sample_rate, max_amplitude): sample_delay = 3500000.0 / sample_rate samples =...
= 0 d0 = 0 d1 = delays[i] t = 0 while 1: while t >= d1: i += 1 if i >= len(delays): break d0 = d1 d1 += delays[i] direction *= -1 if i >= len(delays): break sample = direction * int(max_ampli...
marcostx/BatCNN
mlp/mlp.py
Python
mit
1,571
0.019096
import sys import numpy as np from sklearn.model_selection import StratifiedKFold from sklearn.neural_network import MLPClassifier from sklearn.metrics import f1_score,accuracy_score, recall_score, precision_score import scipy from random import shuffle def load_dataset(filename): f = open(filename) x = [] ...
st = x[test_index] ytest = y[test_index] print("training ...") clf = inductor(xtrain,ytrain) print("predicting ...") ypred = cl
f.predict(xtest) print "(accuracy : %4.3f) "%(accuracy_score(ytest,ypred)) print "(f1 : %4.3f) "%(f1_score(ytest,ypred, average='weighted')) print "(recall : %4.3f) "%(recall_score(ytest,ypred,average='weighted')) print "(precision : %4.3f) "%(precision_score(ytest,ypred,average='weight...
wavii/listy-django-cache
listy/deterministic_cached_model.py
Python
mit
18,356
0.004304
import re import time import logging import traceback import collections import cPickle as pickle from datetime import datetime from django.db import models from django.db.models.query import QuerySet from django.db.models.query_utils import deferred_class_factory from django.conf import settings from listy.list_cach...
(model, na
me) backing_store_class = self.kwargs.pop('django_backing_store_class', DjangoBackingStore) inlined_foreign_key_fields = self.kwargs.pop('inlined_foreign_key_fields', {}) backing_store = backing_store_class(model._rw_objects, inlined_foreign_key_fields=inlined_foreign_key_fields) model.c...
douglasbagnall/nze-vox
voxutils/paths.py
Python
mit
671
0
from os.path import dirname, join, abspath ROOT = dirname(dirname(abspath(__file__))) DICT = join(ROOT, 'dict') DICT_NONFREE = join(ROOT, 'dict', 'non-free') CORPORA_DIR = join(ROOT, 'corpora') RESAMPLED_16K_DIR = join(CORPORA_DIR, '16k') SUBCORPUS_DIR = join(CORPORA_DIR, 'resampled') IGNORED_CORPORA = ['resampled', ...
voxforge', 'wellington', 'hansard'] CORPORA = {x: join(CORPORA_DIR, x) for x in BASE_CORPORA} CMUDICT = join(DICT, 'cmudict.0.7a') UNISYN_DICT = join(DICT_NONFREE, 'unisyn-nz.txt') VOXFORGE_DICT = join(DICT, 'VoxForgeDict') BEEP_DICT = join(DICT_NONFREE, 'beep
', 'beep-1.0') ESPEAK_DICT = join(DICT, 'espeak-corpus+50k.txt')
montyly/manticore
tests/ethereum/EVM/test_EVMGAS.py
Python
apache-2.0
1,877
0.001066
import struct import unittest import json from manticore.platforms import evm from manticore.core import state from manticore.core.smtlib import Operators, ConstraintSet import os class EVMTest_GAS(unittest.TestCase): _multiprocess_can_split_ = True maxDiff = None def _execute(self, new_vm): last...
new_vm.execute() except evm.Stop as e: last_exception = "STOP" except evm.NotEnoughGas: last_exception = "OOG" except evm.StackUnderflow: last_exception = "INSUFFICIENT STACK" except evm.InvalidOpcode: last_exceptio
n = "INVALID" except evm.SelfDestruct: last_exception = "SUICIDED" except evm.Return as e: last_exception = "RETURN" last_returned = e.data except evm.Revert: last_exception = "REVERT" return last_exception, last_returned def test_GAS...
ghackebeil/PyORAM
examples/encrypted_storage_sftp.py
Python
mit
3,559
0.001405
# # This example measures the performance of encrypted storage # access through an SSH client using the Secure File # Transfer Protocol (SFTP). # # In order to run this example, you must provide a host # (server) address along with valid login credentials # import os import random import time import pyoram from pyora...
_name, block_size, block_count, storage_type='sftp', sshclient=ssh, ignore_existing=True) as f: print("...
Time: %2.f s" % (time.time()-setup_start)) print("Total Data Transmission: %s" % (MemorySize(f.bytes_sent + f.bytes_received))) print("") # We close the device and reopen it after # setup to reset the bytes sent and bytes # received st...
sridevikoushik31/openstack
nova/tests/test_metadata.py
Python
apache-2.0
22,819
0.000614
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compli...
'virtual_name': 'ephemeral0', 'delete_on_termination': None, 'device_name': '/dev/sdb'}] self.stubs.Set(db, 'block_device_mapping_get_all_by_instance', fake_bdm_get) expected = {'ami': 'sda1', 'root': '/dev/sda1', ...
emeral0': '/dev/sdb', 'swap': '/dev/sdc', 'ebs0': '/dev/sdh'} capi = conductor_api.LocalAPI() self.assertEqual(base._format_instance_mapping(capi, ctxt, instance_ref0), block_device._DEFAULT_MAPPINGS) self.assertEqual(base._format...
karellodewijk/wottactics
extra/download_hots_map/dragon-shire/download_hots_map.py
Python
mit
1,370
0.026277
import os; link = "http://media.blizzard.com/heroes/images/battlegrounds/maps/dragon-shire/main/6/" column = 0; rc_column = 0; while (rc_column == 0): row = 0; rc_column = os.system('wget ' + link + str(column) + '/' + str(row) + '.jpg -O ' + str(1000 + column) + '-' + str(1000 + row) + '.jpg') rc_row = rc_column ...
(); last_file = p.readline(); column_end = last_file[0:4] row_end = second_last_file[5:9] print column_end print row_end os.system('rm ' + column_end + '*'); os.system('rm *-' + row_end + '.jpg'); column_end = int(column_end) - 1000; row_end = int(row_end) - 1000; os.system('mkdir temp') i = 0; for r in range(0, ...
ow_end): for c in range(0, column_end): file_to_move = str(1000 + c) + '-' + str(1000 + row_end - r - 1) + '.jpg' os.system('cp ' + file_to_move + ' ./temp/' + str(100000 + i) + '.jpg'); i += 1 os.system('montage ./temp/*.jpg -tile ' + str(column_end) + 'x' + str(row_end) + ' -geometry +0+0 result.png'); os.sys...
paplorinc/intellij-community
python/testData/paramInfo/TypingCallableWithKnownParameters.py
Python
apache-2.0
104
0.019231
from t
yping import Callable def f() -> Callable[[int, str], int]: pass
c = f() print(c(<arg1>))
gregrperkins/closure-library
closure/bin/build/jscompiler_test.py
Python
apache-2.0
2,516
0.002782
#!/usr/bin/env python # # Copyright 2013
The Closure Library Authors. All Rights Reserved. # # Licensed u
nder the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License i...
winstonschroeder77/fitch-
fitch_app/webui/fitch/fitch/wsgi.py
Python
gpl-3.0
385
0.002597
""" WSGI config for fitch project. It exposes the WSGI callable as a module-level variable na
med ``application``. For mor
e information on this file, see https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/ """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "fitch.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application()
tanonev/codewebs
src/analogyFinder/src/daemons/example/exampleclient.py
Python
mit
1,439
0.013899
#! /usr/bin/env python import json import sys sys.path.append('..') from CodewebsIndexClient import CodewebsIndexClient def loadTextFile(fname): with open(fname) as fid: return fid.read() def wrap(ast,code,map,codeblockid): astjson = json.loads(ast) wrappedJSON = {'ast': astjson, ...
ndex': 28, 'querytype': 3}
#return json.dumps(wrappedJSON,sort_keys = True,indent=4,separators=(',',': ')) return json.dumps(wrappedJSON) def run(): codeblockid = 30 asttext = loadTextFile('ast.json') codetext = loadTextFile('code') maptext = loadTextFile('map') inputJSON = wrap(asttext,codetext,maptext,codeblockid) ...
cybercomgroup/Big_Data
Cloudera/Code/Titanic_Dataset/title_surv.py
Python
gpl-3.0
1,344
0.040923
import pandas as pd import numpy as np import matplotlib.pyplot as plt # Seperate titles, French -> english, others to rare. def engTitle(title): if title in ["Miss", "Mrs", "Mr", "Dr", "Master"]: return title elif title in ["Mme", "Ms"]: return "Mrs" elif title == "Mlle": return "Miss" else: return "Rare"...
].split(".") return en
gTitle( name[0].strip() ) df = pd.read_csv("train.csv") df["Title"] = df.apply(lambda row: getTitleFromName(row["Name"]), axis = 1) titles = df["Title"].unique() index = np.arange( len(titles) ) opacity = 0.5 bar_width = 0.3 total = [] survived = [] for title in titles: t_all = df[ df["Title"] == title ] total.ap...
googleapis/python-contact-center-insights
setup.py
Python
apache-2.0
2,576
0.000388
# -*- coding: utf-8 -*- # # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law...
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 io import os import setuptools name = "google-cloud-contact-center-insights" description = "Con...
baverman/snaked
snaked/signals/util.py
Python
mit
375
0.008
def app
end_attr(obj, attr, value): """ Appends value to object attribute Attribute may be undefined For example: append_attr(obj, 'test', 1) append_attr(obj, 'test', 2) assert obj.test == [1, 2] """ try: getattr(obj, attr).append(value) except Attr...
ue])
hainm/open-forcefield-group
ideas/bayesian-gbsa-parameterization/evaluate-gbsa.py
Python
gpl-2.0
24,285
0.010089
#!/usr/bin/env python #============================================================================================= # MODULE DOCSTRING #============================================================================================= """ evaluate-gbsa.py Evaluate the GBSA model on hydration free energies of small molec...
ag, "") # Assign atom types using rules. OEAssignAromaticFlags(mol) for pat,type,smarts in self.smartsList: for matchbase in pat.Match(mol): for matchpair in matchbase.GetAtoms(): matchpair.target.SetStringData(self.pattyTag,type) ...
if atom.GetStringData(self.pattyTag)=="": raise AtomTyper.TypingException(mol, atom) def debugTypes(self,mol): for atom in mol.GetAtoms(): print "%6d %8s %8s" % (atom.GetIdx(),OEGetAtomicSymbol(atom.GetAtomicNum()),atom.GetStringData(self.pattyTag)) def getTypeList(se...
RevansChen/online-judge
Codewars/7kyu/shortest-word/Python/solution1.py
Python
mit
69
0.014493
# Python - 3.6.0 find_short = lambda
s: min(map(len, s.split
(' ')))
kernevil/samba
source4/torture/drs/python/getnc_exop.py
Python
gpl-3.0
50,933
0.001492
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Tests various schema replication scenarios # # Copyright (C) Kamen Mazdrashki <[email protected]> 2011 # Copyright (C) Andrew Bartlett <[email protected]> 2016 # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Gen...
seful, # 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 this program. If not, see <http://www.gnu.org/license...
ONPATH="$PYTHONPATH:$samba4srcdir/torture/drs/python" $SUBUNITRUN getnc_exop -U"$DOMAIN/$DC_USERNAME"%"$DC_PASSWORD" # import random import drs_base from drs_base import AbstractLink import samba.tests from samba import werror, WERRORError import ldb from ldb import SCOPE_BASE from samba.dcerpc import drsuapi, mis...
google-research/tf-slim
tf_slim/training/__init__.py
Python
apache-2.0
701
0
# coding=utf-8 # Copyright 2016 The TF-Slim 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 require...
software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either expre
ss or implied. # See the License for the specific language governing permissions and # limitations under the License. # ==============================================================================
alfss/django-sockjs-server
django_sockjs_server/templatetags/sockjs_server_tags.py
Python
bsd-3-clause
580
0.001724
from random import choice from dja
ngo import template from django_sockjs_server.lib.config import SockJSServerSettings from django_sockjs_server.lib.token import Token register = template.Library() @register.simple_tag(name='sockjs_auth_token') def sockjs_auth_token(room_
name, unq_id=None): token = Token() if unq_id: return token.get_secret_data(room_name+str(unq_id)) return token.get_secret_data(room_name) @register.simple_tag(name='sockjs_server_url') def sockjs_server_url(): config = SockJSServerSettings() return choice(config.sockjs_url)
caelan/stripstream
stripstream/fts/clause.py
Python
mit
7,480
0.001337
from collections import defaultdict from stripstream.pddl.logic.connectives import Not from stripstream.pddl.operators import STRIPSAction from stripstream.fts.derived import get_derived from stripstream.fts.variable import FreeParameter, Par, X, nX, VarMember, is_parameter, is_constant, var_args, var_name, make_var_...
derived = get_derived(con.constraint( *new_values), var_map, axiom_map, constants) if derived not in static_preconditions: static_preconditions.append(derived) return static_preconditions def convert_clause(clause, var_m
ap, axiom_map): effect_vars = {item.var for con in clause.constraints for item in con.values if isinstance(item, VarMember) and item.temp == nX} eq_map = get_equality_map(clause.constraints, var_map) if eq_map is None: return None internal_params = set(eq_map) | {X[var] for v...
GenericStudent/home-assistant
tests/helpers/test_update_coordinator.py
Python
apache-2.0
7,348
0
"""Tests for the update coordinator.""" import asyncio from datetime import timedelta import logging import urllib.error import aiohttp import pytest import requests from homeassistant.helpers import update_coordinator from homeassistant.util.dt import utcnow from tests.async_mock import AsyncMock, Mock, patch from ...
_present(hass, crd_without_update_interval): """Test update never happens with no update interval.""" crd = crd_without_update_interval # Test we don'
t update without subscriber with no update interval async_fire_time_changed(hass, utcnow() + DEFAULT_UPDATE_INTERVAL) await hass.async_block_till_done() assert crd.data is None # Add subscriber update_callback = Mock() crd.async_add_listener(update_callback) # Test twice we don't update wi...
Weasyl/weasyl
gunicorn.conf.py
Python
apache-2.0
173
0
wsgi_app = "weasyl.wsgi:make_wsgi_app()" proc_name = "weasyl
" preload_app = False secure_scheme_hea
ders = { 'X-FORWARDED-PROTO': 'https', } forwarded_allow_ips = '*'
chrisnorman7/game
commands/options.py
Python
mpl-2.0
2,845
0
"""Provides the options command.""" from functools import partial from gsb.intercept import Menu from forms import set_value from parsers import parser from options import options from util import done def show_section(section, caller): """Show the player an instance of OptionsMenu.""" caller.con...
yer def invalid_input(caller): """Show invalid input warning.""" player.notify('Invalid input: %r.', caller.text) show_section(option.section, caller) def after(caller): """Set the value.""" done(player) show_section(option.section, caller) valu...
value = 'Enabled' elif value is False: value = 'Disabled' elif value is None: value = 'Clear' else: value = repr(value) player.notify( '%s\n%s\nCurrent value: %s\n', option.friendly_name, option.description, value ) set...
rh-s/heat
contrib/rackspace/rackspace/resources/cloudnetworks.py
Python
apache-2.0
5,069
0
# # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # ...
the network. For example, " "172.16.0.0/24 or 2001:DB8::/64."), required=True, constraints=[ constraints.CustomConstraint('net_cidr') ] ) } attributes_schema = { CIDR_ATTR: attributes.Schema( _("The CIDR for an isola...
ame of the network.") ), } def __init__(self, name, json_snippet, stack): resource.Resource.__init__(self, name, json_snippet, stack) self._network = None def network(self): if self.resource_id and not self._network: try: self._network = self.clo...
transplantation-immunology/EMBL-HLA-Submission
saddlebags/AlleleSubmission.py
Python
lgpl-3.0
3,176
0.003463
# This file is part of saddle-bags. # # saddle-bags is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # saddle-bags is distribut...
line names, if we are submitting the HLA types of cell lines. I'm just using it as a sample ID or cellnum. Lets see where that breaks. self.cellId = None self.ethnicOrigin = None self.sex = None self.consanguineous = None self.homozygous = None # Necessary = A,B, DRB1. Th...
e. # I store the typed alleles as a dictionary. Key is the Locus (HLA-A) and the value is a String with the alleles, separated by a comma (02:01,03:01:14) self.typedAlleles = {} self.materialAvailability = None self.cellBank = None self.primarySequencingMethodology = None ...
gmt/portage
pym/portage/sync/modules/git/git.py
Python
gpl-2.0
3,109
0.024124
# Copyright 2005-2015 Gentoo Foundation # Distributed under the terms of the GNU General Public License v2 import logging import subprocess import portage from portage import os from portage.util import writemsg_level from portage.output import create_color_func good = create_color_func("GOOD") bad = create_color_fun...
pdated. We'll let the user manage branches with git directly. ''' git_cmd_opts = "" if self.settings.get("PORTAGE_QUIET") == "1": git_cmd_opts += " --quiet" git_cmd = "%s pull%s" % (self.bin_command, git_c
md_opts) writemsg_level(git_cmd + "\n") rev_cmd = [self.bin_command, "rev-list", "--max-count=1", "HEAD"] previous_rev = subprocess.check_output(rev_cmd, cwd=portage._unicode_encode(self.repo.location)) exitcode = portage.process.spawn_bash("cd %s ; exec %s" % ( portage._shell_quote(self.repo.location)...
davidbgk/udata
udata/core/post/models.py
Python
agpl-3.0
1,465
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from flask import url_for from udata.core.storages import images, default_image_basename from udata.i18n import lazy_gettext as _ from udata.models import db __all__ = ('Post', ) IMAGE_SIZES = [400, 100, 50] class Post(db.Datetimed, db.Document): ...
equired=True) image_url = db.StringField() image = db.ImageField( fs=images, basename=default_image_basename, thumbnails=IMAGE_SIZES) credit_to = db.StringField() credit_url = db.URLFie
ld() tags = db.ListField(db.StringField()) datasets = db.ListField( db.ReferenceField('Dataset', reverse_delete_rule=db.PULL)) reuses = db.ListField( db.ReferenceField('Reuse', reverse_delete_rule=db.PULL)) owner = db.ReferenceField('User') private = db.BooleanField() meta = {...
cydenix/OpenGLCffi
OpenGLCffi/GL/EXT/ARB/vertex_type_2_10_10_10_rev.py
Python
mit
3,794
0.010543
from OpenGLCffi.GL import params @params(api='gl', prms=['index', 'type', 'normalized', 'value']) def glVertexAttribP1ui(index, type, normalized, value): pass @params(api='gl', prms=['index', 'type', 'normalized', 'value']) def glVertexAttribP1uiv(index, type, normalized, value): pass @params(api='gl', prms=['ind...
ype', 'color']) def glColorP3ui(type, color): pass @params(api='gl', prms=['type', 'color']) def glColorP3uiv(type, color): pass @params(api='gl', prms=['type', 'color']) def glColorP4ui(type, color): pass @para
ms(api='gl', prms=['type', 'color']) def glColorP4uiv(type, color): pass @params(api='gl', prms=['type', 'color']) def glSecondaryColorP3ui(type, color): pass @params(api='gl', prms=['type', 'color']) def glSecondaryColorP3uiv(type, color): pass
amarandon/pinax
pinax/projects/code_project/urls.py
Python
mit
2,413
0.008703
from django.conf import settings from django.conf.urls.defaults import * from django.views.generic.simple import direct_to_template from django.contrib import admin admin.autodiscover() from tagging.models import TaggedItem from wakawaka.models import WikiPage from pinax.apps.account.openid_consumer import PinaxCons...
urls")), url(
r"^notices/", include("notification.urls")), url(r"^avatar/", include("avatar.urls")), url(r"^comments/", include("threadedcomments.urls")), url(r"^announcements/", include("announcements.urls")), url(r"^tagging_utils/", include("pinax.apps.tagging_utils.urls")), url(r"^attachments/", include("attac...
SeMorgana/ctf
defcon2014/3dttt.py
Python
gpl-3.0
5,141
0.024703
#5/17/2014 import telnetlib import random from utility import * tn = telnetlib.Telnet("3dttt_87277cd86e7cc53d2671888c417f62aa.2014.shallweplayaga.me",1234) X = 'X' O = 'O' def get_sym(coor): #sym => symmetric if coor == 0: return 2 if coor == 1: return 1 if coor == 2: return 0 d...
move send = str(x)+","+str(y)+","+str(z) print "sending ",send tn.write(send+"\n")
if __name__=="__main__": main()
BoolLi/LeapMotionDesignChallenge
Plotting.py
Python
mit
602
0.004983
# Name: Seline, Li, Taylor, Son # Leap Motion project import matplotlib as mpl from mpl_toolkits.mplot3d import Axes3D import numpy as np import matplotlib.pyplot as plt import time mpl.rcParams['legend.fontsize'] = 10 fig = plt.figure() ax = Axes3D(fig) theta = np.linspace(-4 * np.pi, 4 * np.pi, 100) z = np.linspac...
gend() plt.ion() plt.show() for ii in xrange(0,360,1): ax.view_init(elev=10, azim=ii)
plt.draw() print "drawn? " + str(ii) time.sleep(0.01)
tino/python-telegram-bot
telegram/contact.py
Python
gpl-3.0
1,745
0
#!/usr/bin/env python # # A library that provides a Python interface to the Telegram Bot API # Copyright (C) 2015 Leandro Toledo de Souza <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser Public License as published by # the ...
son(data): return Contact(phone_number=data.get('phone_number', None), first_name=data.get('first_name', None), last_name=data.get('last_name', None), user_id=data.get('user_id', None)) def to_dict(self): data = {'ph
one_number': self.phone_number, 'first_name': self.first_name} if self.last_name: data['last_name'] = self.last_name if self.user_id: data['user_id'] = self.user_id return data
dhinakg/BitSTAR
api/database/DAL/__init__.py
Python
apache-2.0
1,348
0.006677
# Copyright 2017 Starbot Discord Project # # 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...
close(db_in) def db_create_table(db_in, tablename): if DB.type == "SQLite": SQLite.db_create_table(db_in, tablename) def db_insert(db_in, table, dict_in): if DB.type == "SQLite": return SQLite.db_insert(db_in, table, dict_in) def db_get_contents_of_table(db_in, table, rows): if DB.type ==...
SQLite": return SQLite.db_get_contents_of_table(db_in, table, rows) def db_get_latest_id(db_in, table): if DB.type == "SQLite": return SQLite.db_get_latest_id(db_in, table)
mrc75/django-service-status
tests/settings.py
Python
mit
1,279
0
# -*- coding: utf-8 from __future__ import unicode_literals, absolute_import import django DEBUG = True USE_TZ = True # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii' DATABASES = { 'default': { 'ENGINE': 'django.db.backe...
django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware' ) STATIC_URL = '/static/' TEMPLATES = [ {
'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, # 'OPTIONS': {}, }, ] TEST_RUNNER = 'tests.runner.PytestTestRunner'
Nablaquabla/sns-analysis
_getAcceptanceVsTime.py
Python
gpl-3.0
6,613
0.013912
#!/home/bjs66/anaconda2/bin/python2.7 """ Created on Mon Feb 01 15:03:56 2016 @author: Nablaquabla """ import h5py import numpy as np import easyfit as ef import datetime import pytz import os # Prepare timezones and beginning of epcoch for later use utc = pytz.utc eastern = pytz.timezone('US/Eastern') epochBeginnin...
te() == easternEndTS.date(): lastTSForThisDay = utcEndTS
else: lastTSForThisDay = ((easternDayTS + datetime.timedelta(days=1)).astimezone(utc) - epochBeginning).total_seconds() # Read power data for current day timeData = h5Power['/%s/time'%day][...] powerData = h5Power['/%s/power'%day][...] # Get all ti...
gandrewstone/yadog
PyHtmlGen/menu.py
Python
gpl-3.0
8,114
0.055829
from gen import * from chunk import * from document import * from attribute import * from template import * import pdb import copy from types import * #class MenuItem: # def __init__(self, text, whenclicked): # Send a list of items, this wraps it in code that will change the foreground color when the mouse goees ov...
f submenufn else lambda x
,y: y self.itemfn = itemfn if itemfn else lambda x,y: y self.suppressBody = True # Turn off the Block's automatic div creation because we have another block self.sel = selAttr self.lst = chunkBuffer() self.menu = chunkTag(["div"],self.lst) self.menu.id = self.id for i in items: #(text, item...