prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
#!/usr/bin/env python
# Small wrapper script for weeder2, which needs the FreqFiles directory
# where it is executed. This script allows running weeder2 from anywhere.
import os
import sys
import argparse
import subprocess as sp
# Weeder install dir
weeder_dir = os.path.realpath(os.path.join(os.path.dirname(__file__),... | weeder2"))
weeder_exe = "weeder2"
weeder_help = sp.check_output(
os.path.join(weeder_dir, weeder_exe),
stderr=sp.STDOUT).decode()
parser = argparse.ArgumentParser()
parser.add_argument("-f", dest="fname")
args, | unknownargs = parser.parse_known_args()
if not args.fname:
print(weeder_help)
sys.exit()
fname = os.path.abspath(args.fname)
rest = " ".join(unknownargs)
cmd = "./{} -f {} {}".format(weeder_exe, fname, rest)
sys.exit(sp.call(cmd, shell=True, cwd=weeder_dir))
|
e = ElementTree.SubElement(
xml_role_instances, 'RoleInstance')
xml_role_instance_id = ElementTree.SubElement(
xml_role_instance, 'Id')
xml_role_instance_id.text = self._get_role_instance_id()
xml_role_properties = ElementTree.SubElement(
xml_role_instance, 'P... | parse_xml=False)
@property
def can_post_rdp_cert_thumbprint(self):
return True
def post_rdp_cert_thumbprint(self, thumbprint):
properties = {ROLE_PROPERTY_CERT_THUMB: thumbprint | }
self._post_role_properties(properties)
def _get_hosting_environment(self):
config = self._get_role_instance_config()
return self._wire_server_request(config.HostingEnvironmentConfig.cdata)
def _get_shared_config(self):
config = self._get_role_instance_config()
return ... |
e_ref, 'disk_format': 'vhd'}
conn.finish_migration(self.context, self.migration, instance,
dict(base_copy='hurr', cow='durr'),
network_info, image_meta, resize_instance=True)
self.assertEqual(self.called, True)
self.assertEqual(self.fak... | 'netmask': '255.255.255.0'}],
'label': 'fake',
| 'mac': 'DE:AD:BE:EF:00:00',
'rxtx_cap': 3})]
# Resize instance would be determined by the compute call
image_meta = {'id': instance.image_ref, 'disk_format': 'vhd'}
conn.finish_migration(self.context, self.migration, instance,
... |
# Copyright (C) 2014 - Oscar Campos <oscar.campos@member.fsf.org>
# This program is Free Software see LICENSE file for details
import os
import json
import platform
from collections import defaultdict
from anaconda_go.lib import go
from anaconda_go.lib.plugin import typing
cachepath = {
| 'linux': os.path.join('~', '.local', 'share', 'anaconda', 'cache'),
'darwin': os.path.join('~', 'Library', 'Cache', 'anaconda'),
'windows': os.path.join(os.getenv('APPDATA') or '~', 'Anaconda', 'Cache')
}
cache_directory = os.path.expanduser(
cachepath.get(platform.system().lower())
)
PACKAGES_CA | CHE = defaultdict(lambda: [])
def append(package: typing.Dict) -> None:
"""Append the given package into the cache
"""
global PACKAGES_CACHE
if not package_in_cache(package):
PACKAGES_CACHE[go.GOROOT].append(package)
def package_in_cache(package: typing.Dict) -> bool:
"""Look for the g... |
ABILITY, SATISFACTORY QUALITY, 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/>.
"""Module that implements the Hash Queue machinery."""... | elf.queue = OrderedDict()
| |
html = NOTEBOOK_DIV.render(
plot_script = script,
plot_div = div,
)
return encode_utf8(html)
def _use_widgets(plot_objects):
from .models.widgets import Widget
for o in plot_objects:
if isinstance(o, Document):
if _use_widgets(o.roots):
return Tr... | tems(resources, docs_json, render_items, title, we | bsocket_url,
custom_models, js_resources=None, css_resources=None,
template=FILE, template_variables={}, use_widgets=True):
if resources:
if js_resources:
warn('Both resources and js_resources provided. resources will override js_re... |
# -*- coding: utf-8 -*-
from test_settings import Settings
class TestCase(Settings):
def test_sidebar(self):
# Ayarlari yapiyor.
self.do_settings()
# Genel'e tikliyor.
self.driver.find_element_by_css_selector(
'li.ng-binding:nth-child(3) > a:nth-child(1) > span:nth-chil... | _by_css_selector('#ikamet_ilce').send_keys('Merkez')
# Ikametgah Adresine deger yolluyor.
self.driver.find_element_by_css_selector('#ikamet_adresi').send_keys('balim sokak')
# Posta Kodu'na deger yolluyor.
self.driver.find_element_by_css_selector('#posta_kodu').send_keys('11000')
... | 26286816')
# Kaydet'e tikliyor
self.driver.find_element_by_css_selector('button.btn-danger:nth-child(1)').click()
|
low=self.flow, label="Gender")
age = RuleSet.objects.get(flow=self.flow, label="Age")
# categories should be in the same order as our rules, should have correct counts
result = Value.get_value_summary(ruleset=color)[0]
self.assertEquals(3, len(result['categories']))
self.assertF... | ssage(self.flow, "red", contact=self.c1, restart_participants=True)
# should change our male/female breakdown since c1 now no longer has a gender
result = Value.get_value_summary(ruleset=gender)[0]
self.assertEquals(2, len(result[' | categories']))
self.assertResult(result, 0, "Male", 1)
self.assertResult(result, 1, "Female", 2)
# back to a full flow
run5 = self.run_color_gender_flow(self.c1, "blue", "male", "16")
# ok, now segment by gender
result = Value.get_value_summary(ruleset=color, filters=[]... |
_box_tab"})
a= len(mp_boxes)
for box in mp_boxes:
if(box.text == "Total Lifetime Grosses"):
div_content= box.findNext('div')
trs = div_content.find_all('tr')
for tr in trs:
tds = tr.find_all('td')
if len(... | arrData['Percentage of Total Gross'] = DS_tr_content.text.strip()
| elif DS_tr_title == "Widest\xa0Release:" or DS_tr_title == "Widest Release:":
DS_tr_content = DS_tr.td.findNext('td')
if DS_tr_content:
arrData['Widest Release'] = DS_tr_content.text.strip() # 14.
elif DS... |
create the listCompleter function with a list to complete
from.
"""
def listCompleter(text, state):
line = readline.get_line_buffer()
if not line:
return [c + " " for c in ll][state]
else:
return [c + " " for c in ll if c.st... |
m.edit_field(selection)
print
return m.new_value
def ask_details_for_type(model_type, ask_only_required=True, help_map={}):
'''
Asks fo | r user input to create an object of a specified type.
If the type is registered in a model/builder map, the function associated
with this type is used to create the object instead of the auto-generated
query.
'''
if MODEL_MAP.get(model_type, None):
func = MODEL_MAP[model_type]
ret... |
import urllib2, json, time, sys
from datetime import date, datetime
from dateutil.rrule import rrule, DAILY
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-f", dest="fahrenheit", action | ="store", default=False, type="string", help="C | onvert to FAHRENHEIT")
parser.add_option("-e", dest="end", action="store", default=False, type="string", help="START date")
parser.add_option("-s", dest="start", action="store", default=False, type="string", help="END date")
parser.add_option("-t", dest="token", action="store", default=False, type="string", help="Weath... |
import logging
def | init_logger():
formatter = logging.Formatter('%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]')
logger = logging.getLogger('redberry')
logger.setLevel(logging.DEBUG)
console = logging.StreamHandler()
console.setFormatter(formatter)
logger.addHan | dler(console)
|
from __future__ import absolute_import, unicode_literals
import pytest
from case import Mock, patch
from vine import promise
from amqp.abstract_channel import AbstractChannel
from amqp.exceptions import AMQPNotImplementedError, RecoverableConnectionError
from amqp.serialization import dumps
class test_AbstractChann... | elf.content)
self.content.body.decode.side_effect = KeyError()
self.c.dispatch_method((50, 61), 'payload', self.content)
def test_dispatch_method__unknown_method(self):
with pytest.raises(AMQPNotImplementedError):
self.c. | dispatch_method((100, 131), 'payload', self.content)
def test_dispatch_method__one_shot(self):
self.method.args = None
p = self.c._pending[(50, 61)] = Mock(name='oneshot')
self.c.dispatch_method((50, 61), 'payload', self.content)
p.assert_called_with((50, 61), self.content)
def... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2018-01-24 07:34
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
depende | ncies = [
('appauth', '0016_userprofile_numq'),
]
operations = [
migrations.AddField(
model_name='userprofile',
name='exp_data',
field=models.TextField(default='{}'),
),
| ]
|
#!/usr/bin/python
# vim: set expandtab tabstop=4 shiftwidth=4:
# -*- coding: utf-8 -*-
# gen_cacert <http://rhizomatik.net/>
# Python functions for generate a X509 CA certificate
#
# Copyright (C) 2010 duy at rhizomatik dot net
#
# This program is free software; you can redistribute it and/or modify
# it under the te... | -o, --organization certificate organizationName
-u, --organizationalunit certificate organizationalUnitNam
-e, --email certificate emailAddress
"""
def _version():
"""
Display a formatted version string for the module
"""
print """%(__app__)s %(__version__)s
%(__co... | n(argv):
"""
Create an x509 CA certificate and save it as PEM file
@param CN: certificate commonName
@param C: certificate countryName
@param O: certificate organizationName
@param OU: certificate organizationalUnitName
@param Email: certificate emailAddress
@type CN: string
@ty... |
import six
from unittest import TestCase
from dark.reads import Read, Reads
from dark.score import HigherIsBetterScore
from dark.hsp import HSP, LSP
from dark.alignments import (
Alignment, bestAlignment, ReadAlignments, ReadsAlignmentsParams,
ReadsAlignments)
class TestAlignment(TestCase):
"""
Tests... | rs(self):
"""
An alignment must have the expected attributes.
"""
alignment = Alignment(45, 'title')
self.assertEqual('title', alignment.subjectTitle)
self.assertEqual(45, alignment.subjectLength)
def testNoHspsWhenCreated(self):
"""
An alignment must... | t.hsps))
def testAddHsp(self):
"""
It must be possible to add an HSP to an alignment.
"""
alignment = Alignment(45, 'title')
alignment.addHsp(HSP(3))
self.assertEqual(HSP(3), alignment.hsps[0])
class TestReadAlignments(TestCase):
"""
Tests for the dark.alig... |
ode, bbox
def findBlobs(self, img):
rects= []
cnts= self.findContours(img)
for c in cnts:
c= c.reshape(-1, 2)
if len(c) < 4:
continue
arcl= cv2.arcLength(c, True)
approx= cv2.approxPolyDP(c, 0.02 * arcl, True)
appro... | oes not exists..."
exit()
logger.debug(VisualRecord("letters", [img], fmt = "jpg"))
txt = f.first(img)
e = timer()
logger.debug('tiempo de exe %s', (e-s))
print txt
print 'tiempo de exe %s', (e-s)
#~ def prepare_laplace_highpass(self, img, scale=True):
#~ tinit= timer | ()
#~ gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
#~ self.gauss_gray = cv2.GaussianBlur(gray, (5, 5), 0)
#~ self.lap_gray = cv2.Laplacian(self.gauss_gray, cv2.CV_8U)
#~ min_val= np.min(self.gauss_gray)
#~ max_val= np.max(self.gauss_gray)
#~ dif= max_val - min_val
... |
__all__ = ["wordlists", "roles", "bnc", "processes", "verbs",
"uktous", "tagtoclass", "queries", "mergetags"]
from corpkit.dictionaries.bnc import _get_bnc
from corpkit.dictionaries.process_types import processes
from corpkit.dictionaries.process_types import verbs
from corpkit.dictionaries.roles import ro | les
from corpkit.dictionaries.wordlists import wordlists
from corpkit.dictionaries.queries import queries
from corpkit.dictionaries.word_transforms import taglemma
from corpkit.dictionaries.word_transforms import mergetags
from corpkit.dictionaries.word_transforms import usa_convert
roles = roles
wordlists = wordlists... | erbs = verbs |
from django.contrib import admin
from simulation.models import SimulationStage, SimulationStageMatch, SimulationStageMatchResult
class SimulationStageAdmin(admin.ModelAdmin):
list_display = ["number", "created_at"]
list_filter = | ["created_at"]
class SimulationStageMatchAdmin(admin.Mo | delAdmin):
list_display = ["stage", "order", "raund",
"cat", "rat", "won", "created_at"]
list_filter = ["stage", "created_at"]
search_fields = ["cat", "rat"]
readonly_fields = ["won", "cat_password", "rat_password", "system_password"]
class SimulationStageMatchResultAdmin(admin.ModelAdmin):
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import scipy as sp
#Nome do arquivo em que está os dados da posição
arq = 'CurvaGiro/pos.dat'
#Limites dos eixos
v = [-10,1000, 0, 1000]
#Título eixo x
xl = r'y metros'
#Título do eixo y
yl = r'x | metros'
x = sp.genfromtxt('CurvaGiro/pos.dat')
a = plt.plot(x[:,2], x[:,1], 'k-')
plt.grid(True, 'both', color = '0 | .8', linestyle = '--', linewidth = 1)
plt.axis(v)
plt.xlabel(xl)
plt.ylabel(yl)
plt.show(a)
|
#!/usr/bin/env python3
import os
import re
import itertools
from functools import reduce
from .version import __version__
sep_regex = re.compile(r'[ \-_~!@#%$^&*\(\)\[\]\{\}/\:;"|,./?`]')
def get_portable_filename(filename):
path, _ = os.path.split(__file__)
filename = os.path.join(path, filename)
retur... | + word[1]]]
elif len(word) == 2 and word[0] == word[1]:
return [[word[0]]]
| if word[:2] == 'aa':
return [['A'] + i for i in variations(word[2:])]
elif word[:2] == 'ee':
return [['i'] + i for i in variations(word[2:])]
elif word[:2] in ['oo', 'ou']:
return [['u'] + i for i in variations(word[2:])]
elif word[:3] == 'kha':
return \
[['kha'] ... |
put' function.
# (i.e., __builtin__.raw_input for Python 2.7, builtins.input for Python 3)
_sys_raw_input = Any()
_sys_eval_input = Any()
def __init__(self, **kwargs):
super(IPythonKernel, self).__init__(**kwargs)
# Initialize the InteractiveShell subclass
self.shell = self.she... | release.version
| language_info = {
'name': 'python',
'version': sys.version.split()[0],
'mimetype': 'text/x-python',
'codemirror_mode': {'name': 'ipython',
'version': sys.version_info[0]},
'pygments_lexer': 'ipython%d' % (3 if PY3 else 2),
'nbconvert_exporter'... |
# -*- coding: utf-8 -*-
#
# phys_pkg.py
#
# Copyright (C) 2013 Steve Canny scanny@cisco.com
#
# This module is part of opc-diag and is released under the MIT License:
# http://www.opensource.org/licenses/mit-license.php
"""Interface to a physical OPC package, either a zip archive or directory"""
import os
import shut... | PC packages in either Zip or expanded directory form.
|PhysPkg| objects are iterable, generating a (uri, blob) 2-tuple for each
item in the package.
"""
def __init__(self, blobs, root_uri):
super(PhysPkg, self).__init__()
self._blobs = blobs
self._root_uri = root_uri
def __i... | (self._blobs.items())
@staticmethod
def read(path):
"""
Return a |PhysPkg| instance loaded with contents of OPC package at
*path*, where *path* can be either a regular zip package or a
directory containing an expanded package.
"""
if os.path.isdir(path):
... |
try:
import pkg_resources
p | kg_resources.declare_namespace(__name__)
except ImportError:
import pkgutil
__path__ = pkgutil.extend_path(__path__, __name__)
from ckanext.geonetwork.ha | rvesters.geonetwork import GeoNetworkHarvester
from ckanext.geonetwork.harvesters.utils import GeoNetworkClient
|
# Copyright 2017 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
#
# https://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.
# =====================================... | ======
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
# pylint: disable=g-bad-import-order
from isl import augment
from isl import test_util
from isl import util
flags = tf.flags
test = tf.test
lt = tf.contrib.labeled_tensor
FLAG... |
import pytest
from webdriverwrapper.exceptions import InfoMessagesException
def test_check_info_messages(driver_in | fo_msgs):
with pytest.raises(InfoMessagesException) as excinfo:
driver_info_msgs.check_infos(expected_info_messages=('some-info',))
def test_check_expected_info_messages(driver_info_msgs):
driver_info_msgs.check_infos(expected_info_messages=('some-info', 'another-info'))
def test_check_allowed_info_... | ):
driver_info_msgs.check_infos(expected_info_messages=('some-info',), allowed_info_messages=('another-info',))
|
from yowsup.structs import ProtocolEntity, ProtocolTreeNode
from .iq import IqProtocolEnti | ty
class PingIqProtocolEntity(IqProtocolEntity):
'''
Receive
<iq type="get" xmlns="urn:xmpp:ping" from="s.whatsapp.net" id="1416174955-ping">
</iq>
Send
<iq type="get" xmlns="w:p" to="s.whatsapp.net" id="1416174955-ping">
| </iq>
'''
def __init__(self, _from = None, to = None, _id = None):
super(PingIqProtocolEntity, self).__init__("urn:xmpp:ping" if _from else "w:p", _id = _id, _type = "get", _from = _from, to = to)
|
#!/usr/bin/env python3
import math, logging, threading, concurrent.futures
import numpy
import simplespectral
from soapypower import threadpool
logger = logging.getLogger(__name__)
class PSD:
"""Compute averaged power spectral density using Welch's method"""
def __init__(self, bins, sample_rate, fft_windo... | self._sample_rate = sample_rate
self._fft_window = fft_window
self._fft_overlap = fft_overlap
self._fft_overlap_bins = math.floor(self._bins * self._fft_overlap)
self._crop_factor = crop_factor
self._log_scale = log_scale
self._remove_dc = remove_dc
self._detrend... | max_workers=max_threads,
max_queue_size=max_queue_size,
thread_name_prefix='PSD_thread'
)
self._base_freq_array = numpy.fft.fftfreq(self._bins, 1 / self._sample_rate)
def set_center_freq(self, center_freq):
"""Set center frequency and clear averaged PSD data"""
... |
internal function for counting total reads
required params:
:param data, A dictionary containing seqrun ids a key an read counts as values
:param seqrun_list, A list of sequencing runs
'''
try:
data['run_count'] = 0
if 'total_read' not in data:
data['total_read']=0
if len(seqrun_list) >1... | onvert data frame to json
column_order=tuple(column_list)
return description,interme | diate_data,column_order
except:
raise
def _modify_seqrun_data(data_series,seqrun_col,flowcell_col,path_col):
'''
An internal method for parsing seqrun dataframe and adding remote dir path
required columns: seqrun_igf_id, flowcell_id
:param seqrun_col, Column name for sequencing run id, default seqrun_igf... |
"""
Classes for using robotic or other hardware using Topographica.
This module contains several classes for constructing robotics
interfaces to Topographica simulations. It includes modules that read
input from or send output to robot devices, and a (quasi) real-time
simulation object that attempts to maintain a cor... | ventProcessor
from imagen.image import GenericImage
from playerrobot import Camer | aDevice, PTZDevice
class CameraImage(GenericImage):
"""
An image pattern generator that gets its image from a Player
camera device.
"""
camera = param.ClassSelector(CameraDevice,default=None,doc="""
An instance of playerrobot.CameraDevice to be used
to generate images.""")
def ... |
#!/usr/bin/env python
'''
A/V control for System76 laptop using Unity
'''
import os
from execute import returncode
# check for the existenc | e of /dev/video0 which is used currently for webcam
webcam = lambda: os.path.exists('/dev/video0') == False
def webcam_toggle():
if webcam():
returncode('sudo /sbin/modprobe uvcvideo')
else:
returncode('sudo /sbin/modprobe -rv uvcvideo')
# use the amixer application to glean the status of the m... | le = lambda: returncode("amixer set Capture toggle")
def main():
print "Mic muted ? {0}, Webcam off ? {1}".format(microphone(), webcam())
if __name__ == '__main__':
main()
|
calendar
from django.utils.dates import MONTHS, MONTHS_3, MONTHS_AP, WEEKDAYS, WEEKDAYS_ABBR
from django.utils.tzinfo import LocalTimezone
from django.utils.translation import ugettext as _
from django.utils.encoding import force_unicode
re_formatchars = re.compile(r'(?<!\\)([aAbBcdDfFgGhHiIjlLmMnNOPrsStTUuwWyYzZ])')
... | urs and minutes, with minutes left off if they're
zero.
Examples: '1', '1:30', '2:05', '2'
Proprietary extension.
"""
if self.data.minute == 0:
return self.g()
return u'%s:%s' % (self.g(), self.i())
def g(self):
"Hour, 12-hour format without le | ading zeros; i.e. '1' to '12'"
if self.data.hour == 0:
return 12
if self.data.hour > 12:
return self.data.hour - 12
return self.data.hour
def G(self):
"Hour, 24-hour format without leading zeros; i.e. '0' to '23'"
return self.data.hour
def h(self... |
rgs += ['-e', '%s=%s' % (k, v)]
docker_env = {
'DOCKERFILE_DIR': dockerfile_dir,
'DOCKER_RUN_SCRIPT': 'tools/run_tests/dockerize/docker_run.sh'
}
jobspec = jobset.JobSpec(
cmdline=['tools/run_tests/dockerize/build_and_run_docker.sh'] +
docker_args,
environ=docker_env,... | harp/run_distrib_test%s.sh' %
self.script_suffix,
copy_rel_path='test/distrib')
elif self.platform == 'macos':
return create_jobspec(self.name, [
'test/distrib/csharp/run_distrib_test%s.sh' % self.script_suffix
],
... | # Use double leading / as the first occurrence gets removed by msys bash
# when invoking the .bat file (side-effect of posix path conversion)
environ = {
'MSBUILD_EXTRA_ARGS': '//p:Platform=x64',
'DISTRIBTEST_OUTPATH': 'DistribTest\\bi... |
pass
else:
log.error("Unknown scheme: {scheme}", scheme=scheme)
if credFactory:
wireEncryptedCredentialFactories.append(credFactory)
if schemeConfig.get("AllowedOverWireUnencrypted", False):
wireUnencryptedCredentialFactories.append(credF... | th, error=e)
log.info("Setting up root resource: {cls}", cls=rootResourceClass)
root = rootResourceClass(
config.DocumentRoot,
principalCollections=(principalCollection,),
)
root.putChild("principals", principalCollection)
if config.EnableCalDAV:
root.putChild("calendars",... | nabled and config.EnableSearchAddressBook:
root.putChild(config.DirectoryAddressBook.name, directoryBackedAddressBookCollection)
# /.well-known
if config.EnableWellKnown:
log.info("Setting up .well-known collection resource")
wellKnownResource = SimpleResource(
principa... |
f | rom __future__ import print_function
from .patchpi | pette import PatchPipette
|
"""Models for the util app. """
import cStringIO
import gzip
import logging
from config_models.models import ConfigurationModel
from django.db import models
from django.utils.text import compress_string
from opaque_keys.edx.django.models import CreatorMixin
logger = logging.getLogger(__name__) # pylint: disable=inv... | try:
val = value.encode('utf').decode('base64')
zbuf = cStringIO.StringIO(val)
| zfile = gzip.GzipFile(fileobj=zbuf)
ret = zfile.read()
zfile.close()
except Exception as e:
logger.error('String decompression failed. There may be corrupted data in the database: %s', e)
ret = value
return ret
class CompressedTextField(CreatorMixin, models.TextField):
... |
"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.
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATI... | default: 300
state:
description:
- Specifies the state of the component on the BIG-IP system.
default: present
choices: ['absent', 'present']
terminate_on_bye:
description:
- Enables or disables the termination of a conne | ction when a BYE transaction finishes.
default: enabled
choices: ['disabled', 'enabled']
user_via_header:
description:
- Enables or disables the insertion of a Via header specified by a system administrator.
requirements:
- BIG-IP >= 12.0
- ansible-common-f5
- f5-sdk
... |
to wait for the response, in
seconds. A value of zero (the default) means wait forever. If
the timeout expires before the response is received an exception
will be raised."
compress:
required: False
description:
- "A boolean flag indicating i... | state: absent
name: myvm
always:
- name: Always revoke the SSO token
ovirt_aut | h:
state: absent
ovirt_auth: "{{ ovirt_auth }}"
# When user will set following environment variables:
# OVIRT_URL = https://fqdn/ovirt-engine/api
# OVIRT_USERNAME = admin@internal
# OVIRT_PASSWORD = the_password
# User can login the oVirt using environment variable instead of variables
# in y... |
"""
Application entry point
"""
def main():
pass
if __name__ == "__main__":
# delegates to main_debug during construction
| try:
import main_debug
main_debug.main()
except Impor | tError:
main()
|
"""
XING OAuth1 backend, docs at:
http://psa.matiasaguirre.net/do | cs/backends/xing.html
"""
from social.backends.oauth import BaseOAuth1
class XingOAuth(BaseOAuth1):
"""Xing OAuth authentication backend"""
name = 'xing'
AUTHORIZATION_U | RL = 'https://api.xing.com/v1/authorize'
REQUEST_TOKEN_URL = 'https://api.xing.com/v1/request_token'
ACCESS_TOKEN_URL = 'https://api.xing.com/v1/access_token'
SCOPE_SEPARATOR = '+'
EXTRA_DATA = [
('id', 'id'),
('user_id', 'user_id')
]
def get_user_details(self, response):
... |
#!/usr/bin/env python
import p | ytest
from pyxenon_snippets import slurm_queues_getter_with_p | rops
def test_slurm_queues_getter_with_props():
slurm_queues_getter_with_props.run_example()
|
"""
byceps.services.shop.article.dbmodels.article
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from datetime import datetime
from decimal import Decimal
from typing import Optional
from sqlalchemy.ext.hybrid import... | _id = db.Column(db.UnicodeText, db.ForeignKey('shops.id'), index=True, nullable=False)
ite | m_number = db.Column(db.UnicodeText, unique=True, nullable=False)
_type = db.Column('type', db.UnicodeText, nullable=False)
description = db.Column(db.UnicodeText, nullable=False)
price = db.Column(db.Numeric(6, 2), nullable=False)
tax_rate = db.Column(db.Numeric(3, 3), nullable=False)
available_fro... |
# Copyright 2017 Battelle Energy Alliance, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | ("precompute", contentType=InputTypes.StringType,
descr=r"""Whether to use a precomputed Gram matrix to speed up calculations.
For sparse input this option is always True to preserve sparsity.""", default='auto'))
spec... | he path used to compute the residuals in
the cross-validation""", default=1000))
specs.addSub(InputData.parameterInputFactory("eps", contentType=InputTypes.FloatType,
descr=r"""The machine-precision regularization in t... |
import numpy as np
from bokeh.io import curdoc, show
from bokeh.models import ColumnDataSource, Grid, LinearAxis, Plot, Triangle
N = 9
x = np.linspace(-2, 2, N)
y = x**2
sizes = np.linspace(10, 20, N)
source = ColumnDataSource(dict(x=x, y=y, sizes=sizes))
plot = Plot(
title=None, plot_width=300, plot_height=300... |
yax | is = LinearAxis()
plot.add_layout(yaxis, 'left')
plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker))
plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker))
curdoc().add_root(plot)
show(plot)
|
#!/usr/bin/env python
import pynotify
''' |
No purpose here other than creating a callable library for system n | otifications
'''
class message:
def __init__(self, messagex):
pynotify.init('EventCall')
m = pynotify.Notification("RSEvent Notification", "%s" % messagex)
m.show()
|
# -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2015-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Admin model views for records."""
import json
from flask import flash
from flask... | return True
record = Record(mode | l.json, model=model)
record.delete()
db.session.commit()
except SQLAlchemyError as e:
if not self.handle_view_exception(e):
flash(_('Failed to delete record. %(error)s', error=str(e)),
category='error')
db.session.rollback()
... |
import hashlib as md5
class Palette:
def __init__(self, palette={}, colors=[]):
self.job_status_palette = {
'Received': '#D9E7F8',
'Checking': '#FAFAFA',
'Staging': '#6190CD',
'Waiting': '#004EFF',
'Matched': '#FEF7AA',
| 'Running': '#FDEE65',
'Stalled': '#BC5757',
'Completed': '#00FF21',
'Done': '#238802',
'Failed': '#FF0000',
'failed': '#FF0000',
'Killed': '#111111'
}
self.job_minor_status_palette = {
"AncestorDepth Not Found" : '#BAA312',
'Application Finished Wi... | tegrity Check Failed' : '#BC1143',
'Can not get Active and Banned Sites from JobDB' : '#84CBFF',
'Chosen site is not eligible' : '#B4A243',
'Error Sending Staging Request' : '#B4A243',
'Exceeded Maximum Dataset Limit (100)' : '#BA5C9D',
'Exception During Execution' : '#AA240C',
... |
]"}),
'start': ('django.db.models.fields.DateTimeField', [], {}),
'team': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'sessions'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to'... | {'object_name': | 'Thread'},
'closed': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'deleted': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'downvotes': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
'forum': ('django.d... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.db import connection
from django.utils.translation import ugettext as _
from modoboa.lib.exceptions import InternalError
def db_table_exists(table):
"""Check if table exists."""
return table in conn... | e_names()
def db_type(cname="default"):
"""Return the type of the *default* database
Supported values : 'postgres', 'mysql', 'sqlite'
:param str cname: connection name
:return: a string or None
"""
if cname not in settings.DATABASES:
raise InternalError(
_("Connection to ... | l", "sqlite"]:
if settings.DATABASES[cname]["ENGINE"].find(t) != -1:
return t
return None
|
from base import *
class Te | st (TestBase):
def __init__ (self):
Test | Base.__init__ (self, __file__)
self.name = "Broken header entry III"
self.expected_error = 200
self.request = "GET / HTTP/1.0\r\n" +\
"Entry:value\r\n"
|
tern_cache = {}
def groups_for_host(self, host):
if host in self._hosts_cache:
return self._hosts_cache[host].get_groups()
else:
return []
def groups_list(self):
if not self._groups_list:
groups = {}
for g in self.groups:
... | results.append(x)
self._subset = results
def remov | e_restriction(self):
""" Do not restrict list operations """
self._restriction = None
def is_file(self):
""" did inventory come from a file? """
if not isinstance(self.host_list, basestring):
return False
return os.path.exists(self.host_list)
def basedir(sel... |
= None
self.audio.terminate()
except ImportError:
pass
class WavFile(AudioSource):
def __init__(self, filename_or_fileobject):
if isinstance(filename_or_fileobject, str):
self.filename = filename_or_fileobject
else:
self.filename = None
self.wav_f... | r
def read(self, size = -1):
if size == -1:
return self.wav_reader.readframes(self.wav_reader.getnframes())
return self.wav_reader.readframes(size)
class AudioData(object):
def __init__(self, rate, data):
self.rate = rate
self.data = data
class Reco... | language = "fr-FR", key = "AIzaSyBOti4mM-6x9WDnZIjIeyEU21OpBXqWBgw"):
self.key = key
self.language = language
self.energy_threshold = 1500 # minimum audio energy to consider for recording
self.pause_threshold = 0.8 # seconds of quiet time before a phrase is considered complete
s... |
.arg_scopes_map['resnet_v1_152'] = resnet_arg_scope
nets_factory.arg_scopes_map['resnet_v1_200'] = resnet_arg_scope
nets_factory.arg_scopes_map['resnet_v2_50'] = resnet_arg_scope
nets_factory.arg_scopes_map['resnet_v2_101'] = resnet_arg_scope
nets_factory.arg_scopes_map['resnet_v2_152'] = resnet_arg_sco... | logging.basicConfig(filename='train-%s-%s.log' % (FLAGS.backbone, dat | etime.datetime.now().strftime('%Y%m%d-%H%M%S')),level=logging.DEBUG, format='%(asctime)s %(message)s')
if FLAGS.model:
try:
os.makedirs(FLAGS.model)
except:
pass
if FLAGS.finetune or FLAGS.vgg:
print_red("finetune, using RGB with vgg pixel means")
COLORS... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 2 1 | 7:52:19 2017
Author: Peiyong Jiang : jiangpeiyong@impcas.ac.cn
Function:
______________________________________________________
"""
from numpy.random import multivariate_normal as npmvn
from numpy import diag
def PartGen(emitT,numPart):
meanPart=[0.,0.,0.,0.,0.,0.]
covPart=diag([emitT[0],emitT[0],emitT[1],... | Part,covPart,numPart).T
return x,xp,y,yp,z,zp
|
create_temporary_bill(legisinfo_id=resid,
number=match.group(0), session=self.hansard.session)
except Exception, e:
print "Related bill search failed for callback %s" % resid
print repr(e)
return string
return u'<bill id="%d" na... | me'):
pass
# Heading
elif c.name == 'h2':
c = c.next
if not parsetools.isString( | c): raise ParseException("Expecting string right after h2")
t.setNext('heading', parsetools.titleIfNecessary(parsetools.tameWhitespace(c.string.strip())))
# Topic
elif c.name == 'h3':
top = c.find(text=r_letter)
#if not parsetools.isSt... |
# 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 WARRANTIE... | 'ctx1'
mock_client().get_job.side_effect = exceptions.NotFound('not found')
mock_dataset = bigquery.DatasetReference('project-1', 'dataset-1')
mock_client().dataset.return_value = mock_dataset
mock_client().get_dataset.return_value = bigquery.Dataset(mock_dataset)
mock_response =... | 'query': 'SELECT * FROM table_1'
}
}
}
mock_client().query.return_value.to_api_repr.return_value = mock_response
result = query('SELECT * FROM table_1', 'project-1', 'dataset-1', 'table-1')
self.assertEqual(mock_response, result)
moc... |
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.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 License, or
# (at your option) an... | else:
host = Host(name=hn, port=port)
self.hosts[hn] = host
if len(tokens) > 1:
for t in tokens[1:]:
if t.startswith('#'):
break
try:
... | raise errors.AnsibleError("Invalid ini entry: %s - %s" % (t, str(e)))
host.set_variable(k, self._parse_value(v))
self.groups[active_group_name].add_host(host)
# [southeast:children]
# atlanta
# raleigh
def _parse_group_children(self):
... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2016 Eugene Frolov <eugene@frolov.net.ru>
#
# All Rights Reserved.
#
# License | d under the Apache License, Version 2.0 (the "Lic | ense"); 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" BAS... |
e 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 the implied warranty of
# MERCHANTABILITY or ... | 'name': gap_line.functionality.name[0:100] + " [TEST]",
| 'code_gap': gap_line.code or "",
'project_id': project_id,
'notes': ustr(gap_line.functionality.description or gap_line.functionality.name),
'partner_id': partner_id,
'org_pl... |
#!/usr/bin/env python
"""Contains the Data Model for a cool Resource.
"""
__author__ = "Sanjay Joshi"
__copyright__ = "IBM Copyright 2017"
__credits__ = ["Sanjay Joshi"]
__license__ = "Apache 2.0"
__version__ = "1.0"
__mai | ntainer__ = "Sanjay Joshi"
__email__ = "joshisa@us.ibm.com"
__status__ = "Prototype"
schema = {
'url': 'corpora/ada_diabetes/concepts',
'schema': {
'cloudhost': {
'type': 'string',
'default': 'Powered by IBM Bluemix and Python Eve'
}, |
'base16': {
'type': 'string',
'default': '######'
},
'hex': {
'type': 'string',
'default': '##-##-##'
},
'organization': {
'type': 'string',
'default': 'Doh!MissingOrg'
}
},
'allow_unknown': ... |
import astra
def gpu_fp(pg, vg, v):
v_id = astra.data2d.create('-vol', vg, v)
rt_id = astra.data2d.create('-sino', pg)
fp_cfg = astra.astra_dict('FP_CUDA')
fp_cfg['VolumeDataId'] = v_id
fp_cfg['ProjectionDataId'] = rt_id
fp_id = astra.algorithm.create(fp_cfg)
astra.algorithm.run(fp_id)
out = astra.data... | t_cfg)
astra.algorithm.run(sirt_id, n_iters)
out = astra.data2d.get(v_id)
astra.algorithm.delete(sirt_id)
astra.data2d. | delete(rt_id)
astra.data2d.delete(v_id)
return out
|
# Copyright 2019 The Cirq Developers
#
# 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 ... | path == current_path[:-1]:
# Move up in tree
current_path.pop()
else:
# Jump somewhere else in the tree
current_path[:] = path[:-1]
def handle_error(import_from, import_to):
if import_from[: depth + 1] != import_to[: depth + 1]:
| msg = f"{'.'.join(import_from)} imported {'.'.join(import_to)}"
fail_list.append(msg)
print(f'ERROR: {msg}')
# Import wrap_module_executions without importing cirq
orig_path = list(sys.path)
project_dir = os.path.dirname(os.path.dirname(__file__))
cirq_dir = os.path.jo... |
from flask import jsonify
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import Table, Column, Integer, ForeignKey
from src.webservice.base import Base
from src.webservice._action import Action
db = SQLAlchemy()
Base.query = db.session.query_property()
class Input(Base):
__tablename__ = 'tbl_InputPin'
... | output = []
for input in inputs:
actions = []
actions_id = []
for action in input.actions:
actions.append(action.name)
actions_id.append(action.id)
input_data = {'id': input.id, 'name': input.name, 'device_name': input.parent... | _between_clicks': input.time_between_clicks, 'actions': actions}
output.append(input_data)
db.session.commit()
return jsonify({'response': output})
@staticmethod
def update_input(request):
data = request.get_json()
input = db.session.query(Input).filter_by(id=data['i... |
from distutils.core import setup
setup(
name='Chroma',
version='0.2.0',
author='Seena Burns',
author_email='hello@seenaburns.com',
url='https://github.com/seenaburns/Chroma',
license=open('LICENSE.txt').read(),
description='Color handling made simple.',
long_description=open('README.rst... | d Audience :: Dev | elopers',
'Natural Language :: English',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7'
),
)
|
self.data))
else:
raise ValueError(
"must specify beta0 or provide an estimater with the model"
)
else:
self.beta0 = _conv(beta0)
self.delta0 = _conv(delta0)
# These really are 32-bit integers in FORTRAN (gfortran), even ... | self.partol = partol
self.maxit = maxit
self.stpb = _conv(stpb)
self.stpd = _conv(st | pd)
self.sclb = _conv(sclb)
self.scld = _conv(scld)
self.work = _conv(work)
self.iwork = _conv(iwork)
self.output = None
self._check()
def _check(self):
""" Check the inputs for consistency, but don't bother checking things
that the builtin function... |
# -*- encoding: utf-8 -*-
################################################################################
# #
# Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol #
# ... | #
# it under the terms of the GNU Affero General Public License as publ | ished 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,... |
#
# [The "BSD license"]
# Copyright (c) 2012 Terence Parr
# Copyright (c) 2012 Sam Harwell
# Copyright (c) 2014 Eric Vergnaud
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redis... | .s0 is None:
return None
with StringIO() as buf:
for s in self.dfa.sortedStates():
n = 0
if s.edges is not None:
n = len(s.edges)
for i in range(0, n):
t = s.edges[i]
if t is not N... | buf.write(u"-")
buf.write(label)
buf.write(u"->")
buf.write(self.getStateString(t))
buf.write(u'\n')
output = buf.getvalue()
if len(output)==0:
return None
else:... |
import requests
import json
class DisqusAPI(object):
"""
Lightweight solution to make API calls to Disqus:
More info:
https://disqus.com/api/docs
"""
def __init__(self,
api_key,
| api_secret,
version='3.0',
formats='json'
):
self.api_key = api_key
self.api_secret = api_secret
self.version = version
self.formats = formats
def get(s | elf, method, **kwargs):
"""
Make get requests to retrieve data from Disqus
"""
endpoint = 'https://disqus.com/api/{version}/{method}.{formats}'
url = endpoint.format(
version=self.version,
method=method.replace('.', '/'),
formats=self.formats
... |
#!/usr/bin/env python2
# Copyright (c) 2015 The Aureus Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# Test mulitple rpc user config option rpcauth
#
from test_framework.test_framework import AureusTestFramewo... | ', headers)
resp = conn.getresponse()
assert_equal(resp.status==401, False)
conn.close()
#Use new authpair to confirm both work
headers = {"Authorization": "Basic " + | base64.b64encode(authpairnew)}
conn = httplib.HTTPConnection(url.hostname, url.port)
conn.connect()
conn.request('POST', '/', '{"method": "getbestblockhash"}', headers)
resp = conn.getresponse()
assert_equal(resp.status==401, False)
conn.close()
#Wrong login na... |
# Copyright NuoBiT Solutions, S.L. (<https://www.nuobit.com>)
# Eric Antones <eantones@nuobit.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl)
from odoo import fields, models
class ResPartner(models.Model):
_inherit = "res.partner"
sale_journal_id = fields.Many2one(
"account.journ... | =[("type", "=", "sale")]
)
purchase_journal_id = fields.Many2one(
"account.journal", "Default journal", domain=[("type", "=", " | purchase")]
)
|
uery_qualities",))
# reset qual
b = self.buildRead()
# check flags:
for x in (
"is_paired", "is_proper_pair",
"is_unmapped", "mate_is_unmapped",
"is_reverse", "mate_is_reverse",
"is_read1", "is_read2",
"is_... | zip(
range(0, 0 + 35), range(20, 20 + 35))])
def test_get_aligned_pairs_skip(self):
a = pysam.AlignedSegment()
a.query_name = "read_12345"
a.query_sequence = "ACGT" * 10
a.flag = 0
a.reference_id = 0
a.reference_start = 20
| a.mapping_quality = 20
a.cigartuples = ((0, 2), (3, 100), (0, 38))
a.query_qualities = pysam.fromQualityString("1234") * 10
self.assertEqual(a.get_aligned_pairs(),
[(0, 20), (1, 21)] +
[(None, refpos) for refpos in range(22, 22 + 100)] +
... |
from django import views
from django.shortcuts import render, get_object_or_404
from django.views.generic import TemplateView
from django.views.generic.edit import CreateView
from .models import *
from .forms import *
import requests
import http
from django.urls import reverse_lazy
from django.views.decorators.csrf imp... | if('2018-09-30T | 00:00:00Z'<obj['created_at']<'2018-10-31T23:59:59Z'):
pr_count += 1
user.pr_count = pr_count
user.save()
connected = True
except:
pass
return render(request, 'home/leaderboard.html', {... |
i | mport sys
r, c = map(int, input().split())
while r and c:
lines = [input().strip() for i in range(r)]
rotatedLines = []
for i in range(c):
rotatedLines.append("".join([lines[j][i] for j in range(r)]))
rotatedLines.sort(key=lambda s: s.lower())
for i in range(r):
print("".join([rotatedLines[j][i] for j in rang... | put().split())
|
import json
import sqlite3
def get_room(id, dbfile):
ret = None
con = sqlite3.connect(dbfile)
for row in con.execute("select json from rooms where id=?",(id,)):
jsontext = row[0]
# Outputs the JSON response
#print("json = " + j | sontext)
d = json.loads(jsontext)
d['id'] = id
ret = Room(**d)
break
con.close()
return ret
class Room():
def __init__(self, id=0, name="A room", description="An empty room", neighbors={}):
self.id = id
self.name = name
self.description = ... |
return self.neighbors[direction]
else:
return None
def north(self):
return self._neighbor('n')
def south(self):
return self._neighbor('s')
def east(self):
return self._neighbor('e')
def west(self):
return self._neighbor('w')
|
# Generated by Django 2.0.5 on 2018-05-10 22:56
from django.db import mi | grations
class Migration(migrations.Migrati | on):
dependencies = [("studies", "0001_initial")]
operations = [migrations.AlterModelOptions(name="extension", options={"ordering": ("-id",)})]
|
from markupsafe import escape
import re
from pymongo.objectid import ObjectId
from pymongo.errors import InvalidId
from app.people.people_model import People
from app.board.board_model import BoardTopic, BoardNode
from beaker.cache import CacheManager
from beaker.util import parse_cache_config_options
from lib.fi... | rlink(escape(topic.more_content))) #urlink((mentions(youku(escape(topic. | content)) ) ) , trim_url_limit=30)
extra_content = ''
if topic.video_urls:
video_html = '<p></p>'
for url in topic.video_urls:
video_html += video(url)
extra_content = video_html
return html_more_content + extra_content
except ... |
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... | serv = ListenAndServ("127.0.0.1:0", ["X"], optimizer_mode=False)
with serv.do():
out_var = main.global_block().create_var(
name="scale_0.tmp_0",
psersistable=True,
dtyp | e="float32",
shape=[32, 32])
x = layers.data(
shape=[32, 32],
dtype='float32',
name="X",
append_batch_size=False)
fluid.initializer.Constant(value=1.0)(x, main.global_block())
... |
__authors__ = ""
__copyright__ = "(c) 2014, pymal"
__license__ = "BSD License"
__contact__ = "Name Of Curr | ent Guardian of this file <email@address>"
USER_AGENT = 'api-ind | iv-0829BA2B33942A4A5E6338FE05EFB8A1'
HOST_NAME = "http://myanimelist.net"
DEBUG = False
RETRY_NUMBER = 4
RETRY_SLEEP = 1
SHORT_SITE_FORMAT_TIME = '%b %Y'
LONG_SITE_FORMAT_TIME = '%b %d, %Y'
MALAPPINFO_FORMAT_TIME = "%Y-%m-%d"
MALAPPINFO_NONE_TIME = "0000-00-00"
MALAPI_FORMAT_TIME = "%Y%m%d"
MALAPI_NONE_TIME = "00000... |
from unittest import TestCase
import os
from opencog.atomspace import AtomSpace, TruthValue, Atom, types
from opencog.bindlink import stub_bindlink, bindlink, single_bindlink,\
first_n_bindlink, af_bindlink, \
satisfaction_link, satisfying_set, \
... | VariableNode("$var")
# bindlink needs a handle
)
# Define a pattern to be grounded
self.getlink_atom = \
GetLink(
InheritanceLink(
VariableNode("$var"),
ConceptNode("animal")
)
... | atomspace = ", self.atomspace
# Can't do this; finalize can be called only once, ever, and
# then never again. The second call will never follow through.
# Also, cannot create and delete atomspaces here; this will
# confuse the PythonEval singletonInstance.
# finalize_opencog(... |
#!/usr/bin/env python
# -*- coding: <encoding name> -*-
__author__ = "i_pogorelko"
__email__ = "i.pogorelko@g | mail.com"
__date__ = "2014-11-16"
text='Proin eget tortor risus. Cras ultricies ligula sed mag | na dictum porta.\
Donec rutrum congue leo eget malesuada.'
def percentage_1(text):
print ''
print 'input: ', text
text = text.lower()
text2 = ''
for x in text:
if ord(x) >= ord('a') and ord(x) <= ord('z'):
text2 = text2 + x
d = {}
m = 0
for j in text2:
if ... |
#parser_testing.py
import os, sys, re, StringIO
sys.path.append('/Users/Jason/Dropbox/JournalMap/scripts/GeoParsers')
#from jmap_geoparser_re import *
from jmap_geoparser import *
#def test_parsing():
t | est = "blah blah blah 45º 23' 12'', 123º 23' 56'' and blah blah blah 32º21'59''N, 115º 23' 14''W blah blah blah"
coords = coordinateParser.searchString(test)
for coord in coords:
assert coordinate(coord).calcDD(), "Coordinate Transform Error for "+str(coord)
test = "45.234º, 123.43º"
assert coordinate(coordi | nateParser.parseString(test)).calcDD() == {'latitude': 45.234, 'longitude': 123.43}
test = "-45º 23' 12'', -123º 23' 56''"
assert coordinate(coordinateParser.parseString(test)).calcDD() == {'latitude': -45.38667, 'longitude': 123.39889}
test = "32º21'59''N, 115º 23' 14''W"
assert coordinate(coordinateParser.parseSt... |
import binascii
de | f b2h(the_bytes):
return binascii.hexlify(the_bytes).decode("utf8")
def b2h_rev(the_bytes):
return binascii.hexlify(bytearray(reversed(the_bytes))).dec | ode("utf8")
|
# -*- coding: utf-8 -*-
__author__ = 'frank'
from flask import Flask, request, url_for, render_template, g, session, flash
from flask_wtf.csrf import CsrfProtect
from flask_debugtoolbar import DebugToolbarExtension
from flask.ext.login import LoginManager
from flask.ext.moment import Moment
from . import filters, pe... | fig.SMTP_USER, config.SMTP_PASSWORD)
mail_handler = SMTPHandler(config.SMTP_SERVER, config.SMTP_FROM,
config.SMTP_ADMIN, 's | f-log', credentials, ())
from logging import Formatter
mail_handler.setFormatter(Formatter('''
Message type: %(levelname)s
Location: %(pathname)s:%(lineno)d
Module: %(module)s
Function: %(funcName)s
Time: %(asctime)s
... |
from django.http import HttpResponse, HttpRequest
from typing import Optional
import ujson
from django.utils | .translation import ugettext as _
from zerver.lib.actions import | do_mute_topic, do_unmute_topic
from zerver.lib.request import has_request_variables, REQ
from zerver.lib.response import json_success, json_error
from zerver.lib.topic_mutes import topic_is_muted
from zerver.lib.streams import (
access_stream_by_id,
access_stream_by_name,
access_stream_for_unmute_topic_by_i... |
try:
if ask_vault_pass:
vault_pass = getpass.getpass(prompt="Vault password: ")
if ask_vault_pass and confirm_vault:
vault_pass2 = getpass.getpass(prompt="Confirm Vault password: ")
if vault_pass != vault_pass2:
raise errors.An... | self.options.become_ask_pass = self.options.become_ask_pass or self.options.ask_sudo_pass or self.options.ask_su_pass or C.DEFAULT_BECOME_ASK_PASS
self.options.become_user = self.options.become_user or self.options.sudo_user or self.options.su_user or C.DEFAULT_BECOME_USER
if self.options.bec... | become = True
self.options.become_method = 'sudo'
elif self.options.su:
self.options.become = True
self.options.become_method = 'su'
def validate_conflicts(self, vault_opts=False, runas_opts=False):
''' check for conflicting options '''
op = self.option... |
# -*- coding: utf-8 -*-
import datetime
from django.conf import settings
from django.test import TestCase, override_settings
from django.utils import timezone
from django_dynamic_fixture import G
from apps.events.models import AttendanceEvent, Event
class EventOrderedByRegistrationTestCase(TestCase):
def setUp... | Tests that an AttendanceEvent with registration date within the "featured delta" (+/- 7 days from today)
will be pushed ahead in the event | list, thus sorted by registration start rather than event end.
"""
today = timezone.now()
three_days_ahead = today + datetime.timedelta(days=3)
month_ahead = today + datetime.timedelta(days=30)
month_ahead_plus_five = month_ahead + datetime.timedelta(days=5)
normal_event ... |
from __future__ import absolute_import
from django import forms
from django.contrib import messages
from django.core.urlresolvers import reverse
from sentry.models import Project, Team
from sentry.web.forms.add_project import AddProjectForm
from sentry.web.frontend.base import OrganizationView
from sentry.utils.http ... |
return AddProjectWithTeamForm(request.user, team_list, request.POST or None, initial={
'team': request.GET.get('team'),
})
def handle(self, request, organization):
team_list = [
t for t in Team.objects.get_for_user(
organization=organization,
... | am_list:
messages.error(request, ERR_NO_TEAMS)
return self.redirect(reverse('sentry-organization-home', args=[organization.slug]))
form = self.get_form(request, organization, team_list)
if form.is_valid():
project = form.save(request.user, request.META['REMOTE_ADDR']... |
import os
os.environ["PYSDL2_DLL_PATH"] = os.getcwd()
import sdl2
import win32gui
def get_windows_bytitle(title_text, exact = False):
"""
Gets window by title text. [Windows Only]
"""
def _window_callback(hwnd, all_windows):
all_windows.append((hwnd, win32gui.GetWindowText(hwnd))... | sdl2.SDL_GetWindowSurface(np_window)
print(sdl2.SDL_GetError())
save_sur = sdl2.SDL_CreateRGBSurface(0,np_sur[0].w,np_sur[0].h,32,0,0,0,0)
pri | nt(sdl2.SDL_GetError())
r = sdl2.SDL_BlitSurface(np_sur, None, save_sur, None)
print(sdl2.SDL_GetError())
result = sdl2.SDL_SaveBMP(save_sur,'test.bmp')
print(sdl2.SDL_GetError())
sdl2.SDL_FreeSurface(save_sur)
print(sdl2.SDL_GetError())
|
are using the service.
#
# Special thanks :
# thanks person :5ynl0rd,kiddies aka peneter,ne0 d4rk fl00der,oghie,parc0mx,me0nkz,suryal0e,zee_eichel
# mirwan aka cassaprogy,shadow_maker,suddent_death,aip,r3d3,dawflin,n1nj4,hakz,
# leXel,s3my0n,MaXe,Andre Corleon... | 'total']
print 'Modules found: %s'%result
result2 = m_m['matches']
for i in result2:
print '%s: %s' % (i['type'], i['name'])
download =raw_input('[+]Download module : (y/n)')
if download =='y':
file = _lolz_.msf.download(i['full... | print 'Content-type: %s' % file['content-type']
print file['data']
try_again = raw_input('[+]Do you want to try again ?(y/n)')
while try_again =='y':
os.system(clear())
title()
metasploit()
try_again = raw_... |
# importing | wxPython library, see the reference here :
# http://www.wxpython.org/docs/api/wx-module.html
# and an excelent step by step tutorial there :
# http://zetcode.com/wxpython
import wx
from Controller import *
# main function
def main():
# each wx application must have a wx.App object
app = wx.App()
control... | = "BLANK_PY2WX")
# entering the endless loop that catches all the events
app.MainLoop()
if __name__ == '__main__':
main()
|
import sys
from fabric.api | import *
from fabric.contrib import *
from fabric.contrib.project import rsync_project
from defaults import fab
from config import ssh, sudoers
import {%= name %}
@task
def prepare_vm():
sudoers.setup_sudoers_on_vm()
@task(de | fault=True)
def system():
print 'start here'
|
# -*- coding: utf-8 -*-
#----------------------------------------------------------------------------
# Menu for quickly adding waypoints when on move
#----------------------------------------------------------------------------
# Copyright 2007-2008, Oliver White
#
# This program is free software: you c | an redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# | (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; 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 ... |
field = None
new_class._meta.parents[base] = field
else:
# .. and abstract ones.
for field in parent_fields:
new_class.add_to_class(field.name, copy.deepcopy(field))
# Pass any non-abstract parent classes onto chi... | hrows it, the second
# is *not* consumed. We rely on this, so don't change the order
| # without changing the logic.
for val, field in zip(args, fields_iter):
setattr(self, field.attname, val)
else:
# Slower, kwargs-ready version.
for val, field in zip(args, fields_iter):
setattr(self, field.attname, val)
k... |
,
"original_filename": os.path.split(self.filename)[1],
"time": time_str,
},
"Signal": {
"quantity": quantity_str,
"signal_type": "",
},
}
return metadict
def _build_original_metadata(se... | signal.change_dtype('uint8')
signal.change_dtype('rgb8')
else:
warnings.warn("""RGB-announced data could not be converted to
uint8 or uint16 datatype""")
pass
return signal
### pack/unpack binary quantities
def _get_int16(self,file, defau... | r-definable default value if
no file is given"""
if file is None :
return default
b = file.read(2)
if sys.byteorder == 'big' :
return struct.unpack('>h', b)[0]
else :
return struct.unpack('<h', b)[0]
def _set_int16(self, file, val):
... |
from .base_executor import ScriptExecutor
from judgeenv import env
class RubyExecutor(ScriptExecu | tor):
| ext = '.rb'
name = 'RUBY'
address_grace = 65536
fs = ['.*\.(?:so|rb$)', '/etc/localtime$', '/dev/urandom$', '/proc/self', '/usr/lib/ruby/gems/']
test_program = 'puts gets'
@classmethod
def get_command(cls):
return env['runtime'].get(cls.name.lower())
|
import attr
from navmazing import NavigateToAttribute
from navmazing import NavigateToSibling
from cfme.common import Taggable
from cfme.common import TagPageView
from cfme.containers.provider import ContainerObjectAllBaseView
from cfme.containers.provider import ContainerObjectDetailsBaseView
from cfme.containers.pro... | use_search=search_visible).click()
@navigator.register(Service, 'EditT | ags')
class EditTags(CFMENavigateStep):
VIEW = TagPageView
prerequisite = NavigateToSibling('Details')
def step(self, *args, **kwargs):
self.prerequisite_view.toolbar.policy.item_select('Edit Tags')
|
import sys
import gzip
import logging
from csv import DictReader
from datetime import datetime
from . import app, connect_db
from ..constants import DEFAULT_GENOME_BUILD, BENIGN, UNCERTAIN, UNKNOWN, PATHOGENIC
from ..extensions import mongo
from ..backend import build_variant_doc, get_variant_category, update_variant... | 'clinvar_filename', metavar='CLINVAR_ALLELES_TSV_GZ', type=str,
help='clinvar_alleles.single.b*.tsv.gz from github.com/ | macarthur-lab/clinvar pipeline')
return parser.parse_args()
if __name__ == '__main__':
args = parse_args()
main(args.clinvar_filename)
|
r, phi = self.ldf.calculate_core_distance_and_angle(x, y, core_x,
core_y)
p_ground = self.ldf.calculate_ldf_value(r, phi, size, zenith, azimuth)
num_particles = self.simulate_particles_for_density(
p_ground * detector.get_area()... | ition in m.
:param x0,y0: shower core position in m.
:param theta,phi: shower axis direction in radians.
| :return: distance from detector to the shower core in shower
front plane in m.
"""
x = x - x0
y = y - y0
return sqrt(x ** 2 + y ** 2 -
(x * cos(phi) + y * sin(phi)) ** 2 * sin(theta) ** 2)
class NkgLdf(BaseLdf):
"""The Nishimura-Kamata... |
:vartype time: float
"""
def __init__(self, left, right, node, source, dest, time):
self.left = left
self.right = right
self.node = node
self.source = source
self.dest = dest
self.time = time
class Variant(SimpleContainer):
"""
A variant is represen... | s is equivalent to
>>> sum(
>>> tree.branch_length(u) for u in tree.nodes()
>>> if u not in self.roots)
:return: The sum of all the b | ranch lengths in this tree.
:rtype: float
"""
return sum(
self.get_branch_length(u) for u in self.nodes() if u not in self.roots)
def get_mrca(self, u, v):
# Deprecated alias for mrca
return self.mrca(u, v)
def mrca(self, u, v):
"""
Returns t... |
import pymongo
from flask import g
from flas | k import current_app as app
def get_db():
if not hasattr(g, 'conn'):
print(app.config)
g.conn = pymongo.MongoClient(
app.config['MONGODB_HOST'],
int(app.config['MONGODB_PORT'])
)
if not hasattr(g, 'db'):
g.db = g.conn[app.config['MONGODB_DB']]
retu... | _appcontext
# def teardown_db(exception):
# conn = getattr(g, 'conn', None)
# if conn is not None:
# conn.close() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.