prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
# PyMM - Python MP3 Manager
# Copyright (C) 2000 Pierre Hjalm <pierre.hjalm@dis.uu.se>
#
# Modified by Alexander Kanavin <ak@sensi.org>
# Removed ID tags support and added VBR support
# Used http://home.swipnet.se/grd/mp3info/ for information
#
# This program is free software; you can redistribute it and/or
# modify it... | "
f=open(file)
f.seek(0,2)
size=f.tell()
try:
f.seek(-128,2)
except:
f.close()
return 0
buf=f.read(3)
f.close()
if buf=="TAG":
size=size-128
if size<0:
| return 0
else:
return size
table=[[
[0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448],
[0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384],
[0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320]],
[
[0, 32, 48, 56, 64, 80,... |
from ..base impo | rt BaseShortener
from ..exceptions import ShorteningErrorException
class Shortener(BaseShortener):
"""
TinyURL.com shortener implementation
Example:
>>> import pyshorteners
>>> s = pyshorteners.Shortener()
>>> s.tinyurl.short('http://www.google.com')
'http://tinyurl.com/T... | """Short implementation for TinyURL.com
Args:
url: the URL you want to shorten
Returns:
A string containing the shortened URL
Raises:
ShorteningErrorException: If the API returns an error as response
"""
url = self.clean_url(url)
res... |
import autocomplete_light.shortcuts as autocomplete_light
from django import VERSION
from .models import *
try:
import genericm2m
except ImportError:
genericm2m = None
try:
import taggit
except ImportError:
taggit = None
class DjangoCompatMeta:
if VERSION >= (1, 6):
fields = '__all__'... | autocomplete_light.ModelForm):
class Meta(DjangoCompatMeta):
model = OtoModel
class MtmModelForm(autocomplete_light.ModelForm):
class Meta(DjangoCompatMeta):
model = MtmModel
class GfkModelForm(autocomplete_light.ModelForm):
class Meta(DjangoCompatMeta):
model = GfkModel
if gen... | tmModelForm(autocomplete_light.ModelForm):
class Meta(DjangoCompatMeta):
model = GmtmModel
if taggit:
class TaggitModelForm(autocomplete_light.ModelForm):
class Meta(DjangoCompatMeta):
model = TaggitModel
|
import base64
def toBase6 | 4(s):
return base64.b64enc | ode(str(s))
def fromBase64(s):
return base64.b64decode(str(s))
|
# -*- 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 ... | nchange_state(self, state_id):
if state_id:
state = self.env['res.country.state'].browse(state_id)
return {'value': {'country_id': state.country_id.id}}
return {}
@api.multi
def onchange_type(self, is_company):
value = {'title': False}
if is_company:
value['use_parent_address'] = False
... | pends("image")
def _get_image(self):
""" calculate the images sizes and set the images to the corresponding
fields
"""
image = self.image
# check if the context contains the magic `bin_size` key
if self.env.context.get("bin_size"):
# refetch the image with a clean context
image = se... |
#!/usr/bin/env python
'''
Created on Jan 5, 2011
@author: mkiyer
chimerascan: chimeric transcript discovery using RNA-seq
Copyright (C) 2011 Matthew Iyer
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 Founda... | l Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
'''
import logging
import os
import shutil
import subprocess
import sys
from optparse import OptionParser
# local imports
import chimerascan.pysam as pysam
from chimerascan.lib.feature import GeneFeature
from chimerascan.lib.seq imp... |
BASES_PER_LINE = 50
def split_seq(seq, chars_per_line):
pos = 0
newseq = []
while pos < len(seq):
if pos + chars_per_line > len(seq):
endpos = len(seq)
else:
endpos = pos + chars_per_line
newseq.append(seq[pos:endpos])
pos = endpos
retur... |
# -*- coding: utf-8 -*-
# Generated by D | jango 1.11.9 on 2018-04-09 08:07
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('georegion', '0001_initial_squashed_0004_auto_20180307_2026'),
]
operations = [
mig... | field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='georegion.GeoRegion', verbose_name='Part of'),
),
]
|
# Copyright (c) 2013 Alan McIntyre
import httplib
import json
import decimal
import re
decimal.getcontext().rounding = decimal.ROUND_DOWN
exps = [decimal.Decimal("1e-%d" % i) for i in range(16)]
btce_domain = "btc-e.com"
all_currencies = ("btc", "usd", "rur", "ltc", "nmc", "eur", "nvc",
"trc", "pp... | pile(r'__cfduid=([a-f0-9]{46})')
BODY_COOKIE_RE = re.compile(r'document\.cookie="a=([a-f0-9]{32});path=/;";')
class BTCEConnection:
def __init__(self, t | imeout=30):
self.conn = httplib.HTTPSConnection(btce_domain, timeout=timeout)
self.cookie = None
def close(self):
self.conn.close()
def getCookie(self):
self.cookie = ""
self.conn.request("GET", '/')
response = self.conn.getresponse()
setCookieHeader =... |
cl | ass a(object):
pass
class | b(a):
pass
print a.__subclasses__()
class c(a):
pass
print a.__subclasses__() |
# Generated by Django 2.2.17 on 2021-01-31 06:11
from django.db import migrations, models
class Migration(migra | tions.Migration):
dependencies = [
('conversation', '0032_twitterusertimeline'),
]
operations = [
migrations.AddField(
model_name='twitterusertimeline',
name='last_api_call',
field=models.DateTimeField(blank=True, null | =True),
),
]
|
# -*- co | ding: UTF-8 -*-
from __future__ impo | rt unicode_literals, print_function, division
|
# GUI for pyfdtd using PySide
# Copyright (C) 2012 Patrik Gebhardt
# Contact: grosser.knuff@googlemail.com
#
# 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
... | y of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/ | licenses/>.
from newLayer import *
from newSimulation import *
|
dynamic_individual_grad_values)):
tf.logging.info("Comparing individual gradients iteration %d" % i)
self.assertAllEqual(a, b)
for i, (a, b) in enumerate(zip(static_individual_var_grad_values,
dynamic_individual_var_grad_values)):
tf.logging.info(
"Co... | reateBidirectionalRNN(use_gpu, use_shape, True))
tf.initialize_all_variables().run()
# Run with pre-specified sequence length of 2, 3
out, s_fw, s_bw = sess.run([outputs, state_fw, state_bw],
feed_dict={inputs[ | 0]: input_value,
sequence_length: [2, 3]})
# Since the forward and backward LSTM cells were initialized with the
# same parameters, the forward and backward output has to be the same,
# but reversed in time. The format is output[time][batch][depth], and
# due to... |
er._rank()
else:
return NotImplemented
def __eq__(self, other):
if isinstance(self, Agent):
return self._rank() == other._rank()
else:
return NotImplemented
def __hash__(self):
return hash(self._rank())
def create_context(self):
... | cate(self._id, nbytes, ctypes.byref(buff))
return buff
def free(self, ptr):
hsa.hsa_memory_free(ptr)
_instance_dict = {}
@classmethod
def instance_for(cls, owner, _id):
try:
return cls._instance_dict[_id]
except KeyError:
new_instance = cls(owne... | Queue(object):
def __init__(self, agent, queue_ptr):
"""The id in a queue is a pointer to the queue object returned by hsa_queue_create.
The Queue object has ownership on that queue object"""
self._agent = weakref.proxy(agent)
self._id = queue_ptr
self._as_parameter_ = self._... |
import os
import re
import sublime
import sublime_plugin
| class ExpandTabsOnLoad(sublime_plugin.EventListener):
# Run ST's 'expand_tabs' command when opening a file,
# only if there are any tab characters in the file
def on_load(self, view):
expand_tabs = view.settings().get("expand | _tabs_on_load", False)
if expand_tabs and view.find("\t", 0):
view.run_command("expand_tabs", {"set_translate_tabs": True})
tab_size = view.settings().get("tab_size", 0)
message = "Converted tab characters to {0} spaces".format(tab_size)
sublime.status_message(mes... |
# This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from __future__ import absolute_import, division, print_function
import hmac
from cryptography. | hazmat.bindings._constant_time import lib
if hasattr(hmac, "compare_digest"):
def bytes_eq(a, b):
if not isinstance(a, bytes) or not isinstance(b, bytes):
raise TypeError("a and b must be bytes.")
return hmac.compare_digest(a, b)
else:
def bytes_eq(a, b):
if not isinstanc... | ime_bytes_eq(
a, len(a), b, len(b)
) == 1
|
lg.norm(A, ord='fro')
for i in [5, 10, 50]:
U, s, Vt = randomized_svd(X, n_components, n_iter=i,
power_iteration_normalizer=normalizer,
random_state=0)
A = X - U.dot(np.diag(s).dot(Vt))
error = linal... | ='none')
def test_svd_flip():
# Check that svd_flip works in both situations, and reconstructs input.
rs = np.random.RandomState(1999)
n_samples = 20
n_features = 10
X = rs.randn(n_samples, n_features)
# Check matrix reconstruction
U, S, Vt = linalg.svd(X, full_matrices=False)
U1, V1 ... |
U, S, Vt = linalg.svd(XT, full_matrices=False)
U2, V2 = svd_flip(U, Vt, u_based_decision=True)
assert_almost_equal(np.dot(U2 * S, V2), XT, decimal=6)
# Check that different flip methods are equivalent under reconstruction
U_flip1, V_flip1 = svd_flip(U, Vt, u_based_decision=True)
assert_almost_... |
#!/usr/bin/python
#
# Copyright (c) 2011 The Bitcoin developers
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
import time
import json
import pprint
import hashlib
import struct
import re
import base64
import httplib
import... | e(in_buf):
out_words = []
for i in range(0, len(in_buf), 4):
out_words.append(in_buf[i:i+4])
out_words.reverse()
return ''.join(out_words)
class Miner:
def __init__(self, id):
self.id = id
self.max_nonce = MAX_NONCE
def work(self, datastr, targetstr):
# d | ecode work data hex string to binary
static_data = datastr.decode('hex')
static_data = bufreverse(static_data)
# the first 76b of 80b do not change
blk_hdr = static_data[:76]
# decode 256-bit target value
targetbin = targetstr.decode('hex')
targetbin = targetbin[::-1] # byte-swap and dword-swap
target... |
tin)s['%(op)s'](%(left)s, %(right)s)" % jsvars
except StopIteration:
pass
return left
def node_assert_stmt(self, node):
jsvars = self.jsvars.copy()
childs = node.children.__iter__()
self.assert_value(node, childs.next().value, 'assert')
test = self.dispat... | ror']%(arg)s));
}""" % jsvars
def node_atom(self, node):
jsvars = self.jsvars.copy()
items = []
cls = None
if node.children[0].value == '(':
cls = jsvars['tuple']
if len(nod | e.children) == 3:
items = self.dispatch(node.children[1])
if not isinstance(items, list):
return items
elif len(node.children) != 2:
self.not_implemented(node)
elif node.children[0].value == '[':
cls = jsvars['list']
... |
""" FileDialogDelegateQt.py: Delegate that pops up a file dialog when double clicked.
Sets the model data to the selected file name.
"""
import os.path
try:
from PyQt5.QtCore import Qt, QT_VERSION_STR
from PyQt5.QtWidgets import QStyledItemDelegate, QFileDialog
except ImportError:
try:
from PyQt4... | rent)
def createEditor(self, parent, option, index):
""" Instead of creating an editor, just popup a modal file dialog
and set the model data to the selected file name, if any.
"""
pathToFileNam | e = ""
if QT_VERSION_STR[0] == '4':
pathToFileName = QFileDialog.getOpenFileName(None, "Open")
elif QT_VERSION_STR[0] == '5':
pathToFileName, temp = QFileDialog.getOpenFileName(None, "Open")
pathToFileName = str(pathToFileName) # QString ==> str
if len(pathToFile... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# This file has been created by ARSF Data Analysis Node and
# is licensed under the MIT Licence. A copy of this
# licence is available to download with this file.
#
# Author: Robin Wilson
# Created: 2015-11-16
import sys
import numpy as np
import pandas as pd
# Python 2... | tract spectra from a DART format file
Requires:
* filename - the filename to the DART format file to read
Returns:
* Spectra object with values, radiance, pixel and line
"""
f = open(filename, 'r')
s = StringIO()
within_comment = False
whil... |
line = f.next()
except:
break
if "*" in line and within_comment:
within_comment = False
continue
elif "*" in line and not within_comment:
within_comment = True
if not within_comment and not ... |
ble cls: A custom type or function that will be passed the direct response
:return: NatGateway, or the result of cls(response)
:rtype: ~azure.mgmt.network.v2020_04_01.models.NatGateway
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: Cl... | ap.update(kwargs.pop('error_map', {}))
api_version = "2020-04-01"
content_type = kwargs.pop("content_type", "application/ | json")
accept = "application/json"
# Construct URL
url = self.update_tags.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'natGatewayName': self._serialize.url(... |
# -*- coding: utf-8 -*-
from ..internal.DeadCrypter import DeadCrypter
class Movie2KTo(DeadCrypter):
__name__ = "Movie2KTo"
__type__ = "crypter"
__version__ = "0.56"
__status__ = "stable"
__pattern__ = r'http://(?:www\.)?movie2k\.to/(.+)\.html'
__config__ = [("activated", "bool", "Activated"... | cription__ = """Mo | vie2k.to decrypter plugin"""
__license__ = "GPLv3"
__authors__ = [("4Christopher", "4Christopher@gmx.de")]
|
config = {
"interfaces": {
"google.devtools.clouderrorreporting.v1beta1.ReportErrorsService": {
"retry_codes": {
"idempotent": ["DEADLINE_EXCEEDED", "UNAVAILABLE"],
"non_idempotent": []
},
"retry_params": {
"default": {
... | pc_timeout_multiplier": 1.0,
"max_rpc_timeout_millis": 20000,
"total_timeout_millis": 600000
}
},
"methods": {
"ReportErrorEvent": {
"timeout_millis": 60000,
"retry_codes_name": "non_i... | }
}
}
}
|
import random
rand = random.SystemRandom()
def rabinMiller(num):
if num % 2 == 0:
return False
s = num - 1
t = 0
while s % 2 == 0:
s = s // 2
t += 1
| for trials in range(64):
a = rand.randrange(2, num - 1)
v = pow(a, s, num)
if v != 1:
i = 0
while v != (num - 1):
| if i == t - 1:
return False
else:
i = i + 1
v = (v ** 2) % num
return True
|
'''
salt.targeting
~~~~~~~~~~~~~~
'''
import logging
log = logging.getLogger(__name__)
from .parser import *
from .query import *
from .rules import *
from .subjects import *
#: defines minion targeting
minion_targeting = Query(default_rule=GlobRule)
minion_targeting.register(GlobRule, None, 'glob')
minion_target... | .register(GrainRule, 'G', 'grain')
minion_targeting.register(PillarRule, 'I', 'pillar')
minion_targeting.register(PCRERule, 'E', 'pcre')
minion_targeting.register(GrainPCRERule, 'P', 'grain_pcre')
minion_targeting.register(SubnetIPRule, 'S')
minion_targeting.register(ExselRule, 'X', 'exsel')
minion_targeting.register(L... | eGroupEvaluator, 'N')
|
# Copyright 2011 OpenStack Foundation.
# All Rights Reserved.
# Copyright 2013 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# | http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing | , software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo.messaging.notify import notifier
class... |
oind <0.7 or Eloipool <20120513)
if not self.OldGMP:
self.OldGMP = True
self.logger.warning('Upstream server is not BIP 22 compatible')
oMP = deepcopy(MP)
prevBlock = bytes.fromhex(MP['previousblockhash'])[::-1]
if 'height' in MP:
height = MP['height']
else:
height = self.access.getinfo()... | lf._doing_last = what
self._doing_i = 1
self._doing_s = now
def _floodWarning(self, now, wid, wmsgf = None, doin = True, logf = None):
if doin is True:
doin = self._doing_last
def a | (f = wmsgf):
return lambda: "%s (doing %s)" % (f(), doin)
wmsgf = a()
winfo = self.lastWarning.setdefault(wid, [0, None])
(lastTime, lastDoing) = winfo
if now <= lastTime + max(5, self.MinimumTxnUpdateWait):
return
winfo[0] = now
nowDoing = doin
winfo[1] = nowDoing
if logf is None:
logf = sel... |
#
# Copyright (c) 2014, Arista Networks, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# Redistributions of source code must retain the above copyright notice,
# this list of condit... | ANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ARISTA NETWORKS
# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
# BUSINESS... | NG NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
# IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
#
__version__ = '1.1.0'
__author__ = 'Arista Networks'
|
se, centred = False):
super().__init__()
self.text = text
self.pos = pos
self.colour = colour
self.font = font
self.size = size
self.variable = variable
self.centred = centred
def update(self):
pos = self.pos
font =... | ad(f)
f.close()
except:
print("create new file")
try:
os.mkdir("Saves")
except:
pass
f = open | ("Saves/current.version", "wb")
current = 0000
pickle.dump(current, f)
f.close()
print(current, "vs", latest)
if current != latest:
from os import remove
try:
remove("Update/download.zip")
except:
pass
print("d... |
"""P | redicted Electoral Vote Count"""
import re
from madcow.util.http import getsoup
from madcow.util.col | or import ColorLib
from madcow.util import Module, strip_html
class Main(Module):
pattern = re.compile(r'^\s*(election|ev)\s*$', re.I)
help = u'ev - current election 2008 vote prediction'
baseurl = u'http://www.electoral-vote.com/'
def init(self):
if self.madcow is None:
self.colo... |
hoices:
- half
- full
ssl_send_empty_frags:
description:
- Enable/disable sending empty fragments to avoid attack on CBC IV.
type: str
choices:
- enable
- disab... | s('off')
else:
fos.https('on')
fos.login(host, username, password, verify | =ssl_verify)
def filter_firewall_ssl_server_data(json):
option_list = ['add_header_x_forwarded_proto', 'ip', 'mapped_port',
'name', 'port', 'ssl_algorithm',
'ssl_cert', 'ssl_client_renegotiation', 'ssl_dh_bits',
'ssl_max_version', 'ssl_min_version', 'ssl_mo... |
# ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2015, Numenta, Inc. Unless you have purchased from
# Numenta, Inc. a separate commercial license for this software code, the
# following terms and conditions apply:
#
# This pro... | lementation for details; the
decoding approaches and return objects vary depending on the encoder.
To pretty print the return value from this method, use decodedToStr().
@param encoded (numpy) Encoded 1-d array (an SDR).
| """
raise NotImplementedError
def getWidth(self):
"""
Get an encoding's output width in bits. See subclass implementation for
details.
"""
raise NotImplementedError()
def getDescription(self):
"""
Returns a tuple, each containing (name, offset).
The name is a string descr... |
# Copyright (c) 2015 Quobyte Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required... | ""
parti | tions = psutil.disk_partitions(all=True)
for p in partitions:
if mount_path != p.mountpoint:
continue
if p.device.startswith("quobyte@") or p.fstype == "fuse.quobyte":
statresult = os.stat(mount_path)
# Note(kaisers): Quobyte always shows mount points with size 0
... |
"""
WSGI con | fig for astrology project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on th | is file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.prod")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
|
import os
import sys
import sqlite3
import logging |
from tqdm import tqdm
from pathlib import Path
from whoosh.index import create_in, open_dir
from whoosh.fields import Schema, TEXT, NUMERIC
from whoosh.qparser import QueryParser
from whoosh.spelling import ListCorrector
from whoosh.highlight impor | t UppercaseFormatter
logging.basicConfig(level=logging.INFO)
if getattr(sys, 'frozen', False):
APPLICATION_PATH = os.path.dirname(sys.executable)
elif __file__:
APPLICATION_PATH = os.path.dirname(__file__)
PATH = APPLICATION_PATH
PATH_DATA = Path(PATH) / 'data'
FILE_DB = PATH_DATA / "data.db"
class Searcher:... |
import avango
import avango.script
import avango.gua
from examples_common.GuaVE import GuaVE
class TimedRotate(avango.script.Script):
TimeIn = avango.SFFloat()
MatrixOut = avango.gua.SFMatrix4()
def evaluate(self):
self.MatrixOut.value = avango.gua.make_rot_mat(
self.TimeIn.value * 2.... | nodes.TriMeshPassDescription(),
avango.gua.nodes.LightVisibilityPassDescription(),
res_pass,
| anti_aliasing,
])
cam.PipelineDescription.value = pipeline_description
screen = avango.gua.nodes.ScreenNode(
Name="screen",
Width=2,
Height=1.5,
Children=[cam])
graph.Root.value.Children.value = [transform1, transform2, light, screen]
#setup viewer
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
The MIT license
Copyright (c) 2010 Jonas Nockert
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 without restriction, including without limitation th... | 'jabber:iq:last'
LAST_ACTIVITY = '/iq[@type="get"]/query[@xmlns="' + NS_LAST_ACTIVITY +'"]'
class LastActivityHandler(XMPPHandler, IQHandlerMixin):
"""
XMPP subprotocol handler for Last Activity extension.
This protocol is described in
U{XEP-0012<http://www.xmpp.org/extensions/xep-0012.html>}.
"... |
self.get_last = get_last
def connectionInitialized(self):
self.xmlstream.addObserver(LAST_ACTIVITY, self.handleRequest)
def onLastActivityGet(self, iq):
"""Handle a request for last activity."""
response = toResponse(iq, 'result')
# TODO: Replace 'hello world!' string... |
import numpy as np
import pytest
from nilabels.tools.image_colors_manipulations.relabeller import relabeller, permute_labels, erase_labels, \
assign_all_other_labels_the_same_value, keep_only_one_label, relabel_half_side_one_label
def test_relabeller_basic():
data = np.array(range(10)).reshape(2, 5)
rela... | = [[3 | , 3, 3], [1, 1, 1]]
with pytest.raises(IOError):
permute_labels(np.zeros([3, 3]), invalid_permutation)
def test_permute_labels_valid_permutation():
data = np.array([[1, 2, 3],
[1, 2, 3],
[1, 2, 3]])
valid_permutation = [[1, 2, 3], [1, 3, 2]]
perm_data ... |
= 0.3048
MILE_PER_KM = 0.621371
DEFAULT_PORT = '/dev/ttyS0'
DEBUG_READ = 0
def logmsg(level, msg):
syslog.syslog(level, 'ws1: %s' % msg)
def logdbg(msg):
logmsg(syslog.LOG_DEBUG, msg)
def loginf(msg):
logmsg(syslog.LOG_INFO, msg)
def logerr(msg):
logmsg(syslog.LOG_ERR, msg)
class WS1Driver(weewx... | ef _decode(s, multiplier=None, neg=False):
v = None
try:
v = int(s, 16)
if neg:
bits = 4 * len(s)
if v & (1 << (bits - 1)) != 0:
v -= (1 << bits)
if multiplier is not None:
v *= multiplier
exc... | = '----':
logdbg("decode failed for '%s': %s" % (s, e))
return v
class WS1ConfEditor(weewx.drivers.AbstractConfEditor):
@property
def default_stanza(self):
return """
[WS1]
# This section is for the ADS WS1 series of weather stations.
# Serial port such as /dev/ttyS0, ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import MySQLdb as mdb
import uuid, pprint
def generate(data):
gdata = []
for grade in range(1,4):
for clazz in range(1,10):
if grade != data['grade_number'] and clazz != data['class_number']:
gdata.append("insert into classes(uuid, grade_number, class_number, sch... | _uuid']))
return gdata
def main():
config = {'user': 'root', 'passwd': 'oseasy_db', 'db': 'b | anbantong', 'use_unicode': True, 'charset': 'utf8'}
conn = mdb.connect(**config)
if not conn: return
cursor = conn.cursor()
cursor.execute('select grade_number, class_number, school_uuid from classes;')
base = {}
desc = cursor.description
data = cursor.fetchone()
for i, x in enumerate(data):
base[desc[i][0]] ... |
#!/usr/bin/env python
# coding=utf-8
import errno
import os
import sys
import fileinput
import string
import logging
import traceback
import hashlib
import time
import re
from datetime import date, timedelta
import datetime
from subprocess import call
import redis
from datasource import DataSource
class Items(Dat... | c in value:
if c == '.':
continue
if ord(c) <48 or ord(c) > 57:
return False
return True
def download(self):
try:
cmd = "rm -rf " + self.dir + "/*"
call(cmd, shell=True)
cmd = "hadoop fs -get... | Downloading file:" + self.download_url)
retcode = call(cmd, shell=True)
if retcode != 0:
logging.error("Child was terminated by signal:" + str(retcode) + " for cmd:" + cmd)
return False
else:
self.saveDownloadedDir(self.datedir)
... |
################################################ | ##############################
# Copyright (c) 20 | 13-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-647188
#
# For details, see https://github.com/spack/spack
# Please also see the NOTICE and LICENSE... |
"""Test the roon config flow."""
from homeassistant import config_entries, setup
from homeassistant.components.roon.const import DOMAIN
from homeassistant.const import CONF_HOST
from tests.async_mock import patch
from tests.common import MockConfigEntry
class RoonApiMock:
"""Mock to handle returning tokens for t... | elf, token):
"""Initialize."""
self._token = token
@property
def token(self):
"""Return the auth token from the api."""
return self._token
def stop(self): # pylint: disable=no-self-use
"""Close down the api."""
return
async def test_form_and_auth(hass):
... |
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] == "form"
assert result["errors"] == {}
with patch("homeassistant.components.roon.config_flow.TIMEOUT", 0,), patch(
"homeassistant.components.roon.cons... |
"""engine.SCons.Tool.aixf77
Tool-specific initialization for IBM Visual Age f77 Fortran compiler.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001 - 2014 The SCons Foundation
#
# Permiss... | UT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CON | TRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Tool/aixf77.py 2014/08/24 12:12:31 garyo"
import os.path
#import SCons.Platform.aix
import f77
# It would be good to look for the AIX F77 package the... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import autocomplete_light
from django.utils.encoding import force_text
from .settings import USER_MODEL
from .utils.module_loading import get_real_model_class
class UserAutocomplete(autocomplete_light.AutocompleteModelBase):
search_fields = [
... | l = get_real_model_class(USER_MODEL)
order_by = ['first_name', 'last_name']
# choice_template = 'django_documentos/user_choice_autocomplete.html'
l | imit_choices = 10
attrs = {
'data-autcomplete-minimum-characters': 0,
'placeholder': 'Pessoa que irá assinar',
}
# widget_attrs = {'data-widget-maximum-values': 3}
def choice_value(self, choice):
"""
Return the pk of the choice by default.
"""
return choi... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: Muduo
'''
FastSync
'''
from setuptools import setup, find_packages
setup(
name='FastSync',
version='0.2.0.3',
packages=find_packages(),
install_requires=[
'requests',
| 'watchdog',
'pycrypto',
'future',
'web.py'
],
entry_points={
'console_scripts': [
'fsnd = sync:sending',
'frcv = sync:receiving',
],
},
license='Apache License',
author='Muduo',
author_email='imuduo@16 | 3.com',
url='https://github.com/iMuduo/FastSync',
description='Event driven fast synchronization tool',
keywords=['sync'],
)
|
covariance_type='full',
random_state=rng).fit(X).bic(X)
for covariance_type in ['tied', 'diag', 'spherical']:
bic = GaussianMixture(n_components=n_components,
covariance_type=covariance_type,
random_state=rng).fit(X).... | n_features * (1 + np.log(2 * np.pi)))
for cv_type in COVARIANCE_TYPE:
g = GaussianMixture(
n_components=n_components, covariance_type=cv_type,
random_state=rng, max_iter=200)
g.fit(X)
aic = 2 * n_samples * sgh + 2 * g._n_parameters()
bic = (2 * ... | ) - aic) / n_samples < bound
assert (g.bic(X) - bic) / n_samples < bound
def test_gaussian_mixture_verbose():
rng = np.random.RandomState(0)
rand_data = RandomData(rng)
n_components = rand_data.n_components
for covar_type in COVARIANCE_TYPE:
X = rand_data.X[covar_type]
g = Gaus... |
#
# A sample service to be 'compiled' into an exe-file with py2exe.
#
# See also
# setup.py - the distutils' setup script
# setup.cfg - the distutils' config file for this
# README.txt - detailed usage notes
#
# A minimal service, doing nothing else than
# - write 'start' and 'stop' entries into th... | write a 'stopped' event to the event | log.
win32evtlogutil.ReportEvent(self._svc_name_,
servicemanager.PYS_SERVICE_STOPPED,
0, # category
servicemanager.EVENTLOG_INFORMATION_TYPE,
(self._svc_name_, '')... |
#!/usr/bin/env python
import os
import argparse
import numpy as np
import pandas as pd
import pycondor
import comptools as comp
if __name__ == "__main__":
p = argparse.ArgumentParser(
description='Extracts and saves desired information from simulation/data .i3 files')
p.add_argument('-c', '--config... | add_argument('--overwrite', dest='overwrite',
default=False, action='store_true',
help='Option to overwrite reference map file, '
'if it alreadu exists')
p.add_argument('--test', dest='test', |
default=False, action='store_true',
help='Option to run small test version')
args = p.parse_args()
if args.test:
args.ks_trials = 20
args.n_batches = 10000
args.chunksize = 100
# Define output directories
error = comp.paths.condor_data_dir... |
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... |
... LabeledPoint(1.0, SparseVector(2, {1: 2.0}))
... ]
>>> lrm = LogisticRegressionWithSGD.train(sc.parallelize(sparse_data))
>>> lrm.predict(array([0.0, 1.0])) > 0
True
>>> lrm.predict(array([0.0, 0.0])) <= 0
True
>>> lrm.predict(SparseVector(2, {1: 1.0})) > 0
True
>>> lrm.... | ue
"""
def predict(self, x):
_linear_predictor_typecheck(x, self._coeff)
margin = _dot(x, self._coeff) + self._intercept
prob = 1/(1 + exp(-margin))
return 1 if prob > 0.5 else 0
class LogisticRegressionWithSGD(object):
@classmethod
def train(cls, data, iterations=100, ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_python_2d_ns
----------------------------------
Tests for `python_2d_ns` module.
"""
import sys
import unittest
from python_2d_ns.python_2d_ns import *
class TestPython_2d_ns(unittest.TestCase):
#test x, y coordinates generated by function IC_coor
... |
#this coordinate should be 0
self.assertTrue(x[0,2]==0)
#test initial condition, Taylor green forcing, test whether the value is given on specific wavenu | mber
def test_IC_con(self):
#generate kx, ky, assume 2 threads, rank==0
x, y, kx, ky, k2, k2_exp=IC_coor(32, 32, 16, 1, 1, 0, 2)
Vxhat, Vyhat=IC_condition(1, 2, kx, ky, 32, 16)
#this wavenumber should be zero
self.assertTrue(Vyhat[2,5]==0)
#this wavenumber should be non-zero
self.... |
e for reading and writing.
* `IOStream`: Implementation of BaseIOStream using non-blocking sockets.
* `SSLIOStream`: SSL-aware version of IOStream.
* `PipeIOStream`: Pipe-based IOStream implementation.
"""
from __future__ import absolute_import, division, print_function, with_statement
import collections
import errno... | )`` and a family of ``read_*()`` methods.
All of the methods take callbacks (since writing and reading are
non-blocking and asynchronous).
When a stream is closed due to an error, the IOStream's ``error``
attribute contains the exception object.
Subclasses must implement `fileno`, `close_fd`, `wri... | ze=None,
read_chunk_size=4096):
self.io_loop = io_loop or ioloop.IOLoop.current()
self.max_buffer_size = max_buffer_size or 104857600
self.read_chunk_size = read_chunk_size
self.error = None
self._read_buffer = collections.deque()
self._write_buffer = col... |
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PyYtopt(PythonPackag | e):
"""Ytopt package implements search using Random Forest (SuRF), an autotuning
search method developed within Y-Tune ECP project."""
maintainers = ['Kerilk']
homepage = "https://github.com/ytopt-team/ytopt"
url | = "https://github.com/ytopt-team/ytopt/archive/refs/tags/v0.0.1.tar.gz"
version('0.0.2', sha256='5a624aa678b976ff6ef867610bafcb0dfd5c8af0d880138ca5d56d3f776e6d71')
version('0.0.1', sha256='3ca616922c8e76e73f695a5ddea5dd91b0103eada726185f008343cc5cbd7744')
depends_on('python@3.6:', type=('build', 'run'))
... |
import _plotly_utils.basevalidators
class TickvalssrcValidator(_plotly_utils.basevalidators.SrcValidator):
def __init__(
self,
plotly_name="tickvalssrc" | ,
parent_name="scatter3d.marker.colorbar",
**kwargs
| ):
super(TickvalssrcValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "none"),
**kwargs
)
|
import sys
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
class Visualizer():
def __init__(self, *args):
pass
def show_performance(self, list_of_tuples, fig_size=(9,9), font_scale=1.1, file=''):
"""
Parameters: list_of_tuples:
... | font_scale:
- text scale in seaborn plots (default: 1.1)
file:
- string containing a valid filename (default: '')
Output: f: (matplotlib.pyplot.figure object)
"""
if not (isinstance(list_o... | raise ValueError("Expecting a list of tuples")
sns.set(font_scale=font_scale)
sns.set_style("whitegrid")
data = list()
for name, value in list_of_tuples: data.append([name, value])
data = pd.DataFrame(data, columns=['classifier', 'performance'])
data.sort_values(... |
# -*- coding: utf-8 -*-
from django.conf.urls import patterns, include, url
from .views import (AvailableMapListview, Av | ailableMapsDetailview,
index_view, MyArmiesListView, ArmyCreateView,
ArmyDetailView, RobotCreateView)
urlpatterns = patterns('',
url(r'maingame/maps$', AvailableMapListview.as_view(), name='list_available_ | maps'),
url(r'maingame/map/(?P<pk>\d+)$', AvailableMapsDetailview.as_view(), name="available_map_detail" ),
url(r'maingame/my_armies$', MyArmiesListView.as_view(), name='my_armies'),
url(r'maingame/army/(?P<pk>\d+)$', ArmyDetailView.as_view(), name="army_detail" ),
url(r'maingame/create_armies$', ArmyC... |
#!/usr/bin/env python
####### | #################################################################
# File : dirac-ve | rsion
# Author : Ricardo Graciani
########################################################################
"""
Print version of current DIRAC installation
Usage:
dirac-version [option]
Example:
$ dirac-version
"""
import argparse
import DIRAC
from DIRAC.Core.Base.Script import Script
@Script()
def main():
... |
def is_palindrome(obj):
obj = str(obj)
obj_list = list(obj)
obj_list_reversed = obj_list[::-1]
return obj_list == obj_list_reversed
def generate_rotations(word):
letters = list(word)
string_rotations = []
counter = len(letters)
temp = letters
while counter != 0:
current_l... | string_rotations.append(word)
counter -= 1
return string_rotations
def get_rotated_palindromes(string_rotations):
is_empty = True
for word in string_rotations:
if is_ | palindrome(word) is True:
print(word)
is_empty = False
if is_empty is True:
print("NONE")
def main():
user_input = input("Enter a string: ")
string_rotations = generate_rotations(user_input)
get_rotated_palindromes(string_rotations)
if __name__ == '__main__':
m... |
#!/usr/bin/env python
#-*- coding: utf-8 -*-
from __future__ import unicode_literals
import sqlite3
from flask import Flask, render_template, g, current_app, request
from flask.ext.paginate import Pagination
app = Flask(__name__)
app.config.from_pyfile('app.cfg')
@app.before_request
def before_request():
g.conn... | cur.fetchall()
pagination = get_pagination(page=page,
per_page=per_page,
total=total,
record_name='users',
)
return render_template('index.html', users=users,
... | pagination=pagination,
)
def get_css_framework():
return current_app.config.get('CSS_FRAMEWORK', 'bootstrap3')
def get_link_size():
return current_app.config.get('LINK_SIZE', 'sm')
def show_single_page_or_not():
return current_app.config.get('SHOW_SINGLE_PAGE', F... |
from django.contrib.contenttypes.models import ContentType
import json
from django.http import Http404, HttpResponse
from django.contrib import messages
from django.contrib.auth import get_user_model
from django.contrib.auth.decorators import login_required, user_passes_test
from django.core.urlresolvers import... | t(pk=request.current_department_id)
data['on_settings'] = True
handler = '_settings_% | s_%s' % (section, subsection)
if section == 'system' and request.user.is_superuser is not True:
return redirect('index')
if section == 'department' and not request.user.has_perm('core.change_department', obj=data['department']):
return redirect('index')
if handler in globals():
... |
"""Support for Acmeda Roller Blind Batteries."""
from __future__ import annotations
from homeassistant.components.sensor import SensorDeviceClass, SensorEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import PERCENTAGE
from homeassistant.core import HomeAssistant, callback
from hom... | ry.entry_id]
current: set[int] = set()
@callback
def async_add_acmeda_sensors():
async_add_acmeda_entities(
| hass, AcmedaBattery, config_entry, current, async_add_entities
)
hub.cleanup_callbacks.append(
async_dispatcher_connect(
hass,
ACMEDA_HUB_UPDATE.format(config_entry.entry_id),
async_add_acmeda_sensors,
)
)
class AcmedaBattery(AcmedaBase, Sensor... |
#!/usr/bin/env python
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# (1) Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# ... | CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER C | AUSED AND ON ANY THEORY OF 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 THE
# POSSIBILITY OF SUCH DAMAGE.
"""
Python setup script.
"""
from setuptools import setup, find_packages
def extract_re... |
"quotas", "provider"]
binding_view = "extension:port_binding:view"
binding_set = "extension:port_binding:set"
def __init__(self):
LOG.info(_('Neutron PLUMgrid Director: Starting Plugin'))
super(NeutronPluginPLUMgridV2, self).__init__()
self.plumgrid_init()
... | PLUMgridException(err_msg=err_message)
# Return | updated network
return net_db
def delete_network(self, context, net_id):
"""Delete Neutron network.
Deletes a PLUMgrid-based bridge.
"""
LOG.debug(_("Neutron PLUMgrid Director: delete_network() called"))
net_db = super(NeutronPluginPLUMgridV2,
... |
rt",
MagicMock(return_value=True),
), patch(
"salt.utils.process.SignalHandlingProcess.join",
MagicMock(return_value=True),
):
try:
mock_opts = salt.config.DEFAULT_MINION_OPTS.copy()
mock_opts["cachedir"] = str(tmp_path)
minion = salt.minion.Mi... | load = minion._send_req_sync.call_args[0][0]
assert "grains" not in load
finally:
minion.destroy()
@pytest.mark.slow_test
def test_when_other_events_fired_and_start_event_grains_are_set():
mock_opts = salt.config.DEFAULT_MINION_OPTS.copy()
mock_opts["start_event_grains"] = ["os"]
io_... | oop.make_current()
minion = salt.minion.Minion(mock_opts, io_loop=io_loop)
try:
minion.tok = MagicMock()
minion._send_req_sync = MagicMock()
minion._fire_master("Custm_event_fired", "custom_event")
load = minion._send_req_sync.call_args[0][0]
assert "grains" not in load
... |
#!/usr/bin/env python
import sys
# sys.dont_write_bytecode = True
import glob
import os
import time
import logging
import os.path
from argparse import ArgumentParser
class RtmBot(object):
def __init__(self, token):
self.last_ping = 0
self.token = token
self.bot_plugins = []
self... | a):
if function_name in dir(self.module):
# this makes the plugin fail with stack trace in debug mode
if not debug:
try:
eval("self.module." + function_name)(data)
except:
logging.debug("problem in module {} {}".form... | + function_name)(data)
if "catch_all" in dir(self.module):
try:
self.module.catch_all(data)
except:
logging.debug("problem in catch all")
def do_jobs(self):
for job in self.jobs:
job.check()
def do_output(self):
outpu... |
CFG_SITE_NAME_INTL, \
CFG_SITE_NAME, \
CFG_SITE_ADMIN_EMAIL, \
CFG_MISCUTIL_SMTP_HOST, \
CFG_MISCUTIL_SMTP_PORT, \
CFG_VERSION, \
CFG_DEVEL_SITE
from invenio.errorlib import register_exception
from invenio.messages import wash_language, gettext_set_language
from invenio.miscutil_confi... | email was sent okay, False if it was not.
"""
if html_images is None:
html_images = {}
if type(toaddr) is str:
toaddr = toaddr.strip().split(',' | )
toaddr = remove_temporary_emails(toaddr)
if type(bccaddr) is str:
bccaddr = bccaddr.strip().split(',')
usebcc = len(toaddr) > 1 # More than one address, let's use Bcc in place of To
if copy_to_admin:
if CFG_SITE_ADMIN_EMAIL not in toaddr:
toaddr.append(CFG_SITE_ADMIN_EM... |
import os
from torch.utils.ffi import create_extension
sources = ["src/lib_cffi.cpp"]
headers = ["src/lib_cffi.h"]
extra_objects = ["src/bn.o"]
with_cuda = True
this_file = os.path.dirname(os.path.realpath(__file__))
extra_objects = [os | .path.join(this_file, fname) for fname in extra_objects]
ffi = create_extension(
"_ext",
headers=headers,
sources=sources,
| relative_to=__file__,
with_cuda=with_cuda,
extra_objects=extra_objects,
extra_compile_args=["-std=c++11"],
)
if __name__ == "__main__":
ffi.build()
|
#!/usr/bin/env python
import gtk, sys, string
class Socket:
def __init_ | _(self):
window = gtk.Window()
window.set_default_size(200, 200)
socket = gtk.Socket()
window.add(socket)
print "Socket ID:", socket.get_id()
if len(sys.argv) == 2:
socket.add_id(long(sys.argv[1]))
window. | connect("destroy", gtk.main_quit)
socket.connect("plug-added", self.plugged_event)
window.show_all()
def plugged_event(self, widget):
print "A plug has been inserted."
Socket()
gtk.main()
|
ay the video
And I watch 5 seconds of it
And I pause the video
Then a "load_video" event is emitted
And a "play_video" event is emitted
And a "pause_video" event is emitted
"""
def is_video_event(event):
"""Filter out anything other than the video eve... | ['event_type']
if is_played_event and appears_again:
continue
filtered_events.append(video_event)
for idx, video_event in enumerate(filtered_events):
if idx < 3:
self.assert_bumper_payload_contains_ids(video_event, sources, duration)
... | assert_event_matches({'event_type': 'edx.video.bumper.loaded'}, video_event)
elif idx == 1:
assert_event_matches({'event_type': 'edx.video.bumper.played'}, video_event)
self.assert_valid_control_event_at_time(video_event, 0)
elif idx == 2:
... |
#!/usr/bin/env python
#
# Copyright (c) 2001 - 2016 The SCons Foundation
#
# 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 without restriction, including
# without limitation the rights to us... | <x>0</x>
<y>0</y>
<width>600</width>
<height>385</height>
</rect>
</property>
</widget>
<includes>
<include location="local" impldecl="in implementation">migraform.h</include>
</includes>
</UI>
""")
test.write(['layer', 'aclock', 'qt_bug', 'mi | graform.ui'], """\
<!DOCTYPE UI><UI version="3.3" stdsetdef="1">
<class>MigrateForm</class>
<widget class="QWizard">
<property name="name">
<cstring>MigrateForm</cstring>
</property>
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>600</width>
... |
esult[bucket] = res
return result
class CacheMissRatio:
def run(self, accessor):
result = {}
cluster = 0
for bucket, stats_info in stats_buffer.buckets.iteritems():
values = stats_info[accessor["scale"]][accessor["counter"]]
timestamps = values["timestamp"]
... | result[bucket] = {"error" : num_error}
return result
class MemoryFramentation:
def run(self, accessor):
result = {}
for bucket, bucket_stats in stats_buffer.node_stats.iteritems():
num_error = []
for node, stats_info in bucket_stats.iteritems():
... | ritems():
if key.find(accessor["counter"]) >= 0:
if accessor.has_key("threshold"):
if int(value) > accessor["threshold"]:
if accessor.has_key("unit"):
if accessor["unit"] == "time"... |
"""`main` is the top level module for your Flask application."""
# Import the Flask Framework
import os
import json
from flask import Flask, request, send_from_directory, render_template
app = Flask(__name__, static_url_path='')
# Note: We don't need to call run() since our application is embedded within
# the App E... | h.splitext(path)
if ext == "":
ext = ".json"
SITE_ROOT = os.path.realpath(os.path.dirname(__file__))
json_url = os.path.join(SITE_ROOT, "static", "json", file + ext)
s = ''
with open(json_url) as f:
| for line in f:
s += line
return s
if __name__ == '__main__':
app.run()
|
me": "Always Disable"},
]
LIGHT_MODE_MOTION = "On Motion - Always"
LIGHT_MODE_MOTION_DARK = "On Motion - When Dark"
LIGHT_MODE_DARK = "When Dark"
LIGHT_MODE_OFF = "Manual"
LIGHT_MODES = [LIGHT_MODE_MOTION, LIGHT_MODE_DARK, LIGHT_MODE_OFF]
LIGHT_MODE_TO_SETTINGS = {
LIGHT_MODE_MOTION: (LightModeType.MOTION.value,... | self._unifi_to_hass_options: dict[Any, str] = {
item["id"]: item["name"] for item in options
}
| self._async_set_dynamic_options()
@callback
def _async_update_device_from_protect(self) -> None:
super()._async_update_device_from_protect()
# entities with categories are not exposed for voice and safe to update dynamically
if self.entity_description.entity_category is not None:
... |
f | rom django.db.backends.postgresql.creatio | n import * # NOQA
|
try:
from s | etuptools import setup
except ImportError:
from distutils.core import setup
config = {
'description': 'My Project',
'author': 'Wouter Oosterveld',
'url': 'URL to get it at.',
'download_url': 'Where to download it.',
'author_email': 'wouter@fizzyflux.nl',
'version': '0.1',
'install_requi... | up(**config)
|
# 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... | is agreement definition"""
template_n | ame = cls.email_body_template_name or 'emails/agreement_default_body.html'
template_path = get_overridable_template_name(template_name, cls.plugin, 'events/agreements/')
return get_template_module(template_path, event=event)
@classmethod
@memoize_request
def get_people(cls, event):
... |
m_cache[vm]["instance"]["state"]["state"].title()
server_mac_address = vm_cache[vm]['id']
server_mac_address = str(server_mac_address).replace(':','-')
if(vm_state=="Running"):
isotope_filter_classes = " linux "
if(data_median<17):
... | ocesses_ = []
processes = server['processes']
c=0
for line in processes:
if(c>0):
if not line:break
line = line.split(' ')
line_ = []
for i in line:
| if i: line_.append(i)
line = line_
process_user = line[0]
process_pid = line[1]
process_cpu = line[2]
process_mem = line[3]
process_vsz = line[4]
process_rss = line[5]
pro... |
# Python - 3.6.0
century = lambda year: year // 100 | + ((year % 100) > 0) | |
from datetime import datetime
from django.http import HttpResponse, HttpResponseRedirect
from django.views.generic import View, ListView, DetailView
from django.views.generic.edit import CreateView, UpdateView
from content.models import Sub, SubFollow, Post, Commit
from content.forms import SubForm, PostForm, CommitF... | SubView(CreateView):
template_name = 'content/sub_create.html'
form_class = SubForm
def form_valid(self, form):
obj = form.save(commit=False)
obj.save()
obj.image = 'sub/%s.png' % (obj.slug)
obj.save()
random_avatar_sub(obj.slug)
return HttpResponseRedirect('/sub')
class SubView(ListView):
template_n... | ml'
paginate_by = 4
def get(self, request, *args, **kwargs):
if request.is_ajax(): self.template_name = 'ajax/post_list.html'
return super(FrontView, self).get(request, *args, **kwargs)
def get_queryset(self):
if self.kwargs['tab'] == 'top': return Post.objects.last_commited()
else: return Post.objects.cre... |
# -*- coding: utf-8 -*-
import time
from openerp import api, models
import datetime
class ReportSampleReceivedvsReported(models.AbstractModel):
_name = 'report.olims.report_sample_received_vs_reported'
def _get_samples(self, samples):
datalines = {}
footlines = {}
total_received_coun... | # Footer total data
if total_received_count > 0:
ratio = total_published_count / total_received_count
else:
ratio = total_published_count / 1
try:
footline = {'ReceivedCount': total_received | _count,
'PublishedCount': total_published_count,
'UnpublishedCount': total_received_count - total_published_count,
'Ratio': ratio,
'RatioPercentage': '%02d' % (100 * (
float(total_published_count) / float(
... |
_iter, end_iter)
# if it's a ${cursor} variable we don't want to insert
# any new text. Just go to the else and get it's start
# offset, used later to mark that location
if not var.group() == "${cursor}":
# insert the variable identifier into the buffer
# at the start location
self.editor.buff... | ble_offsets(value, overall_offset)
if offsets:
marks = self.mark_variables(offsets)
if marks:
_iter = self.editor.buff.get_iter_at_offset( offsets[0]["start"] )
self.editor.buff.place_cursor(_i | ter)
marks.reverse()
for mark in marks:
self.SNIPPET_MARKS.insert(0, mark)
offsets.reverse()
for offset in offsets:
self.SNIPPET_OFFSETS.insert(0,offset)
self.IN_SNIPPET = True
else:
self.HAS_NO_VARIABLES=True
def pair_text(self, pair_chars):
se... |
ort os
import itertools
from collections import defaultdict
import angr
UNIQUE_STRING_COUNT = 20
# strings longer than MAX_UNIQUE_STRING_LEN will be truncated
MAX_UNIQUE_STRING_LEN = 70
def get_basic_info(ar_path: str) -> Dict[str,str]:
"""
Get basic information of the archive file.
"""
with tempf... | ked = set()
unique_strings = [ ]
for s in sorted_strings:
if s[:5] in picked:
co | ntinue
unique_strings.append(s[:MAX_UNIQUE_STRING_LEN])
picked.add(s[:5])
ctr += 1
if ctr >= UNIQUE_STRING_COUNT:
break
return unique_strings
def run_pelf(pelf_path: str, ar_path: str, output_path: str):
subprocess.check_call([pelf_path, "-r43:0:0", ar_path, output_... |
of data values. The data values are displayed in successive columns
after the tree label."""
def __init__(self, master=None, **kw):
"""Construct a Ttk Treeview with parent master.
STANDARD OPTIONS
class, cursor, style, takefocus, xscrollcommand,
yscrollcommand
... | n)
def identify(self, component, x, y):
| """Returns a description of the specified component under the
point given by x and y, or the empty string if no such component
is present at that position."""
return self.tk.call(self._w, "identify", component, x, y)
def identify_row(self, y):
"""Returns the item ID of the it... |
'/pywb/')
def head_insert_func(rule, cdx):
if rule.js_rewrite_location != 'urls':
return '<script src="/static/__pywb/wombat.js"> </script>'
else:
return ''
def test_csrf_token_headers():
rewriter = LiveRewriter()
env = {'HTTP_X_CSRFTOKEN': 'wrong', 'HTTP_COOKIE': 'csrftoken=foobar'}
... | =B'}
urlkey = 'example,example,test)/'
url = 'test.example.example/'
req_headers = rewriter.translate_headers(url, urlkey, env)
assert req_headers == {'Cookie': 'A=B; FOO=&bar=1'}
def test_req_cookie_rewrite_2():
rewriter = L | iveRewriter()
env = {'HTTP_COOKIE': 'FOO=goo'}
urlkey = 'example,example,test)/'
url = 'test.example.example/'
req_headers = rewriter.translate_headers(url, urlkey, env)
assert req_headers == {'Cookie': 'FOO=&bar=1'}
def test_req_cookie_rewrite_3():
rewriter = LiveRewriter()
env = {}
... |
# -*- coding: utf-8 -*-
#
# Copyright © 2009-2010 Pierre Raybaut
# Licensed under the terms of the MIT License
# (see spyderlib/__init__.py for details)
"""Online Help Plugin"""
from spyderlib.qt.QtCore import Signal
import os.path as osp
# Local imports
from spyderlib.baseconfig import get_conf_path, ... | anged"""
SpyderPluginMixin.visibility_changed(self, enable)
if enable and not self.is_server_running():
| self.initialize()
#------ SpyderPluginWidget API ---------------------------------------------
def get_plugin_title(self):
"""Return widget title"""
return _('Online help')
def get_focus_widget(self):
"""
Return the widget to give focus to when
thi... |
"""Support for the Hive switches."""
from datetime import timedelta
from homeassistant.components.switch import SwitchEntity
from . import ATTR_AVAILABLE, ATTR_MODE, DATA_HIVE, DOMAIN, HiveEntity, refresh_system
PARALLEL_UPDATES = 0
SCAN_INTERVAL = timedelta(seconds=15)
async def async_setup_platform(hass, config,... | """Turn the switch on."""
if self.device["hiveType"] == "activeplug":
await self.hive.switch.turn_on(self.device)
@refresh_system
async def async_turn_off(self, **kwargs):
"""Turn the device off."""
if self.device["hiveType"] == "activeplug":
await self.hive... | ll Node data from Hive."""
await self.hive.session.updateData(self.device)
self.device = await self.hive.switch.get_plug(self.device)
|
troveTuple[0].split(':', 1)[0] == troveName:
# exact matches take priority
return (jobId, troveTuple)
elif troveTuple[0].startswith(troveName) and startsWith is None:
startsWith = (jobId, troveTuple)
return startsWith
def getTroveState(self, jobId... |
def __init__(self, client, showBuildLogs, out=None, exitOnFinish=None):
self.termInfo = set_raw_mode()
if out is None:
out = open('/dev/tty', 'w')
self.state = self.stateClass(client)
self.display = self.displayClass(client, self.state, out)
self.client = | client
self.troveToWatch = None
self.troveIndex = 0
self.showBuildLogs = showBuildLogs
if exitOnFinish is None:
exitOnFinish = False
self.exitOnFinish = exitOnFinish
def _receiveEvents(self, *args, **kw):
methodname = '_receiveEvents'
method = get... |
#!/usr/bin/env | python
# encoding: utf-8
class MyRange(object):
def __init__(self, n):
self.idx = 0
self.n = n
def __iter__(self):
return self
def next(self):
if self.idx < self.n:
val = self.idx
self.idx += 1
return val
else:
raise St... | i
|
# -*- coding: utf-8 -*-
import os.path
import re
import warnings
try:
from setuptools import setup, find_packages
except ImportError:
from distribute_setup import use_setuptools
use_setuptools()
| from setuptools import setup, find_packages
version = '0.2.1'
news = os.path.join(os.path.dirname(__file__), 'docs', 'news.rst')
news = open(news).read()
parts = re.split(r'([0-9\.]+)\s*\n\r?-+\n\r?', news)
found_news = ''
for i in range(len(parts)-1):
if parts[i] == version:
found_news = parts[i+i]
... | )
long_description = """
keepassdb is a Python library that provides functionality for reading and writing
KeePass 1.x (and KeePassX) password databases.
This library brings together work by multiple authors, including:
- Karsten-Kai König <kkoenig@posteo.de>
- Brett Viren <brett.viren@gmail.com>
- Wakayama Shirou... |
#!/Users/harvey/Projects/face-hack/venv/face/bin/python
#
# The Python Imaging Library
# $Id$
#
from __future__ import print_function
try:
from tkinter import *
except ImportError:
from Tkinter import *
from PIL import Image, ImageTk
import sys
# ------------------------------------------------------------... | self.update_idletasks()
# --------------------------------------------------------------------
# scr | ipt interface
if __name__ == "__main__":
if not sys.argv[1:]:
print("Syntax: python player.py imagefile(s)")
sys.exit(1)
filename = sys.argv[1]
root = Tk()
root.title(filename)
if len(sys.argv) > 2:
# list of images
print("loading...")
im = []
for... |
Thomas J Fan <thomasjpfan@gmail.com>
# License: BSD 3 clause
import numpy as np
from ._base import _BaseImputer
from ..utils.validation import FLOAT_DTYPES
from ..metrics import pairwise_distances_chunked
from ..metrics.pairwise import _NAN_METRICS
from ..neighbors._base import _get_weights
from ..neighbors._base im... | ng_values,
add_indicator=add_indicator
)
self.n_neighbors = n_neighbors
self.weights = weights
self.metric = metric
self.copy = copy
def _calc_impute(self, dist_pot_donors, n_neighbors,
fit_X_col, mask_fit_X_col):
"""Helper function t... | te a single column.
Parameters
----------
dist_pot_donors : ndarray of shape (n_receivers, n_potential_donors)
Distance matrix between the receivers and potential donors from
training set. There must be at least one non-nan distance between
a receiver and a p... |
#!/usr/bin/python -Wall
# ================================================================
# Copyright (c) John Kerl 2007
# kerl.john.r@gmail.com
# ================================================================
from __future__ import division # 1/2 = 0.5, not 0.
from math import *
from sackmat_m import *
import cop... | nml = [nx, ny, nz]
e0 = [1,0,0]
e1 = [0,1,0]
e2 = [0,0,1]
# Project the standard basis for R3 down to the tange | nt plane TM|q.
proj_e0 = projperp(e0, nml)
proj_e1 = projperp(e1, nml)
proj_e2 = projperp(e2, nml)
proj_e = sackmat([proj_e0, proj_e1, proj_e2])
# Row-reduce, compute rank, and trim
proj_e.row_echelon_form()
rank = proj_e.rank_rr()
proj_e.elements = proj_e.elements[0:rank]
# Orthonormalize... |
information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from copy import deepcopy
from typing import Any, Awaitable, Optional, TYPE_CHECKING
... | ns.CertificateRegistrationProviderOperations
:ivar domains: DomainsOperations operations
:vartype domains: azure.mgmt.web.v2020_06_01.aio.operations.DomainsOperations
:ivar top_level_domains: TopLevelDomainsOperations operations
:vartype top_level_domains: azure.mgmt.web.v2020_06_01.aio.operations.TopLe... | main_registration_provider:
azure.mgmt.web.v2020_06_01.aio.operations.DomainRegistrationProviderOperations
:ivar certificates: CertificatesOperations operations
:vartype certificates: azure.mgmt.web.v2020_06_01.aio.operations.CertificatesOperations
:ivar deleted_web_apps: DeletedWebAppsOperations opera... |
from FortyTwo.fortytwo import *
def Start():
"""No Clue what to | ad | d here"""
|
''Saves an uploaded data source to MEDIA_ROOT/data_sources
'''
with open(os.path.join(settings.MEDIA_ROOT, 'data_sources', f.name), 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
return destination
@task()
def extract_features(dataset_id, instance_... | # If the feature has subfeatures, e.g. Spec shape stats
if 'subfeatures' in feature:
full_output = engine.readOutput(output_name)
for i, subfeature_display_name in enumerate(feature['subfeatures']):
outputs[subfeature_display_name] = full_output[:, i... | a = engine.readOutput(output_name) # 2D array
# Transpose data to make it a 1D array
outputs[display_name] = a.transpose()[0]
# Create YAAFE feature objects
feature_obj_list = []
for display_name in outputs.keys():
feature = find_dict_by_item(('display_name', di... |
import unittest
import hashlib
import httpsig.sign as sign
from httpsig.utils import parse_authorization_header
from requests.models import RequestEncodingMixin
c | lass CrossPlatformTestCase(unittest.TestCase):
def test_content_md5(self):
data = {'signature': "HPMOHRgPSMKdXrU6AqQs/i9S7alOakkHsJiqLGmInt05Cxj6b/WhS7kJxbIQxKmDW08YKzoFnbVZIoTI2qofEzk="}
assert RequestEncodingMixin._encode_params(data) == "signature=HPMOHRgPSMKdXrU6AqQs%2Fi9S7alOakkHsJiqLGmInt05Cx... | "utf-8")).hexdigest() == "fdfc1a717d2c97649f3b8b2142507129"
def test_hmac(self):
hs = sign.HeaderSigner(key_id='pda', algorithm='hmac-sha256', secret='secret', headers=['(request-target)', 'Date'])
unsigned = {
'Date': 'today',
'accept': 'llamas'
}
signed = h... |
"""Resource manage module."""
import os
from .utils import RequestUtil
class ResourceAPI(object):
"""Resource wechat api."""
ADD_TEMP_URI = ('https://api.weixin.qq.com/cgi-bin/media/'
'upload?access_token={}&type={}')
@classmethod
def upload(cls, path, token, rtype, upload_type=... | edia to wechat server.
:path str: Upload e | ntity local path
:token str: Wechat access token
:rtype str: Upload entity type
:Return dict:
"""
uri = cls.ADD_TEMP_URI.format(token, rtype)
resp = RequestUtil.upload(uri, {}, path)
return resp
|
# coding=utf-8
from __futur | e__ import unicode_literals, print_function
from flask import request, jsonify, url_for
from flask_login import current_user
import bugsnag
from . import load
from webhookdb.tasks.pull_request_file import spawn_page_tasks_for_pull_request_files
@load.route('/repos/<owner>/<repo>/pulls/<int:number>/files', methods=["P... | ""
Queue tasks to load the pull request files (diffs) for a single pull request
into WebhookDB.
:statuscode 202: task successfully queued
"""
bugsnag_ctx = {"owner": owner, "repo": repo, "number": number}
bugsnag.configure_request(meta_data=bugsnag_ctx)
children = bool(request.args.get("chi... |
import math
import pkg_resources
import itertools
import pandas as pd
import networkx as nx
from postman_problems.viz import add_node_attributes
from postman_problems.graph import (
read_edgelist, create_networkx_graph_from_edgelist, get_odd_nodes, get_shortest_paths_distances
)
from postman_problems.solver import ... | nl == set(), \
"Warning: The following nodes are in the edgelist, but not the nodelist: {}".format(nodes_in_el_but_not_nl)
nodes_in_nl_but_not_el = nodelist_nodes - edgelist_nodes
assert nodes_in_nl_but_not_el == set(), \
"Warning: The following nodes are in the nodelist, but not the edgelist: ... | cpp_solution, graph = cpp(edgelist_filename=EDGELIST, start_node=START_NODE)
# make number of edges in solution is correct
assert len(cpp_solution) == 155
# make sure our total mileage is correct
cpp_solution_distance = sum([edge[3]['distance'] for edge in cpp_solution])
assert math.isclose(cpp_s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.