prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
impor
t _plotly_utils.basevalidators class NticksValidator(_plotly_utils.basevalidators.IntegerValidator): def __init__( self, plotly_name="nticks", parent_name="layout.ternary.baxis", **kwargs ): super(NticksValidator, self).__init__( plotly_name=plotly_name, parent_name=par...
kwargs.pop("min", 1), **kwargs )
from pydatastream import Datastream import json import datetime import sys import os.path #hardcoded directories dir_input = "input/" dir_output = "output/" #check that the login credentials and input file location are being passed in numOfArgs = len(sys.argv) - 1 if numOfArgs != 3: print "Please run this python s...
ile_loc = dir_input + str(sys.argv[3]) #Ensure that the input file location exists if ( not os.path.isfile(str(input_file_loc)) ): print "The file " + str(input_file_loc) + " does not exist." exit() #login credentials to datastream DWE = Datastream(username=username,password=pw) #other info from datastream info = D...
with open(input_file_loc,'r') as input_file: symbol_ref = json.load(input_file) #download timestamp download_date = {'Custom_Download_Date' : datetime.datetime.now().isoformat()} #calculate time taken for entire process time_taken = datetime.datetime.now() time_taken = time_taken - time_taken for desc,desc_v...
import unittest from .Weather_analyzer import is_not_number class BtcPriceTestCase(unittest.TestCase): d
ef test_checking_of_input_in_form(self): input = 46 answer = is_not_n
umber(input) # The bitcoin returned changes over time! self.assertEqual(answer, False)
import datetime from django.shortcuts import render_to_response, get_object_or_404, HttpResponse, HttpResponseRedirect, Http404 from django.template import RequestContext from django.core.urlresolvers import reverse from articles.models import Article from taxonomy.models import TaxonomyMap from core.views ...
_type = 'Category', content_type__model = 'article').values_list('object_id', flat =
True) category_title = TaxonomyMap.objects.filter(term__id = category_id, type__type = 'Category', content_type__model = 'article')[0].term.term articles = Article.objects.filter(id__in = article_ids) return render_to_response('articles/category.html', {'category_id': category_id, 'category_...
_name') or \ 'weechat' completions[plugin][completion_item]['description'] = \ weechat.infolist_string(infolist, 'description') weechat.infolist_free(infolist) return completions def get_url_options(): """ Get list of completions hooked by plugins in a dict ...
opt_max) else:
values = _('any string') default_value = '"{0}"'.format( default_value.replace('"', '\\"')) elif opt_type == 'color': values = _('a WeeChat color name (default, black, ' '(dark)gray,...
from six import iteritems c
lass Playlist: is_folder = False playlist_persistent_id = None parent_persistent_id = None distinguished_kind = None playlist_id = None def __init__(self, playListName=None): self.name = playListName self.tracks = [] def __iter__(self): for attr, value in iteritems(...
ict(self): return {key: value for (key, value) in self}
#!/usr/bin/python ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'version': '1.0'} DOCUMENTATION = ''' --- module: k5_novnc_console short_description: Display the URL to the NoVNC Console version_added: "1.0" description: - returns a URL to the noVN...
ts['endpoints']['compute'] auth_token = k5_facts['auth_token'] session = requests.Session() headers = {'Content-Type': 'application/json', 'Accept': 'application/json', 'X-Auth-Token': auth_token } url = endpoint + '/servers/detail' k5_debug_add('endpoint: {0}'.format(endpoint)) k5_debug_add...
response = session.request('GET', url, headers=headers) except requests.exceptions.RequestException as e: module.fail_json(msg=e) # we failed to get data if response.status_code not in (200,): module.fail_json(msg="RESP: HTTP Code:" + str(response.status_code) + " " + str(response.co...
"""May return true if an empty argument list is to be generated even if the document contains none. """ return self.objtype == 'function' def handle_signature(self, sig, signode): """Transform a Yacas signature into RST nodes. Return (fully qualified name of the th...
# "fuzzy" searching mode
searchname = '.' + name matches = [(oname, objects[oname]) for oname in objects if oname.endswith(searchname) and objects[oname][1] in objtypes] else: # NOTE: searching for exact mat...
import unittest from datetime import timedelta, datetime import sys import json sys.path.append("../../config") sys.path.append("../../html") import ghObjects import ghObjectRecipe class testObjects(unittest.TestCase): def setUp(self): # nothin yet self.test = "rad" def test_spawnHTML(self): # arrange spawn...
redBy = "ioscode" s.veri
fied = daysago = datetime.now() - timedelta(3) s.verifiedBy = "tester" s.unavailable = None s.unavailableBy = None s.maxWaypointConc = None # act mobileHTML = s.getMobileHTML("", 0, 0) normalHTML = s.getHTML(0, "", "", 0, 0) rowHTML = s.getRow(False) invHTML = s.getInventoryObject() spawnJSON = s.g...
import json import dnot from mock import patch import unittest2 class NotifierTes
t(unittest2.TestCase): @patch("dnot.sns.connect_to_region") def test_parameters_are_submitted(self, connect_to_region_mock): topic = "abc" region = "eu-west-2" result_topic = "result" stack_name = "stack1" params = '{"key": "value"}'
notifier = dnot.Notifier(sns_region=region) notifier.publish(sns_topic_arn=topic, stack_name=stack_name, result_topic=result_topic, params=params) connect_to_region_mock.assert_called_with(region) message = json.loads('{{"stackName": "{0}", "notificationARN": "{1}", "region": "eu-west-1...
from __future__ import unicode_literals from django.db import migrations, models import multiselectfield.db.fields class Migration(migrations.Migration): dependencies = [ ('user', '0018_auto_20160922_1258'), ] operation
s = [ migrations.AddField( model_name='userprofile', name='activity_cantons', field=multiselectfield.db.fields.MultiSelectField(default='', verbose_name='Défi Vélo mobile', choices=[('BS', 'Basel-Stadt'), ('BE', 'Berne'), ('FR', 'Fribourg'), ('GE', 'Geneva'), ('LU', 'Lucerne'...
preserve_default=False, ), migrations.AlterField( model_name='userprofile', name='affiliation_canton', field=models.CharField(verbose_name="Canton d'affiliation", choices=[('', '---------'), ('BS', 'Basel-Stadt'), ('BE', 'Berne'), ('FR', 'Fribourg'), ('GE', ...
from __future__ import print_function import inspect import numpy as np import theano from ..layers.advanced_activations import LeakyReLU, PReLU from ..layers.core import Dense, Merge, Dropout, Activation, Reshape, Flatten, RepeatVector, Layer from ..layers.core import ActivityRegularization, TimeDistributedDense, Aut...
input_shapes): """ Utility function to print the shape of the output at each layer of a Model Arguments: model: instance of Model / Merge input_shapes: dict (Graph)
, list of tuples (Merge) or tuple (Sequential) """ if model.__class__.__name__ in ['Sequential', 'Merge']: # in this case input_shapes is a tuple, or a list [shape1, shape2] if not isinstance(input_shapes[0], tuple): input_shapes = [input_shapes] inputs = model.get_input(tra...
to to the txmanager""" bl_idname = "rman_txmgr_list.parse_scene" bl_label = "Parse Scene" bl_description = "Parse the scene and look for textures that need converting." def execute(self, context): rman_txmgr_list = context.scene.rman_txmgr_list texture_utils.parse_for_textures(context...
= "rman_txmgr_list.clear_unused" bl_label = "Clear Unused" bl_description = "Clear unused textures" def execute(self, context): rman_txmgr_list = context.scene.rman_txmgr_list nodeIDs = list() for item in rman_txmgr_list: nodeID = item.nodeID if item.nodeID ...
= texture_utils.get_txmanager().txmanager.get_txfile_from_id(item.nodeID) if not txfile: nodeIDs.append(nodeID) continue tokens = nodeID.split('|') if len(tokens) < 3: continue node_name,param,ob_name = tokens ...
''' Created on Feb 23, 2015 @author: rgroten ''' import ConfigParser import ssl from datetime import datetime from flask.globals import g # Import NetApp API libraries from NaElement import NaElement from NaServer import NaServer # from flask.globals import g def connect(): try: _create_unverified_htt...
" % volattrs.child_get_string('name') continue if (isDebug == 'True'): print 'Volume Name : %s' % volattrs.child_get_string('name') filteredVolumes.child_add(vol) filteredRet = NaElement("results") filt
eredRet.attr_set("status", "passed") filteredRet.child_add(filteredVolumes) if (isDebug == 'True'): print "Number of volumes (after filtering): " + str(ret.child_get("attributes-list").children_get().__len__()) return filteredRet def listSnapshots(volume): cmd = NaElement('snapshot-list-info'...
from django.contrib.auth import get_user_model from django.core.urlresolvers import reverse from django.shortcuts import get_object_or_404 from django.utils.translation import ugettext as _ from selvbetjening.sadmin2 import menu from selvbetjening.sadmin2.decorators import sadmin_pr
erequisites from selvbetjening.sadmin2.forms import UserForm, PasswordForm from selvbetjening.sadmin2.views.generic import generic_create_view
@sadmin_prerequisites def user_change(request, user_pk): user = get_object_or_404(get_user_model(), pk=user_pk) context = { 'sadmin2_menu_main_active': 'userportal', 'sadmin2_breadcrumbs_active': 'user', 'sadmin2_menu_tab': menu.sadmin2_menu_tab_user, 'sadmin2_menu_tab_active':...
# -*- coding: utf-8 -*- from django.shortcuts import ren
der, get_object_or_404 from django.contrib.auth.decorators import login_required from django.utils.translation import ugettext as _ from inviMarket.models import User @login_required def del_partner(request, partner_id): """ Delete the :model:`auth.User` passed by argument from the partners list. **Conte...
partner = get_object_or_404(User.objects.select_related('profile'), pk=partner_id) message = _("Ther user is not your partner.") if partner.profile.partners.filter(pk=user.id).exists(): partner.profile.partners.remove(user) message = _("The partnership proposal h...
from typing import Iterable, Mapping, Optional from lib import data from ..channel import pyramid from ..channel import wall def filterMessage() -> Iterable[data.ChatCommand]: return [] def commands() -> Mapping[str, Optional[data.ChatCommand]]: if not hasattr(commands, 'commands'): setattr(comman...
'commands', { '!pyramid': pyramid.commandPyramid, '!rpyramid': pyramid.commandRandomPyramid, '!wall': wall.commandWall, }) return getattr(commands, 'commands') def commandsStartWith() -> Mapping[str, Optional[data.ChatCommand]]: if not hasattr(commandsStartWith...
WallLong, }) return getattr(commandsStartWith, 'commands') def processNoCommand() -> Iterable[data.ChatCommand]: return []
""" Class defining a production step """ from __future__ import absolute_import from __future__ import division from __future__ import print_function __RCSID__ = "$Id$" import json from DIRAC import S_OK, S_ERROR class ProductionStep(object): """Define the Production Step object""" def __init__(self, **k...
################################## self.ParentStep = None self.Inputquery = None self.Outputquery = None self.GroupSize = 1 self.Body = "body" def getAsDict(self): """It
returns the Step description as a dictionary""" prodStepDict = {} prodStepDict["name"] = self.Name prodStepDict["parentStep"] = [] # check the ParentStep format if self.ParentStep: if isinstance(self.ParentStep, list): prodStepDict["parentStep"] = [] ...
# coding=UTF8 from __fu
ture__ import absolute_import import os from celery import Celery from django.conf import settings os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mydjangoapp.settings") app = Celery('mydjangoapp') CELERY_TIMEZONE = 'UTC' app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INST...
# -
*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigratio
n from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Changing field 'billdetails.end_date' db.alter_column(u'employee_billdetails', 'end_date', self.gf('django.db.models.fields.DateField')(null=True)) # Changing field 'billdetails.start_date' ...
# -*- test-case-name: twisted.test.test_newcred -*- from twisted.internet import defer from twisted.python import components, failure from twisted.cred import error, credentials class ICredentialsChecker(components.Interface): """I check sub-interfaces of ICredentials. @cvar credentialInterfaces: A list of s...
@param credentials: something which implements one of the interfaces in self.credentialInterfaces. @return: a Deferred which will fire a string which identifies an avatar, an empty tuple to specify an authenticated anonymous user (provided as checkers.ANONYMOUS) or fire a...
e do not want None as the value for anonymous because it is too easy to accidentally return it. We do not want the empty string, because it is too easy to mistype a password file. For example, an .htpasswd file may contain the lines: ['hello:asdf', 'world:asdf', 'goodbye', ':world']. ...
b.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'objec...
: "orm['job_runner.Worker']"}) }, 'job_runner.killrequest': { 'Meta': {'object_name': 'KillRequest'}, 'enqueue_dts': ('django.db.models
.fields.DateTimeField', [], {'null': 'True', 'db_index': 'True'}), 'execute_dts': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'db_index': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'run': ('django.db.models.fields.related.Fo...
from django.conf.urls import url from . import views urlpatterns = [ # ex: /album/
url(r'^$', views.index, name='index'), # ex: /al
bum/create/ url(r'^welcome/$', views.welcome, name='welcome'), # ex: /album/create/ url(r'^create/$', views.create, name='create'), # ex: /album/vietnam_2016/ url(r'^(?P<album_permalink>[\w_]+)/$', views.detail, name='detail'), # ex: /album/vietnam_2016/settings url(r'^(?P<album_permalink>[\...
sent += len(chunk) self.__write(chunk) else: for chunk in file_wrapper: if the_len >= len(chunk): the_len -= len(chunk) count += len(chunk) self.__bytes_sent += len(chunk) ...
ern[:-1].strip() ## -> "404" if fnmatch(status, pattern) and (not must_have_referer or referer):
return True return False def application(environ, start_response, handler=None): """ Entry point for wsgi. """ ## Needed for mod_wsgi, see: <http://code.google.com/p/modwsgi/wiki/ApplicationIssues> req = SimulatedModPythonRequest(environ, start_response) #print 'Starting mod_pyth...
import interact class
EvtInteract(interact.Interact): def __init__(self): self.events = [] def checkEventInteraction(self, events): self.events = events self.checkInteraction()
from . import ( Application, Category, Course, Designation, Major, Project, Requirement, User, Year, ) Application = Applicatio
n.Application Category = Category.Category Course = Cour
se.Course Designation = Designation.Designation Major = Major.Major Project = Project.Project Requirement = Requirement.Requirement User = User.User Year = Year.Year
"""empty message Revision ID: 0047 add smtp Revises: 0046 remove long description Create Date: 2020-11-08 01:28:28.386704 """ # revision identifiers, used by Alembic. revision = '0047 add smtp' down_revision = '0046 remove long description' from alembic import op import sqlalchemy as sa def upgrade(): # ### c...
# ### commands auto generated by Alembic - please adjust! ### op.drop_column('email_providers', 'smtp_user') op.drop_column('email_providers', 'smtp_server') op.drop_column('email_providers', 'smtp_password') op.drop_column('email_providers', 'available') op
.drop_column('email_providers', 'created_at') # ### end Alembic commands ###
# -*- coding: UTF-8 -*- # YaBlog # (c) Regis FLORET # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the fol...
# documentation and/or other materials provided with the distribution. # * Neither the name of the <organization> nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE...
LIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL Regis FLORET BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR...
import numpy as np import os import pandas as pd import statsmodels.formula.api as smf import sys # @params: takes mobaid codes string # @returns: list of mobaid strings def splitCode(x): if type(x) is str: codes = x.split(',') return codes else: return [] # @returns binary T/F if string code is in string/lis...
.to_csv('../data/single_day_boardings.csv') deboardings.to_csv('../data/single_day_deboardings.csv') ################################################################### # Need to check with Matthew # # ----------------------------- # # is total dw...
a stop is included for each client row? # # or is total dwell time sum is divided among client rows? # ################################################################### # regression for boarding dwell times x = ' + '.join(boardings.columns.values[6:]) y = 'DwellTime' reg_formula = y + ' ~ ' + x # print reg_f...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'template.ui' # # Created: Sun Sep 18 19:19:10 2016 # by: pyside2-uic running on PySide2 2.0.0~alpha0 # # WARNING! All changes made in this file will be lost! from PySide2 import QtCore, QtGui, QtWidgets class Ui_Form(object): def...
ayout) self.historyList = QtWidgets.QListWidget(self.splitter) font = QtGui.QFont() font.setFamily("Monospace") self.historyList.setFont(font) self.historyList.setObjectName("historyList") self.exceptionGroup = QtWidgets.QGroupBox(self.splitter) self.exceptionGrou...
dLayout_2.setSpacing(0) self.gridLayout_2.setContentsMargins(-1, 0, -1, 0) self.gridLayout_2.setObjectName("gridLayout_2") self.clearExceptionBtn = QtWidgets.QPushButton(self.exceptionGroup) self.clearExceptionBtn.setEnabled(False) self.clearExceptionBtn.setObjectName("clearExcep...
# # # import requests from bs4 import BeautifulSoup import re import os def all_links(URL,abs=False,session=None): '''Generator function for all links in a page. ARGS: URL -> url of the page abs -> (True) returns actual 'href's of each <a> tag (False) process each 'href' to generate the full li...
le from web to disk. ARGS: URL -> URL of the file to be downl
oaded session -> requests session if the file is only available in a session (typically login/auth/etc) dir -> directory of the saved file can be either reletive to the script or absoloute path. example: "archive/" saves files in a folder named archive replace -> if the file exists (True) replac...
tamp)s,%(ip_address)s,%(warning_threshold)s,%(check_timestamp)s,%(refer)s) """ UPDATE_HEADER = "INSERT INTO %s.performance_utilizationstatus" UPDATE_TAIL = """ (machine_name,current_value,service_name,avg_value,max_value,age,min_value,site_name,data_source,critical_threshold,device_name,severity,sys_timestamp,ip_add...
a_ss(**kwargs): site_name = kwargs.get("params").get("site_name") device_type = kwargs.get("params").get("technology") utilization_attributes = kwargs.get("params").get("attributes") if "vrfprv" in site_name: memc_con = vrfprv_me
mc_con elif "pub" in site_name: memc_con = pub_memc_con else: memc_con = memc_con_cluster ss_data_dict = {} all_ss_data = [] if site_name not in hostnames_ss_per_site.keys(): logging.warning("No SS devices found for %s"%(site_name)) return 1 for hostnames_dict in hostnames_ss_per_site....
''' Various tools to interface with pyGSTi for running GST experiments. Created on May 16, 2018 Original Author: Guilhem Ribeill Copyright 2018 Raytheon BBN Technologies 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 ...
'll modify the Clifford indexing here to make Id(length=0) # the first element in the library and Id(length=length) the second. if pulse_library == "STANDARD": #cl
ifford_pulse = lambda x: clifford_seq(x, qubit) clifford_pulse = [clifford_seq(i, qubit) for i in range(24)] clifford_pulse.insert(0, Id(qubit, length=0.0)) elif pulse_library == "DIAC": #clifford_pulse = lambda x: DiAC(qubit, x, diac_compiled) clifford_pulse = [AC(qubit, i, diac_com...
""" Based on http://vaig.be/2009/03/getting-client-os-in-django.html """ import re def client_os(user_agent): ''' Context processor for Django that provides operating system information base on HTTP user agent. A user agent looks like (line break added): "Mozilla/5.0 (X11; U; Linux i686; en-US; r...
t_dict = result.groupdict() full_platform = result_dict['platform_token'] platform_val
ues = full_platform.split(' ') if platform_values[0] in ('Windows', 'Linux', 'Mac'): platform = platform_values[0] elif platform_values[1] in ('Mac',): # Mac is given as "PPC Mac" or "Intel Mac" platform = platform_values[1] else: platform = None ...
import os class Config(object): SPOTIPY_REDIRECT_URI = os.environ['SPOTIPY_REDIRECT_URI'] SPOTIPY_CLIENT_ID = os.environ['SPOTIPY_CLIENT_ID'] SPOTIPY_CLIENT_SECRET = os.environ['SPOTIPY_CLIENT_SECRET'] SPOTIFY_ACCESS_SCOPE = 'playlist-modify-public playlist-modify-private playlist-read-private user-lib...
alse. Set True to make you
r generated playlist public. PUBLIC = False
""" This migration script adds a user actions table to Galaxy. """ from sqlalchemy import * from migrate import * import datetime now = datetime.datetime.utcnow import logging log = logging.getLogger( __name__ ) metadata = MetaData() def display_migration_details(): print "" print "This migration script ad...
512 ) ), Column( "params", Unicode( 1024 ) ) ) def upgrade(migrate_engine): metadata.bind = migrate_engine display_migration_details() metadata.reflect() try: UserAction_table.create() except Exception, e: print str(e) log.debug( "Creating user_action table failed: %s" %...
.bind = migrate_engine metadata.reflect() try: UserAction_table.drop() except Exception, e: print str(e) log.debug( "Dropping user_action table failed: %s" % str( e ) )
#!/usr/bin/env python # -*- coding:
utf-8 -*- import os import tornado.ioloop try: import WebApp except ImportError, ImportWarning: import entire as WebApp if __name__ == "__main__": ip = os.environ['OPENSHIFT_DIY_IP'] port = int(os.environ['OPENSHIFT_DIY_PORT']) WebApp.application.listen(port, ip) tornado.ioloop.IOLoop.insta
nce().start()
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function import os import shutil import time import subprocess import numpy as np from .phonopy_conf_creator import PhonopyConfCreator from vasp.poscar import Poscar from autotools import symlink_force class PhononCalculator(object): def _...
f._dim_sqs variables = self._variables mesh = self._mesh.copy()
print("directory_data:", directory_data) print("mesh:", mesh) spg_number = self.create_spg_number() # Get band path for the specific space group phonopy_conf_creator = PhonopyConfCreator( spg_number, mesh=mesh, tmax=3000, dim_sq...
# coding: utf-8 import sqlalchemy as sa import pandas as pd from niamoto.data_providers.base_occurrence_provider import \ BaseOccurrenceProv
ider from niamoto.exceptions import MalformedDataSourceError class SQLOccurrenceProvider(BaseOccurrenceProvider): """ SQL occurrence provider. Instantiated with a sql query, that must return AT LEAST the following columns: id -> The provider's identifier for the occurrence.
taxon_id -> The provider's taxon id for the occurrence. x -> The longitude of the occurrence (WGS84). y -> The latitude of the occurrence (WGS84). All the remaining column will be stored as properties. """ REQUIRED_COLUMNS = set(['id', 'taxon_id', 'x', 'y']) def __init__(self, data_p...
elf): """Step into the next iteration of the model.""" raise NotImplementedError("Please implement a step instance method") class SimpleContainer(BaseModelClass): """ A container in the aquaponics loop. Each container is a container/tank/basin/growbed/etc containing a volume of water,...
f the next ste
p in seconds. """ inflow = self.get_current_inflow_speed() outflow = self.get_current_outflow_speed() self.state += time / 60 * inflow - time / 60 * outflow class Container(SimpleContainer): _PARAMS = copy.deepcopy(SimpleContainer._PARAMS) _PARAMS['threshold']= (_PARAM_TYPES.IN...
print ("How o
ld are you?",) age = input() print ("How tall are you?",) height = input() print ("How much do you weigh?",) weig
ht = input() print ("So, you are %r years old, %r tall and %r heavy." %(age, height, weight))
#!/usr/bin/env python3 # -*- coding: utf-8 -*- '''Hacky way to make sure imports work''' from os.path import abspath, dirname, realpath, join import sys # This allows imports to work, even if sim_game is
not in python path: package_location = abspath(join(dirname
(realpath(__file__)) , "..")) sys.path.insert(0, package_location)
# -*- Mode: Python; python-indent-offset: 4 -*- # # Time-stamp: <2017-06-03 11:36:32 alex> # # -------------------------------------------------------------------- # PiProbe # Copyright (
C) 2016-2017 Alexandre Chauvin Hameau <ach@meta-x.org> # # 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 # # This program is dis...
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/>. # -------------------------------------------------------------------- """ database package, redis and test modules """ from . import dbRedis ...
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals import json import datetime import mimetypes import os import frappe from frappe import _ import frappe.model.document import frappe.utils import frappe.sessions import werkzeug.u...
dministrator")) except frappe.PermissionError: raise Forbidden(_("You need to be logged in and have System Manager Role to be able to access backups.")) return send_private_file(path) def send_private_file(path): path = os.path.join(frappe.local.conf.get('private_path', 'private'), path.strip("/")) if frappe.l...
onse() response.headers[b'X-Accel-Redirect'] = path else: filename = os.path.basename(path) filepath = frappe.utils.get_site_path(path) try: f = open(filepath, 'rb') except IOError: raise NotFound response = Response(wrap_file(frappe.local.request.environ, f)) response.headers.add(b'Content-Dispos...
f
rom goto_file2 import foo f
oo
""" Tests for `pyleset` module. """ import pytest f
rom pyleset import pyleset class TestPyleset(object): @classmethod def setup_class(cls): pass def test_something(self): pass @cl
assmethod def teardown_class(cls): pass
n ]);\n}", "function() {\n Foo([\n ['sdfsdfsd'],\n ['sdfsdfsdf']\n ]);\n}"); self.options.keep_array_indentation = True; bt("a = ['a', 'b', 'c',\n 'd', 'e', 'f']"); bt("a = ['a', 'b', 'c',\n 'd', 'e', 'f',\n 'g', 'h', 'i']"); bt("a = ['a',...
bt('if (foo)\n{}\nelse /regex/.test();'); bt('if (foo) /regex/.test();'); bt('if (a)\n{\nb;\n}\nelse\n{\nc;\n}', 'if (a)\n{\n b;\n}\nelse\n{\n c;\n}'); test_fragment('if (foo) {', 'if (foo)\n{'); test_fragment('foo {', 'foo\n{'); test_fragment('return {', 'return {')...
ace. test_fragment('return /* inline */ {', 'return /* inline */ {'); # test_fragment('return\n{', 'return\n{'); # can't support this?, but that's an improbable and extreme case anyway. test_fragment('return;\n{', 'return;\n{'); bt("throw {}"); bt("throw {\n foo;\n}"); ...
from tests.package.test_python import TestPythonPackageBase class TestPythonPy2Subproce
ss32(TestPythonPackageBase): __test__ = True config = TestPythonPackageBase.config + \ """ BR2_PACKAGE_PYTHON=y BR2_PACKAGE_PYTHON_SUBPROCESS32=y
""" sample_scripts = ["tests/package/sample_python_subprocess32.py"]
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
ile_path) os.unlink(file_path) assert not os.path.isfile(file_path) u
ntracked_file = 'foobarbaz' touch(untracked_file) assert os.path.isfile(untracked_file) pkg.do_restage() assert not os.path.isfile(untracked_file) assert os.path.isdir(pkg.stage.source_path) assert os.path.isfile(file_path) assert h()...
import logging from anubis.model import builtin from anubis.model import domain from anubis.util import argmethod _logger = logging.get
Logger(__name__) def wrap(method): async def run(): _logger.info('Built in domains') for ddoc in builtin.DOMAINS: _logger.info('Domain: {0}'.format(ddoc['_id']))
await method(ddoc['_id']) _logger.info('User domains') ddocs = domain.get_multi(fields={'_id': 1}) async for ddoc in ddocs: _logger.info('Domain: {0}'.format(ddoc['_id'])) await method(ddoc['_id']) if method.__module__ == '__main__': argmethod._m...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import partialdate.fields class Migration(migrations.Migration): dependencies = [ ('genealogio', '0023_auto_20160303_2105'), ] operations = [ migrations.AlterField( model...
eitem', name='end_date', field=partialdate.fields.PartialDateField(default='', help_text='Datum im Format JJJJ-MM-TT (Teilangaben m\xf6glich); kann freibleiben', verbose_name='Enddatum', blank=True), ), migrations.AlterField( model_name='timelineitem', nam...
tialDateField(default='', help_text='Datum im Format JJJJ-MM-TT (Teilangaben m\xf6glich)', verbose_name='Startdatum', blank=True), ), ]
import os, sys # to read dependencies from ./lib direcroty script_dir = os.path.dirname( os.path.realpath(__file__) ) sys.path.insert(0, script_dir + os.sep + "lib") import logging, boto3, json, random # for dynamodb filter queries from boto3.dynamodb.conditions import Key, Attr # setup log level to DEBUG log = loggi...
return response( {"Message": "Welcome to the Serverless Workshop fully powered by AWS Lambda elastic cloud computing service"}, event) def response(body, event, code=200): if 'resource' in event and 'httpMethod' in event: retu
rn { 'statusCode': code, 'headers': {}, 'body': json.dumps(body, indent=4, separators=(',', ':')) } return body
# Copyright 2011 OpenStack Foundation. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless req...
nd (%s)' % (class_str, traceback.format_exception(*sys.exc_info()))) def import_object(import_str, *args, **kwargs): """Import a class and return an instance of it.""" return import_class(import_str)(*args, **kwargs) def import_object_ns(name_space, impor...
t object from default namespace. Imports a class and return an instance of it, first by trying to find the class in a default namespace, then failing back to a full path if not found in the default namespace. """ import_value = "%s.%s" % (name_space, import_str) try: return import_class...
import numpy as np import scipy.cluster.hierarchy as hr import scipy.spatial as spa import clustering import matplotlib.pyplot as plt from sklearn.cluster import AgglomerativeClustering import filter class textMiningEac: def __init__(self,k,N,low,high=0): self.k = k # Leer datos desde ...
= np.ones(n) - coasocMatrix def startPAM(self): """ Hace sobre PAM sobre la matriz de distancia del EAC """ (a,b,self.labels) = clustering.PAM(self.EAC_D, self.k,True) return self.labels def startHierarchical(self): """ Hace cl
ustering Jerarquico sobre la matriz de distancia del EAC """ z = AgglomerativeClustering(n_clusters=self.k, linkage='ward').fit(self.EAC_D) self.labels = z.labels_ return self.labels def getClustersTweets(self): """ Obtiene clusters en relacion a la frec...
import tornado.web from datetime import date from sqlalchemy.orm.exc import NoResultFound from pyprint.handler import BaseHandler from pyprint.models import User, Link, Post class SignInHandler(BaseHandler): def get(self): return self.background_render('login.html') def post(self): username ...
self.orm.commit() return self.redirect('/kamisama/links') elif action == 'del': link_id = self.get_argument('id', 0) if link_id: link = self.orm.query(Li
nk).filter(Link.id == link_id).one() self.orm.delete(link) self.orm.commit()
import datetime def suffix(d
): return 'th' if 11<=d<=13 else {1:'st',2:'nd',3:'rd'}.get(d%10, 'th') def custom_strftime(format, t): return t.strftime(format).replace('{S}', str(t.day) + suffix(t.day)) print "Welcome to GenerateUpdateLines, the nation's favourite automatic update line generator." start = int(raw_input("Enter initial da...
range(start, stop+1): date = t0 + datetime.timedelta(d-1) print "| "+str(d)+" | "+custom_strftime("%a {S} %B", date)+" | | |" # from datetime import datetime as dt # # def suffix(d): # return 'th' if 11<=d<=13 else {1:'st',2:'nd',3:'rd'}.get(d%10, 'th') # # def custom_strftime(format, t): # return...
to show code editor tabs. """ import logging import os from pyqode.core.dialogs.unsaved_files import DlgUnsavedFiles from pyqode.core.modes.filewatcher import FileWatcherMode from pyqode.core.widgets.tab_bar import TabBar from pyqode.qt import QtCore, QtWidgets from pyqode.qt.QtWidgets import QTabBar, QTabWidget def...
initial_index = self.currentIndex() for i in range(self.count()): try: self.setCurrentIndex(i) self.save_current() except AttributeError: pass self.setCurrentInde
x(initial_index) def addAction(self, action): """ Adds an action to the TabBar context menu :param action: QAction to append """ self._context_mnu.addAction(action) def add_separator(self): """ Adds a separator to the TabBar context menu. :retu...
# Copyright (C) 2012 Hewlett-Packard Development Company, L.P. # 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/LICEN...
t they can handle version cap set to 1.3. 2.0 - Remove 1.x compatibility """
RPC_API_VERSION = '1.3' TOPIC = CONF.backup_topic BINARY = 'storage-backup' def _compat_ver(self, current, legacy): if self.client.can_send_version(current): return current else: return legacy def create_backup(self, ctxt, backup): LOG.debug("create_ba...
is_container="list", user_ordered=False, path_helper=self._path_helper, yang_keys="name", extensions=None, ), is_container="list", yang_name="p2p-primary-path", parent=self...
th, yang_name="p2p-primary-path", parent=self, is_container="list", user_ordered=False, path_helper=self._path_helper,
yang_keys="name", extensions=None, ), is_container="list", yang_name="p2p-primary-path", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, ...
"""coop 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') Class-based...
dmin.site.urls), url(r'^$',area_map,{'area_id':1}), url(r'^guide/', include('guide.urls',namespace="guide")), url(r'^home/', include('homepage.urls',namespace="homepage")), url(r'^members/auth/', include('members.urls')), # note that the (customis
ed) templates for the auth views are in [BASE_DIR]/templates/registration url(r'^members/', include('members.urls',namespace="members")), ] + static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
rror(message) def get_latest_event_id(self): """Query the ftp server and determine the latest event id. :return: A string containing a valid event id. :raises: NetworkError """ ftp_client = FtpClient() try: ftp_client_list = ftp_client.get_listing() ...
y be returned without invoking any network requests. :param event_file: Filename on server
e.g.20110413170148.inp.zip :type event_file: str :param retries: Number of reattempts that should be made in in case of network error etc. :type retries: int :return: A string for the dataset path on the local storage system. :rtype: str :raises: EventU...
on chip version "+str(self.chip.chipID)) # # DCCAL_STAT (0x05C1) # # DCCAL_CALSTATUS<7:0> @property def DCCAL_CALSTATUS(self): """ Get the value of DCCAL_CALSTATUS<7:0> """ if self.chip.chipID == self.chip.chipIDMR3: return self._readReg('STAT', 'D...
-1024..1024]") val = self.intToSignMagnitude(value, 11) self._writeReg('TXAQ', 'DC_TXAQ<10:0>', val) self._writ
eReg('TXAQ', 'DCWR_TXAQ', 0) self._writeReg('TXAQ', 'DCWR_TXAQ', 1) else: raise ValueError("Bitfield TXAQ is not supported on chip version "+str(self.chip.chipID)) # # DCCAL_TXBI ...
""" Grab screen data from OMERO based on Screen ID """ import csv import multiprocessing import progressbar import signal import sys import time import requests import json from argparse import ArgumentParser import omeroidr.connect as connect from omeroidr.data import Data parser = ArgumentParser(prog='OMERO screen ...
# initialize the progress bar widgets = [progressbar.Percentage(), " ", progressbar.Bar(), " ", progressbar.ETA()] pbar = progressbar.ProgressBar(widgets=widgets) def init_worker(): """ Initialise multiprocessi
ng pool """ signal.signal(signal.SIGINT, signal.SIG_IGN) def well_details_callback(well): """ Callback from apply_async. Used to update progress bar :param well: Well metadata object """ pbar.update(pbar.previous_value + 1) # append well the wells data list wells_data.append(well)...
ystemAccessAccount (Opnum 24) class LsarSetSystemAccessAccount(NDRCALL): opnum = 24 structure = ( ('AccountHandle', LSAPR_HANDLE), ('SystemAccess', ULONG), ) class LsarSetSystemAccessAccountResponse(NDRCALL): structure = ( ('ErrorCode', NTSTATUS), ) # 3.1.4.5.9 LsarEnumerateAc...
('EnumerationContext', ULONG), ('PreferedMaximumLength', ULONG), ) class LsarEnumerateTrustedDomainsResponse(NDRCALL): structure = ( ('EnumerationContext', ULONG), ('EnumerationBuffer',LSAPR_TRUSTED_ENUM_BUFFER_EX), ('ErrorCode', NTSTATUS), )
# 3.1.4.7.9 LsarOpenTrustedDomainByName (Opnum 55) # 3.1.4.7.10 LsarCreateTrustedDomainEx2 (Opnum 59) # 3.1.4.7.11 LsarCreateTrustedDomainEx (Opnum 51) # 3.1.4.7.12 LsarCreateTrustedDomain (Opnum 12) # 3.1.4.7.14 LsarSetInformationTrustedDomain (Opnum 27) # 3.1.4.7.15 LsarQueryForestTrustInformation (Opnum 73) class Ls...
for i in range (0, 53): filepath = '/Users/tunder/Dropbox/PythonScripts/requests/pbs/fic' + str(i) + '.pbs' with open(filepath, mode='w', encoding = 'utf-8') as file: file.writ
e('#!/bin/bash\n') file.write('#PBS -l walltime=10:00:00\n') file.write('#PBS -l nodes=1:ppn=12\n') file.write('#PBS -N Fiction' + str(i) + '\n') file.write('#PBS -q ichass\n') file.write('#PBS -m be\n') file.write('cd $PBS_O_WORKDIR\n'
) file.write('python3 extract.py -idfile /projects/ichass/usesofscale/hathimeta/pre20cslices/slice' + str(i) + '.txt -g fic -v -sub -rh' + '\n')
('ilevel',0) if ilevel>8: # Somewhere got into loop - quit # ck.out('Warning: you have a cyclic dependency in your repositories ...') return {'return':0, 'repo_deps':repo_deps} # Load repo r=ck.access({'action':'load', 'module_uoa':cfg['module_deps']['repo'], ...
en(duoa)>il: il=len(duoa) url=d.get('url','') branch='' checkout='' if os.path.isdir(p): # Detect status pc=os.getcwd() os.chdir(p) # Get current branch r=ck.run_and_get_stdout({'cmd':['git','rev-parse...
and r['return_code']==0: branch=r['stdout'].strip() # Get current checkout r=ck.run_and_get_stdout({'cmd':['git','rev-parse','--short','HEAD']}) if r['return']==0 and r['return_code']==0: checkout=r['stdout'].strip() os.chdir(...
# Copyright (C) 2010-2011 Richard Lincoln # # 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, publish...
he master data that describes the attributes of the item such as dimensions, weight, or unit of meas
ure - it describes the item as it exists at a specific location.Utility inventory-related information about an item or part (and not for description of the item and its attributes). It is used by ERP applications to enable the synchronization of Inventory data that exists on separate Item Master databases. This data is...
# -*- coding: utf-8 -*-# """ Basic Twitter Authentication requirements: Python 2.5+ tweepy (easy_install tweepy | pip install tweepy) """ __author__ = 'Bernie Hogan' __version__= '1.0' import string import codecs import os import pickle import copy import sys import json import webbrowser import tweepy from twe...
): user = api.get_user(screen_name) return user.followers_count def getFollowingCount(api, screen_name="BarackObama"): user = api.get_user(screen_name) print user print dir(user) return user.friends_count if __name__=='__main__': CONSUMER_KEY = th.CONSUMER_KEY CONSUMER_SECRET = th.
CONSUMER_SECRET auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) ACCESS_TOKEN_SECRET = th.ACCESS_TOKEN_SECRET ACCESS_TOKEN = th.ACCESS_TOKEN auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET) api = tweepy.API(auth) print "Now you have received an access token." print "Or rather, your account ...
import json from urllib import request import pymongo connection = pymongo.MongoClient('mongodb://localhost') db = connection.reddit stories = db.stories # stories.drop() # req = request.Request('http://www.reddit.com/r/technology/.json') # req.add_header('User-agent', 'Mozilla/5.0') # reddit_page = request.urlopen(...
eddit posts') # for item in parsed_reddit['data']['children']: # stories.insert_one(item['data']) # # print('Finished adding reddit posts') def find(): print('Keyword search started') query = {'title': {'$regex': 'apple|google', '$options': 'i'}} projection = {'title': 1, '_id': 0} try: ...
(e), e) for post in cursor: print(post) find()
# Copyright 2012-2013 Eric Ptak - trouch.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/LICENSE-2.0 # # Unless required by applicable l...
t, vref): SPI.__init__(self, toint(chip), 0, 8, 10000000) DAC.__init__(self, channelCount, 12, float(vref)) self.buffered=False self.gain=False self.shutdown=False self.values = [0 for i in range(channelCount)] def __str__(self): return "MCP492%d(chip=%d)" % ...
el, diff=False): return self.values[channel] def __analogWrite__(self, channel, value): d = bytearray(2) d[0] = 0 d[0] |= (channel & 0x01) << 7 d[0] |= (self.buffered & 0x01) << 6 d[0] |= (not self.gain & 0x01) << 5 d[0] |= (not self.shutdown & 0x01)...
from multicorn import ForeignDataWrapper from cassandra_provider import CassandraProvider from properties import ISDEBUG import properties import schema_importer import time class CassandraFDW(ForeignDataWrapper): def __init__(self, options, columns): super(CassandraFDW, self).__init__(options, columns) ...
self.modify_items = [] pass def explain(self, quals, columns, sortkeys=Non
e, verbose=False): return self.cassandra_provider.build_select_stmt(quals, columns, self.cassandra_provider.allow_filtering, verbose) def end_scan(self): if ISDEBUG: logger.log("end_scan. Total time: {0} ms".format((time.time() - self.scan_start_time) * 1000)) pass def pre_...
#! /
usr/bin/env python import requests, json from os.path import expanduser from coinbase.wallet.client import Client home = expanduser('~') client = Client('YOUR_API_KEY', 'YOUR_API_SECRET') accounts = client.get_accounts() print accounts ['data'][0
]['balance']
import struct import numpy import io import pickle import pyctrl.packet as packet def testA(): # test A assert packet.pack('A','C') == b'AC' assert packet.pack('A','B') == b'AB' assert packet.pack('A','C') != b'AB' assert packet.unpack_stream(io.BytesIO(b'AC')) == ('A', 'C') assert packet.un...
','abc') == struct.pack('<cI3s', b'S', 3, b'abc') assert packet.pack('S','abcd') != struct.pack('<cI3s', b'S', 3, b'abc') assert packet.unpack_stream( io.BytesIO(struct.pack('<cI3s', b'S', 3, b'abc'))) == ('S', 'abc') assert packet.unpack_stream( io.BytesIO(struct.pack('<cI3s', b'S',
3, b'abc'))) != ('S', 'abcd') def testIFD(): # test I assert packet.pack('I',3) == struct.pack('<ci', b'I', 3) assert packet.pack('I',3) != struct.pack('<ci', b'I', 4) assert packet.unpack_stream( io.BytesIO(struct.pack('<ci', b'I', 3))) == ('I', 3) assert packet.unpack_stream( io...
# $Log: pidTK.py,v $ # Revision 1.1 2002/07/12 18:34:47 glandrum # added # # Revision 1.6 2000/11/03 00:56:57 clee # fixed sizing error in TKCanvas # # Revision 1.5 2000/11/03 00:25:37 clee # removed reference to "BaseTKCanvas" (should just use TKCanvas as default) # # Revision 1.4 2000/10/29 19:35:31 clee # ...
clee # update that makes PIL based TKCanvas the default Canvas for TK. # Updated piddletest.py. Also, added clear() methdo to piddlePIL's # canvas it clears to "white" is this correct behavior? Not well # specified in current documents. # class FontManager: __alt_faces = {"serif": "Times", "sansserif": "Helveti...
# the main interface def stringWidth(self, s, font): tkfont = self.piddleToTkFont(font) return tkfont.measure(s) def fontHeight(self, font): tkfont = self.piddleToTkFont(font) return self._tkfontHeight(tkfont) def fontAscent(self, font): tkfont = self.piddleToTkFont(font) return self._...
if kwargs['ip_allocation'] == "all": slave_ips = [self.reserve_ip(project_id=project_id) for i in range(kwargs['slaves'])] self.ips = [ip for ip in [master_ip] + slave_ips if ip] self.master = self.create_vm(vm_name=vm_name, ip=master_ip...
2.168.0.0/24', gateway_ip='192.168.0.1'): """ Creates a private subnets and connects it with this network :param net_id: id of the network :return: the id of the subnet if successfull """ try: subnet = self.
network_client.create_subnet(net_id, cidr, gateway_ip=gateway_ip, enable_dhcp=True) self.subnet = subnet return subnet['id'] except ClientError as ex: raise ex d...
#!/usr/bin/python import sys import urllib2 RAINX_STAT_KEYS = [ ("rainx.reqpersec", "total_reqpersec"), ("rainx.reqputpersec", "put_reqpersec"), ("rainx.reqgetpersec", "get_reqpersec"),
("rainx.avreqtime", "total_avreqtime"), ("rainx.avputreqtime", "put_avreqtime"), ("rainx.avgetreqtime", "get_avreqtime"), ] def parse_info(stream): da
ta = {} for line in stream.readlines(): parts = line.split() if len(parts) > 1: # try to cast value to int or float try: value = int(parts[1]) except ValueError: try: value = float(parts[1]) excep...
'db_table': 'PIPELINE_TOOL', }, ), migrations.CreateModel( name='PipelineReleaseTool', fields=[ ('pipeline', models.ForeignKey(db_column='PIPELINE_ID', on_delete=django.db.models.deletion.DO_NOTHING, primary_key=True, serialize=False,...
True)), ('sequencedata_received', models.DateTimeField(blank=True, db_column='SEQUENCEDATA_RECEIVED', null=Tr
ue)), ('environment_biome', models.CharField(blank=True, db_column='ENVIRONMENT_BIOME', max_length=255, null=True)), ('environment_feature', models.CharField(blank=True, db_column='ENVIRONMENT_FEATURE', max_length=255, null=True)), ('environment_material', models.CharFiel...
""" WSGI config for test_project project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file,
see https://docs.djangoproject.com/en/stable/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefau
lt("DJANGO_SETTINGS_MODULE", "test_project.settings") application = get_wsgi_application()
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-03-27 19:06 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('posts', '0005_post_author'), ] operations = [ migrations.CreateModel( ...
ostImage', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('alt_text', models.CharField(blank=True, max_length=96, null=True)), ('image', models.ImageField(upload_to='')), ], ), migrations.AddField( model_name='post', name='images', field=models.ManyToManyField(related_name='posts', to='posts.P...
set_no_section(self): conf = Config() conf.defaults.add_section("player") conf.defaults.set("player", "backend", "blah") conf.reset("player", "backend") assert conf.get("player", "backend") == "blah" def test_initial_after_set(self): conf = Config() conf.add_...
l(conf.getlis
t("foo", "bar"), [" a", ",", "c"]) self.assertEqual(conf.get("foo", "bar"), " a,\\,,c") conf.setlist("foo", "bar", [" a", ",", "c"], sep=":") self.assertEqual(conf.get("foo", "bar"), " a:,:c") def test_versioning_disabled(self): # we don't pass a version, so versioning is disabled ...
#!/usr/bin/env python # encoding: utf-8 """ update/disease.py Update the disease terms in database Created by Måns Magnusson on 2017-04-03. Copyright (c) 2017 __MoonsoInc__. All rights reserved. """ import logging import os import click from flask.cli import current_app, with_appcontext from scout.constants import...
h("#") is False: LOG.error(f"Resource file '{resname}' doesn't contain valid data.") raise click.Abort() def _fetch_downloaded_resources(resources, downloads_folder): """Populate resource lines if a resou
rce exists in downloads folder Args: resources(dict): downloads_folder(str): path to downloaded files or demo version of these files """ for resname, filenames in UPDATE_DISEASES_RESOURCES.items(): for filename in filenames: resource_path = os.path.join(downloads_folder...
import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/ # SECURITY WARNING: keep the...
afiaConfig', 'dal', 'dal_select2', 'suit', 'django.contrib.admin', 'django.contrib.auth',
'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'debug_toolbar', #'input_mask', ] MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django...
# coding=utf-8 # dictionary value -> 7-segment data Font = { 0: 0b00111111, # (48) 0 1: 0b00000110, # (49) 1 2: 0b01011011, # (50) 2 3: 0b01001111, # (51) 3 4: 0b01100110, # (52) 4 5: 0b01101101, # (53) 5 6: 0b01111101, # (54) 6 7: 0b00100111, # (55) 7 8: 0b01111111, # (56) 8 9: 0b01101111, # (57) ...
d.%d%d%d%d" % ("1" if ((i >> 4) > 9) else " ", (i >> 4) % 10, array10[i & 15
], array100[i & 7], array100[i & 3], array100[(i << 1) & 3])) # else: # print("%d.%d%d%d%d" % (i >> 4, 0, 0, 0, 0))
# -*- coding: utf-8 -*- from django.views.generic import View from django.views.decorators.csrf import csrf_exempt try: from django.http import StreamingHttpResponse as HttpResponse except ImportError: from django.http import HttpResponse from django.utils.decorators import method_decorator from sse import S...
= kwargs response = HttpResponse(self._ite
rator(), content_type="text/event-stream") response['Cache-Control'] = 'no-cache' response['Software'] = 'django-sse' return response def iterator(self): """ This is a source of stream. Must use ``yield`` statement to flush content from sse object to the clie...
import numpy as np import matplotlib.pyplot as plt from matplotlib.widgets import Slider from mpi4py import MPI import sys from cplpy import CPL #initialise MPI and CPL comm = MPI.COMM_WORLD CPL = CPL() MD_COMM = CPL.init(CPL.CFD_REALM) nprocs_realm = MD_COMM.Get_size() ## Parameters of the cpu topology (cartesian g...
_ncxl, BC_ncyl, BC_nczl] = CPL.get_no_cells(BC_portion) #
Allocate send and recv arrays recv_array = np.zeros((4, BC_ncxl, BC_ncyl, BC_nczl), order='F', dtype=np.float64) send_array = np.zeros((9, cnst_ncxl, cnst_ncyl, cnst_nczl), order='F', dtype=np.float64) ft = True Nsteps = 21 for time in range(Nsteps): # send data to update send_array[2,:,:,:] = -5.949063838500...
it__, as it will bypass # our __setitem__ dict.__init__(self) self._as_list = {} self._last_key = None if (len(args) == 1 and len(kwargs) == 0 and isinstance(args[0], HTTPHeaders)): # Copy constructor for k, v in args[0].get_all(): ...
"): log.msg("multipart/form-data value missing name") continue name = disp_params["name"] if disp_params.get("filename"): ctype = headers.get("Content-Type", "application/unknown") files.setdefault(name, []).append(HTTPFile( filename=disp_p...
are copied and modified from python2.7's cgi.py # The original 2.7 version of this code did not correctly support some # combinations of semicolons and double quotes. def _parseparam(s): while s[:1] == ';': s = s[1:] end = s.find(';') while end > 0 and (s.count('"', 0, end) - s.count('\\"', ...
) elif self.summary_method == TimeSeriesSummaryMethod.MAX: masked_summary = numpy.max(masked_stack[band], axis=0) elif self.summary_method == TimeSeriesSummaryMethod.MEAN: masked_summary = numpy.mean(masked_stack[band], axis=0) e...
dataset_str += "NBAR" elif dataset_type == DatasetType.PQ25: dataset_str += "PQA" elif dataset_type == DatasetType.FC25: dataset_str += "FC" elif dataset_type == DatasetType.WATER: dataset_str += "WOFS" if self.apply_pqa_filter and dataset_type !...
setType.PQ25: dataset_str += "_WITH_PQA" return os.path.join(self.output_direc
ck import oauthlib from django.conf import settings from django.core.urlresolvers import reverse from nose.plugins.attrib import attr from courseware.tests import BaseTestXmodule from courseware.views.views import get_course_lti_endpoints from openedx.core.lib.url_utils import quote_slashes from xmodule.modulestore.te...
'preview_handler').rstrip('/?'), 'hide_launch': False, 'has_score': False, 'module_score': None, 'comment':
u'', 'weight': 1.0, 'ask_to_send_username': self.item_descriptor.ask_to_send_username, 'ask_to_send_email': self.item_descriptor.ask_to_send_email, 'description': self.item_descriptor.description, 'button_text': self.item_descriptor.button_text, 'a...
from xblock.fragment import Fragment from xmodule.x_module import XModule from xmodule.seq_module import SequenceDescriptor from xmodule.progress import Progress from pkg_resources import resource_string # HACK: This shouldn't be hard-coded to two types # OBSOLETE: This obsoletes 'type' class_priority = ['video', 'pro...
f.get_display_items(): rendered_child = child.render('student_view', context) fragment
.add_frag_resources(rendered_child) contents.append({ 'id': child.id, 'content': rendered_child.content }) fragment.add_content(self.system.render_template('vert_module.html', { 'items': contents })) return fragment def m...
import require_torch, require_torchaudio from ..test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_speech_available(): from transformers import Speech2TextFeatureExtractor global_rng = random.Random() def floats_list(shape, scale=1.0, rng=None, name=None): """Creates a...
ance_normalization_np(self): feature_extractor = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) speech_
inputs = [floats_list((1, x))[0] for x in range(800, 1400, 200)] paddings = ["longest", "max_length", "do_not_pad"] max_lengths = [None, 16, None] for max_length, padding in zip(max_lengths, paddings): inputs = feature_extractor( speech_inputs, max_length=max_length,...
from django.conf.urls
import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^$', include('lau
nch.urls', namespace="launch", app_name="launch")), url(r'^admin/', include(admin.site.urls)), )
#!/usr/bin/env python import pyflag.IO as IO import pyflag.Registry as
Registry Registry.Init() import pyflag.FileSystem as FileSystem from FileSystem import DBFS case = "demo" ## This gives us a handle to the VFS fsfd = Registry.FILESYSTEMS.fs['DBFS'](case) ## WE just open a file in the VFS: #fd=fsfd.open(inode="Itest|S1/2") ## And read it #print fd.read()
""" Provides the base class for all quadrature rules. """ import numpy as np import copy class QuadRule(object): """ Provides an abstract base class for all quadrature rules. Parameters ---------- order : int The polynomial order up to which the quadrature should be exact """ de...
elf._points = [None] * (dimension + 1) self._weights = [None] * (dimension + 1) self._set_data() def _set_data(self): """ Sets the quadrature points and weights. """ raise NotImplementedError() @property def order(self): return self._order @pro...
return self._dimension @property def points(self): return copy.deepcopy(self._points) @property def weights(self): return copy.deepcopy(self._weights)
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
shed package dependency, execute the following: # python3 -m pip install google-cloud-dialogflow # [START dialogflow_generated_dialogflow_v2_Intents_BatchDeleteIntents_sync] from google.cloud import dialogflow_v2 def sample_batch_
delete_intents(): # Create a client client = dialogflow_v2.IntentsClient() # Initialize request argument(s) intents = dialogflow_v2.Intent() intents.display_name = "display_name_value" request = dialogflow_v2.BatchDeleteIntentsRequest( parent="parent_value", intents=intents, ...
# dj
ango default_app_co
nfig = "zentral.contrib.okta.apps.ZentralOktaAppConfig"
import os import ConfigParser import click from base64 import b64enc
ode import requests import json class B3Notify(object): """ Build status notifier for bitbucket server """ def __init__(self, home='~/.b3notifyrc'): self.home = home self.verbose = True self.config = {} self.build_url = '' self.key = '' self.name = '' ...
nfigParser.ConfigParser() config.read([ os.path.expanduser('~/.b3notifyrc'), '.b3notifyrc', os.path.expanduser('{0}'.format(self.home)), ]) self.url = config.get(profile, 'url').strip("'") self.username = config.get(profile, 'username').strip("'") ...
# import the libraries that you need import requests import csv # make a GET request to the OneSearch X-Service API response = requests.get('http://onesearch.cuny.edu/PrimoWebServices' '/xservice/search/brief?' '&institution=KB' '&query=any,contai...
variable called alldata alldata = response.json() # drill down into a smaller subset of the json # and print this smaller bit of json somedata = alldata['SEGMENTS']['JAGROOT']['RESULT']['FACETLIST']['FACET']\ [1]['FACET_VALUES'] print(somedata) # open a file called mycsv.csv, then loop through the d...
a # and write to that file with open('mycsv.csv', 'wb') as f: writer = csv.writer(f) for x in somedata: writer.writerow([x['@KEY'], x['@VALUE']])
from __future__ im
port print_function, division import numpy as np class Tuning(): """ Equal temperament tuning - allows to convert between frequency and pitch. - unit pitch space - continous, unbounded - 1.0 ~ one octave
- step pitch space - continous, unbounded - N steps ~ one octave - unit pitch space * N - unit pitch class space - continous, bounded [0, 1.0) - unit pitch space % 1.0 - step pitch class space - continous, bounded [0, N) - unit step pitch space % N - integer step pi...
e listed as a tuple with vendor name and device ID. # Examples: ('nvidia', 0x1234), ('arm', 'Mali-T604') # Device IDs must be paired with a GPU vendor. class WebGLConformanceExpectations(test_expectations.TestExpectations): def SetExpectations(self): # Sample Usage: # self.Fail('gl-enable-vertex-attrib.html'...
s/drawingbuffer-test.html', ['mac', 'amd'], bug=314997) # Linux/NVIDIA failures self.Fail('conformance/glsl/misc/empty_main.vert.html', ['linux', ('nvidia', 0x1040
)], bug=325884) self.Fail('conform
esolv_file): return False self.log("Updating jail hostname to `%s-%s`" % (self.vm.name, jail.jail_type)) if not self._update_hostname(jail, rc_file, host_file): return False self.log("Writing yum repository.") if not self._writeYumRepoCon...
msg = "Error while writing authorized keys to jail `%s`: %s" self.log(msg % (jail.jail_type, e)) return False return True def _update_hostname(self, jail, rc
_file, host_file): hostname = "%s-%s" % (self.vm.name, jail.jail_type) self.log("Replacing hostname in %s" % rc_file) (fh, abspath) = tempfile.mkstemp() has_hostname = False tmp = open(abspath, 'w') with open(rc_file, 'r') as f: for line in f: ...