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 |
|---|---|---|---|---|---|---|---|---|
joshshep/golfr | golfr/classify_cells/classify_sample.py | Python | apache-2.0 | 3,882 | 0.01932 | #! /usr/bin/env python
from __future__ import print_function
import cv2
import numpy as np
import keras
from keras.utils import plot_model
from keras.models import Sequential, load_model
from keras.layers import Dense
from os.path import abspath
from golfr.definitions import DFLT_MODEL_PATH
def classify_digit(digit_f... | dilation
kernel = np.ones((5,5),np.uint8)
img = cv2.dilate(img,kernel,iterations = 1)
cv2.imwrite('dilation.jpg',img)
######################################
## resize sample image to (28,28)
contoured = img.copy()
#whose idea was it to make cv2.findContours non-backwards compatible?!
i... | toured, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnt = contours[0]
x,y,w,h = cv2.boundingRect(cnt)
print('x={}, y={}, w={}, h={}'.format(x,y,w,h))
img = img[y:y+h,x:x+w]
print('cropped shape:',img.shape)
cv2.imwrite('3.png',img)
pad_top = 0
pad_bot = 0
pad_left = 0
pad_right... |
modimore/BreezeBlocks | package/breezeblocks/sql/param_store.py | Python | mit | 3,955 | 0.006574 | from .expressions import Value
from ..exceptions import BuilderError
def get_param_store(paramstyle):
if paramstyle == "qmark":
return QmarkParamStore()
elif paramstyle == "numeric":
return NumericParamStore()
elif paramstyle == "named":
return NamedParamStore()
elif paramstyle ... | Error()
def get_param_value(self, key):
return self._find_param(key).get_value()
def set_param_value(self, key, value):
self._find_param(key).set_value(value)
return value
def _find_param(self | , key):
return self._params[key]
def _make_param_name(self, param):
return str(id(param))
class OrderedParamStore(ParamStore):
def get_dbapi_params(self):
return [param.get_value() for param in self._all_params]
class NumberedParamStore(ParamStore):
def __init__(self):
... |
tbpmig/mig-website | mig_main/migrations/0003_officerposition_position_type.py | Python | apache-2.0 | 508 | 0.001969 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencie | s = [
('mig_main', '0002_initial_split'),
]
operations = [
migrations.AddField(
model_name='officerposition',
name='position_type',
field=models.CharField(default=b'O', max_length=1, choices=[(b'O', b'Officer'), (b'C', b'Chair')]),
preserve_defaul... |
]
|
dokterbob/django-popularity | popularity/models.py | Python | agpl-3.0 | 23,734 | 0.012977 | # This file is part of django-popularity.
#
# django-popularity: A generic view- and popularity tracking pluggable for Django.
# Copyright (C) 2008-2010 Mathijs de Bruin
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public Lic | ense 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 be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should hav... |
jonge-democraten/website | website/jdpages/migrations/0004_auto_20170726_0019.py | Python | mit | 441 | 0 | # -*- coding: utf-8 -* | -
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('jdpages', '0003_auto_20170725_2349'),
]
operations = [
migrations.AlterField(
model_name='visionspage',
name='visio | n_pages',
field=models.ManyToManyField(blank=True, to='jdpages.VisionPage'),
),
]
|
MathYourLife/sandbox | python/listener/users.py | Python | mit | 1,371 | 0.002918 | from tw | isted.internet.protocol import Factory
from twisted.protocols.basic import LineReceiver
from twisted.internet import reactor
|
class Chat(LineReceiver):
def __init__(self, users):
self.users = users
self.name = None
self.state = "GETNAME"
def connectionMade(self):
self.sendLine("What's your name?")
def connectionLost(self, reason):
if self.users.has_key(self.name):
del self.us... |
AMOboxTV/AMOBox.LegoBuild | plugin.video.SportsDevil/lib/parser.py | Python | gpl-2.0 | 26,777 | 0.004631 | # -*- coding: utf-8 -*-
import common
import sys, os, traceback
import time
import random
import re
import urllib
import string
from string import lower
from entities.CList import CList
from entities.CItemInfo import CItemInfo
from entities.CListItem import CListItem
from entities.CRuleItem import CRuleItem
import c... | mpList and len(tmpList.rules) > 0:
successfullyScraped = self.__loadRemote(tmpList, lItem)
else:
if ext == 'cfg':
tmpList = self.__loadLocal(url, lItem)
if tmpList and tmpList.start != '' and len(tmpList.rules) > 0:
lItem['url'] = t... | adRemote(tmpList, lItem)
elif cfg:
tmpList = self.__loadLocal(cfg, lItem)
if tmpList and len(tmpList.rules) > 0:
successfullyScraped = self.__loadRemote(tmpList, lItem)
# autoselect
if tmpList and tmpList.skill.find('autoselect') != -1 and... |
youtube/cobalt | third_party/skia/infra/bots/assets/asset_utils.py | Python | bsd-3-clause | 11,910 | 0.009236 | #!/usr/bin/env python
#
# Copyright 2016 Google Inc.
#
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Utilities for managing assets."""
import argparse
import json
import os
import shlex
import shutil
import subprocess
import sys
INFRA_BOTS_DIR = os.path.ab... | d to update depot_tools.')
except sub | process.CalledProcessError:
raise Exception('CIPD not authenticated. You may need to run:\n\n'
'$ %s auth-login' % self._cipd)
def _run(self, cmd, specify_service_url=True):
"""Run the given command."""
cipd_args = []
if specify_service_url:
cipd_args.extend(['--service-... |
eakron/canieatit | canieatit/utils/json_app.py | Python | mit | 776 | 0.024485 | from flask import Flask, jsonify
from werkzeug.exceptions import default_exceptions
from werkzeug.exceptions import HTTPException
|
__all__ = ['make_json_app']
def make_json_app(import_name, **kwargs):
"""
Creates a JSON-oriented Flask app.
All error responses that you don't specifically
manage yourself will have application/json content
type, and will contain JSON like this (just an example):
{ "message": "405: Method Not Allowed" }
" | ""
def make_json_error(ex):
response = jsonify(message=str(ex))
response.status_code = (ex.code
if isinstance(ex, HTTPException)
else 500)
return response
app = Flask(import_name, **kwargs)
for code in default_exceptions.iterkeys():
app.error_handler_spec[None][code] = make_json_error
ret... |
talib570/movie-trailer-website | media.py | Python | gpl-2.0 | 718 | 0 | import webbrowser
class Movie():
""" This class provides a way to store movie related information."""
def __init__(self, title, storyline, poster,
trailer, duration, rating, release_year, access_name):
self.title = title
self.storyline = storyline
self.poster_url = po... | self.rating = rating
self.release_year = release_year
self.trailer_url = trailer
self.duration = duration
self.rating = rating
self.access_name = access_name
def show_tr | ailer(self):
webbrowser.open(self.trailer_url)
def show_poster(self):
print("Show poster image")
def show_info(self):
print("Show info")
|
blmousee/pyctp | example/ctp/talib/__init__.py | Python | mit | 73,624 | 0.005352 | # -*- coding: utf-8 -*-
from __future__ import absolute_import as _init
__author__ = 'lovelylain'
__version__ = '0.3.0'
class TAError(Exception):
pass
class TAFunc(object):
__slots__ = ('inputs', 'outputs', 'params', 'lookback', 'size')
def __call__(self, stop, start=-1):
return 0
@classmeth... | ) -> outNBElement
Vector Trigonometric ATan (Math Transform)
Inputs: real
Outputs: (outReal,d)
"""
__slots__ = ('real', 'outReal')
def __init__(self, real, outReal=None):
pass
class ATR(TAFunc):
"" | "ATR(high, low, close, outReal=None, timeperiod=14) -> Atr
Atr(stop, start=-1) -> outNBElement
Average True Range (Volatility Indicators)
Inputs: [high, low, close]
Outputs: (outReal,d)
Parameters:
timeperiod: Time Period (1 <= i <= 100000)
Number of period
"""
__slots__ = ('h... |
kmatheussen/radium | bin/scheme/repl.py | Python | gpl-2.0 | 543 | 0.014733 | #! /usr/bin/env python
#Writte | n by Kjetil Matheussen: k.s.matheussen@notam02.no
import sys
import os
import urllib2
import readline
executable_path = os.path.split(os.path.abspath(os.path.realpath(sys.argv[0])))[0]
# TODO: Use bin/packages/s7/s7webserver instead, and | delete the local s7webserver directory.
sys.path += [os.path.join(executable_path,os.path.pardir,"s7webserver")]
import s7webserver_repl
portnum = "5080"
if len(sys.argv)>1:
portnum = sys.argv[1]
s7webserver_repl.start("radium>", "http://localhost:"+portnum)
|
materialsvirtuallab/veidt | veidt/describer/tests/test_general_describer.py | Python | bsd-3-clause | 2,379 | 0.00042 | # coding: utf-8
from __future__ import division, print_function, unicode_literals, \
absolute_import
import unittest
import os
import json
import numpy as np
import pandas as pd
from pymatgen import Structure
from veidt.describer.general import FuncGenerator, MultiDescriber
from veidt.describer.structural_descr... | = FuncGenerator.from_dict(json.loads(json_str))
class MultiDescriberTest(unittest.TestCase):
def test_describe(self):
li2o = Structure.from_file(os.path.join(os.path.dirname( | __file__),
"../../tests/Li2O.cif"))
na2o = Structure.from_file(os.path.join(os.path.dirname(__file__),
"../../tests/Na2O.cif"))
d1 = DistinctSiteProperty(['8c', '4a'], ["Z", "atomic_radius"])
d2 = Fun... |
miguelinux/vbox | src/VBox/ValidationKit/tests/api/tdAppliance1.py | Python | gpl-2.0 | 7,406 | 0.014853 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# $Id: tdAppliance1.py $
"""
VirtualBox Validation Kit - IAppliance Test #1
"""
__copyright__ = \
"""
Copyright (C) 2010-2015 Oracle Corporation
This file is part of VirtualBox Open Source Edition (OSE), as
available from http://www.virtualbox.org. This file is free soft... | on. VirtualBox OSE is distributed in the
hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
The contents of this file may alternatively be used under the | terms
of the Common Development and Distribution License Version 1.0
(CDDL) only, as it comes in the "COPYING.CDDL" file of the
VirtualBox OSE distribution, in which case the provisions of the
CDDL are applicable instead of those of the GPL.
You may elect to license modified versions of this file under the
terms and ... |
jolyonb/edx-platform | openedx/core/djangoapps/schedules/management/commands/setup_models_to_send_test_emails.py | Python | agpl-3.0 | 3,410 | 0.003812 | """
A managment command that can be used to set up Schedules with various configurations for testing.
"""
from __future__ import absolute_import
import datetime
import factory
import pytz
from django.contrib.sites.models import Site
from django.core.management.base import BaseCommand
from openedx.core.djangoapps.co... |
)
XMODULE_FACTORY_LOCK.disable()
course_overview = CourseOverview.load_from_module_store(course.id)
ThreeDayNudgeSchedule.create(enrollment__course=course_overview)
TenDayNudgeSchedule. | create(enrollment__course=course_overview)
UpgradeReminderSchedule.create(enrollment__course=course_overview)
ContentHighlightSchedule.create(enrollment__course=course_overview)
ScheduleConfigFactory.create(site=Site.objects.get(name='example.com'))
|
brainstorm/bcbio-nextgen | bcbio/qc/qsignature.py | Python | mit | 8,491 | 0.002355 | """Qsignature: detection of sample mixups.
https://sourceforge.net/p/adamajava/wiki/qSignature/
"""
import os
import shutil
import subprocess
import lxml
import pysam
import toolz as tz
from bcbio import bam, utils
from bcbio.distributed.transaction import file_transaction
from bcbio.log import logger
from bcbio.pro... | ir = samples[0][0]["dirs"]["work"]
count = 0
for data in samples:
data = data[0]
vcf = tz.get_in(["summary", "qc", "qsignature", "base" | ], data)
if vcf:
count += 1
vcf_name = dd.get_sample_name(data) + ".qsig.vcf"
out_dir = utils.safe_makedir(os.path.join(work_dir, "qsignature"))
if not os.path.lexists(os.path.join(out_dir, vcf_name)):
os.symlink(vcf, os.path.join(out_dir, vcf_name... |
gfyoung/pandas | pandas/core/dtypes/common.py | Python | bsd-3-clause | 47,282 | 0.000338 | """
Common type operations.
"""
from __future__ import annotations
from typing import (
Any,
Callable,
)
import warnings
import numpy as np
from pandas._libs import (
Interval,
Period,
algos,
)
from pandas._libs.tslibs import conversion
from pandas._typing import (
ArrayLike,
DtypeObj,
... | YPE = conversion.DT64NS_DTYPE
TD64NS_DTYPE = conversion.TD64NS_DTYPE
INT64_DTYPE = np.dtype(np.int64)
# oh the troubles to reduce import time
_is_scipy_sparse = None
ensure_float64 = algos.ensure_float64
ensure_float32 = algos.ensure_float32
def ensure_f | loat(arr):
"""
Ensure that an array object has a float dtype if possible.
Parameters
----------
arr : array-like
The array whose data type we want to enforce as float.
Returns
-------
float_arr : The original array cast to the float dtype if
possible. Otherwise,... |
tgalal/yowsup | yowsup/common/http/warequest.py | Python | gpl-3.0 | 10,328 | 0.002324 | from .waresponseparser import ResponseParser
from yowsup.env import YowsupEnv
import sys
import logging
from axolotl.ecc.curve import Curve
from axolotl.ecc.ec import ECPublicKey
from yowsup.common.tools import WATools
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from yowsup.config.v1.config import C... | encrypt_params, preview
))
self.response = None
if encrypt_params:
logger.debug("Encrypting parameters")
if logger.level < | = logging.DEBUG:
logger.debug("pre-encrypt (encoded) parameters = \n%s", (self.urlencodeParams(self.params)))
params = self.encryptParams(self.params, self.ENC_PUBKEY)
else:
## params will be logged right before sending
params = self.params
parser = p... |
csm0042/rpihome_v3 | rpihome_v3/messages/get_device_state.py | Python | gpl-3.0 | 11,430 | 0.0007 | #!/usr/bin/python3
""" message_gds.py:
"""
# Import Required Libraries (Standard, Third Party, Local) ********************
import datetime
import logging
if __name__ == "__main__":
import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
from rpihom... | *******************
@property
def ref(self):
self.log.debug('Returning current value of ref | number: %s', self._ref)
return self._ref
@ref.setter
def ref(self, value):
if in_int_range(self.log, value, 100, 999) is True:
self._ref = str(value)
self.log.debug('Ref number updated to: %s', self._ref)
else:
self.log.debug('Ref number update faile... |
EmreAtes/spack | var/spack/repos/builtin/packages/r-tseries/package.py | Python | lgpl-2.1 | 1,765 | 0.000567 | ##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import *
class RTseries(RPackage):
"""Time series analysis and computational finance."""
homepage = "https://c... | eries_0.10-42.tar.gz"
list_url = "https://cran.r-project.org/src/contrib/Archive/tseries"
version('0.10-42', '3feaa5c463bc967d749323163d9bc836')
depends_on('r-quadprog', type=('build', 'run'))
depends_on('r-zoo', type=('build', 'run'))
depends_on('r-quantmod', type=('build', 'run'))
|
simonvh/genomepy | genomepy/cli.py | Python | mit | 11,846 | 0.00076 | #!/usr/bin/env python
"""Command line wrappers"""
import os
import sys
from collections import deque
import click
from colorama import Fore, Style, init
from loguru import logger
import genomepy
init(autoreset=True)
CONTEXT_SETTINGS = dict(help_option_names=["-h", "--help"])
@click.group(context_settings=CONTEXT_... | omes", short_help="list available genomes")
@click.option("-p", "--provider", help="provider")
def genomes(provider=None):
"""
List all available genomes.
Returns the metadata of each found genome, including the availability of a gene annotation.
For UCSC, up to 4 gene annotation styles are available:
... | rovider_init = True
for row in genomepy.list_available_genomes(provider):
if provider_init:
provider_init = False
terminal_header()
if str(provider).lower() in ["none", "ucsc"]:
terminal_subheader()
terminal_formatting(row)
# extended options for... |
viswimmer1/PythonGenerator | data/python_files/34442233/models.py | Python | gpl-2.0 | 827 | 0.004837 | import simplejson
import datetime
#import facebook
import urllib
from django.contrib.auth.models import User
from django.db import models
from django.db.models.signals import pre_save, post_save, pre_delete
from django.utils.translation import ugettext_lazy as _
class GoogleProfile(models.Model):
user = models.... | ld(blank=True, null=True)
location = models.CharField(max_length=100, blank=True, null=True)
created_at = models.DateTim | eField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __unicode__(self):
return self.user.username
|
djedproject/djed.layout | djed/layout/__init__.py | Python | isc | 8,833 | 0.000453 | import re
import json
import logging
import random
import venusian
from collections import namedtuple
from collections import OrderedDict
from zope.interface import providedBy, Interface
from pyramid.compat import string_types
from pyramid.config.views import DefaultViewMapper
from pyramid.location import lineage
from ... | fg.registry.registerAdapter(
info, (root, request_iface, context), ILayout, name)
cfg.action(discr, register, introspectables=(intr,))
class LayoutRenderer(object):
def __init__(self, layout):
self.layout = layout
def layout_info(self, layout, context, request, content):
int... | if view is not None:
layout_factory = '%s.%s'%(view.__module__, view.__name__)
else:
layout_factory = 'None'
data = OrderedDict(
(('name', intr['name']),
('parent-layout', intr['parent']),
('layout-factory', layout_factory),
... |
RaduGatej/SensibleData-Platform | sensible_data_platform/oauth2_authorization_server/urls.py | Python | mit | 421 | 0.007126 | from django.conf.urls import patterns, include, url
from django.c | ontrib import admin
ad | min.autodiscover()
urlpatterns = patterns('',
# url(r'^account/', include('oauth2_authorization_server.account_urls')),
# url(r'^client/', include('oauth2_authorization_server.client_urls')),
url(r'^oauth2/', include('oauth2_authorization_server.oauth2_urls')),
# url(r'^', 'oauth2_authorization_server.vie... |
DougFirErickson/qgisSpaceSyntaxToolkit | esstoolkit/explorer/AttributeSymbology.py | Python | gpl-3.0 | 10,530 | 0.003514 | # -*- coding: utf-8 -*-
"""
/***************************************************************************
essToolkit
Space Syntax Toolkit
Set of tools for essential space syntax network analysis and results exploration
-------------------
begin ... | nges: EqualInterval = 0; Quantile = 1; Jenks = 2; StdDev = 3; Pretty = 4; Custom = 5
intervals = int(settings['intervals'])
mode = int(settings['interval_type'])
attribute = attribute_vals['name']
renderer = None
if mode < 3:
# set symbol type and line width
... | symbol.type() == 1: # line
symbol.setWidth(line_width)
elif symbol.type() == 2: # line
symbol = QgsFillSymbolV2.createSimple({'style': 'solid', 'color': 'black', 'width_border': '%s' % line_width})
elif symbol.type() == 0: # point
... |
orvi2014/kitsune | kitsune/kbadge/tasks.py | Python | bsd-3-clause | 1,390 | 0 | from django.conf import settings
from django.contrib.sites.models import Site
from celery import task
from tower import ugettext as _
from kitsune.sumo.decorators import timeit
from kitsune.sumo import email_utils
@task()
@timeit
def send_award_notification(award):
"""Sends the award notification email
:ar... | mail = email_utils.make_mail(
subject=subject,
text_template='kbadge/email/award_notification.ltxt',
html_template='kbadge/email/award_notification.html',
context_vars=context,
from_email=settings.DEFAULT_FROM_EMAIL,
to_email=email)
ret... | locale=award.user.profile.locale,
context={
'host': Site.objects.get_current().domain,
'award': award,
'badge': award.badge,
},
email=award.user.email
)
# FIXME: this sends emails to the person who was awarded the
# badge. Should we also sen... |
nishij66/Strutagio | strutagio.py | Python | mit | 2,497 | 0.011614 | from __future__ import division
import cv2
import numpy as np
tolerance = 40
visited = []
def rough_scan(image):
width, height = image_size(image)
for j in range(0, height, 100):
for i in range(0, width, 100):
if i > 50 and i < width-50:
if check_difference(image[j,i]) == T... | e)
rotated = np.rot90(rotated)
return rotated
def check_down(image, i ,j, check = False):
good = True
if (j < 2770):
for x in range(200):
if good == True:
visited.append([j+x,i])
if check_difference(image[j+x,i]) == False:
good = F... | tolerance:
return False
return True
#image_size returns the dimensions of the image in width, height format
def image_size(image):
return tuple(image.shape[1::-1])
def get_tolerance(image, width, height):
global tolerance
total = 0
num = 0
for j in range(50, height, 100):
for i... |
EmreAtes/spack | var/spack/repos/builtin/packages/py-virtualenvwrapper/package.py | Python | lgpl-2.1 | 2,186 | 0.000915 | ##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | eir dependencies."""
homepage = "https://bitbucket.org/virtualenvwrapper/virtualenvwrapper.git"
url = "https://pypi.io/packages/source/v/virtualenvwrapper/virtualenvwrapper-4.8.2.tar.gz"
version('4.8.2', '8e3af0e0d42733f15c5e36df484a952e')
depends_on('python@2.6:')
depends_on('py-vir | tualenv', type=('build', 'run'))
depends_on('py-virtualenv-clone', type=('build', 'run'))
depends_on('py-stevedore', type=('build', 'run'))
# not just build-time, requires pkg_resources
depends_on('py-setuptools', type=('build', 'run'))
|
mikesname/python-ocrlab | ocrsite/ocrlab/nodes/web.py | Python | mit | 3,561 | 0.001966 | """
Nodes that use web services to do something.
"""
import json
import httplib2
import urllib
from BeautifulSoup import BeautifulSoup
from nodetree import node, exceptions
from . import base
from .. import stages
class WebServiceNodeError(exceptions.NodeError):
pass
class BaseWebService(node.Node, base.TextW... | ion."""
stage = stages.POST
baseurl = "http://spotlight.dbpedia.org/rest/annotate/"
parameters = [
dict(name="confident", value=0.2),
dic | t(name="support", value=20),
]
def process(self, input):
http = httplib2.Http()
headers = {}
body = dict(
text=input.encode("utf8", "replace"),
confidence=self._params.get("confident"),
support=self._params.get("support"),
)
... |
nicolaoun/NS3-AM-Proto-Simulation | collect_data_v2_mwmr.py | Python | gpl-2.0 | 19,411 | 0.027871 | import os
from time import sleep
import sys
def get_single_test_avg_results(filename):
# For each file
srv_msgs=0
w_sentMsgs = 0
w_invokedWrites = 0
w_completedWrites = 0
r_sentMsgs = 0
r_invokedReads = 0
r_completedReads = 0
r_slowReads = 0
r_fastReads = 0
r_avgtime = 0
r_avgCommtime = 0
r_avgComptime... | hSAM, ohMam and Impossibility MWMR
r_slowReads += int(line.split("3EXCH_reads=")[1].split(",")[0])
r_fastReads += 0
elif (protocol == "SwImp"): #Impossibility for SWMR
r_slowReads += int(line.split("2EXCH_ | reads=")[1].split(",")[0])
r_fastReads += 0
elif (protocol == "oh-Fast") or (protocol == "oh-SamEX") or (protocol == "oh-MamEX"): #Extensions
r_slowReads += int(line.split("3EXCH_reads=")[1].split(",")[0])
r_fastReads += int(line.split("2EXCH_reads=")[1].split(",")[0])
else: #Hybrid #Semifas... |
mycFelix/heron | heronpy/api/tests/python/topology_unittest.py | Python | apache-2.0 | 10,071 | 0.00566 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache... | Grouping
from heronpy.api.component.component_spec import HeronComponentSpec
from her | onpy.proto import topology_pb2
# required environment variable
# note that this test doesn't write anything to /tmp directory
heron_options = "cmdline.topologydefn.tmpdirectory=/tmp,cmdline.topology.initial.state=RUNNING"
os.environ["HERON_OPTIONS"] = heron_options
class TestSane(Topology):
config = {"topology.wide... |
tchellomello/home-assistant | homeassistant/components/androidtv/media_player.py | Python | apache-2.0 | 24,075 | 0.000955 | """Support for functionality to interact with Android TV / Fire TV devices."""
from datetime import datetime
import functools
import logging
import os
from adb_shell.auth.keygen import keygen
from adb_shell.exceptions import (
AdbTimeoutError,
InvalidChecksumError,
InvalidCommandError,
InvalidResponseE... |
}
def setup_androidtv(hass, config):
"""Generate an ADB key (if needed) and load it."""
adbkey = config.get(CONF_ADBKEY, hass.config.path(STORAGE_DIR, "androidtv_adbkey"))
if CONF_ADB_SERVER_IP not in config:
# Use "adb_shell" (Python ADB implementation)
if not os.path.isfile(adbkey):
... | key(adbkey)
adb_log = f"using Python ADB implementation with adbkey='{adbkey}'"
else:
# Use "pure-python-adb" (communicate with ADB server)
signer = None
adb_log = f"using ADB server at {config[CONF_ADB_SERVER_IP]}:{config[CONF_ADB_SERVER_PORT]}"
return adbkey, signer, adb_log
... |
Alberto-Beralix/Beralix | i386-squashfs-root/usr/lib/python2.7/dist-packages/papyon/service/AddressBook/scenario/contacts/block_contact.py | Python | gpl-3.0 | 100 | 0.02 | ../../../../../../../../share/p | yshared/papyon/service/AddressBook/scenario/contacts/block_co | ntact.py |
TailorDev/Watson | tests/conftest.py | Python | mit | 508 | 0 | """Provide fixtures for pytest-based unit tests."""
from click.testing import CliRunner
import pytest
from watson import Watson
@pytest.fixture
def config_dir(tmpdir):
return str(tmpdir.mkdir('config'))
@pytest.fixture
def watson | (config_dir):
return Watson(config_dir=config_dir)
@pytest.fixture
def runner():
return CliRunner()
@pytest.fixture
def watson_df(datafiles):
"""Creates a Watson object with datafiles in config directory."""
return Watson(config_dir=str(datafiles | ))
|
dmpetrov/dataversioncontrol | dvc/command/machine.py | Python | apache-2.0 | 16,882 | 0 | import argparse
from dvc.command.base import CmdBase, append_doc_link, fix_subparsers
from dvc.command.config import CmdConfig
from dvc.compare import TabularData
from dvc.config import ConfigError
from dvc.exceptions import DvcException
from dvc.types import Dict, List
from dvc.ui import ui
from dvc.utils import form... | ad(self.args.level)
try:
print(conf["core"]["machine"])
except KeyError:
ui.write("No default machine set")
return 1
else:
with self.config.edit(self.args.level) as conf:
if sel | f.args.unset:
conf["core"].pop("machine", None)
else:
merged_conf = self.config.load_config_to_level(
self.args.level
)
if (
self.args.name in conf["machine"]
... |
twobraids/socorro | socorro/unittest/external/hbase/test_crashstorage.py | Python | mpl-2.0 | 18,322 | 0.001419 | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import os
import time
import json
from contextlib import nested
import mock
from nose.tools import eq_, ok_, assert_rai... | fake_dumps['adrian'])
# hasn't been processed yet
assert_raises(CrashIDNotFound,
crashstorage.get_processed,
crash_id)
pro = ('{"name":"Peter",'
'"uuid":"86b58ff2-... | bmitted_timestamp":"%d", '
'"completeddatetime": "%d"}' %
(time.time(), time.time()))
crashstorage.save_processed(json.loads(pro))
data = crashstorage.get_processed(crash_id)
eq_(data['name'], u'Peter')
hb_co... |
GerardWassink/elevator.py | gawterm.py | Python | gpl-2.0 | 7,411 | 0.026987 |
# ------------------------------------------------------------------------
# Program : gawterm.py
# Author : Gerard Wassink
# Date : March 17, 2017
#
# Function : supply a terminal window with panes for remote control
# of my elevator, can also be used for other contraptions
#
# History : 20170317 - original... | --------------------------------------------------------------
# Copyright (C) 2017 Gerard Wassink
# ------------------------------------------------------------------------
# ------------------------------------------------------------------------
# Libraries used
# ------------------------------------------------... | +--- staFrame -----------------++--- msgFrame -----------------+
|stawin ||msgwin |
| || |
| || |
| || ... |
gmimano/commcaretest | corehq/apps/reports/standard/cases/basic.py | Python | bsd-3-clause | 9,772 | 0.002251 | import logging
from couchdbkit import RequestFailed
from django.utils.translation import ugettext_noop, ugettext
from django.utils.translation import ugettext as _
import simplejson
from corehq.apps.api.es import CaseES
from corehq.apps.groups.models import Group
from corehq.apps.reports.api import ReportDataSource
fro... | user_filters = list(_filter_gen('owner_id', owner_ids))
if user_filters:
subterms.append({'or': user_filters})
if search_string:
query_block = {
"query_string": {"query": search_stri | ng}} # todo, make sure this doesn't suck
else:
query_block = {"match_all": {}}
and_block = {'and': subterms} if subterms else {}
es_query = {
'query': {
'filtered': {
'query': query_block,
'filter': and_block
... |
plotly/python-api | packages/python/plotly/plotly/validators/scattermapbox/hoverlabel/font/_sizesrc.py | Python | mit | 498 | 0 | import _plotly_utils.basevalida | tors
class SizesrcValidator(_plotly_utils.basevalidators.SrcValidator):
def __init__(
self,
plotly_name="sizesrc",
parent_name="scattermapbox.hoverlabel.font",
**kwargs
):
super(SizesrcValidator, self).__init__(
plotly_name=plotly_name,
parent_na... |
)
|
fxia22/ASM_xf | PythonD/lib/python2.4/site-packages/display/PIL/PcdImagePlugin.py | Python | gpl-2.0 | 1,813 | 0.005516 | #
# The Python Imaging Library.
# $Id: //modules/pil/PIL/PcdImagePlugin.py#4 $
#
# PCD file handling
#
# History:
# 96-05-10 f | l Created
# 96-05-27 fl Added draft mode (128x192, 256x384)
#
# Copyright (c) Secret Labs AB 1997.
# Copyright (c) Fredrik Lundh 1996.
#
# See the README file for information on usage and redistribution.
#
__version__ = "0.1"
import Image, ImageFile
##
# Image plugin for PhotoCD images. This plugin ... | ng.
class PcdImageFile(ImageFile.ImageFile):
format = "PCD"
format_description = "Kodak PhotoCD"
def _open(self):
# rough
self.fp.seek(2048)
s = self.fp.read(2048)
if s[:4] != "PCD_":
raise SyntaxError, "not a PCD file"
orientation = ord(s[1538]) & 3... |
lzamparo/SdA_reduce | plot_scripts/lle_embed_test.py | Python | bsd-3-clause | 3,284 | 0.007917 | from sklearn import metrics
from sklearn.mixture import GMM
from sklearn.preprocessing import scale
from sklearn.manifold import LocallyLinearEmbedding
import logging, os
from optparse import OptionParser
import sys
from time import time
import numpy as np
import pandas as pd
from tables import *
from extract_dataset... | ("--h5file",
dest="inputfile", help="Read data input from this hdf5 file.")
op.add_option("--output",
dest="outputfile", he | lp="Write matrix to .npy output file.")
op.add_option("--size",
dest="size", type="int", help="Extract the first size chunks of the data set and labels.")
op.add_option("--high",
dest="high", type="int", help="Start at high dimensions.")
op.add_option("--low",
dest="low", type=... |
frew/simpleproto | scons-local-1.1.0/SCons/compat/_scons_itertools.py | Python | bsd-2-clause | 3,817 | 0.004192 | #
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the... | for x in iterables:
result.extend(list(x))
return result
def count(n=0):
# returns infinite length, should not be su | pported
raise NotImplementedError
def cycle(iterable):
# returns infinite length, should not be supported
raise NotImplementedError
def dropwhile(predicate, iterable):
result = []
for x in iterable:
if not predicate(x):
result.append(x)
break
result.extend(itera... |
joshowen/django-mailviews | mailviews/previews.py | Python | apache-2.0 | 8,746 | 0.001601 | from base64 import b64encode
from collections import namedtuple
from email.header import decode_header
import logging
from mailviews.helpers import should_use_staticfiles
from mailviews.utils import split_docstring, unimplemented
import os
import pprint
from django.core.urlresolvers import reverse
from django.http imp... |
'headers': headers,
'raw': raw.as_string(),
})
alternatives = getattr(message, 'alternatives', [])
try:
html = next(alternative[0] for alternative in alternatives
if alternative[1] == 'text/html')
context.update({
... | 'escaped_html': b64encode(html.encode('utf-8')),
})
except StopIteration:
pass
return render(request, self.template_name, context)
def send_view(self, request):
"""
Sends a test preview email
"""
context = {
'previe... |
andr3wmac/metaTower | packages/dlmanager/NZB/NZBClient.py | Python | gpl-3.0 | 10,499 | 0.012858 | import sys, os, urllib, time, socket, mt, ssl
from dlmanager.NZB import NZBParser
from dlmanager.NZB.nntplib2 import NNTP_SSL,NNTPError,NNTP, NNTPReplyError
from dlmanager.NZB.Decoder import ArticleDecoder
class StatusReport(object):
def __init__(self):
self.message = "Downloading.."
self.total_byt... | d.
def decodeFailed(self, seg):
if ( seg == None ): return
mt.log.debug("Segment failed to decode: " + seg.msgid)
self.segFailed(seg)
# Article Decoder - Assembly Status.
def assemblyStatus(self, percent):
self.status.assembly = True
self.status.assembly_percent = pe... | f.connection_count -= 1
# NNTP Connection - Segment completed.
def segComplete(self, seg):
if ( seg == None ): return
if ( seg.data ):
data_size = len("".join(seg.data))
current_time = time.time()
if ( (current_time - self.speedTime) > 1 ):
... |
mancoast/CPythonPyc_test | fail/314_test_ssl.py | Python | gpl-3.0 | 52,209 | 0.001475 | # Test the support for SSL and sockets
import sys
import unittest
from test import support
import socket
import select
import errno
import subprocess
import time
import gc
import os
import errno
import pprint
import urllib.parse, urllib.request
import shutil
import traceback
import asyncore
import weakref
from http.s... | em)
pem = ssl.get_server_certificate(("svn.python.org", 443), ca_certs=SVN_PYTHON_ORG_ROOT_CERT)
if not pem:
self.fail("No server certificate on svn.python.org:443!")
if support.verbose:
sys.stdout.write("\nVerified certificate for svn.python.org:443 ... | s\n" % pem)
# Test disabled: OPENSSL_VERSION* not available in Python 3.1
def test_algorithms(self):
if support.verbose:
sys.stdout.write("test_algorithms disabled, "
"as it fails on some old OpenSSL versions")
return
# Issue #8484: all algorithm... |
anaselli/libyui-bindings | swig/python/examples/mga-dialogs.py | Python | lgpl-3.0 | 3,012 | 0.010292 | #!/usr/bin/env python
# vim: set et ts=4 sw=4:
#coding:utf-8
#############################################################################
#
# mga-dialogs.py - Show mga msg dialog and about dialog.
#
# License: GPLv3
# Author: Angelo Naselli <anaselli@linux.it>
#######################################################... | ose")
|
def ask_YesOrNo(self, info):
yui.YUI.widgetFactory
mgafactory = yui.YMGAWidgetFactory.getYMGAWidgetFactory(yui.YExternalWidgets.externalWidgetFactory("mga"))
dlg = mgafactory.createDialogBox(yui.YMGAMessageBox.B_TWO)
dlg.setTitle(info.title)
dlg.setText(info.text, info.rich... |
pre-commit/pre-commit | testing/util.py | Python | mit | 3,561 | 0 | from __future__ import annotations
import contextlib
import os.path
import subprocess
import pytest
from pre_commit import parse_shebang
from pre_commit.util import CalledProcessError
from pre_commit.util import cmd_output
from pre_commit.util import cmd_output_b
from testing.auto_namedtuple import auto_namedtuple
... | diff_on_failure,
commit_msg_filename=commit_msg_filename,
checkout_type=checkout_type,
is_squash_merge=is_squash_merge,
rewrite_command=rewrite_command,
)
@contextlib.contex | tmanager
def cwd(path):
original_cwd = os.getcwd()
os.chdir(path)
try:
yield
finally:
os.chdir(original_cwd)
def git_commit(*args, fn=cmd_output, msg='commit!', all_files=True, **kwargs):
kwargs.setdefault('stderr', subprocess.STDOUT)
cmd = ('git', 'commit', '--allow-empty', '... |
lootr/netzob | netzob/src/netzob/Model/Vocabulary/Messages/L2NetworkMessage.py | Python | gpl-3.0 | 4,639 | 0.00712 | # -*- coding: utf-8 -*-
#+---------------------------------------------------------------------------+
#| 01001110 01100101 01110100 01111010 01101111 01100010 |
#| |
#| Netzob : Inferring communication protocol... | ess="00:02:3f:a8:bf:21")
>>> print(msg.source)
00:02:7b:00:bf:33
>>> print(msg.destination)
00:02:3f:a8:bf:21
>>> print(msg)
\033[0;32m[1352293417.28 \033[0;m\033[1;32m00:02:7b:00:bf:33\033[1;m\033[0;32m->\033[0;m\033[1;32m00:02:3f:a8:bf:21\033[1;m\033[0;32m]\033[0;m '090002300202f000'
"""
... | date=None,
l2Protocol=None,
l2SourceAddress=None,
l2DestinationAddress=None):
super(L2NetworkMessage, self).__init__(
data,
date=date,
source=l2SourceAddress,
destination=l2DestinationAddress,
mess... |
claha/suunto | suunto/__init__.py | Python | mit | 86 | 0.011628 | from .workout import Workout
from .duration | import Time
from .dura | tion import Distance |
ioos/petulant-bear | petulantbear/netcdf_etree.py | Python | gpl-3.0 | 15,893 | 0.002139 | #!/usr/bin/env python
'''
COPYRIGHT 2013 RPS ASA
This file is part of Petulant Bear.
Petulant Bear 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 op... | # containing the variable
nc_object.group().renameVariable(self[NAME], value)
elif key == SHAPE:
raise NetcdfEtreeException(
'''The shape of th | e variable "{}" can not be modified in a NetCDF4 Python Dataset'''.format(
self[NAME]))
elif key == ISUNLIMITED:
raise NetcdfEtreeException(
'''The type of the variable "{}" can not be changed once it is created as in a NetCDF4 Python Dataset'''.format(
... |
neutrons/FastGR | addie/processing/mantid/launch_reduction.py | Python | mit | 3,590 | 0.000836 | import os
import traceback
from mantidqt.utils.asynchronous import AsyncTask
from addie.processing.mantid.master_table.master_table_exporter import TableFileExporter as MantidTableExporter
# Mantid Total Scattering integration
# (https://github.com/marshallmcdonnell/mantid_total_scattering)
try:
import total_scat... | ABLED:
pool = JobPool(reduction_inputs)
pool.start()
else:
| # TODO should be on the status bar
print('total_scattering module not found. Functionality disabled')
|
Yelp/undebt | undebt/examples/deprecated_inequality_operator.py | Python | apache-2.0 | 470 | 0 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from undebt.pattern.lang.python import UNARY_OP_ATOM
from undebt.pattern.util import tokens_as_list
fro | m undebt.pyparsing import Literal
grammar = UNARY_OP_ATOM + Literal("<>").suppress() + UNARY_OP_ATOM
@tokens_as_list(a | ssert_len=2)
def replace(tokens):
"""foo <> bar -> foo != bar"""
return tokens[0] + " != " + tokens[1]
|
ofirr/dojango | dojango/views.py | Python | bsd-3-clause | 14,326 | 0.037135 | # Create your views here.
from django.apps import apps
from functools import reduce
get_model = apps.get_model
from django.db import models
from django.shortcuts import render_to_response
from django.conf import settings
from dojango.util import to_dojo_data, json_encode
from dojango.decorators import json_response
fr... | k(app_name, model_name, k, request, data)]
for k in add_ons:
ret[k] = getattr(data, k)
if 'inclusions' in request.GET:
for k in request.GET['inclusions'].split(','):
if k == "": continue
if a | ccess_field_callback(app_name, model_name, k, request, data):
try:
ret[k] = getattr(data,k)()
except:
try:
ret[k] = eval("data.%s"%".".join(k.split("__")))
... |
mbakker7/ttim | ttim/fit.py | Python | mit | 10,043 | 0.007269 | import numpy as np
import pandas as pd
from scipy.optimize import least_squares
import re
import lmfit
class Calibrate:
def __init__(self, model):
"""initialize Calibration class
Parameters
----------
model : ttim.Model
model to calibrate
"... | ation object
Parameters
----------
name : str
name of series
element: element object with headinside function
t : np.array
array containing timestamps of timeseries
h : np.array
array containing timeseries values, i.e. head obs... | """method to calculate residuals given certain parameters
Parameters
----------
p : np.array
array containing parameter values
printdot : bool, optional
print dot for each function call
Returns
-------
np.array
... |
Nikea/VisTrails | vistrails/core/vistrail/module_function.py | Python | bsd-3-clause | 10,589 | 0.006516 | ###############################################################################
##
## Copyright (C) 2011-2014, NYU-Poly.
## Copyright (C) 2006-2011, University of Utah.
## All rights reserved.
## Contact: contact@vistrails.org
##
## This file is part of VisTrails.
##
## "Redistribution and use in source and binary for... | **kwargs)
if self.name is None:
self.name = ""
if self.real_id is None:
self.real_id = -1
if self.pos is None:
self.pos = -1
self.set_defaults()
def set_defaults(self, other=None):
if other is Non | e:
self.returnType = "void"
self.is_valid = False
else:
self.returnType = other.returnType
self.is_valid = other.is_valid
self.parameter_idx = self.db_parameters_id_index
def __copy__(self):
""" __copy__() -> ModuleFunction - Returns a clone o... |
foglamp/FogLAMP | python/foglamp/common/storage_client/storage_client.py | Python | apache-2.0 | 21,779 | 0.002939 | # -*- coding: utf-8 -*-
# FOGLAMP_BEGIN
# See: http://foglamp.readthedocs.io/
# FOGLAMP_END
""" Storage layer python client
"""
__author__ = "Praveen Garg, Amarendra K Sinha"
__copyright__ = "Copyright (c) 2017 OSIsoft, LLC"
__license__ = "Apache 2.0"
__version__ = "${VERSION}"
import aiohttp
import http.client
imp... | "condition" : "=",
"value" : "SENT_test"
},
"values" : {
"value" : 44444
}
}
"""
if not tbl_name:
| raise ValueError("Table name is missing")
if not data:
raise ValueError("Data to update is missing")
if not Utils.is_json(data):
raise TypeError("Provided data to update must be a valid JSON")
put_url = '/storage/table/{tbl_name}'.format(tbl_name=tbl_name)
... |
seanli9jan/tensorflow | tensorflow/contrib/saved_model/python/saved_model/keras_saved_model.py | Python | apache-2.0 | 16,089 | 0.006464 | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | """
# Save model configuration as a json string under assets folder.
model_json = model.to_json()
model_json_filepath = os.path.join(
saved_model_utils.get_or_create_assets_dir(saved_model_path),
compat.as_text(constants.SAVED_MODEL_FILENAME_JSON))
f | ile_io.write_string_to_file(model_json_filepath, model_json)
# Save model weights in checkpoint format under variables folder.
saved_model_utils.get_or_create_variables_dir(saved_model_path)
checkpoint_prefix = saved_model_utils.get_variables_path(saved_model_path)
model.save_weights(checkpoint_prefix, save_fo... |
markstoehr/spectral_features | local/display_bernoulli_model.py | Python | gpl-3.0 | 2,936 | 0.020436 | from __future__ import division
import numpy as np
import argparse
import matplotlib.pyplot as plt
from matplotlib.colors import colorConverter
from mpl_toolkits.axes_grid1 import ImageGrid
import matplotlib.cm as cm
from amitgroup.stats import bernoullimm
def main(args):
means = np.load('%s_means.npy' % args.sav... | grid[i*ncols+j+1].spines['bottom'].set_color('red')
grid[i*ncols+j+1].spines['top'].set_color('red')
grid[i*ncols+j+1].spines['left'].set_color('red')
grid[i*ncols+j+1].spines['right'].set_color('red')
for a in grid[i*ncols+j+1].axi... | import pdb; pdb.set_trace()
plt.savefig('%s' % args.display_bernoulli_parts
,bbox_inches='tight')
if __name__ == "__main__":
parser = argparse.ArgumentParser("""Clustering and output for bernoulli data with paired spectr... |
gregmuellegger/django-autofixture | autofixture_tests/models.py | Python | bsd-3-clause | 6,350 | 0 | # -*- coding: utf-8 -*-
from django.core.files.storage import FileSystemStorage
import os
from datetime import datetime
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.utils.timezone import utc
from autofixture.compat import get_GenericForeignKey
from autofixture.com... | cIPAddressField as IPAddressField
except ImportError:
from django.models import IPAddressField
filepath = os.path.dirname(os.path.abspath(__file__))
def y2k():
return datetime(2000, 1, 1).replace(tzinfo=utc)
class SimpleModel(models.Model):
name = | models.CharField(max_length=50)
class OtherSimpleModel(models.Model):
name = models.CharField(max_length=50)
class UniqueNullFieldModel(models.Model):
name = models.CharField(max_length=15, null=True, blank=True, unique=True)
class UniqueTogetherNullFieldModel(models.Model):
field_one = models.CharFie... |
opnfv/functest | functest/tests/unit/openstack/cinder/test_cinder.py | Python | apache-2.0 | 11,586 | 0 | #!/usr/bin/env python
# Copyright (c) 2018 Enea AB and others.
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, and is available at
# http://www.apache.org/licenses/LICENSE-2.0
# pylint: ... | ssh2 = mock.Mock()
self.cinder.vm2 = mock.Mock(id='foo')
self.cinder.volume = mock.Mock(id='volume')
stdout = mock.Mock()
self.cinder.ssh2.exec_command.return_value = (
No | ne, stdout, mock.Mock())
stdout.channel.recv_exit_status.return_value = 0
self.assertEqual(self.cinder._read_data(), 0)
self.cinder.ssh2.exec_command.assert_called_once_with(
f"sh ~/read_data.sh {env.get('VOLUME_DEVICE_NAME')}")
self.cinder.cloud.attach_volume.assert_called_o... |
sacharya/nova | nova/compute/api.py | Python | apache-2.0 | 164,307 | 0.000828 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# Copyright 2011 Piston Cloud Computing, Inc.
# Copyright 2012-2013 Red Hat, Inc.
# All Rights Reserved.
#
# Licensed under the Apache Lic... | 'use a raw disk image instead'),
cfg.StrOpt('multi_instance_display_name_template',
default='%(name)s-%(uuid)s',
help='When creating multiple instances with a single request '
'using the os-multiple-create API extension, this '
| 'template will be used to build the display name for '
'each instance. The benefit is that the instances '
'end up with different hostnames. To restore legacy '
'behavior of every instance having the same name, set '
'this option to ... |
JorisPLA7/Super-D-mineur | lib/web.py | Python | gpl-3.0 | 355 | 0.014085 | helppage = "https://github.com/JorisPLA7/Super-D-mineur"
githubpage = "https://github.com/JorisPLA7/Super-D-mineur/"
| rulepage = "http://demineur.hugames.fr/help.php"
import webbrowser
def help():
webbrowser.open(helppage)
def github():
webbrowser.open(githubpage)
def rules():
webbrowser.open(rulepage)
if __name__ == ' | __main__':
help()
|
flashpixx/MachineLearning | examples/other/build.py | Python | lgpl-3.0 | 2,333 | 0.013288 | ############################################################################
# LGPL License #
# #
# This file is part of the Machine Learning Framework. #
# Copyright ... | #
# You should have received a copy of the GNU Lesser General Public License #
# along with this program. If not, see <http://www.gnu.org/licenses/>. #
############################################################################
# -*- coding: utf-8 -*-
# build script for the other example
imp... | |
justhamade/kaleo | kaleo/urls.py | Python | bsd-3-clause | 167 | 0.005988 | from django.conf.urls.defaults import | url, patterns
from kaleo.vi | ews import invite
urlpatterns = patterns("",
url(r"^invite/$", invite, name="kaleo_invite"),
)
|
myvoice-nigeria/myvoice | myvoice/survey/management/commands/import_responses.py | Python | bsd-2-clause | 194 | 0 | from django.core.ma | nagement.base import BaseCommand
from ... import importer
class Command(BaseCommand):
def handle(self, flow_id, **options):
importer.import_responses(flow | _id)
|
rizar/actor-critic-public | lvsr/bricks/recognizer.py | Python | mit | 38,728 | 0.001472 | import copy
import logging
import numpy
import theano
from theano import tensor
from theano.gradient import disconnected_grad
from blocks.bricks import (
Bias, Identity, Initializable, MLP, Tanh, Softmax, Random)
from blocks.bricks.attention import SequenceContentAttention
from blocks.bricks.base import applicati... | data_prepend_eos=True,
# softmax is the default set in SequenceContentAndConvAttention
energy_normalize | r=None,
# for speech this is the approximate phoneme duration in frames
max_decoded_length_scale=1,
# for criterions involving generation of outputs, whether
# or not they should be generated by the recognizer itself
generate_predictio... |
concentricsky/badgr-server | apps/mainsite/migrations/0019_auto_20190710_0805.py | Python | agpl-3.0 | 515 | 0.001942 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.20 on 2019-07-10 15:05
from django.conf import settings
from django.db import migrations
class Migration(migrations | .Mig | ration):
dependencies = [
migrations.swappable_dependency(settings.OAUTH2_PROVIDER_ACCESS_TOKEN_MODEL),
('mainsite', '0018_auto_20190723_1532'),
]
operations = [
migrations.AlterUniqueTogether(
name='accesstokenscope',
unique_together=set([('token', 'scope')... |
siavooshpayandehazad/NoC_Router | Scripts/credit_based/network_tb_gen_parameterized_credit_based.py | Python | gpl-3.0 | 26,573 | 0.016069 | # Copyright (C) 2016 Siavoosh Payandeh Azad
from math import ceil, log
import random
# -D [size]: sets the size of the network, it can be powers of two
# -Rand: generates random traffic patterns
import sys
if '--help' in sys.argv[1:]:
print "\t-D [network size]: makes a test bench for network of [size]X[size]. S... | based.py -D 2 -Rand 0.005 -PS 3 3 -sim 10000 "
print "\t generates a testbench for a 2X2 network which uses random traffic pattern generator with PIR of 0.005 and fixed"
print "\t packet size of 3 and sends packets until 10000 ns"
sys.exit()
network_dime = 4
data_width = 32
random_dest = Fal... | = None
bit_reversal = False
get_packet_size = False
packet_size_min = 3
packet_size_max = 8
verbal = False
# file_path = file_name+'_'+str(network_dime)+"x"+str(network_dime)+'.vhd'
if '-D' in sys.argv[1:]:
network_dime = int(sys.argv[sys.argv.index('-D')+1])
if '-DW' in sys.argv[1:]:
data_width = int(sys.argv[... |
crmccreary/openerp_server | openerp/addons/html_view/html_view.py | Python | agpl-3.0 | 415 | 0.007229 |
from osv import osv, fields
class html_view(osv.osv):
_name = 'html.view'
_columns = {
'name': fields.char('Name', size=128, required=True, select=True),
'comp_id': fields.many2one('res.company', 'Company', select | =1),
'bank_ids': fields.one2many('res.partner.bank', 'partner_id', 'Banks'),
}
html_view()
# vim:expandtab:smartindent:tabstop=4 | :softtabstop=4:shiftwidth=4:
|
opportunitynetwork/devault | devault/devault/wsgi.py | Python | bsd-3-clause | 391 | 0 | """
WSGI config for devault project.
It exposes the WSGI callable as a module-level variable named ``application``.
For m | ore information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", " | devault.settings")
application = get_wsgi_application()
|
makokal/funzo | funzo/models/tests/test_mdp.py | Python | mit | 819 | 0 |
from nose.tools import assert_raises
from funzo.models.mdp import MDPState
from funzo.models.mdp import MDPAc | tion
from funzo.models.mdp import RewardFunction
from funzo.models.mdp import LinearRewardFunction
from funzo.models.mdp import TabularRewardFunction
from fun | zo.models.mdp import MDPTransition
from funzo.models.mdp import MDP
def test_state_init():
# check for non-instantiation of abstract class/interface
assert_raises(TypeError, MDPState, 0)
assert_raises(TypeError, MDPAction, 0)
assert_raises(TypeError, RewardFunction, None)
assert_raises(TypeError, ... |
kandithws/clothes_detection_egbis | clothes_detection/test_nodes/clothes_detection_dummy_node.py | Python | gpl-3.0 | 2,197 | 0.003641 | #! /usr/bin/env python
import rospy
import roslib
roslib.load_manifest('clothing_type_classification')
import actionlib
import clothing_type_classification.msg
import std_msgs
from sensor_msgs.msg import Image
from clothing_type_classification.msg import ClothesArray, Clothes
# Specified target Centroid Points and A... | _type_classification.msg.FindClothesFeedback()
self._result = clothing_type_classification.msg.FindClothesResult()
self._as.start()
| print "Current Clothes: "
index = 0
for i in result_clothes:
print "clothes[" + str(index) + "] = " + str(i)
index += 1
print "-------------Complete Initialization------------------"
def execute_cb(self, goal):
global result_clothes
rospy.loginfo("--... |
pombredanne/django-ostracker | setup.py | Python | bsd-3-clause | 502 | 0.005976 | #!/usr/bin/env python
from distutils.core import setup
setup(name='django-ostracker',
version='0.2.0-dev',
description='Django projec | t for tracking Open Source projects',
author='James Turk',
author_email='jturk@sunlightfoundation.com',
license='B | SD',
url='http://github.com/sunlightlabs/django-ostracker/',
packages=['ostracker', 'ostracker.management', 'ostracker.management.commands',],
package_data={'ostracker': ['templates/ostracker/*.html']},
)
|
AleCandido/Lab3.2 | Utilities/parser.py | Python | gpl-2.0 | 755 | 0.01457 | import numpy as np
import re
import os
def GetBlocks(filename):
'''
prende il filename e ritorna la lista [[[pt1.x,pt1.y],...],[blocco2],...]
'''
f=open(filename)
block=False
lastlist=[]
listone=[]
for i in f:
print(i)
if(re.match(r"[\d\.]+e[\+\-][\d]+\t[\d\.]+e[\+\-][\... | return listone
print("Test...")
l=GetBlocks | (r'C:\Users\silvanamorreale\Documents\GitHub\Lab3.2\parser test.txt')
print(l)
|
wunderlins/learning | python/jsondb/jsondatabase-0.1.1/jsondb/__init__.py | Python | gpl-2.0 | 114 | 0.008772 | from .db import Database
__ | version__ = "0.1.1"
__maintainer__ = "Gunther Co | x"
__email__ = "gunthercx@gmail.com"
|
mpdunne/orthofiller | utils/gff_to_gtf_safe.py | Python | gpl-3.0 | 2,600 | 0.02 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import subprocess
import csv
import sys
import os
# Write the path to the Galaxy file here!
# e.g. path_to_gff_converter_dir = "/you/files/Code/fml_gff3togtf-5c6f33e20fcc/"
path_to_gff_converter_dir = ""
def placehold(path_in, path_out):
lookup={}
with op... | lookup[x] = "pl_" + str(i)
for l in data:
if not "#" in l[0]: l[0] = lookup[l[0]]
write(data, path_out)
return lookup
def unplacehold(path_in, path_out, lookup):
with open(path_ | in, "r") as p:
data = list(csv.reader(p, delimiter="\t"))
for l in data:
if not "#" in l[0]: l[0] = lookup[l[0]]
write(data, path_out)
def write(data, path_out):
with open(path_out, "w") as o:
datawriter = csv.writer(o, del... |
ezotrank/wheezy.template | doc/conf.py | Python | mit | 7,922 | 0 | # -*- coding: utf-8 -*-
#
# wheezy.core documentation build configuration file, created by
# sphinx-quickstart on Fri Sep 9 20:36:50 2011.
#
# This file is execfile()d with the current directory set to its containing
# dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#... | sphinx = False
# If true, '(C) Copyright ...' is shown in the HTML footer. Default is True.
html_show_copyright = False
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is ... | _suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'wheezy.templatedoc'
# -- Options for LaTeX output ------------------------------------------------
# The paper size ('letter' or 'a4').
# latex_paper_size = 'letter'
# The font size ('10pt', '11pt' or '12pt').
# latex_font_size = '1... |
bigmlcom/python | bigml/tests/create_statistical_tst_steps.py | Python | apache-2.0 | 2,418 | 0.004136 | # -*- coding: utf-8 -*-
#
# Copyright 2015-2022 BigML
#
# Licensed under the A | pache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License | at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language govern... |
sebastienhupin/qxrad | tool/lib/qxjsonrpc/_server.py | Python | lgpl-3.0 | 6,539 | 0.007188 | #!/usr/bin/python
# -*- coding: ascii -*-
'''==========================================================================
qxjsonrpc - JSON-RPC backend for the qooxdoo JavaScript library
(C) 2007 - Viktor Ferenczi (python@cx.hu) - Licence: GNU LGPL
-----------------------------------------------------------------... | ns=self._sessions_class()
if logger is None:
self.logger=logging.getLogger(domain or '')
| self.logger.addHandler(logging.StreamHandler())
else:
self.logger=logger
# Information methods
def getDomain(self):
'''Get the domain identifier associated for this server.
Returns a string or None if no domains are supported.'''
return self.domain
... |
tzulitai/flink | flink-python/pyflink/fn_execution/tests/test_process_mode_boot.py | Python | apache-2.0 | 6,884 | 0.002469 | ################################################################################
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this... | self.assertIn("No provision endpoint provided.", exit_message)
| args = [self.runner_path, "--id", "1",
"--logging_endpoint", "localhost:0000",
"--provision_endpoint", "localhost:%d" % self.provision_port]
exit_message = subprocess.check_output(args, env=self.env).decode("utf-8")
self.assertIn("No control endpoint provided.", exi... |
hpfem/agros2d | resources/test/test_suite/particle_tracing/__init__.py | Python | gpl-2.0 | 56 | 0 | __all__ = ["particle_traci | ng"]
import particle | _tracing
|
jricardo27/holiday_planner | holiday_planner/holiday_place/migrations/0001_initial.py | Python | bsd-3-clause | 733 | 0.002729 | # -*- coding: utf-8 -*-
# Generated by Django | 1.9.6 on 2016-05-30 16:52
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Place',
fields=[
('id', m... | place')),
('longitude', models.FloatField(verbose_name='Longitude')),
('latitude', models.FloatField(verbose_name='Latitude')),
],
),
]
|
saurabh6790/test-med-app | utilities/cleanup_data.py | Python | agpl-3.0 | 6,503 | 0.038136 | # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
#!/usr/bin/python
# This script is for cleaning up of all data from system including
# all transactions and masters (excludes default masters).
# Basically after running this file, syste... | es Master': '',
'Letter Head': '',
'Leave Type': ['Leave Without Pay', 'Privilege Leave', 'Casual Leave', 'PL', 'CL', 'LWP',
'Compensatory Off', 'Sick Leave'],
'Appraisal Template': '',
'Item Group': ['All Item Groups', 'Default'],
'Item': '',
'Holiday List': '',
'Activity Type': '',
'Grade': '',
... | '],
'Event': '',
'Employment Type': '',
'Employee': '',
'Earning Type': ['Basic', 'Conveyance', 'House Rent Allowance', 'Dearness Allowance',
'Medical Allowance', 'Telephone'],
'Designation': '',
'Department': '',
'Deduction Type': ['Income Tax', 'Professional Tax', 'Provident Fund', 'Leave Deductio... |
jniediek/mne-python | mne/preprocessing/maxwell.py | Python | bsd-3-clause | 85,148 | 0 | # -*- coding: utf-8 -*-
# Authors: Mark Wronkiewicz <wronk.mark@gmail.com>
# Eric Larson <larson.eric.d@gmail.com>
# Jussi Nurminen <jnu@iki.fi>
# License: BSD (3-clause)
from functools import partial
from math import factorial
from os import path as op
import numpy as np
from scipy import linalg
... | spatiotemporal SSS.
coord_frame : str
The coordinate frame that the ``origin`` is specified in, either
``'meg'`` or ``'head'``. For empty-room recordings that do not have
a head<->meg transform ``info['dev_head_t']``, the MEG coordinate
frame should be used.
destination : str | a... | string path to a FIF file
containing a MEG device<->head transformation, or a 3-element array
giving the coordinates to translate to (with no rotations).
For example, ``destination=(0, 0, 0.04)`` would translate the bases
as ``--trans default`` would in MaxFilter™ (i.e., to the default
... |
agmlego/Creekfleet_Timer | firmware/horn_sequence.py | Python | mit | 2,928 | 0.000342 | LONG_HORN = 750
LONG_HORN_SPACE = LONG_HORN/2
SHORT_HORN = 400
SHORT_HORN_SPACE = SHORT_HORN/2
sequences = {
'CreekFleet': {
# Three long horns immediately (three minutes to start)
0: 'LLL',
# Two long horns a minute later (two minutes to start)
60000: 'LL',
# One... | _TIMES = []
HORN_COMMANDS = []
|
for horn, blasts in sequence.items():
stepTime = horn
for blast in blasts:
HORN_TIMES.append(stepTime)
HORN_COMMANDS.append(True)
if blast == 'L':
stepTime += LONG_HORN
HORN_TIMES.append(stepT... |
teeple/pns_server | work/install/Python-2.7.4/Lib/email/test/test_email.py | Python | gpl-2.0 | 130,364 | 0.000882 | # Copyright (C) 2001-2010 Python Software Foundation
# Contact: email-sig@python.org
# email package unit tests
import os
import sys
import time
import base64
import difflib
import unittest
import warnings
import textwrap
from cStringIO import StringIO
import email
from email.Charset import Charset
from email.Header... | # Subpart 1 is 7bit encoded
eq(msg.get_payload(0).get_payload(decode=True),
'This is a 7bit encoded message.\n')
# Subpart 2 is quopri
eq(msg.get_payload(1).get_payload(decode=True),
'\xa1This is a Quoted Printable encoded message!\n')
# Subpart 3 is base64
... | which
# used to be stripped (issue 7143).
eq(msg.get_payload(3).get_payload(decode=True),
'This is a Base64 encoded message.\n')
# Subpart 5 has no Content-Transfer-Encoding: header.
eq(msg.get_payload(4).get_payload(decode=True),
'This has no Content-Transfer-Encod... |
tomkralidis/geonode | geonode/layers/tasks.py | Python | gpl-3.0 | 1,791 | 0 | # -*- coding: utf-8 -*-
#########################################################################
#
# Copyright (C) 2017 OSGeo
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 ... | eneral Public License
# | along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#########################################################################
"""celery tasks for geonode.layers."""
from geonode.celery_app import app
from celery.utils.log import get_task_logger
from django.db import IntegrityError, transaction
fro... |
yafraorg/yafra-toroam | com.toroam.appengine2/tests/test_crud.py | Python | apache-2.0 | 3,076 | 0 | # Copyright 2015 Google 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 agreed to in writing, ... | rs occur they
# can be retried. This is useful when databases are temporarily unavailable.
@flaky(rerun_filter=flaky_filter)
# Tell pytest to use both the app and model fixtures for all test cases.
# This ensures that configuration is properly applied and that all database
# resources created during tes | ts are cleaned up. These fixtures are defined
# in conftest.py
@pytest.mark.usefixtures('app', 'model')
class TestCrudActions(object):
def test_list(self, app, model):
for i in range(1, 12):
model.create({'title': u'Book {0}'.format(i)})
with app.test_client() as c:
rv = c.... |
c0710204/Ibistu-serverV2 | webserver/ibistu_serverV2_webserver/ibistu_serverV2_webserver/settings.py | Python | apache-2.0 | 5,483 | 0.001277 | # Django settings for ibistu_serverV2_webserver | project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
('admin', 'c0710204@gmail.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'admin.db', # Or path to ... | lite3.
# The following settings are not used with sqlite3:
'USER': '',
'PASSWORD': '',
'HOST': '', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
'PORT': '', # Set to empty string for default.
}... |
ncongleton/njcongleton.com | blog/migrations/0024_auto_20160926_2134.py | Python | gpl-2.0 | 564 | 0.001773 | # -*- coding: | utf-8 -*-
# Generated by Django 1.10.1 on 2016-09-26 21:34
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0023_auto_20160305_0653'),
]
operations = [
migrations.AlterField(
mo... | sTW1T5dnK570oNgrZijTFOYPFguacsyGjRnKVjGanzNGPonDeCuTibwWzAbe7OFBZXJBv6pY7ClG8wsdIIyhbEH5e4NS', max_length=150),
),
]
|
AloneRoad/Inforlearn | vendor/django/forms/widgets.py | Python | apache-2.0 | 25,335 | 0.002881 | """
HTML Widget classes
"""
try:
set
except NameError:
from sets import Set as set # Python 2.3 fallback
import copy
from itertools import chain
from django.conf import settings
from django.utils.datastructures import MultiValueDict, MergeDict
from django.utils.html import escape, conditional_escape
from dj... | self, '_' + name, None))
getattr(combined, 'add_' + name)(getattr(other, '_' + name, None))
| return combined
def media_property(cls):
def _media(self):
# Get the media property of the superclass, if it exists
if hasattr(super(cls, self), 'media'):
base = super(cls, self).media
else:
base = Media()
# Get the media definition for this class
... |
devendermishrajio/nova | nova/network/base_api.py | Python | apache-2.0 | 14,354 | 0.000139 | # Copyright 2014 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 requi... | wargs):
self.skip_policy_check = skip_policy_check
super(NetworkAPI, self).__init__(**kwargs)
def get_all(self, context):
"""Get all the networks for client."""
raise NotImplementedError()
def get(self, context, network_uuid):
"""Get specific network for client."""
... | rror()
def create(self, context, **kwargs):
"""Create a network."""
raise NotImplementedError()
def delete(self, context, network_uuid):
"""Delete a specific network."""
raise NotImplementedError()
def disassociate(self, context, network_uuid):
"""Disassociate a ne... |
spacelis/anatool | anatool/dm/visual.py | Python | mit | 6,377 | 0.007841 | import pdb
#!python
# -*- coding: utf-8 -*-
"""File: visual.py
Description:
This module contains visualizing method for geo data
History:
0.1.0 The first version.
"""
__version__ = '0.1.0'
__author__ = 'SpaceLis'
import dataset
from anatool.dm.db import GEOTWEET
import text_util
from operator im... |
if len(dist[key]) > 1:
dist2[key] = len(dist[key])
del dist
sortdist = sorted(dist2.iteritems(), key=itemgetter(1), reverse=True)
if draw:
width = 0.35
| idx = np.arange(len(sortdist))
plt.bar(idx, [val for key, val in sortdist])
plt.ylabel('Freq')
plt.title('Sorted Words Frequency')
#plt.xticks(idx+width/2., [key for key, val in sortdist] )
plt.show()
return sortdist
def poi_freq(twt_lst, table = 'sample', draw =... |
r0balo/pelisalacarta | python/main-classic/channels/seodiv.py | Python | gpl-3.0 | 5,982 | 0.021237 | # -*- coding: utf-8 -*-
# ------------------------------------------------------------
# Canal (seodiv) por Hernan_Ar_c
# ------------------------------------------------------------
import urlparse,urllib2,urllib,re
import os, sys
from core import logger
from core import config
from core import scraperto... | url_base= item.url |
patron = '<a class="collapsed" data-toggle="collapse" data-parent="#accordion" href=.*? aria-expanded="false" aria-controls=.*?>([^<]+)<\/a>'
matches = re.compile(patron,re.DOTALL).findall(data)
temp=1
if 'Temporada'in str(matches):
for scrapedtitle in matches:
url = url_base
... |
gangadhar-kadam/sms-erpnext | setup/doctype/price_list/test_price_list.py | Python | agpl-3.0 | 146 | 0.047945 | test_records = [
[{
"doctype": "Price List",
"price_list_name": "_Test Price List",
"c | urrency": "INR",
"valid_for_all_countries": 1
}]
] | |
tsandrini/dosu | dosu/utils.py | Python | mit | 2,094 | 0.041109 | """
__/\\\\\\\\\\\\______________________/\\\\\\\\\\\____/\\\________/\\\_
_\/\\\////////\\\__________________/\\\/////////\\\_\/\\\_______\/\\\_
_\/\\\______\//\\\________________\//\\\______\///__\/\\\_______\/\\\_
_\/\\\_______\/\\\_____/\\\\\______\////\\\_________\/\\\_______\/\\\_
_\/\\\_______\/\\\___/... | /.config/dosu/config.yml',
HOME + '/.dosu.yml',
)
def __init__(self):
self.config = self.load_raw_config()
self.subjects = self.load_subjects()
def load_raw_config(self):
| for config_path in self.config_paths:
try:
with open(config_path, 'r') as ymlfile:
return yaml.load(ymlfile)
except IOError as e:
continue
else:
return None
def load_subjects(self):
if not self.config:
... |
NejcZupec/ggrc-core | test/selenium/src/lib/constants/log.py | Python | apache-2.0 | 344 | 0 | # Cop | yright (C) 2016 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
FORMAT = """%(asctime)s
:%(name)s:
%(levelname)s
:%(module)s
:%(funcName)
:%(lineno)s
:%(message)s"""
SELENIUM_REMOTE_CONNECTION = "selenium.webdriver.remote.... | |
HelgeDMI/trollvalidation | trollvalidation/validation_utils.py | Python | apache-2.0 | 5,738 | 0.000523 | import gzip
import logging
import os
import shutil
import uuid
from PIL import Image
from zipfile import ZipFile
import pandas as pd
import numpy as np
import pyresample as pr
from trollvalidation.validations import configuration as cfg
LOG = logging.getLogger(__name__)
# logging.basicConfig(level=logging.DEBUG,
# ... | /areas.cfg', cfg_id)[0]
def uncompress(compressed_file, target=cfg.TMP_DIR):
"""
This function is a utility function to uncompress NetCDF files in
case they are given that way.
The gzipped original is removed after decompression.
:param product_file: str
Path to a zipped ice concentratio... | file.
"""
unpacked_filename, extension = os.path.splitext(compressed_file)
if extension == '.gz':
LOG.info('Unpacking {0}'.format(compressed_file))
if not os.path.isfile(unpacked_filename):
with gzip.open(compressed_file, 'rb') as packed_file:
with open(unpacked_... |
ctSkennerton/CompareM | comparem/lgt_dinucleotide.py | Python | gpl-3.0 | 13,790 | 0.002103 | ############################## | #################################################
# | #
# 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. ... |
weltliteratur/vossanto | first/analyse_patterns.py | Python | gpl-3.0 | 1,679 | 0.008338 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Clean and analyse POS/NER patterns.
#
# Usage:
#
# Author: rja
#
# Changes:
# 2017-05-05 (rja)
# - initial version
from __future__ import print_function
import re
import fileinput
re_clean_ner = re.compile("\(([A-Z]+) .+?\)")
re_clean_sla = re.compile("\w+/([A-Z]+)")
# ... | eturn s.strip()
# (PERSON John Doe) -> PERSON
def clean_ner(s):
return re_clean_ner.sub('\\1', s)
# remove ./. and the like at the end
def clean_end(s):
if s[-3:] in (',/,', './.'):
return s[:-3]
return s
# cle | an everything after "of/IN" or "from/in"
def clean_modifier(s):
if " of/IN " in s:
a, sep, b = s.rpartition(" of/IN ")
sep = "of"
elif " from/IN " in s:
a, sep, b = s.rpartition(" from/IN ")
sep = "from"
else:
return s
# clean b
return " ".join([a, sep, ] + [r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.