prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
from django.core.urlresolvers import reverse from django.shortcuts import redirect, render from django.utils.timezone import now from django.views.generic import DetailView, ListView from .models import Article, Category from .search import Article as SearchArticle def index(request):
return redirect(reverse('blog:article-list')) class ArticleDetailView(DetailView): model = Article def get_queryset(self): qs = super(ArticleDetailView, self).get_queryset() qs = qs.select_related('author', 'category') if not self.request.user.is_authenticated(): qs =...
rticle_detail = ArticleDetailView.as_view() class ArticleListView(ListView): model = Article def get_queryset(self): qs = super(ArticleListView, self).get_queryset() qs = qs.select_related('author', 'category') if not self.request.user.is_authenticated(): qs = qs.filter(is...
# coding: utf-8 # In[1]: import matplotlib.pyplot as plt #import modules import matplotlib.patches as mpatches import numpy as np #get_ipython().magic(u'matplotlib inline') # set to inline for ipython # In[2]: water = [0,2,2,3,1.5,1.5,3,2,2,2,2,2.5,2] #arrange data from lab alc = [0,2.5,2.5,2.5,2.5,3,2.5,2.5] wei...
actWater, 1) #repeat for water print slopeWater,slopeAlc #print values densityWater = 1/(slopeWater * 0.001) #invert and convert to kg/m^3 densityAlc = 1/(slopeAlc * 0.001) print densityWater, densityAlc #print them # In[3]: actualWater = 1000 # finding percent errors in densities kg/m^3 actualAlc = 789 pErrorWa...
s(actualAlc-densityAlc)/actualAlc) *100 print pErrorWater, pErrorAlc #print percent errors # In[4]: plt.figure() #create figure plt.plot(weight,actWater,"o") # plot scatter of water vs weight (ml/g) plt.plot(weight[:len(actalc)],actalc,"o") #plot scatter of actcalc plt.xlabel("Mass (g)") #add labels plt.ylabel("Disp...
# Copyright 2016 ARM Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writin...
iod, drop_threshold): # pylint: disable=too-many-locals """ Generate frame per second (fps) and associated metrics for workload. refresh_period - the vsync interval drop_threshold - data points below this fps will be dropped """ fps = float('nan') frame_count, j...
vsync_interval = refresh_period # fiter out bogus frames. bogus_frames_filter = self.data.actual_present_time != 0x7fffffffffffffff actual_present_times = self.data.actual_present_time[bogus_frames_filter] actual_present_time_deltas = actual_present_times - actual_present_times.sh...
2016.10.05 -- first version -- John Saeger # gly19 -- 2017.5.27 # This version complains about incomplete sidechains. You must fix them up. # I use pymol's mutate wizard to mutate a residue to itself. # This version has a slightly more sophisticated solvent exposure test. # You can tune it with the solv_thresh vari...
2) print("\nChain {} has {} potential {} glycosylation sites:".format(chain, len(sites), name)) print("[site, score, seq, delta hydropathy]") for gs in sites: print gs if len(common) == 0: common.update(short) else: common = common & set(short) scommon = sorted(common) return scommon # main sheet_commo...
f len(sequence) == 0: continue print("\nChain {} sequence has {} residues:\n{}".format(chain, len(sequence), sequence)) singles, pairs = get_exposed(exposed_file, chain) print("\nChain {} has {} solvent accessible residues:\n{}".format(chain, len(singles), singles)) print("\nChain {} has {} solvent accessible pai...
"""Breast Cancer Data""" __docformat__ = 'restructuredtext' COPYRIGHT = """???""" TITLE = """Breast Cancer Data""" SOURCE = """ This is the breast cancer data used in Owen's empirical likelihood. It is taken from Rice, J.A. Mathematical Statistics and Data Analysis. http://www.cengage.com/statistics/dis...
NOTE: None for exog_idx is the complement of endog_idx return du.process_recarray_pandas(data, endog_idx=0, exog_idx=None, dtype=float) def _get_data(): filepath = dirname(abspath(__file__)) ##### EDIT THE FOLLOWING TO POINT TO DatasetName.csv ##### with open(filep...
) as f: data = np.recfromtxt(f, delimiter=",", names=True, dtype=float) return data
.freq_offset = freq_offset = 1.8e6 self.freq = freq = 433.92e6 self.channel_trans = channel_trans = 1.2e6 self.channel_spacing = channel_spacing = 3000000+2000000 self.initpathprefix = initpathprefix = "/home/user/alarm-fingerprint/AlarmGnuRadioFiles/" self.pathprefix = pathprefi...
lf.blocks_file_sink_1 = blocks.file_sink(gr.sizeof_char*1, recfile4, Fal
se) self.blocks_file_sink_1.set_unbuffered(False) self.blocks_complex_to_mag_squared_0 = blocks.complex_to_mag_squared(1) self.blocks_add_const_vxx_0 = blocks.add_const_vff((addconst, )) ################################################## # Connections ###################...
import os import sys import transaction from pyramid.paster import bootstrap import transaction from mojo.models import root_factory from mojo.blog.models import get_blogroot def usage(argv): cmd = os.path.basename(argv[0]) print('usage: %s <config_uri>\n' '(example: "%s development.ini")' % (cmd...
rite('---\n') file.write('title: ' + blog.title.encode('utf-8')) file.write('timestamp: ' + blog.timestamp.ctime()) file.write('tags: ' + str(blog.tags)) file.write('category: ' + blog.category) file.write('---\n') file.wri
te(blog.raw_content.encode('utf-8')) file.close() def main(argv=sys.argv): if len(argv) != 2: usage(argv) config_uri = argv[1] env = bootstrap(config_uri) root = root_factory(env['request']) dump(root) env['closer']()
from PIL import Image from PIL import ImageDraw from PIL import ImageFile ImageFile.LOAD_TRUNCATED_IMAGES = True def make_regalur_image(img, size=(256, 256)): return img.resize(size).convert('RGB') # 几何转变,全部转化为256*256像素大小 def split_image(img, part_size=(64, 64)): w, h = img.size pw, ph = part_size ...
egion可以用来后续的操作(region其实就是一个 # image对象,box是个四元组(上下左右)) def hist_similar(lh, rh): assert len(lh) == len(rh) return sum(1 - (0 if l == r else float(abs(l - r)) / max(l, r)) for l, r in zip(lh, rh)) / len(lh) # 好像是根据图片的左右间隔来计算某个长度,zip是可以接受多个x,y,z数组值统一输出的输出语句 def calc_similar(li, ri): # return hist_similar(...
, r in zip(split_image(li), split_image(ri))) / 16.0 # 256>64 # 其中histogram()对数组x(数组是随机取样得到的)进行直方图统计,它将数组x的取值范围分为100个区间, # 并统计x中的每个值落入各个区间中的次数。histogram()返回两个数组p和t2, # 其中p表示各个区间的取样值出现的频数,t2表示区间。 # 大概是计算一个像素点有多少颜色分布的 # 把split_image处理的东西zip一下,进行histogram,然后得到这个值 def calc_similar_by_path(lf, rf): ...
import datetime import unittest from freezegun import freeze_time from semantic.dates import DateService @freeze_time('2014-01-01 00:00') class TestDate(unittest.TestCase): def compareDate(self, input, target): service = DateService() result = service.extractDate(input) self.assertEqual(t...
eningTime(self): input = "Let's go to the park at 5." target = "17:00" self.compareTime(input, target) def testInT
he(self): input = "I went to the park in the afternoon" target = "15:00" self.compareTime(input, target) def testBothDateAndTime(self): input = "Let's go to the park at 5 tomorrow." target_time = "17:00" target_date = "2014-01-02" self.compareTime(input, targ...
# Copyright (c) 2017, The MITRE Co
rporation. All rights reserved. # See LICENSE.txt for complete terms. from mixbox import fields import stix from stix.data_marking import MarkingStructure import stix.bindings.extensions.marking.simple_marking as simple_marking_binding @stix.register_extension class SimpleMarkingStructure(MarkingStructure): _bi...
rkingStructure#Simple-1' _XSI_TYPE = "simpleMarking:SimpleMarkingStructureType" statement = fields.TypedField("Statement") def __init__(self, statement=None): super(SimpleMarkingStructure, self).__init__() self.statement = statement
# Generated by Django 3.1.2 on 2021-01-13 17:11 from django.db import migrations class Migrati
on(migrations.Migration): dependencies = [ ('product', '0014_auto_20210113_1803'), ] operations = [ migrations.RemoveField( model_name='product',
name='company', ), ]
, n): l = len(iterator) for i in range(0, l, n): yield iterator[i:min(i + n, l)] datasets = [] for files in batch(self._filenames, batch_size): datasets.append( dataset_ops.Dataset.list_files(files, shuffle=False).map( core_readers.TFRecordDataset)) dataset...
alse]))) def testPipelineWithMap(self, shuffle): dataset = dataset_ops.Dataset.list_files(self._filenames, shuffle=False) dataset = dataset.apply( interleave_ops.parallel_interleave(core_readers.TFRecordDataset, 10)) dataset = dataset.map(lambda x: string_ops.sub
str_v2(x, 2, 1000)) dataset = dataset.batch(5) dataset = distribute._AutoShardDataset(dataset, 5, 3) expected = [ b"cord %d of file %d" % (r, f) # pylint:disable=g-complex-comprehension for r in range(0, 10) for f in (3, 8) ] self.assertDatasetProducesWithShuffle(dataset, e...
# -*- coding: utf-8 -*- from django.db import migrations def set_collection_path_collation(apps, schema_editor): """ Treebeard's path comparison logic can fail on certain locales such as sk_SK, which sort numbers after letters.
To avoid this, we explicitly set the collation for the 'path' column to the (non-locale-specific) 'C' collation. See: https://groups.google.com/d/msg/wagtail/q0leyuCnYWI/I9uDvVlyBAAJ """ if schema_editor.connection.vendor == 'postgresql': schema_editor.execute(""" ALTER TABLE wagta...
"") class Migration(migrations.Migration): dependencies = [ ('wagtailcore', '0026_group_collection_permission'), ] operations = [ migrations.RunPython( set_collection_path_collation, migrations.RunPython.noop ), ]
import os import time from urllib.parse import urljoin import requests as rq from bs4 import BeautifulSoup as bs current_page_url = 0 page_soup = 0 def download_file(file_url, file_path): if os.path.exists(file_path): print(file_path, "already exists") return False i = 0 while i <= 30: ...
up try: image_url = web_page_soup.find('img', {'id': 'image'}).get('src') except: page_soup = bs(rq.get(current_page_url).content, 'lxml') image_url = page_soup.find('img', {'id': 'image'}).get('src') return ima
ge_url def get_chapter_name(web_page_soup): return web_page_soup.find('h1', {'class': 'no'}).find('a').text def create_dir(dir_path): if not os.path.exists(dir_path): os.mkdir(dir_path) return True else: # print("Error creating", dir_path) try: print("Removing...
o ``TraceWorker`` instances and collects their results. Args: workers: ``TraceWorker`` handles. Returns: A (16, 256, NUM_SAMPLES) array A, where A[i, j, :] is the mean of all traces where text byte i is j. """ tasks = [worker.count_and_sum_text_traces.remote() for worker in...
idence scores of these differenc
es. The behavior of the shortest path algorithm is modified using the ``DiffScore`` class such that: - The cost/distance of a path is the minimum of the weights, i.e. confidence scores, of the edges on the path, and - Paths with higher confidence scores are preferred. Consequently,...
# -*- coding: utf-8 -*- from httoop.status.types import StatusException from httoop.uri import URI class RedirectStatus(StatusException): u"""REDIRECTIONS = 3xx A redirection to other URI(s) which are set in the Location-header. """ location = None def __init__(self, location, *args, **kwargs): if not isin...
D, self).__init__(None, *args, **kwargs) header_to_remove = ( "Allow", "Content-Encoding", "Content-Language", "Content-Length", "Content-MD5", "Content-Range", "Content-Type", "Expires", "Location" ) class USE_PROXY(RedirectStatus): code = 305 class
TEMPORARY_REDIRECT(RedirectStatus): u"""The request has not processed because the requested resource is located at a different URI. The client should resent the request to the URI given in the Location-header. for GET this is the same as 303 but for POST, PUT and DELETE it is important that the request was not...
import urllib.request import urllib.parse import json from Admit import Data # number:the number of a student # birthday: the student's birthday, like 9301 # try_time: the request reconnect times when it broken. def get_admit_result_by_number_and_birthday(number, birthday, try_times=3): if try_times == 0: ...
t.urlopen(request, post_data) r_data = f.read().decode('utf-8') except: get_admit_result_by_number_and_birthda
y(number, birthday, try_times - 1) result_json = json.loads(r_data) if result_json['flag'] == 1: result = result_json['result'] if result['zymc'] == Data.SCHOOL: file = open('admit.txt', 'a') file.write(str(result['zkzh'] + ' ' + birthday + ' ' + result['zymc'] + ' ' + r...
# -*- coding: utf-8 -*- # # Configuration file for the Sphinx documentation builder. # # This file does only contain a selection of the most common options. For a # full list see the documentation: # http://www.sphinx-doc.org/en/master/config # -- Path setup ------------------------------------------------------------...
.html']``. # # html_sidebars = {} # -- Options for HTMLHelp output --------------------------------------------- # Output file base name for HTML help builder. htmlhelp_basename = 'whitepagesdoc' # -- Options for LaTeX output ------------------------------------------------ latex_elements = { # The paper size...
preamble. # # 'preamble': '', # Latex figure (float) alignment # # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'white...
def extractXvvCpuMybluehostMe(item): ''' Parser for 'xvv.cpu.mybluehost.me' ''
' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None tagmap = [ ('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel'), ] for tagname, name, tl_type in
tagmap: if tagname in item['tags']: return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type) return False
# -*- coding: utf-8 -*- from .. Error import RINGError class Reader(object): """ Reader reads the parsed RING input, and returns the RDkit wrapper objects in pgradd.RDkitWrapper. Attributes ---------- ast : abstract syntax tree obtrained from parser """ def __init__(self, ast): ...
lf.ReadRINGInput(self.ast[1:]) def Read(text, strict=False): """ Return MolQuery, ReactionQuery, or ReactionNetworkEnumerationQuery by interpretting RING input str
ing. Parameters ---------- text : string Specify string describing chemical structure, elementary reaction, or reaction network enumeration rules in RING notation. strict : boolean, optional If True, then disable use of syntactic extensions such as support for "radical e...
#!/usr/local/bin/python a=['red','orange',
'yellow','green','blue','purple'] odds=a[::2] evens=a[1::2] print odds print evens x=b'abcdefg' y=x[::-1] print y c=['a','b','c','d','e','f'] d=c[::2] e=d[1:-1] p
rint e
bda:defaultdict(lambda:None)) ''' The structure of self.portmap is a four-tuple key and a string value. The type is: (dpid string, src MAC addr, dst MAC addr, port (int)) -> dpid of next switch ''' self.portmap = { # h1 <-- port 80 --> h3 ...
put port %d):", packet.dst, dpid_to_str(event.dpid), event.port) key_map = () try: # """ Add your logic here"""" print "Inside add your logic" print packet.find('tcp') key_map = (this_dpid, pa
cket.src, packet.dst, packet.find('tcp').dstport) if not self.portmap.get(key_map): key_map = (this_dpid, packet.src, packet.dst, packet.find('tcp').srcport)
from __future__ import absolute_import, print_function, unicode_literals from builtins import dict, str import logging from copy import copy from indra.databases import get_identifiers_url from indra.statements import * from indra.util import write_unicode_csv logger = logging.getLogger(__name__) class TsvAssembler...
_text = agent.name # Agent db_refs str db_refs = copy(agent.db_refs) if 'TEXT' in db_refs: db_refs.pop('TEXT') db_refs_str = ','.join(['%s|%s' % (k, v) for k, v in db_refs.items()]) # Agent links identifier_links = [] if up_only and 'UP' in db_refs: ...
label, url = _format_id(ns, id) if url is None: identifier_links.append(label) else: identifier_links.append(url) links_str = ', '.join(identifier_links) return [agent_text, links_str, str(agent)]
64-linux-gnu $CPPFLAGS"' in environment) self.assertTrue( 'LDFLAGS="-Lfoo/lib -Lfoo/usr/lib -Lfoo/lib/x86_64-linux-gnu ' '-Lfoo/usr/lib/x86_64-linux-gnu $LDFLAGS"' in environment) self.assertTrue( 'PKG_CONFIG_PATH=foo/lib/pkgconfig:' 'foo/lib/x86_64-linux-...
'(\'plugins\' was unexpected)' self.assertEqual(raised.exception.message, expected_message, msg=self.data) def test_license_hook(self): self.data['license'] = 'LICENSE' snapcraft.yaml._validate_snapcraft_yaml(self.data) def test_full_license_use(self):...
= 'explicit' self.data['license-version'] = '1.0' snapcraft.yaml._validate_snapcraft_yaml(self.data) def test_license_with_license_version(self): self.data['license'] = 'LICENSE' self.data['license-version'] = '1.0' snapcraft.yaml._validate_snapcraft_yaml(self.data) d...
#!/usr/bin/env python # # Copyright (c) 2011 anatanokeitai.com(sakurai_youhei) # # 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 right...
in(opts.domain) for m in ["email","session"]: if not opts.__dict__[m]: print >>sys.stderr, "mandatory opti
on is missing (%s)\n"%m parser.print_help() exit(2) if not opts.password: opts.password = getpass.getpass() if os.path.isdir(opts.session): print >>sys.stderr, "%s should not be directory."%s exit(2) if opts.verbose: print >>sys.stderr, "Loading previous session...", try: ...
import numpy as np import tensorflow as tf from tensorflow.keras.layers import Dense import tensorflow_datasets as tfds import tensorflow_recommenders_addons as tfra ratings = tfds.load("movielens/100k-ratings", split="train") ratings = ratings.map( lambda x: { "movie_id": tf.strings.to_number(x["movie_i...
self.user_embeddings = tfra.embedding_variable.EmbeddingVariable( name="user_dynamic_embeddings", ktype=tf.int64, embedding_dim=self.embedding_size, initializer=tf.keras.initializers.RandomNormal(-1, 1)) self.movie_embeddings = tfra.embedding_variable.EmbeddingVariable( na...
ormal(-1, 1)) self.loss = tf.keras.losses.MeanSquaredError() def call(self, batch): movie_id = batch["movie_id"] user_id = batch["user_id"] rating = batch["user_rating"] user_id_val, user_id_idx = np.unique(user_id, return_inverse=True) user_id_weights = tf.nn.embedding_lookup(params=self.us...
# -*- coding: utf-8 -*- import importlib import json import os def has_installed(dependency): try: importlib.import_module(dependency) return True ex
cept ImportError: return False def is_tox_env(env): if 'VIRTUAL_ENV' in os.environ: return env in os.environ['VIRTUAL_ENV'] def has_django(): return has_installed('django') def has_pillow(): return has_installed('PIL.Image') def has_redis(): return has_installed('redis') class ...
ter__(self): os.environ['overridden_settings'] = json.dumps(self.settings) def __exit__(self, *args, **kwargs): del os.environ['overridden_settings'] override_settings = OverrideSettings
"""ninetofiver serializers.""" from django.contr
ib.auth import models as auth_models from django.core.exceptions import ValidationError from django.utils.translation import ugettext_lazy as _ from django_countries.serializers import CountryFieldMixin from django.db.models import Q from rest_framework import serializers import logging import datetime from ninetofiver...
port models logger = logging.getLogger(__name__)
import numpy as np from apvisitproc import despike import pytest import os DATAPATH = os.path.dirname(__file__) FILELIST1 = os.path.join(DATAPATH, 'list_of_txt_spectra.txt') FILELIST2 = os.path.join(DATAPATH, 'list_of_fits_spectra.txt') @pytest.fixture def wave_spec_generate(): ''' Read in three small chunks...
:9], spec[25:])), newspec)) def test_despike_spectra(wave_spec_generate): ''' Test that new spectra are shorter t
han the original because the outliers are gone ''' wavelist, speclist = wave_spec_generate[2], wave_spec_generate[3] newwavelist, newspeclist = despike.despike_spectra(wavelist, speclist, type='simple', plot=False) assert len(newwavelist) == len(wavelist) assert len(newspeclist) == len(speclist)
#!/usr/bin/env python3 # -*- mode:python; tab-width:4; c-basic-offset:4; intent-tabs-mode:nil; -*- # ex: filetype=python tabstop=4 softtabstop=4 shiftwidth=4 expandtab autoindent smartindent # # Universal Password Changer (UPwdChg) # Copyright (C) 2014-2018 Cedric Dufour <http://cedric.dufour.name> # Author: Cedric Du...
f.oToken.config('./resources/backend-private.pem', './resources/frontend-public.pem') if(self.oToken.readToken('./tmp/password-change.token')): self.skipTest('Failed to read token') def testType(self): self.assertIn('type', self.oToken.keys()) self.assertEqual(self.oToken['type'...
rd-change') def testTimestamp(self): self.assertIn('timestamp', self.oToken.keys()) self.assertRegex(self.oToken['timestamp'], '^20[0-9]{2}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])T([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]Z$') def testUsername(self): self.assertIn('username', self.oToke...
from django.apps import AppConfig from django.template.base import
add_to_builtins class PrxAppConfig(AppConfig): name = 'prx_aplikacja' verbose_name = 'prx_aplikacja'
def ready(self): add_to_builtins('prx_aplikacja.templatetags.tagi')
# -*- coding: utf-8 -*- """ /***********************************************
**************************** LrsPlugin A QGIS plugin Linear reference system builder and editor ------------------- begin : 2013-10-02 copyright : (C) 2013 by Radim Blažek email : radim.b
lazek@gmail.com Partialy based on qgiscombomanager by Denis Rouzaud. ***************************************************************************/ /*************************************************************************** * * * This progr...
from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import ( fix_xml_ampersands, ) class MetacriticIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?metacritic\.com/.+?/trailers/(?P<id>\d+)' _TESTS = [{ 'url': 'http://www.metacritic.com/game/playstation-4/infamo...
www.metacritic.com/game/playstation-4/tales-from-the-borderlands-a-telltale-game-series/trailers/5740315', 'info_dict': {
'id': '5740315', 'ext': 'mp4', 'title': 'Tales from the Borderlands - Finale: The Vault of the Traveler', 'description': 'In the final episode of the season, all hell breaks loose. Jack is now in control of Helios\' systems, and he\'s ready to reclaim his rightful place as king of Hyperion (with or without y...
from os import getenv from time import time, sleep from core import Platform, Instance from SoftLayer import Client from SoftLayer.CCI import CCIManager from paramiko import SSHClient class _SuppressPolicy(object): def missing_host_key(self, client, hostname, key): pass class CCIPlatform(Platform): ...
ot': password = p['password'] break return password def _cci_install_keys(self, id): cci = self._manager.get_instance(id) password = self._get_cci_root_password(cci) if not password: raise Exception('Passwords are not available for insta...
ot keys_url: return client_settings = {'hostname': cci['primaryIpAddress'], 'username': 'root', 'password': password} client = SSHClient() client.set_missing_host_key_policy(_SuppressPolicy()) client.connect(look_for_keys...
#
Sample script for loading volume data. import voreen # usage: voreen.loadVolume(filepath, [name of VolumeSource processor]) voreen.loadVolume(voreen.getBasePath() + "/data/volumes/nucleon.dat",
"VolumeSource")
import pytest from selenium import webdriver @pytest.fixture def driver(request): wd = webdriver.Chrome() request.addfinalizer(wd.quit) return wd def test_example(driver):
driver.get("http://localhost/litecart/") driver.implicitly_wait(10) sticker_number = len(driver.find_elements_by_xpath("//div[contains(@class,'sticker')]")) product_number = len(driver.find_elements_by_xpath("//*
[contains(@href,'products')]")) assert sticker_number == product_number
# -*- coding: utf-8 -*- # import re from core import httptools from core import scrapertools from platformcode import logger import codecs def get_video_url(page_url, video_password): logger.info("(page_url='%s')" % page_url) video_urls = [] data = httptools.downloadpage(page_url).data list = scrap...
url= scrapertools.find_single
_match(data, '<source src="([^"]+)"') video_urls.append(["[youdbox]", url]) return video_urls
ld"), self.srv.rpc_echo("hello", "world")) class TestRPCInit(ServerTestCase): @mock.patch("elpy.jedibackend.JediBackend") @mock.patch("elpy.ropebackend.RopeBackend") def test_should_set_project_root(self, RopeBackend, JediBackend): self.srv.rpc_init({"project_root": "/proj...
srv = server.ElpyRPCServer() srv.rpc_get_pydoc_completions() get_pydoc_completions.assert_called_with(None) srv.rpc_get_pydoc_completions("foo") get_pydoc_completions.assert_called_with("foo") class TestGetPydocDocumentation(ServerTestCase): @mock.patch("pydoc.render_doc")...
oc_documentation("open") render_doc.assert_called_with("open", "Elpy Pydoc Documentation for %s", False) self.assertEqual("expected", actual) def test_should_re
mock_module.user_submissions) json_in = {'problem1': 'fish'} out = mock_module.get_hint(json_in) self.assertTrue(out is None) self.assertTrue(mock_module.previous_answers == old_answers) self.assertTrue(mock_module.user_submissions == old_user_submissions) def test_gethint_1...
gged in previous_answers. self.assertTrue('25.0' in mock_module.user_submissions) self.assertTrue(['25.0', ['1']] in mock_module.previous_answers) def test_gethint_manyhints(self): """ Someone asks for a hint, with many matching hints in the database. - The top-rat
ed hint should be returned. - Two other random hints should be returned. Currently, the best hint could be returned twice - need to fix this in implementation. """ mock_module = CHModuleFactory.create() json_in = {'problem_name': '24.0'} out = mock_module.get_hint...
shelter=False)) self.parking_slots.append(ParkingSlot( crossroad_idx=26, position=mapping.Point(58396.90234375, -50609.53125, self._terrain), large=False, heli=True, airplanes=True, slot_name='35', length=26.0, width=22.0, height=11.0, shelter=False)) self.parking_slots....
, shelter=False)) self.parking_slots.append(ParkingSlot( crossroad_idx=28, position=mapping.Point(58300.6640625, -50411.23828125, self._terrain), large=False, heli=
True, airplanes=True, slot_name='41', length=26.0, width=22.0, height=11.0, shelter=False)) self.parking_slots.append(ParkingSlot( crossroad_idx=29, position=mapping.Point(58740.3046875, -50171.0859375, self._terrain), large=False, heli=True, airplanes=True, slot_...
# construct function string s = 'from py_entitymatching.feature.simfunctions import *\nfrom py_entitymatching.feature.tokenizers import *\n' # get the function name fn_name = get_fn_name(attr1, attr2, sim_func, tok_func_1, tok_func_2) # proceed with function construction fn_st = 'def ' + fn_name...
attr2 + '"]' fn_body = fn_body + ')) ' else: fn_body = fn_body + sim_func + '(' + 'ltuple["' + attr1 + '"], rtuple["' + attr2 + '"])'
s += fn_body return fn_name, attr1, attr2, tok_func_1, tok_func_2, sim_func, s # construct function name from attrs, tokenizers and sim funcs # sim_fn_names=['jaccard', 'lev', 'cosine', 'monge_elkan', # 'needleman_wunsch', 'smith_waterman', 'jaro', 'jaro_winkler', # 'exact_match'...
from django.forms import CharField, ValidationError from django.forms.fields import EMPTY_VALUES import re, string class TinyMCEField(CharField): def clean(self, value): "Validates max_length and min_length. Returns a Unicode object." if value in EMPTY_VALUES: return u'' ...
value_length = len(stripped_value) value_length -= 1 if self.max_length is not None and value_length > self.max_length: raise ValidationError(self.error_messages['max_length'] % {'max': self.max_length, 'length': value_length}) if self.min_length is not None and value_length <...
return value
#### NOTICE: THIS FILE IS AUTOGENERA
TED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Tangible() result.template = "object/tangible/scout/trap/shared_trap_webber.iff" result.attribute_template_id = -1 result.stfN
ame("item_n","trap_webber") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
.hosterHandler import cHosterHandler from resources.lib.gui.gui import cGui from resources.lib.gui.guiElement import cGuiElement from resources.lib.handler.inputParameterHandler import cInputParameterHandler from resources.lib.handler.outputParameterHandler import cOutputParameterHandler from resources.lib.player impor...
logger.info('call download: ' + sMediaUrl) sLink = urlresolver.resolve(sMediaUrl) if (sLink != False): oDownload = cDownload() oDownload.download(sLink, 'Stream') return #except: # logger.fatal('could not load plugin: ' + sHosterFileName...
erHandler.getValue('sHosterIdentifier') sMediaUrl = oInputParameterHandler.getValue('sMediaUrl') bGetRedirectUrl = oInputParameterHandler.getValue('bGetRedirectUrl') sFileName = oInputParameterHandler.getValue('sFileName') if (bGetRedirectUrl == 'True'): sMediaUrl = s
import sys if sys.version_info < (2, 7): import unittest2 as unittest else: import unittest from datetime import datetime from datetime import date from twilio.rest.resources import parse_date from twilio.rest.resources import transform_params from twilio.rest.resources import convert_keys from twilio.rest.reso...
(parse_date(d), None) def test_fparam(self): d = {"HEY": None, "YOU": 3} ed = {"YOU":3} self.assertEquals(transform_params(d), ed) def test_fparam_booleans(self): d = {"HEY": None, "YOU": 3, "Activated": False}
ed = {"YOU":3, "Activated": "false"} self.assertEquals(transform_params(d), ed) def test_normalize_dates(self): @normalize_dates def foo(on=None, before=None, after=None): return { "on": on, "before": before, "after": after, ...
# Generated by Django 2.2.13 on 2020-08-10 09:35 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('terminal', '0024_auto_20200715_1713'), ] operations = [ migrations.AlterField( model_name='session', name='protocol...
), ('rdp', 'rdp'), ('vnc', 'vnc'), ('telnet', 'telnet
'), ('mysql', 'mysql'), ('k8s', 'kubernetes')], db_index=True, default='ssh', max_length=8), ), ]
attachment_revision.attachment = self.attachment attachment_revision.set_from_request(self.request) attachment_revision.previous_revision = self.attachment.current_revision attachment_revision.save() self.attachment.current_revision = attachment_revision ...
hangeRevisionView(ArticleMixin, View): form_class =
forms.AttachmentForm template_name = "know/plugins/attachments/replace.html" @method_decorator(get_article(can_write=True, not_locked=True)) def dispatch(self, request, article, attachment_id, revision_id, *args, **kwargs): if article.can_moderate(request.user): self.attachment = get_o...
import click import newsfeeds import random import sys from config import GlobalConfig def mixer(full_story_list, sample_number): """Selects a random sample of stories from the full list to display to the user. Number of stories is set in config.py Todo: Add argument support for number of stories to displ...
""" mixed_story_list = random.sample(set(full_story_list), sample_number) return mixed_story_list def default_displa
y(list_of_stories): """Displays a set of stories in the following format: n - Story Title -- OutletName -- Section Story abstract: Lorem ipsum dolor sit amet """ index_num = 0 for story in list_of_stories: index_num += 1 click.secho('%r - ' % index_num, bold=True, nl=False) ...
from mock import Mock from ceph_deploy import install class TestSanitizeArgs(object): def setup(self): self.args = Mock() # set the default behavior we set in cli.py self.args.default_release = False self.args.stable = None def test_args_release_not_specified(self): ...
e that. Future improvement: make the default release a # variable in `ceph_deploy/__init__.py` assert result.default_release is True def test_a
rgs_release_is_specified(self): self.args.release = 'dumpling' result = install.sanitize_args(self.args) assert result.default_release is False def test_args_release_stable_is_used(self): self.args.stable = 'dumpling' result = install.sanitize_args(self.args) assert ...
#!/usr/bin/env python # ***** BEGIN LICENSE BLOCK ***** # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at http://mozilla.org/MPL/2.0/. # ***** END LICENSE BLOCK ***** import os import sys import glob...
ry = os.path.join(os.path.dirname(self.binary_path), executable) cmd.extend(self._build_arg('--binary', binary)) cmd.extend(self._build_arg('--p
rofile', profile)) cmd.extend(self._build_arg('--symbols-path', self.symbols_path)) cmd.extend(self._build_arg('--browser-arg', self.config.get('browser_arg'))) # Add support for chunking if self.config.get('total_chunks') and self.config.get('this_chunk'): chunker = [ o...
class LoggingException(Exception): def __init__(self, message, logger): Exception.__init__(self, message) if logger: logger.error(message) class ConfigError(LoggingException): def __init__(self, message, error=None, logger=None): LoggingException.__init__(self, message, ...
def __init__(self, message, errors=None, logger=None): LoggingException.__init__(self, message, logger) self.errors = errors class StackError(LoggingException): def __init__(self, message, errors=None, logger=None): LoggingException.__init__(self, message, logger) self.errors = e...
self.errors = errors
"""Tests for models.""" from unittest.mock import patch from datetime import datetime from django.contrib.auth.models import User from django.test import TestCase from django.utils import timezone from main.models import Post, Comment class ModelPostTest(TestCase): """Main class for testing Post models of this ...
self.user = User.objects.create(username='testuser') self.test_post = Post.objects.create(author=self.user, title='Test', text='superText') self.comment = Comment.objects.create(post=self.test_post, author=self.user.username, text='superComment', is_app...
"""Comment is rendered as its title.""" self.assertEqual(str(self.comment), self.comment.text) def test_comment_approve(self): """Audit for right work of publish method in comment models.""" self.comment.is_approved = False self.comment.approve() self.assertTrue(self.com...
#Faça um programa que
receba dois números inteiros e gere os números i
nteiros que estão no intervalo compreendido por eles. a=int(input('valor incial')) print (a) b=int(input('valor final')) print (b) while a<b: print(a) a=a+1
""" InaSAFE Disaster risk assessment tool developed by AusAid **Messaging styles.** Contact : ole.moller.nielsen@gmail.com .. note:: 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 2 of the License, or (at your option) any later version. Style constants for use with messaging. Example usage:: from messaging.styles import PROGRESS_...
"" __author__ = 'tim@linfiniti.com' __revision__ = '$Format:%H$' __date__ = '06/06/2013' __copyright__ = ('Copyright 2012, Australia Indonesia Facility for ' 'Disaster Reduction') # These all apply to heading elements PROGRESS_UPDATE_STYLE = { 'level': 5, 'icon': 'icon-cog icon-white', '...
# coding=utf-8 # Author: Idan Gutman # Modified by jkaberg, https://github.com/jkaberg for SceneAccess # URL: https://sick-rage.github.io # # This file is part of SickRage. # # SickRage is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the F...
ESS FOR A P
ARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with SickRage. If not, see <http://www.gnu.org/licenses/>. from __future__ import print_function, unicode_literals import re import time from requests.compat import ...
import os, logging, praw, HTMLParser, ConfigParser, pprint, csv from bs4 import BeautifulSoup from urlparse import urlparse from tldextract import tldextract print "Reddit Research Scraper v0.1" print "============================" ''' Grab the config file (we're gonna need it later on) ''' try: config ...
entions fieldnames = ['resource', 'number of links', 'number of mentions'] #let's grab the stuff from reddit using praw reddit = praw.Reddit(user_agent='linux:ResearchRedditScraper:v0.1 (by /u/plzHowDoIProgram)') username = config.get('user', 'username') password = config.get('user', 'password') print "Lo...
Reddit..." reddit.login(username, password) #DEPRECATED. Will be removed in a future version of PRAW. Password-based authentication will stop working on 2015/08/03 and as a result will be removed in PRAW4. print "We're in. Requesting comments from reddit..." commentPile = reddit.get_comments('learnprogramming'...
import sys, os, operator, json from py4j.java_gateway import JavaGateway from py4j.java_collections import ListConverter '
'' @author: Anant Bhardwaj @date: Nov 1, 2013 ''' class Recommender: def __init__(self): self.gateway = JavaGateway() def get_item_based_recommendations(self, paper_id_list): java_paper_id_list = ListConverter().convert( paper_id_list, self.gateway._gateway_client) recs = self.gateway.entry_p...
= rec.split(',') res.append({'id': r[0], 'score': float(r[1])}) return res def main(): r = Recommender() res = r.get_item_based_recommendations(['pn1460']) print res if __name__ == "__main__": main()
.SetComp, ast.Call) def visit_FunctionDef(self, node): for arg in node.args.defaults: if isinstance(arg, self.MUTABLES): self.add_error(arg) super(CheckForMutableDefaultArgs, self).generic_visit(node) def block_comments_begin_with_a_space(physical_line, line_n...
er_imports(alias.name, alias)
return super(CheckForTranslationIssues, self).generic_visit(node) def visit_ImportFrom(self, node): for alias in node.names: full_name = '%s.%s' % (node.module, alias.name) self._filter_imports(full_name, alias) return super(CheckForTranslationIssues, self).generic_visit(no...
iddleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'misago.users.middleware.UserMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOpt...
.UpdateStatsMiddleware', # Note: always keep SaveChangesMiddleware middleware last one 'misago.threads.posting.savechanges.SaveChangesMiddleware', ) MISAGO_THREAD_TYPES = ( # category and redirect types 'misago.forums.forumtypes.RootCategory', 'misago.forums.forumtypes.Category', 'misago.forums...
umtypes.Redirect', # real thread types 'misago.threads.threadtypes.forumthread.ForumThread', 'misago.threads.threadtypes.privatethread.PrivateThread', 'misago.threads.threadtypes.report.Report', ) # Register Misago directories LOCALE_PATHS = ( os.path.join(MISAGO_BASE_DIR, 'locale'), ) STATICFIL...
# # This file is part of GNU Enterprise. # # GNU Enterprise 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 2, or (at your option) any later version. # # GNU Enterprise is distributed ...
Init(self, Max): self._max = Max self._val = 0
self.WorkingArea = float(self.W-9) self.start = 3 self.UsedSpace = int(math.floor(self.WorkingArea / float(self._max))) self.stepsize = self.WorkingArea / self._max if self.UsedSpace < 1: self.UsedSpace = 1 self.Paint(None,None,None) def Paint(self,v1,v2,v3): ## TODO: This is a...
import re import sys def get_wire(input_value): try: int(input_value) return int(input_value) except ValueError: if callable(wires[input_value]): wires[input_value] = wires[input_value]() return wires[input_value] class Gate: def __init__(self, first_input, oper...
(self): print(self.first_input, 'AND', self.second_input) return get_wire(self.first_input) & get_wire(self.second_input) def logic_OR(self): print(self.first_input, 'OR', self.second_input) return get_wire(self.first_input) | get_wire(self.second_input) def logic_NOT(self): ...
, self.first_input, 'by', self.shift_bits, 'bits') return (get_wire(self.first_input) >> int(self.shift_bits)) & 0xFFFF def logic_LSHIFT(self): print('LSHIFT', self.first_input, 'by', self.shift_bits, 'bits') return (get_wire(self.first_input) << int(self.shift_bits)) & 0xFFFF def logi...
#!/usr/bin/env python # -*- coding: utf-8 -*- # File: mnist-visualizations.py """ The same MNIST ConvNet example, but with weights/activations visualization. """ import tensorflow as tf from tensorpack import * from tensorpack.dataflow import dataset IMAGE_SIZE = 28 def visualize_conv_weights(filters, name): "...
return tf.train.AdamOptimizer(lr) def get_data(): train = BatchData(dataset.Mnist('train'), 128) test = BatchData(dataset.Mnist('test'), 256, remainder=True) return train, test if __name__ == '__main__': logger.auto_set_dir() dataset_train, dataset_test = get_data() config =
TrainConfig( model=Model(), dataflow=dataset_train, callbacks=[ ModelSaver(), InferenceRunner( dataset_test, ScalarStats(['cross_entropy_loss', 'accuracy'])), ], steps_per_epoch=len(dataset_train), max_epoch=100, ) launch_t...
# -*- coding: UTF-8 -*- """ this is the default settings, don't insert into your customized settings! """ DEBUG = True
TESTING = True SECRET_KEY = "5L)0K%,i.;*i/s(" SECURITY_SALT = "sleiuyyao" # DB config SQLALCHEMY_DATABASE_URI = "sqlite:///dev.db" SQLALCHEMY_ECHO = True UPLOADS_DEFAULT_DEST = 'uploads' LOG_FILE = 'log.txt' ERROR_LOG_RECIPIENTS = [] # Fla
sk-Mail related configuration, refer to # `http://pythonhosted.org/flask-mail/#configuring-flask-mail` MAIL_SERVER = 'smtp.foo.com' MAIL_USERNAME = 'username' MAIL_PASSWORD = 'password' MAIL_DEFAULT_SENDER = 'user@foo.com' FREEZER_RELATIVE_URLS = False
# $Filename$ # $Authors$ # Last Changed: $Date$ $Committer$ $Revision-Id$ # # Copyright (c) 2003-2011, German Aerospace Center (DLR) # All rights reserved. # # #Redistribution and use in source and binary forms, with or without #modification, are permitted provided that the following conditions are #met: # ...
e # distribution. # # * Neither the name of the German Aerospace Center 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 COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS"...
ND FITNESS FOR #A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT #OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, #SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT #LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, #DATA, OR PROFITS...
# Copyright (c) 2007-2017 Joseph Hager. # # Copycat is free software; you can redist
ribu
te it and/or modify # it under the terms of version 2 of the GNU General Public License, # as published by the Free Software Foundation. # # Copycat is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ...
# -*- coding: utf-8 -*- from time import strftime from django.db.models import Max from django.shortcuts import render_to_response, get_object_or_404 from django.core.paginator import QuerySetPaginator, InvalidPage, EmptyPage from django.core.urlresolvers import reverse from django.utils.feedgenerator import Rss201rev...
link=feed_link) items = items.order_by('-time')[:50] current_site = Site.objects.get_current() for tl_item in items: feed.add_item(title=render_to_string('timeline/feed_item_title.html', {'item': tl_item, 'current_...
eline/item.html', {'item': tl_item, 'current_site': current_site}), link=render_to_string('timeline/feed_item_link.html', {'item': tl_item, 'curren...
max_length is None: max_length = max(min_length * 2, 16) if padding: max_length = max_length - padding min_length = max(min_length - padding, 0) if max_length < required_length: raise MockCreationError( 'This field is too short to hold the mock data') min_leng...
e def validate(self, value): """ Validate the field and return a clean value or raise a ``ValidationError`` with a list of erro
rs raised by the validation chain. Stop the validation process from continuing through the validators by raising ``StopValidation`` instead of ``ValidationError``. """ errors = [] for validator in self.validators: try: validator(value) e...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from hwt.interfaces.std import VectSignal from hwt.interfaces.utils import addClkRstn from hwt.simulator.simTestCase import SimTestCase from hwt.synthesizer.unit import Unit from hwtHls.hlsStreamProc.streamProc import HlsStreamProc from hwtHls.platform.virtual import Virt...
ror from hwtSimApi.utils import freq_to_period class AlapAsapDiffExample(Unit): def _config(self): self.CLK_FREQ = int(400e6) def _declr(self): addClkRstn(self) self.clk.FREQ = s
elf.CLK_FREQ self.a = VectSignal(8) self.b = VectSignal(8) self.c = VectSignal(8) self.d = VectSignal(8)._m() def _impl(self): hls = HlsStreamProc(self) # inputs has to be readed to enter hls scope # (without read() operation will not be schedueled by HLS ...
''' MiPyBot 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. MiPyBot is distributed in the hope that it will be useful, but WITHOUT ANY WARRA...
of the GNU General Public Licens
e along with MiPyBot. If not, see {http://www.gnu.org/licenses/}. ''' # To be implemented
# Loosely based on https://github.com/Skarlso/SublimeGmailPlugin by Skarlso import sublime import sublime_plugin from smtplib import SMTP from email.mime.text import MIMEText from email.header import Header # from email.headerregistry import Address # from email.utils import parseaddr, formataddr config = { # TO...
Lastname", "recipients": "first@recipient.com; second@recipient.com; third@recipient.com", "subject": u"Sent from SublimeText" }, # TODO Set to "true" to be prompted to edit the value, "false" to silently use the default_value from above "interactive": { "smt
p_login": False, "smtp_passwd": False, "from": False, "display_name": True, "recipients": False, "subject": True }, # The prompt message to the user for each field "prompt": { "smtp_login": "GMail User ID", "smtp_passwd": "GMail Password", "fro...
from ginger import utils from datetime impo
rt datetime, timedelta from django.core.cache import cache from django.conf import settings from django.utils import timezone import pytz __all__ = ['CurrentRequestMiddleware', 'MultipleProxyMiddleware', 'ActiveUserMiddleware', 'Last
LoginMiddleware', 'UsersOnlineMiddleware' ] class CurrentRequestMiddleware(object): """ This should be the first middleware """ def process_request(self, request): ctx = utils.context() ctx.request = request def process_response(self, request, response): ctx = ...
# =============================================================================== # Copyright (C) 2010 Diego Duclos # # This file is part of eos. # # eos is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free So
ftware Foundation, either version 2 of the License, or # (at your option) any later version. # # eos is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for...
ave received a copy of the GNU Lesser General Public License # along with eos. If not, see <http://www.gnu.org/licenses/>. # =============================================================================== from sqlalchemy import Column, String, Integer, Boolean, ForeignKey, Table from sqlalchemy.orm import relation, m...
""" Handler for Juniper device specific information. Note that for proper import, the classname has to be: "<Devicename>DeviceHandler" ...where <Devicename> is something like "Default", "Junos", etc. All device-specific handlers derive from the DefaultDeviceHandler, which implements the generic information need...
r(__name__) class JunosDeviceHandler(DefaultDeviceHandler): """ Juniper handler for device specific information. """ def __init__(self, device_params): super(JunosDeviceHandler, self).__init__(device_params) self.__reply_parsing_error_transform_by_cls = { GetSchemaReply: ...
nfiguration dict["load_configuration"] = LoadConfiguration dict["compare_configuration"] = CompareConfiguration dict["command"] = Command dict["reboot"] = Reboot dict["halt"] = Halt dict["commit"] = Commit dict["rollback"] = Rollback return dict def p...
the GNU General
Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GNU Radio Companion is di
stributed 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 this program; if not, writ...
t_dtype indexer = [2, 1, 0, 1] result = algos.take_nd(data, indexer, fill_value=fill_value) assert (result[[0, 1, 2, 3]] == data[indexer]).all() assert result.dtype == dtype def test_2d_fill_nonna(self, dtype_fill_out_dtype): dtype, fill_value, out_dtype = dtype_fill_out_d...
_value=fill_value) assert (result[
[0, 1, 2, 3], :] == data[indexer, :]).all() assert result.dtype == dtype result = algos.take_nd(data, indexer, axis=1, fill_value=fill_value) assert (result[:, [0, 1, 2, 3]] == data[:, indexer]).all() assert result.dtype == dtype def test_3d_fill_nonna(self, dtype_fill_out_dtype): ...
# Generated by Django 2.2.12 on 2020-04-25 15:53 from django.db import migrations, models import django.db.models.deletion import djangocms_text_ckeditor.fields import parler.fields import parler.models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ ...
d(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('language_code', models.CharField(db_index=True, max_length=15, verbose_name='Language')), ('name', models.CharField(max_length=100, verbose_name='Name')), ('description', djangocms_text_ckedito...
ion')), ('master', parler.fields.TranslationsForeignKey(editable=False, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='translations', to='partners.Partner')), ], options={ 'verbose_name': 'partner Translation', 'db_table': 'p...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration):
dependencies = [ ('firecares_core', '0008_auto_20161122_1420'), ] operations = [ migrations.CreateModel( name='RegistrationWhitelist', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False,
auto_created=True, primary_key=True)), ('email_or_domain', models.CharField(unique=True, max_length=254)), ], ), ]
# -*- coding: utf-8 -*- """Prepare configure file for fuzzy slope position inference program. @author : Liangjun Zhu @changelog: - 15-09-08 lj - initial implementa
tion. - 17-07-30 lj - reorganize and incorpo
rate with pygeoc. """ from __future__ import absolute_import, unicode_literals import time from io import open import os import sys if os.path.abspath(os.path.join(sys.path[0], '..')) not in sys.path: sys.path.insert(0, os.path.abspath(os.path.join(sys.path[0], '..'))) from pygeoc.utils import StringClass from au...
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.editor, name="editor"), url(r'^game/$', views.edit_game, name="add_game"), url(r'^game/(?P<gameid>\d+)/$', views.edit_game, name="edit_game"), url(r'^event/$', views.edit_event, name="add_event"), url(r'^event...
/$', views.edit_event, name="edit_event"), url(r'^ajax/player/$', views.ajax_player_sea
rch, name="ajax_player_search"), url(r'^api/game/(?P<game_id>\d+)/$', views.gameview, name='get_game'), url(r'^api/game/$', views.gameview, name='new_game'), url(r'^api/games/$', views.gamelist, name='get_games'), url(r'^api/ev/(?P<ev_id>\d+)/$', views.evview, name='get_ev'), url(r'^api/ev/$', vie...
#!/usr/bin/env python # encoding: utf-8 from efl.evas import EVAS_HINT_EXPAND, EVAS_HINT_FILL from efl import elementary from efl.elementary.window import StandardWindow from efl.elementary.box import Box from efl.elementary.spinner import Spinner EXPAND_BOTH = EVAS_HINT_EXPAND, EVAS_HINT_EXPAND EXPAND_HORIZ = EVAS_H...
lementary.init() spinner_clicked(None) e
lementary.run() elementary.shutdown()
# coding: utf-8 # Copyright (c) P
ymatgen Development Team. # Distributed under the terms of the MIT License. """ This package contains various command line wrappers to progra
ms used in pymatgen that do not have Python equivalents. """
import numpy as np # モジュールnumpyを読み込み import matplotlib.pyplot as plt # モジュールmatplotlibのpylab関数を読み込み def bernstein(t, n, i): # bernstein基底関数の定義 cn, ci, cni = 1.0, 1.0, 1.0 for k in range(2, n, 1): cn = cn *
k for k in range(1, i, 1): if i == 1: break ci = ci * k for k in range(1, n - i + 1, 1): if n == i: break cni = cni * k j = t**(i - 1) * (1 - t)**(n - i) * cn / (ci * cni) return j def bezierplot(t, cp): # bezier曲線の定義 n = len(cp) r = np...
len(t)): sum1, sum2 = 0.0, 0.0 for i in range(1, n + 1, 1): bt = bernstein(t[k], n, i) sum1 += cp[i - 1, 0] * bt sum2 += cp[i - 1, 1] * bt r[k, :] = [sum1, sum2] return np.array(r) cp = np.array([[0, -2], [1, -3], [2, -2], [3, 2], [4, 2], [5, 0]]) # 制御点...
""" bjson/main.py Copyright (c) 2010 David Martinez Marti All rights reserved. Licensed under 3-clause BSD License. See LICENSE.txt for the full license text. """ import socket import bjsonrpc.server import bjsonrpc.connection import bjsonrpc.handlers __all__ = [ "createserver", "...
ocket.SO_REUSEADDR, 1) sock.bind((host, port)) sock.listen(3) return bjsonrpc.server.Server(sock, handler_factory=handler_factory, http=http) def connect(host="127.0.0.1", po
rt=10123, sock=None, handler_factory=bjsonrpc.handlers.NullHandler): """ Creates a *bjson.connection.Connection* object linked to a connected socket. Parameters: **host** Address (IP or Host Name) to connect to. **port** P...
response, actual_response) @mock.patch('testrail.api.requests.get') def test_get_suites_with_project(self, mock_get): mock_response = mock.Mock() expected_response = self.suites_2 url = 'https://<server>/index.php?/api/v2/get_suites/2' mock_response.json.return_value = self.mock...
cted_response, actual_response) @mock.patch('testrail.api.requests.get') def test_get_suite_with_id(self, mock_get): mock_response = mock.Mock() expected_response = next(filter( lambda x: x if x['id'] == 2 else None, self.suites_1))
url = 'https://<server>/index.php?/api/v2/get_suites/1' mock_response.json.return_value = self.mock_suites_data_1 mock_response.status_code = 200 mock_get.return_value = mock_response actual_response = self.client.suite_with_id(2) actual_response = self.client.suite_with_id(2...
import os from django.contrib.auth import authenticate from django.contrib.auth.tests.utils import skipIfCustomUser from django.contrib.auth.models import User, Permission from django.contrib.contenttypes.models import ContentType from django.contrib.auth.context_processors import PermWrapper, PermLookupDict from djan...
apped # User is a fatal TypeError: "function() takes at least 2 arguments # (0 given)" deep inside deepcopy(). # # Python 2.5 and 2.6 succeeded, but logged internally caught exception # sp
ew: # # Exception RuntimeError: 'maximum recursion depth exceeded while # calling a Python object' in <type 'exceptions.AttributeError'> # ignored" Q(user=response.context['user']) & Q(someflag=True) # Tests for user equality. This is hard because User defines ...
# Copyright (C) 2014 Red Hat, Inc., Bryn M. Reeves <bmr@redhat.com> # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # ...
t-el6toel7', 'redhat-upgrade-tool' ) files = ( "/var/log/upgrade.log", "/var/log/redhat_update_tool.log", "/root/preupgrade/all-xccdf*", "/root/preupgrade/kickstart" ) def postproc(self): self.do_file_sub( "/root/preupgrade/kickstart/anaconda...
r"(useradd --password) (.*)", r"\1 ********" ) self.do_file_sub( "/root/preupgrade/kickstart/anaconda-ks.cfg", r"(\s*rootpw\s*).*", r"\1********" ) self.do_file_sub( "/root/preupgrade/kickstart/untrackeduser", r"\...
# -*- coding: utf-8 -*- """ @file @brief Helpers for :epkg:`Flask`. """ import traceback import threading from flask import Response def Text2Response(text): """ convert a text into plain text @param text text to convert @return textReponse """ return Response(text...
//werkzeug.pocoo.org/>`_ returns this instance in function `serving.run_simple <https://github.com/mitsuhiko/werkzeug/blob/master/werkzeug/serving.py>`_ * module `Flask <http://flask.pocoo.org/>`_ returns this instance in method `app.Flask.run <https://github.com/mitsuhik...
k/app.py>`_ """ raise NotImplementedError() # self.server.shutdown() # self.server.server_close()
#!/usr/bin/env python # vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (c) 2012 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 # ...
%(token)s, %(token_dict)s"), {'token': token, 'token_dict': token_dict}) def _validate_token(self, context, token): instance_uuid = token['instance_uuid'] if ins
tance_uuid is None: return False # NOTE(comstud): consoleauth was meant to run in API cells. So, # if cells is enabled, we must call down to the child cell for # the instance. if CONF.cells.enable: return self.cells_rpcapi.validate_console_port(context, ...
# -*- coding: utf-8 -*- from openerp import SUPERUSER_ID from openerp.osv import fields, osv import openerp.addons.decimal_p
recision as dp import datetime import re class rhwl_project(osv.osv): _name = "rhwl.project" _columns = { "name":fields.char(u"项目名称"), "catelog":fields.char(u"类别"), "process":fields.char(u"进度"), "user_id":fields.many2one("res.users",u"负责人"),
"content1":fields.char(string = u"12月5"), "content2":fields.char(string = u"12月12"), "content3":fields.char(string = u"12月19"), "content4":fields.char(string = u"12月26"), "content5":fields.char(string = u"01月2"), "content6":fields.char(string = u"01月9"), "content7":fields...
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
ient = dialogflowcx_v3beta1.SessionsAsyncClient() # Initialize request argument(s) query_input = dialogflowcx_v3beta1.QueryInput() query_input.text.text = "text_value" query_input.language_code = "language_code_value" request = di
alogflowcx_v3beta1.DetectIntentRequest( session="session_value", query_input=query_input, ) # Make the request response = await client.detect_intent(request=request) # Handle the response print(response) # [END dialogflow_v3beta1_generated_Sessions_DetectIntent_async]
# -*- coding: utf-8 -*- # Generated by Django 1.10 on 2017-04-02 19:
34 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('mhap', '0003_auto_20170402_1906'), ] operatio
ns = [ migrations.DeleteModel( name='Quote', ), ]
# coding: utf-8 from __future__ import (absolute_import, division, print_function, unicode_literals) from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(...
se, null=True, blank=True), keep_default=False) # Adding field 'JednostkaAdministracyjna.aktywny' db.add_column(u'teryt_jednostkaadministracyjna', 'aktywny', self.gf('django.db.models.fields.NullBooleanField')(default=False, null=True, blank=True), ...
eryt_rodzajmiejsowosci', 'aktywny', self.gf('django.db.models.fields.NullBooleanField')(default=False, null=True, blank=True), keep_default=False) def backwards(self, orm): # Deleting field 'Miejscowosc.aktywny' db.delete_column(u'teryt_miejscowosc', 'ak...
pool.checkedout() print 'Pool size: %d Connections in pool: %d Current '\ 'Overflow: %d Current Checked out connections: %d' % tup return tup c1 = p.connect() self.assert_(status(p) == (3, 0, -2, 1)) c2 = p.connect() self.assert_(status(p) == (3,...
ol_size=1, max_overflow=0, use_
threadlocal=False) c1 = p.connect() c_id = c1.connection.id c1.close() c1 = None c1 = p.connect() assert c1.connection.id == c_id dbapi.raise_error = True c1.invalidate() c1 = None c1 = p.connect() assert c1.connection.id != c_id ...
#!/usr/bin/python -tt # Quality scores from fastx # Website: ht
tp://hannonlab.cshl.edu/fastx_toolkit/ # Import OS features to run external programs import os import glob v = "Version 0.1" # Versions: # 0.1 - Simple script to run cutadapt on all of the files fastq_indir = "/home/chris/transcriptome/fastq/trimmed/" fastq_outdir = "/home/chris/transcriptome/fastq/reports/quality s...
xt" % (fastq_indir, fastq_outdir)) os.system("fastx_quality_stats -i %s/Sample_1_L002_trimmed.fastq %s/Sample_1_L002_trimmed.txt" % (fastq_indir, fastq_outdir))
# Copyright 2014 Baidu, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file # except in compliance with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unles
s 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. """ This mod...
http responses from TSDB services. """ import http.client import json from baidubce import utils from baidubce.exception import BceClientError from baidubce.exception import BceServerError from baidubce.utils import Expando def parse_json(http_response, response): """If the body is not empty, convert it to a pyth...
'@param prefix a string, the XML namespace prefix being used for this package.', '@param {0}ns a pointer to the namesspaces object ({1}PkgNamespaces) for this package.'.format(package, up_package)] return_lines = [] additional = ['@copydetails doc_what_are_xmlnamespaces', ' ', ...
self.write_constructor_args(ns) # create the function implementation if not self.has_children: code = [] else: code = [dict({'code_type': 'line', 'code': ['connectToChild()']})] return dict({'title_lin
e': title_line, 'params': params, 'return_lines': return_lines, 'additional': additional, 'function': function, 'return_type': return_type, 'arguments': arguments, 'constant...
from setuptools import setup def setup_package(): # PyPi doesn't accept markdown as HTML output for long_description # Pypandoc is only required for uploading the metadata to PyPi and not installing it by the user # Try to covert Mardown to RST file for long_description try: import pypandoc ...
except ImportError: print("warning: pypandoc module not found, could not convert Markdown to RST") with open('README.md') as f: long_description = f.read() # Define the meatadata as dictionary metadata = dict( name='PyOmics',
version='0.0.1.dev8', description='A library for dealing with omic-data in the life sciences', long_description=long_description, url='https://github.com/FloBay/PyOmics.git', author='Florian P. Bayer', author_email='f.bayer@tum.de', license='BSD', classifie...
# Copyright 2015-2017 Cisco Systems, 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 req...
info_len] if inf
o_type == 0: infor_tlv['string'] = info_value.decode('ascii') elif info_type == 1: infor_tlv['reason'] = cls.reason_codict[struct.unpack('!H', info_value)[0]] data = data[4 + info_len:] return cls(value=infor_tlv)
1=1, arg2=2)) """) p = testdir.makepyfile(""" def pytest_generate_tests(metafunc): metafunc.addcall(funcargs=dict(arg1=1, arg2=1)) class TestClass: def test_myfunc(self, arg1, arg2): assert arg1 == arg2 """) res...
ile(""" def pytest_generate_tests(metafunc): metafunc.addcall({'arg1': 10}) metafunc.addcall({'arg1': 20}) class TestClass: def test_func(self, arg1): assert not hasattr(self
, 'x') self.x = 1 """) result = testdir.runpytest("-v", p) result.stdout.fnmatch_lines([ "*test_func*0*PASS*", "*test_func*1*PASS*", "*2 pass*", ]) def test_issue28_setup_method_in_generate_tests(self, testdir): p = tes...
# -*- coding: utf-8 -*- #------------------------------------------------------------ # tvalacarta - XBMC Plugin # Canal para Ecuador TV # http://blog.tv
alacarta.info/plugin-xbmc/tvalacarta/ #------------------------------------------------------------ import urlparse,re import urllib import os from core import
logger from core import scrapertools from core.item import Item DEBUG = False CHANNELNAME = "ecuadortv" def isGeneric(): return True def mainlist(item): logger.info("tvalacarta.channels.ecuadortv mainlist") return programas(item) def programas(item): logger.info("tvalacarta.channels.ecuadortv canal...