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
jdfreder/testandroid
helpguide/rich.py
Python
mit
4,830
0.003934
"""Contains RichPage class""" from __future__ import print_function from kivy.uix.listview import ListView, CompositeListItem, ListItemButton, ListItemLabel from kivy.adapters.simplelistadapter import SimpleListAdapter from kivy.uix.label import Label from kivy.uix.rst import RstDocument from kivy.uix.boxlayout import ...
self.list_view.size_hint = (1., 1.) self._richtext.col
ors['background'] = '000000' self._richtext.colors['paragraph'] = '005599' def _render_link(self, row_index, link_page_id): def _on_open(list_adapter, *args): if not isinstance(self.history, list): new_history = [self.history, self] else: ...
vkuznet/rep
rep/metaml/stacking.py
Python
apache-2.0
4,905
0.002243
""" This module contains stacking strategies (meta-algorithms of machine learning). """ from __future__ import division, print_function, absolute_import import numpy from sklearn.base import clone from ..estimators import Classifier from ..estimators.utils import check_inputs, _get_features __author__ = 'Alex Rogoz...
plit_col
umn_values, X = self._get_features(X) result = numpy.zeros([len(X), self.n_classes_]) for value, estimator in self.base_estimators.items(): mask = split_column_values == value result[mask, :] = estimator.predict_proba(X.loc[mask, :]) return result def staged_predict_...
thaim/ansible
test/units/modules/network/check_point/test_cp_mgmt_install_policy.py
Python
mit
2,564
0.00156
# 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...
s. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # f
rom __future__ import absolute_import, division, print_function __metaclass__ = type import pytest from units.modules.utils import set_module_args, exit_json, fail_json, AnsibleExitJson from ansible.module_utils import basic from ansible.modules.network.check_point import cp_mgmt_install_policy PAYLOAD = { "acce...
aferrari07/devops-aula07
src/testes_inic.py
Python
apache-2.0
355
0.028169
import jogovelha import sys erroInicializar = False jogovelha.inicializar() jogo = jogovelha.tabulei
ro() if len(jogo) != 3: erroInicializar = True else: for linha in jogo: if len(linha) != 3: erroInicializar = True else: for elemento in
linha: if elemento != '.': erroInicializar = True if erroInicializar: print('Erro!') sys.exit(1) else: sys.exit(0)
dtklein/vFense
tp/src/scripts/make_api_calls.py
Python
lgpl-3.0
650
0.003077
import requests import json import cookiel
ib url = 'https://online-demo.toppatch.com' api_version = '/api/v1' api_call = '/agents' login_uri = '/login' creds = {'username': 'admin', 'password': 'toppatch'} session = requests.session() headers = {'Content-type': 'application/json', 'Accept': 'text/plain'} jar = cookielib.CookieJar() authenticated = session.p...
henticated.ok: print 'authenticated' data = session.get(url + api_version + api_call, verify=False, headers=headers, cookies=jar) if data.ok: print json.loads(data.content)
flavio-casacurta/Nat2Py
Adabas/demo/LobDemoCenter/settings.py
Python
mit
4,386
0.013452
"""settings.py - LOB Demo Center settings file Defines databases and other resources for the operation of the LOB Demo Center (LDC) application. Note: The paramters in the settings module must adhere to the normal Python syntax otherwise errors will be reported from the interpreter $Date: 2008-08-22 19:52:28 +...
permissions and # limitations under the License. # MAXIMAGESIZE defines maximum image size # Make sure that the Adabas nuclei and NetWork use adequate parameters # for LU and NAB MAXIMAGESIZE=5100000 # MAXADATCP maximum size for ADATCP # ADATCP is currenlty limited to 999,9
99 bytes MAXADATCP=999999 # HTTP Proxy # Define the proxies to reach the outer world from within the firewall proxies={ 'http': 'http://httpprox.example.com:8080/', } noproxy=('localhost','.exa','.example.de') # List of databases that can be selected in the LDC main menu # each entry is a list of # DB...
takuan-osho/yael
yael/container.py
Python
mit
6,350
0.001102
#!/usr/bin/env python # coding=utf-8 """ The `META-INF/container.xml` file, storing: 1. the Rendition objects 2. the Rendition Mapping Document """ from yael.element import Element from yael.jsonable import JSONAble from yael.mediatype import MediaType from yael.namespace import Namespace from yael.rendition import ...
_MEDIA_TYPE) if (full_path != None) and (media_type != None): r_obj = Rendition(internal_path=full_path) r_obj.v_full_path = full_path r_obj.v_media_type = media_type # multiple renditions r_obj.v_rendition_accessmode = obj.get(Container.A_NS_ACCESSM...
obj.v_rendition_language = obj.get(Container.A_NS_LANGUAGE) r_obj.v_rendition_layout = obj.get(Container.A_NS_LAYOUT) r_obj.v_rendition_media = obj.get(Container.A_NS_MEDIA) self.renditions.append(r_obj) def _parse_link(self, obj): """ Parse the given `<link>` n...
srmcc/survival_factor_model
docs/conf.py
Python
gpl-3.0
8,651
0.006358
# -*- coding: utf-8 -*- # # Survival Factor Analysis documentation build configuration file, created by # sphinx-quickstart on Fri Feb 19 15:12:43 2016. # # 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 # autogene...
The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an
image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain ...
sk89q/Plumeria
orchard/graphviz.py
Python
mit
2,670
0.001124
"""Generate directed and non-directed graphs using Graphviz.""" import asyncio import io import os import subprocess import threading import dot_parser from dot_parser import graph_definition from pyparsing import ParseException from plumeria.command import commands, CommandError from plumeria.message import Respons...
plumeria.util.ratelimit import rate_limit lock = threading.RLock() def parse_dot_data(s): with lock: dot_parser.top_graphs = [] # Clear list of existing graphs because this module is bad parser = graph_definition
() parser.parseWithTabs() tokens = parser.parseString(s) return list(tokens) def render_dot(graph, format="png"): program = 'dot' if os.name == 'nt' and not program.endswith('.exe'): program += '.exe' p = subprocess.Popen( [program, '-T' + format], env={'SE...
oblitum/ycmd
ycmd/tests/clang/testdata/test-include/.ycm_extra_conf.py
Python
gpl-3.0
212
0.066038
import os.path def FlagsForFile( filename, **kw
args ): d = os.path.dirname( filename ) return { 'flags': [ '-iquote', os.path.join( d, 'quote' ),
'-I', os.path.join( d, 'system' ) ] }
RedHatInsights/insights-core
insights/parsers/tests/test_net_namespace.py
Python
apache-2.0
1,815
0.001102
import doctest from insights.parsers import net_namespace from insights.parsers.net_namespace import NetworkNamespace from insights.tests import context_wrap from insights.parsers import SkipException import pytest LIST_NAMESPACE = """ temp_netns temp_netns_2 temp_netns_3 """.strip() LIST_NAMESPACE_2 = """ temp_net...
netns_obj = NetworkNamespace(context_wrap(LIST_NAMESPACE)) assert netns_obj.netns_list.sort() == ['temp_netns', 'temp_netns_2', 'temp_netns_3'].sort() assert len(netns_obj.netns_list) == 3 netns_obj = NetworkNamespace(context
_wrap(LIST_NAMESPACE_2)) assert netns_obj.netns_list == ['temp_netns'] assert len(netns_obj.netns_list) == 1 netns_obj = NetworkNamespace(context_wrap(CMD_LIST_NAMESPACE)) assert netns_obj.netns_list.sort() == ['temp_netns', 'temp_netns_2', 'temp_netns_3'].sort() assert len(netns_obj.netns_list) ==...
veltzer/demos-python
src/examples/short/ftp/ftp_rmdir.py
Python
gpl-3.0
1,089
0.001837
#!/usr/bin/env python import ftplib import os.path import sys p_debug = False def ftp_rmdir(ftp, folder, remove_toplevel, dontremove): for filename, attr in ftp.mlsd(folder): if attr['type'] == 'file' and filename not in dontremove: if p_debug: print( 'rem...
ftp = ftplib.FTP(p_host) ftp.login(user=p_user, p
asswd=p_pass) # ftp_rmdir(ftp, p_dir, False, set(['.ftpquota'])) ftp_rmdir(ftp, p_dir, False, set()) ftp.quit() if __name__ == '__main__': main()
LittleRichard/sormtger
server/utils/StringUtils.py
Python
gpl-3.0
305
0
from psyco
pg2._psycopg import adapt class StringUtils(object): @staticmethod def adapt_to_str_for_orm(value): value = (value.replace('%', '') .replace(':', '') ) adapted_value = adapt(value) return adapted_value
.getquoted()[1:-1]
tusharmakkar08/SQL_PARSER
aggregate.py
Python
mit
3,641
0.043944
#!/usr/bin/env python # -*- coding: utf-8 -*- # # aggregate.py # # Copyright 2013 tusharmakkar08 <[email protected]> # # 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 vers...
k="mv "+filen+" "+newfilen os.system(k) print "------Done-----" else: k="mv "+filen+" "+newfilen os.system(k)
sreader=csv.reader(open(newfilen,"rb")) swriter=csv.writer(open("tring1.csv","wb")) j=0 for row in sreader: if j==0: ti=newattr.split(',') print ti swriter.writerow(ti) else: swriter.writerow(row) j+=1 sreader=csv.reader(open("tring1.csv","rb")) swriter=csv.writer(open(newfilen,"wb")...
lmallin/coverage_test
python_venv/lib/python2.7/site-packages/pandas/core/reshape/reshape.py
Python
mit
45,575
0.000044
# pylint: disable=E1101,E1103 # pylint: disable=W0703,W0622,W0613,W0201 from pandas.compat import range, zip from pandas import compat import itertools import re import numpy as np from pandas.core.dtypes.common import ( _ensure_platform_int, is_list_like, is_bool_dtype, needs_i8_conversion) from pandas.c...
if self.is_categorical is not None: categories = self.is_categorical.categories ordered = self.is_categorical.ordered values = [Categorical(values[:, i], categories=categories, ordered=ordered) for i in range(values.shape[...
)] return DataFrame(values, index=index, columns=columns) def get_new_values(self): values = self.values # place the values length, width = self.full_shape stride = values.shape[1] result_width = width * stride result_shape = (length, result_width) ...
kharazi/summarize
summarize/summarize.py
Python
gpl-3.0
2,018
0.000991
# -*- coding: utf-8 -*- import math from nltk.probability import FreqDist from nltk.corpus import stopwords from hazm import sent_tokenize, word_tokenize fr
om hazm import Normalizer class Summarizer(object): def __init__(self): self.normalizer = Normalizer() def summarize(self, input): self.input = self.normalizer.normalize(input) self.base_words = word_tokenize(self.input) self.working_sentences = sent_tokenize(self.input) ...
def _find_num_sentences(self): return (int(math.log(self.sentences_number) ** 2 + 1) + 1) if self.sentences_number >= 6 else self.sentences_number # return int(self.sentences_number - 0.2 * self.sentences_number) def _get_summarize(self, num_sentences): # if str(word not in stopwords.w...
theo-l/django
tests/datatypes/models.py
Python
bsd-3-clause
779
0
""" This is a basic model to test saving and loading boolean and date-related types, w
hich in the past were problematic for some database backends. """ from django.db import models class Donut(models.Model): name = models.CharField(max_length=100) is_frosted = models.BooleanField(default=False) has_sprinkles = models.BooleanField(null=True) has_sprinkles_old = models.NullBooleanField(...
d(null=True) review = models.TextField() class Meta: ordering = ('consumed_at',) class RumBaba(models.Model): baked_date = models.DateField(auto_now_add=True) baked_timestamp = models.DateTimeField(auto_now_add=True)
idlead/pydebitoor
pydebitoor/client.py
Python
mit
7,309
0
# -*- coding: utf-8 -*- import json import logging import requests from requests.exceptions import ConnectionError, HTTPError from .errors import RequestError, NotFoundError from .services import (CustomerService, InvoiceService, DraftService, TaxService) logger = logging.getLogger('pydebitoor...
elf, uri): """ Build URL from URI. Parameters ---------- uri: Ressource
identifier Returns ------- URL to query """ return '{}{}'.format(self.base_url, uri) def __make_header(self): """ Generate credential headers. Returns ------- Dict reprensenting API header with credential. """ ...
michaelgallacher/intellij-community
python/testData/inspections/PyPropertyAccessInspection/inheritedClassAttrAssignmentAndOwnWithAttrAndInheritedSlots.py
Python
apache-2.0
243
0.032922
class B(object): attr = 'baz' __slots__ = ['f', 'b'] class C
(B): __slots__ = ['attr', 'bar'] C.attr = 'spam' print(C.attr) c = C() <warning descr="'C' object attribute 'attr' is read-only">c.attr</warning> = 'spam' print(c.a
ttr)
oblique-labs/pyVM
rpython/jit/metainterp/optimizeopt/test/test_guard.py
Python
mit
12,148
0.011278
import py from rpython.jit.metainterp import compile from rpython.jit.metainterp.history import (TargetToken, JitCellToken, TreeLoop, Const) from rpython.jit.metainterp.optimizeopt.util import equaloplists from rpython.jit.metainterp.optimizeopt.vector import (Pack, NotAProfitableLoop, VectorizingOptim...
or line in instr.splitlines(): line = line.strip() if
line.startswith("#") or \ line == "": continue if line.startswith("..."): last_glob = Glob() last_glob.prev = prev_op operations.append(last_glob) continue op = parser.parse_next_op(line) ...
akiokio/centralfitestoque
src/.pycharm_helpers/pydev/pydevd_import_class.py
Python
bsd-2-clause
1,825
0.014795
#Note: code gotten from importsTipper. import sys def _imp(name, log=None): try: return __import__(name) except: if '.' in name: sub = name[0:name.rfind('.')] if log is not None: log.AddContent('Unable to import', name, 'trying with', sub) ...
#this happens in the following case: #we have mx.DateTime.mxDateTime.mxDateTime.pyd #but after importing it, mx.DateTime.mxDateTime shadows access to mxDateTime.pyd mod = getattr(mod, comp) except AttributeError: if old_comp != comp: raise ...
Zhang-RQ/OI_DataBase
BZOJ/2729.py
Python
mit
498
0.01004
# def A(n,m):
# ret=1 # while m!=0: # ret=ret*n # n-=1 # m-=1 # return ret # def mul(n): # ret=1 # while n!=1: # ret*=n # n-=1 # return ret # n,m=raw_input().split() # n=int(n) # m=int(m) # print(mul(n)*(A(n+1,2)*A(n+3,m)+2*m*(n+1)*A(n+2,m-1))) def mul(x, y): re = 1...
= int(n); m = int(m) print(mul(1,n+1)*mul(n+4-m,n+2)*(n*(n+3)+2*m))
Nitrokey/libnitrokey
unittest/test_storage.py
Python
lgpl-3.0
27,100
0.00417
""" Copyright (c) 2015-2019 Nitrokey UG This file is part of libnitrokey. libnitrokey 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 License, or any later version. libnitrokey is...
,100))) p = lambda i: hidden_volume_
password + bb(str(i)) assert C.NK_lock_device() == DeviceErrorCode.STATUS_OK assert C.NK_unlock_encrypted_volume(DefaultPasswords.USER) == DeviceErrorCode.STATUS_OK for i in range(4): assert C.NK_create_hidden_volume(i, 20+i*10, 20+i*10+i+1, p(i) ) == DeviceErrorCode.STATUS_OK for i in range(4):...
manglakaran/TrafficKarmaSent
extras/check_break.py
Python
mit
361
0.049861
import csv with open('historical_data.csv', 'rb') as
csvfile: reader = csv.DictReader(csvfile) for row in reader: if int(row["TIME"]) == 0 : save = float(row["Speed"]) else: if(float(row["Spe
ed"]) - save >= 0.1*save or -float(row["Speed"]) + save >= 0.1*save ): print row["SER"] + "->" , int(row["TIME"])-1 save = float(row["Speed"])
aakashsinha19/Aspectus
Image Segmentation/tf-image-segmentation/tf_image_segmentation/models/fcn_32s.py
Python
apache-2.0
6,382
0.004701
from nets import vgg import tensorflow as tf from preprocessing import vgg_preprocessing from ..utils.upsampling import bilinear_upsample_weights slim = tf.contrib.slim # Mean values for VGG-16
from preprocessing.vgg_preprocessing import _R_MEAN, _G_MEAN, _B_MEAN def extract_vgg_16_mapping_without_fc8(vgg_16_variables_mapping): """Removes the fc8 variable mapping from FCN-32s t
o VGG-16 model mapping dict. Given the FCN-32s to VGG-16 model mapping dict which is returned by FCN_32s() function, remove the mapping for the fc8 variable. This is done because this variable is responsible for final class prediction and is different for different tasks. Last layer usually has differen...
jmesteve/saas3
openerp/addons_extra/account_balance_reporting/account_balance_reporting_report.py
Python
agpl-3.0
22,002
0.002727
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP - Account balance reporting engine # Copyright (C) 2009 Pexego Sistemas Informáticos. All Rights Reserved # $Id$ # # This program is free software: you can redistribute it and/or modify # it...
e report objects Generic account balance report document (with header and detail lines). Designed following the needs of the Spanish/Spain localization. """ from openerp.osv import orm,fields from openerp.tools.translate import _ import re import
time import openerp.netsvc as netsvc import logging # CSS classes for the account line templates CSS_CLASSES = [('default','Default'),('l1', 'Level 1'), ('l2', 'Level 2'), ('l3', 'Level 3'), ('l4', 'Level 4'), ('l5', 'Level 5')] class account_balance_reporting(orm.Model): """ Account balance ...
corymintz/mtools
mtools/test/test_util_logevent.py
Python
apache-2.0
7,031
0.021761
import sys from nose.tools import * from mtools.util.logevent import LogEvent import time import datetime from dateutil import parser line_ctime_pre24 = "Sun Aug 3 21:52:05 [initandlisten] db version v2.2.4, pdfile version 4.5" line_ctime = "Sun Aug 3 21:52:05.995 [initandlisten] db version v2.4.5" line_iso8601_loca...
[conn10] query test.new query: { a: 1.0 } planSumma
ry: EOF ntoreturn:0 ntoskip:0 keyUpdates:0 numYields:0 locks(micros) r:103 nreturned:0 reslen:20 0ms""" line_pattern_26_b = """2014-03-18T18:34:34.360+1100 [conn10] query test.new query: { query: { a: 1.0 }, orderby: { b: 1.0 } } planSummary: EOF ntoreturn:0 ntoskip:0 keyUpdates:0 numYields:0 locks(micros) r:55 nreturn...
cogu/autosar
autosar/parser/datatype_parser.py
Python
mit
25,123
0.00617
import sys from autosar.parser.parser_base import ElementParser import autosar.datatype class DataTypeParser(ElementParser): def __init__(self,version=3.0): super().__init__(version) if self.version >= 3.0 and self.version < 4.0: self.switcher = {'ARRAY-TYPE': self.parseArrayT...
f parseBooleanType(self,root,parent=None): if self.version>=3: name=root.find("./SHORT-NAME").text dataType=autosar.datatype.BooleanDataType(name) self.parseDesc(root,dataType) return dataType def parseStringType(self,r
oot,parent=None): if self.version>=3.0: name=root.find("./SHORT-NAME").text length=int(root.find('MAX-NUMBER-OF-CHARS').text) encoding=root.find('ENCODING').text dataType=autosar.datatype.StringDataType(name,length,encoding) self.parseDesc(root...
sakhuja/cookie_lover
tests/test_models.py
Python
bsd-3-clause
1,655
0.001813
# -*- coding: utf-8 -*- """Model unit tests.""" import datetime as dt import pyt
est from cookie_flaskApp.user.models import User, Role from .factories import UserFactory @pytest.mark.usefixtures('db') class TestUser: def test_get_by_id(self): user = User('foo', '[email protected]') user.save() retrieved = User.get_by_id(user.id) assert retrieved == user def t...
t isinstance(user.created_at, dt.datetime) def test_password_is_nullable(self): user = User(username='foo', email='[email protected]') user.save() assert user.password is None def test_factory(self): user = UserFactory(password="myprecious") assert bool(user.username) ...
DanteOnline/free-art
project/free_art/item/urls.py
Python
gpl-3.0
273
0.007326
from django.conf.urls import url from item.views i
mport CategoryDetailView, ScriptDetailView urlpatterns = [ url(r'^category/(?P<pk>\d+)?$', CategoryDetailView.as_view(), name='category'), url(r'^script/(?P<pk>\d+)?$'
, ScriptDetailView.as_view(), name='script'), ]
vfonov/ITK
Wrapping/Generators/Python/Tests/getNameOfClass.py
Python
apache-2.0
3,326
0.000301
# ========================================================================== # # Copyright NumFOCUS # # 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/...
a list of classes to exclude. Typically, the classes with a custom New() # method, which return a subclass of the current class exclude = [ "ForwardFFTImageFilter", "Forward1DFFTImageFilter", "InverseFFTImageFilter", "Inverse1DFFTImageFilter", "OutputWindow", "MultiThreaderBase", "FFTComplex...
"RealToHalfHermitianForwardFFTImageFilter", "CustomColormapFunction", "ScanlineFilterCommon", # Segfault "cvar", ] wrongName = 0 totalName = 0 for t in dir(itk): if t not in exclude: T = itk.__dict__[t] # first case - that's a templated class if isinstance(T, itk.Vector.__...
pixyj/pramod.io
blog/migrations/0002_auto_20160513_1114.py
Python
mit
587
0
# -*- coding: utf-8 -*- # Generated by Django 1.9.6 on 2016-05-13 11:14 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration):
dependencies = [ ('blog', '0001_initial'), ] operations = [ migrations.RenameField( model_name='post', old_name='content', new_name='markdown_content', ), migrations.AddField( model_name='post', name='is_published', ...
), ]
mvidalgarcia/indico
indico/legacy/common/Conversion.py
Python
mit
261
0
# This file is part of Indico. # Copyright (C) 2002 - 2019 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LIC
ENSE file for more details.
from indico.util.fossilize.conversion import *
pluser/nikola_plugins
v7/less/less.py
Python
mit
4,899
0.001633
# -*- coding: utf-8 -*- # Copyright © 2012-2014 Roberto Alsina and others. # 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 t...
utils.makedirs(dst_dir) src = os.path.join(kw['cache_folder'], self.sources_folder, target) run_in_shell = sys.platform == 'win32' try: compiled = subprocess.check
_output([self.compiler_name] + self.compiler_options + [src], shell=run_in_shell) except OSError: utils.req_missing([self.compiler_name], 'build LESS files (and use this theme)', False, False) with open(dst, "wb+...
jardiacaj/finem_imperii
turn/public_order.py
Python
agpl-3.0
1,600
0
import random from unit.models import WorldUnit from world.models.geography import World, Settlement def worldwide_public_order(world: World): for tile in world.tile_set.all(): for settlement in tile.settlement_set.all(): do_settlement_public_order_update(settlement) def do_settlement_publi...
unit in non_barbarian_units: char_vm = non_barbarian_unit.owner_character.get_violence_monopoly() if char_vm == settlement_vm: public_order_contributing_units.append( non_barbarian_unit ) contributing_soldiers = sum( [unit.soldier.count() for unit in p...
ment.public_order += soldier_to_pop_ratio * 500 settlement.make_public_order_in_range() if soldier_to_pop_ratio < 0.05: settlement.public_order -= random.randint(0, 70) settlement.make_public_order_in_range() settlement.save()
Jumpscale/jumpscale6_core
apps/agentcontroller/jumpscripts/extended/system/backup_osis.py
Python
bsd-2-clause
2,202
0.003633
from JumpScale import j descr = """ Creates a targz of the backup under {var directory}/backup/osis/{timestamp}.tgz """ organization = "jumpscale" author = "[email protected]" license = "bsd" version = "1.0" category = "system.backup.osis" period = 60*60*24 enable = True async = True roles = ["admin"] queue ='i...
g', 'sessioncache']: continue outputpath = j.system.fs.joinPaths(backuppath, namespace, category) j.system.fs.createDir(outputpath) oscl.export(namespace, category, outputpath) #targz backupdir = j.system.fs.joinPaths(j.dirs.varDir, 'b...
outputpath = j.system.fs.joinPaths(backupdir, '%s.tar.gz' % timestamp) with tarfile.open(outputpath, "w:gz") as tar: tar.add(backuppath) j.system.fs.removeDirTree(backuppath) except Exception: import JumpScale.baselib.mailclient import traceback error = traceback...
rika/precip
examples/gcloud/hello-world.py
Python
apache-2.0
2,375
0.004632
#!/usr/bin/python import os import time from pprint import pprint from precip import * exp = None PROJECT = '' ZONE = 'us-central1-f' USER = 'precip' IMAGE_PROJECT = 'ubuntu-os-cloud' # look at https://cloud.google.com/compute/docs/operating-systems/linux-os IMAGE_NAME = 'ubuntu-1504-vivid-v20150422' # to list im...
and become accessible. The provision # method only starts the provisioning, and can be used to start a large # number of instances at the same time. The wait method provides a # barrier to when it is safe to start the actual experiment. exp.wait() # Print out the details of the instance. The detai...
exp.list()) # Run a command on the instances having the "test1" tag. In this case we # only have one instance, but if you had multiple instances with that # tag, the command would run on each one. exp.run(["test1"], "echo 'Hello world from a experiment instance'", USER) except ExperimentExcept...
MWers/sd-coldfusion-plugin
plugins/ColdFusion.py
Python
mit
3,975
0.000252
""" Server Density Plugin ColdFusion stats https://github.com/MWers/sd-coldfusion-plugin/ Version: 1.0.2 """ import os import platform import subprocess class ColdFusion: sd_cfstat_opt = 'coldfusion_cfstat_path' cfstat_locations = ['/opt/ColdFusion11/bin/cfstat', '/opt/coldfusi...
'g', 'Reqs TO''ed', 'Avg Q Time', 'Avg Req Time', 'Avg DB Time', 'Bytes In/s', 'Bytes Out/s'] python_version = platform.python_version_tuple() def __init__(self, agent_config, checks_logger, raw_config): s
elf.agent_config = agent_config self.checks_logger = checks_logger self.raw_config = raw_config def run(self): # Determine location of cfstat and make sure it's executable cfstat = None if 'Main' in self.raw_config and \ self.sd_cfstat_opt in self.raw...
Zolomon/reversi-ai
tests/board.py
Python
mit
7,995
0.001126
from game.board import Board from game.settings import * __author__ = 'bengt' import unittest class TestBoard(unittest.TestCase): def setUp(self): pass def test_init(self): b = Board(False) self.assertEqual(len(b.get_move_pieces(WHITE)), 0) self.assertEqual(len(b.get_move_pi...
canvas = """ a.b.c.d.e.f.g.h. 1 ................1 2 ................2 3 ......MM........3 4 ....MMWWBB......4 5 ......BBWWMM....5 6 ........MM......6 7 ................7 8 ................8 a.b.c.d.e.f.g.h.""" b.clear_moves() b.make_move((3, 2), BLACK) b.mark_moves(WHITE) resu...
..1 2 ................2 3 ....MMBBMM......3 4 ......BBBB......4 5 ....MMBBWW......5 6 ................6 7 ................7 8 ................8 a.b.c.d.e.f.g.h.""" b.clear_moves() b.make_move((2, 2), WHITE) b.mark_moves(BLACK) result = b.draw() canvas = """ a.b.c.d.e.f.g.h. 1...
LLNL/spack
var/spack/repos/builtin/packages/examl/package.py
Python
lgpl-2.1
2,255
0.004878
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class Examl(MakefilePackage): """ Exascale Maximum Likelihood (ExaML) code for phylogenetic ...
using MPI. This code implements the popular RAxML search algorithm for maximum likelihood based inference of phylogenetic trees. """ homepage = "https://github.com/stamatak/ExaML" url = "https://github.
com/stamatak/ExaML/archive/v3.0.22.tar.gz" maintainers = ['robqiao'] version('3.0.22', sha256='802e673b0c2ea83fdbe6b060048d83f22b6978933a04be64fb9b4334fe318ca3') version('3.0.21', sha256='6c7e6c5d7bf4ab5cfbac5cc0d577885272a803c142e06b531693a6a589102e2e') version('3.0.20', sha256='023681248bbc7f19821b5...
anushreejangid/csm-ut
csmpe/core_plugins/csm_node_status_check/ios_xe/plugin.py
Python
bsd-2-clause
2,529
0.000791
# ============================================================================= # asr9k # # Copyright (c) 2016, Cisco Systems # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # Redistributions o...
ARE 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 PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, ...
DENTAL, 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 LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERW...
duyet-website/api.duyet.net
lib/gensim/test/test_coherencemodel.py
Python
mit
9,464
0.006762
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2010 Radim Rehurek <ra
dimrehurek@sezna
m.cz> # Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html """ Automated tests for checking transformation algorithms (the models package). """ import logging import unittest import os import os.path import tempfile from gensim.models.coherencemodel import CoherenceModel from gensim.models.ldam...
byaka/flaskJSONRPCServer
flaskJSONRPCServer/gmultiprocessing.py
Python
apache-2.0
6,393
0.022055
# -*- coding: utf-8 -*- """ Add compatibility for gevent and multiprocessing. Source based on project GIPC 0.6.0 https://bitbucket.org/jgehrcke/gipc/ """ import os, sys, signal, multiprocessing, multiprocessing.process, multiprocessing.reduction gevent=None geventEvent=None def _tryGevent(): global gevent, gevent...
getframe(1) _globs_ = frame.f_globals if _locs_ is None:
_locs_ = frame.f_locals del frame elif _locs_ is None: _locs_ = _globs_ exec("""exec _code_ in _globs_, _locs_""") __exec("""def _reraise(tp, value, tb=None): raise tp, value, tb""")
stpettersens/sublimetext-buildtools
ApiGen/apigen_all.py
Python
mit
451
0.02439
# Wrappe
r for ApiGen All (PHP) import sys import platform import os import glob from subprocess import call def invokeApiGen(dir, out_dir): cmd = ['apigen', '--quiet', '--source', dir] if platform.system() == 'Windows': cmd[0] = 'apigen.cmd' os.chdir(
dir) for php in glob.glob('*.php'): print('ApiGen ~ Documenting PHP file: {0}'.format(php)) cmd.append('--destination') cmd.append(out_dir) call(cmd) invokeApiGen(sys.argv[1], sys.argv[2])
MangoMangoDevelopment/neptune
lib/ros_comm-1.12.0/clients/rospy/src/rospy/impl/udpros.py
Python
bsd-3-clause
11,612
0.006631
# Software License Agreement (BSD License) # # Copyright (c) 2008, Willow Garage, 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: # # * Redistributions of source code must retain the above...
nd_address(), self.port)) if self.port == 0: self.port = s.getsockname()[1] self.server = s threading.start_new_thread(self.run, ()) def run(self): buff_size = self.buff_size try: while not rospy.core.is_shutdown():
data = self.server.recvfrom(self.buff_size) print("received packet") #TODO except: #TODO: log pass def shutdown(self): if self.sock is not None: self.sock.close() def create_transport(self, topic_name, pub_uri, protocol_p...
JasperGerth/Mopidy-GPIOcont
tests/test_extension.py
Python
apache-2.0
507
0.003945
from __future__ import unicode_literals from mopidy_gpiocont im
port Extension, frontend as frontend_lib def test_get_default_config(): ext = Extension() config = ext.get_default_config() assert '[gpiocont]' in config assert 'enabled = true' in config def test_get_config_schema(): ext = Extension() schema = ext.get_config_schema() # TODO Test the...
#assert 'username' in schema #assert 'password' in schema # TODO Write more tests
jawilson/home-assistant
tests/components/balboa/test_config_flow.py
Python
apache-2.0
5,737
0.001046
"""Test the Balboa Spa Client config flow.""" from unittest.mock import patch from home
assistant import config_entries, data_entry_flow from homeassistant.components.balboa.const import CONF_SYNC_T
IME, DOMAIN from homeassistant.config_entries import SOURCE_USER from homeassistant.const import CONF_HOST from homeassistant.core import HomeAssistant from homeassistant.data_entry_flow import ( RESULT_TYPE_ABORT, RESULT_TYPE_CREATE_ENTRY, RESULT_TYPE_FORM, ) from . import BalboaMock from tests.common im...
cryptapus/electrum
electrum/gui/qt/qrcodewidget.py
Python
mit
3,675
0.003265
import os import qrcode from PyQt5.QtCore import * from PyQt5.QtGui import * import PyQt5.QtGui as QtGui from PyQt5.QtWidgets import ( QApplication, QVBoxLayout, QTextEdit, QHBoxLayout, QPushButton, QWidget) import electrum from electrum.i18n import _ from .util import WindowModalDialog class QRCodeWidget(QWidg...
vbox.addWidget(text) hbox = QHBoxLayout() hbox.addStretch(1) c
onfig = electrum.get_config() if config: filename = os.path.join(config.path, "qrcode.png") def print_qr(): p = qscreen.grabWindow(qrw.winId()) p.save(filename, 'png') self.show_message(_("QR code saved to file") + " " + filename) ...
renskiy/marnadi
marnadi/http/headers.py
Python
mit
3,678
0
import collections import itertools from marnadi.utils import cached_property, CachedDescriptor class Header(collections.Mapping): __slots__ = 'value', 'params' def __init__(self, *value, **params): assert len(value) == 1
self.value = value[0] self.params = params def __hash__(self): return hash(self.value) def __eq__(self, other): return self.value == other def __ne__(self, other): return self.value != other def __str__(self): ret
urn self.stringify() def __bytes__(self): value = self.stringify() if isinstance(value, bytes): # python 2.x return value return value.encode(encoding='latin1') def __getitem__(self, item): return self.params[item] def __iter__(self): return iter(self....
google-research/google-research
social_rl/gym_multigrid/manual_control_multiagent.py
Python
apache-2.0
3,290
0.010334
# coding=utf-8 # Copyright 2022 The Google Research 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 applicab...
ns are:') for act in env.Actions: print('\t', str(act.value) + ':', act.name) prompt = 'Enter actions for ' + str(env.n_agents) + \ ' agents separated by commas, or r to reset, or q to quit: ' # Check user input while True: user_cmd = input(prompt) if user_cmd == 'q': return False...
ommands for', len(actions), 'agents but there are', str(env.n_agents) + '. Try again?') continue valid = True for i, a in enumerate(actions): if not a.isdigit() or int(a) > max_action or int(a) < min_action: print('Uh oh, action', i, 'is invalid.') valid = False if ...
DES-SL/EasyLens
docs/conf.py
Python
mit
8,340
0.007554
# -*- coding: utf-8 -*- # # complexity 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 # autogenerated file. # # ...
ll overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct ent...
r templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = ...
gc3-uzh-ch/easybuild-framework
easybuild/tools/build_details.py
Python
gpl-2.0
2,178
0.001377
# Copyright 2014-2014 Ghent University # # This file is part of EasyBuild, # originally created by the HPC team of Ghent University (http://ugent.be/hpc/en), # with support of Ghent University (http://ugent.be/hpc), # the Flemish Supercomputer Centre (VSC) (https://vscentrum.be/nl/en), # the Hercules foundation (http:/...
timestamp', int(time_now)), ('build_time', build_time), ('install_size', det_size(app.installdir)), ('command_line', command_line), ('modules_tool', app.modules_tool.buildstats()),
]) for key, val in sorted(get_system_info().items()): buildstats.update({key: val}) return buildstats
greasypizza/grpc
src/python/grpcio/grpc_core_dependencies.py
Python
bsd-3-clause
28,918
0.000069
# Copyright 2015, 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: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the f...
omgr/tcp_client_posix.c', 'src/core/lib/iomgr/tcp_client_uv.c', 'src/core/lib/iomgr/tcp_client_windows.c', 'src/core/lib/iomgr/tcp_posix.c', 'src/core/lib/iomgr/tcp_
server_posix.c', 'src/core/lib/iomgr/tcp_server_uv.c', 'src/core/lib/iomgr/tcp_server_windows.c', 'src/core/lib/iomgr/tcp_uv.c', 'src/core/lib/iomgr/tcp_windows.c', 'src/core/lib/iomgr/time_averaged_stats.c', 'src/core/lib/iomgr/timer_generic.c', 'src/core/lib/iomgr/timer_heap.c', 'src/core/lib/iomgr/ti...
uva-its/awstools
cli/ec2_cli.py
Python
mit
912
0.004386
import argparse def processCommand(mgr, args): parser = argparse.ArgumentParser(usage='''maws ec2 <subcommand> [<args>] maws ec2 help''') parser.add_argu
ment('subcommand', help='ec2 subcommand', choices=[ 'help', 'create' ]) args = parser.parse_args(args) if args.subcommand == "help": print(""" The 'ec2' subcommand performs high-level operations on ec2 instances. Each command will update DNS entries and SimpleDB items
as needed. Sub-commands: create <name> Run a new instance for the first time launch <name> Run an instance that has been previously created and terminated rebuild <name> Terminate and re-launch and instance start <name> Restart a stopped instance stop <name> Stop a running instance reconcile Up...
MaxVanDeursen/tribler
Tribler/Test/Core/Modules/RestApi/test_downloads_endpoint.py
Python
lgpl-3.0
14,983
0.005273
import json import os from binascii import hexlify from urllib import pathname2url from Tribler.Core.DownloadConfig import DownloadStartupConfig from Tribler.Core.Utilities.network_utils import get_random_port from Tribler.Test.Core.Modules.RestApi.base_api_test import AbstractApiTest from Tribler.Test.common import U...
Equal(self.session.get_downloads()[0].get_def().get_name(), 'Unknown name') post_data = {'uri': 'magnet:?xt=urn
:btih:%s' % (hexlify(UBUNTU_1504_INFOHASH))} expected_json = {'started': True, 'infohash': 'fc8a15a2faf2734dbb1dc5f7afdc5c9beaeb1f59'} return self.do_request('downloads', expected_code=200, request_type='PUT', post_data=post_data, expected_json=expected_json).addCallback(v...
portnov/assethub
assethub/assets/email.py
Python
bsd-3-clause
1,412
0.001416
from django.core.mail import send_mail from notifications.signals import notify from django_comments.models import Comment events_registry = [] class Event(object): model = None parent = None verb = None @staticmethod def get_email_subject(instance, parent, actor, recipient): raise NotIm...
"""Should return a tuple: (template name, context) """ raise NotImplementedError @staticmethod def is_user_subscribed(recipient): raise NotImplementedError
@staticmethod def register(event): global events_registry events_registry.append(event) @staticmethod def get(model, parent, verb): global events_registry for event in events_registry: model_ok = event.model is None or model == event.model paren...
mkieszek/jobsplus
jobsplus_recruitment/jp_project.py
Python
agpl-3.0
1,475
0.019661
# -*- coding: utf-8 -*- """ Created on Tue Jul 9 12:06:12 2013 @author: mbereda """ from openerp.osv import fields, osv from openerp.tools.translate import _ import pdb class jp_project(osv.Model): _name = 'jp.project' _description = 'Project' _columns = { 'project_from' : fields.date('From'), 'pro...
orzono nowy projekt") body = _("Utworzono nowy projekt dla deal'a: %s<br/><a href='%s'>Link do deal'a</a>")%(project.deal_id.title, url) self.pool.get('jp.deal').message_post(cr, uid, project.deal_id.id, body=body, subject=subject, type='email', subtype='mail.mt_comment', ...
return project_id
peshay/tpm
tpm.py
Python
mit
32,755
0.000916
#! /usr/bin/env python """Team Password Manager API To simplify usage of Team Password Manager API. You can authenticate with username and password >>> import tpm >>> URL = "https://mypasswordmanager.example.com" >>> USER = 'MyUser' >>> PASS = 'Secret' >>> tpmconn = tpm.TpmApiv5(URL, username=USER...
tion to Team Password Manager.""" class ConfigError(Exception): """To throw Exception based on wrong Settings.""" def __init__(self
, value): self.value = value log.critical(value) def __str__(self): return repr(self.value) def __init__(self, api, base_url, kwargs): """init thing.""" # Check if API version is not bullshit REGEXurl = "^" \ "(?:(?:https?)://)...
Caoimhinmg/PmagPy
programs/foldtest.py
Python
bsd-3-clause
6,056
0.024108
#!/usr/bin/env python from __future__ import division from __future__ import print_function from builtins import input from builtins import range from past.utils import old_div import sys import numpy import matplotlib if matplotlib.get_backend() != "TKAgg": matplotlib.use("TKAgg") import pylab import pmagpy.pmag as...
test -u ANGLE (circular standard deviation) for uncertainty on bedding po
les -b MIN MAX bounds for quick search of percent untilting [default is -10 to 150%] -n NB number of bootstrap samples [default is 1000] -fmt FMT, specify format - default is svg -sav save figures and quit INPUT FILE Dec Inc Dip_Direction Dip in space delimited file OUTPUT P...
ctsit/nacculator
nacc/uds3/np/builder.py
Python
bsd-2-clause
5,859
0
############################################################################### # Copyright 2015-2020 University of Florida. All rights reserved. # This file is part of UF CTS-IT's NACCulator project. # Use of this source code is governed by the license found in the LICENSE file. #######################################...
np.NPBNKE = record['npbnke'] np.NPBNKF = record['npbnkf'] np.NPBNKG = rec
ord['npbnkg'] np.NPFAUT = record['npfaut'] np.NPFAUT1 = record['npfaut1'] np.NPFAUT2 = record['npfaut2'] np.NPFAUT3 = record['npfaut3'] np.NPFAUT4 = record['npfaut4'] packet.append(np) update_header(record, packet) return packet def update_header(record, packet): for header in pac...
willzhang05/postgrestesting1
postgrestesting1/lib/python3.5/site-packages/django/db/models/fields/related.py
Python
mit
114,783
0.002004
from __future__ import unicode_literals import
warnings from operator import attrgetter from django import forms from django.apps import apps from django.core import checks, exceptions from django.core.exceptions import FieldDoesNotExist from django.db import connection, connections, router, transaction from django.db.backends import utils from django.db.models i...
from django.db.models.deletion import CASCADE, SET_DEFAULT, SET_NULL from django.db.models.fields import ( BLANK_CHOICE_DASH, AutoField, Field, IntegerField, PositiveIntegerField, PositiveSmallIntegerField, ) from django.db.models.lookups import IsNull from django.db.models.query import QuerySet from django.db....
ulikoehler/UliEngineering
tests/Utils/TestZIP.py
Python
apache-2.0
411
0.012165
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import io from numpy.testing import assert_approx_equ
al, assert_allclose, assert_array_equal from UliEngineering.Utils.ZIP import * from UliEngineering.Utils.Temporary import * import unittest class TestFileUtils(unittest.TestCase): def setUp(self): self.tmp = AutoDeleteTempfileGenerator() def create_zip_from_directory(self):
pass #TODO
Jgarcia-IAS/SAT
openerp/addons-extra/odoo-pruebas/odoo-server/addons/stock/wizard/stock_return_picking.py
Python
agpl-3.0
8,537
0.002811
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
@param cr: A database cursor @param uid: ID of the user currently logged in @param ids: List of ids selected @param context: A standard dictionary @return: A dictionary which of fields with values. """ new_picki
ng_id, pick_type_id = self._create_returns(cr, uid, ids, context=context) # Override the context to disable all the potential filters that could have been set previously ctx = { 'search_default_picking_type_id': pick_type_id, 'search_default_draft': False, 'search_def...
thelabnyc/django-oscar-api-checkout
src/oscarapicheckout/email.py
Python
isc
229
0
from oscar.core.loading import get_class OrderPlacementMixin = get
_class("checkout.mixins", "OrderPlacementMixin") class OrderMessageSender(OrderPlacementMixin): def __init__(self, request): self.request = request
DrSkippy/Gnacs
acscsv/acscsv.py
Python
bsd-2-clause
13,140
0.011948
#!/usr/bin/env python # -*- coding: UTF-8 -*- __author__="Scott Hendrickson" __license__="Simplified BSD" import sys import datetime import fileinput from io import StringIO # Experimental: Use numba to speed up some fo the basic function # that are run many times per record # from numba import jit # use fastest optio...
d the fix_length() method in _Field class # could be combined? #TODO: set limit=None by default and just return as many as there are, otherwise (by specifying # limi
t), return a maximum of limit. # TODO: # - consolidate _LimitedField() & fix_length() if possible def __init__(self, json_record, limit=1): self.fields = None super( _LimitedField , self).__init__(json_record) # self.value is possibly a list of dicts for ea...
johnlb/strange_wp
strange_bak/document.py
Python
gpl-3.0
28,054
0.000071
# coding: utf-8 """ weasyprint.document ------------------- :copyright: Copyright 2011-2014 Simon Sapin and contributors, see AUTHORS. :license: BSD, see LICENSE for details. """ from __future__ import division, unicode_literals import io import math import shutil import functools ...
_y, border_height) matrix = cairo.Matrix() matrix.translate(origin_x, origin_y) for name, args in box.style.transform: if name == 'scale': matrix.scale(*args) elif name == 'rotate': matrix.rotate(args) elif name == 'tr...
nslate( percentage(translate_x, border_width), percentage(translate_y, border_height), ) else: if name == 'skewx': args = (1, 0, math.tan(args), 1, 0, 0) elif name == 'skewy': ...
hzengin/openvpn-config-splitter
lib/constants.py
Python
apache-2.0
598
0.025084
defaultFileNames = { "caCert": "ca.crt", "userCert":
"user.crt", "privateKey": "private.key", "tlsAuth": "tls.key", "configOutput": "client.new.ovpn",
} parserMatchers = { "caCert": "<ca>([\s\S]*?)<\/ca>", "userCert": "<cert>([\s\S]*?)<\/cert>", "privateKey": "<key>([\s\S]*?)<\/key>", "tlsAuth": "<tls-auth>([\s\S]*?)<\/tls-auth>", } keyDirMatcher = "key-direction\s+([10])" textToInsertRefs = { "caCert": "ca", "userCert": "cert", "privat...
tony-rasskazov/meteo
weewx/bin/user/installer/amphibian/install.py
Python
mit
1,727
0.002316
# $Id: install.py 1169 2014-12-07 14:39:20Z mwall $ # installer for amphibian # Copyright 2014 Matthew Wall from setup import ExtensionInstaller def loader(): return AmphibianInstaller() class AmphibianInstaller(ExtensionInstaller): def __init__(self): super(AmphibianInstaller, self).__init__( ...
'skins/amphibian/year-table.html.tmpl', 'skins/amphibian/year.html.tmp
l']), ] )
bp-kelley/rdkit
rdkit/Chem/MolDb/FingerprintUtils.py
Python
bsd-3-clause
3,612
0.001384
# $Id$ # # Copyright (C) 2009 Greg Landrum # All Rights Reserved # import pickle from rdkit import Chem, DataStructs similarityMethods = { 'RDK': DataStructs.ExplicitBitVect, 'AtomPairs': DataStructs.IntSparseIntVect, 'TopologicalTorsions': DataStructs.LongSparseIntVect, 'Pharm2D': DataStructs.SparseBitVect...
ngerprintAsIntVect(mol) fp._sumCache = fp.GetTotalVal() return fp def BuildTorsionsFP(mol): from rdkit.Chem.AtomPairs import Torsions fp = Torsions.GetTopologicalTorsionFingerprintAsIntVect(mol) fp._sumCache = fp.GetTo
talVal() return fp def BuildRDKitFP(mol): return Chem.RDKFingerprint(mol, nBitsPerHash=1) def BuildPharm2DFP(mol): global sigFactory from rdkit.Chem.Pharm2D import Generate try: fp = Generate.Gen2DFingerprint(mol, sigFactory) except IndexError: print('FAIL:', Chem.MolToSmiles...
jmesteve/saas3
openerp/addons/account/wizard/account_report_account_balance.py
Python
agpl-3.0
1,729
0.001735
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
report_name': 'account.account.balance', 'datas': data} # vim:expandtab:smartindent:
tabstop=4:softtabstop=4:shiftwidth=4:
jeremyosborne/python
scope/scope.py
Python
mit
548
0.005474
""" Python expresses functional and modular scope
for variables. """ # Global to the module, not
global in the builtin sense. x = 5 def f1(): """If not local, reference global. """ return x def f2(): """Local references global. """ global x x = 3 return x # Should print 5. print f1() # Should print 3. print f2() # Should print 3. print x # When done, open the python interpreter ...
gimunu/mopidy-lcdplate
mopidy_lcdplate/__init__.py
Python
apache-2.0
1,698
0.003534
from __future__ import unicode_literals import logging import os # TODO: Remove entirely if you don't register GStreamer elements below import pygst pygst.require('0.10') import gst import gobject from mopidy import config, ext __version__ = '0.1.0' # TODO: If you need to log, use loggers named after the current ...
self): conf_file = os.path.join(os.path.dirname(__file__), 'ext.conf') return config.read(conf_file) def get_config_schema(self): schema = super(Extension, self).get_config_schema() # TODO: Comment in and edit, or remove entirely #schema['username'] = config.String() ...
y only implement one of the following things # in a single extension. # TODO: Edit or remove entirely from .frontend import FoobarFrontend registry.add('frontend', FoobarFrontend) # TODO: Edit or remove entirely from .backend import FoobarBackend registry.add('b...
turbokongen/home-assistant
homeassistant/components/homekit/type_switches.py
Python
apache-2.0
7,993
0.001126
"""Class to hold all switch accessories.""" import logging from pyhap.const import ( CATEGORY_FAUCET, CATEGORY_OUTLET, CATEGORY_SHOWER_HEAD, CATEGORY_SPRINKLER, CATEGORY_SWITCH, ) from homeassistant.components.switch import DOMAIN from homeassistant.components.vacuum import ( DOMAIN as VACUUM_...
"""Reset switch to emulate activate click.""" _LOGGER.debug("%s: Reset switch t
o off", self.entity_id) if self.char_on.value is not False: self.char_on.set_value(False) def set_state(self, value): """Move switch state to value if call came from HomeKit.""" _LOGGER.debug("%s: Set switch state to %s", self.entity_id, value) if self.activate_only and ...
ekaputra07/wpcdesk
wpcdesk/wpcdesk_threads.py
Python
gpl-3.0
3,754
0.00293
# -*- coding: utf-8 -*- # wpcdesk - WordPress Comment Desktop # Copyright (C) 2012 Eka Putra - [email protected] # # 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 t...
_error_msg) else: comments_num = len(comments) self.status_updated.emit('%s comments received.' % str(comments_num)) self.response_received.emit(comments) self.is_loading.emit(False) class EditCommentThread(BaseCommentThread):
""" Edit single comment """ is_loading = QtCore.pyqtSignal(bool) is_success = QtCore.pyqtSignal(bool) def set_data(self, data): self.data = data def set_comment_id(self, comment_id): self.comment_id = comment_id def run(self): self.get_connection() self.is_lo...
pythontech/ptscrape
ptscrape.py
Python
lgpl-2.1
2,668
0.003373
#======================================================================= # Screen-scraping framework #======================================================================= import logging try: import bs4 as soup except ImportError: import BeautifulSoup as soup import urllib2 from urllib import urlencode ...
request on a URL with optional query''' _log.info('POST %s', url) data = '' if query: data = urlencode(query) return self._transact(url, data, tag=tag) def _transact(self, url, data=None, tag=None): '''Perform an HTTP request, or fetch page from cache''' ...
if self.replay: content = self.read_cache(tag) else: doc = self.agent.open(url, data) _log.info('info %r', doc.info()) content = doc.read() if self.cachedir: self.write_cache(tag, content) doc = soup.BeautifulSoup(content) ...
DONIKAN/django
tests/defer/tests.py
Python
bsd-3-clause
11,262
0.000533
from __future__ import unicode_literals from django.db.models.query_utils import DeferredAttribute, InvalidQuery from django.test import TestCase from .models import ( BigChild, Child, ChildProxy, Primary, RefreshPrimaryProxy, Secondary, ) class AssertionMixin(object): def assert_delayed(self, obj, num): ...
"p1", "a new name", ], lambda p: p.name, ordered=False, ) def test_defer_baseclass_when_subclass_has_no_added_fields(self): # Regression for #10572 - A subclass with no extra fields can defer # fields from the base class Child.objects....
ld.objects.defer("value").get(name="c1") self.assert_delayed(obj, 1) self.assertEqual(obj.name, "c1") self.assertEqual(obj.value, "foo") def test_only_baseclass_when_subclass_has_no_added_fields(self): # You can retrieve a single column on a base class with no fields Child.o...
freakboy3742/pyxero
xero/__init__.py
Python
bsd-3-clause
59
0
from .api import Xero # NOQA: F401 __version_
_ = "0.9
.3"
ashang/calibre
src/calibre/devices/mtp/defaults.py
Python
gpl-3.0
1,629
0.006139
#!/usr/bin/env python2 # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:fdm=marker:ai from __future__ import (unicode_literals, division, absolute_import, print_function) __license__ = 'GPL v3' __copyright__ = '2012, Kovid Goyal <kovid at kovidgoyal.net>' __docformat__ = 'restructuredtext en' ...
matches = True for k, v in tests.iteritems(): if k == 'vendor' and v != vid: matches = False break if k == 'product' and v != pid: matches = False break
if matches: return rule[1] return {}
Alberto-Beralix/Beralix
i386-squashfs-root/usr/lib/python2.7/dist-packages/papyon/service/AddressBook/scenario/contacts/check_pending_invite.py
Python
gpl-3.0
107
0.018692
../../../../../../../../share/pyshared/papyon/service/AddressBook/scenario/contac
ts/check_pen
ding_invite.py
geofrenzy/utm-mbsb
ros-src/catkin_ws/build/catkin_generated/order_packages.py
Python
apache-2.0
323
0.003096
# generat
ed from catkin/cmake/template/order_packages.context.py.in source_root_dir = "/opt/geofrenzy/src/catkin_ws/src" whitelisted_packages = "".split(';') if "" != "" else [] blacklisted_packages = "".split(';') if "" != "" else [] underlay_workspaces = "/opt/ros/kinetic".split(';') if "/opt/ros/kinetic" !
= "" else []
doduytrung/odoo-8.0
openerp/addons/base/ir/ir_model.py
Python
agpl-3.0
61,894
0.006301
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Business Applications # Copyright (C) 2004-2014 OpenERP S.A. (<http://openerp.com>). # # This program is free software: you can redistribute it and/or modify # it under the terms ...
field_name, arg, context=None): #pseudo-method used by fields.function in ir.model/ir.model.fields module_pool = self
.pool["ir.module.module"] installed_module_ids = module_pool.search(cr, uid, [('state','=','installed')]) installed_module_names = module_pool.read(cr, uid, installed_module_ids, ['name'], context=context) installed_modules = set(x['name'] for x in installed_module_names) result = {} xml_ids = osv....
Napoleon314/Venus3D
generate_projects.py
Python
mit
1,373
0.020393
import os, sys, multiprocessing, subprocess from build_util import * if __name__ == "__main__": cfg = cfg_from_argv(sys.argv) bi = build_info(cfg.compiler, cfg.archs, cfg.cfg) print("Starting build project: " + build_cfg.project_name + " ...") additional_options = "-DCFG_PROJECT_NAME:STRING=\"%s\"" % build_cfg.pr...
" -DCFG_BUILD_PATH:STRING=\"%s\"" % build_cfg.build_path additional_options += " -DCFG_DEPENDENT_PATH:STRING=\"%s\"" % build_cfg.dependent_path additional_options += " -DCFG_DOCUMENT_PATH:STRING=\"%s\"" % build_cfg.document_path additional_options += " -DCFG_EXTERN
AL_PATH:STRING=\"%s\"" % build_cfg.external_path additional_options += " -DCFG_INCLUDE_PATH:STRING=\"%s\"" % build_cfg.include_path additional_options += " -DCFG_SOURCE_PATH:STRING=\"%s\"" % build_cfg.source_path additional_options += " -DCFG_TEST_PATH:STRING=\"%s\"" % build_cfg.test_path additional_options += " -D...
DavideTonin99/pygameoflife
main.py
Python
mit
7,534
0.006769
""" Simulation of Game of
Life with pygame Instructions: Press ESC or F4 to quit the game Press RETURN to restart the game Press SPACE to stop or resume the game Press "p" or "+" to zoom in Press "m" or "-" to zoom out Press one of the letter below to change the color of the aliv
e cells: - r: red - b: blue - g: green - c: cyan - w: white When the game is stopped, you can click and move the mouse to select new cells """ import numpy as np import pygame import random from pygame.locals import * __author__ = "Davide Tonin" game_ended = False game_stop = False board_changed =...
apache/libcloud
libcloud/test/dns/test_buddyns.py
Python
apache-2.0
6,194
0.000646
# 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 ...
t_zones() sel
f.assertEqual(zones, []) def test_list_zones_success(self): BuddyNSMockHttp.type = "LIST_ZONES" zones = self.driver.list_zones() self.assertEqual(len(zones), 2) zone = zones[0] self.assertEqual(zone.id, "microsoft.com") self.assertIsNone(zone.type) self.ass...
francocurotto/GraphSLAM
src/python-helpers/v3-real-data/data/Parque OHiggins/OHigginsRaw2g2o.py
Python
gpl-3.0
3,023
0.005624
# imports import shlex import math def ohigginsRaw2g2o(infoOdomPos, infoOdomAng, infoPointSen, dataDir, dataSkip, dataSize): # filenames inDeadReckon = dataDir + "deadReckoning.dat" inMeasurement = dataDir + "measurement.dat" outG2O = dataDir + "ohiggins.g2o" fg2o = open(outG2O, 'w') ...
) a1 = float(odomWords[4]) x2 = float(nextWords[2]) y2 = float(nextWords[3]) a2 = float(nextWords[4]) dx = (x2 - x1)*math.cos(a1) + (y2 - y1)*math.sin(a1) dy = -(x2 - x1)*math.sin(a1) + (y2 - y1)*math.cos(a1) ...
(dx) + " " + str(dy) + " " + str(dt) + " " + str(infoOdomPos) + " 0 0 " + str(infoOdomPos) + " 0 " + str(infoOdomAng) + "\n") count = count+1 # measurements measLine = measurements[j] measWords = shlex.split(measLine) odomTime = float(odomW...
staranjeet/fjord
vendor/packages/translate-toolkit/translate/storage/versioncontrol/darcs.py
Python
bsd-3-clause
4,465
0.002912
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2004-2008,2012 Zuza Software Foundation # # This file is part of translate. # # translate 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 vers...
ir, "-a"] exitcode, output_pull, error = run_command(command) if exitcode != 0: raise IOError("[Darcs] error running
'%s': %s" % (command, error)) return output_revert + output_pull def add(self, files, message=None, author=None): """Add and commit files.""" files = prepare_filelist(files) command = ["darcs", "add", "--repodir", self.root_dir] + files exitcode, output, error = run_command...
neuront/pyjhashcode
jhashcode/__init__.py
Python
mit
594
0.003367
import sys def _unknown_hash(_): raise TypeError('Unsupported
type') def hash_str_unicode(s): h = 0 for c in s: h = (31 * h + ord(c)) & 0xFFFFFFFF return ((h + 0x80000000) & 0xFFFFFFFF) - 0x80000000 def hash_int(i): return i if int(sys.version[0]) > 2: _TP_MAPPING = { bytes: hash_str_unicode, str: hash_str_unicode, int: has...
(o): return _TP_MAPPING.get(type(o), _unknown_hash)(o)
jn2840/bitcoin
contrib/devtools/fix-copyright-headers.py
Python
mit
1,492
0.015416
#!/usr/bin/env python ''' Run this script inside of src/ and it will look for all the files that
were changed this year that still have the last year in the copyright headers, and it will fix the headers on that file using a perl regex one liner. For example: if it finds something like this and we're in 2014 // Copyright (c) 2009-2013 The Beardcoi
n Core developers it will change it to // Copyright (c) 2009-2014 The Beardcoin Core developers It will do this for all the files in the folder and its children. Author: @gubatron ''' import os import time year = time.gmtime()[0] last_year = year - 1 command = "perl -pi -e 's/%s The Beardcoin/%s The Beardcoin/' %s...
sebastiandev/pyragraph
filters/words.py
Python
mit
595
0.003361
# -*- coding: utf-8 -*- from .base import Filter, skip_empty_data, ensure_list_input class
StopWordFilter(Filter): """ Filters stop words from the input tokens. Input is expected to be a list """ def __init__(self, stopwords, next_filter=None): super(StopWordFilter, self).__init__(next_filter) self._stopwords = set(stopwords)
# sets lookup works as a dict and makes search time O(1) @skip_empty_data(default=[]) @ensure_list_input def _apply_filter(self, tokens): return [t for t in tokens if t not in self._stopwords]
EliotBerriot/trax
trax/users/apps.py
Python
mit
270
0
from django.apps import AppConfig class UsersConfig(AppConfig): name = 'trax.users' verbose_name = "Users" def ready(self): """Override this to put in:
Users system checks Users signal registration """ p
ass
nickedes/Ni-Algos
Practice/Hr/Data Structures/Stack/Game of two stacks.py
Python
gpl-2.0
567
0
def scoring(a, b, n, m, x): i, j, sumNum = 0, 0, 0 while i < n and (sumNum+a[i]) <= x: sumN
um += a[i] i += 1 ans = i while j < m and i >= 0: sumNum += b[j] j += 1 while sumNum > x and i > 0: i -= 1 sumNum -= a[i] if sumNum <= x and i+j > ans: ans = i+j return ans g = int(input()) for i in range(g): n, m, x = list(m...
m, x))
pwollstadt/IDTxl
demos/demo_active_information_storage.py
Python
gpl-3.0
591
0
# Im
port classes from idtxl.active_information_storage import ActiveInformationStorage from idtxl.data import Data # a) Generate test data data = Data() data.generate_mute_data(n_samples=1000, n_replications=5) # b) Initialise analysis object and define settings network_analysis = ActiveInformationStorage() settings = {'...
yse_network(settings=settings, data=data) # d) Plot list of processes with significant AIS to console print(results.get_significant_processes(fdr=False))
openairproject/sensor-esp32
bin/firmware_installer.py
Python
gpl-3.0
655
0.035115
1. ask for UART NAME 2. make TEMP_DIR git clone https://github.com/espressif/esptool.git -o TEMP_DIR 3. TEMP_DIR/esptool.py --port /dev/tty.SLAB_USBtoUART --after no_reset chip_id 4. fetc
h https://openairproject.com/ota/index.txt to TEMP_DIR parse first line fetch binaries to TEMP_DIR test sha 5. fetch partitions_two_ota.bin fetch bootloader.bin 6. python TEMP_DIR/esptool.py --chip esp32 --port /dev/tty.SLAB_USBtoUART --baud 921600 --before default_reset --after hard_reset write_flash -u --flash_mod...
--flash_freq 40m --flash_size detect 0x1000 TEMP_DIR/bootloader.bin 0x10000 TEMP_DIR/sensor-esp32.bin 0x8000 TEMP_DIR/partitions_two_ota.bin
morpheby/levelup-by
common/djangoapps/course_modes/tests/factories.py
Python
agpl-3.0
397
0.002519
from course_modes.mode
ls import CourseMode from factory import DjangoModelFactory # Factories don't have __init__ methods, and are self documenting # pylint: disable=W0232 class CourseModeFactory(DjangoModelFactory): FACTORY_FOR = CourseMode course_id = u'MITx/999/Robot_Super_Course' mode_slug = 'audit' mode_display_name =...
course' min_price = 0 currency = 'usd'
aliparsai/LittleDarwin
utils/NullExperiment/CompareMutantDatabases.py
Python
gpl-3.0
1,279
0.002346
import os import sys import shelve import random import math import scipy.stats.stats class MutantResults(object): def __init__(self, sourceDatabase, resultsDatabase): # self.resultsDatabase = shelve.open(resultsDatabase, "r") try: self.resultsDatabase = shelve.open(resultsDatabase, "r...
esultsDatabase[
c] if len(survivedList) + len(killedList) > 0: score = float(len(killedList)) / float(len(survivedList) + len(killedList)) else: score = None return score def calculateCoverageForType(self, t): pass if __name__ == "__main__": pass
CollabQ/CollabQ
vendor/django/contrib/contenttypes/views.py
Python
apache-2.0
2,734
0.001463
from django import http from django.contrib.contenttypes.models import ContentType from django.contrib.sites.models import Site from django.core.exceptions import ObjectDoesNotExist def shortcut(request, content_type_id, object_id): "Redirect to an object's page based on a content-type ID and an object ID." # ...
if object_domain is not None: break # Next, look for a many-to-one relationship to Site. if object_domain is None: for field in obj._meta.fields: if field.rel and field.rel.to is Site: try: object_domain = getattr(obj, field.name).domai...
f object_domain is not None: break # Fall back to the current site (if possible). if object_domain is None: try: object_domain = Site.objects.get_current().domain except Site.DoesNotExist: pass # If all that malarkey found an object domain, use i...
Neitsch/ASE4156
authentication/migrations/0005_auto_20171011_1314.py
Python
apache-2.0
616
0.001623
# -*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2017-10-
11 13:14 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('authentication', '0004_userbank_institution_name'), ] operations = [ migr...
=django.db.models.deletion.CASCADE, related_name='userbank', to=settings.AUTH_USER_MODEL), ), ]
mementum/bfplusplus
bfplusplus/guimods/mainframe/onsizesash.py
Python
gpl-3.0
1,795
0.004457
#!/usr/bin/env python # -*- coding: latin-1; py-indent-offset:4 -*- ################################################################################ # #
This file is part of Bfplusplus # # Bfplusplus is a graphical interface to the Betfair Betting Exchange # Copyright (C) 2010 Daniel Rodriguez (aka Daniel Rodriksson) # Copyright (C) 2011 Sensible Odds Ltd. # # You can learn more and contact the author at: # # http://code.google.com/p/bfplusplus/ # # Bfplusplus is f...
are: 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. # # Bfplusplus is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; withou...
exiahuang/SalesforceXyTools
xlsxwriter/chart_pie.py
Python
apache-2.0
6,168
0
############################################################################### # # ChartPie - A class for writing the Excel XLSX Pie charts. # # Copyright 2013-2016, John McNamara, [email protected] # from warnings import warn from . import chart class ChartPie(chart.Chart): """ A class for writing the Exc...
ite_layout(self.plotarea.get('layout'), 'plot') # Write the subclass chart type element. self._write_chart_type(None) self._xml_end_tag('c:plotArea') def _write_legend(self): # Over-ridden method to add <c:txPr> to legend. # Write the <c:legend> element. position ...
(self.legend_delete_series is not None and type(self.legend_delete_series) is list): delete_series = self.legend_delete_series if position.startswith('overlay_'): position = position.replace('overlay_', '') overlay = 1 allowed = { 'right'...
jeffleary00/greenery
potnanny/apps/room/api.py
Python
bsd-2-clause
1,520
0.001974
from flask import Blueprint, request, url_for, jsonify from flask_restful import Api, Resource from flask_jwt_extended import jwt_required from potnanny_core.models impo
rt Room from .schemas import RoomSchema from potnanny.crud import CrudInterface bp = Blueprint('room_api', __name__, url_prefix='/api/1.0/rooms') api = Api(bp) ifc = CrudInterface(Room, RoomSchema) class RoomListApi(Resource): # @jwt_required def get(self): ser, err, code = ifc.get()
if err: return err, code return ser, code # @jwt_required def post(self): data, errors = RoomSchema().load(request.get_json()) if errors: return errors, 400 ser, err, code = ifc.create(data) if err: return err, code re...