prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
import json
from django.db import models
from django.conf import settings
from dj | ango.utils.six import with_metaclass, text_type
from django.utils.translation import ugettext_lazy as _
from . import SirTrevorContent
from .forms import SirTrevorFormField
class SirTrevorField(with_metaclass(models.SubfieldBase, models.Field)):
description = _("TODO")
d | ef get_internal_type(self):
return 'TextField'
def formfield(self, **kwargs):
defaults = {
'form_class': SirTrevorFormField
}
defaults.update(kwargs)
return super(SirTrevorField, self).formfield(**defaults)
def to_python(self, value):
return SirTrevo... |
import sys
from resources.datatables impor | t WeaponType
def setup(core, object):
object.setStfFilename('static_item_n')
object.setStfName('weapon_pistol_trader_roadmap_01_02')
object.setDetailFilename('static_item_d')
object.setDetailName('weapon_pistol_trader_roadmap_01_02')
object.setStringAttribute('class_required', 'Tra | der')
object.setIntAttribute('required_combat_level', 62)
object.setAttackSpeed(0.4);
object.setMaxRange(35);
object.setDamageType("energy");
object.setMinDamage(250);
object.setMaxDamage(500);
object.setWeaponType(WeaponType.Pistol);
return |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import warnings
warnings.warn("the ``irsa_dust`` module has been moved to "
"astroquery.ipac.irsa.irsa_dust, "
| "please update your imports.", DeprecationWarn | ing, stacklevel=2)
from astroquery.ipac.irsa.irsa_dust import *
|
.r = Report()
self.r['ExecutablePath'] = '/usr/bin/napoleon-solod'
self.r['Package'] = 'libnapoleon-solo1 1.2-1'
self.r['Signal'] = '11'
self.r['StacktraceTop'] = """foo_bar (x=2) at crash.c:28
d01 (x=3) at crash.c:29
raise () from /lib/libpthread.so.0
<signal handler called>
__frob (x=4... | =why@entry=0x7f96e0df8b1c "internal error") at . | ./lib/util/fault.c:162
No locals.
#4 0x00007f96e0dece76 in fault_report (sig=<optimized out>) at ../lib/util/fault.c:77
counter = 1
#5 sig_fault (sig=<optimized out>) at ../lib/util/fault.c:88
No locals.
#6 <signal handler called>
No locals.
#7 0x00007f96b9bae711 in sarray_get_safe (indx=<optimized ... |
self.assertEqual(self.lbm.ensure_vxlan(seg_id),
"vxlan-" + seg_id)
add_vxlan_fn.assert_called_with("vxlan-" + seg_id, seg_id,
group="224.0.0.1",
dev=self.lbm.local_int)
... | self.lbm.ensure_physical_in_bridge("123", p_const.TYPE_VXLAN,
"physnet1", "1")
)
self.assertTrue(vlbr_fn.called)
def test_add_tap_interface(self):
with m | ock.patch.object(ip_lib, "device_exists") as de_fn:
de_fn.return_value = False
self.assertFalse(
self.lbm.add_tap_interface("123", p_const.TYPE_VLAN,
"physnet1", "1", "tap1")
)
de_fn.return_value = True
... |
import sys
import logging
import time
import requests
from biokbase.AbstractHandle.Client import AbstractHandle
def getStderrLogger(name, level=logging.INFO):
logger = logging.getLogger(name)
logger.setLevel(level)
# send messages to sys.stderr
streamHandler = logging.StreamHandler(sys.__stderr... | : sid,
"type" : "shock",
"url" : shock_url,
| "file_name": info["file"]["name"],
"remote_md5": info["file"]["md5"]})
except:
try:
handle_id = hs.ids_to_handles([sid])[0]["hid"]
single_handle = hs.hids_to_handles([handle_id])
... |
#!/usr/bin/env python
import fileinput
import re
import sys
refs = {}
complete_file = ""
for line in open(sys.argv[1], 'r'):
complete_file += line
for m in re.findall('\[\[(.+)\]\]\n=+ ([^\n]+)', complete_file):
ref, title = m
refs["<<" + ref | + ">>"] = "<<" + ref + ", " + title + ">>"
def translate(m | atch):
try:
return refs[match.group(0)]
except KeyError:
return ""
rc = re.compile('|'.join(map(re.escape, sorted(refs, reverse=True))))
for line in open(sys.argv[1], 'r'):
print rc.sub(translate, line),
|
'''
import csv
from collections import Counter
counts = Counter()
with open ('zoo.csv') as fin:
cin = csv.reader(fin)
for num, row in enumerate(cin):
if num > 0:
counts[row[0]] += int (row[-1])
for animal, hush in counts.items():
print("%10s %10s" % (animal, hush))
'''
... | r = shapefile.Reader(name)
mleft, mbottom, mright, mtop = r.bbox
# map units
mwidth = mright - mleft
mh | eight = mtop - mbottom
# scale map units to image units
hscale = iwidth/mwidth
vscale = iheight/mheight
img = Image.new("RGB", (iwidth, iheight), "white")
draw = ImageDraw(img)
for shape in r.shapes():
pixels = [
(int(iwidth - ((mright - x) * hscale)), int((mtop - y) * vscale... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from holmes.validators.base import Validator
from holmes.utils import _
class ImageAltValidator(Validator):
@classmethod
def get_without_alt_parsed_value(cls, value):
result = []
for src, name in value:
data = '<a href="%s" target="_blank"... | images)s.'),
'value_parser': cls.get_alt_too_big_parsed_value,
'category': _('SEO'),
'ge | neric_description': _(
'Images with alt text too long are not good to SEO. '
'This maximum value are configurable '
'by Holmes configuration.'
),
'unit': 'number'
}
}
@classmethod
def get_default_vio... |
# 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 may ... | core.pipeline.transport import AsyncHttpResponse, HttpRequest
from azure.mgmt.core.exceptions import ARMErrorForma | t
from ... import models as _models
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class NetworkInterfaceLoadBalancersOperations:
"""NetworkInterfaceLoadBalancersOperations async operations.
You should not instantiate this class dire... |
# -*- coding: utf-8 -*-
# this default value is just for testing in a fake.
# pylint: disable=dangerous-default-value
"""Fake Module containing helper functions for the SQLite plugin"""
from plasoscaffolder.bll.services import base_sqlite_plugin_helper
from plasoscaffolder.bll.services import base_sqlite_plugin_path_he... | rting with the initial (against
loops while testing)"""
if self.change_valid_name:
self.valid_name = not self.valid_name
return not self.valid_name
else:
return self.valid_name
def IsValidRowName(self, row_name: str) -> bool:
"""will return true false true ... starting with the init... | .change_valid_row_name:
self.is_valid_row_name = not self.is_valid_row_name
return not self.is_valid_row_name
else:
return self.is_valid_row_name
return
def IsValidCommaSeparatedString(self, text: str) -> bool:
"""will return true false true ... starting with the initial (against
l... |
#!/usr/bin/env python3
#* This file is part of the MOOSE framework
#* https://www.mooseframework.org
#*
#* All rights reserved, see COPYRIGHT for full restrictions
#* https://github.com/idaholab/moose/blob/master/COPYRIGHT
#*
#* Licensed under LGPL 2.1, please see LICENSE for details
#* https://www.gnu.org/licenses/lgp... | , escape=False)
self.assertLatexString(tex(0)(0), 'int x = 0;', escape=False)
def testLineBreak(self):
text = r'Break\\ this' |
ast = self.tokenize(text)
self.assertToken(ast(0), 'Paragraph', size=3)
self.assertToken(ast(0)(0), 'Word', content='Break')
self.assertToken(ast(0)(1), 'LineBreak')
self.assertToken(ast(0)(2), 'Word', content='this')
text = r'''Break\\
this'''
ast = self.tokeni... |
"""Fi | xer that changes raw_input(...) into input(...)."""
# Author: Andre Roberge
# Local imports
from .. import fixer_base
from ..fixer_util import Name
class FixRawInput(fixer_base.BaseFix):
BM_compatible = True
PATTERN = """
power< name='raw_input' trailer< '(' [any] ')' > any* >
... | name = results["name"]
name.replace(Name("input", prefix=name.prefix))
|
#!/usr/bin/env python3
""" 2018 AOC Day 09 """
import argparse
import typing
import unittest
class Node(object):
''' Class representing node in cyclic linked list '''
def __init__(self, prev: 'Node', next: 'Node', value: int):
''' Create a node with explicit parameters '''
self._prev = prev
... | next
def remove(self) -> 'Node':
''' Remove current Node and return the following Node '''
self._prev._next = self._next
self._next._prev = self._prev
return self._next
def value(self) -> int:
''' Get value '''
return self._value
def chain_values(self):
... | values.append(current.value())
current = current.forward()
return values
def part1(nplayers: int, highest_marble: int) -> int:
""" Solve part 1 """
current = Node.default()
player = 0
scores = {p: 0 for p in range(nplayers)}
for idx in range(1, highest_marble + 1):
... |
# -----------------------------------------------------------------------------
# Copyright (c) 2014--, The Qiita Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... | fps['raw_forward_seqs'],
| rs, qiime_map, out_dir,
parameters)
# Step 3 executing Sortmerna
len_cmd = len(commands)
msg = "Step 3 of 4: Executing ribosomal filtering (%d/{0})".format(len_cmd)
success, msg = _run_commands(qclient, job_id,
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright 2018-2022 F4PGA Authors
#
# 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
#
# Unl... | continue
if group not in fr | eqs:
freqs[group] = dict()
freqs[group]['actual'] = freq
freqs[group]['requested'] = requested_freq
freqs[group]['met'] = freq >= requested_freq
freqs[group]['{}_violation'.format(path_type.lower())
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2007-2013 by Erwin Marsi and TST-Centrale
#
# This file is part of the DAESO Framework.
#
# The DAESO Framework 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 Softwa... | data_files,
platforms = "POSIX, Mac OS X, MS Windows",
keywords = [
"TiMBL"],
classifiers = [
"Development | Status :: 4 - Beta",
"Intended Audience :: Science/Research",
"License :: OSI Approved :: GNU Public License (GPL)",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Topic :: Scientific/Engineering :: Artificial Intelligence",
"Natural Language :: ... |
# 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 ... | ated.
# --------------------------------------------------------------------------
from .operations import Operations
from .components_operations import | ComponentsOperations
from .web_tests_operations import WebTestsOperations
from .export_configurations_operations import ExportConfigurationsOperations
from .proactive_detection_configurations_operations import ProactiveDetectionConfigurationsOperations
from .component_current_billing_features_operations import Componen... |
from extract_feature_lib import *
from sys import argv
from dga_model_eval import *
from __init__ import *
def clear_cache(index, cache):
print "clear cache", index
for tmp in cache:
client[db_name][coll_name_list[index]+"_matrix"].insert(cache[tmp])
def extract_domain_feature(index):
#cursor = ... | ip_count = len(row["ITEMS"])
| min_ttl = min(row["TTLS"])
max_ttl = max(row["TTLS"])
lifetime = int(row["LAST_SEEN"] - row["FIRST_SEEN"])/(60*60*24)
p16_entropy = ip_diversity(row["ITEMS"])
if index == 2 and (ip_count < 2 or min_ttl > 20000 or p16_entropy < 0.08):
continue
gro = growth(row["_id"]... |
# -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2011 OpenERP Italian Community (<http://www.openerp-italia.org>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Gener... | Y 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/>.
#
########################################################################... | ntext):
super(Parser, self).__init__(cr, uid, name, context)
self.localcontext.update({
'time': time,
})
|
# Copyright (c) 2016 Lee Cannon
# Licensed under the MIT License, see included LICENSE File
import click
import os
import re
from datetime import datetime
def _is_file_modnet(file_name: str) -> bool:
"""Returns True if the filename contains Modnet.
:param file_name: The filename to check.
:type file_nam... | s invalid')
exit()
if month_number < 1 or month_number > 12:
click.echo('The month entered is invalid')
exit()
try:
year = int(year)
except ValueError:
click.echo('The year entered is invalid')
exit()
if year < 201 | 5:
click.echo('No data from before 2015 is present')
exit()
raise NotImplementedError
|
from testmodule import *
import sys
class TestWrites(TestRunner):
def __init__(self):
super().__init__()
def mthd(self):
import pysharkbite
securityOps = super().getSecurityOperations()
securityOps.create_user("testUser","password")
## validate that we DON'T see the permissions
assert( Fals... | ption:
print("caught | expected exception")
pass
runner = TestWrites()
runner.mthd() |
#!/us | r/bin/env python
# encoding: utf-8
def run(whatweb, pluginname):
whatweb.recog_from_header(plu | ginname, "X-Cache")
|
# -*- coding: UTF-8 -*-
#######################################################################
# ----------------------------------------------------------------------------
# "THE BEER-WARE LICENSE" (Revision 42):
# @tantrumdev wrote this file. As long as you retain this notice you
# can do whatever you want wit... | , episode):
try:
urls = []
lst = ['1080p','720p','bluray-2','bluray']
clean_season = season if len(season) >= 2 else '0' + season
clean_episode = episode if len(episode) >= 2 else '0' + episode
for i in lst:
url = urlparse... | d(url)
url = urlparse.urljoin(self.base_link, self.movies_search_path % (imdb))
url = client.request(url, output='geturl')
if '-1080p' not in url and '-720p' not in url and '-bluray' not in url:
r = client.request(url)
if r: urls.append(url)
... |
#
# Copyright (C) 2013-2014 Emerson Max de Medeiros Silva
#
# This file is part of ippl.
#
# ippl is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any late... | hape()
# IV - Lines
| l = Line(Point(0, 0), Point(50, 25))
s.outer_loop.append(l)
l = Line(Point(50, 25), Point(0, 0))
l.move(0, 30)
s.outer_loop.append(l)
l = Line(Point(0, 25), Point(50, 0))
l.move(55, 0)
s.outer_loop.append(l)
l = Line(Point(50, 0), Point(0, 25))
l.move(55, 30)
s.outer_loop.append... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Linter to verify that all flags reported by GHC's --show-options mode
are documented in the user's guide.
"""
import sys
import subprocess
from typing import Set
from pathlib import Path
# A list of known-undocumented flags. This should be considered to be a to-do
# ... | for flag in ghc_output.split('\n')
if not expected_undocumented(flag)
if flag != ''}
def main() -> None:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--ghc', type=argparse.FileType('r'),
help='path of GHC executable')
pars... | ype=argparse.FileType('r'),
help='path of ghc-flags.txt output from Sphinx')
args = parser.parse_args()
doc_flags = read_documented_flags(args.doc_flags)
ghc_flags = read_ghc_flags(args.ghc.name)
failed = False
undocumented = ghc_flags - doc_flags
if len(undocumented) ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
=========================================================================
Program: Visualization Toolkit
Module: TestNamedColorsIntegration.py
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or ... | surfaceActor.GetProperty().SetSpecularPower(50)
# Create the RenderWindow, Renderer and both Actors
#
ren = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren)
# Add the actors to the renderer, set the background | and size
#
ren.AddActor(surfaceActor)
ren.SetBackground(1, 1, 1)
renWin.SetSize(300, 300)
ren.GetActiveCamera().SetFocalPoint(0, 0, 0)
ren.GetActiveCamera().SetPosition(1, 0, 0)
ren.GetActiveCamera().SetViewUp(0, 0, 1)
ren.ResetCamera()
re... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.9 on 2016-09-01 11:41
from __future__ import unicode_literals
from django.db import migrations, models |
class Migration(migrations.Migration):
dependencies = [
('profiles', '0006_add_show_security_question_field'),
]
operations = [
migrations.AddField(
model_name='userprofilessettings',
name='num_security_questions',
| field=models.PositiveSmallIntegerField(default=3, verbose_name='Number of security questions asked for password recovery'),
),
migrations.AddField(
model_name='userprofilessettings',
name='password_recovery_retries',
field=models.PositiveSmallIntegerField(... |
from flas | k import render_template, redirect, url_for, request
from flask.views import MethodView
from nastradini import mongo, utils
from positionform import PositionFo | rm
class Position(MethodView):
methods = ['GET', 'POST']
def get(self):
form = PositionForm()
return render_template('position.html', form=form)
def post(self):
# First, let's get the doc id.
doc_id = utils.get_doc_id()
# Create position info object.
form... |
#!/usr/bin/env python
# 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.
"""Given the output of -t commands from a ninja build for a gyp and GN generated
build, report on differences between the command line... | x | not in dash_f and \
x not in warnings and \
x not in cc_file]
# Filter for libFindBadConstructs.so having a relative path in one and
# absolute path in the other.
others_filtered = []
for x in others:
if x.startswit... |
from sender import *
if __na | me__ == '__main__':
connection = Connection().initialize()
connection.send('Default exchange message!')
connection. | destroy()
|
parse import urlparse
from wal_e import log_help
from wal_e.pipeline import get_download_pipeline
from wal_e.piper import PIPE
from wal_e.retries import retry, retry_with_count
assert calling_format
logger = log_help.WalELogger(__name__)
_Key = collections.namedtuple('_Key', ['size'])
WABS_CHUNK_SIZE = 4 * 1024 * 10... | part = conn.get_blob(url_tup.netloc,
url_tup.path,
x_ms_range=ms_range)
except EnvironmentError as e:
if e.errno in (errno.EBUSY, errno.ECONNRESET):
logger.warning(
... | traceback.format_exception(*sys.exc_info()))),
hint="")
gevent.sleep(30)
else:
raise
else:
break
length = len(part)
ret_size += length
data += part
if length > ... |
from django.urls import path
from . import dashboard_views
app_name = 'exam'
urlpatterns = [
path('assignment/new/', dashboard_views.MakeAssignmentVi | ew.as_view(),
name='assignment_new'),
path('assi | gnment/success/',
dashboard_views.MakeAssignmentSuccess.as_view(),
name='assignment_success'),
path('assignment/<int:assignment_id>/name_list/',
dashboard_views.AssignmentNameListView.as_view(),
name='assignment_name_list'),
]
|
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: pogoprotos/networking/requests/messages/release_pokemon_message.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _... | easePokemonMessage.pokemon_ids', index=1,
number=2, type=6, cpp_type=4, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_t | ypes=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=114,
serialized_end=178,
)
DESCRIPTOR.message_types_by_name['ReleasePokemonMessage'] = _RELEASEPOKEMONMESSAGE
ReleasePokemonMessage = _reflection.GeneratedProtocolMessageType('ReleasePokem... |
import os
import sys
import textwrap
from collections import OrderedDict
from argparse import ArgumentParser, RawDescriptionHelpFormatter
from faice.tool | s.run.__main__ import main as run_main
from faice.tools.run.__main__ import DESCRIPTION as RUN_DESCRIPTION
from faice.tools.vagrant.__main | __ import main as vagrant_main
from faice.tools.vagrant.__main__ import DESCRIPTION as VAGRANT_DESCRIPTION
VERSION = '1.2'
TOOLS = OrderedDict([
('run', run_main),
('vagrant', vagrant_main)
])
def main():
description = [
'FAICE Copyright (C) 2017 Christoph Jansen',
'',
'This p... |
from django.contrib.gis.db import models
# Create your models here.
class GeoWaterUse(models.Model):
id = models.AutoField(primary_key=True)
geometry = models.PointField()
api = models.CharField(max_length=20, null=False)
well_name = models.CharField(max_length=100, null=True)
frac_date = models.Da... | ):
id = models.AutoField(primary_key=True)
geometry = models.PointField()
api = models.CharField(max_length=20, null=False)
well_name = models.CharField(max_length=100, null=True)
latitude = models.DecimalField(max_digits=20, decimal_places=6 | )
longitude = models.DecimalField(max_digits=20, decimal_places=6)
volume_date = models.DateField(auto_now=False, auto_now_add=False)
h2o_volume = models.DecimalField(max_digits=10, decimal_places=2)
days_on = models.PositiveIntegerField()
is_prediction = models.BooleanField()
objects = models.G... |
# 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... | w])
qidentity = Matrix(4,1,[S.One,S.Zero,S.Zero,S.Zero])
qfinal = Matrix(4,1,[q0[0]*q1[0] - q0[1]*q1[1] - q0[2]*q1[2] - q0[3]*q1[3],
q0[0]*q1[1] + q0[1]*q1[0] + q0[2]*q1[3] - q0[3]*q1[2],
q0[0]*q1[2] + q0[2]*q1[0] + | q0[3]*q1[1] - q0[1]*q1[3],
q0[0]*q1[3] + q0[3]*q1[0] + q0[1]*q1[2] - q0[2]*q1[1]])
qfinaldtheta = Matrix(4,1,[q0dtheta[0]*q1[0] - q0dtheta[1]*q1[1] - q0dtheta[2]*q1[2] - q0dtheta[3]*q1[3],
q0dtheta[0]*q1[1] + q0dtheta[1]*q1[0] + q0dtheta[2]*q1[3] - q0dtheta[3]*q1[2... |
# -*- coding: utf-8 -*-
#
# codimension - graphics python two-way code editor and analyzer
# Copyright (C) 2010-2017 Sergey Satskiy <sergey.satskiy@gmail.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 Softw... | not be detected
# - replaces ascii to be on | the safe side
DEFAULT_ENCODING = 'utf-8'
# File encoding used for various settings and project files
SETTINGS_ENCODING = 'utf-8'
# Directory to store Codimension settings and projects
CONFIG_DIR = '.codimension3'
|
q1 | _start = 0
q1_end = 1
N_q1 = 128
q2_start = 0
q2_end = 1
N_q2 = 3
p1_start = -4
p1_end = 4
N_p1 = 4
p2_start = -0.5
p2_end = 0.5
N_p2 = 1
p3_start = -0.5
p3_end = 0.5
N_p3 = 1
N_ghost = 3 | |
from ..provider.constants import Provider, string_to_provider
from ..services.base import Service
from .context import DisconnectOnException
from .errors import (
AlreadyConnectedException,
ClusterError,
MultipleClustersConnectionError,
NotConnectedError,
PleaseDisconnectError,
)
class ClusterService(Servic... | rent_cluster_name)
except MultipleClustersConnectionError:
if not disconnect_all:
raise
| for cname in self.connected_clusters():
try:
self.services.cluster_metadata_service.ensure_metadata_deleted(cluster_name=cname)
self.services.kubernetes_service.ensure_config_deleted(cluster_name=cname)
self.services.logging_service.warning(f'Successfully disconnected from {cname}')
... |
import numpy as np
from scipy.integrate import odeint
from scipy.integrate import ode
import matplotlib.pylab as plt
import csv
import time
endpoint = 1000000000; # integration range
dx = 10.0; # step size
lam0 = 0.845258; # in unit of omegam, omegam = 3.66619*10^-17
dellam = np.array([0.00003588645221954444, 0.06486... | bsave[flagsave])
flagsave = | flagsave + 1
flag = flag + 1
print "CONGRATS"
# # ploting using probsave array inside file
# plt.figure(figsize=(18,13))
# plt.plot(probsave[:,0], probsave[:,1],'-')
# plt.title("Probabilities",fontsize=20)
# plt.xlabel("$\hat x$",fontsize=20)
# plt.ylabel("Probability",fontsize=20)
# plt.show()
# # Tem... |
#!/usr/bin/env python
# Usage parse_shear sequences.fna a2t.txt emb_output.b6
import sys
import csv
from collections import Counter, defaultdict
sequences = sys.argv[1]
accession2taxonomy = sys.argv[2]
alignment = sys.argv[3]
with open(accession2taxonomy) as inf:
next(inf)
csv_inf = csv.reader(inf... | counts_dict[species].update([tax])
print("Loaded counts_dict.")
with ope | n("sheared_bayes.txt", "w") as outf:
for i, species in enumerate(counts_dict.keys()):
row = [0] * 10
row[-1] = reads_counter[species]
row[0] = species
counts = counts_dict[species]
if i % 10000 == 0:
print("Processed %d records" % i)
print(coun... |
n_mod
self._result_queue = result_queue
self._startworkingflag_ = True
self._task_queue = Queue(1)
self._count_lock = Lock()
#----------------------------------------------------------------------
def get_result_queue(self):
""""""
return self._r... | ""
try:
self._task_queue.put_nowait(tuple([function, vargs, kwargs]))
return True
except Full:
#format_exc()
return False
#----------------------------------------------------------------------
def run(self):
""""""
whil... | _task = self._task_queue.get(timeout=3)
result = {}
result['from'] = self.name
result['state'] = False
result['result'] = None
result['current_task'] = _task.__str__()
result['exception'] = tuple()
tr... |
import spade
import time
class MyAgent(spade.Agent.Agent):
class ReceiveBehav(spade.Behaviour.Behaviour):
"""This behaviour will receive all kind of messages"""
def _process(self):
self.msg = None
# Blocking receive for 10 seconds
self.msg = self._receive(True... | ssage!"
else:
print "I waited but got no message"
def _setup(self):
print "MyAgent starting . . ."
# Add the "ReceiveBehav" as the default behaviour
rb = | self.ReceiveBehav()
self.setDefaultBehaviour(rb)
if __name__ == "__main__":
a = MyAgent("agent2@127.0.0.1", "secret")
a.start()
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.15 on 2018-09-20 15:04
from __fu | ture__ import unicode_literals
from django.db import migrations
from django.db import models
class Migration(migrations.Migration):
dependencies = [
('meinberlin_plans', '0017_rename_cost_field'),
]
operations = [
migrations.AlterField(
model_name='plan',
name='p... | location'),
),
]
|
from unittest.mock import Mock
from django.db.models import QuerySet
from datagrowth.resources import HttpResource
from core.tests.mocks.requests import MockRequests
MockErrorQuerySet = Mock(QuerySet)
MockErrorQuerySet.count = Mock(return_value=0)
class HttpResourceMock(HttpResource):
URI_TEMPLATE = "http://... | rce mock keyword arguments",
" | type": "object",
"properties": {
"query": {"type": "string"}
},
"required": ["query"]
}
}
CONFIG_NAMESPACE = "mock"
def __init__(self, *args, **kwargs):
super(HttpResourceMock, self).__init__(*args, **kwargs)
self.session = MockRe... |
from pymol.cgo import *
from pymol import cmd
from pymol.vfont import plain
# create the axes object, draw axes with cylinders coloured red, green,
#blue for X, Y and Z
obj = [
CYLINDER, 0., 0., 0., 10., 0., 0., 0.2, 1.0, 1.0, 1.0, 1.0, 0.0, 0.,
CYLINDER, 0., 0., 0., 0., 10., 0., 0.2, 1.0, 1.0, 1.0, 0., 1.0, 0.... | 1.0,
]
# add labels to axes object
cyl_text(obj,plain,[-5.,-5.,-1],'O | rigin',0.20,axes=[[3.0,0.0,0.0],[0.0,3.0,0.0],[0.0,0.0,3.0]])
cyl_text(obj,plain,[10.,0.,0.],'X',0.20,axes=[[3.0,0.0,0.0],[0.0,3.0,0.0],[0.0,0.0,3.0]])
cyl_text(obj,plain,[0.,10.,0.],'Y',0.20,axes=[[3.0,0.0,0.0],[0.0,3.0,0.0],[0.0,0.0,3.0]])
cyl_text(obj,plain,[0.,0.,10.],'Z',0.20,axes=[[3.0,0.0,0.0],[0.0,3.0,0.0],[0.0... |
null_stream = cuda.Stream.null
self.comm.reduce(gg.data.ptr, gg.data.ptr, gg.size,
nccl_data_type, nccl.NCCL_SUM, 0,
null_stream.ptr)
del gg
self.model.cleargrads()
gp = gath... | Updater for new batch size.'.
format(optimizer.eps))
elif hasattr(optimizer, 'lr'):
optimizer.lr /= len(devices)
war | nings.warn('optimizer.lr is changed to {} '
'by MultiprocessParallelUpdater for new batch size.'.
format(optimizer.lr))
super(MultiprocessParallelUpdater, self).__init__(
iterator=iterators[0],
optimizer=optimizer,
converte... |
#Ret Samys, creator of this program, can be found at RetSamys.deviantArt.com
#Please feel free to change anything or to correct me or to make requests... I'm a really bad coder. =)
#Watch Andrew Huang's video here: https://www.youtube.com/watch?v=4IAZY7JdSHU
changecounter=0
path="for_elise_by_beethoven.mid"
prin... | except NameError:
pass
lastnote=i[4:][byte] #set current note to compare to next note before it's changed!
try:i[byte+4]=chr(ord(i[4:][byte])+offset) #change note
except:
if ord(i[4:][byte])+offset>127:
... |
lowcount+=1
#journey to note off starts here
for offbyte in range(len(i[byte+4:])):
if ord(i[byte+4:][offbyte])==255 and ord(i[byte+4:][offbyte+1])==81 and ord(i[byte+4:][offbyte+1])==3: #check for set tempo meta-event
... |
# -*- coding: utf-8 -*-
# Copyright 2014, 2015 OpenMarket Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | ODO
def validate_new(self, event):
self.validate(event)
UserID.from_string(event.sender)
if event.type == EventTypes.Message:
strings = [
"body",
"msgtype",
]
self._ensure_strings(event.content, strings)
elif ev... | trings(event.content, ["topic"])
elif event.type == EventTypes.Name:
self._ensure_strings(event.content, ["name"])
def _ensure_strings(self, d, keys):
for s in keys:
if s not in d:
raise SynapseError(400, "'%s' not in content" % (s,))
if not isin... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# RawSpeed documentation build configuration file, created by
# sphinx-quickstart on Mon Aug 14 18:30:09 2017.
#
# 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
# a... | theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'sphinx_rtd_theme'
# Theme options are theme-specific and customize | the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#
# html_theme_options = {}
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "de... |
"""
Functions for calculating statistics and handling uncertainties.
(c) Oscar Branson : https://github.com/oscarbranson
"""
import numpy as np
import uncertainties.unumpy as un
import scipy.interpolate as interp
from scipy.stats import pearsonr
def nan_pearsonr(x, y):
xy = np.vstack([x, y])
xy = xy[:, ~np.a... | ig * sd
x[lo] = mu - sig * sd
return H15_std(x)
else:
return sd
def H15_se(x):
"""
Calculate the Hube | r (H15) Robust standard deviation of x.
For details, see:
http://www.cscjp.co.jp/fera/document/ANALYSTVol114Decpgs1693-97_1989.pdf
http://www.rsc.org/images/robust-statistics-technical-brief-6_tcm18-214850.pdf
"""
sd = H15_std(x)
return sd / np.sqrt(sum(np.isfinite(x)))
def get_total_n... |
gger
class TestPortalProjectBase(TestPortalProjectBase):
def setUp(self):
super(TestPortalProjectBase, self).setUp()
cr, uid = self.cr, self.uid
# Useful models
self.project_issue = self.registry('project.issue')
# Various test issues
self.issue_1_id = self.proje... | test_issue_ids = set([self.issue_1_id, self.issue_2_id, self.issue_3_id, self.issue_4_id, self.issue_5_id, self.issue_6_id])
self.assertEqual(set(issue_ids), test_issue_ids,
'access rights: project user cannot see all issues of an employees project')
# Do: Chel | l reads project -> ko (portal ko employee)
# Test: no project issue visible + assigned
issue_ids = self.project_issue.search(cr, self.user_portal_id, [('project_id', '=', pigs_id)])
self.assertFalse(issue_ids, 'access rights: portal user should not see issues of an employees project, even if ass... |
#!/u | sr/bin/env python
# -*- coding: utf-8 -*-
#
# Proprietary and confidential.
# Copyright 2011 Perfect Search Corporation.
# All rights reserved.
#
import sys
sys.dont_write_bytecode = True
#import clientplugin
import fastbranches
import serverp | lugin
|
(
self._parse_jsonpath_field, parts)
def parse_jsonpath(self, field):
try:
parts = self.JSONPATH_RW_PARSER.parse(field)
except Exception as e:
raise MeterDefinitionException(_LE(
"Parse error in JSONPath specification "
"'%... | le is not None:
LOG.debug(_LE("Meter Definitions configuration file: %s"), config_file)
with open(config_file) as cf:
config = cf.read()
try:
meters_config = yaml.safe_load(config)
except yaml.YAMLError as err:
if hasattr(err, 'pr | oblem_mark'):
mark = err.problem_mark
errmsg = (_LE("Invalid YAML syntax in Meter Definitions file "
"%(file)s at line: %(line)s, column: %(column)s.")
% dict(file=config_file,
line=mark.line + 1,
... |
# -*- coding: utf-8 -*-
# ########################## Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> ... | (commit.message, "Test commit created around Fri, 13 Jul 2012 18:43:21 GMT, that is vendredi 13 juillet 2012 20: | 43:21 GMT+2\n")
self.assertEqual(commit.author.date, datetime.datetime(2012, 7, 13, 18, 47, 10))
|
import notify2
import os
from time import *
start_time = time()
notify2.init('')
r = notify2.Notification('', '')
while True:
for i in [ ('TO DO', 'Write JavaScript'),
('TO DO', 'Write Python'),
('Thought of the Day', 'Support Open Source'),
('Learn. . .', 'Use Linux... | ing for cheese'),
('Thought of the Day', 'You are cool')]:
r.update(i[0], i[1])
sleep(120)
x = int(time() - start_time)%120
if x == 119:
os.system('play --no-show-progress --null --channels 1 synth %s sine %f' % ( 0.5, 500))
r.show | ()
|
import statsmodels.tsa.stattools as st
import matplotlib.pylab as plt
import numpy as np
import pandas as pd
df = pd.read_csv('gld_uso.csv')
cols = ['GLD','USO']
df['hedgeRatio'] = df['USO'] / df['GLD']
data_mean = pd.rolling_mean(df['hedgeRatio'], window=20)
data_std = pd.rolling_std(df['hedgeRatio'], wind | ow=20)
df['numUnits'] = -1*(df['hedgeRatio']-data_mean) / data_std
positions = df[['numUnits','numUnits']].copy()
positions = positions * np.array([-1., 1.])
pnl = positions.shift(1) * np.array((df[cols] - df[cols].s | hift(1)) / df[cols].shift(1))
pnl = pnl.fillna(0).sum(axis=1)
ret=pnl / np.sum(np.abs(positions.shift(1)),axis=1)
print 'APR', ((np.prod(1.+ret))**(252./len(ret)))-1.
print 'Sharpe', np.sqrt(252.)*np.mean(ret)/np.std(ret)
|
a connection.',
# -- 200's --
CMD_OK: '200 Command OK',
TYPE_SET_OK: '200 Type set to %s.',
ENTERING_PORT_MODE: '200 PORT OK',
SYS_STATUS_OR_HELP_REPLY: '211 System status reply',
DIR_STATUS: '2... | reply(ENTERING_PASV_MODE, encodeHostPort(host, port))
def ftp_QUIT(self):
self.reply(GOODBYE_MSG)
self.close()
def real_path(self, p=None):
if p:
name = os.path.join(self.cwd, p)
else:
name = self.cwd
if len(name) >= 1 and name[0] == '/':
... | e)
return name
def ftp_RETR(self, p):
if not p:
return (SYNTAX_ERR_IN_ARGS, RETR)
name = self.real_path(p)
if not name.startswith(self.basedir):
return (PERMISSION_DENIED, p)
if os.path.exists(name) and os.path.isfile(name):
if self.dtp... |
import collections
import numpy as np
import sympy
from sym2num import function, var
def reload_all():
"""Reload modules for testing."""
import imp
for m in (var, function):
imp.reload(m)
if __name__ == '__main__':
reload_all()
g = var.UnivariateCallable('g')
h = var.Univariat... |
obj = {'data': [w], 'extra': {'other': [m, z]}, 'gg': g}
arguments = function.Arguments(self=obj, | t=t, state=[x, y], H=h)
f = function.FunctionPrinter('f', output, arguments)
print(f.print_def())
sf = function.SymbolicSubsFunction(function.Arguments(t=t, m=[x,y]), t**2+x)
print( "\n" + "*" * 80 + "\n")
print(sf(w**4, [2*x,3*z]))
|
#!/usr/bin/python
#======================================================================
#
# Project : hpp_IOStressTest
# File : IOST_WRun_CTRL.py
# Date : Oct 25, 2016
# Author : HuuHoang Nguyen
# Contact : hhnguyen@apm.com
# : hoangnh.hpp@gmail.com
# License : MIT License
# Copyright : 2016
# ... | :
""
self.IOST_Objs[window_name][window_name+"_Terminal_ScrolledWindow"].connect('button_press_event', lambda *args: True)
self.WRun_Term = IOST_Terminal(self.IOST_Objs[window_name][window_name+"_NoteBook"], self.WRun_Host.name)
self.IOST_Objs[window_name][window_name+"_Terminal_Scrolled... | _Term.IOST_vte.show()
|
#!/usr/bin/env jython
from __future__ import with_statement
from contextlib import | contextmanager
import logging
from plugins import __all__
log = logging.getLogger('kahuna')
class PluginManager:
""" Manages available plugins """
def __init__(self):
""" Initialize the plugin list """
self.__plugins = {}
def load_plugin(self, plugin_name):
""" Loads a single plu... | me in __all__:
raise KeyError("Plugin " + plugin_name + " not found")
try:
plugin = self.__plugins[plugin_name]
except KeyError:
# Load the plugin only if not loaded yet
log.debug("Loading plugin: %s" % plugin_name)
module = __import__("plugins... |
# -*- coding: utf-8 -*-
# | Copyright 2016, 2017 Kevin Reid and the ShinySDR contributors
#
# This file is part of ShinySDR.
#
# ShinySDR 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 Foun | dation, either version 3 of the License, or
# (at your option) any later version.
#
# ShinySDR is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more detail... |
g_value(
'passwd', vm_, __opts__, search_global=False
), search_global=False
)
def get_key():
'''
Returns the ssh private key for VM access
'''
return config.get_cloud_config_value(
'private_key', get_configured_provider(), __opts__, search_global=False
)
def get_... | al deployment: \n{1}'.format(
vm_['name'], str(exc)
),
# Show the traceback if the debug logging level is enabled
exc_in | fo_on_loglevel=logging.DEBUG
)
return False
for device_name in six.iterkeys(volumes):
try:
conn.attach_volume(data, volumes[device_name], device_name)
except Exception as exc:
log.error(
'Error attaching volume {0} on CLOUDSTACK\n\n'
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# -*- Author: ClarkYAN -*-
from get_connection import *
from get_key import *
import Tkinter
import tkMessageBox
class mainFrame:
def __init__(self):
self.root = Tkinter.Tk()
self.root.title('Secure Protocol Systems')
self.root.geometry('600x3... | elf.frm_r = Tkinter.Frame(self.frm)
buttonEncrypted = Tkinter.Button(self.frm_r, text="Encrypting Original data", font=("Arial", 18), height=2)
buttonEncrypted.pack(side=Tkinter.LEFT)
buttonSend = Tkinter.Button(self.frm_r, text="Send to Cloud", font=("Arial" | , 18), height=2)
buttonSend.pack(side=Tkinter.LEFT)
self.frm_r.pack(side=Tkinter.BOTTOM)
self.frm.pack(side=Tkinter.TOP)
self.root.mainloop()
def setUpConnection():
url = 'http://127.0.0.1:4000/'
sender = 'data_owner_1'
result = str(set_up_connection(url, sender))
tkM... |
from os.path import join, dirname
fr | om setuptools import setup
setup(
name = 'xmppgcm',
packages = ['xmppgcm'], # this must be the same as the name above
version = '0.2.3',
description = 'Client Library for Firebase Cloud Messaging using XMPP',
long_description = open(join(dirname(__file__), 'README.txt')).read(),
install_requires=['sleekxmp... | ], # arbitrary keywords
classifiers = [],
)
|
#!/usr/bin/ | env python
"""
Se | rvice Subpackage
"""
from . import test
from . import detect
from . import device
from . import object
from . import cov
from . import file
|
#Pizza please
import pyaudiogame
from pyaudiogame import storage
spk = pyaudiogame.speak
MyApp = pyaudiogame.App("Pizza Please")
storage.screen = ["start"]
storage.toppings = ["cheese", "olives", "mushrooms", "Pepperoni", "french fries"]
storage.your_toppings = ["cheese"]
storage.did_run = False
def is_number(number,... | n[0] = "remove"
storage.did_run = False
elif key == "a":
spk("Press a number to add a topping to your pizza. Press d to remove a topping you don't like")
storage.screen[0] = "add"
storage.did_run = False
elif key == "space":
spk("You sit down to enjoy a yummy pizza. You eat... eat... eat... eat... and are f... | t":
spk("Welcom to pizza madness! Here you can build your own pizza to eat! Press a to add toppings, press d to remove them and when you are done, press space to eat your yummy pizza!!!")
storage.screen.remove("start")
storage.screen.append("add")
elif storage.screen[0] == "add":
say_message("Please choose a n... |
from __future__ import unicode_liter | als
from django.db import models
from modpacks.models.modpack import Modpack
class Server(models.Model):
""" Minecraft Server details for display on the server page """
name = models.CharField(verbose_name='Server Name',
max_length=200)
desc = models.TextField(verbose_name='Se | rver Description',
blank=True)
modpack = models.ForeignKey(Modpack, verbose_name='Server Modpack')
address = models.CharField(verbose_name='Server Address',
max_length=200,
blank=True)
screenshot = models.ImageField(verbose_name='Screenshot',
blank=True)
d... |
#!/usr/bin/python3
# Copyright (c) 2018-2021 Dell Inc. or its subsidiaries.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... | tr(hpg_num))
if enable_numa:
_, node_data = self.nfv_params.select_compute_node(self.node_type,
| self.instackenv)
self.nfv_params.parse_data(node_data)
self.nfv_params.get_all_cpus()
self.nfv_params.get_host_cpus(hostos_cpu_count)
self.nfv_params.get_nova_cpus()
self.nfv_params.get_isol_cpus()
if is_ovs_dpdk:
dpdk_nics = sel... |
from sqlalchemy import *
from test.lib import *
class FoundRowsTest(fixtures.TestBase, AssertsExecutionResults):
"""tests rowcount functionality"""
__requires__ = ('sane_rowcount', )
@classmethod
def setup_class(cls):
global employees_table, metadata
metadata = MetaData(testing.db)
... | ('Bob', 'B'),
('Bobette', 'B'),
('Buffy', 'B'),
('Charlie', 'C'),
('Cynthia', 'C'),
('Chris', 'C') ]
i = employees_table.insert()
i.execute(*[{'name':n, 'department':d} for n, d in data])
def teardown(self):
... | eardown_class(cls):
metadata.drop_all()
def testbasic(self):
s = employees_table.select()
r = s.execute().fetchall()
assert len(r) == len(data)
def test_update_rowcount1(self):
# WHERE matches 3, 3 rows changed
department = employees_table.c.department
... |
#!/usr/bin/python
import RPi.GPIO as GPIO
import signal
import time
from on_off import *
class keypad():
def __init__(self, columnCount = 3):
GPIO.setmode(GPIO.BCM)
# CONSTANTS
if columnCount is 3:
self.KEYPAD = [
[1,2,3],
... | l], GPIO.OUT)
GPIO.output(self.ROW[rowVal], GPIO.HIGH)
# Scan columns for still-pushed key/button
# A valid key press should set "colVal" between 0 and 2.
colVal = -1
for j in range(len(self.COLUMN)):
tmpRead = GPIO.inpu | t(self.COLUMN[j])
if tmpRead == 1:
colVal=j
# if colVal is not 0 thru 2 then no button was pressed and we can exit
if colVal <0 or colVal >2:
self.exit()
return
# Return the value of the key pressed
self.exit()
retu... |
from __future__ import print_function
from builtins import range
import sys
sys.path.insert(1,"../../")
import h2o
from tests import pyunit_utils
import random
import os
def javapredict_dynamic_data():
# Generate random dataset
dataset_params = {}
dataset_params['rows'] = random.sample(list(range(5000,150... | _params['integer_fraction'] - 0.1
else:
dataset_params['categorical_fraction'] = dataset_para | ms['categorical_fraction'] - 0.1
dataset_params['missing_fraction'] = random.uniform(0,0.5)
dataset_params['has_response'] = True
dataset_params['randomize'] = True
dataset_params['factors'] = random.randint(2,2000)
print("Dataset parameters: {0}".format(dataset_params))
train = h2o.create_fram... |
)
file.close()
self.close()
return True
except IOError:
return False
def MoranI(self):
QApplication.setOverrideCursor(Qt.WaitCursor)
if len(self.nb)==0:
if self.comboBox_5.currentText()!='within distance':
nb = sel... | ution of variable does not | meet test assumptions\n')
VI = tmp
else:
VI = (float(nn) * float(S1) - float(n) * float(S2) + 3.0 * float(S02))/(float(S02) * (float(nn) - 1.0))
tmp = (VI - power(EI,2))
if tmp < 0:
self.plainTextEdit.insertPlainText('Negative variance, ndistributi... |
def mm_loops(X,Y,Z):
m = len(X)
n = len(Y)
for i in xrange(len(X)):
xi = X[i]
for j in xrange(len(Y)):
yj = Y[j]
total = 0
for k in xrange(len(yj)):
to | tal += xi[k] * yj[k]
Z[i][j] = total
return Z
def make_matrix(m,n):
mat = []
for i in xrange(m):
mat.append(range(n))
return mat
if __name__ == '__main__':
n = 200
x = make_matrix(n,n)
z = ma | ke_matrix(n,n)
mm_loops(x, x, z)
|
one]
try:
Use(ve, error='should not raise').validate('x')
except SchemaError as e:
assert e.autos == ["ve('x') raised ValueError()"]
assert e.errors == ['should not raise']
try:
Use(se).validate('x')
except SchemaError as e:
assert e.autos == [None, 'first auto']
... | uestions/14588098/docopt-schema-validation
s = Schema({'ID': Use(int, error='ID should be an int'),
'FILE': Or(None, Use(open, error='FILE should be readable')),
Optional(str): object})
data = {'ID': 10, 'FILE': None, 'other': 'other', 'other2': 'other2'}
assert s.validate(da... | ), 'name'): And(str, len)})
with SE: s.validate(dict())
with SE:
try:
Schema({1: 'x'}).validate(dict())
except SchemaMissingKeyError as e:
assert e.args[0] == "Missing keys: 1"
raise
# PyPy does have a __name__ attribute for its callables.
@mark.skipif(platf... |
S,
# 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.
#
"""Module to build p | ipeline fragment that produces given PCollections.
For internal use only; no backwards-compatibility guarantees.
"""
from __future__ import absolute_import
import apache_beam as beam
from apache_beam.pipeline i | mport PipelineVisitor
from apache_beam.testing.test_stream import TestStream
class PipelineFragment(object):
"""A fragment of a pipeline definition.
A pipeline fragment is built from the original pipeline definition to include
only PTransforms that are necessary to produce the given PCollections.
"""
def _... |
"""This test checks for correct wait4() behavior.
"""
import os
import time
from test.fork_wait import ForkWait
from test.test_support import run_unittest, reap_children, get_attribute
# If either of these do not exist, skip this test.
get_attribute(os, 'fork')
get_attribute( | os, 'wait4')
class Wait4Test(ForkWait):
def wait_impl(self, cpid):
for i in range(10):
# wait4() shouldn't hang, but some of the buildbots seem to hang
# in the forking tests. This is an attempt to fix the problem.
spid, status, rusage = os.wait4(cpid, os.WNOHANG)
... | spid == cpid:
break
time.sleep(1.0)
self.assertEqual(spid, cpid)
self.assertEqual(status, 0, "cause = %d, exit = %d" % (status&0xff, status>>8))
self.assertTrue(rusage)
def test_main():
run_unittest(Wait4Test)
reap_children()
if __name__ == "__main__":
t... |
from flask import render_template
from app import app, db, models
import json
@app.route('/')
@app.route('/index')
def index():
# obtain today's words
# words = mode | ls.Words.query.all()
# words = list((str(word[0]), word[1]) for word in db.session.query(models.Words, db.func.count(models.Words.id).label("total")).group_by(models.Words.word).order_by("total DESC"))
data = db.session.query(models.Words, db.func.count(models.Words.id).label("total")).group_by(models.Words.wor... | data]
return render_template('index.html', words=words, count = count) |
, gxparam_extra_kwargs, default=None):
from argparse import FileType
"""Based on a type, convert to appropriate gxtp class
"""
if default is None and (param.type in (int, float)):
default = 0
if param.type == int:
mn = None
mx = None
... | min(param.choices)
mx = max(param.choices)
gxparam = gxtp.IntegerParam(flag, default, label=label, min=mn, max=mx, num_dashes=num_dashes, **gxparam_extra_kwargs)
elif param.choices is not None:
choices = {k: k for k in param.choices}
gxparam = gxtp.SelectPara... | aram_extra_kwargs)
elif param.type == float:
gxparam = gxtp.FloatParam(flag, default, label=label, num_dashes=num_dashes, **gxparam_extra_kwargs)
elif param.type is None or param.type == str:
gxparam = gxtp.TextParam(flag, value=default, label=label, num_dashes=num_dashes, **gxpa... |
from model import Event
from geo.geomodel import | geotypes
def get(handler, response):
lat = handler.request.get('lat')
lon = handler.request.get('lng')
response.events = Event.proximity_fetch(
Event.all(),
geotypes.Point(float(lat),float( | lon)),
)
|
# Copyright (c) 2015-2016 Cisco Systems, Inc.
#
# 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 use, copy, modify, merge... | elif dependency_name == 'shell':
dd = self.molecule.config.config.get('dependency')
if dd.get('command'):
msg = "Downloading dependencies with '{}'...".format(
dependency_name)
util.print_info(msg)
s = shell.Shell(self | .molecule.config.config, debug=debug)
s.execute()
self.molecule.state.change_state('installed_deps', True)
return (None, None)
@click.command()
@click.pass_context
def dependency(ctx): # pragma: no cover
""" Perform dependent actions on the current role. """
d = Depen... |
import save
import client
def start():
def callback():
client.client.chat('/novice')
found_nations = [ (name, style, id) for name, style, id in client.get_nations() if name == 'Poles' ]
if found_nations:
name, style, id = found_nations[0]
print 'change nation to', na... | set_nation_settings(id, ' | Player', style, 2)
return True
save.load_game('data/tutorial.sav', before_callback=callback)
|
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import os
import pytest
from translate.fil... | (language=english)
# There is already an english tutorial was automagically set up
with pytest.raises(IntegrityError):
TranslationProject.objects.create(project=tutorial, language=english)
@pytest.mark.django_db
def test_tp_create_parent_dirs(tp0):
parent = tp0.create_parent_dirs("%sfoo/bar/baz.p... | get(
pootle_path="%sfoo/bar/" % tp0.pootle_path))
@pytest.mark.django_db
def test_tp_create_templates(project0_nongnu, project0,
templates, no_templates_tps, complex_ttk):
# As there is a tutorial template it will automatically create stores for
# our new TP
templa... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import pytest
import numpy as np
import torch.nn as nn
import torch as T
from torch.autograd import Variable as var
import torch.nn.functional as F
from torch.nn.utils import clip_grad_norm_
import torch.optim as optim
import numpy as np
import sys
import os
import mat... | rt mhx['memory'].size() == T.Size([10,1,1])
assert rv.size() == T.Size([10, 1])
def test_rnn_n():
T.manual_seed(1111)
input_size = 100
hidden_size = 100
rnn_type = 'rnn'
num_layers = 3
num_hidden_layers = 5
dropout = 0.2
nr_cells = 12
cell_size = 17
read_heads = 3
gpu_id = -1
debug = True
... | e,
rnn_type=rnn_type,
num_layers=num_layers,
num_hidden_layers=num_hidden_layers,
dropout=dropout,
nr_cells=nr_cells,
cell_size=cell_size,
read_heads=read_heads,
gpu_id=gpu_id,
debug=debug
)
optimizer = optim.Adam(rnn.parameters(), lr=lr)
optimizer.zero_grad(... |
from collections import defaultdict
import fileinput
mem = defaultdict(int)
s1 = -100000
s2 = -100000
def condit | ion(line):
global mem
l = line[-3:]
if l[1] == "==":
if mem[l[0]] == int(l[2]): return True
else: return False
elif l[1] == "<":
if mem[l[0]] < int(l[2]): return True
else: return False
el | if l[1] == ">":
if mem[l[0]] > int(l[2]): return True
else: return False
elif l[1] == "<=":
if mem[l[0]] <= int(l[2]): return True
else: return False
elif l[1] == ">=":
if mem[l[0]] >= int(l[2]): return True
else: return False
elif l[1] == "!=":
if mem... |
import numpy, sys
import scipy.linalg, scipy.special
'''
VBLinRegARD: Linear basis regression with automatic relevance priors
using Variational Bayes.
For more details on the algorithm see Apprendix of
Roberts, McQuillan, Reece & Aigrain, 2013, MNRAS, 354, 3639.
History:
2011: Translated by Thomas Evans from origina... | logdetV = | -logdet(invV)
w = numpy.dot(V, Xy_corr)[:,0]
# parameters of noise model (an remains constant)
sse = numpy.sum(numpy.power(X*w-y, 2), axis=0)
if numpy.imag(sse)==0:
sse = numpy.real(sse)[0]
else:
print 'Something went wrong'
bn = b0 + 0.5 * (ss... |
,'P',pic,Ref)
s[2]=Props('S','T',T[2],'P',pic,Ref)
rho[2]=Props('D','T',T[2],'P',pic,Ref)
T[3]=288
p[3]=pic
h[3]=Props('H','T',T[3],'P',pic,Ref)
s[3]=Props('S','T',T[3],'P',pic,Ref)
rho[3]=Props('D','T',T[3],'P',pic,Ref)
rho3=Props('D','T',T[3],'P',pic,Ref)
h4s=Props('H','T',s[3],'P'... | s[5]=Props('S','T',T[5],'P',pc,Ref)
rho[5]=Props('D','T',T[5],'P',pc,Ref)
p[5]=pc
p[6]=pi
h[6]=h[5]
p[7]=pi
p[8]=pi
p[6]=pi
T[7]=Ti
h[7]=Props('H','T',Ti,'Q',1,Ref)
s[7]=Props('S','T',Ti,'Q',1,Ref)
rho[7]=Props('D','T',Ti,'Q',1,Ref)
T[8]=Ti
h[8]=Props('H','T',Ti,'Q... | ho[7]+(1-x6)/rho[8])
T[6]=Ti
#Injection mass flow rate
x=m*(h[6]-h[8])/(h[7]-h[6])
p[3]=pi
h[3]=(m*h[2]+x*h[7])/(m+x)
T[3]=T_hp(Ref,h[3],pi,T[2])
s[3]=Props('S','T',T[3],'P',pi,Ref)
rho[3]=Props('D','T',T[3],'P',pi,Ref)
T4s=newton(lambda T: Props('S','T',T,'P',pc,Ref)-s[3],T[2]+30... |
jango.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_st... | 'architecture': ('django.db.models.fields.CharFie | ld', [], {'default': "u'i386/generic'", 'max_length': '31'}),
'cpu_count': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'created': ('django.db.models.fields.DateTimeField', [], {}),
'distro_series': ('django.db.models.fields.CharField', [], {'default': 'None', 'max... |
# -*- coding: utf-8 -*-
from __future__ import uni | code_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('freebasics', '0005_remove_selected_template_field'),
]
operations = [
migrations.AlterField(
model_name='freebasicstemplatedata',
name='site_name_url'... | que=True, null=True, blank=True),
),
]
|
#!/usr/bin/env python
imp | ort os
import sys
sys.path.insert(
0,
os.path.join(
os.path.dirname(os.path.abspath(__file__)), '..', '..', '..', 'common',
'security-features', 'tools'))
import generate
class ReferrerPolicyConfig(object):
def __init__(self):
self.selection_pattern = \
'%(source_con... | s/' + \
'%(subresource)s/' + \
'%(origin)s.%(redirection)s.%(source_scheme)s'
self.test_file_path_pattern = 'gen/' + self.selection_pattern + '.html'
self.test_description_template = 'Referrer Policy: Expects %(expectation)s for %(subresource)s to %(origin)s origin and %(re... |
import os.path
import shutil
import zipfile
import click
from pros.config import ConfigNotFoundException
from .depot import Depot
from ..templates import BaseTemplate, Template, ExternalTemplate
from pros.common.utils import logger
class LocalDepot(Depot):
def fetch_template(self, template: BaseTemplate, destin... | location
if not os.path.isfile(os.path.join(location_dir, 'template. | pros')):
raise ConfigNotFoundException(f'A template.pros file was not found in {location_dir}.')
template_file = os.path.join(location_dir, 'template.pros')
elif zipfile.is_zipfile(location):
with zipfile.ZipFile(location) as zf:
with click.progressbar(len... |
import numpy as np
def array_generator():
array = np.array([(1, 2, 3, 4, 5), (10, 20, 30, 40, 50)])
return array
def multiply_by_number(array, number):
print(array)
multiplied = array * number
print(multiplied)
return multiplied
def divide_by_number(array, number):
# Either the numer or the elements of the a... | d
def addition(array_1, array_2):
return array_1 + array_2
def elemtwise_mul(array_1, array_2):
return array_1 * array_2
if __name__ == "__main__":
# -----------------------------------------------------
x = array_generator()
two_x = multiply_by_number(x, 2)
half_x = divide_by_number(x, 2)
added = addition(tw... | 6)]) # !
print(y)
print('Z')
z = np.array([(1, 2), (3, 4), (5, 6)]) # !
print(z)
print('D')
d = np.dot(y, z)
print(d) |
"""
calc.py
>>> import calc
>>> s='2+4+8+7-5+3-1'
>>> calc.calc(s)
18
>>> calc.calc('2*3+4-5*4')
-10
"""
import re
from operator import concat
operator_function_table = { '+' : lambda x, y: x + y,
'-' : lambda x, y: x - y,
'*' : lambda x, y: x ... | dd_sub_operands = re | .split(op_re_add_sub, s)
add_sub_operators = re.findall(op_re_add_sub, s)
post_mult_div = [str(calc_helper(operand)) for operand in add_sub_operands]
new_calc_l = [reduce(concat, list(x)) for x in zip(post_mult_div[:-1], add_sub_operators)]
new_calc_l.extend(post_mult_div[-1])
new_calc_s = redu... |
#!/usr/bin/env python
def main():
import sys
raw_data = load_csv(sys.argv[1])
create_table(raw_data)
def get_stencil_num(k):
# add the stencil operator
if k['Stencil Kernel coefficients'] in 'constant':
if int(k['Stencil Kernel semi-bandwidth'])==4:
stencil = 0
else:
... | p)
# model error
tup['Err %'] = 100 * (tup['Model'] - tup['Actual Bytes/LUP'])/tup['Actual Bytes/LUP']
tup['D_width'] = (tup['Time unroll']+1)*2*tup['Stencil Kernel semi-bandwidth']
tup['Performance'] = tup['WD main-loop RANK0 MStencil/s MAX']
data2.append(tu... | sorted(data2, key=itemgetter('Time stepper orig name', 'Kernel', 'Thread group size', 'Local NX', 'D_width'))
fields = ['Time stepper orig name', 'Kernel', 'Thread group size', 'Local NX', 'Precision', 'D_width', 'Total cache block size (kB):', 'Actual Bytes/LUP', 'Model', 'Err %', 'Performance']
with open('... |
# Copyright 2014 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompa... | nce'])
io.log_warning(prompts['scale.switchtoloadbalancewarn'])
switch = io.get_boolean_response()
if not switch:
return
options.append({'Namespace': namesp | ace,
'OptionName': 'EnvironmentType',
'Value': 'LoadBalanced'})
# change autoscaling min AND max to number
namespace = 'aws:autoscaling:asg'
max = 'MaxSize'
min = 'MinSize'
for name in [max, min]:
options.append(
{'Namespace': nam... |
#!/usr/bin/python
# Copyright 2014 Google Inc.
#
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Script for generating the Android framework's version of Skia from gyp
files.
"""
import android_framework_gyp
import os
import shutil
import sys
import tempfile
... | 'x86'))
# Currently, x86_64 is identical to x86
deviations_from_common.append(makefile_writer.VarsDictData(x86_var_dict,
'x86_64'))
deviations_from_common.append(makefile_writer.VarsDictData(mips_... | deviations_from_common.append(makefile_writer.VarsDictData(arm64_var_dict,
'arm64'))
makefile_writer.write_android_mk(target_dir=target_dir,
common=common, deviations_from_common=deviations_from_common)
finally:
shutil.rmtree(tmp_fold... |
"""
Code : Remove the dependency for Kodak Bank, default excel parser macros and just GNU/Linux to acheive it.
Authors : Ramaseshan, Anandhamoorthy , Engineers, Fractal | io Data Pvt Ltd, Magadi, Karnataka.
Licence : GNU GPL v3.
Code Repo URL : https://github.com/ramaseshan/kodak_bank_excel_parser
"""
im | port pyexcel as pe
import pyexcel.ext.xls
import unicodedata
import sys
import time
def delete_content(pfile):
pfile.seek(0)
pfile.truncate()
filename = sys.argv[1]
fileout = filename.split('.')[0]+".txt"
print "Reading file ",filename
records = pe.get_array(file_name=filename)
f = open(fileout,'w')
print "Starti... |
from py4j.java_gateway import JavaGateway, GatewayParameters
gateway = JavaGateway(gateway_parameters=GatewayParameters(port=25333))
doc1 = gateway.jvm.gate.Fac | tory.newDocument("initial text")
print(doc1.getContent().toString())
doc2 = gateway.jvm.gate.plugin.python.PythonSlave.loadDocument("docs/doc1.xml")
print(doc2.getContent().toString())
js1 = gateway.jvm.gate.plugin.python.PythonSlave.getBdocDocumentJson(doc2)
pr | int(js1)
gateway.close()
|
from django.http import HttpResponse,HttpResponseRedirect
from django.shortcuts import render_to_response
from django import forms
from django.forms import ModelForm
from django.db.models import F
from django.db import connection
from django.utils import simplejson
from django.contrib import messages
from django.contri... | trs={'size': 80}),
| }})
url = request.GET.get('url')
title = request.GET.get('title')
desc = request.GET.get('desc')
#default_tag_id = T.objects.get(name='untagged').id
addNoteForm = AddNForm_scrap(initial={'url': url, 'title':title, 'desc'... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.