prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
# -*- mode: python; coding: utf-8; -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
class KeyValueSerializer(object):
def __init__(self, event, inline=()):
s | elf.event = event
self.inline = inline
def format_string(self):
return ' '.join(
'{}=%s'.format(k)
if k not in self.inline
else '{}="{}"'.format(k, str(v).encode('unicode_escape').decode())
for k, v in self.event.items()
)
def arguments(s... | urn [v for k, v in self.event.items(omit=self.inline)]
|
import shopify
from test.test_help | er import TestCase
class EventTest(TestCase):
def test_prefix_uses_resource(self):
prefix = shopify.Event._prefix(options={"resource": "orders", "resource_id": 42})
self.assertEqual("https://this-is-my-test-show.myshopify.com/admin/api/unstable/orders/42", prefix)
def test_prefix_doesnt_need_... | ix)
|
# Fuck you Disyer. Stealing my fucking paypal. GET FUCKED: toontown.chat.TTSCWhiteListTerminal
from otp.speedchat.SCTerminal import SCTerminal
from otp.otpbase.OTPLocalizer import SpeedChatStaticText
SCStaticTextMsgEvent = 'SCStaticTextMsg'
class TTSCWhiteListTerminal(SCTerminal):
def __init__(self, textId... | f.textId = textId
self.text = SpeedChatStaticText[self.textId]
print 'SpeedText %s %s' % (self.textId, self.text)
def handleSelect(self):
SCTerminal.handleSelect(self)
if not self.parentClass.whisperAvatarId:
base.localAvatar.chatMgr.fsm.request('whiteListOpenChat... | tarId]) |
#### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOS | T IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENT | ATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Creature()
result.template = "object/mobile/shared_dressed_rebel_brigadier_general_sullustan_male.iff"
result.attribute_template_id = 9
result.stfName("npc_name","sullustan_base_male")
#### BEGIN MODIFICATIONS ####
#### END MODIFI... |
"""
9012 : 괄호
URL : https: | //www.acmicpc.net/problem/9012
Input :
6
(())())
(((()())()
(()())((()))
((()()(()))(((())))()
()()()()(()()())()
(()((())()(
| Output :
NO
NO
YES
NO
YES
NO
"""
N = int(input())
for _ in range(N):
ps = input()
if ps[-1] is '(':
print("NO")
else:
count = 0
for c in ps:
if c is '(':
count += 1
elif c is ')':
... |
import configparser
parser = c | onfigparser.SafeConfigParser()
parser.add_section('bug_tracker')
parser.set('bug_tracker', 'url', 'http://localhost:8080/bugs')
parser.set('bug_tracker', 'username', 'dhellmann')
parser.set('bug_tracker', 'password', 'secret')
for section in parser.sections():
print(section)
for name, value in parser.items(se... | print(' {} = {!r}'.format(name, value))
|
import unittest
from .. import views
class TestViews(unittest.TestCase):
def setUp(s | elf):
pass
def test_nothing(self): |
views
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import sys
from intelmq.lib import utils
from intelmq.lib.bot import Bot
from intelmq.lib.message import Event
class MalwareGroupIPsParserBot(Bot):
def process(self):
report = self.receive_message()
if not report:
self.... | " 00:00:00 UTC"
event = Event(report)
event.add('time.source', time_source, sanitize=True)
event.add('classification.type', u'malware')
event.add('source.ip', ip, sanitize=True)
event.add('raw | ', row, sanitize=True)
self.send_message(event)
self.acknowledge_message()
if __name__ == "__main__":
bot = MalwareGroupIPsParserBot(sys.argv[1])
bot.start()
|
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... | atus== 'confirm':
return "Confirmado"
if status== 'recurrent':
return "Recurrente"
return ""
def select_diseases_type(self, diseases_type):
if diseases_type== 'main':
return "Principal"
if diseases_type== 'related':
return "Relacionado"
return ""
report_sxw.report_sxw('report.doctor_disability_... | |
port database_exists, create_database
from datatables import ColumnDT, DataTables
MS_WD = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
CONFIG_FILE = os.path.join(MS_WD, "api_config.ini")
if os.path.join(MS_WD, 'libs') not in sys.path:
sys.path.append(os.path.join(MS_WD, 'libs'))
import ... | base-specific part of the API config file
"""
if os.path.isfile(configfile):
# Read in the old config
config_parser.read(configfile)
if | not config_parser.has_section(self.__class__.__name__):
config_parser.add_section(self.__class__.__name__)
if not usr_override_config:
usr_override_config = self.DEFAULTCONF
# Update config
for key_ in usr_override_config:
config_parser.set(self.__class... |
/neighbor (list)
YANG Description: This list defines ISIS extended reachability neighbor
attributes.
"""
return self.__neighbor
def _set_neighbor(self, v, load=False):
"""
Setter method for neighbor, mapped from YANG variable /network_instances/network_instance/protocols/protocol/isis/... | s/tlv/isis_neighbor_attribute/neighbors/neighbor (lis | t)
If this variable is read-only (config: false) in the
source YANG file, then _set_neighbor is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_neighbor() directly.
YANG Description: This list defines ISIS extended reachability neighb... |
"""
Support for RESTful binary sensors.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/binary_sensor.rest/
"""
import logging
from homeassistant.components.binary_sensor import BinarySensorDevice
from homeassistant.components.sensor.rest import RestData... | rify_ssl = config.get('verify_ssl', True)
rest = RestData(method, resource, payload, verify_ssl)
rest.update()
if rest.data is None:
_LOGGER.error('Unable to fetch Rest data')
return False
add_devices([RestBinarySensor(
hass, rest, config.get('name', DEFAULT_NAME),
con... | binary sensor."""
def __init__(self, hass, rest, name, value_template):
"""Initialize a REST binary sensor."""
self._hass = hass
self.rest = rest
self._name = name
self._state = False
self._value_template = value_template
self.update()
@property
def ... |
# Copyright 2013 Allen Institute
# This file is part of dipde
# dipde is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# dipde is dis... | sys.exit(errcode)
setup(
name='dipde',
version=dipde.__version__,
url='https://github.com/AllenBrainAtlas/DiPDE',
author='Nicholas Cain',
tests_require=['pytest'],
install_requires=[],
cmdclass={'test': PyTest},
author_email='nicholasc@alleninstitute.org',
description='Nume... | nd_packages('dipde'),
include_package_data=True,
package_data={'':['*.md', '*.txt', '*.cfg']},
platforms='any',
classifiers = [
'Development Status :: 3 - Alpha',
'Intended Audience :: Science/Research',
'License :: Apache Software License :: 2.0',
'Natural Language :: En... |
# -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | the ``items`` field | on the
corresponding responses.
All the usual :class:`google.cloud.compute_v1.types.NotificationEndpointList`
attributes are available on the pager. If multiple requests are made, only
the most recent response is retained, and thus used for attribute lookup.
"""
def __init__(
self,
... |
__author_ | _ = 'Pe | r'
|
#!/usr/bin/env python
import TransferErrors as TE
import cPickle as pic | kle
with open('stuck.pkl','rb') as pklfile:
stuck = pickle.load(pklfile)
TE.makeBasicTable(stuck,TE | .workdir+'html/table.html',TE.webdir+'table.html')
TE.makeCSV(stuck,TE.webdir+'data.csv')
for basis in [-6,-5,-4,-3,-1,1,2]:
TE.makeJson(stuck,TE.webdir+('stuck_%i'%basis).replace('-','m')+'.json',basis)
|
"""
Certificate generation module.
"""
from OpenSSL import crypto
TYPE_RSA = crypto.TYPE_RSA
TYPE_DSA = crypto.TYPE_DSA
def createKeyPair(type, bits):
"""
Create a public/private key pair.
Arguments: type - Key type, must be one of TYPE_RSA and TYPE_DSA
bits - Number of bits to use in the... | ountry name
ST - State or province name
L - Locality name
O - Organization name
OU - Organizational unit name
CN | - Common name
emailAddress - E-mail address
Returns: The certificate request in an X509Req object
"""
req = crypto.X509Req()
subj = req.get_subject()
for (key,value) in name.items():
setattr(subj, key, value)
req.set_pubkey(pkey)
req.sign(pkey, digest... |
from threading import Thread
import pickle
import time
from pymouse import PyMouse
# from evdev import InputDevice, ecodes, UInput
from evdev import UInput, ecodes
class History(Thread):
def __init__(self):
Thread.__init__(self)
self.n = 0
self.st = | True # Stop
self.sl = False # Sleep
self.ui = UInput()
self.history = []
self.m = PyMouse()
self.flag = True
self.rec = False
def send_event(self):
i = 0
while i < len(self.history):
now = self.history[i]
if i < len... | self.m.move( now.get("mouse")[0], now.get("mouse")[1])
if now.get("event").type == ecodes.EV_KEY:
self.ui.write(ecodes.EV_KEY, now.get("event").code, now.get("event").value)
self.ui.syn()
if i < len(self.history):
tim... |
# -*- coding: utf-8 -*-
# License | AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
from . import t | est_account_payment_transfer_reconcile_batch
|
class PlotEnum():
| point = 'POINT',
line = | 'LINE',
bar = 'BAR' |
:param test: The test that has been skipped.
:param err: The exc_info of the error that was raised.
:return: None
"""
# This is the python 2.7 implementation
self.expectedFailures.append(
(test, self._err_details_to_string(test, err, details)))
def addErro... | getattr(result, message)(*args, **kwargs)
for result in self._results)
def startTest(self, test):
return self._dispatch('startTest', test)
def stopTest(self, test):
return self._dispatch('stopTest', test)
def addError(self, test, er | ror=None, details=None):
return self._dispatch('addError', test, error, details=details)
def addExpectedFailure(self, test, err=None, details=None):
return self._dispatch(
'addExpectedFailure', test, err, details=details)
def addFailure(self, test, err=None, details=None):
... |
from django.conf.urls import patterns, url
from allauth.socialaccount.providers.oauth2.urls import default_urlpatterns
from .provider import FacebookProvider
from . import views
urlpatterns = default_urlpatterns(FacebookProvide | r)
urlpatterns += patterns('',
url('^facebook/login/token/$', views.login_by_token,
name="facebook_login_by_token"),
url('^facebook/c | hannel/$', views.channel, name='facebook_channel'),
)
|
import re
from decimal import Decimal
import sys
import struct
from rdbtools.parser import RdbCallback, RdbParser
ESCAPE = re.compile(ur'[\x00-\x1f\\"\b\f\n\r\t\u2028\u2029]')
ESCAPE_ASCII = re.compile(r'([\\"]|[^\ -~])')
HAS_UTF8 = re.compile(r'[\x80-\xff]')
ESCAPE_DCT = {
'\\': '\\\\',
'"': '\\"',
'\b': ... | tents of RDB in a format that is unix sort friendly,
so that two rdb files can be diffed easily'''
def __init__(self, out):
self._out = out
self._ind | ex = 0
self._dbnum = 0
def start_rdb(self):
pass
def start_database(self, db_number):
self._dbnum = db_number
def end_database(self, db_number):
pass
def end_rdb(self):
pass
def set(self, key, value, expiry, info):
self.... |
:
q = hawkey.Query(self.sack)
self.assertRaises(hawkey.ValueException, q.filter, flying__eq="name")
self.assertRaises(hawkey.ValueException, q.filter, flying="name")
def test_unicode(self):
q = hawkey.Query(self.sack)
q.filterm(name__eq=u"flying")
self.assertEqual(q.... | (empty=True)
self.assertLength(q, 0)
q = hawkey.Query(self.sack)
self.assertRaises(hawkey.ValueExcep | tion, q.filter, empty=False)
def test_epoch(self):
q = hawkey.Query(self.sack).filter(epoch__gt=4)
self.assertEqual(len(q), 1)
self.assertEqual(q[0].epoch, 6)
def test_version(self):
q = hawkey.Query(self.sack).filter(version__gte="5.0")
self.assertEqual(len(q), 3)
... |
ffix for filtering the variables to return.
Returns:
a list of variables in the trainable collection with scope and suffix.
"""
return get_variables(scope, suffix, ops.GraphKeys.TRAINABLE_VARIABLES)
def get_variables_to_restore(include=None, exclude=None):
"""Gets the list of the variables to restore.
... | et_variables(sco | pe)
vars_to_exclude = set()
if exclude is not None:
if not isinstance(exclude, (list, tuple)):
raise TypeError('exclude is provided but is not a list or a tuple.')
for scope in exclude:
vars_to_exclude |= set(get_variables(scope))
# Exclude the variables in vars_to_exclude
return [v for v in... |
import numpy as np
class LinfinityRegression:
def __init__(self, iterations, learning_rate, regularization_strength):
self.iterations = iterations
self.learning_rate = learning_rate
self.regularization_strength = re | gularization_strength
@staticmethod
def soft_thresholding_operator(x, l):
"""
This method is used to update the weights when performing Gradient Descent.
Whenever the loss function is just the least square loss function, we can minimize by taking the derivative.
However, we cann... | am l:
:return:
"""
maxw = max(x)
for i in range(0, len(x)):
if np.abs(x[i]) > np.abs(maxw):
x[i] = l*np.sign(x[i])
elif np.abs(x[i]) < np.abs(maxw) :
x[i] = l*np.sign(maxw)
return x
@staticmethod
def mse_cost_fun... |
#### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE | SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/loot/loot_schematic/shared_park_bench_schematic.iff"
result.attribute_template_id = -1
result.stfName("craft_item_ingredients_n","park_bench")
#### BEGIN | MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a co | py of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
from ctypes import sizeof, windll, addressof, create_unicode_buffer
from ctypes.wintypes import DWORD, HANDLE
PROCESS_TERMINATE = 0x0001
PROCESS_QUERY_INFORMATION = 0x0400
PROCESS_VM_READ = 0x0010
def get_pids(proc... | sizeof(processes),
addressof(needed))
if not result:
return pids
num_results = needed.value / sizeof(DWORD)
for i in range(num_results):
pid = processes[i]
process = windll.kernel32.OpenProcess(PROCESS_QUERY_... |
nMegaList:
name = a[0]
codeName = a[0].lower().replace(" ", "_")
shortDesc = (a[3][:60] + '...') if len(a[3]) > 60 else a[3]
icon = ("package-x-generic") if iconTheme.has_icon(defaultIconTheme, a[4]) == False else a[4]
installMethod = a[5]
sniqtPrefix = a[1]
if isinstance(a[2], list):
... | if availableComponents[i][1] == "core_icon_theme":
currentTheme = systemSettings.get_string("icon-theme")
if currentTheme == iconThemeName:
componentSwitch.set_active(True)
wrap = G | tk.HBox(0)
wrap.pack_start(item, True, True, 0)
wrap.pack_end(componentSwitch, False, False, 2)
if availableComponents[i][6] is False:
wrap.set_sensitive(False)
wrap.set_tooltip_text(longDesc)
self.lbox.add(wrap)
return scroller
... |
# coding=utf-8
from ._commandbase import RadianceCommand
from ..datatype import RadiancePath
import os
class Epw2wea(RadianceCommand):
"""epw2wea transforms an EnergyPlus weather data (.epw) file into
the DAYSIM weather file format, for use with the RADIANCE gendaymtx
program.
Attributes:
ep... | '),
self.epw_file.to_rad_string(),
self.output_wea_file.to_rad_string())
# self.check_input_files(rad_string)
return rad_string
| @property
def input_files(self):
"""Return input files specified by user."""
return self.epw_file.normpath,
|
', 'coins', 'friends', 'ignores', 'requests', 'inventories', 'mails', 'memberships',
'musicTracks', 'puffles', 'stamps', 'stampCovers', 'igloos']
class Coin(DBObject):
pass
class Igloo(DBObject):
HASMANY = ['iglooFurnitures', 'iglooLikes']
@inlineCallbacks
def get_likes_count(self):
... | res = yield self.iglooFurnitures.get()
returnValue(furnitures)
@inlineCallbacks
def get_furnitures_string(self):
furnitures = yield self.get_furnitures()
furn_data = map(lambda i: '|'.join(map(str, map(int, [i.furn_id, i.x, i.y, i.rotate, i.frame]))), furnitures)
returnValue('... | itures):
yield self.refresh()
yield IglooFurniture.deleteAll(where=['igloo_id = ?', self.id])
furn = [IglooFurniture(igloo_id=self.id, furn_id=x[0], x=x[1], y=x[2], rotate=x[3], frame=x[4])
for x in furnitures]
[(yield i.save()) for i in furn]
yield self.iglooFu... |
from abc import ABCMeta, abstractmethod
import json
import os
try:
import redis
except ImportError:
pass
from .config import Config
def get_cache(cache, config=None):
if isinstance(cache, str):
if cache == 'JsonCache':
return JsonCache()
elif cache == 'RedisCache':
... | self.redis.get(key)
if value is not None:
value = value.decode('UTF-8')
return value
def set(self, key, value):
self._connect()
result = self.redis.set(key, value)
if result > 0:
return True
else:
return False
def delete(sel... | if result > 0:
return True
else:
return False
def _connect(self):
if self.redis is None:
self.redis = redis.StrictRedis.from_url(self.redis_uri)
for name, value in self.redis_config.items():
try:
self.redis.con... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2017-02-17 10:06
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('basicviz', '0049_auto_20170216_2228'),
... | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('intensity', models.FloatField()),
('document', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='basicviz.Document')),
],
),
migrations.Create... | =True, primary_key=True, serialize=False, verbose_name='ID')),
],
),
migrations.CreateModel(
name='FeatureSet',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.... |
# -*- coding: utf-8 -*-
import django
from django.contrib. | auth.models import User
from django.test import TestCase, Client
# compat thing!
if django.VERSION[:2] < (1, 10):
from django.core.urlresolvers import reverse
else:
from django.urls import reverse
class FilerUtilsTests(TestCase):
def setUp(self):
self.client = Client()
self.user = User.ob... | ss(self):
self.client.login(username='fred', password='test')
url = reverse('admin:filer_folder_changelist')
response = self.client.get(url, follow=True)
self.assertEqual(response.status_code, 200)
|
-----------------------------------------------------------------
# The MIT License (MIT)
#
# Copyright (c) 2016 Jonathan Labéjof <jonathan.labejof@gmail.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
... | if (
| (isdict and name not in data) or
|
import os
from ..helper import freq_to_mel
from ..praat import PraatAnalysisFunction
class PraatMfccFunction(PraatAnalysisFunction):
def __init__(self, praat_path=None, windo | w_length=0.025, time_step=0.01, max_frequency=7800,
num_coefficients=13):
script_dir = os.path.dirname(os.path.abspath(__file__))
script = os.path.join(script_dir, 'mfcc.praat')
arguments = [num_coe | fficients, window_length, time_step, freq_to_mel(max_frequency)]
super(PraatMfccFunction, self).__init__(script, praat_path=praat_path, arguments=arguments)
|
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
"""The list of available operations for Data Lake Store.
Variables are only populated by the server, and wi | ll be ignored when
sending a request.
:ivar value: the results of the list operation.
:vartype value: list[~azure.mgmt.datalake.store.models.Operation]
:ivar next_link: the link (url) to the next page of results.
:vartype next_link: str
"""
_validation = {
'value': {'readonly': Tru... |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'RssFeed'
db.create_table(u'rsssync_rssfeed', (
(u'id', self.gf('django.db.models... | u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('title', self.gf('django.db.models.fields.CharField')(max_length=500)),
('summary', self.gf('django.db.models.fields.TextField')(null=True, blank=True)),
('link', self.gf('django.db.models.fields.URLField' | )(max_length=200, null=True, blank=True)),
('date', self.gf('django.db.models.fields.DateTimeField')(null=True, blank=True)),
('feed', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['rsssync.RssFeed'])),
))
db.send_create_signal(u'rsssync', ['RssEntry'])
def b... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import io
import re
from os.path import join, dirname
from setuptools import setup, find_packages
RE_MD_CODE_BLOCK = re.compile(r'```(?P<lan | guage>\w+)?\n(?P<lines>.*?)```', re.S)
RE_SELF_LINK = re.compile(r'\[(.*?)\]\[\]')
RE_LINK_TO_URL = re.compile(r'\[(?P<text>.*?)\]\((?P<url>.*?)\)')
RE_LINK_TO_REF = re.compile(r'\[(?P<text>.*?)\]\[(?P<ref>.*?)\]')
RE_LINK_REF = re.compile(r'^\[(?P<key>[^!].*?)\]:\s*(?P<url>.*)$', re.M)
RE_BADGE = re.compile(r'^\[\!\[(... | >#+)\s*(?P<title>.*)$', re.M)
BADGES_TO_KEEP = []
RST_TITLE_LEVELS = ['=', '-', '*']
RST_BADGE = '''\
.. image:: {badge}
:target: {target}
:alt: {text}
'''
def md2pypi(filename):
'''
Load .md (markdown) file and sanitize it for PyPI.
Remove unsupported github tags:
- code-block directive
... |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import unittest
from openerp.tools.translate import quote, unquote, xml_translate
class TranslationToolsTestCase(unittest.TestCase):
def test_quote_unquote(self):
def test_string(str):
quoted =... | Blah</span>
</a>
</li>
<li class="dropdown" id="menu_more_container" style="display: none;">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">More <b class="caret"/></a>
... | nu" id="menu_more"/>
</li>
</ul>
</t>"""
result = xml_translate(terms.append, source)
self.assertEquals(result, source)
self.assertItemsEqual(terms,
['<span class="oe_menu_text">Blah</span>', 'More <b class="care... |
DeHaan <michael.dehaan@gmail.com>
# (c) 2015 Toshio Kuratomi <tkuratomi@ansible.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 Licens... | ding: utf-8 -*-'
# we've moved the module_common relative to the snippets, so fix the path
_SNIPPET_PATH = os.path.join(os.path.dirname(__file__), '..', 'module_utils')
# *************************************** | ***************************************
def _slurp(path):
if not os.path.exists(path):
raise AnsibleError("imported module support code does not exist at %s" % path)
fd = open(path)
data = fd.read()
fd.close()
return data
def _find_snippet_imports(module_data, module_path, strip_comments):... |
ject = None
self.inject = INJECT_READY
def addControlCard(self, cards):
cardDicts = []
for cardMain in cards:
cardCtrl = sim_card.SimCard(mode=cardMain.mode, type=self.simType)
if cardMain.mode == sim_reader.MODE_SIM_SOFT:
#TODO: try to remove
... | filesReplaced:
return [card]
return cards
def getInsHandler(self, ins, apdu):
#by default execute apdu in card 0
cards = [self.cardsDict[0][MAIN_INTERFACE]]
for cardDict in self.cardsDict:
if cardDict == self.cardsDict[0]:
#cardDict alrea... | cards
continue
card = cardDict[MAIN_INTERFACE]
if (ins == 'GET_RESPONSE' and
card.routingAttr.getFileSelected(apdu[0]) == 'AUTH' and
'INTERNAL_AUTHENTICATE' in card.routingAttr.insReplaced):
return [card]
elif ins in ca... |
==================================
# pylint: disable=unused-import,g-bad-import-order
"""Contains the core layers: Dense, Dropout.
Also contains their functional aliases.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import six
from six.moves import ... | 'weights',
shape=[input_shape[-1].value, self.units],
initializer=self.weights_initializer,
regularizer=self.weights_regularizer,
dtype=self.dtype,
trainable=True)
if self... | shape=[self.units,],
initializer=self.bias_initializer,
regularizer=self.bias_regularizer,
dtype=self.dtype,
trainable=True)
else:
self.bias = None
... |
self.hogCPU = 0.035
self.timesleep = self.TR
self.volumes = int(volumes)
self.sync = sync
self.skip = skip
self.playSound = sound
if self.playSound: # pragma: no cover
self.sound1 = Sound(800, secs=self.TA, volume=0.15, autoLog=False)
self... | break
# "emit" a sync pulse by placing a key in the buffer:
event._onPygletKey(symbol=self.sync, modifiers=0,
emulated=True)
# wait for start of next volume, doing our own hogCPU for
# tighter sync:
core.wait(self.timesleep... | return self
def stop(self):
self.stopflag = True
def launchScan(win, settings, globalClock=None, simResponses=None,
mode=None, esc_key='escape',
instr='select Scan or Test, press enter',
wait_msg="waiting for scanner...",
wait_timeout=300, l... |
the License, or
# (at your option) any later version.
#
# Headphones 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 hav... |
version_file = os.path.join(headphones.PROG_DIR, 'version.txt')
if not os.path.isfile(version_file):
return None, 'master'
with open(version_file, 'r') as f:
current_version = f.read().strip(' \n\r')
if current_version:
return current_version, hea... | RANCH
else:
return None, 'master'
def checkGithub():
headphones.COMMITS_BEHIND = 0
# Get the latest version available from github
logger.info('Retrieving latest version information from GitHub')
url = 'https://api.github.com/repos/%s/headphones/commits/%s' % (
headphones.CONFI... |
# Copyright 2014 OpenStack Foundation
#
# 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 ... | # Do not fill conenctor info as they would be unknown
op.execute("INSERT INTO networkgatewaydevices (id, nsx_id, tenant_id) "
"SELECT gw_dev_ref.id, gw_dev_ref.id as nsx_id, tenant_id "
"FROM networkgatewaydevicereferences AS gw_dev_ref "
"INNER JOIN networkgateways AS... | d=net_gw.id")
|
# Copyright 2017 The TensorFlow 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 applica... | ):
ds_variant = dataset._as_variant_tensor() # pylint: disable=protected-access
self._output_types = dataset.output_types
self._flat_output_types = nest.flatten(dataset.output_types)
self._flat_output_shapes = nest.flatten(dataset.output_shapes)
self._resource = gen_dataset_ops.iterator(
... | ake_iterator(ds_variant, self._resource)
def __del__(self):
if self._resource is not None:
with ops.device("/device:CPU:0"):
resource_variable_ops.destroy_resource_op(self._resource)
self._resource = None
def __iter__(self):
return self
def __next__(self): # For Python 3 compatibilit... |
####################################
# Sample Receiver Script
# [Usage]
# python receiver.py
# python receiver.py > data.csv
# [Data Format]
# id,time,x,y,z
# [Exaple]
# 1,118 | .533,-0.398,-0.199,-0.978
####################################
import sys
import os
import math
import time
import SocketServer
PORTNO = 10552
class handler(SocketServer.DatagramRequestHandler):
def handle(self):
newmsg = self.rfile.readline().rstri | p()
print newmsg
s = SocketServer.UDPServer(('',PORTNO), handler)
print "Awaiting UDP messages on port %d" % PORTNO
s.serve_forever() |
'''
Servants is of primary interest to Python component developers.
The module | names should sufficiently described their inten | ded uses.
'''
__revision__ = "$Id: __init__.py,v 1.4 2005/02/25 23:42:32 dfugate Exp $"
|
#!/usr/bin/env python
strings=['hey','guys','i','am','a','string']
parameter_list=[[strings]]
def features_string_char (strings):
from shogun import StringCharFeatures, RAWBYTE
from numpy import array
#create string features
f=StringCharFeatures(strings, RAWBYTE)
#and output s | everal stats
#print("max string length", f.get_max_vector_length())
#print("number of strings", f.get_num_vectors())
#print("length of first string", f.get_vector_length(0))
#print("string[5]", ''.join(f.get_feature_vector(5)))
#print("strings", f.get_features())
#replace string 0
f.set_feature_vector(array(['t... | features_string_char(*parameter_list[0])
|
# Copyright (C) 2006, Thomas Hamelryck (thamelry@binf.ku.dk)
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
"""Wrappers for PSEA, a program for secondary structure assignment.
See this citation for... | a" and that it is
on the path.
Note that P-SEA will write an output file in the current | directory using
the input filename with extension ".sea".
Note that P-SEA will write output to the terminal while run.
"""
os.system("psea "+fname)
last=fname.split("/")[-1]
base=last.split(".")[0]
return base+".sea"
def psea(pname):
"""Parse PSEA output file."""
fname=run_pse... |
# This file is part of Indico.
# Copyright (C) 2002 - 2017 European Organization for Nuclear Research (CERN).
#
# Indico 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 (a... | super(MultiIPNetworkField, self).process_formdata(valuelist)
self.data = {ip_network(self._fix_network(entry[self.field_name])) for entry in self.data}
self._data_converted = True
def pre_validate(self, form):
pass # nothing | to do
|
import argparse
import hashlib
import json
import csv
import os
MAESTRO_INDEX_PATH = '../mirdata/indexes/maestro_index.json'
def md5(file_path):
"""Get md5 hash of a file.
Parameters
----------
file_path: str
File path.
Returns
-------
md5_hash: str
md5 hash of data in ... | ow['midi_filename'].split('.')[0]
maestro_index[trackid] = | {}
midi_path = os.path.join(data_path, row['midi_filename'])
midi_checksum = md5(midi_path)
maestro_index[trackid]['midi'] = [row['midi_filename'], midi_checksum]
audio_path = os.path.join(data_path, row['audio_filename'])
audio_checksum = md5(audio_path)
... |
import simplejson as json
import xmltodict
import requests
import os
import re
import sys
import base64
from urlparse import urlparse
from os.path import splitext, basename
from BeautifulSoup import BeautifulSoup
nb_token = os.environ.get('NB_TOKEN')
site_slug = os.environ.get('SITE_SLUG')
api_url = "https://" + site_... | xml file and turns it into a dictionary '''
f = open(input_xml, 'r')
doc_xml = f.read()
doc = xmltodict.parse(doc_xml)
return doc
def remove_img_tags(input):
''' Removes img tags from text '''
soup = BeautifulSoup(input)
[s.extract() for s in soup('img')]
return str(soup)
def image_l... | (input):
''' Finds all the image links in a string '''
list_of_images = []
soup = BeautifulSoup(input)
for i in soup.findAll('img'):
list_of_images.append(i)
return list_of_images
def convert_wp2nb(input_xml):
'''
Extracts the relevant items from wordpress posts and converts it int... |
.filename and not self.needs_update():
return
if not os.path.isfile(filename):
return
stats = os.stat(filename)
data = ScriptFile(filename)
self.filename = filename
self.filesize = int(stats.st_size)
self.last_edited = int(stats.st_mtime)
self.data ... | ##########################
### @class ScriptAnalytics
####################################################### | #########################
class ScriptAnalytics():
####################################################################
### @fn __init__()
####################################################################
def __init__(self):
self.script_data = {}
self.load()
####################################... |
"""
Django settings for {{ project_name }} project.
"""
import os
import re
MAIN_APPLICATION_PATH = os.path.dirname(
os.path.dirname(os.path.abspath(__file__))
)
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(MAIN_APPLICATION_PATH)
# Quick-start development s... | BUG:
ALLOWED_HOSTS = ['*']
else:
ah = os.environ.get('ALLOWED_HOSTS', '*')
ah = re.split(',', ah)
ALLOWED_HOSTS = ah
SITE_ID = 1
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.c | ontrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
]
LOCAL_APPS = [
'core',
]
INSTALLED_APPS.extend(LOCAL_APPS)
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django... |
def powers_of_two(limit):
value = 1
while value < limit:
yield value
value += value
# Use the generator
for i in powers_of_two(70):
print(i)
# Explore the mechanism
g = powers_of_two(100) |
assert str(type(powers_of_two)) == "<class 'function'>"
assert str(type(g)) == | "<class 'generator'>"
assert g.__next__() == 1
assert g.__next__() == 2
assert next(g) == 4
assert next(g) == 8
|
(%s, 'D')" % field_name
else:
# http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions050.htm
sql = "EXTRACT(%s FROM %s)" % (lookup_type.upper(), field_name)
return sql, []
def datetime_trunc_sql(self, lookup_type, field_name, tzname):
if settings.USE_TZ:
... | e):
if lookup_type == 'regex':
match_option = "'c'"
else:
match_option = "'i'"
return 'REGEXP_LIKE(%%s, %%s, %s)' % match_option
def regex_lookup(self, lookup_type):
# If regex_lookup is called before it's been initialized, | then create
# a cursor to initialize it and recur.
self.connection.cursor()
return self.connection.ops.regex_lookup(lookup_type)
def return_insert_id(self):
return "RETURNING %s INTO %%s", (InsertIdVar(),)
def savepoint_create_sql(self, sid):
return convert_unicode("SA... |
"""
Import prescribing data from CSV files into SQLite
"""
from collections import namedtuple
import csv
from itertools import groupby
import logging
import os
import sqlite3
import gzip
import heapq
from matrixstore.matrix_ops import sparse_matrix, finalise_matrix
from matrixstore.serializer import serialize_compress... | cribing(connection, prescriptions):
cursor = connection.cursor()
# Map practice codes and date strings to their corresponding row/column
# offset in the matrix
practices = dict(cursor.execute("SELECT code, offset FROM practice"))
dates = dict(cursor.execute("SELECT date, offset FROM date"))
matr... | es, connection)
cursor.executemany(
"""
UPDATE presentation SET items=?, quantity=?, actual_cost=?, net_cost=?
WHERE bnf_code=?
""",
rows,
)
def get_prescriptions_for_dates(dates):
"""
Yield all prescribing data for the given dates as tuples of the form:
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from contextable import Contextable
class Terms(Contextable):
"""
An address in the invoice
"""
def __init__(self, days, string):
self.days = days
self.st | ring = string
def conte | xt(self):
return {
'terms': {
'string': self.string,
'days': self.days
}
}
|
from django.db import models
from django.db.models import Q
class FriendshipManager(models.Manager):
"""
Provides an interface to friends
"""
def friends_for_user(self, user):
"""
Returns friends for specific user
"""
friends = []
qs = self.filter(Q(from_user=... | iendships = self.filter(from_user=user2, to_user=user1)
if friendships:
friends | hips.delete()
class FriendshipInvitationManager(models.Manager):
"""
Provides an interface to friendship invitations
"""
def is_invited(self, user1, user2):
"""
Returns boolean value of whether user1 has been invited to a friendship by user2
"""
return self.filter(
... |
urn ident
def uvf1_download(radio):
"""Download from TYT TH-UVF1"""
data = uvf1_identify(radio)
for i in range(0, 0x1000, 0x10):
msg = struct.pack(">BHB", ord("R"), i, 0x10)
radio.pipe.write(msg)
block = radio.pipe.read(0x10 + 4)
if len(block) != (0x10 + 4):
ra... | oneval):
pol = "N"
rawval = (toneval[1].get_bits(0xFF) << 8) | toneval[0].get_bits(0xFF)
if toneval[0].get_bits(0xFF) == 0xFF:
mode = ""
val = 0
elif toneval[1].get_bits(0xC0) == 0xC0:
mode = "DTCS"
| val = int("%x" % (rawval & 0x3FFF))
pol = "R"
elif toneval[1].get_bits(0x80):
mode = "DTCS"
val = int("%x" % (rawval & 0x3FFF))
else:
mode = "Tone"
val = int(toneval) / 10.0
return mode, val, pol
def _encode_tone(self, _toneval... |
from django.test import TestCase
from django.core.exceptions import FieldError
from models import User, Poll, Choice
class ReverseLookupTests(TestCase):
def setUp(self):
john = User.objects.create(name="John Doe")
jim = User.objects.create(name="Jim Bo")
first_poll = Poll.objects.create(
... | tion?")
p2 = Poll.objects.get(
related_choice__name__exact="This is the answer.")
self.assertEqual(p2.question, "What's the second question?")
def test_reve | rse_field_name_disallowed(self):
"""
If a related_name is given you can't use the field name instead
"""
self.assertRaises(FieldError, Poll.objects.get,
choice__name__exact="This is the answer")
|
#!/usr/bin/env python
# update-dependencies-bad.py - Fails on bad.swift -*- python -*-
#
# This source file is part of the Swift.org open source projec | t
#
# Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See https://swift.org/LICENSE.txt for license information
# See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
#
# ----------------------------------... | s.py. "crash.swift" gives an exit code
# other than 1.
#
# ----------------------------------------------------------------------------
from __future__ import print_function
import os
import shutil
import sys
assert sys.argv[1] == '-frontend'
primaryFile = sys.argv[sys.argv.index('-primary-file') + 1]
if (os.path.... |
# -*- | coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('myhpom', '0012_auto_20180718_1140'),
]
operations = [
migrations.AlterModelOpt | ions(
name='staterequirement',
options={'ordering': ['-state', 'id']},
),
migrations.AlterUniqueTogether(
name='staterequirement',
unique_together=set([('state', 'text')]),
),
migrations.RemoveField(
model_name='staterequirement... |
###############################################################################
#
# 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 with... | ITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
###############################################################################
import json
import random
import sys
from multiprocessing import Process
# from autobahn.asyncio.websocket import WebSocketClientProtocol, \
# WebSocketCl | ientFactory
from autobahn.twisted.websocket import WebSocketClientProtocol, \
WebSocketClientFactory
# import trollius
class MyClientProtocol(WebSocketClientProtocol):
def __init__(self, *args, **kwargs):
self.handle = ''
self.pair_handle = ''
self.open_positions = ''
self.my... |
% (offset, arg_name )
else:
if is_swapped:
if arg_type == "GLfloat" or arg_type == "GLclampf":
retval = "\tWRITE_DATA( %d, GLuint, SWAPFLOAT(%s) );" % (offset, arg_name)
elif arg_type == "GLdouble" or arg_type == "GLclampd":
retval = "\tWRITE_SWAPPE... |
counter += apiutil.sizeof(type)
# finish up
if is_extended:
print "\tWRITE_OPCODE( pc, CR_EXTEND_OPCODE );"
else:
print "\tWRITE_OPCODE( pc, %s );" % apiutil.OpcodeName( func_name )
print '\tCR_UNLOCK_PACKER_CONTEXT(pc);'
print '}\n'
apiutil.CopyrightC()
print... | ode and arguments into a buffer.
*/
#include "packer.h"
#include "cr_opcodes.h"
"""
keys = apiutil.GetDispatchedFunctions(sys.argv[1]+"/APIspec.txt")
for func_name in keys:
if apiutil.FindSpecial( "packer", func_name ):
continue
if not apiutil.HasPackOpcode(func_name):
continue
point... |
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the... | 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License |
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import mrp_byproduct
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
ta=data, params=params,
auth=(self.username, self.password),
headers={'content-type': 'application/xml',
'accept': 'application/xml'})
return self.parse_response(r, accept_status_codes=[200, 201, 202])
def delete(self, u... | the given ISO format date.
last_modified: Since the given ISO format datetime.
udf: dictionary of UDFs with 'UDFNAME[OPERATOR]' as keys.
udtname: UDT name, or list of names.
udt: dictionary of UDT UDFs with 'UDTNAME.UDFNAME[OPERATOR]' as keys
| and a string or list of strings as value.
start_index: Page to retrieve; all if None.
"""
params = self._get_params(name=name,
open_date=open_date,
last_modified=last_modified,
start_index=... |
# -*- coding: utf-8 -*-
import re
from module.plugins.internal.SimpleHoster import SimpleHoster, create_getInfo
class FileStoreTo(SimpleHoster):
__name__ = "FileStoreTo"
__type__ = "hoster"
__version__ = "0.07"
__status__ = "testing"
__pattern__ = r'http://(?:www\.)?filestore\.to/\?d=(?P... | ore.to hoster plugin"""
__license__ = "GPLv3"
__authors__ = [("Walter Purcaro", "vuolter@gmail.com"),
("stickell", "l.stickell@yahoo.it")]
|
INFO_PATTERN = r'File: <span.*?>(?P<N>.+?)<.*>Size: (?P<S>[\d.,]+) (?P<U>[\w^_]+)'
OFFLINE_PATTERN = r'>Download-Datei wurde nicht gefunden<'
TEMP_OFFLINE_PATTERN = r'>Der Download ist nicht bereit !<'
def setup(self):
self.resume_download = True
self.multiDL = Tr... |
de
@return: bool
"""
path1 = GetAbsPath(path1)
path2 = GetAbsPath(path2)
if WIN:
path1 = path1.lower()
path2 = path2.lower()
return path1 == path2
def CopyFile(orig, dest):
"""Copy the given file to the destination
@param orig: file to copy (full path)
@param dest: ... | nd path[1] != u':':
# A valid windows file uri | should start with the drive
# letter. If not make the assumption that it should be
# the C: drive.
path = u"C:\\\\" + path
else:
path = u"/" + path
path = urllib2.unquote(path)
return path
@uri2path
def GetPathName(path):
"""Gets the... |
Background(detector, dfbkg)
fm_left = Measure(image)
logging.debug("Focus level (left) at %f is %f", left, fm_left)
focus_levels[left] = fm_left
last_pos = left
fm_range = (fm_left, fm_center, fm_right)
pos_range = (left, center, r... | e the given detector receive light
selector (Actuator): a rx axis with a position
detector (Component): the component to receive light
return (position): the new position of the selector
raise LookupError: if no position on the selector affects the detector
"""
# TODO: handle every way of indica... | f hasattr(ad, "choices") and isinstance(ad.choices, dict):
for pos, value in ad.choices.items():
if detector.name in value:
# set the position so it points to the target
mv[an] = pos
if mv:
selector.moveAbsSync(mv)
return mv
ra... |
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... | (_('Error!'), _('Please specify a project to schedule.'))
if data['target_project'] == 'one':
project_ids = [data['project_id'][0]]
else:
project_ids = project_pool.search(cr, uid, [('user_id','=',uid)], context=context)
p | roject_pool.schedule_phases(cr, uid, project_ids, context=context)
return self._open_phases_list(cr, uid, data, context=context)
def _open_phases_list(self, cr, uid, data, context=None):
"""
Return the scheduled phases list.
"""
if context is None:
context = {}
... |
t Decimal, ROUND_DOWN
import hashlib
import json
import logging
import os
import random
import re
from subprocess import CalledProcessError
import time
from . import coverage
from .authproxy import AuthSe | rviceProxy, JSONRP | CException
logger = logging.getLogger("TestFramework.utils")
# Assert functions
##################
def assert_fee_amount(fee, tx_size, fee_per_kB):
"""Assert the fee was in range"""
target_fee = round(tx_size * fee_per_kB / 1000, 8)
if fee < target_fee:
raise AssertionError("Fee of %s BTC too low... |
stalk returns an
InvalidParameterCombination error. If you do not specify either,
AWS Elastic Beanstalk returns MissingRequiredParameter error.
"""
params = {'ApplicationName': application_name}
if template_name:
params['TemplateName'] = template_name
... | arams['VersionLabel'] = version_label
if environment_ids:
self.build_list_params(params, environment_ids,
'EnvironmentIds.member')
if environment_names:
s | elf.build_list_params(params, environment_names,
'EnvironmentNames.member')
if include_deleted:
params['IncludeDeleted'] = self._encode_bool(include_deleted)
if included_deleted_back_to:
params['IncludedDeletedBackTo'] = included_deleted_back_to... |
, code)
if account is None:
raise ExchangeError(self.id + ' fetchLedger() could not find account id for ' + code)
request = {
'id': account['id'],
# 'start_date': self.iso8601(since),
# 'end_date': self.iso8601(self.milliseconds()),
# 'before':... | self.extend({'type': 'withdraw'}, params))
def parse_transaction_status(self, transaction):
canceled = self.safe_value(transaction, 'canceled_at')
if canceled:
return 'canceled'
processed = self.safe_value(transaction, 'processed_at')
completed = self.safe_value(transact... | return 'failed'
else:
return 'pending'
def parse_transaction(self, transaction, currency=None):
details = self.safe_value(transaction, 'details', {})
id = self.safe_string(transaction, 'id')
txid = self.safe_string(details, 'crypto_transaction_hash')
timestamp = ... |
from django.template import Library
from django.utils.functional import Promise
import json
register = Library()
@register.filter
def json_dumps(json_object):
if is | instance(json_object, Promise):
json_object = dict(json_object)
return json.dumps(json_object)
@register.filter
def json_dumps_pr | etty(json_object):
if isinstance(json_object, Promise):
json_object = dict(json_object)
return json.dumps(json_object, indent=4, separators=(',', ': '))
|
# Copyright (c) 2014, The Boovix authors that are listed
# in the AUTHORS file. All right | s reserved. Use of this
# source code is governed by the BSD 3-clause license that
# can be found in the LICENSE file.
"""
Function annotations in Python 3:
http://legacy.python.o | rg/dev/peps/pep-3107/
Type checking in Python 3:
* http://code.activestate.com/recipes/578528
* http://stackoverflow.com/questions/1275646
mypy static type checking during compilation:
https://mail.python.org/pipermail/python-ideas/2014-August/028618.html
from typing import List, Dict
def word_count(input: L... |
# -*- coding: utf-8 -*-
REPO_BACKENDS = {}
REPO_TYPES = []
class RepositoryTypeNotAvailable(Exception):
| pass
try:
from brigitte.backends import libgit
REPO_BACKENDS['git'] = libgit.Repo
REPO_TYPES.append(('git', 'GIT'))
except ImportError:
from brigitte.backends import git
REPO_BACKENDS['git'] = git.Repo
REPO_TYPES.append(('git', 'GIT'))
try:
from brigitte.backends import hg
REPO_BA... | _TYPES.append(('hg', 'Mercurial'))
except ImportError:
pass
def get_backend(repo_type):
if not repo_type in REPO_BACKENDS:
raise RepositoryTypeNotAvailable(repo_type)
return REPO_BACKENDS[repo_type]
|
e repository version needs to be the one that is loaded:
sys.path.insert(0, os.path.abspath(os.path.join('..', '..', '..', 'lib')))
VERSION = '2.10'
AUTHOR = 'Ansible, Inc'
# General configuration
# ---------------------
# Add any Sphinx extension module names here, as strings.
# They can be extensions
# coming wit... | module name will be | prepended to all description
# unit titles (such as .. function::).
# add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
# show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx... |
"""
WSGI config for twitter-tools project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on thi | s file, see
https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "twitter-tools.settings")
application = get_wsgi_applic | ation()
|
# Copyright 2008-2013 Nokia Siemens Networks Oyj
#
# 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... | start(elem, result), handler
def start(self, elem, result):
return result
def end(self, elem, result):
pass
def _timestamp(self, elem, attr_name):
timesta | mp = elem.get(attr_name)
return timestamp if timestamp != 'N/A' else None
class RootHandler(_Handler):
def _children(self):
return [RobotHandler()]
class RobotHandler(_Handler):
tag = 'robot'
def start(self, elem, result):
generator = elem.get('generator', 'unknown').split()[0]... |
#!/usr/bin/env python
# ~*~ encoding: utf-8 ~*~
"""
This file is part of SOCSIM.
SOCSIM 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... | port record
# ---
# read file
# generate data
# build meta
#
# build temp record of meta
# save to file
# ---
# * extact
# - sections
# - key, values
# * organise
# - meta
# - others
class ini:
def __init__(self, data, config):
self.data = data
self.store = []
self.c = config
def ... | a:
if self.meta():
if self.sections():
return True
return False
def meta(self):
"""parse meta section"""
if 'meta' in self.c.sections():
meta = self.c.sections()[0]
self.store.append(meta)
return True
... |
ons.add_argument("--psdvar_long_segment", type=float,
meta | var="SECONDS", help="Length of long segment "
"when calculating the PSD variability.")
psd_options.add_argument("--psdvar_overlap", type=float, metavar="SECONDS", help="Sample length of the PSD.")
psd_options.add_argument("--psdvar_low_freq", type=float,... | _high_freq", type=float, metavar="HERTZ", help="Maximum frequency to consider in PSD "
"comparison.")
if include_data_options :
psd_options.add_argument("--psd-estimation",
help="Measure PSD from the data, using "
... |
try:
from account.decorators import login_required
except ImportError:
from djan | go.contrib.auth.decorators import login_required # noqa
try:
from account.mixins import LoginRequiredMixin
except ImportError:
from django.contrib.auth.mixins import LoginRequiredMixin # noqa
| |
a compiler expects
to see.
'''
def __init__(self, member_node):
self.node = member_node
def process(self, callbacks):
properties = OrderedDict()
name = self.node.GetName()
if self.node.GetProperty('deprecated'):
properties['deprecated'] = self.node.GetProperty('deprecated')
for proper... | self.node, properties).process(callbacks)
enum_values = self.node.GetProperty('legalValues')
if enum_values:
if properties['type'] == 'integer':
enum_values = map(int, en | um_values)
elif properties['type'] == 'double':
enum_values = map(float, enum_values)
properties['enum'] = enum_values
return name, properties
class Typeref(object):
'''
Given a TYPEREF property representing the type of dictionary member or
function parameter, converts into a Python dict... |
# -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import
import unittest
from pykit.parsing import cirparser
from pykit.ir import verify, interp
source = """
#include <pykit_ir.h>
Int32 myglobal = 10;
float simple(float x) {
return x * x;
}
Int32 loop() {
Int32 i, sum = 0;
... | n sum;
}
Int32 raise() {
Exception exc = new_exc("TypeError", "");
exc_thro | w(exc);
return 0;
}
"""
mod = cirparser.from_c(source)
verify(mod)
class TestInterp(unittest.TestCase):
def test_simple(self):
f = mod.get_function('simple')
result = interp.run(f, args=[10.0])
assert result == 100.0, result
def test_loop(self):
loop = mod.get_function('l... |
"""
Trabalho T2 da disciplina Teoria dos Grafos, ministrada em 2014/02
'All Hail Gabe Newell'
Alunos:
Daniel Nobusada 344443
Thales Eduardo Adair Menato 407976
Jorge Augusto Bernardo 407844
"""
import networkx as nx
import numpy as... | random_integers(1, graphG.number_of_nodes())
# 2 caminhadas aleatorias de tamanho N = 100
w_random100a = random_walk(nodeA, 100)
w_random100b = random_walk(nodeB, 100)
# 2 caminhadas aleatorias de tamanho N = 10000
w_random10000a = random_walk(nodeA, 10000)
w_random10000b = random_walk(nodeB, 10000)
# Print no console... | dados obtidos
print "w_power5: "
w_power5_lista = []
for i in range(0, w_power5.size):
w_power5_lista.append('%.4f'%w_power5[0, i])
print w_power5_lista
print "w_power100: "
w_power100_lista = []
for i in range(0, w_power100.size):
w_power100_lista.append('%.4f'%w_power100[0, i])
print w_power100_lista
print... |
# Copyright 2014 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... | .
import proboscis
from trove.tests.api import backups
from trove.tests.api import configurations
from trove.tests.api import databases
from trove.tests.api import datastores
from trove.tests.api import flavors
from trove.tests.api import instances
from trove.tests.api import instances_actions
from trove.tests.api.mgm... | rt hosts
from trove.tests.api.mgmt import instances as mgmt_instances
from trove.tests.api.mgmt import storage
from trove.tests.api import replication
from trove.tests.api import root
from trove.tests.api import user_access
from trove.tests.api import users
from trove.tests.api import versions
GROUP_SERVICES_INITIALI... |
# Copyright 2017 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.
from __future__ import print_function
import sys
import os
from gpu_tests import gpu_integration_test
test_harness_script = r"""
function VerifyHardware... | hrome://gpu', (feature))
def RunActualGpuTest(self, test_path, *args):
feature = args[0]
self._Navigate(test_path)
tab = self.tab
tab.WaitForJavaScriptCondition('window.gpuPagePopulated', timeout=30)
if not tab.EvaluateJavaScript(
'VerifyHardwareAccelerated({{ feature }})', feature=featur... | teJavaScript('document.body.innerHTML'))
self.fail('%s not hardware accelerated' % feature)
@classmethod
def ExpectationsFiles(cls):
return [
os.path.join(
os.path.dirname(os.path.abspath(__file__)), 'test_expectations',
'hardware_accelerated_feature_expectations.txt')
... |
from django.db import models
class AssetField(models.ForeignKey):
description = 'A file asset'
def __init__(self, **kwargs):
kwargs.setdefault('blank', True)
kwargs.setdefault('null', True)
kwargs.setdefault('default', None)
# Normally, Django creates a backwards relationship... | lt('related_name', '+')
kwargs['to'] = 'assets.Asset'
kwargs['on_delete'] = | models.SET_NULL
super(AssetField, self).__init__(**kwargs)
|
t(self.zFar)
elif form_data['side'] =='on':
self.side = 'right'
self.shoulder = 'RShoulderPitch'
self.pointing_dict = self.pointing_right
self.zNear = -(math.atan(self.y/self.near)+math.pi/2)
self.zFar = -(math.atan(self.y/self.far)+math.pi/2)
print(self.side)
return
#calculates pointing a... | w.pauseAwareness()
########################################################################
slide_src = self.slides_path + str(self.start_slide) + '.jpg'
self.app.evalua | te_javascript("document.getElementById('presentation_image').style.display='block'")
self.app.evaluate_javascript("document.getElementById('presentation_content').innerHTML = 'Log:<br>Starting presentation at: %s<br>IP: %s<br>Notes: '" %(self.my_path, self.my_ip))
self.app.evaluate_javascript("document.getElementBy... |
yright 2002-2018, Neo4j
#
# 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, softw... | d == u"false"
class CypherIntegerRepresentationTestCase(TestCase):
def test_should_encode_zero(self):
| encoded = cypher_repr(0)
assert encoded == u"0"
def test_should_encode_positive_integer(self):
encoded = cypher_repr(123)
assert encoded == u"123"
def test_should_encode_negative_integer(self):
encoded = cypher_repr(-123)
assert encoded == u"-123"
class CypherFloatRe... |
# This is a sample configuration file for an ISAPI filter and extension
# written in Python.
#
# Please see README.txt in this directory, and specifically the
# information about the "loader" DLL - installing this sample will create
# "_redirector_with_filter.dll" in the current directory. The readme explains
# this.
... | k to the client.
# That is perfect for this sample, so we don't catch our own.
#print 'IIS dispatching "%s"' % (ecb.GetServerVariable("URL"),)
url = ecb.GetServerVariable("URL")
if url.startswith(virtualdir):
new_url = proxy + url[len(virtualdir):]
print("Opening"... | fp = urllib.request.urlopen(new_url)
headers = fp.info()
ecb.SendResponseHeaders("200 OK", str(headers) + "\r\n", False)
ecb.WriteClient(fp.read())
ecb.DoneWithSession()
print("Returned data from '%s'!" % (new_url,))
else:
# this should n... |
##############################################################################
#
# Copyright (C) 2018 Compassion CH (http://www.compassion.ch)
# @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file __manifest__.py
#
#########################################################################... | """Invalidate the form if they order 0 flyers"""
is_valid = super().form_check_empty_value(fname, field, value, **req_values)
is_valid | |= int(req_values["flyer_french"]) + int(req_values["flyer_german"]) <= 0
return is_valid
def _form_create(self, values):
""" Run as Muskathlon user to authorize lead creation,
and prevents default mail notification to staff
(a better one is sent just after)."""
uid = self.e... |
def build_from_db_model(db_model):
raise NotImplementedError("Any entity subclass should implement the build_from_db_model method!")
class StudyModel(EntityModel):
@staticmethod
def build_from_db_model(db_study):
study_model = StudyModel()
study_model = StudyModel.copy_fi... | dest_alib.instrument_model = src_alib.instrument_ | model
return dest_alib
class LibraryModel(AbstractLibraryModel, EntityModel):
@staticmethod
def build_from_db_model(db_lib):
lib_model = LibraryModel()
lib_model = LibraryModel.copy_fields(db_lib,lib_model)
return lib_model
@staticmethod
def copy_fiel... |
DO_PROFILE)
def splitIterator(text, size):
# assert size > 0, "size should be > 0"
for start in range(0, len(text), size):
yield text[start:start + size]
prev_sum = 0
MMAP_NO_DATA_INDICATE_ZERO = False
MMAP_NO_DATA_INDICATE_NON_ZERO = True
@do_profile(DO_PROFILE)
def get_data_from_mmap():
#
... | ', this_element)[0]
if round(this_element, 8) != DATA_RECEIVED_ACK_NUM:
new_data_found[mmap_file_index] = 1
# none of the files contain new data
if sum(n | ew_data_found) == 0:
return create_empty_data_buffer(nbr_mmap_files, zeros, nbr_buffers_received)
''' read out transferred data '''
data = []
# this is ~ 10ms slower.
#data = np.zeros((nbr_mmap_files, nbr_buffers_received, NBR_DATA_POINTS_PER_BUFFER_INT))
# at least one new buffer has... |
# -*- coding: utf-8 -*-
import urllib
from oauth2 import Consumer
from webob import Request, Response
from wsgioauth import calls
from wsgioauth.provider import Application, Storage
from wsgioauth.utils import CALLS
from wsgioauth.provider import Storage, Token
ROUTES = {
u'getConsumers': calls.getCons... | age():
from wsgioauth.provider import OAUTH_CLASSES
OAUTH_CLASSES['consumer'] = Consumer
OAUTH_CLASSES['request_token'] = Token
return Storage
def echo_app(environ, start_response):
"""Simple app that echos a POST request"""
req = Request(environ)
resp = Response(urllib.urlencode... | global_conf, **local_conf):
CALLS.update(ROUTES)
global STORAGE
if STORAGE is None:
storage_cls = getMockStorage()
STORAGE = storage_cls(local_conf)
def storage_lookup(environ, conf):
return STORAGE
return Application(storage_lookup, **local_conf)
def filter_factor... |
import uuid
import xbmc
import xbmcaddon
settings = {}
addon = xbmcaddon.Addon()
settings['debug'] = addon.getSetting('debug') == "true"
settings['powersave_minutes'] = int(addon.getSetting(' | powersave_minutes'))
s | ettings['version'] = addon.getAddonInfo('version')
settings['uuid'] = str(addon.getSetting('uuid')) or str(uuid.uuid4())
addon.setSetting('uuid', settings['uuid'])
|
ll_table[1044]="eventfd"
syscall_table[19]="eventfd2"
syscall_table[221]="execve"
syscall_table[93]="exit"
syscall_table[94]="exit_group"
syscall_table[48]="faccessat"
syscall_table[223]="fadvise64"
syscall_table[47]="fallocate"
syscall_table[262]="fanotify_init"
syscall_table[263]="fanotify_mark"
syscall_table[50]="fc... | uncate64"
syscall_table[98]="futex"
syscall_table[1066]="futimesat"
syscall_table[168]="getcpu"
syscall_table[17]="getcwd"
syscall_table[1065]="getdents"
syscall_table[61]="getdents64"
syscall_table[177]="getegid"
syscall_table[175]="geteuid"
syscall_table[176]="getgid"
syscall_table[158]="getgroups"
syscall_table[102]... | scall_table[155]="getpgid"
syscall_table[1060]="getpgrp"
syscall_table[172]="getpid"
syscall_table[173]="getppid"
syscall_table[141]="getpriority"
syscall_table[150]="getresgid"
syscall_table[148]="getresuid"
syscall_table[163]="getrlimit"
syscall_table[100]="get_robust_list"
syscall_table[165]="getrusage"
syscall_tabl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.