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
OutOfOrder/sshproxy
lib/console_extra/__init__.py
Python
gpl-2.0
1,214
0.001647
#!/usr/bin/env python # -*- coding: ISO-8859-15 -*- # # Copyright (C) 2005-2007 David Guerizec <david@guerizec.net> # # Last modified: 2006 Sep 02, 01:40:01 by david # # 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...
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 __plugin_name__ = "Console Extra Commands" __description__ = """ This plugin offers several new commands for the console session: ...
ser@site cmd args... Run a command remotely on user@site. """ def __init_plugin__(): import commands
paulrouget/servo
tests/wpt/web-platform-tests/tools/third_party/pytest/doc/en/example/py2py3/conftest.py
Python
mpl-2.0
324
0
im
port sys import pytest py3 = sys.version_info[0] >= 3 class DummyCollector(pytest.colle
ct.File): def collect(self): return [] def pytest_pycollect_makemodule(path, parent): bn = path.basename if "py3" in bn and not py3 or ("py2" in bn and py3): return DummyCollector(path, parent=parent)
pandas-dev/pandas
pandas/tests/io/parser/test_skiprows.py
Python
bsd-3-clause
7,845
0.001147
""" Tests that skipped rows are properly handled during parsing for all of the parsers defined in parsers.py """ from datetime import datetime from io import StringIO import numpy as np import pytest from pandas.errors import EmptyDataError from pandas import ( DataFrame, Index, ) import pandas._testing as ...
\n' \r\tline 32", 1]], ), ], ) def test_skip_row_with_newline_and_quote(all_parsers, data, exp_data): # see gh-12775 and gh-10911 parser = all_parsers result = parser.read_csv(StringIO(data), skiprows=[1]) expected = DataFrame(exp_data, columns=["id", "text", "num_lines"]) tm.assert_fra...
@pytest.mark.parametrize( "lineterminator", ["\n", "\r\n", "\r"] # "LF" # "CRLF" # "CR" ) def test_skiprows_lineterminator(all_parsers, lineterminator, request): # see gh-9079 parser = all_parsers data = "\n".join( [ "SMOSMANIA ThetaProbe-ML2X ", "2007/01/01 01:00 0...
OpenXT/sync-database
sync_db/run_script.py
Python
gpl-2.0
2,130
0.002347
# # Copyright (c) 2012 Citrix Systems, Inc. # # 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 dist...
metavar="SCRIPT", help="sqlplus script to run") parser.set_defaults(func=_run) parser.set_defaults(need_config=True) parser.set_defaults(need_metadata=True) def _run(args, metadata, config): sqlplus.run_steps([(args.user, args.script)], metada...
a, config, args.schema_dir, False, None, None, False)
dl1ksv/gnuradio
gnuradio-runtime/python/gnuradio/gr/packet_utils.py
Python
gpl-3.0
4,116
0.000243
#!/usr/bin/env python # # Copyright 2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # SPDX-License-Identifier: GPL-3.0-or-later # # from gnuradio import gr import pmt def make_lengthtags(lengths, offsets, tagname='length', vlen=1): tags = [] assert(len(offsets) == len(lengths)) f...
"Packets cannot have zero length.") if pos + length > len(data): raise ValueError("The final packet is incomplete.") packets.append(data[pos: pos + length]) pos += length return packets def packets_to_vectors(packets, tsb_tag_key, vlen=1): """ Returns a single data vector a...
. """ tags = [] data = [] offset = 0 for packet in packets: data.extend(packet) tag = gr.tag_t() tag.offset = offset // vlen tag.key = pmt.string_to_symbol(tsb_tag_key) tag.value = pmt.from_long(len(packet) // vlen) tags.append(tag) offset = offset...
knagra/farnsworth
threads/models.py
Python
bsd-2-clause
3,639
0.002473
''' Project: Farnsworth Author: Karandeep Singh Nagra ''' from django.contrib.auth.models import User, Group, Permission from django.core.urlresolvers import reverse from django.db import models from base.models import UserProfile class Thread(models.Model): ''' The Thread model. Used to group messages. ...
sage model. Contains a body, owner, and post_date, referenced by thread. ''' body = models.TextField( blank=False, null=False, help_text="Body of this message.", ) owner = models.ForeignKey( UserProfile, help_text="The user who posted this message.", ...
reignKey( Thread, help_text="The thread to which this message belongs.", ) edited = models.BooleanField( default=False, ) def __str__(self): return self.__unicode__() def __unicode__(self): return self.body class Meta: ordering = ['post_...
mryab/askme
labs/L1 - Gradient descent and linear models.py
Python
mit
32,558
0.00386
# coding: utf-8 # # L1 - Градиентый спуск и линейные модели # In[1]: import numpy as np import matplotlib import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from scipy.optimize import minimize import math get_ipython().magic('matplotlib notebook') matplotlib.rcParams['figure.figsize'] = '12,8' ...
$b$ и получить исходное равенство), получаем следующие зависимости $Q$ от $M$: # # 1) $Q = [y_{pred} \neq y_{true}]=[y\cdot(wx)<0]=[M < 0]$ # # 2) $Q = ((wx) - y)^{2}=\fra
c{1}{y^2}((wx\cdot y) - y^2)^2=\frac{1}{y^2}(M - y^2)^2$. Так как $y=\pm 1$, то $Q=(M - 1)^2$. # # 3) $Q = max(0, 1 - y\cdot(wx))=max(0,1-M)$ # # 4) $Q = \ln(1 + e^{-y\cdot(wx)})=\ln(1+e^{-M})$ # In[7]: margin = np.linspace(-7, 7, 1000) @np.vectorize def exact_loss_m(x): return 1 if x < 0 else...
mikefeneley/topcoder
src/SRM-697/triangle_making.py
Python
mit
423
0.002364
class TriangleMaki
ng: def maxPerimeter(self, a, b, c): first = a second = b third = c sides = [first, second, third] for idx, side in enumerate(sides): one = (idx + 1) % 3 two = (idx + 2) % 3 total = sides[one] + sides[two] while sides[idx] >...
return sum(sides)
sean-abbott/chamberlain
tests/factories.py
Python
bsd-3-clause
769
0
# -*- coding
: utf-8 -*- """Factories to help in tests.""" from factory import PostGenerationMethodCall, Sequence from factory.alchemy import SQLAlchemyModelFactory from cham
berlain.database import db from chamberlain.user.models import User class BaseFactory(SQLAlchemyModelFactory): """Base factory.""" class Meta: """Factory configuration.""" abstract = True sqlalchemy_session = db.session class UserFactory(BaseFactory): """User factory.""" u...
snirp/juis
manage.py
Python
mit
250
0
#!/usr/bin/
env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "juisapp.settings") from django.core.management import execute_from_command_line execu
te_from_command_line(sys.argv)
stackforge/cloudkitty
cloudkitty/api/v2/scope/state.py
Python
apache-2.0
4,899
0
# Copyright 2019 Objectif Libre # # 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 agr...
), voluptuous.Optional('fetcher', default=[]): api_utils.MultiQueryParam(str), voluptuous.Optional('collector', default=[]): api_utils.MultiQueryParam(str), }) @api_utils.add_output_schema({'results': [{ voluptuous.Required('scope_id'): vutils.get_string_type(), ...
voluptuous.Required('scope_key'): vutils.get_string_type(), voluptuous.Required('fetcher'): vutils.get_string_type(), voluptuous.Required('collector'): vutils.get_string_type(), voluptuous.Required('state'): vutils.get_string_type(), }]}) def get(self, offset=0, ...
freerangerouting/frr
tests/lib/test_frrlua.py
Python
gpl-2.0
358
0
import frrtest import pytest if 'S["SCRIPTING_TRUE"]=""\
n' not in open("../config.status").readlines(): class TestFrrlua: @pytest.mark.skipif(True, reason="Test unsupported") def test_exit_cleanly(self): pass else: class TestFrrlua(frrtest.TestMultiOut): program
= "./test_frrlua" TestFrrlua.exit_cleanly()
smartsheet-platform/smartsheet-python-sdk
smartsheet/models/alternate_email.py
Python
apache-2.0
2,281
0
# pylint: disable=C0111,R0902,R0904,R0912,R0913,R0915,E1101 # Smartsheet Python SDK. # # Copyright 2018 Smartsheet.com, 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....
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from __future__ import absolute_import from ..types import * from ..util import serialize from ..util import deserialize class AlternateEmail(objec...
Email model.""" self._base = None if base_obj is not None: self._base = base_obj self._confirmed = Boolean() self._email = String() self._id_ = Number() if props: deserialize(self, props) # requests package Response object self.r...
ESSICS/org.csstudio.display.builder
org.csstudio.display.builder.model/examples/script_util/write_any_pv.py
Python
epl-1.0
855
0.003509
# Example for script that connects to PV, # writes a value, then disconnects from the PV. # # This is usually a bad idea. # It's better to have widgets connect to PVs, # 1) More efficient. Widget
connects once on start, then remains connected. # Widget subscribes to PV updates instead of polling its value. # 2) Widget will reflect the connection and alarm state of the PV # 3) Widget will properly disconnect # # pvs[0]: PV with name of PV to which to connect # pvs[1]: PV with value that will be written to th...
il.getString(pvs[0]) value = PVUtil.getDouble(pvs[1]) print("Should write %g to %s" % (value, pv_name)) try: PVUtil.writePV(pv_name, value, 5000) except: ScriptUtil.showErrorDialog(widget, "Error writing %g to %s" % (value, pv_name))
cpaulik/pyscaffold
tests/extensions/test_travis.py
Python
mit
1,578
0
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys from os.path import exists as path_exists from pyscaffold.api import create_project from pyscaffold.cli import run from pyscaffold.extensions import travis def test_create_project_with_travis(tmpfolder): # Given options with the travis extension, opts ...
# when pyscaffold runs, run() # then travis files should exist assert path_exists("proj/.travis.yml") assert path_exists("proj/tests/travis_install.sh") def test_cli_without_travis(tmpfolder): # Given the command line without the travis option, sys.argv = ["pyscaffold", "p
roj"] # when pyscaffold runs, run() # then travis files should not exist assert not path_exists("proj/.travis.yml") assert not path_exists("proj/tests/travis_install.sh")
MarkTheF4rth/youtube-dl
devscripts/make_supportedsites.py
Python
unlicense
1,152
0.001736
#!/usr/bin/env python from __future__ import unicode_literals import io import optparse import os import sys # Import youtube_dl ROOT_DIR = os.path.join(os.path.dirname(__file__), '..') sys.path.insert(0, ROOT_DIR) import youtube_dl def main(): parser = optparse.OptionParser(usage='%prog OUTFILE.md') optio...
upported sites\n' + ''.join( ' - ' + md + '\n' for md in gen_ies_md(ies)) with io.open(outfile, 'w'
, encoding='utf-8') as outf: outf.write(out) if __name__ == '__main__': main()
perryjohnson/biplaneblade
biplane_blade_lib/prep_stn18_mesh.py
Python
gpl-3.0
30,755
0.006763
"""Write initial TrueGrid files for one biplane blade station. Usage ----- start an IPython (qt)console with the pylab flag: $ ipython qtconsole --pylab or $ ipython --pylab Then, from the prompt, run this script: |> %run biplane_blade_lib/prep_stnXX_mesh.py or |> import biplane_blade_lib/prep_stnXX_mesh ...
polygons pu.cut_plot_and_write_alt_layer(st.lower_external_surface, 'triax', label, bounding_polygon, airfoil='lower') pu.cut_plot_and_write_alt_layer(st.lower_external_surface, 'gelcoat', label, bounding_polygon, airfoil='lower') p
u.cut_plot_and_write_alt_layer(st.lower_internal_surface_2, 'resin', label, bounding_polygon, airfoil='lower') pu.cut_plot_and_write_alt_layer(st.lower_internal_surface_2, 'triax', label, bounding_polygon, airfoil='lower') # TE reinforcement, upper 1 ------------------------------------------------ lab...
ngcurrier/ProteusCFD
tools/extractCM.py
Python
gpl-3.0
990
0.009091
#!/usr/bin/env python import sys import math def main(): if len(sys.argv) != 3: print('USAGE: ' + sys.argv[0] + ' <filename> ' + ' <boundary id of interest>') return targetString = 'Moment coefficient for body[' + sys.argv[2] targetTimestep = ': \n' filename = sys.argv[1] t...
ame, 'r') except: print('File does not exist: ' + filename) return for line in f: if targetTimestep in line: 'replace the colon and newline with a comma
so we get a CSV file' line = line.replace (targetTimestep, ', ') print(line), continue if targetString in line: 'find the last colon and get the string after that which is the numeric value' 'of the lift coefficient' pos = line.rfind(':') ...
mixman/djangodev
tests/regressiontests/localflavor/it/tests.py
Python
bsd-3-clause
2,453
0.000815
from django.contrib.localflavor.it.forms import (ITZipCodeField, ITRegionSelect, ITSocialSecurityNumberField, ITVatNumberField) from django.test import SimpleTestCase class ITLocalFlavorTests(Simp
leTestCase): def test_ITRegionSelect(self): f = ITRegionSelect() out = u'''<select name="regions"> <option value="ABR">Abruzzo</option> <option value="BAS">Basilicata</option> <option value="CAL">Calabria</option> <option value="CAM">Campania</option> <option value="EMR">Emilia-Romagna</option> <opt...
-Venezia Giulia</option> <option value="LAZ">Lazio</option> <option value="LIG">Liguria</option> <option value="LOM">Lombardia</option> <option value="MAR">Marche</option> <option value="MOL">Molise</option> <option value="PMN" selected="selected">Piemonte</option> <option value="PUG">Puglia</option> <option value="SAR...
mholtrop/Phys605
Python/DevLib/MCP320x.py
Python
gpl-3.0
11,971
0.002423
#!/usr/bin/env python # # MCP320x # # Author: Maurik Holtrop # # This module interfaces with the MCP300x or MCP320x family of chips. These # are 10-bit and 12-bit ADCs respectively. The x number indicates the number # of multiplexed analog inputs: 2 (MCP3202), 4 (MCP3204) or 8 (MCP3208) # Communications with this chi...
202, 4 for the MCP3204 or 8 for the MCS3208.""" self._CLK = clk_pin self._MOSI = mosi_pin self._MISO = miso_pin self._CS_bar = cs_bar_pin chip_dictionary = { "MCP3202": (2, 12), "MCP3204": (4, 12), "MCP3208": (8, 12), ...
P3004": (4, 10), "MCP3008": (8, 10) } if chip in chip_dictionary: self._ChannelMax = chip_dictionary[chip][0] self._BitLength = chip_dictionary[chip][1] elif chip is None and (channel_max is not None) and (bit_length is not None): self._Channe...
nathangeffen/tbonline-old
tbonlineproject/external/filebrowser/models.py
Python
mit
51
0.019608
# This fil
e is only necessary for the tests to work
abutcher/Taboot
taboot-func/__init__.py
Python
gpl-3.0
851
0
# -*- coding: utf-8 -*- # Taboot - Client utility for performing deployments with Func. # Copyright © 2009, Red Hat, Inc. # # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it
will be useful, # 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.or...
foolcage/fooltrader
fooltrader/datasource/tdx.py
Python
mit
854
0.004684
# -*- coding: utf-8 -*- from pytdx.hq import TdxHq_API from fooltrader.api import technical from fooltrader.contract.data_contract import KDATA_COLUMN_SINA from fooltrader.utils.utils import get_exchange def get_tdx_kdata(security_item, start, end): api = TdxHq_API() with api.connect(): # open close...
df = api.get_k_data(security_item['code'], start, end) df = df[['date', 'code', 'low', 'open', 'close', 'high', 'vol', 'amount']] df['securityId'] = df['code'].apply(lambda x: 'stock_{}_{}'.format(get_exchange(x), x)) df['vol'] = df['vol'].apply(lambda x: x * 100) df.columns = KD...
ame__ == '__main__': pass
moniquehw/quoterizer
quotes/migrations/0001_initial.py
Python
gpl-3.0
1,134
0.002646
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2017-07-24 20:36 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.Crea...
dels.FloatField(default=0)), ], ), migrations.CreateModel( name='Quote',
fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=255)), ], ), migrations.AddField( model_name='lineitem', name='quote', ...
fake-name/ReadableWebProxy
WebMirror/management/rss_parser_funcs/feed_parse_extractMkkbunkotoikemenWordpressCom.py
Python
bsd-3-clause
565
0.033628
def extractMkkbunkotoikemenWordpressCom(item): ''' Parser for 'mkkbunkotoikemen.wordpress.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None tagmap = [ ('PRC', 'PRC', 'translate...
_buil
dReleaseMessage(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type) return False
cosee-concourse/slack-upload-resource
opt/resource/slack_post.py
Python
mit
3,302
0.004543
import os from concourse_common import jsonutil def post_successful_tests(filepath, payload, sc, total_string): sc.api_call("chat.postMessage", as_user=True, channel=jsonutil.get_params_value(payload, "channel"), attachments=[{"fallback": "Test Results", ...
g, "short": False}]}]) def post_failed_tests(failed_string, filepath, payload, sc, total_string): sc.api_call(
"chat.postMessage", as_user=True, channel=jsonutil.get_params_value(payload, "channel"), attachments=[{"fallback": "Test Results", "pretext": "Test results of " + os.environ["BUILD_JOB_NAME"] + " in version " + open( os.path...
HEPData/hepdata
hepdata/modules/search/webpack.py
Python
gpl-2.0
1,105
0
# # This file is part of HEPData. # Copyright (C) 2016 CERN. # # HEPData is free software; you can redistribute it and/or # modify it unde
r 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. # # HEPData is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FIT...
py of the GNU General Public License # along with HEPData; if not, write to the Free Software Foundation, Inc., # 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. # from flask_webpackext import WebpackBundle search_js = WebpackBundle( __name__, 'assets', entry={ 'hepdata-search-js': './js/he...
thandal/passe-partout
pp/pp_parse.py
Python
mit
1,809
0.028192
# The following parse_* methods are from bitcoin-abe import base58 def parse_TxIn(vds): d = {} d['prevout_hash'] = vds.read_bytes(32) d['prevout_n'] = vds.read_uint32() d['scriptSig'] = vds.read_bytes(vds.read_compact_size()) d['sequence'] = vds.read_uint32() return d def parse_TxOut(vds): d = {} d['...
return d def parse_BlockHeader(vds): d = {} blk_magic = vds.read_bytes(4) #if blk_ma
gic != '\xf9\xbe\xb4\xd9': # if blk_magic != '\xbf\xfa\xda\xb5': # raise Exception('Bad magic' + str(blk_magic)) # return d blk_length = vds.read_int32() header_start = vds.read_cursor d['version'] = vds.read_int32() d['hashPrev'] = vds.read_bytes(32) d['hashMerkleRoot'] = vds.read_bytes(32) d['nTim...
QuantCrimAtLeeds/PredictCode
tests/network_test.py
Python
artistic-2.0
25,390
0.037968
import pytest import unittest.mock as mock import open_cp.network as network import open_cp.data import numpy as np import datetime def test_PlanarGraphBuilder(): b = network.PlanarGraphBuilder() assert b.add_vertex(0.2, 0.5) == 0 b.set_vertex(5, 1, 2) b.add_edge(0, 5) g = b.build() assert g....
ngths == [pytest.approx((np.sqrt(25+16)+np.sqrt(32))/2)] def test_shortest_edge_paths(graph1): dists, prevs = network.shortest_edge_paths(graph1, 0) assert dists == {0:5, 1:5} assert prevs == {0:0, 1:1}
dists, prevs = network.shortest_edge_paths(graph1, 0, 0.1) assert dists == {0:1, 1:9} assert prevs == {0:0, 1:1} def test_shortest_paths(graph1): dists, prevs = network.shortest_paths(graph1, 0) assert dists == {0:0, 1:10, 2:-1, 3:-1, 4:-1} assert prevs == {0:0, 1:0} dists, prevs = network.shor...
oleiade/Elevator
elevator/__init__.py
Python
mit
177
0
#!/usr/bin/env python # -*- coding: utf-8 -*- version = (
0, "5d") __title__ = "Elevator" __author__ = "Oleiade" __license__ = "MIT" __version__ = '.'.join(map(str, vers
ion))
coala-analyzer/coala-quickstart
tests/generation/UtilitiesTest.py
Python
agpl-3.0
11,382
0.000088
import inspect import itertools import types import unittest from tempfile import NamedTemporaryFile from tests.test_bears.AllKindsOfSettingsDependentBear import ( AllKindsOfSettingsDependentBear) from coala_quickstart.generation.Utilities import ( contained_in, get_hashbang, get_default_args, get_all...
self.assertEqual(get_default_args(AllKindsOfSettingsDependentBear.run), {'chars': False,
'dependency_results': {}, 'max_line_lengths': 1000, 'no_chars': 79, 'use_spaces': None, 'use_tabs': False}) def test_get_all_args(self): empty = inspect._empty self.assertEqual(get_...
karanisverma/feature_langpop
librarian/utils/timer.py
Python
gpl-3.0
1,356
0
""" timer.py: Request timer statistical tool Code adapted from Bottle documentation Copyright 2014-2015, Outernet Inc. Some rights reserved. This software is free
software licensed under the terms of GPLv3. See COPYING file that comes with the source code, or http://www.gnu.org/licenses/gpl.txt. """ from __future__ import division import time from functools import wraps try: import resource except ImportError: # Platform does not support ``resources`` module. reso...
rss = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss # in KB return round(rss / 1024, 3) def request_timer(label): t_header = str('X-%s-Time' % label) m_header = str('X-%s-Mem' % label) def _timer(callback): @wraps(callback) def wrapper(*args, **kwargs): start = time....
erigones/esdc-ce
gui/docs/views.py
Python
apache-2.0
1,344
0.000744
from django.shortcuts import render, resolve_url from django.con
trib.auth.decorators import login_required from gui.decorators import profile_required from gui.utils import collect_view_data from gui.signals import view_faq from api.decorators import setting_required @login_required @profile_required def api(request): """ API Documentation view (via iframe).
""" context = collect_view_data(request, 'api_docs') return render(request, 'gui/docs/api.html', context) @login_required @profile_required def user_guide(request): """ User Guide view (via iframe). """ context = collect_view_data(request, 'user_guide') return render(request, 'gui/docs...
Ecotrust/F2S-MOI
moi/recommendations/migrations/0002_auto_20151230_0007.py
Python
apache-2.0
1,297
0.002313
# -*- coding: utf-8 -*- # Generated by Django 1.9 on 2015-12-30 00:07 from __future__ import unicode_literals from django.db import migrati
ons, models import django.db.models.deletion import wagtail.wagtailcore.fields class Migration(migrations.Migration
): dependencies = [ ('wagtailimages', '0010_change_on_delete_behaviour'), ('recommendations', '0001_initial'), ] operations = [ migrations.AddField( model_name='recommendation', name='displayTitle', field=wagtail.wagtailcore.fields.RichTextField(...
sqor/3rdeye
fetch_repos.py
Python
mit
789
0.032953
""" To use this, create a settings.py file and make these variables:
TOKEN=<oath token for github> ORG=<your org in github> DEST=<Path to download to> """ from github import Github from subprocess import call import os from settings import TOKEN, ORG, DEST def download(): """Quick and Dirty Download all repos function""" os.chdir(DEST) print "Downloading to destination: ", os.ge...
(ORG, repo.name)) total = len(repos) print "Found %s repos" % total count = 0 for repo in repos: count +=1 print "Cloning Repo [%s]/[%s]: %s" % (count, total, repo) call([u'git', u'clone', repo]) download()
higee/project_euler
11-20/12.py
Python
mit
439
0.009112
def count_factor(n, factor=0): for i in range(1, int(n**0.5)+1): if n % i == 0: factor += 2 return factor def nth_triangular_number(n): return int(n+(n*(n-1))/2
) def find_triangular_number_over(k, n=0): while count_factor(nth_triangular_number(n)) <= k: n += 1 return nth_triangular_number(n) def main(): print(find_triangular_number_over(500)) if __name__ == "__main__": m
ain()
jmluy/xpython
exercises/practice/robot-simulator/robot_simulator.py
Python
mit
201
0
# Globals for the directions # Change the values as you see fit EAST
= None NORTH = None WEST =
None SOUTH = None class Robot: def __init__(self, direction=NORTH, x_pos=0, y_pos=0): pass
plotly/python-api
packages/python/plotly/plotly/validators/scatter/unselected/textfont/_color.py
Python
mit
470
0.002128
import _plotly_utils.basevalida
tors class ColorValidator(_plotly_utils.basevalidators.ColorValidator): def __init__( self
, plotly_name="color", parent_name="scatter.unselected.textfont", **kwargs ): super(ColorValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "style"), role=kwargs.pop("role", "style"), **kw...
piller-imre/grimoire-tk
grimoire/document.py
Python
gpl-3.0
806
0.003722
""" Document class definition """ class Document(object): """Represents a document""" def __init__(self, id, name, type, path): if '\n' in name: raise ValueEr
ror('The document name cannot contain newline character!') if '\n' i
n type: raise ValueError('The document type cannot contain newline character!') if '\n' in path: raise ValueError('The document path cannot contain newline character!') self._id = id self._name = name self._type = type self._path = path @property ...
xenserver/xs-cbt-samples
cbt_import_whole_vdi.py
Python
bsd-3-clause
2,718
0.000368
#!/usr/bin/env python """ For a given vdi and import file this script will import a VDI on to a XS host. This script needs to be run whenever you want to restore a VDI to a previous version. example: python cbt_import_whole_vdi.py -ip <host address> -u <host username> -p <host password> -v <vdi uuid> -f <impo...
here. # Depends on CP-23051. urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) with requests.Session() as session: request = session.put(url, filehandle, verify=False) request.raise_for_status() def main(): parser = argparse.ArgumentParser...
parser.add_argument('-v', '--vdi-uuid', dest='vdi_uuid') parser.add_argument('-f', '--filename', dest='path') parser.add_argument('--as-new-vdi', dest='new_vdi', action='store_const', const=True, default=False, help='Create a new VDI for the import') ...
forslund/mycroft-core
mycroft/util/log.py
Python
apache-2.0
4,287
0
# Copyright 2017 Mycroft AI Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writin...
cls.handler = logging.StreamHandler(sys.stdout) cls.handler.setFormatter(formatter) config = mycroft
.configuration.Configuration.get(cache=False, remote=False) if config.get('log_format'): formatter = logging.Formatter(config.get('log_format'), style='{') cls.handler.setFormatter(formatter) cls.level = logging.getLevelNa...
Azure/azure-sdk-for-python
sdk/appservice/azure-mgmt-web/azure/mgmt/web/v2020_09_01/aio/_configuration.py
Python
mit
3,315
0.004223
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
self.redirect_policy = kwargs.get('redirect_poli
cy') or policies.AsyncRedirectPolicy(**kwargs) self.authentication_policy = kwargs.get('authentication_policy') if self.credential and not self.authentication_policy: self.authentication_policy = AsyncARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)
30loops/libthirty
libthirty/documents.py
Python
bsd-3-clause
6,039
0.001325
from docar import Document, Collection from docar import fields from docar.backends.http import HttpBackendManager from libthirty.state import uri, app_uri, service_uri, resource_collection_uri from libthirty.validators import naming, max_25_chars, naming_with_dashes import os HttpBackendManager.SSL_CERT = os.path....
username = fields.StringField(validators=[naming, max_25_chars]) email = fields.StringField() is_active = fields.Boolea
nField() class Account(Document): name = fields.StringField(validators=[naming, max_25_chars]) #users = fields.CollectionField(User) class Meta: backend_type = 'http' identifier = 'name' class CnameRecord(Document): record = fields.StringField() class Meta: backend_type...
LegNeato/buck
scripts/migrations/include_def.py
Python
apache-2.0
1,059
0.000944
import ast import label import repository import os class IncludeDef: """ Represents build file include definition like include_defs("//inclu
de/path"). """ def __init__(self, ast_call: ast.Call) -> None: self.ast_call = ast_call def get_location(self) -> str: """ Returns an include definition location. For include_defs("//include/path") it is "//include/path". """ return self.ast_call.args[0].s ...
"""Returns a label identifying a build extension file.""" return label.from_string(self.get_location()) def get_include_path(self, repo: repository.Repository): """Returns a path to a file from which symbols should be imported.""" l = self.get_label() return os.path.join(repo....
mapossum/SeymourSolo
tester.py
Python
gpl-3.0
495
0.006061
import
relayManager import dronekit class ShotManager(): def __init__(self): # see the shotlist in app/shots/shots.p print "init" def Start(self, vehicle): self.vehicle = vehicle # Initialize relayManager self.relayManager = relayManager.RelayManager(self) target = 'udp:127...
)
Freso/listenbrainz-server
listenbrainz/listenstore/tests/test_redislistenstore.py
Python
gpl-2.0
4,058
0.002957
# coding=utf-8 import datetime import logging import time import uuid from dateutil.relativedelta import relativedelta from redis.connection import Connection import listenbrainz.db.user as db_user from listenbrainz.db.testing import DatabaseTestCase from listenbrainz import config from listenbrainz.listen import Li...
, 'user_name': self.testuser['musicbrainz_id'], 'listened_at': int(time.time()), 'track_metadata': { 'artist_name': 'The Strokes', 'track_name': 'Call It Fate, Call It Karma', 'additional_info': {},
}, } self._redis.put_playing_now(listen['user_id'], listen, config.PLAYING_NOW_MAX_DURATION) playing_now = self._redis.get_playing_now(listen['user_id']) self.assertIsNotNone(playing_now) self.assertIsInstance(playing_now, Listen) self.assertEqual(playing_now....
loosecannon93/chittyrc
tests/chirc/tests/common.py
Python
apache-2.0
28,644
0.031804
import subprocess import tempfile import random import os import shutil import re import chirc.replies as replies from chirc.client import ChircClient from chirc.types import ReplyTimeoutException import pytest import time class IRCSession(): def __init__(self, chirc_exe = None, msg_timeout = 0.1, randomize...
user[0] == "
+": mode = "+v" self.set_channel_mode(users[op], op, channel, mode, nick) for user2 in joined: self.verify_relayed_mode(users[user2], from_nick=op, channel=channel, mode=mode, mode_nick=nick) ...
alexbruy/QGIS
python/plugins/processing/gui/FileSelectionPanel.py
Python
gpl-2.0
3,127
0.00064
# -*- coding: utf-8 -*- """ *************************************************************************** FileSelectionPanel.py --------------------- Date : August 2012 Copyright : (C) 2012 by Victor Olaya Email : volayaf at gmail dot com ********************...
* * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public L
icense as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ******************************************************************...
plotly/plotly.py
packages/python/plotly/plotly/validators/scatter3d/marker/colorbar/title/font/_family.py
Python
mit
558
0
import _plotly_utils.basevalidators class FamilyValidator(_plotly_utils.basevalidators.StringValidator): def __init__( self, plotly_name="family", pare
nt_name="scatter3d.marker.colorbar.title.font", **kwargs ): super(FamilyValidator, self).__init__( plotly_name=plotly_name, parent_name=
parent_name, edit_type=kwargs.pop("edit_type", "calc"), no_blank=kwargs.pop("no_blank", True), strict=kwargs.pop("strict", True), **kwargs )
thinkle/gourmet
gourmet/plugins/import_export/gxml_plugin/gxml_exporter_plugin.py
Python
gpl-2.0
2,889
0.014192
import re from gourmet.plugin import ExporterPlugin from gourmet.convert import seconds_to_timestring, float_to_frac from . import gxml2_exporter from gettext import gettext as _ GXML = _('Gourmet XML File') class GourmetExportChecker: def check_rec (self, rec, file): self.txt = file.read() self...
c.yields: assert re.search(r'<yields>\s*%s\s*%s\s*</yields>'%( sel
f.rec.yields, self.rec.yield_unit), self.txt) or \ re.search(r'<yields>\s*%s\s*%s\s*</yields>'%( float_to_frac(self.rec.yields), self.rec.yield_unit), ...
fajoy/horizon-example
openstack_dashboard/dashboards/project/instances/urls.py
Python
apache-2.0
1,941
0.000515
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Copyright 2012 Nebula, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # no...
stack_dashboard.dashboards.project.instances.views' urlpatterns = patterns(VIEW_MOD, url(r'^$', IndexVi
ew.as_view(), name='index'), url(r'^launch$', LaunchInstanceView.as_view(), name='launch'), url(r'^(?P<instance_id>[^/]+)/$', DetailView.as_view(), name='detail'), url(INSTANCES % 'update', UpdateView.as_view(), name='update'), url(INSTANCES % 'console', 'console', name='console'), url(INSTANCES % '...
jazinga/psutil
examples/process_detail.py
Python
bsd-3-clause
3,753
0.00373
#!/usr/bin/env python # $Id$ """ Print detailed information about a process. """ import os import datetime import socket import sys import psutil from psutil._compat import namedtuple def convert_bytes(n): if n == 0: return '0B' symbols = ('k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y') prefix = {} ...
lip, lport = conn.local_address if not conn.remote_address: rip, rport = '*', '*' else: rip, rport = conn.remote_address print_('', '%s:%s -> %s:%s type=%s status=%s' \ % (lip, lport, rip, rport, type, conn.status)) def ma...
) == 1: sys.exit(run(os.getpid())) elif len(argv) == 2: sys.exit(run(int(argv[1]))) else: sys.exit('usage: %s [pid]' % __file__) if __name__ == '__main__': sys.exit(main())
mekkablue/Glyphs-Scripts
Guides/Guides through All Selected Nodes.py
Python
apache-2.0
2,786
0.037688
#MenuTitle: Guides through All Selected Nodes # -*- coding: utf-8 -*- from __future__ import division, print_function, unicode_literals __doc__=""" Creates guides through all selected nodes. """ from Foundation import NSPoint import math thisFont = Glyphs.font # frontmost font selectedLayers = thisFont.selectedLayers...
rees) of the straight line between firstPoint and secondPoint, 0 degrees being the second point to the right of first point. firstPoint, secondPoint: must be NSPoint or GSNode """
xDiff = secondPoint.x - firstPoint.x yDiff = secondPoint.y - firstPoint.y return math.degrees(math.atan2(yDiff,xDiff)) def newGuide( position, angle=0 ): try: # GLYPHS 3 newGuide = GSGuide() except: # GLYPHS 2 newGuide = GSGuideLine() newGuide.position = position newGuide.angle = angle return newGuide ...
rs2/pandas
pandas/core/groupby/base.py
Python
bsd-3-clause
3,488
0.000573
""" Provide basic components for groupby. These definitions hold the allowlist of methods that
are exposed on the SeriesGroupBy and the DataFrameGroupBy objects. """ from __future__ import annotations impor
t dataclasses from typing import Hashable @dataclasses.dataclass(order=True, frozen=True) class OutputKey: label: Hashable position: int # special case to prevent duplicate plots when catching exceptions when # forwarding methods from NDFrames plotting_methods = frozenset(["plot", "hist"]) common_apply_all...
qedsoftware/commcare-hq
corehq/apps/style/forms/widgets.py
Python
bsd-3-clause
10,116
0.00257
import collections from django import forms from django.forms.fields import MultiValueField, CharField from django.forms.utils import flatatt from django.forms.widgets import ( CheckboxInput, Input, RadioChoiceInput, RadioSelect, RadioFieldRenderer, TextInput, MultiWidget, Widget, ) from...
-bootstrap.css') } js = ('select2-3.5.2-legacy/select2.js',) def __init__(self, attrs=None, page_size=20): self.page_si
ze = page_size super(Select2Ajax, self).__init__(attrs) def set_url(self, url): self.url = url def _clean_initial(self, val): if isinstance(val, collections.Sequence) and not isinstance(val, (str, unicode)): return {"id": val[0], "text": val[1]} else: re...
michaelhelmick/lassie
tests/test_open_graph.py
Python
mit
2,426
0.001237
import lassie from .base import LassieBaseTestCase class LassieOpenGraphTestCase(LassieBaseTestCase): def test_open_graph_all_properties(self): url = 'http://lassie.it/open_graph/all_properties.html' data = lassie.fetch(url) self.assertEqual(data['url'], url) self.assertEqual(dat...
tion/x-shockwave-flash') def test_open_graph_no_og_title_no_og_url(self): url = 'http://lassie.it/open_graph/no_og_title_no_og_url.html' data = lassie.fetch(url) self.assertEqual(data['url'], url) self.assertEqual(data['title'], 'Lassie Open Graph Test | No og:title, No og:url') ...
ie.it/open_graph/og_image_plus_two_body_images.html' data = lassie.fetch(url) # Try without passing "all_images", then pass it self.assertEqual(len(data['images']), 1) data = lassie.fetch(url, all_images=True) self.assertEqual(len(data['images']), 3) image_0 = data['...
mkfifo/open-source-stats
scripts/gen_colour_palette.py
Python
gpl-3.0
6,213
0.002253
#!/usr/bin/python3 import sys import os # this script allows the loading of palettes from files # when invoked you must specify a palette # google-blue.hex # google-light-blue.hex # old-blue.rgb # # each palette must contain 10 colours for the graduations between 0 and 100 % # and an 11th colour for ...
ding and trailing whitespace are ignored: # # chris@Ox1b open-source-stats(master)-> cat palettes/old-blue.rgb # 227 242 253 # 187 222 251 # 144 202 249 # 100 181 246 # 66 165 245 # 33 150 243 # 30 136 229 # 25 118 210 # 21 101 192 # 13 71 161 # 124 1 159 # def ...
b = hex[4:6] return [ "%4d" %(int(r,16)), "%4d" %(int(g,16)), "%4d" %(int(b,16)) ] def rgb_str_to_list(rgbstr): parts = rgbstr.split() out = [] for part in parts: part = "%3d" %(int(part)) out.append(part) print(part) return out def parse_pale...
stanvit/pyomapic
__init__.py
Python
mit
31
0.032258
from
PyOMAPIc import PyOMA
PIc
pitomba/libra
libra/settings.py
Python
mit
259
0
from settings_base import * PORT =
80 SERVER_NAME = 'ht
tp://libra.pitomba.org:%s' % PORT MONGODB_DATABASE_URL = "localhost" MONGODB_DATABASE_PORT = 27017 MONGODB_DATABASE_USER = "usr_libra" MONGODB_DATABASE_PWD = "usr_libra" MONGODB_DATABASE_POOL_SIZE = 50
MyRobotLab/pyrobotlab
home/kwatters/harry/gestures/italianhello.py
Python
apache-2.0
2,293
0.066289
def italianhello(): i01.setHandSpeed("left", 0.60, 0.60, 1.0, 1.0, 1.0, 1.0) i01.setHandSpeed("right", 1.0, 1.0, 1.0, 1.0, 1.0, 1.0) i01.setArmSpeed("left", 1.0, 1.0, 1.0, 1.0) i01.setArmSpeed("right", 1.0, 1.0, 1.0, 1.0) i01.setHeadSpeed(0.65, 0.75) i01.moveHead(105,78) i01.moveArm("left",78,48,37,11) ...
oveArm("left",5,94,28,15) i01.moveArm("right",5,82,28,15) i01.moveHand("left",42,58,42,55,71,35) i01.moveHand("right",81,50,82,60,105,113) ear.res
umeListening()
jimi-c/ansible
lib/ansible/plugins/cliconf/junos.py
Python
gpl-3.0
7,917
0.001768
# # (c) 2017 Red Hat Inc. # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is d...
@configure def discard_changes(self): command = 'rollback 0'
for cmd in chain(to_list(command), 'exit'): self.send_command(cmd) @configure def validate(self): return self.send_command('commit check') @configure def compare_configuration(self, rollback_id=None): command = 'show | compare' if rollback_id is not None: ...
why168/PythonProjects
MxOnlie/extra_apps/xadmin/apps.py
Python
artistic-2.0
396
0
from django.apps import AppConfig from django.core import checks from django.utils.translation import ugettext_lazy as _ import xadmin class XAdminConfig(AppConfig): """Simple AppConfig which does not do automatic discovery.""" name = '
xadmin' verbose_name = _("Administration") def ready(self): self.module.autodiscover()
setattr(xadmin, 'site', xadmin.site)
gmjosack/modlunky
setup.py
Python
mit
1,002
0.001996
#!/usr/bin/env python from distutils.core import setup execfile('modlunky/version.py') with open('requirements.txt') as requirements: required = requirements.read().splitlines() kwargs = { "name": "modlunky", "version": str(__version__), "packages": ["modlunky"], "scripts": ["bin/modlunky"], ...
thor": "Gary M. Josack", "maintainer": "Gary M. Josack", "author_email": "gary@byoteki.com", "maintainer_email": "gary@byoteki.com", "license": "MIT", "url": "https://github.com/gmjosack/modlunky", "download_url": "https://github.com/gmjosack/modlunky/archive/master.tar.gz", "classifiers": [...
Libraries :: Python Modules", ] } if required: kwargs["install_requires"] = required setup(**kwargs)
bladealslayer/nettraf-scripts
tcp2tcp.py
Python
gpl-2.0
2,816
0.003196
#!/usr/bin/python ############################################################################ # tcp2tcp.py # # v0.1 # # ...
= re.split('\t', line[:-1]) cstart = float(l[8]) cend = float(l[9]) if cend <= cstart: continue raise Exception('bad connection times') cbytes = 0 fr.seek(f_index) seeking = True for f in fr: ll = len(f) f = re.split('\t', f[:-1]) ts = float(f[0]) ...
t(f[1]) thr = float(cbytes) / (cend - cstart) print line[:-1] + '\t' + str(thr)
obi-two/Rebelion
data/scripts/templates/object/ship/player/shared_player_z95.py
Python
mit
434
0.048387
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Ship() result.template = "ob
ject/ship/player/shared_player_z95.iff" result.a
ttribute_template_id = -1 result.stfName("space_ship","player_z95") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
bennylope/django-lokoj
locations/utils.py
Python
mit
5,917
0.00169
import csv from django.db.models import Max from django.utils.translation import ugettext_lazy as _ from urllib2 import URLError from googlemaps import GoogleMaps, GoogleMapsError from locations.models import Location from locations.exceptions import LocationEncodingError class CsvParseError(csv.Error): pass d...
for point in points: lat += point[0] lng += point[1] return (lat/count, lng/count) def get_address_latlng(location): """ Requests the latitude and longitude for the given location's address. Uses the Google Maps API, but
could be extended to use a different API. """ address = u"%s, %s, %s %s" % (location.street_address, location.city, location.state, location.postal_code) try: return GoogleMaps().address_to_latlng(address) except GoogleMapsError: raise LocationEncodingError(_("Google reported...
fraunhoferfokus/fixmycity
dummy/templatetags/value_from_settings.py
Python
lgpl-3.0
2,196
0.013206
''' /******************************************************************************* * * Copyright (c) 2015 Fraunhofer FOKUS, All rights reserved. * * This library 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 Sof...
= settingsvar[1:-1] if settingsvar[0] == '"' else settingsvar asvar = None bits = bits[2:] if len(bits) >= 2 and bits[-2] == 'as': asvar = bits[-1] bits = bits[:-2] if len(bits): raise TemplateSyntaxError("'value_from_settings' didn't recognise " \ "the arguments '%s'" % ", ".join(bits)) re...
def __init__(self, settingsvar, asvar): self.arg = Variable(settingsvar) self.asvar = asvar def render(self, context): ret_val = getattr(settings,str(self.arg)) if self.asvar: context[self.asvar] = ret_val return '' else: return ret_val
mlperf/training_results_v0.5
v0.5.0/google/cloud_v3.8/ssd-tpuv3-8/code/ssd/model/tpu/models/official/retinanet/retinanet_architecture.py
Python
apache-2.0
25,570
0.004263
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www
.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distribute
d 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. # ============================================================================== """Re...
PlanTool/plantool
code/Uncertainty/T0/translator/generators/sortnum.py
Python
gpl-2.0
3,602
0.009162
#! /usr/bin/env python # -*- coding: latin-1 -*- # Copyright (C) 2006 Universitat Pompeu Fabra # # Permission is hereby granted to distribute this software for # non-commercial research purposes, provided that this copyright # notice is included with any such distribution. # # THIS SOFTWARE IS PROVIDED "AS IS" WI...
>> domain, """ ))""" for i in range(1,n+1): for j in range(i+1,n+1): if i != j: print_act(i
,j) print >> domain, """ ) """ problem = file(path + "/p.pddl", "w") if cff: t = '' else: t = '(and ' print >> problem, """ (define (problem s%d) (:domain %s) (:init %s""" % (n,name,t), for i in range(1,n+1): for j in range(1,n+1): if i != j: print >> problem, """ ...
mjasher/gac
original_libraries/flopy-master/flopy/modflow/mfupw.py
Python
gpl-2.0
13,021
0.010598
import sys import numpy as np from flopy.mbase import Package from flopy.utils import util_2d,util_3d from flopy.modflow.mfpar import ModflowPar as mfpar class ModflowUpw(Package): 'Upstream weighting package class\n' def __init__(self, model, laytyp=0, layavg=0, chani=1.0, layvka=0, laywet=0, iupwcb...
f noparcheck: self.options = self.options + 'NOPARCHECK ' self.hk = util_3d(model,(nlay,nrow,ncol),np.float32,hk,name='hk',locat=self.unit_number[0]) self.hani = util
_3d(model,(nlay,nrow,ncol),np.float32,hani,name='hani',locat=self.unit_number[0]) self.vka = util_3d(model,(nlay,nrow,ncol),np.float32,vka,name='vka',locat=self.unit_number[0]) self.ss = util_3d(model,(nlay,nrow,ncol),np.float32,ss,name='ss',locat=self.unit_number[0]) self.sy = util_3d(model,...
DonYum/LogAna
app/log_analyzer/__init__.py
Python
mit
101
0.009901
fr
om flask import Blueprint log_analyzer = Blueprint('log_analyzer', __name__) from . import views
curoverse/libcloud
libcloud/test/compute/test_gce.py
Python
apache-2.0
123,700
0.001156
# 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 ...
rgs) def test_default_scopes(self): self.assertEqual(self.driver.scopes, None) def test_timestamp_to_datetime(self): timestamp1 = '2013-06-26T10:05:19.340-07:00' datetime1 = datetime.datetime(2013, 6, 26, 17, 5, 19) self.assertEqual(timestamp_to_datetime(timestamp1), datetime1)...
43:15.000-00:00' datetime2 = datetime.datetime(2013, 6, 26, 17, 43, 15) self.assertEqual(timestamp_to_datetime(timestamp2), datetime2) def test_get_object_by_kind(self): obj = self.driver._get_object_by_kind(None) self.assertIsNone(obj) obj = self.driver._get_object_by_kind(...
ancho85/pylint-playero-plugin
tests/fulltest.py
Python
gpl-2.0
2,139
0.004675
import os import sys import unittest from logilab.common import testlib from pylint.testutils import make_tests, LintTestUsingFile, cb_test_gen, linter import ConfigParser HERE = os.path.dirname(os.path.abspath(__file__)) PLUGINPATH = os.path.join(HERE, "..") linter.prepare_import_path(PLUGINPATH) linter.load_plugin_...
"config", ".pylintrc")) convs = ['C0111', 'C0103', 'C0301', 'C0303', 'C0304', 'C0321'] warns = ['W0141', 'W0142', 'W0212', 'W0312', 'W0401', 'W0403', 'W0511', 'W0512', 'W0614', 'W0622'] refac = ['R0903', 'R0904', 'R0913'] for disabled in convs + warns + refac: linter.disable(disabled
) config = ConfigParser.SafeConfigParser() config.read(os.path.join(HERE, "..", "config", "playero.cfg")) PLAYEROPATH = config.get('paths', os.name) sys.path.append(os.path.join(PLAYEROPATH, "core")) for scriptdir in ["base", "standard", "extra/StdPy"]: for pydir in ['records', 'windows', 'reports', 'routines', 'd...
EddyCodeIt/SPA_Project_2016_Data_Rep-Quering
db_downgrade.py
Python
apache-2.0
600
0.006667
# code source: https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-iv-database from migr
ate.versioning import api from config import SQLALCHEMY_DATABASE_URI from config import SQLALCHEMY_MIGRATE_REPO v = api.db_version(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO) api.downgrade(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO, v - 1) print 'Current database version: ' + str(api.db_version(SQLALCHEMY_D...
ATE_REPO)) # This script downgrades database by 1 revision every time it runs. # To downgrade in multiple revisions, run script as many as needed.
zaneb/heat-convergence-prototype
scenarios/basic_create_rollback.py
Python
apache-2.0
358
0
e
xample_template = Template({ 'A': RsrcDef({}, []), 'B': RsrcDef({}, []), 'C': RsrcDef({'a': '4alpha'}, ['A', 'B']), 'D': RsrcDef({'c': GetRes('C')}, []), 'E': RsrcDef({'ca': GetAtt('C', 'a')}, []), }) engine.create_stack('foo', example_template) engine.noop(3) engine.rollback_stack('foo') engine.
noop(6) engine.call(verify, Template())
SlateScience/MozillaJS
js/src/python/mozboot/mozboot/openbsd.py
Python
mpl-2.0
954
0.013627
# This Source Code For
m is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at http://mozilla.org/MPL/2.0/. import os from mozboot.base import BaseBootstrapper class OpenBSDBootstrapper(BaseBootstrapper): def __init__(self, version): Ba...
z because there's no other way to say "any autoconf-2.13" self.run_as_root(['pkg_add', '-z', 'mercurial', 'llvm', 'autoconf-2.13', 'yasm', 'gtk+2', 'libIDL', 'gmake', 'gtar', 'wget', 'unzip', ...
Rosebotics/cwc-projects
lego-ev3/examples/analog_sensors/ir_sensor/print_beacon_seeking.py
Python
gpl-3.0
1,582
0.003793
#!/usr/bin/env python3 """ The goal of this example is to show you the syntax for IR seeking readings. When using IR-SEEK with a remote control you get both heading and distance data. The code below shows the syntax for beacon seeking. Additionally it's good to play with a demo so that you can see how well or not we...
touch sensor to exit") print("--------------------------------------------") ev3.Sound.speak("Printing beacon seeki
ng").wait() touch_sensor = ev3.TouchSensor() ir_sensor = ev3.InfraredSensor() assert touch_sensor assert ir_sensor ir_sensor.mode = "IR-SEEK" while not touch_sensor.is_pressed: current_heading = ir_sensor.value(0) current_distance = ir_sensor.value(1) print("IR Heading...
artur-shaik/qutebrowser
tests/unit/misc/test_split.py
Python
gpl-3.0
6,878
0.000583
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: # Copyright 2014-2015 Florian Bruhin (The Compiler) <mail@qutebrowser.org> # # This file is part of qutebrowser. # # qutebrowser 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 S...
put, keep=True) assert ''.join(items) == split_test_case.input def test_split_keep(self, split_test_case): """Test splitting with keep=True.""" items = split.split(split_test_case.input, keep=True) assert items == split_test_case.no_keep class TestSimpleSplit: """Test simple_...
['f', '\ti', '\ts', '\th'], 'foo\nbar': ['foo', '\nbar'], } @pytest.mark.parametrize('test', TESTS) def test_str_split(self, test): """Test if the behavior matches str.split.""" assert split.simple_split(test) == test.rstrip().split() @pytest.mark.parametrize('s, maxsplit', ...
cinp/python
cinp/common.py
Python
apache-2.0
4,279
0.038093
import re import sys class URI(): def __init__( self, root_p
ath ): super().__init__() if root_path[-1]
!= '/' or root_path[0] != '/': raise ValueError( 'root_path must start and end with "/"' ) self.root_path = root_path self.uri_regex = re.compile( r'^({0}|/)(([a-zA-Z0-9\-_.!~*<>]+/)*)([a-zA-Z0-9\-_.!~*<>]+)?(:([a-zA-Z0-9\-_.!~*\'<>]*:)*)?(\([a-zA-Z0-9\-_.!~*<>]+\))?$'.format( self.root_path ) ) def ...
sgerhart/ansible
test/units/modules/network/cnos/cnos_module.py
Python
mit
3,502
0.000571
# Copyrig
ht (C) 2017 Lenovo, Inc. # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free
Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed 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 ...
eunchong/build
masters/master.client.mojo/master_source_cfg.py
Python
bsd-3-clause
386
0.005181
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is govern
ed by a BSD-style license that can be # found in the LICENSE file. from master import gitiles_poller def Update(config, active_master, c): master_poller = gitiles_poller.GitilesPoller( 'https://chromium.googlesource.com/external/mojo
') c['change_source'].append(master_poller)
bm2-lab/MLClass
cgh_deep_learning/mnist_mlp.py
Python
apache-2.0
1,723
0.001741
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('data', one_hot=True) mnist_train = mnist.train mnist_val = mnist.validation p = 28 * 28 n = 10 h1 = 300 func_act = tf.nn.sigmoid x_pl = tf.placeholder(dtype=tf.float32, shape=[None, p]) y_pl = tf.pl...
ccuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) eta = 0.3 train_op = tf.train.AdagradOptimizer(learning_rate=0.3).minimize(cross_entropy) batch_size = 50 batch_per_epoch = mnist_train.num_examples // batch_size epoch = 2 with tf.Session() as sess: tf.global_variables_initializer().run() x_va...
for sp in range(batch_per_epoch): xtr, ytr = mnist_train.next_batch(batch_size) loss_value, _ = sess.run([cross_entropy, train_op], feed_dict={x_pl: xtr, y_pl: ytr}) if sp == 0 or (sp + 1) % 100 == 0: print(f'Loss: {loss_value:.4f}') acc = sess.run(accuracy, f...
plotly/plotly.py
packages/python/plotly/plotly/validators/carpet/baxis/_tickvals.py
Python
mit
407
0.002457
import _plotly_utils.basevalidators class TickvalsValidator(_plotly_utils.basevalidators.DataArrayValidator): def __init__(self, plotly_name="t
ickvals", parent_name="carpet.baxis", **kwargs): super(TickvalsValidator, self).__init__(
plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "calc"), **kwargs )
StepicOrg/django-oauth-toolkit
oauth2_provider/admin.py
Python
bsd-2-clause
1,114
0.000898
from django.contrib import admin from .models import Grant, AccessToken, RefreshToken, get_application_model class ApplicationAdmin(admin.ModelAdmin): list_display = ("name", "user", "client_type", "authorization_grant_ty
pe") list_filter = ("client_type", "authorization_grant_type", "skip_authorization") radio_fields = { "client_type": admin.HORIZONTAL, "authorization_grant_type": admin.VERTICAL, } raw_id_fields = ("user", ) class GrantAdmin(admin.ModelAdmin): list_display = ("code", "application",...
lay = ("token", "user", "application", "expires") raw_id_fields = ("user", ) class RefreshTokenAdmin(admin.ModelAdmin): list_display = ("token", "user", "application") raw_id_fields = ("user", "access_token") Application = get_application_model() admin.site.register(Application, ApplicationAdmin) admin...
lmotta/Roam
tests/__init__.py
Python
gpl-2.0
234
0.008547
import os import sys # Add parent directory to path to make test aware of other modules srcfolder = os.path.abspath(os.path.jo
in(os.path.dirname(__file__), '..', "src")) if srcfolder not in sys.path: sys.path.a
ppend(srcfolder)
gamechanger/kafka-python
test/service.py
Python
apache-2.0
3,648
0.003289
import logging import os import re import select import subprocess import threading import time __all__ = [ 'ExternalService', 'SpawnedService', ] log = logging.getLogger(__name__) class ExternalService(object): def __init__(self, host, port): log.info("Using already running service at %s:%d",...
stderr=subprocess.PIPE) self.alive = True def _despawn(s
elf): if self.child.poll() is None: self.child.terminate() self.alive = False for _ in range(50): if self.child.poll() is not None: self.child = None break time.sleep(0.1) else: self.child.kill() def run...
yejia/order_system
service_order/urls.py
Python
mit
542
0.00369
from django.conf.urls import patterns, include, url from service_order import views, data_views urlpatterns = patterns('', url(r'^$', views.index), url(r'^order_state_machi
ne/$', views.order_state_machine), url(r'^make_order/$', views.make_order), url(r'^make_order2/$', views.make_order2), url(r'^make_order3/$', views.make_order3), url(r'^create_order/$', views.create_order), url(r'^view_refund_sheet/$', views.view_refund_sheet), url(r'^data/validate_code/',...
views.validate_code), )
PetePriority/home-assistant
tests/components/google/test_calendar.py
Python
apache-2.0
16,362
0
"""The tests for the google calendar component.""" # pylint: disable=protected-access import logging import unittest from unittest.mock import patch, Mock import pytest import homeassistant.components.calendar as calendar_base from homeassistant.components.google import calendar import homeassistant.util.dt as dt_uti...
ent device_name = 'Test All Day' cal = calendar.GoogleCalendarEventDevice(self.hass, None, '', {'name': device_name}) assert cal.name == device_name assert cal.state == STATE_OFF assert not cal.offset_reached() assert...
'offset_reached': False, 'start_time': '{} 00:00:00'.format(event['start']['date']), 'end_time': '{} 00:00:00'.format(event['end']['date']), 'location': event['location'], 'description': event['description'], } @patch('homeassistant.components.google....
AdrianGaudebert/socorro
socorro/unittest/cron/jobs/base.py
Python
mpl-2.0
1,178
0
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from socorro.unittest.cron.setup_configman import ( get_config_manager_for_crontabber, ) from crontabber.tests impo...
verriding the implementation here, we get a default Socorro configuration file with many of the standard Socorro defaults already in place: logging, executors, etc. This allows the bootstraping of the integration tests to participate fully with the environment variables, commandline argu...
ts offers""" config = get_config_manager_for_crontabber().get_config() return config
uweschmitt/emzed_optimizations
tests/test_sample.py
Python
bsd-3-clause
77
0
rai
se Exception("tests wh
ere moved to emzed to avoid circular dependencies")
rbranson/craystack
upload.py
Python
bsd-3-clause
343
0.002915
import sys from craystack import cf if len(sys.argv) < 4: print "Usage: %s <key> <subkey> <path>" % sys.argv[0] sys.exit(2) _,
key, subkey, filename = sys.argv with open(filename) as f: content = f.read() cf.insert(key, {subkey: content}) print "Uploaded %s to %s/%s (%s bytes)" % (filename, key, subkey, len(con
tent))
liamfraser/lantex
lantex/types.py
Python
bsd-3-clause
19,172
0.002921
import re import svgwrite import math class LantexBase(object): def __init__(self): self.identifier = None self.description = None self.properties = [ 'description' ] def __repr__(self): out = "{0} {1}:\n".format(type(self).__name__, self.identifier) for p in self.prop...
(self): self.from_e = None self.to_e = None # 1 based port indexes self.from_i = None self.to_i = None def __repr__(self): out = "Connection: {0}->{1} : ".format(self.from_e.identifier, self.from_i) if self.to_i...
ut def update_ports(self): """ Update the port.networks entries for the relevant entity """ if self.to_i != None: self.from_e.ports[self.from_i - 1].networks = self.to_e.ports[self.to_i - 1].networks else: self.from_e.ports[self.from_i - 1].networks ...
jclgoodwin/bustimes.org.uk
vosa/management/commands/import_vosa.py
Python
mpl-2.0
11,021
0.002087
import csv from datetime import datetime from django.conf import settings from django.core.management import BaseCommand from bustimes.utils import download_if_changed from ...models import Licence, Registration, Variation def parse_date(date_string): if date_string: return datetime.strptime(date_string, ...
n' # ): # print(reg_no) # print(f"'{key}': '{prev}', '{value}'") # cardinals.add(key) #
# print(line) variation = Variation(registration=registration, variation_number=var_no) if reg_no in variations_dict: if var_no in variations_dict[reg_no]: continue # ? e
tmxdyf/CouchPotatoServer
couchpotato/core/providers/info/_modifier/main.py
Python
gpl-3.0
3,402
0.004409
from couchpotato import get_session from couchpotato.core.event import addEvent, fireEvent from couchpotato.core.helpers.variable import mergeDicts, randomString from couchpotato.core.logger import CPLog from couchpotato.core.plugins.base import Plugin from couchpotato.core.settings.model import Library import copy imp...
}, 'runtime': 0, 'plot': '', 'tagline': '', 'imdb': '', 'genres': [], 'mpaa': None, 'actors': [], 'actor_roles': {} } def __init__(self): addEvent('result.modify.info.
search', self.returnByType) addEvent('result.modify.movie.search', self.combineOnIMDB) addEvent('result.modify.movie.info', self.checkLibrary) def returnByType(self, results): new_results = {} for r in results: type_name = r.get('type', 'movie') + 's' if typ...
TylerKirby/cltk
cltk/tests/test_nlp/test_prosody.py
Python
mit
3,978
0.001078
"""Test cltk.prosody.""" __license__ = 'MIT License. See LICENSE.' from cltk.prosody.latin.scanner import Scansion as ScansionLatin from cltk.prosody.latin.clausulae_analysis import Clausulae from cltk.prosody.greek.scanner import Scansion as ScansionGreek from cltk.prosody.latin.macronizer import Macronizer import u...
tandem , ō catilīnā , abūtēre nostrā patientia ?" curr
ent = Macronizer("tag_ngram_123_backoff").macronize_text(text) self.assertEqual(current, correct) if __name__ == '__main__': unittest.main()
bdh1011/wau
venv/lib/python2.7/site-packages/pandas/tseries/tests/test_frequencies.py
Python
mit
16,705
0.004071
from datetime import datetime, time, timedelta from pandas.compat import range import sys import os import nose import numpy as np from pandas import Index, DatetimeIndex, Timestamp, Series, date_range, period_range import pandas.tseries.frequencies as frequencies from pandas.tseries.tools import to_datetime impor...
for month in ['JAN', 'FEB', 'MAR']: self._check_generated_range('1/1/
2000', 'Q-%s' % month) def test_annual(self): for month in MONTHS: self._check_generated_range('1/1/2000', 'A-%s' % month) def test_business_annual(self): for month in MONTHS: self._check_generated_range('1/1/2000', 'BA-%s' % month) def test_annual_ambiguous(self):...
cydenix/OpenGLCffi
OpenGLCffi/GL/EXT/GREMEDY/string_marker.py
Python
mit
123
0.02439
from OpenGLCf
fi.GL import params @param
s(api='gl', prms=['len', 'string']) def glStringMarkerGREMEDY(len, string): pass
pepincho/Python101-and-Algo1-Courses
Programming-101-v3/week6/1-Who-Follows-You-Back/github_person_test.py
Python
mit
185
0
import unittest from github_person import GithubPerson class Test_GithubPerson(unittest.TestCase):
def setUp(self): pass if __name__ == '__main__': unitt
est.main()
CauldronDevelopmentLLC/dockbot
dockbot/Image.py
Python
gpl-3.0
6,147
0.00667
import shutil import os import hashlib import dockbot def gen_hash(data): return hashlib.sha256(data).hexdigest() class Image(object): def __init__(self, root, name, path, platform = None, projects = [], modes = None, slave = False, remote = False): self.root = root self.con...
e return False def cmd_status(self): for container in self.containers: container.cmd_status() def cmd_config(self): for container in self.containers: container.cmd_config() def cmd_shell(self): raise dockbot.Error('Cannot open shell in image') ...
ner.cmd_start() def cmd_stop(self): for container in self.containers: container.cmd_stop() def cmd_restart(self): self.cmd_stop() self.cmd_start() def cmd_build(self): # Check if image is running if self.is_running(): if dockbot.args.all ...
ketancmaheshwari/hello-goog
src/python/newtonraphson.py
Python
apache-2.0
209
0.004785
#!/bin/env python # mainly for sys.argv[], sys.argv[0] is the name of the program import sys # mainly for arrays import nump
y as np def newtraph(fx, fxprime): if __name__ == '__main__': p
rint 'hello'