prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
# Make
sure to update package.json, too! version_info = (4, 3, 0) __version__ = '.'.join(map(str,
version_info))
#!/usr/bin/env python # -*- coding: utf-8 -*- #Author: Tim Henderson #Email: tim.
tadh@hackthology
.com #For licensing see the LICENSE file in the top level directory. from predictive import parse def t_expr_compound(): assert (4*3/2) == parse('4*3/2') assert (4/2*3) == parse('4/2*3') assert ((3+9)*4/8) == parse('(3+9)*4/8') assert (((9-3)*(5-3))/2 + 2) == parse('((9-3)*(5-3))/2 + 2') assert (5...
import urllib2 import eyed3 import mechanize import os from bs4 import BeautifulSoup as bs import unicodedata as ud import sys import string reload(sys) sys.setdefaultencoding('utf-8') class Song: def __init__(self, keyword, filename, albumart, aaformat, dd='/home/praneet/Music/'): self.info = keyword.split('@') ...
etchalbum(self
): browser = mechanize.Browser() browser.set_handle_robots(False) browser.addheaders = [('User-agent','Mozilla')] searchURL = "https://www.google.co.in/search?site=imghp&source=hp&biw=1414&bih=709&q="+urllib2.quote(self.title+' '+self.artist+' album name') html = browser.open(searchURL) soup = bs(html, 'htm...
etting. """ apphooks = ( '%s.%s' % (APP_MODULE, APP_NAME), ) with SettingsOverride(CMS_APPHOOKS=apphooks): apphook_pool.clear() hooks = apphook_pool.get_apphooks() app_names = [hook[0] for hook in hooks] self.assertEqual(len(hoo...
plateUsed(response, 'sampleapp/extra.html') self.assertContains(response, "test urlconf") path = reverse('de:extra_first') response = self.client.get(path) self.assertEquals(response.status_code, 200) self.assertTemplateUsed(response, 'sampleapp/extra.html') ...
th = reverse('de:extra_second') response = self.client.get(path) self.assertEquals(response.status_code, 200) self.assertTemplateUsed(response, 'sampleapp/extra.html') self.assertContains(response, "test included urlconf") apphook_pool.clear() def test_a...
from django.conf.urls import patterns, url, includ
e fr
om .views import GalleryListView, GalleryDetailView urlpatterns = patterns("", url( regex=r"^gallery_list/$", view=GalleryListView.as_view(), name="gallery_list", ), url( regex=r"^gallery/(?P<pk>\d+)/$", view=GalleryDetailView.as_view(), name="gallery_detai...
# Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain
a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or 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. """Flag related helpers for sole tenancy related commands.""" from googlecloudsdk.comm...
import unittest, time, sys, re sys.path.extend(['.','..','../..','py']) import h2o, h2o_nn, h2o_cmd, h2o_browse as h2b, h2o_import as h2i, h2o_gbm def write_syn_dataset(csvPathname, rowCount, rowDataTrue, rowDataFalse, outputTrue, outputFalse): dsf = open(csvPathname, "w+") for i in range(int(rowCount/2)): ...
h2o.tear_down_cloud(h2o.nodes) def test_DeepLearning_twovalues(self): SYNDATASETS_DIR = h2o.make_syn_dir() csvFilename = "syn_twovalues.csv" csvPathname = SYNDATASETS_DIR + '/' + csvFilename rowDataTrue = "1, 0, 65, 1, 2, 1, 1, 4, 1, 4, 1, 4" rowDataFalse = ...
twoValueList = [ ('A','B',0, 14), ('A','B',1, 14), (0,1,0, 12), (0,1,1, 12), (0,1,'NaN', 12), (1,0,'NaN', 12), (-1,1,0, 12), (-1,1,1, 12), (-1e1,1e1,1e1, 12), (-1e1,1e1,-1e1, 12), ]...
de, default_temp) config.default_temp_away = default_temp else: config.indoor_temp_target=default_temp_away elif (0 <= now.hour < 7) and home_status=='home': config.mode='night' if config.mode == default_temp_mode and default_temp !...
rn furnace_state def
checkOutdoorTemp(zip_code): """Gets outdoor temperature for our ZIP code from Yahoo!""" try: yahoo_com_result = pywapi.get_weather_from_yahoo( zip_code, units = 'metric' ) outdoor_temperature = int(yahoo_com_result['condition']['temp']) except (KeyError, AttributeError, httplib.BadStatusLin...
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE L
OST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Creature() result.template = "object/mobile/shared_dressed_binayre_ruffian_trandoshan_male_01.iff" result.attribute_template_id = 9 result.stfName("npc_name","trandoshan_base_male...
t
# -*- coding: utf-8 -*- # # This tool helps you rebase your package to the latest version # Copyright (C) 2013-2019 Red Hat, Inc. # # 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...
sage, default_yes=True, any_input=False):
"""Prompts a user with yes/no message and gets the response. Args: message (str): Prompt string. default_yes (bool): If the default value should be YES. any_input (bool): Whether to return default value regardless of input. Returns: bool: True or False, ...
#!/usr/bin/env python #coding=utf8 import datetime import logging from handler import UserBaseHandler from lib.route import route from lib.util import vmobile @route(r'/user', name='user') #用户后台首页 class UserHandler(UserBaseHandler): def get(self): user = self.get_current_user() try: ...
pass self.render('user/index.html') @route(r'/user/profile', name='user_profile') #用户资料 class ProfileHandler(UserBaseHandler):
def get(self): self.render('user/profile.html') def post(self): self.redirect('/user/profile')
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
e_GetGlossary_sync] from google.clo
ud import translate_v3beta1 def sample_get_glossary(): # Create a client client = translate_v3beta1.TranslationServiceClient() # Initialize request argument(s) request = translate_v3beta1.GetGlossaryRequest( name="name_value", ) # Make the request response = client.get_glossary(r...
from galaxy.test.base.twilltestcase import TwillTestCase #from twilltestcase import TwillTestCase class EncodeTests(TwillTestCase): def test_00_first(self): # will run first due to its name """3B_GetEncodeData: Clearing histo
ry""" self.clear_history() def test_10_Encode_Data(self): """3B_GetEncodeData: Getting encode data"""
self.run_tool('encode_import_chromatin_and_chromosomes1', hg17=['cc.EarlyRepSeg.20051216.bed'] ) # hg17=[ "cc.EarlyRepSeg.20051216.bed", "cc.EarlyRepSeg.20051216.gencode_partitioned.bed", "cc.LateRepSeg.20051216.bed", "cc.LateRepSeg.20051216.gencode_partitioned.bed", "cc.MidRepSeg.20051216.bed", "cc.MidRepSeg.200512...
from django.conf.urls import url from django.contrib.auth.views import login, \ logout, \ logout_then_login, \ password_change, \ password_change_done,
\ password_reset, \ password_reset_done, \ password_reset_confirm, \ password_reset_complete from . import views urlpatterns = [ url(r'^$', views.dashboard, name=
'dashboard'), # login / logout urls url(r'^login/$', view=login, name='login'), url(r'^logout/$', view=logout, name='logout'), url(r'^logout-then-login/$', view=logout_then_login, name='logout_then_login'), # change password urls url(r'^password-change/$', view=password_change, name='password_...
from lacuna.building import MyBuilding class fis
sion(MyBuilding): path = 'fission' def __init__( self, client, body_id:int = 0, building_id:int = 0 ): super().__init__( client, body_id,
building_id )
import unittest from nose.tools import assert_equals from robotide.robotapi import TestCaseFile, TestCaseFileSettingTable from robotide.controller.filecontrollers import TestCaseFileController from robotide.controller.tablecontrollers import ImportSettingsController VALID_NAME = 'Valid name' class TestCaseNameVali...
d, expected_valid) class TestCaseCreationTest(unittest.TestCase): def setUp(self): self.ctrl = TestCaseFileController(TestCaseF
ile()).tests def test_whitespace_is_stripped(self): test = self.ctrl.new(' ' + VALID_NAME + '\t \n') assert_equals(test.name, VALID_NAME) class LibraryImportListOperationsTest(unittest.TestCase): def setUp(self): self._parent = lambda:0 self._parent.mark_dirty = lambda:0 ...
#!/usr/bin/python # coding: utf-8 -*- # (c) 2017, Wayne Witzel III <wayne@riotousliving.com> # # This module 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 opti...
ansible.module_utils.ansible_tower import ( tower_auth_config, tower_check_mode, tower_argument_spec, ) HAS_TOWER_CLI = True except ImportError: HAS_TOWER_CLI = False def main(): argument_spec = tower_argument_spec() argument_s
pec.update(dict( job_template=dict(required=True), job_type=dict(choices=['run', 'check', 'scan']), inventory=dict(), credential=dict(), limit=dict(), tags=dict(type='list'), extra_vars=dict(type='list'), )) module = AnsibleModule( argument_spec, ...
# coding: utf-8 from django.views.generic import CreateView, UpdateView, DeleteView from django.http import HttpResponse, HttpResponseRedirect from django.template.loader import render_to_string from django.template import RequestContext from django.core.serializers.json import DjangoJSONEncoder from django.conf import...
elf.object, 'object': self.object } def get_message_template_html(self): return render_to_string( self.message_template, self.get_message_template_context(), context_instance=RequestContext(self.request) ) def get_response_message(self): ...
ge_template_html() return message def get_success_result(self): return {'status': 'ok', 'message': self.get_response_message()} def get_error_result(self, form): html = render_to_string( self.template_name, self.get_context_data(form=form), context_i...
from django.apps import
AppConfig class IndexConfig(AppConfig): name = 'web.
index'
import pandas as pd from requests import get from StringIO import StringIO from pandas.io.common import ZipFile def get_movielens_data(local_file=None, get_genres=False): '''Downloads movielens data and sto
res it in pandas da
taframe. ''' if not local_file: #print 'Downloading data...' zip_file_url = 'http://files.grouplens.org/datasets/movielens/ml-1m.zip' zip_response = get(zip_file_url) zip_contents = StringIO(zip_response.content) #print 'Done.' else: zip_contents = local_file ...
""" Copyright (c) 2015 Michael Bright and Bamboo HR 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 agreed...
_app): self.flask_app = flask_app def configure_routing(self): self.flask_app.add_url_rule('/api/upgrade/<path:version>', 'upgrade_master', api_key_required(self.upgrade_master), methods=['POST']) def upgrade_master(self, version): worked = UpgradeUtil.upgrade_version(version, self.fla...
{} restored!".format(Version.get_version()), status=200 if worked else 505)
#!/usr/local/bin/python3 import cgi print("Content-type: text/html") print(
''' <!DOCTYPE html> <html> <head> <title>Python</title> </head> <body> <h1>Python</h1> <p>Python</p> <p>This is the article for Pytho
n</p> </body> </html> ''')
# Copyright 2014 Red Hat, 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 # # Unless required by applicable law or agre...
: systemd.notify_once() else: systemd.notify() self.assertTrue(self.ready) self.assertTrue(self.closed) def test_notify(self): self._test__sd_notify() def test_notify_once(self): os.environ['NOTIFY_SOCKET'] = '@fake_socket'
self._test__sd_notify(unset_env=True) self.assertRaises(KeyError, os.environ.__getitem__, 'NOTIFY_SOCKET') @mock.patch("socket.socket") def test_onready(self, sock_mock): recv_results = [b'READY=1', '', socket.timeout] expected_results = [0, 1, 2] for recv, expected in ...
from __futur
e__ import print_function from eventlet import hubs from eventlet.support import greenlets as greenlet __all__ = ['Event'] class NOT_USED: def __repr__(self): return 'NOT_USED' NOT_USED = NOT_USED() class Event(object): """An abstraction where an arbitrary number of coroutines can wait for on...
that can only hold one item, but differ in two important ways: 1. calling :meth:`send` never unschedules the current greenthread 2. :meth:`send` can only be called once; create a new event to send again. They are good for communicating results between coroutines, and are the basis for how :me...
from canvas.exceptions import ServiceError, ValidationError from canvas.economy import InvalidPurchase from drawquest imp
ort knobs from drawquest.apps.palettes.models import get_palette_by_name, all_palettes from drawquest.signals import balance_changed def balance(user): return int(user.kv.stickers.currency.get() or 0) def _adjust_balance(user, amount): if amount >= 0: user.kv.stickers.currency.increment(amount) el...
InvalidPurchase("Insufficient balance.") balance_changed.send(None, user=user) publish_balance(user) def publish_balance(user): user.redis.coin_channel.publish({'balance': balance(user)}) def credit(user, amount): _adjust_balance(user, amount) def debit(user, amount): _adjust_balance(user, -am...
blished by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ...
t connection before # proceeding... self.current_query = text text = self.quote(str(text)) # Is there a way to get the result_limit in the init method # so we don't have to assign it everytime search is called? self.result_limit = result_limit query = self.quer...
tream = self.File(query) self.search_controller.reset() self.stream.load_contents_async(self.handle_search_result, cancellable=self.search_controller) def cancel(self): if not self.search_controller.is_cancelled(): self.search_controller.cancel() def handle_search_result(...
# Author: Mr_Orange <mr_orange@hotmail.it> # URL: http://code.google.com/p/sickbeard/ # # 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 Free Software Foundation, either version 3 of the Lic...
e def _set_torrent_priority(self, result): arguments = {'ids': [result.hash]} if result.priority == -1: arguments['priority-low'] = [] elif result.priority == 1: # set high priority for all files in torrent arguments['priority-high'] = [] # ...
ueue arguments['queuePosition'] = 0 if sickbeard.TORRENT_HIGH_BANDWIDTH: arguments['bandwidthPriority'] = 1 else: arguments['priority-normal'] = [] post_data = json.dumps({'arguments': arguments, 'method': 'torrent-set'...
#!/usr/bin/python import sys,os from email.Utils import COMMASPACE, formatdate from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText from email.MIMEImage import MIMEImage from email.MIMEImage import MIMEImage from email.MIMEBase import MIMEBase from email import Encoders import smtplib impor...
ion.lower()) and (option["name"]==user)): option_selected = option msg = MIMEMultipart() msg['Subject'] = conf["subject"] msg['From'] = conf["source"] msg['To'] = CO
MMASPACE.join([option_selected["config"]]) msg['Date'] = formatdate(localtime=True) text = "Your scanner happely delivered this pdf to your mailbox.\n" msg.attach( MIMEText(text) ) part = MIMEBase('application', "pdf") part.set_payload( open(filename,"rb").read() ) Encoders.encode_base64(part) part.add_header('Conte...
#-- # Copyright (c) 2012-2014 Net-ng. # All rights reserved. # # This software is licensed under the BSD License, as described in # the file LICENSE.txt, which you should have received as part of # this distribution. #-- from nagare import presentation, security, var, ajax from nagare.i18n import _ from comp import N...
for index, item in enumerate(self.items): h << h.li(item.on_answer(lambda v, index=index: self.delete_item(index)), id='checklist_item_%s' % item().id) h << self.new_item return h.root @presentation.render_for(Checklist, 'progress') def render_Checklist_progress(self, h, comp, mod...
h << h.div(class_='bar', style='width:%s%%' % progress) h << h.span(progress, u'%', class_='percent') return h.root @presentation.render_for(ChecklistItem) def render_ChecklistItem(self, h, comp, model): h << h.a(h.i(class_='icon-checkbox-' + ('checked' if self.done else 'unchecked'))).action(self.se...
import tempfile import salt.utils.files from salt.modules import x509 as x509_mod from salt.states import x509 from tests.support.helpers import dedent from tests.support.mixins import LoaderModuleMockMixin from tests.support.mock import MagicMock from tests.support.unit import TestCase, skipIf try: import M2Cryp...
HOBIgEp4DWvV1vgs +z82LT6Qy5kxUQvnlQ4dEaGdrQKBgQD175f0H4enRJ3BoWTrqt2mTAwtJcPsKmGD 9YfFB3H4+O2rEKP4FpBO5PFXZ0dqm54hDtxqyC/lSXorFCUjVUBero1ECGt6Gnn2 TSnhgk0VMxvhnc0GReIt4K9WrXGd0CMUDwIhFHj8k
bb1X1yqt2hwyw7b10xFVStl sGv8CQB+VQKBgAF9q1VZZwzl61Ivli2CzeS/IvbMnX7C9ao4lK13EDxLLbKPG/CZ UtmurnKWUOyWx15t/viVuGxtAlWO/rhZriAj5g6CbVwoQ7DyIR/ZX8dw3h2mbNCe buGgruh7wz9J0RIcoadMOySiz7SgZS++/QzRD8HDstB77loco8zAQfixAoGBALDO FbTocfKbjrpkmBQg24YxR9OxQb/n3AEtI/VO2+38r4h6xxaUyhwd1S9bzWjkBXOI ...
import re print " Wri
te product name : " nume_produs = raw_input() print " Write product price : " cost_produs = input() if (nume_produs == re.sub('[^a-z]',"",nume_produs)
): print ('%s %d'%(nume_produs,cost_produs)) else: print "Error ! You must tape letters" input()
from _sha256 import sha256 from typing import Optional from common.serializers.serialization import domain_state_serializer from plenum.common.constants import DOMAIN_LEDGER_ID from plenum.common.request import Request from plenum.common.txn_util import get_payload_data, get_from, get_req_id from plenum.server.databas...
database_manager: DatabaseManager): super().__init__(database_manager, BUY, DOMAIN_LEDGER_ID) def static_validation(self, request: Request): self._validate_request_type(request) def dynamic_validation(self, request: Request, req_pp_time: Optional[int]): self._validate_request_type(requ...
tate_key(txn) value = domain_state_serializer.serialize({"amount": get_payload_data(txn)['amount']}) self.state.set(key, value) logger.trace('{} after adding to state, headhash is {}'. format(self, self.state.headHash)) def gen_state_key(self, txn): identifier =...
import os import finder import re import sys def makefilter(name, xtrapath=None): typ, nm, fullname = finder.identify(name, xtrapath) if typ in (finder.SCRIPT, finder.GSCRIPT, finder.MODULE): return ModFilter([os.path.splitext(nm)[0]]) if typ == finder.PACKAGE: return PkgFilter([fullname]) ...
{} for ext in extlist: if ext[0:1] != '.': ext = '.'+ext self.elements[ext] = 1 self.include = include class TypeFilter(_TypeFilter): """ A filter for resource types. TypeFi
lter(typlist, include=0) where typlist is a subset of ['a','b','d','m','p','s','x','z'] """ def __init__(self, typlist, include=0): self.elements = {} for typ in typlist: self.elements[typ] = 1 self.include = include class FileFilter(_NameFilter): """ A filter for da...
''' Created on Nov 17, 2011 @author: mmornati ''' from django.http import HttpResponse from django.ut
ils import simplejson as json import logging from celery.result import Asyn
cResult from webui.restserver.template import render_agent_template import sys logger = logging.getLogger(__name__) def get_progress(request, taskname, taskid): logger.info("Requesting taskid: %s"%taskid) result = AsyncResult(taskid, backend=None, task_name=taskname) logger.info("TASKID: %s"%result.task_i...
from django.db import models from djangotoolbox.fields import EmbeddedModelField, ListField from django_mongodb_engine.contrib import MongoDBManager import os # Create your models here. # save the created json file name path # only one file for summary should be kept here class UserJSonFile(models.Model): user_id ...
rsion = models.FloatField(null=True, blank=True) # request part ends # response fields # header and version is here also reason = models.CharField(max_length="5", null=True, blank=True) status = models.IntegerField(null=True, blank=True) # i might need body body = models.TextField(null=True,...
e, blank=True) content_encoding = models.CharField(max_length=25, null=True, blank=True) # response ends # i might need files also files = ListField(null=True, blank=True) file_path = models.CharField(max_length=200, null=True, blank=True) flow_details = EmbeddedModelField('FlowDetails', null=Tr...
from django.urls import reverse from oppia.test import OppiaTestCase from reports.models import DashboardAccessLog class ContextProcessorTest(OppiaTestCase): fixtures = ['tests/test_user.json', 'tests/test_oppia.json', 'tests/test_quiz.json', 'tests/test_permissio...
rdAccessLog.objects.all().count() self.assertEqual(dal_start_count+1, dal_end_count) # admin pages get def test_get_admin(self): dal_start_count = DashboardAccessLog.objects.all().c
ount() self.client.force_login(user=self.admin_user) self.client.get(reverse('admin:oppia_course_changelist')) dal_end_count = DashboardAccessLog.objects.all().count() # shouldn't add a log for admin self.assertEqual(dal_start_count, dal_end_count) # admin pages post # ...
import os, requests, tempfile, time, webbrowser import lacuna.bc import lacuna.exceptions as err ### Dev notes: ### The tempfile containing the captcha image is not deleted until solveit() ### ha
s been ca
lled. ### ### Allowing the tempfile to delete itself (delete=True during tempfile ### creation), or using the tempfile in conjunction with a 'with:' expression, ### have both been attempted. ### ### The problem is that, when using those auto-deletion methods, the tempfile ### is occasionally being removed from t...
from __future__ import unicode_literals import os.path from pre_commit.commands.clean import clean from pre_commit.util import rmtree def test_clean(runner_w
ith_mocked_store): assert os.path.exists(runner_with_mocked_store.store.directory) clean(runner_with_mocked_store) assert not os.pa
th.exists(runner_with_mocked_store.store.directory) def test_clean_empty(runner_with_mocked_store): """Make sure clean succeeds when we the directory doesn't exist.""" rmtree(runner_with_mocked_store.store.directory) assert not os.path.exists(runner_with_mocked_store.store.directory) clean(runner_with...
class Controller(object): def __init__(self, model): self._model = model self._view = None def register_view(self, view): self._view = view def on_quit(self, *args): raise NotImplementedErro
r def on_keybinding_activated(self, core, time): raise NotImplementedError def on_show_about(self, sender): raise NotImplementedError def on_toggle_history(self, sender): raise NotImplementedError def on_show_preferences(self, sender): raise NotImpleme...
t(self, entry, event): raise NotImplementedError def on_query_entry_activate(self, entry): raise NotImplementedError def on_treeview_cursor_changed(self, treeview): raise NotImplementedError def on_match_selected(self, treeview, text, match_obj, event): ...
# Copyright (C) 2016 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> from ggrc.converters import errors from integration.ggrc import
converters class TestBasicCsvImport(converters.TestCase): def setUp(
self): converters.TestCase.setUp(self) self.client.get("/login") def test_policy_basic_import(self): filename = "ca_setup_for_deletion.csv" self.import_file(filename) filename = "ca_deletion.csv" response_data_dry = self.import_file(filename, dry_run=True) response_data = self.import_fil...
import setuptools with open("README.md", "r") as fh: long_description = fh.read() with open('requirements.txt') as f: requirements = f.read().splitlines() with open('cli-requirements.txt') as f: cli_requirements = f.read().splitlines() setuptools.setup( name="uwg", use_scm_version=True, setu...
g.cli:main"] }, classifiers=[ "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: Implementation :: CPython", "License :: OSI Approved :: GNU General Public License v...
nt" ], )
from collections import UserList from gear import ffxiv, xivdb from gear import power as p """Class representing a simple gear element. """ class Gear(object): """Gear(slot, item_id, **attributes) slot : in which slot of the gearset is this precise gear, as defined in ffxiv.slots.
item_id : identifier from xivdb.com. Will load the gear from there if provided attributes : the attributes of the gear as defined in ffxiv.attributes. """ def __init__(self, slot, item_id = None, **attributes): if item_id is not None : attributes = xivdb.getId(item_id)
assert(slot in ffxiv.slots) self.slot = slot # We filter out what is not a legitimate FFXIV attribute self.attributes = dict(filter( lambda a:a[0] in ffxiv.attributes, attributes.items())) # We put the rest in self.misc self.misc = di...
import sys sys.path.insert(1, "../../../") import h2o def binop_plus(ip,port): # Connect to h2o h2o.init(ip,port) iris = h2o.import_frame(path=h2o.locate("smalldata/iris/iris_wheader_65_rows.csv")) rows, cols = iris.dim() iris.show() ###########################################################...
# LHS: scaler, RHS: H2OVec res = 1.2 + iris[2] res2 = res[21,:] + iris[1] res2.show() # LHS: s
caler, RHS: scaler res = 1.1 + iris[2] res2 = res[21,:] + res[10,:] assert abs(res2 - 5.2) < 1e-1, "expected same values" # LHS: scaler, RHS: scaler res = 2 + iris[0] res2 = res[21,:] + 3 assert abs(res2 - 10.1) < 1e-1, "expected same values" ###########################################...
""" https://codility.com/programmers/task/equi_leader/ """ from collections import Counter, defaultdict def solution(A): def _is_equi_leader(i): prefix_cou
nt_top = running_counts[top] suffix_count_top = total_counts[top] - prefix_count_top return (prefix_count_top * 2 > i + 1) and (su
ffix_count_top * 2 > len(A) - i - 1) total_counts = Counter(A) running_counts = defaultdict(int) top = A[0] result = 0 for i in xrange(len(A) - 1): n = A[i] running_counts[n] += 1 top = top if running_counts[top] >= running_counts[n] else n if _is_e...
# Copyright 2014 Modelling, Simulation and Design Lab (MSDL) at # McGill University and the University of Antwerp (http://msdl.cs.mcgill.ca/) # # 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...
of the f
irst model that has to transition :returns: timestamp of the first model """ first = self.heap[0] while len(self.mapped[first]) == 0: del self.mapped[first] heappop(self.heap) first = self.heap[0] # The age was stripped of return (firs...
# Grid Search for Algorithm Tuning import numpy as np import pandas as pd from sklearn import datasets from sklearn.linear_model import Ridge from sklearn.grid_search import GridSearchCV ### Plotting function ### from matplotlib import pyplot as plt from sklearn.metrics import r2_score def plot_r2(y, y_pred, titl...
text(xmn + buff, mx - buff, "R2 Score: %f" % (r2_score(y, y_pred), ), size=15) plt.plot([0., mx], [0., mx]) plt.xlim(
xmn, mx) plt.ylim(ymn, mx) ### Preprocessing ### dataset = pd.read_csv("train.csv") dataset.head() feats = dataset.drop("revenue", axis=1) X = feats.values #features y = dataset["revenue"].values #target # prepare a range of alpha values to test alphas = np.array([1,0.1,0.01,0.001,0.0001,0]) # 100000 works...
fro
m .site import
Site
.mapping[self.state]) self.state = state def is_acceptable(self, state): if self.mapping is None: return True if state not in self.mapping: return False next_types = self.mapping[self.state] return '*' in next_types or state in next_types DEFAULT_RE...
assert (yield OrderRecord()) yield TerminatorRecord() # we may do not care about rejection :class:`Client` thought :class:`RecordsStateMachine` keep track on this order, raising :exc:`AssertionError` if it is broken. When `emitter` terminates with :exc:`StopIteration` or :exc:`GeneratorExit...
ource from time to time. Note, that server may have communication timeouts control and may close session after some time of inactivity, so be sure that you're able to send whole session (started by Header record and ended by Terminator one) within limited time frame (commonly 10-15 sec.). """ #: Wr...
# -*- coding: utf-8 -*- # # LICENCE MIT # # DESCRIPTION Callgraph builder. # # AUTHOR Michal Bukovsky <michal.bukovsky@trilogic.cz> # from operator import attrgetter from inspect import signature from callgraph.hooks import Hooks from callgraph.utils import AuPair from callgraph.symbols import Symbol, ...
rgs=[], kwargs={}): # attach new node to parent list node = make_node(symbol) with AuPair(self, node): if parent: where = parent.filename, self.current_lineno if not parent.attach(node, where): return node # builtins or c/c++ objects have ...
de if node.is_opaque: return node if not symbol.iscallable(): return node # print nice banner self.print_banner(self.printer, node) # magic follows with self.printer as printer: self.inject_arguments(printer, node, args, kwargs) ...
s current selected track: " + str(x)) return True else: print("[MoviePlayer] audio track is current selected track: " + str(x)) return True elif entry == x[1] and seltrack != x[0]: if useAc3: if x[2].startswith('AC'): print("[MoviePlayer] audio track match: " + str(x)) tracks...
PlayerConfirmed(self,
answer): answer = answer and answer[1] if answer is None: return if answer in ("quitanddelete", "quitanddeleteconfirmed", "deleteandmovielist", "deleteandmovielistconfirmed"): ref = self.session.nav.getCurrentlyPlayingServiceOrGroup() serviceHandler = enigma.eServiceCenter.getInstance() if answer in ...
class target(object): def __init__(self): self.encodingString = "1,10 1,10 1,10 1,10 1,10 1.0 p1-1,10 1,10 1,10 1,10 1,10 1.0 p2" self.canAdd = False self.canRemove = False self.initializationType = "sequential" self.encodingTable = None self.group1 = [] ...
self.group1 = genome[0][1:] self.group2 = genome[1][1:] #self.params = [delta,minArea,maxArea,maxVariation,minDiversity,maxEvolution,areaThreshold,minMargin,edgeBlurSize] def evaluate(self): genes = [] m = 1 s = 0 for arg in self.group1: ...
s.append(arg) duplicateCount = len(genes) - len(set(genes)) m-=360 s-=36 fitness = -(abs(m) + abs(s)) - duplicateCount #print("\nFITNESS:",fitness,"\n") return fitness def validate_genome(self,genome): return True
if "freq" in parameters_dict: self.set_frequency(parameters_dict["freq"]) if "dac_overridden" in parameters_dict: self._dac_overridden = parameters_dict["dac_overridden"] else: self._dac_overridden = False def get_iqawg(self): self._iqawg.set_p...
nter in range(3): try: self.set_frequency(frequency) break except ValueError: print("Poor calibration at %.3f GHz, retry count " "%d" % (frequency / 1e9, counter)) self._calibration_...
np.random.uniform(.03, 0.1, size=2) self._recalibrate_mixer = False def test_calibration(self, fstart, fstop, step=1e6, sidebands_to_plot=[-1, 0, 1], remeasure=False): """ Tests the saved calibrations by monitoring all the sidebands throu...
if config_value: options[opt_key] = entry.render(config_value) elif entry_value: options[opt_key] = entry.render(entry_value) # Convert priority from string to int priority = options.get('priority') if priority and priority in self.p...
string'}, 'digest_auth': {'type': 'boolean', 'default': False}, 'start': {'type': 'boolean', 'default': True}, 'mkdir': {'type': 'boolean', 'default': True}, 'action': {'type':
'string', 'emun': ['update', 'delete', 'add'], 'default': 'add'}, # properties to set on rtorrent download object 'message': {'type': 'string'}, 'priority': {'type': 'string'}, 'path': {'type': 'string'}, 'custom1': {'type': 'string'}, 'custom2': {...
Frame, Index, MultiIndex, ) import pandas._testing as tm def test_default_separator(python_parser_only): # see gh-17333 # # csv.Sniffer in Python treats "o" as separator. data = "aob\n1o2\n3o4" parser = python_parser_only expected = DataFrame({"a": [1, 3], "b": [2, 4]}) result = p...
ta = 'a,,b\n1,,a
\n2,,"2,,b"' if quoting == csv.QUOTE_NONE: msg = "Expected 2 fields in line 3, saw 3" with pytest.raises(ParserError, match=msg): parser.read_csv(StringIO(data), quoting=quoting, **kwargs) else: msg = "ignored when a multi-char delimiter is used" with pytest.raises(P...
""" The I_downarrow unique measure, proposed by Griffith et al, and shown to be inconsistent. The idea is to measure unique information as the intrinsic mutual information between and source and the target, given the other sources. It turns out that these unique values are inconsistent, in that they produce differing ...
---------- d : Distribution The distribution to compute I_SKAR for. sources : iterable of iterables The source variables. target : iterable The target variable. Returns ------- i_sk
ar_tw : dict The value of I_SKAR_tw for each individual source. """ uniques = {} for source in sources: others = list(sources) others.remove(source) others = list(flatten(others)) uniques[source] = two_way_skar(d, [source, target], othe...
# To run: # pytest -c cadnano/tests/pytestgui.ini cadnano/tests/ import pytest from PyQt5.QtCore import Qt, QPointF from PyQt5.QtTest import QTest from cadnano.fileio.lattice import HoneycombDnaPart from cadnano.views.sliceview import slicestyles from cnguitestcase import GUITestApp @pytest.fixture() def cnapp(): ...
main_toolbar action_new_honeycomb = toolbar.widgetForAction(cnapp.window.action_new_dnapart_honeycomb) QTest.mouseClick(action_new_honeycomb, Qt.LeftButton, delay=DELAY) slicerootitem = cnapp.window.views['slice'].root_item assert len(slicerootitem.instance_items) == 1 slice_part_item = list(slicer...
, Qt.Key_C, delay=DELAY) cnapp.processEvents() cmd_count = 1 # already added the part for row in range(-2, 2): for col in range(-2, 2): # print(row, col) x, y = HoneycombDnaPart.latticeCoordToModelXY(RADIUS, row, col) pt = QPointF(x, y) cnapp.graphic...
# Copyright (c) 2007-2008 The Hewlett-Packard Development Company # All rights reserved. # # The license below extends only to copyright in the software and shall # not be construed as granting a license to any other intellectual # property including but not limited to intellectual property relating # to a hardware imp...
ld t3, tsg, [1, t0, t3], dataSize=8 processDescriptor: chks t2, t3, IretCheck, dataSize=8 # There should be validity checks on the RIP checks here, but I'll do # that later. wrdl cs, t3, t2 wrsel
cs, t2 wrip t0, t1 br label("end") # Do other stuff if they're not. end: fault "NoFault" }; '''
import unittest from plow.ldapadaptor import LdapAdaptor class FakeLA(LdapAdaptor): def bind(self, *args): """ Nothing to see here move along """ initialize = bind class Test_Ldap_DN_Compare(unittest.TestCase): def setUp(self): self.ldap_case_i = FakeLA("uri", "base", case_insensitive_dn...
): if case_sensitive: match = self.ldap_case_s.compare_dn(ref, other) else: match = self.ldap_case_i.compare_dn(ref, other) if res: self.assertTrue( match, "Expected '{0}' to match '{1}' (Case Sensitive: {2})".format(ref, other...
) else: self.assertFalse( match, "'{0}' and '{1}' should not match (Case Sensitive: {2})".format(ref, other, case_sensitive), ) def test_basic(self): self._do_compare("CN=Test", "CN=test", False, case_sensitive=True) sel...
# Script used to create Mni
st_mini and Mnist_full datasets. import numpy as np from sklearn.datasets import fetch_mldata from pandas import DataFrame # Default download location for caching is # ~/scikit_learn_data/mldata/mnist-original.mat unless specified otherwise. mnist = fetch_mldata('MNIST original') # Create DataFrame, group data by c...
les, status) status[node] = 2 # set this node as completed elif status.get(node) == 1: # has been entered but not yet done if break_cycles: logging.warning("Hierarchy cycle removed at %s -> %s", localname(parent), localname(node)) rdf.remove((nod...
ge if lang not in prefLabels: prefLabels[lang] = [] prefLabels[lang].append(label) for lang, labels in prefLabels.items(): if len(labels) > 1: if policies[0] == 'all': logging.warning( "Resource %s ha...
more than one prefLabel@%s, " "but keeping all of them due to preflabel-policy=all.", res, lang) continue chosen = sorted(labels, key=key_fn)[0] logging.warning( "Resource %s has more than one prefL...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- from pwn import * context(arch='amd64', os='linux', aslr=False, terminal=['tmux', 'neww']) env = {'LD_PRELOAD': './libc.so.6'} if args['GDB']: io = gdb.debug( './artifact-amd64-2.24-9ubuntu2.2', env=env, gdbscript='''\ set follow-fork-...
# $ ./artifact.py REMOTE # [+] Opening connection to 52.192.178.153 on port 31337: Done # [*] '/home/ubuntu/
vbox/artifact-4c4375825c4a08ae9d14492b34b3bddd/artifact' # Arch: amd64-64-little # RELRO: Full RELRO # Stack: Canary found # NX: NX enabled # PIE: PIE enabled # [*] '/home/ubuntu/vbox/artifact-4c4375825c4a08ae9d14492b34b3bddd/libc.so.6' # Arch: amd64-64-little # RELR...
r letsencrypt_apache.parser.""" import os import shutil import unittest import augeas import mock from letsencrypt import errors from letsencrypt_apache.tests import util class BasicParserTest(util.ParserTest): """Apache Parser Test.""" def setUp(self): # pylint: disable=arguments-differ super(Ba...
nd_dir("documentroot") self.assertEqual(len(test), 1) self.assertEqual(len(test2), 4) def test_add_dir(self): aug_default = "/files" + self.parser.loc["default"]
self.parser.add_dir(aug_default, "AddDirective", "test") self.assertTrue( self.parser.find_dir("AddDirective", "test", aug_default)) self.parser.add_dir(aug_default, "AddList", ["1", "2", "3", "4"]) matches = self.parser.find_dir("AddList", None, aug_default) for i,...
============================================== class S3ExtractLazyFKRepresentationTests(unittest.TestCase): """ Test lazy representation of foreign keys in datatables """ tablename = "export_lazy_fk_represent" # ------------------------------------------------------------------------- @classmethod ...
data = resource.select(["id", "organisation_id"], limit=None, represent=True,
show_links=False) result = data["rows"] self.assertEqual(renderer.queries, 1) self.assertTrue(isinstance(result, list)) self.assertEqual(len(result), 1) output = result[0] self.assertTrue(isinstance(output, Storage)) self.as...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals from argparse import ArgumentParser from .core import Core def getopt(argv): parser = ArgumentParser(description='Another webui for youtube-dl') parser.add_argument('-c', '--config', metavar="CONFIG_FILE", h
elp="config file") parser.add_argum
ent('--host', metavar="ADDR", help="the address server listens on") parser.add_argument('--port', metavar="PORT", help="the port server listens on") return vars(parser.parse_args()) def main(argv=None): from os import getpid print("pid is {}".format(getpid())) print("----------------------------...
(rlens, _cnt_to_dsp(rlens)), _get_mpi_type(msgtype)], root) ys = [rbuf[i:i + l].reshape(s) for i, l, s in zip(_cnt_to_dsp(rlens), rlens, shapes)] return tuple(ys) else: sbuf = _memory_utility.array_to_buffer_object( ...
dule(x) # TODO(kuenishi): do we check all messages have same shape and dims? # Source buffer sbuf = _memory_utility.array_to_buffer_object( x, _get_mpi_type(msgtype)) # Destination buffer and its object shape = msgtype.shapes[0] dbuf = xp.empty( ...
er.utils.size_of_shape(shape)], dtype=msgtype.dtype) dbuf_buffer_obj = _memory_utility.array_to_buffer_object( dbuf, _get_mpi_type(msgtype)) self.mpi_comm.Allreduce(sbuf, dbuf_buffer_obj) return dbuf.reshape(shape) def scatter(self, xs, root=0): """A primitive of inter-...
from __future__ import absolute_import, division, print_function, unicode_literals import struct import datetime from aspen import Response from aspen.http.request import Request from base64 import urlsafe_b64decode from cryptography.fernet import Fernet, InvalidToken from gratipay import security from gratipay.model...
n def test_unpacks_decryptingly(self): assert Identity.encrypting_packer.unpack(self.packed) == {"foo": "bar"} def test_fails_to_unpack_old_data_with_a_new_key(self): encrypting_packer = EncryptingPacker(Fe
rnet.generate_key()) raises(InvalidToken, encrypting_packer.unpack, self.packed) def test_can_unpack_if_old_key_is_provided(self): old_key = str(self.client.website.env.crypto_keys) encrypting_packer = EncryptingPacker(Fernet.generate_key(), old_key) assert encrypting_packer.unpack(...
# -*- coding: utf-8 -*- from __futu
re__ import unicode_literals from django.shortcuts import render from django.conf.urls import url from .views import HomePageView, LeaderboardView, MiscView, Sign_upView urlpatterns = [ url(r'^$', HomePageView.as_view(), name='home'), url(r'^misc$', MiscView.as_view(), name='misc'), url(r'^leaderboard$'...
, ]
# -*- coding: utf-8 -*- from __future__ import print_function import pytak.call as call import pytak.runners.tools as tools from fakeapi import CreateTag from fakeapi import GetInformationAboutYourself from fakeapi import CreateAPost new_request_body = { "title" : "New Employee [XXXXX]", "body" : "Please w...
CreateAPost() << new_request_body def test_assign_randomization(): create_tag = CreateTag(assign={"name" : "pytak-[XXXX]"}) assert create_tag.assign != {"name" : "pytak-[XXXX]"} def test_request_body_randomization(): create_post = CreateAPost
() << new_request_body print(create_post.request_body)
class Solution(object): def containsNearbyAlmostDuplicate(self, nums, k, t): """ :type nums: List[int] :type k: int :type t: int :rtype: bool """ if k < 1 or t < 0: return False dic = {} t += 1 for i in range(len(nums)): ...
(nums[i] - dic[m - 1]) < t: return True if m + 1 in dic and abs(nums[i] - dic[m + 1]) < t: return True dic[m] = nums[i] return False test = Solution() print(test.containsNearbyAlmostDupl
icate([1, 3, 1], 1, 1))
ON_TITLE = "Wireless Sensor Tag Setup" DOMAIN = "wirelesstag" DEFAULT_ENTITY_NAMESPACE = "wirelesstag" # Template for signal - first parameter is tag_id, # second, tag manager mac address SIGNAL_TAG_UPDATE = "wirelesstag.tag_info_updated_{}_{}" # Template for signal - tag_id, sensor type and # tag manager mac addres...
) hass.bus.listen("wirelesstag_binary_event", hass.data[DOMAIN].handle_binary_event) return True class WirelessTagBaseSensor(Entity): """Base class for HA implementation for Wireless Sensor Tag.""" def __init__(self, api, tag): """Initialize a base sensor for Wireless Sensor Tag platform."...
g_manager_mac = self._tag.tag_manager_mac self._name = self._tag.name self._state = None @property def should_poll(self): """Return the polling state.""" return True @property def name(self): """Return the name of the sensor.""" return self._name @p...
''' Python program for implementation of Merge Sort l is left index, m is middle index and r is right index L[l...m] and R[m+1.....r] are respective left and right sub-arrays ''' def merge(arr, l, m, r): n1 = m - l + 1 n2 = r-m #create temporary arrays L = [0]*(n1) R = [0]*(n2) #Copy data to temp arrays L[...
opy the remaining element of L[], if there are any while i < n1: arr[k] = L[i] i += 1 k += 1 # Copy the remaining element of R[], if there are any while j < n2: arr[k] R[j] j += 1 k += 1 # l is for left index and r is for right index of the # subarray of arr to be sorted def mergeSort(arr, l,
r): if l < r: #Same as (l+r)/2, but avoid overflow for large l and h m = (l+(r-1))/2 # Sort first and second halves mergeSort(arr, l, m) mergeSort(arr, m+1, r) merge(arr, l, m, r)
# coding: utf-8 from __future__ import unicode_literals import re from .adobepass import AdobePassIE from ..utils import ( int_or_none, determine_ext, parse_age_limit, urlencode_postdata, ExtractorError, ) class GoIE(AdobePassIE): _SITE_INFO = { 'abc': { 'brand': '001', ...
': requestor_id = site_info['requestor_id'] resource = self._get_mvpd_resource( requestor_id, title, video_id, None) auth = self._extract_mvpd_auth( url, video_id, requestor_id, resource) ...
e': 'ap', 'adobe_requestor_id': requestor_id, }) entitlement = self._download_json( 'https://api.entitlement.watchabc.go.com/vp2/ws-secure/entitlement/2020/authorize.json', video_id, data=urlencode_po...
#!/usr/bin/env python3 # Review Lines from the Selected Deck in Random Order Until All Pass # Written in 2012 by 伴上段 # # To the extent possible under law, the author(s) have dedicated all copyright # and related and neighboring rights to this software to the public domain # worldwide. This software is distributed with...
New log file entries will have this format: <ID> <field-separator> <timestamp> <field-separator> <result> where <ID> is the unique ID of the line (card) associated with the record, <field-sep
arator> is the CSV field separator, <timestamp> is the record's timestamp (you can modify its format via the -f option), and <result> is the result of the review. For Leitner-system-based reviews, <result> is either '+' or '-'. '+' indicates that the user passed the review at the specified time, whereas '-' ...
from pymc3 import * import theano.tensor as t from theano.tensor.nlinalg import matrix_inverse as inv from numpy import array, diag, linspace from numpy.random import multivariate_normal # Generate some multivariate normal data: n_obs = 1000 # Mean values: mu = linspace(0, 2, num=4) n_var = len(mu) # Standard devia...
form('sigma', shape=n_var) corr_triangle = LKJCorr('corr', n=1, p=n
_var) corr_matrix = corr_triangle[tri_index] corr_matrix = t.fill_diagonal(corr_matrix, 1) cov_matrix = t.diag(sigma).dot(corr_matrix.dot(t.diag(sigma))) like = MvNormal('likelihood', mu=mu, tau=inv(cov_matrix), observed=dataset) def run(n=1000): if n == "short": n = 50 with model: ...
# Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: vraj@reciprocitylabs.com # Maintained By: vraj@reciprocitylabs.com """Defines a Revision model for storing snapshots.""" from ggrc import db from ...
mapping_verb = "linked" if self.resource_type in link_objects else "mapped" if self.action == 'created': result = u"{1} {2} to {0}".format(source, destination, mapping_verb) elif self.action == 'deleted': result = u"{1} un{2} from {0}".format(source, destination, mapping_verb) else: re...
(display_name, self.action) return result @computed_property def description(self): """Compute a human readable description from action and content.""" link_objects = ['ObjectDocument'] if 'display_name' not in self.content: return '' display_name = self.content['display_name'] if not...
from .base import * DEBUG
= True EMAIL_BACKEND
= 'nr.sendmailemailbackend.EmailBackend'
# coding: utf-8 from google.appengine.ext import ndb from flask.ext import restful import flask from api import helpers import auth import model import util from main import api_v1 ############################################################################### # Admin ##############################################...
n/song/', endpoint='api.admin.song.list') class AdminSongListAPI(restful.Resource): @auth.admin_required def get(self): song_keys = util.param('song_keys', list) if song_keys: s
ong_db_keys = [ndb.Key(urlsafe=k) for k in song_keys] song_dbs = ndb.get_multi(song_db_keys) return helpers.make_response(song_dbs, model.song.FIELDS) song_dbs, song_cursor = model.Song.get_dbs() return helpers.make_response(song_dbs, model.Song.FIELDS, song_cursor) @api_v1.resource('/admin/song/...
t 2017 LasLabs Inc. # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). import os import mock from odoo.modules import get_module_path from odoo.tests.common import TransactionCase from odoo.tools import mute_logger from odoo.addons.module_auto_update.addon_hash import addon_hash from ..models.module_d...
_uninstall`.""" module_path_mock.return_value = self.own_dir_path vals = { 'name': 'module_auto_update_test_module', 'state': 'installed', } test_module = self.create_test_module(vals) test_module.checksum_installed = 'test' uninstall_module = self...
ate, 'to upgrade', 'Auto update logic was triggered during uninstall.', ) def test_button_immediate_uninstall_no_recompute(self): """It should not attempt update on `button_immediate_uninstall`.""" uninstall_module = self.env['ir.module.module'].search([ ('name', '=...
import json import click from tabulate import tabulate @click.command('notes', short_help='List notes') @click.option('--alert-id', '-i', metavar='UUID', help='alert IDs (can use short 8-char id)') @click.pass_obj def cli(obj, a
lert_id): """List notes.""" client = obj['client'] if alert_id: if obj['output'] == 'json': r = client.http.get('/alert/{}/notes'.format(alert_id)) click.echo(json.dumps(r['notes'], sort_keys=True, indent=4, ensure_ascii=False)) else: timezone = obj['timez...
'createTime': 'CREATED', 'updateTime': 'UPDATED', 'related': 'RELATED ID', 'customer': 'CUSTOMER' } click.echo(tabulate([n.tabular(timezone) for n in client.get_alert_notes(alert_id)], headers=headers, tablefmt=obj['output'])) else: raise click.UsageError('Need "--alert-id...
# -*- coding: utf-8 -*- # python+selenium识别验证码 # import re import requests import pytesseract from selenium import webdriver from PIL import Image,Image import time # driver = webdriver.Chrome() driver.maximize_window() driver.get("https://higo.flycua.com/hp/html/login.html") driver.implicitly_wait(30) # 下面用户名和密码涉及到我个...
nt_by_name('memberId').send_keys('xxxxxx') driver.find_element_by_name('password').send_keys('xxxxxx') # 因为验证码不能一次就正确识别,我加了循环,一直识别,直到登录成功 while True:   # 清空验证码输入框,因为可能已经识别过一次了,里面有之前识别的错的验证码 driver.find_element_by_name("verificationCode").clear() # 截图或验证码图片保存地址 screenImg = "H:\screenImg.
png" # 浏览器页面截屏 driver.get_screenshot_as_file(screenImg) # 定位验证码位置及大小 location = driver.find_element_by_name('authImage').location size = driver.find_element_by_name('authImage').size   # 下面四行我都在后面加了数字,理论上是不用加的,但是不加我这截的不是验证码那一块的图,可以看保存的截图,根据截图修改截图位置 left = location['x'] + 530 top = locat...
""" def create_repository(self, shared=False): """See ControlDir.create_repository.""" return "A repository" def open_repository(self): """See ControlDir.open_repository.""" return SampleRepository(self) def create_branch(self, name=None): """See ControlDir.create_...
gistry.make_bzrdir('knit') self.make_repository('.', shared=True, format=format) branch = bzrdir.BzrDir.create_branch_and_repo(self.get_url('child'), force_new_repo=True, format=format) br...
_repository() def test_create_standalone_working_tree(self): format = SampleBzrDirFormat() # note this is deliberately readonly, as this failure should # occur before any writes. self.assertRaises(errors.NotLocalUrl, bzrdir.BzrDir.create_standalone_workingt...
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-03-07 06:05 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('news', '0003_auto_20170228_2249'), ] operations = ...
', name='prev_paper', field=models.ForeignKey(default=None, on_delete=django.db.models.deletion.CASCADE, related_name='+', to='news.Newspaper'), ), migrations.AlterField( model_name='newspaper', name='date
_ended', field=models.DateField(blank=True, null=True, verbose_name='date ended'), ), migrations.AlterUniqueTogether( name='location', unique_together=set([('city', 'state')]), ), migrations.AddField( model_name='newspaper', nam...
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. #!/usr/bin/env python from __future__ impo
rt division, unicode_literals """ #TODO: Write module doc. """ __author__ = 'Shyue Ping Ong' __copyright__ = 'Copyright 2013, The Materials Virtual Lab' __version__ = '0.1' __maintainer__ = 'Shyue Ping Ong' __email__ = 'ongsp@ucsd.edu' __date__ = '8/1/15' import warnings warnings.warn("pymatgen.io.aseio
has been moved pymatgen.io.ase. This stub " "will be removed in pymatgen 4.0.", DeprecationWarning) from .ase import *
#!/usr/bin/env python3 """tests.test_io.test_read_gfa.py: tests for exfi.io.read_gfa.py""" from unittest import TestCase, main from exfi.io.read_gfa import read_gfa1 from tests.io.gfa1 import \ HEADER, \ SEGMENTS_EMPTY, SEGMENTS_SIMPLE, SEGMENTS_COMPLEX, \ SEGMENTS_COMPLEX_SOFT, SEGMENTS_COMPLEX_HARD, ...
PTY)) def test_simple(self): """ex
fi.io.read_gfa.read_gfa1: simple case""" gfa1 = read_gfa1(GFA1_SIMPLE_FN) self.assertTrue(gfa1['header'].equals(HEADER)) self.assertTrue(gfa1['segments'].equals(SEGMENTS_SIMPLE)) self.assertTrue(gfa1['links'].equals(LINKS_SIMPLE)) self.assertTrue(gfa1['containments'].equals(CONTA...
# coding=utf-8 import json import codecs import os import transaction from nextgisweb import DBSession from nextgisweb.vector_layer import VectorLayer from nextgisweb_compulink.compulink_admin.model import BASE_PATH def update_actual_lyr_names(args): db_session = DBSession() transaction.manager.begin() ...
_real_lyr_names[up_lyr_name] = new_name # update now resources = db_session.query(VectorLayer).filter(VectorLayer.keyname.like('real_%')).all() for vec_layer in resources: lyr_name = vec_layer.keyname if not lyr_name:
continue for up_lyr_name in upd_real_lyr_names.keys(): if lyr_name.startswith(up_lyr_name) and not lyr_name.startswith(up_lyr_name + '_point'): # ugly! vec_layer.display_name = upd_real_lyr_names[up_lyr_name] print '%s updated' % lyr_name br...
# # SPDX-License-Identifier: MIT # import os import shutil import unittest from oeqa.core.utils.path import remove_safe from oeqa.sdk.case import OESDKTestCase from oeqa.utils.subprocesstweak import errors_have_output errors_have_output() class GccCompileTest(OESDKTestCase): td_vars = ['MACHINE'] @classmet...
r, 'test.cpp' : self.tc.files_dir, 'testsdkmakefile' : self.tc.sdk_files_dir} for f in files: shutil.copyfile(os.path.join(files[f], f),
os.path.join(self.tc.sdk_dir, f)) def setUp(self): machine = self.td.get("MACHINE") if not (self.tc.hasHostPackage("packagegroup-cross-canadian-%s" % machine) or self.tc.hasHostPackage("^gcc-", regex=True)): raise unittest.SkipTest("GccCompileTest class:...
#!/usr/bin/env
python3 print('Content-type: text/html') print() primes = [2, *range(3, 10001, 2)] for div in primes: idx = div + 1 while(idx < len(primes)): if (primes[idx] % div == 0): del primes[idx] idx += 1 print(primes)
#!/usr/bin/env python # # Copyright (c) 2001 - 2016 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaini
ng # 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, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is f...
rtions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGE...
# Licensed to the Software Freedom Conservancy (SFC) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The SFC licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
er.start() FirefoxSelectElementHandlingTests.webserver = webser
ver FirefoxSelectElementHandlingTests.driver = webdriver.Firefox() class FirefoxSelectElementHandlingTests(select_class_tests.WebDriverSelectSupportTests): pass def teardown_module(module): FirefoxSelectElementHandlingTests.driver.quit() FirefoxSelectElementHandlingTests.webserver.stop()
from google.appengine.ext import webapp from google.appengine.ext.webapp import util from google.appengine.api.labs import taskqueue from google.appengine.api import memcache from lifestream import * class LifeStreamQueueWorker(webapp.Reques
tHandler): def get(self): memcache.set('fresh_count', 0) indexes = LifeStream.instance().indexes for index in indexes: taskqueue.add(url='/app_worker/task', method='GET', params={'in
dex':index}) taskqueue.add(url='/app_worker/refresh', method='GET', countdown=10) class LifeStreamTaskWorker(webapp.RequestHandler): def get(self): index = int(self.request.get('index')) LifeStream.update_feed(index) class LifeStreamRefreshWorker(webapp.RequestHandler): def get(self): LifeStream.refresh_...
notebook_json = data.pop('notebook_json', None) notebook = Notebook(notebook_path, notebook_json) try: template_name, template_data = views.render( view_name, notebook=notebook, data=data, method=method) except ResponseError as e:
self.send_error(e.status_code) return except: template_name = 'internal_error.html' template_data = {'error': traceback.format_exc()} self.set_status(500) template_data.update(
notebook=notebook, ) template = env.get_template(template_name) self.finish(template.render(template_data)) def get(self): self.handle_request('GET') def post(self): self.handle_request('POST') def check_xsrf_cookie(self): return class SaagieCheckHand...
# -*- coding: utf-8 -*- # Generated by Django 1.10.3 on 2016-12-23 10:13 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('blog', '0006_auto_20160321_1527'), ] operations = ...
', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ], ), migrations.AddField( model_name='post', name='blog', fiel
d=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='blog.Blog'), ), ]
# Generated by D
jango 2.2.24 on 2021-10-21 02:45 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("cases", "0015_case_is_quarantied"), ] operations = [ migrations.AddIndex( model_name="case", index=models.Index(
fields=["created"], name="cases_case_created_a615f3_idx" ), ), ]
""" WSGI config for ffstats project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` ...
s to the Django one. For example, you could introduce WSGI middleware here, or combine a Django application with an application of another framework. """ import os # We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks # if running multiple sites in the same mod_wsgi process. To fix this, use ...
stats.settings") # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. from django.core.wsgi import get_wsgi_application application = get_wsgi_application() # Apply WSGI middleware here. # from hel...
#!/usr/bin/env python from __future__ import print_function import argparse import xml.etree.ElementTree as ET def main(): parser = argparse.ArgumentParser(description="List all error without a CWE assigned in CSV format") parser.add_argument("-F", metavar="filename", requi
red=True, help="XML file containing output from: ./cppcheck --errorlist --xml-version=2") parsed = parser.parse_args() tree = ET.parse(vars(parsed)["F"]) root = tree.getroot() for child in root.iter("error"): if "cwe" not in child.attrib: print(child.attrib["...
"], child.attrib["verbose"], sep=", ") if __name__ == "__main__": main()
import django_filters from .models import Resource class ResourceFilter(django_filters.FilterSet)
: class Meta: model = Resource fields = [ 'title', 'description',
'domains', 'topics', 'resource_type', 'suitable_for', ]
#!/usr/bin/env python # encoding: utf-8 """ Download command for ssstat--download logs without adding to MongoDB. 2012-11-18 - Created by Jonathan Sick """ import os import logging from cliff.command import Command
import ingest_core class DownloadCommand(Command): """ssstat download""" log = logging.getLogger(__name__) def get_parser(self, progName): """Adds command line options.""" parser = super(DownloadCommand, self).get_parser(progName) parser.add_argument('log_bucket', h...
gument('prefix', help='Prefix for the desired log files') parser.add_argument('--cache-dir', default=os.path.expandvars("$HOME/.ssstat/cache"), action='store', dest='cache_dir', help='Local directory where logs are cached') parser.add_argument(...
# Co
pyright (c) 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import unittest from perf_insights import local_directory_corpus_driver cl
ass LocalDirectoryCorpusDriverTests(unittest.TestCase): def testTags(self): self.assertEquals( local_directory_corpus_driver._GetTagsForRelPath('a.json'), []) self.assertEquals( local_directory_corpus_driver._GetTagsForRelPath('/b/c/a.json'), ['b', 'c'])
""" import params # Must kinit before running the HDFS command if params.security_enabled: Execute(format("{kinit_path_local} -kt {hdfs_user_keytab} {hdfs_principal_name}"), user = params.hdfs_user) active_namenode_id = None standby_namenode_id = None active_namenodes, standby_namenodes, u...
est", "-f", pid_file]) + " && " + as_sudo(["pgrep", "-F", pid_file]) # on STOP directories shouldn't be created # since during stop still old dirs are used (which were created during previous start) if action != "
stop": if name == "nfs3": Directory(params.hadoop_pid_dir_prefix, mode=0755, owner=params.root_user, group=params.root_group ) else: Directory(params.hadoop_pid_dir_prefix, mode=0755, owner=params.hdfs_user, ...
import os import logging import numpy as np import theano from pandas import DataFrame, read_hdf from blocks.extensions import Printing, SimpleExtension from blocks.main_loop import MainLoop from blocks.roles import add_role logger = logging.getLogger('main.utils') def shared_param(init, name, cast_float32, role, ...
if cast_float32: v = np.float32(init) p = theano.shared(v, name=name, **kwargs) add_role(p, role) return p class AttributeDict(dict): __getattr__ = dict.__getitem__ def __setattr__(self, a, b):
self.__setitem__(a, b) class DummyLoop(MainLoop): def __init__(self, extensions): return super(DummyLoop, self).__init__(algorithm=None, data_stream=None, extensions=extensions) def run(self): ...