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
Vysybyl/motuus
players/3d_model_sample.py
Python
gpl-3.0
1,369
0.006574
from motuus.play.base_player import BasePlayer class Player(BasePlayer): """This is the main class of motuus. Use it to process Movement objects as they come in and to bind them to multimedia events. An instance of this class is kept alive throughout ever
y http session between the mobile device browser and the computer. If you need to store variables between inputs, you'll have to initialize them appropriately in the __init__ method. Some useful variables are already present in the BasePlayer and can be called directly. """ def __init__(self, ): ...
ine): super(Player, self).__init__(graph3D=True) # Initialize here variables that might be used at every new event. def play(self, mov): """This method is called anytime a new Movement input comes in from the device. Use it to process every new mov and bind it to multimedia event,...
eamonnmag/hepdata3
hepdata/modules/submission/views.py
Python
gpl-2.0
5,414
0.001293
# # This file is part of HEPData. # Copyright (C) 2016 CERN. # # HEPData 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. # # HEPData is...
ern.ch :param separator: by default '::' :return: name, email """
if separator in person_string: string_parts = person_string.split(separator) return {'name': string_parts[0], 'email': string_parts[1]}, return {'name': person_string, 'email': person_string}
wagnerand/addons-server
src/olympia/ratings/migrations/0004_auto_20210823_1255.py
Python
bsd-3-clause
573
0.001745
# Generated by Django 3.2.6 on 2021-08-23 12:55 from django.db import migrations, models class Migration(migrations.Migration):
dependencies = [ ('ratings', '0003_auto_20210813_0941'), ] operations = [ migrations.AlterField( model_name='rating', name='ip_address', field=models.CharField(default='0.0.0.0', max_length=45), ), migrations.AddIndex( model_name='...
), ]
areebbeigh/anime-scraper
src/websites/gogoanime.py
Python
apache-2.0
4,738
0.002533
import os import re from src.config import TimeoutConfig from src.scrape_utils.selectors import GoGoAnimeSelectors, LOAD_STATUS_SELECTOR from src.scrape_utils.servers import StreamServers from src.stream_servers.openupload import OpenUploadScraper from src.stream_servers.mp4upload import Mp4UploadScraper from src.stre...
place("Episode ", "")): return self.fetch_episode(episode_name) raise ValueError("Episode %d does not exist" % episode_number) def fetch_all_episodes(self, episodes_dict): # -> { 'Episode 1': { 'stream_page': http://.../watch/episode-01, 'stream_url': http://.../file.mp4 } } ...
episodes_dict[ep_name] = self.fetch_episode(ep_name) except ValueError: episodes_dict[ep_name] = ""
sinner/testing-djrf
tutorial/snippets/models/TimeStampable.py
Python
mit
426
0
from django.db import models class TimeStampable(models.Model): """TimeStampable""" STATUS_CHOICES = ( ('A', 'Active'), ('I', 'Inactive') ) created_at = models.DateTimeField(aut
o_now_add=True, auto_now=False)
updated_at = models.DateTimeField(auto_now_add=False, auto_now=True) status = models.CharField(max_length=1, choices=STATUS_CHOICES) class Meta: abstract = True
Kyria/LazyBlacksmith
lazyblacksmith/models/sde/solarsystem.py
Python
bsd-3-clause
345
0
# -*- encoding: utf-8 -*- from . import db class SolarSyste
m(db.Model): id = db.Column(db.Integer, primary_key=True, autoincrement=False) name = db.Column(db.String(100), nullable=False) region_id = db.Column(db.Integer, db.ForeignKey('region.id')) constellation_id = db.Column(db.In
teger, db.ForeignKey('constellation.id'))
ProjectCalla/SomeCrawler
somecrawler/queue/QueueManager.py
Python
gpl-3.0
802
0.002494
__author__ = 'j' from somecrawler.queue import PriorityQueue from somecrawler.user import User, UserController class QueueManager: pQueue
= PriorityQueue.PQueue() userCon = UserController.UserController() def __init__(self): pass def add_to_queue(self, pQueue, job, priority): pQueue.put(job, priority) def create_user_priority_queue(self, pQueue): userList = self.userCon.getAllUsers() self.add_dict_to_qu...
[str(i)] pQueue.put(job, job.priority) return pQueue def emptyQueueDEBUG(self, pQueue): i = 0 while not pQueue.empty(): print i, pQueue.get() i += 1
xchenum/quantum
quantum/plugins/linuxbridge/tests/unit/test_database.py
Python
apache-2.0
11,211
0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright 2012, Cisco Systems, 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...
: LOG.error("Failed to get all vlan bindings: %s" % str(exc))
return vlans def get_vlan_binding(self, network_id): """Get a vlan binding""" vlan = [] try: for vlan_bind in l2network_db.get_vlan_binding(network_id): LOG.debug("Getting vlan binding for vlan: %s" % vlan_bind.vlan_id) ...
ultima51x/shelltag
test/functions.py
Python
gpl-2.0
1,243
0.005632
# Copyright 2010 David Hwang # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # """ These are some helper functions for tests. """ import shutil import os import os.path front = "....
ee("../test/data/original/2010 - The Noise", "../test/data/2010 - The Noise") def clear(): """ Deletes all files whic
h exist under pathlist """ for path in pathlist: if os.path.exists(path): if os.path.isdir(path): shutil.rmtree(path) else: os.remove(path)
wackerly/faucet
faucet/valve_util.py
Python
apache-2.0
6,228
0.000642
"""Utility functions for FAUCET.""" # Copyright (C) 2015 Brad Cowie, Christopher Lorier and Joe Stringer. # Copyright (C) 2015 Research and Education Advanced Network New Zealand Ltd. # Copyright (C) 2015--2018 The Contributors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this ...
le(loc): result = loc break if result is None: result = locations[0] # Check for setting that expects a boolean result. if isinstance(default_value, bool): return _cast_bool(result) # Special default for FAUCET_EVENT_SOCK. if name == 'FAUCET_EV...
esult def get_logger(logname, logfile, loglevel, propagate): """Create and return a logger object.""" stream_handlers = { 'STDOUT': sys.stdout, 'STDERR': sys.stderr, } try: if logfile in stream_handlers: logger_handler = logging.StreamHandler(stream_handlers[logfi...
ingadhoc/sale
crm_survey/models/crm_job.py
Python
agpl-3.0
291
0
from
odoo import fields, models class Job(models.Model): _inherit = "crm.team" survey_id = fields.Many2one( 'survey.survey', "Interview Form", help="Choose an interview form") def action_print_survey(self):
return self.survey_id.action_print_survey()
LaFriOC/LabJack
Python_LJM/Examples/eAddresses.py
Python
gpl-3.0
1,299
0.009238
""" Demonstrates how to use the labjack.ljm.eAddresses (LJM_eAddresses) function. """ from labjack import ljm # Open first found LabJack handle = ljm.open(ljm.constants.dtANY, ljm.constants.ctANY, "ANY") #handle = ljm.openS("ANY", "ANY", "ANY") info = ljm.getHandleInfo(handle) print("Opened a LabJack with Device t...
] aValues = [2.5, 12345, 0] # [write 2.5 V, write 1
2345, read] results = ljm.eAddresses(handle, numFrames, aAddresses, aDataTypes, aWrites, aNumValues, aValues) print("\neAddresses results: ") start = 0 for i in range(numFrames): end = start + aNumValues[i] print(" Address - %i, data type - %i, write - %i, values: %s" % \ (aAddresses[i], aDataTypes[...
thaim/ansible
test/integration/targets/s3_bucket_notification/files/mini_lambda.py
Python
mit
145
0
import json def lambda_handle
r(event, context): return { 'statusCode': 200, 'bod
y': json.dumps('Hello from Lambda!') }
opennewzealand/linz2osm
linz2osm/data_dict/migrations/0007_add_model_Dataset.py
Python
gpl-3.0
3,063
0.005224
# -*- coding: utf-8 -*- # LINZ-2-OSM # Copyright (C) 2010-2012 Koordinates Ltd. # # This pro
gram 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 WIT...
ou should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): #...
molobrakos/home-assistant
homeassistant/components/mobile_app/sensor.py
Python
apache-2.0
2,104
0
"""Sensor platform for mobile_app.""" from functools import partial from homeassistant.const import CONF_WEBHOOK_ID from homeassistant.core import callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from .const import (ATTR_SENSOR_STATE, ATTR_SENSOR_TYPE_SENSOR as ENTITY...
erty def state(self): """Return the state of the sensor.""" return self._config[ATTR_SENSOR_STATE] @property def unit_of_measurement(self)
: """Return the unit of measurement this sensor expresses itself in.""" return self._config.get(ATTR_SENSOR_UOM)
mscuthbert/abjad
abjad/tools/datastructuretools/test/test_datastructuretools_TreeContainer_append.py
Python
gpl-3.0
796
0.001256
# -*- encoding: utf-8 -*- from abjad import * def test_datastructuretools_TreeContainer_append_01(): leaf_a = datastructuretools.TreeNode() leaf_b = datastructuretools.TreeNode() leaf_c = datastructuretools.TreeNode() leaf_d = datastructuretools.TreeNode() container = datastructuretools.TreeConta...
nd(leaf_a) assert container.children == (leaf_a,) container.append(leaf_b) assert container.children == (leaf_a, leaf_b) container.append(leaf_c) assert container.children == (leaf_a, leaf_b, leaf_c) container.append(leaf_d) assert container.children == (leaf_a, leaf_b, leaf
_c, leaf_d) container.append(leaf_a) assert container.children == (leaf_b, leaf_c, leaf_d, leaf_a)
iamahuman/angr
tests/test_tracer.py
Python
bsd-2-clause
7,429
0.003231
import os import sys import logging import nose import angr from common import bin_location, do_trace, slow_test def tracer_cgc(filename, test_name, stdin, copy_states=False): p = angr.Project(filename) p.simos.syscall_library.update(angr.SIM_LIBRARIES['cgcabi_tracer']) trace, magic, crash_mode, crash_a...
000) # make sure there is no crash state nose.tools.assert_false(simgr.crashed) # make sure angr modeled the correct output
stdout_dump = simgr.traced[0].posix.dumps(1) nose.tools.assert_true(stdout_dump.startswith(b"\nWelcome to Palindrome Finder\n\n" b"\tPlease enter a possible palindrome: " b"\t\tYes, that's a palindrome!\n\n" ...
0ps/wfuzz
src/wfuzz/externals/moduleman/modulefilter.py
Python
gpl-2.0
4,524
0.002653
# mimicking nmap script filter # nmap --script "http-*" # Loads all scripts whose name starts with http-, such as http-auth and http-open-proxy. The argument to --script had to be in quotes to protect the wildcard from the shell. # not valid for categories! # # More complicated script selection can be done using...
equivalent to nmap --script "default,safe". It loads all scripts that are in the default category or the safe
category or both. # # nmap --script "default and safe" # Loads those scripts that are in both the default and safe categories. # # nmap --script "(default or safe or intrusive) and not http-*" # Loads scripts in the default, safe, or intrusive categories, except for those whose names start with http-. PYPARSI...
pandas-dev/pandas
pandas/tests/frame/indexing/test_coercion.py
Python
bsd-3-clause
5,463
0.001464
""" Tests for values coercion in setitem-like operations on DataFrame. For the most part, these should be multi-column DataFrames, otherwise we would share the tests with Series. """ import numpy as np import pytest import pandas as pd from pandas import ( DataFrame, MultiIndex, NaT, Series, Times...
xpected) indexer_al(df)["C", "D"] = 44.5 expected = DataFrame({"D": [0, 0, 44.5]}, index=["A", "B", "C"], dtype=np.float64) tm.assert_frame_equal(df, e
xpected) indexer_al(df)["C", "D"] = "hello" expected = DataFrame({"D": [0, 0, "hello"]}, index=["A", "B", "C"], dtype=object) tm.assert_frame_equal(df, expected) @pytest.mark.xfail(reason="unwanted upcast") def test_15231(): df = DataFrame([[1, 2], [3, 4]], columns=["a", "b"]) df.loc[2] = Series(...
kapilt/cloud-custodian
c7n/handler.py
Python
apache-2.0
6,491
0.000616
# Copyright 2016-2017 Capital One Services, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed ...
t lambda role and # used to provision the lambda. # - profile doesnt translate to lambda its `home` dir setup dependent # - dryrun doesn't translate (and shouldn't be present) # - region doesn't translate from cli (the lambda is bound to a region), and # on the cli represents the region the...
exec_options.pop(k, None) # a cli local directory doesn't translate to lambda if not exec_options.get('output_dir', '').startswith('s3'): exec_options['output_dir'] = '/tmp' account_id = None # we can source account id from the cli parameters to avoid the sts call if exec_options.get('a...
divija96/Emotion-Detection
code/mouthdetection.py
Python
gpl-3.0
1,760
0.029545
""" input: a loaded image; output: [[x,y],[width,height]] of the detected mouth area """ import cv def findmouth(img): # INITIALIZE: loading the classifiers haarFace = cv.Load('haarcascade_frontalface_default.xml') haarMouth = cv.Load('haarcascade_mouth.xml') # running the classifiers storage = cv.CreateM...
# FILTER MOUTH filteredMouth = [] if detectedMouth: for mouth in detectedMouth: if mouth_in_lower_face(mouth,maxFace): filteredMouth.append(mouth) maxMouthSize = 0 for mouth in filteredMouth: if mouth[0][3]* mouth[0][2] > maxMouthSize: maxMouthS
ize = mouth[0][3]* mouth[0][2] maxMouth = mouth try: return maxMouth except UnboundLocalError: return 2
eukaryote31/chaos
github_api/prs.py
Python
mit
8,393
0.000953
import arrow import settings from . import misc from . import voting from . import comments from . import exceptions as exc def merge_pr(api, urn, pr, votes, total, threshold): """ merge a pull request, if possible, and use a nice detailed merge commit message """ pr_num = pr["number"] pr_title = pr[...
(pr, window): now = arrow.utcnow() updated = get_pr_last_updated(pr) delta = (now - updated).total_seconds() return window - delta def is_pr_in_voting_window(pr, window): return voting_window_remaining_seconds(pr, window) <= 0 def get_pr_reviews(api, urn, pr_num): """ get all pr reviews on a...
.DEFAULT_PAGINATION } path = "/repos/{urn}/pulls/{pr}/reviews".format(urn=urn, pr=pr_num) data = api("get", path, params=params) return data def get_is_mergeable(api, urn, pr_num): return get_pr(api, urn, pr_num)["mergeable"] def get_pr(api, urn, pr_num): """ helper for fetching a pr. neces...
SimpleTax/merchant
billing/templatetags/billing_tags.py
Python
bsd-3-clause
740
0
""" Template tags for Offsite payment gateways """ from django import template from billing.templatetags.paypal_tags import paypal from billing.templatetags.world_pay_tags import world_pay from billing.templatetags.google_c
heckout_tags import google_checkout from billing.templatetags.amazon_fps_tags import amazon_fps from billing.te
mplatetags.braintree_payments_tags import braintree_payments from billing.templatetags.stripe_tags import stripe_payment from billing.templatetags.samurai_tags import samurai_payment register = template.Library() register.tag(google_checkout) register.tag(paypal) register.tag(world_pay) register.tag(amazon_fps) regist...
spirali/qit
src/qit/base/file.py
Python
gpl-3.0
133
0.015038
from qit.base.type import Type class File(Type):
pass_by_value = True
def build(self, builder): return "FILE*"
pekingduck/emacs-sqlite3-api
tools/gen-consts.py
Python
gpl-3.0
908
0.01652
#!/usr/bin/env python3 import sys import os import re useful_codes = [] with open(sys.argv[1]) as f: for l in f.readlines(): useful_codes.append(l.rstrip()) # Read from sqlite3.h (from stdin) # only codes that exist in useful_codes are included in consts.c for line in sys.stdin.readlines(): # fields = [ "#de...
fields[1]))
continue sym = re.sub("_", "-", fields[1].lower()) if len(fields) > 2 and fields[2] != "": print("#ifdef {0}".format(fields[1])) if fields[2].startswith('"'): print('defconst(env, "{0}", env->make_string(env, {1}, strlen({1})));'.format(sym, fields[1])) else: print('defconst(env, "{0}",...
eseidel/native_client_patches
src/trusted/service_runtime/export_header.py
Python
bsd-3-clause
2,925
0.014701
#!/usr/bin/python # # Copyright 2008, 2009, The Native Client Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can # be found in the LICENSE file. """Tools for exporting Native Client ABI header files. This module is used to export Native Client ABI header files -- whi...
ile(pat) inc = (r'^#\s*include\s+"native_client(?:/src/trusted/service_runtime)?'+ r'/include/([^"]*)"') cinc = re.compile(inc) nostrip_beg = r'^#defin
e NACL_NO_STRIP' cnostrip_beg = re.compile(nostrip_beg) nostrip_end = r'^#undef NACL_NO_STRIP' cnostrip_end = re.compile(nostrip_end) nostrip = False for line in instr: if cinc.search(line): print >>outstr, cinc.sub(r'#include <\1>', line) else: if nostrip: if cnostrip_end.searc...
renguochao/PySymTool
py_group.py
Python
mit
8,872
0.001826
# coding=UTF-8 import mysql.connector import xlrd import xlsxwriter import os from mysql.connector import errorcode from datetime import datetime # 符号化后的 Excel 文件名 EXCEL_NAME = '20170223_4.0.1_feedback_result_py' DB_NAME = 'zl_crash' config = { 'user': 'root', 'password': '123456', 'host': '127.0.0.1', ...
e") query_specific_exception = ( "SELECT * FROM " + table_name + " " "WHERE exception_type = %s") cursor.execute(group_exceptio
n_type) for (exception_type, nums) in cursor: EXCEPTION_TYPE_COUNT[exception_type] = nums # print("exception_type:" + exception_type + ", nums:" + str(nums)) for exception_type in EXCEPTION_TYPE_COUNT.keys(): cursor.execute(query_specific_exception, (exception_type,...
zorna/zorna
zorna/notes/migrations/0003_changed_mime_type_length.py
Python
bsd-3-clause
9,634
0.007785
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Changing field 'ZornaNoteFile.mimetype' db.alter_column('zorna_note_attachments', 'mimetype', self.gf('dj...
ote_related'", 'null': 'True', 'to': "orm['auth.User']"}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'user_owner_notes_zornanote_related'", 'null': 'True', 'to': "orm['auth.User']"}), 'site': ('django.db.models.fields.related.ForeignKey', [], {'related_name': ...
, 'tags': ('tagging.fields.TagField', [], {}), 'time_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'time_updated': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'auto_now_add': 'True', 'blank': 'True'}), ...
chovanecm/sacredboard
sacredboard/app/data/pymongo/mongodb.py
Python
mit
3,502
0.000286
# coding=utf-8 """Accesses data in Sacred's MongoDB.""" import pymongo from sacredboard.app.data.datastorage import Cursor, DataStorage from sacredboard.app.data.pymongo import GenericDAO, MongoMetricsDAO, MongoFilesDAO from sacredboard.app.data.pymongo.rundao import MongoRunDAO class MongoDbCursor(Cursor): """I...
ef __init__(self, uri, database_name, collection_name): """ Set up MongoDB access layer, don't connect yet. Better use the static methods build_data_access or build_data_access_with_uri """ super().__init__() self._uri = uri self._db_name = database_name ...
neric_dao = None def connect(self): """Initialize the database connection.""" self._client = self._create_client() self._db = getattr(self._client, self._db_name) self._generic_dao = GenericDAO(self._client, self._db_name) def _create_client(self): """Return a new Mongo...
sonofatailor/django-oscar
src/oscar/apps/address/abstract_models.py
Python
bsd-3-clause
21,058
0
import re import zlib from django.conf import settings from django.core import exceptions from django.db import models from django.utils.encoding import python_2_unicode_compatible from django.utils.six.moves import filter from django.utils.translation import ugettext_lazy as _ from django.utils.translation import pge...
{5}$', 'LU': r'^[0-9]{4}$', 'LV': r'^LV-[0-9]{4}$', 'LY': r'^[0-9]{5}$', 'MA': r'^[0-9]{5}$', 'MC': r'^980[0-9]{2}$', 'MD': r'^MD-?[0-9]{4}$', 'ME': r'^[0-9]{5}$', 'MF': r'^[0-9]{5}$', 'MG': r'^[
0-9]{3}$', 'MH': r'^[0-9]{5}$', 'MK': r'^[0-9]{4}$', 'MM': r'^[0-9]{5}$', 'MN': r'^[0-9]{5}$', 'MP': r'^[0-9]{5}$', 'MQ': r'^[0-9]{5}$', 'MT': r'^[A-Z]{3}[0-9]{4}$', 'MV': r'^[0-9]{4,5}$', 'MX': r'^[0-9]{5}$', 'MY': r'^[0-9]{5}$', '...
zahodi/ansible-mikrotik
pythonlibs/mt_api/__init__.py
Python
apache-2.0
12,353
0.001376
from __future__ import unicode_literals import binascii import hashlib import logging import socket import ssl import sys from ansible.module_utils.mt_api.retryloop import RetryError from ansible.module_utils.mt_api.retryloop import retryloop from ansible.module_utils.mt_api.socket_utils import set_keepalive PY2 = s...
if reply == b'!done': if output[0][0] == b'!trap': raise RosAPIError(output[0][1]) if output[0][0] == b'!fatal': self.socket.close() raise RosAPIFatalError(output[0][1]) return output def write_sen...
ite_word(b'') return words_written def read_sentence(self): sentence = [] while True: word = self.read_word() if not len(word): return sentence sentence.append(word) def write_word(self, word): logger.debug('>>> %s' % word) ...
hartwork/wnpp.debian.net
wnpp_debian_net/management/commands/importdebbugs.py
Python
agpl-3.0
15,162
0.00376
# Copyright (C) 2021 Sebastian Pipping <sebastian@pipping.org> # Licensed under GNU Affero GPL v3 or later import datetime import re import sys from itertools import islice from signal import SIGINT from typing import Any from django.core.management import CommandError from django.core.management.base import BaseComm...
pp.objects.bulk_create(issues_to_create) self._success(f'Created {len(issues_to_create)} new issues') else: self._notice('No new issues created.') def _analyze_remote_properties(sel
f, remote_properties_of_issue): future_local_properties_of_issue: dict[int, dict[str, Any]] = {} for issue_id, properties in remote_properties_of_issue.items(): self._notice(f'Processing upcoming issue {issue_id}...') try: future_local_properties_of_issue[issue_id...
Mlieou/oj_solutions
leetcode/python/ex_424.py
Python
mit
629
0.00159
class Solution(object): def characterReplacement(self, s, k): """ :type s: str :type k: int :rtype: int """ count = [0] * 26 res = char_count = start = end = 0 while end <
len(s): count[ord(s[end]) - ord('A')] += 1 char_count = max(char_count, count[ord(s[end]) - ord('A')])
end += 1 while end - start - char_count > k: count[ord(s[start]) - ord('A')] -= 1 start += 1 char_count = max(count + [char_count]) res = max(end - start, res) return res
labordoc/labordoc-next
modules/webdeposit/lib/deposition_fields/issn_field.py
Python
gpl-2.0
1,643
0.008521
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2012, 2013 CERN. ## ## Invenio is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 2 of the ## License, or (at your opt...
General Public License ## along with Invenio; if not, write to the Free
Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. from wtforms import TextField from invenio.webdeposit_field import WebDepositField from invenio.webdeposit_validation_utils import sherpa_romeo_issn_validate __all__ = ['ISSNField'] class ISSNField(WebDepositField(key='issn'), Tex...
starofrainnight/rabird.pyside
tests/__init__.py
Python
mit
63
0
# -*- coding: utf-8 -
*- """Unit test
package for qt-aider."""
DayGitH/Python-Challenges
DailyProgrammer/DP20170717A.py
Python
mit
795
0.013836
""" [2017-07-17] Challenge #324 [Easy] "manual" square root procedure (intermediate) https://www.reddit.com/r/dailyprogrammer/comments/6nstip/20170717_challenge_324_easy_manual_square_root/ Write a program that outputs the highest number that is lower or equal than the square root of the given number, with the given ...
ion digits. Use this technique, (do not use your language's built in square root function): https://medium.com/i-math/how-to-find-square-roots-by-hand-f3f7cadf94bb **input format: 2 numbers:** precision-digits Number **sample input** 0 7720.17 1 7720.17 2 7720.17 **sample output** 87 87.8 87.86 **c
hallenge inputs** 0 12345 8 123456 1 12345678901234567890123456789 """ def main(): pass if __name__ == "__main__": main()
tjcsl/ion
intranet/apps/bus/consumers.py
Python
gpl-2.0
3,019
0.001987
from asgiref.sync import async_to_sync from channels.generic.websocket import JsonWebsocketConsumer from django.conf import settings from django.utils import timezone from .models import Route class BusConsumer(JsonWebsocketConsumer): groups = ["bus"] def connect(self): self.user = sel
f.scope["user"] headers = dict(self.scope["headers"]) remote_addr = headers[b"x-real-ip"].decode() if b"x-real-ip" in headers else self.scope["client"][0] if (not self.user.is_authenticated
or self.user.is_restricted) and remote_addr not in settings.INTERNAL_IPS: self.connected = False self.close() return self.connected = True data = self._serialize(user=self.user) self.accept() self.send_json(data) def receive_json(self, content):...
saltstack/pytest-logging
setup.py
Python
apache-2.0
2,340
0.000427
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import, with_statement import os import sys import codecs from setuptools import setup, find_packages # Change to source's directory prior to running any command try: SETUP_DIRNAME = os.path.dirname(__file__) except NameError: # We'...
) # pylint: disable=exec-used VERSION = _LOCALS['__version__'] LONG_DESCRIPTION = read('README.rst') setup( name='pytest-logging', version=VERSION, aut
hor='Pedro Algarvio', author_email='pedro@algarvio.me', maintainer='Pedro Algarvio', maintainer_email='pedro@algarvio.me', license='MIT', url='https://github.com/saltstack/pytest-logging', description='Configures logging and allows tweaking the log level with a py.test flag', long_descriptio...
villaverde/iredadmin
libs/languages.py
Python
gpl-2.0
3,515
0
# encoding: utf-8 # Author: Zhang Huangbin <zhb@iredmail.org> import os import glob import web langmaps = { 'en_US': u'English (US)', 'sq_AL': u'Albanian', 'ar_SA': u'Arabic', 'hy_AM': u'Armenian', 'az_AZ': u'Azerbaijani', 'bs_BA': u'Bosnian (Serbian Latin)', 'bg_BG': u'Bulgarian', 'ca...
'GMT+06:30': 390, 'GMT+07:00': 420, 'GMT+08:00': 480, 'GMT+08:45': 525, 'GMT+09:00': 540, 'GMT+09:30': 570, 'GMT+10:00': 600, 'GMT+10:30': 630, 'GMT+11:00': 660, 'GMT+11:30': 690, 'GMT+12:00': 720, 'GMT+12:45': 765, 'GMT+13:00': 780, 'GMT+14:00': 840, } # Get availa...
s = [ web.safestr(os.path.basename(v)) for v in glob.glob(rootdir + 'i18n/[a-z][a-z]_[A-Z][A-Z]') if os.path.basename(v) in langmaps] available_langs += [ web.safestr(os.path.basename(v)) for v in glob.glob(rootdir + 'i18n/[a-z][a-z]') if os.path.basename(v) in langm...
JConwayAWT/PGSS14CC
lib/python/multimetallics/ase/test/jacapo/jacapo.py
Python
gpl-2.0
1,380
0.01087
# do some tests here before we import # Right version of Scientific? from ase.test import NotAvailable import os try: import Scientific version = Scientific.__version__.split(".") print 'Found ScientificPython version: ',Scientific.__version__ if map(int,version) < [2,8]: print 'ScientificPython...
m from ase.calculators.jacapo import Jacapo atoms = Atoms([Atom('H',[0,0,0])], cell=(2,2,2)) calc = Jacapo('Jacapo-test.nc', pw=200, nbands=2,
kpts=(1,1,1), spinpol=False, dipole=False, symmetry=False, ft=0.01) atoms.set_calculator(calc) print atoms.get_potential_energy() os.system('rm -f Jacapo-test.nc Jacapo-test.txt')
electronic-library/electronic-library-core
library/exceptions.py
Python
gpl-3.0
62
0.016129
""" Conta
ins exception classes specific to this project. """
ranji2612/leetCode
combinationSum.py
Python
gpl-2.0
622
0.016077
# Combination Sum # https://leetcode.com/problems/combination-sum/ class Solution(object): def combinationSum(self, candidates, target): "
"" :type candidates: List[int] :type target: int :rtype: Li
st[List[int]] """ if len(candidates)==0 or target<=0: return [[]] if target==0 else [] candidates.sort() j = len(candidates)-1 res = [] while j>=0: for x in self.combinationSum(candidates[:j+1],target-candidates[j]): ...
Karosuo/Linux_tools
xls_handlers/xls_sum_venv/lib/python3.6/site-packages/pip/_internal/configuration.py
Python
gpl-3.0
13,243
0
"""Configuration management setup Some terminology: - name As written in config files. - value Value associated with a name - key Name combined with it's section (section.name) - variant A single word describing where the configuration key-value pair came from """ import locale import logging import os from ...
self.load_only is not None, \ "Need to be specified a file to be editing" try: return self._get_parser_to_modify()[0] except IndexError: return None def items(self): # type: () -> Iterable[Tuple[str, Any]] """Returns key-value pairs like dict.ite...
: # type: (str) -> Any """Get a value from the configuration. """ try: return self._dictionary[key] except KeyError: raise ConfigurationError("No such key - {}".format(key)) def set_value(self, key, value): # type: (str, Any) -> None "...
pymfony/pymfony
src/pymfony/component/config/resource.py
Python
mit
5,243
0.010872
# -*- coding: utf-8 -*- # This file is part of the pymfony package. # # (c) Alexandre Quercia <alquerci@email.com> # # For the full copyright and license information, please view the LICENSE # file that was distributed with this source code. from __future__ import absolute_import; import os.path; import re; from pick...
red i
n a subdirectory tree. @author Fabien Potencier <fabien@symfony.com> """ def __init__(self, resource, pattern = None): """Constructor. @param string resource The file path to the resource @param string pattern A pattern to restrict monitored files """ self.__re...
ComfyLabs/beefeater
users/views/registration.py
Python
apache-2.0
281
0
from rest_framework import generics from ..serializers import UserSerializer cl
ass UserRegistration(generics.CreateAPIView): """ This is
basically an API to create a user. This currently provides no email functionality. """ serializer_class = UserSerializer
texta-tk/texta
dataset_importer/document_reader/readers/entity/rtf_reader.py
Python
gpl-3.0
750
0.02
from entity_reader import EntityReader import textract from dataset_importer.utils import HandleDatasetImportException class RTFReader(EntityReader): @staticmethod def get_features(**kwargs): directory = kwargs['directory'] for file_path in RTFReader.get_file_list(directory, 'rtf'): try: features = R...
th yield features except Exception as e: HandleDatasetImportException(kwargs, e, file_path=file_path) @staticmethod def count_total_documents(**kwargs): directory = kwargs['directory'] return RTFReader.count_documents(root_dire
ctory=directory, extension='rtf')
Qwaz/solved-hacking-problem
TWCTF/2019/php_note/solver.py
Python
gpl-2.0
982
0.004073
import requests URL = "http://phpnote.chal.ctf.westerns.tokyo/" def trigger(c, idx): import string sess = requests.Session() # init session sess.post(URL + '/?action=login', data={'realname': 'new_session'}) # manipulate session p = '''<script>f=function(n){eval('X5O!P%@AP[4\\\\PZX54(P^)7CC)7...
tion=login', data={'realname': '"http://127.0.0.1/flag?a=' + p, 'nickname': '</body>'}) return "<h1>Welcome" not in resp.text def leak(idx): l, h = 0, 0x100
while h - l > 1: m = (h + l) // 2 if trigger(m, idx): l = m else: h = m return chr(l) # "2532bd172578d19923e5348420e02320" secret = '' for i in range(14, 14+34): secret += leak(i) print(secret)
nischu7/paramiko
paramiko/hostkeys.py
Python
lgpl-2.1
12,117
0.000825
# Copyright (C) 2006-2007 Robey Pointer <robeypointer@gmail.com> # # This file is part of paramiko. # # Paramiko 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 2.1 of the License, or (a...
ostnames.remove(h) if len(e.hostnames): self._entries.append(e) f.close() def save(self, filename): """ Save host keys into a file, in the format used by openssh. The order of keys in the file will be preserved when possible (if these keys were ...
nto individual key lines, which is arguably a bug. @param filename: name of the file to write @type filename: str @raise IOError: if there was an error writing the file @since: 1.6.1 """ f = open(filename, 'w') for e in self._entries: line = e.to_li...
stackforge/python-tackerclient
tackerclient/tacker/v1_0/nfvo/vnffgd.py
Python
apache-2.0
3,389
0
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under t...
ource = parsed_args.template_source if parsed_args.template_source: search_opts.update({'template_source': template_source}) return search_opts class ShowVNFFGD(tackerV10.ShowCommand): """Show information of a given VNFFGD.""" resource = _VNFFGD class CreateVNFFGD(tackerV10.Crea...
"Create a VNFFGD.""" resource = _VNFFGD remove_output_fields = ["attributes"] def add_known_arguments(self, parser): parser.add_argument('--vnffgd-file', help=_('Specify VNFFGD file')) parser.add_argument( 'name', metavar='NAME', help=_('Set a name for the VNFFGD')) ...
pepaslabs/pywiki
pam_authenticate.py
Python
mit
684
0.004386
#!/usr/bin/
python # pam_authenticate.py: a script to check a user's password against PAM. # part of the pywiki project, see https://github.com/pepaslabs/pywiki # written by jason pepas, released under the terms of the MIT license. # usage: pipe a password into this script, giving the username as the first
argument. # a zero exit status indicates successful authentication. import sys import pam # pip install python-pam p = pam.pam() logged_in = False try: user = sys.argv[1] passwd = sys.stdin.read() logged_in = p.authenticate(user, passwd) except Exception as e: sys.exit(2) else: if logged_in == T...
mohamedattahri/Greendizer-Python-Library
greendizer/clients/base.py
Python
bsd-3-clause
1,742
0.002296
# -*- coding: utf-8 -*- import re from math import modf from datetime import datetime, timedelta ## {{{ http://code.activestate.com/recipes/65215/ (r5) EMAIL_PATTERN = re.compile('^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]' \ '+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$') def to_unicode(text): ''' C...
submitted string is a valid email address. @param s:str Email @return: bool ''' return (s and len(s) > 7 and EMAIL_PATTERN.match(s)) def timestamp_to_datetime
(s): ''' Parses a timestamp to a datetime instance. @param: s:str Timestamp string. @return: datetime ''' f, i = modf(long(s) / float(1000)) return datetime.fromtimestamp(i) + timedelta(milliseconds=f * 1000) def datetime_to_timestamp(d): ''' Converts a datetime instance into a tim...
zalew/fabric-pgbackup
setup.py
Python
mit
1,243
0
#!/us
r/bin/env python # -*- coding: utf-8 -*- import os import sys try: from setuptools import setup except ImportError: from distutils
.core import setup if sys.argv[-1] == 'publish': os.system('python setup.py sdist upload') sys.exit() readme = open('README.rst').read() history = open('HISTORY.rst').read().replace('.. :changelog:', '') setup( name='fabric-pgbackup', version='0.1.0', description='PostgreSQL backup/restore utilit...
RaumZeit/gdesklets-core
shell/plugins/PackageInstaller/Downloader.py
Python
gpl-2.0
3,008
0.004654
import gobject import gtk class Downloader(gtk.Dialog): def __init__(self, path): self.__is_cancelled = False gtk.Dialog.__init__(self, title = "", buttons = (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL)) self.set_default_size(300, 100)...
te(data) so_far += len(data) value = (100 * so_far / max(0.1, float(total_size))) gob
ject.timeout_add(0, self.__bar.set_fraction, value / 100.0) gobject.timeout_add(0, self.__bar.set_text, "%i%%" % (value)) src_fd.close() dest_fd.close() gobject.timeout_add(0, self.hide)
mcclurmc/juju
juju/unit/tests/test_address.py
Python
agpl-3.0
3,698
0
import subprocess import zookeeper from twisted.internet.defer import inlineCallbacks, succeed, returnValue from twisted.web import client from juju.errors import JujuError from juju.lib.testing import TestCase from juju.unit.address import ( EC2UnitAddress, LocalUnitAddress, OrchestraUnitAddress, DummyUnitAddres...
s()), "foobar") self.assertEqual( (yield self.address.get_public_address()), "foobar") class LocalAddressTest(TestCase): def setUp(self): self.address =
LocalUnitAddress() @inlineCallbacks def test_get_address(self): self.patch( subprocess, "check_output", lambda args: "192.168.1.122 127.0.0.1\n") self.assertEqual( (yield self.address.get_public_address()), "192.168.1.122") self.assertEqu...
dungeonsnd/test-code
dev_examples/pyserver/conf/pyserverconf.py
Python
gpl-3.0
779
0.03466
#!/bin/env python # -*- coding: utf-8 -*- process_count = 1 start_server_port =8600 log_file ='../log/pyserver.log' db_host ='192.168.17
.153' db_port =3306 db_username ='root' db_passwd ='tm' db_database ='test' db_connection_pool_size =16 coroutine_pool_size_per_process =100000 tcp_backlog =1024 tcp_listen_on_ip ='0.0.0.0' cache_conf ={'pyscache0': {'cache_host':'192.168.17.153', 'cache_port':6379, ...
e1': {'cache_host':'192.168.17.153', 'cache_port':6379, 'cache_database':14, 'cache_connection_pool_size':4} }
wenli810620/twitter-photos
twphotos/increment.py
Python
bsd-2-clause
1,165
0
import ConfigParser from .settings import SECTIONS, CONFIG config = ConfigParser.ConfigParser() config.read(CONFIG) if not config.has_section(SECTIONS['INCREMENTS']): config.add_section(SECTIONS['INCREMENTS']) with open(CONFIG, 'w') as f: config.write(f) def read_since_ids(users): """ Read ...
param max_ids: A dictionary mapping users to ids """ config.read(CONFIG) for user, max_id in max_ids.items(): config.set(SECTIONS['INCREMENTS'], user, str(max_id)) with open(CONFIG, 'w') as f: config.write(f) def remove_since_id(user): if config.has_option(SECTIONS['INCREMENTS'], u...
config.write(f)
Scan-o-Matic/scanomatic
tests/unit/scanning/test_terminate_scanjob.py
Python
gpl-3.0
2,729
0
from datetime import datetime, timedelta from freezegun import freeze_time from mock import MagicMock import pytest from pytz import utc from scanomatic.data.scanjobstore import ScanJobStore from scanomatic.models.scanjob import ScanJob from scanomatic.scanning.terminate_scanjob import ( TerminateScanJobError, Un...
ob', scanner_id='scnr000', start_time=start_time, termination_time=termination_time, ) class TestTerminateScanjob: def test_unknown_scanjob(self): store = MagicMock(ScanJobStore) store.get_scanjob_by_id.side_effect = LookupError with pytest.raises(UnknownScanjo...
(store, 'unknown', 'The Message') def test_not_started(self): store = MagicMock(ScanJobStore) store.get_scanjob_by_id.return_value = make_scanjob(start_time=None) with pytest.raises(TerminateScanJobError): terminate_scanjob(store, 'scjb000', 'The Message') def test_already_...
markpasc/termtool
setup.py
Python
mit
1,440
0.002778
from distutils.core import setup long_description = """ `termtool` helps you write subcommand-based command line tools in Python. It collects several Python libraries into a declarative syntax: * `argparse`, the argument parsing module with subcommand support provided in the standard library in Python 2.7 and later....
larative terminal tool programming', author='Mark Paschal', author_email='markpasc@markpasc.org', url='https://github.com/markpasc/termtool', long_description=long_description, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended A...
stem :: Unix', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 3', 'Topic :: Software Development :: Libraries :: Application Frameworks', ], packages=[], py_modules=['termtool'], requires=['argparse', 'PrettyTable', 'progressbar'], )
dvspirito/pymeasure
docs/conf.py
Python
mit
8,651
0.005895
# -*- coding: utf-8 -*- # # PyMeasure documentation build configuration file, created by # sphinx-quickstart on Mon Apr 6 13:06:00 2015. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # #...
nal stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ ('index', 'PyMeasure.tex', u'PyMeasure Documentation', u'PyMeasure Developers', ...
itle page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Docume...
DavidNorman/tensorflow
tensorflow/python/keras/mixed_precision/experimental/policy.py
Python
apache-2.0
24,791
0.005042
# Copyright 2019 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...
To use mixed precision in a Keras model, the `'mixed_float16'` or `'mixed_bfloat16'` policy can be used. `tf.keras.mixed_precision.experimental.set_policy` can be used to set the default policy for layers if no policy is passed to them. For example: ```python tf.keras.mixed_prec
ision.experimental.set_policy('mixed_float16') model = tf.keras.models.Sequential([ tf.keras.layers.Input((100,)), # Dense layers use global policy of 'mixed_float16', which does # computations in float16 while keeping variables in float32. tf.keras.layers.Dense(10), tf.keras.layers.Dens...
vasili-v/ctauto
test/test_parser.py
Python
gpl-3.0
9,771
0.000819
import unittest from ctauto.exceptions import CTAutoMissingEndOfMetablockError, \ CTAutoBrokenEndOfMetablockError, \ CTAutoInvalidMetablockError, \ CTAutoInvalidIdError, \ CTAutoMissingEndOfStringErr...
self.assertEqual(block.content, "\n" "#include <stdio.h>\n"
"\n" "int main(void)\n" "{\n" " ") block = blocks[2] self.assertIsInstance(block, MetaBlock) self.assertEqual(block.content, " metacode...
CentralLabFacilities/pepper_behavior_sandbox
pepper_behavior/skills/calculate_person_position.py
Python
gpl-3.0
4,483
0.002456
import smach import rospy import tf import math import random class CalculatePersonPosition(smach.Sta
te): def __init__(self, controller, controller_2=None, sensor=None, max_distance=2.5, onlyhorizontal=False, knownperson=True): self.person_sensor =
controller self.max_distance = max_distance self.person_id = sensor self.talk_known = controller_2 self.ignoreknownperson = knownperson self.talks = ['Oh, ich denke Dich habe ich schon begrüsst', 'Dich kenne ich schon, ich mache weiter', ...
borfast/housing-reviews
housing_reviews/settings/auth.py
Python
mit
476
0
AUTHENTICATION_BACKENDS = ( # Needed to login by username in Django admin, regardless of `allauth` 'django.contrib.auth.backends.ModelBackend', # `allauth` specific authentication methods, such as login by e-mail 'allauth.account.auth_backends.AuthenticationBackend', ) LOGIN_REDIRECT_URL = 'reviews' A...
True ACCOUNT_PASSWORD_MIN_LENGTH = 10 ALLOW_NEW_
REGISTRATIONS = True
bmng-dev/PyBitmessage
src/helper_sent.py
Python
mit
132
0.015152
from helpe
r_sql import sqlExecute def insert(t): sqlExecute('''INSERT INTO sent VALUES (?,?,?,?
,?,?,?,?,?,?,?,?,?,?,?)''', *t)
tomato42/tlsfuzzer
scripts/test-early-application-data.py
Python
gpl-2.0
9,619
0.002911
# Author: Hubert Kario, (c) 2015 # Released under Gnu GPL v2.0, see LICENSE file for details from __future__ import print_function import traceback import sys import getopt from itertools import chain from random import sample from tlsfuzzer.runner import Runner from tlsfuzzer.messages import Connect, ClientHelloGene...
tmp = None argv = sys.argv[1:] opts, args = getopt.getopt(argv, "h:p:e:x:X:n:", ["help"]) for opt, arg
in opts: if opt == '-h': host = arg elif opt == '-p': port = int(arg) elif opt == '-e': run_exclude.add(arg) elif opt == '-x': expected_failures[arg] = None last_exp_tmp = str(arg) elif opt == '-X': if not la...
pallets/jinja
examples/basic/test.py
Python
bsd-3-clause
675
0
from jinja2 import Environment from jinja2.loader
s import DictLoader env = Environment( loader=DictLoader( { "child.html": """\ {% extends default_layout or 'default.html' %} {% include helpers = 'helpers.html' %} {% macro get_the_answer() %}42{% endmacro %} {% title = 'Hello World' %} {% block body %} {{ get_the_answer() }} {{ helper...
ndblock %} """, "helpers.html": """\ {% macro conspirate() %}23{% endmacro %} """, } ) ) tmpl = env.get_template("child.html") print(tmpl.render())
neversettle7/image-color-sorter
pixelsorter.py
Python
gpl-3.0
4,583
0.002618
# The time library is needed to measure execution time # PIL library to manipulate images # colorsys library to manipulate colors # operator library to sort the values of the array in the fastest way import os import sys import time from sorter import * from painter import * from explorer import * start_time = time.ti...
', '4': 'red', '5': 'hsl'} userinput = input("Select the algorithm: ") # Choose the fill pattern print("\nWhich fill pattern do you want to use?\n") print("1. Vertical pattern (column by column)") print("2. Horizontal pattern (row by row)") print("3. Spiral pattern") pattern = ({ '1': 'vertical', '2' : 'horizontal', '...
e pattern: ") patternchoice = pattern[fillpattern] if fillpattern in pattern: if userinput in algo: userchoice = algo[userinput] run(input_path, userchoice, patternchoice) elif userinput == "0": for x in range(1, len(algo) + 1): userchoice = algo[str(x)] run(inp...
eugeneks/zmeyka
fb_req.py
Python
mit
10,919
0.013736
import requests import copy # Получаем участников группы FB def fb_get_group_members(fb_page_id, access_token): url = 'https://graph.facebook.com/v2.8/%s/members?limit=1000&access_token=%s' % (fb_page_id, access_token) fb_group_members = {'status':'OK', 'data':{'members':[], 'users_count':0}} while T...
keys = response.json().keys() url = '' if 'paging' i
n keys: keys = response.json()['paging'].keys() if 'next' in keys: url = response.json()['paging']['next'] for fb_comment in content: fb_comments['data']['comments'].append(fb_comment) ...
stack-of-tasks/rbdlpy
tutorial/lib/python2.7/site-packages/OpenGL/raw/GL/EXT/vertex_shader.py
Python
lgpl-3.0
11,362
0.04031
'''Autogenerated by xml_generate script, do not edit!''' from OpenGL import platform as _p, arrays # Code generation uses this from OpenGL.raw.GL import _types as _cs # End users want this... from OpenGL.raw.GL._types import * from OpenGL.raw.GL import _errors from OpenGL.constant import Constant as _C import ctypes _...
TS_EXT=_C('GL_MAX_VERTEX_SHADER_LOCAL_CONSTANTS_EXT',0x87C8) GL_MAX_VERTEX_SHADER_VARIANTS_EXT=_C('GL_MAX_VERTEX_SHADER_VARIANTS_EXT',0x87C6) GL_MVP_MATRIX_EXT=_C('GL_MVP_MATRIX_EXT',0x87E3) GL_NEGATIVE_ONE_EXT=_C('GL_NEGATIVE_ONE_EXT',0x87DF) GL_NEGATIVE_W_EXT=_C('GL_NEGATIVE_W_EXT',0x87DC) GL_NEGATIVE_X
_EXT=_C('GL_NEGATIVE_X_EXT',0x87D9) GL_NEGATIVE_Y_EXT=_C('GL_NEGATIVE_Y_EXT',0x87DA) GL_NEGATIVE_Z_EXT=_C('GL_NEGATIVE_Z_EXT',0x87DB) GL_NORMALIZED_RANGE_EXT=_C('GL_NORMALIZED_RANGE_EXT',0x87E0) GL_ONE_EXT=_C('GL_ONE_EXT',0x87DE) GL_OP_ADD_EXT=_C('GL_OP_ADD_EXT',0x8787) GL_OP_CLAMP_EXT=_C('GL_OP_CLAMP_EXT',0x878E) GL_O...
SYSU-MATHZH/Dedekind-Django
project/sua/views/form/views2.py
Python
gpl-3.0
8,417
0.001901
from .base import BaseViewSet from rest_framework.permissions import IsAdminUser from project.sua.views.utils.mixins import NavMixin from project.sua.permissions import IsTheStudentOrIsAdminUser, IsAdminUserOrReadOnly,IsAdminUserOrActivity,IsAdminUserOrStudent from project.sua.models import Student, Sua, Activity, App...
'add', 'change', 'detail']: return firs.AddActivitySerializer else: return self.serializer_class def get_permissions(self):
if self.action in ['add', 'change', 'detail']: permission_classes = (IsAdminUserOrActivity,) else: permission_classes = (IsAdminUserOrActivity, ) return [permission() for permission in permission_classes] def perform_create(self, serializer): serializer.save(owner...
datalogics/scons
test/Fortran/F90FLAGS.py
Python
mit
6,990
0.00329
#!/usr/bin/env python # # __COPYRIGHT__ # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish,...
: outfile.write(l) sys.exit(0) """) test.write('SConstruct',
""" env = Environment(LINK = r'%(_python_)s mylink.py', LINKFLAGS = [], F90 = r'%(_python_)s myfortran.py g90', F90FLAGS = '-x', FORTRAN = r'%(_python_)s myfortran.py fortran', FORTRANFLAGS = '-y') env.Program(target = 'test01', ...
DannyVim/ToolsCollection
Outdated/db_movie.py
Python
gpl-2.0
2,485
0.000461
# -*- coding: utf-8 -*- """ 这是一个用以获取用户豆瓣数据的爬虫,使得用户可以进行数据的本地备份。 支持: 1.豆瓣电影,豆瓣读书【暂不支持】 2.csv文件为逗号分割符文件。 @author: DannyVim """ import urllib2 as ur from bs4 import BeautifulSoup as bs import sys import time reload(sys) sys.setdefaultencoding('utf8') # BASE URL def basepage(wa): m_wish = 'http://movie.douban.com/p...
tag in soup.body(attrs={'class': 'item'}): datum = open('datum.csv', 'a+') title = ta
g.em.string.strip() url = tag.li.a.get('href') date = tag.find('span', class_='date').get_text() comment = tag.find('span', class_='comment') if comment == None: comment = '' else: comment = comment.get_text() comment = comment.encode('utf-8') ...
yrchen/CommonRepo
commonrepo/groups/migrations/0002_group_members.py
Python
apache-2.0
508
0
# -*- coding: u
tf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('groups', '0001_initial'), ] operations = [ ...
), ), ]
mdda/Reverse-GoL
benchmark/speed_numpy.py
Python
mit
1,447
0.034554
import numpy def iterate(Z): # find number of neighbours that each square has N = numpy.zeros(Z.shape) N[1:, 1:] += Z[:-1, :-1] N[1:, :-1] += Z[:-1, 1:] N[:-1, 1:] += Z[1:, :-1] N[:-1, :-1] += Z[1:, 1:] N[:-1, :] += Z[1:, :] N[1:, :] += Z[:-1, :] N[:, :-1] += Z[:, 1:] N[:, 1:] +...
nitial state:' print Z[1:-1,1:-1] for i in range(65): Z = iterate(
Z) print 'Final state:' #print Z[1:-1,1:-1] print Z[:,:] print "Problem with edges..." def test_timing(): import timeit def time_iter(): Z = numpy.zeros((22,22), dtype=numpy.int) Z[1:1+glider.shape[0], 1:1+glider.shape[1]] = glider for i in range(65): Z = iterate(Z) ...
orbitfp7/nova
nova/tests/unit/test_hacking.py
Python
apache-2.0
22,417
0.000491
# Copyright 2014 Red Hat, 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 a...
al(len(list(checks.assert_true_or_false_with_in( "self.assertFalse(A in B)"))), 1) self.assertEqual(len(list(checks.assert_true_or_false_with_in( "self.assertTrue(A not in B)"))), 1) self.assertEqual(len(list(checks.assert_true_or_false_with_in(
"self.assertFalse(A not in B)"))), 1) self.assertEqual(len(list(checks.assert_true_or_false_with_in( "self.assertTrue(A in B, 'some message')"))), 1) self.assertEqual(len(list(checks.assert_true_or_false_with_in( "self.assertFalse(A in B, 'some message')"))), 1) se...
sachinpro/sachinpro.github.io
tensorflow/python/training/momentum_test.py
Python
apache-2.0
17,251
0.002493
# Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
e 10, initialized with 0.0, gets updated with 10 consecutive momentum steps. It uses random gradients. Returns: db_grad: The gradients to apply db_out: The parameters after the momentum update. """ db_grad = [[]] * 10 db_out = [[]] * 10 # pylint: disable=line-too-long db_grad[0...
018, 0.93197989, 0.78648776, 0.50036013, 0.55345792, 0.96722615] db_out[0] = [-9.6264346e-05, -0.017914793, -0.093945466, -0.041396622, -0.053037018, -0.093197994, -0.078648776, -0.050036013, -0.055345792, -0.096722618] db_grad[1] = [0.17075552, 0.88821375, 0.20873757, 0.25236958, 0.57578111, 0.15312378, 0.5513...
addition-it-solutions/project-all
addons/resource/faces/__init__.py
Python
agpl-3.0
1,258
0.00159
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (
<http://tiny.be>). # # 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) 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. ...
tacaswell/channelarchiver
tests/mock_archiver.py
Python
mit
5,534
0.002168
# -*- coding: utf-8 -*- import os import json import re try: from xmlrpclib import Fault, ProtocolError except ImportError: # Python 3 from xmlrpc.client import Fault, ProtocolError from channelarchiver import codes, utils tests_dir = os.path.dirname(os.path.realpath(__file__)) data_dir = os.path.join(tests...
return archives def names(self, key, pattern): check_type(key, int, 'INT') check_type(pattern, utils.StrType, 'STRING') pattern = '.*{0}.*'.format(pattern) key = str(key) self._check_key(key) archive_data = self._archives[key]['data'] regex = re.compile(patte...
l, channel_data in archive_data.items(): if regex.match(channel) is None: continue values = channel_data['values'] first_value = values[0] last_value = values[-1] return_data.append({ 'name': channel, 'start_sec'...
c-goosen/mytransport-hackathon
api/endpoints/interest.py
Python
mit
7,851
0.008661
import os.path, sys sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir)) import json import falcon import urllib import uuid import settings import requests from geopy.geocoders import Nominatim import geopy.distance from geopy.distance import vincenty import datetime radius = [] radius...
def on_get(self, req, resp): resp_dict = {"message":"Post request needed with GeoLocation data"} resp.body = json.dumps(resp_dict) resp.status = falcon.HTTP_200 def on_post(self, req, resp): # Main API method, post the following ''' POST Request data type: JS...
at : { "name" : "Yourname", "address" : "Your number and street address, province, etc" "geometry" : { "coordinates" : ["x", "y"] } ''' global radius_maps global radius print(req.headers) user_name = "" post_data = json.load(req.stream) pri...
ptonner/GPy
GPy/testing/model_tests.py
Python
bsd-3-clause
25,915
0.002971
# Copyright (c) 2012, GPy authors (see AUTHORS.txt). # Licensed under the BSD 3-clause license (see LICENSE.txt) import unittest import numpy as np import GPy class MiscTests(unittest.TestCase): def setUp(self): self.N = 20 self.N_new = 50 self.D = 1 self.X = np.random.uniform(-3....
edict(self.X_new, full_cov=True) self.assertEquals(mu.shape, (self.N_new, self.D)) self.assertEquals(covar.shape, (self.N_new, self.N_n
ew)) np.testing.assert_almost_equal(K_hat, covar) np.testing.assert_almost_equal(mu_hat, mu) mu, var = m._raw_predict(self.X_new) self.assertEquals(mu.shape, (self.N_new, self.D)) self.assertEquals(var.shape, (self.N_new, 1)) np.testing.assert_almost_equal(np.diag(K_hat)...
wooga/airflow
tests/providers/google/cloud/operators/test_dataflow.py
Python
apache-2.0
11,898
0.001009
# # 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...
self.dataflow.execute(None) self.assertTrue(dataflow_mock.called) expected_options = { 'project': 'test', 'staging_location': 'gs://test/staging', 'output': 'gs://test/output',
'labels': {'foo': 'bar', 'airflow-version': TEST_VERSION} } gcs_provide_file.assert_called_once_with(object_url=PY_FILE) start_python_hook.assert_called_once_with( job_name=JOB_NAME, variables=expected_options, dataflow=mock.ANY, py_optio...
numpy/numpy-refactor
numpy/random/mtrand/generate_mtrand_c.py
Python
bsd-3-clause
352
0
import re import subprocess def remove_long_path(): path = 'mtrand.c' pat = re.compile(r'"
[^"]*mtrand\.pyx"') code = open(path).read() code = pat.sub(r'"mtrand.pyx"
', code) open(path, 'w').write(code) def main(): subprocess.check_call(['cython', 'mtrand.pyx']) remove_long_path() if __name__ == '__main__': main()
AkioNak/bitcoin
test/functional/wallet_importprunedfunds.py
Python
mit
5,280
0.001515
#!/usr/bin/env python3 # Copyright (c) 2014-2020 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test the importprunedfunds and removeprunedfunds RPCs.""" from decimal import Decimal from test_framew...
edfunds, txnid1) assert not [tx for tx in w1.listtransactions(include_watchonly=True) if tx['txid'] == txnid1] wwatch.r
emoveprunedfunds(txnid2) assert not [tx for tx in wwatch.listtransactions(include_watchonly=True) if tx['txid'] == txnid2] w1.removeprunedfunds(txnid3) assert not [tx for tx in w1.listtransactions(include_watchonly=True) if tx['txid'] == txnid3] if __name__ == '__main__': ImportPrunedFunds...
rnowling/humbaba
humbaba/augment_samples.py
Python
apache-2.0
6,775
0.002657
""" Co
pyright 2017 Ronald J. Nowling 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" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import argparse ...
joachimmetz/dfvfs
tests/vfs/apfs_file_system.py
Python
apache-2.0
4,316
0.002549
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for the file system implementation using pyfsapfs.""" import unittest from dfvfs.lib import definitions from dfvfs.path import factory as path_spec_factory from dfvfs.resolver import context from dfvfs.vfs import apfs_file_system from tests import test_lib as sh...
ileEntryByPathSpec(self): """Tests the GetFileEntryByPathSpec function.""" file_system = apfs_file_system.APFSFileSystem( self._resolver_context, self._apfs_path_spec) self.assertIsNotNone(file_system) file_system.Open() path_spec = path_spec_factory.Factory.NewPathSpec( definition...
TXT, parent=self._apfs_container_path_spec) file_entry = file_system.GetFileEntryByPathSpec(path_spec) self.assertIsNotNone(file_entry) # There is no way to determine the file_entry.name without a location string # in the path_spec or retrieving the file_entry from its parent. path_spec =...
sulami/feed2maildir
feed2maildir/reader.py
Python
isc
778
0.007712
import feedparser from multiprocessing.pool import ThreadPool def fetch_and_parse_feed(args): name, feed = args return (name, feedparser.parse(feed)) class Reader: """Get updates on the feeds supplied""" def __init__(self, feeds, silent=False, njobs=4): self.feeds = [] self.silent = s...
with ThreadPool(processes=njobs) as pool: for feed, f in pool.imap_unordered(fetch_and_parse_feed, feeds.items()): if f.bozo: self.output('WARNING: could not parse feed {}'.format(feed)) else: f.feed_alias_name = feed # user provided
text self.feeds.append(f) def output(self, arg): if not self.silent: print(arg)
PatSunter/pyOTPA
TAZs-OD-Matrix/taz_files.py
Python
bsd-3-clause
1,176
0.004252
import csv import osgeo.ogr from osgeo import ogr, osr EPSG_LAT_LON = 4326 def read_tazs_from_csv(csv_zone_locs_fname): taz_tuples = [] tfile = open(csv_zone_locs_fname, 'rb') treader = csv.reader(tfile, delimiter=',', quotechar="'") for ii, row in enumerate(treader): if ii == 0: continue ...
az_tuples.append(taz_tuple) return taz_tuples def read_tazs_from_shp(shp_zone_locs_fname): taz_tuples = [] tazs_shp = osgeo.ogr.Open(shp_zone_locs_fname) tazs_layer = tazs_shp.GetLayer(0) src_srs = tazs_layer.GetSpatialRef() target_srs = osr.SpatialReference() target_srs.ImportFromEPSG(EPSG...
sform_to_lat_lon = osr.CoordinateTransformation(src_srs, target_srs) for taz_feat in tazs_layer: taz_id = taz_feat.GetField("N") taz_geom = taz_feat.GetGeometryRef() taz_geom.Transform(transform_to_lat_lon) taz_lat = taz_geom.GetX() taz_lon = taz_geom.GetY() t...
stackforge/senlin
senlin/tests/unit/engine/test_environment.py
Python
apache-2.0
13,402
0
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed unde...
stry_name) self.assertEqual('policies', e.policy_registry.registry_name) self.assertEqual('drivers', e.driver_registry.registry_name) self.assertEqual('endpoints', e.endpoint_registry.registry_name) self.assertTrue(e.profile_registry.is_global) self.assertTrue(e.policy_registry.i...
int_registry.is_global) def test_create_default(self): ge = environment.global_env() e = environment.Environment() reg_prof = e.profile_registry reg_plcy = e.policy_registry reg_driv = e.driver_registry reg_endp = e.endpoint_registry self.assertEqual({}, e....
flackr/quickopen
src/db_exception.py
Python
apache-2.0
665
0.003008
# Copyright 2011 Google Inc. # #
Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the...
See the License for the specific language governing permissions and # limitations under the License. from silent_exception import SilentException class DBException(SilentException): pass
msabramo/pyOpenSSL
OpenSSL/test/test_rand.py
Python
apache-2.0
6,054
0.00446
# Copyright (c) Frederick Dean # See LICENSE for details. """ Unit tests for :py:obj:`OpenSSL.rand`. """ from unittest import main import os import stat from OpenSSL.test.util import TestCase, b from OpenSSL import rand class RandTests(TestCase): def test_bytes_wrong_args(self): """ :py:obj:`Op...
ne) def test_status(self): """ :py:obj:`OpenSSL.rand.status`
returns :py:obj:`True` if the PRNG has sufficient entropy, :py:obj:`False` otherwise. """ # It's hard to know what it is actually going to return. Different # OpenSSL random engines decide differently whether they have enough # entropy or not. self.assertTrue(rand.status...
Tekco/django-pipeline
docs/conf.py
Python
mit
7,041
0.006678
# -*- coding: utf-8 -*- # # Pipeline documentation build configuration file, created by # sphinx-quickstart on Sat Apr 30 17:47:55 2011. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # Al...
= '1.3' # The full version, including alpha/beta/rc tags. release = '1.3.25' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to
some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default rol...
leapalazzolo/XSS
test/test_links.py
Python
mit
5,360
0.014179
#!/usr/bin/python # -*- coding: utf-8 -*- import unittest import mechanize from links import links class LinksTest(unittest.TestCase): """Test para 'links.py'""" def test_obtener_parametros_de_la_url(self): url_unlam = 'http://www.unlam.edu.ar/index.php' url_unlam_con_parametros = '...
mechanize.Browser() links.configurar_navegador(br) lista_cookies = links.obtener_cookies_validas('DXGlobalization_lang=en;DXGlobalization_locale=en-US;DXGlobalization_currency=ARS') self.assertFalse(links.abrir_url_en_navegador(br, 'https://sitioquenoesasfasdasda.org')) self.a...
l_en_navegador(br, 'https://www.python.org')) self.assertTrue(links.abrir_url_en_navegador(br, 'https://cart.dx.com/')) self.assertTrue(links.abrir_url_en_navegador(br, 'https://cart.dx.com/', lista_cookies)) def test_validar_formato_cookies(self): lista_cookies = links.obtener_cookies...
badele/home-assistant
homeassistant/components/light/__init__.py
Python
mit
9,768
0
""" homeassistant.components.light ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Provides functionality to interact with lights. For more details about this component, please refer to the documentation at https://home-assistant.io/components/light/ """ import logging import os import csv from homeassistant.components import group, ...
too-many-locals, too-many-statements def setup(hass, config): """ Exposes light control via statemachine and services. """ component = EntityComponent( _LOGGER, DOMAIN, hass, SCAN_INTERVAL, DISCOVERY_PLATFORMS, GROUP_NAME_ALL_LIGHTS) component.setup(config) # Load built-in profiles an...
LIGHT_PROFILES_FILE), hass.config.path(LIGHT_PROFILES_FILE)] profiles = {} for profile_path in profile_paths: if not os.path.isfile(profile_path): continue with open(profile_path) as inp: reader = csv.reader(inp) # Skip the header ...
pabloest/piradio
ada_radio.py
Python
gpl-3.0
23,437
0.037377
#!/usr/bin/env python # # Raspberry Pi Internet Radio # using an Adafruit RGB-backlit LCD plate for Raspberry Pi. # $Id: ada_radio.py,v 1.37 2014/11/04 19:53:46 bob Exp $ # # Author : Bob Rathbone # Site : http://www.bobrathbone.com # # This program uses Music Player Daemon 'mpd'and it's client 'mpc' # See http://...
lect(lcd,radio) elif display_mode == radio.MODE_OPTIONS: display_options(lcd,radio) elif display_mode == radio.MODE_IP: lcd.line2("Radio v" + radio.getVersion()) if ipaddr is "": lcd.line1("No IP network") else: lcd.scroll1("IP " + ipaddr, interrupt) elif display_mode == rad
io.MODE_RSS: displayTime(lcd,radio) display_rss(lcd,rss) elif display_mode == radio.MODE_SLEEP: displayTime(lcd,radio) display_sleep(lcd,radio) time.sleep(0.3) # Timer function checkTimer(radio) # Check state (pause or play) checkState(radio) # Alarm wakeup function if displ...
lucasdavid/drf-base
src/authority/urls.py
Python
mit
518
0
from infrastructure.routers import Router from . import views r = Router() r.register('users', views.UsersViewSet) \ .register('groups', views.GroupsViewSet, base_name='user-groups', parents_query_lookups=['user']) r.register('grou
ps', views.GroupsViewSet) \ .register('permissions', views.PermissionsViewSet, base_name='group-permissions', parents_query_lookups=['group']) r.register('permissions', views.PermissionsViewSet
) urlpatterns = r.urls
HEP-DL/dl_data_validation_toolset
dl_data_validation_toolset/framework/report_gen/individual.py
Python
mit
1,048
0.009542
import logging from ..report.individual import IndividualReport class IndividualGenerator(object): logger = logging.getLogger("ddvt.rep_gen.ind") def __init__(self, test): self.test = test async def generate(self, parent): test_group = None try: test_group = self.test(parent.filename) ex...
{'error': str(e)}))
return for test in test_group._tests_: self.logger.info("Starting Test: {}".format(test)) try: result, status = getattr(test_group, test)() parent.report.reports.append(IndividualReport(test, status, result)) # TODO: Figure out what to do next except Exception as e: ...
drptbl/webium
tests/alert_page/test_switch_to_new_window.py
Python
apache-2.0
736
0
from unittest import TestCase from nose.tools import assert_false, ok_, eq_ from tests.alert_page import AlertPage from webium.windows_handler import WindowsHa
ndler class TestSwitchToNewWindow(TestCase): def test_switch_to_new_window(self): page = AlertPage() handler = WindowsHandler() page.open() pa
rent = handler.active_window handler.save_window_set() assert_false(handler.is_new_window_present()) page.open_new_window_link.click() ok_(handler.is_new_window_present()) new = handler.new_window handler.switch_to_new_window() eq_(new, handler.active_window) ...
thatblstudio/svnScripts
ignore.py
Python
mit
562
0.009025
# coding=utf-8 # Created by bl 2015/10/30. import os import shutil basePath = os.getcwd() pathList = list() # 获取目录 for dirName in os.listdir(basePath): path = os.path.join(basePath, dirName) if os.path.isdir(path): pathLis
t.append(path) # print pathList for path in pathList: shutil.copy(basePath+"\ignore.myignore",path+"\ignore.myignore") os.chdir(path) os.system('svn propdel svn:global-ignores')
os.system('svn propset svn:ignore -F ignore.myignore .') os.remove(path+"\ignore.myignore") os.system('pause')
bslatkin/pycon2014
lib/asyncio-0.4.1/tests/test_selector_events.py
Python
apache-2.0
62,747
0.000096
"""Tests for selector_events.py""" import collections import errno import gc import pprint import socket import sys import unittest import unittest.mock try: import ssl except ImportError: ssl = None import asyncio from asyncio import selectors from asyncio import test_utils from asyncio.selector_events impor...
self.assertRaises(NotImplementedError, self
.loop._socketpair) def test_read_from_self_tryagain(self): self.loop._ssock.recv.side_effect = BlockingIOError self.assertIsNone(self.loop._read_from_self()) def test_read_from_self_exception(self): self.loop._ssock.recv.side_effect = OSError self.assertRaises(OSError, self.loo...
TracyWebTech/django-revproxy
tests/settings.py
Python
mpl-2.0
1,241
0.000806
SECRET_KEY = 'asdf' DATABASES = { 'default': { 'NAME': 'test.db', 'ENGINE': 'django.db.backends.sqlite3', } } INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.staticfiles', 'revproxy', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sess...
es', 'APP_DIRS': True, 'DIRS': TEMPLATE_DIRS, }, ] LOGGING = { 'version': 1, 'handlers': { 'null': { 'level': 'DEBUG',
'class': 'logging.NullHandler', }, }, 'loggers': { 'revproxy': { 'handlers': ['null'], 'propagate': False, }, }, }