prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
xt
import os
import re
import json
import shutil
import subprocess
from tempfile import mkdtemp, mktemp
from distutils.spawn import find_executable
import frappe
from frappe.utils.minify import JavascriptMinify
import click
import psutil
from urllib.parse import urlparse
from simple_chalk import green
from semantic_... | elopment else "production"
assets_json = frappe.read_file("assets/assets.json")
if assets_json:
assets_json = frappe.parse_json(assets_json)
for bundle_file, output_file in assets_json.items():
if not output_file.startswith('/assets/frappe'):
continue
if os.path.basename(output_file) not in current_a... | missing_assets.append(bundle_file)
if missing_assets:
click.secho("\nBuilding missing assets...\n", fg="yellow")
files_to_build = ["frappe/" + name for name in missing_assets]
bundle(build_mode, files=files_to_build)
else:
# no assets.json, run full build
bundle(build_mode, apps="frappe")
def get_ass... |
__ | all__ = ["bayes", "cpt", "heuristic", "payoff", "r | ecognition", "rl", "sharing"] |
# -*- coding: utf-8 -*-
# Description: sort audio clips by intensity, frequency, or duration; outputs .csv file for use in sequence.ck via ChucK
# python sort_audio.py -sort syllables
# python sort_audio.py -sort syllables -by frequency
# python sort_audio.py -sort syllables -by duration -fixed 0
import argpars... | fault="data/ck_sequence.csv", help="Path to output csv sequence file")
parser.add_argument('-sort', dest="SORT_FIELD", default="words", help="Field to sort: syllables, words, or lines")
parser.add_argument('-by', dest="SORT_BY", default="intensity", help="Feature to sort | by: intensity, frequency, or duration")
parser.add_argument('-dir', dest="SORT_DIRECTION", type=int, default=1, help="Sort direction: -1 or 1")
parser.add_argument('-overlap', dest="OVERLAP_MS", type=int, default=50, help="Amount of ms to overlap in clip")
parser.add_argument('-fixed', dest="FIXED_MS", type=int, defaul... |
"""SocialNewspaper URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
... | interesting"),
url(r'^print_articl | es/$', views.print_articles, name="print_articles"),
url(r'^editorial/$', views.editorial, name="editorial"),
url(r'^$', views.editorial, name="home")
]
|
"""Authenticating HTTP Server
This module builds on BaseHTTPServer and implements basic authentication
"""
import base64
import binascii
import BaseHTTPServer
DEFAULT_AUTH_ERROR_MESSAGE = """
<head>
<title>%(code)s - %(message)s</title>
</head>
<body>
<h1>Authorization Required</h1>
this server could not verify th... | t the user is not authorized.
"""
# False means no authentiation
DO_AUTH = 1
def parse_request(self):
if not BaseHTTPServer.BaseHTTPRequestHandler.parse | _request(self):
return False
if self.DO_AUTH:
authorization = self.headers.get('Authorization', '')
if not authorization:
self.send_autherror(401, "Authorization Required")
return False
scheme, credentials = authorization.split()
... |
"""
Tests related specifically to the FacilityDataset model.
"""
from django.db.utils import IntegrityError
from django.test import TestCase
from ..models import Classroom
from ..models import Facility
from ..models import FacilityDataset
from ..models import FacilityUser
from ..models import LearnerGroup
class Faci... |
def test_cannot_pass_inappropriate_dataset(self):
facility2 = Facility.objects.create()
with self.assertRaises(IntegrityError):
FacilityUser.objects.create(
facility=self.facility, datase | t=facility2.dataset
)
def test_cannot_change_dataset(self):
facility2 = Facility.objects.create()
self.facility_user.dataset = facility2.dataset
with self.assertRaises(IntegrityError):
self.facility_user.save()
def test_cannot_change_facility(self):
faci... |
a_level] [--output]
Synopsis:
Takes alignment data from short reads mapped to an assembly in BAM format
and the phylogeny of those short reads from the Phylosift
sequence_taxa_summary.txt file to identify and color the phylogeny of each
contig in the assembly.
Copyright:
esom_tracer2.py Color ES... | Hyer
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program i | s distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with th... |
# -*- coding: UTF-8 -*-
#
# generated by wxGlade 0.6.8 on Thu Apr 2 20:01:32 2015
#
import wx
# begin wxGlade: dependencies
# end wxGlade
# begin wxGlade: extracode
# end wxGlade
class SocketFrame(wx.Frame):
def __init__(self, *args, **kwds):
# begin wxGlade: SocketFrame.__init__
kwds["style"] ... | edroom, self.button_bedroom)
self.Bind(wx.EVT_BUTTON, self.OnBtnBack, self.button_back)
self.Bind(wx.EVT_TOGGLEBUTTON, self.OnBtnLivingroom, self.button_livingroom)
# end wxGlade
def __set_properties(self):
# begin wxGlade: SocketFrame.__set_properties
self.SetTitle("frame_1... | 3, 0, 0)
grid_sizer_2.Add(self.button_aquarium, 0, wx.ALL | wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_CENTER_VERTICAL, 5)
grid_sizer_2.Add(self.button_kitchen, 0, wx.ALL | wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_CENTER_VERTICAL, 5)
grid_sizer_2.Add(self.button_bedroom, 0, wx.ALL | wx.ALIGN_CENTER_HORI... |
from django.contrib.auth.models import User
from djblets.testing.decorators import add_fixtures
from djblets.testing.testcases import TestCase
from reviewboard.accounts.models import LocalSiteProfile
from reviewboard.reviews.models import ReviewRequest
class ProfileTests(TestCase):
"""Testing the Profile model."... | fixtures = ['test_users']
def test_is_profile_visible_with_public(self):
"""Testing User.is_profile_public with public profiles."""
user1 = User.objects.get(username='admin')
user2 = User.objects.get(username='doc')
self.assertTrue(user1.is_profile_visible(user2))
def test_is_... | iles."""
user1 = User.objects.get(username='admin')
user2 = User.objects.get(username='doc')
profile = user1.get_profile()
profile.is_private = True
profile.save()
self.assertFalse(user1.is_profile_visible(user2))
self.assertTrue(user1.is_profile_visible(user1))... |
# -*- coding: utf-8 -*-
| # Generated by Django 1.10.4 on 2017-05-30 22:20
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pattern', '0014_pattern_editnumber'),
]
operations = [
migrations.AddFiel | d(
model_name='pattern',
name='json',
field=models.TextField(null=True),
),
]
|
#
import io
import json
import sys
from django.core.management import call_command
from leaves.models import (
Harvester,
Panda,
)
from aloe import after, step
from aloe.tools import guess_types
from aloe_django.steps.models import (
test_existence,
tests_existence,
write_models,
writes_mode... | f 'name' in has | h_:
hash_['name'] += ' Panda'
return write_models(Panda, data, field)
|
"""Unit tests of authorization searches."""
import pytest
from ..utilities.general import is_never_authz, is_no_authz, uses_cataloging, uses_filesystem_only
from dlkit.abstract_osid.osid import errors
from dlkit.primordium.id.primitives import Id
from dlkit.primordium.type.primitives import Type
from dlkit.runtime ... | , 'TEST_SERVICE_CATALOGING', 'TEST_SERVICE_FILESYSTEM', 'TEST_SERVICE_MEMCACHE'])
def vault_search_class_fixture(request):
# From test_templates/resource.py::ResourceSearch::init_template
re | quest.cls.service_config = request.param
request.cls.svc_mgr = Runtime().get_service_manager(
'AUTHORIZATION',
proxy=PROXY,
implementation=request.cls.service_config)
create_form = request.cls.svc_mgr.get_vault_form_for_create([])
create_form.display_name = 'Test catalog'
create_... |
import plotly.plotly as py
import plotly.graph_objs as go
data = open('Real_Final_database_02.csv')
alldata = data.readlines()
listdata = []
for i in alldata:
listdata.append(i.strip().split(','))
type_z = ['Flood', 'Epidemic', 'Drought', 'Earthquake', 'Storm']
size_fill = [15,20,25,30,35]
fill_colors = ['#00d0f5'... | [i]:
year_x.append(int(j[1]))
death_z.append(int(j[5]))
types_y.append(type_z[i])
trace.append(g | o.Scatter(
x=year_x,
y=death_z,
name=type_z[i],
mode='markers',
marker=dict(
color = [fill_colors[i] for k in death_z],
size=[size_fill[i] for k in death_z]
)
)
)
data = trace
layout = go.Layout(
title='Total Death In Indonesia',
showlegend=True,
... |
import bala | nced
balanced.configure('ak-test-2eKlj1ZDfAcZSARMf3NMhBHywDej0avSY')
debit = balanced.Debit.fetch(' | /debits/WD5EW7vbyXlTsudIGF5AkrEA')
debit.description = 'New description for debit'
debit.meta = {
'facebook.id': '1234567890',
'anykey': 'valuegoeshere',
}
debit.save() |
# -* | - coding: utf-8 -*-
from aero.__version__ import __version_info__
__author__ = 'nickl-'
from .base import CommandProcessor as CommandProcessor
class InstallCommand(CommandProcessor):
from .base import coroutine
package = ''
adapter = ''
def wiring(self):
self.out = self.write()
self... | False):
self.package = package
self.adapter = adapter
return result
@coroutine
def res(self):
while True:
res = (yield)
if res[1] == 0:
print 'Successfully installed package: {} with {}'.format(self.package, self.adapter)
else:... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2016-12-01 17:4 | 3
from __future__ import unicode_literals
from django.db | import migrations, models
class Migration(migrations.Migration):
dependencies = [
('polls', '0003_bettoride_success'),
]
operations = [
migrations.AlterField(
model_name='bet',
name='isBetSuccessful',
field=models.NullBooleanField(default=None, verbos... |
ature, Maturity, Reference, Section, Specification, Support,
Version)
from .base import TestCase
class TestCache(TestCase):
def setUp(self):
self.cache = Cache()
self.login_user(groups=['change-resource'])
def test_browser_v1_serializer(self):
browser = self.create(Browser)
... | 1"}')
page2 = self.create(
Feature, slug='page2', parent=child2,
mdn_uri='{"en": "https://example.com/page2"}')
feature = Feature.objects.get(id=feature.id)
out = self.cache.feature_v1_serializer(feature)
self.assertEqual(out['descendant_count'], 5)
self.a... | pk, child2.pk, child21.pk, page2.pk, page1.pk])
self.assertEqual(
out['row_descendant_pks'], [child1.pk, child2.pk, child21.pk])
self.assertEqual(out['page_children_pks'], [page1.pk])
self.assertEqual(out['row_children_pks'], [child1.pk, child2.pk])
@override_settings(PAGINATE_V... |
running_pipeline['kwargs'].get('username')
backend_name = running_pipeline['backend']
requested_provider = provider.Registry.get_by_backend_name(backend_name)
try:
user = pipeline.get_authenticated_user(username, backend_name)
third_party_auth_successful = True
... | the top of the page.").format(
pl | atform_name=settings.PLATFORM_NAME
),
content_type="text/plain",
status=403
)
else:
if 'email' not in request.POST or 'password' not in request.POST:
return JsonResponse({
"success": False,
"value": _('... |
#!/usr/bin/env python
"""Tests for grr.client.client_actions.tempfiles."""
import os
import tempfile
import time
from grr.client.client_actions import tempfiles
from grr.lib import config_lib
from grr.lib import flags
from grr.lib import rdfvalue
from grr.lib import test_lib
from grr.lib import utils
class GRRTempF... | sertRaises(tempfiles.ErrorNotTempFile,
tempfiles.DeleteGRRTempFile,
fd.name)
self.assertTrue(os.path.exists(fd.name))
class DeleteGRRTempFiles(test_lib.EmptyActionTest):
"""Test DeleteGRRTempFiles client action."""
def setUp(self):
super(DeleteGRRTempFiles, sel... | efix"]
self.tempfile = utils.JoinPath(self.temp_dir,
"delete_test", filename)
self.dirname = os.path.dirname(self.tempfile)
os.makedirs(self.dirname)
config_lib.CONFIG.Set("Client.tempdir", self.dirname)
self.not_tempfile = os.path.join(self.temp_dir, "notatempfil... |
import demowlcutils
from demowlcutils import ppxml, WLC_login
from pprint import pprint as pp
f | rom jnpr.wlc import WirelessLanController as WLC
wlc = WLC(host='a', user='b', password='c')
r = wlc.RpcMake | r( target='vlan', name='Jeremy')
# you can access the following attributes, refer to the jnpr.wlc.builder
# file for more details
# r.cmd
# r.target
# r.args
|
import django
if django.VERSION >= (1, 5):
from django.conf.urls im | port patterns, url
else:
from djang | o.conf.urls.defaults import patterns, url
def simpleAction(request):
pass
urlpatterns = patterns(
'',
url(r'^simple/action/$', simpleAction, name='simpleAction'),
)
|
#--------------------------------------------------------------------------
# Software: InVesalius - Software de Reconstrucao 3D de Imagens Medicas
# Copyright: (C) 2001 Centro de Pesquisas Renato Archer
# Homepage: http://www.softwarepublico.gov.br
# Contact: invesalius@cti.gov.br
# License: GNU ... | self, -1,_("Add text annotations"))
txt_annotation.SetUnderlines(False, False, False)
txt_annotation.SetColours("BLACK", "BLACK", "BLACK")
txt_annotation.SetToolTip(tooltip)
txt_annotation.AutoBrowse(False)
txt_annotation.UpdateLink()
txt_annotation.Bind(hl.EVT_HYPERLINK_... | Image(s) for buttons
BMP_ANNOTATE = wx.Bitmap(os.path.join(const.ICON_DIR, "annotation.png"), wx.BITMAP_TYPE_PNG)
BMP_ANGLE = wx.Bitmap(os.path.join(const.ICON_DIR, "measure_angle.jpg"), wx.BITMAP_TYPE_JPEG)
BMP_DISTANCE = wx.Bitmap(os.path.join(const.ICON_DIR, "measure_line.png"), wx.BITMAP_TYP... |
##
##
# File auto-generated against equivalent DynamicSerialize Java class
from .Property import Propert | y
class Header(object):
def __init__(self, properties=None, multimap=None):
if properties is None:
self.properties = []
else:
self.pr | operties = properties
if multimap is not None:
for k, l in multimap.items():
for v in l:
self.properties.append(Property(k, v))
def getProperties(self):
return self.properties
def setProperties(self, properties):
self.properties = proper... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import unittest as ut
import numpy as np
import scipy.spatial.distance as spd
from .mock_data import Data
from ....algorithms.similarities import cosine_binary, cosine, dice, jaccard
from ....algorithms.similarities import kulsinski, russellrao, sokalsneath
MATRIX = np.a... | :
n_items = MATRIX.shape[1]
should_be = np.zeros((n_items, n_items))
for i in range(n_items):
for j in range(n_items):
should_be[i, j] = spd.russellrao(BOOL_MATRIX.T[i],
B | OOL_MATRIX.T[j])
actually_is = (1 - russellrao(self.data).toarray())
self.assertTrue(np.allclose(should_be, actually_is))
def test_sokalsneath(self):
should_be = spd.squareform(spd.pdist(BOOL_MATRIX.T, spd.sokalsneath))
actually_is = (1 - sokalsneath(self.data).toarray())
se... |
import subprocess
import os
# setup the path to extopenscad (aka implicitCAD)
cad_bin=os.path.expanduser('~/.cabal/bin/extopenscad')
# set the current input dir to this script file's dir
inp_dir = '.'
# set the output to a directory next to this script file
out_dir = './output'
# set the output file extension to .stl
... | )
# the -o option tells extopenscad to ouput a file to the subsequent path
o='-o'
try:
os.makedirs(out_dir)
except OSError as e:
# don't c | omplain if the dir already exists
if e.errno!=17:
raise e
# go through each item in the input dir
for f in os.listdir(inp_dir):
# if the item is a .escad file, process
if '.escad' in f:
# remove .escad from the filename
n=f[0:f.index('.escad')]
# join the output dir with the... |
from pycraft_minetest import *
pos = where()
chat(pos)
maze("maze1.csv")
t = turtle(obsidian)
t.forward(10)
move(3, 10, 5)
chat(where())
sphere(ice, y=-20)
circle([wool, 5], direction="horizontal")
line(gold, 0, 0, 0, 0, 50, 0)
block(iron, y=3)
blocks(wood, x=5, y=6, z=10)
size = readnumber("tell the size...... | 1)
# cube(air, 5, x, y, z, | absolute=True)
# x += 1
|
# pilas en | gine: un motor para hacer videojuegos
#
# Copyright 2010-2014 - Hugo Ruscitti
# License: LGPLv3 | (see http://www.gnu.org/licenses/lgpl.html)
#
# Website - http://www.pilas-engine.com.ar
from pilasengine.fondos import fondo
class Color(fondo.Fondo):
def __init__(self, pilas, color):
fondo.Fondo.__init__(self, pilas)
(ancho, alto) = self.pilas.obtener_area()
self.imagen = self.pilas.i... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache Licen | se, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable | law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import time
import mxnet as mx
... |
# coding=utf-8
import numpy as np
class CovalentAutocorrelation:
def __init__(self, lattice):
self.reset(lattice)
def reset(self, lattice):
self.lattice = lattice.copy()
def calculate(self, lattice):
return np.sum((lattice == self.lattice) & (lattice != 0))
class MeanSquareDis... | lattice, atombox):
proton_number = np.sum(lattice > 0)
self.snapshot = np.zeros((proton_number, 3))
self.displacement = np.zeros_like(self.snapshot)
self.snapshot = self.determine_proton_positions(atom_positions, lattice)
self.atombox = atombox
def determine_proton_positions... | lattice):
proton_positions = np.zeros_like(self.snapshot)
proton_labels = lattice[lattice > 0]
site_idx, = np.where(lattice)
proton_positions[proton_labels - 1] = atom_positions[site_idx]
return proton_positions
def update_proton_positions(self, atom_positions, lattice):
... |
#!/usr/bin/env python
# Little script to make HISTORY.rst more easy to format properly, lots TODO
# pull message down and embed, use arg parse, handle multiple, etc...
import os
import sys
try:
import requests
except ImportError:
requests = None
import urllib.parse
import textwrap
PROJECT_DIRECTORY = os.path.j... | history_path = os.path.join(PROJECT_DIRECTORY, "HISTORY.rst")
history = open(history_path, "r", encoding="utf-8").read()
def extend(from_str, line):
from_str += "\n"
return history.replace(from_str, from_str + line + "\n")
ident = argv[1]
message = ""
if len(argv) > 2:
... | .startswith("issue")):
api_url = urllib.parse.urljoin(PROJECT_API, "commits/%s" % ident)
req = requests.get(api_url).json()
commit = req["commit"]
message = commit["message"]
message = get_first_sentence(message)
elif requests is not None and ident.startswith("pr"):
p... |
mile:', ':GAKUEngine:', ':pistol:', ':relieved:',
':wink:', ':grimacing:', ':rainbow_solid:', ':blowfish:',
':kissing_smiling_eyes:', ':tropical_drink:', ':face_with_medical_mask:',
':pill:', ':ruby:', ':cactus:', ':smiley_stuck_out_tongue_winking_eye:',
':boar:', ':smile:', ':face_with_tear_of_joy:', '... | :
return EMOJIS
if files:
return [':{}:'.format(fn[:-4]) for fn in files if fn.endswith('.png')]
else:
return EMOJIS
def url_for_emoji(emoji): |
return '/static/emoji/%s.png' % emoji[1:-1]
def all_line_emojis():
return sum([EMOJIONE, TWEMOJI], [])
RE_EMOJI = re.compile(r'(' + '|'.join(
[re.escape(x) for x in all_emojis |
#
# FBrowserBase.py -- Base class for file browser plugin for fits viewer
#
# Eric Jeschke (eric@naoj.org)
#
# Copyright (c) Eric R. Jeschke. All rights reserved.
# This is open-source software licensed under a BSD license.
# Please see the file LICENSE.txt for details.
#
import os, glob
import stat, time
from ging... | pose gpmon!
rsobj = self.fv.gpmon.getPlugin('Thumbs')
self.fv.nongui_do(rsobj.make_thumbs, chname, filelist)
def start(self):
self.win = None
self.browse(self.curpath)
def pause(self):
pass
def resume(self):
pass
def stop(self):
pass
... | elf):
return True
#END
|
the
# License for the specific language governing permissions and limitations
# under the License.
from cinder import exception
from cinder.openstack.common import log as logging
from cinder import test
from cinder.volume.drivers.solidfire import SolidFire
LOG = logging.getLogger(__name__)
class SolidFireVolu... | 0c9a66',
'volume_type_id': 'fast'}
sfv = SolidFire()
model_update = sfv.create_volume(testvol)
def test_create_volume(self):
self.stubs.Set(SolidFire, '_issue_api_request',
self.fake_issue_api_request)
testvol = {'project_id': 'testprjid',
... | 'volume_type_id': None}
sfv = SolidFire()
model_update = sfv.create_volume(testvol)
def test_create_volume_with_qos(self):
preset_qos = {}
preset_qos['qos'] = 'fast'
self.stubs.Set(SolidFire, '_issue_api_request',
self.fake_issue_api_request)
... |
# Generated by Django 2.2.13 on 2020-10-29 21:34
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("server", "0017_merge_20181217_1829")]
operations = [
migrations.AlterField(
model_name="computer",
name="serial | ",
| field=models.CharField(
max_length=200, unique=True, verbose_name="Serial Number"
),
),
migrations.AlterField(
model_name="secret",
name="secret_type",
field=models.CharField(
choices=[
("recove... |
the TP-Link router is up to date.
Return boolean if scanning successful.
"""
_LOGGER.info("Loading wireless clients...")
url = 'http://{}/userRpm/WlanStationRpm.htm'.format(self.host)
referer = 'http://{}'.format(self.host)
page = requests.get(
url, auth=(s... | date.
Return boolean if scanning successful.
"""
if (self.stok == '') or | (self.sysauth == ''):
self._get_auth_tokens()
_LOGGER.info("Loading wireless clients...")
url = ('http://{}/cgi-bin/luci/;stok={}/admin/wireless?'
'form=statistics').format(self.host, self.stok)
referer = 'http://{}/webpages/index.html'.format(self.host)
res... |
"""
Tests are performed against csr1000v-universalk9.03.15.00.S.155-2.S-std.
"""
import unittest
from iosxe.iosxe import IOSXE
from iosxe.exceptions import AuthError
node = '172.16.92.134'
username = 'cisco'
password = 'cisco'
port = 55443
class TestIOSXE(unittest.TestCase):
def setUp(self):
self.xe = ... | self.assertEqual(self.xe.url_base, 'https://{0}:{1}/api/v1'.format(node, port))
| def test_token_uri(self):
self.assertEqual(self.xe.token_uri, '/auth/token-services')
def test_save_config_success(self):
resp = self.xe.save_config()
self.assertEqual(204, resp.status_code)
|
import glob
import logging
import os
import shutil
from threading import Thread, Lock
class ClientFiles:
"""Processes the clients files to be moved etc"""
def __init__(self, settings, clients):
self.settings = settings
self.clients = clients
# Logging
self._logger = logging.... | to be moved
:param client: Client to have file list generated
:return: Client files if any, otherwise returns None
""" |
# print("Checking " + client + " for files")
client_files = []
for file_type in self.settings.file_types:
client_files.extend(glob.glob(self.file_path.format(client) +
file_type))
if len(client_files) > 0:
client_files ... |
specifiers declarator
"""
spec = p[1]
if not spec['type']:
spec['type'] = [c_ast.IdentifierType(['int'],
coord=self._coord(p.lineno(1)))]
p[0] = self._build_declarations(
spec=spec,
decls=[dict(decl=p[2])])[0]
def p_parameter_decla... | """ initializer_list : designation_opt initializer
| | initializer_list COMMA designation_opt initializer
"""
if len(p) == 3: # single initializer
init = p[2] if p[1] is None else c_ast.NamedInitializer(p[1], p[2])
p[0] = c_ast.InitList([init], p[2].coord)
else:
init = p[4] if p[3]... |
'''
Created on Jan 30, 2011
@author: mkiyer
chimerascan: chimeric transcript discovery using RNA-seq
Copyright (C) 2011 Matthew Iyer
This program is free softwar | e: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the ... | eceived a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
'''
import collections
import logging
from nominate_chimeras import Chimera, parse_discordant_reads
from find_discordant_reads import DiscordantType
def to_fastq(mate, qname, seq, qual):
return "... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from itertools import groupby
from time import time
from functools import partial
import re
import django
django.setup()
from django.db import transaction
from clldutils.dsv import reader
from clldutils.text import split_text
from clldutils.path import Path
fro... | load_society_relations
from loader.phylogenies import load_phylogenies
from loader.variables import load_vars
from loader.values import load_data
from loader.sources import load_references
from loader.glottocode import loa | d_languages
comma_split = partial(split_text, separators=',', strip=True, brackets={})
semicolon_split = partial(split_text, separators=';', strip=True, brackets={})
def valid_enum_member(choices, instance, attribute, value):
if value not in choices:
raise ValueError(value)
@attr.s
class Variable(objec... |
#
# Copyright 2015 by Justin MacCallum, Alberto Perez, Ken Dill
# All rights reserved
#
import numpy as np
import math
class ProteinBase(object):
'''
Base class for other Protein classes.
Provides functionality for translation/rotation and adding H-bonds.
'''
def __init__(self):
self._t... | res_index_i: one-based index of residue i
:param res_index_j: one-based index of residue j
:param atom_name_i: string name of i
:param atom_name_j: string name of j
:param bond_type: string specifying the "S", "D","T"... bond
.. note::
| indexing starts from one and the residue numbering from the PDB file is ignored.
'''
self._general_bond.append((res_index_i, res_index_j,atom_name_i,atom_name_j,bond_type))
def add_disulfide(self, res_index_i, res_index_j):
'''
Add a disulfide bond.
:param res_index... |
"""
Django settings for gnucash_explorer project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR... | acking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'gnucash_explorer.urls'
WSGI_APPLICATION = 'gnucash_explorer.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BAS... | USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/
STATIC_URL = '/static/'
try:
from gnucash_explorer.local_settings import *
except ImportError as e:
print('You should set up your local_settings.py')
|
('id'))
return {'vsa': _vsa_view(context, vsa, True, instances)}
def delete(self, req, id):
"""Delete a VSA."""
context = req.environ['nova.context']
authorize(context)
LOG.audit(_("Delete VSA with id: %s"), id, context=context)
try:
self.vsa_api.delete... | self.direction)
if own_vsa_id != vsa_id:
LOG.error(_("%(obj)s with ID %(id)s belongs to VSA %(own_vsa_id)s"\
" and not to VSA %(vsa_id)s."), locals())
raise exception.Invalid()
def _items(self, req, vsa_id, details):
"""Return ... | uthorize(context)
vols = self.volume_api.get_all(context,
search_opts={'metadata': {self.direction: str(vsa_id)}})
limited_list = common.limited(vols, req)
res = [self._translation(context, vol, vsa_id, details) \
for vol in limited_list]
return {self.ob... |
# coding=utf-8
# Copyright 2022 The Google Research 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
#
# Unless required by applicab... | ymmetric(tensor, padding):
"""Symmetric pad a 2D Tensor."""
if tensor.shape.ndims != 2:
raise ValueError(f'tensor must be rank 2: {tensor.shape}')
t_len = | tf.shape(tensor)[1]
return tf.cond(
padding > t_len,
lambda: _repeat_n_times_with_extra(tensor, padding, t_len),
lambda: tf.pad(tensor, [(0, 0), (0, padding)], mode='SYMMETRIC'))
def _repeat_n_times_with_extra(tensor, padding,
t_len):
"""Pad symmetric longer than ... |
# Copyright 2013 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | property_name, self._ParseType(property_type)))
additional = None
additional_properties = discovery_object_type.get('additionalProperties')
if additional_properties is not None:
additional = self._ParseType(additional_properties)
return properties, additional
def _ParseSchemas(self, discove... | y_schemas.iteritems():
self._ParseSchema(discovery_schema)
def _ParseMethods(self, discovery_methods):
for method_name, discovery_method in discovery_methods.iteritems():
self._ParseMethod(method_name, discovery_method)
def _ParseParameter(self, parameter_name, parameter_type):
return mock_api... |
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). |
from . import res_company
# WARNING: Order of imports matters on this module, so don't put res_company
# below the other modules since it will lead to a missing column error when
# the module is initialized for the first time since there are fields with
# default values wich refer to this new res.company field.
from ... | rom . import event_mail
from . import event_type
from . import res_config_settings
|
from contextional import GCM
with GCM("A") as A:
@GCM.add_setup
def setUp():
pass
@GCM.add_teardown
def tearDown():
pass
with GCM.add_group("B"):
@GCM.add_setup
def setUp():
pass
@GCM.add_test("some test")
def test(case):
... | " B",
" # setup w/ description ",
" some test ... ok",
" # teardown (1/2) ERROR",
"A",
" # setup w/ description ",
" B",
" # setup w/ description ",
" some test ... ok",
" # teardown (1/2) ERROR",
"A",
" # setup w/ description ",
" B",
" # se... | " # teardown (1/2) ERROR",
"A",
" # setup w/ description ",
" B",
" # setup w/ description ",
" some test ... ok",
" # teardown w/ description ",
" # teardown (2/3) ERROR",
" # teardown w/ description ",
"A",
" # setup w/ description ",
" B",
" # se... |
from django.conf.urls import include, url
from django.contrib import admin
from Poller import views
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^(?P<pk>\d+)/$', views.Deta | ilView.as_view(), name='detail'),
url(r'^(?P<pk>\d+)/results/$', views.ResultsView.as_view(), name='results'),
url(r'^(?P<question_id>\d+) | /vote/$', views.vote, name='vote'),
]
|
#!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4 fileencoding=utf-8
import json
from django.conf import settings
from django.core.management import BaseCommand
from django.utils import timezone
from django.utils.dateparse import parse_datetime
from django.utils.translation import ugettext_lazy
from onadata.apps.log... | = ugettext_lazy("Fixes deleted instances by syncing "
"deleted items from mongo.")
| def handle(self, *args, **kwargs):
# Reset all sql deletes to None
Instance.objects.exclude(
deleted_at=None, xform__downloadable=True).update(deleted_at=None)
# Get all mongo deletes
query = '{"$and": [{"_deleted_at": {"$exists": true}}, ' \
'{"_deleted_at":... |
port ZCA_Dataset
from pylearn2.utils import serial
if __name__ == "__main__":
rng = np.random.RandomState(1234)
# data augmentation
zero_pad = 0
affine_transform_a = 0
affine_transform_b = 0
horizontal_flip = False
# batch
# keep a factor of 10000 i... | train_set.X = train_set.X.reshape(45000,3,32,32)
valid_set.X = valid_set.X.reshape(5000,3,32,32)
test_set.X = test_set.X.reshape(10000,3,32,32)
# flatten targets
train_set.y = np.hstack(train_set.y)
valid_set.y = np.hstack(valid_set.y)
test_set.y = np.hstack(test_set.y)
# ... | t32(np.eye(10)[valid_set.y])
test_set.y = np.float32(np.eye(10)[test_set.y])
# for hinge loss
train_set.y = 2* train_set.y - 1.
valid_set.y = 2* valid_set.y - 1.
test_set.y = 2* test_set.y - 1.
print 'Creating the model'
class DeepCNN(Network):
def __init_... |
#
# BTZen - library to asynchronously access Bluetooth devices.
#
# Copyright (C) 2015-2021 by Artur Wroblewski <wrobell@riseup.net>
#
# 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 vers... | 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, see <http://www.gnu.org/licenses/>.
#
"""
Bluetooth services implemented by BlueZ pr | otocol stack.
"""
from .data import Make, ServiceType, Trigger, TriggerCondition
from .service import ServiceInterface, register_service
from .util import to_uuid
register_service(
Make.STANDARD,
ServiceType.BATTERY_LEVEL,
ServiceInterface(
to_uuid(0x180f),
'org.bluez.Battery1',
'P... |
p2_test_server.py']
def cloud_to_prod_env(self):
return {}
def global_env(self):
return {}
def unimplemented_test_cases(self):
return _TEST_CASES
def unimplemented_test_cases_server(self):
return _TEST_CASES
def __str__(self):
return 'http2'
class Http2Client:
"""Represents the HTT... | urn {}
def unimplemented_test_cases(self):
return _SKIP_COMPRESSION
def unimplemented_test_cases_server(self):
return []
def __str__(self):
return 'php'
class PHP7Language:
def __init__(self):
self.clie | nt_cwd = None
self.safename = str(self)
def client_cmd(self, args):
return ['src/php/bin/interop_client.sh'] + args
def cloud_to_prod_env(self):
return {}
def global_env(self):
return {}
def unimplemented_test_cases(self):
return _SKIP_COMPRESSION
def unimplemented_test_cases_server(s... |
# coding: utf-8
from __future__ import absolute_import
import flask
import auth
import model
import util
from main import app
yahoo_config = dict(
access_token_url='https://api.login.yahoo.com/oauth/v2/get_token',
authorize_url='https://api.login.yahoo.com/oauth/v2/request_auth',
base_url='https://query.yaho... | ')
return flask.redirect(util.get_next_url())
flask.session['oauth_token'] = (
response['oauth_token'],
response['oauth_token_secret'],
)
fields = 'guid, emails, familyName, givenName, nickname'
me = yahoo.get(
'/v1/yql',
data={
'format': 'json',
'q': 'select %s from social.pro... | id = me;' % fields,
'realm': 'yahooapis.com',
},
)
user_db = retrieve_user_from_yahoo(me.data['query']['results']['profile'])
return auth.signin_user_db(user_db)
@yahoo.tokengetter
def get_yahoo_oauth_token():
return flask.session.get('oauth_token')
@app.route('/signin/yahoo/')
def signin_yahoo():... |
#!/usr/bin/env python -tt
# encoding: utf-8
#
"""Use a descriptive macro instead of assert(false);"""
error_msg = 'Use NEVER_HERE() from base/macros.h here.'
regexp = r"""assert *\( *(0|false) | *\)"""
forbidden = [
'assert(0)',
'assert(fals | e)',
]
allowed = [
'NEVER_HERE()',
]
|
# -*- coding: utf-8 -*-
#
# Copyright (C) 2012-2016 Ben Kurtovic <ben.kurtovic@gmail.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation ... | d(self.__unicode__())
def __contains__(self, item):
return str(item) in self.__unicode__()
def __getattr__(self, attr):
return getattr(self.__unicode__(), attr)
if py3k:
maketrans = str.maketrans # Static method can't rely on __getattr__
if py26:
@inheritdoc
... | ding = getdefaultencoding()
if errors is not None:
return self.__unicode__().encode(encoding, errors)
return self.__unicode__().encode(encoding)
del inheritdoc
|
#############
# Python types and their operations
##########################################################################
class Callable:
class invoke:
def process(self, context):
context.add_opcodes(
JavaOpcodes.INVOKEINTERFACE(
'org/python/Callable',
... | args=['Lorg/python/Object;'],
returns='Lorg/python/Object;'
),
)
class set_item:
def process(self, context):
context.add_opcodes(
JavaOpcodes.INVOKEINTERFACE(
'org/python/Object',
'_... | eturns='V'
),
)
class del_item:
def process(self, context):
context.add_opcodes(
JavaOpcodes.INVOKEINTERFACE(
'org/python/Object',
'__delitem__',
args=['Lorg/python/Object;'],
... |
.. [1] Jamil, M. & Yang, X.-S. A Literature Survey of Benchmark Functions
For Global Optimization Problems Int. Journal of Mathematical Modelling
and Numerical Optimisation, 2013, 4, 150-194.
TODO: equation needs to be fixed up in the docstring. Jamil#19
"""
def __init__(self, dimensions=2):
... | problem defined as follows:
.. math::
f_{\text{Bukin02}}(x) = 100 (x_2^2 - 0.01x_1^2 + 1)
+ 0.01(x_1 + 10)^2
with :math:`x_1 \in [-15, -5], x_2 \in [-3, 3]`
*Global optimum*: :math:`f(x) = -124.75` for :math:`x = [-15, 0]`
.. [1] Jamil, M. & Yang, X.-S. A Literature Survey of Benc... | ation Problems Int. Journal of Mathematical Modelling
and Numerical Optimisation, 2013, 4, 150-194.
TODO: I think that Gavana and Jamil are wrong on this function. In both
sources the x[1] term is not squared. As such there will be a minimum at
the smallest value of x[1].
"""
def __init__(self... |
#!/usr/bin/python
import os
import signal
import struct
import sys
import time
ALLOWED_INTERFACES = [ "cpu_dma_latency", "network_latency", "ne | twork_throughput" ]
def read_pmqos(name):
filename = "/dev/%s" % name
old = open(filename)
old_value = struct.unpack("i", old.read())[0]
print "PMQOS value for %s is %d"%(name, old_value)
if __name__=="__main__":
if len(sys.argv) < 2:
print "Must specify what to read"
sys.exit(1)
read = sys.... | qos(read)
|
tainerTest()
self.element = MockGuiWidget("")
self.setting_presenter = MockSettingPresenter(self.settings['file_extension'], self.element)
self.presenters = MockSettingPresenterContainer()
self.presenters.add(self.setting_presenter)
self.presenters.add(MockSettingPresenter(self.settings['overwr... | ror it could be")
with self.assertRaises(settings.SettingStreamWriteError):
self.stream.write(self.settings)
def test_read_ioerror_oserror(self, mock_file):
mock_file.side_effect = I | OError("File not found or whatever other I/O error it could be")
with self.assertRaises(settings.SettingStreamReadError):
self.stream.read(self.settings)
mock_file.side_effect = OSError("Permission denied or whatever other OS error it could be")
with self.assertRaises(settings.SettingStreamReadEr... |
_methods.classes.TH1
from iqtools.iqbase import IQBase
from iqtools.tcapdata import TCAPData
from iqtools.tdmsdata import TDMSData
from iqtools.bindata import BINData
from iqtools.iqtdata import IQTData
from iqtools.tiqdata import TIQData
from iqtools.csvdata import CSVData
from iqtools.wavdata import WAVData
from iqt... | urn '{}{}{}{}'.format(flag, int(abs(value) / 10 ** num * 10 ** decimal_place) / 10 ** decimal_place, mult,
unit)
def get_cplx_spectrogram(x, nframes, lframes):
sig = np.reshap | e(x, (nframes, lframes))
zz = np.fft.fft(sig, axis=1)
return zz
def get_inv_cplx_spectrogram(zz, nframes, lframes):
inv_zz = np.fft.ifft(zz, axis=1)
inv_zz = np.reshape(inv_zz, (1, nframes * lframes))[0]
return inv_zz
def get_root_th2d(xx, yy, zz, name='', title=''):
from ROOT import TH2D
... |
return self._wrap_output(output=output,
index=self.grouper.result_index,
names=names)
def _wrap_transformed_output(self, output, names=None):
return self._wrap_output(output=output,
index=self.obj.index... | if ids[0] == -1:
res = out[1:]
| idx = idx[np.flatnonzero(idx)]
else:
res = out
else:
res = out[1:]
ri = self.grouper.result_index
# we might have duplications among the bins
if len(res) != len(ri):
res, out = np.zeros(len(ri), dtype=out.dtype), res
... |
import json, logging
class Farm:
"""
Main class holding the whole farm.
"""
def __in | it__(self,json_file):
"""
"""
# load in json file
data = json.loads(open(json_file,'r').read())
# Make sure required data is in the json file
required_attr_list = ["latitude","longitude"]
for a in required_attr_list:
if a not in data.keys():
... | err)
# parse resulting json
for k in data.keys():
self.__setattr__("_{}".format(k),data[k])
# Get the utc offset for our current time
self._utc_offset = datetime.now() - datetime.utcnow()
# get the current sunrise, sunset etc.
self._get_suntimes()
|
c_unknown = mutagen.File(aac_files["unknown"])
id3_t1 = mutagen.File(id3_files["t1"])
id3_picard = mutagen.File(id3_files["picard"])
id3_unknown = mutagen.File(id3_files["unknown"])
def test_artist_name(self):
vorbis_tag_type = self.vorbis.album_artist
aac_tag_type = self.aac.a... | date")
def test_title(self):
self.write_test(self.format.title, "title")
def test_artist(self):
self.write_test(self.format.artist, "artist")
def test_disc_num(self):
self.wri | te_test(self.format.disc_num, "discnumber")
def test_track_num(self):
self.write_test(self.format.track_num, "tracknumber")
def write_test(self, tag_builder, tag_name):
correct_tag = self.tags.get(tag_name)
tag = tag_builder(self.meta)
self.check_ta... |
) #uni069C.medi
glyphs.append(0x0118) #uni0672.fina
glyphs.append(0x0074) #beh_dotless_alt.init
glyphs.append(0x0290) #uni0766.init
glyphs.append(0x012A) #uni067B.medi
glyphs.append(0x01DD) #uni06B9.init
glyphs.append(0x0172) #uni069A.fina
glyphs.append(0x0... | hs.append(0x0222) #uni060F
glyphs.append(0x0221) #uni060E
glyphs.append(0x0211) #uni06440673.isol
glyphs.append(0x024E) #uni0754.init
glyphs.append(0x024F) #uni0754.medi
glyphs.append(0x0299) #uni0768.medi
glyphs.append(0x01B8) #uni06B0.fina
glyphs.append(0... | hs.append(0x010B) #uni0651064B
glyphs.append(0x010D) #uni0651064F
glyphs.append(0x010C) #uni0651064E
glyphs.append(0x0150) #uni0687.fina
glyphs.append(0x0050) #uni06BE
glyphs.append(0x01E5) #uni06BD
glyphs.append(0x01B6) #uni06AE.medi
glyphs.append(0x0059) ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2016-2018, Eric Jacob <erjac77@gmail.com>
#
# 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/LICENS... | source_mask:
description:
- Specifies a source IP address mask for the system to use when evaluating traffic flow.
source_port:
description:
- Specifies a source port | for the system to use when evaluating traffic flow.
default: 0
state:
description:
- Specifies the state of the component on the BIG-IP system.
default: present
choices: ['absent', 'present']
requirements:
- BIG-IP >= 12.0
- ansible-common-f5
- f5-sdk
'''
EXA... |
# -*- coding: utf-8 -*-
from flask_testing import TestCase
import mock
import journalist
from utils import db_helper, env
from db import (Journalist, Submission, Reply, get_one_or_else,
LoginThrottledException)
class TestDatabase(TestCase):
def create_app(self):
return journalist.app
... | esentation(self):
test_journalist, _ = db_helper.init_journalist()
test_journalist.__repr__()
def test_source_string_representation(self):
test_source, _ = db_helper.init_source()
test_source.__repr__()
def test_throttle_login(self):
journalist, _ = db_helper.init_journ... |
for _ in range(Journalist._MAX_LOGIN_ATTEMPTS_PER_PERIOD):
Journalist.throttle_login(journalist)
with self.assertRaises(LoginThrottledException):
Journalist.throttle_login(journalist)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Fungiform
~~~~~~~~~
A form handling system that previously was used for Pocoo's Zine
and Plurk's Solace software. Unbundled into a separate library that
| is framework independent.
This is still a preview release. Check the source for more information.
| :copyright: (c) 2010 by Armin Ronacher, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name = 'Fungiform',
version = '0.2',
url = 'http://github.com/mitsuhiko/fungifor... |
# -*- coding: utf-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "Li... | ram prefix: the main keyword for configuration of this space
:type prefix: str
:param id: the unique identifier of the related space (optional)
:type id: str
:param db: name of the file that contains Sqlite data (optional)
:type db: str
Example::
store = S... | ``sqlite`` in the context of this bot.
"""
assert prefix
self.prefix = prefix
self.id = id if id else '*id'
if db:
self.context.set(self.prefix+'.db', db)
def check(self):
"""
Checks configuration
"""
self.context.check(self.pref... |
from xmediusmailrelayserver impor | t * | |
import pytest
import responses
from urlobject import URLObject
from flask import Flask
from flask_dance.contrib.reddit import make_reddit_blueprint, reddit
from flask_dance.consumer import OAuth2ConsumerBlueprint
from flask_dance.consumer.storage import MemoryStorage
@pytest.fixture
def make_app():
"A callable to... | e an exception
with pytest.raises(RuntimeError):
reddit.get("https://google.com")
# inside of a request context, `reddit` should be a | proxy to the correct
# blueprint session
with app1.test_request_context("/"):
app1.preprocess_request()
reddit.get("https://google.com")
request = responses.calls[0].request
assert request.headers["Authorization"] == "Bearer app1"
with app2.test_request_context("/"):
... |
0,
"Colonel***": 540000,
"General": 660000,
"General*": 800000,
"General**": 950000,
"General***": 1140000,
"Field Marshal": 1350000,
"Field Marshal*": 1600000,
"Field Marshal**": 1875000,
"Field Marshal***": 218... | ctualizar y guardar los datos
self.run = True
# Se paraleliza la carga de datos en un hilo nuevo, el cual es demonio del invocador en caso de "muerte prematura"
th = threading.Thread(target=self.data_loader)
th.daemon = True
th.start()
# Metodo invocador, carga datos y crea... | o desde constructor
def data_loader(self):
self.load_data()
self.data_saver_th = threading.Thread(target=self.data_saver)
self.data_saver_th.daemon = True
self.data_saver_th.start()
self.data_updater_th = threading.Thread(target=self.data_updater)
self.data_updater_... |
"""
===========================
Orthogonal Matching Pursuit
===========================
Using orthogonal matching pursuit for recovering a sparse signal from a noisy
measurement encoded with a dictionary
"""
import matplotlib.pyplot as plt
import numpy as np
from sklearn.linear_model import OrthogonalMatchingPursuit... | ed_signal
n_components, n_features = 512, 100
n_nonzero_coefs = 17
# generate the data
# y = Xw
# |x|_0 = n_nonzero_coefs
y, X, w = make_sparse_coded_signal(
n_samples=1,
n_components= | n_components,
n_features=n_features,
n_nonzero_coefs=n_nonzero_coefs,
random_state=0,
)
(idx,) = w.nonzero()
# distort the clean signal
y_noisy = y + 0.05 * np.random.randn(len(y))
# plot the sparse signal
plt.figure(figsize=(7, 7))
plt.subplot(4, 1, 1)
plt.xlim(0, 512)
plt.title("Sparse signal")
plt.ste... |
import logging
from django.contrib import messages
from django.contrib.auth import authenticate
from django.core.urlresolvers import reverse
from django.http.response import Http404, HttpResponseRedirect
from django.shortcuts import render, redirect, render_to_response
# Create your views here.
from django.template.co... | {'form': form,'callback':callback}
# context = {}
return render_to_response('ui/login.html', {'form': form}, context_instance=RequestContext(request))
def auth(request):
callback = request.GET.get('callback', '')
token = request.GET.get('token', '')
if not callback.endswith("/"):
... | quest.method == 'POST':
token = Token.objects.get(key=token)
app = App.objects.get(callback=callback)
crowduser = token.user.crowduser
crowduser.auth_apps.add(app)
crowduser.save()
redirect_to = callback+"?token="+token.key+"&id="+crowduser.user.pk
return HttpResp... |
"""Attachment utils."""
from pathlib import Path
from uuid import uuid4
from blobstash.docstore.error import DocStoreError
from blobstash.filetree import FileTreeClient
_FILETREE_POINTER_FMT = "@filetree/ref:{}"
_FILETREE_ATTACHMENT_FS_PREFIX = "_filetree:docstore"
class Attachment:
"""An attachment represents ... | leobj, content_type)
pointer = _FILETREE_POINTER_FMT.format(node.ref)
return Attachment(pointer, node)
def fget_attachment(client, attachment):
"""Returns a fileobj (that needs to be closed) with the content off the attachment."""
node = attachment.node
if node.is_dir():
raise DocStoreErro... | d"
)
return FileTreeClient(client=client).fget_node(node)
def get_attachment(client, attachment, path):
node = attachment.node
if node.is_file():
FileTreeClient(client=client).get_node(node, path)
return
FileTreeClient(client=client).fs(
ref=node.ref, prefix=_FILETREE... |
#! /usr/bin/python
import MDAnalysis
import sys
from pylab import *
my_traj = sys.argv[1]
myTitle = sys.argv[2]
u = MDAnalysis.Universe(my_traj,my_traj)
OH = u.selectAtoms("segid B and resid 18 and name HO")
xArr = []
yArr = []
zArr = []
data = []
for ts in u.trajectory:
xArr.append(OH.coordinates()[0,0])
... | malise(myArray)
data.append(newArray)
boxplot(data)
xticks([1,2,3],["x","y","z"])
ylim(-0.4,0.4)
title("%s_HO"%myTitle)
savefig("%s_HO. | png"%myTitle)
|
from flask import Flask | , render_template, request, jso | nify, session, redirect, escape, url_for
import bcrypt
class ServerError(Exception):pass
def loginForm(db, form):
error = None
try:
username = form['username']
cur = db.query("SELECT COUNT(1) FROM users WHERE user = %s", [username])
if not cur.fetchone()[0]:
raise ServerError('Incorrect username / passwo... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import versatileimagefield.fields
import jsonfield.fields
from decimal import Decimal
import saleor.product.models.fields
import django.core.validators
import django_prices.models
import satchless.item
class Migr... | n | ame='Stock',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('location', models.CharField(max_length=100, verbose_name='location')),
('quantity', models.IntegerField(default=Decimal('1'), verbose_nam... |
TION_EXCEPTION = '09000'
# Class 0A - Feature Not Supported
FEATURE_NOT_SUPPORTED = '0A000'
# Class 0B - Invalid Transaction Initiation
INVALID_TRANSACTION_INITIATION = '0B000'
# Class 0F - Locator Exception
LOCATOR_EXCEPTION = '0F000'
INVALID_LOCATOR_SPECIFICATION = '0F001'
# Class 0L - Invalid Grantor
INVALID_GRA... | CAPE_OCTET = '2200D'
ZERO_LENGTH_CHARACTER_STRING = '2200F'
MOST_SPECIFIC_TYPE_MISMATCH = '2200G'
NOT_AN_XML_DOCUMEN | T = '2200L'
INVALID_XML_DOCUMENT = '2200M'
INVALID_XML_CONTENT = '2200N'
INVALID_XML_COMMENT = '2200S'
INVALID_XML_PROCESSING_INSTRUCTION = '2200T'
INVALID_INDICATOR_PARAMETER_VALUE = '22010'
SUBSTRING_ERROR = '22011'
DIVISION_BY_ZERO = '22012'
INVALID_ARGUMENT_FOR_NTILE_FUNCTION = '22014'
INTERVAL_FIELD_OVERFLOW = '22... |
"""Autocomplete fields for QuerySetSequence choices."""
from dal_contenttypes.fields import (
ContentTypeModelMultipleFieldMixin,
GenericModelMixin,
)
from django import forms
from django.contrib.contenttypes.models import ContentType
from queryset_sequence import QuerySetSequence
class QuerySetSequenceFie... | -%s' % (content_type_id, object_ids[0])
)
)
querysets.append(queryset.filter(pk__in=object_ids))
return QuerySetSequence(*querysets)
def _check_values(self, value):
valu | es = self._deduplicate_values(value)
pks = self._get_ctype_objects(values)
queryset = self._get_queryset_for_pks(pks)
fetched_values = [
'%s-%s' % (ContentType.objects.get_for_model(o).pk, o.pk)
for o in queryset
]
for val in value:
if val no... |
# -*- coding: utf-8 -*-
"""This module contains custom roles to use in Sphinx.
"""
from docutils import nodes
def setup(app):
"""Install the extension.
Parameter | s:
app: Sphinx application context.
"""
app.add_role('arts', arts_docserver_role)
def arts_docserver_role(name, rawtext, text, lineno, inliner, options=None,
content=None):
"""Create a link to ARTS do | cserver.
Parameters:
name (str): The role name used in the document.
rawtext (str): The entire markup snippet, with role.
text (str): The text marked with the role.
lineno (str): The line number where rawtext appears in the input.
inliner (str): The inliner instance that cal... |
--------------------------------------------------------------------
"""
Reference GENI GCF Clearinghouse. Uses SFA Certificate and credential objects.
Run from gcf-ch.py
Will produce signed user credentials from a GID, return a
list of aggregates read from a config file, and create a new Slice Credential.
"""
import... | en=None, slice_len=None, config=None):
"""Run the clearinghouse server."""
# ca_certs is a dir of several certificates for peering
# If not supplied just use the certfile as the only trusted root
self.keyfile = keyfile
self.certfile = certfile
self.config = config
... | # Error check the keyfile, certfile all exist
if keyfile is None or not os.path.isfile(os.path.expanduser(keyfile)):
raise Exception("Missing CH key file %s" % keyfile)
if certfile is None or not os.path.isfile(os.path.expanduser(certfile)):
raise Exception("Missing CH cert f... |
class ParserError(Exception):
pass
class Sentence(object):
def __init__(self, subject, verb, obj):
# We take ('noun','thing') tuples and convert them.
self.subject = subject[1]
self.verb = verb[1]
self.object = obj[1]
def peek(word_list):
if word_list:
word = word_... | st, 'noun')
elif next_word == 'verb':
return ('noun', 'player')
else:
| raise ParserError("Expected a verb next.")
def parse_sentence(word_list):
subj = parse_subject(word_list)
verb = parse_verb(word_list)
obj = parse_object(word_list)
return Sentence(subj, verb, obj)
|
xmako should be
# integrated better with Django's rendering and event system.
response = render_to_response(path, context)
response.mako_context = context
response.mako_template = path
return response
@ddt.ddt
class TestInstructorDashboard(ModuleStoreTestCase, LoginEnrollmentTestCase, XssTestMixin... | Down | load tab only shows up for certain roles
"""
download_section = '<li class="nav-item"><button type="button" class="btn-link data_download" '\
'data-section="data_download">Data Download</button></li>'
user = UserFactory.create(is_staff=access_role == 'global_staff')
... |
# Copyright 2012 Hewlett-Packard Development Company, L.P.
#
# 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... | g':
{'description': 'Zuul provided key to link builds with Gerrit'
' events (deprecated use ZUUL_UUID instead)',
'name': 'UUID'}},
{'string':
{'description': 'Zuul pipeline triggering this job',
'name': 'ZUUL_PIPELINE'}},
{'string':
{'description': 'Zuul provid... | oject',
'name': 'ZUUL_PROJECT'}},
{'string':
{'description': 'Zuul provided branch name',
'name': 'GERRIT_BRANCH'}},
{'string':
{'description': 'Branch name of triggering change',
'name': 'ZUUL_BRANCH'}},
{'string':
{'description': 'Zuul provided list of de... |
from django.conf.urls.defaults import *
urlpatterns = patte | rns('mmda.tags.views',
url(r'^(?P<tag_id>.+?)/$', 'show | _tag', name='show-tag')
)
|
ns import \
ContinuousHazardPopulationMetadata
from safe.impact_functions.bases.continuous_rh_continuous_re import \
ContinuousRHContinuousRE
from safe.impact_functions.impact_function_manager import ImpactFunctionManager
from safe.impact_functions.core import (
evacuated_population_needs,
population_ro... | sing data was '
'carried through to the impact layer.' | ),
tr('`No data` values in the impact layer were treated as 0 '
'when counting the affected or total population.')
])
total_needs = evacuated_population_needs(
total_impact, minimum_needs)
for frequency, needs in total_needs.items():
... |
c.save()
dev = tvm.device(target, 0)
vm_exec = tvm.runtime.vm.Executable.load_exec(code, lib)
return VirtualMachine(vm_exec, dev), dev
def get_output(rt_mod, names, inputs):
for name, inp in zip(names, inputs):
rt_mod.set_input(name, inp)
rt_mod.run()
return rt_mod.get_output(0).asnump... | ms, sm)
rt_mod_ref, dev = get_ref_vm(mod, params, target=ref_target)
x = tvm.nd.array(np_data, device=dev)
out = get_output_vm(rt_mod, ["data"], [x])
ref_out = get_output_vm(rt_mod_ref, ["data"], [x])
else:
rt_mod_ref, dev = get_ref_rt_mod(mod, params, target=ref_target)
... | a"], [x])
ref_out = get_output(rt_mod_ref, ["data"], [x])
assert num_partition > 0
np.testing.assert_allclose(out, ref_out, atol=atol, rtol=rtol)
if run_benchmark:
print("CUTLASS:", rt_mod.benchmark(dev, number=1, repeat=600))
print("TVM with target %s:" % ref_target, rt_mod_ref.be... |
""" Fantasm: A taskqueue-based Finite State Machine for App Engine Python
Docs and examples: http://code.google.com/p/fantasm/
Copyright 2010 VendAsta Technologies Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may ob... | "%(stateName)s"' % {'stateName': stateConfig.name})
if stateConfig.final:
lines.append('"%(stateName)s" -> "__end__"' % {'stateName': stateConfig.name})
for transitionConfig in machineConfig.transitions.values():
if transitionConfig.fromState.name in skipStateNames or \
trans... | .join(lines) |
# proxy module
from __future__ import absolute_import
from envisage.plugins.remote_editor.i_remote_shell i | mpo | rt *
|
import os
def get_files(extension): |
for root, dirnames, filenames in os.walk("."):
for filename in filenames:
if filename.endswith(extension):
| yield os.path.join(root, filename)
def get_roles():
return sorted(os.listdir("./roles"))
def pytest_generate_tests(metafunc):
if "jinja2_file" in metafunc.fixturenames:
metafunc.parametrize("jinja2_file", get_files(".j2"))
if "json_file" in metafunc.fixturenames:
metafunc.par... |
from flask_user import DBAdapter
class DataStoreAdapter(DBAdapter):
""" An Wrapper to be use by Flask User to interact with
the database in this case, the DataStore """
def __init__(self, db, objMOdel):
super().__init__(db, objMOdel)
def get_object(self, ObjectClass, pk):
""" Ret... | ters in
kwargs or None. """
# TODO:
# The filters should be case sensitive
for field, value in kwargs.items():
ObjectClass.add_query_filter(field, "=", value)
entity = ObjectClass.fetch(limit=1)
return entity
def ifind_first_object(self, ObjectClass, **kw... |
# The filters should be case insensitive
for field, value in kwargs.items():
ObjectClass.add_query_filter(field, "=", value)
entity = ObjectClass.fetch(limit=1)
return entity
def add_object(self, ObjectClass, **kwargs):
""" Create an Entity with the fields speci... |
from __future__ import absolute_import
import os
import sys
from collections import defaultdict
from .gemini_constants import *
from . import GeminiQuery
class Site(object):
def __init__(self, row):
self.chrom = row['chrom']
self.end = int(row['end'])
self.gt_type = None
def _prune_run(ru... | :
curr_run.append(site)
un | k_count += 1
try:
site = next(sites)
except StopIteration:
break
# skip the current run unless it contains enough sites.
if hom_count >= args.min_snps:
run_start = min(c for c in curr_run if c not in ['H', ... |
from google.appengine.ext import ndb
class Users(ndb.Model):
password = ndb.Strin | gProperty(required=True)
full_name = ndb.StringProperty(required=True)
phone_no = ndb.StringProperty(required=False)
timestamp = ndb.DateTimeProperty(auto_now_add=True)
@classmethod
def query_user(cls, ancestor_key):
return cls.query(ancestor=ancestor_key).orde | r(cls.full_name)
@classmethod
def user_key(cls, user_email):
return ndb.Key('MyAppName_User', user_email) |
# 053. Maximum Subarray
# The simple O(n) solution.
import unittest
class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
ret = nums[0]
pre = nums[0]
for i in nums[1:]:
if ret < i and ret < 0:
... | ret = pre = cur
continue
if cur >= 0:
pre = cur
continue
# if cur < 0: # Better start over.
pre = 0
return ret
class SolutionUnitTest(unittest.TestCase):
def setup(self): |
pass
def tearDown(self):
pass
def testMaxSubArray(self):
s = Solution()
self.assertEqual(s.maxSubArray([-2,1,-3,4,-1,2,1,-5,4]), 6)
self.assertEqual(s.maxSubArray([-2,1]), 1)
self.assertEqual(s.maxSubArray([-1]), -1)
if __name__ == '__main__':
unittest.main(... |
# Copyright ( | c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import json
from telemetry import timeline_model
def Import(data):
trace = json.loads(data) # pylint: disable=W06 | 12
model = timeline_model.TimelineModel()
# TODO(nduca): Actually import things.
return model
|
import logging
from django.core.urlresolvers import reverse
from django.utils.safestring import mark_safe
from corehq.apps.adm.dispatcher import ADMSectionDispatcher
from corehq.apps.adm.models import REPORT_SECTION_OPTIONS, ADMReport
| from corehq.apps.reports.datatables import DataTablesHeader, DataTablesColumn, DTSortType
from corehq.apps.reports.generic import GenericReportView, GenericTabularReport
from corehq.apps.reports.standard import DatespanMixin, ProjectReportParametersMixin
from dimagi.utils.decorators.memoized import memoized
from django... | s.translation import ugettext as _, ugettext_noop
class ADMSectionView(GenericReportView):
section_name = ugettext_noop("Active Data Management")
base_template = "reports/base_template.html"
dispatcher = ADMSectionDispatcher
hide_filters = True
emailable = True
# adm-specific stuff
adm_sl... |
#!/usr/bin/env python
# (c) 2015-2018, ETH Zurich, Institut fuer Theoretische Physik
# Author: Dominik Gresch <greschd@gmx.ch>
"""
Test the Model constructors.
"""
import itertools
import pytest
import numpy as np
import tbmodels
def test_on_site_too_long(get_model):
"""
Check that error is raised when th... | 1),
occ=1,
pos=((0.0,) * 3, (0.5, 0.5, 0.0)),
sparse=sparse,
)
model2 = get_model(t1, t2, sparse=sparse)
models_close(model1, model2)
@pytest.mark.parametrize("sparse", [True, False])
def test_pos_outside_uc_with_hoppings(
get_model, models_equal, sparse
): # pylint: disable=i... | r with positions outside of the UC.
"""
t1 = 0.1
t2 = 0.2
hoppings = []
for phase, R in zip([1, -1j, 1j, -1], [(1, 1, 0), (1, 0, 0), (0, 1, 0), (0, 0, 0)]):
hoppings.append([t1 * phase, 0, 1, R])
for R in ((r[0], r[1], 0) for r in itertools.permutations([0, 1])):
hoppings.append... |
from django.contrib.admindocs.middlewar | e import XViewMiddleware
from django.http import HttpResponse
|
from django.utils.decorators import decorator_from_middleware
from django.views.generic import View
xview_dec = decorator_from_middleware(XViewMiddleware)
def xview(request):
return HttpResponse()
class XViewClass(View):
def get(self, request):
return HttpResponse()
|
# -*- coding: utf-8 -*-
#pylint: skip-file
import sys
import os
# 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.inser... | True
html_show_sourcelink = False
html_show_sphinx = False
html_show_copyright = True
htmlhelp_basename = 'rspacedoc'
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'rspace', ... | llaneous'),
]
|
class StretchException(Exception):
"""Common base class for all exceptions raised explicitly by stretch.
Exceptions which are subclasses of this typ | e will be handled nicely by
stretch and will not cause the program to exit. Any exceptions raised
which are not a subclass o | f this type will exit(1) and print a traceback
to stdout.
"""
level = "error"
def __init__(self, message, **kwargs):
Exception.__init__(self, message)
self.message = message
self.kwargs = kwargs
def format_message(self):
return self.message
def __unicode__(self... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.