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
USStateDept/FPA_Core
openspending/model/dimension.py
Python
agpl-3.0
20,686
0.00116
from sqlalchemy.schema import Column from sqlalchemy.types import Integer from sqlalchemy.sql.expression import select, func from openspending.core import db from openspending.model.attribute import Attribute from openspending.model.common import TableHandler, ALIAS_PLACEHOLDER from openspending.model.constants import...
d['key'] = self.name d['name'] = self.name return d def has_attribute(self, attribute): """ Check whether an instance has a given attribute. This methods exposes the hasattr for parts of OpenSpending
where hasattr isn't accessible (e.g. in templates) """ return hasattr(self, attribute) class GeomTimeAttribute(Dimension, Attribute): """ A simple dimension that does not create its own values table but keeps its values directly as columns on the facts table. This is somewhat un...
open-machine-learning/mldata-utils
ml2h5/converter/basehandler.py
Python
gpl-3.0
11,241
0.006939
import os, h5py, numpy from scipy.sparse import csc_matrix import ml2h5.task from ml2h5 import VERSION_MLDATA from ml2h5.converter import ALLOWED_SEPERATORS class BaseHandler(object): """Base handler class. It is the base for classes to handle different data formats. It implicitely handles HDF5. @c...
where if not h5py.is_hdf5(self.fname): return h5 = h5py.File(self.fname, 'r') contents = { 'name': h5
.attrs['name'], 'comment': h5.attrs['comment'], 'mldata': h5.attrs['mldata'], } if contents['comment']=='Task file': contents['task']=dict() contents['ordering']=list() group='task' for field in ml2h5.task.task_data_fields: ...
kohr-h/odl
examples/solvers/proximal_lang_tomography.py
Python
mpl-2.0
2,158
0
"""Tomography with TV regularization using the ProxImaL solver. Solves the optimization problem min_{0 <= x <= 1} ||A(x) - g||_2^2 + 0.2 || |grad(x)| ||_1 Where ``A`` is a parallel beam forward projector, ``grad`` the spatial gradient and ``g`` is given noisy data. """ import numpy as np import odl import prox...
- x)] # Solve the problem using ProxImaL prob = proximal.Problem(funcs) prob.s
olve(verbose=True) # Convert back to odl and display result result_odl = reco_space.element(x.value) result_odl.show('ProxImaL result', force_show=True)
yejianye/microblog
asura/conf/dev.py
Python
mit
170
0
SQLALCHEMY
_DATABASE_URI = 'mysql+pymysql://root@localhost:3306/microblog' SQLALCHEMY_TRACK_MODIFICATIONS = False REDIS_HOST = 'loca
lhost' REDIS_PORT = 6379 DEBUG = False
annahs/atmos_research
sqlite_test.py
Python
mit
1,520
0.028289
import sqlite3 from datetime import datetime from pprint import pprint import sys import numpy as np conn = sqlite3.connect('C:/projects/dbs/SP2_data.db') c = conn.cursor() #sp2b_file TEXT, eg 20120405x001.sp2b #file_index INT, #instr TEXT, eg UBCSP2, ECSP2 #instr_locn TEXT, eg WHI, DMT, POLAR6 #parti...
#c.execute('''ALTER TABLE SP2_coating_analysis ADD COLUMN FF_fit_function TEXT''') #c.execute('''ALTER TABLE SP2_coating_analysis ADD COLUMN zeroX_to_LEO_limit FLOAT''') #c.execute('''CREATE INDEX SP2_coating_analysis_index1 ON SP2_coating_analysis(instr,instr_locn,par
ticle_type,unix_ts_utc,unix_ts_utc,FF_gauss_width,zeroX_to_peak)''') #c.execute('''SELECT * FROM SP2_coating_analysis''') c.execute('''DELETE FROM SP2_coating_analysis WHERE instr=? and instr_locn=? and particle_type=?''', ('UBCSP2', 'POLAR6','nonincand' )) #names = [description[0] for description in c.description] #...
leppa/home-assistant
tests/components/yessssms/test_notify.py
Python
apache-2.0
12,228
0.001063
"""The tests for the notify yessssms platform.""" import logging import unittest from unittest.mock import patch import pytest import requests_mock from homeassistant.components.yessssms.const import CONF_PROVIDER import homeassistant.components.yessssms.notify as yessssms from homeassistant.const import CONF_PASSWOR...
fy", level="ERROR"): self.yessssms.send_message(message) self.assertTrue(mock.called) self.assertEqual(mock.call_count, 2) def test_error_account_suspended_2(self): """Test login that fails after multiple attempts.""" message = "Testing YesssSMS platform :)" # py...
ms.notify", level="ERROR" ) as context: self.yessssms.send_message(message) self.assertIn("Account is suspended, cannot send SMS.", context.output[0]) @requests_mock.Mocker() def test_send_message(self, mock): """Test send message.""" message = "Testing YesssSMS plat...
looprock/Megaphone
sample_service.py
Python
isc
1,823
0.016456
#!/usr/bin/env python import json import sys import os from bottle import route, run, get import time import httplib server = "127.0.0.1" statport = "18081" host = "%s:18001" % server staturl = "http://%s:%s/status" % (server,statport) blob = {"id": "bar", "url": staturl} data = json.dumps(blob) connection = httplib...
ovy!", "Unknown": "Unknown error!", "Warning": "Houstin, I think we have a warning!", "Critical": "Danger Will Rogers! Danger!" } t = len(sys.argv) if t < 2: usage() sys.exit(1) else: statusm = sys.argv[1] t = time.localtime() ts = time.strftime('%Y-%m-%dT%H:%M:%S%Z', t) rootdir = "./" ...
s.path.insert(0, root) # generate nested python dictionaries, copied from here: # http://stackoverflow.com/questions/635483/what-is-the-best-way-to-implement-nested-dictionaries-in-python class AutoVivification(dict): """Implementation of perl's autovivification feature.""" def __getitem__(self, item):...
vermouth1992/Leetcode
python/594.longest-harmonious-subsequence.py
Python
mit
1,636
0.014059
# # @lc app=leetcode id=594 lang=python3 # # [594] Longest Harmonious Subsequence # # https://leetcode.com/problems/longest-harmonious-subsequence/description/ # # algorithms # Easy (51.44%) # Total Accepted: 97.9K # Total Submissions: 190.2K # Testcase Example: '[1,3,2,2,5,2,3,7]' # # We define a harmonious array ...
en an integer array nums, return the length of its longest harmonious # subsequence among all its possible subsequences. # # A subsequenc
e of array is a sequence that can be derived from the array by # deleting some or no elements without changing the order of the remaining # elements. # # # Example 1: # # # Input: nums = [1,3,2,2,5,2,3,7] # Output: 5 # Explanation: The longest harmonious subsequence is [3,2,2,2,3]. # # # Example 2: # # # Input:...
chen0031/nupic
tests/unit/nupic/encoders/random_distributed_scalar_test.py
Python
agpl-3.0
19,698
0.004315
#!/usr/bin/env python # ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2013, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions ...
self.assertGreater(len(encoder.bucketMap), 23,
"Number of buckets is not 2") self.assertEqual(e25.sum(), 23, "Number of on bits is incorrect") self.assertEqual(e25.size, 500, "Width of the vector is incorrect") self.assertLess(computeOverlap(e0, e25), 4, "Overlap is too high") # Test encoding consistency. The encodings for previous num...
nlproc/splunkml
bin/nlcluster.py
Python
apache-2.0
4,186
0.029384
#!env python import os import sys sys.path.append( os.path.join( os.environ.get( "SPLUNK_HOME", "/opt/splunk/6.1.3" ), "etc/apps/framework/contrib/splunk-sdk-python/1.3.0", ) ) from collections import Counter, OrderedDict from math import log from nltk import tokenize import execnet import json from splunkl...
umber(str): try: n = float(str)
return True except ValueError: return False need_sim = args['alg'] in {'affinity_propagation','spectral'} if records: records = np.array(records) input = None # StringIO.StringIO() X = None # sp.lil_matrix((len(records),len(fields))) for i, record in enumerate(records): nums = [] strs = [] fo...
ahye/FYS2140-Resources
examples/plotting/plot_initial.py
Python
mit
964
0.018672
#!/usr/bin/env python """ Created on Mon 2 Dec 2013 Plotter grunntilstanden for en harmonisk oscillator. @author Benedicte Emilie Brakken """ from numpy import * from matplotlib.pyplot import * # Kun for aa teste omega = 1 # [rad / s] # Fysiske parametre hbarc = 0.1973 # [MeV pm] E0p = 938.27 ...
sk oscillator. ''' A = ( E0p * omega / ( pi * hbarc * c ) )**0.25 B = exp( - E0p * omega / ( 2 * hbarc * c) * x**2 ) return A * B # Henter funksjonsverdier og lagrer i arrayen Psi Psi = Psi0(x) # Lager et nytt figurvindu figure() # Plotter x mot Psi0 plot( x, abs( Psi )**2 ) # Tekst langs x-aksen xl...
st langs y-aksen ylabel('$|\Psi_0 (x, 0)|^2$ [1/pm]') # Tittel paa plottet title('Grunntilstanden for harmonisk oscillator') # Viser det vi har plottet show()
mhbu50/erpnext
erpnext/regional/france/utils.py
Python
gpl-3.0
222
0.018018
# Copyright (c) 2018, Fra
ppe Technologies and contributors # For license information, please see license.txt # don't remove this function it
is used in tests def test_method(): '''test function''' return 'overridden'
mozman/ezdxf
src/ezdxf/entities/view.py
Python
mit
5,728
0.000698
# Copyright (c) 2019-2022, Manfred Moitzi # License: MIT License from typing import TYPE_CHECKING import logging from ezdxf.lldxf import validator from ezdxf.lldxf.attributes import ( DXFAttr, DXFAttributes, DefSubclass, XType, RETURN_DEFAULT, group_code_mapping, ) from ezdxf.lldxf.const import...
processor.simple_dxfattribs_loader(dxf, acdb_view_group_codes) # type: ignore return dxf def export_entity(self, tagwriter: "TagWriter") -> None: super().export_entity(tagwriter) if tagwriter.dxfversion > DXF12: tagwriter.write_tag2(SUBCLASS_MARKER, acdb_symbol_table_record....
tagwriter, [ "name", "flags", "height", "width", "center", "direction", "target", "focal_length", "front_clipping", "back_clipping", ...
opennode/nodeconductor-openstack
src/waldur_openstack/openstack_tenant/extension.py
Python
mit
1,984
0.000504
from waldur_core.core import WaldurExtension class OpenStackTenantExtension(WaldurExtension): class Settings: # wiki: https://opennode.atlassian.net/wiki/display/WD/OpenStack+plugin+configuration WALDUR_OPENSTACK_TENANT = { 'MAX_CONCURRENT_PROVISION': { 'OpenStackTenan...
: (), }, 'openstacktenant-schedule-snapshots': { 'task': 'openstack_tenant.ScheduleSnapshots', 'schedule': timedelta(minutes=10), 'args': (), }, 'openstacktenant-delete-expired-snapshots': { 'task': 'op
enstack_tenant.DeleteExpiredSnapshots', 'schedule': timedelta(minutes=10), 'args': (), }, 'openstacktenant-set-erred-stuck-resources': { 'task': 'openstack_tenant.SetErredStuckResources', 'schedule': timedelta(minutes=10), ...
bigswitch/nova
nova/objects/instance_numa_topology.py
Python
apache-2.0
8,588
0.000116
# Copyright 2014 Red Hat Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
NOTE(sahid): Used as legacy, could be renamed in # _legacy_to_dict_ to the future to avoid confusing. return {'cpus': hardware.format_cpu_spec(self.cpuset, allow_ranges=False), 'mem': {'total': self.memory}, 'id': self.id, ...
ata_dict): # NOTE(sahid): Used as legacy, could be renamed in # _legacy_from_dict_ to the future to avoid confusing. cpuset = hardware.parse_cpu_spec(data_dict.get('cpus', '')) memory = data_dict.get('mem', {}).get('total', 0) cell_id = data_dict.get('id') pagesize = data...
pierre-haessig/sysdiag
sysdiag.py
Python
mit
21,428
0.007049
#!/usr/bin/python # -*- coding: utf-8 -*- """ sysdiag Pierre Haessig — September 2013 """ from __future__ import division, print_function def _create_name(name_list, base): '''Returns a name (str) built on `base` that doesn't exist in `name_list`. Useful for automatic creation of subsystems or wires ...
f __repr__(self): cls_name = self.__class__.__name__ s = "{:s}('{.name}')".format(cls_name, self) return s
def __str__(self): s = repr(self) if self.parent: s += '\n Parent: {:s}'.format(repr(self.parent)) if self.params: s += '\n Parameters: {:s}'.format(str(self.params)) if self.ports: s += '\n Ports: {:s}'.format(str(self.ports)) if self.sub...
realer01/aiohttp-debugtoolbar
aiohttp_debugtoolbar/panels/middlewares.py
Python
apache-2.0
1,143
0
from .base import DebugPanel from ..utils import STATIC_ROUTE_NAME __all__ = ['MiddlewaresDebugPanel'] class MiddlewaresDebugPanel(DebugPanel): """ A panel to display the middlewares used by your aiohttp application. """ name = 'Middlewares' has_content = True template = 'middlewares.jinja2' ...
f __init__(self, request): super().__init__(request) if not request.app.middlewares: self.has_content = False self.is_active = False else: self.populate(request) def populate(self, request): middleware_names = [] for m in request.app.middl...
middleware_names.append(m.__repr__()) self.data = {'middlewares': middleware_names} def render_vars(self, request): static_path = self._request.app.router[STATIC_ROUTE_NAME]\ .url(filename='') return {'static_path': static_path}
s-i-newton/clang-hook
lib_hook/filter.py
Python
apache-2.0
1,601
0.004372
"""Filters allows to match the output against a regex and use the match for statistic purpose.""" import re import typing from lib_hook.auto_number import AutoNumber from .stage import Str_to_stage, Stage class InvalidStage(Exception): """A filter was applied at a wrong stage.""" pass class FilterMode(Aut...
f search(self, output: str, stage: Stage) -> typing.Union[bool, int, float, str, None]: """Looks for a match in the given string and returns the match. If the filter does not match, return None.""" if stage not in self.stages: return None match = self.regex.search(output)
if match is None: return None if self.mode == FilterMode.Groups: return self.type(match.group(self.group)) return self.type(match.group(0))
YilunZhou/Klampt
Python/demos/gltemplate.py
Python
bsd-3-clause
1,532
0.02611
#!/usr/bin/python import sys from klampt import * from klampt.vis import GLSimulationProgram class MyGLViewer(GLSimulationProgram): def __init__(self,files): #create a world from the given files world = WorldModel() for fn in files: res = world.readFile(fn) if not r...
,dy): return GLSimulationProgram.motionfunc(self,x,y,dx,dy) if __name__ == "__main__": print "gltemplate.py: This example demonstrates how to simulate a world and read user input" if len(sys.argv)<=1: print "USAGE: gltemplate.py [world_file]" exit() viewer = MyGLViewer(sys.argv[1:]...
er.run()
craws/OpenAtlas-Python
openatlas/views/types.py
Python
gpl-2.0
4,440
0
from typing import Any, Dict, List, Union from flask import abort, flash, g, render_template, url_for from flask_babel import format_number, lazy_gettext as _ from werkzeug.utils import redirect from werkzeug.wrappers import Response from openatlas import app from openatlas.database.connect import Transaction from op...
ity in Node.get_untyped(hierarchy.id): table.rows.append([ link(entity), entity.class_.label, entity.
first, entity.last, entity.description]) return render_template( 'table.html', entity=hierarchy, table=table, crumbs=[ [_('types'), url_for('node_index')], link(hierarchy), _('untyped entities')])
eblur/dust
astrodust/distlib/__init__.py
Python
bsd-2-clause
67
0
from .sizedist im
port * from .WD01 import make_WD01_DustSpectr
um
nddsg/SimpleDBMS
simple_dbms/table_iterator.py
Python
gpl-3.0
9,205
0.000869
from relation_iterator import RelationIterator from true_expression import TrueExpression from operation_status import OperationStatus from data_input_stream import DataInputStream from insert_row import InsertRow from column import Column import simple_dbms class TableIterator(RelationIterator, object): """ ...
t the specified index in the relation that this iterator iterates over. The leftmost column has an index of 0. :param col_index: :return: the column """ return self.table.get_column(col_index) def get_column_val(self, col_index): """ Gets the value of the co...
dex in the row on which this iterator is currently positioned. The leftmost column has an index of 0. This method will unmarshall the relevant bytes from the key/data pair and return the corresponding Object -- i.e., an object of type String for CHAR and VARCHAR values, an obje...
victal/ulp
test/test_urlextract.py
Python
mit
1,212
0.00495
from ulp.urlextract import escape_ansi, parse_input import os TEST_DIR = os.path.dirname(os.path.realpath(__file__)) def test
_parse_no_url_input(): assert len(parse_input("")) == 0 multiline_text = """ text without URLs and multiple lines """ assert len(parse_input(multiline_text)) == 0 def test_extract_one_url(): with open(os.path.join(TEST_DIR, 'example_bitbucket.txt')) as f: result = parse_input(f...
1 assert result[0] == 'https://bitbucket.org/owner/repository/pull-requests/new?source=BRANCH&t=1' def test_extract_multiple_urls_per_line(): input_text = """ two urls https://example.org/?q=1 https://example.org/?p=2 on the same line""" result = parse_input(input_text) assert len(resul...
WilliamMarti/gitlistener
gitlistener.py
Python
mit
1,001
0.02997
from flask import Flask from flask import request from subprocess import call import git, json, os, sys newname = "gitlistener" from ctypes import cdll, byref, create_string_buffer libc = cdll.LoadLibrary('libc.so.6') #Loading a 3rd party library C buff = create_string_buffer(len(newname)+1) #Note: One larger ...
hod == 'POST': repo = git.Repo('/var/www/lunch_app') print repo.git.status(
) print repo.git.pull() f = open("keyfile.txt") pw = f.read() os.popen("sudo service apache2 reload", "w").write(pw) else: print "Wrong" return "Ran" if __name__ == "__main__": app.run(host='0.0.0.0',port=5001)
pedrohml/smartbot
smartbot/joke_behaviour.py
Python
mit
2,199
0.005462
# coding: utf-8 from smartbot import Behaviour from smartbot import Utils from smartbot import ExternalAPI import re import os import random class JokeBehaviour(Behaviour): def __init__(self, bot): super(JokeBehaviour, self).__init__(bot) self.language = self.bot.config.get('main', 'language') if...
r(lambda c: len(re.split('\W+', c, re.MULTILINE)) < 200, jokes) jokes = sorted(jokes, lambda x, y: len(x) - len(y)) if jokes: joke = jokes[0] audioFile = ExternalAPI.textToSpeech(joke, language=self.language, encode='mp3') if os.path.exists(audioFi...
self.bot.sendAudio(chat_id=update.message.chat_id, audio=audioFile, performer=self.bot.getInfo().username) else: self.bot.sendMessage(chat_id=update.message.chat_id, text=u'Não consigo contar') else: self.bot.sendMessage(chat_id=update.message.chat_id, te...
1337/yesterday-i-learned
leetcode/172e.py
Python
gpl-3.0
222
0
class Solution: d
ef trailingZeroes(self, n: int) -> int: powers_of_5 = [] for i in range(1, 10): powers_of_5.append(5 ** i) return su
m(n // power_of_5 for power_of_5 in powers_of_5)
Azure/azure-sdk-for-python
sdk/network/azure-mgmt-network/azure/mgmt/network/v2020_04_01/models/_models.py
Python
mit
848,302
0.003644
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
] :ivar etag: A unique read-only string that changes whenever the resource is updated. :vartype etag: str :param zones: A list of availability zones denoting where the resource needs to come fro
m. :type zones: list[str] :param identity: The identity of the application gateway, if configured. :type identity: ~azure.mgmt.network.v2020_04_01.models.ManagedServiceIdentity :param sku: SKU of the application gateway resource. :type sku: ~azure.mgmt.network.v2020_04_01.models.ApplicationGatewaySk...
steventimberman/masterDebater
venv/lib/python2.7/site-packages/haystack/backends/elasticsearch2_backend.py
Python
mit
14,291
0.003149
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals import datetime from django.conf import settings from haystack.backends import BaseEngine from haystack.backends.elasticsearch_backend import ElasticsearchSearchBackend, ElasticsearchSearchQuery from haystack.c...
limit_to_registered_models, result_class=result_class) filters = [] if start_offset is not None: kwargs['from'] = start_offset if e...
narrow_queries = set() if facets is not None: kwargs.setdefault('aggs', {}) for facet_fieldname, extra_options in facets.items(): facet_options = { 'meta': { '_type': 'terms', }, 't...
alfredodeza/merfi
merfi/backends/rpm_sign.py
Python
mit
5,502
0.000364
from time import sleep import os import shutil import merfi from merfi import logger from merfi import util from merfi.collector import RepoCollector from merfi.backends import base class RpmSign(base.BaseBackend): help_menu = 'rpm-sign handler for signing files' _help = """ Signs files with rpm-sign. Crawls ...
for path in repo.releases: self.sign_release(path) # Public key: if self.keyfile: logger.info('placing release.asc in %s' % repo.path) if merfi.config.get('check'):
logger.info('[CHECKMODE] writing release.asc') else: shutil.copyfile( self.keyfile, os.path.join(repo.path, 'release.asc')) def sign_release(self, path): """ Sign a "Release" file from a Debian repo. "...
appsembler/mayan_appsembler
fabfile/platforms/linux.py
Python
gpl-3.0
922
0.004338
import os from fabric.api import run, sudo, cd, env, task, settings from ..literals import FABFILE_MARKER def delete_mayan(): """ Delete Mayan EDMS files from an Linux system """ sudo('rm %(virtualenv_path)s -Rf' % env) def install_mayan(): """ Install Mayan EDMS on an Linux system ...
'virtualenv --no-site-packages %(virtualenv_name)s' % env) with cd
(env.virtualenv_path): sudo('git clone git://github.com/rosarior/mayan.git %(repository_name)s' % env) sudo('source bin/activate; pip install --upgrade distribute') sudo('source bin/activate; pip install -r %(repository_name)s/requirements/production.txt' % env) def post_install(): """ ...
cisco-openstack/tempest
tempest/cmd/workspace.py
Python
apache-2.0
9,103
0
# Copyright 2016 Rackspace # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, s...
e) workspace_path = se
lf.workspaces.pop(name) self._write_file() return workspace_path @lockutils.synchronized('workspaces', external=True) def remove_workspace_directory(self, workspace_path): self._validate_path(workspace_path) shutil.rmtree(workspace_path) @lockutils.synchronized('workspaces'...
Psycojoker/wanawana
events/emails.py
Python
gpl-3.0
2,656
0.006401
from django.core.mail import send_mail from django.template.loader import render_to_string from wanawana.utils import get_base_url def send_admin_link_on_event_creation(request, event): if not event.admin_email: return email_body = render_to_string("emails/new_event.txt", { "url_scheme": req...
email_body, "noreply@%s" % get_base_url(request), [event.admin_email]) def send_admin_notification_for_new_comme
nt(request, event, comment): if not event.admin_email or not event.send_notification_emails: return email_body = render_to_string("emails/event_for_admin_new_comment.txt", { "url_scheme": request.META["wsgi.url_scheme"], "base_url": get_base_url(request), "event": event, ...
bnjones/Mathics
mathics/core/characters.py
Python
gpl-3.0
43,648
0
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals # Character ranges of letters letters = 'a-zA-Z\u00c0-\u00d6\u00d8-\u00f6\u00f8-\u0103\u0106\u0107\ \u010c-\u010f\u0112-\u0115\u011a-\u012d\u0131\u0141\u0142\u0147\u0148\ \u0150-\u0153\u0158-\u0161\u0164\u0165\u016e-\u0171\u017d\u01...
uF817\uF818\uF819\uF81A\uF81B\uF81C\uF81D\ \uF81E\uF81F\uF820\uF821\uF822\uF823\uF824\uF825\uF826\uF827\uF828\uF829\ \uF82A\uF82B\uF82C\uF82D\uF82E\uF82F\uF830\uF831\uF832\uF833\uFE35\uFE36\ \uFE37\uFE38' # All supported longname characters named_characters = { 'AAcute': '\u00E1', 'ABar': '\u0101', 'ACup':...
: '\u00E0', 'AHat': '\u00E2', 'Aleph': '\u2135', 'AliasDelimiter': '\uF764', 'AliasIndicator': '\uF768', 'AlignmentMarker': '\uF760', 'Alpha': '\u03B1', 'AltKey': '\uF7D1', 'And': '\u2227', 'Angle': '\u2220', 'Angstrom': '\u212B', 'ARing': '\u00E5', 'AscendingEllipsis': '...
yast/yast-python-bindings
examples/PatternSelector-empty.py
Python
gpl-2.0
722
0.01385
# encoding: utf-8 # Simple example for Patt
ernSelector from yast import import_module import_module('UI') from yast import * class PatternSelectorEmptyClient: def main(self): if not UI.HasSpecialWidget("PatternSelector"): UI.OpenDialog( VBox( Label("Error: This UI doesn't support the PatternSelector widget!"), ...
UI.UserInput() UI.CloseDialog() return UI.OpenDialog(Opt("defaultsize"), PatternSelector(Id("selector"))) input = UI.RunPkgSelection(Id("selector")) UI.CloseDialog() ycpbuiltins.y2milestone("Input: %1", input) PatternSelectorEmptyClient().main()
super3/PyDev
Class/IsoGame/main.py
Python
mit
2,825
0.044248
# Name: Main.py # Author: Shawn Wilkinson # Imports from random import choice # Welcome Message print("Welcome to the Isolation Game!") # Make Board board = [['' for col in range(4)] for row in range(4)] # Print Board Functin def show(): # Tmp
string tmpStr = "" # Loop through board tmpStr += "\nBoard:" tmpStr += "\n-------------------------\n" for x in range(4): for y in range(4): if board[x][y] == '': tmpStr += " |" else: tmpStr += str( board[x][y] ) + "|" tmpStr += "\n-------------------------\n" # Return tmp string print(tmpStr) ...
x' player = 'o' break elif isXO == 'o': ai = 'o' player = 'x' break else: print("Invalid choice. Try again.") # Loop For First State while 1: firstPlay = input("Do I got first ('y' or 'n')? ") if firstPlay == 'y': playBool = True break elif firstPlay == 'n': playBool = False break else: p...
Toilal/mailinabox
tools/mail.py
Python
cc0-1.0
4,331
0.027938
#!/usr/bin/python3 import sys, getpass, urllib.request, urllib.error, json def mgmt(cmd, data=None, is_json=False): # The base URL for the management daemon. (Listens on IPv4 only.) mgmt_uri = 'http://127.0.0.1:10222' setup_key_auth(mgmt_uri) req = urllib.request.Request(mgmt_uri + cmd, urllib.parse.urlencode(d...
", { "email": sys.argv[3] })) elif sys.argv[1] == "user" and sys.argv[2] in ("make-admin", "remove-admin") and len(sys.argv) == 4: if sys.argv[2] == "make-admin": action = "add" else: action = "remove" print(mgmt("/mail/user
s/privileges/" + action, { "email": sys.argv[3], "privilege": "admin" })) elif sys.argv[1] == "user" and sys.argv[2] == "admins": # Dump a list of admin users. users = mgmt("/mail/users?format=json", is_json=True) for domain in users: for user in domain["users"]: if "admin" in user['privileges']: print(use...
oxc/Flexget
flexget/plugins/output/rapidpush.py
Python
mit
6,452
0.00124
from __future__ import unicode_literals, division, absolute_import from builtins import * # pylint: disable=unused-import, redefined-builtin import logging from requests import RequestException from flexget import plugin from flexget.event import event from flexget.utils import json from flexget.utils.template impo...
except RenderError as e: log.error('Error setting RapidPush category: %s' % e) group = entry.get('group', config['group']) try: group = entry.render(group) except RenderError as e: log.error('Error sett...
'title': title, 'message': message, 'priority': priority, 'category': category, 'group': group}) data = {'apikey': apikey, 'command': 'notify', 'data': data_string} else: channel = confi...
dtrodrigues/nifi-minifi-cpp
docker/test/integration/minifi/core/RemoteProcessGroup.py
Python
apache-2.0
353
0
import uuid class RemoteProcessGroup(object): def __init__(self, url, name=Non
e): self.uuid = uuid.uuid4() if name is None: self.name = str(self.uuid) else: self.name = n
ame self.url = url def get_name(self): return self.name def get_uuid(self): return self.uuid
scheib/chromium
third_party/blink/web_tests/external/wpt/service-workers/service-worker/resources/update-claim-worker.py
Python
bsd-3-clause
661
0.001513
import time script = u''' // Time stamp: %s // (This ens
ures the source text is *not* a byte-for-byte match with any // previously-fetc
hed version of this script.) // This no-op fetch handler is necessary to bypass explicitly the no fetch // handler optimization by which this service worker script can be skipped. addEventListener('fetch', event => { return; }); addEventListener('install', event => { event.waitUntil(self.skipWaiting()); }...
TheWardoctor/Wardoctors-repo
script.stargate.guide/ResizeLogos.py
Python
apache-2.0
1,738
0.010357
import xbmc import xbmcgui import xbmcaddon import xbmcvfs from PIL import Image, ImageOps ADDON = xbmcaddon.Addon(id = 'script.stargate.guide') def autocrop_image(infile,outfile): infile = xbmc.translatePath(infile) image = Image.open(infile) border = 0 size = image.size bb_image = image bbox...
quit() new_path = d.browse(0, 'Destination Logo Folder', 'files', '', False, False,'special://home/') if not new_path or old_path == new_path: quit() dirs, files = xbmcvfs.listdir(old_path) p = xbmcgui.DialogProgressBG() p.create('TVGF', 'Processing Logos') images = [f for f in files if f.endswith('.png')] total...
ges: infile = old_path+f outfile = new_path+f autocrop_image(infile,outfile) percent = 100.0 * i / total i = i+1 p.update(int(percent),"TVGF",f) p.close()
Partoo/scrapy
scrapy/contrib_exp/iterators.py
Python
bsd-3-clause
1,404
0.000712
from scrapy.http import Response from scrapy.selector import Selector def xml
iter_lxml(obj, nodename, namespace=None, prefix='x'): from lxml import etree reader = _StreamReader(obj) tag = '{%s}%s' % (namespace, nodename) if namespace else nodename iterable = etree.iterparse(reader, tag=tag, encoding=reader.encoding) selxpath = '//' + ('%s:%s' % (prefix, nodename) if namespac...
xs.register_namespace(prefix, namespace) yield xs.xpath(selxpath)[0] class _StreamReader(object): def __init__(self, obj): self._ptr = 0 if isinstance(obj, Response): self._text, self.encoding = obj.body, obj.encoding else: self._text, self.encoding = obj...
hasgeek/hasjob
instance/testing.py
Python
agpl-3.0
602
0
import os #: The title of this site SITE_TITLE = 'Job
Board' #: Database backend SQLALCHEMY_DATABASE_URI = 'postgresql:///hasjob_testing' SERVER_NAME = 'hasjob.travis.local:5000' #: LastUser server LAS
TUSER_SERVER = 'https://hasgeek.com/' #: LastUser client id LASTUSER_CLIENT_ID = os.environ.get('LASTUSER_CLIENT_ID', '') #: LastUser client secret LASTUSER_CLIENT_SECRET = os.environ.get('LASTUSER_CLIENT_SECRET', '') STATIC_SUBDOMAIN = 'static' ASSET_SERVER = 'https://static.hasgeek.co.in/' ASSET_MANIFEST_PATH = "st...
FinalsClub/karmaworld
karmaworld/apps/document_upload/migrations/0002_auto__add_field_rawdocument_user.py
Python
agpl-3.0
6,785
0.008106
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): depends_on = ( ('users', '0001_initial'), ) def forwards(self, orm): # Adding field 'RawDocument.user' db.add_column...
models
.fields.IntegerField', [], {'default': '2013', 'null': 'True', 'blank': 'True'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'desc': ('django.db.models.fields.TextField', [], {'max_length': '511', 'null': 'True', 'blank': 'True'}), ...
chen0040/pyalgs
pyalgs/__init__.py
Python
bsd-3-clause
291
0.006873
# -*- coding: utf-8 -*-
""" pyalgs ~~~~~ pyalgs provides the python implementation of the Robert Sedgwick's Coursera course on Algorithms (Part I and Part II). :copyright: (c) 2017 by Xianshun Chen. :license: BSD, see LICENSE for more details. """ __vers
ion__ = '0.0.14'
funbaker/astropy
astropy/table/__init__.py
Python
bsd-3-clause
2,381
0.00378
# Licensed under a 3-clause BSD style license - see LICENSE.rst from .. import config as _config class Conf(_config.ConfigNamespace): """ Configuration parameters for `astropy.table`. """ auto_colname = _config.ConfigItem( 'col{0}', 'The template that determines the name of a column ...
from .sor
ted_array import SortedArray from .serialize import SerializedColumn # Finally import the formats for the read and write method but delay building # the documentation until all are loaded. (#5275) from ..io import registry with registry.delay_doc_updates(Table): # Import routines that connect readers/writers to a...
skade/scrapy-elasticsearch-bulk-item-exporter
scrapyelasticsearch.py
Python
bsd-3-clause
473
0.023256
"""An Itemexporter for scrapy that wri
tes elasticsearch bulk format""" from scrapy.contrib.exporter import BaseItemExporter from scrapy.contrib.exporter import JsonLinesItemExporter class ElasticSearchBulkItemExporter(JsonLinesItemExporter): def export_item(self, item): requestdict = { "index": { "typ
e": item.__class__.__name__ } } self.file.write(self.encoder.encode(requestdict) + '\n') super(ElasticSearchBulkItemExporter, self).export_item(item)
greyfenrir/taurus
bzt/resources/locustio-taurus-wrapper.py
Python
apache-2.0
4,812
0.001455
#! /usr/bin/env python import csv import json import os import sys import time from collections import OrderedDict from locust import main, events from locust.exception import StopUser from requests.exceptions import HTTPError from bzt.utils import guess_csv_dialect class LocustStarter(object): def __init__(sel...
N")) if os.getenv("LOCUST_NUMREQUESTS"): self.num_requests = float(os.getenv("LOCUST_NUMREQUESTS")) def __check_limits(self): i
f self.locust_start_time is None: self.locust_start_time = time.time() # Only raise an exception if the actual test is running if self.locust_stop_time is None: if time.time() - self.locust_start_time >= self.locust_duration: raise StopUser('Duration limit reache...
itielshwartz/BackendApi
lib/simplejson/tests/test_item_sort_key.py
Python
apache-2.0
1,154
0.004333
from unittest import TestCase from operator import itemgetter import simplejson as json class TestItemSortKey(TestCase): def test_simple_first(self): a = {'a': 1, 'c': 5, 'jack': 'jill', 'pick': 'axe', 'array':
[1, 5, 6, 9], 'tuple': (83, 12, 3), 'crate': 'dog', 'zeak': 'oh'} self.assertEqual(
'{"a": 1, "c": 5, "crate": "dog", "jack": "jill", "pick": "axe", "zeak": "oh", "array": [1, 5, 6, 9], "tuple": [83, 12, 3]}', json.dumps(a, item_sort_key=json.simple_first)) def test_case(self): a = {'a': 1, 'c': 5, 'Jack': 'jill', 'pick': 'axe', 'Array': [1, 5, 6, 9], 'tuple': (83, 12, 3), 'cr...
haroldtreen/python_koans
runner/path_to_enlightenment.py
Python
mit
1,482
0
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Functions to load the test cases ("koans") that make up the Path to Enlightenment. ''' import io import unittest # The path to enlightenment starts with the following: KOANS_FILENAME = 'koans.txt' def filter_koan_names(lines): ''' Strips leading and traili...
me) suite.addTests(tests) return suite def koans(filename=KOANS_FILENAME): ''' Returns a ``TestSuite`` loaded with all the koans (``TestCase``s) listed in ``filename``. ''' names = names_
from_file(filename) return koans_suite(names)
seccom-ufsc/hertz
hertz/settings.py
Python
mit
3,237
0.001236
import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ # SECURITY WARNING: keep t...
inimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization LANGUAGE_CODE = 'en
-us' TIME_ZONE = 'America/Sao_Paulo' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') # STATICFILES_DIRS = [ # os.path.join(BASE_DIR, 'static'), # ] LOGIN_REDIRECT_URL = '/' LOGIN_URL = '/login'
karaage0703/denpa-gardening
send_mail.py
Python
mit
1,390
0.003644
#!/usr/bin/env python # -*- coding: utf-8 -*- # send mail utf-8 using gmail smtp server /w jpegs from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.image import MIMEImage from email.Header import Header from email.Utils import formatdate import smtplib def send_email...
encoding='utf-8' msg = MIMEMultipart() mt = MIMEText(body.encode(encoding), 'plain', encoding) if jpegs: for fn in jpegs: img = open(fn, 'rb').read() mj = MIMEImage(img, 'jpeg', filename=
fn) mj.add_header("Content-Disposition", "attachment", filename=fn) msg.attach(mj) msg.attach(mt) else: msg = mt msg['Subject'] = Header(subject, encoding) msg['From'] = from_addr msg['To'] = to_addr msg['Date'] = formatdate() _user = "[email protected]" ...
WorkflowConversion/CTDConverter
ctdconverter/common/exceptions.py
Python
gpl-3.0
884
0
#!/usr/bin/env python """ @author: delagarza """ from CTDopts
.CTDopts import ModelError class CLIError(Exception): # Generic exception to raise and log different fatal errors. def __init__(self, msg): super(CLIError).__init__(type(self)) self.msg = "E: %s" % msg def __str__(self): return self.msg def __unicode__(self): return s...
ModelException(ModelError): def __init__(self, message): super().__init__() self.message = message def __str__(self): return self.message def __repr__(self): return self.message class ApplicationException(Exception): def __init__(self, msg): super(ApplicationE...
bmcculley/splinter
tests/test_zopetestbrowser.py
Python
bsd-3-clause
5,355
0.000378
# -*- coding: utf-8 -*- # Copyright 2013 splinter authors. All rights reserved. # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file. import os import unittest import sys from splinter import Browser from .base import BaseBrowserTests from .fake_webapp import EXAMPLE_A...
l(EXAMPLE_APP, browser.url) browser.quit() def test_cant_switch_to_frame(self): "zope.testbrowser should not be able to switch to frames" with self.assertRaises(NotImplementedError) as cm: self.browser.get_iframe("frame_123") self.fail() e = cm.exception ...
""" zope.testbrowser won't support type method because it doesn't interact with JavaScript """ with self.assertRaises(NotImplementedError): self.browser.type("query", "with type method") def test_simple_type_on_element(self): """ zope.testbrowser won't su...
goday-org/learnPython
src/Arrays.py
Python
gpl-3.0
119
0.02521
# -*- coding:
utf-8 -*- ''' Created on May 3, 2014 @author: andy ''' #list Tuple if
__name__ == '__main__': pass
jgolebiowski/graphAttack
controlTrainRNN.py
Python
mit
5,411
0.000924
import graphAttack as ga import numpy as np import pickle """Control script""" def run(simulationIndex, X, Y=None): """Run the model""" print("Training with:", simulationIndex) seriesLength, nFeatures = X.shape # ------ it is important that the exampleLength is the same as # ------ the number if ...
ions) for i in range(nLayers): hactivations[i][0].assignData(hactivations[i][-1].getValue()) cStates[i][0].assignData(cStates[i][-1].getValue()) return c, g param0 = mainGraph.unrollGradientParam
eters() print("Number of parameters to train:", len(param0)) adamGrad = ga.adaptiveSGDrecurrent(trainingData=X, param0=param0, epochs=1e3, miniBatchSize=nExamples, ...
SonyStone/pylib
Practical Maya Programming/input.py
Python
mit
199
0.005025
fro
m sys import version_info py3 = version_info[0] > 2 if py3: response = input("Please enter your
name: ") else: response = raw_input("Please enter your name: ") print("Hello " + response)
dpxxdp/berniemetrics
private/scrapers/realclearpolitics-scraper/scraper.py
Python
mit
1,355
0.005904
import os, scrapy, argparse from realclearpolitics.spiders.spider import RcpSpider from scrapy.crawler import CrawlerProcess parser = argparse.ArgumentParser('Scrap realclearpolitics polls data') parser.add_argument('url', action="store") parser.add_argument('--locale', action="store", default='') parser.add_argument('...
] output = filename + ".csv" print("No output file specified : using " + output) else: output = args.output if not output.endswith(".csv"): output = output + ".csv" if os.path.isfile(output): os.remove(output) os.system("scrapy crawl realclearpoliticsSpide...
: 'ERROR', 'DOWNLOAD_HANDLERS' : {'s3': None,} } process = CrawlerProcess(settings); process.crawl(RcpSpider, url, extra_fields) process.start()
nephila/djangocms-apphook-setup
tests/test_utils/urls.py
Python
bsd-3-clause
842
0.002375
from cms.utils.conf import get_cms_setting from django.conf import settings from django.conf.urls import include, url from django.conf.urls.i18n import i18n_patterns from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.views.i18n import JavaScriptCatalog from ...
_cms_setting("MEDIA_ROOT"), "show_indexes": True}), url(r"^jsi18n/$", JavaScriptCatalog.as_view(), name="javascript-catalog"), ] urlpatterns += staticfiles_urlpatterns() urlpatterns += i18n_patterns( url(r"^admin/", admin.site.urls), url(r"^", include
("cms.urls")), )
michardy/account-hijacking-prevention
hijackingprevention/api.py
Python
mit
4,967
0.02879
# The primary purpose of this module is to run
data hashing and comparison functions # It is also called during the intialization of modules to register their hashing and comparison functions. # Try to leave all the boilerplate calls like DB access and JSON decoding in the main.py file import hijackingprevention.session as session import hijackingprevention.api_u...
Receiver(): """This class handles all requests to hash and interpret data. Most of the shared functionalty that underpins the API is defined here. Functions in here fall into two catagories: Functions that allow modules to register hashers or comparers. Functions that run the registered hashers or comparers. Pl...
kuldeep-k/pySocialFactory
socialFactory/core/AuthenticationError.py
Python
mit
56
0.017857
c
lass AuthenticationError
(Exception): pass
gangadharkadam/shfr
frappe/widgets/event.py
Python
mit
1,523
0.0348
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt # Event # ------------- from __future__ import unicode_literals import frappe @frappe.whitelist() def get_cal_events(m_st, m_end): # load owned events res1 = frappe.db.sql("""select name from `tabEvent` WHERE...
name from `tabEvent` t1, `tabEvent Role` t2 where ifnull(t1.event_date,'2000-01-01') between %s and %s and t1.name = t2.parent and t1.event_type != 'Cancel' and %s""" % ('%s', '%s', myroles), (m_st, m_end)) # load
public events res4 = frappe.db.sql("select name from `tabEvent` \ where ifnull(event_date,'2000-01-01') between %s and %s and event_type='Public'", (m_st, m_end)) doclist, rl = [], [] for r in res1 + res2 + res3 + res4: if not r in rl: doclist += frappe.get_doc('Event', r[0]) rl.append(r) return do...
twitter/pants
src/python/pants/reporting/reporting_server.py
Python
apache-2.0
17,903
0.00849
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import absolute_import, division, print_function, unicode_literals import http.server import itertools import json import logging import mimetypes import os...
RequestHandler): """A handler t
hat demultiplexes various pants reporting URLs.""" def __init__(self, settings, renderer, request, client_address, server): self._settings = settings # An instance of ReportingServer.Settings. self._root = self._settings.root self._renderer = renderer self._client_address = client_address # The ...
renatopp/liac-chess
main.py
Python
mit
25
0.04
import chess chess
.run
()
LookThisCode/DeveloperBus
Season 2013/Bogota/Projects/06.Agile_Business/backend/app/models/user.py
Python
apache-2.0
231
0.021645
import logging from google.appengine.ext import ndb from endpoints_proto_datastore.ndb.m
odel import EndpointsModel, EndpointsAliasProperty class UserModel(EndpointsModel): email = ndb.StringProperty() na
me = ndb.StringProperty()
sndnv/cadb
cadb/utils/Stats.py
Python
mit
9,700
0.005773
# MIT License # Copyright (c) 2016 https://github.com/sndnv # See the project's LICENSE file for the full text def get_header_files_size_data(sources_dir, header_files_by_size, rows_count): """ Builds table rows list containing data about header files sizes (largest/smallest). :param sources_dir: configur...
= "-" if bottom is not None: bottom_count = (
len(bottom.internal_dependencies) + len(bottom.external_dependencies) ) else: bottom_count = "-" data.append( ( top.file_path.replace(sources_dir, '~') if top is not None else "-", top_count, bottom.file_path.replac...
pczhaoyun/obtainfo
zinnia/urls/entries.py
Python
apache-2.0
335
0
"""Urls fo
r the Zinnia entries""" from django.conf.urls import url from django.conf.urls import patterns from zinnia.views.entries import EntryDetail urlpatterns = patterns( '', url(r'^(?P<yea
r>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/(?P<slug>[-\w]+)/$', EntryDetail.as_view(), name='zinnia_entry_detail'), )
henkelis/sonospy
web2py/applications/admin/controllers/mercurial.py
Python
gpl-3.0
1,107
0.00813
from mercurial import cmdutil _hgignore_content = """\ syntax: glob *~ *.pyc *.pyo *.bak cache/* databases/* sessions/* errors/* """ def commit(): app = request.args[0] path = apath(app, r=request) uio = ui.ui() uio.quiet = True if not os.environ.get('HGUSER') and not uio.config("ui", "usernam...
.addremove(r) r.commit(text=form.vars.comment) if r[r.lookup('.')] == oldid: response.flash = 'no changes' files = r[r.lookup('.')].files() return dict(form=form,files=TABLE(*[TR(file) for file in files]),repo
=r)
kionetworks/openstack-api-scripts
tenant_glance_images.py
Python
apache-2.0
1,996
0.002004
#!/usr/bin/python import os import json from pprint import pprint from os import environ as env import glan
ceclient.exc from collections import Counter import novaclient.v1_1.client as nvclient import glanceclient.v2.client as glclient import keystoneclient.v2_0.client as ksclient def get_nova_credentials(): cred = {} cred['username'] = os.environ['OS_USERNAME'] cred['api_key'] = os.environ['OS_PASSWORD'] ...
NANT_NAME'] return cred def main(): keystone = ksclient.Client(auth_url=env['OS_AUTH_URL'], username=env['OS_USERNAME'], password=env['OS_PASSWORD'], tenant_name=env['OS_TENANT_NAME']) credentials = get_nova_cre...
mlperf/training_results_v0.6
Fujitsu/benchmarks/resnet/implementations/mxnet/3rdparty/onnx-tensorrt/third_party/onnx/onnx/backend/test/case/node/atan.py
Python
apache-2.0
767
0
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np # type: ignore import onnx from ..base import Base from . import expect class Atan(Bas
e): @staticmethod def export(): # type: () -> None node = onnx.helper.make_node( 'Atan', inputs=['x'], outputs=['y'], ) x = np.array([-1, 0, 1]).astype(np.float32) y = np.arctan(x) expect(node, inputs=[x], outputs=[y], ...
name='test_atan')
FlorisTurkenburg/ManyMan
SCC_backend/server.py
Python
gpl-2.0
14,884
0.000336
""" ManyMan - A Many-core Visualization and Management System Copyright (C) 2012 University of Amsterdam - Computer Systems Architecture Jimi van der Woning and Roy Bakker 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 t...
100: 16 } } class Client: """Client object for storing front-end connections.""" def __init__(self, request, name): self.request = request self.name = name self.initialized = False class Server(SocketServer.TCPServer): """Server object. Sets up, handle...
etLogger('Server') self.chip = chip self.settings = settings self.connection_count = 0 self.clients = [] self.frequency_scaler = None self.frequency_thread = None self.logger.debug("Initialized on port %d" % address[1]) tcps.__init__(self, address,...
nhuntwalker/astroML
book_figures/chapter10/fig_LINEAR_BIC.py
Python
bsd-2-clause
3,400
0.001176
""" BIC for LINEAR light curve -------------------------- Figure 10.19 BIC as a function of the number of frequency components for the light curve shown in figure 10.18. BIC for the two prominent frequency peaks is shown. The inset panel details the area near the maximum. For both frequencies, the BIC peaks at between...
i].plot(terms, BIC_max[i], '-k') ax_inset[i].xaxis.set_major_
locator(plt.MultipleLocator(5)) ax_inset[i].xaxis.set_major_formatter(plt.NullFormatter()) ax_inset[i].yaxis.set_major_locator(plt.MultipleLocator(25)) ax_inset[i].yaxis.set_major_formatter(plt.FormatStrFormatter('%i')) ax_inset[i].set_xlim(7, 19.75) ax_inset[i].set_ylim(ylims[i]) ax_inset[i].se...
GertBurger/pcapcffi
tests/test_pcapcffi.py
Python
bsd-3-clause
542
0
#!/usr/bin/env python #
-*- coding: utf-8 -*- """ test_pcapcffi ---------------------------------- Tests for `pcapcffi` module. """ import pytest import pcapcffi from pcapcffi.wrappers import PcapError def test_findalldevs(): devs = pcapcffi.wrappers.pcap_findalldevs() assert devs def test_pcap(): pcap = pcapcffi.Pcap() ...
lose()
xpspectre/multiple-myeloma
prep_patient_data.py
Python
mit
8,458
0.002365
# Prepare per-patient clinical data # TODO: Possibly incorporate Palumbo data import os from load_patient_data import load_per_patient_data import numpy as np import pandas as pd pd.options.mode.chained_assignment = None # Load input data data, per_patient_dict, per_patient_fields = load_per_patient_data() # Dictio...
DEATH'] = death_reason_map endp = endp.jo
in(data['D_PT_CAUSEOFDEATH'].replace(death_reason_map)) data.drop('D_PT_CAUSEOFDEATH', axis=1, inplace=True) # Date of death endp = endp.join(data['D_PT_deathdy']) data.drop('D_PT_deathdy', axis=1, inplace=True) # Drop some redundant cols that are hard to interpret # A bunch of these are coded versions of more desc...
onaio/kpi
kpi/admin.py
Python
agpl-3.0
241
0
# coding: utf-8 from django.contrib import admin from hub.
models import ExtraUserDetail from .models import AuthorizedApplication # Register your models here. admin.
site.register(AuthorizedApplication) admin.site.register(ExtraUserDetail)
scode/pants
tests/python/pants_test/backend/jvm/subsystems/test_shader.py
Python
apache-2.0
7,708
0.007654
# coding=utf-8 # Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os import tem...
ert_inference('**', '__prefix__.', '__prefix__.@1') def test_
shading_exclude(self): def assert_exclude(from_pattern, to_pattern): self.assertEqual((from_pattern, to_pattern), Shading.Exclude.new(from_pattern).rule()) assert_exclude('com.foo.bar.Main', 'com.foo.bar.Main') assert_exclude('com.foo.bar.**', 'com.foo.bar.@1') assert_exclude('com.*.bar.**', 'com...
Stellarium/stellarium
util/skyTile.py
Python
gpl-2.0
4,700
0.004681
#!/usr/bin/python # # Fabien Chereau [email protected] # import gzip import os def writePolys(pl, f): """Write a list of polygons pl into the file f. The result is under the form [[[ra1, de1],[ra2, de2],[ra3, de3],[ra4, de4]], [[ra1, de1],[ra2, de2],[ra3, de3]]]""" f.write('[') for idx, poly in enumer...
or self.serverCredits.infoUrl != None: f.write(levTab + '\t"serverCredits": {\n') self.serverCredits.outJSON(f, levTab) f.write(levTab + '\t},\n') if self.imageUrl: f.write(
levTab + '\t"imageUrl": "' + self.imageUrl + '",\n') f.write(levTab + '\t"worldCoords": ') writePolys(self.skyConvexPolygons, f) f.write(',\n') f.write(levTab + '\t"textureCoords": ') writePolys(self.textureCoords, f) f.write(',\n') if self.maxBrightness: ...
poorsquinky/traktor-tools
pl2dir.py
Python
gpl-3.0
4,990
0.012024
#!/usr/bin/python # pl2dir - Generates a directory structure based on your Traktor playlists. # Copyright (C) 2015 Erik Stambaugh # 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 versio...
f) allfiles.append(fullpath) d = pathdict.get(f,[]) d.append(fullpath) pathdict[
f] = d ### collection class Track: def __str__(self): if self.artist: return "%s - %s" % (self.artist.encode('utf8'),self.title.encode('utf8')) return "%s" % (self.title.encode('utf8')) def __unicode__(self): return self.__str__() def __init__(self,soup): self...
twister/twister.github.io
lib/TscTelnetLib.py
Python
apache-2.0
17,030
0.003288
# File: TscTelnetLib.py ; This file is part of Twister. # version: 2.002 # # Copyright (C) 2012 , Luxoft # # Authors: # Adrian Toader <[email protected]> # # # 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...
self.activeConnection: del(self.connections[self.activeConnection]) self.activeConnection = None return True try: del(self.connections[name]) if name == self.activeConnection: self.activeConnection = None except Exception, e...
return False return True def close_all_connections(self): """ close all connections """ del(self.connections) self.connections = {} self.activeConnection = None print('all connections closed') return True class TelnetConnection: """ ts...
weissercn/learningml
learningml/GoF/chi2/gauss/miranda_adaptive_binning_systematics_Gaussian_same_projection_evaluation_of_optimised_classifiers.py
Python
mit
3,491
0.030077
import adaptive_binning_chisquared_2sam import os systematics_fraction = 0.01 dim_list = [1,2,3,4,5,6,7,8,9,10] adaptive_binning=True CPV = True PLOT = True if CPV: orig_name="chi2_gauss_0_95__0_95_CPV_not_redefined_syst_"+str(systematics_fraction).replace(".","_")+"_" orig_title="Gauss 0.95 0.95 syst{} adaptbi...
im_list = [2,6,10] orig_name="plot_"+orig_name orig_title= "Plot "+orig_title sample_list_typical= [79, 74, 22] sample_list= [[item,item+1] for item in sample_list_typical] else: sample_list = [range(100)]*len(dim_list) comp_file_list_list = [] for dim_data_index, dim_data in enumerate(dim_list): comp_file_list...
mple_list[dim_data_index]: if CPV: comp_file_list.append((os.environ['learningml']+"/GoF/data/gaussian_same_projection_on_each_axis/gauss_data/gaussian_same_projection_on_each_axis_{1}D_10000_0.0_1.0_1.0_{0}.txt".format(i,dim_data),os.environ['learningml']+"/GoF/data/gaussian_same_projection_on_each_axis/gauss_da...
wfxiang08/sqlalchemy
examples/generic_associations/__init__.py
Python
mit
748
0.005348
""" Illustrates various methods of associating multiple types of parents with a particular c
hild object. The examples all use the declarative extension along with declarative mixins. Each one presents the identical use case at the end - two classes, ``Customer`` and ``Supplier``, both subclassing the ``HasAddresses`` mixin, which ensures that the parent class is provided with an ``addresses`` collection wh...
2007 blog post `Polymorphic Associations with SQLAlchemy <http://techspot.zzzeek.org/2007/05/29/polymorphic-associations-with-sqlalchemy/>`_. .. autosource:: """
googleapis/storage-testbench
tests/test_error.py
Python
apache-2.0
3,099
0.001291
#!/usr/bin/env python3 # # Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
rt_called_once_with(grpc.StatusCode.ABORTED, ANY) def test_notfound(self): with self.assertRaises(error.RestException) as rest: error.notfound("test-object", None) self.assertEqual(rest.exception.code, 404) context = Mock() e
rror.notfound("test-object", context) context.abort.assert_called_once_with(grpc.StatusCode.NOT_FOUND, ANY) def test_not_allowed(self): with self.assertRaises(error.RestException) as rest: error.notallowed(None) self.assertEqual(rest.exception.code, 405) if __name__ == "__main...
EmilienDupont/cs229project
convertToSparseMatrix.py
Python
mit
3,343
0.007777
""" Script used to convert data into sparse matrix format that can easily be imported into MATLAB. Use like this python convertToSparseMatrix.py ../../../../../data/train_triplets.txt 1000 ../../../../../data/eval/year1_test_triplets_visible.txt ../../../../../data/eval/year1_test_triplets_hidden.txt 100 """ import sys...
alysing command line arguments if len(sys.argv) < 5: print 'Usage:' print ' python %s <triplets training file> <nu
mber of triplets> <triplets visible history file> <triplets hidden history file> <number of triplets>' % sys.argv[0] exit() inputTrainingFile = sys.argv[1] numTriplets = int(sys.argv[2]) inputTestFile = sys.argv[3] inputHiddenTestFile = sys.argv[4] numTripletsTest = int(sys.argv[5]) start = time.time() userIdToInd...
google/starthinker
dags/itp_audit_dag.py
Python
apache-2.0
35,487
0.026968
########################################################################### # # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/l...
ument to deploy to.','d
efault':''}} } } }, { 'dataset':{ 'auth':{'field':{'name':'auth_bq','kind':'authentication','order':1,'default':'service','description':'Credentials used for BigQuery.'}}, 'dataset':{'field':{'name':'recipe_slug','kind':'string','order':1,'default':'ITP_Audit_Dashboard','desc...
anhstudios/swganh
data/scripts/templates/object/tangible/ship/components/reactor/shared_rct_sds_imperial_1.py
Python
mit
482
0.045643
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from
swgpy.object import * def create(kernel): result = Tangible() result.template = "object/tangible/ship/components/reactor/shared_rct_sds_imperial_1.iff" result.attribute_template_id = 8 result.stfName("space/space_item","rct_sds_imperial_1_n") #### BEG
IN MODIFICATIONS #### #### END MODIFICATIONS #### return result
vascotenner/holoviews
holoviews/plotting/util.py
Python
bsd-3-clause
10,673
0.002342
from __future__ import unicode_literals import numpy as np import param from ..core import (HoloMap, DynamicMap, CompositeOverlay, Layout, GridSpace, NdLayout, Store) from ..core.util import (match_spec, is_number, wrap_tuple, basestring, get_overlay_spec, unique_iterator,...
"area".'.format(scaling_method)) sizes = size_fn(sizes) return (base_size*scaling_factor*sizes) def get_sideplot_ranges(plot, element, main, ranges): """ Utility to find the range for an adjoined plot given the plot, the element, the Element the plot is adjoined to and the dictionary of ra...
" key = plot.current_key dims = element.dimensions(label=True) dim = dims[1] if dims[1] != 'Frequency' else dims[0] range_item = main if isinstance(main, HoloMap): if issubclass(main.type, CompositeOverlay): range_item = [hm for hm in main.split_overlays()[1] ...
kuiche/chromium
tools/grit/grit/node/message.py
Python
bsd-3-clause
9,031
0.009412
#!/usr/bin/python2.4 # Copyright (c) 2006-2008 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. '''Handling of the <message> element. ''' import re import types from grit.node import base import grit.format.rc_header imp...
super(type(self), self).EndParsing() # Make the text (including placeholder references) and list of placeholders, # then strip and store leading and trailing whitespace and create the # tclib.Message() and a clique to contain it. text = '' placeholders = [] for item in self.mixed_content: ...
rs['name'].upper() text += presentation ex = ' ' if len(item.children): ex = item.children[0].GetCdata() original = item.GetCdata() placeholders.append(tclib.Placeholder(presentation, original, ex)) m = _WHITESPACE.match(text) if m: self.ws_at_start = m.g...
kytos/kytos
kytos/core/exceptions.py
Python
mit
3,168
0
"""Kytos Core-Defined Exceptions.""" class KytosCoreException(Exception): """Exception thrown when KytosCore is broken.""" def __str__(self): """Return message of KytosCoreException.""" return 'KytosCore exception: ' + super().__str__() class KytosSwitchOfflineException(Exception): """E...
class:`~kytos.core.switch.Switch`): A switch offline. """ super().__init__() self.switch = switch def __str__(self): """Return message of KytosSwitchOfflineException."""
msg = 'The switch {} is not reachable. Please check the connection ' msg += 'between the switch and the controller.' return msg.format(self.switch.dpid) class KytosEventException(Exception): """Exception thrown when a KytosEvent have an illegal use.""" def __init__(self, message="KytosEven...
Psirus/altay
altai/lib/vented_box.py
Python
bsd-3-clause
1,632
0
# -*- coding: utf-8 -*- """ Vented box enclosure """ import numpy as np from . import air class VentedBox(object): """ Model a vented box loudspeaker enclosure """ def __init__(self, Vab, fb, Ql): self._Vab = Vab #: Acoustic compliance of box :math:`C_{ab}` #:
#: .. note:: Do not set this directly, use :meth:`Vab` self.Cab = Vab / (air.RHO*air.C**2) self._fb = fb #: Angular frequency :math:`\omega_b = 2 \pi f_b`
#: #: .. note:: Do not set this directly, use :meth:`fb` self.wb = 2.0*np.pi*fb #: Time constant of the box :math:`T_b = \frac{1}{\omega_b}`; not to #: be confused with a period #: :math:`t = \frac{1}{f} = \frac{2\pi}{\omega}` #: #: .. note:: Do not set t...
wraithan/reciblog
urls.py
Python
bsd-2-clause
617
0.003241
from django.conf.urls.defaults import patterns, url, include from django.contrib import admin from django.conf import settings from django.views.generic.simple import direct_to_template admin.autodiscover() urlpatterns = patterns( '', url(r'^', include('reciblog.blog.urls')), url(r'^about$', direct_to_tem...
ut'), url(r'^admin/', include(admin.site.urls))
, ) if settings.DEBUG == True: urlpatterns += patterns( '', url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), )
Rudloff/youtube-dl
youtube_dl/extractor/generic.py
Python
unlicense
99,048
0.002343
# encoding: utf-8 from __future__ import unicode_literals import os import re import sys from .common import InfoExtractor from .youtube import YoutubeIE from ..compat import ( compat_etree_fromstring, compat_urllib_parse_unquote, compat_urlparse, compat_xml_parse_error, ) from ..utils import ( d...
legraaf.nl/tv/nieuws/binnenland/24353229/__Tikibad_ontruimd_wegens_brand__.html { 'url': 'http://www.telegraaf.nl/xml/playlist/2015/8/7/mZlp2ctYIUEB.xspf', 'info_dict': { 'id': 'mZlp2ctYIUEB', 'ext': 'mp4', 'title': 'Tikibad ontruimd wegens...
/.*\.jpg$', 'duration': 33, }, 'params': { 'skip_download': True, }, }, # MPD from http://dash-mse-test.app
smendez-hi/SUMO-hib
tools/xml/rebuildSchemata.py
Python
gpl-3.0
848
0.005896
#!/usr/bin/env python """ @file rebuildSchemata.py @author Michael Behrisch @date 2011-07-11 @version $Id: rebuildSchemata.py 11671 2012-01-07 20:14:30Z behrisch $ Let all SUMO binarie write the schema for their config SUMO, Simulation of Urban MObility; see http://sumo.sourceforge.net/ Copyright (C) 2011-2012...
reserved """ import os, sys, subprocess homeDir = os.environ.get("SUMO_HOME", os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) binDir = os.environ.get("SUMO_BINDIR", os.path.join(homeDir, "bin")) for exe in "activitygen dfrouter duarouter jtrrouter netconvert netgen od2trips polyconvert sum...
ernet", "xsd" , exe+"Configuration.xsd")])
batermj/algorithm-challenger
code-analysis/programming_anguage/python/source_codes/Python3.8.0/Python-3.8.0/Lib/test/test_fstring.py
Python
apache-2.0
47,266
0.000783
# -*- coding: utf-8 -*- # There are tests here with unicode string literals and # identifiers. There's a code in ast.c that was added because of a # failure with a non-ascii-only expression. So, I have tests for # that. There are workarounds that would let me run tests for
that # code without un
icode identifiers and strings, but just using them # directly seems like the easiest and therefore safest thing to do. # Unicode identifiers in tests is allowed by PEP 3131. import ast import types import decimal import unittest a_global = 'global variable' # You could argue that I'm too strict in looking for specif...
kusamau/cedaMarkup
ceda_markup/markup.py
Python
bsd-3-clause
2,962
0.009453
''' BSD Licence Copyright (c) 2012, Science & Technology Facilities Council (STFC) 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 n...
ace to the document root element _tag = tagName if root is not None: if isinstance(root, _ElementInterface): if root.get('xmlns') == tagNamespace: _tag = tagName else:
root.set("xmlns:%s" % (tagPrefix), tagNamespace) if tagName is not None and tagPrefix is not None: _tag = "%s:%s" % (tagPrefix, tagName) markup = Element(_tag) if root is None: markup.set("xmlns", tagNamespace) return markup...
mupi/tecsaladeaula
core/templatetags/usergroup.py
Python
agpl-3.0
1,920
0.001563
# https://djangosnippets.org/snippets/2566/ from django import template from django.template import resolve_variable, NodeList from django.contrib.auth.models import Group register = template.Library() @register.tag() def ifusergroup(parser, token): """ Check to see if the currently logged in user belongs to a ...
and middleware. Usage:
{% ifusergroup Admins %} ... {% endifusergroup %}, or {% ifusergroup Admins|Group1|"Group 2" %} ... {% endifusergroup %}, or {% ifusergroup Admins %} ... {% else %} ... {% endifusergroup %} """ try: _, group = token.split_contents() except ValueError: raise template.Tem...
opennode/nodeconductor-assembly-waldur
src/waldur_jira/migrations/0018_project_runtime_state.py
Python
mit
465
0
# Generated by Django 1.11.7 on 2018-05-21 09:16 fro
m django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('waldur_jira', '0017_project_action'), ] operations = [ migrations
.AddField( model_name='project', name='runtime_state', field=models.CharField( blank=True, max_length=150, verbose_name='runtime state' ), ), ]
AndrewHanes/Python-Webnews
webnews/api.py
Python
mit
2,609
0.004983
import json import enum from urllib.parse import urlencode from urllib.request import urlopen from urllib import request class APINonSingle: def __init__(self, api_key, agent = "webnews-python", webnews_base = "https://webnews.csh.rit.edu/"): self.agent = agent self.api_key = api_key self....
s = {}): return self.GET(API.Actions.search, params) def post_specifics(self, newsgroup, index, params={}): return self.GET(str(newsgroup)+"/"+str(index), params) def compose(self, newsgroup, subject, body, params={}): params['subject'] = subject params['body'] = body p...
tion for object implementation """ class API(APINonSingle): _instance = {} def __new__(cls, *args, **kwargs): if not args[0] in cls._instance: cls._instance[args[0]] = APINonSingle(*args, **kwargs) return cls._instance[args[0]]
UnrememberMe/pants
src/python/pants/backend/docgen/register.py
Python
apache-2.0
1,019
0.004907
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) from pants.backend.d...
ile_aliases import BuildFileAliases from pants.goal.task_registrar import TaskRegistrar as task def build_file_aliases(): return BuildFileAliases( targets={ 'page': Page, }, objects={ 'wiki_artifact': WikiArtifact, # TODO: Why is this capitalized? 'Wiki': Wiki, }, ) def r...
action=MarkdownToHtml).install(), task(name='reference', action=GeneratePantsReference).install()
BobbyJacobs/cs3240-demo
hello.py
Python
mit
30
0.033333
def main
(): print(
"Hello!")
mesonbuild/meson
mesonbuild/interpreter/primitives/string.py
Python
apache-2.0
6,549
0.003207
# Copyright 2021 The Meson development team # SPDX-license-identifier: Apache-2.0 from __future__ import annotations import re import os import typing as T from ...mesonlib import version_compare from ...interpreterbase import ( ObjectHolder, MesonOperator, FeatureNew, typed_operator, noArgsFlatt...
# Comparison MesonOperator.EQUALS: (str, lambda x: self.held_object == x), MesonOperator.NOT_EQUALS: (str, lambda x: self.held_object != x), MesonOperator.GREATER: (str, lambda x: self.held_object > x), MesonOperator.LESS: (str, lambda x: self.held_object < x), ...
MesonOperator.LESS_EQUALS: (str, lambda x: self.held_object <= x), }) # Use actual methods for functions that require additional checks self.operators.update({ MesonOperator.DIV: self.op_div, MesonOperator.INDEX: self.op_index, }) def display_name(se...
nesterione/problem-solving-and-algorithms
problems/Checkio/TheFlatDictionary.py
Python
apache-2.0
1,262
0.003962
def flatten(dictionary): stack = [((), dictionary)] result = {} while stack:
path, current = stack.pop() for k, v in current.items(): if isinstance(v, dict) and bool(v): stack.append((path + (k,), v)) else: whatadd = "" if isinstance (v, dict) else v result["/".join((path + (k,)))] = whatadd ...
assert flatten( {"key": {"deeper": {"more": {"enough": "value"}}}} ) == {"key/deeper/more/enough": "value"}, "Nested" assert flatten({"empty": {}}) == {"empty": ""}, "Empty value" assert flatten({"name": { "first": "One", "last": "Drone"}, ...