prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
# coding:utf-8
import logging
import numpy as np
from scipy.linalg import svd
from mla.base import BaseEstimator
np.random.seed(1000)
class PCA(BaseEstimator):
y_required = False
def __init__(self, n_components, solver="svd"):
"""Principal component analysis (PCA) implementation.
Transfor... | e variance and each following component as the
largest possible variance given the previous components. This causes
the early components to contain most of the variability in the dataset.
Parameters
------- | ---
n_components : int
solver : str, default 'svd'
{'svd', 'eigen'}
"""
self.solver = solver
self.n_components = n_components
self.components = None
self.mean = None
def fit(self, X, y=None):
self.mean = np.mean(X, axis=0)
self._de... |
"""
| Add user scren name to whitelist if it is not to be unfollowed
"""
whitelist = [
|
] |
['ne'] in PRE_MERGE_NETAG)
b0_atomics['isne']=b0_atomics['ne'] in PRE_MERGE_NETAG
b0_atomics['hastrace'] = len(self.A.nodes[self.cidx].incoming_traces) > 0
# prop feature
b0_atomics['isarg']=self.cidx in s0_args if s0_args else NOT_ASSIGNED
b0_atomics['arglab... | #a0_atomics['iscycle'] = parent_to_attach in self.A.nodes[self.cidx].children or parent_to_att | ach in self.A.nodes[self.cidx].parents
# prop feature
b0_prds = None
b0_args = None
if isinstance(self.cidx,int) and GraphState.sent[self.cidx].get('pred',{}):
b0_prds = GraphState.sent[self.cidx]['pred']
if isinstance(... |
# -*- coding: utf-8 -*-
#+---------------------------------------------------------------------------+
#| 01001110 01100101 01110100 01111010 0110 | 1111 01100010 |
#| |
#| Netzob : Inferring communication protocols |
#+---------------------------------------------------------------------------+
#| Copyright (C) 2011 Georges Bossert and Frédéric Guihé... | General Public License as published by |
#| the Free Software Foundation, either version 3 of the License, or |
#| (at your option) any later version. |
#| |
#| This program is distributed in th... |
def sync(self):
self.googlecalendar.read()
def load_preferences(self):
configuration = Configuration()
self.time = configuration.get('time')
self.theme = configuration.get('theme')
self.calendars = configuration.get('calendars')
self.visible_calendars = []
for calendar in self.calendars:
if calen... | conector_event = 'activate',conector_action = self.on_menu_refresh)
self.menu_show_calendar = add2menu(self.menu, text = _('Show Calendar'), conector_event = 'activate',conector_action = self.menu_show_calendar_response)
self.menu_preferences = add2menu(self.menu, text = _('Preferences'), conector_event = 'activa | te',conector_action = self.menu_preferences_response)
add2menu(self.menu)
menu_help = add2menu(self.menu, text =_('Help'))
menu_help.set_submenu(self.get_help_menu())
add2menu(self.menu)
add2menu(self.menu, text = _('Exit'), conector_event = 'activate',conector_action = self.menu_exit_response)
self.menu.sh... |
continue
if result is None:
continue
vectors.append(
(hexlify(public_key), hexlify(private_key), hexlify(shared), result)
)
return vectors
def generate_ecdh(filename):
vectors = []
data = load_json_testvectors(filename)
if not... | if curve is None:
raise NotSupp | orted("Curve not supported: {}".format(curve_name))
public_key = unhexlify(public_key)
signature = unhexlify(signature)
message = unhexlify(message)
computed_result = (
lib.ecdsa_verify(curve, hasher, public_key, signature, message, len(message))
== 0
)
assert result == compute... |
# -*- coding: utf-8 -*-
from .common import *
class ReferenceDescriptorTest(TestCase):
def setUp(self):
self.reference_descriptor = ReferenceD | escriptor.obje | cts.create(
content_type=ContentType.objects.get_for_model(Model))
self.client = JSONClient()
def test_reference_descriptor_list(self):
url = reverse('business-logic:rest:reference-descriptor-list')
response = self.client.get(url)
self.assertEqual(200, response.status_co... |
"""
Define a few commands
"""
from .meeseeksbox.utils import Session, fix_issue_body, fix_comment_body
from .meeseeksbox.scopes import admin, write, everyone
from textwrap import dedent
def _format_doc(function, name):
if not function.__doc__:
doc = " "
else:
doc = function.__doc__.splitli... | eturn
issue_title = payload["issue"]["title"]
issue_body = payload["issue"]["body"]
original_org = payload["organization"]["login"]
original_repo = payload["repository"]["name"]
original_poster = payload["issue"]["user"]["login"]
original_number = payload["issue"]["number"]
migration_reques... | user"]["login"]
request_id = payload["comment"]["id"]
original_labels = [l["name"] for l in payload["issue"]["labels"]]
if original_labels:
available_labels = target_session.ghrequest(
"GET",
"https://api.github.com/repos/{org}/{repo}/labels".format(
org=org,... |
vertex set
vt_list[face.index, i]=tex_count
backlist[tex_count] = face.verts[i].index
tex_count+=1
else:
vt_list[face.index, i]=tex_list[tex_key]
backlist[tex_count] = face.verts[i].index
mdl.num_vertices=tex_count
for this_tex in range (0, mdl.num_vertices):
mdl.tex_coords.append(mdl_te... | le and read it in
file=open(g_frame_filename.val,"r")
lines=file.readlines()
file.close()
#check header (first line)
if lines[0].strip()<>"# MDL Frame Name List":
print "its not a valid file"
result=Blender.Draw.PupMenu("This is not a valid frame definition file-using default%t|OK")
return M... | in range(1, len(lines)):
current_line=lines[counter].strip()
if current_line[0]=="#":
#found a comment
pass
else:
data=current_line.split()
frame_list.append([data[0],num_frames+1, num_frames+in |
disk.split(':')[1].lstrip()
elif key.strip() == "SysFS ID":
devlist["sysfs_id"] = \
disk.split(':')[1].lstrip()
elif key.strip() == "SysFS BusID":
devlist["sysfs_busid"] = \
disk.split(':')... | to_minor_no'] = dev_info['MAJ:MIN']
device['fstype'] = dev_info['FSTYPE']
device['mount_point'] = dev_info['MOUNTPOINT']
device['label'] = dev_info['LABEL']
device['fsuuid'] = dev_info['UUID']
device['read_ahead'] = dev_info['RA']
if dev_info['RO']... | ce'] = False
else:
device['removable_device'] = True
device['size'] = dev_info['SIZE']
device['state'] = dev_info['STATE']
device['owner'] = dev_info['OWNER']
device['group'] = dev_info['GROUP']
device['mode'] = dev_info['MODE']
... |
# This is your "setup.py" file.
# See the following sites for general guide to Python packaging:
# * `The Hitchhiker's Guide to Packaging <http://guide.python-distribute.org/>`_
# * `Python Project Howto <http://infinitemonkeycorps.net/docs/pph/>`_
from setuptools import setup, find_packages
import sys
import os
#... | join(here, 'NEWS.rst')).read()
version = '0.1'
install_requires = [
# List your project dependencies here.
# For more details, see:
# http://packages.python.org/distribute/setuptools.html#decla | ring-dependencies
# Packages with fixed versions
# "<package1>==0.1",
# "<package2>==0.3.0",
# "nose", "coverage" # Put it here.
]
tests_requires = [
# List your project testing dependencies here.
]
dev_requires = [
# List your project development dependencies here.\
]
dependency_links = [
... |
from testscenarios import TestWithScenarios
import unittest
from geocode.geocode import GeoCodeAccessAPI
class GeoCodeTests(TestWithScenarios, unittest.TestCase):
scenarios = [
(
"Scenario - 1: Get latlng from address",
{
'address': "Sydney NSW",
'l... | "Scenario - 2: Get address from latlng",
{
'address': "Sydney NSW" | ,
'latlng': (-33.8674869, 151.2069902),
'method': "address",
}
),
]
def setUp(self):
self.api = GeoCodeAccessAPI()
def test_geocode(self):
if self.method == 'geocode':
expected_address = self.address
expected_lat =... |
"""
A simple client to query a TensorFlow Serving instance.
Example:
$ python client.py \
--images IMG_0932_sm.jpg \
--num_results 10 \
--model_name inception \
--host localhost \
--port 9000 \
--timeout 10
Author: Grant Van Hor | n
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import time
import tfserver
def parse_args():
parser = argparse.ArgumentParser(description='Command line classification client. Sorts and prints the classification results.')
pars... | type=str, nargs='+', required=True)
parser.add_argument('--num_results', dest='num_results',
help='The number of results to print. Set to 0 to print all classes.',
required=False, type=int, default=0)
parser.add_argument('--model_name', dest='model_name',
... |
"""A backport | of the get_terminal_size function from Python 3.3's shutil."""
__title__ = "backports.shutil_get_terminal_size"
__version__ = "1.0.0"
__license__ = "MIT"
__author__ = "Christopher Rosell"
__copyright__ = "Copyright 2014 Christopher Rosell"
__all__ = ["get_terminal_size"]
fro | m .get_terminal_size import get_terminal_size
|
from django.test import TestCase
from django.contrib.auth.models import User
from django.urls import reverse
from .models import UserProfile
from imagersite.tests import AuthenticatedTestCase
# Create your tests here.
class ProfileTestCase(TestCase):
"""TestCase for Profile"""
def setUp(self):
"""Set... | ).content)
class EditProfileTestCase(TestCase):
"""Edit profile test case."""
def setUp(self):
"""GET the route named edit_profile."""
self.user = User(username='test')
self.user.save()
self.client.force_login(self.user)
self.response = self.client.get(reverse('edit_pr... | rtEqual(self.response.status_code, 200)
def test_edit_profile(self):
"""Test editing a album stores the updated value."""
new_camera_type = 'camera'
data = {
'camera_type': new_camera_type,
}
response = self.client.post(reverse('edit_profile'), data)
self... |
"""
Revision ID: 0146_add_service_callback_api
Revises: 0145_add_notification_reply_to
Create Date: 2017-11-28 15:13:48.730554
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
revision = '0146_add_service_callback_api'
down_revision = '0145_add_notification_reply_to'
de... | KeyConstraint(['updated_by_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_service_callback_api_service_id'), 'service_callback_api', ['service_id'], unique=True)
op.create_index(op.f('ix_ | service_callback_api_updated_by_id'), 'service_callback_api', ['updated_by_id'], unique=False)
def downgrade():
op.drop_index(op.f('ix_service_callback_api_updated_by_id'), table_name='service_callback_api')
op.drop_index(op.f('ix_service_callback_api_service_id'), table_name='service_callback_api')
op.dr... |
is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
# If extensions (or modules to docu... | le will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help... | _elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, ti... |
# -*- coding: utf-8 -* | -
"""Controllers for the pypollmanage pluggable application."""
from .root import RootController | |
# -*- coding: utf-8 -*-
# © 2016 Comunitea
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
from odoo import api, fields, models
class GeneralLedgerReportWizard(models.TransientModel):
_inherit = "general.ledger.report.wizard"
@api.onchange('company_id')
def onchange_company_id(self):
... | per(GeneralLedgerReportWizard, self).onchange_company_id()
if self.company_id:
res['domain']['partner_ids'] = [
('is_company', '=', True)
]
re | turn res |
.getLogger(__name__)
configdrive_opts = [
cfg.StrOpt('config_drive_format',
default='iso9660',
choices=('iso9660', 'vfat'),
help='Config drive format.'),
# force_config_drive is a string option, to allow for future behaviors
# (e.g. use config_drive based on im... | it',
'-s', CONFIGDRIVESIZE_BYTES,
'-t', 'ext4',
path + '/disk.config.hds',
attempts=1,
run_as_root=True)
with utils.tempdir() as mountdir:
mounted = False
try:
_,... | 'ploop', 'mount',
'-m', mountdir,
'-t', 'ext4',
path + '/DiskDescriptor.xml',
run_as_root=True)
if os.path.exists(mountdir):
utils.execute('chown', '-R',
... |
from django.contrib.admin.models import LogE | ntry
from django.contrib.auth.models import User, Group, Permission
from simple_history import register
from celsius.tools import register_for_permission_handling
register(User)
register(Group)
register_for_permission_handling(User)
register_for_permission_handling(Group)
register_for_permission_handling(Permission)... | ssion_handling(LogEntry)
|
from django.test import TestCase
from voice.models import Call
class CallModelTestCase(TestCase):
def setUp(self):
self.call = Call(sid="CAxxx",
| from_number="+15558675309",
to_number="+15556667777")
self.call.save()
def test_string_representation(self):
self.assertEqual(str(self.call),
| "{0}: from +15558675309 to "
"+15556667777".format(self.call.date_created))
|
cdss = [feature]
else:
cdss = list(genes(feature.sub_features, feature_type="CDS", sort=True))
if cdss == []:
return "None"
res = (sum([len(cds) for cds in cdss]) / 3) - 1
if floor(res) == res:
res = int(res)
return str(res)
de... | """Strand
"""
return "+" if feature.location.strand > 0 else "-"
def sd_spacing(record, feature):
"""Shine-Dalgarno spacing
"""
rbss = get_rbs_from(gene)
if len(rbss) == 0:
return "None"
else:
resp = []
for rbs in rbss:... | =True))
if len(cdss) == 0:
return "No CDS"
if rbs.location.strand > 0:
distance = min(
cdss, key=lambda x: x.location.start - rbs.location.end
)
distance_val = str(distance.location.star... |
'flavor_ref': '1',
},
'os-scheduler-hints:scheduler_hints': 'here',
}
req.body = jsonutils.dumps(body)
res = req.get_response(self.app)
self.assertEqual(400, res.status_int)
class ServersControllerCreateTest(test.TestCase):
def setUp(self):
""... | req.headers["content-type"] = "application/json"
if override_controller:
server = override_controller.create(req, body).obj['server']
else:
server = self.controller.create(req, body).obj['server']
def test_create_instance_with_scheduler_hints_disabled(self):
hints = ... | , **kwargs):
self.assertNotIn('scheduler_hints', kwargs)
# self.assertEqual(kwargs['scheduler_hints'], {})
return old_create(*args, **kwargs)
self.stubs.Set(compute_api.API, 'create', create)
self._test_create_extra(params,
override_control... |
urn generic_combine(intl_combine.mean_method(), arrays, masks=masks,
dtype=dtype, out=out,
zeros=zeros, scales=scales,
weights=weights)
def median(arrays, masks=None, dtype=None, out=None,
zeros=None, scales=None,
w... | result = sigmaclip(arrays, masks=masks,
dtype=dtype, scales=scales,
low=low, high=high)
# Substitute values <= 0 by blank
mm = result[0] | <= 0
result[0, mm] = blank
# Add values to mask
result[1:2, mm] = 0
return result
def zerocombine(arrays, masks, dtype=None, scales=None):
"""Combine zero arrays.
:param arrays: a list of arrays
:param masks: a list of mask arrays, True values are masked
:param dtype: data type of th... |
"""
Constants used across the ORM in general.
"""
# S | eparator used to split filter strings apart.
LOOKUP_S | EP = '__'
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2014 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio 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 versio... | A = (
(1, 0),
(0, 1),
)
self.run_once(X_in, A)
def test_002_t (self):
""" Switch check: N==M, flipped unit matrix """
X_in = (
(1, 2, 3, 4),
(5, 6, 7, 8),
)
A = (
| (0, 1),
(1, 0),
)
self.run_once(X_in, A)
def test_003_t (self):
""" Average """
X_in = (
(1, 1, 1, 1),
(2, 2, 2, 2),
)
A = (
(0.5, 0.5),
(0.5, 0.5),
)
self.run_once(X_in, A)
def test_004... |
import pyautogui, win32api, win32con, ctypes, autoit
from PIL import ImageOps, Image, ImageGrab
from numpy import *
import os
import time
import cv2
import rando | m
from Bot import *
def main():
bot = Bot()
autoit.win_wait(bot.title, 5)
counter = 0
poitonUse = 0
cycle = True
fullCounter = 0
while cycle:
hpstatus = bot.checkOwnHp()
print 'hp ' + str(hpstatus)
if hpstatus == 0:
autoit.c | ontrol_send(bot.title, '', '{F9}', 0)
bot.sleep(0.3,0.6)
print 'Dead'
cv2.imwrite('Dead' + str(int(time.time())) + '.png',bot.getScreen(leftCornerx,leftCornery,x2,fullY2))
cycle = False
if hpstatus == 1:
if poitonUse == 0:
autoit.contro... |
# | -*- coding: utf-8 -*-
import system_tests
class TestCvePoC(metaclass=system_tests.CaseMeta):
url = "https://github.com/Exiv2/exiv2/issues/208"
filename = "$data_path/2018-01-09-exiv2-crash-001.tiff"
commands = ["$exiv2 " + filename]
retval = [1]
stdout = [""]
stderr = [
"""$exiv2_ex... | mageType
"""]
|
import subprocess
import sys
import os
import time
from collections import namedtuple
sys.path.append(os.path.join(os.getcwd(), "src"))
from utils import settings
from utils import logger
settings.initialize('watcher')
original_plist = '/opt/TopPatch/agent/daemon/com.toppatch.agent.plist'
osx_plist = '/System/Libra... | ger.log('Agent started.')
result = True
elif 'No such process' in error_output:
logger.log('Agent not found.')
else:
logger.log('Unknown output: "%s"' % error_output)
except Exception as e:
logger.log("Could not start agent.", logger.LogLevel.Error)
... | _exception(e)
return result
def restart_agent():
try:
process = subprocess.Popen(stop_command, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
raw_output, error_output = process.communicate()
if raw_output == '' and error_output == '':
... |
# When some software has issues and we need to fix it in a
# hackish way, we put it in here. This one day will be empty.
import copy_reg
from twisted.web.client import SchemeNotSupported
from txsocksx.http import SOCKS5Agent as SOCKS5AgentOriginal
def patched_reduce_ex(self, proto):
"""
This is a hack to ov... | uce_ex.
Some background on the issue can be found here:
http://stackoverflow.com/questions/569754/how-to-tell-for-which-object-attribute-pickle
http://stacko | verflow.com/questions/2049849/why-cant-i-pickle-this-object
There was also an open bug on the pyyaml trac repo, but it got closed because
they could not reproduce.
http://pyyaml.org/ticket/190
It turned out to be easier to patch the python core library than to monkey
patch yaml.
XXX see if th... |
try:
im | port _pygeapi
except ImportError as e:
e.msg += ' (this module can be imported only from greenev)'
raise
from .evloop import event_l | oop
|
# -*- coding: ISO-8859-15 -*-
from twisted.web import client
from twisted.internet.defer import inlineCallbacks
from core.Uusipuu import UusipuuModule
import urllib, simplejson
class Module(UusipuuModule):
def startup(self | ):
self.log('google.py loaded')
@inlineCallbacks
def cmd_google(self, user, target, params):
self.log('Querying google for "%s"' % params)
data = yield client.getPage(
'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s' %
urllib.urlencode({'q': param... | ds(data)
results = json['responseData']['results']
if not results:
self.log('No results found matching "%s"' % keyword)
self.chanmsg('No results found matching "%s"' % keyword)
return
self.chanmsg('%s: %s' % \
(results[0]['titleNoFormatting'].... |
# -*- 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... | e purposes only.
# It may require modifications to work in your environment.
# To install the latest published package dependency, execute the following:
# python3 -m pip install google-cloud-private-ca
# [START privateca_v1beta1_generated_CertificateAuthorityService_UpdateCertificateAuthority_async]
from google.c... |
async def sample_update_certificate_authority():
# Create a client
client = privateca_v1beta1.CertificateAuthorityServiceAsyncClient()
# Initialize request argument(s)
certificate_authority = privateca_v1beta1.CertificateAuthority()
certificate_authority.type_ = "SUBORDINATE"
certificate_autho... |
# -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2016 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# | @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file __openerp__.py
#
##############################################################################
from openerp import models, fields
class MailMessage(models.Model):
""" Add relation to communication configuration to track generated
... | ############################################
# FIELDS #
##########################################################################
communication_config_id = fields.Many2one('partner.communication.config')
|
__author__ = 'Ralph'
from ui.app import Application
if __name__ == '__main__':
from ui.app import Example
import wx
app = wx.App()
Example(None, title='Example')
app.MainLoop()
# application = Application()
# application.run()
# node1 = Import | ARFF()
# node2 = SelectAttributes()
# node3 = SupportVectorMachine()
# node4 = SelectAttributes()
# node5 = ApplyModel()
#
# node1.get_config().set('file_name', '/Users/Ralph/datasets/imagemend/out/prepared/features_prepared.arff')
#
# node2.get_config().set('selector_type', 'subset')
... |
# node3.get_config().set('auto_detect', True)
# node3.get_config().set('performance_measure', 'accuracy')
# node3.get_config().set('n_folds', 2)
# node3.get_config().set('n_grid_folds', 2)
# node3.get_config().set('model_output_dir', '/Users/Ralph/tmp/model')
#
# node4.get_config().set('sel... |
#!/usr/bin/env py | thon
#-*- coding: utf-8 -*-
import sys, urllib2
|
def main():
if len(sys.argv) < 2:
print("Error, usage: {0} <your url>".format(sys.argv[0]))
return 1
url = sys.argv[1]
print(urllib2.urlopen('http://t34.me/api/?u=' + url).read())
return 0
if __name__ == '__main__':
main()
|
######################################################
from __future__ import absolute_import
LICENSE = """\
This file is part of pagekite.py.
Copyright 2010-2020, the Beanstalks Project ehf. and Bjarni Runar Einarsson
This program is free softwa | re: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option) any
later version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; witho... | ved a copy of the GNU Affero General Public License
along with this program. If not, see: <http://www.gnu.org/licenses/>
"""
##############################################################################
import six
import re
import time
import pagekite.logging as logging
from pagekite.compat import *
class TunnelF... |
from .allow_origin import allow_origin_tween_factory # noqa
from .api_headers import api_headers_ | tween_factory # noqa
from .basic_auth import basic_auth_tween | _factory # noqa
|
See the License for the specific language governing permissions and
# limitations under the License.
# ===============================================================================
# ============= standard library imports ========================
from itertools import groupby
import six
# ============= enthought li... | get_ranges(ls)
self.connector.rights = get_ranges(rs)
self.connector.update()
class _DiffEditor(Editor):
_no_update = False
def init(self, parent):
self.control = self._create_control(parent)
def _create_control(self, parent):
control = QDiffEdit(parent)
# QtCore... | object)
# QtCore.QObject.connect(ctrl.right,
# QtCore.SIGNAL('textChanged()'), self.update_right_object)
control.left.textChanged.connect(self.update_left_object)
control.right.textChanged.connect(self.update_right_object)
return control
def update_ed... |
# 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 ... | ttribute_map = {
'id': {'key': 'id', 'type': 'str'},
| 'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'routes': {'key': 'properties.routes', 'type': '[Route]'},
'subnets': {'key': 'properties.subnets', 'type': '... |
#!/usr/bin/env python3
import socket
HOST = '127.0.0.1' | # The server's hostname or IP address
PORT = 65432 # The port used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
s.sendall(b'Hello, world')
da | ta = s.recv(1024)
print('Received', repr(data))
|
import transform_util
from lingvo.tasks.car.waymo import waymo_ap_metric
from lingvo.tasks.car.waymo import waymo_metadata
import numpy as np
class WaymoOpenDatasetDecoder(base_decoder.BaseDecoder):
"""A decoder to use for decoding a detector model on Waymo."""
@classmethod
def Params(cls):
p = super().Par... | es_3d_mask': input_labels.bboxes_3d_mask,
'labels': input_labels.labels,
'label_ids': input_labels.label_ids,
'speed': input_labels.speed,
'acceleration': input_labels.acceleration,
# Fill the following in.
'source_ids': source_ids,
'difficulti | es': input_labels.single_frame_detection_difficulties,
'unfiltered_bboxes_3d_mask': input_labels.unfiltered_bboxes_3d_mask,
'run_segment': input_metadata.run_segment,
'run_start_offset': input_metadata.run_start_offset,
'pose': input_metadata.pose,
})
if p.draw_visualizations:
... |
WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundati... | getChangeCounter(self):
"""
Returns the current change counter.
:return: The current change counter
:rtype: int
"""
return int(self.dynapi.callAPI("X_AVM-DE_GetC | hangeCounter")["NewX_AVM-DE_GetChangeCounter"])
def wakeUp(self,mac):
"""
Sends a WakeOnLAN request to the specified Host.
:param str mac: MAC Address to wake up
:raises AssertionError: if the MAC Address is invalid, e.g. not a string
:raises ValueError: if the MAC A... |
--------------------------------------------------------
def current_state(self):
return self.lexstate
# ------------------------------------------------------------
# skip() - Skip ahead n characters
# ------------------------------------------------------------
def skip(self,n):
s... | expos # This is here in case user has updated lexpos.
lexignore = self.lexignore # This is here in case there was a state change
break
# Verify type of the token. If not in the token m | ap, raise an error
if not self.lexoptimize:
if not newtok.type in self.lextokens:
raise LexError("%s:%d: Rule '%s' returned an unknown token type '%s'" % (
func_code(func).co_filename, func_code(func).co_firstlineno,
... |
iated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following co... | hon SequenceMatcher. Install python-Levenshtein to remove this warning')
from difflib import SequenceMatcher
from . import utils
###########################
# Basic Scoring Functions #
###########################
@utils.check_for_none
@utils.check_empty_string
def ratio(s1, s2):
s1, s2 = utils.make_type_con... | atio of the most similar substring
as a number between 0 and 100."""
s1, s2 = utils.make_type_consistent(s1, s2)
if len(s1) <= len(s2):
shorter = s1
longer = s2
else:
shorter = s2
longer = s1
m = SequenceMatcher(None, shorter, longer)
blocks = m.get_matching_blo... |
estObjectCountingGuiMultiImage, cls).setupClass()
if hasattr(cls, 'SAMPLE_DATA'):
cls.using_random_data = False
else:
cls.using_random_data = True
cls.SAMPLE_DATA = []
cls.SAMPLE_DATA.append(os.path.split(__file__)[0] + '/random_data1.npy')
cl... | n up: Delete any test files we generated
removeFiles = [ TestObjectCountingGuiMultiImage.PROJECT_FILE ]
if cls.using_random_data:
| removeFiles += TestObjectCountingGuiMultiImage.SAMPLE_DATA
for f in removeFiles:
try:
os.remove(f)
except:
pass
def test_1_NewProject(self):
"""
Create a blank project, manipulate few couple settings, and save it.
"""
... |
port test_functions as funcs
from .common import Benchmark
from .lsq_problems import extract_lsq_problems
class _BenchOptimizers(Benchmark):
"""a framework for benchmarking the optimizer
Parameters
----------
function_name : string
fun : callable
der : callable
function that returns t... | for name, result_list in grouped_results.items():
newres = scipy.optimize.OptimizeResult()
newres.name = name
newres.mean_nfev = np.mean([r.nfev for r in result_list])
newres.mean_njev = np.mean([r.njev for r in result_list])
newres.mean_nhev = np.mean([r.nhev... | .mean([r.time for r in result_list])
newres.ntrials = len(result_list)
newres.nfail = len([r for r in result_list if not r.success])
try:
newres.ndim = len(result_list[0].x)
except TypeError:
newres.ndim = 1
averaged_results[nam... |
def foo(x):
pass
x | = 42
y = 4 | 2
z = 42
foo(x, y, <caret>) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2015-2015: Alignak team, see AUTHORS.txt file for contributors
#
# This file is part of Alignak.
#
# Alignak is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free So... | the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Alignak. If not, see <http://www.gnu.org/licenses/>.
#
#
# This file incorporates work covered by the foll | owing copyright and
# permission notice:
#
# Copyright (C) 2009-2014:
# Jean Gabes, naparuba@gmail.com
# Hartmut Goebel, h.goebel@goebel-consult.de
# Grégory Starck, g.starck@gmail.com
# Sebastien Coavoux, s.coavoux@free.fr
# This file is part of Shinken.
#
# Shinken is free software: you can redist... |
## This file is part of PyGaze - the open-source toolbox for eye tracking
##
## PyGaze is a Python module for easily creating gaze contingent experiments
## or other software (as well as non-gaze contingent experiments/software)
## Copyright (C) 2012-2013 Edwin S. Dalmaijer
##
## This program is free... | ame, without path
LOGFILE = LOGFILENAME[:] # .txt; adding path before logfilename is optional; logs responses (NOT eye movements, these are stored in an EDF file!)
TRIALS = 5
# DISPLAY
# used in libscreen, for the *_display functions. The values may be adjusted,
# but not the constant's names
SCREENNR = 0 # num... | IZE = (34.5, 19.7) # physical display size in cm
MOUSEVISIBLE = False # mouse visibility
BGC = (125,125,125) # backgroundcolour
FGC = (0,0,0) # foregroundcolour
FULLSCREEN = False
# SOUND
# defaults used in libsound. The values may be adjusted, but not the constants'
# names
SOUNDOSCILLATOR = 'sine' # 'sine',... |
def send_simple_message():
return requests.post(
"https://api.mailgun.net/v3/sandbox049ff464a4d54974bb0143935f9577ef.mailgun.org/messages",
auth=("api", "key-679dc79b890e700f11f001a6bf86f4a1"),
data={"from": "Mailgun Sandbox <postmaster@sandbox049ff464a | 4d54974bb0143935f9577ef.mailgun.org | >",
"to": "nick <nicorellius@gmail.com>",
"subject": "Hello nick",
"text": "Congratulations nick, you just sent an email with Mailgun! You are truly awesome! You can see a record of this email in your logs: https://mailgun.com/cp/log . You can send up to 300 emails/day from ... |
import os
from pyramid.config import Configurator
from pyramid.renderers import JSONP
from pyramid.settings import aslist
from citedby import controller
from citedby.controller import cache_region as controller_cache_region
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application... | er(request):
es = os.environ.get(
'ELASTICSEARCH_HOST',
| settings.get('elasticsearch_host', '127.0.0.1:9200')
)
es_index = os.environ.get(
'ELASTICSEARCH_INDEX',
settings.get('elasticsearch_index', 'citations')
)
return controller.controller(
aslist(es),
sniff_on_connection_fail=True,
... |
# Ridiculously simple test of the os.startfile function for Windows.
#
# empty.vbs is an empty file (except for a comment), which does
# nothing when run with cscript or wscript.
#
# A possible improvement would be to have empty.vbs d | o something that
# we can detect here, to make sure that not only the os.startfile()
# call succeeded, but also the script actually has run.
import unittest
from test import support
import os
import sys
from os i | mport path
startfile = support.get_attribute(os, 'startfile')
class TestCase(unittest.TestCase):
def test_nonexisting(self):
self.assertRaises(OSError, startfile, "nonexisting.vbs")
def test_empty(self):
# We need to make sure the child process starts in a directory
# we're not about... |
# Copyright 2014 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.
import shutil
from profile_creators import profile_generator
from profile_creators import small_profile_extender
from telemetry.page import pa | ge as page_module
from telemetry.page import shared_page_state
from telemetry import story
class Typical25ProfileSharedState(shared_page_state.SharedDesktopPageState):
"""Shared state associated wi | th a profile generated from 25 navigations.
Generates a shared profile on initialization.
"""
def __init__(self, test, finder_options, story_set):
super(Typical25ProfileSharedState, self).__init__(
test, finder_options, story_set)
generator = profile_generator.ProfileGenerator(
small_pro... |
import os
from unittest import TestCase
from click.testing import CliRunner
from regparser.commands.clear import clear
from regparser.index import entry
class CommandsClearTests(TestCase):
def setUp(self):
self.cli = CliRunner()
def test_no_errors_when_clear(self):
"""Should raise no errors... | em():
entry.Entry('aaa', 'bbb').write('ccc')
entry.Entry('bbb', 'ccc').write('ddd')
| self.assertEqual(1, len(entry.Entry("aaa")))
self.assertEqual(1, len(entry.Entry("bbb")))
self.cli.invoke(clear)
self.assertEqual(0, len(entry.Entry("aaa")))
self.assertEqual(0, len(entry.Entry("bbb")))
def test_deletes_can_be_focused(self):
"""If params a... |
from util import ap | p
import hashlib
import os
phase2_url = '/phase2-%s/' % os.environ.get('PHASE2_TOKEN')
admin_password = u'adminpass'
admin_hash = hashlib.sha1(admin_password.encode('utf-8')).hexdigest()
session_key = 'sessionkey'
admin_session_key = 'adminsessionkey'
def init_ | data(redis):
redis.set('user:test:password', hashlib.sha1(b'test').hexdigest())
redis.set('user:admin:password', admin_hash)
redis.set('user:test:1', 'Buy groceries')
redis.set('user:test:2', 'Clean the patio')
redis.set('user:test:3', 'Take over the world')
redis.rpush('items:test', 1, 2, 3)
... |
import unittest
from mock import patch, Mock
from the_ark import rhino_client
__author__ = 'chaley'
rhino_client_ojb = None
class UtilsTestCase(unittest.TestCase):
def setUp(self):
self.rhino_client_obj = rhino_client.RhinoClient('test_name',
'... | ient_obj.test_data['test_id'] = 156465465
self.rhino_client_obj.posted = True
request_json = Mock()
request_json.status_code = 201
requests_put.return_value = request_json
self.rhino_client_obj.send_test("status")
self.assertEqual(True, self.rhino_client_obj.posted)
i... | e__ == '__main__':
unittest.main()
|
import zipfile
import imghdr
from django import forms
from .models import Image, ImageBatchUpload, Album
class AlbumAdminForm(forms.ModelForm):
class Meta:
model = Album
fields = '__all__'
def clean(self):
cleaned_data = self.cleaned_data
if cleaned_data.get('authorized_u... | l_users'] = False
return cleaned_data
class ImageAdminForm(forms.Mod | elForm):
class Meta:
model = Image
fields = ('public', 'title', 'image', 'albums', 'user')
def clean_image(self):
image = self.cleaned_data['image']
if image is None:
return image
elif not imghdr.what(image):
raise forms.ValidationError(u"The fil... |
import CatalogItem
from toontown.toonbase import ToontownGlobals
from toontown.toonbase import TTLocalizer
from otp.otpbase import OTPLocalizer
from direct.interval.IntervalGlobal import *
from direct.gui.DirectGui import *
class CatalogNametagItem(CatalogItem.CatalogItem):
sequenceNumber = 0
def makeNewItem(... | npaidNameTag
else:
name = TTLocalizer.NametagFontNames[self.nametagStyle]
if TTLocalizer.NametagReverse:
name = TTLocalizer.NametagLabel + name
else:
name = name + TTLocalizer.NametagLab | el
return name
if self.nametagStyle == 0:
name = TTLocalizer.NametagPaid
elif self.nametagStyle == 1:
name = TTLocalizer.NametagAction
elif self.nametagStyle == 2:
name = TTLocalizer.NametagFrilly
def recordPurchase(self, avatar, optional):
... |
org/licenses/>.
import time
@VOLT.Command(
bundles = VOLT.AdminBundle(),
description = 'Pause the VoltDB cluster and switch it to admin mode.',
options = (
VOLT.BooleanOption('-w', '--wait', 'waiting',
'wait for all DR and Export transactions to be externally processed',... | , partition_min_host, partition_min, partition_max)
if last_table_stat_time > 1:
curr_table_stat_time = check_export(runner, export_tables_with_data, last_table_stat_time)
if last_table_stat_time == 1 or curr_table_stat_time > last_table_ | stat_time:
# have a new sample from table stat cache or there are no tables
if not export_tables_with_data and not partition_min:
runner.info('All export and DR transactions have been processed.')
return
notifyInterval -= 1
... |
#!/usr/bin/env python3
import os, sys, glob, pickle, subprocess
sys.path.insert(0, os.path.dirname(__file__))
from clang import cindex
sys.path = sys.path[1:]
def configure_libclang():
llvm_libdirs = ['/usr/lib/llvm-3.2/lib', '/usr/lib64/llvm']
try:
libdir = subprocess.check_output(['llvm-config', '... | fname = cursor.location.file.name.decode('utf-8')
if fname in files:
yield cursor
proc += list(cursor.get_children())
def newer(a, b):
try:
return os.stat(a).st_mtime > os.stat(b).st_mtime
except:
return True
def scan_libgit2_glib(cflags, files, git2di... | = {}
l = 0
if not os.getenv('SILENT'):
sys.stderr.write('\n')
i = 0
for f in files:
if not os.getenv('SILENT'):
name = os.path.basename(f)
if len(name) > l:
l = len(name)
perc = int((i / len(files)) * 100)
sys.stderr.... |
# generate | d from catkin/cmake/template/pkg.context.pc.in
CATKIN_PACKAGE_PREFIX = ""
PROJECT_PKG_CONFIG_INCLUDE_DIRS = "/home/bjornl/ros/workspaces/bjorn_ws/install/include".split(';') if "/home/bjornl/ros/workspaces/bjorn_ws/install/include" != "" else []
PROJECT_CATKIN_DEPENDS = "message_runtime".replace(';', ' ')
PKG_CONFIG_LI... | = "".split(';') if "" != "" else []
PROJECT_NAME = "rosserial_mbed"
PROJECT_SPACE_DIR = "/home/bjornl/ros/workspaces/bjorn_ws/install"
PROJECT_VERSION = "0.7.6"
|
# -*- coding: utf-8 -*-
'''
Funimation|Now Add-on
Copyright (C) 2016 Funimation|Now
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at yo... | lobals()[func.get(controlID)](landing_page, parent, child, controlID);
except Exception as inst:
logger.error(inst);
landi | ng_page.result_code = result;
return result;
def home(landing_page, parent, child, controlID):
RESULT_CODE = REST_CODE;
if child == HOME_WINDOW:
RESULT_CODE = REST_CODE;
else:
RESULT_CODE = HOME_SCREEN_CODE;
return RESULT_CODE;
def search(landing_page, parent, child, ... |
import AnimatedProp
from direct.actor import Actor
from direct.interval.IntervalGlobal import *
from toontown.effects.Splash import *
from toontown.effects.Ripples import *
import random
class FishAnimatedProp(AnimatedProp.AnimatedProp):
def __init__(self, node):
AnimatedProp.AnimatedProp.__init__(self, n... | exitRipples.setPosHprScale(-0.3 | , 0.0, 1.24, 0.0, 0.0, 0.0, 0.7, 0.7, 0.7)
self.splash = Splash(self.geom, wantParticles=0)
self.splash.setPosHprScale(-1, 0.0, 1.23, 0.0, 0.0, 0.0, 0.7, 0.7, 0.7)
randomSplash = random.choice(self.splashSfxList)
self.track = Sequence(FunctionInterval(self.randomizePosition), Func(self.n... |
"""
viscount.task.models
Task models
"""
from ..core import db
from ..utils import JSONSerializer
class TaskInputFile(JSONSerializer, db.Model):
__tablename__ = 'tasks_input_files'
id = db.Column(db.Integer, primary_key=True)
task_id = db.Column(db.Integer, db.ForeignKey('tasks.id'), nullable=False)
file_type_... |
task_id = db.Column(db.Integer, db.ForeignKey('tasks.id'), nullable=False)
file_type_id = db.Column(db.Integer, db.ForeignKey('file_types.id'), nullable=False)
name = db.Column(db.String(255), nullable=False, primary_key=True)
description = db.Column(db.Text, nullable=False)
class TaskJSONSerializer(JSONSerializ... | nput.id) for input in inputs],
'outputs': lambda outputs, _: [dict(id=output.id) for output in outputs],
'task_instances': lambda task_instances, _: [dict(id=task_instance.id) for task_instance in task_instances],
}
class Task(TaskJSONSerializer, db.Model):
__tablename__ = 'tasks'
id = db.Column(db.Integer, ... |
from __future__ import unicode_literals
from django.utils.encoding import python_2_unicode_compatible
from django.conf import settings
from django.db import models
from django.core.urlresolvers import reverse
from django.db.models.signals import pre_save
from django.utils import timezone
from django.utils.text import... | ield(auto_now = True, auto_now_add = False)
timestamp = models.DateTimeField(auto_now = False, auto_now_add = True)
objects = CareerManager()
def __unicode__(self):
return self.role
def __str__(self):
return self.role
def get_absolute_url(self):
return reverse('careers:de... | nce.title)
if new_slug is not None:
career_slug = new_slug
qs = Career.objects.filter(career_slug = career_slug).order_by("-id")
exists = qs.exists()
if exists:
new_slug = "%s-%s" %(career_slug, qs.first().id)
return create_slug(instance, slug = new_slug)
return career_slug
... |
def task_hello():
"""hello py """
def python_hello(times, text, targets):
with open(targets[0], "a") as output:
out | put.write(times * text)
return {'actions': [(python_hello, [3, "py!\n"])] | ,
'targets': ["hello.txt"],
}
|
from numpy imp | ort *
from matplotlib.pyplot import *
import scipy.constants as sc
import copy
import scipy.integrate as integ
# test sun/earth with hw5(1.989e30,5.972e24,149.6e6,0.0167,1000)
def hw5(m1, m2, a, e, tmax, tstep=0.001, tplot=0.025, method='leapfrog'):
if method != 'leapfrog' and method != 'odeint':
print("Th... | time 0
q = m1 / m2
r0 = (1-e)*a/(1+q)
v0 = (1/(1+q))*sqrt((1+e)/(1-e))*sqrt(sc.G*(m1+m2)/a)
rv = array([r0, 0, 0, v0, -q*r0, 0, 0, -q*v0])
# set up figure
figure(1)
gca().set_aspect('equal')
xlim([-2*a, 2*a])
ylim([-2*a, 2*a])
rv_list = []
if method == 'leapfrog':
... |
heme as csp
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# -- General configuratio... | ctories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_f | unction_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the P... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on | 2016-05-09 23:22
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('player', '0002_auto_20160505_0350'),
]
operations = [
migrations.RenameField(
model_name='player',
old_name='usern... | mail',
),
]
|
#!/usr/bin/env python
import sys
import textwrap
try:
import virtualenv # @UnresolvedImport
except:
from .lib import virtualenv # @Reimport
from . import snippits
__version__ = "0.9.1"
def file_search_dirs():
dirs = []
for d in virtualenv.file_search_dirs():
if "vootstrap" not in d:
... | al environment (defa | ult; deprecated)")
parser.add_option(
"--system-site-packages",
dest="system_site_packages",
action="store_true",
help="Give access to the global site-packages dir to the "
"virtual environment")
parser.add_option(
"--unzip-setuptools",
dest="unzip_... |
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
# Import sile objects
from .sile import *
from sisl._internal import set_module
from sisl import Geometry
__all__ = [... | supercell
self.write_supercell(geometry.sc)
# Write in ATOM mode
self._write('[Atoms] Angs\n')
# Write out the cell information in the co | mment field
# This contains the cell vectors in a single vector (3 + 3 + 3)
# quantities, plus the number of supercells (3 ints)
fmt_str = '{{0:2s}} {{1:4d}} {{2:4d}} {{3:{0}}} {{4:{0}}} {{5:{0}}}\n'.format(fmt)
for ia, a, _ in geometry.iter_species():
self._write(fmt_str... |
#!/usr/bin/env python
from __future__ import print_function
import boto3
import time
from botocore.exceptions import ClientError
from datetime import datetime
def get_unix_timestamp():
"""
Generate a Unix timestamp string.
"""
d = datetime.now()
t = time.mktime(d.timetuple())
return str(int... | ue']
else:
instance_tags.append(tag)
try:
# Create the AMI
image_name = instance_name + '-' + get_unix_timestamp()
i | mage = instance.create_image(
Name=image_name,
NoReboot=True,
DryRun=event['DryRun']
)
print('Started image creation: ' + image_name)
image_tags = [{'Key': 'ops:retention', 'Value': '30'}] + instance_tag... |
#!/usr/bin/env python
from __future__ import print_function
import argparse
import numpy as N
import os
import sys
def parse_args(args):
p = argparse.ArgumentPar | ser()
p.add_argument('-i', '--input-files', default=[sys.stdin], nargs="+",
type=argparse.FileType('rt'),
help='input file or empty (stdin)')
p.add_argument( | '-d', '--decorate',default=False,action='store_true'
,help='put the stat name before the value (e.g mean:1)')
g = p.add_mutually_exclusive_group()
g.add_argument('-A','--all-stats',action='store_true',default=False)
h = p.add_argument_group('stat')
h.add_argument('-a', '--mean', action='store_... |
"""
This module implements atom/bond/structure-wise descriptor calculated from
pretrained megnet model
"""
import os
from typing import Dict, Union
import numpy as np
from tensorflow.keras.models import Model
from megnet.models import GraphModel, MEGNetModel
from megnet.utils.typing import StructureOrMolecule
DEFAU... | lf._predict_structure(structure)
self._cache[s] = result
return result
def _get_features(self, structure: StructureOrM | olecule, prefix: str, level: int, index: int = None) -> np.ndarray:
name = prefix
if level is not None:
name = f"{prefix}_{level}"
if index is not None:
name += f"_{index}"
if name not in self.valid_names:
raise ValueError(f"{name} not in original meg... |
#!/usr/bin/env python
import sys
import json
import logging
from logging import warning, error, info
from math import pi, degrees
from PyQt4 import Qt, QtCore, QtGui
from connection import Connection
arrow_points = (
Qt.QPoint(-1, -4),
Qt.QPoint(1, -4),
Qt.QPoint(1, 4),
Qt.QPoint(4, 4),
Qt.QPoin... | 't joint correctly when using
# the meter units directly.
# there is a scale(0.1,0.1) further down to put things
# back to the correct size.
Lf = 16 # length of chass from middle to front axle
Lb = 23 # length of chassis from middle to back axle
Wa = 13 # half axle lengt... | cale(0.1, 0.1)
qp.drawLine(0, -Lb, 0, Lf) # main body
qp.save() # begin rear end
qp.translate(0.0, -Lb)
qp.drawLine(-Wa, 0.0, Wa, 0.0) # rear axle
qp.drawLine(-Wa,-Lw, -Wa, Lw) #left wheel
qp.drawLine(Wa, -Lw, Wa, Lw) # right wheel
qp.restore()
... |
""" Example of reasoning about the approximate node completeness. """
from tulip import *
from tulipgui import *
import tulippaths as tp
# Load graph
graphFile = '../data/514_4hops.tlp'
graph = tlp.loadGraph(graphFile)
# Compute completeness for each node label
completeness = tp.utils.g | etApproximateAnnotationCompleteness(graph)
# Tally completeness
numComplete = 0
numAlmostComplete = 0
numIncomplete = 0
for node in graph.getNodes():
currCompl | eteness = completeness[node]
if currCompleteness <= 1.0 and currCompleteness > 0.75:
numComplete += 1
elif currCompleteness <= 0.75 and currCompleteness > 0.25:
numAlmostComplete += 1
else:
graph.delNode(node)
numIncomplete += 1
print('num complete, num almost complete, num ... |
)
class RHAbstractIntCommentBase(RHTrackAbstractBase):
def _checkParams(self,params):
RHTrackAbstractBase._checkParams(self,params)
id=params.get("intCommentId","")
if id=="":
raise MaKaCError( _("the internal comment identifier hasn't been specified"))
self._comment=s... | contribFilters.BoardNumberSF.getId():contribFilters.BoardNumberSF,
contribFilters.SessionSF.getId():contribFilters.SessionSF,
contribFilters.TitleSF.getId():contribFilters.TitleSF
}
class RHContribList(RHTrackAbstractsBase):
def _checkProtection(self):
RHTrackAbstractsBase._checkP... | ce()
filterUsed=params.has_key("OK")
#sorting
self._sortingCrit=ContribSortingCrit([params.get("sortBy","number").strip()])
self._order = params.get("order","down")
#filtering
filter = {"author":params.get("authSearch","")}
ltypes = []
if not filterUsed:
... |
import logging
from functools import partial
from unittest import (
TestCase,
mock,
)
from pcs.common import file_type_codes
from pcs.common.reports import ReportItemSeverity as severity
from pcs.common.reports import codes as report_codes
from pcs.lib.env import LibraryEnvironment
from pcs_test.tools.asserti... | env.user_groups)
def test_usergroups_not_set(self):
env = LibraryEnvironment(self.mock_logger, self.mock_reporter)
self.assertEq | ual([], env.user_groups)
class GhostFileCodes(TestCase):
def setUp(self):
self.mock_logger = mock.MagicMock(logging.Logger)
self.mock_reporter = MockLibraryReportProcessor()
def _fixture_get_env(self, cib_data=None, corosync_conf_data=None):
return LibraryEnvironment(
self... |
addressLine1Union = "union(){"
for rowIndex in range(len(addressLine1Dots)):
row = addressLine1Dots[rowIndex]
for colIndex in range(len(row)):
if row[colIndex] == '1':
translateHeight = walletHeight if textDepth>0 else w... | lace('width',str(walletWidth)).replace('addressLine1Union',addressLine1Union)
addressParts.append(addressLine1Final)
# Create the second line of the address
addressLine2Union = "union(){"
for rowIndex in range(len(addressLine2Dots)):
row = addressLine2Dot... | r colIndex in range(len(row)):
if row[colIndex] == '1':
translateHeight = walletHeight if textDepth>0 else walletHeight+textDepth
addressLine2Union += "translate([colIndex,rowIndex,translateHeight]){cube([1,1,textDepth]);}".replace('colIndex',str(colIn... |
def test(options, buildout):
from subprocess import Popen, PIPE
import os
import sys
python = options['python']
if not os.path.exists(python):
raise IOError("There is no file at %s" % python)
if sys.platform == 'darwin':
output = Popen([python, "-c", "import platform; print (pla... | or platform.mac_ver(), got: %s" % (pytho | n, output))
elif sys.platform == 'linux2' and (2, 4) <= sys.version_info < (2, 5):
output = Popen([python, "-c", "import socket; print (hasattr(socket, 'ssl'))"], stdout=PIPE).communicate()[0]
if not output.startswith("True"):
raise IOError("Your python at %s doesn't have ssl support, go... |
t61.fits 1293120 2021-04-09 08:04:28
pcadf126695890N007_adat71.fits 1293120 2021-04-09 08:04:28
>>> get_archive_file_list(obsid=400, detector='acis', level=2, filetype='evt2')
<Table length=1>
Filename Filesize Timestamp
str24 int64 ... | else:
# SR services API us | es "target" to select substrings of target_name
params['target'] = target_name
# For any positional search include the radius
if 'ra' in params and 'dec' in params:
params['radius'] = radius
return params
def get_ocat_web(obsid=None, *, summary=False,
target_name=Non... |
#### NOTICE: THI | S 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 = Creature()
result.template = "object/mobile/shared_mynock.iff"
result.attribute_template_id = 9
result.stfName("monster_name","m... | MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
#!/usr/bin/env python
# Copyright NumFOCUS
#
# 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.txt
#
# Unless required by applic | able law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
import itk
itk.aut... | tputFileName> [Extension]")
sys.exit(1)
inputFileName = sys.argv[1]
outputFileName = sys.argv[2]
if len(sys.argv) > 3:
extension = sys.argv[3]
else:
extension = ".png"
fileNameFormat = outputFileName + "-%d" + extension
Dimension = 3
PixelType = itk.UC
InputImageType = itk.Image[PixelType, Dimension]
R... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2018-03-21 13:53
from __future__ import unicode_literals
from django.db import mi | grations
class Migration(migrations.Migration):
| dependencies = [
('erudit', '0086_auto_20180321_0717'),
]
operations = [
migrations.RemoveField(
model_name='articleabstract',
name='article',
),
migrations.DeleteModel(
name='ArticleAbstract',
),
]
|
{
'name': 'View Editor',
'category': 'Hidden',
'description': """
OpenE | RP Web to edit views.
==========================
""",
'version': '2.0',
'depends':['web'],
'data' : [
'views/web_view_editor.xml',
],
'qweb': ['static/src/x | ml/view_editor.xml'],
'auto_install': True,
}
|
gh=None, get_smpar=False):
"""Load the initial values for Wilson coefficients from a
wcxf.WC instance.
Parameters:
- `scale_high`: since Wilson coefficients are dimensionless in
smeftrunner but not in WCxf, the high scale in GeV has to be provided.
If this parameter... | string in WCxf format.
Note that Standard Model parameters have to be provided separately
and are assumed to be in the weak basis used for the Warsaw basis as
defined in WCxf, i.e. in the basis where the down-type and charged
lepton mass matrices are diagonal."""
import wcxf
... | =None, fmt='lha', skip_redundant=True):
"""Return a string representation of the parameters and Wilson
coefficients `C_out` in DSixTools output format. If `stream` is
specified, export it to a file. `fmt` defaults to `lha` (the SLHA-like
DSixTools format), but can also be `json` or `yaml... |
t_queue()
self.SetBackgroundColour("WHITE")
self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))
# Mouse buttons and motion
wx.EVT_LEFT_DOWN(self, self.OnLeftDown)
wx.EVT_LEFT_UP(self, self.OnLeftUp)
wx.EVT_MOTION(self, self.OnMotion)
wx.EVT_PAINT(self, self.OnP... | that contains the point."
for n in self.node_dict.itervalues():
if n.HitTest(point):
return n
| return None
def OnLeftDown(self, evt):
node = self.FindNode(evt.GetPosition())
if node:
self.dragNode = node
self.dragStartPos = evt.GetPosition()
def OnLeftUp(self, evt):
if not self.dragImage or not self.dragNode:
self.dragImage = None
... |
from typing import Any
from typing import List
from typing import Optional
from typing import Union
import bpy
import compas_blender
from compas.artists import PrimitiveArtist
from compas.geometry import Line
from compas.colors import Color
from compas_blender.artists import BlenderArtist
class LineArtist(BlenderAr... | .. code-block:: python
from compas.geometry import Line
from compas_blender.artists import LineArtist
line = Line([0, 0, 0], [1, 1, 1])
artist = LineArtist(line)
artist.draw()
Or, use the artist through the plugin mechanism.
.. code-block:: python
from compa... | artist.draw()
"""
def __init__(self,
line: Line,
collection: Optional[Union[str, bpy.types.Collection]] = None,
**kwargs: Any
):
super().__init__(primitive=line, collection=collection or line.name, **kwargs)
def draw(self... |
n = int(input())
grid = [[int(c) for c in input()] for i in range (0, n)]
cavities = []
for i in range(0, n):
if i > 0 and i < n - 1:
for j in range(0, n):
if j > 0 and j < n - 1:
v = grid[i][j]
if grid[i - 1][j] | < v and grid[i + 1][j] < v and grid[i][j - 1] < v and grid[i][j + 1] < v:
cavities.append((i, j))
for i, j in cavities:
grid[i][j] = 'X'
print('\n'.join(''.join(str(i) for i in row) for row in gr | id))
|
import tkinter
tk = tkinter.Tk()
tk.title("Bounce")
tk.resizable(0, 0)
# Keep the window on the top
tk.wm_attributes("-topmost", 1)
canvas = tkinter.Canvas(tk, width=500, height=400)
# Remove border. Apparently no effect o | n Linux, but good on Mac
canvas.configure(bd=0)
# Make the 0 horizontal and vertical line apparent
canvas.configure(highlightthickness=0)
canvas.pack()
ball = canvas.create_oval(10, 10, 25, 25, fill='red')
def handle_timer_event():
canvas.move(ball, 10, 0)
tk.after(100, handle_timer | _event)
handle_timer_event()
tk.mainloop()
|
hat on windows this DLL is automatically provided for you
discord.opus.load_opus('opus')
class VoiceEntry:
def __init__(self, message, player):
self.requester = message.author
self.channel = message.channel
self.player = player
def __str__(self):
fmt = '*{0.title}* uploaded... | er)
state.voice = voice
def __unload(self):
for state in self.voice_states.values():
try:
state.audio_player.cancel()
| if state.voice:
self.bot.loop.create_task(state.voice.disconnect())
except:
pass
@commands.command(pass_context=True, no_pm=True)
async def join(self, ctx, *, channel : discord.Channel):
"""Joins a voice channel."""
try:
await self.cr... |
impo | rt csv
import os
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse_lazy
from django.utils.decorators import method_decorator
from django.db import models
from converter.exceptions import UploadException
from .models import SystemSource, R | eference, ReferenceKeyValue
from django.db import transaction
class TimeStampedModel(models.Model):
"""
An abstract base class model that provides self-
. fields.
updating ``created`` and ``modified``
"""
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTi... |
# -*- coding: utf-8 -*-
# Copyright 2020 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... | he following:
# python3 -m pip install google-cloud-datacatalog
# [START datacatalog_generated_datacatalog_v1_PolicyTagManagerSerialization_ImportTaxonomies_sync]
from google.cloud import datacatalog_v1
def sample_import_taxonomies():
# Create a client
client = datacatalog_v1.PolicyTagManagerSerialization... | atalog_v1.ImportTaxonomiesRequest(
inline_source=inline_source,
parent="parent_value",
)
# Make the request
response = client.import_taxonomies(request=request)
# Handle the response
print(response)
# [END datacatalog_generated_datacatalog_v1_PolicyTagManagerSerialization_ImportTa... |
import multiprocessing
import Library.interfaz
import Library.config
import handler
import server
try:
config = Library.config.read()
except:
import sys
print("FAILED TO OPEN CONFIG FILE, EXITING")
sys.exit()
man = multiprocessing.Manager()
adios = man.Value(bool, False)
interfaz = Library.interfaz.Int... | alla("INIT", prompt=False)
input("")
key_bits = int(config["key_length"])
hand.pantalla("GENERATING_KEY", args=(key_bits,), prompt=False)
server = server.Server(adios, hand, Library.Encriptacion.genera(key_bits), ip=config["host"], port=int(config["port"] | ))
g = multiprocessing.Process(target=server.listen)
p = multiprocessing.Process(target=server.server_handler)
p2 = multiprocessing.Process(target=hand.listen, args=(server, ))
p.start()
g.start()
hand.listen(server)
adios.value = True
p.join()
g.join()
server.handler.exit()
|
# -*- coding: utf-8 -*-
#
# Viper documentation build configuration file, created by
# sphinx-quickstart on Mon May 5 18:24:15 2014.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All c... | he language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to | some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = []
# The reST default role (used ... |
# coding: utf-8
"""
EVE Swagger Interface
An OpenAPI for EVE Online
OpenAPI spec version: 0.4.6
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
class GetOpportunitiesTasksTaskIdOk(object):
"""
NOTE: T... | be `None`")
self._name = name
@property
def notification(self):
"""
Gets the notification of this GetOpportunitiesTasksTaskIdOk.
notification string
:return: The notification of this GetOpportunitiesTasksTaskIdOk.
:rtype: str
"""
return self._n... | ksTaskIdOk.
notification string
:param notification: The notification of this GetOpportunitiesTasksTaskIdOk.
:type: str
"""
if notification is None:
raise ValueError("Invalid value for `notification`, must not be `None`")
self._notification = notification
... |
# -*- coding: utf-8 -*-
import requests
import json
misperrors = {'error': 'Error'}
mispattributes = {'input': ['md5', 'sha1', 'sha256', 'domain', 'url', 'email-src', 'ip-dst|port', 'ip-src|port'], 'output': ['text']}
moduleinfo = {'version': '0.1', 'author': 'Corsin Camichel', 'description': 'Module to search for an ... | ret_val = ""
for | input_type in mispattributes['input']:
if input_type in request:
to_query = request[input_type]
break
else:
misperrors['error'] = "Unsupported attributes type:"
return misperrors
data = {"query": "search_ioc", "search_term": f"{to_query}"}
response = request... |
# -*- coding: utf-8 -*-
from py3Des.pyDes import triple_des, ECB, PAD_PKCS5
class TripleDES:
__triple_des = None
@staticmethod
def init():
TripleDES.__triple_des | = triple_des('1234567812345678',
mode=ECB,
IV = '\0\0\0\0\0\0\0\0',
pad=None,
padmode = PAD_PKCS5)
@staticmethod
def encrypt(data):
... | ES.__triple_des.encrypt(data)
@staticmethod
def decrypt(data):
return TripleDES.__triple_des.decrypt(data) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.