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
Lynx3d/pylotro
PyLotROLauncher/Information.py
Python
gpl-3.0
441
0.004535
# coding=utf-8 Version = "0.2.0" Description = "LOTRO/DDO Launcher" Author
= "Alan Jackson" Email = "ajackson@bcs.org.uk" WebSite = "http://www.lotrolinux.com" LongDescription = "Lord of the Rings Online and Dungeons & Dragons Online\nLauncher for Linux & Mac OS X" Copyright=" (C) 2009-2010 AJackson" CLIRef
erence = "Based on CLI launcher for LOTRO\n(C) 2007-2010 SNy" LotROLinuxReference = "Based on LotROLinux\n(C) 2007-2009 AJackson"
kaixinjxq/web-testing-service
wts/tests/csp/csp_media-src_corss-origin_audio_allowed_ext.py
Python
bsd-3-clause
3,027
0.001321
def main(request, response): import simplejson as json f = file('config.json') source = f.read() s = json.JSONDecoder().decode(source) url1 = "http://" + s['host'] + ":" + str(s['ports']['http'][1]) url2 = "http://" + s['host'] + ":" + str(s['ports']['http'][0]) _CSP = "media-src " + url1 + ...
ntel.com> --> <html> <head> <title>CSP Test: csp_media-src_cross-origin_audio_allowed_e
xt</title> <link rel="author" title="Intel" href="http://www.intel.com"/> <link rel="help" href="http://www.w3.org/TR/2012/CR-CSP-20121115/#media-src"/> <meta name="flags" content=""/> <meta charset="utf-8"/> <script src="../resources/testharness.js"></script> <script src="../resources/testharne...
D-K-E/cltk
src/cltk/ner/processes.py
Python
mit
4,577
0.001374
"""This module holds the ``Process``es for NER.""" from copy import deepcopy from dataclasses import dataclass from typing import Any, List from boltons.cacheutils import cachedproperty from cltk.core.data_types import Doc, Process from cltk.ner.ner import tag_ner @dataclass class NERProcess(Process): """To be...
ens = [Word(string=token) for token in split_punct_ws(get_example_text("fro"))] >>> a_process = OldFrenchNERProcess() >>> output_doc = a_process.run(Doc(raw=get_example_text("fro"), words=tokens)) >>> output_doc.words[30].string 'Bretaigne' >>> output_doc.words[30].named_entity 'LOC' >>> out...
ld French."
websauna/pyramid_sms
docs/conf.py
Python
isc
8,451
0.005325
#!/usr/bin/env python # -*- coding: utf-8 -*- # # pyramid_sms documentation build configuration file, created by # sphinx-quickstart on Tue Jul 9 22:26:36 2013. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this #...
List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'pyramid_sms', u'SMS for Pyramid Documentation', u'Mikko Ohtamaa', 'pyramid_sms', 'One line description of project.', 'Miscellaneous'), ] # Documents t...
dix to all manuals. #texinfo_appendices = [] # If false, no module ind
asciimoo/searx
searx/engines/json_engine.py
Python
agpl-3.0
3,207
0.000624
from collections import Iterable from json import loads from sys import version_info from searx.url_utils import urlencode from searx.utils import to_string if version_info[0] == 3: unicode = str search_url = None url_query = None content_query = None title_query = None paging = False suggestion_query = '' result...
def response(resp): resul
ts = [] json = loads(resp.text) if results_query: rs = query(json, results_query) if not len(rs): return results for result in rs[0]: try: url = query(result, url_query)[0] title = query(result, title_query)[0] except: ...
Sonophoto/PythonNotes
primalPython/primalPython.py
Python
bsd-2-clause
2,338
0.010265
# Primal Python: # # Functions for calculating primeness of numbers. # Implementation (c) 2016-2020 Brig Young (github.com/Sonophoto) # License: BSD-2c, i.e. Cite. [LINK TO REPO] # # Original Problem Statement # accept number input # list all primes upto and including this number. # return a python list in ascending or...
ital root. Recurses as needed to reduce digital_root to a single digit. See: https://oeis.org/A010888 for more on digital roots. """ number = _validate(number) digital_root = 0 for c in number: digital_root += int(c) i
f digital_root < 10: return digital_root elif digital_root >= 10: # We have more than one digit, recurse return digitalRoot(digital_root) def digitalSum(number): """ Takes a single value "number" as type(int) of type(str) and sums the digits to a multi-digit digital sum....
andnovar/kivy
kivy/tools/report.py
Python
mit
5,809
0.002238
''' Report tool =========== This tool is a helper for users. It can be used to dump information for help during the debugging process. ''' import os import sys from time import ctime from configparser import ConfigParser from io import StringIO import kivy report = [] report_dict = {} # One key value pair for eac...
GL_VENDOR)) report.append('GL Renderer: %s' % gl.glGetString(gl.GL_RENDERER)) report.append('GL Version: %s' % gl.glGetString(gl.GL_VERSION)) ext = gl.glGetString(gl.GL_EXTENSIONS) if ext is None: report.append('GL Extensions: %s' % ext) else: report.append('GL Extensions:') for x in ext.split(): re...
ppend('Audio = %s' % SoundLoader._classes) from kivy.core.camera import Camera report.append('Camera = %s' % Camera) from kivy.core.image import ImageLoader report.append('Image = %s' % ImageLoader.loaders) from kivy.core.text import Label report.append('Text = %s' % Label) from kivy.core.video import Video report....
lgarren/spack
var/spack/repos/builtin/packages/r-gridextra/package.py
Python
lgpl-2.1
1,773
0.000564
############################################################################## # Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
ace, Suite 330, Boston, MA 02111-1307 USA ############################################################################## from spack import * class RGridextra(RPackage): """Provides a number of user-level functions to work with "grid" graphics, notably to
arrange multiple grid-based plots on a page, and draw tables.""" homepage = "https://cran.r-project.org/package=gridExtra" url = "https://cran.r-project.org/src/contrib/gridExtra_2.2.1.tar.gz" list_url = homepage version('2.3', '01e0ea88610756a0fd3b260e83c9bd43') version('2.2.1', '7076c2122d3...
angelbarrera92/simple-python-load-balancer
loadbalancer/validator.py
Python
mit
1,735
0.004035
from jsonschema import validate import jsonschema, sys user_schema = { "type": "object", "properties": { "email": {"type": "string", "pattern": "(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)"}, "password":
{"type": "string", "minLength": 6, "maxLength": 30}, }, "required": ["email", "password"] } app_new_machine_schema = { "type": "object", "properties": { "host": {"type": "string"}, "port": {"type": "number", "minimum": 0, "maximum": 65535}, "statuspath" : {"type": "string"} ...
erties": { "host": {"type": "string"}, "port": {"type": "number", "minimum": 0, "maximum": 65535} }, "required": ["host", "port"] } def is_user_json_valid(user_json): try: validate(user_json,user_schema) return True except jsonschema.exceptions.ValidationError as ve: ...
sgraham/nope
tools/perf/benchmarks/start_with_url.py
Python
bsd-3-clause
1,178
0.014431
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from measurements import startup import page_sets from tele
metry import benchmark class _StartWithUrl(benchmark.Benchmark): page_set = page_sets.StartupPagesPageSet test = startup.StartWithUrl @classmethod def Name(cls): return 'start_with_url.startup_pages' def CreatePageTest(self, options): is_cold = (self.tag == 'cold') retu
rn self.test(cold=is_cold) @benchmark.Enabled('has tabs') @benchmark.Disabled('chromeos', 'linux', 'mac', 'win') class StartWithUrlCold(_StartWithUrl): """Measure time to start Chrome cold with startup URLs""" tag = 'cold' options = {'pageset_repeat': 5} @classmethod def Name(cls): return 'start_with_u...
krintoxi/NoobSec-Toolkit
NoobSecToolkit /scripts/sshbackdoors/backdoors/escalation/shell.py
Python
gpl-2.0
1,559
0.007056
from backdoor import * class Shell(Backdoor): prompt = Fore.RED + "(shell) " + Fore.BLUE + ">> " + Fore.RESET def __init__(self, core): cmd.Cmd.__init__(self) self.intro = GOOD + "Using Shell backdoor..." self.core = core self.options = { "name" : Option(...
dged user, simply run \".bash -p\", and you will have root access." def get_command(self): return "echo " + self.core.curtarget.pword + " | sudo -S cp /bin/bash " + self.get_value("name") + " && echo " + self.core.curtarget.pword + " | sudo -S chmod 4755 " + self.get_value("name") def do_exploit(self...
ommand()) print(GOOD + "Shell Backdoor attempted.") for mod in self.modules.keys(): print(INFO + "Attempting to execute " + mod.name + " module...") mod.exploit()
bmarshallk/NAASC
packaging_scripts/PackageManualDataset.py
Python
gpl-3.0
14,173
0.02025
#This code packages manually calibrated and imaged datasets # -------------------------------------------------------------------------------------------------- def ReadDataFromWeb(mousid): # -------------------------------------------------------------------------------------------------- """ This function...
------------------------------ def Packaging(datadict, username, qa2_dir): # -------------------------------------------------------------------------------------------------- ''' #Running the QA2 Packaging (creates the tarballs and directory to be checked by DRMs) ''' import os import glob import subprocess ...
f os.path.isdir('%s/Packages' % qa2_dir) == False: os.mkdir('Packages') os.chdir('Packages') package_dir = os.getcwd() #Copying in the scriptForPI.py os.system('cp -f /users/thunter/AIV/science/qa2/scriptForPI.py %s/%s_%s' % (qa2_dir, datadict['code'], datadict['mous'])) #Getting the cycle number for the style...
AlphaSmartDog/DeepLearningNotes
Note-6 A3CNet/Note-6.2 A3C与HS300指数择时/agent/framework.py
Python
mit
6,700
0.001343
import numpy as np import tensorflow as tf from agent.forward import Forward from config import * _EPSILON = 1e-6 # avoid nan # local network for advantage actor-critic which are also know as A2C class Framework(object): def __init__(self, access, state_size, action_size, scope_name): self.Access = acc...
ctor_grads, self.a_actor_grad = tf.clip_by_global_norm(actor_grads, MAX_GRAD_NORM) critic_grads, self.a_critic_grad = tf.clip_by_global_norm(critic_grads, MAX_GRAD_NORM) # update
Access actor_apply = self.Access.optimizer_actor.apply_gradients( zip(list(actor_grads), list(global_actor_params))) critic_apply = self.Access.optimizer_critic.apply_gradients( zip(list(critic_grads), list(global_critic_params))) self.update_global = [actor_apply, criti...
zuun77/givemegoogletshirts
codejam/2020/qual/test.py
Python
apache-2.0
167
0.011976
f
rom __future__ import print_function import sys def eprint(*args, **kwargs): print(*args, file=sys.stderr, **kwa
rgs) print("Python version") eprint(sys.version)
ktan2020/legacy-automation
win/Lib/site-packages/pip-1.3.1-py2.7.egg/pip/status_codes.py
Python
mit
87
0
SUCCESS
= 0 ERROR = 1 UNKNOWN_ERROR = 2 VIRTUALENV_NOT_FOUND = 3 NO_MATCHES_FOUND = 2
3
alexeblee/s2n
tests/integration/common/s2n_test_scenario.py
Python
apache-2.0
5,789
0.002937
## # Copyright Amazon.com, Inc. or its affiliates. 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. # A copy of the License is located at # # http://aws.amazon.com/apache2.0 # # or in the "license" file accompany...
A256", Version.TLS13), Cipher("TLS_AES_128_GCM_SHA256", Version.TLS13) ] # Older Openssl and libressl do not support CHACHA20 LEGACY_COMPATIBLE_CIPHERS = list(filter(lambda x: "CHACHA20" not in x.name, ALL_CIPHERS)) ALL_CIPHERS_PER_LIBCRYPTO_VERSION = { "openssl-1.1.1" : ALL_CIPHERS, "openssl-1.0....
LE_CIPHERS, "libressl" : LEGACY_COMPATIBLE_CIPHERS, } ALL_CURVES = ["P-256", "P-384"] class Scenario: """ Describes the configuration for a specific TLS connection. """ def __init__(self, s2n_mode, host, port, version=None, cipher=None, curve=None, s2n_flags=[], peer_flags=[]): ...
sslavic/kafka
tests/kafkatest/tests/client/client_compatibility_produce_consume_test.py
Python
apache-2.0
4,454
0.004041
# 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 # (the "License"); you may not use ...
"partitions": 10,
"replication-factor": 2}}) self.num_partitions = 10 self.timeout_sec = 60 self.producer_throughput = 1000 self.num_producers = 2 self.messages_per_producer = 1000 self.num_consumers = 1 def setUp(self): self.zk.start() def min_clust...
Captain-Coder/tribler
Tribler/Core/defaults.py
Python
lgpl-3.0
2,390
0.001255
""" Default values for configurable parameters of the Core. Author(s): Arno Bakker, Bram Cohen, Egbert Bouman """ # WARNING: # As we have release Tribler 4.5.0 you must now take into account that # people have stored versions of these params on their disk. Make sure # you change the version number of the str...
[] dldefaults['download_defaults']['correctedfilename'] = None dldefaults['download_defaults']['safe_seeding'] = False # Valid values: 'forever', 'never', 'ratio', 'time' d
ldefaults['download_defaults']['user_stopped'] = False dldefaults['download_defaults']['time_added'] = 0 dldefaults['download_defaults']['credit_mining'] = False tdefdictdefaults = {} tdefdictdefaults['comment'] = None tdefdictdefaults['created by'] = None tdefdictdefaults['announce'] = None tdefdictdefaults['announce...
vrk-kpa/ckanext-xroad_integration
ckanext/xroad_integration/auth.py
Python
agpl-3.0
501
0.003992
from ckan.plugins.toolkit import check_access, NotAuthorized, _ def xroad_error_list(context,
data_dict): if not data_dict.get('organization'): return check_access('sysadmin', context) else: try: check_access('organization_update', context, {"id": data_dict.get('organization')}) return {"success": True} except NotAuthorized: return {"success"...
list for organization")}
J-Sorenson/annnotations-line2d
annotations_line2d.py
Python
cc0-1.0
20,221
0.009798
# -*- coding: utf-8 -*- """ annotations_line2d module Created on Thu Sep 10 21:51:23 2015 @author: James Sorenson """ import matplotlib import matplotlib.pyplot as plt # This is to prevent overlapping annotations from being dragged simultaneously # due to the multi-threaded nature of the matplotlib gui. import threadi...
# We may have a logarithmic scale, but update offset only gives us delta pixels. # Add the delta to the starting pixels, then convert to data coordinates pixels_dxy = matplotlib.numpy.array((dx,dy)) new_data_xy = self.drag_trans_pix2dat.transform(self.drag_start_pixels+pixe...
etermine if the new data coordinates reach or exceed the next line data point. index=self.index while (index > 0) and (self.xydata[index-1][0] > new_data_xy[0]): #Move left index -= 1 while (index < self.xydata.shape[0] - 1) and (self.xydata[index+1][0...
ghostrocket/django-debug-toolbar-gae
tests/urls.py
Python
bsd-3-clause
404
0.007426
""" URLpatterns for the debug toolbar. These sh
ould not be loaded explicitly; the debug toolbar middleware will patch this into the urlconf for the request. """ from django.conf.urls.defaults import * from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # This pattern should be last to ensure tests still work url(r'^execute_sql...
)
VioletRed/script.module.urlresolver
lib/urlresolver/plugins/videohut.py
Python
gpl-2.0
5,173
0.007539
""" urlresolver XBMC Addon Copyright (C) 2011 t0mm0 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. ...
R A PARTICULAR PURPOSE. See the GNU General Public Li
cense 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/>. """ import re from t0mm0.common.net import Net import urllib2, os from urlresolver import common from urlresolver.plugnplay.interfaces import UrlResol...
vyscond/cocos
test/test_menu_centered.py
Python
bsd-3-clause
1,329
0.034612
from __future__ import division, print_function, unicode_literals # This code is so you can run the samples without installing the package import sys import os sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..')) # testinfo = "s, q" tags = "menu, menu_valign, menu_halign" from pyglet import image from p...
* class MainMenu(Menu): def __init__( self ): super( MainMenu, self ).__init__("TITLE" ) self.menu_valig
n = CENTER self.menu_halign = CENTER # then add the items items = [ ( MenuItem('Item 1', self.on_quit ) ), ( MenuItem('Item 2', self.on_quit ) ), ( MenuItem('Item 3', self.on_quit ) ), ( MenuItem('Item 4', self.on_quit ) ), ( MenuItem(...
rsepassi/tensor2tensor
tensor2tensor/data_generators/gene_expression_test.py
Python
apache-2.0
2,513
0.002786
# 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...
): encoder = dna_encoder.DNAEncoder(chunk_size=2) raw_inputs = ["A", "C", "G", "N", "C", "T"] # Put in numpy arrays in the same format as in the h5 file inputs = self._o
neHotBases(raw_inputs) mask = np.array([True, False, True]) outputs = np.array([[1.0, 2.0, 3.0], [5.0, 1.0, 0.2], [5.1, 2.3, 2.3]]) # Convert to example dict ex_dict = gene_expression.to_example_dict(encoder, inputs, mask, outputs) self.assertEqual(len(raw_inputs) // 2 + 1, len(ex_dict["inputs"])) ...
siconos/siconos-deb
externals/renderer/SimpleGui.py
Python
apache-2.0
7,843
0.00459
#!/usr/bin/env python ##Copyright 2009-2014 Thomas Paviot (tpaviot@gmail.com) ## ##This file is part of pythonOCC. ## ##pythonOCC is free software: you can redistribute it and/or modify ##it under the terms of the GNU Lesser General Public License as published by ##the Free Software Foundation, either version 3 of the...
).lower(), self) # if not, the "exit" action is now shown... _action.setMenuRole(QtGui.QAction.NoRole) self.connect(_action, QtCore.SIGNAL("triggered()"), _callable) self._menus[menu_name].addAction(_a
ction) except KeyError: raise ValueError('the menu item %s does not exist' % menu_name) # following couple of lines is a twek to enable ipython --gui='qt' app = QtGui.QApplication.instance() # checks if QApplication already exists if not app: # create QAppli...
taygetea/lwbot
bot.py
Python
mit
2,345
0.004264
from twisted.words.protocols import irc from twisted.internet import protocol import re import plugins.pomodoro print plugins.modules class IrcBot(irc.IRCClient): def _get_nickname(self): return self.factory.nickname nickname = property(_get_nickname) def signedOn(self): self.join(self.fac...
__(self, op, user, channel): self.operator = op self.banned = user self.ch
annel = channel def timer(self): def opmsg(self): IrcBot.privmsg(self.op, self.channel, "ban " + self.user + "?") class IrcBotFactory(protocol.ClientFactory): protocol = IrcBot def __init__(self, channel, nickname='Elua'): self.channel = channel self.nickname = nickname ...
DemocracyClub/EveryElection
every_election/apps/elections/migrations/0020_auto_20170110_1556.py
Python
bsd-3-clause
823
0
# -*- coding: utf-8 -*- # Generated by Django 1.10.2 on 2017-01-10 15:56 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [("election
s", "0019_auto_20170110_
1329")] operations = [ migrations.AddField( model_name="electedrole", name="elected_role_name", field=models.CharField(blank=True, max_length=255), ), migrations.AlterField( model_name="election", name="group", field=mo...
mezz64/home-assistant
homeassistant/components/octoprint/__init__.py
Python
apache-2.0
7,884
0.001268
"""Support for monitoring OctoPrint 3D printers.""" from datetime import timedelta import logging from typing import cast from pyoctoprintapi import ApiError, OctoprintClient, PrinterOffline import voluptuous as vol from yarl import URL from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry from homeassi...
entry.data[CONF_SSL], entry.data[CONF_PATH], ) client.set_api_key(entry.data[CONF_API
_KEY]) coordinator = OctoprintDataUpdateCoordinator(hass, client, entry, 30) await coordinator.async_config_entry_first_refresh() hass.data[DOMAIN][entry.entry_id] = {"coordinator": coordinator, "client": client} hass.config_entries.async_setup_platforms(entry, PLATFORMS) return True async de...
tkalus/fogspoon
fogspoon/api/__init__.py
Python
mit
1,585
0
# -*- coding: utf-8 -*- import simplejson as json from functools import wraps from flask import current_app, jsonify, request from ..core import FogspoonError from ..helpers import JSONEncoder from .. impo
rt factory def create_app(settings_override=None): """Returns the Fogspoon API application instance""" app = factory.create_app(__name__, __path__, settings_override) # Set the default JSON encoder app.json_encoder = JSONEncoder # Register custom error handlers app.errorhandler(FogspoonErro...
decorator that does blueprint fun and jsonify for api calls """ kwargs.setdefault('strict_slashes', False) def decorator(f): @bp.route(*args, **kwargs) @wraps(f) def wrapper(*args, **kwargs): sc = 200 rv = f(*args, **kwargs) if isinstance(rv, tup...
sjsrey/pysal_core
pysal_core/weights/tests/test_spatial_lag.py
Python
bsd-3-clause
2,394
0.00543
import os import unittest from ..weights import W from ..util import lat2W from ..spatial_lag import lag_spatial, lag_categorical import numpy as np class Test_spatial_lag(unittest.TestCase): def setUp(self): self.neighbors = {'c': ['b'], 'b': ['c', 'a'], 'a': ['b']} self.weights = {'c': [1.0], '...
'b': [1.0, 1.0], 'a': [1.0]} self.w = W(self.neighbors, self.weights, self.id_order) self.y = np.array([0, 1, 2]) self.wlat = lat2W(3, 3) self.ycat = ['a','b','a','b','c','b','c','b','c'] self.ycat2 = ['a', 'c', 'c', 'd', 'b', 'a', 'd', 'd', 'c'] self.ym =
np.vstack((self.ycat,self.ycat2)).T self.random_seed = 503 def test_lag_spatial(self): yl = lag_spatial(self.w, self.y) np.testing.assert_array_almost_equal(yl, [1., 2., 1.]) self.w.id_order = ['b', 'c', 'a'] y = np.array([1, 2, 0]) yl = lag_spatial(self.w, y) ...
gisce/OCB
openerp/addons/base/res/res_partner.py
Python
agpl-3.0
41,659
0.005329
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
r_category_display']`` is ``'short'``, the short version of the category name (without the direct parent) is used. The default is the long version. """ if not isinstance(ids, list): ids = [ids] if context is None: context = {} if context.g...
text=context) res = [] for category in self.browse(cr, uid, ids, context=context): names = [] current = category while current: names.append(current.name) current = current.parent_id res.append((category.id, ' / '.join(reve...
ekivemark/bofhirdev
accounts/forms/other.py
Python
gpl-2.0
2,816
0.002131
""" accounts FILE: forms.py Created: 6/21/15 8:31 PM """ __author__ = 'Mark Scrimshire:@ekivemark' from django.conf import settings from django import forms from django.utils.safestring import mark_safe from registration.forms import (RegistrationFormUniqueEmail, RegistrationFormTerms...
RegistrationFormTermsOfService, ): class Meta: model = User fields = ['user', 'email', 'first_name', 'last_name'] # exclude = ['us
er'] # pass class RegistrationFormTOSAndEmail( RegistrationFormUniqueEmail, RegistrationFormTermsOfService, ): pass
joachimmetz/dfvfs
dfvfs/vfs/ntfs_directory.py
Python
apache-2.0
1,709
0.005851
# -*- coding: utf-8 -*- """The NTFS directory implementation.""" from dfvfs.lib import errors from dfvfs.path import ntfs_path_spec from dfvfs.vfs import directory class NTFSDirectory(directory.Directory): """File system directory that uses pyfsntfs.""" _FILE_REFERENCE_MFT_ENTRY_BITMASK = 0xffffffffffff def ...
tfs_file_entry.sub_file_entries: directory_entry = fsntfs_sub_file_entry.name # Ignore references to self or parent. if directory_entry in ('.', '..'): continue file_reference = fsntfs_sub_file_entry.file_reference directory_entry_mft_entry = ( file_refere...
_FILE_REFERENCE_MFT_ENTRY_BITMASK) if not location or location == self._file_system.PATH_SEPARATOR: directory_entry = self._file_system.JoinPath([directory_entry]) else: directory_entry = self._file_system.JoinPath([ location, directory_entry]) yield ntfs_path...
panosl/helios
helios/store/forms.py
Python
bsd-3-clause
1,013
0
from django import forms from django.core.exceptions import ObjectDoesNotExist from helios.store.models import Category from helios.conf import settings if settings.USE_PAYPAL: from helios.paypal.forms import * class MyCategoryAdminForm(forms.ModelForm): class Meta: model = Category fields = ...
a['slug'] parent = self.cleaned_data['parent'] if slug and parent: try: this_category = Category.objects.get(slug=slug) parent_category = Category.objects.get(pk=int(parent.id)) if ( parent_category.id == this_category.id ...
y.parent == this_category ): raise forms.ValidationError( 'Can\'t have a category as parent of itself.' ) except ObjectDoesNotExist: pass return parent
vesellov/visio2python
automat.py
Python
lgpl-3.0
12,453
0.007147
#!/usr/bin/python #automat.py # # <<<COPYRIGHT>>> # # # # """ .. module:: automat This is the base class for State Machine. You can read more about `Automata-based programming <http://en.wikipedia.org/wiki/Automata-based_programming>`_ principles and learn how to develop your project in such way. T...
tid = self.id name = self.name debug_level = self.debug_level if _Index is None: self.log(debug_level, 'automat.__del__ WARNING Index is None: %r %r' % (automatid, name)) return
index = _Index.get(automatid, None) if index is None: self.log(debug_level, 'automat.__del__ WARNING %s not found' % automatid) return del _Index[automatid] self.log(debug_level, 'DESTROYED AUTOMAT %s with index %d' % (str(o), index)) del o if _Sta...
ktdreyer/rdopkg
rdopkg/utils/log.py
Python
apache-2.0
1,968
0
import logging import terminal INFO = logging.INFO # between info and debug VERBOSE = (logging.INFO + logging.DEBUG) / 2 DEBUG = logging.DEBUG log = logging.getLogger('rdopkg') log.setLevel(logging.INFO) if len(log.handlers) < 1: formatter = logging.Formatter(fmt='%(message)s') handler = logging.StreamHandl...
.yellow @property def important(self): return self.yellow_bold @property def error(self): return self.red @property def good(self): return self.green @property def cmd(self): return sel
f.cyan term = LogTerminal() def set_colors(colors): global term if colors == 'yes': if not terminal.COLOR_TERMINAL: return False term = LogTerminal(force_styling=True) return True elif colors == 'no': if not terminal.COLOR_TERMINAL: return True ...
realizelol/xenmailserv
management/dns_update.py
Python
gpl-3.0
37,781
0.024139
#!/usr/bin/python3 # Creates DNS zone files for all of the domains of all of the mail users # and mail aliases and restarts nsd. ######################################################################## import sys, os, os.path, urllib.parse, datetime, re, hashlib, base64 import ipaddress import rtyaml import dns.resol...
ow any output return "" else: return "updated DNS: " + ",".join(updated_domains) + "\n" ######################################################################## def build
_zones(env): # What domains (and their zone filenames) should we build? domains = get_dns_domains(env) zonefiles = get_dns_zones(env) # Custom records to add to zones. additional_records = list(get_custom_dns_config(env)) from web_update import get_web_domains www_redirect_domains = set(get_web_domains(env)) - ...
jriguera/Diamond
src/diamond/utils/scheduler.py
Python
mit
3,514
0
# coding=utf-8 import time import math import multiprocessing import os import random import sys import signal try: from setproctitle import getproctitle, setproctitle except ImportError: setproctitle = None from diamond.utils.signals import signal_to_exception from diamond.utils.signals import SIGALRMExcept...
time_to_sleep = (next_window + stagger_offset) - time.time() if time_to_sleep > 0: time.sleep(time_to_sle
ep) next_window += interval # Ensure collector run times fit into the collection window signal.alarm(max_time) # Collect! collector._run() # Success! Disable the alarm signal.alarm(0) except SIGALRMException: lo...
danriti/python-traceview
traceview/host.py
Python
mit
688
0
# -*- coding: utf-8 -*- """ traceview.hosts This module contains the objects associated with Hosts API resources. http://dev.appneta.com/docs/api-v2/hosts.html """ from .resource import Resource class Host(Resource): def get(self, app=None): if app: path = 'app/{app}/hosts'.forma
t(app=app) else: path = 'hosts' return self.api.get(path) def delete(self, host_id): path = 'hosts/{host_id}'.format(host_id=host_id) return self.api.delete(path) class Instrumentation(Resource): def get(self, host_id): path = 'hosts/{host_id}/versions'.fo...
turn self.api.get(path)
qedsoftware/commcare-hq
corehq/sql_accessors/migrations/0035_add_undelete_functions.py
Python
bsd-3-clause
612
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations from corehq.sql_db.operations import RawSQLMigration from corehq.form_processor.models import XFormInstanceSQL migrator = RawSQLMigration(('corehq', 'sql_accessors', 'sql_templates'), { 'FORM_STATE_DELETED': XFormInst...
gration(migrations.Migration): dependencies = [ ('sql_accessors', '0034_update_reindex_functions'), ] operations = [ migrator.get_migration('soft_undelete_cases.sql'), migrator.get_migration(
'soft_undelete_forms.sql'), ]
maliubiao/python_netlink
setup.py
Python
mit
277
0.057762
#! /usr/bin/env python from distutils.c
ore import setup, Extension m = Extension('netdev', sources = ['netdev.c']
) setup(name = 'netdev', version = '1.0', description = 'python native library for network device', ext_modules = [m])
deepeshmittal/daytona
Scheduler+Agent/action.py
Python
apache-2.0
25,730
0.008511
# This file implements all actions performed by agent to start execution script on exec host and sar data collection # from all exec and stat hosts. Each procedure is mapped with particular daytona command used by scheduler to # communicate with agent. Upon recieving command from daytona scheduler, agent execute below ...
(t, aid, tst, ts) = (None, None, None, None) if sync == "T": lctx.debug("Execute cmd in Sync ctx") cthread.join() if sfile is not None: sfile.flush() else: # async action entry in the server table (need this to che
ck self alive below) for tp in obj.async_actions: if tp[1] == actionid: (t, aid, tst, ts) = tp lctx.debug("Execute cmd in asSync ctx : " + str(actionid)) timer_expire = False while True: lctx.debug("waiting for async action to complete : " + str(...
yiannist/ganeti
test/py/ganeti.rapi.client_unittest.py
Python
bsd-2-clause
64,077
0.004573
#!/usr/bin/python # # Copyright (C) 2010, 2011 Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # 1. Redistributions of source code must retain the above copyright notice, # this l...
_used_handlers.add(handler_cls) self._last_handler = handler_cls(items, args, None) if not hasattr(self._last_handler, method.upper()): raise http.HttpNotImplemented(message="Method not implemented") except http.HttpException, ex: code = ex.code respo
nse = ex.message else: if not self._responses: raise Exception("No responses") (code, response) = self._responses.pop() return (code, NotImplemented, response) class TestConstants(unittest.TestCase): def test(self): self.assertEqual(client.GANETI_RAPI_PORT, constants.DEFAULT_RAPI_P...
creative-workflow/pi-setup
test.py
Python
mit
748
0.02139
import sys, unittest, os sys.path.append(os.path.realpath(os.path.dirname(__file__))+'/lib') tests_folder = os.path.realpath(os.path.dirname(__file__))+'/tests' from tests import ConsoleTestRunner def load_tests(loader, tests, pattern): suite = unittest.TestSui
te() pattern='test_*.py' for dirname, dirnames, filenames in os.walk(tests_folder): for path in dirnames: path=dirname+'/'+path for all_test_suite in unittest.defaultTestLoader.discover(path, pattern=pattern, top_level_dir=path): for test_suite in all_test_suite: suite.addTest(tes...
'test' unittest.main(verbosity=2, exit=False, testRunner=ConsoleTestRunner)
DMS-Aus/Roam
src/roam/api/utils.py
Python
gpl-2.0
8,657
0.001733
import collections import os import subprocess import sys from contextlib import contextmanager from PyQt5.QtWidgets import QScroller from qgis.core import QgsProject, QgsFeatureRequest, QgsGeometry, NULL, Qgis, QgsExpressionContext, \ QgsExpressionContextScope, QgsExpression, QgsFeature from roam.structs import ...
essionContext() scope = QgsExpressionContextScope(
) context.appendScope(scope) if feature is not None: scope.setVariable("roamgeometry", feature.geometry()) context.setFeature(feature) return context def new_expression_context(fields=None): """ Create a new expression context with the given fields :param fields: The fields to ...
ribag/ganeti-experiments
test/py/cmdlib/testsupport/__init__.py
Python
gpl-2.0
1,827
0
# # # Copyright (C) 2013 Google Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed ...
sting the cmdlib module. """ from cmdlib.testsupport.cmdlib_testcase import CmdlibTestCase, \ withLockedL
U from cmdlib.testsupport.config_mock import ConfigMock from cmdlib.testsupport.iallocator_mock import patchIAllocator from cmdlib.testsupport.livelock_mock import LiveLockMock from cmdlib.testsupport.utils_mock import patchUtils from cmdlib.testsupport.netutils_mock import patchNetutils, HostnameMock from cmdlib.tests...
tingelst/pymanopt
pymanopt/tools/multi.py
Python
bsd-3-clause
2,443
0.000819
import numpy as np def multiprod(A, B): """ Inspired by MATLAB multiprod function by Paolo de Leva. A and B are assumed to be arrays containing M matrices, that is, A and B have dimensions A: (M, N, P), B:(M, P, Q). multiprod multiplies each matrix in A with the corresponding matrix in B, using ma...
return np.sum(a * b, axis=2) # Approx 5x faster, only supported by numpy version >= 1.6: return np.einsum('ijk,ikl->ijl', A, B) def multitransp(A): """ Inspired by MATLAB multitransp function by Paolo de Leva. A is assumed to be an array containing M matrices, each of which has dimension N x P. ...
ltitransp then returns an array containing the M matrix transposes of the matrices in A, each of which will be P x N. """ # First check if we have been given just one matrix if A.ndim == 2: return A.T return np.transpose(A, (0, 2, 1)) def multisym(A): # Inspired by MATLAB multisym ...
eternnoir/pyTelegramBotAPI
telebot/storage/__init__.py
Python
gpl-2.0
381
0.007874
from telebo
t.storage.memory_storage import StateMemoryStorage from telebot.storage.redis_storage import StateRedisStorage from telebot.storage.pickle_storage import StatePickleStorage from telebot.storage.base_storage import StateContext,StateStorag
eBase __all__ = [ 'StateStorageBase', 'StateContext', 'StateMemoryStorage', 'StateRedisStorage', 'StatePickleStorage' ]
kevgliss/lemur
lemur/models.py
Python
apache-2.0
8,273
0.007494
""" .. module: lemur.models :platform: Unix :synopsis: This module contains all of the associative tables that help define the many to many relationships established in Lemur :copyright: (c) 2015 by Netflix Inc., see AUTHORS for more :license: Apache, see LICENSE for more details. .. moduleauthor::...
= db.Table('certificate_associations', Column('domain_id', Integer
, ForeignKey('domains.id')), Column('certificate_id', Integer, ForeignKey('certificates.id')) ) Index('certificate_associations_ix', certificate_associations.c.domain_id, certificate_associations.c.certificate_id) certificate_destination_associat...
teoliphant/numpy-refactor
numpy/polynomial/polytemplate.py
Python
bsd-3-clause
21,267
0.000094
""" Template for the Chebyshev and Polynomial classes. This module houses a Python string module Template object (see, e.g., http://docs.python.org/library/string.html#template-strings) used by the `polynomial` and `chebyshev` modules to implement their respective `Polynomial` and `Chebyshev` classes. It provides a m...
n self.__class__(-self.coef, self.domain) def __pos__(self) : return self def __add__(self, other) : """Returns sum""" if isinstance(other, self.__class__) : if np.all(self.domain == other.domai
n) : coef = ${nick}add(self.coef, other.coef) else : raise PolyDomainError() else : try : coef = ${nick}add(self.coef, other) except : return NotImplemented return self.__class__(coef, self.domain) d...
atlefren/beerdatabase
web/models.py
Python
mit
13,140
0
# -*- coding: utf-8 -*- import json import sqlalchemy as sa from sqlalchemy.orm import relationship from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.types import UserDefinedType from flask.ext.jsontools import JsonSerializableBase from util import ratebeer_url Base = declarative_base(cls=(Json...
nicode(255)) class RatebeerCountry(Base): __tablename__ = 'rb_countries' id = sa.Column('id', sa.Integer, primary_key=True) name = sa.Column('name', sa.Unicode(255)) class Country(Base): __tablename__ = 'countries_no' rb_id = sa.Column('rb_id', sa.Integer, primary_key=True) name = sa.Column(...
)) iso_code = sa.Column('iso_code', sa.Unicode(2)) def serialize(self, extra_data=None): serialized = { 'rb_id': self.rb_id, 'name': self.name, 'iso_code': self.iso_code } if isinstance(extra_data, dict): serialized.update(extra_data) ...
mvanorder/dosh
doshlib/commands/__init__.py
Python
mit
2,196
0.015027
import doshlib import pprint import dateutil.parser as dp def help(command): print "listdroplets" print "dropletup <droplet ID>" print "dropletdown <droplet ID>" print "dropletsnapshots <droplet ID>" def invalid(command): print "Invalid command: " + command def listdroplets(args): result = do...
['id'],i['name'],i['status']]
print("{: >10} {: >40} {: >10}".format(*row)) def rebootdroplet(command): print('not implimented yet') def dropletup(command): droplet_id = int(command.split()[1]) if doshlib.isdroplet(int(droplet_id)): status = doshlib.client.droplets.get(droplet_id)['droplet']['status'] if status == '...
morris254/polymode
Polymode/ExternalSolvers.py
Python
gpl-3.0
14,250
0.009614
# _*_ coding=utf-8 _*_ """ Solver class to interface with JCMsuite """ import os,sys,logging import Waveguide, Modes from numpy import * from .Solver import Solve class JCMWaveSolver(Solve): ''' External solver class for the JCMSuite solvers supply the project_path where the files for the solver will be ...
zorder_min = inf for shape in self.wg.shapes: if shape.material not in self.materials: material_id += 1 self.materials[shape.material]= material_id self.zorder_min = m
in(shape.zorder, self.zorder_min) return self.materials def export_wg(self, domainxy=False, sectors=None): ''' Export the internal PolyMode waveguide shapes to a JCMSuite file ''' if sectors is None: sectors = self.wg.symmetry pml_sf = 2.0 ...
smattis/BET-1
examples/parallel_and_serial_sampling/serial_serial.py
Python
gpl-3.0
927
0.001079
# Copyright (C) 2016 The BET Development Team # -*- coding: utf-8 -*- # This demonstrates how to use BET in serial to sample a serial external model. # run by calling "python serial_serial.py" import os import subprocess import scipy.io as sio import bet.sampling.basicSampling as bsam def lb_model(inp
ut_data): io_file_name = "io_file" io_mdat = dict() i
o_mdat['input'] = input_data # save the input to file sio.savemat(io_file_name, io_mdat) # run the model subprocess.call(['python', 'serial_model.py', io_file_name]) # read the output from file io_mdat = sio.loadmat(io_file_name) output_data = io_mdat['output'] return output_data my...
mvidner/cnetworkmanager
dbusclient/__init__.py
Python
gpl-2.0
6,611
0.004084
"Convenience wrappers around dbus-python" import dbus import functools # TODO rename to adaptors from func import Adaptor, MethodAdaptor, PropertyAdaptor, SignalAdaptor def object_path(o): """Return the object path of o. If o is a proxy object, use its appropriate attribute. Otherwise assume that o alre...
(because dbus.proxies.ProxyObject does not store introspection data for properties, boo. TODO.) """ iface = self.__default_interface # TODO cache # TODO _introspect_property_map pmi = dbus.Interface(self, "org.freedesktop.DBus.Properties") return pmi.Set(iface, key, valu...
"""Return a list. Tuples are made into lists, everything else a singleton list. """ if isinstance(x, list): return x elif isinstance(x, tuple): return [i for i in x] else: return [x] class DBusClient(DBusMio): """ """ _adaptors = { "methods": {}, ...
RentennaDev/partial
partial/application.py
Python
mit
1,463
0.004101
from werkzeug.exceptions import HTTPException from werkzeug.wsg
i import SharedDataMiddleware from partial import routing, scanner from partial.request import Request class Application(object): def dispatch_request(self, request): scanner.LOCAL.request = request adapter = scanner.GLOBAL['routemap'].bind_to_environ(request.environ) try: endpoint, args ...
view = cls(request) response = view.dispatch(methodName, args) del scanner.LOCAL.request return response def wsgi_app(self, environ, start_response): request = Request(environ) response = self.dispatch_request(request) request.session.save_cookie(response) ...
EmanueleCannizzaro/scons
test/WhereIs.py
Python
mit
4,794
0.005632
#!/usr/bin/env python # # Copyright (c) 2001 - 2016 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to us...
est.wr
ite(subdir_SConscript, """ env = Environment() print WhereIs('xxx.exe') print WhereIs('xxx.exe', %s) print env.WhereIs('xxx.exe', %s) print WhereIs('xxx.exe', %s) print WhereIs('xxx.exe', %s) """ % (repr(os.pathsep.join(pathdirs_1234)), repr(os.pathsep.join(pathdirs_1243)), repr(pathdirs_1234), rep...
lento/cortex
test/IECore/IgnoredExceptionsTest.py
Python
bsd-3-clause
2,674
0.032536
########################################################################## # # Copyright (c) 2010, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistribu...
promote products derived from this software without specific prior # written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS # IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICUL...
HALL THE COPYRIGHT OWNER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # L...
safwanrahman/readthedocs.org
fabfile.py
Python
mit
979
0
from fabric.api import lcd, local from fabric.decorators import
runs_once import os fabfile_dir = os.path.dirname(__file__) def i18n_push_source(): """rebuild and push the source language to transifex""" with lcd('readthedocs'): local('rm -rf rtd_tests/tests/builds/') local('django-admin makemes
sages -l en') local('tx push -s') local('django-admin compilemessages -l en') def i18n_pull(): """pull the updated translation from transifex""" with lcd('readthedocs'): local('rm -rf rtd_tests/tests/builds/') local('tx pull -f ') local('django-admin makemessages --all'...
alex-Symbroson/BotScript
BotScript/res/RaspiBot.py
Python
mit
4,428
0.007453
#!/usr/bin/python3.6 # initialized correctly ISBOT = True # object containing components objs = {} def warn(msg, type): warnings.warn(msg, type) try: import warnings, raspibot, RPi.GPIO as GPIO from serial import Serial, PARITY_EVEN from smbus import SMBus from time import sleep # creat...
2^16], [0 - 2^16], [0 - 100]) setBuzzer = objs["Attiny"].set_buzzer resetEncoders = objs["Attiny"].reset_encoders # () stopMotors = objs["Attiny"].stop_motors # ()
stopBuzzer = objs["Attiny"].stop_buzzer # () # getEncoders -> [left, right] = ([0 - 100], [0 - 100]) def getEncoders(_, opt = None): vals = objs["Attiny"].get_encoders() if opt == "raw": return vals return (vals[0]/22.5, vals[1]/22.5) # ADC def getSha...
jkonecny12/anaconda
pyanaconda/payload/dnf/__init__.py
Python
gpl-2.0
1,037
0
# # Copyright (C) 2020 Red Hat, Inc. # # 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) any later version. # This program is distributed in the hope that it will be...
o the GNU General Public # License and may only be used or replicated with the express permission of # Red Hat, Inc. # from pyanaconda.payload.dnf.payload import DNFPayload
__all__ = ["DNFPayload"]
gplayersv/pypop
pypop/example/project_to_test/tests/pageobjects/login.py
Python
gpl-2.0
533
0
import os from s
elenium.webdriver.common.by import By from pypop.pageobjects.base_page_object import PageObject from pypop.pageobjects.base_page_element import InputField, PasswordField class LoginPageObject(PageObject): '''Page object for the login page''' url = 'file:///' + os.path.dirname(__file__) + '/../../login.html' ...
btn_login = InputField(By.ID, 'btn-login') def go_to(self): self.driver.get(self.url)
lufornpy/aliyun-cli
aliyuncli/ossadp/ossHandler.py
Python
apache-2.0
88,246
0.004657
#!/usr/bin/env python #coding=utf-8 # Copyright (C) 2011, Alibaba Cloud Computing #Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to ...
ket --allow_empty_referer true --referer "referer1,referer2,...,refererN" GetBucketReferer oss://bucket GetAcl oss://bucket SetAcl oss://bucket --
acl [acl] allow private, public-read, public-read-write List oss://bucket/[prefix] [marker] [delimiter] [maxkeys] oss://bucket/[prefix] --marker xxx --delimiter xxx --maxkeys xxx MkDir oss://bucket/dirname ...
quantumlib/Cirq
cirq-core/cirq/contrib/acquaintance/shift_swap_network_test.py
Python
apache-2.0
11,590
0.00099
# Copyright 2018 The Cirq Developers # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in ...
2)) with pytest.raises(ValueError): cca.ShiftSwapNetworkGate((1, 1), (2, -3)) @pytest.mark.parametrize( 'left_part_lens,right_part_lens', [tuple(random_part_lens(2, 2) for _ in ('left', 'right')) for _ in range(5)], ) def test_shift_swap_network_gate_repr(left_part_lens, right_part_lens): gat...
t_part_lens, right_part_lens, cirq.ZZ) cirq.testing.assert_equivalent_repr(gate) @pytest.mark.parametrize( 'left_part_lens,right_part_lens', [tuple(random_part_lens(2, 2) for _ in ('left', 'right')) for _ in range(5)], ) def test_shift_swap_network_gate_permutation(left_part_lens, right_part_lens): ga...
chrisguitarguy/GuitarSocieties.org
website/urls.py
Python
bsd-3-clause
624
0.001603
# -*- coding: utf-8 -*- """ Gu
itarSocieties.org ~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2014 Christopher Davis <http://christopherdavis.me> :license: http://opensource.org/licenses/bsd-3-clause """ from django.conf.urls import patterns, include, url from django.contrib import admin from django.utils.translation import ugettext_lazy as _ admin.site.s...
admin/', include(admin.site.urls)), url(r'^', include('societies.urls', namespace='societies')), )
haoyuchen1992/CourseBuilder
modules/admin/config.py
Python
apache-2.0
13,933
0
# Copyright 2012 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 ...
configuration property.""" return SCHEMA_JSON_TEMPLATE % cls.get_value_type(config_property) def get_add_course(self): """Handles 'add_course' action and renders new course entry editor.""" exit_url = '/admin?action=courses' rest_url = CoursesItemRESTHandler.URI template_v...
se' template_values['main_content'] = oeditor.ObjectEditor.get_html_for( self, CoursesItemRESTHandler.SCHEMA_JSON, CoursesItemRESTHandler.SCHEMA_ANNOTATIONS_DICT, None, rest_url, exit_url, auto_return=True, save_button_caption='Add New Course') ...
codeforamerica/mdc-feedback
feedback/dashboard/views.py
Python
mit
18,098
0.00116
# -*- coding: utf-8 -*- import arrow import datetime import ujson import timeit from flask.ext.login import login_required from flask import ( Blueprint, render_template ) from feedback.dashboard.vendorsurveys import ( get_rating_scale, get_surveys_by_role, get_surveys_by_completion, get_surveys_by_pur...
"sms_es": "Text (Spanish)" } }, {}, {}, {}, {
}, {}, {}, {}, { "title": "Surveys by Survey Role", "data": get_surveys_by_role(survey_table) }, {}, { "title": "How many completions?", "data": get_surveys_by_completion(survey_table) }, { ...
kylejusticemagnuson/pyti
pyti/linear_weighted_moving_average.py
Python
mit
700
0.002857
from __future__ import absolute_import from pyti import catch_errors from pyti.function_helper import fill_for_noncomputable_vals from six.moves import range def linear_weighted_moving_
average(data, period): """ Linear Weighted Moving Average. Formula: LWMA = SUM(DATA[i]) * i / SUM(i) """ catch_errors.check_for_period_error(data, period) idx_period = list(range(1, period+1)) lwma = [(sum([i * idx_period[data[idx-(period-1):idx+1].index(i)] for i in data...
lwma) return lwma
fr34k8/packstack
packstack/plugins/amqp_002.py
Python
apache-2.0
9,717
0.000206
# -*- coding: utf-8 -*- """ Installs and configures amqp """ import logging impor
t uuid import os from packstack.installer import validators from packstack.installer import processors from packstack.installer import basedefs from packstack.installer import utils from packstack.modules.common import filtered_hosts from packstack.modules.ospluginutils import (getManifestTemplate, ...
endManifestFile) #------------------ oVirt installer initialization ------------------ PLUGIN_NAME = "AMQP" PLUGIN_NAME_COLORED = utils.color_text(PLUGIN_NAME, 'blue') def initConfig(controller): params = [ {"CMD_OPTION": "amqp-backend", "USAGE": ("Set the AMQP service backend. Allowed values ...
hbldh/wlmetrics
wlmetrics/data/processing.py
Python
mit
1,548
0.003876
#!/usr/bin/env python # -*- coding: utf-8 -*- """ :mod:`processing` ================== .. module:: processing :platform: Unix, Windows :synopsis: .. moduleauthor:: hbldh <henrik.blidh@nedomkull.com> Created on 2015-08-26, 14:48 """ from __future__ import division from __future__ import print_function from _...
57.2957795 sc2 = StandardCalibration.load('/home/hbldh/Dropbox/Encrypted/PyBerryIMU/.pyberryimu-BACKUP_g2') sc_sh = StandardCalibration.load('/home/hbldh/Dropbox/Encrypted/PyBerryIMU/.pyberryimu
') sc_sh.set_datasheet_values_for_gyroscope(data.client_settings) g_sc1 = [] g_sc2 = [] g_sh = [] for row in data.gyroscope: g_sc1.append(sc1.transform_gyroscope_values(row.tolist())) g_sc2.append(sc2.transform_gyroscope_values(row.tolist())) g_sh.append(sc_sh.transform_gyroscope_values(row.tolist())) d =...
techtonik/devassistant
devassistant/cli/cli_runner.py
Python
gpl-2.0
4,484
0.001561
import logging import os import sys import six try: # stdout/stdrr wrapper to render ANSI sequences in Windows import colorama colorama.init() except ImportError: pass from devassistant import actions from devassistant import bin from devassistant.cli import argparse_generator from devassistant import...
ffered way of running "{binary}".'.format(binary=binary) logger.logger.info('*' * len(msg)) logger.logger.info(msg)
logger.logger.info('*' * len(msg)) @classmethod def transform_executable_assistant_alias(cls, parsed_args): key = settings.SUBASSISTANT_N_STRING.format(0) for assistant in [bin.CreatorAssistant, bin.TweakAssistant, bin.PreparerAssistant, bin.ExtrasAssistant]: ...
mooosu/python-utils
encrypt/pkcs7.py
Python
apache-2.0
1,944
0.003086
import binascii import StringIO class PKCS7Encoder(object): ''' RFC 2315: PKCS#7 page 21 Some content-encryption algorithms assume the input length is a multiple of k octets, where k > 1, and let the application define a method for handling inputs whose lengths are not a multiple of k octets. F...
. In oth
er words, the input is padded at the trailing end with one of the following strings: 01 -- if l mod k = k-1 02 02 -- if l mod k = k-2 . . . k k ... k k -- if l mod k = 0 The padding can be removed un...
bryanforbes/Erasmus
alembic/env.py
Python
bsd-3-clause
2,487
0.000402
from __future__ import with_statement from alembic import context from sqlalchemy import engine_from_config, pool from logging.config import fileConfig from erasmus.db import db from botus_receptus.config import load from pathlib import Path # this is the Alembic Config object, which provides # access to the values w...
un_migrations() if context.is_offline_mode(): run_migrations_offline() else: run_migration
s_online()
cgqyh/pyalgotrade-mod
samples/bccharts_example_2.py
Python
apache-2.0
3,396
0.000883
from pyalgotrade import bar from pyalgotrade import strategy from pyalgotrade import plotter from pyalgotrade.technical import vwap from pyalgotrade.barfeed import csvfeed from pyalgotrade.bitstamp import broker from pyalgotrade import broker as basebroker class VWAPMomentum(strategy.BacktestingStrategy): MIN_TRA...
)) def main(plot): i
nstrument = "BTC" initialCash = 1000 vwapWindowSize = 100 buyThreshold = 0.02 sellThreshold = 0.01 barFeed = csvfeed.GenericBarFeed(bar.Frequency.MINUTE*30) barFeed.addBarsFromCSV(instrument, "30min-bitstampUSD.csv") brk = broker.BacktestingBroker(initialCash, barFeed) strat = VWAPMomen...
syrrim/werkzeug
werkzeug/_internal.py
Python
bsd-3-clause
13,953
0.001433
# -*- coding: utf-8 -*- """ werkzeug._internal ~~~~~~~~~~~~~~~~~~ This module provides internally used helpers and constants. :copyright: (c) 2014 by
the Werkzeug Team, see AUTHORS for more details. :l
icense: BSD, see LICENSE for more details. """ import re import string import inspect from weakref import WeakKeyDictionary from datetime import datetime, date from itertools import chain from werkzeug._compat import iter_bytes, text_type, BytesIO, int_to_byte, \ range_type, integer_types _logger = None _empty_s...
smc/silpa
src/silpa/modules/transliterator/cmudict.py
Python
agpl-3.0
5,575
0.071214
#! /usr/bin/env python # -*- coding: utf-8 -*- # Any Indian Language to any other Indian language transliterator # Copyright 2008-2010 Santhosh Thottingal <santhosh.thottingal@gmail.com> # http://www.smc.org.in # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Gene...
on 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 Library General Public License for more details. # # Yo...
eived a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # # If you find any bugs or have any suggestions email: santhosh.thottingal@gmail.com # URL: http://www.smc.org.in import string impo...
tekulvw/Squid-Plugins
selfbotstatus/selfbotstatus.py
Python
mit
1,817
0
import keyboard as kb import time import discord import asyncio class SelfBotStatus: def __init__(self, bot): self.bot = bot self.is_online = True self._last_time = 0 kb.hook(self.kb_press) self.status_task = None self.start = False def __unload(self): ...
st
atus=discord.Status.online, afk=False) self.is_online = True async def on_ready(self): self.start = True def setup(bot): bot.add_cog(SelfBotStatus(bot))
mjfarmer/scada_py
pymodbus/examples/common/callback-server.py
Python
gpl-3.0
5,075
0.010443
#!/usr/bin/env python ''' Pymodbus Server With Callbacks -------------------------------------------------------------------------- This is an example of adding callbacks to a running modbus server when a value is written to it. In order for this to work, it needs a device-mapping file. ''' #--------------------------...
self).__init__(values) def setValues(self, address, value):
''' Sets the requested values of the datastore :param address: The starting address :param values: The new values to be set ''' super(CallbackDataBlock, self).setValues(address, value) self.queue.put((self.devices.get(address, None), value)) #---------------------------...
hasgeek/lastuser
lastuser_ui/views/index.py
Python
bsd-2-clause
174
0
# -*- coding:
utf-8 -*- from flask import render_template from .. import lastuser_ui @lastuser_ui.route('/') def
index(): return render_template('index.html.jinja2')
jonparrott/google-cloud-python
spanner/tests/unit/test_streamed.py
Python
apache-2.0
40,891
0
# Copyright 2016 Google LLC 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...
est__merge_chunk_int64(self): iterator = _MockCancellableIterator() streamed = self._make_one(iterator) FIELDS = [ self._make_scalar_field('age', 'INT64'), ] streamed._metadata = self._make_result_set_metadata(FIELDS) streamed._pending_chunk = self._make_value...
e(streamed._pending_chunk) def test__merge_chunk_float64_nan_string(self): iterator = _MockCancellableIterator() streamed = self._make_one(iterator) FIELDS = [ self._make_scalar_field('weight', 'FLOAT64'), ] streamed._metadata = self._make_result_set_metadata(FIE...
mezz64/home-assistant
homeassistant/components/ecovacs/vacuum.py
Python
apache-2.0
6,203
0.000645
"""Support for Ecovacs Ecovacs Vaccums.""" from __future__ import annotations import logging import sucks from homeassistant.components.vacuum import ( SUPPORT_BATTERY, SUPPORT_CLEAN_SPOT, SUPPORT_FAN_SPEED, SUPPORT_LOCATE, SUPPORT_RETURN_HOME, SUPPORT_SEND_COMMAND, SUPPORT_STATUS, SU...
ssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: Discovery
InfoType | None = None, ) -> None: """Set up the Ecovacs vacuums.""" vacuums = [] for device in hass.data[ECOVACS_DEVICES]: vacuums.append(EcovacsVacuum(device)) _LOGGER.debug("Adding Ecovacs Vacuums to Home Assistant: %s", vacuums) add_entities(vacuums, True) class EcovacsVacuum(VacuumEnt...
obi-two/Rebelion
data/scripts/templates/object/mobile/shared_moncal_female.py
Python
mit
441
0.047619
#### NOTICE: THIS FILE IS A
UTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Creature() result.template = "object/mobile/shared_moncal_female.iff" result.attribute_template_id = 9 result.stfName("npc_name","moncal_ba...
male") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
voidfiles/incursion
tests/test_client.py
Python
mit
1,150
0.00087
imp
ort incursion as indb from .utils import InfluxDBClientTest class TestResponseParser(InfluxDBClientTest): def test_simple(self): self.generateData() query = indb.q('page_views').limit(None) resp = indb.get_result(query, conn=self.client) series = resp.get('page_views') ...
series = resp.get('page_views') assert len(list(series)) == 10 query = indb.q('page_views').columns(indb.count('category_id')).limit(None) resp = indb.get_result(query, conn=self.client) series = resp.get('page_views') self.assertEqual(list(series)[0].count, len(self.points))...
Dhivyap/ansible
lib/ansible/modules/network/fortios/fortios_user_security_exempt_list.py
Python
gpl-3.0
13,462
0.001931
#!/usr/bin/python from __future__ import (absolute_import, division, print_function) # Copyright 2019 Fortinet, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the Lic...
e: "present" user_security_exempt_list: d
escription: "<your_own_value>" name: "default_name_4" rule: - devices: - name: "default_name_7 (source user.device.alias user.device-group.name user.device-category.name)" dstaddr: - name: "default_name_9 (source ...
cschenck/blender_sim
fluid_sim_deps/blender-2.69/2.69/scripts/presets/tracking_camera/Canon_1D.py
Python
gpl-3.0
219
0
import bpy camera = bpy.context.edit_movieclip.tracking.camera camera.sensor
_width = 27.9 camera.units = 'MILLIMETERS' camera.focal_length = 24.0 camera.pixel_aspect =
1 camera.k1 = 0.0 camera.k2 = 0.0 camera.k3 = 0.0
jjneely/webkickstart
archive/centos5.py
Python
gpl-2.0
1,227
0.00163
#!/usr/bin/python # # centos5.py - A webKickstart module to handle changes needed from # RHEL 5 to CentOS 5 Kickstart generation. # # Copyright 2007 NC State University # Written by Jack Neely <jjneely@ncsu.edu> # # SDG # # This program is free software; you can redistribute it and/or modify # it under the...
it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. from baseRealmLinuxKickstart import baseRealmLinuxKickstart class Kickstart(baseRealmLinuxKickstart): def __init__(self, url, cfg, sc=None): baseRealmLinuxKickstart.__init__(self, url...
bewareoftheapp/fluxapp
expense/forms.py
Python
mit
749
0
from .models import Budget, Reimburse from django.forms import ModelForm class BudgetForm(ModelForm): '''Form for expense.models.Budget model.''' class Meta: # pylint: disable=missing-docstring model = Budget fields = [ 'value', 'description', ] label...
ue': 'Valor', 'description': 'Descrição' } class ReimburseForm(ModelForm): '''Form for expense.models.Reimburse model.''' class Meta: # pylint: disable=missing-docstring model = Reimburse fields = [ 'value', 'description', ]
labels = { 'value': 'Valor', 'description': 'Descrição' }
madisona/django-image-helper
image_helper/widgets.py
Python
bsd-3-clause
858
0.002331
from django.contrib.admin.widgets import AdminFileWidget from django.utils.safestring import mark_safe class AdminImagePreviewWidget(AdminFileWidget): """ An admin widget that shows a preview of currently selected image. """ def __init__(self, attrs=None, storage=None): super(AdminImagePrevie...
name, value, attrs=None, **kwargs): content = super(AdminImagePreviewWidget, self).render( name, value, attrs, **kwargs) return mark_safe(content + self._get_pre
view_tag(value)) def _get_preview_tag(self, value): if value and hasattr(value, "url"): return '<p class="file-upload current-file-preview">Current Preview:<br />' \ '<img src="{0}" style="max-width: 300px;" /></p>'.format(value.url) return ''
wwright2/dcim3-angstrom1
sources/openembedded-core/scripts/contrib/verify-homepage.py
Python
mit
2,175
0.006897
#!/usr/bin/env python # This script is used for verify HOMEPAGE. # The res
ult is influenced by network environment, since the timeout of connect url is 5 seconds as default. im
port sys import os import subprocess import urllib2 def search_bitbakepath(): bitbakepath = "" # Search path to bitbake lib dir in order to load bb modules if os.path.exists(os.path.join(os.path.dirname(sys.argv[0]), '../../bitbake/lib/bb')): bitbakepath = os.path.join(os.path.dirname(sys.argv[0])...
Clinical3PO/Platform
dev/ML-Flex/Internals/Python/DemoArffFeatureRanker.py
Python
apache-2.0
2,847
0.004917
# THIS SOURCE CODE IS SUPPLIED "AS IS" WITHOUT WARRANTY OF ANY KIND, AND ITS AUTHOR AND THE JOURNAL OF MACHINE LEARNING RESEARCH (JMLR) AND JMLR'S PUBLISHERS AND DISTRIBUTORS, DISCLAIM ANY AND ALL WARRANTIES, INCLUDING BUT NOT LIMITED TO ANY IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AN...
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 ML-Flex. If not, see <http://www.gnu.org/licenses/>. import os, sys, random def parse...
# Get lines in the file that have no comment character and are not empty fileLines = [line.strip() for line in file(filePath) if not line.startswith("%") and len(line.strip()) > 0] # Parse out only the lines that are attributes (except the class attribute) attributeLines = [line.replace("\t", " ") for line...
prasanna08/oppia
core/controllers/custom_landing_pages_test.py
Python
apache-2.0
3,649
0
# Copyright 2018 The Oppia Authors. All Rights Reserved. # # Licensed under the Apac
he 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...
erning permissions and # limitations under the License. """Tests for custom landing pages.""" from __future__ import absolute_import # pylint: disable=import-only-modules from __future__ import unicode_literals # pylint: disable=import-only-modules from core.tests import test_utils import feconf class FractionLa...
cnobile2012/inventory
inventory/regions/api/urls.py
Python
mit
1,144
0
# -*- coding: utf-8 -*- # # inventory/regions/api/urls.py # """ Reg
ion API URLs """ __docformat__ = "restructuredtext en" from django.urls import re_path
from inventory.regions.api import views urlpatterns = [ re_path(r'countries/$', views.country_list, name='country-list'), re_path(r'countries/(?P<pk>\d+)/$', views.country_detail, name='country-detail'), re_path(r'subdivisions/$', views.subdivision_list, name='subdivision-list'), ...
stickwithjosh/hypodrical
apps/podcast/migrations/0006_auto__del_field_podcast_clean__add_field_podcast_explicit__del_field_e.py
Python
mit
5,558
0.007557
# -*- 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 'Podcast.clean' db.delete_column('podcast_podcast', 'clean') # Adding field 'Podca...
[], {'max_length': '100', 'blank': 'True'}), 'contributors': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'episodes'", 'blank': 'True', 'to': "orm['podcast.Contributor']"}), 'episode_number': ('djang
o.db.models.fields.IntegerField', [], {'unique': 'True', 'blank': 'True'}), 'explicit': ('django.db.models.fields.CharField', [], {'max_length': '1', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'length': ('durationfield.db.models.field...
Royal-Society-of-New-Zealand/NZ-ORCID-Hub
orcid_api/models/credit_name.py
Python
mit
2,882
0.000694
# coding: utf-8 """ ORCID Member No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: Latest Generated by: https://github.com/swagger-api/swagger-codegen.git """ from pprint import pformat from six import iteritems import r...
ts the value
of this CreditName. :return: The value of this CreditName. :rtype: str """ return self._value @value.setter def value(self, value): """ Sets the value of this CreditName. :param value: The value of this CreditName. :type: str """ ...
vegitron/permissions_logging
permissions_logging/__init__.py
Python
apache-2.0
3,690
0.000271
""" A collection of log handlers that allow file permissions to be specified. """ import logging import logging.handlers as handlers import os import datetime class FileHandler(logging.FileHandler): """ A subclass of logging.FileHandler that accepts a permissions argument. The file used for logging will h...
For example, you could configure a handler to to have this filename: /tmp/logs/my_app-%Y-%M-%d.log """ def __init__(self, *args, **kwargs): self._originalBaseFilename = None FileHandler.__init__(self, *args, **kwargs)
def emit(self, *args, **kwargs): """ If we our open file's name no longer matches the current moment's version of the filename, close it. emit in FileHandler will open a new handle as needed. """ if self.baseFilename != self._get_current_filename(): self.clos...
linuxdeepin/deepin-translator
src/tts_interface.py
Python
gpl-3.0
4,811
0.008938
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2011 ~ 2013 Deepin, Inc. # 2011 ~ 2013 Wang Yong # # Author: Wang Yong <lazycat.manatee@gmail.com> # Maintainer: Wang Yong <lazycat.manatee@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under t...
c_lang"), False) voice_engine_names = map(lambda (name, display_name): name, voice_engines) if len(voice_engine_names) > 0: local_simple = imp.load_source("local_simple", tts_plugin.get_plugin_file(voice_engine_names[0])) return [local_simple] else: return [] ...
ig.get_trayicon_config("local_translate"): voice_engines = tts_plugin.get_voice_engines(setting_config.get_translate_config("src_lang"), False) voice_engine_names = map(lambda (name, display_name): name, voice_engines) if len(voice_engine_names) > 0: local_simple = imp.load_source("l...
AdrienVR/NaoSimulator
TPINFO/Partie3/exercice1.py
Python
lgpl-3.0
659
0.045524
#Initialisation from time import sleep from NaoCommunication import * nao=NaoControle(Nao()) # 1 - Decrire le resultat de ce
morceau de code # ... for a in range(16): if a%2==0: nao.reglerCouleur(a,a*15,50,50) else : nao.reglerCouleur(a,255,0,0) sleep(0.1) for a in range(15,-1,-1): nao.eteindreLed(a) sleep(0.1) # 2 - Decrire le resultat de ce deuxieme morceau de code # ... for a in range(15,-1,-1): nao.allumerLed...
sleep(0.1) for a in range(0,16,1): nao.eteindreLed(a) sleep(0.1) # 3 - A partir des exemples precedents, ecrire un code qui # allume alternativement les deux leds 1 seconde chacune # pendant 10 secondes.
TimSchmittmann/HamiltonSAT
competition.py
Python
mit
10,521
0.044578
import sys import subprocess import string import random import glob; import os; import shutil; from subprocess import * import resource import signal # # set the default timeout to some value # DEFAULT_TIMEOUT = 10 DEFAULT_MEMORYLIMIT = 1024*1024*1024*2 # # Set maximum CPU time to the global timeout # GLOBALTIMEO...
e solver to terminate childTimer = os.times()[2] - childTimer # print call + " " + filename + " with exitCode " + str(exitCode) + " and runtime " + str( childTimer ) + " vs " + str(timeout) os.chdir(competitionDir) # if exit code is negative, the process has been terminated by a signal (includi...
stance is considered as unsolved as well if childTimer >= timeout or (exitCode != 10 and exitCode != 20): evaFile.write("T "); sys.stdout.write("T "); states.append(0) else: # otherwise, check the returned solution # subprocess.call(["cat","/tmp/"+solver+"-"+basename+"-"+str(pid)]) c...
jashwanth9/Expert-recommendation-system
code/labels_range.py
Python
apache-2.0
806
0.008685
import json import numpy as np import cPickle as pickle
with open('../validation/v_xgboost_word_tfidf.csv') as train_file: content = train_file.readlines() testData = [] scores = [] element = content[1].strip("\r\n").split(",") for i in range(1, len(content)): element = content[i].strip("\r\n").split(",") testData.append([element[0],element[1]]) score...
dictions.append((score-minscore)/float(maxscore-minscore)) ypred = predictions with open('../validation/v_xgboost_word_tfidf_0-1.csv', 'w') as f1: f1.write('qid,uid,label\n') for i in range(0, len(ypred)): f1.write(testData[i][0]+','+testData[i][1]+','+str(ypred[i])+'\n')
okfn/hashtag-listener
app.py
Python
mit
519
0.003854
#!/usr/bin/env python import logging from os import environ from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy app = Flask(__name__) stream_handler = logging.StreamHandler() app.logger.setLevel(logging.DEBUG) app.logger.addHandler(stream_handler) app.config['SQLALCHEMY_DATABASE_URI'] = (environ.get('...
ron.get('APIKEY') db = SQLAlchemy(app) from models import *
from controllers import *