repo_name
stringlengths
5
100
path
stringlengths
4
231
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
6
947k
score
float64
0
0.34
prefix
stringlengths
0
8.16k
middle
stringlengths
3
512
suffix
stringlengths
0
8.17k
jacksarick/My-Code
Python/python challenges/euler/012_divisable_tri_nums.py
Python
mit
219
0.03653
## Close ### What is the value of the first triangle number to have over five hundred divisors? pri
nt max
([len(m) for m in map(lambda k: [n for n in range(1,(k+1)) if k%n == 0], [sum(range(n)) for n in range(1,1000)])])
akash1808/nova_test_latest
nova/tests/unit/compute/test_compute_cells.py
Python
apache-2.0
18,463
0.0013
# Copyright (c) 2012 Rackspace Hosting # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless req...
est is incompatible with cells.") def test_delete_instance_no_cell(self): cells_rpcapi = self.compute_api.cells_rpcapi self.mox.StubOutWithMock(cells_rpcapi, 'instance_delete_eve
rywhere') inst = self._create_fake_instance_obj() cells_rpcapi.instance_delete_everywhere(self.context, inst, 'hard') self.mox.ReplayAll() self.stubs.Set(self.compute_api.network_api, 'deallocate_for_instance', lambda *a, **kw: None) self.co...
PetePriority/home-assistant
homeassistant/components/knx/climate.py
Python
apache-2.0
11,010
0
""" Support for KNX/IP climate devices. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/climate.knx/ """ import voluptuous as vol import homeassistant.helpers.config_validation as cv from homeassistant.components.climate import ( PLATFORM_SCHEMA, SUP...
NT_SHIFT_STATE_ADDRESS): cv.string, vol.Optional(CONF_SETPOINT_SHIFT_STEP, default=DEFAULT_SETPOINT
_SHIFT_STEP): vol.All( float, vol.Range(min=0, max=2)), vol.Optional(CONF_SETPOINT_SHIFT_MAX, default=DEFAULT_SETPOINT_SHIFT_MAX): vol.All(int, vol.Range(min=0, max=32)), vol.Optional(CONF_SETPOINT_SHIFT_MIN, default=DEFAULT_SETPOINT_SHIFT_MIN): vol.All(int, vol.Range(min=-3...
tboyce021/home-assistant
homeassistant/components/zwave/node_entity.py
Python
apache-2.0
12,522
0.000878
"""Entity class that represents Z-Wave node.""" # pylint: disable=import-outside-toplevel from itertools import count from homeassistant.const import ATTR_BATTERY_LEVEL, ATTR_ENTITY_ID, ATTR_WAKEUP from homeassistant.core import callback from homeassistant.helpers.device_registry import async_get_registry as get_dev_r...
node.product_name self._manufacturer_name = self.node.manufacturer_name self._name = node_name(self.node) self._attributes = attributes if not self._unique_id: self._unique_id = self._compute_unique_id() if self._uniqu
e_id: # Node info parsed. Remove and re-add self.try_remove_and_add() self.maybe_schedule_update() async def node_renamed(self, update_ids=False): """Rename the node and update any IDs.""" identifier, self._name = node_device_id_and_name(self.node) #...
MarcosCommunity/odoo
addons/purchase/purchase.py
Python
agpl-3.0
93,906
0.0064
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
] = all(line.invoiced for line in purchase.order_line if
line.state != 'cancel') return res def _get_journal(self, cr, uid, context=None): if context is None: context = {} user = self.pool.get('res.users').browse(cr, uid, uid, context=context) company_id = context.get('company_id', user.company_id.id) journal_obj =...
anhlt/twitter_cli
twitter_cli/main.py
Python
mit
3,569
0.00028
from prompt_toolkit import Application from prompt_toolkit.interface import CommandLineInterface from prompt_toolkit.shortcuts import create_eventloop from prompt_toolkit.key_binding.manager import KeyBindingManager from prompt_toolkit.keys import Keys from prompt_toolkit.buffer import Buffer, AcceptAction from prompt_...
t_toolkit.layout.containers import VSplit, Window, HSplit from prompt_toolkit.layout.controls import BufferControl, FillControl, TokenListControl from prompt_toolkit.layout.dimension import LayoutDimension as D from prompt_to
olkit.auto_suggest import AutoSuggestFromHistory from pygments.token import Token def get_titlebar_tokens(cli): return [ (Token.Title, ' Hello world '), (Token.Title, ' (Press [Ctrl-Q] to quit.)'), ] def handle_action(cli, buffer): ' When enter is pressed in the Vi command line. ' te...
fronzbot/blinkpy
blinkpy/sync_module.py
Python
mit
12,603
0.000714
"""Defines a sync module for Blink.""" import logging from requests.structures import CaseInsensitiveDict from blinkpy import api from blinkpy.camera import BlinkCamera, BlinkCameraMini, BlinkDoorbell from blinkpy.helpers.util import time_to_seconds from blinkpy.helpers.constants import ONLINE _LOGGER = logging.getL...
.""" try: return ONLINE[self.status] except KeyError:
_LOGGER.error("Unknown sync module status %s", self.status) self.available = False return False @property def arm(self): """Return status of sync module: armed/disarmed.""" try: return self.network_info["network"]["armed"] except (KeyError, Type...
Elivis/opsa-master
opsa/mysql.py
Python
gpl-2.0
1,197
0.020084
#!/usr/bin/env python # -*- coding: utf-8 -*- # @author: Elivis.Zhang <[email protected]> # QQ Group:99798703 # Created on Aug 8, 2015 # -*- coding: utf-8 -*- import MySQLdb import settings class db_operate: def mysql_command(self,conn,sql_cmd): try: ret = [] conn=MySQLdb.con...
i) except MySQLdb.
Error,e: ret.append(e) return ret
piotr1212/gofed
ggi.py
Python
gpl-2.0
8,925
0.032381
# #################################################################### # gofed - set of tools to automize packaging of golang devel codes # Copyright (C) 2014 Jan Chaloupka, [email protected] # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public Licen...
Print() if not options.scanalldirs: noGodeps = Config().getSkippedDirectories() else: noGodeps = [] if options.skipdirs: for dir in options.skipdirs.split(','): dir = dir.strip() if dir == "": continue noGodeps.append(dir) gse_obj = GoSymbolsExtractor(path, imports_only=True, skip_errors=optio...
()) exit(1) package_imports_occurence = gse_obj.getPackageImportsOccurences() ip_used = gse_obj.getImportedPackages() ipd = ImportPathsDecomposer(ip_used) if not ipd.decompose(): fmt_obj.printError(ipd.getError()) exit(1) warn = ipd.getWarning() if warn != "": fmt_obj.printWarning("Warning: %s" % warn)...
mdurrant-b3/acos-client
acos_client/tests/unit/v30/test_slb_virtual_port.py
Python
apache-2.0
22,343
0.001074
# Copyright 2014, Doug Wiegley, A10 Networks. # # 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 appli...
ol1' } } resp = self.client.slb.virtual_server.vport.create( VSERVER_NAME, 'test1_VPORT', protocol=self.client.slb.virtual_server.vport.HTTP, port='80', service_group_name='pool1' ) self.assertEqual(resp, json_response) self.assert
Equal(len(responses.calls), 2) self.assertEqual(responses.calls[1].request.method, responses.POST) self.assertEqual(responses.calls[1].request.url, CREATE_URL) self.assertEqual(json.loads(responses.calls[1].request.body), params) @responses.activate def test_virtual_port_create_with_par...
stuckyb/sqlite_taxonomy
utilities/taxolib/taxonomy.py
Python
gpl-3.0
15,593
0.005066
""" Provides classes that represent complete taxonomies, built using components from the taxacomponents module. """ from taxacomponents import Citation, RankTable, Taxon from taxonvisitor import TaxonVisitor from taxonvisitors_concrete import PrintTaxonVisitor, CSVTaxonVisitor from nameresolve import CoLNamesResolver...
FROM taxon_concepts tc, ranks r WHERE tc.tc_id=? AND tc.rank_id=r.rank_id""" pgcur.execute(query, (roottc_id,)) res = pgcur.fetchone() rankid = res[0] root_taxonomy_id = res[1] # Initialize the rank lookup table. rankt = RankTable() rankt.loadFr...
gcur) # Load the taxa tree. self.roottaxon = Taxon(self.taxonomy_id, rankid, rankt, roottaxo_id = root_taxonomy_id, isroot=True) self.roottaxon.loadFromDB(pgcur, roottc_id, taxanum, maxdepth) def persist(self): """ Persist the Taxonomy to the database. This method should b...
gwpy/gwpy.github.io
docs/latest/examples/timeseries/inject-5.py
Python
gpl-3.0
136
0.007353
from gwpy.plot import Plot plo
t = Plot(noise, signal, data, separate=True, sharex=True, s
harey=True) plot.gca().set_epoch(0) plot.show()
Nettacker/Nettacker
lib/scan/wp_timthumbs/engine.py
Python
gpl-3.0
10,981
0.003461
#!/usr/bin/env python # -*- coding: utf-8 -*- # Author Pradeep Jairamani; github.com/pradeepjairamani import socket import socks import time import json import threading import string import requests import random import os from core.alert import * from core.targets import target_type from core.targets import target_t...
et) != 'HTTP' or target_type(target) != 'SINGLE_IPv6': # rand useragent user_agent_list = useragents.useragents() http_methods = ["GET", "HEAD"] user_agent = {'User-agent'
: random.choice(user_agent_list)} # requirements check new_extra_requirements = extra_requirements_dict() if methods_args is not None: for extra_requirement in extra_requirements_dict(): if extra_requirement in methods_args: new_extra_requirements...
patrabu/carbu
import_csv.py
Python
gpl-3.0
1,167
0.007712
#!/usr/bin/env python # -*- coding: utf-8 -*- """ import_csv.py ~~~~~~~~~~~~~~~~~~~~ Import csv file into database. The CSV file should be in this format: Datetime;price;quantity;mileage 2013/10/03 07:00:00;34.01;25.90;149340 :copyright: (c) 2014 by Patrick Rabu. :license: ...
t datetime import locale import csv import sqlite3
csvfile = sys.argv[1] db = sqlite3.connect(sys.argv[2]) car_id = sys.argv[3] cursor = db.cursor() with open(csvfile, 'rb') as f: locale.setlocale(locale.LC_ALL, 'fra_fra') reader = csv.reader(f, delimiter=';', quoting=csv.QUOTE_NONE) reader.next() # Skip the first row for row in reader: d...
rlowrance/re-avm
AVM.py
Python
bsd-3-clause
3,934
0.001525
'Automated Valuation Model' import pdb import numpy as np import pandas as pd from pprint import pprint import
sklearn import sklearn.ensemble import sklearn.linear_model import sklearn.preprocessing from columns_contain import columns_contain import AVM_elastic_net import AVM_gradient_boosting_regressor import AVM_rando
m_forest_regressor from Features import Features cc = columns_contain def avm_scoring(estimator, df): 'return error from using fitted estimator with test data in the dataframe' # TODO: make a static method of class AVM assert isinstance(estimator, AVM) X, y = estimator.extract_and_transform(df) as...
dirkjanm/ldapdomaindump
ldapdomaindump/__main__.py
Python
mit
66
0
#!/usr/bin/env python import ldapdomaindu
mp ldapdomai
ndump.main()
mauerflitza/Probieren2
Webpage/cgi-bin/upload.py
Python
mit
1,801
0.048333
#!/usr/bin/python3 import os import os.path import cgi, cgitb import re import pickle #own packages import dbcPattern def dbc_main(): # NEW except for the call to processInput form = cgi.FieldStorage() # standard cgi script lines to here! # use format of next two lines with YOUR names and default data...
ead() file2.close() file=open("htmltext.html",'w') file.write(html_string) file.close() return html_string #Muss später ins Hauptprogramm kopiert werden try: # NEW cgitb.enable() print("Content-Type: text/html;charset:UTF-8") # say generating html
print("\n\n") msg_list=dbc_main() filename=os.path.join('/home/pi/datalogger/loggerconfigs/','testdump.txt') with open(filename, 'wb') as file: pickle.dump(msg_list, file) except: cgi.print_exception() # catch and print errors
dsparrow27/zoocore
zoo/libs/pyqt/uiconstants.py
Python
gpl-3.0
1,709
0.005266
# Colors DARKBGCOLOR = tuple([93, 93, 93]) MEDBGCOLOR = tuple([73, 73, 73]) MAYABGCOLOR = tuple([68, 68, 68]) # D
PI DEFAULT_DPI = 96 # Pixel Size is not handled by dpi, use utils.dpiScale() MARGINS = (2, 2, 2, 2) # default margins left, top, right, bottom SPACING
= 2 SSML = 4 # the regular spacing of each widget, spacing is between each sub widget SREG = 6 # the regular spacing of each widget, spacing is between each sub widget SLRG = 10 # larger spacing of each widget, spacing is between each sub widget SVLRG = 15 # very large spacing of each widget, spacing is between ea...
ActiveState/code
recipes/Python/578171_Just_Another_Password_Generator/recipe-578171.py
Python
mit
2,824
0.004958
############################### # old_password_generator.py # ############################### import string, random, sys SELECT = string.ascii_letters + string.punctuation + string.digits SAMPLE = random.SystemRandom().sample def main(): while True: size = get_size() password = generate_pw(size...
]) for char
acter in password[1:]: trial = select(character) if trial is group: return False group = trial return True def select(character): for group in (string.ascii_uppercase, string.ascii_lowercase, string.punctuation, string.di...
wutron/compbio
rasmus/testing.py
Python
mit
3,789
0.000792
import optparse import os import shutil import sys import unittest from itertools import izip from . import util from . import stats #============================================================================= # common utility functions for testing def clean_dir(path): if os.path.exists(path): shutil...
>= pval, p _do_pause = True def pause(text="press enter to continue: "
): """Pause until the user presses enter""" if _do_pause: sys.stderr.write(text) raw_input() def set_pausing(enabled=True): global _do_pause _do_pause = enabled #============================================================================= # common unittest functions def list_tests...
ecleya/project_cron
main.py
Python
mit
2,772
0.002165
import json import os from AppKit import NSApplication, NSStatusBar, NSMenu, NSMenuItem, NSVariableStatusItemLength, NSImage from PyObjCTools import AppHelper from project_cron.models import Schedule from threading import Timer from project_cron.utils import logutil class App(NSApplication): def finishLaunching(...
o in schedules: self._schedules.append(Schedule(raw_info)) def _init
ialize_menu(self): self.menubarMenu = NSMenu.alloc().init() for schedule in self._schedules: menu_item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(schedule.name, 'execute:', '') self._menu_items.append(menu_item) self.menubarMenu.addItem_(menu_item) ...
MihawkHu/CS433_ParallerProgramming_Project
Project4/wordcount/python_wordcount/reducer.py
Python
mit
574
0.057491
import sys current_word = None current_count = 0 word = None for line in sys.stdin: line = line.strip() word,count = line.split('\t',1)
try: count = int(count) except ValueError: continue if current_word == word: current_count +=count else: if current_word: print '%s\t%s' %(current_word,current_count) current_count =count current_word =word ...
t '%s\t%s' % (current_word,current_count)
yloiseau/Watson
watson/frames.py
Python
mit
4,355
0
import uuid import arrow from collections import namedtuple HEADERS = ('start', 'stop', 'project', 'id', 'tags', 'updated_at') class Frame(namedtuple('Frame', HEADERS)): def __new__(cls, start, stop, project, id, tags=None, updated_at=None,): try: if not isinstance(start, arrow.Arrow): ...
__(self, frames=None): if not frames: frames = [] rows = [Frame(*frame) for frame in frames] self._rows = rows self.changed = False def __len__(self): return len(self._rows) def __getitem__(self, key): if key in HEADERS: return tuple(se...
(key)) elif isinstance(key, int): return self._rows[key] else: return self._rows[self._get_index_by_id(key)] def __setitem__(self, key, value): self.changed = True if isinstance(value, Frame): frame = value else: frame = self....
coldeasy/python-driver
tests/integration/cqlengine/test_batch_query.py
Python
apache-2.0
8,003
0.002249
# Copyright 2013-2017 DataStax, 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 agreed to in writi...
def my_callback(*args, **kwargs):
call_history.append(args) # adding on init: batch = BatchQuery() batch.add_callback(my_callback) batch.add_callback(my_callback, 'more', 'args') batch.execute() self.assertEqual(len(call_history), 2) self.assertEqual([(), ('more', 'args')], call_history)...
andersonsilvade/python_C
Python32/ED/Distâncias em uma Rede.py
Python
mit
444
0.027027
A = [[0, 1, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 1, 0], [0, 0, 1, 0, 1, 0], [1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0]] def Distancias(n, origem): d = [-1] * n d[origem] = 0 f = [] f.append(origem) while len(f) >
0: x = f[0] del f[0] for y in range(n): if A[x][y] == 1 and d[y] == -1: d[y] = d[x] + 1 print (y) f.append(y) return d print (Distancias(6, 3)
)
mlperf/training_results_v0.5
v0.5.0/google/research_v3.32/gnmt-tpuv3-32/code/gnmt/model/t2t/tensor2tensor/layers/common_layers.py
Python
apache-2.0
132,971
0.007994
# coding=utf-8 # Copyright 2018 The Tensor2Tensor Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable...
+ 0.5 return tf.minimum(1.0, tf.nn.relu(x_shifted)), saturation_cost def hard_tanh(x, saturation_limit=0.9): saturation_cost = tf.reduce_mean(tf.nn.relu(tf.abs(x) - saturation_limit)) return tf.minimum(1.0, tf.maximum(x, -1.0)), saturation_cost def inverse_exp_decay(max_step, min_value=0.01, step=None): ""...
float(max_step)) if step is None: step = tf.train.get_global_step() if step is None: return 1.0 step = tf.to_float(step) return inv_base**tf.maximum(float(max_step) - step, 0.0) def inverse_lin_decay(max_step, min_value=0.01, step=None): """Inverse-decay linearly from 0.01 to 1.0 reached at max_step...
chrxr/wagtail
wagtail/wagtailcore/migrations/0023_alter_page_revision_on_delete_behaviour.py
Python
bsd-3-clause
622
0.001608
# -*- coding: utf-8 -*- from __future__ import unicode_literals import django.db.models.deletion from django.conf import settings from django.db import migrations, models class Migration(
migrations.Migration): dependencies = [ ('wagtailcore', '0022_add_site_name'), ]
operations = [ migrations.AlterField( model_name='pagerevision', name='user', field=models.ForeignKey( on_delete=django.db.models.deletion.SET_NULL, verbose_name='user', blank=True, to=settings.AUTH_USER_MODEL, null=True ), ...
aalpern/tessera
tessera-server/tessera/views_api.py
Python
apache-2.0
10,412
0.004898
# -*- mode:python -*- import flask import json import logging from datetime import datetime import inflection from functools import wraps from flask import request, url_for from werkzeug.exceptions import HTTPException from .client.api.model import * from . import database from . import helpers from .application imp...
(dashboards): """Return a Flask response object for a list of dashboards in API format. dashboards must be a list of dashboard model objects, which will be converted to their JSON representation. """ if not isinstance(dashboards, list): dashboards = [dashboards] include_definition = helpers.get...
] def _set_tag_hrefs(tag): """Add ReSTful href attributes to a tag's dictionary representation. """ id = tag['id'] tag['href'] = url_for('api.tag_get', id=id) return tag def _tags_response(tags): """Return a Flask response object for a list of tags in API format. tags must be a list of tag mod...
bugsduggan/locust
docs/conf.py
Python
mit
2,962
0.005739
# -*- coding: utf-8 -*- # # This file is execfile()d with the current directory set to its containing dir. # # The contents of this file are pickled, so don't put values in the namespace # that aren't pickleable (module imports are okay, they're removed automatically). # # All configuration values have a default value;...
odule_names = False # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. show_authors = False # Sphinx will recurse into subversion configuration folders and try to read
# any document file within. These should be ignored. # Note: exclude_dirnames is new in Sphinx 0.5 exclude_dirnames = [] # Options for HTML output # ----------------------- html_show_sourcelink = False html_file_suffix = ".html" # on_rtd is whether we are on readthedocs.org, this line of code grabbed from docs.r...
physicalattraction/PATinderBot
src/common.py
Python
gpl-3.0
821
0
import os from typing import Dict, List, Union OptionalJSON = Union[List, Dict, float, int, str, bool, None] def ensure_dir_exists(directory): if not os.path.exists(directory): os.mkdir(directory) def get_dir(directory: str) -> str: """ Return a string which contains the complete path to the in...
:p
aram directory: string of the directory to search for :return: string with the complete path to the searched for directory """ current_dir = os.path.dirname(__file__) project_dir = os.path.join(current_dir, '..') result = os.path.join(project_dir, directory) ensure_dir_exists(result) return...
taijiji/sample_jsnapy
run_test_bgp_advertised_route.py
Python
mit
2,089
0.011967
#! /usr/bin/env python # -*- coding: utf-8 -*- import os # arranged print from pprint import pprint, pformat # Jinja2 Template Engine from jinja2 import Template, Environment # JSNAPy from jnpr.junos import Device from jnpr.junos.utils.config import Config from jnpr.jsnapy import SnapAdmin
template_dir_name = './test_templates/' template_base_name = 'test_bgp_advertised_route.jinja2' param_advertised_route = {
"neighbor_address_ipv4" : "192.168.35.2", "advertised_route_address_ipv4" : "10.10.10.0", "advertised_route_subnet_ipv4" : "24", } print 'Load test_template : ' template_filename = template_dir_name + template_base_name with open(template_filename, 'r') as conf: template_txt = conf.read() ...
Smerity/glove-guante
cosine_similarity.py
Python
mit
1,457
0.008922
import sys import numpy as np if __name__ == '__main__': print 'Loading word vectors...' wordvecs = None wordlist = [] for i, line in enumerate(sys.
stdin): word, vec = line.strip().split(' ', 1) vec = map(float, vec.split()) if wordvecs is None: wordvecs = np.ones((400000, len(vec)), dtype=np.float) wordvecs[i] = vec wordlist.append(word) words = dict((k, wordvecs[v]) for v, k in enumerate(wordlist)) tests = [('he', words['he']), ('s...
])] tests = [ ('athens-greece+berlin', words['athens'] - words['greece'] + words['berlin']), ('sydney-australia+berlin', words['sydney'] - words['australia'] + words['berlin']), ('australia-sydney+germany', words['australia'] - words['sydney'] + words['berlin']), ('king-male+female', words['ki...
dichen001/Go4Jobs
JackChen/string/385. Mini Parser.py
Python
gpl-3.0
2,721
0.00294
""" Given a nested list of integers represented as a string, implement a parser to deserialize it. Each element is either an integer, or a list -- whose elements may also be integers or other lists. Note: You may assume that the string is well-formed: String is non-empty. String does not contain white spaces. String...
" # # def add(self, elem): # """ # Set this NestedInteger to hold a nested list and adds a nested integer elem to it. # :rtype void # """ # # def setInteger(self, value): # """ # Set this NestedInteger to hold a si
ngle integer equal to value. # :rtype void # """ # # def getInteger(self): # """ # @return the single integer that this NestedInteger holds, if it holds a single integer # Return None if this NestedInteger holds a nested list # :rtype int # """ # # def getList(self...
Matrixeigs/Optimization
Two_stage_stochastic_optimization/optimal_power_flows/opf_branch_power.py
Python
mit
4,744
0.005691
""" Optimal power flow based on branch power flow modelling Additional case33 is added to the test cases Note: The proposed method has been verified @author: Tianyang Zhao @email: [email protected] """ from Two_stage_stochastic_optimization.power_flow_modelling import case33 from pypower import runopf from gurobip...
rix Cf = sparse((ones(nl), (i, f)), (nl, nb)) Ct = sparse((ones(nl), (i, t)), (nl, nb)) Cg = sparse((ones(ng), (gen[:, GEN_BUS], rang
e(ng))), (nb, ng)) Branch_R = branch[:, BR_R] Branch_X = branch[:, BR_X] Cf = Cf.T Ct = Ct.T # Obtain the boundary information Slmax = branch[:, RATE_A] / baseMVA Pij_l = -Slmax Qij_l = -Slmax Iij_l = zeros(nl) Vm_l = turn_to_power(bus[:, VMIN], 2) Pg_l = gen[:, PMIN] / base...
winguru/graphite-api
tests/test_render.py
Python
apache-2.0
24,960
0.00004
# coding: utf-8 import json import os import time from graphite_api._vendor import whisper from . import TestCase, WHISPER_DIR try: from flask.ext.cache import Cache except ImportError: Cache = None class RenderTest(TestCase): db = os.path.join(WHISPER_DIR, 'test.wsp') url = '/render' def crea...
data = js
on.loads(response.data.decode('utf-8')) self.assertEqual(len(data), 2) def test_sumseries(self): response = self.app.get(self.url, query_string={ 'target': ['sumSeries(sin("foo"), sin("bar", 2))',
anderscui/spellchecker
simple_checker/checker_tests_google_dict.py
Python
mit
17,844
0.00863
from common.persistence import from_pickle NWORDS = from_pickle('../data/en_dict.pkl') print(len(NWORDS)) print(NWORDS['word']) print(NWORDS['spell']) alphabet = 'abcdefghijklmnopqrstuvwxyz' def edits1(word): s = [(word[:i], word[i:]) for i in range(len(word) + 1)] deletes = [a + b[1:] for a, b in s if b] ...
sors sissors', 'separate': 'seperate', 'singular': 'singulaur', 'someone': 'somone', 'sources': 'sorces', 'southern': 'southen', 'special': 'speaical specail specal speical', 'splendid': 'spledid splended splened splended', 'standardizing': 'stanerdizing', 'stomach': ...
'transfred', 'transportability': 'transportibility', 'triangular': 'triangulaur', 'understand': 'undersand undistand', 'unexpected': 'unexpcted unexpeted unexspected', 'unfortunately': 'unfortunatly', 'unique': 'uneque', 'useful': 'usefull', 'valuable': 'valubale valuble', ...
NDykhuis/team-formation-study-software
humanagent.py
Python
gpl-2.0
25,571
0.013922
# # humanagent.py - provides server-side backend for interaction with # human players in team formation # # Copyright (C) 2015 Nathan Dykhuis # # 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 Softw...
sage(self.client) responses = [] for i in range(n_qs): (qtext, qresponse) = receive_message(self.client) responses.append( (qtext, qresponse) ) self.finalpay = receive_message(self.client) self.hideratings() self.cfg._dblog.log_exitsurvey(self.id, responses) self...
self.logp(("Agent", self.id, "exit survey submitted"), 0) def startcapture(self): """Client: start video capture""" send_message(self.client, ('startcapture', 0)) def stopcapture(self): """Client: pause video capture""" send_message(self.client, ('stopcapture', 0)) def endcapture(self): ...
flake123p/ProjectH
Python/_Basics_/A11_Reference/test.py
Python
gpl-3.0
817
0.007344
""" A list is a sequence 1.Can be any type 2.The values in a list are called elements or sometimes items 3.Declare with square brackets: [ ] 4.Can be nested. [x, y, [z1, z2]] """ myStr1 = 'aabbcc' myStr2 = 'aabbcc' print('myStr1 = ', myStr1) print('myStr2 = ', myStr2) print('myStr1 is myStr2 = ', myStr1 is myStr2,...
function gets a reference
to the list.') t1 = [1, 2] t2 = t1.append(3) t3 = t1 + [3] print('t1 = [1, 2]') print('t2 = t1.append(3)') print('t3 = t1 + [3]') print('t1 now is ', t1) print('t2 now is ', t2) print('t3 now is ', t3)
roncapat/RWOL
rwol-web-src/utilities.py
Python
gpl-3.0
3,772
0.012725
#!/usr/bin/python #coding: UTF-8 #COPIRIGHT: Patrick Roncagliolo #LICENCE: GNU GPL 3 import cgi, json argsDict = cgi.FieldStorage() EMPTY_DICT = {} def getState (init = False): dataDict = getDataDict () if dataDict is None \ and init is True: (key, uri) = generateTOTP () generateQR (k...
ataDict = newDataDict (key, uri) setDataDict (dataDict) devDict = getDevDict () if devDict is None \ and init is True: devDict = newDevDict () setDevDict (devDict) return (dataDict, devDict) def generateTOTP (): import string, rand
om from otpauth import OtpAuth as otpauth key=''.join((random.choice(string.ascii_uppercase + string.digits)) for x in range(30)) auth = otpauth(key) uri = auth.to_uri('totp', 'patrick@WakeOnLAN', 'WakeOnLAN') return (key, uri) def generateQR (key, uri): import os, qrcode from glob import...
NoctuaNivalis/qutebrowser
tests/unit/browser/test_tab.py
Python
gpl-3.0
3,502
0
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: # Copyright 2016-2017 Florian Bruhin (The Compiler) <[email protected]> # # This file is part of qutebrowser. # # qutebrowser 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 S...
seful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with qutebrowser. If not, see <http://www.gnu.org/lic
enses/>. import pytest from qutebrowser.browser import browsertab pytestmark = pytest.mark.usefixtures('redirect_webengine_data') try: from PyQt5.QtWebKitWidgets import QWebView except ImportError: QWebView = None try: from PyQt5.QtWebEngineWidgets import QWebEngineView except ImportError: QWebEngi...
kennethlove/django_bookmarks
dj_bookmarks/dj_bookmarks/wsgi.py
Python
bsd-3-clause
402
0
""" WSGI config for d
j_bookmarks project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "d...
tion()
fqez/JdeRobot
src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v20/test.py
Python
gpl-3.0
31,243
0.004161
''' MAVLink protocol implementation (auto-generated by mavgen.py) Generated from: test.xml Note: this file has been auto-generated. DO NOT EDIT ''' import struct, array, time, json, os, sys, platform from ...generator.mavcrc import x25crc import hashlib WIRE_PROTOCOL_VERSION = '2.0' DIALECT = 'test' PROTOCOL_MARK...
__eq__(self, other): if other == None: return False if self.get_type() != other.get_type(): return False # We do not compare CRC because native code doesn't provide it #if self.get_crc() != other.get_crc(): # return False if self.get_seq() !=...
r.get_srcSystem(): return False if self.get_srcComponent() != other.get_srcComponent(): return False for a in self._fieldnames: if getattr(self, a) != getattr(other, a): return False return True def to_dict(se...
bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs
jpa/eclipselink.jpa.test/resource/weblogic/wls_composite_reset.py
Python
epl-1.0
998
0.018036
############################################################################ # Generic script applicable on any Operating Environments (Unix, Windows) # ScriptName : wls_reset.py # Properties : weblogic.properties # Author : Kevin Yuan #############################################################...
============= # Remove Data Sources using wlst on-line commonds for three composite models #=========================================================================== edit() startEdit() delete('EclipseLinkDS','JDBCSystemResource') delete('EclipseLinkDS2','JDBCSystemResource') delete('EclipseLinkDS3','JDBCSystemResour...
ivate() exit()
avatartwo/avatar2
avatar2/archs/x86.py
Python
apache-2.0
6,401
0.010155
from capstone import * from .architecture import Architecture from avatar2.installer.config import GDB_X86, OPENOCD class X86(Architecture): get_gdb_executable = Architecture.resolve(GDB_X86) get_oocd_executable = Architecture.resolve(OPENOCD) qemu_name = 'i386' gdb_name = 'i386' registers =...
'ymm7': {'format': '{{{:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}}}', 'gdb_expression': '$ymm7.v8_int32', }, 'ymm8': {'format': '{{{:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}}}', 'gdb_expression': '$ymm8.v8_int32', }, 'ymm9'...
expression': '$ymm9.v8_int32', }, 'ymm10': {'format': '{{{:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}}}', 'gdb_expression': '$ymm10.v8_int32', }, 'ymm11': {'format': '{{{:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}}}', 'gdb_expression'...
Boussadia/weboob
modules/dlfp/browser.py
Python
agpl-3.0
9,155
0.005789
# -*- coding: utf-8 -*- # Copyright(C) 2010-2011 Romain Bignon # # This file is part of weboob. # # weboob 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 you...
ki_edit_page(self, name): """ Go on the wiki page named 'name'. Return True if this is a new page, or False if the page already exist. Return None if it isn't a right wiki page name. """ url, _id = self.parse_id('W.%s' % name) if url is None: ...
new = True else: new = False assert self.is_on_page(WikiEditPage) return new def set_wiki_content(self, name, content, message): new = self._go_on_wiki_edit_page(name) if new is None: return None if new: title = name.re...
akx/shoop
shoop_workbench/settings/__init__.py
Python
agpl-3.0
1,393
0.000718
# -*- coding: utf-8 -*- # This file is part of Shoop. # # Copyright (c) 2012-2016, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. import os from django.core.exceptions import ImproperlyConfigured from sho...
ngs_ns) if 'configure' not in local_settings_ns: raise ImproperlyConfigured('No configure in local_settings') local_configure = local_settings_ns['c
onfigure'] local_configure(setup) return setup globals().update(Setup.configure(configure))
dserv01/BackupMailToHTML
SavableLazyMail.py
Python
gpl-3.0
10,434
0.007188
from LazyMail import LazyMail, encode_string import email import datetime import os import cgi import re import logging from email.header import decode_header __author__ = 'doms' class SavableLazyMail(LazyMail): def __init__(self, config, mail_connection, uid, stats): self.STATS = stats self.CONF...
OCTYPE.*?>", "", strip_header, flags=re.DOTALL) strip_header = re.sub(r"(?i)POSITION: absolute;",
"", strip_header, flags=re.DOTALL) strip_header = re.sub(r"(?i)TOP: .*?;", "", strip_header, flags=re.DOTALL) html_file.write(strip_header) #HTML-Footer #html_file.write("</div> <div class=\"col-md-8 col-md-offset-1 footer\"> <hr /><div style=\"white-space: pre-w...
alexandrovteam/pyImagingMSpec
pyImagingMSpec/scripts/process_mz_query.py
Python
apache-2.0
1,468
0.017711
from __future__ import print_function import numpy as np import sys import bisect import datetime import gzip def my_print(s): print("[" + str(datetime.datetime.now()) + "] " + s, file=sys.stderr) if len(sys.argv) < 3: print("Usage: process_mz_query.py dump_file[.gz] query_file") exit(0) my_print("Readi...
f = gzip.open(sys.argv[1], 'rb') else: f = open(sys.argv[1]) spectra = [] arr = [] for line in f: arr = line.strip().split("|") if len(arr) < 3: continue spectra.append( ( arr[0], np.array([ float(x) for x in arr[2].split(" ") ]), np.array([ float(x) for x in arr[1].split(" ") ]) ) ) f.close(...
"Reading and processing queries from %s..." % sys.argv[2]) def get_one_group_total(mz_lower, mz_upper, mzs, intensities): return np.sum(intensities[ bisect.bisect_left(mzs, mz_lower) : bisect.bisect_right(mzs, mz_upper) ]) def get_all_totals(mz, tol, spectra): mz_lower = mz - tol mz_upper = mz + tol r...
FederatedAI/FATE
python/federatedml/feature/binning/quantile_tool.py
Python
apache-2.0
3,447
0.001451
# # Copyright 2019 The FATE 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 appli...
is_sparse=is_sparse) summary_dict_table = data_instances.mapReducePartitions(f, self.copy_merge) # summary_dict = dict(summary_dict.collect()) if is_sparse: total_count = data_instances.count() summary_dict_table = summary_dict_table.mapValues(lambda x: x.set_total_coun...
ry_dict_table def get_quantile_point(self, quantile): """ Return the specific quantile point value Parameters ---------- quantile : float, 0 <= quantile <= 1 Specify which column(s) need to apply statistic. Returns ------- return a dict ...
MrNuggelz/sklearn-glvq
sklearn_lvq/gmlvq.py
Python
bsd-3-clause
12,014
0.000083
# -*- coding: utf-8 -*- # Author: Joris Jensen <[email protected]> # # License: BSD 3 clause from __future__ import division import math from math import log import numpy as np from scipy.optimize import minimize from .glvq import GlvqModel from sklearn.utils import validation class GmlvqModel(Glv...
the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. Attributes ---------- w_ : array-like, shape = [n_prototypes, n_features] ...
classes_ : array-like, shape = [n_classes] Array containing labels. dim_ : int Maximum rank or projection dimensions omega_ : array-like, shape = [dim, n_features] Relevance matrix See also -------- GlvqModel, GrlvqModel, LgmlvqModel """ def __init__(self, pr...
earthreader/libearth
libearth/sanitizer.py
Python
gpl-2.0
5,176
0.000193
""":mod:`libearth.sanitizer` --- Sanitize HTML tags ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """ import cgi try: import htmlentitydefs import HTMLParser except ImportError: from html import entities as htmlentitydefs, parser as HTMLParser import re try: import urlparse except ImportError: ...
for name, value in attrs if not name.startswith('on'
) for chunk in ( [' ', name] if value is None else [ ' ', name, '="', cgi.escape( ('' if value.startswith(disallowed_schemes) else value) if name == 'href' else (remove...
COMP90024CloudComputing/Submit_Cloud_Computing
analysis.py
Python
apache-2.0
8,425
0.01543
import couchdb import matplotlib.pyplot as plt from matplotlib.path import Path import matplotlib.patches as patches import json import matplotlib.path as mplPath import numpy as np import requests from textblob import TextBlob import Queue import time, socket, threading import re from pycorenlp import StanfordCoreNLP ...
out': '1000' }) sentiment_value = 0 tweets = "" count_tweet_sentence = 0 sentiment_desc="" for s in res["sentences"]: sentiment_value += int(s['sentimentValue'].encode('ascii')) tweets += "...
= s["index"] if plaintext != '' and count_tweet_sentence == 0: count_tweet_sentence = 1 if count_tweet_sentence != 0: # Calculate sentiment value average_sentiment_value= sentiment_value/count_tweet_sentence if...
freeitaly/Trading-System
vn.trader/dataRecorderAlone/DataRecorder -Paolo版本/uiDataRecorder1.py
Python
mit
13,588
0.003854
# encoding: UTF-8 ''' 1. 合约选择 Contracts_init.json中写入需要订阅的期货品种,如需要订阅pp和IF,写入 { "pp": "0", "IF": "0" } 2. 主力合约判断 运行程序后,点击‘合约初始化’按钮,程序会获取通联的期货数据,自动判断主力合约。并写入Contracts_init.json中。 注:通联选择的是持仓量判断主力,本程序选择的是昨日成交量判断,两者不同时会给出提示。 3. 合约订阅 4. Tick存储 ''' import json import os import pymongo import tushare as ts # ts.set_tok...
合约初始化 (判断主力合约)') startButton = QtGui.QPushButton(u'启动订阅') stopButton = QtGui.QPushButton(u'停止订阅') ctpButton.clicked.connect(self.ctpConnect) mongoButton.clicked.connect(self.dbConnect)
initButton.clicked.connect(self.contractsInit) # 初始化合约,主力合约判断 startButton.clicked.connect(self.startAll) stopButton.clicked.connect(self.stopAll) # 放置订阅合约(由于订阅的合约较多,所以选择了两个monitor展示订阅的合约) self.symbolMonitor1 = SymbolMonitor() self.symbolMonitor2 = SymbolMonitor() ...
plotly/plotly.py
packages/python/plotly/plotly/validators/bar/error_x/_arrayminussrc.py
Python
mit
429
0
import _plotly_utils.basevalidators class ArrayminussrcValidator(_plotly_uti
ls.basevalidators.SrcValidator): def __init__( self, plotly_name="arrayminussrc", parent_name="bar.error_x", **kwargs ): super(ArrayminussrcValidator, self).__init__( plotly_name=plotly_name, paren
t_name=parent_name, edit_type=kwargs.pop("edit_type", "none"), **kwargs )
lizardsystem/lizard-neerslagradar
lizard_neerslagradar/management/commands/create_geotiffs.py
Python
gpl-3.0
2,139
0.002338
from optparse import make_option from optparse import OptionParser import logging #import os #import sys import contextlib #import hashlib import datetime from django.core.management.base import BaseCommand from django.conf import settings #from django.db.models import Q import dateutil import netCDF4 from lizard_ne...
times_list = [time_from] if time_to: interval = datetime.timedelta(minutes=5) time = time_from
while time < time_to: time += interval times_list.append(time) nc = netCDF4.Dataset(settings.RADAR_NC_PATH, 'r') with contextlib.closing(nc): for time in times_list: try: path = netcdf.time_2_path(time) ...
wexi/python-for-android
pythonforandroid/recipes/libsecp256k1/__init__.py
Python
mit
1,139
0
from pythonforandroid.toolchain import shprint, current_directory from pythonforandroid.recipe import Recipe from multiprocessing import cpu_count from os.path import exists import sh class LibSecp256k1Recipe(Recipe): url = 'https://github.com/bitcoin-core/secp256k1/archive/master.zip' def build_arch(self, ...
figure'), '
--host=' + arch.toolchain_prefix, '--prefix=' + self.ctx.get_python_install_dir(), '--enable-shared', '--enable-module-recovery', '--enable-experimental', '--enable-module-ecdh', _env=env) shprint(sh.make, '-j' +...
astronomeralex/morphology-software
morphology.py
Python
mit
3,255
0.009831
import numpy as np import scipy.interpolate as interp import warnings from astropy.io import fits def concentration(radii, phot, eta_radius=0.2, eta_radius_factor=1.5, interp_kind='linear', add_zero=False): """ Calculates the concentration parameter C = 5 * log10(r_80 / r2_0) Inputs: radii -- 1d a...
< np.max(radii): maxphot = phot_interp(eta_r) else: maxphot = np.max(phot) norm_phot = phot / maxphot radius_interp = interp.interp1d(norm_phot, radii, kind=interp_kind) r20 = radius_interp(0.2) r80 = radius_interp(0.8) assert r20 < r80 < np.max
(radii) c = 5 * np.log10(r80 / r20) return c def eta(radii, phot): """ eta = I(r) / \bar{I}(<r) radii -- 1d array of aperture photometry radii phot -- 1d array of aperture photometry fluxes this is currently calculated quite naively, and probably could be done better """ ...
SOCR/HTML5_WebSite
HTML5/BrainPainter/X/lib/closure-library/closure/bin/build/depswriter.py
Python
lgpl-3.0
6,203
0.009028
#!/usr/bin/env python # # Copyright 2009 The Closure Library 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 ...
ath, provides, requires) def _GetOptionsParser(): """Get the options parser.""" parser = optparse.OptionParser(__doc__) parser.add_option('--output_file', dest='output_file', action='store', help=('If specified, write output to this path instead of '...
default=[], action='append', help='A root directory to scan for JS source files. ' 'Paths of JS files in generated deps file will be ' 'relative to this path. This flag may be specified ' 'multiple times.') p...
chrisndodge/edx-platform
common/lib/xmodule/xmodule/capa_base.py
Python
agpl-3.0
62,222
0.002588
"""Implements basics of Capa, including class CapaModule.""" import cgi import copy import datetime import hashlib import json import logging import os import traceback import struct import sys import re # We don't want to force a dependency on datadog, so make the import conditional try: import dogstats_wrapper a...
ntal navigation at the top of the page."), scope=Scope.settings, # it'd be nice to have a useful default but it screws up other things; so, # use display_name_
with_default for those default=_("Blank Advanced Problem") ) attempts = Integer( help=_("Number of attempts taken by the student on this problem"), default=0, scope=Scope.user_state) max_attempts = Integer( display_name=_("Maximum Attempts"), help=_("Defines t...
gramps-project/gramps
gramps/gui/widgets/grampletbar.py
Python
gpl-2.0
28,336
0.002188
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2000-2007 Donald N. Allingham # Copyright (C) 2011 Nick Hall # Copyright (C) 2011 Gary Burton # # 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 #...
WIKI_HELP_GRAMPLETBAR = URL_WIKISTR
ING + URL_MANUAL_PAGE + '_-_Main_Window#Gramplet_Bar_Menu' WIKI_HELP_ABOUT_GRAMPLETS = URL_WIKISTRING + URL_MANUAL_PAGE + '_-_Gramplets#What_is_a_Gramplet' NL = "\n" #------------------------------------------------------------------------- # # GrampletBar class # #-----------------------------------------------------...
hbenaouich/Learning-Python
class-1/ex10_confParse.py
Python
apache-2.0
760
0.009211
#!/usr/bin/env python import re from ciscoconfparse import CiscoConfParse def main(): ''' using the ciscoconfparse to
find the crypto maps that are not using AES ''' cisco_file = 'cisco_ipsec.txt' cisco_cfg = CiscoConfParse(cisco_file) crypto_maps = cisco_cfg.find_objects_wo_child(parentspec=r"^crypto map CRYPTO", childspec=r"AES") print "\n Crypto M
aps not using AES:" for entry in crypto_maps: for child in entry.children: if 'transform' in child.text: match = re.search(r"set transform-set (.*)$", child.text) encryption = match.group(1) print " {0} >>> {1}".format(entry.text.strip(), encryption)...
nathanhilbert/FPA_Core
openspending/forum/management/models.py
Python
agpl-3.0
8,135
0
# -*- coding: utf-8 -*- """ flaskbb.management.models ~~~~~~~~~~~~~~~~~~~~~~~~~ This module contains all management related models. :copyright: (c) 2014 by the FlaskBB Team. :license: BSD, see LICENSE for more details. """ from wtforms import (TextField, IntegerField, FloatField, BooleanField, ...
lue = value db.session.add(setting) db.session.commit() cls.invalidate_cache() @classmethod def get_settings(cls, from_group=None): """This will return all settings with the key as the key for the dict and the values are packed again in a dict which contains ...
attributes. :param from_group: Optionally - Returns only the settings from a group. """ result = None if from_group is not None: result = from_group.settings else: result = cls.query.all() settings = {} for setting in result: ...
branchard/ludacity
manage.py
Python
gpl-2.0
253
0
# -*- coding: utf-8 -*- import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ludacity.settings")
from django.core.management import execute_from_co
mmand_line execute_from_command_line(sys.argv)
ingwinlu/python-twitch
twitch/api/v3/blocks.py
Python
gpl-3.0
430
0
# -*- encoding: utf-8 -*
- # https://github.com/justintv/Twitch-API/blob/master/v3_resources/blocks.md from twitch.queries import query # Needs Authentification @query def by_name(user): raise NotImplementedError # Needs Authentification, needs PUT @query def add_block(user, target): raise NotImplementedError # Needs Authentific...
daicang/Leetcode-solutions
087-scramble-string.py
Python
mit
759
0.00527
class Solution(object): def isScramble(self, s1, s2): """ :type s1: str :type s2: str :rtype: bool """ if s1 == s2: return True
if len(s1) != len(s2): return False from collections import Counter if Counter(s1) != Counter(s2): return False for i in range(1, len(s1)): if self.isScramble(s1[:i], s2[:i]) and self.isScramble(s1[i:], s2[i:]): return True if ...
, "caebd"] ] for i in inputs: print s.isScramble(*i)
dontnod/weblate
weblate/wladmin/models.py
Python
gpl-3.0
6,438
0.000777
# -*- coding: utf-8 -*- # # Copyright © 2012 - 2019 Michal Čihař <[email protected]> # # This file is part of Weblate <https://weblate.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, eith...
'post', settings.SUPPORT_API_URL, headers=headers, data=data ) response.raise_for_status() payload = response.json() self.name = payload['name'] self.expiry = dateutil.parser.parse(paylo
ad['expiry']) self.in_limits = payload['in_limits'] BackupService.objects.get_or_create( repository=payload['backup_repository'], defaults={"enabled": False} ) @python_2_unicode_compatible class BackupService(models.Model): repository = models.CharField( max_length=500,...
slowrunner/RWPi
posie/posie-web/rwpilib/motorsClass.py
Python
gpl-3.0
27,889
0.033992
#!/usr/bin/python # # motorsClass.py MOTORS CLASS # # METHODS: # motors(readingPerSec) # create instance and motor control thread # cancel() # stop motors, close motor control thread # drive(driveSpeed) # ramp speed to go fwd(+) or back(...
controlTravel() # monitor drive until distance reached # controlTurn() # monitor spin until angle reached # controlStop() # monitor drive or spin while stopping # controlStopped() # routine called while motors are not running # # motors_off() # # motors_fwd() # motors_bwd() # motors_ccw(...
import sys # uncomment when testing below rwpilib\ #sys.path.insert(0,'..') import PDALib import myPDALib import myPyLib from myPyLib import sign, clamp import time import threading import traceback import datetime import encoders class Motors(): # CLASS VARS (Avail to all instances) # Access as Motors.class_v...
KaranToor/MA450
google-cloud-sdk/lib/surface/compute/health_checks/create/http.py
Python
apache-2.0
3,471
0.004033
# Copyright 2015 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 ag...
.healthC
heck.httpHealthCheck.response = args.response return requests Create.detailed_help = { 'brief': ('Create a HTTP health check to monitor load balanced instances'), 'DESCRIPTION': """\ *{command}* is used to create a HTTP health check. HTTP health checks monitor instances in a load balancer ...
cako/mpl_grandbudapest
grandbudapest.py
Python
mit
1,318
0
#!/usr/bin/env python import numpy as np import matplotlib.pyplot as plt plt.style.use('grandbudapest') # Fixing random state for reproducibility np.random.seed(1) fig, axes = plt.subplots(ncols=2, nrows=2) ax1, ax2, ax3, a
x4 = axes.ravel() # scatter plot (Note: `plt.scatter` doesn't use default colors) x, y = np.random.normal(size=(2, 200)) ax1.plot(x, y, 'o') ax1.set_title('Scatter plot') # sinusoidal lines with colors from default color cycle L = 2*np.pi x = np.linspace(0, L) ncolors = len(plt.rcParams['axes.prop_cycle']) shift = np...
ax2.plot(x, np.sin(x + s), '-') ax2.margins(0) ax2.set_title('Line plot') # bar graphs x = np.arange(5) y1, y2 = np.random.randint(1, 25, size=(2, 5)) width = 0.25 ax3.bar(x, y1, width) ax3.bar(x + width, y2, width, color=list(plt.rcParams['axes.prop_cycle'])[2]['color']) ax3.set_xticks(x + width) ax3.set...
ashwingoldfish/eddy
eddy/core/commands/nodes.py
Python
gpl-3.0
14,989
0.000267
# -*- coding: utf-8 -*- ########################################################################## # # # Eddy: a graphical editor for the specification of Graphol ontologies # # Copyright (C) 2015 Daniele Pantaleone <[email protected]> ...
# # 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 General Public License for more details. # # # # You should have received a copy of the GNU General Public License # # along with this prog...
marktoakley/LamarckiAnt
SCRIPTS/AMBER/symmetrise_prmtop/perm-prmtop.ff02.py
Python
gpl-3.0
25,578
0.020916
#!/usr/bin/env python import os import os.path import sys import string ############################################################### ## # ## Edyta Malolepsza # ## David Wales' group, University of Cambridge ...
a3], a[aa.index(residue)][a4] d1 = '-'+dihedrals[j][0] d2 = dihedrals[j][3][1:] dihedrals[j][0] = d2 dihedrals[j][3] = d1 ##test a1 = (int(dihedrals[j][0])-currentAtomNumber)/3 ##test a2 = (int(dihedrals[j][1])-currentAtomNumber)/3 ##test a3 = (int(dihedrals[j][2][1:])-currentAtom...
[j][3][1:])-currentAtomNumber)/3 ##test print dihedrals[j], a[aa.index(residue)][a1], a[aa.index(residue)][a2], a[aa.index(residue)][a3], a[aa.index(residue)][a4] def exchange_atoms_ring3(a, aa, residue, dihedrals): find_atom1 = a[aa.index(residue)].index('CE1') atomNumber1 = find_atom1+currentAtomNumber at...
lhupfeldt/multiconf
multiconf/bits.py
Python
bsd-3-clause
515
0.001942
# Copyright (c) 2012 Lars Hupfeldt Nielsen, Hupfeldt IT # All rights reserved. This work is
under a BSD license, see LICENSE.TXT. def int_to_bin_str(value, max_bits=8192): """Convert an int to a string representation of a bitmask (binary number)""" mask = value bits = 1 while 1 << bits < value or bits < 16 and bits < max_bits: bits *= 2 rep = '' while bits: rep =
('1' if mask & 1 else '0') + rep bits = bits - 1 mask = mask >> 1 return '0b' + rep
pfitzer/youtube2mp3
youtube2mp3/__init__.py
Python
gpl-2.0
55
0
# __author__ = 'Michael Pfister' __versi
on__ = '1.4.0
'
SFII/cufcq-new
modules/linechart_module.py
Python
mit
5,898
0.000848
from modules.chart_module import ChartModule import tornado.web import logging class LineChartModule(ChartModule): def render(self, raw_data, keys, chart_id="linechart"): self.chart_id = chart_id self.chart_data = self.overtime_linechart_data(raw_data, keys) return self.render_string('mod...
d = { 'percent_a': 'y-axis-3', 'percent_b': 'y-axis-3', 'percent_c': 'y-axis-3', 'percent_d': 'y-axis-3',
'percent_f': 'y-axis-3', 'percent_incomplete': 'y-axis-3', 'average_grade': 'y-axis-2', }.get(key, 'y-axis-1') fill = { 'percent_a': True, 'percent_b': True, 'percent_c': True, 'percent_d': True, ...
iandmyhand/python-utils
DataStructuresAndAlgorithmsInPython/Palindrome.py
Python
mit
595
0.011765
def firstCharacter(str): return str[:1] assert(firstCharacter("abc") is "a") def lastCharacter(str): return str[-1:] assert(lastCharacter("abc") is "c") def middleCharacters(str
): return str[1:-1] assert(middleCharacters("abc") == "b") assert(middleCharacters("abcde") == "bcd") def isPalindrome(str): if len(str) <= 1: return
True if firstCharacter(str) != lastCharacter(str): return False return isPalindrome(middleCharacters(str)) assert(isPalindrome("a") == True) assert(isPalindrome("taste") == False) assert(isPalindrome("roror") == True)
colinta/MotionLookitup
compile.py
Python
bsd-2-clause
4,942
0.006273
if __name__ == '__main__': import os from bs4 import BeautifulSoup def get_class(cls): class_name = cls['name'] _instance_methods = cls.find_all('method', recursive=False, class_method=lambda m: m != 'true') retval = cls.find('retval') if retval: if retval.has_a...
ector), 'type': declared_type} def get_const_name(const): # do this at "output time" # return const['name'][0].upper() + const['name'][1:] return const['name'] RUBYMOTION_FOLDER = '/Libr
ary/RubyMotion/data/' def parse_bridgesupport(prefix): everything = {} for filename in os.listdir(os.path.join(RUBYMOTION_FOLDER, prefix)): name, ext = os.path.splitext(filename) print((prefix + '/' + name).replace('/BridgeSupport/', '/')) bridgesupport = Beautif...
zachriggle/idapython
hrdoc.py
Python
bsd-3-clause
3,025
0.00562
import os import sys import shutil from glob import glob # -------------------------------------------------------------------------- DOC_DIR = 'hr-html' PYWRAPS_FN = 'idaapi.py' # -------------------------------------------------------------------------- def add_footer(lines): S1 = 'Generated by Epydoc' S2 =...
------------------------------------------------------------------- def main(): # Save old directory and adjust import path curdir = os.getcwd() + os.sep sys.pa
th.append(curdir + 'python') sys.path.append(curdir + 'tools') sys.path.append(curdir + 'docs') old_dir = os.getcwd() try: print "Generating documentation....." os.chdir('docs') gen_docs() os.chdir(DOC_DIR) patch_docs() print "Documentation generated!...
JoaquimPatriarca/senpy-for-gis
gasp/ine/__init__.py
Python
gpl-3.0
41
0.02439
""" Tools to put to g
ood use
INE data """
hyperized/ansible
lib/ansible/modules/cloud/amazon/aws_netapp_cvs_FileSystems.py
Python
gpl-3.0
12,011
0.001915
#!/usr/bin/python # (c) 2019, NetApp Inc # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) """AWS Cloud Volumes Services - Manage fileSystem""" from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '...
Update, Delete fileSystem on AWS Cloud Volumes Servi
ce. options: state: description: - Whether the specified fileSystem should exist or not. required: true choices: ['present', 'absent'] type: str region: description: - The region to which the filesystem belongs to. required: true type: str creationToken: description: ...
AtsushiSakai/PyAdvancedControl
finite_horizon_optimal_control/main.py
Python
mit
2,743
0.032446
#! /usr/bin/python # -*- coding: utf-8 -*- u""" Finite Horizon Optimal Control author Atsushi Sakai """ import numpy as np import scipy.linalg as la def CalcFiniteHorizonOptimalInput(A,B,Q,R,P,N,x0): u""" Calc Finite Horizon Optimal Input # TODO optimize in: see below min x'Px+sum(x'Qx+u'Ru...
print(A.shape) print("x0 shape:") print(x0.shape) return None elif B.shape[1] is not R.shape[1]: print("Data Error
: B's col == R's row") print("B shape:") print(B.shape) print("R's shape:") print(R.shape) return None sx=np.eye(A.ndim) su=np.zeros((A.ndim,B.shape[1]*N)) #calc sx,su for i in range(N): #generate sx An=np.linalg.matrix_power(A, i+1) sx=n...
wcmitchell/insights-core
insights/parsers/sysconfig.py
Python
apache-2.0
7,321
0.000137
""" Sysconfig - files in ``/etc/sysconfig/`` ======================================== This is a collection of parsers that all deal with the system's configuration files under the ``/etc/sysconfig/`` folder. Parsers included in this module are: ChronydSysconfig - file ``/etc/sysconfig/chronyd`` ---------------------...
t('OPTIONS') '' >>> 'NOOP' in httpd_syscfg False
""" pass @parser(sysconfig_irqbalance) class IrqbalanceSysconfig(SysconfigOptions): """ A parser for analyzing the ``irqbalance`` service config file in the ``/etc/sysconfig`` directory. Sample Input:: #IRQBALANCE_ONESHOT=yes # # IRQBALANCE_BANNED_CPUS # 64 bit b...
timvideos/flumotion
flumotion/test/test_worker_medium.py
Python
lgpl-2.1
2,617
0
# -*- Mode: Python; test-case-name:flumotion.test.test_worker_worker
-*- # vi:si:et:sw=4:sts=4:ts=4 # Flumotion - a streaming media server # Copyright (C) 2004,2005,2006,2007,2008,2009 Fluendo, S.L.
# Copyright (C) 2010,2011 Flumotion Services, S.A. # All rights reserved. # # This file may be distributed and/or modified under the terms of # the GNU Lesser General Public License version 2.1 as published by # the Free Software Foundation. # This file is distributed without any warranty; without even the implied # w...
eshandas/simple_django_logger
simple_django_logger/admin.py
Python
mit
1,281
0.000781
from django.contrib import admin from .models import ( Log, RequestLog, EventLog, ) class LogAdmin(admin.ModelAdmin): readonly_fields = [ 'log_level', 'request_url', 'request_method', 'get_data', 'request_body', 'cookies', 'meta', 'exception_type', 'message', 'stack_trace', 'u...
eadonly_fields = [ 'log_level', 'message', 'stack_trace', 'tag', 'created_on'] def has_add_permission(self, request): return False admin.site.register(Log, LogAdmin) admin.site.register(RequestLog, RequestLogAdmin
) admin.site.register(EventLog, EventLogAdmin)
apache/bloodhound
bloodhound_multiproduct/tests/versioncontrol/api.py
Python
apache-2.0
4,299
0.001163
# -*- coding: utf-8 -*- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (...
MultiproductTestCase): @property def env(self): env = getattr(self,
'_env', None) if env is None: self.global_env = self._setup_test_env() self._upgrade_mp(self.global_env) self._setup_test_log(self.global_env) self._load_product_from_data(self.global_env, self.default_product) self._env = env = ProductEnvironment( ...
mikel-egana-aranguren/SADI-Galaxy-Docker
galaxy-dist/eggs/Cheetah-2.2.2-py2.7-linux-x86_64-ucs4.egg/Cheetah/CacheStore.py
Python
gpl-3.0
3,059
0.006538
''' Provides several CacheStore backends for Cheetah's caching framework. The methods provided by these classes have the same semantics as those in the python-memcached API, except for their return values: set(key, val, time=0) set the value unconditionally add(key, val, time=0) set only if the server doesn't alr...
or def delete(self, key): raise NotImplementedError def get(self, key): raise NotImplementedError class MemoryCacheStore(AbstractCacheStore): def __init__(self): self._data = {} def set(self, key, val, time=0): self._data[key] = (val,
time) def add(self, key, val, time=0): if self._data.has_key(key): raise Error('a value for key %r is already in the cache'%key) self._data[key] = (val, time) def replace(self, key, val, time=0): if self._data.has_key(key): raise Error('a value for key %r is alr...
grundprinzip/sublemacspro
lib/mark_ring.py
Python
bsd-3-clause
2,686
0.004468
import sublime, sublime_plugin # # Classic emacs mark ring with multi-cursor support. Each entr
y in t
he ring is implemented # with a named view region with an index, so that the marks are adjusted automatically by # Sublime. The special region called "jove_mark" is used to display the current mark. It's # a copy of the current mark with gutter display properties turned on. # # Each entry is an array of 1 or more regio...
chrissly31415/amimanera
keras_tools.py
Python
lgpl-3.0
10,881
0.01351
#!/usr/bin/python # coding: utf-8 import numpy as np from keras.models import Sequential, Model, load_model from keras.optimizers import SGD,Adagrad,RMSprop,Adam from keras.layers import Dense, Input, Activation from keras.layers import BatchNormalization, Add, Dropout from keras import optimizers from keras.layer...
) else: model.add(Dropout(dropout)) model.add(Dense(layer, kernel_initializer='normal', activation=activation)) model.add(Dense(1, kernel_initializer='normal',activation='linear')) # Compile model #model.compile(loss='mean_squared_error', optimizer=optimizers.Adadelta(lr=1.0...
compile(loss='mean_squared_error', optimizer=Adagrad(lr=self.learning_rate) # 0.01 if optimizer is None: optimizer = optimizers.RMSprop(lr=learning_rate) model.compile(loss=loss,optimizer=optimizer) return model def create_regression_model(input_dim=64,learning_rate=0.001,layers=[256,256],dropouts...
stephtdouglas/k2spin
k2io.py
Python
mit
2,475
0.006061
"""Read in lightcurve files.""" import logging import numpy as np import astropy.io.ascii as at def read_single_aperture(filename): """Read in one of AMC's K2 light curves, inputs ------ filename: string should look like EPIC_205030103_xy_ap1.5_fixbox_cleaned.dat outputs ------- ...
in the file x_pos, y_pos, qual_flux: arrays apertures: array, length=2 The apertures contained in the file
""" # Read in the file lc = at.read(filename, delimiter=' ',data_start=1) split_filename = filename.split("/")[-1].split('_') logging.debug(split_filename) epicID = split_filename[1] # Extract the useful columns time = lc["Dates"] fluxes = np.array([lc["Flux5"], lc["Flux3"]]) ...
patrikhuber/eos
share/scripts/convert-bfm2017-to-eos.py
Python
apache-2.0
3,067
0.005546
import numpy as np import eos import h5py # This script converts the Basel Face Model 2017 (BFM2017, [1]) to the eos model format, # specifically the files model2017-1_face12_nomouth.h5 and model2017-1_bfm_nomouth.h5 from the BFM2017 download. # # The BFM2017 does not come with texture (uv-) coordinates. If you have t...
triangle_list.transpose().tolist()) # Construct and save an eos model from the BFM data: model = eos.morphablemodel.MorphableModel(shape_model, expression_model, color_model, vertex_definitions=
None, texture_coordinates=[], texture_triangle_indices=[]) # uv-coordinates can be added here eos.morphablemodel.save_model(model, "bfm2017-1_bfm_nomouth.bin") print("Converted and saved model as bfm2017-1_bfm_nomouth.b...
JackDanger/sentry
src/sentry/templatetags/sentry_assets.py
Python
bsd-3-clause
1,943
0.003603
from __future__ import absolute_
import from django.conf import settings from django.template import Library from sen
try import options from sentry.utils.assets import get_asset_url from sentry.utils.http import absolute_uri register = Library() register.simple_tag(get_asset_url, name='asset_url') @register.simple_tag def absolute_asset_url(module, path): """ Returns a versioned absolute asset URL (located within Sentry'...
barrachri/epcon
p3/admin.py
Python
bsd-2-clause
27,045
0.00281
# -*- coding: UTF-8 -*- from collections import defaultdict from decimal import Decimal from django import forms from django import http from
django.conf import settings from django.conf.urls import url, patterns from django.contrib import admin from django.core import urlresolvers from dj
ango.db.models import Q from django.contrib.auth.models import User from assopy import admin as aadmin from assopy import models as amodels from assopy import stats as astats from assopy import utils as autils from conference import admin as cadmin from conference import models as cmodels from conference import forms a...
valtandor/easybuild-easyblocks
easybuild/easyblocks/generic/versionindependentpythonpackage.py
Python
gpl-2.0
4,223
0.002368
## # Copyright 2013 Ghent University # # This file is part of EasyBuild, # originally created by the HPC team of Ghent University (http://ugent.be/hpc/en), # with support of Ghent University (http://ugent.be/hpc), # the Flemish Supercomputer Centre (VSC) (https://vscentrum.be/nl/en), # the Hercules foundation (http://w...
iring a specific python package.""" def build_step(self):
"""No build procedure.""" pass def prepare_step(self): """Set pylibdir""" self.pylibdir = 'lib' super(VersionIndependentPythonPackage, self).prepare_step() def install_step(self): """Custom install procedure to skip selection of python package versions.""" fu...
mozaik-association/mozaik
mozaik_mandate/models/res_partner.py
Python
agpl-3.0
3,660
0.000273
# Copyright 2018 ACSONE SA/NV # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import _, fields, models class ResPartner(models.Model): _inherit = "res.partner" _allowed_inactive_link_models = ["res.partner"] _inactive_cascade = True sta_mandate_ids = fields.One2many( ...
", False)], ) ext_mandate_count = fields.Integer( string="External Mandates Nbr", compute="_compute_mandate_assembly_co
unt" ) ext_assembly_count = fields.Integer( string="External Assemblies", compute="_compute_mandate_assembly_count" ) def get_mandate_action(self): """ return an action for an ext.mandate contains into the domain a specific tuples to get concerned mandates """ ...
ricotabor/opendrop
opendrop/app/common/image_acquisition/configurator/__init__.py
Python
gpl-2.0
1,447
0
# Copyright © 2020, Joseph Berry, Rico Tabor ([email protected]) # OpenDrop is released under the GNU GPL License. You are free to # modify and distribute the code, but always under the same license # (i.e. you cannot make commercial derivatives). # # If you use this software in your research, please cite the foll...
op tensiometry. Journal of Colloid and Interface Science 454 # (2015) 226–237. https://doi.org/10.1016/j.jcis.2015.05.012 # # E. Huang, T. Denning, A. Skoufis, J. Qi, R. R. Dagastine, R. F. Tabor # and J. D. Berry, OpenDrop: Open-source software for pendant drop # tensiometry & contact angle measurements, submitted to ...
purpose, but also to justify # continued development of this code and other open source resources. # # OpenDrop is distributed WITHOUT ANY WARRANTY; without even the # implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR # PURPOSE. See the GNU General Public License for more details. You # should have rece...
formicablu/digischool
schools/migrations/0004_auto__add_field_metrictype_unit.py
Python
gpl-2.0
2,337
0.007274
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'MetricType.unit' db.add_column(u'schools_metrictype', 'unit', self.gf(...
'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'position': ('django.contrib.gis.db.models.fields.PointField', [], {}) }, u'schools.year
': { 'Meta': {'object_name': 'Year'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.IntegerField', [], {}) } } complete_apps = ['schools']
MagicSolutions/django-email-subscription
setup.py
Python
mit
888
0
import os from setuptools import setup, find_packages R
EADME = open(os.path.join(os.path.dirname(__file__), 'README.md')).read() os
.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name='django-email-subscription', url='https://github.com/MagicSolutions/django-email-subscription', version='0.0.1', description='Django app for creating subcription accoutns.', long_description=README, install...
EPiCS/soundgates
hardware/tools/to_rawdata.py
Python
mit
1,000
0.019
#!/usr/bin/env python # -*- coding: ascii -*- """ package.module ~~~~~~~~~~~~~ A description which can be long and explain the complete functionality of this module even with indented code examples. Class/Function however should not be documented here. :copyright: year by my name, see AUTHORS for more details :licen...
'r') f_out = open(outputfilename, 'wb') sample = 0 for line in f_in: try: sample = int(line) data = struct.pack("i", sample) # pack integer in a binary string f_out
.write(data) except: print "Cannot convert: " + line finally: f_in.close() f_out.close() if __name__=='__main__': print "Converting..." do_convert(sys.argv[1]) print "done. Written to " + outputfilename
varlib1/servermall
jenkins/test_jenkins.py
Python
bsd-3-clause
5,889
0.000849
# stdlib from collections import defaultdict import datetime import logging import os import shutil import tempfile # 3p import xml.etree.ElementTree as ET # project from tests.checks.common import AgentCheckTest logger = logging.getLogger(__file__) DATETIME_FORMAT = '%Y-%m-%d_%H-%M-%S' LOG_DATA = 'Finished: SUCCE...
, 'duration': '60'} UNSUCCESSFUL_BUILD = {'number': '99', 'result': 'ABORTED', 'duration': '60'} CONFIG = """ init_config: instances: - name: default jenkins_home: <JENKINS_HOME> """ def dict_to_xml(metadata_dict): """ Convert a dict to xml for use in a build.xml file """ build = ET.Element('b...
ent(build, k) node.text = v return ET.tostring(build) def write_file(file_name, log_data): with open(file_name, 'w') as log_file: log_file.write(log_data) class TestJenkins(AgentCheckTest): CHECK_NAME = 'jenkins' def setUp(self): super(TestJenkins, self).setUp() self...
arcapix/gpfsapi-examples
type_sizes_piechart.py
Python
mit
519
0.001927
from collections import Counter from os.path import splitext import matplotlib.pyplot as plt from arcapix.fs.gpfs import ListProcessingRule, ManagementPolicy def type_sizes(file_list): c = Counter() for f in file_list:
c.update({splitext(f.name): f.filesize})
return c p = ManagementPolicy() r = p.rules.new(ListProcessingRule, 'types', type_sizes) result = p.run('mmfs1')['types'] plt.pie(list(result.values()), labels=list(result.keys()), autopct='%1.1f%%') plt.axis('equal') plt.show()
rdmorganiser/rdmo
rdmo/questions/migrations/0043_django2.py
Python
apache-2.0
1,023
0.00391
# Generated by Django 2.2rc1 on 2019-03-26 13:29 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('questions', '0042_remove_null_true'), ] operations = [ migrations.AlterModelOptions( name='catalog', options={'ordering': (...
migrations.AlterModelOptions( name='questionset', options={'ordering': ('section', 'order'), 'verbose_name': 'Question set', 'verbose_name_plural': 'Question set'}, ), migrations.AlterM
odelOptions( name='section', options={'ordering': ('catalog__order', 'order'), 'verbose_name': 'Section', 'verbose_name_plural': 'Sections'}, ), ]