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
niorehkids/firmanal
analyze.py
Python
mit
6,828
0.006737
#!/usr/bin/env python import argparse import sys import re import os import locale import subprocess from multiprocessing import Process def dbquery(query): import psycopg2 db = psycopg2.connect(dbname = "firmware", user = "firmadyne", password = "firmadyne", host = "127.0.0.1") ret = None try: ...
bname = "firmware", user = "firmadyne", password = "firmadyne", host = "127.0.0.1") try: cur = db.cursor() cur.execute("SELECT ip FROM image WHERE id=" + iid) except BaseException: traceback.print_exc(
) finally: if cur: ip = cur.fetchone()[0] cur.close() return ip def rootfs_extracted(iid): query = 'select rootfs_extracted from image where id=' + iid + ';' return dbquery(query)[0][0] def main(): os.chdir(os.path.dirname(os.path.realpath(__file__))) parser = ...
skulumani/asteroid_dumbbell
blender_sim.py
Python
gpl-3.0
26,548
0.007571
"""Simulation of controlled dumbbell around Itokawa with simulated imagery using Blender This will generate the imagery of Itokawa from a spacecraft following a vertical descent onto the surface. 4 August 2017 - Shankar Kulumani """ from __future__ import absolute_import, division, print_function, unicode_literals ...
ut_path = './visualization/blender' asteroid_name = 'itokawa_low' # create a HDF5 dataset hdf5_path = './data/itokawa_landing/{}_controlled_vertical_landing.
hdf5'.format( datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S")) dataset_name = 'landing' render = 'BLENDER' image_modulus = 400 RelTol = 1e-6 AbsTol = 1e-6 ast_name = 'itokawa' num_faces = 64 t0 = 0 dt = 1 tf = 7200 num_steps = 7200 periodic_pos = np.array([...
Moth-Tolias/LetterBoy
LetterBoy_backend.py
Python
gpl-3.0
788
0.01269
"""Functions for the backend of LetterBoy""" def lb_standardcase(): """Capitalise the first letter of each sentence, and set all others to lowercase.""" pass def lb_uppercase(): """Cap
italise each letter.""" pass def lb_lowercase(): """Set all letters to lowercase.""" pass def lb_camelcase(): """Capitalise the first letter of each word, and set all others to lowercase.""" pass def lb_staggercase(): """Alternate each character between upper- and lower-case.""" ...
"""Add glitch text to the plaintext.""" pass def lb_zstrip(): """Remove glitch text.""" pass
G4brym/GetCompany.info
Main/handlers/utilities.py
Python
mit
1,191
0.006717
import uuid import datetime as dt import json import urllib.request import urllib.parse from Main.handlers.settings import RECAPTCHA_SECRET_KEY def get_title(title=""): if title == "": return "GetCompany info" else: return title + " - GetCompany info" def get_new_token(): return str(str(...
secret": RECAPTCHA_SECRET_KEY, "response": response, "remoteip": ip}) binary_data = data.encode('utf-8') u = urllib.request.urlopen("https://www.google.com/recaptcha/api/siteverify", binary_data) r
esult = u.read() recaptcha_result = json.loads(result.decode('utf-8')) return recaptcha_result["success"]
lmazuel/azure-sdk-for-python
azure-mgmt-network/azure/mgmt/network/v2017_09_01/models/effective_network_security_rule.py
Python
mit
5,618
0.002492
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
pecified by the user (if created by the user). :type name: str :param protocol: The network protocol this rule applies to. Possible values are: 'Tcp', 'Udp', and 'All'. Possible values include: 'Tcp', 'Udp', 'All' :type protocol: str or ~azure.mgmt.network.v2017_09_01.
models.EffectiveSecurityRuleProtocol :param source_port_range: The source port or range. :type source_port_range: str :param destination_port_range: The destination port or range. :type destination_port_range: str :param source_port_ranges: The source port ranges. Expected values include a sing...
FireballDWF/cloud-custodian
tools/c7n_azure/c7n_azure/resources/storage.py
Python
apache-2.0
14,922
0.002211
# Copyright 2018 Capital One Services, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in...
: 0 actions: - type: set-network-rules default-action: Deny bypass: [Logging, Metrics] ip-rules: - ip-address-or-range: 11.12.13.14 - ip-address-or-range: 21.22.23.24 virtual-...
resource-id: <subnet_resource_id> - virtual-network-resource-id: <subnet_resource_id> """ schema = type_schema( 'set-network-rules', required=['default-action'], **{ 'default-action': {'enum': ['Allow', 'Deny']}, 'bypass': {'type': 'array',...
incuna/incuna-bookmarks
bookmarks/templatetags/bookmark_tags.py
Python
mit
421
0.007126
from django import template from bookmarks.models import BookmarkInstance from tagging.models import Tag register = template.Library() @registe
r.inclusion_tag('bookmarks/tags.html') def show_bookmarks_tags(): """ Show a box with tags for all articles that belong to current site. """ return {'bookmark_tags': Tag.objects.usage_for_queryset
(queryset=BookmarkInstance.on_site.all(), counts=True, min_count=1)}
meerkat-code/meerkat_auth
translate.py
Python
mit
1,780
0.008989
""" Helper file to manage translations for the Meerkat Authentication module. We have two types of translations, general and implementation specific The general translations are extracted from the python, jijna2 and js files. """ from csv import DictReader import a
rgparse import os import shutil import datetime from babel.messages.pofile import read_po, write_po from babel.messages.catalog import Catalog, Message from babel._compat import BytesIO parser = argparse.ArgumentParser() parser.add_
argument("action", choices=["update-po", "initialise", "compile" ], help="Choose action" ) parser.add_argument("-l", type=str, help="Two letter langauge code") if __name__ == "__main__": args = parser.parse_args() lang_dir = "meerkat_auth" if a...
Diego-debian/Free-infrarossi
free_infrarossi/bin/Atenuacion.py
Python
gpl-3.0
2,477
0.031617
#/usr/bin/python #!*-* coding:utf-8 *-* # Este script es sofware libre. Puede redistribuirlo y/o modificarlo bajo # los terminos de la licencia pública general de GNU, según es publicada # por la free software fundation bien la versión 3 de la misma licencia # o de cualquier versión posterior. (según su elección )....
it() exit() def Grafica(): os.system("python g_p_Ate.py &") def Comenzar1(): tkMe
ssageBox.showinfo("Infrarossi", message= "Se procede a capturar datos, para detener el proceso cierre la ventana de captura de datos 'de color azul'") os.system("xterm -T Infrarossi -geom 50x8+185+100 +cm -bg blue -e python bin/c_p_Ate.py &") # os.system("python bin/c_p_Ate.py") # ----------------------------...
lasote/conan
conans/client/conf/config_installer.py
Python
mit
4,484
0.001338
import os from conans.tools import unzip import shutil from conans.util.files import rmdir, mkdir from conans.client.remote_registry import RemoteRegistry from conans import tools from conans.errors import ConanException def _handle_remotes(registry_path, remote_file, output): registry = RemoteRegistry(registry_p...
hutil.copy(os.path.join(root, f), os.path.join(target_folder, profile)) def _process_git_repo(repo_url, client_cache, output, runner, tmp_folder): output.info("Trying to clone repo %s" % repo_url) wit
h tools.chdir(tmp_folder): runner('git clone "%s" config' % repo_url, output=output) tmp_folder = os.path.join(tmp_folder, "config") _process_folder(tmp_folder, client_cache, output) def _process_zip_file(zippath, client_cache, output, tmp_folder, remove=False): unzip(zippath, tmp_folder) if r...
yangalex/Otomata-python
Otomata.py
Python
mit
7,139
0.001541
""" RUN FROM THIS FILE Alexandre Yang ITP 115 Final Project 05/08/2014 Description: Refer to readme.txt """ import pygame from Oto import Oto from Button import Button from Label import Label # Input: pygame.Surface, tuple, int, int, int, int # Output: none # Side-effect: Draws the grid on the screen def drawBoard...
, "Original") buttonList.add(o
riginalButton) clarinetButton = Button(screen, 700, 130, 140, 50, "Clarinet") buttonList.add(clarinetButton) guitarButton = Button(screen, 700, 220, 140, 50, "Guitar") buttonList.add(guitarButton) synthButton = Button(screen, 700, 320, 140, 50, "Synth") buttonList.add(synthButton) pianoButto...
diego04/cmput410-project
Distributed_Social_Networking/SocialNetworkModels/migrations/0007_comments_comment_author.py
Python
apache-2.0
483
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals fr
om django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('SocialNetworkModels', '0006_remove_commen
ts_post_author'), ] operations = [ migrations.AddField( model_name='comments', name='comment_author', field=models.CharField(default='aaa', max_length=200), preserve_default=False, ), ]
Cytrill/tools
led_tools/set_led.py
Python
gpl-3.0
407
0.014742
#!/usr/bin/env python import sys import socket import colorsys import time try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) except:
print('Failed to create socket') sys.exit(1) host = sys.argv[1]; port = 1337; r = int(sys.argv[3]) g = int(sys.argv[4]) b = int(sys.argv[5]) msg = bytes([ 0x20 + int(sys.argv[2]), r, g, b, 0x1F, 0x20 + int(sys.a
rgv[2]) ]) s.sendto(msg, (host, port))
noelevans/sandpit
kaggle/titanic/categorical_and_scaler_prediction.py
Python
mit
773
0
from __future__ import print_function import pandas from sklearn.naive_bayes import MultinomialNB from sklearn.cross_validation import train_test_split from sklearn.preprocessing import LabelEncoder def main(): train_all = pandas.DataFrame.from_csv('train.csv')
train = train_all[['Survived', 'Sex', 'Fare']][:200] gender_label = LabelEncoder() train.Sex = gender_label.fit_transform(train.Sex) X = tr
ain[['Sex', 'Fare']] y = train['Survived'] X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.33, random_state=42) clf = MultinomialNB() clf.fit(X_train, y_train) print('Accuracy: ', end='') print(sum(clf.predict(X_test) == y_test) / float(len(y_test))) if __name_...
mattseymour/django
django/db/backends/utils.py
Python
bsd-3-clause
7,044
0.000568
import datetime import decimal import hashlib import logging from time import time from django.conf import settings from django.utils.encoding import force_bytes from django.utils.timezone import utc logger = logging.getLogger('django.db.backends') class CursorWrapper: def __init__(self, cursor, db): se...
ckend-specific behavior # (#17671). Catch errors liberally because errors in cleanup code # aren't useful. try: self.close() except self.db.Database.Error: pass # The following methods cannot be implemented in __getattr__, because the # code must run when...
ransaction() with self.db.wrap_database_errors: if params is None: return self.cursor.callproc(procname) else: return self.cursor.callproc(procname, params) def execute(self, sql, params=None): self.db.validate_no_broken_transaction() ...
lluxury/codewars
Simple Pig Latin.py
Python
mit
564
0.006198
def pig_it(text): return ' '.j
oin([x[1:]+x[0]+'ay' if x.isalpha() else x for x in text.split()]) # 其实就是2个字符串过滤拼接,比移动方便多了,思路巧妙 # a if xx else b, 单行判断处理异常字符,xx为判断,标准套路 for x in text.split() if x.isalpha() x[1:]+x[0]+'ay' ...
])
ghchinoy/tensorflow
tensorflow/python/grappler/layout_optimizer_test.py
Python
apache-2.0
60,128
0.015018
# 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...
.conv2d(x, w, strides=[1, 1, 1, 1], padding='SAME') def _max_pool_2x2(x): """Downsamples a feature map by 2X.""" return nn.max_pool( x, ksize=[1, 2, 2
, 1], strides=[1, 2, 2, 1], padding='SAME') # Taken from tensorflow/examples/tutorials/mnist/mnist_deep.py def _two_layer_model(x): x_image = array_ops.reshape(x, [-1, 28, 28, 1]) w_conv1 = _weight([5, 5, 1, 32]) b_conv1 = _bias([32]) h_conv1 = nn.relu(_conv2d(x_image, w_conv1) + b_conv1) h_pool1 = _max_poo...
cgomezfandino/Project_PTX
API_Connection_Oanda/PTX_oandaInfo.py
Python
mit
972
0.009259
from configparser import ConfigParser import v20 # Create an object config config = ConfigParser() # Read the config config.read("../API_Connection_Oanda/pyalgo.cfg") ctx = v20.Context( 'api-fxpractice.oanda.com', 443, True, application = 'sample_code', token = config['oanda_v20']['access_token'],...
'Account: %s' %account) print account def get_instruments(): response = ctx.account.instruments( config['oanda_v20']['account_id']) instruments = response.get('instruments') # instruments[0].dict() for instrument in instruments: ins = instrument.dict() print('%20s | %...
ins['name']))
cloudzfy/euler
src/18.py
Python
mit
1,684
0.006532
# By starting at the top of the triangle below and moving to adjacent numbers on the # row below, the maximum total from top to bottom is 23. # 3 # 7 4 # 2 4 6 # 8 5 9 3 # That is, 3 + 7 + 4 + 9 = 23. # Find the maximum total from top to bottom of the triangle below: # 75 # 95 64 # 17 47 82 # 18 35 87 10 # 20 04 8...
solved by brute force, and requires a clever method! ;o) text = '75\n\ 95 64\n\ 17 47 82\n\ 18 35 87 10\n\ 20 04 82 47 65\n\ 19 01 23 75 03 34\n\ 88 02 77 73 07 63 67\n\ 99 65 04 28 06 16 70 92\n\ 41 41 26 56 83 40 80 70 33\n\ 41 48 72 33 47 32 37 16 94 29\n\ 53 71 44 65 25 43 91 52 97 51 14\n\ 70 11
33 28 77 73 17 78 39 68 17 57\n\ 91 71 52 38 17 14 91 43 58 50 27 29 48\n\ 63 66 04 68 89 53 67 30 73 16 69 87 40 31\n\ 04 62 98 27 23 09 70 98 73 93 38 53 60 04 23' digits = [[int (y) for y in x.split(' ')] for x in text.split('\n')] for i in range(1, len(digits)): digits[i][0] += digits[i - 1][0] digits[i][len(d...
vsquare95/JiyuuBot
modules/permissions.py
Python
gpl-3.0
1,361
0.005878
def get_perm_argparser(self, args): args = args.split(" ") if args[0] == "nick": self.conman.gen_send("Permission level for %s: %s" % (args[1], self.permsman.get_nick_perms(args[1]))) elif args[0] == "cmd": if args[1].startswith("."): args[1] = args[1][1:] self.conman.gen...
with("."): args[1] = args[1][1:] self.conman.gen_send("Setting permission level for %s: %s" % (args[1], args[2])) self.permsman.set_cmd_perms(args[1], args[2]) elif args[0] == "msg": args[2] = args[2].lower() == "true" or args[2] == "1" self.conman.gen_send("Setting messa...
erms(args[1], args[2]) self._map("command", "getperm", get_perm_argparser) self._map("command", "setperm", set_perm_argparser)
wm3ndez/realestate
testproject/manage.py
Python
bsd-2-clause
464
0.002155
#!/usr/bin/env python import os import sys PROJECT_DIR = os.path.abspath(os.path.dirname(__file__)) sys.path.append(PROJECT_DIR) sys.path.append(os.path.abspath(PROJECT_DIR + '/../')) sys.path.append(os.path.abspath(PROJECT_DIR + '/../realestate/')) if __name__ == "__main__": os.environ.setdefault("DJANGO_SETT
INGS_MODULE", "testproject.settings") from django.core.management import execute_from_command_line execute_from_command_
line(sys.argv)
nagaozen/my-os-customizations
home/nagaozen/.gnome2/gedit/plugins/codecompletion/utils.py
Python
gpl-3.0
1,420
0.008451
# -*- coding: utf-8 -*- # gedit CodeCompletion plugin # Copyright (C) 2011 Fabio Zendhi Nagao # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your o...
r() #if not (ch.isalnum
() or ch in ['_', ':', '.', '-', '>']): if not (ch.isalnum() or ch in "_:.->"): a.forward_char() break word = a.get_visible_text(b) return a, word def get_document(piter): a = piter.copy() b = piter.copy() while True: if not a.backward_char(): ...
jambonsw/django-improved-user
src/improved_user/admin.py
Python
bsd-2-clause
1,256
0
"""Admin Configuration for Improved User""" from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.utils.translation import gettext_lazy as _ from .forms import UserChangeForm, UserCreationForm class UserAdmin(B
aseUserAdmin): """Admin panel for Improved User, mimics Django's default""" fieldsets = ( (None, {"fields": ("email", "password")}), (_("Personal info"), {"fields": ("full_name", "short_name")}), ( _("Permissions"), { "fields": ( ...
"groups", "user_permissions", ), }, ), (_("Important dates"), {"fields": ("last_login", "date_joined")}), ) add_fieldsets = ( ( None, { "classes": ("wide",), "fields": ("ema...
Bloodoff/raidinfo
lib/raid_megaraid.py
Python
gpl-3.0
8,614
0.003018
import os import re import struct from . import helpers from .raid import RaidCont
roller, RaidLD, RaidPD, DeviceCapacity from .mixins import TextAttributeParser from .smart import SMARTinfo if os.name == 'nt': raidUtil = 'C:\\Program Files (x86)\\MegaRAID Storage Manager\\StorCLI64.exe' elif 'VMkern
el' in os.uname(): raidUtil = '/opt/lsi/storcli/storcli' else: raidUtil = '/opt/MegaRAID/storcli/storcli64' class RaidControllerLSI(TextAttributeParser, RaidController): _attributes = [ (r'(?i)^Model\s=\s(.*)$', 'Model', None, False, None), (r'(?i)^Serial\sNumber\s=\s(.*)$', 'Serial', Non...
mscuthbert/abjad
abjad/demos/desordre/test/test_demos_desordre.py
Python
gpl-3.0
198
0.005051
# -*- encoding: utf-8 -*- import os from abjad import abjad_configuration from abjad.demo
s import desordre def test_demos_desordre_01(
): lilypond_file = desordre.make_desordre_lilypond_file()
anhstudios/swganh
data/scripts/templates/object/tangible/furniture/all/shared_frn_all_lamp_free_s01_lit.py
Python
mit
461
0.047722
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LO
ST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Tangible() result.template = "object/tangible/furniture/all/shared_frn_all_lamp_free_s01_lit.iff" result.attribute_template_id = 6 result.stfName("frn
_n","frn_lamp_free") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
mrcslws/nupic.research
src/nupic/research/frameworks/vernon/mixins/step_based_logging.py
Python
agpl-3.0
4,696
0.000213
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2020, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This progra...
ep_freq: Configures mixins and subclasses that log every timestep to only log every nth times
tep (in addition to the final timestep of each epoch). Set to 0 to log only at the end of each epoch. """ super().setup_experiment(config) self._current_timestep = 0 self.log_timestep_freq = config.get("log_timestep_freq",...
openhealthcare/randomise.me
rm/trials/migrations/0035_auto__del_field_trial_max_participants.py
Python
agpl-3.0
7,643
0.008112
# -*- 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): # Deleting field 'Trial.max_participants' db.delete_column(u'trials_trial', 'max_participants') def ba...
Key', [], {'to': u"orm['trials.Trial']"}), 'variable': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['trials.Variable']"}) }, u'trials.trial': { 'Meta': {'object_name': 'Trial'}, 'de
scription': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'featured': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'finish_date': ('django.db.models.fields.DateField', [], {}), 'group_a': ('django.db.models.fields.TextField', [],...
kvar/ansible
test/units/modules/network/check_point/test_cp_mgmt_host.py
Python
gpl-3.0
3,853
0.001557
# Ansible module to manage CheckPoint Firewall (c) 2019 # # Ansible 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. # # Ansible is dist...
reate_idempotent(self, mocker, connection_mock): mock_function = mocker.patch(function_path) mock_function.return_value = {'changed': False, api_call_object: OBJECT} result = self._run_module(CREATE_PAYLOAD) assert not result['changed'] def test_update(self, mocker, connection_mock...
'changed': True, api_call_object: OBJECT_AFTER_UPDATE} result = self._run_module(UPDATE_PAYLOAD) assert result['changed'] assert OBJECT_AFTER_UPDATE.items() == result[api_call_object].items() def test_update_idempotent(self, mocker, connection_mock): mock_function = mocker.patch(fu...
promil23/django-remote-forms
django_remote_forms/fields.py
Python
mit
10,077
0.002481
import datetime from django.conf import settings from django_remote_forms import logger, widgets class RemoteField(object): """ A base object for being able to return a Django Form Field as a Python dictionary. This object also takes into account if there is initial data for the field coming in ...
as_dict(self): field_dict = OrderedDict() field_dict['title'] = self.field.__class__.__name__ field_dict['required'] = self.field.required field_dict['label'] = self.fi
eld.label field_dict['initial'] = self.form_initial_data or self.field.initial field_dict['help_text'] = self.field.help_text field_dict['error_messages'] = self.field.error_messages # Instantiate the Remote Forms equivalent of the widget if possible # in order to retrieve the ...
janusnic/21v-python
unit_01/23.py
Python
mit
210
0.033333
#!/usr/bin/python import math # return statement def printLog(x): if x <= 0: print "Positive number only, please." return result = math.log(x) print "The log of x is", result x, y = -2, 3 printLog(
y)
RandyLowery/erpnext
erpnext/projects/doctype/project/project.py
Python
gpl-3.0
8,909
0.02851
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals
import frappe from frappe.utils import flt, getdate, get_url from frappe import _ from frappe.model.document import Document from erpnext.controllers.queries import get_filters_cond from frappe.desk.reportview import get_match_cond class Project(Document): def get_feed(self): return '{0}: {1}'.format(_(self.statu...
): """Load project tasks for quick view""" if not self.get('__unsaved') and not self.get("tasks"): self.load_tasks() self.set_onload('activity_summary', frappe.db.sql('''select activity_type, sum(hours) as total_hours from `tabTimesheet Detail` where project=%s and docstatus < 2 group by activity_type ...
aino/aino-convert
convert/__init__.py
Python
bsd-3-clause
105
0
from base
import MediaFile from fields import Media
FileField from widgets import AdminMediaFileWidget
jmesteve/saas3
openerp/addons/auth_crypt/__openerp__.py
Python
agpl-3.0
1,628
0
# -*- encoding: 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 GNU Affero General Public License as # published by...
tion, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public ...
ProfessorX/Config
.PyCharm30/system/python_stubs/-1247972723/pyexpat/__init__.py
Python
gpl-2.0
1,861
0.009672
# encoding: utf-8 # module pyexpat # from /usr/lib/python2.7/lib-dynload/pyexpat.x86_64-linux-gnu.so # by ge
nerator 1.135 """ Python wrapper for Expat parser. """ # imports import pyexpat.errors as errors # <module 'pyexpat.errors' (built-in)> import pyexpat.mode
l as model # <module 'pyexpat.model' (built-in)> # Variables with simple values EXPAT_VERSION = 'expat_2.1.0' native_encoding = 'UTF-8' XML_PARAM_ENTITY_PARSING_ALWAYS = 2 XML_PARAM_ENTITY_PARSING_NEVER = 0 XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE = 1 __version__ = '2.7.8' # functions def ErrorString(errno): ...
rohitranjan1991/home-assistant
homeassistant/components/accuweather/weather.py
Python
mit
6,728
0.002081
"""Support for the AccuWeather service.""" from __future__ import annotations from statistics import mean from typing import Any, cast from homeassistant.components.weather import ( ATTR_FORECAST_CONDITION, ATTR_FORECAST_PRECIPITATION, ATTR_FORECAST_PRECIPITATION_PROBABILITY, ATTR_FORECAST_TEMP, A...
eed(self) -> float: """Return the wind speed.""" return cast( float, self.coordinator.data["Wind"]["Speed"][self._unit_system]["Value"] ) @property def wind_bearing(self) -> int: """Return the wind bearing.""" return cast(int, self.coordinator.data["Wind"]["D...
ection"]["Degrees"]) @property def visibility(self) -> float: """Return the visibility.""" return cast( float, self.coordinator.data["Visibility"][self._unit_system]["Value"] ) @property def ozone(self) -> int | None: """Return the ozone level.""" # ...
kghatala/googlePythonCourse
basic/string1.py
Python
apache-2.0
3,654
0.011768
#!/usr/bin/python -tt # Copyright 2010 Google Inc. # Licensed under the Apache License, Version 2.0 # http://www.apache.org/licenses/LICENSE-2.0 # Google's Python Class # http://code.google.com/edu/languages/google-python-class/ # Basic string exercises # Fill in the code for the functions below. main() is already se...
or that call. test(donuts(4), 'Number of donuts: 4') test(donuts(9), 'Number of donuts: 9') test(donuts(10), 'Number of donuts: many') test(donuts(99), 'Number of donuts: many') print print 'both_ends' test(both_ends('spring'), 'spng') test(both_ends('Hello'), 'Helo') test(both_ends('a'), '') test(...
gle'), 'goo*le') test(fix_start('donut'), 'donut') print print 'mix_up' test(mix_up('mix', 'pod'), 'pox mid') test(mix_up('dog', 'dinner'), 'dig donner') test(mix_up('gnash', 'sport'), 'spash gnort') test(mix_up('pezzy', 'firm'), 'fizzy perm') # Standard boilerplate to call the main() function. if __na...
jeremykid/FunAlgorithm
python_practice/data_structure/array/array.py
Python
mit
869
0.073648
def main(): #init an array named a a = list() a = [] b = [1,'1',[1,2]] #Get the size of a list a_size = len(a) #how to check if a list is empty if (a): print ("not empty") else: print ("empty") index = 0 a = ['a','b','c'] print (a[index]) a.append('d') a.extend(['e']) print ('After append a, ex...
#Find the index of a item in an array answer_1 = a.index('a') answer_0 = a.index('a0') print ('use a.index(item) to find the index only for the first item') #list.pop() r eturn last item in the list and remove the last item print 'Before a.pop(), a = ', a print 'a.pop() = ', a.pop() print 'After a.pop(), a = ...
ove an item a.remove('a0') print 'After remove(a0), a = ' a main()
rackerlabs/django-DefectDojo
dojo/tool_type/views.py
Python
bsd-3-clause
2,344
0.002133
# # product import logging from django.contrib import messages from django.contrib.auth.decorators import user_passes_test from django.urls import reverse from django.http import HttpResponseRedirect from django.shortcuts import render from dojo.utils import add_breadcrumb from dojo.forms import ToolTypeForm from doj...
_valid(): tform.save() messages.add_message(request, messages.SUCCESS, 'Tool Type Configuration Successfully Created.', extra_tags='alert-success') return HttpResponseRedirec
t(reverse('tool_type', )) else: tform = ToolTypeForm() add_breadcrumb(title="New Tool Type Configuration", top_level=False, request=request) return render(request, 'dojo/new_tool_type.html', {'tform': tform}) @user_passes_test(lambda u: u.is_staff) def edit_tool_type(request,...
R-daneel-olivaw/mutation-tolerance-voting
pyvotecore/schulze_helper.py
Python
lgpl-3.0
8,939
0.002685
# Copyright (C) 2009, Brad Beattie # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in ...
e(0, self.required_winners + 1): for pattern in unique_permutations( [PREFERRED_LESS] * (self.required_winners - i) + [PREFERRED_MORE] * (i) ): self.completed_patterns.append(tuple(pattern)) def proportional_completion(self, candidate,...
* len(self.completed_patterns))) # Obtain an initial tally from the ballots for ballot in self.ballots: pattern = [] for other_candidate in other_candidates: if ballot["ballot"][candidate] < ballot["ballot"][other_candidate]: pattern.append(PR...
UManPychron/pychron
pychron/experiment/conflict_resolver.py
Python
apache-2.0
4,802
0.001874
# =============================================================================== # Copyright 2015 Jake Ross # # 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...
this L#', editable=False)] v = okcancel_view(UItem('conflicts', editor=TableEditor(columns=cols)), title='Resolve Repository Conflicts') return v if __name__ == '__main__': def main(): from pychron.paths import paths paths.bu...
ore.helpers.logger_setup import logging_setup from pychron.experiment.automated_run.spec import AutomatedRunSpec logging_setup('dvcdb') from pychron.dvc.dvc_database import DVCDatabase from itertools import groupby db = DVCDatabase(kind='mysql', host='localhost', username='root',...
bitmazk/django-review
review/south_migrations/0001_initial.py
Python
mit
10,388
0.007605
# flake8: noqa # -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models from ..compat import USER_MODEL class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Review' db.create_table(u'review_review', ( ...
('django.db.models.fields.CharField')(max_length=2)), )) db.send_create_signal(u'review', ['RatingCategoryTranslation']) # Adding model 'Rating' db.create_table(u'review_rating', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('value',...
to=orm['review.Review'])), ('category', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['review.RatingCategory'])), )) db.send_create_signal(u'review', ['Rating']) def backwards(self, orm): # Deleting model 'Review' db.delete_table(u'review_review') ...
joakim-hove/ert
ert_gui/tools/plot/__init__.py
Python
gpl-3.0
555
0
from .plot_widget import PlotWidget from .filter_popup import FilterPopup from .filterable
_kw_list_model import FilterableKwListModel from .data_type_keys_list_model import DataTypeKeysListModel from .data_type_proxy_model import DataTypeProxyModel from .data_type_keys_widget import DataTypeKeysWidget from .plot_case_model import PlotCaseModel from .plot_case_selection_widget import CaseSelectionWidget fr...
ool import PlotTool
munk/play2048
tfe.py
Python
mit
1,792
0.004464
from selenium import webdriver from selenium.webdriver.common.keys import Keys from random import randint from time import sleep import brain import game drv = webdriver.Firefox() drv.get('http://gabrielecirulli.github.io/2048/') container = drv.find_element_by_class_name('tile-container') retry = drv.find_element_by_...
: global board board = [[None, None, None, No
ne], [None, None, None, None], [None, None, None, None], [None, None, None, None]] def update_board(): global board sleep(0.1) tiles = container.find_elements_by_class_name('tile') tiledata = list(map(lambda x: x.get_attribute('class').split(), tiles)) zero_bo...
diagramsoftware/l10n-spain
l10n_es_igic/data/__init__.py
Python
agpl-3.0
985
0
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2004-2011 Pexego Sistemas Informáticos. All Rights Reserved # $Omar Castiñeira Saavedra$ # # This program is free software: you can redistribute it and/or modify # it under the terms of th...
R A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ##########################################
####################################
sean797/tracer
tracer/resources/collections.py
Python
gpl-2.0
3,632
0.022577
#-*- coding: utf-8 -*- # collections.py # Define various kind of collections # # Copyright (C) 2016 Jakub Kadlcik # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) ...
types(self, app_types):
"""app_types -- see Applications.TYPES""" applications = filter(lambda app: app.type not in app_types, self) return ApplicationsCollection(applications) def filter_types(self, app_types): """app_types -- see Applications.TYPES""" applications = filter(lambda app: app.type in app_types, self) return Applic...
linkedin/indextank-service
storefront/templatetags/analytical.py
Python
apache-2.0
2,352
0.002976
""" Analytical template tags and filters. """ from __future__ import absolute_import import logging from django import template from django.template import Node, TemplateSyntaxError from django.utils.importlib import import_module from templatetags.utils import AnalyticalException TAG_LOCATIONS = ['head_top', 'hea...
analytical.woopra', ''' logger = logging.getLogger(__name__) register = template.Library() def _location_tag(location): def analytical_tag(parser, token): bits = token.split_contents() if len(bits) > 1:
raise TemplateSyntaxError("'%s' tag takes no arguments" % bits[0]) return AnalyticalNode(location) return analytical_tag for loc in TAG_LOCATIONS: register.tag('analytical_%s' % loc, _location_tag(loc)) class AnalyticalNode(Node): def __init__(self, location): self.nodes = [node_cls...
alex/warehouse
warehouse/migrations/versions/a65114e48d6f_set_user_last_login_automatically_in_.py
Python
apache-2.0
1,008
0
# 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 # # ht
tp://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing p
ermissions and # limitations under the License. """ Set User.last_login automatically in the DB Revision ID: a65114e48d6f Revises: 104b4c56862b Create Date: 2016-06-11 00:28:39.176496 """ from alembic import op import sqlalchemy as sa revision = 'a65114e48d6f' down_revision = '104b4c56862b' def upgrade(): op....
northern-bites/nao-man
noggin/GameController.py
Python
gpl-3.0
4,831
0.002484
from man import comm from . import NogginConstants as Constants from . import GameStates from .util import FSA from . import Leds TEAM_BLUE = 0 TEAM_RED = 1 class GameController(FSA.FSA): def __init__(self, brain): FSA.FSA.__init__(self,brain) self.brain = brain self.gc = brain.comm.gc...
comm.STATE_INITIAL: self.switchTo('gameInitial')
elif self.gc.state == comm.STATE_SET: self.switchTo('gameSet') elif self.gc.state == comm.STATE_READY: self.switchTo('gameReady') elif self.gc.state == comm.STATE_PLAYING: if self.gc.penalty != comm.PENALTY_NONE: self.switchTo...
ahmedbodi/AutobahnPython
autobahn/autobahn/wamp/message.py
Python
apache-2.0
84,035
0.020694
############################################################################### ## ## Copyright (C) 2013-2014 Tavendo GmbH ## ## 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 ## ## h...
ption import ProtocolError from autobahn.wamp.interfaces import IMessage from autobahn.wamp.role import ROLE_NAME_TO_CLASS ## strict URI check allowing empty URI components _URI_PAT_STRICT = re.compile(r"^(([0-9a-z_]{2,}\.)|\.)*([0-9a-z_]{2,})?$") ## loose URI check allowing empty URI components _URI_PAT_LOOSE = re....
pile(r"^(([^\s\.#]+\.)|\.)*([^\s\.#]+)?$") ## strict URI check disallowing empty URI components _URI_PAT_STRICT_NON_EMPTY = re.compile(r"^([0-9a-z_]{2,}\.)*([0-9a-z_]{2,})?$") ## loose URI check disallowing empty URI components _URI_PAT_LOOSE_NON_EMPTY = re.compile(r"^([^\s\.#]+\.)*([^\s\.#]+)?$") def check_or_ra...
mrcslws/nupic.research
projects/rsm/rsm_samplers.py
Python
agpl-3.0
9,884
0.001315
# Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2019, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This program is free software: you can redistribute it and/or modify # it unde...
LongTensor( 1, roll_mask.sum() ).random_(0, self.n_sequences) self.sequence_cursor[1, roll_mask] = 0 def _get_next_batch(self): """ """ # First row is current inputs inp_labels_batch = self.sequences_mat[ self.sequence_id[0], self....
inputs tgt_labels_batch = self.sequences_mat[ self.sequence_id[1], self.sequence_cursor[1] ] tgt_idxs = [self._get_sample_image(digit.item()) for digit in tgt_labels_batch] # Roll next to current self.sequence_id[0] = self.sequence_id[1] self.sequence_cursor...
aplicatii-romanesti/allinclusive-kodi-pi
.kodi/addons/plugin.video.salts/service.py
Python
apache-2.0
5,535
0.00271
""" SALTS XBMC Addon Copyright (C) 2014 tknorris This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. T...
arProperty('salts.playing.episode')
self.win.clearProperty('salts.playing.srt') self.win.clearProperty('salts.playing.resume') self.tracked = False self._totalTime = 999999 self.trakt_id = None self.season = None self.episode = None self._lastPos = 0 def onPlayBackStarted(self): ...
zstackorg/zstack-woodpecker
integrationtest/vm/hybrid/test_attach_detach_oss_bucket.py
Python
apache-2.0
1,062
0.003766
''' New Integration Test for hybrid. @author: Quarkonics ''' import zstackwoodpecker.test_util as test_util import zstackwoodpecker.test_lib as test_lib import zstackwoodpecker.test_state as test_state import zstackwoodpecker.operations.hybrid_operations as hyb_ops import zstackwoodpecker.operations.resou...
hybrid.oss_bucket_create: hybrid.del_bucket() #Will be called only if exception happens in test(). def error_cleanup(): global test_obj_dict
test_lib.lib_error_cleanup(test_obj_dict)
ff0000/scarlet
scarlet/assets/models.py
Python
mit
7,186
0.000835
import os import uuid from django.db import models from django.core.files.uploadedfile import UploadedFile from django.forms.forms import pretty_name from . import get_image_cropper from . import tasks from . import settings from . import utils from . import signals from .managers import AssetManager from .fields imp...
""" if not self.pk and not self.slug: self.slug = self.generate_slug() if self.__original_file and self.file != self.__original_file: self.delete_real_file(self.__original_file) file_changed = True if self.pk: new_value = getattr(self, 'file')
if hasattr(new_value, "file"): file_changed = isinstance(new_value.file, UploadedFile) else: self.cbversion = 0 if file_changed: self.user_filename = os.path.basename(self.file.name) self.cbversion = self.cbversion + 1 if not self...
arrayfire/arrayfire_python
tests/simple/algorithm.py
Python
bsd-3-clause
3,357
0.000298
#!/usr/bin/env python ####################################################### # Copyright (c) 2015, ArrayFire # All rights reserved. # # This file is distributed under 3-clause BSD license. # The complete license agreement can be obtained at: # http://arrayfire.com/licenses/BSD-3-Clause ###############################...
isplay_func(af.sumByKey(rk, a, dim=1)) display_func(af.productByKey(rk, a, dim=0)) display_func(af.productByKey(rk, a, dim=1))
display_func(af.minByKey(rk, a, dim=0)) display_func(af.minByKey(rk, a, dim=1)) display_func(af.maxByKey(rk, a, dim=0)) display_func(af.maxByKey(rk, a, dim=1)) display_func(af.anyTrueByKey(rk, a, dim=0)) display_func(af.anyTrueByKey(rk, a, dim=1)) display_func(af.allTrueByKey(rk, a, dim=0))...
jiahao/godot
parseh5.py
Python
mit
5,010
0.011976
#!/usr/bin/env python import datetime import logging import math import socket import tables import xml.etree.ElementTree as ET logging.basicConfig(filename = 'mbta_daemon.log', level=logging.INFO) logger = logging.getLogger('xml2hdf5') class VehicleLocation(tables.IsDescription): vehicleID = tables.StringCol(4) ...
itions', filters = compressionOptions) #Create table indexers thetable.cols.time.createIndex() thetable.cols.vehicleID.createIndex() #Hash current data presentData = {} for row in thetable: presentData[row['vehicleID'], row['time']] = True for filename in sorted(glob.gl...
esentData) if Cleanup: os.unlink(filename) f.close() if __name__ == '__main__': ParseAll()
nathanhilbert/FPA_Core
openspending/views/api_v2/cubes_ext.py
Python
agpl-3.0
9,418
0.008388
import logging from datetime import datetime import os import json from flask import request, g, Response #from openspending.core import cache from openspending.auth import require from openspending.lib.jsonexport import jsonify from openspending.views.api_v2.common import blueprint from openspending.views.error impo...
ueprint.route("/api/slicer/cube/<star_name>/cubes_facts", methods=["JSON", "GET"]) @requires_complex_browser @api_json_errors @cache.cached(timeout=60, key_prefix=cache_key) #@log
_request("facts", "fields") def cubes_facts(star_name): cubes_arg = request.args.get("cubes", None) try: cubes = cubes_arg.split("|") except: raise RequestError("Parameter cubes with value '%s'should be a valid cube names separated by a '|'" % (cubes_arg) ) if len (cub...
JMSkelton/Transformer
Transformer/Utilities/__init__.py
Python
gpl-3.0
36
0
#
Transformer/Utilities/__i
nit__.py
pieterdp/helptux
helptux/models/user.py
Python
gpl-2.0
2,613
0.001148
import bcrypt from hashlib import sha512 from helptux import db, login_manager class Role(db.Model): __tablename__ = 'roles' id = db.Column(db.Integer, primary_key=True) role = db.Column(db.String(255), index=True, unique=True) def __repr__(self): return '<Role {0}>'.format(self.role) de...
g(255), index=True, unique=True, nullable=False) password_hash = db.Column(db.String(), nullable=False) posts = db.relationship('Post', backref='author', lazy='dynamic') authenticated = db.Column(db.Boolean, default=False) roles = db.relationship('Role', secon
dary=users_roles, primaryjoin=(users_roles.c.user_id == id), secondaryjoin=(users_roles.c.role_id == Role.id), backref=db.backref('users', lazy='dynamic'), lazy='dynamic') def __init__(self, email, passw...
whereskenneth/Dwarfsquad
dwarfsquad/lib/build/from_xlsx/build_full_ac.py
Python
mit
1,706
0.004103
import csv from openpyxl import load_workbook import io from dwarfsquad.lib.build.from_export import build_compound_methods, build_lots_and_levels from dwarfsquad.lib.build.from_export.build_assay_configuration import build_assay_configuration from dwarfsquad.lib.build.from_export.build_rulesettings import add_rules_to...
return '' def read_csv_from_sheet(worksheet): stream = io.StringIO() for row in worksheet.rows: stream.write(u','.join([get_column_value(c) for c in row])) stream.write(u'\n') reader = csv.DictReader(stream.getvalue().splitlines())
rows = [r for r in reader] return rows def validate_workbook(wb): assert 'Assay' in wb assert 'Compound' in wb assert 'Lots' in wb assert 'Rule' in wb
jkimbo/freight
freight/config.py
Python
apache-2.0
8,210
0.000853
from __future__ import absolute_import, unicode_literals import flask import os import logging from flask_heroku import Heroku from flask_redis import Redis from flask_sslify import SSLify from flask_sqlalchemy import SQLAlchemy from raven.contrib.flask import Sentry from werkzeug.contrib.fixers import ProxyFix from...
['REDIS_URL'] = os.environ['REDISCLOUD_URL'
] app.config['WORKSPACE_ROOT'] = os.environ.get('WORKSPACE_ROOT', '/tmp') app.config['DEFAULT_TIMEOUT'] = int(os.environ.get('DEFAULT_TIMEOUT', 300)) app.config['LOG_LEVEL'] = os.environ.get('LOG_LEVEL', 'INFO' if config.get('DEBUG') else 'ERROR') # Currently authentication requires Google app.c...
openstack/tripleo-heat-templates
tools/convert_nic_config.py
Python
apache-2.0
7,737
0
#!/usr/bin/env python # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software...
out_str += " #%s\n" % i.group(1) next_line_break = False else: if next_line_break: out_str += '\n' out_str += line next_line_break = True if next_line_break:
out_str += '\n' with open(filename, 'w') as f: f.write(out_str) return out_str class TemplateDumper(yaml.SafeDumper): def represent_ordered_dict(self, data): return self.represent_dict(data.items()) def description_presenter(self, data): if not len(data) > 80: ...
Vesihiisi/COH-tools
importer/DkBygningDa.py
Python
mit
3,500
0
from Monument import Monument, Dataset import importer_utils as utils import importer as importer class DkBygningDa(Monument): def set_adm_location(self): if self.has_non_empty_attribute("kommune"): if utils.count_wikilinks(self.kommune) == 1: adm_location = utils.q_from_first...
s("da") self.set_commonscat() self.set_image("billede") self.set_coords(("lat", "lon")) self.set_adm_location() self.set_l
ocation() self.set_sagsnr() self.set_address() self.set_inception() self.exists_with_prop(mapping) self.print_wd() if __name__ == "__main__": """Point of entrance for importer.""" args = importer.handle_args() dataset = Dataset("dk-bygninger", "da", DkBygningDa) ...
ujac81/PiBlaster
Pi/PyBlaster/src/helpers.py
Python
gpl-3.0
541
0
"""helpers.py -- supporting routines for PyBlaster project @Author Ulrich Jansen <ulrich
.jansen@rwth-aachen.de> """ suffixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'] def humansize(nbytes): if nbytes == 0: return
'0 B' i = 0 while nbytes >= 1024 and i < len(suffixes)-1: nbytes /= 1024. i += 1 f = ('%.2f' % nbytes).rstrip('0').rstrip('.') return '%s %s' % (f, suffixes[i]) def seconds_to_minutes(nsecs): if nsecs == 0: return "" return "%d:%02d" % (int(nsecs / 60), nsecs % 60)
SalesforceFoundation/CumulusCI
cumulusci/robotframework/tests/test_template_util.py
Python
bsd-3-clause
1,872
0.000534
import unittest from cumulusci.core import template_utils class TemplateUtils(unittest.TestCase): def test_string_generator(self): x = 100 y = template_utils.StringGenerator(lambda: str(x)) assert str(y) == "100" x = 200 assert str(y) == "200" def test_faker_library(se...
aker = template_utils.FakerTemplateLibrary("no_NO") val = template_utils.format_str( "{{vikingfake.first_name}} {{abc}}", {"abc": 5, "vikingfake": norwegian_faker},
) assert "5" in val def cosmopolitan_faker(language): return template_utils.FakerTemplateLibrary(language) val = template_utils.format_str( "{{fakei18n('ne_NP').first_name}} {{abc}}", {"abc": 5, "fakei18n": cosmopolitan_faker, "type": type}, ) ...
fitnr/buoyant
tests/test_buoyant.py
Python
gpl-3.0
5,408
0.001664
"""General tests for Buoyant library.""" import datetime import unittest from io import BytesIO import buoyant from buoyant import buoy sampledata = [ { "latitude (degree)": "39.235", "sea_surface_wave_peak_period (s)": "13.79", "polar_coordinate_r1 (1)": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;...
6014", "sea_surface_wind_wave_period (s)": "3.80", "spectral_energy (m**2/Hz)": "0;0;0;0;0.117495;0.347233;0.340078;1
.07545;1.31407;0.644604;0.319928;0.20951;0.203445;0.407703;0.501098;1.05528;0.552653;0.982512;0.40238;0.259344;0.176087;0.156276;0.10127;0.0713481;0.1257;0.0469963;0.0294347;0.0344079;0.0196117;0.0208386;0.0207157;0.0185725;0.0112313;0.0140935;0.00829521;0.0135329;0.0103501;0.00823833;0.00611987;0.00516951;0.00295949;0...
Javex/mixminion
lib/mixminion/server/ServerKeys.py
Python
mit
49,832
0.003793
# Copyright 2002-2011 Nick Mathewson. See LICENSE for licensing information. """mixminion.ServerKeys Classes for servers to generate and store keys and server descriptors. """ #FFFF We need support for encrypting private keys. __all__ = [ "ServerKeyring", "generateServerDescriptorAndKeys", "genera...
tityKey(self): """Retu
rn this server's
JCraft40/finalproject
polls/models.py
Python
gpl-2.0
899
0.006674
import datetime from django.db import models from django.utils import
timezone class Question(models.Mo
del): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __unicode__(self): # __unicode__ on Python 2 return self.question_text def was_published_recently(self): now = timezone.now() return now - datetime.timedelta(...
krmahadevan/selenium
py/selenium/webdriver/safari/webdriver.py
Python
apache-2.0
4,520
0.001991
# Licensed to the Software Freedom Conservancy (SFC) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The SFC licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
/WebDriverEndpointDoc/Commands/Commands.html # First available in Safari 11.1 and Safari Te
chnology Preview 41. def set_permission(self, permission, value): if not isinstance(value, bool): raise WebDriverException("Value of a session permission must be set to True or False.") payload = {} payload[permission] = value self.execute("SET_PERMISSIONS", {"permission...
oldpa/luigi
luigi/scheduler.py
Python
apache-2.0
45,889
0.002245
# -*- coding: utf-8 -*- # # Copyright 2012-2015 Spotify AB # # Licensed under the Apache License, Version
2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://
www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and...
mechaphish/colorguard
tests/test_cromu70_caching.py
Python
bsd-2-clause
1,245
0.006426
import nose from nose.plugins.attrib import attr import logging import colorguard import os bin_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../binaries')) @attr(speed='slow') def test_cromu_00070_caching(): # Test exploitation of CROMU_00070 given an input which causes a leak. Th...
e(2): payload = bytes.fromhex("06000006020a00000000000000000000000c030c00000100e1f505000000000000eb") cg = colorguard.ColorGuard(os.path.join(bin
_location, "tests/cgc/CROMU_00070"), payload) pov = cg.attempt_exploit() nose.tools.assert_not_equal(pov, None) nose.tools.assert_true(pov.test_binary()) def run_all(): functions = globals() all_functions = dict(filter((lambda kv: kv[0].startswith('test_')), functions.items())) for...
aleixo/cnn_fire
googlemanager.py
Python
gpl-3.0
4,878
0.009842
# coding=utf-8 #https://developers.google.com/drive/v3/web/quickstart/python from __future__ import print_function import httplib2 import os import io from apiclient import discovery import oauth2client from
oauth2client import client from oauth2client import tools from apiclient.http import MediaIoBaseDownload from apiclient.http import MediaFileUpload import sys import argparse from pyfcm import FCMNotification import h5py """ DESCRIPTION Script with class that manages operations with Google. Send file, uploads file an...
oogleapis.com/auth/drive' self.CLIENT_SECRET_FILE = 'GoogleDrive_Client_secret.json' self.APPLICATION_NAME = 'pythonscript' print("[GOOGLE MANAGER] Google Manager started") def init_for_upload(self,upload_file=None,upload_file_name=None): if upload_file and upload_file_name: ...
V3sth4cks153/Python-Programs
equation_solver.py
Python
mit
1,645
0.024924
# -*- coding: utf-8 -*- #Import libraries from sys import exit from math import sqrt #Print title (http://patorjk.com/software/taag/#p=display&f=Small%20Slant&t=Equation%20Solver%20V2.1) print " ____ __ _ ____ __ _ _____ ___" print " / __/__ ___ _____ _/ /_(_)__ ___ ...
for 'a', 'b' and 'c' as follows: f(x) = Ax^2+Bx+C.\n" #Define check function def check(x): if x != 0: pass else:
exit("Invalid value. Please enter only numbers other than zero.") #Input and check a = float(input("Value of 'A': ")) check(a) b = float(input("Value of 'B': ")) check(b) c = float(input("Value of 'C': ")) check(c) #Formulas dis = (b * b) - 4 * (a * c) x1 = (-b - sqrt(dis) ) / (2 * a) x2 = (-b + sqrt(dis) ) / (2 * a)...
Banno/getsentry-javascript-lite
sentry_javascript_lite/plugin.py
Python
apache-2.0
3,880
0.004897
""" sentry_javascript_lite.plugin ~~~~~~~~~~~~~~~~~~~~~ """ import re from django.conf import settings from sentry.lang.javascript.plugin import JavascriptPlugin from sentry.lang.javascript.processor import SourceProcessor from sentry.interfaces.stacktrace import (Frame, Stacktrace) from sentry_javascript_lite import...
vascriptLiteSourceProcessor.firefox_safari_stacktrace_expr.findall(frame)[0] frame = {
'filename': tokens[2], 'function': tokens[0] or '?', 'in_app': True, } if tokens[1]: frame['args'] = tokens[1].split(',') try: frame['lineno'] = int(float(tokens[3])) except: pass try: frame['coln...
creasyw/IMTAphy
framework/scenarios/PyConfig/scenarios/placer/positionList.py
Python
gpl-2.0
2,880
0.010069
############################################################################### # This file is part of openWNS (open Wireless Network Simulator) # _____________________________________________________________________________ # # Copyright (C) 2004-2007 # Chair of Communication Networks (ComNets) # Kopernikusstr. 16, D-...
BS in Meters for every single node @type rotate: float @par
am rotate: Rotate the final result by rotate in radiant [0..2pi] """ self.center = openwns.geometry.position.Position(x = 0.0, y = 0.0, z = 0.0) self.numberOfNodes = numberOfNodes self.positionsList = positionsList self.rotate = rotate def setCenter(self, center): s...
ossobv/asterisklint
asterisklint/__init__.py
Python
gpl-3.0
1,096
0
# AsteriskLint -- an Asterisk PBX config syntax checker # Copyright (C) 2015-2016 Walter Doekes, OSSO B.V. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or ...
ral Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>.
from .config import ConfigAggregator from .dialplan import DialplanAggregator from .file import FileReader from .func_odbc import FuncOdbcAggregator class FileConfigParser(ConfigAggregator, FileReader): pass class FileDialplanParser(DialplanAggregator, FileReader): pass class FileFuncOdbcParser(FuncOdbcAg...
won0089/oppia
extensions/rules/real_test.py
Python
apache-2.0
2,944
0
# coding: utf-8 # # Copyright 2014 The Oppia 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 requi...
self.assertTrue(real.IsGreaterThan(3.0).eval(4)) self.assertTrue(real.IsGreaterThan(3.0).eval(4.0)) self.assertFalse(real.IsGreaterThan(3).eval(3)) self.assertFalse(real.IsGreaterThan(3.0).eval(3.0)) self.assertFalse(real.IsGreaterThan(4.0).eval(3.0)) self.assertFalse(real....
lf.assertTrue(rule.eval(2)) self.assertTrue(rule.eval(3)) self.assertFalse(rule.eval(4)) def test_is_greater_than_or_equal_to_rule(self): rule = real.IsGreaterThanOrEqualTo(3) self.assertTrue(rule.eval(4)) self.assertTrue(rule.eval(3)) self.assertFalse(rule.eval(2))...
Geode/geonode
geonode/upload/migrations/0001_initial.py
Python
gpl-3.0
2,961
0.00304
# -*- coding: utf-8 -*- ######################################################################### # # Copyright (C) 2016 OSGeo # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 ...
go.conf import settings class Migration(migrations.Migration): dependencies = [ ('layers', '0002_initial_step2'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Upload', fields=[ ('...
se_name='ID', serialize=False, auto_created=True, primary_key=True)), ('import_id', models.BigIntegerField(null=True)), ('state', models.CharField(max_length=16)), ('date', models.DateTimeField(default=datetime.datetime.now, verbose_name=b'date')), ('uploa...
jessicayuen/cmput410-lab2
sample5.py
Python
gpl-3.0
1,165
0.017167
# Sample 5 import socket import sys try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error as msg: print('Failed to create socket!') print('Error code: ' + str(msg[0]) + ', error message: ' + msg[1]) sys.exit() print('Socked created successfully.') # Part 1 host = '' port = 8888 try: s....
to keep the socket listening for clients while True: conn, addr = s.accept() # blocking call, to accept the first client that comes # can type in bash the following to talk to the socket: telnet
localhost 8888 # Part 2 data = conn.recv(1024) if not data: break reply = '<<<Hello ' + str(data) + '>>>' conn.sendall(reply.encode('UTF8')) # once you start the socket with python sample5.py # try telnet localhost 8888 in another terminal # type test, and it should echo back <<<Hello test>>> conn.close() s...
mitsuhiko/werkzeug
src/werkzeug/wrappers/base_request.py
Python
bsd-3-clause
1,174
0
import typing as t import warnings from .request import Request class _FakeSubclassCheck(type): def __subclasscheck__(cls, subclass: t.Type) -> bool: warnings.warn( "'BaseRequest' is deprecated and will be removed in" " Werkzeug 2.1. Use 'issubclass(cls, Request)' instead.", ...
BaseRequest(Request, metaclass=_FakeSubclassCheck): def __init__(self, *args: t.Any, **kwargs: t.Any) -> None: warnings.warn( "'BaseRequest' is deprecated and will be removed in" " Werkzeug 2.1. 'Request' now includes the functionality" " directly.", Deprecati...
s)
mikeshultz/icenine
icenine/contrib/transactions.py
Python
gpl-3.0
9,242
0.003787
# -*- coding: utf-8 -*- import rlp import secp256k1 from rlp.sedes import big_endian_int, binary, Binary from rlp.utils import str_to_bytes, ascii_chr from eth_utils.address import to_normalized_address from eth_utils.hexidecimal import encode_hex, decode_hex try: from Crypto.Hash import keccak sha3_256 = lambd...
ice, startgas, to, value, data, v=0, r=0, s=0): self.data = None to = normalize_address(to, allow_blank=True) super(Transact
ion, self).__init__(nonce, gasprice, startgas, to, value, data, v, r, s) if self.gasprice >= TT256 or self.startgas >= TT256 or \ self.value >= TT256 or self.nonce >= TT256: raise InvalidTransaction("Values way too high!") @property def sender(self): if not self._se...
jhoenicke/python-trezor
trezorlib/ontology.py
Python
lgpl-3.0
2,134
0.001406
# This file is part of the Trezor project. # # Copyright (C) 2012-2018 SatoshiLabs and contributors # # This librar
y is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License version 3 # as published by the Free Software Foundation. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY W
ARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the License along with this library. # If not, see <https://www.gnu.org/licenses/lgpl-3.0.html>. from . import messa...
edno/udacity-sandbox
ud889/AIND_Sudoku/solution.py
Python
unlicense
6,141
0.006839
assignments = [] rows = 'ABCDEFGHI' cols = '123456789' def assign_value(values, box, value): """ Please use this function to update your values dictionary! Assigns a value to a given box. If it updates the board record it. """ # Don't waste memory appending actions that don't actually change any v...
ssibilities _,box = min((len(v),k) for k,v in values.items() if len(v) > 1) # Now use recursion to solve each one of the resulting sudokus, and if one returns a value (not False), return that answer! # If you're stuck, see the solution.py tab! for val in values[box]: new_values = values.copy() ...
f res: return res def solve(grid): """ Find the solution to a Sudoku grid. Args: grid(string): a string representing a sudoku grid. Example: '2.............62....1....7...6..8...3...9...7...6..4...4....8....52.............3' Returns: The dictionary representation...
jpmontez/jenkins-rpc
scripts/build-summary/cachequery.py
Python
gpl-2.0
492
0
import click import pickle from build import Build @click.group() def cli(): pass @cli.command() @click.option('--cache-file', default='test-cache') @click.option('--query') def query(cache_file, query): w
ith open(cache_file, 'rb') as f: key, criteria = query.split('=') buildobjs = pickle.load(f)
for name, build in buildobjs.items(): item = getattr(build, key, '') if criteria in item: print(build, item) cli()
bchappet/dnfpy
src/dnfpyUtils/stats/trajectory.py
Python
gpl-2.0
1,105
0.021719
from dnfpyUtils.stats.statistic import Statistic import numpy as np class Trajectory(Statistic): """ Abstract class for trajectory """ def __init__(self,name,dt=0.1,dim=0,**kwargs): super().__init__(name=name,size=0,dim=dim,dt=dt,**kwargs) self.trace = [] #save the trace ...
elf): return self._data#,self.getMean() def reset(self): super().reset() self.trace = [] self._data = np.nan def getMean(self): return np.nanmean(self.trace) def getRMSE(self): return np.sqrt(np.nanmean(self.trace)) def getCount(self): ret...
f.trace)) def getMax(self): return np.max(self.trace) def getPercentile(self,percent): return np.nanpercentile(self.trace,percent) def getMin(self): return np.min(self.trace) def getStd(self): return np.std(self.trace) def getTrace(self): """ ...
aevum/moonstone
src/moonstone/gui/qt/component/mwindow.py
Python
lgpl-3.0
14,404
0.00854
# -*- coding: utf-8 -*- # # Moonstone is platform for processing of medical images (DICOM). # Copyright (C) 2009-2011 by Neppo Tecnologia da Informação LTDA # and Aevum Softwares LTDA # # This file is part of Moonstone. # # Moonstone is free software: you can redistribute it and/or modify # it under the terms of the GN...
None, QtGui.QApplication.UnicodeUTF8)) self.addSagittalAction.setIconVisibleInMenu(True) self.addSagittalAction.setObjectName("addSagittalAction") self.addVolumeAction = QtGui.QAction(self) self.addVolu...
Akrog/cinder
cinder/api/contrib/consistencygroups.py
Python
apache-2.0
14,556
0
# Copyright (C) 2012 - 2014 EMC Corporation. # 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 # # Unle...
ps as co
nsistencygroup_views from cinder.api import xmlutil from cinder import consistencygroup as consistencygroupAPI from cinder import exception from cinder.i18n import _, _LI from cinder.openstack.common import log as logging from cinder import utils LOG = logging.getLogger(__name__) def make_consistencygroup(elem): ...
CraveFood/restkiss
tests/test_preparers.py
Python
bsd-3-clause
2,628
0.003805
import unittest from restkiss.preparers import Preparer, FieldsPreparer class InstaObj(object): def __init__(self, **kwargs): for k, v in kwargs.items(): setattr(self, k, v) class LookupDataTestCase(unittest.TestCase): def setUp(self): super(LookupDataTestCase, self).setUp() ...
ertEqual(self.preparer.lookup_data('parent.id', self.obj_data), None) def test_empty_lookup(self): # We could possibly get here in the recursion. self.assertEqual(self.preparer.lookup_da
ta('', 'Last value'), 'Last value') def test_complex_miss(self): with self.assertRaises(AttributeError): self.preparer.lookup_data('more.nested.nope', self.dict_data)
coopie/huzzer
test/test_function_generator.py
Python
mit
3,071
0.001954
from huzzer.function_generator import generate_expression, generate_unary_expr from huzzer.expressions import VariableExpression, FunctionExpression, BRANCH_EXPRESSIONS from huzzer.namers import DefaultNamer from huzzer import INT, BOOL empty_variables = { INT: [], BOOL: [] } def test_generate_unary_expr(): ...
e, # variables, # functions, # branch_expressions, # tree_depth, # branching_probability=0.4, # variable_probability=0.7, # function_call_probability=0.5 def test_generate_expression(): int_function = FunctionExpression([BOOL, INT, INT], 1) bool_function = FunctionExpres
sion([BOOL, BOOL, BOOL, BOOL], 2) functions = { INT: [int_function], BOOL: [bool_function] } # this should definitely start with the bool func, as the probabilities are one bool_expr = generate_expression( BOOL, empty_variables, functions, BRANCH_EXPRESSI...
karamanolev/persephone
persephone/persephone/celery.py
Python
mit
231
0
import os from celery imp
ort Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'persephone.settings') app = Celery('persephone') app.config_from_object('django.conf:settings',
namespace='CELERY') app.autodiscover_tasks()
SNoiraud/gramps
gramps/gen/filters/rules/_regexpidbase.py
Python
gpl-2.0
1,899
0.005793
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2002-2006 Donald N. Allingham # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 o
f 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 General Public License for more details. # # You should have ...
, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # #------------------------------------------------------------------------- # # Standard Python modules # #------------------------------------------------------------------------- import re from ...const impo...
almarklein/scikit-image
skimage/measure/_marching_cubes.py
Python
bsd-3-clause
6,374
0.000157
import numpy as np from . import _marching_cubes_cy def marching_cubes(volume, level, spacing=(1., 1., 1.)): """ Marching cubes algorithm to find iso-valued surfaces in 3d volumetric data Parameters ---------- volume : (M, N, P) array of doubles Input data volume to find isosurfaces. Will...
ue to search for isosurfaces in `volume`. spacing : length-3 tuple of floats Voxel spacing in spatial dimensions corresponding to numpy array indexing dimensions (M, N, P) as in `volume`. Returns ------- verts : (V, 3) array Spatial coordinates for V unique mesh vertices. Coordi...
erts``. This algorithm specifically outputs triangles, so each face has exactly three indices. Notes ----- The marching cubes algorithm is implemented as described in [1]_. A simple explanation is available here:: http://www.essi.fr/~lingrand/MarchingCubes/algo.html There ar...
pavpanchekha/oranj
oranj/core/builtin.py
Python
gpl-3.0
1,879
0.010112
#!/bin/false # -*- coding: utf-8 -*- from objects.orobject import OrObject from objects.function import Function from objects.number import Number from objects.file import File from objects.inheritdict import InheritDict from objects.ordict import OrDict from objects.orddict import ODict import objects.console as cons...
onsole.error), "endl": expose("\n"), "repr": expose(repr), "join": expose(libbuiltin.join), "range": expose(range), "type": expose(libbuiltin.typeof, "type"), "dir": expose(libbuiltin.dirof, "dir"), "attrs": expose(libbuiltin.attrsof, "attrs"), "reverse": expose(reversed), "sort": ...
s, "hasattr"), "getattr": expose(OrObject.get, "getattr"), "setattr": expose(OrObject.set, "setattr"), }) stolen_builtins = [ 'abs', 'all', 'any', 'bool', 'callable', #buffer 'cmp', #chr (not as unichr) 'dict', 'divmod', 'enumerate', #delattr 'exit', 'filter', # frozenset 'hash', 'id', #get...
bewallyt/Classy
authentication/serializers.py
Python
mit
1,481
0.000675
from django.contrib.auth import update_session_auth_hash from rest_framework
import serializers from authentication.models import Account class AccountSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True, required=False) confirm_password = serializers.CharField(
write_only=True, required=False) class Meta: model = Account fields = ('id', 'email', 'username', 'created_at', 'updated_at', 'first_name', 'last_name', 'tagline', 'password', 'confirm_password', 'userType') read_only_fields = ('created_at', 'updated_at',...
xvitaly/stmbot
stmbot/checker.py
Python
gpl-3.0
5,895
0.002969
#!/usr/bin/python # coding=utf-8 # Simple Steam profile checker Telegram bot # Copyright (c) 2017 EasyCoding Team # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the Licen...
:return: API check results """ apiuri = 'https://check.team-fortress.su/api.php?action=check&token=%s&id=%s' % (self.__token, self.__id) req = request(apiuri, data=None, headers={'User-Agent': 'Mozilla/5.0 (Windows NT
10.0; rv:52.0.0)' 'Gecko/20100101 Firefox/52.0.0'}) with urlopen(req) as xmlres: return xmlres.read().decode('utf-8') @property def sitestatus(self): """ TEAM-FORTRESS.SU user friendly status of checked user pro...
justinpotts/mozillians
vendor-local/lib/python/tablib/formats/_json.py
Python
bsd-3-clause
991
0
# -*- coding: utf-8 -*- """ Tablib - JSON Support """ import tablib import sys from tablib.packages import omnijson
as json title = 'json' extentions = ('json', 'jsn') def export_set(dataset): """Returns JSON representation of Dataset.""" return json.dumps(dataset.dict) def export_book(databook): """Returns JSON representation of Databook.""" return json.dumps(databook._package()) def import_set(dset, in_stre...
JSON stream.""" dbook.wipe() for sheet in json.loads(in_stream): data = tablib.Dataset() data.title = sheet['title'] data.dict = sheet['data'] dbook.add_sheet(data) def detect(stream): """Returns True if given stream is valid JSON.""" try: json.loads(stream) ...
leppa/home-assistant
homeassistant/components/nest/__init__.py
Python
apache-2.0
14,138
0.000637
"""Support for Nest devices.""" from datetime import datetime, timedelta import logging import socket import threading from nest import Nest from nest.nest import APIError, AuthorizationError import voluptuous as vol from homeassistant import config_entries from homeassistant.const import ( CONF_BINARY_SENSORS, ...
EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_STOP, ) from homeassistant.core import callback from homeassistant.helpers import config_validation as cv from homeassistant.helpers.dispatcher import async_dispatcher_connect, dispatcher_send from homeassistant.helpers.entity import Entity from . import local_aut...
= {} _LOGGER = logging.getLogger(__name__) SERVICE_CANCEL_ETA = "cancel_eta" SERVICE_SET_ETA = "set_eta" DATA_NEST = "nest" DATA_NEST_CONFIG = "nest_config" SIGNAL_NEST_UPDATE = "nest_update" NEST_CONFIG_FILE = "nest.conf" CONF_CLIENT_ID = "client_id" CONF_CLIENT_SECRET = "client_secret" ATTR_ETA = "eta" ATTR_ETA...
pythonindia/junction
tests/conftest.py
Python
mit
212
0
# -*- coding: utf-8 -*- import os import django from .fixtures import * # noqa
# import pytest os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings") def p
ytest_configure(config): django.setup()
vsfs/vsfs-bench
ec2/fabfile.py
Python
apache-2.0
3,913
0
#!/usr/bin/env python # # Copyright 2014 (c) Lei Xu <eddyxu@gmail.com> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by ...
cluster_start(ami, nmaster, nindexd, nclient, yaml='example.yaml'): """Starts a cluster (ami='', nmaster=0, nindexd=0, nclient=0, \ yaml='example.yaml')
Configuration of cluster is defined in 'example.yaml' """ num_masters = int(nmaster) num_indexd = int(nindexd) num_client = int(nclient) vsfs.start_cluster(ami, num_masters, num_indexd, num_client, conf_yaml=yaml) @task def vpc_list(): """Prints all available VPC and...
JazzeYoung/VeryDeepAutoEncoder
pylearn2/pylearn2/datasets/tests/test_mnistplus.py
Python
bsd-3-clause
1,978
0
""" This file tests the MNISTPlus class. majorly concerning the X and y member of the dataset and their corresponding sizes, data scales and topological views. """ from pylearn2.datasets.mnistplus import MNISTPlus from pylearn2.space impo
rt IndexSpace, VectorSpace import unittest from pylearn2.testing.skip import skip_if_no_data import numpy as np def test_MNISTPlus(): """ Test the MNISTPlus warper. Tests the scale of data, the splitting of train, valid, test sets. Tests that a topological batch has 4 dimensions. Tests that it wor...
ip_if_no_data() for subset in ['train', 'valid', 'test']: ids = MNISTPlus(which_set=subset) assert 0.01 >= ids.X.min() >= 0.0 assert 0.99 <= ids.X.max() <= 1.0 topo = ids.get_batch_topo(1) assert topo.ndim == 4 del ids train_y = MNISTPlus(which_set='train', label...