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
dmnfarrell/epitopemap
modules/pepdata/hpv.py
Python
apache-2.0
2,977
0.003023
# Copyright (c) 2014. Mount Sinai School of Medicine # # 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 o...
mask &= epitopes.str.len() == peptide_length df = df[mask] if reduced_alphabet: epitopes = df[epitope_column_name] df[epitope_column_name] = \ epitopes.map(make_alphabet_transformer(reduced_alphabet)) return df def load_tcell(*args, **kwargs): tcell_path = join(DATA...
ataframe(tcell_path, 'Epitope sequence', *args, **kwargs) def load_tcell_set(*args, **kwargs): df = load_tcell(*args, **kwargs) return set(df['Epitope sequence']) def load_tcell_ngrams(*args, **kwargs): return make_unlabeled_ngram_dataset_from_args( load_tcell_set, *args, **kwargs) def load_mhc(*...
oihane/odoo-addons
account_invoice_validate_tax/tests/__init__.py
Python
agpl-3.0
48
0
from . import test_ac
count_invoice_
validate_tax
onshape-public/onshape-clients
python/onshape_client/oas/models/btpl_value_var_reference252_all_of.py
Python
mit
4,301
0
# coding: utf-8 """ Onshape REST API The Onshape REST API consumed by all clients. # noqa: E501 The version of the OpenAPI document: 1.111 Contact: api-support@onshape.zendesk.com Generated by: https://openapi-generator.tech """ from __future__ import absolute_import import sys # noqa: F401 ...
_item=(), _configuration=None, **kwargs ): # noqa: E501 """
btpl_value_var_reference252_all_of.BTPLValueVarReference252AllOf - a model defined in OpenAPI Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the...
kstilwell/tcex
app_init/service_webhook/args.py
Python
apache-2.0
186
0
"""Playbook Args""" from argparse import ArgumentParser class Args: """Playbook Args""" def __init__(self, parser: ArgumentParser): """Initial
ize
class properties."""
ip-tools/ip-navigator
patzilla/access/sip/client.py
Python
agpl-3.0
15,596
0.004681
# -*- coding: utf-8 -*- # (c) 2014-2018 Andreas Motl <andreas.motl@ip-tools.org> import timeit import logging import requests from lxml import etree from beaker.cache import cache_region from requests.exceptions import ConnectionError, ConnectTimeout from patzilla.access.generic.exceptions import NoResultsException, Ge...
nse={3}'.format( ex.__class__, ex.message, response.status_code, response.content, username=self.username)) self.logout() raise else: message = 'SIP login failed. status_code={0}, content={1}'.format(response.status_code, response.content) ...
ream database failed.' self.logout() raise error self.sessionid = None return False def logout(self): log.info('Logging out user "{username}"'.format(username=self.username)) self.stale = True def search(self, expression, options=None): options...
skosukhin/spack
var/spack/repos/builtin.mock/packages/openblas/package.py
Python
lgpl-2.1
1,575
0.000635
############################################################################## # Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is pa
rt of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-647188 # # For details, see https://github.com/spack/spack # Please also see the NOTICE and LICENSE files for our notice and the LGPL. # # This program is free software; you can redistribute it and/or modify # it under the term
s of the GNU Lesser General Public License (as # published by the Free Software Foundation) version 2.1, February 1999. # # 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 term...
oss/shrunk
backend/shrunk/client/aggregations.py
Python
mit
2,981
0.001342
from typing import Any from collections import OrderedDict def match_link_id(link_id: str) -> Any: return {'$match': {'link_id': link_id}} # daily visits aggregations phases group_tracking_ids = {'$group': { '_id': '$tracking_id', 'visits': { '$addToSet': '$$ROOT', }, }} find_first = {'$pro...
'input': '$visits.rest', 'as': 'visit', 'in': {'$mergeObjects': ['$$visit', {'first_time': 0}]}, }}, },
'in': {'$concatArrays': [['$$first'], '$$rest']}, }, }, }} unwind_ips = {'$unwind': '$visits'} group_days = {'$group': { '_id': { 'month': {'$month': '$visits.time'}, 'year': {'$year': '$visits.time'}, 'day': {'$dayOfMonth': '$visits.time'}, }, 'first_time_visits'...
RensaProject/nodebox_linguistics_extended
nodebox_linguistics_extended/plural.py
Python
gpl-2.0
12,919
0.021209
# PLURAL - last updated for NodeBox 1rc7 # Author: Tom De Smedt <tomdesmedt@organisms.be> # See LICENSE.txt for details. # Based on "An Algorithmic Approach to English Pluralization" by Damian Conway: # http://www.csse.monash.edu.au/~damian/papers/HTML/Plurals.html # Prepositions are used to solve things like # "moth...
ey", None, False], ["^her$|^him$|^it$|^them$", "them", None, False], ["^herself$|^himself$|^itself$|^themself$", "themselves", None, False], ["^oneself$", "one
selves", None, False] ], # 4/ # Words that do not inflect. [ ["$", "", "uninflected", False], ["$", "", "uncountable", False], ["s$", "s", "s-singular", False], ["fish$", "fish", None, False], ["([- ])bass$", "\\1bass", None, False], ["ois$", "ois", None, False], ["sheep...
hesseltuinhof/mxnet
example/dsd/mlp.py
Python
apache-2.0
4,340
0.004608
import mxnet as mx import os import logging import argparse from math import ceil import sparse_sgd # symbol net def get_symbol(): data = mx.symbol.Variable('data') fc1 = mx.symbol.FullyConnected(data, name='fc1', num_hidden=128) act1 = mx.symbol.Activation(fc1, name='relu1', act_type="relu") fc2 = mx....
zer='sparsesgd', optimizer_params=optimizer_params) logging.info('Finish traning...') # remove files for i in range(num_epoch): os.remove('%s-%04d.params' % (prefix, i + 1)) os.remove('%s-symbol.json' % prefix) if __name__ == "__main__"
: # print logging by default logging.basicConfig(level=logging.DEBUG) parser = argparse.ArgumentParser(description="sparse training") parser.add_argument('--pruning_switch_epoch', type=str) parser.add_argument('--weight_sparsity', type=str, default=None) parser.add_argument('--bias_sparsity', ...
emad8878/is210-week-05-warmup
task_02.py
Python
mpl-2.0
160
0
#!/usr/bin/env python # -*-
coding: utf-8
-*- """This is week5 warmup task_02 Import a Module Namespace""" import task_01.peanut TIME = task_01.peanut.BUTTER
cms-ttbarAC/CyMiniAna
python/runDeepLearning.py
Python
mit
4,594
0.014367
""" Created: 12 November 2016 Last Updated: 11 April 2018 Dan Marley daniel.edison.marley@cernSPAMNOT.ch Texas A&M University ----- Script for running the deep learning implementation To run: $ python python/runDeepLearning.py config/mlconfig.txt -- the second argument is the text file with configurati...
ayers','nNodes','input_dim','kfold_splits'] featureKeys = json.load(open('config/features.json')) featureKey = -1 for key in featureKeys.keys(): if Counter(featureKeys[key])==Counter(config.features): featureKey = int(key) break if featureKey
<0: featureKey = max([int(i) for i in featureKeys.keys()])+1 featureKeys[str(featureKey)] = config.features vb.INFO("RUN : New features for NN ") with open('config/features.json','w') as outfile: json.dump(featureKeys,outfile) ## Set output directory output_dir = "nHiddenLayers{0}_".format(co...
AgResearch/prbdf
database_paper/figure_4/fasta_yank.py
Python
gpl-3.0
467
0.025696
#!/usr/bin/python2.6 # # filters a fasta file (from standard input), pulling o
ut sequences by name # from Bio import SeqIO import sys usage = "usage : cat some_file.fa | fasta_yank.py file_of_names " if len(sys.argv) != 2: print usage sys.exit(1) SeqIO.write ((r for r in SeqIO.parse(sys.stdin, "fasta") if r.name in [name.strip() for name in open(sys.argv[1],"r")]) , sys.stdout, "fa...
asta"): # print r.name
krisss2121/bpmn-python
bpmn_python/graph/classes/activities/activity_type.py
Python
gpl-3.0
1,224
0.001634
# coding=utf-8 """ Class used for representing
tActivity of BPMN 2.0 graph """ import graph.classes.flow_node_type as flow_node class Activity(flow_node.FlowNode): """ Class used for representing tActivity of BPMN 2.0 graph Fields (except inherited): - default: ID of default
flow of gateway. Must be either None (default is optional according to BPMN 2.0 XML Schema) or String. """ def __init__(self): """ Default constructor, initializes object fields with new instances. """ super(Activity, self).__init__() self.__default = None def ...
biggapoww/Python-CIS-5
simple pypy/compute_time_8.py
Python
mit
375
0.010667
##Write Python s
tatements to prompt for and collect values ##for the time in hours and minutes (two integer quantities). def time(): hours = input('What are the hours ') minutes = input('What are the minutes ') if (int(hours) >= 1 and i
nt(hours) <= 12 and int(minutes) >= 0 and int(minutes) <= 59): print('The time is '+ hours + ':' + minutes) time()
daStrauss/subsurface
src/expts/numSensorsCTX.py
Python
apache-2.0
1,572
0.01464
''' Created on Oct 5, 2012 Copyright © 2013 The Board of Trustees of The Leland Stanford Junior University. 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 distributed under the License is distributed on an "...
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. @author: dstrauss ''' import numpy as np import scipy.io as spio # F = spio.loadmat('incCondGo.mat') # numRuns = F['goTo'].shape[0] D = {'solve...
jtara1/SimpleFlaskWebsite
app/views.py
Python
apache-2.0
3,783
0.001322
from flask import render_template, flash, redirect, session, url_for, request, g from flask_login import login_user, logout_user, current_user, login_required from app import app, db, lm, oid from .forms import LoginForm, EditForm from .models import User from datetime import datetime @app.before_request def before_r...
if nickname is None or nickname == "": nickname = resp.email.split('@')[0] nickname = User.make_unique_nickname(nickn
ame=nickname) user = User(nickname=nickname, email=resp.email) db.session.add(user) db.session.commit() remember_me = False if 'remember_me' in session: remember_me = session['remember_me'] session.pop('remember_me', None) login_user(user, remember = remember_me) ...
dougbeal/nosy
nosy/nosy.py
Python
bsd-3-clause
5,722
0
"""Watch for changes in a collection of source files. If changes, run the specified test runner (nosetests, by default). """ from argparse import ArgumentParser import ConfigParser import glob import os import stat import subprocess import sys import time class Nosy(object): """Watch for changes in all source fil...
setests) whenever the source files (default ./*.py) change. Re-read the configuration before each run so that options and arguments may be changed. """ checksum = 0 self._read_config() while True: if self._checksum() != checksum: self....
test_runner.split() if ' ' in self.test_runner else [self.test_runner]) try: subprocess.call( cmd + self.cmd_opts.replace('\\\n', '').split() + self.cmd_args.replace('\\\n', '').split()) ...
lento/cortex
test/IECoreRI/ParameterisedProcedural.py
Python
bsd-3-clause
4,780
0.038494
########################################################################## # # Copyright (c) 2009-2013, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redis...
Called = False def doBound( self, args ) : self.boundCalled = True return IECore.Box3f( IECore.V3f( -1 ), IECore.V3f( 1 ) ) def doRenderState( self, renderer,
args ) : self.renderStateCalled = True renderer.setAttribute( "ri:visibility:diffuse", IECore.BoolData( 1 ) ) def doRender( self, renderer, args ) : self.renderCalled = True renderer.geometry( "teapot", {}, {} ) class ParameterisedProceduralTest( IECoreRI.TestCase ) : def checkContents( self, fileName,...
ulikoehler/UliEngineering
tests/SignalProcessing/TestUtils.py
Python
apache-2.0
6,677
0.002097
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from numpy.testing import assert_approx_equal, assert_allclose, assert_array_equal from UliEngineering.SignalProcessing.Utils import * from parameterized import parameterized import concurrent.futures import numpy as np import datetime import unittest unstairMethods = [ ...
Range(*params, endpoint=endpoint) linspc = np.linspace(*params, endpoint=endpoint) self.assertEqual(len(spc), params[2]) self.assertEqual(len(spc), linspc.size) self.assertEqual((len(spc),), linspc.shape)
assert_allclose(spc[:], linspc) # Test samplerate assert_approx_equal(spc.samplerate(), (n - 1 if endpoint else n) / (end - start)) # Test some slice istart, iend = len(spc) // 3, len(spc) // 2 assert_allclose(spc[istart:iend], linspc[istart:iend]) # Test negative...
rakeshmi/tempest
tempest/tests/services/compute/test_security_group_rules_client.py
Python
apache-2.0
2,571
0
# Copyright 2015 NEC Corporation. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required ...
port fake_auth_provider from tempest.tests.services.compute import base class TestS
ecurityGroupRulesClient(base.BaseComputeServiceTest): FAKE_SECURITY_GROUP_RULE = { "security_group_rule": { "id": "2d021cf1-ce4b-4292-994f-7a785d62a144", "ip_range": { "cidr": "0.0.0.0/0" }, "parent_group_id": "48700ff3-30b8-4e63-845f-a79c9633...
DongElkan/flavonoid
flavonoid_parser.py
Python
gpl-3.0
15,159
0.000264
""" Parse flavonoid molecule object read from Indigo toolkit. The molecular identifiers accepted are canonical SMILES, InchI or file like format ..mol (file stored in ChemSpider database), and ..sdf (in PubChem database). """ import collections from re import findall, sub from indigo import Indigo, IndigoException fro...
= "b" elif db == 2: # candidate benzene ring label = "bx" # other types of aromatic rings if label is None or label == "bx": c2o = [
] for j in rgix: for nei in self.atoms[j].neighbors: if nei.symbol == "o" and nei.bondorder == 2: c2o.append(nei.index) if db >= 1: if db == 2 and len(c2o) == 2: # quinone ...
lafranceinsoumise/api-django
agir/events/views/jitsi_views.py
Python
agpl-3.0
1,950
0.002062
from datetime import timedelta from django.http import JsonRespo
nse from django.utils import timezone from django.views.decorators.csrf import csrf_exempt from django.views.decorators.http import require_POST, require_http_methods from agir.events.models import JitsiMeeting @csrf_exempt @require_POST def jitsi_reservation_view(request): try: meeting = JitsiMeeting.ob...
oesNotExist: return JsonResponse({"message": "Cette conférence n'existe pas."}, status=404) else: if meeting.event is not None and not meeting.event.is_current(): return JsonResponse( { "message": "L'événement n'est pas encore commencé ou est déjà term...
fedora-conary/rmake-2
rmake/worker/command.py
Python
apache-2.0
19,427
0.001596
# # Copyright (c) SAS Institute 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 w...
ke import failure from rmake.build import subscriber from rmake.worker import resolver from rmake.lib import logfile from rmake.lib import logger from rmake.lib import procutil from rmake.lib import repocache from rmake.lib import recipeutil from rmake.lib import server from rmake.lib.apiutils imp
ort thaw, freeze class Command(server.Server): """ Superclass for commands. Expects information to run one operation which it will perform and report about. The command is set up to handle forked operation: The main action occurs inside the pipe and any information ...
DarthMaulware/EquationGroupLeaks
Leak #4 - Don't Forget Your Base/EQGRP-Auction-File/Linux/bin/earlyshovel/tmpnam.py
Python
unlicense
54
0
#!/usr/bin/python import utils print utils.tmpn
am()
mitodl/open-discussions
course_catalog/migrations/0007_alters_created_on_field_20190111_1755.py
Python
bsd-3-clause
922
0.001085
# Generated by Django 2.0.8 on 2019-01-11 17:55 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("course_catalog", "0
006_adds_timestampedmodel_20190111_0031")] operations = [ migrations.AlterField( model_name="course", name="created_on", field=models.DateTimeField(auto_now_add=True), ), migrations.AlterField(
model_name="courseinstructor", name="created_on", field=models.DateTimeField(auto_now_add=True), ), migrations.AlterField( model_name="courseprice", name="created_on", field=models.DateTimeField(auto_now_add=True), ), mig...
digidotcom/python-wvalib
wva/test/test_subscriptions.py
Python
mpl-2.0
2,119
0.000472
# 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/. # # Copyright (c) 2015 Digi International Inc. All Rights Reserved. import json from wva.test.test_utilities import WVAT...
"subscriptions/b",
] }) subs = self.wva.get_subscriptions() self.assertEqual(len(subs), 2) self.assertEqual(subs[0].short_name, "a") self.assertEqual(subs[1].short_name, "b") def test_get_metadata(self): self.prepare_json_response("GET", "/ws/subscriptions/speedy", { ...
JGulic/empathy
tools/glib-gtypes-generator.py
Python
gpl-2.0
12,522
0.001677
#!/usr/bin/python # Generate GLib GInterfaces from the Telepathy specification. # The master copy of this program is in the telepathy-glib repository - # please make any changes there. # # Copyright (C) 2006, 2007 Collabora Limited # # This library is free software; you can redistribute it and/or # modify it under the...
' % tp_type) self.d(' * named <literal>%s</literal>):\n' % member.getAttribute('name')) docstring = get_docstring(member) or '(Undocumented)' self.d(' * %s\n' % xml_escape(docstring)) self.d(' *\n') self.d(' */\n\n') self.h(...
ame.upper()) impl = self.prefix_ + 'type_dbus_array_' + esc_impl_sig self.d('/**\n * %s:\n\n' % array_name) self.d(' * Expands to a call to a function\n') self.d(' * that returns the #GType of a #GPtrArray\n') self.d(' * of #%s.\n' % name) self.d('...
oldstylejoe/pychess-timed
lib/pychess/widgets/BorderBox.py
Python
gpl-3.0
2,441
0.006555
from gi.repository import Gtk from gi.repository import GObject class BorderBox (Gtk.Alignment): def __init__ (self, widget=None, top=False, right=False, bottom=False, left=False): GObject.GObject.__init__(self) self.connect("draw", self._onExpose) if wi...
xt.set_line_width(1) context.stroke() def _updateBorders (self): self.set_padding(self.top and 1 or 0, self.bottom and 1 or 0, self.right and 1 or 0, self.left and 1 or 0) def isTop(self): retu...
_left def setTop(self, value): self.__top = value self._updateBorders() def setRight(self, value): self.__right = value self._updateBorders() def setBottom(self, value): self.__bottom = value self._updateBorders() def setLeft(self, value): self...
amaas-fintech/amaas-core-sdk-python
amaascore/corporate_actions/dividend.py
Python
apache-2.0
1,565
0.005751
from __future__ import absolute_import, division, print_function, unicode_literals from decimal import Decimal from amaascore.corporate_actions.corporate_action import CorporateAction class Dividend(CorporateAction): def __init__(self, asset_manager_id, corporate_action_id, record_date, dividend_rate, dividend...
ge=None, description='', references=None, *args, **kwargs): se
lf.dividend_rate = dividend_rate self.dividend_asset_id = dividend_asset_id super(Dividend, self).__init__(asset_manager_id=asset_manager_id, corporate_action_id=corporate_action_id, record_date=record_date, corporate_action_status=corporate_action_status, ...
PavlovVitaly/python__homework_ITMO
task_html.py
Python
gpl-3.0
4,695
0.000429
class TagException(Exception): pass class ArgumentException(Exception): pass class Tag(object): __slots__ = ['_name', '_attributes', '_parent', '_previous_sibling', '_next_sibling', '_first_child', '_last_child', '_children'] def __init__(self, name, attr=None): self._name ...
self.last_child def insert_before(self, tag, next_sibling): if not issubclass(type(tag), Tag): raise TypeError("Argument isn't subclass of Tag.") if next_sibling not in self._children: self.append_child(tag) return index_inserted_elemnt = self._children.i...
d] self._children[index_inserted_elemnt].parent = self if index_inserted_elemnt == 0: self._first_child = self._children[index_inserted_elemnt] def __str__(self): result = '<' + self._name for key, value in self._attributes.items(): result += ' ' + key + '="'...
CyrilPeponnet/Archipel
ArchipelAgent/archipel-central-agent-platformrequest/setup.py
Python
agpl-3.0
3,265
0.006738
# # setup.py # # Copyright (C) 2010 Antoine Mercadal <antoine.mercadal@inframonde.eu> # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option...
d Audience :: Education', 'Intended Audience :: End Users/Desktop', 'Intended Audience :: Science/Research', 'Intended Audience :: System Administrators', 'Intended Audience :: Telecommunications Industry', 'License :: OSI Approved :: GNU Affero General Public License v...
:: Emulators', 'Topic :: System :: Operating System'], keywords='archipel, virtualization, libvirt, orchestration', author=AUTHOR, author_email=MAIL, url=URL, license=LICENSE, packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), include_package_data=Tru...
sandrofolk/girox
girox/blog/migrations/0007_auto_20170620_0011.py
Python
gpl-3.0
467
0
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-06-20 00:11 from __future__ import unicode_literals from django.db import migrations, models class Migrat
ion(migrations.Migration): dependencies = [ ('blog', '0006_auto_20170620_0010'), ] operations = [ migrations.AlterField( model_name='post', nam
e='posted', field=models.DateField(db_index=True, verbose_name='data'), ), ]
Krish95/tango
evaluator.py
Python
mit
3,730
0.00563
import pdb from scan_lexer import * from global_env import * from sys import exit macros = {} scope = [] def evaluate(exp, envs = [global_env]): #Use the global scope list global scope # Is exp an atom? if atom(exp): if type(exp) == Symbol: return lookup(exp, envs)...
evaluate(exp[2], envs)) elif exp[0] == "define": envs[0].insert(0, (exp[1], evaluate(exp[2], envs))) elif exp[0] == "lambda": return make_function(exp[1], exp[2:], envs) elif exp[0] == "macro": return (exp[1], exp[2]) # exp is a macro expansion elif type(evaluate(exp...
xpanded_form = macro_expand(f[0], exp[1:], f[1], envs) return evaluate(evaluate(expanded_form, envs), envs) # exp is function application else: return invoke(evaluate(exp[0], envs), evlist(exp[1:], envs)) #Preserve current scope scope = [str(inner[0]) for outer in envs for inner ...
iandees/all-the-places
locations/spiders/ljsilvers.py
Python
mit
1,524
0.007218
# -*-
coding: utf-8 -*- import scrapy import json import re from locations.items import GeojsonPointItem class LjsilversSpider(scrapy.Spider): name = "ljsilvers" allowed_domai
ns = ["ljsilvers.com"] start_urls = ( 'http://www.ljsilvers.com/locator?postalcode=76010', ) def parse(self, response): data = response.body_as_unicode() base_data = re.search('dataout\s--Array\s\((.*)\)\s\s--><style type="text/css">', data, re.DOTALL).group(1) detail_matche...
Ginkgo-Biloba/Misc-Python
sklearn/SKLearn3KMOutlier.py
Python
gpl-3.0
1,135
0.004955
# coding = utf-8 """ 3.8 将 KMeans 用于离群点检测 http://git.oschina.net/wizardforcel/sklearn-cb/blob/master/3.md """ # 生成 100 个点的单个数据块,然后识别 5 个离形心最远的点 import numpy as np from sklearn.datasets import make_blobs from sklearn.cluster import KMeans (x, labels) = make_blobs(100, centers=1) kms = KMeans(n_clusters=1) kms.fit(x) # ...
_centers_[:, 0], kms.cluster_centers_[:, 1], label="形心", s=50, alpha=0.7) ax.scatter(x[sortedIdx][:, 0], x[sortedIdx][:, 1], label="极值", s=100, alpha=0.7) ax.scatter(nkms.cluster_centers_[:, 0], nkms.cluster_centers_[:, 1], label="新的形心", s=50, alpha=0.7) ax.set_title("单点簇集") ax.legend(loc="best") fig.tight_lay
out() fig.show() plt.show()
johngumb/danphone
wavetx2.py
Python
gpl-3.0
2,677
0.065745
import sys import os import time import serial #DTR0 - blue DATA #RTS0 - purple STB RX #DTR1 - (blue on 232 side) then green CLK #CTS0 - black LD #RTS1 - purple STB TX delay=0.001 def getserials(): s0 = serial.Serial("/dev/ttyUSB0") s1 = serial.Serial("/dev/ttyUSB1") return (s0,s1) def test(): per...
outbit(s0,s1,x) latch(s0) return if __name__=="__main__": os.system("/usr/bin/chrt -r -p 99 %s"%os.getpid())
(s0,s1)=getserials() # set up reference divider # r=[1,0,0,0,0,0,0,0,0,0,0,1] r=[1,1,1,1,1,1,1,1,1,1,1,0] r=[0,0,1,1,1,1,0,0,0,0,1,0] # good r=[1,1,1,1,1,1,1,0,0,0,1,0] # good 1 jan r=[1,0,1,1,1,1,0,0,0,0,1,0] # good r=[0,0,0,0,0,0,1,0,0,0,1,0] # good r=[0,0,0,0,0,0,0,0,1,1,1,0] # ...
Weil0ng/gem5
util/cpt_upgraders/arm-sysreg-mapping-ns.py
Python
bsd-3-clause
4,062
0.00837
# Copyright (c) 2016 ARM Limited # All rights reserved # # The license below extends only to copyright in the software and shall # not be construed as granting a license to any other intellectual # property including but not limited to intellectual property relating # to a hardware implementation of the functionality o...
mr[280] =
mr[279] # TPIDRPRW_NS = TPIDRPRW mr[274] = mr[273] # TPIDRURW_NS = TPIDRURW mr[132] = mr[131] # TTBCR_NS = TTBCR mr[126] = mr[125] # TTBR0_NS = TTBR0 mr[129] = mr[128] # TTBR1_NS = TTBR1 mr[263] = mr[262] # VBAR_NS = VB...
memo/tensorflow
tensorflow/contrib/data/python/kernel_tests/zip_dataset_op_test.py
Python
apache-2.0
4,387
0.004331
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
st_session() as sess: equal_length_components = [ np.tile(np.array([[1], [2], [3], [4]]), 20), np.tile(np.array([[12], [13], [14], [15]]), 22), np.array([37.0, 38.0, 39.0, 40.0]) ] sess.run(init_op, feed_dict={ph: value for ph, value in zip( component_placeholde...
onent in zip( equal_length_components, results): self.assertAllEqual(component[i], result_component) with self.assertRaises(errors.OutOfRangeError): sess.run(get_next) variable_length_components = [[1, 2, 3, 4], [1, 2, 3, 4, 5], [1.0, 2.0]] sess.run(init_op, feed_dict={p...
npuichigo/ttsflow
third_party/tensorflow/tensorflow/contrib/keras/python/keras/layers/noise_test.py
Python
apache-2.0
1,668
0.004197
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
========================================================== """Tests for noise layers.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.contrib.keras.python import keras from tensorflow.contrib.ke
ras.python.keras import testing_utils from tensorflow.python.platform import test class NoiseLayersTest(test.TestCase): def test_GaussianNoise(self): with self.test_session(): testing_utils.layer_test( keras.layers.GaussianNoise, kwargs={'stddev': 1.}, input_shape=(3, 2, 3))...
YuepengGuo/sina_weibo_crawler
crawler/blogcrawler.py
Python
apache-2.0
10,877
0.001023
# !/usr/bin/env python # -*- coding: utf-8 -*- import os import time import math from BeautifulSoup import BeautifulSoup import config from toolkit.downloader import Downloader, DownloadError from toolkit import datetimelib as dt from parser.commonblogparser import CommonBlogParser class PreprocessError(Exception):...
tag = "$CONFIG['page_id']='" etag = "'" page_id = ''
if content: bpos = content.find(btag) if bpos: bpos += len(btag) epos = content.find(etag, bpos) page_id = content[bpos:epos] return page_id def _caculate_pagenum(self, content): """ 计算微博的总页数 ----------...
lmazuel/azure-sdk-for-python
azure-mgmt-network/azure/mgmt/network/v2017_08_01/models/troubleshooting_result_py3.py
Python
mit
1,603
0.001871
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated
by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from msrest.serialization import Model class TroubleshootingResult(Model): """Troubleshooting information g...
_time: The start time of the troubleshooting. :type start_time: datetime :param end_time: The end time of the troubleshooting. :type end_time: datetime :param code: The result code of the troubleshooting. :type code: str :param results: Information from troubleshooting. :type results: l...
skdaccess/skdaccess
skdaccess/engineering/webcam/mit_sailing/stream.py
Python
mit
2,645
0.006049
# The MIT License (MIT) # Copyright (c) 2018 Massachusetts Institute of Technology # # Authors: Cody Rude # This software has been created in projects supported by the US National # Science Foundation and NASA (PI: Pankratius) # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this so...
IED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNE...
k.data_class import DataFetcherStream, ImageWrapper from skdaccess.framework.param_class import * # Standard library imports from collections import OrderedDict class DataFetcher(DataFetcherStream): """ Data Fetcher for retrieving webcam images from the MIT Sailing Pavilion """ def __init__(self, c...
guillaumelenoir/WAVEPAL
carmcmc/carma_pack.py
Python
mit
72,802
0.005096
__author__ = 'Brandon C. Kelly' import numpy as np import matplotlib.pyplot as plt from scipy.linalg import solve from scipy.optimize import minimize import samplers import multiprocessing import _carmcmc as carmcmcLib class CarmaModel(object): """ Class for performing statistical inference assuming a CARMA(...
:param y: Th
e measured time series. :param ysig: The standard deviation in the measurements errors on the time series. :param p: The order of the autoregressive (AR) polynomial. Default is p = 1. :param q: The order of the moving average (MA) polynomial. Default is q = 0. Note that p > q. """ ...
skirsdeda/django-filer
filer/server/backends/xsendfile.py
Python
bsd-3-clause
647
0.001546
# -*- coding: utf-8 -*- from __future__ import absolute_import from django.http import HttpResponse from .base import ServerBase class ApacheXSendfileServer(ServerBase): def serve(self, request, file_obj, **kwargs): response = HttpResponse() response['X-Sendfile
'] = file_obj.path # This is needed for lighttpd
, hopefully this will # not be needed after this is fixed: # http://redmine.lighttpd.net/issues/2076 response['Content-Type'] = self.get_mimetype(file_obj.path) self.default_headers(request=request, response=response, file_obj=file_obj, **kwargs) return response
zhlinh/leetcode
0204.Count Primes/solution.py
Python
apache-2.0
1,253
0.002394
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' ***************************************** Author: zhlinh Email: zhlinhng@gmail.com Version: 0.0.1 Created Time: 2016-03-24 Last_modify: 2016-03-24 ****************************************** ''' ''' Description: Count the number of prime n...
ct): def countPrimes(self, n): """ :type n: int :rtype: int """ if n < 3: return 0 res = 1 primes = [True] * n upper = math.sqrt(n) for i in range(3, n, 2): if primes[i]: res += 1 if i > u...
ue for j in range(i*i, n, i): primes[j] = False return res
sergey-a-berezin/acme-tiny-cron
acme_tiny_cron/protos/__init__.py
Python
apache-2.0
575
0
# Copyright 2017 Sergey Berezin # 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 # distributed under the License is distributed on an "AS IS...
ense for the specific language governing permissions and # limitations under the License.
iamgp/pyCa
pyCa/Cell.py
Python
gpl-3.0
1,577
0.000634
from Stimulant import * import pandas as pd class Cell(object): """docstring for Cell""" def __init__(self): self.stimulants = {} self.stimulant = Stimulant() self.p1 = Point() self.p2 = Point() self.p1.x = 0 self.p1.y = 0 self.p2.x = 0 self....
self.p1 = Point() self.p2 = Point() self.p1.x = 0 self.p1.y = 0 self.p2.x = 0 self.p2.y = 0 def addFirstPoint(self, x, y): self.p1.x = x self.p1.y = y self.stimulant.p1 = self.p1 def addSecondPointWithName(self, x, y, name): self.p2...
nts[name] = self.stimulant del(self.stimulant) del(self.p1) del(self.p2) self.stimulant = Stimulant() self.p1 = Point() self.p2 = Point() def makePandasDF(self): bpdict = {} gdict = {} for s in self.stimulants: bpdict[self.stimula...
InQuest/ThreatKB
app/routes/errors.py
Python
gpl-2.0
952
0.002101
from flask import abort, jsonify, request, send_file, json, Response from flask_login import login_required, current_user from app import app, db, admin_only, auto from app.models import errors @app.route('/ThreatKB/errors', methods=['GET']) @auto.doc() @login_required @admin_only() def get_all_errors(): """Retu
rn all releases in ThreatKB R
eturn: list of release dictionaries""" entities = errors.Error.query.order_by(errors.Error.id.desc()).limit(50).all() return Response(json.dumps([entity.to_dict() for entity in entities]), mimetype="application/json") @app.route('/ThreatKB/errors/<int:error_id>', methods=['GET']) @auto.doc() @login_required @...
pycroscopy/pycroscopy
pycroscopy/image/image_atoms.py
Python
mit
7,225
0.002215
""" Voronoi analysis of atom positions author Gerd and Rama part of pycrosocpy """ import numpy as np import sys # from skimage.feature import peak_local_max from skimage.feature import blob_log from sklearn.cluster import KMeans from scipy.spatial import cKDTree import scipy.optimize as optimization import pyTEM...
append = True elif area.sum() > min_int: append = True pout = [0, 0, 0, 0] if append: if (x - rr
) < 0 or y - rr < 0 or x + rr + 1 > image.shape[0] or y + rr + 1 > image.shape[1]: pass else: [pout, _] = optimization.leastsq(gauss_difference, guess, args=area) if (abs(pout[1]) > max_dist) or (abs(pout[2]) > max_dist): pout = [0, 0, 0, 0] ...
estebanfallasf/python_training
ex2.py
Python
gpl-2.0
978
0.005112
# A comment, this is so you can read your program later. # Anything after the # is ignored by python. print "I could have code like this." # and the comment after is ignored # You can also use a comment to "disable" or comment out a piece of code: # print "This won't run." print "
This will run." # Adding another few lines just for fun. print 'Q: Why does the "#" in "print "Hi # there." not get ignored?' # print 'The # in that code is inside a string, so it will put into the string until the ending " character is hit. These pound characters are just considered characters and are not considered c...
g until the ending \" character is hit. These pound characters are just considered characters and aren't considered comments." # The backslash will escape the special character, as seen on the code above. Isaac Albeniz - Asturias :-)
nwjs/chromium.src
testing/unexpected_passes_common/data_types.py
Python
bsd-3-clause
22,630
0.006805
# Copyright 2020 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. """Various custom data types for use throughout the unexpected pass finder.""" from __future__ import print_function import collections import copy import f...
f the unexpected pass finder. """ def __init__(self, test, tags, actual_result, step, build_id): """ Args: test: A string containing the name of the test. tags: An iterable containing the typ tags for the result. actual_result: The actual result of the test as a string. step: A stri...
n the builder. build_id: A string containing the Buildbucket ID for the build this result came from. """ self.test = test self.tags = frozenset(tags) self.actual_result = actual_result self.step = step self.build_id = build_id def __eq__(self, other): return (isinstance(ot...
decvalts/iris
lib/iris/tests/integration/test_pp_constrained_load_cubes.py
Python
gpl-3.0
2,825
0
# (C) British Crown Copyright 2014 - 2015, Met Office # # This file is part of Iris. # # Iris 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 l...
H='m01s00i004') stcon2 = iris.AttributeConstraint(STASH='m01s00i010') pp_constraints = pp._convert_constraints([stcon1, stcon2]) pp_loader = iris.fileformats.rules.Loader(pp.load, {}, convert, pp._load_rules) cubes = list(load_cubes(filen...
ual(len(cubes), 76) @tests.skip_data def test_pp_no_constraint(self): filenames = [tests.get_data_path(('PP', 'globClim1', 'dec_subset.pp'))] pp_constraints = pp._convert_constraints(None) pp_loader = iris.fileformats.rules.Loader(pp.load, {}, ...
project-chip/connectedhomeip
scripts/idl/generators/types.py
Python
apache-2.0
14,504
0.002965
# Copyright (c) 2022 Project CHIP Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
or implied. # See the License for the specific l
anguage governing permissions and # limitations under the License. import logging import enum from idl.matter_idl_types import DataType from idl import matter_idl_types # to explicitly say 'Enum' from typing import Union, List, Optional from dataclasses import dataclass def ToPowerOfTwo(bits: int) -> int: """...
PythonSanSebastian/python-rtmbot
rtmbot/logger.py
Python
mit
246
0.012195
import logging def setup_logging(logfile, level=logging.IN
FO): log_args = {'level' : level, 'format' : '%(asctime)s %(message)s'} if logfile: log_args['filename'] = logfile logging.basicC
onfig(**log_args)
picklecai/OMOOC2py
_src/om2py3w/3wex0/notebooknetc.py
Python
mit
645
0.006656
# _*_coding:utf-8_*_ # 客户端程序 from socket import * import time from sys import exit import notebooknets def main(): BUF_SIZE = 65565 ss
_addr = ('127.0.0.1', 8800) cs = socket(AF_INET, SOCK_DGRAM) notebooknets.printhistory() while True: global data data = raw_input('今日记录,请输入(输入quit退出程序):') if data == 'quit': exit(0) el
se: cs.sendto(data, ss_addr) data, addr = cs.recvfrom(BUF_SIZE) print "Data: ", data notebooknets.save(data) cs.close if __name__ == '__main__': main()
hycis/TensorGraph
tensorgraph/layers/cast.py
Python
apache-2.0
306
0
import tensorflow as tf from .template import Bas
eLayer class ToFloat(BaseLayer): def _train_fprop(self, state_below): retu
rn tf.to_float(state_below, name='ToFloat') class ToInt32(BaseLayer): def _train_fprop(self, state_below): return tf.to_int32(state_below, name='ToInt32')
ssut/py-hanspell
tests.py
Python
mit
2,729
0.002597
# -*- coding: utf-8 -*- import unittest from hanspell import spell_checker from hanspell.constants import CheckResult from textwrap import dedent as trim class SpellCheckerTests(unittest.TestCase): def setUp(self): pass def test_basic_check(self): result = spell_checker.check(u'안녕 하세요. 저는 한국인...
CING assert items[u'아이가'] == CheckResult.WRONG_SPACING assert items[u'장난감을'] == CheckResult.STATISTICAL_CORRECTION assert items[u'갖고'] == CheckResult.WRONG_SPACING assert items[u'놀고'] == CheckResult.WRONG_SPACING assert items[u'있다.'] == CheckResult.WRONG_SPACING assert it...
ecker.check([u'안녕 하세요.', u'저는 한국인 입니다.']) assert results[0].checked == u'안녕하세요.' assert results[1].checked == u'저는 한국인입니다.' def test_long_paragraph(self): paragraph = trim(""" ubit.info(유빗인포)는 코나미 리듬게임, 유비트의 플레이 데이터 관리 및 열람 서비스입니다. 등록 후에 자신과 친구의 기록을 p.eagate.573.jp에 접속할 필요 없이 본 웹 사이...
alxgu/ansible
lib/ansible/modules/network/netvisor/pn_port_cos_bw.py
Python
gpl-3.0
4,163
0.000961
#!/usr/bin/python # Copyright: (c) 2018, Pluribus Networks # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['...
pn_cliswitch=dict(required=False, type='str'), state=dict(required=True, type='str', choices=state_map.keys()), pn_max_bw_limit=dict(required=False, type='str'), pn_cos=dict(required=False, type=
'str'), pn_port=dict(required=False, type='str'), pn_weight=dict(required=False, type='str', choices=['priority', 'no-priority']), pn_min_bw_guarantee=dict(required=False, type='str'), ), required_if=( ['state', 'update', ['pn_co...
plotly/plotly.py
packages/python/plotly/plotly/validators/waterfall/_constraintext.py
Python
mit
500
0.002
import _plotly_utils.basevalidators class ConstraintextValidator(_plotly_utils.basevalidators.EnumeratedValidator): def __init__(self, plotly_name="constraintext", parent_name="waterfall", **kwargs): super(ConstraintextValidator, self).__init__( plotly_name=plotly_name, parent_name...
, **kwargs
)
ssarangi/numba
numba/tests/test_utils.py
Python
bsd-2-clause
3,857
0.000519
""" Tests for numba.utils. """ from __future__ import print_function, absolute_import import threading import time from numba import utils from numba import unittest_support as unittest class C(object): def __init__(self, value): self.value = value def __eq__(self, o): return self.value ==...
.release() lock.acquire() lock.release() self.assertFalse(lock.is_owned()) def test_multithreaded(self): lock
= self._lock() errors = [] def do_things(): for i in range(5): self.assertFalse(lock.is_owned()) lock.acquire() time.sleep(1e-4) self.assertTrue(lock.is_owned()) lock.release() def wrapper(): ...
ProfessorKazarinoff/staticsite
content/code/statistics/box_plot.py
Python
gpl-3.0
931
0.120301
from statistics import mean, median, mode, stdev import matplotlib.pyplot as plt plt.style.use('seaborn') data1 = [83,83,93,91,85,64,79,97,95,67,83,90,92,73,82,85,96,84,82,71,86,68,66,95,87,81,77,81,97] data2 = [60,79,89,97,68,82,67,59,77,87,99,102
,73,78,91,89,84,81,78,90,92,97,82] data3 = [85,94,100,100,47,78,100,92,49,86,90,100,84,89,82,100,100,100,96,82,65,92,96,85,76,100,90,100] data4 = [79,100,90,82,76,90,86,88,86,93,99,92,84,77,100,100,96,93,91,86,74,74,100,93,69,89,93,100] data = data1 + data2 + data3 + data4 data_mean = mean(data) data_median = median(d
ata) try: data_mode = mode(data) except: data_mode = 'None' data_stdev = stdev(data) print('mean: %4.1f' %data_mean) print('median: %4.1f' %data_median) print('mode: %s' %data_mode) print('std dev: %4.1f ' %data_stdev) plt.hist(data) plt.xlabel('Grade Range') plt.ylabel('Number of Students') plt.title('Histor...
ilastik/ilastik-0.5
ilastik/core/testThread.py
Python
bsd-2-clause
6,464
0.01052
from PyQt4 import QtCore import numpy from ilastik.core import dataImpex import shlex from ilastik.core.listOfNDArraysAsNDArray import ListOfNDArraysAsNDArray from ilastik.core.overlays.selectionOverlay import SelectionAccessor
from subprocess import Popen, PIPE import h5py # this is the core replacement of the guiThread used to test module functionality #******************************************************************************* # T e s t T h r e a d * #***************************...
achine def setUp(): if not ilastik.core.jobMachine.GLOBAL_WM: ilastik.core.jobMachine.GLOBAL_WM = ilastik.core.jobMachine.WorkerManager() def tearDown(): ilastik.core.jobMachine.GLOBAL_WM.stopWorkers() del ilastik.core.jobMachine.GLOBAL_WM ilastik.core.jobMachine.GLOBAL_WM = None class Te...
RagingRoosevelt/BackupMediaSyncer
_sync.py
Python
mit
3,135
0.010526
from os import remove, mkdir, listdir, rmdir from os.path import join, expanduser, isdir from os.path import split as splitdir import codecs from shutil import copy2 indir = join(expanduser("~"),"Desktop") orgdir = "" bakdir = "" with codecs.open(join(indir,"_diff.txt"), 'r', encoding='utf8') as diff: # Read fir...
quit() # Read second line. Should contain backup directory line = diff.readline() try: line = line.replace
("\n","").split("**") if line[0] == "[BAK_DIR]": bakdir = line[1] except: print("error: Bad logfile") quit() # If either of the directories weren't read in, then quit print("orig: %s, bak: %s" % (orgdir, bakdir)) if orgdir == "" or bakdir == "": print...
rackerlabs/deuce
deuce/tests/db_mocking/__init__.py
Python
apache-2.0
46
0
import deuce.tests.db_mocking
.mongodb_mockin
g
IvayloTsankov/carty
src/carty.py
Python
gpl-2.0
649
0
import remote_controller import blu
etooth class Carty: """ this is the main module of the application """ def __init__(self): self.controller
= remote_controller.RemoteController() self.bluetooth = bluetooth.Bluetooth(self.controller.on_open, self.controller.on_message, self.controller.on_close, self.controller.on_err...
jeffre/docker-rdr
bootstrap/env_to_xml.py
Python
gpl-2.0
5,303
0.004903
#!/usr/bin/python import os from AhsayTools import XmlConf, env_true, env_false # Map Enviroment Variables to server.xml > Xpath > attibute server_conf = XmlConf("/rdr/conf/server.xml") server_conf.set_attrib("Service/Connector", "port", "RDR_HTTP_PORT") server_conf.set_attrib("Service/Connector[@scheme='https']", "...
' if env_false("RDR_ENFORCE_SSL"): if rdr_web.find(xpath) is not None: rdr_web.remove('.', xpath) rdr_web.write() # Enforce SSL on /obs/jsp/user/* and /obs/jsp/system/* if "ROOT_ENF
ORCE_SSL" in os.environ: namespace = "http://java.sun.com/xml/ns/j2ee" elem = "security-constraint" xpath = '%s' % (elem) root_web = XmlConf("/rdr/webapps/ROOT/WEB-INF/web.xml") if env_true("ROOT_ENFORCE_SSL"): if root_web.find(xpath) is None: root_web.subelement('.', elem) ...
walteryang47/ovirt-engine
packaging/setup/plugins/ovirt-engine-common/vmconsole_proxy_helper/__init__.py
Python
apache-2.0
841
0
# # ovirt-engine-setup -- ovirt engine setup # Copyright (C) 2015 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in complianc
e with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
or implied. # See the License for the specific language governing permissions and # limitations under the License. # """ovirt-host-setup vmconsole_proxy plugin.""" from otopi import util from . import core @util.export def createPlugins(context): core.Plugin(context=context) # vim: expandtab tabstop=4 shi...
plipp/Python-Coding-Dojos
katas/2X-Racing-Car-Katas/TurnTicketDispenser/test_turn_ticket.py
Python
mit
264
0.015152
import unittest
from turn_ticket import TicketDispenser class TicketDispenserTest(unittest.TestCase): def test_do_something(self): dispenser = TicketDispenser() ticket = dispenser.getTurnTicket() if _
_name__ == "__main__": unittest.main()
ikoz/mitmproxy
mitmproxy/models/http.py
Python
mit
14,861
0.001144
from __future__ import (absolute_import, print_function, division) import Cookie import copy import warnings from email.utils import parsedate_tz, formatdate, mktime_tz import time from netlib import encoding from netlib.http import status_codes, Headers, Request, Response, decoded from netlib.tcp import Address from ...
quest.http_version, headers=request.headers, content=request.content, timestamp_start=request.timestamp_start, timestamp_end=request.timestamp_end, form_out=(request.form_out if hasattr(request, 'form_out') else None), ) return req @proper...
def form_out(self): warnings.warn(".form_out is deprecated, use .first_line_format instead.", DeprecationWarning) return self.first_line_format @form_out.setter def form_out(self, value): warnings.warn(".form_out is deprecated, use .first_line_format instead.", DeprecationWarning) ...
south-coast-science/scs_mfr
src/scs_mfr/eeprom_read.py
Python
mit
2,020
0.002475
#!/usr/bin/env python3 """ Created on 26 Sep 2016 @author: Bruno Beloff (bruno.beloff@southcoastscience.com) DESCRIPTION The eeprom_read utility presents a formatted copy of the South Coast Science digital front-end (DFE) boar
d's EEPROM contents to stdout. The EEPROM con
tains information on vendor, product ID and a universally unique ID (UUID) code, as specified by either the Raspberry Pi HAT or BeagleBone cape standards. SYNOPSIS eeprom_read.py EXAMPLES ./eeprom_read.py SEE ALSO scs_mfr/dfe_id scs_mfr/eeprom_write RESOURCES https://github.com/raspberrypi/hats https://github.com/p...
barentsen/reproject
reproject/spherical_intersect/tests/test_high_level.py
Python
bsd-3-clause
1,908
0.003145
# Licensed under a 3-clause BSD style license - see LICENSE.rst import numpy as np import pytest from astropy.io import fits from astropy.utils.data import get_pkg_data_filename from astropy.wcs import WCS from numpy.testing import assert_allclose from ..high_level import reproject_exact class TestReprojectExact(ob...
self.array_in = np.ones((100, 100)) self.wcs_in = WCS(self.header_in) self.wcs_out = WCS(self.header_out
) def test_array_wcs(self): reproject_exact((self.array_in, self.wcs_in), self.wcs_out, shape_out=(200, 200)) def test_array_header(self): reproject_exact((self.array_in, self.header_in), self.header_out) def test_parallel_option(self): reproject_exact((self.array_in, self.header...
SimonWang2014/DockerConsoleApp
libs/stormed-amqp/examples/tutorial6/rpc_server.py
Python
apache-2.0
972
0.004115
#!/usr/bin/env python import logging from tornado.ioloop import IOLoop from stormed import Connection, Message def fib(n): if n == 0: return 0 elif n == 1: return 1 else: return fib(n-1) + fib(n-2) def on_connect(): global ch ch = conn.channel() ch.queue_declare(queue=...
ble=True) ch.qos(prefetch_count=1) ch.consume('rpc_queue', on_request) def on_request(msg): n = int(msg.body) print " [.] fib(%s)" % n response = str(fib(n)) response_msg = Message(response, delivery_mode=2, correlation_id=msg.correlation_id) ch.publish(response_m...
change='', routing_key=msg.reply_to) msg.ack() logging.basicConfig() ch = None conn = Connection(host='localhost') conn.connect(on_connect) io_loop = IOLoop.instance() print ' [*] Waiting for messages. To exit press CTRL+C' try: io_loop.start() except KeyboardInterrupt: conn.close(io_loop.stop)
Opentrons/labware
shared-data/python/setup.py
Python
apache-2.0
5,215
0.000384
import os import sys from setuptools.command import build_py, sdist from setuptools import setup, find_packages HERE = os.path.abspath(os.path.dirname(__file__)) sys.path.append(os.path.join(HERE, '..', '..', 'scripts')) from python_build_utils import normalize_version # make stdout blocking since Travis sets it to...
trons" EMAIL = "engineering@opentrons.com" URL = "https://github.com/Opentrons/opentrons" DOWNLOAD_URL
= '' CLASSIFIERS = [ 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Operating System :: OS Independent', 'Intended Audience :: Science/Research', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.7', '...
vug/personalwebapp
views/login.py
Python
mit
1,797
0.002226
""" This Blueprint gives the ability of user logins, and login_required functionality using Flask-Login extension. """ from flask import Blueprint, render_template, request, flash, redirect, url_for from flask_login import login_required, logout_user, login_user from extensions import login_manager from models import ...
n to reload the user object from the user ID stored in the session. :rtype: User
:return: A User if user_id exists, else None.""" return User.query.get(int(user_id)) @login.route('/login', methods=['GET', 'POST']) def login_page(): if request.method == 'GET': return render_template('login.html') elif request.method == 'POST': email = request.form['email'] ...
willcampbel/Character-Distribution
distribution.py
Python
mit
1,888
0.03125
""" distribution.py Author: Will Campbell Credit: Dave Wilson, Ethan Adner, http://stackoverflow.com/questions/3121979/how-to-sort-list-tuple-of-lists-tuples Assignment: Write and submit a Python program (distribution.py) that computes and displays the distribution of characters in a given sample of text. Output of...
s that are more common appear first in the list. * Where the same number of characters occur, the lines are ordered alphabetically. For example, in the printout above, the letters e, h, l, p and y both occur twice in the text and they are listed in the output in alphabetical order. * Letters that do not occur in ...
better): ") string = string1.lower() print('The distribution of characters in "'+string1+'" is:') list1 = list(string) alpha=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"] freq=[] for x in alpha: freq.append(0) for x in list1: if x in alpha: f...
tlangerak/Multi-Agent-Systems
spade/odict.py
Python
lgpl-2.1
10,695
0
# -*- coding: utf-8 -*- """ odict ~~~~~ This module is an example implementation of an ordered dict for the collections module. It's not written for performance (it actually performs pretty bad) but to show how the API works. Questions and Answers ===================== Why would any...
der in a dict is guaranteed it's also a great help to have an equivalent data structure in Python to ease the transition. Where are new keys added? At the end. This behavior is consistent with Ruby 1.9 Hashmaps and PHP Arrays. It also matches what common ordered dict implementati...
y a subclass very easily:: class movingodict(odict): def __setitem__(self, key, value): self.pop(key, None) odict.__setitem__(self, key, value) Moving keys to the end of a ordered dict on reassignment is not very useful for most appli...
lmazuel/azure-sdk-for-python
azure-mgmt-compute/azure/mgmt/compute/v2016_04_30_preview/models/key_vault_secret_reference_py3.py
Python
mit
1,467
0
# 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 ...
e_vault: Required. The relative URL of the Key Vault containing the secret. :type source_vault: ~azure.mgmt.compute.v2016_04_30_preview.models.SubResource """ _validation = { 'secret_url': {'required': True}, 'source_vault': {'required': True}, } _attribute_map = {
'secret_url': {'key': 'secretUrl', 'type': 'str'}, 'source_vault': {'key': 'sourceVault', 'type': 'SubResource'}, } def __init__(self, *, secret_url: str, source_vault, **kwargs) -> None: super(KeyVaultSecretReference, self).__init__(**kwargs) self.secret_url = secret_url self...
brian-team/brian2genn
examples/simple_example_synapses.py
Python
gpl-2.0
971
0.00103
from brian2 import * import brian2genn set_device('genn', directory='simple_example_synapses') #set_device('cpp_standalone') N = 100 tau = 10*ms eqs = ''' dV/dt = -V/tau + Iin/tau : 1 Iin : 1 ''' G = NeuronG
roup(N, eqs, threshold='V>1', reset='V=0', name='PN') G.V = rand() G2 = NeuronGroup(N, eqs, threshold='V>1', reset='V=0', name='LN') G2.V = 2 * rand() alpha = 20/ms beta = 30/ms S = Synapses(G, G2, model=''' ds/dt= alpha*(1-s) - beta*s: 1 g: 1 ''', pre='Iin...
beta2 = 60/ms p_post = 1 p_pre = 30 S2 = Synapses(G2, G, model=''' ds/dt= alpha2*(1-s) - beta2*s: 1 g: 1 ''', pre='Iin_post+= g*p_pre', post=''' g*= p_post-0.9; ''', name='inh_syns') S.connect(i=1,...
snogaraleal/adjax
adjax/serializer.py
Python
mit
2,855
0
from json import loads, dumps class ObjectType(object): """ Class defining a pluggable type. """ TYPE = '__type__' name = None cls = None @classmethod def encode(cls, value): """ Convert value to dictionary. """ return { 'value': value, } ...
Use object type decode if the dictionary specifies a type. """ if ObjectType.TYPE in dct: name = dct[ObjectType.TYPE] object_type = self
.object_types_by_name.get(name) if object_type: return object_type.decode(dct) return dct return loads(data, object_hook=object_hook) serializer = Serializer()
pombredanne/TSP-CloudStack
src/it/tsp/cloudstack/pimf/extract_cr.py
Python
gpl-3.0
2,778
0.007559
# -*- Mode: python; py-indent-offset: 4; indent-tabs-mode: nil; coding: utf-8; -*- # Copyright (C) 2011 Khaled Ben Bahri - Institut Telecom # # 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 Software Foundati...
turn self.__crList__ = [] for crs in self.getRootElement().getElementsByTagName("cr"): if crs.nodeType == crs.ELEMENT_NODE: obj=Indicator() try: #ext
raction of value for each indicator obj.name = self.getText(crs.getElementsByTagName("name")[0]) obj.maxPhy = self.getText(crs.getElementsByTagName("maxPhysicalThreshold")[0]) obj.maxApp = self.getText(crs.getElementsByTagName("maxApplicationThreshold")[0]) ...
metulburr/puzzle
data/levels/level3.py
Python
gpl-3.0
5,988
0.01169
import pygame as pg from .. import prepare, tools from ..components import drop_box, var_display from ..states import game class Level3(game.Game): def __init__(self): game.Game.__init__(self) self.next = 'MENU' self.drop_boxes = { 'move_down':drop_box.DropBox(self.tile_rect.siz...
].rect, self.text_flow['reset_var'][1], self.text_flow['check'][1], self.end_text_rect,
self.drop_boxes['move_down'].rect, self.text_flow['while'][1], self.drop_boxes['move_left'].rect, self.text_flow['continue'][1], ] def fill_tile_queue_order(self): '''fill tile queue to specific level order ''' self.tile_queue = [ ] ...
VerifiableRobotics/ReSpeC
src/respec/formula/gr1_formulas.py
Python
bsd-3-clause
8,371
0.030701
#!/usr/bin/env python from ..ltl import ltl as LTL """ Formulas for the GR(1) fragment of Linear Temporal Logic This module contains two main classes: * GR1Formula for vanilla GR(1) formulas * FastSlowFormula for extended GR(1) formulas following the paradigm in Vasumathi Raman and Hadas Kress-Gazit (ICRA 2...
type of GR(1) subformulas (e.g. fairness conditions) type (str) GR(1) subformu
la type (sys_init, env_init, sys_trans, env_trans, sys_liveness, env_liveness) Raises: ValueError: When a proposition is neither a system nor an environment proposition """ def __init__(self, env_props = [], sys_props = [], ts = {}): #FIX: TS should be an argument of a subcl...
cloudify-cosmo/yo-ci
yoci/tests/__init__.py
Python
apache-2.0
21
0
__autho
r__ =
'nir0s'
Microvellum/Fluid-Designer
win64-vc/2.78/python/lib/site-packages/sqlalchemy/dialects/mysql/mysqlconnector.py
Python
gpl-3.0
5,323
0.000188
# mysql/mysqlconnector.py # Copyright (C) 2005-2016 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """ .. dialect:: mysql+mysqlconnector :name: MySQL Connector/Python ...
ient_flags = opts.get( 'client_flags', ClientFlag.get_default()) client_flags |= ClientFlag.FOUND_ROWS opts['client_flags'] = client_flags except Exception: pass return [[], opts] @util.memoized_property
def _mysqlconnector_version_info(self): if self.dbapi and hasattr(self.dbapi, '__version__'): m = re.match(r'(\d+)\.(\d+)(?:\.(\d+))?', self.dbapi.__version__) if m: return tuple( int(x) for x in m.group...
LibCrowds/libcrowds-statistics
tests/test_event_listeners.py
Python
bsd-3-clause
1,768
0
# -*- coding: utf8 -*- from mock import patch, MagicMock from default import with_context, Test from pybossa.model.task_run import TaskRun from factories import TaskRunFactory from sqlalchemy import event from libcrowds_statistics import event_listeners class TestEventListener(Test): def setUp(self): se...
s.event_listeners.request') def test_ip_address_set_for_new_task_run(self, mock_request): mock_target = MagicMock() mock_conn = MagicMock() mock_request.remot
e_addr = '1.2.3.4' mock_request.headers.getlist.return_value = False event_listeners.record_new_task_run_ip_event(None, mock_conn, mock_target) tr_info_args = mock_target.info.__setitem__.call_args_list assert tr_info_args[0][0] == ('i...
mcallaghan/tmv
BasicBrowser/scoping/migrations/0099_auto_20170512_1404.py
Python
gpl-3.0
444
0
#
-*- coding: utf-8 -*- # Generated by Django 1.10.2 on 2017-05-12 14:04 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('scoping', '0098_auto_20170511_0955'), ] operations = [ migrations.AlterField(...
jonahbron/clue
setup.py
Python
gpl-3.0
3,316
0.000905
import card from card import Card from player import Player from hand import Hand from prompt import Prompt, IntegerPrompt, SetPrompt import pprint class Setup: def run(self, game): self.game = game self.cards_accounted_for = 0 self.setup_conviction() self.initialize_cards() ...
.add(Card(card.TYPE_ROOM, 'Study')) self.game.cards.add(Card(card.TYPE_ROOM, 'Hall')) self.game.cards.add(Card(card.TYPE_PERSON, 'Miss Scarlett')) self.game.cards.add(Card(card.TYPE_PERSON, 'Coloniel Mustard')) self.game.cards.add(Card(card.TYPE_PERSON, 'Misses White')) self.gam...
PERSON, 'Misses Peacock')) self.game.cards.add(Card(card.TYPE_PERSON, 'Professor Plumb')) self.game.cards.add(Card(card.TYPE_WEAPON, 'Lead Pipe')) self.game.cards.add(Card(card.TYPE_WEAPON, 'Wrench')) self.game.cards.add(Card(card.TYPE_WEAPON, 'Knife')) self.game.cards.add(Card(...
cladmi/RIOT
tests/nordic_softdevice/tests/01-run.py
Python
lgpl-2.1
291
0
#!/usr/bin/env python3 import sys from testrunner import run def testfunc(child): child.expect("All up, running the shell now") child.sendline("ifconfig") child.exp
ect(r"Iface\s+(\d+)\s+HWaddr:") if __name__ == "__main__": sys.
exit(run(testfunc, timeout=1, echo=False))
vikingco/django-advanced-reports
advanced_reports/backoffice/decorators.py
Python
bsd-3-clause
1,384
0.002168
from functools import wraps from django.utils.translation import ugettext as _ from django.contrib.admin.forms import AdminAuthenticationForm from django.contrib.auth.views import login from django.contrib.auth import REDIRECT_FIELD_NAME def staff_member_required(backoffice): def decorate(view_func): """ ...
id. Continue to the admin page. return view_func(request, *args, **kwargs) assert hasattr(request, 'session'), "Advanced Reports Backoffice requires session middleware to be installed. Edit your MIDDLEWARE_CLASSES setting to insert 'django.contrib.sessions.middleware.SessionMiddleware'.
" defaults = { 'template_name': backoffice.login_template, 'authentication_form': AdminAuthenticationForm, 'extra_context': { 'backoffice': backoffice, REDIRECT_FIELD_NAME: request.get_full_path(), }, ...
almarklein/flexx
flexx/ui/__init__.py
Python
bsd-2-clause
725
0
""" flexx.ui GUI toolkit based on web technology with a Pythonic API. """ # We follow the convention of having one module per widget class (or a # small set of closely related classes). In order not to pollute this # namespace, we prefix the module names with an underscrore. from ._widget import Widget from ._layou...
rom ._plotlayo
ut import PlotLayout
JamesNickerson/py-junos-eznc
lib/jnpr/junos/utils/__init__.py
Python
apache-2.0
39
0
from jnpr.j
unos.utils.util
import Util
apple/coremltools
coremltools/converters/mil/frontend/torch/torchir_passes.py
Python
bsd-3-clause
12,830
0.002104
# Copyright (c) 2021, Apple Inc. All rights reserved. # # Use of this source code is governed by a BSD-3-clause license that can be # found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause from coll
ections import defaultdict, OrderedDict import logging as _logging from .internal_graph import InternalTorchIRNode, InternalTorchIRGraph def generate_tensor_assignment_ops(graph): """ This graph pass handles inplace tensor assignements, specifically it handles: `torch.Tensor.copy_` and `torch.Tensor.fill_...
stance: def forward(self, x): # x a tensor with shape [4,10] x[:2, 4] = [[1],[3]] return x In Pytorch, this is represented by a sequence of slice / select ops followed by a copy op: input -> %x %1 = slice(%x, dim=0, begin=0, end=2) # the slice for dimension 0 ...
boldprogressives/django-opendebates
opendebates/opendebates/models.py
Python
apache-2.0
7,910
0.003667
# coding=utf-8 import datetime from django.db import models from django.conf import settings from django.contrib.auth.models import User from django.core.signing import Signer from djorm_pgfulltext.models import SearchManager from djorm_pgfulltext.fields import VectorField from urllib import quote_plus from django.util...
en(self.email) @classmethod def make_account_token(cls, email): signer = Signer() value = signer.sign(email) return value class Vote(models.Model): submission = models.ForeignKey(Submission) voter = models.ForeignKey(Voter) ip_address = models.CharField(max_length=255, db...
l_merged_submission = models.ForeignKey(Submission, null=True, blank=True, related_name="votes_merged_elsewhere") class Meta: unique_together = [("submission", "voter")] created_at = models.DateTimeField(db_index=True) source = models.CharField(ma...
Shebella/HIPPO
clc/tools/src/euca_admin/groups.py
Python
gpl-3.0
2,776
0.023775
import boto,sys,euca_admin from boto.exception import EC2ResponseError from euca_admin.generic import BooleanResponse from euca_admin.generic import StringList from boto.resultset import ResultSet from euca_admin import EucaAdmin from optparse import OptionParser SERVICE_PATH = '/services/Accounts' class Group(): ...
up_users) r = '%s\nAUTH\t%s\t%s' % (r,self.group_groupName,self.group_auths) return r def startElement(self, name, attrs, conne
ction): if name == 'euca:users': return self.group_users if name == 'euca:authorizations': return self.group_auths else: return None def endElement(self, name, value, connection): if name == 'euca:groupName': self.group_groupName = value else: setattr(self, name, val...
EmanueleCannizzaro/scons
src/engine/SCons/Tool/aixc++.py
Python
mit
2,413
0.002072
"""SCons.Tool.aixc++ Tool-specific initialization for IBM xlC / Visual Age C++ compiler. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001 - 2016 The SCons Foundation # # Permission is h...
# permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIE...
ENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Tool/aixc++.py...
hapylestat/apputils
src/modules/apputils/progressbar/__init__.py
Python
lgpl-3.0
9,262
0.010169
# 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...
# Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and #
limitations under the License. # # Github: https://github.com/hapylestat/apputils # # import sys import time import os from datetime import datetime from enum import Enum from .string_utils import safe_format from ..terminal.get_terminal_size import get_terminal_size """ Template description: begin_line ...
decipherinc/decipher-clips
plugin/test/functions.py
Python
mit
1,693
0.002363
# -*- coding: utf-8 -*- import os import sys import re import string from urllib import quote sys.path.append('plugin/decipherclips') # noinspection PyUnresolvedReferences import decipherclips FUNCTION_DEPS = (os, string.uppercase, string.lowercase, quote, decipherclips) class ClipParserException(Exception): p...
ng them in the global namespace""" FUNC_RGX = re.compile(r'\s*def ([A-Z].*?)\(.*') # testable funcs are capitalized def __init__(self, clip_path): try: self.clip_lines = open(clip_path).readlines() except IOError: raise ClipParserException('Could not read plugin: {path}...
e: int """ return len(s) - len(s.lstrip()) def parse(self): parsing = False capture = [] indent = 0 for line in self.clip_lines: if parsing: if line.strip() and self.get_indent(line) <= indent: self._exec(''.join(captu...
abhishek-malani/python-basic-coding
python-basic-coding/python-basic-coding/voter_data_download.py
Python
mit
1,936
0.009298
import urllib2 import os baseurl = "http://ceoaperms.ap.gov.in/TS_Rolls/PDFGeneration.aspx?urlPath=D:\SSR2016_Final\Telangana\AC_001\English\S29A" constituencyCount = 0 constituencyTotal = 229 while constituencyCount <= constituencyTotal: pdfCount = 1 notDone = True constituencyCount = constituencyCount ...
seurl+str(constituencyCount).zfill(2)+'P'+str(pdfCount).zfill(3)+".pdf" pdfCount = pdfCount + 1 try: u = urllib2.urlopen(url) response_headers = u.info() if response_headers.type == 'application/pdf': directory = "Path to dir" + str(constituencyCount)...
+ url.split('/')[-1] u = urllib2.urlopen(url) f = open(file_name, 'wb') meta = u.info() file_size = int(meta.getheaders("Content-Length")[0]) print "Downloading: %s Bytes: %s" % (file_name, file_size) file_size_dl = 0 ...
ShoufuLuo/csaw
3rd/byzauth/tools/mail_trace_scripts/filter_by_sendrecv.py
Python
apache-2.0
941
0.017003
#!/usr/bin/python # # Load the mail graph and try to filter the messages # by count of target addresses import string import re from traceparser import traceparser class SendRecvFilter: def __init__( self, filename ) : self.parser = traceparser(filename) self.senders = set() self....
while self.parser.Next(): if self.parser.From() in self.sendrecv: print self.parser.Line() if __name__ == "__main__": import sys if len(sys.argv) != 2 : print 'Usage : %s <mesglog>' % sys.argv[0] sys.exit(1)
file = sys.argv[1] mg = SendRecvFilter(file)
aurelo/lphw
source/ex8.py
Python
mit
351
0
formatter = "%r %r %r %r" print formatter % (1, 2, 3, 4) print
formatter % ("one", "two", "three", "four") print formatter % (True, False, False, True) print formatter % (formatter
, formatter, formatter, formatter) print formatter % ( "I had this thing", "that you could type up right", "But it didn't sing", "So I said goodnight" )