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 |
|---|---|---|---|---|---|---|---|---|
anish/buildbot | master/buildbot/test/unit/test_reporters_utils.py | Python | gpl-2.0 | 8,181 | 0.001834 | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without eve... | erid=80),
fakedb.BuildRequest(id=11, buildsetid=98, builderid=80),
fakedb.BuildRequest(id=12, buildsetid=98, builderid=80),
fakedb.Build(id=18, number=0, builderid=80, buildrequestid=9, wo | rkerid=13,
masterid=92, results=FAILURE),
fakedb.Build(id=19, number=1, builderid=80, buildrequestid=10, workerid=13,
masterid=92, results=RETRY),
fakedb.Build(id=20, number=2, builderid=80, buildrequestid=11, workerid=13,
... |
zack3241/incubator-airflow | airflow/contrib/hooks/redshift_hook.py | Python | apache-2.0 | 4,181 | 0.001196 | # -*- coding: utf-8 -*-
#
# 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
... | ster'] else None
def create_cluster_snapshot(self, snapshot_identifier, cluster_identifier):
"""
| Creates a snapshot of a cluster
:param snapshot_identifier: unique identifier for a snapshot of a cluster
:type snapshot_identifier: str
:param cluster_identifier: unique identifier of a cluster
:type cluster_identifier: str
"""
response = self.get_conn().create_cl... |
STOP2/stop2.0-backend | src/db.py | Python | mit | 4,799 | 0.004168 | import asyncio
import time
import psycopg2
import psycopg2.pool
import os
import sys
class Database:
def __init__(self):
loop = asyncio.get_event_loop()
loop.run_until_complete(self.init_connection())
@asyncio.coroutine
def init_connection(self):
result = 1
loop_end =... | ion(conn)
return result
def cancel_request(self, request_id):
conn = self.get_connection()
cur = conn.cursor()
values = (request_id,) |
sql = "UPDATE request SET canceled = true, cancel_time = now() WHERE id = %s RETURNING trip_id"
cur.execute(sql, values)
trip_id = cur.fetchone()[0]
conn.commit()
self.put_connection(conn)
return trip_id
def get_requests(self, trip_id):
conn = self.g... |
Azure/azure-sdk-for-python | sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/v2018_06_01/aio/operations/_subscriptions_operations.py | Python | mit | 12,046 | 0.004649 | # 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 ... | e passed the direct response
| :return: An iterator like instance of either SubscriptionListResult or the result of
cls(response)
:rtype:
~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.subscriptions.v2018_06_01.models.SubscriptionListResult]
:raises: ~azure.core.exceptions.HttpResponseError
... |
lmazuel/azure-sdk-for-python | azure-servicefabric/azure/servicefabric/models/cluster_upgrade_description_object.py | Python | mit | 5,840 | 0.00137 | # 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 ... | on has not changed (the upgrade
only changes configuration or data).
:type force_restart: bool
:param enable_delta_health_evaluation: When true, enables delta health
evaluation rather | than absolute health evaluation after completion of each
upgrade domain.
:type enable_delta_health_evaluation: bool
:param monitoring_policy: Describes the parameters for monitoring an
upgrade in Monitored mode.
:type monitoring_policy:
~azure.servicefabric.models.MonitoringPolicyDescription... |
lbovet/platane | restlite.py | Python | lgpl-3.0 | 29,388 | 0.010617 | '''
restlite: REST + Python + JSON + XML + SQLite + authentication.
http://code.google.com/p/restlite
Copyright (c) 2009, Kundan Singh, kundan10@gmail.com. All rights reserved.
License: released under LGPL (Lesser GNU Public License).
This light-weight module allows quick prototyping of web services using the... | nd( ('Accept-Charset', 'utf-8') )
orig = Cookie.SimpleCookie(); cookie = env['COOKIE']
if 'HTTP_COOKIE' in env: orig.lo | ad(env['HTTP_COOKIE'])
map(lambda x: cookie.__delitem__(x), [x for x in orig if x in cookie and str(orig[x]) == str(cookie[x])])
if len(cookie): headers.extend([(x[0], x[1].strip()) for x in [str(y).split(':', 1) for y in cookie.itervalues()]])
start_respon... |
a2ron44/alfredHomeAutomation | alfredPHP/controller.py | Python | gpl-3.0 | 539 | 0.012987 | import smbus, sys
import time
bus = smbus.SMBus(1)
# i2c address
address = | 0x04
if len(sys.argv) < 3:
print -1
sys.exit()
cmd = sys.argv[1]
msg = sys.argv[2]
msAr = []
for x in msg:
msAr.append(ord(x))
def writeNumber():
#bus.write_byte(address, value)
bus.write_i2c_block_data(address,ord(cmd), msAr)
return -1
def readNumber():
number = bus.read_byte(address... | adNumber()
print res |
hugovk/terroroftinytown | terroroftinytown/tracker/database.py | Python | mit | 992 | 0 | # encoding=utf-8
import sqlalchemy
from sqlalchemy.engine import create_engine
from sqlalchemy.pool import SingletonThreadPool
from terroroftinytown.tracker.model import Session, Base
class Database(object):
def __init__(self, path, delete_everything=False):
if path.startswith('sqlite:'):
sel... | if delete_everything == 'yes-really!':
self._delete_everything()
Base.metadata.create_all(self.engine)
@classmethod
| def _apply_pragmas_callback(cls, connection, record):
connection.execute('PRAGMA journal_mode=WAL')
connection.execute('PRAGMA synchronous=NORMAL')
def _delete_everything(self):
Base.metadata.drop_all(self.engine)
|
astrobin/astrobin | astrobin/settings/components/caches.py | Python | agpl-3.0 | 824 | 0.002427 | import os
CACHE_TYPE = os.environ.get('CACHE_TYPE', 'redis').strip()
if CACHE_TYPE == 'redis':
CACHES = {
'default': {
'BACKEND': 'django_redis.cache.RedisCache',
'LOCATION': os.environ.get('CACHE_URL', 'redis://redis:6379/1').strip(),
'OPTIONS': {
'CLIE... | 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
}
| }
else:
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
}
}
|
t3dev/odoo | addons/mrp/models/__init__.py | Python | gpl-3.0 | 608 | 0 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from . import mrp_document
from . import mrp_abstract_workorder
from . import res_config_settings
from . import mrp_bo | m
from . import mrp_routing
from . import mrp_workcenter
from . import mrp_production
from . import stock_traceability
from . import mrp_unbuild
from . import mrp_workorder
from . import product
from . import res_company
from . import stock_move
from . import stock_picking
from . import stock_production_lot
from . impo... | port stock_scrap
from . import stock_warehouse
|
helldorado/ansible | test/units/modules/network/f5/test_bigiq_device_facts.py | Python | gpl-3.0 | 3,123 | 0.00064 | # -*- coding: utf-8 -*-
#
# Copyright: (c) 20 | 18, F5 Networks Inc.
# 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
import os
import json
import pytest
import sys
if sys.version_info < (2, 7):
pytestmark = pytest.mark.skip("F5 A... | from library.modules.bigiq_device_facts import SystemInfoFactManager
from library.modules.bigiq_device_facts import ModuleManager
from library.modules.bigiq_device_facts import ArgumentSpec
# In Ansible 2.8, Ansible changed import paths.
from test.units.compat import unittest
from test.units.compa... |
googleapis/python-securitycenter | google/cloud/securitycenter_v1p1beta1/types/source.py | Python | apache-2.0 | 2,762 | 0.000362 | # -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | "projects/{project_number}/sources/{source_id}", depending
on the closest CRM ancestor of the resource associated with
the finding.
"""
name = proto.Field(proto.STRING, number=1,)
display_name = proto.Field(proto.STRING | , number=2,)
description = proto.Field(proto.STRING, number=3,)
canonical_name = proto.Field(proto.STRING, number=14,)
__all__ = tuple(sorted(__protobuf__.manifest))
|
ntymtsiv/tempest | tempest/api/compute/v3/admin/test_servers.py | Python | apache-2.0 | 7,222 | 0 | # Copyright 2013 IBM Corp.
#
# 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... | # Verify server's state
resp, server = self.client.get_server(self.s1_id)
self.assertEqual(server['status'], 'ACTIVE')
@attr(type='gate')
@skip_because(bug="1240043")
def test_get_server_diagnostics_by_admin(self):
# Retrieve server diagnostics by admin user
resp, diagnost... | .client.get_server_diagnostics(self.s1_id)
self.assertEqual(200, resp.status)
basic_attrs = ['rx_packets', 'rx_errors', 'rx_drop',
'tx_packets', 'tx_errors', 'tx_drop',
'read_req', 'write_req', 'cpu', 'memory']
for key in basic_attrs:
sel... |
metabrainz/picard | picard/formats/mutagenext/tak.py | Python | gpl-2.0 | 2,426 | 0.000825 | # -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2008 Lukáš Lalinský
# Copyright (C) 2013, 2018-2021 Laurent Monin
# Copyright (C) 2017 Sambhav Kothari
# Copyright (C) 2018-2019 Philipp Wolfer
#
# This program is free software; you can redistribute it and/or
# modify it under... | if len(header) != 4 or not header.startswith(b"tBaK"):
raise TAKHeaderError("not a TAK file")
@staticmethod
def pprint():
return "Tom's lossless Audio Kompressor"
class TAK(APEv2File):
"""TAK(filething)
Arguments:
filething (filething)
... | nfo (`TAKInfo`)
"""
_Info = TAKInfo
_mimes = ["audio/x-tak"]
@staticmethod
def score(filename, fileobj, header):
return header.startswith(b"tBaK") + filename.lower().endswith(".tak")
Open = TAK
|
chimkentec/KodiMODo_rep | plugin.video.torrenter/Localization.py | Python | gpl-3.0 | 56,942 | 0.008658 | # -*- coding: utf-8 -*-
'''
Torrenter v2 plugin for XBMC/Kodi
Copyright (C) 2012-2015 Vadim Skorba v1 - DiMartino v2
https://forums.tvaddons.ag/addon-releases/29224-torrenter-v2.html
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public Li... | ,
'This vastly decreases load speed, but you will be asked to download premade bases!': 'זה יאט את קצב ההעלאה אך יוריד מיד | ע על הסרטים',
'Do you want to preload full metadata?': 'האם תרצה להוריד את כל המידע',
'It is highly recommended!': 'מומלץ',
'TV Shows': 'סדרות',
'Cartoons': 'אנימציה',
'Anime': 'אנימה',
'Most Recent': 'החדשים ביותר',
'Top 250 Movies': '... |
wxgeo/geophar | wxgeometrie/sympy/codegen/tests/test_rewriting.py | Python | gpl-2.0 | 4,843 | 0.000413 | # -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function)
from sympy import log, exp, Symbol, Pow, sin
from sympy.printing.ccode import ccode
from sympy.codegen.cfunctions import log2, exp2, expm1, log1p
from sympy.codegen.rewriting import (
optimize, log2_opt, exp2_opt, expm1_opt,... | pt7 = optimize(expr7, optims_c99)
delta7 = opt7 - (log(3) + log1p(x))
assert delta7 == 0
assert (opt7.rewrite(log) - expr7).simplify() == 0
expr8 = log(2*x + 3)
opt8 = optimize(expr8, optims_c99)
assert opt8 == ex | pr8
def test_create_expand_pow_optimization():
my_opt = create_expand_pow_optimization(4)
x = Symbol('x')
assert ccode(optimize(x**4, [my_opt])) == 'x*x*x*x'
x5x4 = x**5 + x**4
assert ccode(optimize(x5x4, [my_opt])) == 'pow(x, 5) + x*x*x*x'
sin4x = sin(x)**4
assert ccode(optimize(sin4x,... |
mitchellrj/touchdown | touchdown/aws/cloudfront/streaming_distribution.py | Python | apache-2.0 | 6,002 | 0.001666 | # Copyright 2014-2015 Isotoma Limited
#
# 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 wr... | eamingDistributionConfig=serializers.Resource(
Enabled=False,
),
)
yield self.get_ | waiter(
["Waiting for streaming distribution to enter disabled state"],
"streaming_distribution_deployed",
)
yield RefreshMetadata(self)
for change in super(Destroy, self).destroy_object():
yield change
class AliasTarget(route53.AliasTarget... |
michaelarnauts/home-assistant | homeassistant/components/script.py | Python | mit | 5,105 | 0 | """
homeassistant.components.script
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Scripts are a sequence of actions that can be triggered manually
by the user or automatically based upon automation events, etc.
"""
import logging
from datetime import timedelta
import homeassistant.util.dt as date_util
import threading
from homeas... | otherwise. """
for action in self.actions:
if CONF_SERVICE in action:
self._call_service(action)
elif CONF_DELAY in action:
delay = timedelta(**action[CONF_DELAY])
point_in_time = date_util.now() + delay
self.listener = tra... | __call__(self, *args, **kwargs):
""" Executes the script. """
_LOGGER.info("Executing script %s", self.alias)
with self._lock:
if self.actions is None:
self.actions = (action for action in self.sequence)
if not self._execute_until_done():
... |
m-lab/operator | plsync/sites.py | Python | apache-2.0 | 25,116 | 0.01067 | #!/usr/bin/python
from planetlab.model import *
from users import user_list
# NOTE: The legacy network remap is used to re-order the automatically
# generated, sequential list of ipaddresses to a legacy order to preserve
# pre-existing slice-and-IP assignments. Otherwise, slices would be assigned
# to new IPs,... | ue),
makesite('arn03','213.242.86.64', '2001:4c08:2003:44::', 'Stockholm', 'SE', 59.651900, 17.918600, user_list, count=4, arch='x86_64-r630', nodegroup='MeasurementLabCentos', roundrobin=True),
makesite('arn04','62.115.225.128', '2001:2030:0:38::', 'Stockholm', 'SE', 59.651900, 17.918600, user_list, coun... | 'arn05','77.67.119.64', '2001:668:1f:6a::', 'Stockholm', 'SE', 59.651900, 17.918600, user_list, count=4, arch='x86_64-r630', nodegroup='MeasurementLabCentos', roundrobin=True),
makesite('ath03','193.201.166.128', '2001:648:25e0::', 'Athens', 'GR', 37.936400, 23.944400, user_list, count=4, arch='x86_64-r63... |
inuyasha2012/pypsy | demo/demo_grm.py | Python | mit | 220 | 0 | # coding=utf-8
# 项目反应理论中的等级反应模型
from __future__ import divis | ion, print_function, unicode_literals
from psy import Grm, data
score | s = data['lsat.dat']
grm = Grm(scores=scores)
print(grm.em())
|
feigaochn/leetcode | p435_non_overlapping_intervals.py | Python | mit | 823 | 0 | # Definition for an interval.
class Interval:
def __init__(self, s=0, e=0):
self.start = s
self.end = e
class Solution:
def eraseOverlapIntervals(self, intervals):
"""
:type intervals: List[Interval]
:rtype: int
"""
if not intervals:
return | 0
| intervals.sort(key=lambda i: (i.end, i.start))
kicks = 0
pre_end = intervals[0].end
for it in intervals[1:]:
if it.start < pre_end:
kicks += 1
else:
pre_end = it.end
return kicks
fn = Solution().eraseOverlapIntervals
print(fn(... |
pythonkr/pyconkr-2014 | pyconkr/forms.py | Python | mit | 1,760 | 0 | from django import forms
from django.utils.t | ranslation import ugettext_lazy as _
from django_summernote.widgets import SummernoteInplaceWidget
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
from .models import Speaker, Program
class EmailLoginForm(forms.Form):
email = fo | rms.EmailField(
max_length=255,
label='',
widget=forms.TextInput(attrs={
'placeholder': 'Email address',
'class': 'form-control',
})
)
def clean(self):
cleaned_data = super(EmailLoginForm, self).clean()
return cleaned_data
class SpeakerF... |
dana-i2cat/felix | expedient/src/python/plugins/vt_plugin/models/VtPlugin.py | Python | apache-2.0 | 3,112 | 0.008676 | from django.db import models
from django.core.exceptions import MultipleObjectsReturned
from expedient.clearinghouse.aggregate.models import Aggregate
from expedient.common.permissions.shortcuts import must_have_permission
from vt_plugin.models.VM import VM
# Virtualization Plugin class
class VtPlugin(Aggregate):
... | self.stop_slice(slice)
self.remove_from_slice(slice, next)
except:
pass
raise MultipleObjectsReturned("Please delete all VMs inside aggregate '%s' before removing it from slices %s" % (self.name, str(offending_slices)))
# Aggregate has ... | super(VtPlugin, self).remove_from_project(project, next)
"""
aggregate.remove_from_slice on a VT AM will get here first to check
that the slice does not contain VMs for the given aggregate
"""
def remove_from_slice(self, slice, next):
# If any VM (created inside this slice) is found inside... |
brandonheller/mediawiki_to_gollum | split_by_headers.py | Python | bsd-3-clause | 2,218 | 0.002705 | #!/usr/bin/env python
"""Script to split a large mediawiki file into multiple files, by header."""
import sys
import re
import os
ADD_TOC = True # Add TOC everywhere?
def usage():
print "Usage: [scriptname] [infilename]"
if len(sys.argv) != 2:
usage()
exit()
filename_in = sys.argv[1]
if '.' in filename... | = '' # Original.
current_text = '' # Build up the next file to write.
file_in = open(filename_in, 'r')
header_names = [] # list of (hyphenated, orig) file name pairs
TOC_FILE = 'Home.mediawiki' # location of intro text before headers + TOC.
def cap_firsts(s):
s_caps = ''
words = s.split(' ')
for j, ... | in(words)
first = True
i = 0
for line in file_in.readlines():
m = header.match(line)
if m:
assert len(m.groups()) == 1
# dump string to file.
if first:
filename = TOC_FILE
first = False
else:
filename = current_filename + '.mediawiki'
... |
cyrilkyburz/bhwi_proxy | bhwi_proxy.py | Python | mit | 1,516 | 0.019789 | from flask import Flask, request, jsonify, abort
import os
import requests
app = Flask(__name__)
app.debug = os.getenv('DEBUG', '') == 'True'
def access_token():
return os.getenv('ACCESS_TOKEN', '')
def check_user_id(user_id):
if user_id not in os.getenv('USER_IDS', ''):
return abort(403)
def check_user_nam... | status=202)
response.headers.add('Access | -Control-Allow-Origin', '*')
return response
def build_recent_images_url(user_id):
return 'https://api.instagram.com/v1/users/' + user_id + '/media/recent/?access_token=' + access_token()
def build_user_profile_url(user_id):
return 'https://api.instagram.com/v1/users/' + user_id + '?access_token=' + access_toke... |
hamgravy/volk-fft | python/volk_fft_modtool/cfg.py | Python | gpl-3.0 | 3,621 | 0.005523 | #!/usr/bin/env python
#
# Copyright 2013, 2014 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio 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, or (at your opti... | \')',
'os.path.exists(\'$2\')']
self.remapification = [(self.config_name, self.config_defaults_re | map)]
self.verification = [(self.config_name, self.config_defaults_verify)]
default = os.path.join(os.getcwd(), 'volk_fft_modtool.cfg')
icfg = ConfigParser.RawConfigParser()
if cfg:
icfg.read(cfg)
elif os.path.exists(default):
icfg.read(default)
el... |
marshallflax/NVDARemoteServer | daemon.py | Python | gpl-2.0 | 3,540 | 0.051695 | import sys, os, time, atexit
from signal import SIGTERM, SIGKILL
class Daemon:
"""
A generic daemon class.
Usage: subclass the Daemon class and override the run() method
"""
def __init__(self, pidfile, stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'):
self.stdin = stdin
self.stdout = stdout
self... | daemon
self.daemonize()
self.run()
def stop(self):
"""
Stop the daemon
"""
# Get the pid from the pidfile
try:
pf = file(self.pidfile,'r')
pid = int(pf.read().strip())
pf.close()
except IOError:
pid = None
if not pid:
message = "pidfile %s does not exist. Daemon not running?\n"
... | err.write(message % self.pidfile)
return # not an error in a restart
# Try killing the daemon process
try:
while 1:
os.kill(pid, SIGTERM)
time.sleep(0.1)
except OSError, err:
err = str(err)
if err.find("No such process") > 0:
if os.path.exists(self.pidfile):
os.remove(self.pidfile)
... |
prawn-cake/pilvi | pilvi/urls.py | Python | mit | 762 | 0 | """pilvi URL Configuration
The `urlpatterns` list routes URLs to views. For more information | please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_a | pp.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django... |
cprogrammer1994/Python-ComputeShader | Prepare.py | Python | gpl-3.0 | 121 | 0.024793 | import | os, shutil
if not os.path.isdir('Bin'):
os.mkdir('Bin')
if not os.path.isdir('Temp'):
os.mkdir('Tem | p')
|
toabctl/contrail-sandesh | library/python/pysandesh/sandesh_logger.py | Python | apache-2.0 | 6,516 | 0 | #
# Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
#
#
# Sandesh Logger
#
import logging
import logging.config
import logging.handlers
from gen_py.sandesh.ttypes import SandeshLevel
import sandesh_base_logger
import util
def create_logger(generator, logger_class, logger_config_file=None):
l_cl... | logging.handlers.SysLogHandler.LOG | _LOCAL0)
)
self._logger.addHandler(self._logging_syslog_handler)
super(SandeshLogger, self).set_logging_syslog(enable_syslog,
syslog_facility)
# end set_logging_syslog
# end class SandeshLogger
|
andrelaszlo/qtile | examples/config/tailhook-config.py | Python | mit | 6,113 | 0.003278 | # -*- coding: utf-8 -*-
from libqtile.manager import Key, Click, Drag, Screen, Group
from libqtile.command import lazy
from libqtile import layout, bar, widget, hook
from libqtile import xcbq
xcbq.keysyms["XF86AudioRaiseVolume"] = 0x1008ff13
xcbq.keysyms["XF86AudioLowerVolume"] = 0x1008ff11
xcbq.keysyms["XF86AudioMute... | 1, **border))),
layout.Slice('left', 192, role='gimp-toolbox',
fallback=layout.Slice('right', 256, role='gimp-dock',
fallback=layout.Stack(1, **border))),
]
floating_layout = layout.Floating(**border)
groups = [
Group('1'),
Gr | oup('2', layout='max'),
Group('3'),
Group('4', layout='treetab'),
Group('5'),
Group('6'),
Group('7'),
Group('8'),
Group('9'),
]
for i in groups:
keys.append(
Key([mod], i.name, lazy.group[i.name].toscreen())
)
keys.append(
Key([mod, "shift"], i.name, lazy.win... |
Mickey32111/pogom | pogom/pgoapi/protos/POGOProtos/Networking/Requests/Messages/CollectDailyDefenderBonusMessage_pb2.py | Python | mit | 2,108 | 0.010436 | # Generated by the protocol buffer compiler. DO NOT EDIT!
# source: POGOProtos/Networking/Requests/Messages/CollectDailyDefenderBonusMessage.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import mes... | s=[
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ra | nges=[],
oneofs=[
],
serialized_start=123,
serialized_end=157,
)
DESCRIPTOR.message_types_by_name['CollectDailyDefenderBonusMessage'] = _COLLECTDAILYDEFENDERBONUSMESSAGE
CollectDailyDefenderBonusMessage = _reflection.GeneratedProtocolMessageType('CollectDailyDefenderBonusMessage', (_message.Message,), dict(
... |
mr-ping/tornado | tornado/test/httpserver_test.py | Python | apache-2.0 | 41,934 | 0.000501 | #!/usr/bin/env python
from __future__ import absolute_import, division, print_function, with_statement
from tornado import netutil
from tornado.escape import json_decode, json_encode, utf8, _unicode, recursive_unicode, native_str
from tornado import gen
from tornado.http1connection import HTTP1Connection
from tornado... | exception)'):
with ExpectLog(gen_log, 'Uncaught exception', required=False):
self.http_client.fetch(
self.get_url("/").replace('https:', 'http:'),
self.stop,
request_timeo | ut=3600,
connect_timeout=3600)
response = self.wait()
self.assertEqual(response.code, 599)
def test_error_logging(self):
# No stack traces are logged for SSL errors.
with ExpectLog(gen_log, 'SSL Error') as expect_log:
self.http_client.fetch(
... |
klausweiss/python-aui | aui/widgets.py | Python | bsd-2-clause | 4,207 | 0.000475 | import sys
# widgets
class Button:
"""
Represents button
Keyword arguments:
text -- button text
| str
onclick -- function invoked after pressing the button
| function: Button -> void
Attributes:
wide -- makes the button wide
"""
def __new__(cl... | -- default value
| str (default: "")
onenter -- function called after the return key is pressed
| function: Input -> void
Attributes:
wide -- makes the input wide
"""
def __new__(cls, value="", onenter=None, *args):
return object.__new... | field"""
pass
class Label:
"""
Represents label in UI
Keyword arguments:
text -- label text
| str
"""
def __new__(cls, text=None, *args):
return object.__new__(sys.modules['aui.widgets'].Label)
def __init__(self, text):
pass
def destroy(self):
... |
linuxdeepin/deepin-ui | dtk/ui/cycle_strip.py | Python | gpl-3.0 | 2,087 | 0.001917 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2011 ~ 2012 Deepin, Inc.
# 2011 ~ 2012 Wang Yong
#
# Author: Wang Yong <lazycat.manatee@gmail.com>
# Maintainer: Wang Yong <lazycat.manatee@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the... | dpixbuf: DynamicPixbuf background.
'''
gtk.HBox.__init__(self)
self.background_dpixbuf = background_dpixbuf
self.cache_pixbuf = CachePixbuf()
self.set_size_request(-1, self.background_dpixbuf.get_pixbuf().get_height())
self.connect("expose-event", self.expose_cycle_stri... | cairo_create()
rect = widget.allocation
background_pixbuf = self.background_dpixbuf.get_pixbuf()
self.cache_pixbuf.scale(
background_pixbuf,
rect.width,
rect.height)
draw_pixbuf(
cr,
self.cache_pixbuf.get_cache(),
... |
mfogel/django-signup-login | signup_login/urls.py | Python | bsd-3-clause | 1,287 | 0.006993 | from django.conf.urls.defaults import *
from .views import *
urlpatterns = patterns('',
url(r'^signup/$',
view=SignupLoginView.as_view(
featured_form_mixin_class=SignupMultipleFormMixin),
name='accounts_signup'
),
url(r'^login/$',
view=SignupLoginView.as_view(
... | iew(
featured_form_mixin_class=SignupIframeMultipleFormMixin),
name='accounts_signup_iframe'
| ),
url(r'^iframes/login/$',
view=SignupLoginIframeView.as_view(
featured_form_mixin_class=LoginIframeMultipleFormMixin),
name='accounts_login_iframe'
),
url(r'^iframes/signup-login/$',
view=SignupLoginIframeView.as_view(),
name='accounts_signup_login_iframe'
... |
ERPXE/erpxe | erpxe/cli.py | Python | gpl-3.0 | 2,519 | 0.030171 | # import the ERPXE core API
import core
# Global variables
TFTPBOOT_DIR = "/tftpboot"
PLUGINS_DIR = TFTPBOOT_DIR + "/er/plugins"
# try to Load configuration from file system or use defaults
def load_configuration():
# try to fetch configuration from file
try:
config = core.get_configuration()
exce... | e_menu():
try:
core.get_configuration()
print("ERPXE menu rendered succesfully")
exc | ept Exception, e:
print str(e)
print "missing configuration file. use 'erpxe create-configuration-file' command to create one from template"
return
core.generate_menu(TFTPBOOT_DIR, PLUGINS_DIR)
def similar(PLUGIN):
from difflib import SequenceMatcher
plugins = core.get_plugins_list(PLUGINS_DIR)
... |
mitodl/django-server-status | server_status/tests/urls.py | Python | agpl-3.0 | 328 | 0 | """URLs to run the tests."""
try:
from django.urls import include
except ImportError:
from django.c | onf.urls import include
from django.conf.urls import url
from django.contrib import admin
admin.autodiscover()
urlpatterns = (
url(r'^admin/', admin.site.urls), |
url(r'^status', include('server_status.urls')),
)
|
r41d/pytradfri | pytradfri/mood.py | Python | mit | 383 | 0 | """Represent a mood on the gateway." | ""
from .const import ROOT_MOODS
from .resource import ApiResource
class Mood(ApiResource):
def __init__(self, raw, parent):
super().__init__(raw)
self._parent = parent
@property
def path(self):
r | eturn [ROOT_MOODS, self._parent, self.id]
def __repr__(self):
return '<Mood {}>'.format(self.name)
|
juliatem/aiohttp | aiohttp/abc.py | Python | apache-2.0 | 3,396 | 0 | import asyncio
import sys
from abc import ABC, abstractmethod
from collections.abc import Iterable, Sized
PY_35 = sys.version_info >= (3, 5)
class AbstractRouter(ABC):
def _ | _init__(self):
self._frozen = False
def post_init(s | elf, app):
"""Post init stage.
Not an abstract method for sake of backward compatibility,
but if the router wants to be aware of the application
it can override this.
"""
@property
def frozen(self):
return self._frozen
def freeze(self):
"""Freeze ro... |
VRaviTheja/SDN-policy | testing/testing_portrange.py | Python | apache-2.0 | 112 | 0 | from port_range import PortRange
pr | = PortRange('1027/15')
print(pr.bounds)
pr = Po | rtRange('4242-42')
print(pr)
|
nootropics/propane | propane.py | Python | mit | 3,698 | 0.027853 | #!/usr/bin/env python
import sys
import optparse
import socket
import random
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
if sys.platform == 'win32':
HEADER... | found or accessed")
s.send("site cpto %s" % resultpath)
if "250" in s.recv(1024):
good("Copy sucessful! Check http://%s/%s for your file!" % (options.target, resultpath))
else:
error("Access denied!")
if options | .chosenmode == "3":
shellkey = ''.join(random.choice('0123456789ABCDEF') for i in range(16)) + ".php"
s.send("site cpfr /etc/passwd")
s.recv(1024)
s.send("site cpto <?php @$_GET['x']($_GET['a']); ?>")
s.recv(1024)
s.send("site cpfr /proc/self/fd/3")
s.recv(1024)
s.send("site cpto %s%s" % (options.webdir... |
stuart-knock/tvb-framework | tvb/core/code_versions/code_update_scripts/4750_update_code.py | Python | gpl-2.0 | 2,378 | 0.006728 | # -*- coding: utf-8 -*-
#
#
# TheVirtualBrain-Framework Package. This package holds all Data Management, and
# Web-UI helpful to run brain-simulations. To use it, you also need do download
# TheVirtualBrain-Scientific Package (for simulators). See content of the
# documentation-folder for more details. See also http:/... | in network dynamics.
# Frontiers in Neuroinformatics (7:10. doi: 10.3389/fninf.2013.00010)
#
#
"""
.. moduleauthor:: Bogdan Neacsa <bogdan.neacsa@codem | art.ro>
"""
from tvb.basic.logger.builder import get_logger
from tvb.core.entities.storage import dao
from tvb.core.services.event_handlers import handle_event
LOGGER = get_logger(__name__)
PAGE_SIZE = 20
EVENT_FILE_IDENTIFIER = "CodeVersionsManager.update.4750"
def update():
"""
Update TVB code to SVN rev... |
Williams224/davinci-scripts | ksteta3pi/NTupleMaker_MagDown.py | Python | mit | 17,928 | 0.01863 | from Gaudi.Configuration import *
from Configurables import DaVinci
#from Configurables import AlgTool
from Configurables import GaudiSequencer
MySequencer = GaudiSequencer('Sequence')
#For 2012 MC
DaVinci.DDDBtag='dddb-20130929-1'
DaVinci.CondDBtag='sim-20130522-1-vc-md100'
#for 2011 MC
#DaVinci.DDDBtag='dddb-2013092... | e"]
for stream in streams:
for line in stream.lines:
if line.name() in MyLines:
MyStream.appendLines( [ line ])
from Configurables import ProcStatusCheck
filterBadEvents=ProcStatusCheck()
sc=StrippingConf( Streams= [ MyStream ],
MaxCandidates ... | alse,
BadEventSelection = filterBadEvents)
DaVinci().appendToMainSequence([event_node_killer,sc.sequence()])
##################Creating NTuples#####################################
from Configurables import DecayTreeTuple
from Configurables import TupleToolL0Calo
from Decay... |
chrisjsewell/PyGauss | pygauss/analysis.py | Python | gpl-3.0 | 44,913 | 0.00993 | # -*- coding: utf-8 -*-
from itertools import product, imap
import copy
import math
import string
import multiprocessing
import platform
import numpy as np
import pandas as pd
from pandas.tools.plotting import radviz
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from matplotlib.colors import ColorConverte... | ide | ntifiers, ipython_print)
#add the molecules to the internal table
for molecule, idents, inputs, read_error in zip(molecules, identifiers,
mol_inputs, read_errors):
num_files = filter(lambda x:x, [inputs['init_fname'], inputs['opt_f... |
sadahanu/DataScience_SideProject | Stack_Exchange/py2_text.py | Python | mit | 7,689 | 0.017167 | # -*- coding: utf-8 -*-
"""
Created on Tue Dec 13 23:10:40 2016
@author: zhouyu
"""
#%%
import pandas as pd
import numpy as np
import os
import re
import nltk
from nltk.corpus import stopwords
from bs4 import BeautifulSoup
os.chdir('/Users/zhouyu/Documents/Zhou_Yu/DS/kaggle_challenge/text processing')
#%% step1: impor... | f_transformer = TfidfTransformer(use_idf = False).fit(X_train_counts)
X_train_tf = tf_transformer.transform(X_train_counts)
#%% training a linear model
# METHOD 1: BUILD randomforestclassifier...
from sklearn.ensemble import RandomForestClassifier
rf = RandomForestClassifier(n_estimators = 10)
forest = rf.fit(X_train_t... | X_train_tf)
from sklearn.metrics import confusion_matrix
from sklearn.metrics import classification_report
from collections import OrderedDict
import matplotlib.pyplot as plt
import itertools
def plot_confusion_matrix(cm, classes,
normalize=False,
title='Confusion ma... |
detman/stomplooper | recorder.py | Python | gpl-3.0 | 646 | 0.010836 | #!/usr/bin/python
import time
class Recorder(object):
debug = 0
def __init__(self):
self.recordings = []
self.lastRecord = 0
if Recorder.debug:
print("init Recorder")
def record(self):
now = time.time();
if self.lastRecord != 0:
sel | f.recordings.append(now-self.lastRecord)
if Recorder.debug:
print(len(self.recordings), " ", self.recordings[-1]);
self.lastRecord = now
def empty(self):
return len(self.recordings) > 0
def minInterval(self):
return 0 if len(self.recording) == 0 else self.r... | cording[0]
|
jezdez/django-hosts | django_hosts/templatetags/hosts.py | Python | bsd-3-clause | 5,070 | 0 | import re
from django import template
from django.conf import settings
from django.template import TemplateSyntaxError
from django.template.base import FilterExpression
from django.template.defaulttags import URLNode
from django.utils.encoding import iri_to_uri, smart_str
from django.urls import set_urlconf, get_urlco... | arg_re = re.compile(r"(?:(\w+)=)?(. | +)")
class HostURLNode(URLNode):
def __init__(self, *args, **kwargs):
self.host = kwargs.pop('host')
self.host_args = kwargs.pop('host_args')
self.host_kwargs = kwargs.pop('host_kwargs')
self.scheme = kwargs.pop('scheme')
self.port = kwargs.pop('port')
super(HostUR... |
luzfcb/cookiecutter | tests/replay/test_replay.py | Python | bsd-3-clause | 2,207 | 0 | # -*- coding: utf-8 -*-
"""test_replay."""
import os
import pytest
from cookiecutter import replay, main, exceptions
def test_get_replay_file_name():
"""Make sure that replay.get_file_name generates a valid json file path."""
exp_replay_file_name = os.path.join('foo', 'bar.json')
assert replay.get_file... | n `replay`."""
mock_ | prompt = mocker.patch('cookiecutter.main.prompt_for_config')
mock_gen_context = mocker.patch('cookiecutter.main.generate_context')
mock_gen_files = mocker.patch('cookiecutter.main.generate_files')
mock_replay_dump = mocker.patch('cookiecutter.main.dump')
mock_replay_load = mocker.patch('cookiecutter.mai... |
a5kin/hecate | examples/__init__.py | Python | mit | 107 | 0 | """
A colle | ction of Xentica models and experiments.
Indende | d to illustrate how to use the framework.
"""
|
tykkz/hasherapp | algorithm.py | Python | mit | 1,194 | 0.002513 | import hashlib
def | hash_list():
return str(hashlib.algorithms_guaranteed)
def hash_text(algorithm_array, text, pass_count):
result_dict = {}
# Type checking
if type(pass_count) is not int:
return [False, {"error": "Pass count should be of 'integer' type."}]
elif type(text) is not str:
return [False, ... | list should be of 'list' type."}]
# Bounds checking
avail_alg_set = set(algorithm_array) & set(hashlib.algorithms_guaranteed)
if pass_count > 1000000 or pass_count <= 0:
return [False, {"error": "Pass count should be larger than 0 and smaller than 1000000."}]
elif len(avail_alg_set) == 0:
... |
ONLYOFFICE/core | Test/Applications/StandardTester/tester/scripts/generate.py | Python | agpl-3.0 | 134 | 0.014925 | #! | /usr/bin/env python
import tester
tester.make(["--input='./result/standard'", "--output='./result/out'", "--standard", "--cores=1" | ]) |
prymitive/bootstrap-breadcrumbs | django_bootstrap_breadcrumbs/templatetags/django_bootstrap_breadcrumbs.py | Python | mit | 7,292 | 0 | # -*- coding: utf | -8 -*-
"""
:copyrigh | t: Copyright 2013 by Łukasz Mierzwa
:contact: l.mierzwa@gmail.com
"""
from __future__ import unicode_literals
import logging
from inspect import ismethod
from django.utils.html import escape
from django.utils.safestring import mark_safe
from django.utils.encoding import smart_text
from django.db.models import M... |
OpenISA/riscv-sbt | scripts/auto/llvm.py | Python | mit | 3,402 | 0.004409 | #!/usr/bin/env python3
from auto.config import DIR, RV32_LINUX
from auto.gnu_toolchain import GnuToolchain
from auto.utils import cat, cd, path, shell
import auto.pkg
import os
class LLVM(auto.pkg.Package):
def _prepare(self):
link = path(DIR.submodules, "llvm/tools/clang")
if not os.path.exist... | refix):
return cat(
"cmake",
"-G Ninja",
'-DLLVM_TARGETS_TO_BUIL | D="ARM;X86"',
"-DCMAKE_BUILD_TYPE=Debug",
"-DBUILD_SHARED_LIBS=True",
"-DLLVM_USE_SPLIT_DWARF=True",
"-DLLVM_OPTIMIZED_TABLEGEN=True",
"-DLLVM_BUILD_TESTS=True",
"-DCMAKE_C_COMPILER=/usr/bin/clang-{0}",
"-DCMAKE_CXX_COMPILER=/usr/bin/cl... |
rohitranjan1991/home-assistant | homeassistant/components/ovo_energy/sensor.py | Python | mit | 6,463 | 0.000928 | """Support for OVO Energy sensors."""
from __future__ import annotations
from collections.abc import Callable
from dataclasses import dataclass
from datetime import datetime, timedelta
from typing import Final
from ovoenergy import OVODailyUsage
from ovoenergy.ovoenergy import OVOEnergy
from homeassistant.components... | )
entities.append(OVOEnergySensor(coordinator, description, client))
if coordinator.data.gas:
for description in SENSOR_TYPES_GAS:
if (
description.key == KEY_LAST_GAS_COST
and coordinator.data.gas[-1] is | not None
and coordinator.data.gas[-1].cost is not None
):
description.native_unit_of_measurement = coordinator.data.gas[
-1
].cost.currency_unit
entities.append(OVOEnergySensor(coordinator, description, ... |
daweiwu/meta-iotqa-1 | lib/oeqa/runtime/sensor/test_gyro_lsm330dlc.py | Python | mit | 2,634 | 0.006834 | """
@file test_gyro_lsm330dlc.py
"""
##
# @addtogroup soletta sensor
# @brief This is sensor test based on soletta app
# @brief test sensor lsm330dlc on Galileo/MinnowMax/Edison
##
import os
import time
from oeqa.utils.helper import shell_cmd
from oeqa.oetest import oeRuntimeTest
from EnvirSetup import EnvirSetup
from ... | ut:
(status, output) = self.target.run(
"cd /sys/bus/i2c/devices; \
echo 0x6b >i2c-1/delete_device")
if "Galileo" in output:
(status, output) = self.target.run(
"cd /sys/bus/i2c/devices; \
... | output:
(status, output) = self.target.run(
"cd /sys/bus/i2c/devices; \
echo 0x6b >i2c-6/delete_device")
def test_Gyro_LSM330DLC(self):
'''Execute the test app and verify sensor data
@fn test_Gyro_LSM330DLC
@param self
... |
napalm-automation/napalm-yang | napalm_yang/models/openconfig/network_instances/network_instance/protocols/protocol/ospfv2/areas/area/lsdb/lsa_types/lsa_type/lsas/lsa/as_external_lsa/__init__.py | Python | apache-2.0 | 19,446 | 0.001337 | # -*- coding: utf-8 -*-
from operator import attrgetter
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType
from pyangbind.lib.yangtypes import RestrictedClassType
from pyangbind.lib.yangtypes import TypedListType
from pyangbind.lib.yangtypes import YANGBool
from pyangbind.lib.yangtypes import YANGListTy... | s import OrderedDict
from decimal import Decimal
f | rom bitarray import bitarray
import six
# PY3 support of some PY2 keywords (needs improved)
if six.PY3:
import builtins as __builtin__
long = int
elif six.PY2:
import __builtin__
from . import state
from . import types_of_service
class as_external_lsa(PybindBase):
"""
This class was auto-generate... |
warner83/micropython | tests/bytecode/mp-tests/class5.py | Python | mit | 96 | 0.03125 | class A(B):
pass
class A(object):
pass
class A(x.y()):
| pass
class A(B, C):
| pass
|
ZeroCater/Eyrie | eyrie/wsgi.py | Python | mit | 478 | 0 | """
WSGI config for eyrie project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more i | nformation on this file, see
https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
from whitenoise.django import DjangoWhiteNoise
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "eyrie.settings")
application = get_wsgi_application()
application ... | ngoWhiteNoise(application)
|
lodevil/pyparser | pyparser/symbol.py | Python | apache-2.0 | 72 | 0 |
class Symb | ol(object):
def __init__(self, num, name):
| pass
|
ade25/ade25.assetmanager | ade25/assetmanager/tests/test_setup.py | Python | mit | 1,209 | 0.002481 | # -*- coding: utf-8 -*-
"""Setup/installation tests for this package."""
from ade25.assetmanager.testing import IntegrationTestCase
from plone import api
class TestInstall(IntegrationTestCase):
"""Test installation of ade25.assetmanager into Plone."""
def setUp(self):
"""Custom shared utility setup ... | ']
self.installer = api.portal.get_tool('portal_quickinstaller')
def test_product_installed(self):
"""Test if ade25.assetmanager is installed with portal_quickinstaller."""
self.assertTrue(self.installer.isProductInstalled('ade25.assetmanager'))
def test_uninstall(self):
"""Tes... | alled."""
self.installer.uninstallProducts(['ade25.assetmanager'])
self.assertFalse(self.installer.isProductInstalled('ade25.assetmanager'))
# browserlayer.xml
def test_browserlayer(self):
"""Test that IAde25AssetmanagerLayer is registered."""
from ade25.assetmanager.interfaces ... |
kcthrn/clontris | clontris/meta.py | Python | gpl-3.0 | 1,028 | 0 | # Copyright (C) 2017 Kacy Thorne
#
# This file is part of Clontris.
#
# Clontris is free s | oftware: 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.
#
# Clontris is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; with... | ave received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""This module containts project metadata.
If using setuptools, then within setup.py put::
meta = {}
with open(clontris/meta.py) as f:
exec(f.read(), meta)
Then access this mod... |
ManrajGrover/CodeSprint_India_2014 | Qualification_Round_2/Editorials/array_simp_2.py | Python | mit | 683 | 0.030747 | t = int(raw_input())
MOD = 10**9 + 7
def modexp(a,b):
res = 1
while b:
if b&1:
res *= a
res %= MOD
a = (a*a)%MOD
b /= 2
return res
fn = [1 for _ in xrange(100001)]
ifn = [1 for _ in xrange(100001)]
for i in range(1,100000):
fn[i] = fn[i-1] * i
fn[i] %... | ]
for ti in range(t):
n = int(raw_input())
a = map(int,raw_input().split())
ans = 0
for i in range(n):
if i%2==0:
ans += nCr(n-1,i)%MOD * a[i]%MOD
else:
ans -= nCr(n-1,i)%MOD * a[i]%MOD
ans %= MOD
print | ans |
zcbenz/cefode-chromium | third_party/harfbuzz/contrib/tables/scripts-parse.py | Python | bsd-3-clause | 2,516 | 0.010731 | import sys
from unicode_parse_common import *
# http://www.unicode.org/Public/5.1.0/ucd/Scripts.txt
script_to_harfbuzz = {
# This is the list of HB_Script_* at the time of writing
'Common': 'HB_Script_Common',
'Greek': 'HB_Script_Greek',
'Cyrillic': 'HB_Script_Cyrillic',
'Armenian': 'HB_Script_Armenian',
... | na',
'Devanagari': 'HB_Script_Devanagari',
'Bengali': 'HB_Script_Bengali',
'Gurmukhi': 'HB_Script_Gurmukhi',
'Gujarati': 'HB_Script_Gujarati',
'Oriya': 'HB_Script_Oriya',
| 'Tamil': 'HB_Script_Tamil',
'Telugu': 'HB_Script_Telugu',
'Kannada': 'HB_Script_Kannada',
'Malayalam': 'HB_Script_Malayalam',
'Sinhala': 'HB_Script_Sinhala',
'Thai': 'HB_Script_Thai',
'Lao': 'HB_Script_Lao',
'Tibetan': 'HB_Script_Tibetan',
'Myanmar': 'HB_Script_Myanmar',
'Georgian': 'HB_Script_Georgia... |
openstack/neutron-lib | neutron_lib/callbacks/resources.py | Python | apache-2.0 | 1,353 | 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
# d... | governing permissions and limitations
# under the License.
# String literals representing core resources.
ADDRESS_GROUP = 'address_group'
AGENT = 'agent'
FLOATING_IP = 'floatingip'
LOCAL_IP_ASSOCIATION = 'local_ip_association'
NETWORK = 'network'
NETWORKS = 'networks'
PORT = 'port'
PORTS = 'ports'
PORT_BINDING = '... | UTER = 'router'
ROUTER_CONTROLLER = 'router_controller'
ROUTER_GATEWAY = 'router_gateway'
ROUTER_INTERFACE = 'router_interface'
SECURITY_GROUP = 'security_group'
SECURITY_GROUP_RULE = 'security_group_rule'
SEGMENT = 'segment'
SEGMENT_HOST_MAPPING = 'segment_host_mapping'
SUBNET = 'subnet'
SUBNETS = 'subnets'
SUBNETPOOL... |
camilaavilarinho/monitorador-twitter | monitortwitter/settings/production.py | Python | mit | 3,261 | 0.000613 | from decouple import Csv, config
from dj_database_url import parse as db_url
from .base import * # noqa
DEBUG = False
SECRET_KEY = config('SECRET_KEY')
DATABASES = {
'default': config('DATABASE_URL', cast=db_url),
}
DATABASES['default']['ATOMIC_REQUESTS'] = True
ALLOWED_HOSTS = | config('ALLOWED_HOSTS', cast=Csv())
STAT | IC_ROOT = 'staticfiles'
STATIC_URL = '/static/'
MEDIA_ROOT = 'mediafiles'
MEDIA_URL = '/media/'
SERVER_EMAIL = 'foo@example.com'
EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_HOST_USER = config('SENDGRID_USERNAME')
EMAIL_HOST_PASSWORD = config('SENDGRID_PASSWORD')
EMAIL_PORT = 587
EMAIL_USE_TLS = True
# Security
SECURE_PR... |
Swan/ManiaStarReducer | test/example.py | Python | mit | 398 | 0.005025 | import sys
sys.path.append("..")
from deflate import fix_star_rating
# The | beatmap that you are checking and fixing inflated patterns for
beatmap_path = "./necro.osu"
# The new difficulty name (Version) of the beatmap
new_difficulty_name = "star rating fix"
# The output file path of the beatmap
output | _path = "./necro_fixed.osu"
fix_star_rating(beatmap_path, new_difficulty_name, output_path) |
PLyczkowski/Sticky-Keymap | 2.74/scripts/startup/bl_ui/properties_data_armature.py | Python | gpl-2.0 | 10,538 | 0.001803 | # ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distrib... | needed to allow
# add/replace options to be used properly
col.operator("poselib.pose_add", icon='ZOOMIN', text="")
col.operator_context = 'EXEC_DEFAULT' # exec not invoke, so that menu doesn't need showing
| pose_marker_active = poselib.pose_markers.active
if pose_marker_active is not None:
col.operator("poselib.pose_remove", icon='ZOOMOUT', text="")
col.operator("poselib.apply_pose", icon='ZOOM_SELECTED', text="").pose_index = poselib.pose_markers.active_index
... |
google/tmppy | _py2tmp/unification/__init__.py | Python | apache-2.0 | 920 | 0 | # Copyright 2017 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... | import (
UnificationAmbiguousException,
UnificationFailedException,
CanonicalizationFailedException)
from ._strategy import (
UnificationStrategy,
UnificationStrategyForCanonicalization,
TupleExpansion)
from ._unification import unify
from ._canonicalization | import canonicalize
|
bitmovin/bitcodin-python | bitcodin/test/input/testcase_create_input_incomplete_data.py | Python | unlicense | 727 | 0 | __author__ = 'Dominic Miglar <dominic.miglar@bitmovin.net>'
import unittest
from bitcodin import create_input
from bitcodin import Input
from bitcodin.exceptions import BitcodinBadRequestError
from bitcodin.test.bitcodin_test_case import BitcodinTestCase
class CreateInputIncompleteDataTestCase(BitcodinTestCase):
... | lf):
super(CreateInputIncompleteDataTestCase, self).setUp()
self.inputUrl = ''
def runTest(self):
input = Input(self.inputUrl)
with self.assertRaises(BitcodinBadRequestError):
result = create_input(input)
def tearDown(self):
super(CreateInputIncompleteDataTe... | _main__':
unittest.main()
|
ikkebr/PyBozoCrack | docs/conf.py | Python | bsd-3-clause | 8,453 | 0.005442 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# complexity documentation build configuration file, created by
# sphinx-qu | ickstart on Tue Jul 9 22:26:36 2013.
#
# 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 fil | e.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
# If extensions (or modules to document with autodoc) are in another
# directory, add these directories to sys.path here. If the directory is
# relative to the documentation root, use os.pat... |
tiborsimko/invenio-oauthclient | invenio_oauthclient/alembic/97bbc733896c_create_oauthclient_tables.py | Python | mit | 2,898 | 0 | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2016-2018 CERN.
#
# Inve | nio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Create oauthclient tables."""
import sqlalchemy as sa
import sqlalchemy_utils
from alembic import op
from sqlalchemy.engin | e.reflection import Inspector
# revision identifiers, used by Alembic.
revision = '97bbc733896c'
down_revision = '44ab9963e8cf'
branch_labels = ()
depends_on = '9848d0149abd'
def upgrade():
"""Upgrade database."""
op.create_table(
'oauthclient_remoteaccount',
sa.Column('id', sa.Integer(), nul... |
AdamRTomkins/Neurokernel-singularity-container | examples/data/gen_generic_lpu.py | Python | apache-2.0 | 12,988 | 0.004312 | #!/usr/bin/env python
"""
Create generic LPU and simple pulse input signal.
"""
from itertools import product
import sys
import numpy as np
import h5py
import networkx as nx
def create_lpu_graph(lpu_name, N_sensory, N_local, N_proj):
"""
Create a generic LPU graph.
Creates a graph containing the neuron... | G.add_node(id,
{'class': 'LeakyIAF',
'name': name+'_s',
'initV': np.rando | m.uniform(-60.0,-25.0),
'reset_potential': -67.5489770451,
'resting_potential': 0.0,
'threshold': -25.1355161007,
'resistance': 1002.445570216,
'capacitance': 0.0669810502993,
... |
dextervip/rpv | GerenDisponibilidade/professor/urls.py | Python | gpl-3.0 | 1,015 | 0.009852 | from django.conf.urls.defaults import patterns, url, include
urlpatterns = patterns('professor.views',
url(r'^$', 'home', name='home'),
url(r'^adicionar-compromisso$', 'adicionarCompromisso', name='adicionarCompromisso'),
url(r'^ | visualizar-compromisso/(?P<id>\d{1,10})$', 'visualizarCompromisso', name='visualizarCompromisso'),
url(r'^editar-compromisso/(?P<id>\d{1,10})$', 'editarCompromisso', name='editarCompromisso'),
url(r'^excluir-compromisso/(?P<id>\d{1,10})$', 'excluirCompromisso', name='excluirCompromisso'),
url(r'^get-comprom... | isponibilidadeAula$', 'disponibilidadeAula', name='disponibilidadeAula'),
url(r'^informarInteresseDisciplina$', 'informarInteresseDisciplina', name='informarInteresseDisciplina'),
url(r'^getInteressesDisciplina$', 'getInteressesDisciplina', name='getInteressesDisciplina'),
url(r'^getDisponibilidadeAula$', '... |
fbouliane/ddns-updater-aws | setup.py | Python | mit | 1,053 | 0 | from distutils.core import setup
from setuptools import find_packages
setup(name='ddns_updater_aws',
version='0.1',
| author='Felix Bouliane',
license='MIT',
py_modules=[],
packages=find_packages(exclude=['contrib', 'docs', 'test']),
url='https://github.com/fbouliane/ddns-updater-aws',
classifiers=[
'Development Status :: 3 - Alpha',
| 'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Topic :: Internet',
'Topic :: Internet :: Name Service (DNS)'
],
keywords='DNS, Dynamic DNS, fi... |
rickerc/cinder_audit | cinder/tests/db/test_name_id.py | Python | apache-2.0 | 2,344 | 0 | # Copyright 2013 IBM Corp.
#
# 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... |
from cinder import db
from cinder import test
from cinder.tests import utils as testutils
CONF = cfg.CONF
class NameIDsTestCase(test.TestCase):
"""Test cases for naming volumes with name_id."""
def setUp(self):
super(NameIDsTestCase, self).setUp()
self.ctxt = context.RequestContext(user_id... | :
"""New volume should have same 'id' and 'name_id'."""
vol_ref = testutils.create_volume(self.ctxt, size=1)
self.assertEqual(vol_ref['name_id'], vol_ref['id'])
expected_name = CONF.volume_name_template % vol_ref['id']
self.assertEqual(vol_ref['name'], expected_name)
def tes... |
xingyepei/edx-platform | lms/djangoapps/survey/views.py | Python | agpl-3.0 | 4,127 | 0.002908 | """
View endpoints for Survey
"""
import logging
import json
from django.contrib.auth.decorators import login_required
from django.http import (
HttpResponse, HttpResponseRedirect, HttpResponseNotFound
)
from django.core.urlresolvers import reverse
from django.views.decorators.http import require_POST
from django... | m field
redirect_url = answers['_redirect_url'] if '_redirect_url' in answers else reverse('dashboard')
course_key = CourseKey.from_string(answers['course_id']) if 'course_id' in answers else None
allowed_field_names = survey.get_fiel | d_names()
# scrub the answers to make sure nothing malicious from the user gets stored in
# our database, e.g. JavaScript
filtered_answers = {}
for answer_key in answers.keys():
# only allow known input fields
if answer_key in allowed_field_names:
filtered_answers[answer_key... |
agmscode/agms_python | agms/util/requests_client.py | Python | mit | 509 | 0.001965 | from __future__ import absolute_import
from agms.exception.not_found_exception import NotFoundException
try:
import requests
except ImportError as e:
raise NotFoundException(e)
class RequestsClient(object):
def http_do(self, http_verb, url, headers, request_body):
response = requests.request... | eaders=headers,
data=request_body,
verify=True
)
return [respons | e.status_code, response.text]
|
langara/MyBlocks | picon.py | Python | apache-2.0 | 3,366 | 0.007427 | #!/usr/bin/env python
"""Small tool for copying android icons from material-design-icons repo to specified android gradle module.
It copies all density versions of png files to appropriate res subdirectories.
Usage:
picon.py add <category> <name> [-i <path>] [-o <path>] [-c <color>] [-s <size>]
... | + density)
if not isdir(odir):
mkdir(odir)
copyfile(join(idir, name), join(odir, name))
def rem(name, color, size, outp):
if color == "all":
rem(name, "black", size, outp)
rem(name, "white", size, outp)
return
if size == "all":
rem(name, co | lor, "18", outp)
rem(name, color, "24", outp)
rem(name, color, "36", outp)
rem(name, color, "48", outp)
return
name = name + "_" + color + "_" + size + "dp.png"
for density in densities:
ofile = join(outp, "src", "main", "res", "drawable-" + density, name)
try:... |
awickert/river-network-evolution | backup/run_ThreeChannels_generalizing.py | Python | gpl-3.0 | 3,834 | 0.021127 | import numpy as np
from scipy.sparse import spdiags, block_diag
from scipy.sparse.linalg import spsolve, isolve
from matplotlib import pyplot as plt
import copy
import time
import ThreeChannels_generalizing
reload(ThreeChannels_generalizing)
r = ThreeChannels_generalizing.rnet()
self = r
plt.ion()
# PER RIVER #
#... | dx[-1] #Very specific to this 5-ri | ver set here
self.x[-2] += self.x[1][-1] + self.dx[-1] #Very specific to this 5-river set here
self.x[-1] += self.x[2][-1] + self.dx[-1] #Very specific to this 5-river set here
#self.x[-1] += self.x[-2][-1] + self.dx[-1] #Very specific to this 2-river set here
for row in self.x:
self.eta.append( -S * row + np.max(sel... |
redhat-performance/tuned | tuned/profiles/functions/function_cpulist_present.py | Python | gpl-2.0 | 691 | 0.023155 | import os
import tuned.logs
from . import base
from tuned.utils.commands import commands
log = tuned.logs.get()
class cpulist_present(base.Function):
"""
Checks whether CPUs from list are present, returns list containing
only present CPUs
"""
def __init__(self):
# arbitrary number of arguments
super(cpulist_... | self).execute(args):
return None
cpus = self | ._cmd.cpulist_unpack(",,".join(args))
present = self._cmd.cpulist_unpack(self._cmd.read_file("/sys/devices/system/cpu/present"))
return ",".join(str(v) for v in sorted(list(set(cpus).intersection(set(present)))))
|
inventree/InvenTree | InvenTree/plugin/plugin.py | Python | mit | 2,145 | 0.000932 | # -*- coding: utf-8 -*-
"""
Base Class for InvenTree plugins
"""
import warnings
from django.db.utils import OperationalError, ProgrammingError
from django.utils.text import slugify
class InvenTreePluginBase():
"""
Base class for a plugin
DO NOT USE THIS DIRECTLY, USE plugin.IntegrationPluginBase
"""... | = self.plugin_config()
if cfg:
return cfg.active
else:
return False
# TODO @matmair remove after InvenTree 0.7 | .0 release
class InvenTreePlugin(InvenTreePluginBase):
"""
This is here for leagcy reasons and will be removed in the next major release
"""
def __init__(self):
warnings.warn("Using the InvenTreePlugin is depreceated", DeprecationWarning)
super().__init__()
|
jackfirth/pyramda | pyramda/math/product.py | Python | mit | 147 | 0 | from pyra | mda.function.curry import curry
from pyramda.iterable.reduce import reduce
fr | om .multiply import multiply
product = reduce(multiply, 1)
|
3299/visioninabox | server.py | Python | mit | 2,744 | 0.027697 | #!/usr/bin/env python
import json, time
from flask import Flask, request, render_template, Response
from gevent import pywsgi, monkey
from helpers.generateCalibration import GenerateCalibration
#monkey.patch_all()
app = Flask(__name__)
#cameraInstance = Camera()
runCalibration = GenerateCalibration('frames', 'calib... | equest.form['max']})
elif (request.form['action'] == 'getHSL'):
return json.dumps(cameraInstance.getHSL())
elif (r | equest.form['action'] == 'saveHSL'):
return str(cameraInstance.saveHSL())
elif (request.form['action'] == 'setExposure'):
return str(cameraInstance.setExposure(int(request.form['exposure'])))
elif (request.form['action'] == 'on' or request.form['action'] == 'off'):
... |
qedi-r/home-assistant | homeassistant/components/simplisafe/alarm_control_panel.py | Python | apache-2.0 | 5,527 | 0.000543 | """Support for SimpliSafe alarm control panels."""
import logging
import re
from simplipy.entity import EntityTypes
from simplipy.system import SystemStates
from homeassistant.components.alarm_control_panel import (
FORMAT_NUMBER,
FORMAT_TEXT,
AlarmControlPanel,
)
from homeassistant.components.alarm_contr... | data[self._system.system_id]
if event_data.get("pinName"):
self._changed_by = event_data["pinName"]
if self._system.state == SystemStates.error:
self._online = False
return
self._online = True
if self._system.state == SystemStates.off:
... | RMED
elif self._system.state in (SystemStates.home, SystemStates.home_count):
self._state = STATE_ALARM_ARMED_HOME
elif self._system.state in (
SystemStates.away,
SystemStates.away_count,
SystemStates.exit_delay,
):
self._state = STATE_... |
TheCamusean/DLRCev3 | scripts/benchmarks/demo3.py | Python | mit | 27,312 | 0.028412 | #Euclidean path planning control with Kalman filter for localization
import time
import cv2
from ev3control.rpc import Robot
from rick.controllers import *
from rick.A_star_planning import *
from rick.core import State
from rick.core import main_loop
from rick.async import AsyncCamera
from rick.utils import TrackerWra... | lego_boxes"
for bbox in BB_legos:
image_complete_name="{}_{}{}".format(image_name,iteration,".png")
iteration+=1
input_frame=frame[bbox[1]:bbox[3],b | box[0]:bbox[2],:]
cv2.imwrite(image_complete_name,input_frame)
#frame = plot_bbox(frame, bbox)
lego_landmarks = mapping.cam2rob(BB_legos,H)
mtx,dist=load_camera_params()
frame,marker_list=get_marker_pose(frame,mtx,dist,marker_list=[0,1,2,3],markerLength=8.6)
print("################... |
DmitryFillo/rknfilter | rknfilter/targets/store.py | Python | bsd-2-clause | 1,324 | 0.002266 | from rknfilter.targets import BaseTarget
from rknfilter.db import Resource, Decision, CommitEvery
from rknfilter.core import DumpFilesParser
class StoreTarget(BaseTarget):
def __init__(self, *args, **kwargs):
super(StoreTarget, self).__init__(*args, **kwargs)
self._dump_files_parser = DumpFilesPars... | _org'],
num=decision['decision_num']
)
resource.sync_m2m_proxy('domains_list | ', domains)
resource.sync_m2m_proxy('urls_list', urls)
resource.sync_m2m_proxy('ips_list', ips)
commit()
commit(force=True)
|
praekelt/mc2 | mc2/forms.py | Python | bsd-2-clause | 1,161 | 0 | from django import forms
from django.contrib.auth.models import User as user_model
from django.contrib.auth.forms import UserCreationForm
from mc2.models import UserSettings
class UserSettingsForm(forms.ModelForm):
settings_level = forms.ChoiceField(
choices=UserSettings.SETTINGS_LEVEL_CHOICES,
... | first_name = forms.CharField(required=False)
last_name = forms.CharField(required=False)
email = forms.EmailField(required=True)
def clean_email(self):
'''
Validate that the supplied email address is unique for the
s | ite.
'''
if user_model.objects.filter(
email__iexact=self.cleaned_data['email']).exists():
raise forms.ValidationError('This email address is already in use.'
' Please supply a different'
' email addre... |
wangmiao1981/spark | python/pyspark/sql/pandas/map_ops.py | Python | apache-2.0 | 3,806 | 0.002365 | #
# 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 us... | a, functionType=PythonEvalType.SQL_MAP_PANDAS_ITER_UDF)
udf_column = udf(*[self[col] for col in self.columns])
| jdf = self._jdf.mapInPandas(udf_column._jc.expr())
return DataFrame(jdf, self.sql_ctx)
def _test():
import doctest
from pyspark.sql import SparkSession
import pyspark.sql.pandas.map_ops
globs = pyspark.sql.pandas.map_ops.__dict__.copy()
spark = SparkSession.builder\
.master("lo... |
makinacorpus/mapnik2 | scons/scons-local-1.2.0/SCons/Tool/g++.py | Python | lgpl-2.1 | 3,111 | 0.0045 | """SCons.Tool.g++
Tool-specific initialization for g++.
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, 2002, 2003, 2004, 2005, 2006, 2007, 2008 The SCons Foundation
#
# Permission is... | nerate(env)
env['CXX'] = env.Detect(compilers)
# platform specific settings
if env['PLATFORM'] == 'aix':
env['SHCXXFLAGS'] = SCons.Util | .CLVar('$CXXFLAGS -mminimal-toc')
env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 1
env['SHOBJSUFFIX'] = '$OBJSUFFIX'
elif env['PLATFORM'] == 'hpux':
env['SHOBJSUFFIX'] = '.pic.o'
elif env['PLATFORM'] == 'sunos':
env['SHOBJSUFFIX'] = '.pic.o'
# determine compiler version
... |
geowurster/gj2ascii | tests/test_cli.py | Python | bsd-3-clause | 13,853 | 0.000361 | """
Unittests for gj2ascii CLI
"""
from __future__ import division
import os
import tempfile
import unittest
import click
import emoji
import fiona as fio
import pytest
import gj2ascii
from gj2ascii import cli
def test_complex(runner, expected_line_40_wide, line_file, compare_ascii):
result = runner.invoke(c... | tilayer_file + ',polygons,lines',
'--char', '+',
'--char', '8',
'--char', '0' # 2 layers but 3 values
])
assert result.exit_code != 0
assert result.output.startswith(' | Error:')
assert '--char' in result.output
assert 'number' in result.output
assert 'equal' in result.output
def test_iterate_too_many_layers(runner, multilayer_file):
result = runner.invoke(cli.main, [
multilayer_file,
'--iterate', '--no-prompt'
])
assert result.exit_code != 0
... |
daj0ker/BinPy | BinPy/tests/tree_tests.py | Python | bsd-3-clause | 2,286 | 0.000875 | from __future__ import print_function
from BinPy.connectors.connector import *
from BinPy.gates.tree import *
from BinPy.connectors.connector import *
from BinPy.gates.gates import *
from BinPy.combinational.combinational import *
from nose.tools import with_setup, nottest
'''
Testing backtrack() function for depths ... | assert False
def backtrack_depth_test():
for i in range(6):
tree_inst | , tree_testing = get_tree_for_depth_checking(i)
compare_trees(tree_inst, tree_testing, i)
'''
Test to see if the set_depth method works
'''
def set_depth_test():
tree_inst, tree_testing = get_tree_for_depth_checking(0)
for i in range(1, 6):
tree_inst.set_depth(i)
tree_inst.backtrack(... |
rht/zulip | zerver/webhooks/helloworld/tests.py | Python | apache-2.0 | 3,346 | 0.002092 | from django.conf import settings
from zerver.lib.test_classes import WebhookTestCase
from zerver.models import get_realm, get_system_bot
class HelloWorldHookTests(WebhookTestCase):
STREAM_NAME = "test"
URL_TEMPLATE | = "/api/v1/external/helloworld?&api_key={api_key}&stream={stream}"
PM_URL_TEMPLATE = "/api/v1/external/helloworld?&api_key={api_key}"
WEBHOOK_DIR_NAME = "helloworld"
# Note: Include a test function per | each distinct message condition your integration supports
def test_hello_message(self) -> None:
expected_topic = "Hello World"
expected_message = "Hello! I am happy to be here! :smile:\nThe Wikipedia featured article for today is **[Marilyn Monroe](https://en.wikipedia.org/wiki/Marilyn_Monroe)**"
... |
krismcfarlin/todo_angular_endpoints_sockets | bp_content/themes/default/handlers/handlers.py | Python | lgpl-3.0 | 10,823 | 0.00462 | # -*- coding: utf-8 -*-
"""
A real simple app for using webapp2 with auth and session.
It just covers the basics. Creating a user, login, logout
and a decorator for protecting certain handlers.
Routes are setup in routes.py and added in main.py
"""
# standard library imports
import logging
# related ... | skqueue
from webapp2_extras.auth import InvalidAuthIdError, InvalidPasswordError
f | rom webapp2_extras.i18n import gettext as _
from bp_includes.external import httpagentparser
# local application/library specific imports
import bp_includes.lib.i18n as i18n
from bp_includes.lib.basehandler import BaseHandler
from bp_includes.lib.decorators import user_required
from bp_includes.lib import captcha, util... |
reamdc1/gene_block_evolution_old | loci_filtering.py | Python | gpl-3.0 | 8,117 | 0.014291 | #!/usr/bin/python
from multiprocessing import Pool
import time
import os
import sys
import argparse
from homolog4 import *
from collections import defaultdict
# Copyright(C) 2014 David Ream
# Released under Biopython license. http://www.biopython.org/DIST/LICENSE
# Do not remove this comment
# This exists to make t... | if source_annotation != hit_annotation:
if source_annotation not in result.keys():
result.update({source_annotation: [hit_annotation]})
else:
result[source_annotation].append(hit_annotation)
print "got here 2"
return result
# The purpose of... | on of the gene at
# that position. To do this the program will make a dict of each [locus/start] ? and then determine the annotations that
# exist for it. If there are two annotations that have homologous genes then the best hit will be used. if there are two
# annotations for a locus which are not homologous then s... |
arpitar/osf.io | website/files/utils.py | Python | apache-2.0 | 3,388 | 0.000885 | from modularodm.exceptions import ValidationValueError
def copy_files(src, target_node, parent=None, name=None):
"""Copy the files from src to the target node
:param Folder src: The source to copy children from
:param Node target_node: The node settings of the project to copy files to
:param Folder pa... | t__(self, mqs):
self.mqs = mqs
def __iter__(self):
"""Return | s a generator that wraps all StoredFileNodes
returned from self.mqs
"""
return (x.wrapped() for x in self.mqs)
def __repr__(self):
return '<website.files.utils.GenWrapper({!r})>'.format(self.mqs)
def __getitem__(self, x):
"""__getitem__ does not default to __getattr__
... |
alanjw/GreenOpenERP-Win-X86 | python/Lib/site-packages/_xmlplus/dom/html/HTMLSelectElement.py | Python | agpl-3.0 | 4,750 | 0.008421 | ########################################################################
#
# File Name: HTMLSelectElement.py
#
#
"""
WWW: http://4suite.com/4DOM e-mail: support@4suite.com
Copyright (c) 2000 Fourthought Inc, USA. All Rights Reserved.
See http://4suite.com/COPYRIGHT for license and copyright info... |
for ctr in range(len(options)):
node = options.item(ctr)
if node._get_selected() == 1:
return ctr
return -1
def _set_selectedIndex(self,index):
options = self._get_options()
if index < 0 or index >= | len(options):
raise IndexSizeErr()
for ctr in range(len(options)):
node = options.item(ctr)
if ctr == index:
node._set_selected(1)
else:
node._set_selected(0)
def _get_value(self):
options = self._get_options()
... |
aquametalabs/django-telegram | telegram/handlers/dummy.py | Python | bsd-3-clause | 387 | 0 | fr | om telegram.handlers.base import BasePlatformHandler
class DummyHandler(BasePlatformHandler):
def handle(self):
print 'Channel: %s' % self.telegram.channel.name
print 'Subject: %s' % self.telegram.subject
print 'Message: %s' % self.telegram.content
print 'Level: %s' % self.subscri... | _level_display()
print 'Extra: %s' % self.extra
|
SKA-ScienceDataProcessor/algorithm-reference-library | processing_components/simulation/testing_support.py | Python | apache-2.0 | 47,842 | 0.007504 | """
Functions that aid testing in various ways. A typical use would be::
lowcore = create_named_configuration('LOWBD2-CORE')
times = numpy.linspace(-3, +3, 13) * (numpy.pi / 12.0)
frequency = numpy.array([1e8])
channel_bandwidth = numpy.array([1e7])
# Define th... | rray) in Hz
:param phasecentre: Phase centre of image (SkyCoord)
:param polarisation_frame: Polarisation frame
:return: Image
"""
if frequency is None:
frequency = [1e8]
im = import_image_from_fits(arl_path("data/models/M31.MOD"))
if canonical:
if polarisation_frame ... | )
elif isinstance(polarisation_frame, PolarisationFrame):
im.polarisation_frame = polarisation_frame
else:
raise ValueError("polarisation_frame is not valid")
im = replicate_image(im, frequency=frequency, polarisation_frame=im.polarisation_frame)
if cells... |
fmfi-svt/votr | aisikl/components/button.py | Python | apache-2.0 | 1,203 | 0.002494 |
from aisikl.events import action_event
from .actionablecontrol import ActionableControl
class Button(ActionableControl):
def __init__(self, dialog, id, type, parent_id, properties, element):
super().__init__(dialog, id, type, parent_id, properties, element)
self.image = properties.get('img')
... | lf.access_key = ' '.join(self. | access_key) # BeautifulSoup :(
def _ais_setAccessKey(self, value):
self.access_key = value
def _ais_setImage(self, value):
self.image = value
def _ais_setConfirmQuestion(self, value):
self.confirm_question = value
def click(self):
self.log('action', 'Clicking {}'.forma... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.