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 |
|---|---|---|---|---|---|---|---|---|
plotly/plotly.py | packages/python/plotly/plotly/validators/layout/ternary/baxis/_nticks.py | Python | mit | 459 | 0.002179 | import _plotly_utils.basevalidators
class NticksVa | lidator(_plotly_utils.basevalidators.IntegerValidator):
def __init__(
self, plotly_name="nticks", parent_name="layout.ternary.baxis", **kwargs
):
super(NticksValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edi... | **kwargs
)
|
jinser/automate_pydatastream | getcustom.py | Python | mit | 3,917 | 0.038295 | from pydatastream import Datastream
import json
import datetime
import sys
import os.path
#hardcoded directories
dir_input = "input/"
dir_output = "output/"
#check that the login credentials and input file location are being passed in
numOfArgs = len(sys.argv) - 1
if numOfArgs != 3:
print "Please run this python s... | for (key,value) in (category.items() + data_with_group.items())}
#append download timestamp
final_data = {key : value for (key,value) in (download_date.items() + data_with_category.items())}
final_data_json = json.dumps(final_data)
#decode to the right format for saving to disk
json_file = json.JS... | (len(group_value) > 1):
filename = dir_output + desc + '_' + group + '_' + code_key + '.json'
else:
filename = dir_output + desc + '_' + group + '.json'
with open(filename,'w') as outfile:
json.dump(json_file,outfile,sort_keys=True)
print "time taken for " + str(sys.argv[3]) + " to be retrieved:... |
AntonKuksov/Weather_analyzer | test_form.py | Python | gpl-3.0 | 300 | 0.006667 | import unittest
from .Weather_analyzer imp | ort is_not_number
class BtcPriceTestCase(unittest.TestCase):
def test_checking_of_input_in_form(self):
input = 46
answer = is_not_number(input) # The bitcoin returned chan | ges over time!
self.assertEqual(answer, False) |
Kami/sgrstats.com | sgrstats/articles/views.py | Python | apache-2.0 | 1,447 | 0.026261 | import datetime
from django.shortcuts import render_to_response, get_object_or_404, HttpResponse, HttpResponseRedirect, Http404
from django.template import RequestContext
from django.core.urlresolvers import reverse
from articles.models import Article
from taxonomy.models import TaxonomyMap
from core.views ... | s/index.html', {'articles': articles}, context_instance = RequestContext(request))
@update_online_users
def category(request, category_id):
article_ids = TaxonomyMap.objects.filter(term__id = category_id, type__type = 'Category', content_type__model = 'article').values_list('object_id', flat = True)
categ... | y', content_type__model = 'article')[0].term.term
articles = Article.objects.filter(id__in = article_ids)
return render_to_response('articles/category.html', {'category_id': category_id, 'category_title': category_title, 'articles': articles}, context_instance = RequestContext(request))
@update... |
guns/weechat | doc/docgen.py | Python | gpl-3.0 | 29,781 | 0.000067 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2008-2014 Sébastien Helleu <flashcode@flashtux.org>
#
# 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 opt... | ',
r'logger\.mask\..*',
r'relay\.port\..*',
r'trigger\.trigger\..*',
r'weechat\.palette\..*',
r'weechat\.proxy\..*',
r'weechat\.bar\..*',
r'weechat\.debug\..*',
r'weechat\.notify\..*',
)
# comp | letions to ignore
IGNORE_COMPLETIONS_ITEMS = (
'docgen.*',
'jabber.*',
'weeget.*',
)
def get_commands():
"""
Get list of commands in a dict with 3 indexes: plugin, command, xxx.
"""
commands = defaultdict(lambda: defaultdict(defaultdict))
infolist = weechat.infolist_get('hook', '', 'co... |
liamks/pyitunes | libpytunes/Playlist.py | Python | mit | 470 | 0.002128 | from six import | iteritems
class Playlist:
is_folder = False
playlist_persistent_id = None
parent_persistent_id = None
distinguished_kind = None
playlist_id = None
def __init__(self, playListName=None):
self.name = p | layListName
self.tracks = []
def __iter__(self):
for attr, value in iteritems(self.__dict__):
yield attr, value
def ToDict(self):
return {key: value for (key, value) in self}
|
mohclips/k5-ansible-modules | k5_novnc_console.py | Python | gpl-3.0 | 5,289 | 0.008697 | #!/usr/bin/python
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'version': '1.0'}
DOCUMENTATION = '''
---
module: k5_novnc_console
short_description: Display the URL to the NoVNC Console
version_added: "1.0"
description:
- returns a URL to the noVN... | json))
try:
response = session.request('POST', url, headers=headers, json=query_json | )
except requests.exceptions.RequestException as e:
module.fail_json(msg=e)
# we failed to make a change
if response.status_code not in (200,):
module.fail_json(msg="RESP: HTTP Code:" + str(response.status_code) + " " + str(response.content), debug=k5_debug_out)
if k5_debug:
mo... |
martanoga/yacas | docs/util/yacasdomain.py | Python | lgpl-2.1 | 13,972 | 0.001288 | # -*- coding: utf-8 -*-
"""
The Yacas domain.
:copyright: Copyright 2014 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
from docutils import nodes
from docutils.parsers.rst import directives
from sphinx import addnodes
from sphinx.roles import XRefRole
from sphinx... |
return fullname, ''
def get_index_text(self, modname, name):
"""Return the text for the index entry of the object."""
if self.objtype == 'function':
return _('%s()') % name[0]
elif self.objtype == 'data':
return _('%s') % name[0]
else:
... | x(self, name_cls, sig, signode):
modname = self.options.get(
'module', self.env.temp_data.get('ys:module'))
fullname = (modname and modname + '.' or '') + name_cls[0]
# note target
if fullname not in self.state.document.ids:
signode['names'].append(fullname)
... |
pwillworth/galaxyharvester | test/pyunit/testObjects.py | Python | gpl-3.0 | 2,899 | 0.029665 | import unittest
from datetime import timedelta, datetime
import sys
import json
sys.path.append("../../config")
sys.path.append("../../html")
import ghObjects
import ghObjectRecipe
class testObjects(unittest.TestCase):
def setUp(self):
# nothin yet
self.test = "rad"
def test_spawnHTML(self):
# arrange
spawn... | l Copper", 877, "This is great")
r.recipeIngredients.append(i1)
r.recipeIngredients.append(i2)
# act
slotHTML = r.getIngredientSlots()
rowHTML = r.getRow()
# assert
self.assertIn("steel_kiirium", slotHTML, "Resource id not in slot html.")
self.assertIn("Test Recipe", rowHTML, "Title not in row html | .")
self.assertIn("yellow", slotHTML, "Expected quality color not present in slot HTML.")
if __name__ == '__main__':
unittest.main()
|
ImmobilienScout24/aws-deployment-notifier | src/unittest/python/notifier_tests.py | Python | apache-2.0 | 900 | 0.003333 | import json
import dnot
from mock import patch
import unittest2
class NotifierTest(unittest2.TestCase):
@patch("dnot.sns.connect_to_region")
def test_parameters_are_submitted(self, connect_to_region_mock):
topic = "abc"
region = "eu-west-2"
result_topic = "result"
stack_name = ... | kName": "{0}", "notificationARN": "{1}", "re | gion": "eu-west-1", "params": {2}}}'
.format(stack_name, result_topic, params))
connect_to_region_mock.return_value.publish.assert_called_with(
topic=topic,
message=json.dumps(message))
|
defivelo/db | apps/user/migrations/0019_auto_20160922_1342.py | Python | agpl-3.0 | 1,161 | 0.001726 | from __future__ import unicode_literals
from django.db import migrations, models
import multiselectfield.db.fields
class Migration(migrations.Migration):
dependencies = [
('user', '0018_auto_20160922_1258'),
]
operations = [
migrations.AddField(
model_name='userprofile',
... | neva'), ('LU', 'Lucerne'), ('NE', 'Neuchatel'), ('SG', 'St. Gallen'), ('VS', 'Valais'), ('VD', 'Vaud'), ('ZH', 'Zurich')], max_length=29),
| preserve_default=False,
),
migrations.AlterField(
model_name='userprofile',
name='affiliation_canton',
field=models.CharField(verbose_name="Canton d'affiliation", choices=[('', '---------'), ('BS', 'Basel-Stadt'), ('BE', 'Berne'), ('FR', 'Fribourg'), ('GE', 'Ge... |
Cadene/keras | keras/utils/layer_utils.py | Python | mit | 4,856 | 0.002265 | from __future__ import print_function
import inspect
import numpy as np
import theano
from ..layers.advanced_activations import LeakyReLU, PReLU
from ..layers.core import Dense, Merge, Dropout, Activation, Reshape, Flatten, RepeatVector, Layer
from ..layers.core import ActivityRegularization, TimeDistributedDense, Aut... | ))
shaped_params.append(data.reshape(shape))
base_layer.set_weights(shaped_params)
return base_layer
def print_layer_shapes(model, input_shapes):
"""
Utility function to print the shape of the output at each layer of a Model
Arguments:
model: instance of Model ... | nput_shapes: dict (Graph), list of tuples (Merge) or tuple (Sequential)
"""
if model.__class__.__name__ in ['Sequential', 'Merge']:
# in this case input_shapes is a tuple, or a list [shape1, shape2]
if not isinstance(input_shapes[0], tuple):
input_shapes = [input_shapes]
inp... |
prman-pixar/RenderManForBlender | rman_ui/rman_ui_txmanager.py | Python | mit | 27,755 | 0.00508 | import bpy
from bpy.props import StringProperty, IntProperty, CollectionProperty, EnumProperty, BoolProperty, FloatProperty
from bpy.types import PropertyGroup, UIList, Operator, Panel
from bpy_extras.io_utils import ImportHelper
from .rman_ui_base import _RManPanelHeader
from ..rfb_utils import texture_utils
from ..rf... | EnumProperty(
name="Data Type",
default=txparams.TX_DATATYPE_FLOAT,
items=items,
description="The data storage txmake uses")
items = []
for item in txparams.TX_RESIZES:
items.append((item, item, ''))
resize: EnumPrope | rty(
name="Resize",
default=txparams.TX_RESIZE_UP_DASH,
items=items,
description="The type of resizing flag to pass to txmake")
bumpRough: EnumProperty(
name="Bump Rough",
default="-1",
items=(
("-1", "Off", ""),
... |
rgroten/NetApp-Snapshot-Manager | snapmgr/NaFunctions.py | Python | gpl-2.0 | 6,288 | 0.00493 | '''
Created on Feb 23, 2015
@author: rgroten
'''
import ConfigParser
import ssl
from datetime import datetime
from flask.globals import g
# Import NetApp API libraries
from NaElement import NaElement
from NaServer import NaServer
# from flask.globals import g
def connect():
try:
_create_unverified_htt... | executeCmd(cmd)
# Remove volumes from list that contain filterStrings
filterString = getConfigOption("VolFilters")
filterList = filterString.replace(" ","").split(",")
filteredVolumes = NaElement("attributes-list")
for vol in ret.child_get("attributes-list").children_get():
volattrs = vol... | = 'True'):
print "Skipping filtered vol : %s" % volattrs.child_get_string('name')
continue
if (isDebug == 'True'):
print 'Volume Name : %s' % volattrs.child_get_string('name')
filteredVolumes.child_add(vol)
filteredRet = NaElement("results")
... |
animekita/selvbetjening | selvbetjening/sadmin2/views/user.py | Python | mit | 1,851 | 0.001621 | from django.contrib.auth import get_user_model
from django.core.urlresolvers import reverse
from django.shortcuts import get_object_or_404
from django.utils.translation import ugettext as _
from selvbetjening.sadmin2 import menu
from selvbetjening.sadmin2.decorators import sadmin_prerequisites
from selvbetjening.sadmi... | n_active': 'userportal',
'sadmin2_breadcrumbs_active': 'user',
'sadmin2_menu_tab': menu.sadmin2_menu_tab_user,
'sadmin2_menu_tab_active': 'user',
'user': user
}
return generic_create_view(request,
UserForm,
reverse('... | args={'user_pk': user.pk}),
message_success=_('User updated'),
context=context,
instance=user)
@sadmin_prerequisites
def user_password(request, user_pk):
user = get_object_or_404(get_user_model(), pk=user_pk)
contex... |
moiseshiraldo/inviMarket | inviMarket/views/del_partner.py | Python | agpl-3.0 | 1,187 | 0.001685 | # -*- coding: utf-8 -*-
from django.shortcuts import r | ender, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.utils.translation import ugettext as _
from inviMarket.models import User
@login_required
def del_partner(request, partner_id):
"""
Delete the :model:`auth.User` passed by argument from the partners list.
**Con... | ket/addpartner.html`
"""
user = request.user
partner = get_object_or_404(User.objects.select_related('profile'),
pk=partner_id)
message = _("Ther user is not your partner.")
if partner.profile.partners.filter(pk=user.id).exists():
partner.profile.partners.rem... |
MeGotsThis/BotGotsThis | pkg/spam/items/channel.py | Python | gpl-3.0 | 941 | 0 | from typing import Iterable, Mapping, Optional
from lib import data
from ..channel import pyramid
from ..channel import wall
def filterMessage() -> Iterable[data.ChatCommand]:
return []
def commands() -> Mappin | g[str, Optional[data.ChatCommand]]:
if not hasattr(commands, 'commands'):
setattr(commands, 'commands', {
'!pyramid': pyramid.commandPyramid,
'!rpyramid': pyramid.commandRandomPyramid,
'!wall': wall.commandWall,
})
return getattr(commands, 'commands')
de... | s', {
'!pyramid-': pyramid.commandPyramidLong,
'!wall-': wall.commandWallLong,
})
return getattr(commandsStartWith, 'commands')
def processNoCommand() -> Iterable[data.ChatCommand]:
return []
|
ic-hep/DIRAC | src/DIRAC/ProductionSystem/Client/ProductionStep.py | Python | gpl-3.0 | 2,408 | 0.000415 | """ Class defining a production step """
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
__RCSID__ = "$Id$"
import json
from DIRAC import S_OK, S_ERROR
class ProductionStep(object):
"""Define the Production Step object"""
def __init__(self, **k... | ptional fields
prodStepDict["inputquery"] = json.dumps(self.Inputquery)
prodStepDict["outputquery"] = json.dumps(self.Outputquery)
prodStepDict["groupsize"] = self.GroupSize
prodStepDict["body"] = json.dumps(se | lf.Body)
return S_OK(prodStepDict)
|
wenxinwilliam/docker-django-celery | mydjangoapp/mydjangoapp/celeryconf.py | Python | mit | 354 | 0.002825 | # coding=UTF8
from __future__ import absolute_import
import os
from celery im | port Celery
from django.conf import set | tings
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mydjangoapp.settings")
app = Celery('mydjangoapp')
CELERY_TIMEZONE = 'UTC'
app.config_from_object('django.conf:settings')
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) |
asm-technologies/management | employee/migrations/0006_auto__chg_field_billdetails_end_date__chg_field_billdetails_start_date.py | Python | mit | 4,781 | 0.008576 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Changing field 'billdetails.end_date'
db.alter_column(u'employee_billd... | 'django.db.models.fields.CharField', [], {'max_length': '100'}),
'personal_email': ('django.db.models.fields.EmailField', [], {'max_length': '50', 'blank': 'True'}),
'proj': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['employee.Project']"}),
'start_date': ('django... | e': 'Project'},
'description': ('django.db.models.fields.CharField', [], {'max_length': '254'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
}
}
complete_apps = ['... |
fxia22/ASM_xf | PythonD/site_python/twisted/cred/checkers.py | Python | gpl-2.0 | 2,547 | 0.003141 | # -*- test-case-name: twisted.test.test_newcred -*-
from twisted.internet import defer
from twisted.python import components, failure
from twisted.cred import error, credentials
class ICredentialsChecker(components.Interface):
"""I check sub-interfaces of ICredentials.
@cvar credentialInterfaces: A list of s... | ith persistence.
"""
ANONYMOUS = ()
class AllowAnonymousAccess:
__implements__ = ICredentialsChecker
credentialInterfaces = credentials.IAnonymous,
def requestAvatarId(self, credentials):
return defer.succeed(ANONYMOUS)
class InMemoryUsernamePasswordDatabaseDontUse:
credentialInterfa... | lements__ = ICredentialsChecker
def __init__(self):
self.users = {}
def addUser(self, username, password):
self.users[username] = password
def _cbPasswordMatch(self, matched, username):
if matched:
return username
else:
return failure.Failure(error.U... |
spilgames/job-runner | job_runner/apps/job_runner/migrations/0013_auto__add_field_worker_ping_response_dts.py | Python | bsd-3-clause | 9,629 | 0.007789 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Worker.ping_response_dts'
db.add_column('job_runner_worker', 'ping_response_dts',
... | els.fields.AutoField', [], {'primary_key': 'True'}),
'notification | _addresses': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'worker': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['job_runner.Worker']"})
},
'job_runner.killrequest': {
... |
AlexandreGuinaudeau/ClasseurPhoto | classeur_photo/classeur_photo/album/urls.py | Python | gpl-3.0 | 519 | 0.001927 | from django.conf.urls import url
from . import views
urlpatterns = [
# ex: /album/
u | rl(r'^$', views.index, name='index'),
# ex: /album/create/
url(r'^welcome/$', views.welcome, name='welcome'),
# ex: /album/create/
url(r'^create/$', views.create, name='create'),
# ex: /album/vietnam_2016/
url(r'^(?P<album_permalink>[\w_]+)/$', views.detail, name='detail'),
# ex: /album/viet... | s, name='settings'),
]
|
egabancho/invenio | invenio/legacy/wsgi/__init__.py | Python | gpl-2.0 | 25,601 | 0.004336 | # -*- coding: utf-8 -*-
## This file is part of Invenio.
## Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014 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
## Lic... | else:
raise
self.__buffer = ''
def set_content_type(self, content_type):
self.__content_type_set_p = True
self.response.content_type = content_type
if self.__is_https:
if content_type.startswith("text/html") or content_type.startswith("a... |
self.__replace_https = True
def get_content_type(self):
return self.response.content_type
def send_http_header(self):
for (k, v) in self.__low_level_headers:
self.response.headers[k] = v
for k, v in iteritems(self.headers_out):
self.response.hea... |
m4nolo/steering-all | src/interact/evtInteract.py | Python | mit | 196 | 0.015306 | import interact
class | EvtInteract(interact.I | nteract):
def __init__(self):
self.events = []
def checkEventInteraction(self, events):
self.events = events
self.checkInteraction()
|
BunsenMcDubbs/cs4400-project | app/models/__init__.py | Python | mit | 386 | 0 | from . import | (
Application,
Category,
Course,
Designation,
Major,
Project,
Requirement,
User,
Year,
)
Application = Application.Application
Category = Category.Category
Course = Course.Course
Designation = Designation.Designation
Major = Major.Major
Project = Project.Project
Requirement = Requir... | nt
User = User.User
Year = Year.Year
|
NewAcropolis/api | migrations/versions/0047.py | Python | mit | 1,247 | 0.005613 | """empty message
Revision ID: 0047 add smtp
Revises: 0046 remove long description
Create Date: 2020-11-08 01:28:28.386704
"""
# revision identifiers, used by Alembic.
revision = '0047 add smtp'
down_revision = '0046 remove long description'
from alembic import op
import sqlalchemy as sa
def upgrade():
# ### c... | , sa.Column('created_at', sa.DateTime(), nullable=True))
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by A | lembic - please adjust! ###
op.drop_column('email_providers', 'smtp_user')
op.drop_column('email_providers', 'smtp_server')
op.drop_column('email_providers', 'smtp_password')
op.drop_column('email_providers', 'available')
op.drop_column('email_providers', 'created_at')
# ### end Alembic commands... |
regisf/yablog | blog/templatetags/__init__.py | Python | bsd-3-clause | 1,525 | 0.001311 | # -*- coding: UTF-8 -*-
# YaBlog
# (c) Regis FLORET
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the fol... | * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the <organization> nor the
# names of its contributors may be use... | BUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL Regis FLORET BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLU... |
DSSG-paratransit/main_repo | Access_Analysis_Project/Scripts/dwellTimeAnalysis.py | Python | agpl-3.0 | 4,203 | 0.025696 | import numpy as np
import os
import pandas as pd
import statsmodels.formula.api as smf
import sys
# @params: takes mobaid codes string
# @returns: list of mobaid strings
def splitCode(x):
if type(x) is str:
codes = x.split(',')
return codes
else:
return []
# @returns binary T/F if string code is in string/lis... | ave all 0 data
bool_column_df = data.apply(lambda x: (min(x) == 0) and (max(x) == 0))
bool_column_df.columns = ['values']
print(bool_column_df.values) # debug
columns = bool_column_df[bool_column_df.values].index.values
print(columns) # debug
data.drop(columns,1,inplace=True)
data.reset_index(inplace=True)
# pr... | ta = None
try:
data_path = os.path.join(os.pardir,'data',sys.argv[1])
data = pd.read_csv(data_path)
except IOError:
print('\n\tError: No file at ../data/' + sys.argv[1] + ' from ' + os.getcwd() + '\n')
quit()
except IndexError:
print('\n\tdwellTimeAnalysis.py takes a csv file from\n\n\t\tmain_repo\data\n\n\tassum... |
SpaceGroupUCL/qgisSpaceSyntaxToolkit | esstoolkit/external/pyqtgraph/console/template_pyside2.py | Python | gpl-3.0 | 6,517 | 0.002302 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'template.ui'
#
# Created: Sun Sep 18 19:19:10 2016
# by: pyside2-uic running on PySide2 2.0.0~alpha0
#
# WARNING! All changes made in this file will be lost!
from PySide2 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
def... | eUi(self, Form):
Form.setWindowTitle(QtWidgets.QApplication.translate("Form", "Console", None, -1))
self.historyBtn.setText(QtWidgets.QApplication.translate("Form", "History..", None, -1))
self.exceptionBtn.setText(QtWidgets.QApplication.translate("Form", "Exceptions..", None, -1))
self.... | r Exception", None, -1))
self.catchAllExceptionsBtn.setText(QtWidgets.QApplication.translate("Form", "Show All Exceptions", None, -1))
self.catchNextExceptionBtn.setText(QtWidgets.QApplication.translate("Form", "Show Next Exception", None, -1))
self.onlyUncaughtCheck.setText(QtWidgets.QApplicati... |
RRostami/Spiderpy | spiderpy/core.py | Python | gpl-3.0 | 2,986 | 0.045211 | #
#
#
import requests
from bs4 import BeautifulSoup
import re
import os
def all_links(URL,abs=False,session=None):
'''Generator function for all links in a page.
ARGS:
URL -> url of the page
abs -> (True) returns actual 'href's of each <a> tag (False) process each 'href' to generate the full li... | e:
filename='undefined'
else:
filename=altname
if (dir!="" and not os.path.exists(dir)):
os.makedirs(dir)
path=dir+filename
if(replace==False and os.path.exists(path)) :
return True
else:
if(session):
dl = session.get(URL, stream=True)
else:
dl = | requests.get(URL, stream=True)
if (dl.status_code != 200):
raise Exception(dl.status_code)
with open(path, 'wb') as f:
for i,chunk in enumerate(dl.iter_content(chunksize)):
f.write(chunk)
if(max_size and f.tell()>max_size):
dl.close()
break;
else:
return f.tell()
return False
|
vipul-tm/DAG | dags-ttpl/subdags/utilization_kpi_subdag.py | Python | bsd-3-clause | 17,641 | 0.03832 | from airflow.models import DAG
from airflow.operators.dummy_operator import DummyOperator
from datetime import datetime, timedelta
from airflow.operators import PythonOperator
from airflow.hooks import RedisHook
from airflow.models import Variable
from airflow.hooks import MemcacheHook
from etl_tasks_functions import... | "
ERROR_DICT ={404:'Device not found yet',405:'No SS Connected to BS-BS is not s | kipped'}
ERROR_FOR_DEVICE_OMITTED = [404]
kpi_rules = eval(Variable.get("kpi_rules"))
DEBUG = False
sv_to_ds_mapping = {}
#O7_CALC_Q = "calculation_q"
O7_CALC_Q = "poller_queue"
down_and_unresponsive_devices = eval(redis_hook_static_5.get("current_down_devices_all"))
def process_utilization_kpi(
parent_dag_name,
child... |
BBN-Q/QGL | QGL/GSTTools.py | Python | apache-2.0 | 7,229 | 0.004288 | '''
Various tools to interface with pyGSTi for running GST experiments.
Created on May 16, 2018
Original Author: Guilhem Ribeill
Copyright 2018 Raytheon BBN Technologies
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 ... | 00, diac_compiled=True):
pulse_library = pulse_library.upper()
# QGL pulse libraries handle the Id pulse differently. In the standard
# case, the Id is of finite length equal to all the other one-pulse
# elements of the library. In the Atomic and DiAtomic cases, the ID is
# of length 0 by defaul... | he ID
# gate with the first experiment in any GST experiment equal to {} =
# Id(length = 0). All other Id gates in the sequence should be of finite
# length. So we'll modify the Clifford indexing here to make Id(length=0)
# the first element in the library and Id(length=length) the second.
if pul... |
Alwnikrotikz/marinemap | lingcod/common/uaparser/clientos.py | Python | bsd-3-clause | 1,804 | 0.007206 | """
Based on http://vaig.be/2009/03/getting-client-os-in-django.html
"""
import re
def client_os(user_agent):
'''
Context pr | ocessor for Django that provides operating system
information base on HTTP user agent.
A user agent looks like (line break added):
"Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.6) \
Gecko/2009020409 Iceweasel/3.0.6 (Debian-3.0.6-1)"
'''
# Mozilla/5.0
regex = '(?P<application_name>\w+)/(?... | "MSIE" in user_agent: # some UA strings leave out the U;
regex += '(?P<version_token>[\w .]+)'
regex += '; '
# Linux i686
regex += '(?P<platform_token>[\w ._]+)'
# anything else
regex += '; .*'
result = re.match(regex, user_agent)
if result:
result_dict = result.group... |
jzimbel/artist-expander | config.py | Python | mit | 1,176 | 0.001701 | import os
class Config(object):
SPOTIPY_REDIRECT_URI = os.environ['SPOTIPY_REDIRECT_URI']
SPOTIPY_CLIENT_ID = os.environ['SPOTIPY_CLIENT_ID']
SPOTIPY_CLIENT_SECRET = os.environ['SPOTIPY_CLIENT_SECRET']
SPOTIFY_ACCESS_SCOPE = 'playlist-modify-public playlist-modify-private playlist-read-private user-lib... | LATE #
# By default, the playlist will be ordered like:
# - ARTIST A TRACK 1
# - ARTIST A TRACK 2
# - ARTIST A TRACK 3
# - ARTIST A TRACK 4
# - ARTIST A TRACK 5
# - ARTIST B TRACK 1
# - ARTIST B TRACK 2
# | - ARTIST B TRACK 3
# ...
# if COLLATE is set to True, it will instead be ordered like so:
# - ARTIST A TRACK 1
# - ARTIST B TRACK 1
# - ARTIST C TRACK 1
# ...
# - ARTIST Z TRACK 1
# - ARTIST A TRACK 2
# - ARTIST B TRACK 2
# ...
COLLATE = False
# PUBLIC #
# Default F... |
mikel-egana-aranguren/SADI-Galaxy-Docker | galaxy-dist/lib/galaxy/model/migrate/versions/0029_user_actions.py | Python | gpl-3.0 | 1,371 | 0.030635 | """
This migration script adds a user actions table to Galaxy. |
"""
from sqlalchemy import *
from migrate import *
import datetime
now = datetime.datetime.utcnow
import logging
log = logging.getLogger( __name__ )
metadata = MetaData()
def display_migration_details():
print ""
print "This migration script adds a user actio | ns table to Galaxy."
print ""
# New table to store user actions.
UserAction_table = Table( "user_action", metadata,
Column( "id", Integer, primary_key=True ),
Column( "create_time", DateTime, default=now ),
Column( "user_id", Integer, ForeignKey( "galaxy_user.id" ), index=True ),
Column( "session_... |
swoiow/iabe-tool | openshift.py | Python | mit | 370 | 0.005405 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import tornado.ioloop
try:
import WebApp
except ImportError, ImportWarning:
impor | t entire as WebApp
if __name__ == "__main__":
ip = os.environ['OPENSHIFT_DIY_ | IP']
port = int(os.environ['OPENSHIFT_DIY_PORT'])
WebApp.application.listen(port, ip)
tornado.ioloop.IOLoop.instance().start()
|
yuzie007/ph_analysis | ph_analysis/phonon_calculator.py | Python | mit | 6,728 | 0.000297 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import os
import shutil
import time
import subprocess
import numpy as np
from .phonopy_conf_creator import PhonopyConfCreator
from vasp.poscar import Poscar
from autotools import symlink_force
class PhononCalculator(object):
def _... | ber,
mesh=mesh,
tmax=3000,
dim_sqs=dim_sqs,
is_average_mass=self._is_average_mass,
is_primitive=self._is_primitive,
band_points=101,
poscar_name="POSCAR", # For getting the chemical symbols
magmom_line=None,
var... |
spg_number is used to determine the primitive axis and band paths.
"""
if self._poscar_average_filename is not None:
poscar_filename = self._poscar_average_filename
else:
poscar_filename = self._poscar_filename
print('SPG number is searched from {... |
dimitri-justeau/niamoto-core | niamoto/data_providers/sql_provider/sql_occurrence_provider.py | Python | gpl-3.0 | 2,139 | 0 | # coding: utf-8
import sqlalchemy as sa
import pandas as pd
from niamoto.data_providers.base_occurrence_provider import \
BaseOccurrenceProvider
from niamoto.exceptions import MalformedDataSourceError
class SQLOccurrenceProvider(BaseOccurrenceProvider):
"""
SQL occurrence provider. Instantiated with a s... | y -> The latitude of the occurrence (WGS84).
All the remaining column will be stored as | properties.
"""
REQUIRED_COLUMNS = set(['id', 'taxon_id', 'x', 'y'])
def __init__(self, data_provider, occurrence_sql):
super(SQLOccurrenceProvider, self).__init__(data_provider)
self.occurrence_sql = occurrence_sql
def get_provider_occurrence_dataframe(self):
connection = sa.... |
dolfandringa/AquaponicsModeler | AquaponicsModeler/model.py | Python | gpl-3.0 | 14,950 | 0.000401 | # -*- coding: utf-8 -*-
"""
The :mod:`AquaponicsModeler.model` module contains all components to be used in
models.
All model components are classes that should inherit from
:class:`BaseModelClass`. So far there are two groups of component types:
containers and pumps.
:class:`Containers <Container>` are compents that... | self.state = None
def __str__(self):
return self.__class__.__name__
def get_state(self):
"""
Get the current contents of this container.
Returns:
float: current state value
"""
return self.state
@classmethod
def getParameter | s(cls):
"""
Return the model parameters.
Returns:
collections.OrderedDict: The parameters for this class.
"""
log.debug('Getting parameters for class %s: %s' % (cls, cls._PARAMS))
return cls._PARAMS
def step(self):
"""Step into the next iteration... |
SunWalter/Hard | ex11.py | Python | apache-2.0 | 231 | 0.025974 |
print ("How old a | re you?",)
age = input()
print ("How tall are you?",)
height = input()
pr | int ("How much do you weigh?",)
weight = input()
print ("So, you are %r years old, %r tall and %r heavy." %(age, height, weight))
|
olehermanse/sim_game | tests/path_fix.py | Python | mit | 331 | 0.003021 | #!/usr/bin/env python3
# | -*- coding: utf-8 -*-
'''Hacky way to make sure imports work'''
from os.path import abspath, dirname, realpath, join
import sys
# This allows imports to work, even if sim_game is not in python path:
package_location = abspath(join(dirname(realpath(__file__)) , ".."))
sys.path.insert(0, package_lo | cation)
|
achauvinhameau/netProbe | py-net-probe/database/__init__.py | Python | gpl-3.0 | 1,035 | 0 | # -*- Mode: Python; python-indent-offset: 4 -*-
#
# Time-stamp: <2017-06-03 11:36:32 alex>
#
# --------------------------------------------------------------------
# PiProbe
# Copyright (C) 2016-2017 Alexandre Chauvin Hameau <ach@meta-x.org>
#
# This program is free software: you can redistribute it and/or modify
# it... | u.org/licenses/>.
# --------------------------------------------------------------------
"""
database package, redis and test modules
"""
from . import dbRedis
fr | om . import dbTest
|
gangadharkadam/saloon_frappe | frappe/utils/response.py | Python | mit | 4,943 | 0.025086 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import json
import datetime
import mimetypes
import os
import frappe
from frappe import _
import frappe.model.document
import frappe.utils
import frappe.sessions
import werkzeug.u... | pe.local.response['http_status_code']
del frappe.local.response['http_status_code']
response.headers[b"Content-Type"] = b"application/json; charset: utf-8"
response.data = json.dumps(frappe.local.response, default=json_handler, separators=(',',':'))
return response
def make_logs(response = None):
"""make string... | and errprint"""
if not response:
response = frappe.local.response
if frappe.error_log:
# frappe.response['exc'] = json.dumps("\n".join([cstr(d) for d in frappe.error_log]))
response['exc'] = json.dumps([frappe.utils.cstr(d) for d in frappe.local.error_log])
if frappe.local.message_log:
response['_server_m... |
indianajohn/ycmd | ycmd/tests/python/testdata/goto_file1.py | Python | gpl-3.0 | 31 | 0 | from got | o_file2 import foo
fo | o
|
westurner/pyleset | test/test_pyleset.py | Python | mit | 267 | 0.003745 | "" | "
Tests for `pyleset` module.
"""
import pytest
from pyleset import pyleset
class TestPyleset(object):
@classmethod
def setup_class(cls):
pass
def test_something | (self):
pass
@classmethod
def teardown_class(cls):
pass |
JT5D/Alfred-Popclip-Sublime | Sublime Text 2/JsFormat/libs/jsbeautifier/tests/testjsbeautifier.py | Python | gpl-2.0 | 64,176 | 0.013246 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
import unittest
import jsbeautifier
class TestJSBeautifier(unittest.TestCase):
def test_unescape(self):
# Test cases contributed by <chrisjshull on GitHub.com>
test_fragment = self.decodesto
bt = self.bt
bt('"\\\\s"'); # == "... | \',"\\x5c",\'\\x5c\',"\\xff and \\xzz","unicode \\u0000 \ | \u0022 \\u0027 \\u005c \\uffff \\uzzzz"', '"\\x22\\x27", \'\\x22\\x27\', "\\x5c", \'\\x5c\', "\\xff and \\xzz", "unicode \\u0000 \\u0022 \\u0027 \\u005c \\uffff \\uzzzz"');
self.options.unescape_strings = True
bt('"\\x41\\x42\\x43\\x01"', '"ABC\\x01"');
bt('"\\u2022"', '"\\u2022"');
bt... |
masahir0y/buildroot-yamada | support/testing/tests/package/test_python_subprocess32.py | Python | gpl-2.0 | 348 | 0 | from tests.package.test_python import TestPythonPackageBase
class TestPythonPy2Subprocess32(TestPythonPackageBase):
__test__ = True | config = TestPythonPackageBase.config + \
"""
BR2_PACKAGE_PYTHON=y
BR2_PACKAGE_PYTHON_SUBPROCESS32=y
"""
sample_scripts = ["tests/package/sample_python_subprocess32.py"]
| |
tmerrick1/spack | lib/spack/spack/test/svn_fetch.py | Python | lgpl-2.1 | 3,303 | 0 | ##############################################################################
# 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... | epository.checks[type_of_test]
| h = mock_svn_repository.hash
# Construct the package under test
spec = Spec('svn-test')
spec.concretize()
pkg = spack.repo.get(spec)
pkg.versions[ver('svn')] = t.args
# Enter the stage directory and check some properties
with pkg.stage:
with spack.config.override('config:verify_ss... |
KawashiroNitori/Anubis | anubis/util/domainjob.py | Python | gpl-3.0 | 765 | 0 | import logging
from anubis.model import builtin
from anub | is.model import domain
from anubis.util import argmethod
_logger = logging.getLogger(__name__)
def wrap(m | ethod):
async def run():
_logger.info('Built in domains')
for ddoc in builtin.DOMAINS:
_logger.info('Domain: {0}'.format(ddoc['_id']))
await method(ddoc['_id'])
_logger.info('User domains')
ddocs = domain.get_multi(fields={'_id': 1})
async for ddoc in ... |
ugoertz/django-familio | genealogio/migrations/0024_auto_20160316_2039.py | Python | bsd-3-clause | 3,111 | 0.003214 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import partialdate.fields
class Migration(migrations.Migration):
dependencies = [
('genealogio', '0023_auto_20160303_2105'),
]
operations = [
migrations.AlterField(
model... | (siehe Dokumentation).', verbose_name='Beschreibung', blank=True),
),
migrations.AlterField(
model_name='timelineitem',
name='end_date',
field=partialdate.fields.PartialDateField(default='', hel | p_text='Datum im Format JJJJ-MM-TT (Teilangaben m\xf6glich); kann freibleiben', verbose_name='Enddatum', blank=True),
),
migrations.AlterField(
model_name='timelineitem',
name='start_date',
field=partialdate.fields.PartialDateField(default='', help_text='Datum im Form... |
akranga/mafia-serverless | game/day.py | Python | apache-2.0 | 979 | 0.015322 | import os, sys
# to read depend | encies from ./lib direcroty
script_dir = os.path.dirname( os.path.realpath(__ | file__) )
sys.path.insert(0, script_dir + os.sep + "lib")
import logging, boto3, json, random
# for dynamodb filter queries
from boto3.dynamodb.conditions import Key, Attr
# setup log level to DEBUG
log = logging.getLogger()
log.setLevel(logging.DEBUG)
# initialize DynamoDB client
dynamodb = boto3.resource('dynamodb... |
fredericlepied/os-net-config | os_net_config/openstack/common/importutils.py | Python | apache-2.0 | 2,368 | 0 | # 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 req... | from default namespace.
Imports a class and return an instance of it, first by trying
to find the class in a default namespace, then failing back to
a full path if not found in the default namespace.
"""
import_value = "%s.%s" % (name_space, import_str)
try:
return import_class(import_... | port a module."""
__import__(import_str)
return sys.modules[import_str]
def import_versioned_module(version, submodule=None):
module = 'os_net_config.v%s' % version
if submodule:
module = '.'.join((module, submodule))
return import_module(module)
def try_import(import_str, default=None):... |
fbr1/textmining-eac | main.py | Python | mit | 3,609 | 0.019119 | import numpy as np
import scipy.cluster.hierarchy as hr
import scipy.spatial as spa
import clustering
import matplotlib.pyplot as plt
from sklearn.cluster import AgglomerativeClustering
import filter
class textMiningEac:
def __init__(self,k,N,low,high=0):
self.k = k
# Leer datos desde ... | s[j]=maxvalue/50
j=j+1
print("Setosa= " + '%.2f' % results[0] + "\nVersicolor= " + '%.2f' % results[1] + "\nVirginica= " + '%.2f' % results[2])
def getSilhouette(self):
"""
Grafica silhouet | te
"""
clustering.Silhouette(self.D,self.labels,self.k) |
RicterZ/pyprint | pyprint/views/background.py | Python | mit | 3,116 | 0.001284 | import tornado.web
from datetime import date
from sqlalchemy.orm.exc import NoResultFound
from pyprint.handler import BaseHandler
from pyprint.models import User, Link, Post
class SignInHandler(BaseHandler):
def get(self):
return self.background_render('login.html')
def post(self):
username ... |
posts = self.orm.query(Post.title, Post.id).order_by(Post.id.desc()).all()
self.background_render('posts.html', posts=posts)
@tornado.web.authenticated
def post(self):
action = self.get_argument('action', None)
if action == 'del':
post_id = self.get_argument('id', 0... | if post_id:
post = self.orm.query(Post).filter(Post.id == post_id).one()
self.orm.delete(post)
self.orm.commit()
class AddPostHandler(BaseHandler):
@tornado.web.authenticated
def get(self):
self.background_render('add_post.html', post=None)
@tornad... |
ArthurStart/arthurstart.github.io | GenerateUpdateLines.py | Python | mit | 889 | 0.013498 | import datetime
def suffix(d):
return 'th' if 11<=d<=13 else {1:'st',2:'nd',3:'rd'}.get(d%10, 'th')
def custom_strftime(format, t):
return t.strftime(format).replace('{S}', str(t.day) + suffix(t.day))
print "Welcome to GenerateUpdateLines, the nation's favourite automatic update line generator."
start = in... | else {1:'st',2:'nd',3:'rd'}.get(d%10, 'th')
#
# def custom_strftime(format, t):
# return t. | strftime(format).replace('{S}', str(t.day) + suffix(t.day))
#
# print custom_strftime('%B {S}, %Y', dt.now())
|
jmwright/cadquery-x | gui/libs/pyqode/core/widgets/tabs.py | Python | lgpl-3.0 | 16,288 | 0 | # -*- coding: utf-8 -*-
"""
This module contains the implementation of a tab widget specialised to
show code editor tabs.
"""
import logging
import os
from pyqode.core.dialogs.unsaved_files import DlgUnsavedFiles
from pyqode.core.modes.filewatcher import FileWatcherMode
from pyqode.core.widgets.tab_bar import TabBar
f... | xcept AttributeError:
pass
self.setCurrentIndex(initial_index)
def addAction(self, action):
"""
Adds an action to the TabBar context menu
:param action: QAction to append
"""
self._context_mnu.addAction(action)
def add_separator(self):
"... | r to the TabBar context menu.
:returns The separator action.
"""
return self._context_mnu.addSeparator()
def index_from_filename(self, path):
"""
Checks if the path is already open in an editor tab.
:param path: path to check
:returns: The tab index if foun... |
HybridF5/jacket | jacket/storage/backup/rpcapi.py | Python | apache-2.0 | 4,652 | 0 | # Copyright (C) 2012 Hewlett-Packard Development Company, L.P.
# 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/LICEN... | n_send_version(current):
return current
else:
return legacy
def create_backup(self, ctxt, backup):
LOG.debug("create_backup in rpcapi backup_id %s", backup.id)
version = self._compat_ver('2.0', '1.1')
cctxt = self.client.prepare(server=backup.host, version=ve... | LOG.debug("restore_backup in rpcapi backup_id %s", backup.id)
version = self._compat_ver('2.0', '1.1')
cctxt = self.client.prepare(server=volume_host, version=version)
cctxt.cast(ctxt, 'restore_backup', backup=backup,
volume_id=volume_id)
def delete_backup(self, ctxt,... |
napalm-automation/napalm-yang | napalm_yang/models/openconfig/network_instances/network_instance/mpls/lsps/constrained_path/tunnels/tunnel/p2p_tunnel_attributes/p2p_primary_path/__init__.py | Python | apache-2.0 | 14,694 | 0.001021 | # -*- coding: utf-8 -*-
from operator import attrgetter
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType
from pyangbind.lib.yangtypes import RestrictedClassType
from pyangbind.lib.yangtypes import TypedListType
from pyangbind.lib.yangtypes import YANGBool
from pyangbind.lib.yangtypes import YANGListTy... |
defining_module="openconfig-network-instance",
yang_type="list",
is_config=True,
)
p2p_primary_path = __builtin__.property(
_get_p2p_primary_path, _set_p2p_primary_path
)
|
_pyangbind_elements = OrderedDict([("p2p_primary_path", p2p_primary_path)])
from . import p2p_primary_path_
class p2p_primary_path(PybindBase):
"""
This class was auto-generated by the PythonClass plugin for PYANG
from YANG module openconfig-network-instance-l2 - based on the path /network-instances/ne... |
jalibras/coop | coop/coop/urls.py | Python | apache-2.0 | 2,258 | 0.0124 | """coop URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based... | h/',include('rest_framework.urls',namespace='rest_framework')),
url(r'^admin/', admin.site.urls),
url(r'^$',area_map,{'area_id':1}),
url(r'^guide/', include('guide.urls',namespace="guide")),
url(r'^home/', include('homepage.urls',namespace="homepage")),
url(r'^members/auth/', include('members.urls')... | ', include('members.urls',namespace="members")),
] + static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
|
opengeogroep/inasafe | realtime/shake_data.py | Python | gpl-3.0 | 15,213 | 0.000394 | # coding=utf-8
"""
InaSAFE Disaster risk assessment tool developed by AusAid and World Bank
- **Functionality related to shake data files.**
Contact : ole.moller.nielsen@gmail.com
.. note:: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License a... | r as zip files. For example:
* `ftp://118.97.83.243/20110413170148.inp.zip`_
* `ftp://118.97.83.243/20110413170148.out.zip`_
There are numerous files provided within these two zip files, but there
is only really one that we are interested in:
| * grid.xml - which contains all the metadata pertaining to the event
The remaining files are fetched for completeness and possibly use in the
future.
This class provides a high level interface for retrieving this data and
then extracting various by products from it.
"""
def __init__(se... |
bvacaliuc/pyrasdr | plugins/pyLMS7002M/pyLMS7002M/LMS7002_DCCAL.py | Python | gpl-3.0 | 27,053 | 0.007467 | #***************************************************************
#* Name: LMS7002_DCCAL.py
#* Purpose: Class implementing LMS7002 DCCAL functions
#* Author: Lime Microsystems ()
#* Created: 2017-02-10
#* Copyright: Lime Microsystems (limemicro.com)
#* License:
#**********************************************... | value of PD_DCDAC_TXB
"""
if self.chip.chipID == self.chip.chipIDMR3:
if value not in [0, 1]:
raise ValueError("Value must be [0,1]")
self._writeReg('CFG', 'PD_DCDAC_TXB', value)
else:
raise ValueError("Bitfield PD_DCDAC_TXB is not supported on... | f PD_DCDAC_TXA
"""
if self.chip.chipID == self.chip.chipIDMR3:
return self._readReg('CFG', 'PD_DCDAC_TXA')
else:
raise ValueError("Bitfield PD_DCDAC_TXA is not supported on chip version "+str(self.chip.chipID))
@PD_DCDAC_TXA.setter
def PD_DCDAC_TXA(self, value):... |
zegami/omero-idr-fetch | fetch_omero_data.py | Python | mit | 3,129 | 0.003196 | """
Grab screen data from OMERO based on Screen ID
"""
import csv
import multiprocessing
import progressbar
import signal
import sys
import time
import requests
import json
from argparse import ArgumentParser
import omeroidr.connect as connect
from omeroidr.data import Data
parser = ArgumentParser(prog='OMERO screen ... | ing pool
"""
signal.signal(signal.SIGI | NT, signal.SIG_IGN)
def well_details_callback(well):
"""
Callback from apply_async. Used to update progress bar
:param well: Well metadata object
"""
pbar.update(pbar.previous_value + 1)
# append well the wells data list
wells_data.append(well)
def main():
# login
session = conn... |
hecchi777/S3-SlaacSecuritySolution | impacket-0.9.11/impacket/dcerpc/v5/lsad.py | Python | apache-2.0 | 57,687 | 0.0121 | # Copyright (c) 2003-2014 CORE Security Technologies
#
# This software is provided under under a slightly modified version
# of the Apache Software License. See the accompanying LICENSE file
# for more information.
#
# $Id: lsad.py 1106 2014-01-19 14:17:01Z bethus@gmail.com $
#
# Author: Alberto Solino
#
# Description:... | = 0x00000008
TRUSTED_SET_POSIX = 0x00000010
TRUSTED_SET_AUTH = 0x00000020
TRUSTED_QUERY_AUTH = 0x00000040
# 2.2.1.2 POLICY_SYSTEM_ACCESS_MODE
POLICY_MODE_INTERACTIVE = 0x00000001
POLICY_MODE_NETWORK = 0x00000002
POLICY_MODE_BATCH = 0x00000004
POLIC... | E_SERVICE = 0x00000010
POLICY_MODE_DENY_INTERACTIVE = 0x00000040
POLICY_MODE_DENY_NETWORK = 0x00000080
POLICY_MODE_DENY_BATCH = 0x00000100
POLICY_MODE_DENY_SERVICE = 0x00000200
POLICY_MODE_REMOTE_INTERACTIVE = 0x00000400
POLICY_MODE_DENY_REMOTE_INTERACTIVE ... |
tedunderwood/GenreProject | python/extract/GenerateExtractPBS.py | Python | mit | 630 | 0.009524 | for i in range (0, 53):
filepath = '/Users/tunder/Dropbox/PythonScripts/requests/pbs/fic' + str(i) + '.pbs'
with open(filepath, mode='w', encoding = 'utf-8') as file:
file.write('#!/bin/bash\n')
file.write('#PBS -l walltime=10:00: | 00\n')
file.write('#PBS -l nodes=1:ppn=12\n')
file.write('#PBS -N Fiction' + str(i) + '\n')
file.write('#PBS -q ichass\n')
file.write('#PBS -m be\n')
file.write('cd $PBS_O_WORKDIR\n')
file.write('python3 extract.py -idfile | /projects/ichass/usesofscale/hathimeta/pre20cslices/slice' + str(i) + '.txt -g fic -v -sub -rh' + '\n')
|
ctuning/ck-env | module/artifact/module.py | Python | bsd-3-clause | 12,275 | 0.037882 | #
# Collective Knowledge (artifact description (reproducibility, ACM meta, etc))
#
# See CK LICENSE.txt for licensing details
# See CK COPYRIGHT.txt for copyright details
#
# Developer: Grigori Fursin, Grigori.Fursin@cTuning.org, http://fursin.net
#
cfg={} # Will be updated by CK (meta description of this module)
wor... | eckout
r=ck.run_and_get_stdout({'cmd':['git','rev-parse','--short','HEAD']})
if r[' | return']==0 and r['return_code']==0:
checkout=r['stdout'].strip()
os.chdir(pc)
x={'branch':branch, 'checkout':checkout, 'path':p, 'type':t, 'url':url, 'data_uoa':duoa}
else:
x={'path':p, 'type':t, 'data_uoa':duoa}
pp.append(x)
pp2[duoa]=x
... |
rwl/PyCIM | CIM15/IEC61970/Informative/InfERPSupport/ErpInventory.py | Python | mit | 2,914 | 0.001373 | # Copyright (C) 2010-2011 Richard Lincoln
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish... | UDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A P | ARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
from CIM15.IE... |
oxfordinternetinstitute/scriptingcourse | DSR-Week 2/wk02_twitter_test.py | Python | gpl-3.0 | 1,313 | 0.033511 | # -*- coding: utf-8 -*-#
"""
Basic Twitter Authentication
requirements: Python 2.5+ tweepy (easy_install tweepy | pip install tweepy)
"""
__author__ = 'Bernie Hogan'
__version__= '1.0'
import string
import codecs
import os
import pickle
import copy
import sys
import json
import webbrowser
import tweepy
from twe... | r rather, your account has authorized this application to use the twitter api."
print "You have this many hits to the API left this hour: "
# | print json.dumps(api.rate_limit_status(), indent = 1) #['remaining_hits']
print getFollowerCount(api, "blurky")
print getFollowingCount(api, "blurky")
|
dossorio/python-blog | reddit-data-extractor.py | Python | mit | 891 | 0.001122 |
import json
from urllib import request
import pymongo
connection = pymongo.MongoClient('mongodb://localhost')
db = connection.reddit
stories = db.stories
# stories.drop()
# req = request.Request('http://www.reddit.com/r/technology/.json')
# req.add_header('User-agent', 'Mozilla/5.0')
# reddit_page = request.urlopen(... | t = json.loads(reddit_page.read().decode())
#
# print('Ad | ding reddit posts')
# for item in parsed_reddit['data']['children']:
# stories.insert_one(item['data'])
#
# print('Finished adding reddit posts')
def find():
print('Keyword search started')
query = {'title': {'$regex': 'apple|google', '$options': 'i'}}
projection = {'title': 1, '_id': 0}
try:
... |
thortex/rpi3-webiopi | webiopi_0.7.1/python/webiopi/devices/analog/mcp492X.py | Python | apache-2.0 | 1,847 | 0.005414 | # Copyright 2012-2013 Eric Ptak - trouch.com
#
# 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 l... | & 0x01) << 7
d[0] |= (self.buffered & 0x01) << 6
d[0] |= (not self.gain & 0x01) << 5
d[0] |= (not self.shutdown & 0x01) << 4
d[0] |= (value >> 8) & 0x0F
d[1] = value & 0xFF
self.writeBytes(d)
self.values[channel] = value
class MCP4921(MCP492X):
| def __init__(self, chip=0, vref=3.3):
MCP492X.__init__(self, chip, 1)
class MCP4922(MCP492X):
def __init__(self, chip=0, vref=3.3):
MCP492X.__init__(self, chip, 2)
|
rankactive/cassandra-fdw | cassandra-fdw/__init__.py | Python | mit | 4,389 | 0.00319 | from multicorn import ForeignDataWrapper
from cassandra_provider import CassandraProvider
from properties import ISDEBUG
import properties
import schema_importer
import time
class CassandraFDW(ForeignDataWrapper):
def __init__(self, options, columns):
super(CassandraFDW, self).__init__(options, columns)
... | s
def pre_commit(self):
if ISDEBUG:
logger.log("pre commit")
| pass
def rollback(self):
if ISDEBUG:
logger.log("rollback")
pass
def sub_begin(self, level):
if ISDEBUG:
logger.log("sub begin {0}".format(level))
pass
def sub_commit(self, level):
if ISDEBUG:
logger.log("sub commit {0}".forma... |
lightningvapes/conky-ethereum-ticker-with-graph-chart | cb_balance_grabber.py | Python | gpl-3.0 | 267 | 0.011236 | #! /usr/bin/env python
import requests, json
from os.path import exp | anduser
from coinbase.wallet.client import Client
home = expanduser('~')
client = Client('YOUR_API_KEY', 'YOUR_API_SECRET')
accounts = cli | ent.get_accounts()
print accounts ['data'][0]['balance']
|
mcdeoliveira/ctrl | test/test_packet.py | Python | apache-2.0 | 5,810 | 0.012909 | import struct
import numpy
import io
import pickle
import pyctrl.packet as packet
def testA():
# test A
assert packet.pack('A','C') == b'AC'
assert packet.pack('A','B') == b'AB'
assert packet.pack('A','C') != b'AB'
assert packet.unpack_stream(io.BytesIO(b'AC')) == ('A', 'C')
assert packet.un... | et.pack('V',vector) == struct.pack('<ccIddd', b'V', b'D', 3, 1.3, -2, | 3)
(type, rvector) = packet.unpack_stream(
io.BytesIO(struct.pack('<ccIddd', b'V', b'D', 3, 1.3, -2, 3)))
assert type == 'V'
assert numpy.all(rvector == vector)
def testM():
# test MI
vector = numpy.array(((1,2,3), (3,4,5)), int)
assert packet.pack('M',vector) == struct.pack('<cIccIii... |
rvianello/rdkit | rdkit/sping/TK/pidTK.py | Python | bsd-3-clause | 16,537 | 0.010099 | """
A Tkinter based backend for piddle.
Perry A. Stoll
Created: February 15, 1999
Requires PIL for rotated string support.
Known Problems:
- Doesn't handle the interactive commands yet.
- PIL based canvas inherits lack of underlining strings from piddlePIL
You can find the latest version ... | scrollingViewPortSize=None, # a 2-tuple to define the size of the viewport
**kw):
"""This canvas allows you to add a tk.Canvas with a sping API for drawing.
To add scrollbars, the simpliest method is to set the 'scrollingViewPortSize'
equal to a tuple that describes the width and ... | of the canvas on screen. This sets scrollregion=(0,0, size[0], size[1]).
Then you can add scrollbars as you would any tk.Canvas.
Note, because this is a subclass of tk.Canvas, you can use the normal keywords
to specify a tk.Canvas with scrollbars, however, you should then be careful to... |
themiszamani/okeanos-LoD | core/fokia/provisioner.py | Python | agpl-3.0 | 21,373 | 0.001544 | from __future__ import (absolute_import, division,
print_function, unicode_literals)
import logging
import re
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
from kamaki.clients import astakos, cyclades
from kamaki.clients import ClientError
from kamaki.cli.config ... | vcpus = kwargs['slaves'] * kwargs['vcpus_slave'] + kwargs['vcpus_master']
ram = kwargs['slaves'] * kwargs['ram_slave'] + kwargs['ram_master']
disk = kwargs['slaves'] * kwargs['disk_slave'] + kwargs['disk_master']
project_id = self.find_project_id(**kwargs)['id']
cluster_size = kw... | vcpus=vcpus,
ram=ram,
disk=disk,
ip_allocation=kwargs['ip_allocation'],
network_request=kwargs['network_req... |
redcurrant/redcurrant | svc-monitor/contrib/rainx-monitor.py | Python | lgpl-3.0 | 1,285 | 0.010117 | #!/usr/bin/python
import sys
import urllib2
RAINX_STAT_KEYS = [
("rainx.reqpersec", "total_reqpersec"),
("rainx.reqputpersec", "put_reqpersec"),
("rainx.reqgetpersec", "get_reqpersec"),
("rainx.avreqtime", "total_avreqtime"),
("rainx.avputreqtime", "put_avreqtime"),
("rainx.avgetreqtime", "get_avreqtime"),
]
... | data
def get_stat_lines(url | , stat_keys):
stream = urllib2.urlopen(url)
data = parse_info(stream)
stream.close()
stats = [("stat.%s = %s" % (k[1], str(data[k[0]])))
for k in stat_keys if k[0] in data]
return stats
def main(args):
ip_port = args[1].split("|")[2]
stats_url = "http://%s/stat" % ip_port
fo... |
EBI-Metagenomics/emgapi | emgapi/migrations/0001_initial.py | Python | apache-2.0 | 19,658 | 0.006511 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2017-06-28 20:51
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.Cre... | ('author_name', models.CharField(blank=True, db_column='AUTHOR_NAME', max_length=100, null=True)),
('last_update', models.DateTimeField(db_column='LAST_UPDATE')),
('submission_account_id', models.CharField(blank=True, db_column='SUBMISSION_ACC | OUNT_ID', max_length=15, null=True)),
('result_directory', models.CharField(blank=True, db_column='RESULT_DIRECTORY', max_length=100, null=True)),
('first_created', models.DateTimeField(db_column='FIRST_CREATED')),
('project_id', models.CharField(blank=True, db_column='PR... |
mgrouchy/django-stronghold | test_project/test_project/wsgi.py | Python | mit | 402 | 0 | """
WSGI config for test_project project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
| https://docs.djangoproject.com/en/stable/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTI | NGS_MODULE", "test_project.settings")
application = get_wsgi_application()
|
jokuf/hack-blog | posts/migrations/0006_auto_20170327_1906.py | Python | mit | 843 | 0.003559 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-03-27 19:06
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('posts', '0005_post_author'),
]
operations = [
migrations.CreateModel(
... | ='posts.PostImage'),
| ),
]
|
ptitjes/quodlibet | tests/test_util_config.py | Python | gpl-2.0 | 11,883 | 0 | # 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.
import os
from tests import TestCase, mkstemp
from .helper import temp_... | "two", "three"]
conf.setstringlist("foo", "bar", vals)
self.failUnlessEqual(conf.getstringlist("foo", "bar"), vals)
| def test_stringlist_mixed(self):
conf = Config()
conf.add_section("foo")
self.failIf(conf.get("foo", "bar", None))
conf.setstringlist("foo", "bar", ["one", 2])
self.failUnlessEqual(conf.getstringlist("foo", "bar"), ["one", "2"])
def test_stringlist_quoting(self):
... |
Clinical-Genomics/scout | scout/commands/update/disease.py | Python | bsd-3-clause | 3,712 | 0.002156 | #!/usr/bin/env python
# encoding: utf-8
"""
update/disease.py
Update the disease terms in database
Created by Måns Magnusson on 2017-04-03.
Copyright (c) 2017 __MoonsoInc__. All rights reserved.
"""
import logging
import os
import click
from flask.cli import current_app, with_appcontext
from scout.constants import... | sources["genemap_lines"],
| hpo_disease_lines=resources["hpo_gene_lines"],
)
LOG.info("Successfully loaded all disease terms")
|
gvizquel/comunidad | comunidad/settings.py | Python | gpl-3.0 | 4,931 | 0.001825 | import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/
# SECURITY WARNING: keep the... | sql_psycopg2',
'HOST': '127.0.0.1',
'NAME': 'comunidad',
'PASSWORD': '123456',
'PORT': '5432',
'USER': 'postgres',
'SCHEMAS': 'public,demografia'
}
}
# Password validation
# https://docs.djangoproject.com/en | /1.9/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.pas... |
thilaire/missionBoard | src/AVR/genTableCountDown.py | Python | gpl-3.0 | 1,264 | 0.019778 | # coding=utf-8
# dictionary value -> 7-segment data
Font = {
0: 0b00111111, # (48) 0
1: 0b00000110, # (49) 1
2: 0b01011011, # (50) 2
3: 0b01001111, # (51) 3
4: 0b01100110, # (52) 4
5: 0b01101101, # (53) 5
6: 0b01111101, # (54) 6
7: 0b00100111, # (55) 7
8: 0b01111111, # (56) 8
9: 0b01101111, # (57) ... | ",".join(str(Font[array100[i]]) for i in range(8)) + "};")
# check
for i in range(256):
# if i&15:
p | rint("%s%d.%d%d%d%d" % ("1" if ((i >> 4) > 9) else " ", (i >> 4) % 10, array10[i & 15], array100[i & 7],
array100[i & 3], array100[(i << 1) & 3]))
# else:
# print("%d.%d%d%d%d" % (i >> 4, 0, 0, 0, 0))
|
raspberrywhite/django-sse | django_sse/views.py | Python | bsd-3-clause | 1,543 | 0.000648 | # -*- coding: utf-8 -*-
from django.views.generic import View
from django.views.decorators.csrf import csrf_exempt
try:
from django.http import StreamingHttpResponse as HttpResponse
except ImportError:
from django.http import HttpResponse
from django.utils.decorators import method_decorator
from sse import S... | in self.request.META:
return self.request.META['HTTP_LAST_EVENT_ID']
return None
def _iterator(self):
for subiterator in self.it | erator():
for bufferitem in self.sse:
yield bufferitem
@method_decorator(csrf_exempt)
def dispatch(self, request, *args, **kwargs):
self.sse = Sse()
self.request = request
self.args = args
self.kwargs = kwargs
response = HttpResponse(self._i... |
Crompulence/cpl-library | test/lammps/single/no_wall/time_varying_force/CFD_single_ball.py | Python | gpl-3.0 | 2,218 | 0.008566 | import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
from mpi4py import MPI
import sys
from cplpy import CPL
#initialise MPI and CPL
comm = MPI.COMM_WORLD
CPL | = CPL()
MD_COMM = CPL.init(CPL.CFD_REALM)
nprocs_realm = MD_COMM.Get_size()
## P | arameters of the cpu topology (cartesian grid)
npxyz = np.array([1, 1, 1], order='F', dtype=np.int32)
NProcs = np.product(npxyz)
print 'Number of arguments:', len(sys.argv), 'arguments: ', str(sys.argv)
if len(sys.argv) > 1:
g = float(sys.argv[1])
else:
g = 9.81
xyzL = np.array([1.5000000000000000E-003,
... |
shirk3y/cyclone | cyclone/httputil.py | Python | apache-2.0 | 9,933 | 0.000101 | # coding: utf-8
#
# Copyright 2010 Alexandre Fiori
# based on the original Tornado by Facebook
#
# 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... | ("http://exampl | e.com/foo?a=b", dict(c="d"))
'http://example.com/foo?a=b&c=d'
"""
if not args:
return url
if url[-1] not in ('?', '&'):
url += '&' if ('?' in url) else '?'
return url + urllib.urlencode(args)
class HTTPFile(ObjectDict):
"""Represents an HTTP file. For backwards compatibility, i... |
alex-ip/agdc | api-examples/source/main/python/tool/summarise_dataset_time_series.py | Python | bsd-3-clause | 25,656 | 0.004249 | #!/usr/bin/env python
# ===============================================================================
# Copyright (c) 2014 Geoscience Australia
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
... | DIAN = 8
MEDIAN_NON_INTERPOLATED = 9
SUM = 10
STANDARD_DEVIATION = 11
VARIANCE = 12
PERCENTILE = 13
class SummariseDatasetTimeSeriesWorkflow():
application_name = None
x = None
y = None
acq_min | = None
acq_max = None
process_min = None
process_max = None
ingest_min = None
ingest_max = None
satellites = None
apply_pqa_filter = None
pqa_mask = None
dataset_type = None
output_directory = None
overwrite = None
list_only = None
summary_method = None
c... |
miptliot/edx-platform | lms/djangoapps/courseware/tests/test_lti_integration.py | Python | agpl-3.0 | 9,169 | 0.002508 | """LTI integration tests"""
import json
import urllib
from collections import OrderedDict
import mock
import oauthlib
from django.conf import settings
from django.core.urlresolvers import reverse
from nose.plugins.attrib import attr
from courseware.tests import BaseTestXmodule
from courseware.views.views import get_... | ted_content = self.item_descriptor.render(STUDENT_VIEW).content
expected_content = self.runtime.r | ender_template('lti.html', self.expected_context)
self.assertEqual(generated_content, expected_content)
def test_lti_preview_handler(self):
generated_content = self.item_descriptor.preview_handler(None, None).body
expected_content = self.runtime.render_template('lti_form.html', self.expecte... |
XiaodunServerGroup/ddyedx | common/lib/xmodule/xmodule/vertical_module.py | Python | agpl-3.0 | 2,477 | 0.002019 | from xblock.fragment import Fragment
from xmodule.x_module import XModule
from xmodule.seq_module import SequenceDescriptor
from xmodule.progress import Progress
from pkg_resources import resource_string
# HACK: This shouldn't be hard-coded to two types
# OBSOLETE: This obsoletes 'type'
class_priority = ['video', 'pro... | text):
fragment = Fragment()
| contents = []
for child in self.get_display_items():
rendered_child = child.render('student_view', context)
fragment.add_frag_resources(rendered_child)
contents.append({
'id': child.id,
'content': rendered_child.content
})
... |
huggingface/transformers | tests/speech_to_text/test_feature_extraction_speech_to_text.py | Python | apache-2.0 | 10,984 | 0.003733 | # coding=utf-8
# Copyright 2021 HuggingFace Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | _and_variance_normalization_trunc_max_length(self):
feature_extractor = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict())
speech_inputs = [floats_list((1, x))[0] for x in range(800, 1400, 200)]
inputs = feature_extractor(
speech_inputs,
... | ntion_mask=True,
)
input_features = inputs.input_features
attention_mask = inputs.attention_mask
fbank_feat_lengths = np.sum(attention_mask == 1, axis=1)
self. |
eltonsantos/dom | dom/urls.py | Python | mit | 263 | 0.003802 | f | rom django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', include('launch.urls', namespace="launch", app_name="launch")),
url(r'^admin/', include(admin.site.urls)),
| )
|
naototty/pyflag | tests/init.py | Python | gpl-2.0 | 364 | 0.019231 | #!/usr/bin/env python
import pyflag.IO as IO
import pyflag.Registry as Registry
Registry.Init()
import pyflag.FileSystem as FileSystem
from FileSystem import DBF | S
case = "demo"
## This gives us a handle to the VFS
fsfd = Registry.FILESYSTEMS.fs['DBFS'](case)
## WE just open a file in the VFS:
#fd=fsfd.open(inode="Itest|S1/2")
## And read it
#print fd.rea | d()
|
pysofe/pysofe | pysofe/quadrature/base.py | Python | bsd-3-clause | 977 | 0.002047 | """
Provides the base class for all quadrature rules.
"""
import numpy as np
import copy
class QuadRule(object):
"""
Provides an abstract base class for all quadrature rules.
Parameters
----------
order : int
The polynomial order up | to which the quadrature should be exact
"""
def __init__(self, order, dimension):
| self._order = order
self._dimension = dimension
self._points = [None] * (dimension + 1)
self._weights = [None] * (dimension + 1)
self._set_data()
def _set_data(self):
"""
Sets the quadrature points and weights.
"""
raise NotImplementedError()
... |
googleapis/python-dialogflow | samples/generated_samples/dialogflow_generated_dialogflow_v2_intents_batch_delete_intents_sync.py | Python | apache-2.0 | 1,696 | 0.00059 | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | :
# Create a client
client = dialogflow_v2.IntentsClient()
# Initialize request argument(s)
intents = dialogflow_v2.Intent()
intents.display_name = "display_name_value"
request = dialogflow_v2.BatchDeleteIntentsRequest(
parent="parent_value",
intents=intents,
)
# Make ... | ("Waiting for operation to complete...")
response = operation.result()
# Handle the response
print(response)
# [END dialogflow_generated_dialogflow_v2_Intents_BatchDeleteIntents_sync]
|
zentralopensource/zentral | zentral/contrib/okta/__init__.py | Python | apache-2.0 | 79 | 0 | # django
default_app | _config = "z | entral.contrib.okta.apps.ZentralOktaAppConfig"
|
xydinesh/b3notify | b3notify.py | Python | apache-2.0 | 3,613 | 0 |
import os
import ConfigParser
import click
from base64 import b64encode
import requests
import json
class B3Notify(object):
"""
Build status notifier for bitbucket server
"""
def __init__(self, home='~/.b3notifyrc'):
self.home = home
self.verbose = True
self.config = {}
... | username = config.get(profile, 'username').strip("'")
self.password = config.get(profile, 'password').strip("'")
self.auth = '{0}'.format(
b64encode('{0}:{1}'.format(self.username, self.password))
)
@property
def headers(self):
return {
'Content-Type': 'a... | asic {0}'.format(self.auth)
}
def notify(
self, commit, build_url, build_key, build_name,
build_state='FAIL'):
data = {
# <INPROGRESS|SUCCESSFUL|FAILED>",
'state': build_state,
'key': build_key,
'name': build_name,
... |
MarkEEaton/api-workshop | 4-json-to-csv.py | Python | mit | 1,093 | 0.000915 | # import the libraries that you need
import requests
import csv
# make a GET request to the OneSearch X-Service API
response = requests.get('http://onesearch.cuny.edu/PrimoWebServices'
'/xservice/search/brief?'
'&institution=KB'
'&query=any,contai... | son
# and print this smaller bit of json
somedata = alldata['SEGMENTS']['JAGROOT']['RESULT']['FACETLIST']['FACET']\
[1]['FACET_VALUES']
print(somedata)
# open a file called mycsv.csv, then loop through the data
# and write to that file
with open('mycsv.csv', 'wb') as f:
writer = csv.writer(f)
... | |
bzamecnik/tfr | tfr/tuning.py | Python | mit | 1,850 | 0.001622 | from __future__ import print_function, division
import numpy as np
class Tuning():
"""
Equal temperament tuning - allows to convert between frequency and pitch.
- unit pitch space
- continous, unbounded
- 1.0 ~ one octave
- step pitch space
- continous, unbounded
- N steps ~ o... | in_division = bin_division
def quantize(self, freqs):
"""
Quantizes frequencies to nearest pitch bins (with optional division of
bins).
"""
retu | rn np.round(self.tuning.freq_to_pitch(freqs) * self.bin_division) / self.bin_division
|
qtekfun/htcDesire820Kernel | external/chromium_org/content/test/gpu/gpu_tests/webgl_conformance_expectations.py | Python | gpl-2.0 | 9,671 | 0.009616 | # Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.page import test_expectations
# Valid expectation conditions are:
#
# Operating systems:
# win, xp, vista, win7, mac, leopard, snowle... | /refract/refract_001_to_006.html',
['lion', 'intel'], bug=323736)
self.Skip('conformance/ogles/GL/tan/tan_001_to_006.html',
['lion', 'intel'], bug=323736)
# Mac/ATI failures
self.Skip('conformance/extensions/oes-texture-float-with-image-data.html',
['mac', 'amd'], bug=308328)
se... | self.Skip('conformance/textures/tex-image-and-sub-image-2d-with-array-buffer-view.html',
['mac', 'amd'], bug=308328)
self.Skip('conformance/textures/tex-image-and-sub-image-2d-with-image-data.html',
['mac', 'amd'], bug=308328)
self.Skip('conformance/textures/tex-image-and-sub-image-2d-with-image... |
masom/Puck | client/pixie/lib/setup_plugin.py | Python | lgpl-3.0 | 24,567 | 0.001628 | '''
Pixie: FreeBSD virtualization guest configuration client
Copyright (C) 2011 The Hotel Communication Network inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the Li... | command = cmd % (self.vm.interface, ip, netmask)
self.log('executing: `%s`' % command)
subprocess.Popen(shlex.split(str(command))).wait()
def _add_rc_ip(self, rc_addresses, file, alias_count, netaddr):
for item in rc_addresses:
if item.find(netaddr['ip']) > 0:
s... |
self.log("Registering new rc value for ip `%s`" % netaddr['ip'])
template = 'ifconfig_%s_alias%s="inet %s netmask %s"'
line = "%s\n" % template
va |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.