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 |
|---|---|---|---|---|---|---|---|---|
OCA/carrier-delivery | delivery_auto_refresh/tests/__init__.py | Python | agpl-3.0 | 131 | 0 | # | -*- coding: utf-8 -*-
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from . import test_delivery_auto_refresh
| |
AHAAAAAAA/HackCU2016 | sentiment.py | Python | mit | 2,307 | 0.010837 | """
Sentiment prediction module
"""
import nltk
import numpy as np
from cPickle import load
def get_word_index_array(words, word2index):
u"""
Transform the words into list of int(word index)
Note: Unknown words are dropped
>>> words = [u"I", u"love", u"you", u"RANDOM STUFF"]
>>> word2ind... | ne # filter out those unknown
]
def pad_sents(sents, padding_token_index):
"""
Pad the sents(in word index form) into same length so they can form a matrix
# 15447
>>> sents = [[1,2,3], [1,2], [1,2,3,4,5]]
>>> pad | _sents(sents, padding_token_index = -1)
[[1, 2, 3, -1, -1], [1, 2, -1, -1, -1], [1, 2, 3, 4, 5]]
"""
max_len_sent = max(sents,
key = lambda sent: len(sent))
max_len = len(max_len_sent)
get_padding = lambda sent: [padding_token_index] * (max_len - len(sent))
padded_se... |
lutcheti/webtext | src/request/backends/BackendWiki.py | Python | gpl-3.0 | 9,114 | 0.004182 | # -- coding: utf-8 --
###########################################################################
# #
# WebText #
# ... | n(("Amboise" in a or "libertin" in a or "commune" in a) or # Bussy
("Git" in a and "Ruby" in a) or # Github
("Battle" in a or "Sunweb-Napoleon" in a) or # Napoleon
("cathédrale" in a)) | # Sully
class BackendWiki(Backend):
backendName = WIKI # defined in static.py
def answer(self, request, config):
if len(request.argsList) > 0:
return(wikiSummary(request))
else:
return("Vous avez mal tapé votre requête. Rappel: " + self.help())
def tes... |
geometalab/geoconverter | GeoConverter/database.py | Python | mit | 4,858 | 0.00597 | class DatabaseRouter(object):
'''
These functions are called when Django accesses the database.
Returns the name of the database to use depending on the app and model.
Returning None means use default.
'''
def db_for_read(self, model, **hints):
return self.__db_for_read_and_write(model... | eta.db_table == 'ogrgeoconverter_conversion_job_folders' \
or model._meta.db_table == | 'ogrgeoconverter_conversion_job_file_matches' \
or model._meta.db_table == 'ogrgeoconverter_conversion_job_files' \
or model._meta.db_table == 'ogrgeoconverter_conversion_job_file_id_tracking' \
or model._meta.db_table == 'ogrgeoconverter_conversion_job_urls' ... |
browseinfo/odoo_saas3_nicolas | addons/email_template/wizard/mail_compose_message.py | Python | agpl-3.0 | 12,835 | 0.004753 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2010-Today OpenERP SA (<http://www.openerp.com>)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms o... | e, attachments of an email template
also have to be duplicated to avoid changing their ownership. """
if context is None:
context = {}
wizard_context = dict(context)
| for wizard in self.browse(cr, uid, ids, context=context):
if wizard.template_id:
wizard_context['mail_notify_user_signature'] = False # template user_signature is added when generating body_html
wizard_context['mail_auto_delete'] = wizard.template_id.auto_delete # mass... |
it-projects-llc/pos-addons | pos_wechat/__manifest__.py | Python | mit | 1,032 | 0 | # Copyright 2018 Ivan Yelizariev <https://it-projects.info/team/yelizariev>
# License MIT (https://opensource.org/licenses/MIT).
{
"name": """WeChat Payments in POS""",
"summary": """Support WeChat QR-based payments (scan and show)""",
"category": "Point of Sale",
# "live_test_url": "",
"images": ["... | ther OSI approved licence", # MIT
"price": 165.00,
"currency": "EUR",
"depends": [
"wechat",
"pos_qr_scan",
"po | s_qr_show",
"pos_qr_payments",
"pos_longpolling",
],
"external_dependencies": {"python": [], "bin": []},
"data": ["views/assets.xml", "wizard/pos_payment_views.xml"],
"demo": [],
"qweb": ["static/src/xml/pos.xml"],
"auto_install": False,
"installable": False,
}
|
blazek/lrs | lrs/lrs/lrslayer.py | Python | gpl-2.0 | 3,504 | 0.001998 | # -*- coding: utf-8 -*-
"""
/***************************************************************************
LrsPlugin
A QGIS plugin
Linear reference system builder and editor
-------------------
begin : 2017-5-29
copyright ... | # sleep(1) # progress debug
geo = feature.geometry()
# if geo:
# if self.lineTransform:
# geo.transform(self.lineTransform)
routeId = feature[self.routeFieldName]
route | = self.getRoute(routeId)
#line = LrsLine(feature.id(), routeId, geo)
#self.lines[feature.id()] = line
if geo:
for g in geo.asGeometryCollection():
part = LrsLayerPart(g)
route.addPart(part)
count += 1
pe... |
emergence/django-simple-history | simple_history/templatetags/simple_history_compare.py | Python | bsd-3-clause | 1,074 | 0.001862 | from __future__ import unicode_literals
import difflib
from django import template
register = template.Library()
@register.simple_tag
def diff_table(a, b, line_sp | lit="\n"):
differ = difflib.HtmlDiff(wrapcolumn=80)
try:
return differ.make_table(a.split(line_split), b.split(line_split))
except AttributeError:
if a != b:
a = '<span class="diff_sub">{a}</span>'.format(a=a)
b = '<span class="diff_add">{b}</span>'.format(b=b)
... | p> <colgroup></colgroup>
<colgroup></colgroup> <colgroup></colgroup> <colgroup></colgroup>
<tbody>
<tr><td class="diff_next"><a href="#difflib_chg_to0__top">t</a></td><td class="diff_header" id="from0_1">1</td><td nowrap="nowrap">{a}</td><td class="diff_next"><a href="#difflib_chg_to0__top">t</a></td><... |
paulharter/fam | src/fam/database/caching.py | Python | mit | 56 | 0.017857 | from | fam.buffer import buffered_db
cache = buffered_ | db
|
wyliew/AutoPokeDraw | index.py | Python | mit | 3,166 | 0.04801 | """
Auto-drawer for http://pokedraw.net/
All coordinates assume a screen resolution of 1366x768, and Chrome
maximized with the Bookmarks Toolbar enabled.
Down key has been hit 4 times to center play area in browser, and Let's Draw has been clicked.
"""
import math
import win32api, win32con, win32gui
import ImageGrab
i... | x_pad= 804
colors_y_pad = 548
color_coords = [(829,571), (891,571), (955,571), (1017,571), (1079,571), (1145,571),
(829,629), (891,629), (955,629), (1017,629), (1079,629), (1145,629)]
color_rgb = [(244,42,53), (255,162,0), (255,213,0), (168,191,18), (46,181,47), (0,170,181),
(50,90, | 197), (250,208,222), (148,109,155), (135,94,55), (142,150,155), (0,0,0), (255,255,255)]
pixelMap = {}
def leftClick():
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0)
time.sleep(.001)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0)
def leftDown():
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDO... |
schleichdi2/OPENNFR-6.3-CORE | opennfr-openembedded-core/meta/lib/oeqa/selftest/cases/gotoolchain.py | Python | gpl-2.0 | 2,594 | 0.000386 | #
# SPDX-License-Identifier: MIT
#
import glob
import os
import shutil
import tempfile
from oeqa.selftest.case import OESelftestTestCase
from oeqa.utils.commands import runCmd, bitbake, get_bb_vars
class oeGoToolchainSelfTest(OESelftestTestCase):
"""
Test cases for OE's Go toolchain
"""
@staticmetho... | runCmd("cd %s; tar -xf %s" % (self.tmpdir_SDKQA, ver+archive))
runCmd("mkdir -p %s/src/%s" % (self.go_path, proj))
runCmd("mv %s/dep-0.3.1 %s/src/%s/%s"
% (self.tmpdir_SDKQA, self.go_path, proj, name))
retv = self.run_sdk_go_command('build %s/%s/cmd/dep'
... | msg="Running go build failed for %s" % name)
|
MaximNevrov/neutron | neutron/common/utils.py | Python | apache-2.0 | 22,681 | 0.00022 | # Copyright 2011, VMware, 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... | permissions mode."""
try:
os.makedirs(dir_path, 0o755)
except OSError as e:
# If the directory already existed, don't raise the error.
if e.errno != errno.EEXIST:
raise
def _subprocess_setup():
# Python installs a SIGPI | PE handler by default. This is usually not what
# non-Python subprocesses expect.
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
def subprocess_popen(args, stdin=None, stdout=None, stderr=None, shell=False,
env=None, preexec_fn=_subprocess_setup, close_fds=True):
return subprocess.Pop... |
civilian/competitive_programing | leetcode/4/443/best.py | Python | mit | 990 | 0.007071 | class Solution:
def compress(self, chars) -> int:
n = len(chars)
if n == 1:
return 1
l = r = 0
while r < n: |
current = chars[r]
count = 0
while r < n and chars[r] == current:
r += 1
count += 1
chars[l] = current
if count > 1:
for i in str(count):
chars[l + 1] = i
l += 1
... | (["a", "a", "b", "b", "c", "c", "c"]))
# print(obj.compress(["a", "a", "b", "b", "c", "c", "c"]))
# print(obj.compress(["a"]))
# print(obj.compress(["a", "b", "b", "b", "b", "b", "b", "b", "b", "b", "b", "b", "b"]))
# print(obj.compress(["a", "a", "a", "b", "b", "a", "a"]))
# print(obj.compress([chr(ord('a') + elem) fo... |
Hitatm/Concentrator | app/utils/num_of_rounds.py | Python | gpl-3.0 | 10,818 | 0.011941 | #coding:UTF-8
import time,datetime
import os
from gxn_get_sys_config import Config
import sqlite3
from db_operate import DBClass
# 根据调度计算所选时间段内轮数
def countrounds(start_time, end_time):
g = Config()
num_in_schedule = len(g.get_active_time()) # 24h中轮数
get_schedule = g.get_active_time()
# print get_schedu... | lit(':')[1])*60 + int(item[1].split(':')[2])
if (start_time_second > bitmap_second):
schedule_list.append(start_date1+' '+item[1])
start_date1 = date_addone(start_year,start_month,start_day)
for item in get_schedule:
bitmap_second =... | *60*60 + int(item[1].split(':')[1])*60 + int(item[1].split(':')[2])
if (start_time_second < bitmap_second and bitmap_second < end_time_second):
schedule_list.append(end_date+' '+item[1])
schedule_list = sorted(schedule_list)
# print "case1"
|
knutz3n/sportlocations | sportlocations/api/handlers.py | Python | apache-2.0 | 2,134 | 0.003749 | from piston.handler import BaseHandler
from piston.utils import FormValidationError, rc
from sportlocations.api.forms import SearchForm, PositionUpdateForm
from sportlocations.api import mongo_manager
# IMPORTANT!
# To have Post requests working with JQuery:
# In Piston's utils.py edit from
# if ctype == type_formenc... | if form.is_valid():
lat = form.cleaned_data['lat']
lng = form.cleaned_data['lng']
comment = form.cleaned_data['comment']
mongo_manager.update_facility_position(_id, lat, lng, comment)
return rc.ALL_OK
else:
raise FormValidationError(form... | owed_methods = ('GET',)
def read(self, request, *a, **kw):
form = SearchForm(request.GET)
if form.is_valid():
lat = form.cleaned_data['lat']
lng = form.cleaned_data['lng']
limit = form.cleaned_data['limit']
if limit is None:
limit = 2... |
pshchelo/heat | heat/rpc/client.py | Python | apache-2.0 | 28,301 | 0 | #
# Copyright 2012, 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... | (self, ctxt, filters=None, tenant_safe=True,
show_deleted=False, show_nested=False, show_hidden=False,
tags=None, tags_ | any=None, not_tags=None,
not_tags_any=None):
"""
Return the number of stacks that match the given filters
:param ctxt: RPC context.
:param filters: a dict of ATTR:VALUE to match against stacks
:param tenant_safe: if true, scope the request by the current tena... |
code64/stepcounter | examples/json/logger-gpio.py | Python | gpl-3.0 | 781 | 0 | #!/usr/bin/env python
import time |
import json
import RPi.GPIO as GPIO
import sys
# Defaults
visitors = int(sys.argv[1]) if len(sys.argv) > 1 else 0
# Hardware interface
pin = 18
GPIO.setmode( | GPIO.BCM)
GPIO.setup(pin, GPIO.IN)
# Log visitor to console
def log(count):
print 'Logged visitor #%d' % count
# Update JSON file
def store(count):
# Prepare dictionary
data = {
'data': str(count)
}
# Open and write to file
with open('./logs/data.json', 'w') as outfile:
json.... |
batxes/4Cin | SHH_WT_models_highres/SHH_WT_models_highres_final_output_0.1_-0.1_5000/mtx1_models/SHH_WT_models_highres12150.py | Python | gpl-3.0 | 88,213 | 0.02452 | import _surface
import chimera
try:
import chimera.runCommand
except:
pass
from VolumePath import markerset as ms
try:
from VolumePath import Marker_Set, Link
new_marker_set=Marker_Set
except:
from VolumePath import volume_path_dialog
d= volume_path_dialog(True)
new_marker_set= d.new_marker_set
marker_set... | 7, 0.7, 0.7), 138.617)
if "particle_30 geometry" not in marker_sets:
s=new_marker_set('particle_30 geometry')
marker_sets["particle_30 geometry"]=s
s= marker_sets["particle_30 geometry"]
mark=s.place_marker((1774.11, 800.71, 2362.81), (0.7, 0.7, 0.7), 130.03)
if "particle_31 geometry" not in marker_sets:
s=new_ma... | 6.552)
if "particle_32 geometry" not in marker_sets:
s=new_marker_set('particle_32 geometry')
marker_sets["par |
Pathel/deuterium | game/gamesrc/objects/character.py | Python | bsd-3-clause | 1,817 | 0 | """
Template for Characters
Copy this module up one level and name it as you like, then
use it as a template to create your own Character class.
To make new logins default to creating characters
of your new type, change settings.BASE_CHARACTER_TYPECLASS to point to
your new class, e.g.
settings.BASE_CHARACTER_TYPEC... | example/object.py for
a list of properties and methods), except it actually implements
some of its hook methods to do some work:
| at_basetype_setup - always assigns the default_cmdset to this object type
(important!)sets locks so character cannot be picked up
and its commands only be called by itself, not anyone else.
(to change things, use at_object_creation() instead)
at_after_mo... |
anthropo-lab/XP | EPHEMER/dill_resp_project/settings.py | Python | gpl-3.0 | 2,310 | 0.000867 | from os import environ
# if you set a property in SESSION_CONFIG_DEFAULTS, it will be inherited by all configs
# in SESSION_CONFIGS, except those that explicitly override it.
# the session config can be accessed from methods in your apps as self.session.config,
# e.g. self.session.config['participation_fee']
SESSION_... | set admin password in an environment variable
ADMIN_PASSWORD = environ.get('OTREE_ADMIN_PASSWORD')
# Consider '', None, and '0' to be empty/false
DEBUG = (environ.get('OTREE_PRODUCTION') in {None, '', '0'})
DEMO_PAGE_INTRO_HTML = """ """
# don't share this with anybody.
SECRET_KEY = '29*rluv^s95qdbcfe6&mql^2$-_^e7n... | 8g27p(q'
# if an app is included in SESSION_CONFIGS, you don't need to list it here
INSTALLED_APPS = ['otree']
|
simonwydooghe/ansible | lib/ansible/modules/network/aci/mso_schema_template_external_epg_contract.py | Python | gpl-3.0 | 7,387 | 0.002031 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
... | 1
type: consumer
state: present
delegate_to: localhost
- name: Remove a Contract
mso_schema_template_external_epg_contract:
host: mso_host
username: admin
password: SomeSecretPassword
schema: Schema 1
template: Template 1
epg: EPG 1
contract:
name: Contract 1
state:... | retPassword
schema: Schema 1
template: Template 1
epg: EPG 1
contract:
name: Contract 1
state: query
delegate_to: localhost
register: query_result
- name: Query all Contracts
mso_schema_template_external_epg_contract:
host: mso_host
username: admin
password: SomeSecretPasswo... |
wallnerryan/quantum_migrate | quantum/plugins/common/constants.py | Python | apache-2.0 | 1,169 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 OpenStack Foundation.
# 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 obt | ain
# 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.
# service type constants:
CORE = "CORE"
DUMMY = "DUMMY"
LOADBALANCER = "LOADBALANCER"
# TODO(salvatore-orlando): Move these (or derive them) from conf file
ALLOWED_SERVICES = [CORE,... |
ebrahimraeyat/civilTools | py_widget/torsion.py | Python | gpl-3.0 | 2,302 | 0.003475 | from pathlib import Path
from PySide2 import QtWidgets
import FreeCADGui as Gui
from PySide2.QtCore import Qt
civiltools_path = Path(__file__).absolute().parent.parent
class Form(QtWidgets.QWidget):
def __init__(self, | etabs_obj):
super(Form, self).__init__()
self.form = Gui.PySideUic.loadUi(str(civiltools_path / 'widgets' / 'torsion.ui'))
# self.setupUi(self)
# self.form = self
self.etabs = etabs_obj
self.fill_xy_loadcase_names()
def fill_xy_loadcase_names(self):
x_names, ... | atterns = self.etabs.load_patterns.get_drift_load_pattern_names()
all_load_case = self.etabs.SapModel.Analyze.GetCaseStatus()[1]
x_names = set(x_names).intersection(set(all_load_case))
y_names = set(y_names).intersection(set(all_load_case))
self.form.x_loadcase_list.addItems(x_names)
... |
nthall/pip | pip/__init__.py | Python | mit | 10,278 | 0 | #!/usr/bin/env python
from __future__ import absolute_import
import logging
import os
import optparse
import warnings
import sys
import re
from pip.exceptions import InstallationError, CommandError, PipError
from pip.utils import get_installed_distributions, get_prog
from pip.utils import deprecation, dist_is_editab... | ame(os.path.dirname(os.path.abspath(__file__)))
parser.version = 'pip %s from %s (python %s)' % (
__version__, pip_pkg_dir, sys.version[:3])
# add the general options
gen_opts = cmdoptions.make_option_group(cmdoptions.general_group, pa | rser)
parser.add_option_group(gen_opts)
parser.main = True # so the help formatter knows
# create command listing for description
command_summaries = get_summaries()
description = [''] + ['%-27s %s' % (i, j) for i, j in command_summaries]
parser.description = '\n'.join(description)
retur... |
thomasbarillot/DAQ | HHGMonitor/ADQAPI_python/SDR14_Playlist_example.py | Python | mit | 8,460 | 0.012648 | #
# (C)opyright 2015 Signal Processing Devices Sweden AB
#
# This script showcases in Python
# - How to connect to ADQ devices in Python
# - Upload of waveforms to the SDR14
# - Using a playlist on the SDR14
# - How to setup an acquisition of data
# - How to read data by GetData API in Python
# - How to plot data in Py... | 1 2 3 4 5 6 | 7 8 9
tc["index"] = (ct.c_uint32 * ns)( 1, 2)
tc["segment"] = (ct.c_uint32 * ns)( 1, 2)
tc["next"] = (ct.c_uint32 * ns)( 2, 1)
tc["wrap"] = (ct.c_uint32 * ns)( 4, 3)
tc["ulsign"] = (ct.c_uint32 * ns)( 0, ... |
stormeyes/moli | tests/testClient.py | Python | apache-2.0 | 210 | 0.004762 | from moli.client import Client
c = Client('http://127.0.0.1:8013/')
@c.on('ss')
def user_event(conne | ction | ):
pass
#print('ss event is trigger', connection)
c.emit('mybaby', 'aaaa')
c.run_forever()
|
patrickwestphal/owlapy | owlapy/model/owlobjecthasself.py | Python | gpl-3.0 | 863 | 0 | from .owlclassexpressionvisitor import OWLClassExpressionVisitor, \
OWLClassExpressionVisitorEx
from .owlobjectvisitor import OWLObjectVisitor, OWLObjectVisitorEx
from .owlrestriction import OWLRestriction
from owlapy.util import accept_default, accept_default_ex
class OWLObjectHasSelf(OWLRestriction):
"""TOD... | "
super().__init__(property)
self._accept_fn_for_visitor_cls[OWLClassExpressionVisitor] = \
| accept_default
self._accept_fn_for_visitor_cls[OWLClassExpressionVisitorEx] = \
accept_default_ex
self._accept_fn_for_visitor_cls[OWLObjectVisitor] = accept_default
self._accept_fn_for_visitor_cls[OWLObjectVisitorEx] = accept_default_ex
|
lscalendars/ccoal | src/vsop87/compute-vsop.py | Python | cc0-1.0 | 5,375 | 0.015814 | #!/usr/bin/python
# coding=utf-8
#
# Python vsop optimized file generator.
#
# Copyright (c) 2013 Elie Roux <elie.roux@telecom-bretagne.eu>
#
# 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 w... | e("""
coord_t %s (time_t t) {
return ((((%s_5(t) *t + %s_4(t)) * t + %s_3(t)) *t + %s_2(t)) * t + %s_1(t)) *t + %s_0(t);
}
""" % (common_str, common_str, common_str, common_str, common_str, common_str, common_str))
elif factor == 4:
fout.write("""
coord_t %s (time_t t) {
return (((%s_4(t) * t + %s_3(t)) *t + ... | _str, common_str, common_str, common_str, common_str, common_str))
elif factor == 3:
fout.write("""
coord_t %s (time_t t) {
return ((%s_3(t) *t + %s_2(t)) * t + %s_1(t)) *t + %s_0(t);
}
""" % (common_str, common_str, common_str, common_str, common_str))
else:
print "error!!! Factor %d not taken into accou... |
haifengkao/ReactiveCache | .ycm_extra_conf.py | Python | mit | 13,022 | 0.024113 | #!/usr/local/bin/python
import os
# import ycm_core
# return the filename in the path without extension
def findFileName(path, ext):
name = ''
for projFile in os.listdir(path):
# cocoapods will generate _Pods.xcodeproj as well
if projFile.endswith(ext) and not projFile.startswith('_Pods'):
name= proj... | g in flags:
# include the directory of flag as well
new_flag = [flag.replace('-ISUB', '-I')]
if make_next_include_subdir:
make_next_include_subdir = False
for sub | dir in Subdirectories(os.path.join(working_directory, flag)):
new_flag.append('-I')
new_flag.append(subdir)
for path_flag in path_flags:
if flag == path_flag:
make_next_include_subdir = True
break
|
achanda/flocker | admin/acceptance.py | Python | apache-2.0 | 32,426 | 0.000185 | # Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
Run the acceptance tests.
"""
import sys
import os
import yaml
import json
from pipes import quote as shell_quote
from tempfile import mkdtemp
from zope.interface import Interface, implementer
from characteristic import attributes
from eliot import add_... | PROVIDERS
import flocker
from flocker.provision._ssh import (
run_remotely)
from flocker.provision._install impo | rt (
ManagedNode,
task_pull_docker_images,
uninstall_flocker,
install_flocker,
configure_cluster,
configure_zfs,
)
from flocker.provision._ca import Certificates
from flocker.provision._ssh._conch import make_dispatcher
from flocker.provision._common import Cluster
from flocker.acceptance.testto... |
syl20bnr/nupic | nupic/test/temporal_memory_test_machine.py | Python | gpl-3.0 | 7,649 | 0.006929 | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2014, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This progra... | ctiveCellsList,
predictedInactiveCellsList,
predictedActiveColumnsList,
predictedInactiveCo | lumnsList,
unpredictedActiveColumnsList
) = detailedResults
for i in xrange(len(sequence)):
pattern = sequence[i]
if pattern == None:
row = ["<reset>", 0, 0, 0, 0, 0]
if verbosity > 2:
row += [0, 0]
else:
row = []
row.append(patternMachine.pre... |
pisskidney/leetcode | medium/378.py | Python | mit | 745 | 0.010738 | #!/usr/bin/python
from heapq import heapify, heapreplace
class Solution(object):
def kthSmallest(self, matrix, k):
"""
:type matrix: List[List[int]]
:type k: int
:rtyp | e: int
"""
| if len(matrix) is 1:
return matrix[0][0]
z = zip(*matrix[1:])
h = [(matrix[0][i], z[i]) for i in xrange(len(matrix))]
heapify(h)
i = 0
while i < k - 1:
val, nextval = h[0]
if nextval:
heapreplace(h, (nextval[0], nextval[1... |
martinghunt/Fastaq | pyfastaq/runners/count_sequences.py | Python | gpl-3.0 | 379 | 0.013193 | import argparse
from pyfastaq import tas | ks
def run(description):
parser = argparse.ArgumentParser(
description = 'Prints the number of sequences in input file to stdout',
usage = 'fastaq count_sequences <infile>')
parser.add_argument('infile', help='Name of input file')
options = parser.parse_args()
| print(tasks.count_sequences(options.infile))
|
dmlb2000/pacifica-archiveinterface | setup.py | Python | lgpl-3.0 | 1,765 | 0.001133 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""Setup and install the archive interface with hpss."""
import sys
from os.path import isfile
from os import path
from setuptools.extension import Extension
from setuptools import setup, find_packages
HPSS = Extension(
'pacifica.archiveinterface.backends.hpss._hpssExtensi... | 'README.md')).read(),
long_description_content_type='text/markdown',
author='David Brown',
author_email='david.brown@pnnl.gov',
packages=find_packages(include='pacifica.*'),
namespace_packages=['pacifica'],
entry_points={
'console_scripts': [
'pacifica-archiveinterface=pacifi... |
},
install_requires=[
'cherrypy',
'peewee>2',
'PyMySQL',
],
ext_modules=EXT_MODULES
)
|
390910131/Misago | misago/core/shortcuts.py | Python | gpl-2.0 | 736 | 0 | from django.shortcuts import * # noqa
def paginate(object_list, page, per_page, orphans=0,
allow_empty_first_page=True):
from django.http import Http404
from django.core.paginator import Paginator, EmptyPage
from misago.core.exceptions import ExplicitFirstPage
if page in (1, "1"):
... | object_list, per_page, orphans=orphans,
allow_empty_first_page=allow_empty_first_page).page(page)
except EmptyPage:
raise Http404()
def validate_slug(model, slug):
from misago.core.exceptions import OutdatedSlug
if model.slug != slug:
raise Outdate | dSlug(model)
|
pFernbach/hpp-rbprm-corba | script/scenarios/sandbox/dynamic/plateform_hrp2_interp_testTransition.py | Python | lgpl-3.0 | 7,681 | 0.021612 | from hpp.corbaserver.rbprm.rbprmbuilder import Builder
from hpp.corbaserver.rbprm.rbprmfullbody import FullBody
from hpp.gepetto import Viewer
import time
from constraint_to_dae import *
from hpp.corbaserver.rbprm.rbprmstate import State,StateHelper
from display_tools import *
import plateform_hrp2_path as tp
import ti... | filterStates = False)
tInterpolateConfigs = time.time() - tStart
print "number of configs :", len(configsFull)
"""
q_init[0] += 0.05
createSphere('s',r)
n = [0,0,1]
p = [0,0.1,0]
q_init[-6:-3] = [0.2,0,0]
q_goal[-6:-3] = [0.1,0,0]
sf = State(fullBody,q=q_goal,limbsIncontact=[lLegId,rLegId])
si = State(fullBody,q=q_... | ct(si,lLegId,p,n,100)
assert(success)
smid2,success = StateHelper.addNewContact(sf,lLegId,p,n,100)
assert(success)
r(smid.q())
sf2 = State(fullBody,q=q_goal,limbsIncontact=[lLegId,rLegId])
"""
fullBody.isDynamicallyReachableFromState(smid.sId,smid2.sId,True)
fullBody.isDynamicallyReachableFromState(smid.sId,smid2.sI... |
chrisxue815/leetcode_python | problems/test_0396.py | Python | unlicense | 723 | 0 | import unittest
import itertools
class Solution:
def maxRotateFunction(self, A):
"""
:type A: List[int]
:rtype: int
"""
if not A:
return 0
n = len(A)
sum_ = sum(A)
f = sum(i * num for i, num in enumerate(A))
max_ = f
for ... | urn max_
class Test(unittest.TestCase):
def test | (self):
self._test([4, 3, 2, 6], 26)
def _test(self, A, expected):
actual = Solution().maxRotateFunction(A)
self.assertEqual(expected, actual)
if __name__ == '__main__':
unittest.main()
|
khattori/kimpira | kimpira/main.py | Python | mit | 745 | 0.002685 | #!/usr/bin/env python
import optparse
import sys
from kimpira.core import Runtime
from kimpira.version import get_version
def parse_args():
usage = "usage: %prog [opti | ons] <jobfile>"
p = optparse.OptionParser(usage)
p.add_option('-V', '--version', action='store_true', dest='show_version', default=False, help='show version number and exit')
p.add_option('-t', '--task', dest='task_name', default=None, help='task name to run')
return p.parse_args()
def main():
opt... | et_version()))
sys.exit(0)
if len(args) > 0:
Runtime().run(args[0], options.task_name, *args[1:])
if __name__ == '__main__':
main()
|
qilicun/python | python3/src/ode1/pop_exp_growth.py | Python | gpl-3.0 | 376 | 0.005319 | #!/usr/bin/env python
import numpy as np
import sys
try:
t1 = int(sys.argv[1])
except:
print "usage:", sys.argv[0], "n (number of years)"
sys.exit(1)
t0 = 1750
u0 = 2
t = np.linspace(t0, t0 | + t1 + .5, t1)
u = np.zeros(t1 + 1)
a = 0.0218
u[0] = | u0
for i in range(len(u) - 1):
u[i+1] = (1 + a)*u[i]
print "Expected population in year %d is" %(t0 + t1), u[-1]
|
pozdnyakov/chromium-crosswalk | tools/telemetry/telemetry/core/chrome/form_based_credentials_backend_unittest_base.py | Python | bsd-3-clause | 4,429 | 0.011741 | # Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by | a BSD-style license that can be
# found in the LICENSE file.
import logging
import os
import unittest
from telemetry.core import browser_finder
from telemetry.unittest import simple_mock
from telemetry.unittest import options_for_unittests
from telemetry.unittest import DisabledTest
_ = simple_mock.DONT_CARE
def _... | path = os.path.join(
os.path.dirname(__file__),
'..', '..', '..', '..', 'perf', 'data', 'credentials.json')
if not os.path.exists(credentials_path):
return None
return credentials_path
class FormBasedCredentialsBackendUnitTestBase(unittest.TestCase):
def setUp(self):
self._credentials_type =... |
Caranarq/01_Dmine | 03_UsoDeSuelo/P0311/P0311.py | Python | gpl-3.0 | 8,216 | 0.005242 | # -*- coding: utf-8 -*-
"""
Started on Wed Sep 13 15:55:22 2017
@author: carlos.arana
Descripcion: Creación de dataset para el parámetro 0311 "Superficie Agricola"
Informacion disponible para 2015
"""
import pandas as pd
import numpy as np
import sys
# Librerias locales utilizadas
module_path = r'D:\PCCS\01_Dmine\... | RIDAD': 'Revision de integridad de la información POR CLAVE DEL SUN. '
'Promedio de | VAR_INTEGRIDAD de los municipios que componen una ciudad. '
'Si no se tiene información para el municipio, VAR_INTEGRIDAD es igual a cero',
'EXISTENCIA': 'Revision de integridad de la información POR MUNICIPIO.',
' ': np.nan,
'DESCRIPCION DE VARIABLES': np.nan
}
d_mineria = {
' ... |
Brocade-OpenSource/OpenStack-DNRM-Neutron | neutron/plugins/cisco/db/nexus_models_v2.py | Python | apache-2.0 | 1,756 | 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-... | lass NexusPortBinding(model_base.BASEV2):
"""Represents a binding of VM's to nexus ports."""
__tablename__ = "nexusport_bindings"
id = Column(Integer, primary_key=True, autoincrement=True)
port_id = Column(String(255))
vlan_id = Column(Integer, nullable=False)
switch_ip = Column(String(255))
... | _id, switch_ip, instance_id):
self.port_id = port_id
self.vlan_id = vlan_id
self.switch_ip = switch_ip
self.instance_id = instance_id
def __repr__(self):
return "<NexusPortBinding (%s,%d, %s, %s)>" % \
(self.port_id, self.vlan_id, self.switch_ip, self.instance_id... |
aelse/MrHappy | botplugins/cmd_ping.py | Python | gpl-3.0 | 158 | 0 | from botplugin import BotPlugin
class CommandPing(BotPlugin):
def command_ping(self, bot, command, args, n | ick):
| bot.speak('Pong!', paste=True)
|
att-comdev/drydock | tests/unit/test_reference_resolver.py | Python | apache-2.0 | 2,055 | 0 | # Copyright 2017 AT&T Intellectual Property. All other 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... | url = 'http://user:pass@foo.com/test.yaml'
auth_header = "Basic %s" % base64.b64encode(
"user:pass".encode('utf-8')).decode('utf-8')
responses.add(responses.GET, url)
ReferenceResolver.resolve_reference(url)
assert len(responses.calls) == 1
assert 'Authorizatio... | assert responses.calls[0].request.headers.get(
'Authorization') == auth_header
|
FakerKimg/sulley | process_monitor.py | Python | gpl-2.0 | 13,992 | 0.006075 | #!c:\\python\\python.exe
import subprocess
import threading
import getopt
import time
import sys
import os
import pydbg
import pydbg.defines
import utils
from sulley import pedrpc
PORT = 26002
ERR = lambda msg: sys.stderr.write("ERR> " + msg + "\n") or sys.exit(1)
USAGE = """USAGE: process_monitor... | r.log("debugger thread-%s exiting" % self.getName())
except:
pass
# TODO: removing the following line appears to cause some concurrency issue | s.
del self.dbg
def watch (self):
"""
Continuously loop, watching for the target process. This routine "blocks" until the target process is found.
Update self.pid when found and return.
"""
while not self.pid:
for (pid, name) in self.dbg.enumer... |
grandmasterchef/WhatManager2 | WhatManager2/management/commands/file_metadata_indexer.py | Python | mit | 1,499 | 0.004003 | from django.core.management.base import BaseCommand
from home.models import ReplicaSet, WhatTorrent, \
TransTorrent, WhatFileMetadataCache
class Command(BaseCommand):
help = u'Cache all .flac and .mp3 metadata in download locations.'
def handle(self, *args, **options):
masters = ReplicaSet.get_w... | e_size])
start += page_size
trans_torrents = {
t.what_torrent_id: t for t in
TransTorrent.objects.filter(instance__in=masters, what_torrent__in=bulk.values())
}
for what_torrent in bulk.itervalues():
trans_ | torrent = trans_torrents.get(what_torrent.id)
if trans_torrent is not None and trans_torrent.torrent_done == 1:
try:
WhatFileMetadataCache.get_metadata_batch(what_torrent, trans_torrent, True)
except Exception as ex:
... |
illing2005/django-airports-apis | airports/serializers.py | Python | mit | 433 | 0.027714 | from rest_framework import serializers |
from rest_framework import pagination
from .models import Airport
class AirportSerializer(serializers.ModelSerializer):
read_only_fields = ('id','name','city','country','country_code','iata','icao')
class Meta:
model = Airport
class PaginationAirportSerializer(pagination.PaginationSeria... | bject_serializer_class = AirportSerializer |
deanishe/alfred-fakeum | src/libs/faker/providers/phone_number/pl_PL/__init__.py | Python | mit | 937 | 0 | from __future__ import unicode_literals
from .. import Provider as PhoneNumberProvider
class Provider(PhoneNumberProvider):
formats = (
# Mobile
# Government website: http://www.uke.gov.pl/numeracja-843
'50# ### ###',
'51# ### ###',
'53# ### ###',
'57# ### ###',
... | ##',
'+48 66# ### ###',
'+48 69# ### ###',
'+48 72# ### ###',
'+48 73# ### ###',
'+48 78# ### ###',
'+ | 48 79# ### ###',
'+48 88# ### ###',
'32 ### ## ##',
'+48 32 ### ## ##',
'22 ### ## ##',
'+48 22 ### ## ##',
)
|
tzpBingo/github-trending | codespace/python/telegram/ext/messagequeue.py | Python | mit | 14,773 | 0.004468 | #!/usr/bin/env python
#
# Module author:
# Tymofii A. Khodniev (thodnev) <thodnev@mail.ru>
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2022
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# ... | = None) -> None:
"""Used to gently stop processor and shutdown its thread.
Args:
timeout (:obj:`float`): Indicates maximum time to wait for processor to stop and its
thread to exit. If tim | eout exceeds and processor has not stopped, method silently
returns. :attr:`is_alive` could be used afterwards to check the actual status.
``timeout`` set to :obj:`None`, blocks until processor is shut down.
Defaults to :obj:`None`.
"""
self.__exit_req = ... |
headmastersquall/caatinga | caatinga/lscaat/diff.py | Python | gpl-3.0 | 2,568 | 0 | #!/usr/bin/env python
# Copyright 2015 Chris Taylor
#
# This file is part of caatinga.
#
# Caatinga 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 l... | have proper number items to compare.
"""
if not items:
raise Exception("No items found to compare.")
if len(items) > 1:
_raiseMultipleFileException()
def _raiseMultipleFileException():
raise Exception("Cannot perform diff on more than one file.")
def _getLines(fileName):
"""
... | _getDiff():
"""
Get the program that will be used to perform the diff.
"""
return Differ().compare
|
mfalesni/cfme_tests | cfme/tests/test_db_migrate.py | Python | gpl-2.0 | 8,770 | 0.002281 | import tempfile
import pytest
from os import path as os_path
from wait_for import wait_for
from cfme.base.ui import navigate_to
from cfme.utils import version, os
from cfme.utils.appliance import ApplianceException
from cfme.utils.blockers import BZ
from cfme.utils.conf import cfme_data, credentials
from cfme.utils.l... | ad database: {}".format(out)
# The v2_key is potentially here
v2key_url | = os_path.join(os_path.dirname(db_url), "v2_key")
# Stop EVM service and drop vmdb_production DB
app.evmserverd.stop()
app.db.drop()
app.db.create()
# restore new DB and migrate it
rc, out = app.ssh_client.run_command(
'pg_restore -v --dbname=vmdb_production /tmp/{}'.format(url_basename)... |
rail-berkeley/d4rl | scripts/generation/generate_kitchen_datasets.py | Python | apache-2.0 | 5,546 | 0.000902 | """Script for generating the datasets for kitchen environments."""
import d4rl.kitchen
import glob
import gym
import h5py
import numpy as np
import os
import pickle
np.set_printoptions(precision=2, suppress=True)
SAVE_DIRECTORY = '~/.offline_rl/datasets'
DEMOS_DIRECTORY = '~/relay-policy-learning/kitchen_demos_multit... | ppend(relab | elled_obs[:terminate_at])
demos_actions.append(demo['actions'][:terminate_at])
demos_rewards.append(np.array(rewards))
demos_terminals.append(np.arange(len(rewards)) >= len(rewards) - 1)
demos_infos.append([idx] * len(rewards))
all_obs.append(... |
JavaRabbit/CS496_capstone | compute/autoscaler/demo/frontend_test.py | Python | apache-2.0 | 2,404 | 0 | # Copyright 2015, 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 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 pytes... | and the wall clocks by fixed
intervals (cpu_time_step and wall_time_step, respectively). This can be
used to simulate arbitrary fraction of CPU time available to the process.
"""
def __init__(self, cpu_time_step=1.0, wall_time_step=1.0):
self.cpu_time = 0.0
self.wall_time = 0.0
... |
gileno/tapioca-github | tests/fixtures.py | Python | mit | 4,950 | 0.00303 | # -*- coding: utf-8 -*-
# flake8: noqa
import json
SINGLE_GIST_PAYLOAD = json.loads('''{
"url": "https://api.github.com/gists/1383930894d29dde5015f24c0e279a2b",
"forks_url": "https://api.github.com/gists/1383930894d29dde5015f24c0e279a2b/forks",
"commits_url": "https://api.github.com/gists/1383930894d29dde5015f... | https://gist.githubusercontent.com/fjsj/1383930894d29dde5015f24c0e279a2b/raw/5f4a4c279359819437b0749a7e925216612e5cb8/test-for-tapioca-github.md",
"size": 9,
"truncated": false,
"content": "test\\ngist"
}
},
"public": true,
| "created_at": "2016-09-22T21:32:03Z",
"updated_at": "2016-09-22T21:39:19Z",
"description": "Test for gileno/tapioca-github",
"comments": 1,
"user": null,
"comments_url": "https://api.github.com/gists/1383930894d29dde5015f24c0e279a2b/comments",
"owner": {
"login": "fjsj",
"id": 397989,
"avatar_u... |
lucemia/django-p | django_p/migrations/0002_auto_20160529_1026.py | Python | mit | 549 | 0.001821 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2016-05-29 10:26
from __future__ impo | rt unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('dj | ango_p', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='barrier',
name='target',
field=models.OneToOneField(
on_delete=django.db.models.deletion.CASCADE, to='django_p.Pipeline'),
),
]
|
pombredanne/bokeh | examples/models/custom.py | Python | bsd-3-clause | 2,401 | 0.006247 | from __future__ import print_function
from bokeh.core.properties import String
from bokeh.document import Document
from bokeh.embed import file_html
from bokeh.models.callbacks import Callback
from bokeh.models.glyphs import Circle
from bokeh.models import Plot, DataRange1d, LinearAxis, ColumnDataSource, PanTool, Whee... | which will be formatted with data from the data source.
""")
class MyHBox(HBox):
__im | plementation__ = """
HBox = require "models/layouts/hbox"
class MyHBoxView extends HBox.View
render: () ->
super()
@$el.css({border: "5px solid black"})
class MyHBox extends HBox.Model
type: "MyHBox"
default_view: MyHBoxView
module.exports = {
Model: MyHBox
View: MyHBoxView
}
"""
source = ColumnDa... |
wesm/statsmodels | scikits/statsmodels/tsa/tests/test_ar.py | Python | bsd-3-clause | 7,036 | 0.007533 | """
Test AR Model
"""
import scikits.statsmodels.api as sm
from scikits.statsmodels.tsa.ar_model import AR
from numpy.testing import assert_almost_equal, assert_equal
from results import results_ar
import numpy as np
import numpy.testing as npt
DECIMAL_6 = 6
DECIMAL_5 = 5
DECIMAL_4 = 4
class CheckAR(object):
def ... | st_equal(model.predict(params, start=200, end=333),
self.res2.FVMLEstart200end334, DECIMAL_4)
assert_almost_equal(model.predict(params, start=308, end=333),
self.res2.FVMLEstart308end334, DECIMAL_4)
assert_almost_equal(model.predict(params, start=9,end=309),
... | ),
self.res2.FVMLEstart0end301, DECIMAL_4)
assert_almost_equal(model.predict(params, start=4, end=312),
self.res2.FVMLEstart4end312, DECIMAL_4)
assert_almost_equal(model.predict(params, start=2, end=7),
self.res2.FVMLEstart2end7, DECIMAL_4)
class TestAuto... |
alanconway/dispatch | console/dispatch-dashboard/dispatch/topology/urls.py | Python | apache-2.0 | 693 | 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 r | equired 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.
from djang | o.conf.urls import url
from dispatch.topology import views
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
]
|
rsgemignani/dotfiles | root/usr/lib/gedit/plugins/smart_highlight/smart_highlight.py | Python | gpl-2.0 | 9,699 | 0.0299 | # -*- encoding:utf-8 -*-
# smart_highlight.py is part of smart-highlighting-gedit.
#
#
# Copyright 2010-2012 swatch
#
# smart-highlighting-gedit 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... | = self.config_manager.load_configure('smart_highlight')
self._insert_menu()
def deactivate(self):
# Remove any installed menu items
self._window.disconnect(self.active_tab_added_id)
self.config_manager.update_config_file(self.config_manager.config_file, 'search_option', self.options)
| self.config_manager.update_config_file(self.config_manager.config_file, 'smart_highlight', self.smart_highlight)
def _insert_menu(self):
# Get the GtkUIManager
manager = self._window.get_ui_manager()
# Create a new action group
self._action_group = Gtk.ActionGroup("SmartHighlightActions")
self._action_g... |
rodekruis/shelter-database | src/scripts/create_user.py | Python | mit | 386 | 0.005181 | #! /usr/bin/python
#-*- coding:utf-8 -*
import csv
from werkzeug import generate_password_hash |
from web.models import User
from bootstrap import db
def create_user(email, name, password):
user = User(email=email,
name=name,
pwdhash=generate_pa | ssword_hash(password),
is_active=True)
db.session.add(user)
db.session.commit()
|
olivierverdier/sfepy | tests/test_term_consistency.py | Python | bsd-3-clause | 4,677 | 0.01796 | # c: 19.05.2008, r: 19.05.2008
from sfepy import data_dir
filename_mesh = data_dir + '/meshes/2d/special/circle_in_square.mesh'
dim = 2
field_1 = {
'name' : 'scalar_field',
'dtype' : 'real',
'shape' : 'scalar',
'region' : 'Omega',
'approx_order' : 1,
}
field_2 = {
'name' : 'vector_field',
... | t_terms:
term_template, (prefix, par_name, d_vars, dw_vars, mat_mode) = aux
print term_template, prefix, par_name, d_vars, dw_vars, mat_mode
term1 = term_template % ((prefix,) + d_vars)
variables = Variables.from_conf(self.conf.variables, pb.fields)
for var... | es[var_name]
n_dof = var.field.n_nod * var.field.shape[0]
aux = nm.arange( n_dof, dtype = nm.float64 )
var.data_from_data(aux)
pb.materials['m'].function.set_extra_args(term = mat_mode)
if prefix == 'd':
val1 = pb.evaluate(term1, ... |
Beyond-Imagination/BlubBlub | ChatbotServer/ChatbotEnv/Lib/site-packages/jpype/_windows.py | Python | gpl-3.0 | 2,127 | 0.002821 | #**************************** | *************************************************
# Copyright 2004-2008 Steve Menard
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use thi | s 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 CONDITI... |
jjdmol/LOFAR | CEP/GSM/bremen/src/updater.py | Python | gpl-3.0 | 1,838 | 0 | #!/usr/bin/python
from src.sqllist import get_sql
_UPDATER_EXTRAS = {
'runningcatalog': ['runcatid'],
'runningcatalog_fluxes': ['runcat_id', 'band', 'stokes'],
}
def _refactor_update(sql):
"""
Special refactoring for MonetDB update..from imitation.
"""
def _get_extra_conditions(tabname):
... | eld) | , 'x.%s' % field)
update_field = []
for sqlf in sqlupd_list:
field, update_stmt = sqlf.split('=')
update_field.append('%s = (select %s from %s x, %s %s %s)' % (
field, update_stmt.replace(table, 'x'),
table, sqlfrom2, sqlwhere,
... |
mytliulei/DCNRobotInstallPackages | windows/win32/paramiko-1.14.0/paramiko/compress.py | Python | apache-2.0 | 1,245 | 0 | # Copyright (C) 2003-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... | lf):
self.z = zlib.decompressobj()
| def __call__(self, data):
return self.z.decompress(data)
|
romeokpolo/SVMPython | src/01-Week2/find_largest.py | Python | mit | 456 | 0.010965 |
num_list1 = [1, 3, 21, 9, 88, 77, 0, 20]
num_lis | t2 = [10, 3, 21, 9, 88, 77, 0, 1000]
# Defining/creating the function:
def romeos_version_of_max( nlst ):
print nlst
largest = nlst[0]
# Find the largest, and update the variable
for number in nlst:
if number >= largest:
largest = number
| return largest
# Calling the function
print romeos_version_of_max(num_list1)
print romeos_version_of_max(num_list2)
|
fdvarela/odoo8 | addons/crm/base_partner_merge.py | Python | agpl-3.0 | 30,328 | 0.002506 | #!/usr/bin/env python
from __future__ import absolute_import
from email.utils import parseaddr
import functools
import htmlentitydefs
import itertools
import logging
import operator
import re
from ast import literal_eval
from openerp.tools import mute_logger
# Validation Library https://pypi.python.org/pypi/validate_e... | AND cl2.relname = %s
AND att2.attname = 'id'
| AND array_lower(con.confkey, 1) = 1
AND con.confkey[1] = att2.attnum
AND att2.attrelid = cl2.oid
AND con.contype = 'f'
"""
return cr.execute(q, (table,))
def _update_foreign_keys(self, cr, uid, src_partners, dst_partner, context=None):
... |
apruden/genwiki | main.py | Python | lgpl-3.0 | 32 | 0 | from genwi | ki.ge | nwiki import app
|
biocommons/hgvs-eval | hgvseval/testservice/interface.py | Python | apache-2.0 | 1,686 | 0.003559 | import abc
class HGVSTestService(object):
@abc.abstractmethod
def info(self):
"""retu | rns dictionary of package info
"""
pass
@abc.abstractmethod
def project_t_to_g(self, hgvs_string, ac):
"""projects transcript (c. or n.) variant hgvs_string onto genom | ic
sequence specified by ac, returning g. hgvs string
Transcripts may be coding or non-coding.
"""
pass
@abc.abstractmethod
def project_g_to_t(self, hgvs_string, ac):
"""projects g. variant hgvs_string onto transcript sequence
specified by ac, returning a c. o... |
oozappa/maiden | tests/__init__.py | Python | apache-2.0 | 148 | 0 | import doctest |
from maiden import config
def load_tests(loader, tests, ignore):
tests.addTests(doctest.DocTestSuite(config))
return t | ests
|
Bodidze/21v-python | unit_05/alive/test.py | Python | mit | 5,183 | 0.000193 | import main
def test_get_board():
alive_cons = [(1, 1),
(2, 2),
(3, 1),
(3, 3),
(4, 0)]
board = [[0, 0, 0, 0, 0],
[0, 1, 0, 0, 0],
[0, 0, 1, 0, 0],
[0, 1, 0, 1, 0],
[1, 0, 0, 0, 0]]
... | )]
|
class TestNewStep(object):
def test_glader(self):
alive_cons = [(1, 2),
(2, 3),
(3, 1),
(3, 2),
(3, 3)]
new_alive_cons = [(2, 1),
(2, 3),
(3, 2),
... |
iambibhas/django | django/views/csrf.py | Python | bsd-3-clause | 5,059 | 0.001186 | from django.conf import settings
from django.http import HttpResponseForbidden
from django.template import Context, Template
from django.utils.translation import ugettext as _
from django.utils.version import get_docs_version
# We include the template inline since we need to be able to reliably display
# this error me... | ref="https://docs.djangoproject.com/en/{{ docs_version }}/ref/templates/api/#subclassing-context-requestcontext"><code>RequestContext</code></a>
for the template, instead of <code>Context</code>. | </li>
<li>In the template, there is a <code>{% templatetag openblock %} csrf_token
{% templatetag closeblock %}</code> template tag inside each POST form that
targets an internal URL.</li>
<li>If you are not using <code>CsrfViewMiddleware</code>, then you must use
<code>csrf_protect</code> on any ... |
nareshppts/account_chart_update | account_renumber/test/create_moves.py | Python | agpl-3.0 | 5,324 | 0.000752 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP - Account renumber wizard
# Copyright (C) 2009 Pexego Sistemas Informáticos. All Rights Reserved
# $Id$
#
# This program is free software: you can redistribute it and/or modify
# it under th... | bname, user, passwd, howmany):
"""
Small OpenERP function that will create lots of account moves
on the selected database, that can later be used for
testing the renumber wizard.
Note: The database must have demo data, and a fiscal year 2009 created.
"""
url_template = "http://%s:%s/xmlrpc/%... | lhost"
port = 8069
user_id = 0
login_facade = xmlrpclib.ServerProxy(
url_template % (server, port, 'common'))
user_id = login_facade.login(dbname, user, passwd)
object_facade = xmlrpclib.ServerProxy(
url_template % (server, port, 'object'))
for i in range(1, howmany):
#... |
JakeCowton/invenio-data | invenio_data/modules/deposit/workflows/alice.py | Python | gpl-2.0 | 3,371 | 0.003856 | # -*- coding: utf-8 -*-
##
## This file is part of Invenio.
## Copyright (C) 2012, 2013, 2014 CERN.
##
## Invenio is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Publi | c License as
## published by the Fre | e Software Foundation; either version 2 of the
## License, or (at your option) any later version.
##
## Invenio is distributed in the hope that it will be useful, but
## WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
## General Public Licen... |
TheTimmy/spack | var/spack/repos/builtin/packages/pathfinder/package.py | Python | lgpl-2.1 | 2,190 | 0.000913 | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | even the IMPLIED WARRANTY OF
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foun... | ##################################
from spack import *
class Pathfinder(MakefilePackage):
"""Proxy Application. Signature search."""
homepage = "https://mantevo.org/packages/"
url = "http://mantevo.org/downloads/releaseTarballs/miniapps/PathFinder/PathFinder_1.0.0.tgz"
tags = ['proxy-app']
... |
GbalsaC/bitnamiP | venv/lib/python2.7/site-packages/sympy/concrete/tests/test_products.py | Python | agpl-3.0 | 1,362 | 0.002937 | from sympy import (symbols, product, factorial, rf, sqrt, cos,
Function, Product, Rational)
a, k, n = symbols('a,k,n', integer=True)
def test_simple_products():
assert product(2, (k, a, n)) == 2**(n-a+1)
assert product(k, (k, 1, n)) == factorial(n)
assert product(k**3, (k, 1, n)) == fac... | 2
def test__eval_product():
from sympy.abc import i, n
# 17 | 10
a = Function('a')
assert product(2*a(i), (i, 1, n)) == 2**n * Product(a(i), (i, 1, n))
# 1711
assert product(2**i, (i, 1, n)) == 2**(n/2 + n**2/2)
|
FrodeSolheim/fs-uae-launcher | launcher/controllertest/ControllerTestWindow.py | Python | gpl-2.0 | 2,019 | 0 | import logging
from fsgamesys.input.inputservice import (
GamepadConnectedEvent,
GamepadDisconnectedEvent,
JoystickConnectedEvent,
JoystickDisconnectedEvent,
useInputService,
)
from launcher.fswidgets2.flexcontainer import FlexContainer
from launcher.fswidgets2.panel import Panel
from launcher.fswi... | self.textArea = TextArea(style={"flexGrow": 1, "margin": 10})
self.inputService = useInputService()
self.listen(
self.inputService.gamepadConnectedEvent, self.onGamepadConnected
)
self.lis | ten(
self.inputService.gamepadDisconnectedEvent,
self.onGamepadDisconnected,
)
self.listen(
self.inputService.joystickConnectedEvent, self.onJoystickConnected
)
self.listen(
self.inputService.joystickDisconnectedEvent,
self.onJ... |
OpenMined/PySyft | tests/integration/smpc/store/crypto_primitive_provider_test.py | Python | apache-2.0 | 5,243 | 0.000954 | # # stdlib
# from typing import Any
# from typing import Dict
# from typing import Iterable
# from typing import List
# from typing import Tuple
# # third party
# import numpy as np
# import pytest
# # syft absolute
# from syft import Tensor
# # absolute
# from syft.core.smpc.store import CryptoPrimitiveProvider
# f... | e len."""
# Crypto | PrimitiveProvider._transfer_primitives_to_parties(
# op_str="test", primitives=[1], parties=[], p_kwargs={}
# )
# @pytest.mark.skip
# def test_register_primitive() -> None:
# val = CryptoPrimitiveProvider.get_state()
# expected_providers = "test"
# assert expected_providers in val, "... |
robmcmullen/peppy | peppy/plugins/macro.py | Python | gpl-2.0 | 47,677 | 0.005013 | # peppy Copyright (c) 2006-2010 Rob McMullen
# Licenced under the GPLv2; see http://peppy.flipturn.org for more info
"""Simple macros created by recording actions
This plugin provides macro recording
"""
import os
import wx
from wx.lib.pubsub import Publisher
from peppy.yapsy.plugins import *
from peppy.actions im... | me, mode).actionKeystroke(%s, %d)" % (self.actioncls.__name__, CharEvent.getScripted(self.evt), self.multiplier)
class RecordedMenuAction(RecordedAction) | :
"""Subclass of L{RecordedAction} for menu events.
"""
def __init__(self, action, index, multiplier):
RecordedAction.__init__(self, action, multiplier)
self.index = index
def __str__(self):
return "%s x%d, index=%s" % (self.actioncls.__name__, self.multiplier, self.ind... |
omargammoh/rpislave | website/proc/rebooter.py | Python | gpl-2.0 | 1,426 | 0.007714 | import datetime
import time
import website.processing
def get_laststatusloop():
try:
f = file('/home/pi/data/laststatusloop','r')
s = f.read()
f.close()
dt = datetime.datetime.strptime(s, '%Y%m%d%H%M%S')
return dt
except:
print ">> rebooter: !!! failed to read la... | c' %(str(now), sec, deviation_cou | nter))
f.close()
website.processing.execute(cmd="sudo reboot")
else:
print ">> rebooter: is fine"
except:
print ">> rebooter: !!! error"
pass
time.sleep(300)#500
|
msegado/edx-platform | common/test/acceptance/tests/lms/test_lms_user_preview.py | Python | agpl-3.0 | 5,975 | 0.001841 | # -*- coding: utf-8 -*-
"""
Tests the "preview" selector in the LMS that allows changing between Staff, Learner, and Content Groups.
"""
from textwrap import dedent
from common.test.acceptance.fixtures.course imp | ort CourseFixture, XBlockFixtureDesc
from common. | test.acceptance.pages.common.auto_auth import AutoAuthPage
from common.test.acceptance.pages.lms.courseware import CoursewarePage
from common.test.acceptance.pages.lms.staff_view import StaffCoursewarePage
from common.test.acceptance.tests.helpers import UniqueCourseTest, create_user_partition_json
from openedx.core.li... |
deepmind/deepmind-research | cs_gan/main_ode.py | Python | apache-2.0 | 12,654 | 0.008219 | # Copyright 2019 DeepMind Technologies Limited and Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... | rics', True,
'Whether or not to run image metrics on samples.')
FLAGS = flags | .FLAGS
# Log info level (for Hooks).
tf.logging.set_verbosity(tf.logging.INFO)
def _copy_vars(v_list):
"""Copy variables in v_list."""
t_list = []
for v in v_list:
t_list.append(tf.identity(v))
return t_list
def _restore_vars(v_list, t_list):
"""Restore variables in v_list from t_list."""
ops = []
... |
geraintpalmer/ASQ | asq/exit_node.py | Python | mit | 759 | 0.002635 | from __future__ import division
class ExitNode:
"""
Class for the exit node on our network
"""
def _ | _init__(self, max_simulation_time):
"""
Initialise a node.
"""
self.individuals = []
self.id_number = -1
self.next_event_date = max_simulation_time
self.node_capacity = "Inf"
def __repr__(self):
"""
Representation of a node::
"""
... | ode'
def accept(self, next_individual, current_time):
"""
Accepts a new customer to the queue
"""
self.individuals.append(next_individual)
def update_next_event_date(self):
"""
Finds the time of the next event at this node
"""
pass |
angelmtenor/IDSFC | L2_Data_Wrangling/P8_get_hourly_entries_and_exits.py | Python | mit | 2,645 | 0.00794 | import pandas
def get_hourly_entries(df):
"""
The data in the MTA Subway Turnstile data reports on the cumulative
number of entries and exits per row. Assume that you have a dataframe
called df that contains only the rows for a particular turnstile machine
(i.e., unique SCP, C/A, and UNIT). This... | -00 05-01-11 16:00:00 REGULAR 3144594 1088275 170
5 A002 R051 02-00-00 05-01-11 20:00:00 REGULAR 3144808 1088317 214
6 A002 R051 02-00-00 05-02-11 00:00:00 REGULAR 3144895 1088328 | 87
7 A002 R051 02-00-00 05-02-11 04:00:00 REGULAR 3144905 1088331 10
8 A002 R051 02-00-00 05-02-11 08:00:00 REGULAR 3144941 1088420 36
9 A002 R051 02-00-00 05-02-11 12:00:00 REGULAR 3145094 1088753 153
10 A002 R051 ... |
nikdoof/test-auth | app/groups/migrations/0002_groupinformation.py | Python | bsd-3-clause | 5,402 | 0.00759 | # encoding: utf-8
import datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
class Migration(DataMigration):
def forwards(sel | f, orm):
for group in orm['auth.Group'].objects.all():
try:
obj = orm.GroupInformation.objects.get(group=group)
except orm.Group | Information.DoesNotExist:
obj = orm.GroupInformation(group=group)
obj.save()
def backwards(self, orm):
orm.GroupInformation.objects.all().delete()
models = {
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.f... |
liquidm/druid | docs/_bin/generate-license-dependency-reports.py | Python | apache-2.0 | 2,924 | 0.004788 | #!/usr/bin/env python3
# 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 "Lic... | ct_notice = {}
def main():
if len(sys.argv) != 3:
sys.stderr.write('usage: program <druid source path> <full tmp path>\n')
sys.exit(1)
druid_path = sys.argv[1]
tmp_path = sys.argv[2]
generate_reports(druid_path, tmp_path)
def generate_reports(druid_path, tmp_path):
license_main_path ... | os.mkdir(license_ext_path)
print("********** Generating main LICENSE report.... **********")
os.chdir(druid_path)
command = "mvn -Pdist -Ddependency.locations.enabled=false project-info-reports:dependencies"
outstr = subprocess.check_output(command, shell=True).decode('UTF-8')
command = "cp -r dis... |
ESSolutions/ESSArch_Core | ESSArch_Core/essxml/ProfileMaker/migrations/0007_auto_20160908_1428.py | Python | gpl-3.0 | 1,696 | 0 | """
ESSArch is an open source archiving and digi | tal pre | servation system
ESSArch
Copyright (C) 2005-2019 ES Solutions AB
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any late... |
poppogbr/genropy | packages/adm/model/connection.py | Python | lgpl-2.1 | 3,070 | 0.00456 | # encoding: utf-8
from __future__ import with_statement
from datetime import datetime
class Table(object):
def use_dbstores(self):
return False
def config_db(self, pkg):
tbl = pkg.table('connection', pkey='id', name_long='!!Connection',
name_plural='!!Connections', broa... | page.connection_id, username=page.user,
userid=avatar.userid, start_ts=datetime.now(),
| ip=page.request.remote_addr,
user_agent=page.request.get_header('User-Agent'))
with self.db.tempEnv(connectionName='system'):
self.insertOrUpdate(new_connection_record)
self.db.commit()
|
JPro173/cloudpie | client/main.py | Python | gpl-3.0 | 1,186 | 0.001686 | import htmlPy
import socket
import json
import os
sock = socket.socket()
sock.connect(('localhost', 5002))
sock.send(b'')
sock.recv(1024)
sock.recv(1024)
sock.recv(1024)
app = htmlPy.AppGUI(title=u"Python Best Ever", maximized=True)
app.template_path = os.path.abspath("./html")
app.static_path = os.path.abspath("./... | ut':
a | pp_data[subcommand] = data
class App(htmlPy.Object):
def __init__(self):
super(App, self).__init__()
@htmlPy.Slot(str)
def link(self, url):
template_name = str(url)
app.template = (template_name, app_data)
@htmlPy.Slot(str)
def command(self, cmd):
cmd = bytes(cmd)... |
rafasis1986/EngineeringMidLevel | flaskiwsapp/settings/devConfigTemplate.py | Python | mit | 539 | 0.001855 | '''
Created on Sep 22, 2016
@author: rtorres
'''
import os
from flaskiwsapp.settings.baseConfig import BaseConfi | g
class DevConfig(BaseConfig):
"""Development configuration"""
ENV = 'dev'
DEBUG = True
DEBUG_TB_ENABLED = True
SQLALCHEMY_DATABASE_URI = 'postgresql://localhost/example'
AUTH0_CALLBACK_URL = 'http://localhost/auth/callback'
AUTH0_CLIENT_ID = ''
AUTH0_CLIENT_SECRET = ''
AUTH0_DOMAI... | IN = 'localhost'
APP_URL = 'http://%s' % APP_DOMAIN
SERVER_NAME = 'locahost'
|
mkesicki/excel_validator | validator/NotBlankValidator.py | Python | mit | 401 | 0.009975 | from validator.BaseValidator impor | t BaseValidator
import re
class NotBlankValidator(BaseValidator):
required = True
message = "Cell can not be blank"
def validate(self, value):
if self.required == False or (value != None and value != ""):
return True
return False
def | __init__(self, params):
super(NotBlankValidator, self).__init__(params)
|
AAT-SP2017/tweet-miner | tweet-miner/main.py | Python | mit | 684 | 0.005848 | import log
import taglistener
import setti | ngs
if __name__ == '__main__':
try:
import time
logger = log.get_logger(__name__)
listener = taglistener.TagListener()
print('Started listening for {}'.format(settings.TAGS))
print('Press CTRL+C to exit. It may take a minute or two for it to gracefully terminate.')
... | threaded request is being handled.')
print('Be patient.')
if listener.is_running():
listener.disconnect()
|
chrislit/abydos | tests/fingerprint/test_fingerprint_consonant.py | Python | gpl-3.0 | 1,933 | 0 | # Copyright 2019-2020 by Christopher C. Little.
# This file is part of Abydos.
#
# Abydos 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 versio... | sonant."""
# Base case
self.assertEqual(Consonant().fingerprint(''), '')
# Test cases from paper
self.assertEqual(Consonant(variant=1).fingerprint('ABRAMS'), 'ABRMS')
self.assertEqual(Consonant(variant=2).fingerprint('AR | ROW'), 'ARR')
self.assertEqual(Consonant(variant=3).fingerprint('ABRAHAM'), 'ABRM')
self.assertEqual(
Consonant(variant=1, doubles=False).fingerprint('ARROW'), 'ARW'
)
self.assertEqual(
Consonant(variant=2, doubles=False).fingerprint('ARROW'), 'AR'
)
... |
neo5g/server-gsrp5 | server-gsrp5/orm/fields.py | Python | agpl-3.0 | 18,659 | 0.064902 | # -*- coding: utf-8 -*-
import base64
import decimal
from psycopg2 import Binary
import datetime as DT
import pytz
import logging
_logger = logging.getLogger(__name__)
def _set_symbol(symb):
if symb is None or symb == False:
return None
return str(symb)
class _column(object):
__slots__ = ('__dict_... |
_symbol_get = None
def __init__(self, label = 'unknown', readonly = False, priority = 0, context = {}, required = False, size = 32, change_default = True, translate = False, selectable = False, filtering = None, domain=None, manual = False, help = False, unique = False, check = None):
super(char, self).__init__(l... | size = size, change_default = change_default, translate = translate, selectable = selectable, filtering=filtering, domain=domain, manual = manual, help=help, unique = unique, check = check)
class varchar(_column):
_classic_read =True
_classic_write = True
_prefetch = True
_type = 'varchar'
_db_type = 'character ... |
participedia/api | migrations/utils/fake_users.py | Python | mit | 968 | 0.001033 | import csv
import json
fake_usernames = json.loads(open('members.json').read())
print '{} fake users'.format(len(fake_usernames))
csv_reader = csv.DictReader(open('../data-transport/migrations/users.csv'))
users = [user for user in csv_reader]
print '{} real users'.format(len(users))
print '{} merged'.format(len(zip(u... | e, real) in zip(fake_usernames, users)]
fieldnames = sorted(users[-1].keys())
with open('migrations/users.csv' | , 'w') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=fieldnames, extrasaction='ignore')
writer.writeheader()
for user in newusers:
writer.writerow(user)
|
mitchcapper/mythbox | resources/lib/mysql-connector-python/python2/mysql/connector/cursor.py | Python | gpl-2.0 | 24,598 | 0.005285 | # MySQL Connector/Python - MySQL driver written in Python.
# Copyright (c) 2009, 2012, Oracle and/or its affiliates. All rights reserved.
# MySQL Connector/Python is licensed under the terms of the GPLv2
# <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most
# MySQL Connectors. There are special exceptio... | available.
Returns a long value or None.
"""
return self._last_insert_id
class MySQLCursor | (CursorBase):
"""Default cursor for interacting with MySQL
This cursor will execute statements and handle the result. It will
not automatically fetch all rows.
MySQLCursor should be inherited whenever other functionallity is
required. An example would to change the fetch* member functions
... |
ztenma/Swap | itertoolsExt.py | Python | mit | 5,830 | 0.025729 |
import random
import collections
from itertools import *
def take(n, iterable):
"Return first n items of the iterable as a list"
return list(islice(iterable, n))
def tabulate(function, start=0):
"Return function(0), function(1), ..."
return map(function, count(start))
def consume(iterator, n):
"Advance the ite... | tirely."
# Use functions that consume iterators at C speed.
if n is None:
# feed the entire iterator into a zero-length deque
collections.deque(iterator, maxlen=0)
else:
# advance to the empty sli | ce starting at position n
next(islice(iterator, n, n), None)
def nth(iterable, n, default=None):
"Returns the nth item or a default value"
return next(islice(iterable, n, None), default)
def quantify(iterable, pred=bool):
"Count how many times the predicate is true"
return sum(map(pred, iterable))
def padnone(... |
luuloe/python-duco | tests/test_enum_types.py | Python | mit | 569 | 0 | """Test methods in duco/modbus.py."""
import unittest
from duco.const import (DUCO_MODULE_TYPE_MASTER,
DUCO_MODULE_TYPE_ACTUATOR_PRINT)
from duco.enum_types im | port (ModuleType)
class TestModuleType(unitte | st.TestCase):
def test_supported(self):
for idx in range(DUCO_MODULE_TYPE_MASTER, 10):
self.assertTrue(ModuleType.supported(idx), "msg")
self.assertFalse(ModuleType.supported(DUCO_MODULE_TYPE_MASTER-1), "")
self.assertFalse(ModuleType.supported(
DUCO_MODULE_TYPE_ACTU... |
danielrcardenas/ac-course-2017 | frameworks/pycellchem-2.0/src/NetFraglets.py | Python | apache-2.0 | 2,152 | 0.004647 | #---------------------------------------------------------------------------
#
# NetFraglets: networked examples of Fraglets, a chemically-inspired
# programming language for computer networks
#
# so far only one example available:
# CDP: confirmed delivery protocol
#
# Reference:
#
# C. Tschudin. Fraglets: A metabolis... |
print >> sys.stderr, "INIT:"
n1.trace()
n2.trace()
cnt = 0
for i in range(niter):
print >> sys.stderr, "ITER=", i
if i % 4 == 0:
mol = 'cd' + str(cnt)
n1.inject(mol)
cnt = (cnt + 1) % 10
net.propensity()
net.gillespie()
prin... | ame__ == '__main__':
cdp()
|
probml/pyprobml | scripts/xcorr_demo.py | Python | mit | 1,136 | 0.003521 | # adpated from http://docs.scipy.org/doc/scipy-0.15.1/reference/generated/scipy.signal.correlate2d.html
import superimport
import matplotlib.pyplot as plt
import numpy as np
from scipy import signal
from scipy import misc
print("cross correlation demo")
face = misc.face() - misc.face().mean()
face = face.sum(-1)
tem... | ots(2, 2)
ax_orig.imshow(face, cmap='gray')
ax_orig.set_title('Original')
ax_orig.set_axis_off()
ax_orig.plot(x, y, 'ro')
ax_template.imshow(template, cmap='gray')
ax_template.set_title('Template')
ax_template.set_axis_off()
ax_noisy.imshow( | noisyface, cmap='gray')
ax_noisy.set_title('Noisy')
ax_noisy.set_axis_off()
ax_noisy.plot(x, y, 'ro')
ax_corr.imshow(corr, cmap='gray')
ax_corr.set_title('Cross-correlation')
ax_corr.set_axis_off()
fig.show()
|
openstack/designate | designate/common/policies/zone_transfer_request.py | Python | apache-2.0 | 4,669 | 0 | # All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... | h': '/v2/zones/tasks/transfer_requests',
'method': 'GET'
}
],
),
policy.RuleDefault(
name="find_zone_transfer_request",
check_str=base.RULE_ANY
),
policy.DocumentedRuleDefault(
name="update_zone_transfer_request",
check_str=base.SYSTEM_... | /tasks/transfer_requests/{zone_transfer_request_id}', # noqa
'method': 'PATCH'
}
],
deprecated_rule=deprecated_update_zone_transfer_request
),
policy.DocumentedRuleDefault(
name="delete_zone_transfer_request",
check_str=base.SYSTEM_ADMIN_OR_PROJECT_ME... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.