prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
import logging
import io
from pathlib import Path
from rdflib import URIRef, RDF
from dipper.graph.RDFGraph import RDFGraph
LOG = logging.getLogger(__name__)
class TestUtils:
@staticmethod
def test_graph_equality(turtlish, graph):
"""
:param turtlish: file path or string of triples in turtl... | ight hand difference: %s",
sorted(turtle_triples - ref_triples),
sorted(ref_triples - turtle_triples)
)
return equality
@staticmethod
def remove_ontology_axioms(graph):
"""
Given an rdflib graph, remove any triples
connected to an onto... | for subject in graph.subjects(RDF.type, ontology_iri):
for predicate, obj in graph.predicate_objects(subject):
graph.remove((subject, predicate, obj))
graph.remove((subject, RDF.type, ontology_iri))
|
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import re
import sys
def read_file(path):
try:
with open(path, 'r') as f:
return f.read()
except Exception as ex: # pylint: disable=broad-except
print('%s:%d:%d: unable to read required file %... | (r'\s+', ' ', str(ex))))
| return None
def main():
ORIGINAL_FILE = 'requirements.txt'
VENDORED_COPY = 'test/lib/ansible_test/_data/requirements/ansible.txt'
original_requirements = read_file(ORIGINAL_FILE)
vendored_requirements = read_file(VENDORED_COPY)
if original_requirements is not None and vendored_requirements ... |
_render_edit_form_for(
self, rest_handler_cls, title, annotations_dict=None,
delete_xsrf_token='delete-unit', page_description=None):
"""Renders an editor form for a given REST handler class."""
if not annotations_dict:
annotations_dict = rest_handler_cls.SCHEMA_ANNOTATIONS_D... | transforms.send_json_response(
self, 404, 'Object not found.', {'key': key})
return
payload = request.get('payload')
updated_unit_dict = transforms.json_to_dict(
transforms.loads(payload), self.SCHEMA_DICT)
errors = []
self.apply_updates(unit,... | |
"""
Support for Eneco Slimmer stekkers (Smart Plugs).
This provides controls for the z-wave smart plugs Toon can control.
"""
import logging
from homeassistant.components.switch import SwitchDevice
import custom_components.toon as toon_main
_LOGGER = logging.getLogger(__name__)
def setup_platform(hass, config, add... | er usage in W."""
return self.toon_data_store.get_data('current_power', self.name)
@property
def today_energy_kwh(self):
"""Today total energy usage in kWh."""
return self.toon_data_store.get_data('today_energy', self.name)
@property
def is_on(self):
"""Return true if s... | switch is available."""
return self.smartplug.can_toggle
def turn_on(self, **kwargs):
"""Turn the switch on."""
return self.smartplug.turn_on()
def turn_off(self):
"""Turn the switch off."""
return self.smartplug.turn_off()
def update(self):
"""Update stat... |
- qtcreator
| |-- plugins
|
|-- plugins
| |-- qt plugins
| |-- csdaquick plguins
|
|-- qml
|-- CSDataQuick
|-- QtQuick
Linux:
|-- bin
| |-- qt.conf -> Prefix=..
| |-- csdataquick executibles
| |-- qtcreator
|
|-- lib
| |-- qt sha... | t and Qt Creator for packaging')
parser.add_argument('--target', required=True, help='target path')
parser.add_argument('--qtcreator', help='qt creator path')
parser.add_argument('--qmake', required=True, help='qmake file path')
args = parser.parse_args(sys.argv[1:])
qtcreator_path = args.qtcreator
target_path = args.... | arget_path, 'bin')
lib_dir = os.path.join(target_path, 'lib')
libexec_dir = os.path.join(target_path, 'libexec')
plugins_dir = os.path.join(target_path, 'plugins')
qml_dir = os.path.join(target_path, 'qml')
def smartCopy(src, dst, follow_symlinks=True, ignore=None):
"""
same as shell cp command. If *src* is a... |
from data_vault import VaultEnvironment
class KeeperApiHelper:
_expected_commands = []
_vault_env = VaultEnvironment()
@staticmethod
def communicate_expect(actions):
# type: (list) -> None
KeeperApiHelper._expected_commands.clear()
KeeperApiHelper._expected_commands.extend(act... | t) -> dict
rs = {
'result': 'success',
'result_code': '',
'message': ''
| }
action = KeeperApiHelper._expected_commands.pop(0)
if callable(action):
props = action(request)
if type(props) == dict:
rs.update(props)
return rs
if type(action) == str:
if action == request['command']:
ret... |
import os
import shutil
class BasicOperations_TestClass:
TEST_ROOT =' __test_root__'
def setUp(self):
self.regenerate_root
print(self.TEST_ROOT)
assert os.path.isdir(self.TEST_ROOT)
def tearDown(self):
return True
def test_test(self):
assert self.bar == 1
... | EST_ROOT)
| |
###############################################################################
##
## Copyright (C) 2011-2014, NYU-Poly.
## Copyright (C) 2006-2011, University of Utah.
## All rights reserved.
## Contact: contact@vistrails.org
##
## This file is part of VisTrails.
##
## "Redistribution and use in source and binary for... | LIABILITY,
## WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
## OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
## ADVISED OF T | HE POSSIBILITY OF SUCH DAMAGE."
##
###############################################################################
name = "R"
identifier = "org.vistrails.vistrails.rpy"
version = "0.1.2"
old_identifiers = ["edu.utah.sci.vistrails.rpy"]
|
# Import everything needed to edit video clips
from moviepy.editor import *
# Load myHolidays.mp4 and select the subclip 00:00:50 - 0 | 0:00:60
clip = VideoFileClip("myHolidays.mp4").subclip(50,60)
# Reduce the audio volume (volume x 0.8)
clip = clip.volumex(0.8)
# Generate a text clip. You can customize the font, color, etc.
txt_clip = TextClip("My Holidays 2013",fontsize=70,color='white')
# Say that you want it to appear | 10s at the center of the screen
txt_clip = txt_clip.set_pos('center').set_duration(10)
# Overlay the text clip on the first video clip
video = CompositeVideoClip([clip, txt_clip])
# Write the result to a file (many options available !)
video.write_videofile("myHolidays_edited.webm")
|
ramework.test_framework import ComparisonTestFramework
from test_framework.util import *
from test_framework.mininode import CTransaction, network_thread_start
from test_framework.blocktools import create_coinbase, create_block
from test_framework.comptool import TestInstance, TestManager
from test_framework.script imp... | sion = version
block.rehash()
block.solve()
test_blocks.append([block, True])
self.last_block_time += 1
self.tip = block.sha256
self.height += 1
return test_blocks
def get_bip9_status(self, key):
info = self.nodes[0].getblockch... | vated_version, invalidate, invalidatePostSignature, bitno):
assert_equal(self.get_bip9_status(bipName)['status'], 'defined')
assert_equal(self.get_bip9_status(bipName)['since'], 0)
# generate some coins for later
self.coinbase_blocks = self.nodes[0].generate(2)
self.height = 3 #... |
#!/usr/bin/python
import glob, os
from cjh.cli import Cli, ListPrompt
from cjh.lists import ItemList
class Fileman(object):
@classmethod
def pwd(cls, getstr=False):
"""
Emulate 'pwd' command
"""
string = os.getcwd()
if getstr:
return string
else: pr... | index, file_ in enumerate(file_list):
if os.path.isdir(file_):
dir_list.append(file_ + '/')
del file_list[index]
elif os.access(file_, os.X_OK):
fil | e_list[index] = file_ + '*'
if 'get_list' not in kwargs or kwargs['get_list'] is not True:
string = ''
for dir_ in dir_list:
string += (dir_ + '\n')
for file_ in file_list:
string += (file_ + '\n')
if len(dir_list) + len(file_list)... |
image by fitting the image I(x,y,z) to a
polynomial, then subtracts this fitted intensity variation and uses
centroid methods to find the particles.
"""
# We just want a smoothed field model of the image so that the residuals
# are simply the particles without other complications
m = models.Smo... | then optimizing the globals + positions until
termination as called in _optimize_from_centroid.
The ``Other Parameters`` are passed to _optimize_from_centroid.
"""
if actual_rad is None:
actual_rad = feature_rad
_, im_name = _pick_state_im_name('', im_name, use_full_path=use_full_path)
... | Image(im_name, tile=tile)
pos = locate_spheres(im, feature_rad, invert=invert, **featuring_params)
if np.size(pos) == 0:
msg = 'No particles found. Try using a smaller `feature_rad`.'
raise ValueError(msg)
rad = np.ones(pos.shape[0], dtype='float') * actual_rad
s = statemaker(im, pos, ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""DataGroupXanes: work with XANES data sets
============================================
- DataGroup
- DataGroup1D
- DataGroupXanes
"""
from .datagroup import MODNAME
from .datagroup1D import DataGroup1D
class DataGroupXanes(DataGroup1D):
"""DataGroup for XANES... | t__(self, kwsd=None, _larch=None):
super(DataGroupXanes, se | lf).__init__(kwsd=kwsd, _larch=_larch)
### LARCH ###
def datagroup_xan(kwsd=None, _larch=None):
"""utility to perform wrapped operations on a list of XANES data
groups"""
return DataGroupXanes(kwsd=kwsd, _larch=_larch)
def registerLarchPlugin():
return (MODNAME, {'datagroup_xan' : datagroup_xan})
... |
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
# ex: set expandtab softtabstop=4 shiftwidth=4:
#
# Copyright (C) 2010,2011,2012,2013,2014,2015,2016,2017 Contributor
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obt... | nal col we c | annot make it non-null
@validates('priority')
def _validate_priority(self, key, value): # pylint: disable=W0613
if not value:
raise ValueError("Shared addresses require a priority")
return value
@property
def is_shared(self):
return True
__mapper_args__ = {'pol... |
from __future__ import print_function
import time
import argparse
import grpc
from jaeger_client import Config
from grpc_opentracing import open_tracing_client_interceptor
from grpc_opentracing.grpcext import intercept_channel
import command_line_pb2
def run():
parser = argparse.ArgumentParser()
parser.ad... | or(
tracer, log_payloads=args.log_payloads)
channel = grpc.insecure_channel('localhost:50051')
channel = intercept_channel(channel, tracer_interceptor)
stub = command_line_pb2.CommandLineStub(channel)
| response = stub.Echo(command_line_pb2.CommandRequest(text='Hello, hello'))
print(response.text)
time.sleep(2)
tracer.close()
time.sleep(2)
if __name__ == '__main__':
run()
|
from collections import Counter
c = Counter(input())
print(min | (c['t'], c['r'], c['e']//2))
| |
#!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Script to install ARM root image for cross building of ARM chrome on linux.
This script can be run manually but is more often ru... | $NACL_REV/sysroot-arm-trusted.tgz
"""
import os
import shutil
import subprocess
import sys
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
URL_PREFIX = 'https://storage.googleapis.com'
URL_PATH = 'nativeclient-archive2/toolchain'
REVISION = 13035
TARBALL = 'sysroot-arm-trusted.tgz'
def main(args):
if '--l... | s case we return early on non-linux platforms
# or if GYP_DEFINES doesn't include target_arch=arm
if not sys.platform.startswith('linux'):
return 0
if "target_arch=arm" not in os.environ.get('GYP_DEFINES', ''):
return 0
src_root = os.path.dirname(os.path.dirname(SCRIPT_DIR))
sysroot = os.p... |
from .context import CorpusContext
from .audio import Audio | Context
from .importable import ImportContext
from .lexical import LexicalContext
from .pause import PauseContext
from .utterance import UtteranceContext
from .structured import StructuredContext
from .syllabic import SyllabicContext
from | .spoken import SpokenContext
|
from SCons.Script import *
def exists(env):
return (env["PLATFORM"]=="win32")
def ConvertNewlines(target,source,env):
for t,s in zip(target,source):
f_in=open(str(s),"rb")
f_out=open(str(t),"wb")
f_out.write(f_in.read().replace("\n","\r\n"))
f_out.close()
f_in.close()
... | "))
f_out.close()
f_in.close()
return None
def generate(env):
env["BUILDERS"]["ConvertNewlines"]=Builder(action=Co | nvertNewlines,suffix=".txt")
env["BUILDERS"]["ConvertNewlinesB"]=Builder(action=ConvertNewlinesB,suffix=".txt")
|
import requests
from django.conf import settings
from django.http import HttpResponse, HttpResponseBadRequest
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
@csrf_exempt
@require_http_methods(["POST"])
def post_service_request(request):
payload =... | oing:
del outgoing["internal_feedback"]
api_key = settings.OPEN311["INTERNAL_FEEDBACK_API_KEY"]
else:
api_key = settings.OPEN311["API_KEY"]
outgoing["api_key"] = api_key
url = settings.OPEN311["URL_BASE"]
session = requests.Session()
# Modify parameters for request in ca... | if "smbackend_turku" in settings.INSTALLED_APPS:
outgoing.pop("service_request_type")
outgoing.pop("can_be_published")
outgoing["address_string"] = "null"
outgoing["service_code"] = settings.OPEN311["SERVICE_CODE"]
r = session.post(url, data=outgoing)
if r.status_code != 200:... |
from uuid import uuid4
from django.test import TestCase
from casexml.apps.case.cleanup import claim_case, get_first_claim
from casexml.apps.case.mock import CaseBlock
from casexml.apps.case.util import post_case_blocks
from corehq.apps.case_search.models import CLAIM_CASE_TYPE
from corehq.apps.domain.shortcuts impor... | AIN = 'test_domain'
USERNAME = 'lina.stern@ras.ru'
PASSWORD = 'hemato-encephalic'
# https://en.wikipedia.org/wiki/Lina_Stern
def index_to_dict(instance):
keys = ('identifier', 'referenced_type', 'referenced_id', 'relationship')
return {k: str(getattr(instance, k)) for k in keys}
class CaseClaimTests(TestCas... | E, PASSWORD, None, None)
self.restore_user = get_restore_user(DOMAIN, self.user, None)
self.host_case_id = uuid4().hex
self.host_case_name = 'Dmitri Bashkirov'
self.host_case_type = 'person'
self.create_case()
def tearDown(self):
self.user.delete(self.domain.name, de... |
ty.text() + '" '
exiftool_params += '-iptc:City="' + self.xmp_city.text() + '" '
# Map date/time and format stuff
if self.chk_gps_timestamp.isChecked():
exiftool_params += '-exif:Copyright="' + self.exif_Copyright.text() + '" '
if self.chk_gps_datestamp.isChecked():
exiftool_params... | descriptor == "Subject":
self.xmp_subject.setText(description)
if descriptor == "Title":
self.xmp_title.setText(description)
if descriptor == "Rating":
if description == "1":
self.xmp_rating1.setChecked | (1)
elif description == "2":
self.xmp_rating2.setChecked(2)
elif description == "3":
self.xmp_rating3.setChecked(3)
elif description == "4":
self.xmp_rating4.setChecked(4)
elif description == "5":... |
text = 'th | is is a sample file\nnew line'
savefile = open('newtext', 'w')
save | file.write(text)
savefile.close()
|
ike ID and title
def get_top_ten_movies():
returnmovies = []
fullurl = '%s/media/trailer/' % MAIN_URL
link = get_cached_url(fullurl, 'mainpage.cache', GetSetting('cache_movies_list'))
matchtopten = re.compile('<tr><td valign="top" align="right"><b>([0-9]+)</b></td><td width=100% style="text-align:left;... | .compile('<tr><td(?: valign="top"><b>[A-Z0-9]</b)?></td><td style="text-align:left;"><a href="/media/trailer/([0-9]+),(?:[0-9]+?,)?([^",]+?)">([^<]+)</a></td></tr>').findall(link)
| for movieid, urlend, title in matchtacttrailers:
movie = {'movieid': movieid,
'title': title,
'urlend': urlend,
'rank': '',
'date': ''}
returnmovies.append(movie)
return returnmovies
# Function to get a dict of detailed movie inf... |
#!/usr/bin/env python
import webapp2
import logging
from google.appengine.ext.webapp.mail_handlers import InboundMailHandler
from google.appengine.ext import ndb
from MailMessage import MailMessage
# the email domain of this app is @pomis-newsletterman.appspotmail.com
class EmailHandlerV1(InboundMailHandler):
... | persistent_mail_ | message.put()
app = webapp2.WSGIApplication([EmailHandlerV1.mapping()], debug=True)
|
# -*- Mode: python; coding: utf-8; tab-width: 8; indent-tabs-mode: t; -*-
#
# Copyright (C) 2009 Jonathan Matthew <jonathan@d14n.org>
#
# 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 ve... |
def get_release_cb (self, data, args):
(key, store, callback, cbargs) = args
if data is None:
print("musicbrainz release request returned nothing")
callback(*cbargs)
return
try:
parsed = dom.parseString(data)
storekey = RB.ExtDBKey.create_storage('album', key.get_field('album'))
# check tha... | s an artist that isn't 'various artists'
artist_tags = parsed.getElementsByTagName('artist')
if len(artist_tags) > 0:
artist_id = artist_tags[0].attributes['id'].firstChild.data
if artist_id != MUSICBRAINZ_VARIOUS_ARTISTS:
# add the artist name (as album-artist) to the storage key
nametags = art... |
#!/usr/bin/env python
from sciwonc.dataflow.DataStoreClient import DataStoreClient
import ConfigDB_SessionCompute_2
import pprint
# connector and config
client = DataStoreClient("mongodb", ConfigDB_SessionCompute_2)
config = ConfigDB_SessionCompute_2
# according to config
dataList = client.getData() # return an array... | print contributor_username.encode('utf-8')
while True:
doc = i['data'].next()
if doc is None:
| break;
print doc["timestamp"]
if start_time is None:
start_time = float(doc["timestamp"])
if end_time is None:
end_time = start_time + ONE_HOUR_IN_SECONDS
else:
if float(doc... |
###############################################################################
#
# The MIT License (MIT)
#
# Copyright (c) Tavendo GmbH
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software wit | hout restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distri | bute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVID... |
#!/usr/bin/env python
'''
Plot distribution of each feature,
conditioned on its bfeature type
'''
import argparse
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
from common import *
from information import utils
from scipy.stats import itemfreq
nbins = 100
def opts():
parse... | om=h, width=dx)
| h += h_new
plt.xlim(f_min, f_max)
plt.xlabel('f')
plt.ylabel('P(f)')
plt.title('FFeature %d. # NaN = %d' % (j, np.sum(np.isnan(f))))
pdf.savefig(fig)
plt.close()
print "Plotting integer features"
for j, x in enumerate(dfs.T):
print "...dfeat... |
#!/usr/bin/env python3
import os
from pathlib import Path
import numpy as np
from pysisyphus.helpers import geom_from_xyz_file
from pysisyphus.stocastic.align import matched_rmsd
THIS_DIR = Path(os.path.dirname(os.path.realpath(__file__)))
def test_matched_rmsd():
geom1 = geom_from_xyz_file(THIS_DIR / "eins.x... | ol=1e-10)
np.testing.assert_allclose(geom1_matched.coords, geom2_matched.coords)
geom2 = geom_from_xyz_file(THIS_DIR / "zwei.xyz")
min_rmsd, _ = matched_rmsd(geom1, geom2)
np.testing.assert_allclose(min_rmsd, 0.057049, atol=1e-5)
if __name__ | == "__main__":
test_matched_rmsd()
|
ssertTrue(np.isfinite(b[0, 0]))
self.assertTrue(np.isfinite(b[100, 100]))
def test_reproject_stere(self):
n1 = Nansat(self.test_file_gcps, log_level=40, mapper=self.default_mapper)
n2 = Nansat(self.test_file_stere, log_level=40, mapper=self.default_mapper)
n1.reproject(n2)
t... | =40, mapper=self.default_mapper)
tmpfilename = os.path.join(self.tmp_data_path, 'nansat_write_geotiffimage.tif')
n1.write_geotiffimage(tmpfilename, band_id=1)
self.assertTrue(os.path.exists(tmpfilename))
def test_get_metadata(self):
n1 = Nansat(self.test_file_ster | e, log_level=40, mapper=self.default_mapper)
m = n1.get_metadata()
self.assertEqual(type(m), dict)
self.assertTrue('filename' in m)
def test_get_metadata_key(self):
n1 = Nansat(self.test_file_stere, log_level=40, mapper=self.default_mapper)
m = n1.get_metadata('filename')
... |
# Copyright 2013 Daniel Narvaez
#
# 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/LICEN | SE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under | the License.
import subprocess
from setuptools import setup, Extension
classifiers = ["License :: OSI Approved :: Apache Software License",
"Programming Language :: Python :: 2",
"Topic :: Software Development :: Build Tools"]
setup(name="sourcestamp",
version="0.1",
descri... |
config = {
"interfaces": {
"google.cloud.talent.v4beta1.TenantService": {
"retry_codes": {
"idempotent": ["DEADLINE_EXCEEDED", "UNAVAILABLE"],
"non_idempotent": [],
},
"retry_params": {
"default": {
"init... | _name": "idempotent",
"retry_params_name": "default",
},
"UpdateTenant": {
"timeout_millis": 60000,
"retry_codes_name": "non_idempoten | t",
"retry_params_name": "default",
},
"DeleteTenant": {
"timeout_millis": 60000,
"retry_codes_name": "idempotent",
"retry_params_name": "default",
},
"ListTenants": {
... |
x = raw_inp | ut()
print x[0].upp | er() + x[1:]
|
.next_element
while i is not None:
yield i
i = i.next_element
@property
def next_siblings(self):
i = self.next_sibling
while i is not None:
yield i
i = i.next_sibling
@property
def previous_elements(self):
i = self.previou... | attribute_value = attribute_value.split()
return value in attribute_value
return _includes_value
elif operator == '^':
# string representation of `attribute` starts with `value`
return lambda el: el._attr_value_as_string(
attribute, | '').startswith(value)
elif operator == '$':
# string represenation of `attribute` ends with `value`
return lambda el: el._attr_value_as_string(
attribute, '').endswith(value)
elif operator == '*':
# string representation of `attribute` contains `value... |
from __future__ import unicode_literals
import uuid
from django.forms import UUIDField, ValidationError
from django.test import SimpleTestCase
class UUIDFieldTest(SimpleTestCase):
def test_uuidfield_1(self):
field = UUIDField()
value = field.clean('550e8400e29b41d4a716446655440000') |
self.assertEqual(value, uuid.UUID('550e8400e29b41d4a716446655440000'))
def test_uuidfield_2(self):
field = UUIDField(required=False)
value = field.clean('')
self.assertEqual(value, None)
def test_uuidfield_3(self):
field = UUIDField()
with self.assertRaises(Val... | m:
field.clean('550e8400')
self.assertEqual(cm.exception.messages[0], 'Enter a valid UUID.')
def test_uuidfield_4(self):
field = UUIDField()
value = field.prepare_value(uuid.UUID('550e8400e29b41d4a716446655440000'))
self.assertEqual(value, '550e8400e29b41d4a7164466554400... |
# coding=utf-8
import asyncio
import random
import json
import hashlib
import aiohttp
import async_timeout
import sys
class BaiduTranslate:
lang_auto = 'auto'
lang_zh = 'zh'
lang_en = 'en'
timeout = 20
api_addr = 'http://fanyi-api.baidu.com/api/trans/vip/translate'
def __init__(self, loop=... | , 'appid': self.appid, 'salt': salt, 'sign': sign}
async with aiohttp.ClientSession(loop=self.loop) as session:
with async_timeout.timeout(self.timeout, loop=self.loop):
async with session.post(self.api_addr,
data=params) as resp:
... | res['error_code'] != '52000':
raise RuntimeError(res['error_msg'])
return res['trans_result'][0]['dst']
|
from core.plugins.lib.proxies import MetricProxy, SourceProxy
from core.plugins.lib.models import PluginDataModel
from core.plugins.lib.fields import Field, ListField, DateTimeField, FloatField, IntegerField
from core.plugins.lib.scope import Scope, ZonePerm, BlockPerm
class BaseFitbitModel(PluginDataModel):
metri... | ance": DistanceModel,
"sleep/timeInBed": TimeInBedModel,
"sleep/minutesAsleep": MinutesAsleepModel,
"body/weight": WeightModel,
"sleep/efficiency": SleepEfficiencyModel,
"activities/activityCalories": ActivityCaloriesModel,
"sleep/startTime": SleepStartTimeModel,
"foods/log/caloriesIn": Calo... | /calories": CaloriesModel,
"foods/log/water": WaterModel
}
|
(self, TypeError, msg)
except:
from sys import exc_info
exc, value, tb = exc_info()
del tb
self.errorhandler(self, exc, value)
r = self._query('\n'.join([query[:p], ',\n'.join(q), query[e:]]))
if not self._defer_warnings: self._warning_check()
... | f mode == 'relative':
r = self.rownumber + value
| elif mode == 'absolute':
r = value
else:
self.errorhandler(self, ProgrammingError,
"unknown scroll mode %s" % `mode`)
if r < 0 or r >= len(self._rows):
self.errorhandler(self, IndexError, "out of range")
self.rownumber = r
... |
from django.contrib import admin
from holidays.models import (Holiday, StaticHoliday,
NthXDayHoliday, NthXDayAfterHoliday, CustomHoliday)
class HolidayAdmin(admin.ModelAdmin):
| pass
class StaticHolidayAdmin(admin.ModelAdmin):
pass
class NthXDayHolidayAdmin(admin.Mod | elAdmin):
pass
class NthXDayAfterHolidayAdmin(admin.ModelAdmin):
pass
class CustomHolidayAdmin(admin.ModelAdmin):
pass
admin.site.register(Holiday, HolidayAdmin)
admin.site.register(StaticHoliday, StaticHolidayAdmin)
admin.site.register(NthXDayHoliday, NthXDayHolidayAdmin)
admin.site.register... |
from datetime import timedelta
from django.conf import settings
from django.utils import timezone
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse
from django.contrib.auth.decorators import user_passes_test
from django.utils.importlib import import_module
from djangae.core.pa... | r.page(paginator.num_pages)
return render(request, "centaur/error.html", {
"error": error,
"events": events,
"series": series,
})
CLEANUP_QUEUE = getattr(settings, 'QUEUE_FOR_EVENT_CLEANUP', 'default')
@permission_decorator
def clear_old_events(request):
defer(_clear_old_events, ... | EANUP_QUEUE)
return HttpResponse("OK. Cleaning task deferred.")
EVENT_BATCH_SIZE = 400
ERROR_UPDATE_BATCH_SIZE = 50
def _update_error_count(error_id, events_removed):
@db.transactional(xg=True)
def txn():
_error = Error.objects.get(pk=error_id)
_error.event_count -= events_removed
... |
import functools
import pfp.interp
def native(name, ret, interp=None, send_interp=False):
"""Used as a decorator to add the decorated function to the
pfp interpreter so that it can be used from within scripts.
:param str name: The name of the function as it will be exposed in template scripts.
:param pfp.fields.... | for the :any:`Int3 <pfp.native.dbg.int3>` function. Notice that it
requires that the interpreter be sent as a parameter: ::
@native(name="Int | 3", ret=pfp.fields.Void, send_interp=True)
def int3(params, ctxt, scope, stream, coord, interp):
if interp._no_debug:
return
if interp._int3:
interp.debugger = PfpDbg(interp)
interp.debugger.cmdloop()
"""
def native_decorator(func):
@functools.wraps(func)
def native_wrapper(*args, **kwa... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
plot the results from the files igraph_degree_assort_study and degree_assortativity
'''
from igraph import *
import os
import numpy as np
import matplotlib.pyplot as plt
#########################
IN_DIR = '/home/sscepano/Projects7s/Twitter-workspace/ALL_SR'
img_out_pl... | ###################
#########################
# read from a file the res
#########################
def read_in_res():
f = open('7MODeg_assort_study.weighted_edge_list', 'r')
DA = []
TH = []
for line in f:
if line.startswith('stats for'):
th = float(line.split()[-1])
TH.append(th)
if line.startswith('Th... | t = th
f2 = open('plot_da_0.2.txt', 'r')
for line in f2:
(th, da) = line.split()
th = float(th)
if th < th_last:
continue
da = float(da)
TH.append(th)
DA.append(da)
f3 = open('DA_SR_th.tab', 'w')
for i in range(len(TH)):
f3.write(str(TH[i]) + '\t' + str(DA[i]) + '\n')
return TH, DA
def plot... |
from dungeon.dungeon import Dungeon
def main():
testdungeon = Dungeon('level1.txt')
pr | int(testdungeon)
if main.__name__ == '__mai | n__':
main() |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import sys
from getpass import getpass
from datetime import datetime
import pprint
from docopt import docopt
import requests
from .spelling import spellchecker
from .dispatch import dispatch
from .utils import login, validate_usernam... | args = parse_respect_args(sys.argv[1:])
if validate_username(args['<username>']):
print("processing...")
else:
print("@"+args['<username>'], "is not a valid username.")
print("Username may only contain alphanumeric ASCII characters or "
"dashes and cannot begin with a das... | r = requests.get(urljoin(GITHUB_USERS, args['<username>']))
except ConnectionErrorException as e:
print('Connection Error from requests. Request again, please.')
print(e)
if r.status_code == 404 or r.status_code == 403:
session = login(401, args=args)
return dispatch(args,... |
# ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2021, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This progra... | hook)
hooks.append(hook)
handles.append(handle)
tracked_modules[n] = m
return hooks, handles, tracked_modules
def start_tracking(self):
self._tracking = True
for hook in self.hooks:
hook.start_tracking()
| def stop_tracking(self):
self._tracking = False
for hook in self.hooks:
hook.stop_tracking()
def get_statistics(self):
"""
This returns a generator with elements
`(name, module, statistic_0, ..., statistic_n)`.
"""
return (
(name, m... |
# -*- encoding: utf-8 -*-
__author__ = 'pp'
__date__ = '6/25/14'
"""
georest.view.utils
~~~~~~~~~~~~~~~~~
helper/mixin things for views
"""
import sys
from functools import wraps
from flask import request
from .exceptions import InvalidRequest
from ..geo import GeoException
def get_json_content():
... | .get_data().decode('utf-8')
except UnicodeError:
raise InvalidRequest('Cannot decode content with utf-8')
return data
def get_if_match():
"""get if_match etag from request"""
etag = None
if request.if_match and not request.if_match.star_tag:
| try:
etag, = request.if_match.as_set() # only 1 allowed
except ValueError:
raise InvalidRequest('Cannot process if_match %s' % \
request.if_match)
return etag
def catcher(f):
"""catching uncatched errors, and filling the traceback"""
@wr... |
import sys
from sim import Sim
from node import Node
from link import Link
from transport import Transport
from tcp import TCP
from network import Network
import optparse
import os
import subprocess
class AppHandler(object):
def __init__(self,filename, directory):
self.filename = filename
self.di... | help="filename to send")
parser.add_option("-l","--loss",type="float",dest="loss",
default=0.0,
help="random loss rate")
parser.add_option("-w","--window",type="int",dest="window",
default=1000,
... | default=1,
help="number of iterations to run")
(options,args) = parser.parse_args()
self.filename = options.filename
self.loss = options.loss
self.window = options.window
self.iterations = options.iterations
def diff(self):
args = ['diff','... |
y.array('B')
a.fromstring(s)
d = Decoder(a, 0, len(a))
self.TryMerge(d)
def _CMergeFromString(self, s):
raise AbstractMethod
def __getstate__(self):
return self.Encode()
def __setstate__(self, contents_):
self.__init__(contents=contents_)
def sendCommand(self, server, url, resp... | .buf.append((v >> 0) & 255)
self.buf.append((v >> 8) & 255)
return
def put32(self, v):
if v < 0 or v >= (1L<<32): raise ProtocolBufferEncodeError, "u32 too big"
self.buf.append((v | >> 0) & 255)
self.buf.append((v >> 8) & 255)
self.buf.append((v >> 16) & 255)
self.buf.append((v >> 24) & 255)
return
def put64(self, v):
if v < 0 or v >= (1L<<64): raise ProtocolBufferEncodeError, "u64 too big"
self.buf.append((v >> 0) & 255)
self.buf.append((v >> 8) & 255)
self.buf.... |
"""
Copyright (C) 2017, 申瑞珉 (Ruimin Shen)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the | Free Software Foundation, either version 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 ... | with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import os
import re
import time
import shutil
import argparse
import configparser
import operator
import itertools
import struct
import numpy as np
import pandas as pd
import tensorflow as tf
import model.yolo2.inference as inference
import utils
d... |
model_search = "http://api.nytimes.com/svc/search/v2/" + \
"articlesearch.response-format?" + \
"[q=search term&" + \
"fq=filter-field:(filter-term)&additional-params=values]" + \
"&api-key=9key"
"""http://api.nytimes.com/svc/search/v2/articlesearch.json?q=terrorism+OR+t... | rms+dates+api)
original_json = json.loads(r.text)
response_json = original_json['response']
json_file = response_json['docs']
json_files.append(json_file)
frames = []
for x in json_files:
df = pd.DataFrame.from_dict(x)
frames.append(df)
#print(frames)
re | sult = pd.concat(frames)
result
|
import os
from django import template
from django.conf import settings
from django.utils.safestring import mark_safe
register = template.Library()
@register.simple_tag()
def custom_css():
theme_path = os.path.join(
settings.MEDIA_ROOT,
"overrides.css"
)
if os.path.exists(theme_path):
... | return ""
@register.simple_tag()
def custom_js():
theme_path = os.path.join(
settings.MEDIA_ROOT,
"override | s.js"
)
if os.path.exists(theme_path):
return mark_safe(
'<script src="{}"></script>'.format(
os.path.join(settings.MEDIA_URL, "overrides.js")
)
)
return ""
|
constants import *
def case3(output=True):
accuracy_in_each_turn = list()
precision_in_each_turn_spam = list()
recall_in_each_turn_spam = list()
precision_in_each_turn_ham = list()
recall_in_each_turn_ham = list()
m = np.loadtxt(open("resources/normalized_data.csv","rb"),delimiter=',')
... | = 1 ):
is_spam += 1
|
if guess == 1:
guessed_spam += 1
correctly_is_spam += 1
else:
guessed_ham += 1
else:
is_ham += 1
if guess == 1:
guessed_spam += 1
else:
... |
#!/usr/bin/python
# Copyright: (c) 2017, Giovanni Sciortino (@giovannisciortino)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
... | dule, argumen | ts):
# Execute subuscription-manager with arguments and manage common errors
rhsm_bin = module.get_bin_path('subscription-manager')
if not rhsm_bin:
module.fail_json(msg='The executable file subscription-manager was not found in PATH')
lang_env = dict(LANG='C', LC_ALL='C', LC_MESSAGES='C')
... |
import unittest
from factorial import fact
class TestFactorial(unittest.TestCase):
"""
Our basic test class
"""
def test_fact(self):
"""
The actual test.
Any method which starts with ` | `test_`` will considered as a t | est case.
"""
res = fact(5)
self.assertEqual(res, 120)
if __name__ == '__main__':
unittest.main()
|
# -*- coding: utf-8 -*-
#############################################################################
#
# Copyright (c) 2007 Martin Reisenhofer <martin.reisenhofer@funkring.net>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as pu... | raise osv.except_osv(_("Error!"), _("PDF is corrupted and unable to fix!"))
if not report_obj.write_attachment(cr, uid, "account.invoice", invoice_id, report_name="account.report_invoice", datas=base64.encodestring(data), context=context, origin="account.invoice | .attachment.wizard"):
raise osv.except_osv(_("Error!"), _("Unable to import document (check if invoice is validated)"))
return { "type" : "ir.actions.act_window_close" }
_columns = {
"document" : fields.binary("Document")
} |
# partial unit test for gmpy2 threaded mpz functionality
# relies on Tim Peters' "doctest.py" test-driver
import gmpy2 as _g, doctest, sys, operator, gc, queue, threading
from functools import reduce
__test__={}
def _tf(N=2, _K=1234**5678):
"""Takes about 100ms on a first-generation Macbook Pro"""
for i in ra... | es: (Number) {0}".format(_g.get_cache()[0]))
print(" Caching Values: (Size, | limbs) {0}".format(_g.get_cache()[1]))
thismod = sys.modules.get(__name__)
doctest.testmod(thismod, report=0)
if chat: print("Repeating tests, with caching disabled")
_g.set_cache(0,128)
sav = sys.stdout
class _Dummy:
def write(self,*whatever):
pass
try:
sys.s... |
class WordDistance(object):
def __init__(self, words):
""" |
initialize your data structure here.
:type words: List[str]
"""
self.word_dict = {}
for idx, w in enumerate(words):
self.word_dict[w] = | self.word_dict.get(w, []) + [idx]
def shortest(self, word1, word2):
"""
Adds a word into the data structure.
:type word1: str
:type word2: str
:rtype: int
"""
return min(abs(i - j) for i in self.word_dict[word1] for j in self.word_dict[word2])
#... |
# pylint: skip-file
# vim: expandtab:tabstop=4:shiftwidth=4
#pylint: disable=too-many-branches
def main():
''' ansible module for gcloud iam servicetaccount'''
module = AnsibleModule(
argument_spec=dict(
# credentials
state=dict(default='present', type='str',
... | ud.needs_update():
if module.check_mode:
module.exit_json(changed=False, msg='Would have performed an update.')
api_rval = gcloud.update_service_account()
if api_rval['returncode'] != 0:
module.fail_json(msg=api_rval)
module.exit_json(ch... | nged=True, results=api_rval, state="present|update")
module.exit_json(changed=False, results=api_rval, state="present")
module.exit_json(failed=True,
changed=False,
results='Unknown state passed. %s' % state,
state="unknown")
# pylint: disab... |
from framework.db import models
from framework.config import config
from framework.dependency_management.dependency_resolver import BaseComponent
from framework.dependency_management.interfaces import ResourceInterface
from framework.lib.general import cprint
import os
import logging
from framework.utils import FileOpe... | )
ConfigFile = FileOperations.open(resource_file, 'r').re | ad().splitlines() # To remove stupid '\n' at the end
for line in ConfigFile:
if '#' == line[0]:
continue # Skip comment lines
try:
Type, Name, Resource = line.split('_____')
# Resource = Resource.strip()
resources.add((Type,... |
a given user
-skipuser: Only process pages not edited by a given user
-timestamp: (With -user or -skipuser). Only check for a user where his edit is
not older than the given timestamp. Timestamp must be writen in
MediaWiki timestamp format which is "%Y%m%d%H%M%S"
If this para... | n category to every page that is edited. This is
useful when a category is being broken out from a template
parameter or when templates are being upmerged but more information
must be preserved.
other: First argument is the old templa | te name, second one is the new
name.
If you want to address a template which has spaces, put quotation
marks around it, or use underscores.
Examples:
If you have a template called [[Template:Cities in Washington]] and want to
change it to [[Template:Cities in Washington state]]... |
# -*- coding: utf-8 -*-
from canaimagnulinux.wizard.interfaces import IChat
from canaimagnulinux.wizard.interfaces import ISocialNetwork
from canaimagnulinux.wizard.utils import CanaimaGnuLinuxWizardMF as _
from collective.beaker.interfaces import ISession
from collective.z3cform.wizard import wizard
from plone impor... | plate import viewpagetemplatefile
import logging
logger = logging.getLogger(__name__)
class ChatGroup(group.Group) | :
prefix = 'chats'
label = _(u'Chats Information')
fields = field.Fields(IChat)
class SocialNetworkGroup(group.Group):
prefix = 'socialnetwork'
label = _(u'Social Network Information')
fields = field.Fields(ISocialNetwork)
class SocialNetworkStep(wizard.GroupStep):
prefix = 'Social'
... |
"""Pathname and path-related operations for the Macintosh."""
import os
from stat import *
__all__ = ["normcase","isabs","join","splitdrive","split","splitext",
"basename","dirname","commonprefix","getsize","getmtime",
"getatime","islink","exists","isdir","isfile",
"walk","exp... | (prefix)):
if prefix[:i+1] != item[:i+1]:
prefix = prefix[:i]
if i == 0: return ''
break
return prefix
def expandvars(path):
"""Dummy to retain interface-compatibility with other operating systems."""
return path
def expanduser(path)... | with other operating systems."""
return path
norm_error = 'macpath.norm_error: path cannot be normalized'
def normpath(s):
"""Normalize a pathname. Will return the same result for
equivalent paths."""
if ":" not in s:
return ":"+s
comps = s.split(":")
i = 1
while i... |
from datetime import datetime
def | foo(p):
"""Foo
:param datetime p: a date | time
<ref>
""" |
kState(QtCore.Qt.Checked)
else:
field.setCheckState(QtCore.Qt.Unchecked)
elif isinstance(value, float):
field = QtWidgets.QLineEdit(repr(value), self)
field.setCursorPosition(0)
field.setValidator(QtGui.QDoubleValidator(fiel... | box.button(btn_type)
if btn is not None:
btn.setEnabled(valid)
def accept(self):
self.data = self.formwidget.get()
QtWidgets.QDialog.accept(self)
def reject(self):
self.data = None
QtWidgets.QDialog.reject(self)
def apply(self):
self.app... | ", comment="", icon=None, parent=None, apply=None):
"""
Create form dialog and return result
(if Cancel button is pressed, return None)
data: datalist, datagroup
title: string
comment: string
icon: QIcon instance
parent: parent QWidget
apply: apply callback (function)
datalist:... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from PIL import Image
def graf2png(weburl, username, password, timeout, imgname, hwin, wwin, onlypanel):
driver = webdriver.PhantomJS()
driver.set_window_size(hwin, wwin)
... | ')
plocation = panel.location
psize = panel.size
left = plocation['x']
top = plocation['y']
right = plocation['x'] + psize['width']
bottom = plocation['y'] + psize['height']
pimg = Image.op | en(imgname)
pimg = pimg.crop((left, top, right, bottom))
pimgname = 'panel_' + imgname
pimg.save(pimgname)
print("Panel recortado guardado como: " + pimgname)
|
# -*- coding: utf-8 -*-
# Copyright © 2014-2018 GWHAT Project Contributors
# https://github.com/jnsebgosselin/gwhat
#
# This file is part of GWHAT (Ground-Water Hydrograph Analysis Toolbox).
# Licensed under the terms of the GNU General Public License.
# ---- Standard library imports
import os
import csv
import sys
... | _dir__, 'BRFOutput.txt')
with open(filename, 'r') as f:
reader = list(csv.reader(f))
header = []
for row in reader:
header.append(row)
if 'LagNo Lag A sdA SumA sdSumA B sdB SumB sdSumB' in row[0]:
break
# well = header[2][0].split()[-1]
# date0 = header[8][0].sp... | dataf.append([float(i) for i in row[0].split()])
count += 1
elif count in [2, 3]:
dataf[-1].extend([float(i) for i in row[0].split()])
count += 1
elif count == 4:
dataf[-1].extend([float(i) for i in row[0].split()])
count = 1
# ... |
_LUA_CMD_VERSION = '3'
_LUA_VERSION = '2.0'
_LUA_RECOVERY = 'LUARecovery'
_RM_HDISK = 'RemoveDevice'
_MGT_CONSOLE = 'ManagementConsole'
class LUAType(object):
"""LUA Vendors."""
IBM = "IBM"
EMC = "EMC"
NETAPP = "NETAPP"
HDS = "HDS"
HP = "HP"
OTHER = "OTHER"
class LUAStatus(object):
... | uid,
xag=(c.XAG.VIO_SMAP, c.XAG.VIO_FMAP))
scrub_ids = tsk_stg.find_stale_lpars(vwrap)
if scrub_ids:
# Detailed warning message by _log_lua_status
LOG.warning(_("hdisk discovery failed; will scrub stale storage "
"for L... | scrub_task = tx.FeedTask('scrub_vios_%s' % vios_uuid, [vwrap])
tsk_stg.add_lpar_storage_scrub_tasks(scrub_ids, scrub_task)
scrub_task.execute()
status, devname, udid = lua_recovery(adapter, vios_uuid, itls,
vendor=vendor,
... |
def create_consumer(self, topic, proxy, fanout=False):
self.connection.create_consumer(topic, proxy, fanout)
def create_worker(self, topic, proxy, pool_name):
self.connection.create_worker(topic, proxy, pool_name)
def join_consumer_pool(self, callback, pool_name, topic, exchange_name):
... | . There could be a MulticallProxyWaiter '
'leak.') % self._num_call_waiters_wrn_threshhold)
self._num_call_waiters_wrn_threshhold *= 2
self._call_waiters[msg_id] = waiter
def del_call_waiter(self, msg_id):
self._num_call_waiters -= 1
del self._call_waiters... | , connection_pool, reply=None,
failure=None, ending=False, log_failure=True):
"""Sends a reply or an error on the channel signified by msg_id.
Failure should be a sys.exc_info() tuple.
"""
with ConnectionContext(conf, connection_pool) as conn:
if failure:
failure = rp... |
owing:
# days, hours, minutes, seconds, milliseconds, microseconds, weeks
#
# Example for 1.5 days: sensorAutoReset = dict(days=1,hours=12),
#
# (value generated from SENSOR_AUTO_RESET)
'sensorAutoReset' : None,
},
'spEnable': Tr... | nfig['modelParams']['clParams']['steps'] = str(predictionSteps)
# Adjust config by applying ValueGetterBase-derived
# futures. NOTE: this MUST be called after updateConfigFromSubConfig() in order
# to support value-getter-based substitutions from the sub-experiment | (if any)
applyValueGettersToContainer(config)
dataPath = os.path.abspath(os.path.join(os.path.dirname(__file__),
'data.csv'))
control = {
# The environment that the current model is being run in
"environment": 'nupic',
# Input stream specification per py/nupicengine/cl... |
# - | *- coding: utf-8 -*-
from ihm.main_window import launch
if __name__ == '__main__':
launc | h()
|
"""
This component provides HA cover support for Abode Security System.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/cover.abode/
"""
import logging
from homeassistant.components.abode import AbodeDevice, DOMAIN as ABODE_DOMAIN
from homeassistant.comp... | er(data, device))
data.devices.extend(devices)
add_devices(devices)
class AbodeCover(AbodeDevice, CoverDevice):
"""Representation of an Abode cover."""
@property
def is_closed( | self):
"""Return true if cover is closed, else False."""
return not self._device.is_open
def close_cover(self, **kwargs):
"""Issue close command to cover."""
self._device.close_cover()
def open_cover(self, **kwargs):
"""Issue open command to cover."""
self._devi... |
source", resource['name'], resource['version'], "zip")
paths.append(
download(resource['name'], '%s/%s-%s.zip' % (resources_path, resource['name'], resource['version']), url))
return paths
def download_services(services):
paths = []
for service in services:
# for release < 1.22... | _files_into(policies_path, bundle_path + "plugins")
copy_files_into(resources_path, bundle_path + "plugins")
copy_files_into(fetchers_path, bundle_path + "plugins")
copy_files_into(repositories_path, bundle_path + "plugins", [".*gravitee-repository | -ehcache.*", ".*gravitee-repository-gateway-bridge-http-client.*", ".*gravitee-repository-gateway-bridge-http-server.*"])
copy_files_into(services_path, bundle_path + "plugins", [".*gravitee-gateway-services-ratelimit.*"])
copy_files_into(connectors_path, bundle_path + "plugins")
os.makedirs(bundle_path + "... |
import pandas as pd
from sqlalchemy import create_engine
from bcpp_rdb.private_settings import Rdb
class CCC(object):
"""CDC data for close clinical cohort."""
def __init__(self):
self.engine = create_engine('postgresql://{user}:{password}@{host}/{db}'.format(
user=Rdb.user, password=Rd... | rom dw.oc_crf_ccc_enrollment"""
def sql_refused(self):
"""
* If patient is from BCPP survye, oc_study_id is a BHP identifier.
* ssid is the CDC allocated identifier of format NNN-NNNN.
"""
return """select ssid as cdcid, oc_study_id as subject_ide | ntifier,
appt_date from dw.oc_crf_ccc_enrollment"""
|
c | lass Information(object):
def __init__(self, pygame):
self.pygame = pygame
self.display_fps = False
def _show_fps(self, clock, screen):
font = self. | pygame.font.SysFont('Calibri', 25, True, False)
text = font.render("fps: {0:.2f}".format(clock.get_fps()), True, (0, 0, 0))
screen.blit(text, [0, 0])
def show_fps(self, clock, screen):
if self.display_fps:
self._show_fps(clock, screen)
def toggle_fps(self):
self.dis... |
#!/usr/bin/env python
from __future__ import division
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib as mpl
import matplotlib.pyplot as plt
from scipy import linalg
import csv
import codecs
import copy
def comparison(trajOne, trajTwo):
segmentOne=np.array(trajOne)
segmentTwo=np.... | entOne[:,i]= segmentOne[:,i] - segmentOne[0,i]
segmentTwo[:,i]= segmentTwo[:,i] - segmentTwo[0,i]
dist=0
for i in range(min(len(trajOne), len(trajTwo))):
dist = dist + np.linalg.norm(segmentOne[i,2:]-segmentTwo[i,2:])
return dist
def plotTraj(jointTrajectory):
fig = plt.figure()
a... | abel("$\Theta_{3}$ [deg]", size=30)
# ax.plot(jointTrajectory[:,2], jointTrajectory[:,3], jointTrajectory[:,4], lw=2,color='red',label='Human-Guided Random Trajectory')
ax.plot(jointTrajectory[:,2], jointTrajectory[:,3], jointTrajectory[:,4], lw=2,color='red',label='Human-Guided Random Trajectory .')
ax.le... |
import os
import sys
import numpy as np
import math
def findBinIndexFor(aFloatValue, binsList):
#print "findBinIndexFor: %s" % aFloatValue
returnIndex = -1
for i in range(len(binsList)):
thisBin = binsList[i]
if (aFloatValue >= thisBin[0]) and (aFloatValue < thisBin[1]):
returnIndex = i
break
return ... |
if joint_xy!=0 and marginal_y!=0:
h_acc-=joint_xy*math.log(joint_xy/marginal_y, 2)
# for yVal in yVals:
# new_xDist = getXForFixedY(joint_prob_dist, yVal)
# h_yVal = compute_h(new_xDist)
# p_yVal = reduce(lambda x, y: x+y, new_xDist)
# h_acc+=p_yVal * h_yVal
returnFloat = h_acc
r | eturn returnFloat
def getYMarginalDist(joint_prob_dist):
returnDict = {}
for xKey in joint_prob_dist:
for yKey in joint_prob_dist[xKey]:
if not yKey in returnDict:
returnDict[yKey] = 0
returnDict[yKey]+=joint_prob_dist[xKey][yKey]
return returnDict
def getXMarginalDist(joint_prob_dist):
returnDict... |
onfig) as sess:
sess.run(self.init) # sess.run(tf.initialize_all_variables())
dynStats = DynStats(validation=valid_data is not None)
for epoch in range(epochs):
train_error, runTime = getRunTime(
lambda:
self.trainEpoch(
... | print hidden_enc_layer
print
with tf.name_scope('encoder_state_out_process'):
# don't really care for encoder outputs, but only for its final state
# the encoder consumes all the input to get a sense of the trend of price history
... | batch_norm_and_l2(fcId='encoder_state_out_process',
# inputs=encoder_final_state,
# input_dim=enc_num_units, output_dim=self.DIM_REDUCTION,
# ... |
import sys
sys.path.insert(1,"../../../")
import h2o, tests
def deepLearningDemo():
# Training data
train_data = h2o.import_file(path=tests.locate("smalldata/gbm_test/ecology_model.csv"))
train_data = train_data.drop('Site')
train_data['Angaus'] = train_data['Angaus'].asfactor()
print train_data.descri... | validation_y= test_data ['Angaus'],
ntrees=100,
distribution="bernoulli")
gbm.show()
# Run DeepLearning
dl = h2o.deeplearning(x = train_data[1:],
y = train_data['Angaus'],
validation_x= test_data [1:] ... | = 1000,
hidden = [20, 20, 20])
dl.show()
if __name__ == "__main__":
tests.run_test(sys.argv, deepLearningDemo)
|
vcs links, regression test for issue #798.
"""
result = script.pip(
'download', '-d', '.', 'git+git://github.com/pypa/pip-test-package.git'
)
assert (
Path('scratch') / 'pip-test-package-0.1.1.zip'
in result.files_created
)
assert script.site_packages / 'piptestpackage' ... | ,
'--only-binary=:all:',
'--dest', '.',
'--python-version', '2',
| 'fake'
)
assert (
Path('scratch') / 'fake-1.0-py2.py3-none-any.whl'
in result.files_created
)
result = script.pip(
'download', '--no-index', '--find-links', data.find_links,
'--only-binary=:all:',
'--dest', '.',
'--python-version', '3',
'f... |
from bottle import route, default_app
app = default_app()
data = {
"id": 78874,
"seriesName": "Firefly",
"aliases": [
"Serenity"
],
"banner": "graphical/78874-g3.jpg",
"seriesId": "7097",
"status": "Ended",
"firstAired": "2002-09-20",
"network": "FOX (US)",
"networkId": "... | rama",
"Science-Fiction"
],
"overview": "In the far-distant future, Captain Malcolm \"Mal\" Reynolds is a renegade former brown-coat sergeant, now turned smuggler & rogue, "
"who is the commander of a small spacecraft, with a loyal hand-picked crew made up of the first mate, Zoe Warren; the pilot Hoba... | he gung-ho grunt Jayne Cobb; the engineer Kaylee Frye; the fugitives Dr. Simon Tam and his psychic sister River. "
"Together, they travel the far reaches of space in search of food, money, and anything to live on.",
"lastUpdated": 1486759680,
"airsDayOfWeek": "",
"airsTime": "",
"rating": "TV-14",
... |
# -*- coding: utf-8 -*-
"""
Copyright (C) 201 | 4-2016 bromix (plugin.video.youtube)
Copyright (C) 2016-2018 plugin.video.youtube
SPDX-License-Identifier: GPL-2.0-only
See LICENSES/GPL-2.0-only for more information.
"""
from . import const_settings as setting
from . import const_localize as localize
from . import const_sort_methods as sort_method
from ... | 'localize', 'sort_method', 'content_type', 'paths']
|
l plus 2" or channel == "canal+ 2 hd":
channel = "canal+ 2"
epg_channel = epg_formulatv(params, channel)
return epg_channel
elif channel == "canal+ 1 ...30" or channel == "canal+ 1... 30":
channel = "canal+ 1 ...30"
epg_channel = epg_formulatv(params, channel) ... | return epg_channel
elif channel == "40 TV":
channel = "40 tv"
epg_channel = epg | _formulatv(params, channel)
return epg_channel
elif channel == "canal sur" or channel == "andalucia tv":
channel = "canal sur"
epg_channel = epg_formulatv(params, channel)
return epg_channel
elif channel == "aragón tv" or channel == "aragon tv":
channel = ... |
ctType, values.W_Object, procedure,
values.W_Object, values.W_Object], simple=False, extra_info=True)
@jit.unroll_safe
def do_checked_procedure_check_and_extract(type, v, proc, v1, v2, env, cont, calling_app):
from pycket.interpreter import check_one_val, return_value
if isinstance(v, values_struct.W_R... | !", [values.W_MBox, values.W_Object], simple=False)
def unsafe_make_place_local(p, v, env, cont):
return p.set_box(v, env, cont)
@expose("set!-transformer?", [values.W_Object], only_old=True)
def set_bang_transformer(v):
if isinstance(v, values.W_AssignmentTransformer):
return values.w_true
elif is... | ansformer)
return values.W_Bool.make(w_property is not None)
else:
return values.w_false
@expose("object-name", [values.W_Object])
def object_name(v):
if isinstance(v, values.W_Prim):
return v.name
elif isinstance(v, values_regex.W_AnyRegexp) or isinstance(v, values.W_Port):
... |
import sys
from resources.datatables import Options
from resources.datatables import StateStatus
def addPlanetSpawns(core, planet):
stcSvc = core.staticService
objSvc = core.objectService
#junkdealer
stcSvc.spawnObject('junkdealer', 'naboo', long(0), float(-5694), float(6.5), float(4182), float(0.707), float(... | loat(6.6), float(4234), float(0.71), float(0.71))
stcSvc.spawnObject('junkdealer', 'naboo', long(0), float(-5475), float(6), float(4105), float(0.71), float(0.71))
stcSvc.spawnObject('junkdealer', 'naboo', long(0), float(-4999), float(6), float(4119), float(0.71), float(0.71))
s | tcSvc.spawnObject('junkdealer', 'naboo', long(0), float(-5883), float(6), float(4214), float(0.71), float(0.71))
return
|
#!/usr/bin/env python
#
# Copyright 2016 timercrack
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. | You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# L... | the License.
def str_to_number(s):
try:
if not isinstance(s, str):
return s
return int(s)
except ValueError:
return float(s)
|
'VolumeId': vol_id,
'DeleteOnTermination': True
}
}
]
)
if instance_running:
client.start_instances(InstanceIds=[instance_id])
if self.verbose:
... | d" % volume_id)
elif | instance_id:
if self.verbose:
self.log.debug("Waiting on instance stop")
waiter = client.get_waiter('instance_stopped')
waiter.wait(InstanceIds=[instance_id])
if self.verbose:
self.log.debug("Instance: %s stopped" % instance_id)
@EBS.act... |
from django_comments.forms import CommentForm
from bogofil | ter.models import BogofilterComment
import time
class BogofilterCommentForm(CommentForm):
def get_comment_model(self):
retu | rn BogofilterComment
|
import subprocess
import pynotify
import time
def notify_with_subprocess(title, message):
subprocess.Popen(['notify-send', title, message])
return
def notify_with_pynotify(title, message):
| pynotify.init("Test")
notice = pynotify.Notification(title, message)
notice.show()
return
def update_with_pynotify():
pynotify.init("app_name")
n = pynotify.Notification("", "message A", icon='some_icon')
n.set_urgency(pynotify.URGENCY_CRITICAL)
n.set_timeout(10)
n.show()
n.upda... | =None, action=None, data=None):
print "It worked!"
pynotify.init("app_name")
n = pynotify.Notification("Title", "body")
n.set_urgency(pynotify.URGENCY_NORMAL)
n.set_timeout(100)
n.show()
#n.add_action("clicked","Button text", callback_function, None)
#n.update("Notification", "Update for you")
#n.show()
... |
#!/usr/bin/env python
# Creates and saves a JSON file to update the D3.js graphs
import MySQLdb
import MySQLdb.cursors
import json
import Reference as r
import logging
def CreateSentimentIndex(NegativeWords, PositiveWords, TotalWords):
''' Creates a sentiment value for the word counts'''
if TotalWords... | nt = CreateSentimentIndex(Row['Negative'], Row['Positive'], Row['TotalWords'])
Output.append({"date" : RowDate, "index" : RowSentiment})
return Output
def Outpu | tJsonFile(InputDictionary):
'''Saves a dictionary to an output file in a JSON format'''
JsonOutput = json.dumps(InputDictionary)
OutputFileName = 'json/twittermetrics_sentiment.js'
FileOutput = open(OutputFileName,'w')
print >> FileOutput, JsonOutput
return True
def CreateJson... |
#
# DBus interface for payload Repo files image source.
#
# Copyright (C) 2020 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# ... | py o | f the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and ma... |
import pandas as pd
import numpy as np
import sklearn.preprocessing
from sklearn.linear_model import LinearRegression, LogisticRegression
FILENAME = 'BrainMets.xlsx'
MONTHS_TO_LIVE = 9
N_TRAIN = 250
def categorical_indices(values):
"""
When we have a categorical feature like 'cancer type', we want to transform its ... | p.array(Y.isnull())
X_train = X[~(missing)]
Y_train = Y[~missing]
X_test = X[missing]
model.fit(X_train, Y_train)
Y_test = model.predict(X_test)
Y_test = postprocess(Y_test)
if maxval:
Y_test = np.minimum(Y_test, maxval)
Y_filled = Y.copy()
Y_filled[missing] = Y_test
df[name] = Y_filled
def impute_missing... | rior WBRT',
'Diagnosis of Primary at the same time as Brain tumor'
]]
X = np.array(input_fields)
missing = df['Extracranial Disease Status'].isnull()
impute(X, df, 'Extracranial Disease Status', LogisticRegression())
impute(X, df, 'K Score', LinearRegression(), lambda x: 10*(x.astype('int')/10), maxval = 100)
... |
# -*- coding: utf-8 -*-
from rdflib import Namespace
ONTOLEX = Namesp | ace("http://www.w3.org/ns/lemon/ontolex#")
LEXINFO = Namespace("http://www.lexinfo.net/ontology/2.0/lexinfo#")
DECOMP = Namespac | e("http://www.w3.org/ns/lemon/decomp#")
ISOCAT = Namespace("http://www.isocat.org/datcat/")
LIME = Namespace("http://www.w3.org/ns/lemon/lime#")
|
'''
'''
import sys
import os
import gzip
import regex
# 'borrowed' from CGAT - we may not need this functionality
# ultimately. When finalised, if req., make clear source
def openFile(filename, mode="r", create_dir=False):
''' | open file called *filename* with mode *mode*.
gzip - compressed files are recognized by the
suffix ``.gz`` and opened transparently.
Note that there are differences in the file
like objects returned, for example in the
ability to seek.
Arguments
---------
filename : string
mode : ... | eated if it does not exist.
Returns
-------
File or file-like object in case of gzip compressed files.
'''
_, ext = os.path.splitext(filename)
if create_dir:
dirname = os.path.dirname(filename)
if dirname and not os.path.exists(dirname):
os.makedirs(dirname)
i... |
from comics.aggregator.crawler import CrawlerBase
from comics.core.comic_data import ComicDataBase
class ComicData(ComicDataBase):
name = "PartiallyClips"
| language = "en"
url = "http://partiallyclips.com/"
| start_date = "2002-01-01"
rights = "Robert T. Balder"
active = False
class Crawler(CrawlerBase):
def crawl(self, pub_date):
pass
|
# !/usr/bin/env python
"""Testing a sprite.
The ball should bounce off the sides of the window. You may resize the
window.
This test should just run without failing.
"""
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import os
import unittest
from pyglet.gl import glClear
import pyglet.window
import pygl... | cySprite(288, 0, 64, 64, image,
| properties=dict(dx=-10, dy=5))
view = FlatView(0, 0, 320, 320, sprites=[ball1, ball2])
view.fx, view.fy = 160, 160
clock.set_fps_limit(60)
e = TintEffect((.5, 1, .5, 1))
while not w.has_exit:
clock.tick()
w.dispatch_events()
... |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "itf.settings")
try:
from django.core.management import execute_from_command_line
except | ImportError:
# The above import may fail for some other reason. Ensure that the
# issue is really that Django is missing to avoid masking other
# exceptions on Python 2.
try:
import django
except ImportError:
| raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
)
raise
execute_from_command_line(sys.argv)
|
#!/usr | /bin/env python
# Copyright (C) 2006-2016 Music Technology Group - Universitat Pompeu Fabra
#
# This file is part of Essentia
#
# Essentia is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Foundation (FSF),... | ibuted 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 the Affero GNU General Public License
# version 3 along ... |
# PyParticles : Particles simulation in python
# Copyright (C) 2012 Simone Riva
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any late... | oundary( self , p_set ):
v_mi = np.zeros((3))
v_mx = np.zeros((3))
for i in range( self.dim ) :
j = 2*i
v_mi[:] = 0.0
v_mx[:] = 0.0
#delta = self.bound[i,1] - self.bound[i,0]
b_mi... | = p_set.X[:,i] < self.bound[i,0]
b_mx = p_set.X[:,i] > self.bound[i,1]
v_mi[i] = self.bound[i,0]
v_mx[i] = self.bound[i,1]
p_set.X[b_mi,:] = p_set.X[b_mi,:] + 2.0 * self.__N[j,:] * ( v_mi - p_set.X[b_mi,:] )
p_set.X[b_mx,:... |
, matricula , full_search = False ):
# Exibicao default de matricula/nome/curso/situacao/periodo/CRA
# full search para as demais informacoes
# Main url
self.aluno_online_url = 'https://www.alunoonline.uerj.br'
# parameters
self.matricula = matricula
self.full_search = full_search
# Ma... | situacao = self.main_html.find_all( 'div' )[4].text[11:]
except:
situacao = ''
return situacao
def _extract_periodo( self ):
try:
for element in self.main_html.select( 'div > b' ):
if ( element.te | xt == "Períodos Utilizados/Em Uso para Integralização Curricular:" ):
periodo = int( element.parent.text[59:] )
except:
periodo = ''
return periodo
def _format_telefone( self , ddd , tel , ramal ):
return '({0}) {1} [{2}]'.format( ddd , tel[:4] + '-' + tel[4:] , ( 'Sem Ramal' if not ramal else ( 'Ramal... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.