prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
import json
import numpy as np
from glob import glob
inputs = {
'xml_file_path' : "./da | ta/single_wavelength_copy",
'file_set' : {'p38' : glob( "./data/single_wavelength_copy/*.xml")},
'section' : '280_480_TOP_120',
'ligand_order' : ['Bosutinib','Bosutinib Isomer','Erlotin | ib','Gefitinib','Ponatinib','Lapatinib','Saracatinib','Vandetanib'],
'Lstated' : np.array([20.0e-6,14.0e-6,9.82e-6,6.88e-6,4.82e-6,3.38e-6,2.37e-6,1.66e-6,1.16e-6,0.815e-6,0.571e-6,0.4e-6,0.28e-6,0.196e-6,0.138e-6,0.0964e-6,0.0676e-6,0.0474e-6,0.0320e-6,0.0240e-6,0.0160e-6,0.0120e-6,0.008e-6,0.0], np.float64... |
ddField(
model_name='knowninstitution',
name='validated_on',
field=models.DateTimeField(null=True, blank=True),
),
migrations.AddField(
model_name='knownlocation',
name='validated_on',
field=models.DateTimeField(null=True, blank=Tru... | name='validated',
field=models.BooleanField(default=False, help_text=b'Indicates that a record has been examined for accuracy. This does not necessarily mean that the record has been disambiguated with respect to an authority accord.'),
),
migrations.AlterField(
model_name='... | sarily mean that the record has been disambiguated with respect to an authority accord.'),
),
migrations.AlterField(
model_name='coursegroup',
name='validated',
field=models.BooleanField(default=False, help_text=b'Indicates that a record has been examined for accuracy... |
ow be associated
with any :class:`.Connectable` including :class:`.Connection`,
in addition to the existing support for :class:`.Engine`.
"""
_target_class_doc = "SomeEngine"
_dispatch_target = Connectable
@classmethod
def _listen(cls, event_key, retval=False):
target, iden... | nly the 'before_execute' and "
"'before_cursor_execute' engine "
"e | vent listeners accept the 'retval=True' "
"argument.")
event_key.with_wrapper(fn).base_listen()
def before_execute(self, conn, clauseelement, multiparams, params):
"""Intercept high level execute() events, receiving uncompiled
SQL constructs and other objects prior to re... |
# Copyright 2013: Mirantis 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 b... | nterfaces"),
cfg.StrOpt("https_cacert | ", default=None,
help="Path to CA server cetrificate for SSL")
])
# NOTE(boris-42): super dirty hack to fix nova python client 2.17 thread safe
nova._adapter_pool = lambda x: nova.adapters.HTTPAdapter()
class Clients(object):
"""This class simplify and unify work with openstack python clients."""... |
from s3v1 import *
def filter_col_by_string(data_sample, field, filter_condition):
filtered_rows = [] # create a new list
col = int(data_sample[0].index(field)) # create a variable (col) and asign it to an i | nteger which is pulled from the header row of the data_sample and which is the index (probably also an integer to begin with) of the field name that we passed in as an argument
filtered_rows.append(data_sample[0]) # add the header row to the new lis | t
for item in data_sample[1:]:
if item[col] == filter_condition:
filtered_rows.append(item)
return filtered_rows
def filter_col_by_float(data_sample, field, direction, filter_condition):
filtered_rows = []
col = int(data_sample[0].index(field)) # you must use integers to access indexes. So this is just to b... |
import pytz
from pyrfc3339.utils import timezone, timedelta_seconds
def generate(dt, utc=True, accept_naive=False, microseconds=False):
'''
Generate an :RFC:`3339`-formatted timestamp from a
:class:`datetime.datetime`.
>>> from datetime import datetime
>>> generate(datetime(2009,1,1,12,59,59,0,p... | >>> generate(dt, utc=False)
'2009-01-01T12:59:59-05:00'
Unless `accept_naive=True` is specified, the `datetime` must not be naive.
>>> genera | te(datetime(2009,1,1,12,59,59,0))
Traceback (most recent call last):
...
ValueError: naive datetime and accept_naive is False
>>> generate(datetime(2009,1,1,12,59,59,0), accept_naive=True)
'2009-01-01T12:59:59Z'
If `accept_naive=True` is specified, the `datetime` is assumed to be UTC.
Atte... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2015, Corwin Brown <corwin@corwinbrown.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the... | myendpoint
register: http_output
# Set a HOST header to hit an internal webserver:
---
- name: Hit a Specific Host on the Server
win_uri:
url: http://my.internal.server.com
method: GET
headers:
host: "www.somesite.com"
# Do a HEAD request on an endpoint
---
- name: Perform a HEAD on an Endpoint
... | ody to an Endpoint
win_uri:
url: http://www.somesite.com
method: POST
body: "{ 'some': 'json' }"
"""
RETURN = """
url:
description: The Target URL
returned: always
type: string
sample: "https://www.ansible.com"
method:
description: The HTTP method used.
returned: always
type: string
sampl... |
"""private_base will be populated from puppet and placed in this directory"""
import logging
import os
import dj_database_url
from lib.settings_base import CACHE_PREFIX, ES_INDEXES, KNOWN_PROXIES, LOGGING
from .. import splitstrip
import private_base as private
ENGAGE_ROBOTS = False
EMAIL_BACKEND = 'django.core.m... | B_LOCK_PREFIX = 'addons-landfill'
BUILDER_SECRET_KEY = private.BUILDER_SECRET_KEY
BUILDER_VERSIONS_URL = "https://builder-addons-dev.allizom.org/repackage/sdk-versions/"
ES_HOSTS = splitstrip(private.ES_HOSTS)
ES_URLS = ['http://%s' % h for h in ES_HOSTS]
ES_INDEXES = dict((k, '%s_landfill' % v) for k, v in ES_INDEX... | RT = private.STATSD_PORT
STATSD_PREFIX = private.STATSD_PREFIX
GRAPHITE_HOST = private.GRAPHITE_HOST
GRAPHITE_PORT = private.GRAPHITE_PORT
GRAPHITE_PREFIX = private.GRAPHITE_PREFIX
CEF_PRODUCT = STATSD_PREFIX
ES_TIMEOUT = 60
EXPOSE_VALIDATOR_TRACEBACKS = True
KNOWN_PROXIES += ['10.2.83.105',
'10.... |
ltin):
"""Import one module's content into another."""
def accept(self, visitor): visitor.visit_using_directive(self)
class UsingDeclaration(Builtin):
"""Import a declaration into this module."""
def __init__(self, file, line, type, name, alias):
super(UsingDeclaration, self).__init__(file, l... | self.constr = constr
def accept(self, visitor): visitor.visit_variable(self)
class Const(Declaration):
"""Constant declaration. A constant is a name with a type and value."""
def __init__(self, file, line, type, name, ctype, value):
Declaration.__init__(self, file, line, type, name)
self.c... | ""Function Parameter"""
def __init__(self, premod, type, postmod, name='', value=''):
self.premodifier = premod
self.type = type
self.postmodifier = postmod
self.name = name
self.value = value or ''
def accept(self, visitor): visitor.visit_parameter(self)
def __cmp__(self... |
"""calculate bootstrap bounds on a sample game"""
import argparse
import json
import sys
import numpy as np
from gameanalysis import bootstrap
from gameanalysis import gameio
from gameanalysis import regret
from gameanalysis import scriptutils
CHOICES = {
'regret': (bootstrap.mixture_regret, regret.mixture_regr... | list with an entry for each mixture in order. Each element is a
dictionary mapping percentile to value.""")
parser.add_argument(
'--input', '-i', metavar='<input-file>', default=sys.std | in,
type=argparse.FileType('r'), help="""Input sample game to run bootstrap
on. (default: stdin)""")
parser.add_argument(
'--output', '-o', metavar='<output-file>', default=sys.stdout,
type=argparse.FileType('w'), help="""Output file for script. (default:
stdout)""")
par... |
import shutil
import os
import base64
from PySide.QtCore import *
from PySide.QtGui import *
from maya.app.general.mayaMixin import MayaQWidgetBaseMixin, MayaQWidgetDockableMixin
from maya import cmds
from luka import Luka
from luka.gui.qt import TakeSnapshotWidget, SnapshotListWidget
__all__ = ['LukaTakeSnapshotUI... | super(LukaTakeSnapshotUI, self).take_snapshot()
class LukaUI(MayaQWidgetBaseMixin, SnapshotListWidget):
def __init__(self, *args, **kwargs):
scene = currentScenePath()
self.luka = Luka(scene, load= | True) if len(scene) > 0 else None
super(LukaUI, self).__init__(luka=self.luka, *args, **kwargs)
def initUI(self):
super(LukaUI, self).initUI()
self.newSnapshotButton = QPushButton("New Snapshot", self)
self.newSnapshotButton.clicked.connect(self.showTakeSnapshotUI)
se... |
im | port unittest
import tests
import tests.test_logic
import tests.test_graph
import tests.tes | t_output
|
# -*- coding: utf-8 -*-
# vim: sw=4:ts=4:expandtab
"""
riko.modules.strreplace
~~~~~~~~~~~~~~~~~~~~~~~
Provides functions for string search-and-replace.
You provide the module with the text string to search for, and what to replace
it with. Multiple search-and-replace pairs can be added. You can specify to
replace all... | """A processor module that asynchronously replaces the text of a field of
an item.
Args:
item (dict): The entry to process
kwargs (dict): The keyword arguments passed to the wrapper
Kwargs:
conf (dict): The pipe configuration. Must contain the key 'rule'.
rule (dic... | The string to find.
replace (str): The string replacement.
param (str): The type of replacement. Must be one of: 'first',
'last', or 'every' (default: 'every').
assign (str): Attribute to assign parsed content (default: strreplace)
field (str): Item a... |
# -*- coding: utf-8 -*-
import sys
import os
import shutil
import psutil
import subprocess
import time
import numpy as np
import itertools
# from matplotlib import pyplot
from routeGen import routeGen
from sumoConfigGen import sumoConfigGen
from stripXML import stripXML
import multiprocessing as mp
from glob import glo... | )
model = './models/{}_{}/'.format(modelName, procID)
simport = 8812 + procID
N = 10000 # Last time to insert vehicle at (10800=3hrs)
stepSize = 0.1
CAVtau = 1.0
configFile = model + modelName + ".sumocfg"
# Configure the Map of controllers to be run
tlCo... | GPSVA': GPSControl.GPSControl,
'HVA1': HVA1.HybridVA1Control,
'HVA': HybridVAControl.HybridVAControl}
tlController = tlControlMap[tlLogic]
exportPath = '/hardmem/results/' + tlLogic + '/' + modelName + '/'
# Check if model copy for this process e... |
import pygame
music_on = 0
# Set up a button class for later usage
class Button:
def __init__(self, x, y, w, h, img):
self.x = x
self.y = y
self.w = w
self.h = h
self.img = img
self.surface = w * h
def buttonHover(self):
mouse = pygame.mo... | uttonGrayImg = pygame.image.load('img/QuitButtonGray.png')
backGroundImg = pygame.image.load('img/B | ackDrop.png')
buttonInstructionImg = pygame.image.load('img/ButtonInstructionWhite.png')
buttonInstructionGrayImg = pygame.image.load('img/ButtonInstructionGray.png')
buttonGameRulesImg = pygame.image.load('img/GameRulesWhite.png')
buttonGameRulesGrayImg = pygame.image.load('img/GameRulesGray.png')
... |
from fabric.api import hosts, run, sudo, local
from fabric.contrib.console import confirm
from fabric.utils import puts,warn
DEV_PROVISIONING_UUID = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
DEV_SIGN = "Mobi Ten"
DEV_APP_NAME = "Gym Mama"
DEV_APP_ID = 'com.mobiten.gym_mama'
TITANIUM_SDK_VERSION = '1.5.1'
IPHONE_SDK_VERS... | pplication\ Support/Titanium/mobilesdk/osx/%s/iphone/builder.py" % (TITANIUM_SDK_VERSION)
def coffee():
local("coffee --watch -o Resources/js/ --compile App/*.coffee ", False)
def debug():
local("%s simulator %s ./ %s %s %s" % (BUILDER,IPHONE_SDK_VERSION,DEV_APP_ID,DEV_APP_N | AME,DEVICE_FAMILY), False)
def device():
local("%s install %s ./ %s %s %s" % (BUILDER,IPHONE_SDK_VERSION, DEV_APP_ID, DEV_APP_NAME, DEV_PROVISIONING_UUID, DEV_SIGN))
def package():
print "nothing"
def clean():
if confirm("Clean will delete any files that is ignored by gitignore\nand also any files that not yet t... |
# -*- coding: utf-8 -*-
#-----------------------------------------------------------------------------
# OpenModes - An eigenmode solver for | open electromagnetic resonantors
# Copyright (C) 2013 David Powell
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version... | Y; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#----------------------... |
# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
# Copyright (C) 2011,2017 Nominum, Inc.
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose with or without fee is hereby granted,
# provided that the above copyright notice and this permis... | GENCE OR OTHER TORTIOUS ACTION, ARISING OUT
# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
"""DNS Wire Data Helper"""
import dns.exception
from ._compat import binary_type, string_types, PY2
# Figure out what consta | nt python passes for an unspecified slice bound.
# It's supposed to be sys.maxint, yet on 64-bit windows sys.maxint is 2^31 - 1
# but Python uses 2^63 - 1 as the constant. Rather than making pointless
# extra comparisons, duplicating code, or weakening WireData, we just figure
# out what constant Python will use.
cl... |
s
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
import shlex
# 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 th... | None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the... |
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False
# If true, `todo`... |
LDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXE... | if self.irc_nicknames:
for nickname in self.irc_nicknames:
if string in nickname.lower():
return True
for email in self.emails:
if string in email:
return True
return False
def matches_glob(self, glob_string):
if fn... | or nickname in self.irc_nicknames:
if fnmatch.fnmatch(nickname, glob_string):
return True
for email in self.emails:
if fnmatch.fnmatch(email, glob_string):
return True
return False
class Committer(Contributor):
def __init__(self, name... |
return
elif result._result.get('changed', False):
if delegated_vars:
msg = "changed: [%s -> %s]" % (result._host.get_name(), delegated_vars['ansible_host'])
else:
msg = "changed: [%s]" % result._host.get_name()
color = C.COLOR_CHANGED
... | vars['ansible_host'])
else:
msg = "ok: [%s]" % result._host.get_na | me()
color = C.COLOR_OK
self._handle_warnings(result._result)
if result._task.loop and 'results' in result._result:
self._process_items(result)
else:
if (self._display.verbosity > 0 or '_ansible_verbose_always' in result._result) and '_ansible_verbose_overr... |
"""Simple HTTP Server.
This module builds on BaseHTTPServer by implementing the standard GET
and HEAD requests in a fairly straightforward manner.
"""
__version__ = "0.6"
__all__ = ["SimpleHTTPRequestHandler"]
import os
import posixpath
import BaseHTTPServer
import urllib
import cgi
import sys
i... | = os.path.join(path, word)
if trailing_slash:
path += '/'
return path
def copyfile(self, source, outputfile):
"""Copy all data between two file objects.
The SOURCE argument is a file object open for reading
(or anything with a read() method) and the DE... | ange
the block size or perhaps to replace newlines by CRLF
-- note however that this the default server uses this
to copy binary data as well.
"""
shutil.copyfileobj(source, outputfile)
def guess_type(self, path):
"""Guess the type of a file.
Arg... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import tinymce.models
class Migration(migration | s.Migration):
dependencies = [
('cms', '0004_auto_20141112_1610'),
]
operations = [
migrations.CreateModel(
name='Text',
fields=[
('cmsplugin_ptr', models.OneToOneField(parent_link=True, auto_created=True | , primary_key=True, serialize=False, to='cms.CMSPlugin')),
('body', tinymce.models.HTMLField(verbose_name='body')),
],
options={
'abstract': False,
},
bases=('cms.cmsplugin',),
),
]
|
on
class TestModuleI18nService(ModuleStoreTestCase):
""" Test ModuleI18nService """
def setUp(self):
""" Setting up tests """
super(TestModuleI18nService, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.test_language = 'dummy language'
self.request = m... | 18n_service
def test_django_service_translation_works(self):
"""
Test django translation service works fine.
"""
| class wrap_ugettext_with_xyz(object): # pylint: disable=invalid-name
"""
A context manager function that just adds 'XYZ ' to the front
of all strings of the module ugettext function.
"""
def __init__(self, module):
self.module = module
... |
#! /usr/bin/env python
# -*- coding=utf-8 -*-
from distutils.core import setup
setup(
name='pythis',
version='1.4',
description='zen of python in Simplified Chinese',
url='https://github.com/vincentping/pythis',
author='Vincent Ping',
author_email='vincentping@gmail.com',
licen... | Common values are
# 3 - Alpha
# 4 - Beta
# 5 - Production/Stable
'Development Status :: 4 - Beta',
# Indicate who your project is intended for
'Intended Audience :: Developers',
'Topic :: Software Development',
# Specify the Python versions you support here. In particu... | dicate whether you support Python 2, Python 3 or both.
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python ... |
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
import sys
import json
from twit.models import User, Tweet, Mention, UserMention
from javanlp.models import Sentence, Sentiment
from javanlp.util import AnnotationException, annotate_document_with_sentiment
class Com... | parser.add_argument('--input', type=argparse.FileType('r'), help="Input file containing a json tweet on each line.")
def handle(self, *args, **options):
for tweet in Tweet.objects.all():
if Sentence.objects.filter(doc_id = tweet.id).exists(): continue
try:
with tra... | ment(tweet.id, tweet.text):
sentence.save()
sentiment.sentence = sentence
sentiment.save()
except AnnotationException:
pass # Couldn't annotate this sentence...
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""This module provides a function that knows what you mean"""
def know_what_i_me | an(wink, numwink=2):
""" Prints "Know what I mean?" with a variable number of winks.
Args:
wink (mixed): Represents a wink.
numwink (int): Wink multiplier. Defaults to 2.
Returns:
str: Arguments are contatenated in a sentence.
Examples:
>>> know_what_i_mean('wink')
... |
winks = (wink * numwink).strip()
nudges = ('nudge ' * numwink).strip()
retstr = 'Know what I mean? {}, {}'.format(winks, nudges)
return retstr
|
# Channel-Signals
connect_signal("topic", channelTopic_cb)
connect_signal("banlist", channelBanlist_cb)
# Maki signals
connect_signal("shutdown", makiShutdown_cb)
init = True
_add_servers()
def maki_disconnected_cb(sushi):
pass
@types (server = basestring)
def _setup_server(server):
tab = gui.tabs.... | are reported by maki.
"""
channels = sushi.channels(server_tab.name)
for channel in channels:
add = False
nicks, prefixes = sushi.channel_nicks(server_tab.name, channel)
tab = gui.tabs.search_tab(server_tab.name, channel)
if not tab:
tab = gui.tabs.create_channel(server_tab, channel)
add = True
... | tab.nickList.set_away(nick, sushi.user_away(server_tab.name, nick))
tab.topic = sushi.channel_topic(server_tab.name, channel)
tab.topicsetter = ""
if tab.is_active():
gui.set_topic(markup.markup_escape(tab.topic))
gui.mgmt.set_user_count(
len(tab.nickList),
tab.nickList.get_operator_count())
... |
"""
GravMag: Use the DipoleMagDir class to estimate the magnetization direction
of dipoles with known centers
"""
import numpy
from fatiando import mesher, gridder
from fatiando.utils import ang2vec, vec2ang, contaminate
from fatiando.gravmag import sphere
from fatiando.vis import mpl
from fatiando.gravmag.magdir impo... | gridder.scatter(area, 1000, z=-150, seed=0)
tf | = contaminate(sphere.tf(x, y, z, model, inc, dec), 5.0, seed=0)
# Give the centers of the dipoles
centers = [[3000, 3000, 1000], [7000, 7000, 1000]]
# Estimate the magnetization vectors
solver = DipoleMagDir(x, y, z, tf, inc, dec, centers).fit()
# Print the estimated and true dipole monents, inclinations and declina... |
from django.conf.urls import url
from . import views
from core.views import list_evidence_view, creat | e_evidence_view, list_submissions_view
app_name = 'core'
urlpatterns = [
# ex: /core/
url(r'^$', views.index, name='index'),
url(r'^(?P<corecomp_id>[0-9]+)/$', views.detail, name='detail'),
url(r'^submitted', views.submitted, name='submitted'),
url(r'^evidence_form/$', create_evidence_view, name='evid... |
] |
from haps.scopes.instance import InstanceScope
def test_get_object(some_class):
some_in | stance = InstanceScope().get_object(some_class)
assert isinstance(some_instance, some_class)
def test_get_multiple_objects(some_class):
scope = InstanceScope()
objects = {scope.get_object(s | ome_class) for _ in range(100)}
assert all(isinstance(o, some_class) for o in objects)
assert len({id(o) for o in objects}) == 100
|
#!/usr/bin/env python
import sys
from setuptools import setup, find_packages
from setuptools.command.test import test as TestCommand
import versioneer
class PyTest(TestCommand):
user_options = [('pytest-args=', 'a', "Arguments to pass to py.test")]
def initialize_options(self):
TestCommand.initializ... | 'path.py==7.3',
'pgcli==0.17.0',
'python-stdnum==1.1',
'SQLAlchemy-Searchable==0.9.3',
'SQLAlchemy-Utils==0.30.12',
],
extras_require={
'devel': [
'ansible',
'autopep8',
'flake8',
'ipython',
],
},
tests_requi... | 'testing.postgresql'
],
entry_points={
'console_scripts': [
'registry=registry.cli:main'
]
}
)
|
ved sucessfully.")
if prog.wasCanceled() :
return None
except :
QMessageBox.information(self, "Info", "Inventory was no saved.")
def invent_2 (self) :
prog=QProgressDialog("Compiling inventory...","Cancel",0,100,self)
prog.open()
allconn=curs... | try :
percent=((internal[0]/internal[1])*100)
except :
percent=100
prog.setValue(percent)
if prog.wasCanceled() :
return None
b=a.returnbook()
try :
fname=QFileDialog.getSaveFileName(self, 'Save File', '/... | tion(self, "Info", "Inventory was no saved.")
def new (self) :
self.prop=display.Ui_chem()
curs=cursor.connection()[0]
curs.execute('''SELECT MAX(id) FROM chem''')
maximum=curs.fetchone()[0]
maximum=int(maximum)
if maximum==-1 :
maximum=0
sel... |
"""
Ops for masked arrays.
"""
from typing import (
Optional,
Union,
)
import numpy as np
from pandas._libs import (
lib,
missing as libmissing,
)
def kleene_or(
left: Union[bool, np.ndarray],
right: Union[bool, np.ndarray],
left_mask: Optional[np.ndarray],
right_mask: Optional[np.nd... | right_mask)
mask = (left_mask & ~right_false) | (right_mask & ~left_false)
return result, mask
def raise_for_nan(value, method: str):
if lib.is_float(value) and np.isnan(value):
raise ValueError(f"Cannot perform logical '{method}' | with floating NaN")
|
"""
Classes to represent the default SQL aggregate functions
"""
import copy
from django.db.models.fields import IntegerField, FloatField
# Fake fields used to identify aggregate types in data-conversion operations.
ordinal_aggregate_field = IntegerField()
computed_aggregate_field = FloatField()
class Aggregate(obje... | aggregate into SQL.
* is_ordinal, a boolean indicating if the output of this aggregate
is an integer (e.g., a count)
* is_computed, a boolean indicating if this output of this aggregate
is a computed float (e.g., an average), regardless of the input
type.
... | egate sources back until you find an
# actual field, or an aggregate that forces a particular output
# type. This type of this field will be used to coerce values
# retrieved from the database.
tmp = self
while tmp and isinstance(tmp, Aggregate):
if getattr(tmp, 'is_... |
#
# 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... | meter | Value if some mandatory information
is missing on the node or on invalid inputs.
"""
driver_info = parse_driver_info(node)
client = drac_client.Client(**driver_info)
return client
def find_xml(doc, item, namespace, find_all=False):
"""Find the first or all elements in a ElementTree ob... |
# Author: Jason Lu
import urllib.request
from bs4 import BeautifulSoup
import time
req_header = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
#'Accept-Language': 'en-U... | eProcessor(cjar)
checked_num = 0
grasp_num = 0
for page in range(1, 3):
# req = urllib2.Request('http://www.xici.net.co/nn/' + str(page), None, req_header)
# html_doc = urllib2.urlopen(req, None, req_timeout).read()
req = urllib.request.Request('http://www.xici.net.co/nn/' + str(page))
req.add_header(... | ,
"Mozilla/5.0 (iPhone; CPU iPhone OS 10_3 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) CriOS/56.0.2924.75 Mobile/14E5239e Safari/602.1")
html_doc = urllib.request.urlopen(req).read().decode('utf-8')
# html_doc = urllib2.urlopen('http://www.xici.net.co/nn/' + str(page)).read()
... |
from contextlib import contextmanager
import pkg_resources |
import os
def local_stream(name):
return pkg_resources.resource_stream(__name__, name)
def local_file(name):
return pkg_resources.resource_filename(__name__, name)
@contextmanager
def Environ(**kwargs):
orig = os.environ.copy()
replace = set(kwargs.keys()) & set(orig.keys())
removes = set(kwa... | os.environ.update(kwargs)
yield
finally:
for r in removes:
os.environ.pop(r)
for r in replace:
os.environ[r] = orig[r]
class O(dict):
def __getattr__(self, key):
return self[key]
|
from django.db import models
# Django doesn't support big auto fields out of the box, see
# https://code.djangoproject.com/ticket/14286.
# This is a stripped down version of the BoundedBigAutoField from Sentry.
class BigAutoField(models.AutoField):
des | cription = "Big Integer"
def db_type(self, connection):
engine = connection.settings_dict['ENGINE']
if 'mysql' in engine:
return "bigint AUTO_INCREMENT"
elif 'postgres' in engine:
return "bigserial"
else:
raise NotImplemented
def get_related_... | tegerField"
class FlexibleForeignKey(models.ForeignKey):
def db_type(self, connection):
# This is required to support BigAutoField
rel_field = self.related_field
if hasattr(rel_field, 'get_related_db_type'):
return rel_field.get_related_db_type(connection)
return super(... |
from django.core.exceptions import ValidationError
from django.utils.deconstruct import deconstructible
from django.utils.translation import gettext_lazy as _
from django.core import validators
@deconstructible
class SkypeValidator:
message = _('Enter a valid URL.')
code = 'invalid'
... | code=self.code)
@deconstructible
class UrlValidator:
message = _('Enter a valid URL.')
code = 'invalid'
validators = [validators.URLValidator(), validators.EmailValidator(), SkypeValidator()]
def __call__(self, value):
def apply_validator(value):
def _apply_validator(validator):
... | except ValidationError as e:
skype_failed = True
return _apply_validator
if any(map(apply_validator(value), self.validators)):
raise ValidationError(self.message, code=self.code)
|
#-*-coding:utf-8-*-
from . import about_blueprint
from flask imp | ort render_template
@about_blueprint.route("/")
def about_index():
| return render_template("about.html") |
"""
Caching framework.
This package defines set of cache backends that all conform to a simple API.
In a nutshell, a cache is a set of values -- which can be any object that
may be pickled -- identified by string keys. For the complete API, see
the abstract BaseCache class in django.core.cache.backends.base.
Client ... | """
# Try to get the CACHES entry for the given backend name first
conf = settings.CACHES.get(backend, None)
if conf is not None:
args = conf.copy()
backend = args.pop('BACKEND')
location = args.pop('L | OCATION', '')
return backend, location, args
else:
# Trying to import the given backend, in case it's a dotted path
mod_path, cls_name = backend.rsplit('.', 1)
try:
mod = importlib.import_module(mod_path)
backend_cls = getattr(mod, cls_name)
except (At... |
class DinkyFish:
def monthsUntilCrowded(self, tankVolume, maleNum, femaleNum):
months = 0
while maleNum + femaleNum <= (tankVolume * 2):
minFishes = min(maleNum, femaleNum)
maleNum += minFishes
femaleNum | += minFishes
months += 1
return mont | hs |
SERV
C8 D8 S8 # / TYPES OF OBSERV
30.0000 INTERVAL
17 LEAP SECONDS
0 RCV CLOCK OFFS APPL
2017 7 ... | ersion=3.02,
glo_freq_nums=glo_freq_nums_v3,
)
@fixture
def obs_absent_slot_v3(glo_freq_nums_v3):
del glo_freq_nums_v3[4]
obs_file = StringIO(RNX_V3)
return ObsFileV3(
obs_file,
version=3.02,
glo_freq_nums=glo_freq_nums_v3,
)
@fixture(params=['obs_absent_slot_v2',... | .param)
@fixture
def nav_v2_stream():
content = '''\
2.01 GLONASS NAV DATA RINEX VERSION / TYPE
CCRINEXG V1.4 UX CDDIS 09-MAR-16 12:44 PGM / RUN BY / DATE
17 LEAP SECONDS
... |
'x-dvi'): 0.8,
http_headers.MimeType('text', 'x-c'): 1.0}),
("text/*, text/html, text/html;level=1, */*",
{http_headers.MimeType('text', '*'): 1.0,
http_headers.MimeType('text', 'html'): 1.0,
http_headers.MimeType('text', 'html', (('level', '1'),)): 1... | ndtripTest("Authorization", table)
def testCookie(self):
table = (
('name=value', [Cookie('name', 'value')]),
('"name"="value"', [Cookie('"name"', '"value"')]),
('name,"blah=value,"', [Cookie('name,"blah', 'value,"')]),
('name,"blah = value," ', [Cookie('n... | , ['name,"blah=value,"']),
("`~!@#$%^&*()-_+[{]}\\|:'\",<.>/?=`~!@#$%^&*()-_+[{]}\\|:'\",<.>/?", [Cookie("`~!@#$%^&*()-_+[{]}\\|:'\",<.>/?", "`~!@#$%^&*()-_+[{]}\\|:'\",<.>/?")]),
(
'name,"blah = value," ; name2=val2',
[Cookie('name,"blah', 'value,"'), Cookie('n... |
import os
from jflow.utils.importlib import import_module
from jflow.conf import global_settings
#If django is installed used the django setting object
try:
from django.conf import settings as django_settings
except:
django_settings = None
ENVIRONMENT_VARIABLE = "JFLOW_SETTINGS_MODULE"
cla... | gs)
for setting in dir(global_settings):
if setting == | setting.upper():
if not hasattr(self,setting):
setattr(self, setting, getattr(global_settings, setting))
return self
def get_settings():
settings_module = os.environ.get(ENVIRONMENT_VARIABLE,None)
if settings_module:
try:
mod =... |
# Written by Greg Ver Steeg (http://www.isi.edu/~gregv/npeet.html)
import scipy.spatial as ss
from scipy.special import digamma
from math import log
import numpy.random as nr
import numpy as np
import random
# continuous estimators
def entropy(x, k=3, base=2):
"""
The classic K-L k-nearest nei... | ]
if x is a one-dimensional scalar and we have four samples
"""
assert k <= len(x) - 1, "Set k smaller than num. samples - 1"
assert k <= len(xp) - 1, " | Set k smaller than num. samples - 1"
assert len(x[0]) == len(xp[0]), "Two distributions must have same dim."
d = len(x[0])
n = len(x)
m = len(xp)
const = log(m) - log(n-1)
tree = ss.cKDTree(x)
treep = ss.cKDTree(xp)
nn = [tree.query(point, k+1, p=float('inf'))[0][k] for point in ... |
# Generated by Django 3.1.7 on 2021-09-27 16:10
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('product', '0 | 016_product_company'),
]
operations = [
migrations.RemoveField(
model_name='product | ',
name='companies',
),
]
|
#!/usr/bin/env python
# coding=utf-8
"""
Distinct powers
Problem 29
Consider all integer combinations of ab for 2 ≤ a ≤ 5 and 2 ≤ b ≤ 5:
2^2=4, 2^3=8, 2^ | 4=16, 2^5=32
3^2=9, 3^3=27, 3^4=81, 3^5=243
4^2=16, 4^3=64, 4^4=256, 4^5=1024
5^2=25, 5^3=125, 5^4=625, 5^5=3125
If they are then placed in numerical order, with any repeats removed, we get
the following sequence of 15 distinct terms:
4, 8, 9, 16, 25, 27, | 32, 64, 81, 125, 243, 256, 625, 1024, 3125
How many distinct terms are in the sequence generated by ab for 2 ≤ a ≤ 100 and
2 ≤ b ≤ 100?
"""
from __future__ import print_function
def power_combinations(a, b):
for i in range(2, a):
for j in range(2, b):
yield i ** j
if __name__ == '__main__':... |
pplication is None:
err_fmt = 'There is no \'{0}\' application for {1}. Make sure what ' \
'correct application name has been passed. If application ' \
'doesn\'t exist you can create it on admin.pubnub.com.'
email = account.owner.email
module.fail_json(msg=er... | ion')
return block
def pubnub_event_handler(block, data):
"""Retrieve reference on target event handler from application model.
:type block: Block
:param block: Reference on block model from which reference on event
handlers should be fetched.
:type data: dict
:param dat... | it should be created or not.
:rtype: EventHandler
:return: Reference on initialized and ready to use event handler model.
'None' will be returned in case if there is no handler with
specified name and no request to create it.
"""
event_handler = block.event_handler(data['name... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import connection
from django.db import models, migrations
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.management import update_all_contenttypes
def create_notifications(apps, schema_editor):... | rstory.id""".format(content_type_id=ContentType.objects.get(model='userstory').id)
cursor = connection.cursor()
cursor.execute(sql)
class Migration(migrations.Migration):
dependencies = [
('notifications', '0004_watched'),
('userstories', '0009_remove_userstory_is_archived'),
]
o... | el_name='userstory',
name='watchers',
),
]
|
# Copyright 2014 Netflix, 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... | ect(environment, 'ec2')
where environment is ( | test, prod, dev )
s3 = sts_connect.connect(environment, 's3')
ses = sts_connect.connect(environment, 'ses')
:param account: Account to connect with (i.e. test, prod, dev)
:raises Exception: RDS Region not valid
AWS Tech not supported.
:returns: STS Connection Object for g... |
#!/usr/bin/env python
"""
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");... | d = format(
"{kinit_cmd_decommission} {hbase_cmd} --config {hbase_conf_dir} org.jruby.Main {region | _mover} unload {host}")
Execute(regiondrainer_cmd,
user=params.hbase_user,
logoutput=True
)
Execute(regionmover_cmd,
user=params.hbase_user,
logoutput=True
)
pass
pass
pass
pass
|
)
coal = db.Column("coal", db.String(20))
titanium = db.Column("titanium", db.String(20))
diamond = db.Column("diamond", db.String(20))
def __init__(self, id, user, password, saltWater, freshWater, elixir, pearl, iron, coal, titanium, diamond):
self.id = id
self.user = user
self.password = pa... | ter_by(user = g.user).all()
stringMessage = item + ' was added to inventory!'
return json.dumps( | {'stringMessage':stringMessage, 'newVal1':newVal1, 'newVal2':newVal2})
@app.route("/3d_test_1")
def test_1():
if g.user:
return render_template("3 |
''' Work of Cameron Palk '''
import sys
import pandas as pd
def main( argv ):
try:
csv_filepath = argv[ 0 ]
output_filepath = argv[ 1 ]
except IndexError:
print( "Error, usage: \"python3 coord_bounds.py <CSV> <output_file>\"" )
return
training_data = pd.read_c | sv( csv_filepath )
training_data[ 'clean_Latitude' ] = training_data[ training_data.Latitude > 47 ].Latitude
training_data[ 'clean_Longitude' ] = training_data[ training_data.Longitude < -122 ].Longitude
training_data.dropna()
print( training_data[ 'clean_Latitude' ] )
for axis in [ 'clean_Longitude', 'cle... | s,
min( training_data[ axis ] ),
max( training_data[ axis ] )
) )
#
if __name__=='__main__':
main( sys.argv[ 1: ] )
|
checking path
start: bool (False)
Whether to start running immediately; otherwise call stream.start()
explicitly.
Examples
--------
>>> source = Stream.filenames('path/to/dir') # doctest: +SKIP
>>> source = Stream.filenames('path/to/*.csv', poll_interval=0.500) # doctest: +SKIP
... | ation = Application([
| (self.path, Handler),
])
self.server = HTTPServer(application, **self.server_kwargs)
self.server.listen(self.port)
def start(self):
"""Start HTTP server and listen"""
if self.stopped:
self.loop.add_callback(self._start_server)
self.stopped ... |
# -*- coding: utf-8
#------------------------------------------------------------------#
__author__ = "Xavier MARCELET <xavier@marcelet.com>"
#------------------------------------------------------------------#
import json
import sys
import cherrypy
from xtd.core import logger, config
from xtd.co... | : True,
"description" : | "TLS CA-Certificate file"
},{
"name" : "tlscert",
"default" : None,
"valued" : True,
"description" : "TLS Certificate file"
},{
"name" : "tlskey",
"default" : None,
"valued" : True,
"description" : "TLS key file"
}])
def _ini... |
\n'
runString +='CUT:N 2j 0 0 \n'
return runString
def getSrcString(self):
"""
Returns the MCNPX formated source string
"""
srcString = 'c -------------------------- Source Defination --------------... | ""
for l in loading:
for p in polymers:
for pos in positions:
| RunCylinder(l,p,pos)
def createInputPlotDecks():
positions = list()
positions.append(((4.23,10.16),(4.23,-10.16)))
positions.append(((4.23,7.625),(4.23,0),(4.23,-7.625)))
#positions.append(((4.23,9.15),(4.23,3.05),(4.23,-3.05),(4.23,-9.15)))
for pos in positions:
m = CylinderRP... |
import errors
def validate_num_arguments_eq(num_args):
"""Validate that the number of supplied args is equal to some number"""
def decorator(func):
def wrapped_func(*args, **kwargs):
if len(args[1]) != num_args:
raise errors.InvalidArgumentError
else:
... | ater than to some number"""
def decorator(func):
def wrapped_func(*args, **kwargs):
if len(args[1]) < num_args:
raise errors.InvalidArgumentError
else:
func(*args, **kwargs)
return wrapped_func
return decorator
def parse_index(lst, id):
... | = int(id) - 1
if idx > len(lst) - 1 or idx < 0:
raise errors.InvalidItemError
return idx
|
# ChangeFile
# A class which represents a Debian change file.
# Copyright 2002 Colin Walters <walters@gnu.org>
# This file 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... | '
def __init__(self):
DpkgControl.DpkgParagraph.__init__(self)
self._logger = logging.getLogger("mini-di | nstall")
self._file = ''
def load_from_file(self, filename):
self._file = filename
f = SignedFile.SignedFile(open(self._file))
self.load(f)
f.close()
def getFiles(self):
return self._get_checksum_from_changes()['md5']
def _get_checksum_from_changes(self):
... |
##############################################################################
#
# OSIS stands for Open Student Information System. It's an application
# designed to manage the core business of higher education institutions,
# such as universities, faculties, institutes and professional schools.
# The core ... | it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even t... | S FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# A copy of this license - GNU General Public License - is available
# at the root of the source code of this program. If not,
# see http://www.gnu.org/licenses/.
#
########################################################... |
ok so this essentially groups up some tokens to make later parsing easier,
# when it encounters brackets it will recurse and then unrecurse when RecursionStopIteration is raised.
if token == ')':
raise RecursionStopIteration() # Should be recursive so this should work
elif token == ... | return lhs in rhs
class FuncAttrExists(Func):
FUNC = 'attribute_exists'
def __init__(self, attribute):
self.attr = attribute
d | ef expr(self, item):
return self.attr in item.attrs
class FuncAttrNotExists(Func):
FUNC = 'attribute_not_exists'
def __init__(self, attribute):
self.attr = attribut |
import cPickle
import os.path as osp
from smqtk.representation.code_index import CodeIndex
from smqtk.utils import SimpleTimer
__author__ = "paul.tunison@kitware.com"
class MemoryCodeIndex (CodeIndex):
"""
Local RAM memory based index with an optional file cache
"""
@classmethod
def is_usable(... | added to this index.
This cache file is a pickle serialization.
:type file_cache: None | str
"""
| super(MemoryCodeIndex, self).__init__()
self._num_descr = 0
self._file_cache = file_cache
# Mapping of code to a dictionary mapping descrUUID->Descriptor
#: :type: dict[collections.Hashable, dict[collections.Hashable, smqtk.representation.DescriptorElement]]
self._table =... |
from issues.models import ReportedLink, ReportedUser
from issues.serializers import ReportedLinkSerializer | , ReportedUserSerializer
class ReportedLinkAPI(object):
serializer_class = ReportedLinkSerializer
def get_queryset(self):
return ReportedLink.objects.all()
class Repo | rtedLinkSelfAPI(object):
def get_queryset(self):
return ReportedLink.objects.filter(reporter=self.request.user)
def pre_save(self, obj):
obj.reporter = self.request.user
class ReportedUserAPI(object):
serializer_class = ReportedUserSerializer
def get_queryset(self):
return ... |
supports pre-generated makefiles and assembly files.
# Developers don't need an installation of Perl anymore to build Python. A svn
# checkout from our svn repository is enough.
#
# In Order to create the files in the case of an update you still need Perl.
# Run build_ssl in this order:
# python.exe build_ssl.py Releas... | = os.path.dirname(perl) + \
os.pathsep + \
os.en | viron["PATH"]
run_configure(configure, do_script)
if debug:
print("OpenSSL debug builds aren't supported.")
#if arch=="x86" and debug:
# # the do_masm script in openssl doesn't generate a debug
# # build makefile so we generate it here:
... |
import pytest
from webtest import TestApp
from pyramid.config import Configurator
from pyramid.testing import DummyRequest
from pyramid.authorization import ACLAuthorizationPolicy
from pyramid.authentication import AuthTktAuthenticationPolicy
def make_app(config):
return TestApp(config.make_wsgi_app())
@pytest.... | config.scan('resource_get_renderer')
app = make_app(config)
r = app.get('/')
assert r.content_type == 'text/plain'
assert r.unicode_body == 'hello'
def test_add_controller():
config = Configurator()
config.scan('controller')
app = make_app(config)
app.post('/engage')
def test_nested_... | _toolkit/issues/12
config = Configurator()
config.scan('controller')
app = make_app(config)
app.post('/resource/engage')
def test_controller_default_to_json_renderer():
config = Configurator()
config.scan('controller')
app = make_app(config)
r = app.post('/engage')
assert r.content... |
import urllib
from askbot.deps.django_authopenid.util import OAuthConnection
class Twitter(OAuthConnection):
def __init__(self):
super(Twitt | er, self).__init | __('twitter')
self.tweet_url = 'https://api.twitter.com/1.1/statuses/update.json'
def tweet(self, text, access_token=None):
client = self.get_client(access_token)
body = urllib.urlencode({'status': text})
return self.send_request(client, self.tweet_url, 'POST', body=body)
|
return action
def _get_optional_actions(self):
return [action
for action in self._actions
if action.option_strings]
def _get_positional_actions(self):
return [action
for action in self._actions
if not action.option_strings]
#... | else:
msg = _('ignored explicit argument %r')
raise ArgumentError(action, msg % explicit_arg)
# if the action expect exactly one argument, we've
# successfully matched the option; exit the loop
... | ount == 1:
stop = start_index + 1
args = [explicit_arg]
action_tuples.append((action, args, option_string))
break
# error if a double-dash option did not use the
# explicit argument
... |
# 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
# distribu... | ext.use_stubs and ext._links_to_dynamic:
d, fn = os.path.split(filename)
return os.path.join(d, 'dl-' + fn)
return filename
def build_extension(self, ext):
_compiler = self.compiler
try:
force_shared = False
if isinstance(ext, _Library... | self.compiler = self.shlib_compiler
force_shared = ext.force_shared and not build_ext.use_stubs
if force_shared:
self.compiler.link_shared_object = sh_link_shared_object.__get__(self.compiler)
build_ext._build_ext.build_extension(self, ext)... |
# !/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
try:
from PyQt4.QtGui import QApplication, QKeySequence
except ImportError:
| from PyQt5.QtWidgets import QApplication
from PyQt5.QtGui import QKeySequ | ence
from pygs import QxtGlobalShortcut
def hotkeyBinding():
SHORTCUT_SHOW = "Ctrl+Alt+S" # Ctrl maps to Command on Mac OS X
SHORTCUT_EXIT = "Ctrl+Alt+F" # again, Ctrl maps to Command on Mac OS X
def show_activated():
print("Shortcut Activated!")
app = QApplication([])
... |
import unittest
from mock import patch, | call
from chaser.controller import MotorController, LEFT_KEY, RIGHT_KEY, UP_KEY, DOWN_KEY, MotorInputError
class ControllerTestCase(unittest.TestCase):
@patch('chaser.controller.gpio')
def test_init(self, io):
io.OUT = True
calls = [call(4, True), call(17, True), call(24, True), call(25, True... | io.reset_mock()
controller.shut_down()
calls = [call(4, False), call(17, False), call(24, False), call(25, False)]
io.output.assert_has_calls(calls)
@patch('chaser.controller.gpio')
def test_left(self, io):
controller = MotorController()
controller.left()
calls =... |
# Copyright 2019 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 applicable law or agreed to in writing, ... | ticGraphProperty):
def __init__(self, label, cls):
super().__init__(label)
self._cls = cls
def from_node(self, obj, value):
if value is None:
return None
return self._cls(obj._graph, guid=value.guid)
def to_node(self, | value):
# Value should already by a GuidNode.
return value
def make_guid_property(wrapped):
def __init__(self, label):
GuidProperty.__init__(self, label, wrapped)
return type(
wrapped.__name__ + "Property",
(GuidProperty,),
{
"__init__": __init__,
... |
#!/usr/bin/python
# encoding: utf-8
# filename: outroTipoDeProducaoBibliografica.py
#
# scriptLattes V8
# Copyright 2005-2013: Jesús P. Mena-Chalco e Roberto M. Cesar-Jr.
# http://scriptlattes.sourceforge.net/
#
#
# Este programa é um software livre; você pode redistribui-lo e/ou
# modifica-lo dentro dos termos d... | ANO : " + str(self.ano) + "\n"
s += "+NATUREZA : " + self.natureza.encode('utf8','replace') + "\n"
s += "+ite | m : " + self.item.encode('utf8','replace') + "\n"
return s
|
from os.path import abspath
import wptools
from mycroft.messagebus.message import Message
from mycroft.skills.LILACS_knowledge.services import KnowledgeBackend
from mycroft.util.log import getLogger
__author__ = 'jarbas'
logger = getLogger(abspath(__file__).split('/')[-2])
class WikidataService(KnowledgeBackend):... | # parse for distant child of
node_data["description"] = page.description
# direct child of
node_data["what"] = page.what
# data fields
| node_data["data"] = page.wikidata
# related to
# TODO parse and make cousin/child/parent
node_data["properties"] = page.props
# id info source
dict["wikidata"] = node_data
except:
logger.error("Could no... |
# -*- coding: utf-8 -*-
from __future__ import print_function
from IPython import get_ipython
from IPython.display import (
display,
Javascript,
HTML,
)
from IPython.core import magic_arguments
from IPython.core.magic import (
Magics,
magics_class,
cell_magic,
)
import pyjade
__version_info_... | lf, shell):
super(JadeMagics, self).__init__(shell)
@cell_magic
@magic_arguments.magic_arguments()
@magic_arguments.argument(
"var_name",
default=None,
nargs="?",
help="""Name of local variable to set to parsed value"""
)
def jade(self, line, cell):
l... | "notebook/js/codecell",
"codemirror/mode/jade/jade"
],
function(cc){
cc.CodeCell.options_default.highlight_modes.magic_jade = {
reg: ["^%%jade"]
}
}
);
... |
# This is to see that the t | otal memory usage doesn't increase with time
# i.e. no leakage / link between consecutive usages of hsp.
# This will run for ever, to be monitored by the printout and some external monitor.
def t():
from | guppy import hsp
while 1:
import guppy.heapy.UniSet
import gc
reload( guppy.heapy.UniSet )
hp = hsp()
x = None
x = hp.heap()
print x
gc.collect()
print x[0]
print x[1]
print x[2]
gc.collect()
print x&dict
|
cks']:
hcid = self.store_healthcheck(health_check)
if hcid:
ids.append(hcid)
#remove healthchecks that no longer exist in route53
if len(ids):
self.db.execute("delete from route53_healthchecks where id not in " + " ({0})".format(",".join("{0}".format(... | s)
# since we are pulling a complete list every time, we do not need records that exist prior to this load step #TODO should possibly implement more atomic way of doing this
self.db.execute("truncate route53_records")
self.dbconn.commit()
for z in zones:
| self.logger.debug(z)
recs = z.get_records()
zone_id = recs.hosted_zone_id
# if identifier is set, then the record is one of WRR, latency or failover. WRR will include a value for weight,
# latency will include a value for region, and failover will not include ... |
es
from test import test_doctest, sample_doctest
from test.test_importhooks import ImportHooksBaseTestCase
from test.test_cmd_line_script import temp_dir, _run_python, \
_spawn_python, _kill_python, \
_make_test_script, \
... | with test.test_support.check_warnings(*deprecations):
for obj in known_good_tests:
_run_object_doctest(obj, test_zipped_doctest)
def test_doctest_main_issue4197(self):
test_src = textwrap.dedent("""\
class Test:
">>> 'li... | |
'pyComtrade instance created!'
def clear(self):
"""
Clear the internal (private) variables of the class.
"""
self.filename = ''
self.filehandler = 0
# Station name, identification and revision year:
self.station_name = ''
self.rec_dev_id = ''... | ]
self.Aph = []
self.Accbm = []
self.uu = []
self.a = []
self.b = []
self.skew = []
self.min = []
self.max = []
self.primary = []
self.secondary = []
self.PS = []
# Digital channel information:
self.Dn = []
s... | m = []
self.y = []
# Line frequency:
self.lf = 0
# Sampling rate information:
self.nrates = 0
self.samp = []
self.endsamp = []
# Date/time stamps:
# defined by: [dd,mm,yyyy,hh,mm,ss.ssssss]
self.start = [00,00,0000,00,00,0.0]
sel... |
__version__ | = "0.1.3"
get_version = lambda: | __version__ |
# highSpeedManuveringCapacitorNeedMultiplierPostPercentCapacitorNeedLocationShipModulesRequiringHighSpeedManuvering
#
# Used by:
# Implants named like: Eifyr and Co. 'Rogue' High Spee | d Maneuvering HS (6 of 6)
# Skill: High Speed Maneuvering
type = "passive"
def handler(fit, contain | er, context):
level = container.level if "skill" in context else 1
fit.modules.filteredItemBoost(lambda mod: mod.item.requiresSkill("High Speed Maneuvering"),
"capacitorNeed", container.getModifiedItemAttr("capacitorNeedMultiplier") * level)
|
# This code is part of Ansible, but is an independent component.
# This particular file snippet, and this file snippet only, is BSD licensed.
# Modules you write using this snippet, which is embedded dynamically by Ansible
# still belong to the author of the module, and may assign their own license
# to the complete wo... | code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the | documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAI... |
iles,
ask_vault_pass,
create_new_password,
auto_prompt=auto_prompt)
for vault_id_slug in vault_ids:
vault_id_name, vault_id_value = CLI.split_vault_id(vault_id_slug)
i... | string_types):
options.listofhosts = string_types.split(',')
| return options
"""
# process tags
if hasattr(options, 'tags') and not options.tags:
# optparse defaults does not do what's expected
options.tags = ['all']
if hasattr(options, 'tags') and options.tags:
tags = set()
for tag_set in options.... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
fro | m nltk.parse.generate import generate, demo_grammar
from nltk import CFG
grammar = CFG.fromstring(demo_grammar)
print(grammar)
for sentence in generate(grammar, n=10):
print(' '.join(sentence))
for sentence in generate(grammar, depth=4):
print(' '.join(sentence))
print | (len(list(generate(grammar, depth=3))))
print(len(list(generate(grammar, depth=4))))
print(len(list(generate(grammar, depth=5))))
print(len(list(generate(grammar, depth=6))))
print(len(list(generate(grammar))))
|
from itertools im | port | imap, chain
def set_name(name, f):
try:
f.__pipetools__name__ = name
except (AttributeError, UnicodeEncodeError):
pass
return f
def get_name(f):
from pipetools.main import Pipe
pipetools_name = getattr(f, '__pipetools__name__', None)
if pipetools_name:
return pipetool... |
# -*- coding: utf-8 -*-
# __init__.py
#
# Copyright (C) 2007 - Guillaume Desmottes
#
# 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, or (at your option)
# any later version.
#... | OURCE_GROUP_CATEGORY_FIXED)
theme = gtk.icon_theme_get_default()
rb.append_plugin_source_path(theme, "/icons/")
width, height = gtk.icon_size_lookup(gtk.ICON_SIZE_LARGE_TOOLBAR)
icon = rb.tr | y_load_icon(theme, "jamendo", width, 0)
self.source = gobject.new (JamendoSource,
shell=shell,
entry_type=self.entry_type,
plugin=self,
icon=icon,
source_group=group)
shell.register_entry_type_for_source(self.source, self.entry_type)
shell.append_source(self.source, None) ... |
(self._parent._play._ds, '_line_number'):
path = "%s:%s" % (self._parent._play._ds._data_source, self._parent._play._ds._line_number)
return path
def get_name(self, include_rol | e_fqcn=True):
''' return the name of the task '''
if self._role:
role_name = self._role.get_name(include_role_fqcn=include_role_fqcn)
if self._role and self.name and role_name not in self.name:
return "%s : %s" % (role_name, self.name)
elif self.name:
... | n "%s" % (self.action,)
def _merge_kv(self, ds):
if ds is None:
return ""
elif isinstance(ds, string_types):
return ds
elif isinstance(ds, dict):
buf = ""
for (k, v) in iteritems(ds):
if k.startswith('_'):
c... |
from django.conf import settings
def posthog_configurations(request):
return { |
'POSTHOG_API_KEY': settings.POSTHOG_API_KEY,
| 'POSTHOG_API_URL': settings.POSTHOG_API_URL,
}
|
import parole
from parole.colornames import colors
from parole.display import interpolateRGB
import pygame, random
import sim_creatures, main, random
from util import *
description = \
"""
This guy should really look into another line of work.
"""
nagLines = [
'*sigh*',
"It's not been the same 'round... |
]
class NPCClass(sim_creatures.NPC):
def __init__(self):
sim_creatures.NPC.__init__(
self,
'retired miner', # name
parole.map.AsciiTile('@', colors['Gray']), # symbol, color
11, # str
8, # dex
11, # con
11, # per
... | , # spd
1, # level
description=description,
)
parole.info('New NPC: retiredminer.')
main.schedule.listen('enter tile', self)
def listen(self, event):
super(NPCClass, self).listen(event)
if random.random() < 0.9:
return
if not vis... |
whil | e 1:
arr=input().split(' ')
k=arr[0]
n=arr[1]
if k=='0' and n=='0':
break
ans=int(int(k)**int(n))
print | (int(ans))
|
"""Ensure credentials are preserved through the authorization.
The Authorization Code Grant will need to preserve state as well as redirect
uri and the Implicit Grant will need to preserve state.
"""
from __future__ import absolute_import, unicode_literals
import json
import mock
from .test_utils import get_query_cre... | alidate_code.side_effect = self.set_state('xyz')
_, body, _ = self.web.create_token_response(token_uri,
body='grant_type=authorization_code&code=%s' % code)
self.assertEqual(json.loads(body)['state'], 'xyz')
# implicit grant
h, _, s = self.mobile.create_authorization_r | esponse(
auth_uri + 'token', scopes=['random'])
self.assertEqual(s, 302)
self.assertIn('Location', h)
self.assertEqual(get_fragment_credentials(h['Location'])['state'][0], 'xyz')
def test_redirect_uri_preservation(self):
auth_uri = 'http://example.com/path?redirect_u... |
fIFFT(x, rank)
def testGrad_Simple(self):
with self._fft_kernel_label_map():
for rank in VALID_FFT_RANKS:
for dims in xrange(rank, rank + 2):
re = np.ones(shape=(4,) * dims, dtype=np.float32) / 10.0
im = np.zeros(shape=(4,) * dims, dtype=np.float32)
self._checkGradComp... | r("invalid rank")
def _npIFFT(self, x, rank, fft_length=None):
if rank == 1:
return np.fft.irfft2(x, s=fft_length, axes=(-1,))
elif rank == 2:
return np.fft.irfft2(x, s=fft_length, axes=(-2, -1))
elif rank == 3:
return np.fft.irfft2(x, s=fft_length, | axes=(-3, -2, -1))
else:
raise ValueError("invalid rank")
def _tfFFTForRank(self, rank):
if rank == 1:
return spectral_ops.rfft
elif rank == 2:
return spectral_ops.rfft2d
elif rank == 3:
return spectral_ops.rfft3d
else:
raise ValueError("invalid rank")
def _tfIFF... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
faq_en = '''
<p>
<b>Why statistics on the site does not coincide with the statistics in the game?</b>
</p>
<p>
Algorithms collection statistics IL2 stats differs from statistics in-game. As a consequence of these... | е заработанных пилотом очков, среднего количества очков за жизнь и за час. Такой способ расчета рейтинга учитывает не только количественные, но и качественные показатели пилота, а так же сводит в единую систему оценки пилотов разных специализаций.<br>
Как именно рассчитывается рейтинг:<br>
1) вычисляем сколько игрок за... | а один час налета - очки / налет часов = ОЧ<br>
3) вычисляем рейтинг по формуле: (ОС * ОЧ * очки) / 1000
</p>
<br>
<p>
<b>Почему мой профиль не отображается в общей таблице игроков?</b>
</p>
<p>
В статистике включена опция которая исключает неактивных игроков из общего рейтинга. По умолчанию игроки неактивные более 7 ... |
lds.S3EnabledImageField', [], {'max_length': '100', 'thumb_options': "{'upscale': True, 'crop': 'smart'}", 'null': 'True', 'blank': 'True'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '2048', 'blank': 'True'}),
'video': ('django.db.models.fields.related.ForeignKey', [], {... | blank': 'True'}),
'writelock_time': ('django.db.models.fields.DateTimeField', [], {'null': 'True'})
},
'videos.video': {
'Meta': {'object_name': 'Video'},
'allow_community_edits': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
... | 'True', 'blank': 'True'}),
'complete_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'description': ('django.db.models.fields.TextField', [], ... |
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 28 19:18:58 2015
@author: alex_
"""
# General Imports
import matplotlib as mpl
mpl.use('TkAgg') # Force mpl backend not to use qt. Else we have a conflict.
import numpy as np
import pickle
import time
from datetime import datetime
from collections import namedtuple
impor... | s):
"""
Method to be called to run the preprocessor.
Times the process and saves output where applicable.
"""
dt_start = datetime.now()
tim_start = time.time()
map_output = self._preprocessor()
tim_duration = time.time() - tim_start
map_output.me... | elf.filepath)
return map_output
|
im | port os
import sys
import getopt
import json
def main(argv):
"""Specify input to generator with:
-s : save path
-f : model_def folder
"""
opts, args = getopt.getopt(argv,"s:f:")
save_location = "models/ddpg_models/"
model_def_folder = ""
print(opts)
for opt, arg in opts:
... | er,'config.json')).read()
config_dict = json.loads(json_data)
print(config_dict)
exec('')
os.system("script2.py 1")
if __name__ == "__main__":
main(sys.argv[1:])
|
#40/40
#Part 1: Terminology (15 points) --> 15/15
#1 1pt) What is the symbol "=" used for?
#to assign and store values to and in variables
# 1pt
#
#2 3pts) Write a technical definition for 'function'
#a named sequence of calculations which takes input and returns output
# 3pts
#
#3 1pt) What does the keyword "return" d... | dius and multiples by 2 to get diameter
def sum_three(x, y, z): #takes three valu | es and adds them
return x + y + z
#1pt for header line
#1pt for parameter names
#1pt for return value
#1pt for correct output format
#3pt for correct use of format function
def output(d1, d2, d3, total):
return """
Circle Diameter
C1 {}
C2 {}
C3 {}
Totals {}
""".format(d1, d2, d3, total)
#1pt header line
#... |
try:
from pygments.lexer import bygroups, include, using
from pygments.lexers.agile import PythonLexer, PythonTracebackLexer
from pygments.token import Text, Name, Number, Generic, String, Operator
except ImportError: # pragma: no cover
# this is for nose coverage which does a recursive import on the p... | (r"^((?:-+>)?)( +)(\d+)(.+\n)",
| bygroups(Generic.Error, Text, Number, using(XPythonLexer))),
# variable continuation
(r"^([ ]+)('[^']+')(: )(.*)([,}]?\n)",
bygroups(Text, String, Name.Operator, using(XPythonLexer), Text)),
# variable
(r"^([ ]+)((?:g:)?)(\**... |
# coding:utf-8
import logging
import regex as re
import email.quoprimime
import email.base64mime
from base64 import b64encode
from flanker.mime.message import charsets, errors
log = logging.getLogger(__name__)
#deal with unfolding
foldingWhiteSpace = re.compile(r"(\n\r?|\r\n?)(\s*)")
def unfold(value):
"""
... | mime encoding
Returns (charset, decoded-string)
"""
if encoding == 'q':
return (charset, email.quoprimime.header_decode(str(value)))
elif encoding == 'b':
# Postel's law: add missing padding
paderr = len(value) % 4
if paderr:
value += '==='[:4 - paderr]
... | )
elif not encoding:
return (charset, value)
else:
raise errors.DecodingError(
"Unknown encoding: {0}".format(encoding))
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# function: 剪切更改图片尺寸大小
import os
import os.path
import sys
import argparse
from PIL import Image
def CutImage(filein, fileout, width, height, type):
'''
# 从左上角开始 剪 | 切 width*height的图片
filein: 输入图片
fileout: 输出图片
width: 输出图片宽度
height:输出图片高度
type:输出图片类型(png, gif, jpeg...)
'''
img = Image.open(file | in)
out = img.crop((1, 1, width, height))
out.save(fileout, type)
if __name__ == "__main__":
argc = len(sys.argv)
cmdargs = str(sys.argv)
parser = argparse.ArgumentParser(description="Tool for change the picture to custom size")
parser.add_argument('-f', '--file', required=True, help='the file... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.