prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
'Fe3O4': 231.531, 'BaO': 153.326, 'SrO': 103.619, 'Cr2O3': 151.98919999999998, } def __init__(self, parent=None, df=pd.DataFrame()): QMainWindow.__init__(self, parent) self.setWindowTitle('Chemical Index of Alteration &...
'Chemical Index of Alteration & Index of Compositional Variability') self.tableView = CustomQTableView(self.main_fr
ame) self.tableView.setObjectName('tableView') self.tableView.setSortingEnabled(True) self.textbox = GrowingTextEdit(self) self.textbox.setText(self.reference) # Other GUI controls self.save_button = QPushButton('&Save') self.save_button.clicked.connect(self.sa...
# -*- coding: utf-8 -*- import usb class LuxaforFlag(object): DEVICE_VENDOR_ID = 0x04d8 DEVICE_PRODUCT_ID = 0xf372 MODE_STATIC_COLOUR = 1 MODE_FADE_COLOUR = 2 MODE_STROBE = 3 MODE_WAVE = 4 MODE_PATTERN = 6 LED_TAB_1 = 1 LED_TAB_2 = 2 LED_TAB_3 = 3 LED_BACK_1 = 4 LED_B...
port multiple specific LEDs. """ command = self.create_strobe_command(led, r, g, b, duration, repeat) self.write(command) def do_wave(self, wave_type, r, g, b, duration, repeat
): """ Animate the flag with a wave pattern of the given type, using the specified colour, duration and number of times to repeat. """ command = self.create_wave_command( wave_type, r, g, b, duration, repeat ) self.write(command) def do_pattern(se...
0]*1024 #self._ = self.write(t); #print "CWeatherStationConfig._CheckSumm (should be retrieved) --> 0x%x" % self._CheckSumm def read(self,buf,start): self.logger.debug("wsconfig") nbuf=[0] nbuf[0]=buf[0] #print "read",nbuf[0] CheckSumm = nbuf[0][43+start] | (nbuf[0][42+start] << 8); self._CheckSumm = ...
AlarmTempIndoor); #v25 = v2; #v24 = CWeatherTraits.TemperatureOffset() + v2; #v21 = v24; #v22 = CWeatherTraits.TemperatureOffset() + CWeatherStationHighLowAlarm::GetLow
Alarm(&thisa->_AlarmTempIndoor); #v4 = v22; #USBHardware::ToTempAlarmBytes(nbuf, 7, v22, v21); #((void (__thiscall *)(CWeatherStationHighLowAlarm *))thisa->_AlarmTempOutdoor.baseclass_0.baseclass_0.vfptr[1].__vecDelDtor)(&thisa->_AlarmTempOutdoor); #v25 = v4; #v24 = CWeatherTraits.TemperatureOffset() + v4; ...
from....import a from...import b from..import c from.import d
from : keyword.control.import.python, source.python .... : punctuation.separator.period.python, source.python import : keyword.control.import.python, source.python : source.python a : source.python from : keyword.control.import.python, source.python ... ...
: punctuation.separator.period.python, source.python import : keyword.control.import.python, source.python : source.python b : source.python from : keyword.control.import.python, source.python .. : punctuation.separator.period.python, source.python import : ke...
der(self, data, ttFont): format, length, language = struct.unpack(">HHH", data[:6]) assert len(data) == length, "corrupt cmap table format %d (data length: %d, header length: %d)" % (format, len(data), length) self.format = int(format) self.length = int(length) self.language = int(language) self.data = data...
def decompile(self, data, ttFont): # we usually get here indirectly from the subtable __getattr__ function, in which case both args must be None. # If not, someone is calling the subtable decompile() directly, and must provide both args. if data is not None and ttFont is not None: self.decompileHeader(data[of...
is None and ttFont is None), "Need both data and ttFont arguments" data = self.data # decompileHeader assigns the data after the header to self.data assert 262 == self.length, "Format 0 cmap subtable not 262 bytes" glyphIdArray = array.array("B") glyphIdArray.fromstring(self.data) self.cmap = cmap = {} len...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Datetools provide a method of manipulating and working dates and times. # Copyright (C) 2013-2018 Chris Caron <lead2gold@gmail.com> # # This file is part of Datetools. Datetools is free software; you can # redistribute it and/or modify it under the terms of the GNU Gener...
", ref=datetime(2000, 5, 3, 10, 10, 0)) # Support python date object print dateblock("*/1", ref=date(2000, 5, 3)) # Support python time object print dateblock("*/1", ref=time(20, 5, 3), block=False) # Time equals 'now' print dateblock("*/1", ref=None, block=False) # Epoch Time print dateblock("*/1", ref=7999434323, blo...
e is in the past print dateblock("*/10 +7", ref=999434323, block=True) # Drifting inline print dateblock("*/10 +5", ref=date(2000, 1, 1), block=False) # Drifting inline (with option specified, inline should over-ride) # Drifting without use of + print dateblock("*/10 * * * * * 5", ref=date(2000, 2, 1), block=False) # D...
import pandas as pd import numpy as np from random import sample from sklearn.ensemble import RandomForestClassifier def ML_BuySell(all_data, predictDate, predictors, previous_results, limit=0.0051, limit_comp=np.arange(-.015, 0.02, 0.001), days_previous=252, train_split=0.8, n=3,acc_limit=0.75): "...
.index <= predictDate].shift(-1) ALLY_DATA = ALLY_DATA.drop(ALLY_DATA.index[-1]) fluc_m = [] X_TEST_B = ALLX_DATA[(-1 * days_previous):] Y_TEST_B = ALLY_DATA[(-1 * days_previous):] # Get parameters for the day in question PREDICT_X = all_data.ix[a
ll_data.index == predictDate, predictors] if PREDICT_X.empty: return pred_v = [] acc = [] for x in np.nditer(limit_comp): indices = sample(range(days_previous), int(np.round(days_previous * train_split))) X_TRAIN = X_TEST_B.ix[indices] Y_TRAIN = Y_TEST_B.ix[indices] ...
#!/usr/bin/env python """ This script is a python version of TimingAccuracyDHC. We use numpy functions to simplify the creation of random coefficients. """ import os import sys import time import numpy as np sys.path.append(os.path.join(os.path.dirname(__file__), "../../..")) import pyshtools as shtools #==== MAIN F...
ampling=sampling) tend = time.time() tforward = tend - tstart # compute error err = np.abs(cilm_trim[mask_trim] - cilm2_trim[mask_
trim]) / np.abs(cilm_trim[mask_trim]) maxerr = err.max() rmserr = np.mean(err**2) print '{:4d} {:1.2e} {:1.2e} {:1.1e}s {:1.1e}s'.\ format(lmax, maxerr, rmserr, tinverse, tforward) lmax = lmax * 2 #==== EXECUTE SCRIPT ==== if __name__ == "__main__": main()
ed. # See the License for the specific language governing permissions and # limitations under the License. # # google-cloud-functions documentation build configuration file # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are presen...
uiltin "default.css". html_static_path = ["_static"] #
Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. # html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format...
lf.H2s[None]) if term is None: raise ValueError(f"No term has been set for sites {sites}, either " "specifically or via a default term.") # add single site term to left site if present H1 = self.H1s.get(i, self.H1s[None]) # but only if this site...
1) U = self.get_gate(dt_frac, sites) self._pt.left_canonize(start=max(0, i - 1), stop=i) self._pt.gate
_split_( U, where=sites, absorb='right', **self.split_opts) elif direction == 'left': # Apply odd gates: # # >->->- ->->->->->->->->-o # | | | | | | | | | | | | o~<~<~<~<~<~<~<~<~<~<~< # | UUU ... UUU UUU UU...
import sys if sys.platform.startswith('win32'): import win32gui GetForegroundWindow = win32gui.GetForegroundWindow SetForegroundWindow = win32gui.SetForegroundWindow elif sys.platform.startswith('darwin'): from Foundation import NSAppleScript def GetForegroundWindow(): return NSAppl...
ow(pid): NSAppleScript.alloc().initWithSource_(""" tell application "System Events" set the frontmost of first process whose unix id is %d to true end tell""" % pid).executeAndReturnError_(None) elif sys.platform.startswith('linux'): from subprocess import call, check_output, CalledProcessError ...
sError: return None def SetForegroundWindow(w): """Returns focus to previous application.""" try: call(['wmctrl', '-i', '-a', str(w)]) except CalledProcessError: pass
#!/usr/bin/env python #/****************************************************************************** # * $Id$ # * # * Project: GDAL Make Histogram and Cumulative graph from Tab delimited tab as # generated by gdal_hist.py # * Purpose: Take a gdal_hist.py output and create a histogram plot using matp...
t " This program is geared to run on a table as generated by gdal_hist.py" print 'slope_histogram_cumulativ
e_graph.py -name "E_Marg_CE 01" DEM_1m_E_Marg_CE_adir_1m_hist.xls DEM_1m_E_Marg_CE_adir_1m_hist.png' sys.exit(0) #set None for commandline options name = "" infile = None outfile = None # ============================================================================= # Parse command line arguments. # ==============...
# -*- coding: utf-8 -*- ''' Pupil Player Third Party Plugins by cpicanco Copyright (C) 2016 Rafael Picanço. The present file is distributed under the terms of the GNU General Public License (GPL v3.0). You should have received a copy of the GNU General Public License along
with this program. If not, see <http://www.gnu.org/licenses/>. ''' import cv2 from pyglui import ui from plugin import Plugin blue, green, red = 0, 1, 2 class Filter_Opencv_Threshold(Plugin): """ Apply cv2.threshold in each channel of the (world) frame.img """ uniqueness = "not_unique" def _...
n before all plugins # self.order = .1 # run after all plugins self.order = .99 # initialize empty menu self.menu = None # filter properties self.threshold = threshold self.thresh_mode = thresh_mode self.otsu = otsu def update(self,frame,ev...
import antlr3; import sqlite3; import pickle; import sys, os; import re; from SpeakPython.SpeakPython import SpeakPython; from SpeakPython.SpeakPythonLexer import SpeakPythonLexer; from SpeakPython.SpeakPythonParser import SpeakPythonParser; #sort results based on length of labels def sortResults(results): l = len(r...
ch test cases passed."; c = conn.cursor(); c.executemany("INSERT INTO matches VALUES (?,?,?,?)", matchEntries)
; conn.commit(); print "Running test cases for functions..."; for f in functions: f = functions[f]; #perform in-suite test cases succeededTests = performTestCases(f, f.testCases); if not succeededTests: return; #save all regex groups in database under function name if len(f.kGroupRegexes) > 0: ...
from distutils.core import setup version = '1.1.1' setup(name='CacheGenerator', version=version, des
cription="CacheGenerator for Django", author="Ricardo Santos", author_email="ricardo@getgears.com",
url="http://github.com/ricardovice/CacheGenerator/", packages = ['cachegenerator'] )
# Copyright (c) 2022 PaddlePaddle Authors. 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 ap...
use_bn_add_act")]) pass_manager.apply([main_prog], [startup_prog]) print(pass_manager.names) op_type = [] for op in main_prog.global_block().ops: op_type.append(op.type) self.assertTrue("fused_bn_add_activation" in op_type) self.assertTrue("fused_bn_add_activ...
ain()
from django.conf.urls import patterns, include, url from django.conf import settings # Here, user contacts.profile will cause some 'mismatch' since contacts is also a module from profile import ProfileView from contacts import ContactsView from authen import Authenticate strid = settings.CONTACT_URL['strid'] user = s...
RL['auth'] urlpatterns = patterns('', url(r'^api/'+auth+'$', Authenticate.as_view()), url(r'^api/(?P<'+strid+r'>\w{16})/$', ProfileView.as_view())
, url(r'^api/(?P<'+strid+r'>\w{16})/(?P<'+contact+r'>\d+)/$', ContactsView.as_view()), url(r'^(?P<'+user+r'>\w{5,18})/(?P<'+strid+r'>\w{16})/$', ProfileView.as_view()), url(r'^(?P<'+user+r'>\w{5,18})/(?P<'+strid+r'>\w{16})/(?P<'+contact+r'>\d+)/$', ContactsView.as_view()), )
import sys from django.core.management.base import BaseCommand, CommandError import nflgame from terminaltables import AsciiTable from ...models import Player, Team, Season, Week, WeeklyStats class Command(BaseCommand): help = 'takes option position, displays top play
ers as table' def add_arguments(self, parser): # Named (optional) arguments parser.add_argument('position', nargs=1) def handle(self, *args, **
options): p = options['position'] if p: Player.show_top_players(position=p[0]) else: Player.show_top_players()
ftware # 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. # # Keystone documentation build configuration file, created by ...
rt sys # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. BASE_DIR = os.path.dirname(os.path.abspath(__file__)) ROOT_DIR = os.path.a...
ral configuration --------------------------------------------------- # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.coverage', 'sphinx.ext.ifco...
# -*- coding: utf8 -*- import logging import math from Graphx import graphx from GameEngine.GameObjects.gameObjectBehaviour import GameObjectBehaviour from Brains.human import HumanBrain from conf import conf class CarBehaviour(GameObjectBehaviour): brainTypes = { 'human': HumanBrain } """ Behaviour of the ...
ding using the car's maniability. The velocity does not change """ self._newHeading = self._model.headingAngle - \ self._model.constant('maniability') self._newVelocity = self._model.velocity self.move() def turnLeft(self): """ Turn left relatively to the car'
s heading using the car's maniability The velocity does not change """ self._newHeading = self._model.headingAngle + \ self._model.constant('maniability') self._newVelocity = self._model.velocity self.move() def update(self, stateManager): """ Use the brain the take the decision about what is the nex...
#!/usr/bin/env python3 # Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST. # Basically, the deletion can be divided into two stages: # Search for a node to remove. # If the node is found, delete the node. # Not...
root.left = self.deletemax(node.left) root.right = node.right return root def getmax(self, root): if root == None or root.right == None: return root return getmax(root.right) def deletemax(self, root): if root == None: return None i...
sol = Solution() root = treeBuilder(nodeString) print('lala') traverse(sol.deleteNode(root, 3))
# -*- coding: utf-8 -*- """ requests.auth ~~~~~~~~~~~~~ This module contains the authentication handlers for Requests. """ import os import re import time import hashlib from base64 import b64encode from .compat import urlparse, str from .cookies import extract_cookies_to_jar from .utils import parse_dict_header ...
rithm == 'MD5-SESS': def md5_utf8(x): if isinstance(x, str): x = x.encode('utf-8') return hashlib.md5(x).hexdigest()
hash_utf8 = md5_utf8 elif _algorithm == 'SHA': def sha_utf8(x): if isinstance(x, str): x = x.encode('utf-8') return hashlib.sha1(x).hexdigest() hash_utf8 = sha_utf8 KD = lambda s, d: hash_utf8("%s:%s" % (s, d)) ...
ssert(self.is_driver_job()) return self.stats.get("Driver.NumDriverJobsSkipped", 0) def driver_jobs_total(self): """Return the total count of a driver job's ran + skipped sub-jobs""" assert(self.is_driver_job()) return self.driver_jobs_ran() + self.driver_jobs_skipped() def mer...
ided_stats) def incrementality_percentage(self): """Assuming the job is a driver job, return the amoun
t of jobs that actually ran, as a percentage of the total number.""" assert(self.is_driver_job()) ran = self.driver_jobs_ran() total = self.driver_jobs_total() return round((float(ran) / float(total)) * 100.0, 2) def to_catapult_trace_obj(self): """Return a JSON-form...
from models import db from models.Post import Post class PostFile(db.Model): __tablename__ = 'PostFile' Id = db.Column
(db.Integer, primary_key = True) Post = db.Column(db.Integer, db.ForeignKey(Post.Id)) FileName = db.Column(db.String(128)) def __init__(self, post, file):
self.Post = post self.FileName = file
# -*- coding: utf-8 -*- """ Created on Fri Jun 25 16:20:12 2015 @author: Balázs Hidasi @lastmodified: Loreto Parisi (loretoparisi at gmail dot com) """ import sys import os import numpy as np import pandas as pd import datetime as dt # To redirect output to file class Logger(object): def __init__(self, filename=...
onId, session_lengths[session_lengths>=2].index)] tmax = data.Time.max() session_max_times = data.groupby('SessionId').Time.max() session_train = session_max_times[session_max_times < tmax-86400].index session_test = session_max_times[session_max_times >= tmax-86400].index train = data[np.in1d(data.
SessionId, session_train)] test = data[np.in1d(data.SessionId, session_test)] test = test[np.in1d(test.ItemId, train.ItemId)] tslength = test.groupby('SessionId').size() test = test[np.in1d(test.SessionId, tslength[tslength>=2].index)] print('Full train set\n\tEvents: {}\n\tSessions: {}\n\tItems: {}'.format(len(train),...
a = [
1 2 3
]
om .data_model import PGSqlResultModel return PGSqlResultModel(self, sql, parent) def registerDatabaseActions(self, mainWindow): Database.registerDatabaseActions(self, mainWindow) # add a separator separator = QAction(self) separator.setSeparator(True) mainWindow.r...
rule_name = parts[1] rule_action = parts[2] msg = u"Do you want to %s rule %s?" % (rule_action, rule_name) QApplication.restoreOverrideCursor() try: if QMessageBox.question(None, self.
tr("Table rule"), msg, QMessageBox.Yes | QMessageBox.No) == QMessageBox.No: return False finally: QApplication.setOverrideCursor(Qt.WaitCursor) if rule_action == "delete": self.aboutToChange.emit() ...
from yaml import dump from twisted.internet.defer import succeed, fail from txaws.s3.exception import S3Error from juju.lib.testing import TestCase from juju.providers.ec2.tests.common import EC2TestMixin class EC2StateTest(TestCase, EC2TestMixin): def setUp(self): EC2TestMixin.setUp(self) sup...
"" When loading saved state from S3, the provider bootstrap gracefully handles the scenario where there is no saved state. """ self.s3.get_object(self.env_name, "provider-state") self.mocker.result(succeed(dump([]))) self.mocker.replay() provider = self.get_provi...
e) return d
from django.conf.urls import patterns, include, url from django.conf.urls.static import static from django.conf import settings
from django.contrib import admin urlpatterns = patterns('', # Examples: # url(r'^$', 'isucdc2.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^', include('cdc.urls', namespace="cdc")), ) + static(settings.MEDIA_URL, document_root...
ttings.MEDIA_ROOT)
""" 33. get_or_create() ``get_or_create()`` does what it says: it tries to look up an object with the given parameters. If an object isn't found, it creates one with the given parameters. """ from __future__ import unicode_literals from django.db import models from django.utils.encoding import python_2_unicode_compa...
Person(models.Model)
: first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) birthday = models.DateField() def __str__(self): return '%s %s' % (self.first_name, self.last_name) class DefaultPerson(models.Model): first_name = models.CharField(max_length=100, default="Anonym...
""" smashlib.plugins.cli_update The handler for "smash --update".
This will default to using whatever branch is already checked out """ from fabric import api from goulash.python import splitext, ops from smashlib import get_smash from smashlib.util import CLOpt from smashlib.plugins import Plugin from smashlib.util.events import receives_event from smashlib.channels import C_...
E from smashlib import data class UpdateSmash(Plugin): """ This plugin is responsible for doing the work whenever smash is invoked with "--update". """ update = None verbose = True # do not change, user needs some feedback def get_cli_arguments(self): return [ CLOpt( ...
from django.core.management.base import
BaseCommand from lizard_blockbox import import_helpers class Command(BaseCommand): args = "" help = "Merge the measure shapes to get one json." def handle(self, *args, **kwargs): import
_helpers.merge_measures_blockbox(self.stdout)
import clr clr.AddReference('RevitAPI') from Autodesk.Revit.DB import * mats = UnwrapElement(IN[0]) colorlist = list() glowlist = list() classlist = list() shinylist = list() smoothlist = list() translist = list() for mat in mats: colorlist.append(mat.Color) if mat.Glow: glowlist.append(True) else: glowlist.ap...
append(mat.Shininess) smoothlist.
append(mat.Smoothness) translist.append(mat.Transparency) OUT = (classlist,colorlist,glowlist,shinylist,smoothlist,translist)
# The MIT License (MIT) # # Copyright shifvb 2015 # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge,...
import select def read_write(client, target): time_out_max = 20 socs = [client, target] count = 0 while 1: count += 1 (recv, _, error) = select.select(socs, [], socs, 3) if error: break if recv: for in_ in recv: data = in_.recv(...
ug # if out == target: # print('client->server {}\n'.format(data)) # else: # print('server->client {}\n'.format(data)) out.send(data) count = 0 if count == time_out_max: br...
import sys import random import collections import itertools import bisect # @include def nonuniform_random_number_generation(values, probabilities): prefix_sum_of_probabilities = ( [0.0] + list(itertools.accumulate(probabilities))) interval_idx = bisect.bisect(prefix_sum_of_probabilities, ...
_times)) for i in range(n): print(counts[i] / (n * k_
times), P[i]) assert abs(counts[i] / (n * k_times) - P[i]) < 0.01 if __name__ == '__main__': main()
""" def toLocal(dt, offset = 8): dt: datetime offset: default 8 china time """
import datetime def toLocal(dt, offset = 8): localDateTime = dt + datetim
e.timedelta(hours=offset) return localDateTime if __name__ == '__main__': now = datetime.datetime.utcnow() print now print toLocal(now) print now
DING 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, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH...
y functions. def GetFileValues(filename): values = [] with open(filename, 'r') as filecontent: if 'overhead-babeltrace' in filename: for line in filecontent.readlines():
match = re.match(r'(.*)real\s0m(.*)s.*', line, re.M|re.I) if (match): values.append(eval(match.group(2))) if 'overhead-find' in filename: for line in filecontent.readlines(): match = re.match(r'(.*)real\s0m(.*)s.*', line, re.M|re.I) if (match): values.append(eval...
# Copyright (c) 2010-2013 by Yaco Sistemas <goinnn@gmail.com> or <pmartin@yaco.es> # # This program 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 Software Foundation, either ver
sion 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 # GNU Lesser General Public License for more details. # # Y...
If not, see <http://www.gnu.org/licenses/>. try: from django.conf.urls import include, patterns, url except ImportError: # Django < 1.4 from django.conf.urls.defaults import include, patterns, url urlpatterns = patterns('testing.example_extra_fields.views', url(r'^$', 'extra_index', name='extra_index'...
# coding=utf-8 # URL: https://pymedusa.com # # This file is part of Medusa. # # Medusa 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....
", "tvdb_userabort", "tvdb_shownotfound", "tvdb_showincomplete", "tvdb_seasonnotfound", "tvdb_episodenotfound", "t
vdb_attributenotfound"] # link API exceptions to our exception handler indexer_exception = tvdb_exception indexer_error = tvdb_error indexer_userabort = tvdb_userabort indexer_attributenotfound = tvdb_attributenotfound indexer_episodenotfound = tvdb_episodenotfound indexer_seasonnotfound = tvdb_seasonnotfound indexer_...
ICENSE files for our notice and the LGPL. # # This program 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 Software Foundation) version 2.1, February 1999. # # This program is distributed in the hope that it will be useful...
``. """ style, color, text = match.groups() m = match.group(0) if m == '@@': return '@' elif m == '@.': return self.escape(0) elif m == '@': raise ColorParseError("Incomplete color format: '%s' in %s" ...
ParseError("invalid color specifier: '%s' in '%s'" % (color, match.string)) string += ';' + str(colors[color]) colored_text = '' if text: colored_text = text + self.escape(0) return self.escape(string) + colored_text def colorize(...
import matplotlib.pyplot as plt import numpy as np from scipy.optimize import root import bct eps = np.finfo(float).eps def pij_wij(x,y,t): xij = np.outer(x,x) yij = np.outer(y,y) pij = xij*((yij)**t)/(1.0+xij*(yij**t) - (yij**t)) wij = (t*(xij-1.0)*(yij**t))/((1.0 + xij*(yij**t) - (yij**t) )) - 1.0/(n...
mshow(W) plt.colorbar(im,fraction=0.046, pad=0.04) plt.grid(False) plt.title('empirical matrix') plt.subplot(2,3,4) plt.plot((W>0).sum(axis=0),pij.sum(axis=0), 'b.') plt.plot(np.linspace(0,pij.sum(axis=0).max()),np.linspace(0,pij.sum(axis=0).max()),'r-') plt.grid(True) plt.axis('equal')...
in((W>0).sum(axis=0).max(),pij.sum(axis=0).max())]) #plt.ylim([0,min((W>0).sum(axis=0).max(),pij.sum(axis=0).max())]) plt.subplot(2,3,5) plt.plot(W.sum(axis=0),wij.sum(axis=0), 'b.') plt.plot(np.linspace(0,wij.sum(axis=0).max()),np.linspace(0,wij.sum(axis=0).max()),'r-') plt.title('$ s_i - <s_i>$')...
from configparser import ConfigParser import psycopg2 class Postgres(object): def __init__(self, db_name): filename = 'database.ini' section = 'postgresql' parser = ConfigParser() parser.read(filename) self.db = {} if parser.has_section(section): self.db['database'] = db_name par...
nn = None try: self.conn = psycopg2.connect(**self.db) self.cur = self.conn.cursor() except (Exception, psycopg2.DatabaseError) as error: print(error) def close(self): self.conn.close() def execute(self, sql, params = ()): self.cur.execute(sql, params) self.conn.commit() def g...
sion = self.cur.fetchone() self.close() return version
import io import json import os import subprocess import sys import unittest from os.path import join, abspath, dirname sys.path.append('..') from python_driver import __version__, get_processor_instance from python_driver.requestprocessor import ( Request, Response, RequestProcessorJSON, InBuffer, EmptyCodeExcept...
abspath(dirname(__file__)) # Disabled until I update the new module with typing # class TestTypeCheck(uni
ttest.TestCase): # def test_10_check(self) -> None: # prevdir = os.getcwd() # try: # os.chdir(dirname(CURDIR)) # srcdir = abspath(join(dirname(CURDIR), 'python_driver', '*')) # self.assertEqual(subprocess.call(['test/typecheck.sh', srcdir], shell=True), 0) ...
# -*- coding: utf-8 -*- """Factories to help in tests.""" from factory import PostGenerationMethodCall, Sequence from factory.alchemy import SQLAlchemyModelFactory from authmgr.database import db from authmgr.user.models import User class BaseFactory(SQLAlchemyModelFactory): """Base factory.""" class Meta: ...
abstract = True sqlalchemy_session = db.session class UserFactory(BaseFactory): """User factory.""" usern
ame = Sequence(lambda n: 'user{0}'.format(n)) email = Sequence(lambda n: 'user{0}@example.com'.format(n)) password = PostGenerationMethodCall('set_password', 'example') active = True class Meta: """Factory configuration.""" model = User
############################################################################### # Name: txtutil.py # # Purpose: Text Utilities. # # Author: Cody Precord <cprecord@editra.org> # ...
----------------------------------------# def IsUnicode(txt): """Is the given string a unicode string @param txt: object @return: bool """ return isinstance(txt, ty
pes.UnicodeType)
d
ef on_square(): pass def total_after():
pass
# -*- coding: utf-8 -*- import user import inscriptio
n import notes import util import stage # vim:expandtab:s
martindent:tabstop=4:softtabstop=4:shiftwidth=4:
pr
int("test\n")
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-06-01 12:02 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('website', '0030_github_user'), ] operations = [ migrations.AddField( ...
name='technology1', field=models.CharField(default='', max_length=50), ), migrations.AddField( model_name='linkedin_user', name='technology2', field=models.CharField(default='', max_length=50), ), migrations.AddField( mo...
th=50), ), ]
from django.db import models class BranchManager(models.Manager): def get_branch(self, user, project): try: return self.get(user=user, project=project, active=True)
except: return self.create(user=user, project=project, active=True) class Branch(models.Model): user = models.ForeignKey('auth.User') project = models.ForeignKey('projects.Project') active = models.BooleanField(default=True) pushed = models.BooleanField(default=False) title = models.Te...
(default='') objects = BranchManager() def __unicode__(self): return "Branch of %s by %s (%s)" % (self.project, self.user, self.pk)
from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ class NavConfig(AppCo
nfig): name = 'cms.nav' verbose_name = _('Na
vigation')
import sys import os import cv2 from keras.models import load_m
odel sys.path.append("/Users/alexpapiu/Documents/Conv/OpenCV_CNN") from webcam_cnn_pipeline import return_compiled_model_2, real_time_pred model_name = sys
.argv[1] w = 1.5*144 h = 2*144 #keep track of all labels: all_labels = {"model_hand":["A", "B", "C", "D", "No Hand"], "basic_model":["happy", "sad", "normal", "incredulous"], "model_face":["happy", "sad", "normal"]} labelz = dict(enumerate(all_labels[model_name])) os.chdir("/Users/alexpa...
# pandas and numpy for data manipulation import pandas as pd import numpy as np import sqlite3 from bokeh.plotting import Figure from bokeh.models import ( CategoricalColorMapper, HoverTool, ColumnDataSource, Panel, FuncTickFormatter, SingleIntervalTicker, LinearAxis, ) from bokeh.models im...
+ 1 cline = p.line( perfmon.index.values, perfmon[key], line_width=1, alpha=0.8,
color=mypal[col], ) legenditems += [(key, [cline])] p.legend.click_policy = "hide" legend = Legend(items=legenditems, location=(0, 0)) p.add_layout(legend, "below") return p def update(attr, old, new): perfmons_to_plot = [ perfmon_sel...
# Copyright (c) Meta Platforms, Inc. and affiliates. # Copyright (c) Mercurial Contributors. # # This software may be used and distributed according to the terms of the # GNU General Public License version 2 or any later v
ersion. from __future__ import absolute_import from testutil.dott import feature, sh, testtmp # noqa: F401 feature.require(["symlink"]) # https://bz.mercurial-scm.or
g/1438 sh % "hg init repo" sh % "cd repo" sh % "ln -s foo link" sh % "hg add link" sh % "hg ci -mbad link" sh % "hg rm link" sh % "hg ci -mok" sh % "hg diff -g -r '0:1'" > "bad.patch" sh % "hg up 0" == "1 files updated, 0 files merged, 0 files removed, 0 files unresolved" sh % "hg import --no-commit bad.patch" == "...
present. Args: builder_run: See builder_run on ArchivingStage. board: See board on ArchivingStage. archive_stage: See archive_stage on ArchivingStage. channels: Explicit list of channels to generate payloads for. If empty, will instead wait on values from push_image. ...
mpleted result, remember it. self.signing_results[channel][url] = signer_json # If we don't have full results for this channel, we aren't done # waiting. if (len(self.signing_results[channel]) != len(instruction_urls_per_channel[channel]))
: results_completed = False continue # If we reach here, the channel has just been completed for the first # time. # If all results 'passed' the channel was successfully signed. channel_success = True for signer_result in self.signing_results[channel].values(): if...
tings. Raises: Http404 if the course doesn't exist. """ return _get_course_cohort_settings(course_key).id def set_course_cohorted(course_key, cohorted): """ Given a course course and a boolean, sets whether or not the course is cohorted. Raises: Value error if `cohorted` is n...
s: course: the course for which cohorts should be returned assignment_type: cohort assignment type Returns: A list of CourseUserGroup objects. Empty if there are no cohorts. Does not check whether the course is cohorted. """ # Migrate cohort settings for this course migr...
query_set = CourseUserGroup.objects.filter( course_id=course.location.course_key, group_type=CourseUserGroup.COHORT ) query_set = query_set.filter(cohort__assignment_type=assignment_type) if assignment_type else query_set return list(query_set) def get_cohort_names(course): """Return...
# Copyright 2013-2020 Lawrence Livermore National Security, LLC a
nd other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class ExuberantCtags(AutotoolsPackage): """The canonical ctags generator""" homepage = "http://c
tags.sourceforge.net" url = "http://downloads.sourceforge.net/project/ctags/ctags/5.8/ctags-5.8.tar.gz" version('5.8', sha256='0e44b45dcabe969e0bbbb11e30c246f81abe5d32012db37395eb57d66e9e99c7')
# Getting started with APIC-EM APIs # Follows APIC-EM Basics Learning Lab # Basics Learning Lab Full example for Get Devices, Get Hosts, Get Policies, Get Applications # * THIS SAMPLE APPLICATION AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY # * OF ANY KIND BY CISCO, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT ...
h device returned, print the networkDeviceId for item in hosts_parent: print (item["hostIp"]) # Get Policies # This function allows you to view a list of all the policies in the network. get_policies_url = controller_url + 'api/v0/policy' #Perform GET on get_hosts_url and load response into a json ...
s_url) get_policies_json = get_policies_response.json() #Now let's read and display some specific information from the json # set our parent as the top level response object policies_parent = get_policies_json["response"] print ("Policies= ") # for each device returned, print the networkDeviceId for item in polic...
#!/usr/bin/env python import click import logging import os import pagoda import pagoda.viewer def full(name): return os.path.join(os.path.dirname(__file__), name) @click.command() def main(): logging.basicConfig() w = pagoda.cooper.World(dt=1. / 120) w.load_skeleton(full('../optimized-skeleton.txt...
3d'),
full('../optimized-markers.txt')) pagoda.viewer.Viewer(w).run() if __name__ == '__main__': main()
# module for the Container List <dsc> import xml.etree.cElementTree as ET from components import components import globals import wx from messages import error from mixed_content import mixed_content def dsc(dsc_root, FASheet, version): from wx.lib.pubsub import pub wx.CallAfter(pub.sendMessage, "update_spread", msg...
nt.tag == 'c09' o
r component.tag == 'c10' or component.tag == 'c11' or component.tag == 'c12': child_tag_name = component.tag[1:] if int(child_tag_name) < 10: child_tag = "c0" + str(int(child_tag_name) + 1) else: child_tag = "c" + str(int(child_tag_name) + 1) if component.find(child_tag) is None: p...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # This file is part of overview archive. # Copyright © 2015 seamus tuohy, <stuohy@internews.org> # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by the Free # Software Foundation...
R A PARTIC
ULAR PURPOSE. See the included LICENSE file for details. # identification from os import path from os.path import abspath from urllib.parse import urlparse from urllib.request import urlopen import magic from urllib.error import HTTPError # logging import logging log = logging.getLogger("oa.{0}".format(__name__)) d...
# Copyright 2017 The TensorFlow Authors. 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 applica...
sattr(parent_object, node.attr): raise AttributeError('%s has no attribute %s' % (parent_object, node.attr)) anno.setanno(node, 'parent_type', type(parent_object)) anno.setanno(node, 'live_val', getattr(parent_object, node.attr)) anno.se...
gate the role built-in annotations can play here. elif anno.hasanno(node.value, 'type'): parent_type = anno.getanno(node.value, 'type') if hasattr(parent_type, node.attr): # This should hold for static members like methods. # This would not hold for dynamic members like function attribut...
# Copyright 2015 Mellanox Technologies, Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed t...
T}, 'device': self.ASSIGNED_MAC} def test_create_rule(self): self.qos_driver.create(self.port, self.qos_policy) self.max_rate_mock.assert_called_once_with( self.ASSIGNED_MAC, self.PCI_SLOT, self.rule.max_kbps) def test_update_rule(self): self.qos_driver.upda...
te_mock.assert_called_once_with( self.ASSIGNED_MAC, self.PCI_SLOT, self.rule.max_kbps) def test_delete_rules(self): self.qos_driver.delete(self.port, self.qos_policy) self.max_rate_mock.assert_called_once_with( self.ASSIGNED_MAC, self.PCI_SLOT, 0) def test__set_vf_max_r...
""" mod_customized Controllers =================== In this module, users can test their fork branch with customized set of regression tests """ from flask import Blueprint, g, request, redirect, url_for, flash from github import GitHub, ApiError from datetime import datetime, timedelta from decorators import template_...
sers to run tests. User can enter commit or select the commit from their repo that are not more than 30 days old. User can customized test based on selected regression tests and platforms. Also Display list of customized tests started by user. User will be redirecte
d to the same page on submit. """ fork_test_form = TestForkForm(request.form) username = fetch_username_from_token() commit_options = False if username is not None: gh = GitHub(access_token=g.github['bot_token']) repository = gh.repos(username)(g.github['repository']) # Only ...
#!/usr/bin/python # Copyright 2017 Dhvani Patel # # This file is part of UnnaturalCode. # # UnnaturalCode is free software: you can redistribute it and/or modify # it
under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # UnnaturalCode is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warrant...
e details. # # You should have received a copy of the GNU Affero General Public License # along with UnnaturalCode. If not, see <http://www.gnu.org/licenses/>. from check_eclipse_syntax import checkEclipseSyntax from compile_error import CompileError import unittest ERROR_TEST = """public class HelloWorld { ...
pend((chr_name, chr_id, chr_len, cent_s, cent_e)) return r def build_ref_config_file(chr2acc_fname, agp_fnames): """ Build a configuration file of reference genome chromosomes from a chr2acc file and a series of AGP files that describe the assembled chromosomes. :param chr2acc_fname: a name ...
d element is the list of the AxesSubplot objects """ fig, axes = plt.subplots(ncols=1, nrows=len(ref_chrom_config)) max_len = reduce(max, map(itemgetter(2), ref_chrom_config)) shift = max_len / 30 for ax, chrom in zip(axes, ref_chrom_config): chr_name, _, chr_len, _, _ = chrom ...
ax.axis('off') ax.text(-shift, 0, chr_name, horizontalalignment="right", verticalalignment="center") ax.add_line(Line2D([0, chr_len], [0, 0], color="black", linewidth=0.5)) return fig, axes def add_centromeres(fig, ref_chrom_config, p, style): ...
# This file is generated by /tmp/buildd/python-numpy-1.8.2/setup.py # It contains system_info results at the time of building this package. __all__ = ["get_info","show"] blas_info={'libraries': ['blas'], 'library_dirs': ['/usr/lib'], 'language': 'f77'} lapack_info={'libraries': ['lapack'], 'library_dirs': ['/usr/lib']...
t.items(): v = str(v)
if k == "sources" and len(v) > 200: v = v[:60] + " ...\n... " + v[-60:] print(" %s = %s" % (k,v))
import numpy as np from gym.spaces import Box from metaworld.envs import reward_utils from metaworld.envs.asset_path_utils import full_v2_path_for from metaworld.envs.mujoco.sawyer_xyz.sawyer_xyz_env import SawyerXYZEnv, _assert_task_is_set class SawyerHammerEnvV2(SawyerXYZEnv): HAMMER_HANDLE_LENGTH = 0.14 ...
margin=0.2, sigmoid='long_tail', ) return in_place def compute_reward(self, actions, obs): hand = obs[:3] hammer = obs[4:7] hammer_head = hammer + np.array([.16, .06, .0]) # `self._gripper_caging_reward` assumes that the target object can be #...
ging_reward` we pass in a # modified hammer position. # This modified position's X value will perfect match the hand's X value # as long as it's within a certain threshold hammer_threshed = hammer.copy() threshold = SawyerHammerEnvV2.HAMMER_HANDLE_LENGTH / 2.0 if abs(hamm...
from random import randint import os PAN_HOST = "pan.baidu.com" PAN_INDEX = "http://" + PAN_HOST DISK_HOME = PAN_INDEX + '/disk/home' FILE_MANAGER = PAN_INDEX + "/api/filemanager" CLOUD_DL = PAN_INDEX + "/rest/2.0/services/cloud_dl" PASSPORT_HOST = 'passport.baidu.com' PASSPORT_INDEX = "https://" + PASSPORT_HOST PASSPO...
e/41.0.2272.89 Safari/537.36', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.71 Safari/537.36', 'Mozilla/5.0 (X11; Linux x86_64; rv:24.0) Gecko/20100101 Firefox/24.0',
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36',] USERAGENT = USERAGENTLIST[randint(0,len(USERAGENTLIST)-1)] GREEN = u"\033[42m%s\033[m" BLUE = u"\033[44m%s\033[m" RED = u"\033[41m%s\033[0m" WHITE= u"%s" SAVINGPATH = os.path.expanduser("~/Downloads")
# -*- coding: utf-8 -*- from __future__ import unicode_literals from
wtforms import validators from jinja2 import Markup from flask.ext.admin.contr
ib.sqla import ModelView from studio.core.engines import db from suibe.models import SlideModel, ArticleModel from .forms import CKTextAreaField class Article(ModelView): create_template = 'panel/article_edit.html' edit_template = 'panel/article_edit.html' column_labels = {'id': 'ID', ...
# -*- coding: utf-8 -
*- import mock import pytest from future.moves.urllib.parse import urlparse, urljoin from addons.base.tests import views from addons.base.tests.utils import MockFolder from addons.mendeley.models import Mendeley from addons.mendeley.tests.utils import MendeleyTestCase, mock_responses from tests.base import OsfTestCas...
mport MendeleyCitationsProvider from addons.mendeley.serializer import MendeleySerializer API_URL = 'https://api.mendeley.com' pytestmark = pytest.mark.django_db class TestAuthViews(MendeleyTestCase, views.OAuthAddonAuthViewsTestCaseMixin, OsfTestCase): pass class TestConfigViews(MendeleyTestCase, views.OAuthCi...
# Copyright (C) 2010-2019 The ESPResSo project # # This file is part of ESPResSo. # # ESPResSo 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 v...
800], background_color=[0, 0, 0], camera_position=[20, 15, 80], particle_coloring='node', draw_nodes=True, draw_cells=True) system.time_step = 0.0005 system.cell_system.set_regular_decomposition(use_verlet_lists=True) system.cell_system.skin = 0.4 #system.cell_system.node_grid = [i, j, k] for i i...
nded_inter[0, 0].lennard_jones.set_params( epsilon=100.0, sigma=1.0, cutoff=3.0, shift="auto") energy = system.analysis.energy() print(f"Before Minimization: E_total = {energy['total']:.2e}") system.integrator.set_steepest_descent(f_max=50, gamma=30.0, max_displacement=0.001)...
# -*- coding: utf-8 -*- """ ################################################ Plataforma ActivUFRJ ################################################ :Author: *Núcleo de Computação Eletrônica (NCE/UFRJ)* :Contact: carlo@nce.ufrj.br :Date: $Date: 2009-2010 $ :Status: This is a "work in progress" :Revision: $Revision: 0.0...
} if (doc.type=="group" ) { emit([doc.registry_id, doc._id, doc.data_cri, 0], doc); } } ...
tartkey=[registry_id],endkey=[id, {}, {}]) activity_list_by_registry = ViewDefinition('activity', 'list_by_registry', \ ''' function (doc) { if (doc.type=="activity" ) { ...
# encoding: utf-8 from setuptools import setup, find_packages
import toasyncio setup( name='toasyncio', packages=find_packages(exclude=['tests']), install_requires=( 'tornado>=4.2', 'asyncio', ), author=toasyncio.__author__, version=toasyncio.__version__,
author_email=", ".join("{email}".format(**a) for a in toasyncio.author_info), long_description=open('README.rst', 'r').read(), license='MIT', keywords=( "tornado", "asyncio", ), url='https://github.com/mosquito/toasyncio', description='Transparent convert any asyncio futures...
# Project : Dlab-Finance # W251 Nital Patwa and Ritesh Soni # Desc : This program counts for each exchange, the #of times it produced best bid (or ask) and average size of bid (or ask) # The purpose is to understand what roles exchanges such as BATS play. # Usage Instructions # Change inputDir for daily quote file and ...
((list1[i][2] == 0) or (list1[i][8] == 'B')): bidList[exchangeList.index(list1[i][6])] = 0 bidSize[exchangeList.index(list1[i][6])] = 0 # size if ((list1[i][4]
!= 0) & (list1[i][5] != 0)): askList[exchangeList.index(list1[i][7])] = list1[i][4] askSize[exchangeList.index(list1[i][7])] = list1[i][5] elif ((list1[i][4] == 0) or (list1[i][8] == 'B')): askList[exchangeList.index(list1[i][7])] = sys.maxsize askSize[exchangeLis...
unctions.py') from TephigramPlot import * from SoundingRoutines import * imp.load_source('GeogFuncs', '/nfs/see-fs-01_users/eepdw/python_scripts/modules/GeogFunctions.py') from GeogFuncs import * pmin=200. station_list_cs=[42182, 43003, 43014, 42867, 43371, 43353, 43285, 43192, 43150, 42339, 40990, 40948] #station_...
# Parse the data for stat in station_list_cs: station_name,la,lo, st_height=StationInfoSearch(stat) load_file = load('/nfs/a90/eepdw/Data/Observations/Radiosonde_Numpy/Radiosonde_Cross_Section_' 'IND_SOUNDING_INTERP_MEAN_Climat_%s_%s_%s_%s.npz'
% (date_min.strftime('%Y%m%d'), date_max.strftime('%Y%m%d'), delta, stat)) data=load_file['date_bin_mean_all_dates_one_station'] dates=load_file['dates_for_plotting'] for bin in range(data.shape[0]): try: p=data[bin,0,:]/100 T=data[bin,1,:]-273.15 ...
from __future__ import absolute_import from changes.api.base import APIView from changes.models import Task class TaskIndexAPIView(APIView): def get(self): q
ueryset = Task.query.order_by(Task.date_created.desc()) return self.paginat
e(queryset)
#!/usr/bin/env python # vi:ai:et:ts=4 sw=4 # # -*- coding: utf8 -*- # # PyMmr My Music Renamer # Copyright (C) 2007-2010 mathgl67@gmail.com # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundatio...
ort MySQLdb self.db = MySQLdb.connect( host=self._config_['host
'], user=self._config_['user'], passwd=self._config_['password'], db=self._config_['db'] ) self.db.set_character_set("utf8") self._album_ = Album('freedb', self._base_score_) def do_album(self): for res in self._album_list_: if res.art...
# -*- coding: utf-8 -*- # Copyright(C) 2010-2011 Nicolas Duhamel # # This file is part of a weboob module. # # This weboob module 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 Software Foundation, either version 3 of the...
epositionnerCheminCourant, BadLoginPage, AccountDesactivate, UnavailablePage, Validated2FAPage, TwoFAPage, SmsPage, DecoupledPage, ) from .accountlist import AccountList, AccountRIB, Advisor, RevolvingAttributesPage from .accounthistory import AccountHistory, CardsList from .transfer import TransferChooseAccoun...
ValidateCountry, ConfirmPage, RcptSummary from .subscription import SubscriptionPage, DownloadPage, ProSubscriptionPage __all__ = ['LoginPage', 'Initident', 'CheckPassword', 'repositionnerCheminCourant', "AccountList", 'AccountHistory', 'BadLoginPage', 'AccountDesactivate', 'TransferChooseAccounts', 'Co...
rses), 1) found_course = courses[0]['course'] self.assertIn('courses/{}/about'.format(self.course.id), found_course['course_about']) self.assertIn('course_info/{}/updates'.format(self.course.id), found_course['course_updates']) self.assertIn('course_info/{}/handouts'.format(self.course....
self.course) self.assertIsNotNone(expected_course_image_url) self.assertIn(expected_course_image_url, found_course['course_image']) self.assertIn(expected_course_ima
ge_url, found_course['media']['course_image']['uri']) def verify_failure(self, response, error_type=None): self.assertEqual(response.status_code, 200) courses = response.data self.assertEqual(len(courses), 0) @patch.dict(settings.FEATURES, {'ENABLE_MKTG_SITE': True}) def test_sort_...
# Copyright 2018 Politecnico di Torino # # 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...
"/vnsf/r4/running" LOG.info("VNSFO API call: " + url) try: response = requests.get(url, verify=False, timeout=timeout) LOG.info("VNSFO API response: " + response.text) vnsfs = response.json()["vnsf"] # search for first running instance which matches the query
for vnsf in vnsfs: target_vnf = vnsf['vnfd_id'][:-5].lower() if vnfd_id[:-5].lower() in target_vnf and attack_name.lower() in target_vnf: LOG.info("Found instance=" + vnsf['vnfr_id'] + " for attack=" + attack_name) return vnsf['vnfr...
import pandas as pd
from sklearn import linear_model import matplotlib.pyplot as plt df = pd.read_fwf('brain_body.txt') x_values = df[['Brain']] y_values = df[['Body']] #train model on data body_reg = linear_model.LinearRegression() body_reg.fit(x_values, y_values) # visualise results plt.scatter(x_values, y_values) plt.plot(x_value...
g.predict(x_values)) plt.show()
import sys import time import traceback import javascript from browser import document as doc, window, alert has_ace = True try: editor = window.ace.edit("editor") session = editor.getSession() session.setMode("ace/mode/python") editor.setOptions({ 'enableLiveAutocompletion': True, 'enableS...
pen(_name).read()) # run a script, in global namespace if in_globals is True def run(*args): global output doc["console"].value = '' src = editor.getValue() if storage is not None: storage["py_src"] = src t0 = time.perf_counter() try: #ns = {'__name__':'__main__'} ns = {...
ate = 0 output = doc["console"].value print('<completed in %6.2f ms>' % ((time.perf_counter() - t0) * 1000.0)) return state if has_ace: reset_src() else: reset_src_area() def clear_console(ev): doc["console"].value = "" doc['run'].bind('click',run) doc['show_console'].bind('click',show_c...
from crits.vocabulary.vocab import vocab class RelationshipTypes(vocab): """ Vocabulary for Relationship Types. """ COMPRESSED_FROM = "Compressed From" COMPRESSED_INTO = "Compressed Into" CONNECTED_FROM = "Connected From" CONNECTED_TO = "Connected To" CONTAINS = "Contains" CONTA...
return cls.DECRYPTED_BY elif relationship == cls.DECRYPTED_BY: return cls.DECRYPTED elif relationship == cls.DOWNLOADED: return cls.DOWNLOADED_BY elif relationship == cls.DOWNLOADED_BY: return cls.DOWNLOADED elif relationship == cls.DOWNLOAD...
return cls.DOWNLOADED_FROM elif relationship == cls.DROPPED: return cls.DROPPED_BY elif relationship == cls.DROPPED_BY: return cls.DROPPED elif relationship == cls.INSTALLED: return cls.INSTALLED_BY elif relationship == cls.INSTALLED_BY: re...
from .Base_Action import * class ProfileAction(Base_Action): def __init__(self, action_xml, root_action=None): super(self.__class__, self)
.__init__(action_xml, root_action) self.shouldUseL
aunchSchemeArgsEnv = self.contents.get('shouldUseLaunchSchemeArgsEnv'); self.savedToolIdentifier = self.contents.get('savedToolIdentifier'); self.useCustomWorkingDirectory = self.contents.get('useCustomWorkingDirectory'); self.buildConfiguration = self.contents.get('buildConfiguration'); ...
# Copyright 2015 ETH Zurich # # 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, sof...
umber of seconds per sibra tick SIBRA_TICK = 4 #: How far in the future a steady path can reserve at a time. SIBRA_MAX_STEADY_TICKS = 45 #: How far in the future an ephemeral path c
an reserve at a time. SIBRA_MAX_EPHEMERAL_TICKS = 4 #: Length of steady path ID in bytes SIBRA_STEADY_ID_LEN = 8 #: Length of ephemeral path ID in bytes SIBRA_EPHEMERAL_ID_LEN = 16 #: SIBRA Bandwidth multiplier SIBRA_BW_FACTOR = 16 * 1024 #: SIBRA max reservation index SIBRA_MAX_IDX = 16 PATH_FLAG_SIBRA = "SIBRA" MAX...
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the...
el
se: return super(Env, self).__getitem__(key) def _eval_expr(cr, ident, workitem, action): ret=False assert action, 'You used a NULL action in a workflow, use dummy node instead.' for line in action.split('\n'): line = line.strip() uid=ident[0] model=ident[1] ids=...
#!/usr/bin/env python # # Copyright (c) 2016, The OpenThread Authors. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright # ...
s[LEADER].add_prefix(
'2001:2:0:1::/64', 'paros') self.nodes[LEADER].add_prefix('2001:2:0:2::/64', 'paro') self.nodes[LEADER].register_netdata() self.nodes[ROUTER].start() time.sleep(5) self.assertEqual(self.nodes[ROUTER].get_state(), 'router') self.nodes[ED1].start() time.sleep(5) ...
""" This demo creates multiple processes of Producers to spam a socketcan bus. """ i
mport time import logging import concurrent.futures import can can.rc['interface'] = 'socketcan_native' from can.interfaces.interface import Bus can_interface = 'vca
n0' def producer(id): """:param id: Spam the bus with messages including the data id.""" bus = Bus(can_interface) for i in range(16): msg = can.Message(arbitration_id=0x0cf02200, data=[id, i, 0, 1, 3, 1, 4, 1]) bus.send(msg) # TODO Issue #3: Need to keep running to ensure the writing ...
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2017 Didotech SRL import logging from openerp.osv import fields, orm import tools from openerp import addons _logger = logging.getLogger(__name__) ...
mage_resize_image_b
ig(open(image_path, 'rb').read().encode('base64')) _columns = { 'image': fields.binary("Image", help="This field holds the image used as avatar for this contact, limited to 1024x1024px"), 'image_medium': fields.function(_get_image, fnct_inv=_set_image, string="Medium-sized i...
""".""" def get_systeminfo(resource, config, interactive=False):
""".""" ret
urn {'ohai': 'there!'}
from abc import ABCMeta, abstractmethod class Parent(
object): __metaclass__ = ABCMeta
@abstractmethod def my_method2(self): pass @abstractmethod def my_method(self, foo): pass
import os, sys from functools import partial if 'DJANGO_SETTINGS_MODULE' not in os.environ: sys.path.append('.') os.environ['DJANGO_SETTINGS_MODULE'] = 'settings' from django.conf import settings from django.test.client import Client from django.test.utils import setup_test_environment, teardown_test_environmen...
.''' return request.cached_setup(partial(user_creator, "user", "user@example.com"), lambda user: user.delete(), "session") def pytest_funcarg__admin(request): '''Creat...
"admin@example.com", is_superuser=True, is_staff=True), lambda user: user.delete(), "session")
default=False) parser.add_argument('--high_replication', action=boolean_action.BooleanAction, const=True, default=False) parser.add_argument('--require_indexes', action=boolean_action.BooleanAction, ...
SMTP server. This v
alue may be None if smtp_host or smtp_user is also None. smtp_port: The SMTP port number that should be used when sending e-mails. If this value is None then smtp_host must also be None. smtp_user: The username to use when authenticating with the SMTP server. This value may be ...
import os import signal import socket from pathlib import Path from tornado.ioloop import IOLoop from tornado.locks import Lock from tornado.web import Application from pcs import settings from pcs.daemon import log, ruby_pcsd, session, ssl, systemd from pcs.daemon.app import sinatra_ui, sinatra_remote, ui from pcs.d...
sable_gui=False, debug=False, ): def make_app(https_server_manage: HttpsServerManage): """ https_server_manage -- allows to controll the server (specifically reload its SSL certific
ates). A relevant handler should get this object via the method `initialize`. """ routes = sinatra_remote.get_routes( ruby_pcsd_wrapper, sync_config_lock, https_server_manage, ) if not disable_gui: routes.extend( ...
#!/usr/bin/env python ''' ******************************************************************************* Description: This tool can help you determine the character encoding of a text file by converting one line from the file to every(?) possible character encoding. It wri...
********************************************
****************** ''' import io import os import sys from encodings.aliases import aliases encs = { "ascii", "big5", "big5hkscs", "cp037", "cp424", "cp437", "cp500", "cp720", "cp737", "cp775", "cp850", "cp852", "cp855", "cp856", "cp857", "cp858", "cp860", "cp861", "cp862", "cp863", "cp864", "cp865", ...
# #LiloConf.py # import sys, re, os import logging import GrubConf class LiloImage(object): def __init__(self, lines, path): self.reset(lines, path) def __repr__(self): return ("title: %s\n" " root: %s\n" " kernel: %s\n" " args: %s\n" ...
lse: self.lines.pop(replace) self.lines.insert(replace, line) def set_kernel(self, val): self._kernel = (None, self.path + "/" + val) def get_kernel(self):
return self._kernel kernel = property(get_kernel, set_kernel) def set_initrd(self, val): self._initrd = (None, self.path + "/" + val) def get_initrd(self): return self._initrd initrd = property(get_initrd, set_initrd) def set_args(self, val): self._args = val def ge...
# Copyright 2019 DeepMind Technologies 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 agr...
r to return how much best response exploits the given
mixed strategy (default is False) Returns: br: int, index of strategy (ties split randomly) exp: u(br) - u(mixed_strategy) """ logging.warn("Assumes symmetric game! Returns br for player 0.") gradient = misc.pt_reduce(self.pt[0], [mixed_strategy] * self.num_play...
1122334455667788, for which plenty of generated rainbow tables exist already. """ # parse NTLM/LM hashes # scapy has very limited SMB packet support, so we have to do this manually def parse_credentials(self, data): # offsets based on security blob st...
"\x00\x4c\x00\x41\x00\x4e\x00\x20\x00\x4d\x00" payload += "\x61\x00\x6e\x00\x61\x00\x67\x00\x65\x00\x72" payload += "\x00\x00" return (payload, 0
) elif message_type == '0x3': # should be an AUTH packet # parse credentials self.parse_credentials(data) # send a STATUS_LOGIN_FAILURE # netbios payload = "\x00\x00\x00\x23" # smb header ...
"reducesPending": 1, # "reducesRunning": 0, # "uberized": false, # "diagnostics": "", # "newReduceAttempts": 1, # "runningReduceAttempts": 0, # "failedReduceAttempts": 0, # "killedReduceAttempts": 0, ...
ach MapReduce job. Return a dictionary for each MapReduce job { job_id: { 'job_name': job_name, 'app_name': app_name, 'user_
name': user_name, 'tracking_url': tracking_url } ''' try: running_jobs = {} for app_id, (app_name, tracking_url) in running_apps.iteritems(): ts = time.time() metrics_json = self.request_url("%s%s" % (tracking_url,REST_API['MAPR...