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 |
|---|---|---|---|---|---|---|---|---|
pavlenko-volodymyr/codingmood | codemood/social/admin.py | Python | mit | 270 | 0.003704 | from django.contrib import admin
from .models import Post
class PostAdmin(admin.ModelAdmin):
list_display = ('user', 'mood', 'mood_positive', 'mood_negative', 'mood_neutral', 'created' | )
list_filter = ('mood', 'created')
admin.site.register(Post, P | ostAdmin)
|
sdague/home-assistant | homeassistant/components/wink/fan.py | Python | apache-2.0 | 3,014 | 0 | """Support for Wink fans."""
import pywink
from homeassistant.components.fan import (
SPEED_HIGH,
SPEED_LOW,
SPEED_MEDIUM,
SUPPORT_DIRECTION,
SUPPORT_SET_SPEED,
FanEntity,
)
from . import DOMAIN, WinkDevice
SPEED_AUTO = "auto"
SPEED_LOWEST = "lowest"
SUPPORTED_FEATURES = SUPPORT_DIRECTION + S... | return SPEED_MEDIUM
if SPEED_HIGH == current_wink_speed:
return SPEED_HIGH
return None
@property
def current_direction(self):
"""Return direction of the fan [forward, reverse]."""
return self.wink.current_fan_direction()
@property
def speed_list(self)... | fan_speeds()
supported_speeds = []
if SPEED_AUTO in wink_supported_speeds:
supported_speeds.append(SPEED_AUTO)
if SPEED_LOWEST in wink_supported_speeds:
supported_speeds.append(SPEED_LOWEST)
if SPEED_LOW in wink_supported_speeds:
supported_speeds.appen... |
dannyroberts/eulxml | eulxml/__init__.py | Python | apache-2.0 | 903 | 0 | # file eulxml/__init__.py
#
# Copyright 2010,2011 Emory University Libraries
#
# License | d 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, software
# distrib | uted 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 governing permissions and
# limitations under the License.
__version_info__ = (0, 22, 0, None)
# Dot-connect all but the last. Last is... |
aspc/mainsite | aspc/courses/migrations/0014_auto_20160904_2350.py | Python | mit | 1,605 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.9 on 2016-09-04 23:50
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('courses', '0013_auto_20160903_0212'),
]
operations = [
migrations.RenameField(
... | ew_name='cached_approachable_rating',
),
migrations.RenameField(
model_name='section',
old_name='competency_rating',
new_name='cached_competency_rating',
),
migrations.RenameField(
model_name='section',
old_name='difficulty_rati | ng',
new_name='cached_difficulty_rating',
),
migrations.RenameField(
model_name='section',
old_name='engagement_rating',
new_name='cached_engagement_rating',
),
migrations.RenameField(
model_name='section',
old_name=... |
EricSchles/veyepar | dj/volunteers/urls.py | Python | mit | 1,412 | 0.010623 | # volunteers/urls.py
from django.conf.urls import *
from django.contrib.auth.decorators import login_required
from volunteers.views import *
urlpatterns = patterns('',
#(r'^$', login_required(ShowsInProcessing.as_view()), {}, 'volunteer_show_list'),
#(r'^(?P<show_slug>\[-\w]+)/$', login_required(ShowReview.... | d+)/(?P<edit_key>\w+)/$', ExpandCutList.as_view(), {}, 'guest_expand_cutlist'),
(r'^reopen/(?P<episode_id>\d+)/$', login_required(ReopenEpisode.as_view()), {}, 'volunteer_reopen'),
(r'^reopen/(?P<episode_id>\d+)/(?P<edit_key>\w+)/$', ReopenEpisode.as_view(), {}, 'guest_reopen'),
(r'^(?P<show_slug>[-\w]+)/(?... | , {}, 'volunteer_episode_review'),
(r'^(?P<show_slug>[-\w]+)/(?P<episode_slug>[-\w]+)/(?P<edit_key>\w+)/$', EpisodeReview.as_view(), {}, 'guest_episode_review'),
(r'^(?P<show_slug>[-\w]+)/(?P<episode_slug>[-\w]+)/$', login_required(EpisodeReview.as_view()), {'advanced': True}, 'volunteer_episode_review_advanced... |
okfish/django-oscar-shipping | oscar_shipping/packers.py | Python | bsd-3-clause | 4,871 | 0.006775 | from decimal import Decimal as D
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.utils.translation import ugettext_lazy as _
from oscar.core import loading
Scale = loading.get_class('shipping.scales', 'Scale')
weight_precision = getattr(settings, 'OSCAR_SHIPPING_WE... |
def volume(self):
return D(self.height*self.width*self.length).quantize(volume_precision)
class Container(Box):
name = ''
def __init__(self, h, w, l, name):
self.name = name
super(Container, self).__init__(h, w, l)
class ProductBox(Box): |
"""
'Packs' given product to the virtual box and scale it.
Takes size and weight from product attributes (if present)
"""
weight = 0
def __init__(self,
product,
size_codes=('width', 'height', 'length'),
weight_code='weight',
... |
Danielweber7624/pybuilder | src/main/python/pybuilder/plugins/exec_plugin.py | Python | apache-2.0 | 3,101 | 0.00258 | # -*- coding: utf-8 -*-
#
# This file is part of PyBuilder
#
# Copyright 2011-2015 PyBuilder Team
#
# 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/l... | tput.split('\n'):
logger.info(line)
logger.info('{0} end of verbatim {1} output {0}'.format(separator, output_type))
def run_command(phase, project, logger):
command_line = project.get_property('%s_command' % phase)
if not command_line:
return
process_handle = Popen(command_line, std... | ocess_handle.communicate()
stdout, stderr = stdout.decode(sys.stdout.encoding or 'utf-8'), stderr.decode(sys.stderr.encoding or 'utf-8')
process_return_code = process_handle.returncode
_write_command_report(project,
stdout,
stderr,
... |
a-krebs/finances | finances/django_registration/urls.py | Python | gpl-3.0 | 3,598 | 0.005837 | # Copyright (C) 2012 Aaron Krebs [email protected]
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is... |
# since the namspace is determined by the importing app
# TODO: see Issue #1
'post_change_redirect': reverse_lazy('r | egistration:auth_password_change_done')
},
name='auth_password_change'
),
url(r'^password/change/done/$',
auth_views.password_change_done,
{'template_name': 'registration/password_change_done.hamlpy'},
name='auth_password_change_done'
),
url(r'^password/reset/$',
... |
satyarth/pixelsort | pixelsort/util.py | Python | mit | 1,262 | 0.001585 | from colorsys import rgb_to_hsv
import time
def id_generator():
timestr = time.strftime("%Y%m%d-%H%M%S")
return timestr
def lightness(pixel):
# For backwards compatibility with python2
return rgb_to_hsv(pixel[0], pixel[1], pixel[2])[2] / 255.0
def hue(pixel):
return rgb_to_hsv(pixel[0], pixel[... | ])[0] / 255.0
| def saturation(pixel):
return rgb_to_hsv(pixel[0], pixel[1], pixel[2])[1] / 255.0
def crop_to(image_to_crop, reference_image):
"""
Crops image to the size of a reference image. This function assumes that the relevant image is located in the center
and you want to crop away equal sizes on both the left... |
HEPData/hepdata | tests/converter_test.py | Python | gpl-2.0 | 4,511 | 0.00133 | # This file is part of HEPData.
# Copyright (C) 2016 CERN.
#
# HEPData 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.
#
# HEPData is d... | d a copy of the GNU General Public License
# along with HEPData; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its statu | s
# as an Intergovernmental Organization or submit itself to any jurisdiction.
import os.path
import responses
import zipfile
from hepdata.config import CFG_CONVERTER_URL
from hepdata.modules.converter.tasks import convert_and_store
from hepdata.modules.records.utils.old_hepdata import mock_import_old_record
def tes... |
UT-Austin-FIS/django-coverage | django_coverage/utils/coverage_report/templates/default_module_exceptions.py | Python | apache-2.0 | 2,058 | 0.00243 | """
Copyright 2009 55 Minutes (http://www.55minutes.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 law or agreed t... | 3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />
<title>Test coverage report: %(title)s</title>
<style type="text/css" media="screen">
b | ody
{
font-family: "Lucida Sans Unicode", "Lucida Grande", sans-serif;
font-size: 13px;
}
#content-header
{
margin-left: 50px;
}
#content-header h1
{
font-size: 18px;
margin-bottom: 0;
}
#content-header p
{
... |
jbedorf/tensorflow | tensorflow/python/util/tf_inspect.py | Python | apache-2.0 | 13,772 | 0.01002 | # Copyright 2017 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... | pec = _inspect.FullArgSpec # pylint: disable=invalid-name
else:
FullArgSpec = namedtuple('FullArgSpec', [
'args', 'varargs', 'varkw', 'defaults', 'kwonlyargs', 'kwonlydefaults',
'annotations'
])
def _convert_maybe_argspec_to_fullargspec(argspec):
if isinstance(argspec, FullArgSpec):
return args... | argspec.args,
varargs=argspec.varargs,
varkw=argspec.keywords,
defaults=argspec.defaults,
kwonlyargs=[],
kwonlydefaults=None,
annotations={})
if hasattr(_inspect, 'getfullargspec'):
_getfullargspec = _inspect.getfullargspec # pylint: disable=invalid-name
def _getargspec(target... |
hariharaselvam/djangotraining | products/migrations/0002_stat.py | Python | apache-2.0 | 566 | 0.001767 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2016-10-16 04:54
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies | = [
('products', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Stat',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
| ('category_count', models.IntegerField()),
],
),
]
|
UNICT-DMI/Telegram-DMI-Bot | module/utils/__init__.py | Python | gpl-3.0 | 24 | 0 | """Var | ious ut | ilities"""
|
Ultimaker/Uranium | plugins/FileHandlers/OBJReader/OBJReader.py | Python | lgpl-3.0 | 5,356 | 0.003547 | # Copyright (c) 2020 Ultimaker B.V.
# Copyright (c) 2013 David Braam
# Uranium is released under the terms of the LGPLv3 or higher.
import os
from UM.Job import Job
from UM.Logger import Logger
from UM.Mesh.MeshReader import MeshReader
from UM.Mesh.MeshBuilder import MeshBuilder
from UM.Scene.SceneNode import SceneNo... | eVertexCount(3 * len(face_list))
num_vertices = len(vertex_list)
for face in face_list:
# Substract 1 from index, as obj starts counting at 1 instead of 0
i = face[0] - 1
j = face[1] - 1
k = face[2] - 1
ui = face[3... | uj = face[4] - 1
uk = face[5] - 1
ni = face[6] - 1
nj = face[7] - 1
nk = face[8] - 1
if i < 0 or i >= num_vertices:
i = 0
if j < 0 or j >= num_vertices:
j = 0
i... |
audreyr/opencomparison | apiv1/tests/data.py | Python | mit | 6,264 | 0.000958 | from grid.models import Grid
from django.contrib.auth.models import Group, User, Permission
from package.models import Category, PackageExample, Package
from grid.models import Element, Feature, GridPackage
from core.tests import datautil
def load():
category, created = Category.objects.get_or_create(
pk=... | last_login=u'2010-01-01 12:00:00',
#groups=[group1],
password=u'sha1$e6fe2$78b744e21cddb39117997709218f4c6db4e91894',
email='',
date_joined=u'2010-01-01 12:00:00',
)
user2.groups = [group1]
user3, created = User.objects.get_or_create(
pk=3,
username=u'st... | first_name='',
last_name='',
is_active=True,
is_superuser=False,
is_staff=True,
last_login=u'2010-01-01 12:00:00',
password=u'sha1$8894d$c4814980edd6778f0ab1632c4270673c0fd40efe',
email='',
date_joined=u'2010-01-01 12:00:00',
)
user4, created =... |
modera/mcloud | tests/test_remote.py | Python | apache-2.0 | 6,741 | 0.005192 | import sys
from flexmock import flexmock
import inject
from mcloud.events import EventBus
from mcloud.txdocker import IDockerClient, DockerTwistedClient
from mcloud.util import txtimeout
import pytest
from mcloud.remote import Server, Client, ApiError, Task, ApiRpcServer
from twisted.internet import reactor, defer
fr... | s stopped and returned some result
yield task_defered.callback('this is respnse')
# and client should recieve this resul
yield sleep(0.1)
assert task.data == ['nami-nam | i']
assert task.is_running == False
assert task.response == 'this is respnse'
assert len(server.rpc_server.tasks_running) == 0
assert len(server.rpc_server.task_list()) == 0
#-----------------------------------
# Cleanup
#-----------------------------------
client.shutdown()
serv... |
alfa-addon/addon | plugin.video.alfa/channels/freeporn.py | Python | gpl-3.0 | 5,059 | 0.016024 | # -*- coding: utf-8 -*-
#------------------------------------------------------------
import sys
PY3 = False
if sys.version_info[0] >= 3: PY3 = True; unicode = str; unichr = chr; long = int
if PY3:
import urllib.parse as urlparse # Es muy lento en PY2. En PY3 es nativo
else:
import... | lone(title="Mejor valorada" , action="lista", url=host + "/top-rated/"))
itemlist.append(item.clone(title="Mas largo" , action="lista", url=host + "/longest/"))
itemlist.append(item.clone(title="Modelos" , action="categorias", url=host + "/models/most-popular/"))
| itemlist.append(item.clone(title="Categorias" , action="categorias", url=host + "/categories/"))
itemlist.append(item.clone(title="Buscar", action="search"))
return itemlist
def search(item, texto):
logger.info()
texto = texto.replace(" ", "%20")
item.url = "%s/search/%s/?mode=async&action=get_bl... |
mmasaki/trove | trove/tests/unittests/guestagent/test_pkg.py | Python | apache-2.0 | 21,209 | 0 | # Copyright (c) 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 ... | d 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 governing permissions and limitations
# under the License.
import ... | n import utils
from trove.guestagent import pkg
from trove.tests.unittests import trove_testtools
"""
Unit tests for the classes and functions in pkg.py.
"""
class PkgDEBInstallTestCase(trove_testtools.TestCase):
def setUp(self):
super(PkgDEBInstallTestCase, self).setUp()
self.pkg = pkg.DebianP... |
SnowWalkerJ/quantlib | quant/data/wind/tables/ccommodityfutureseodprices.py | Python | gpl-3.0 | 1,944 | 0.015819 | from ....common.db.sql import VARCHAR, Numeric as NUMBER, DateTime as DATETIME, Column, BaseModel, CLOB, DATE
VARCHAR2 = VARCHAR
class CCommodityFuturesEODPrices(BaseModel):
"""
4.182 中国商品期货日行情
Attributes
----------
object_id: VARCHAR2(100)
对象ID
s_info_windcode: VARCHAR2(40)
... |
s_dq_open: NUMBER(20,4)
开盘价(元)
s_dq_high: NUMBER(20,4)
最高价(元)
s_dq_low: NUMBER(20,4)
最低价(元)
s_dq_close: NUMBER(20,4)
收盘价(元)
s_dq_settle: NUMBER(20,4)
结算价(元)
s_dq_volume: NUMBER(20,4)
成交量(手)
s_dq_amount: NUMBER(20,4)
成... | AR2(10)
合约类型 1:主力合约2:真实合约3:连续合约
opdate: DATETIME
opdate
opmode: VARCHAR(1)
opmode
"""
__tablename__ = "CCommodityFuturesEODPrices"
object_id = Column(VARCHAR2(100), primary_key=True)
s_info_windcode = Column(VARCHAR2(40))
trade_dt = Column(VARCHAR2(8))
s_... |
bilbeyt/ituro | ituro/results/models.py | Python | mit | 11,573 | 0.000432 | from django.db import models
from django.dispatch import receiver
from django.utils.encoding import python_2_unicode_compatible
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from django.core.validators import MaxValueValidator, MinValueValidator
from projects.models import Pro... | ender=LineFollowerJuniorResult)
def line_follower_junior_result_calculate_score(sender, instance, *args,
**kwargs):
instance.score = instance.duration * (1 + 0.2 * instance.runway_out)
@python_2_unicode_compatible
class ConstructionResult(BaseResult):
project = ... | odels.ForeignKey(
Project, limit_choices_to={"category": "construction"})
class Meta:
verbose_name = _("Construction Result")
verbose_name_plural = _("Construction Results")
ordering = [
"disqualification", "-score", "minutes", "seconds", "milliseconds"]
def __str__... |
seibert/blaze-core | blaze/blir/passes.py | Python | bsd-2-clause | 6,473 | 0.006334 | import sys
import time
import lexer
import parser
import cfg
import typecheck
import codegen
import errors
import exc
from threading import Lock
compilelock = Lock()
#------------------------------------------------------------------------
# Pipeline
#---------------------------------------------------------------... | f args.ddump_lex:
lexer.ddump_lex(source)
if args.ddump_parse:
parse | r.ddump_parse(source)
if args.ddump_blocks:
cfg.ddump_blocks(source)
if args.ddump_optimizer:
codegen.ddump_optimizer(source)
if args.ddump_tc:
typecheck.ddump_tc(source)
try:
# =====================================
start = time.time()
with errors.list... |
wasit7/visionmarker | beta/wl_auth/urls.py | Python | mit | 244 | 0.016393 | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^signin/', | views.signin, name='signin'),
url(r'^signout/', views.signout, name='signout'),
url(r'^change_password/', views.change_password, name='cha | nge_password'),
] |
mytliulei/DCNRobotInstallPackages | windows/win32/scapy-2/scapy/arch/windows/__init__.py | Python | apache-2.0 | 19,506 | 0.009382 | ## This file is part of Scapy
## See http://www.secdev.org/projects/scapy for more informations
## Copyright (C) Philippe Biondi <[email protected]>
## This program is published under a GPLv2 license
"""
Customizations needed to support Microsoft Windows.
"""
import os,re,sys,socket,time
from glob import glob
from scap... | rint list of available network interfaces in human readable form"""
print "%s %s %s" % ("IFACE".ljust(5), "IP".ljust(15), "MAC | ")
for iface_name in sorted(self.data.keys()):
dev = self.data[iface_name]
mac = str(dev.mac)
if resolve_mac:
mac = conf.manufdb._resolve_MAC(mac)
|
bruecksen/isimip | isi_mip/core/templatetags/footer.py | Python | mit | 833 | 0.0012 | from django import template
from django.template.loader import render_to_string
from isi_mip.core.models import FooterLinks
register = template.Library()
@register.simple_tag(takes_context=True)
def footer(context, **kwargs):
request = conte | xt['request']
settings = FooterLinks.for_site(request.site)
page = context.get('page')
links = []
for link in settings.footer_links.all():
n | ame = link.name
target = link.target.specific
if page and target == page:
active = True
else:
active = False
if target.url:
links.append({'url': target.url + (link.anchor or ''), 'text': name, 'active': active})
context = {
'links': links
... |
lzw120/django | django/contrib/admin/util.py | Python | bsd-3-clause | 15,005 | 0.0012 | import datetime
import decimal
from django.db import models
from django.db.models.sql.constants import LOOKUP_SEP
from django.db.models.deletion import Collector
from django.db.models.related import RelatedObject
from django.forms.forms import pretty_name
from django.utils import formats
from django.utils.html import ... | tected]
return to_delete, perms_needed, protected
class NestedObjects(Collector):
def __init__(self, *args, **kwargs):
super(NestedObjects, self).__init__(*args, **kwargs | )
self.edges = {} # {from_instance: [to_instances]}
self.protected = set()
def add_edge(self, source, target):
self.edges.setdefault(source, []).append(target)
def collect(self, objs, source_attr=None, **kwargs):
for obj in objs:
if source_attr:
self... |
thibault/UrbanJungle | site/urbanjungle/controllers/frontend.py | Python | gpl-3.0 | 2,808 | 0.006766 | import os
import Image
from flask import Module, request, current_app, render_template, jsonify, send_file, abort
from werkzeug import secure_filename
from urbanjungle.models import db
from urbanjungle.models.report import Report
from sqlalchemy.ext.serializer import dumps
frontend = Module(__name__)
def allowed_file... | e_path or not os.path.exists(image_path):
abort(404)
if not os.path.exists(thumb_path):
image = Image.open(image_path)
image.thumbnail((current_app.config['THUMB_WIDTH'], current | _app.config['THUMB_HEIGHT']), \
Image.ANTIALIAS)
image.save(thumb_path)
return send_file(thumb_path, mimetype="image/jpeg")
@frontend.route('/map')
def map():
'''Render the main map page'''
return render_template('map.html')
@frontend.route('/map/markers/<ne_lat>,<ne_lng>,<sw_lat>,<sw... |
adaptivdesign/odooku-compat | odooku/cli/commands/info.py | Python | apache-2.0 | 365 | 0 | import click
__all__ = [
'info'
]
INFO_MESSAGE = """
Odooku
--------------------------------------
availa | ble modules: {num_modules}
"""
@click.command()
@click.pass_context
def info(ctx):
logger = (
ctx.obj['logger']
)
from odoo.modules import get_modules
print INFO_MESSAGE.format(
num_modules=len(get_module | s())
)
|
genie9/pulp | pulp_simulator.py | Python | gpl-3.0 | 13,319 | 0.015166 | import sys
import numpy
import scipy
import json
import itertools
import random
import os
from sys import stderr, exit, argv
from scipy.sparse.linalg import spsolve
from sklearn.metrics.pairwise import euclidean_distances
from nltk.stem import SnowballStemmer
def load_data_sparse(prefix) :
return scipy.sparse.csr... | v ]
def order_keys_by_value(d) :
return [ i[0] for i in sorted(d.items(), key=lambda x : x[1], reverse=True) ]
def okapi_bm25(query, n, data, features) :
stemmer = SnowballStemmer('english')
query_terms = [ stemmer.stem(term) for term in query.lower().split() ]
tmp = {}
for qt in query_terms :
... | continue
findex = features[qt]
for aindex in numpy.nonzero(data[:, findex])[0] :
akey = aindex.item()
if akey not in tmp :
tmp[akey] = 1.0
tmp[akey] *= data[aindex,findex]
return order_keys_by_value(tmp)[:n]
def linrel(articles, feedbac... |
kelvinguu/lang2program | strongsup/predicate.py | Python | apache-2.0 | 1,835 | 0 | """Predicate: output token."""
from gtd.utils import ComparableMi | xin
class Predicate(ComparableMixin):
"""Represents a step in the logical form (i.e., an output token)."""
__slots__ = ['_name', '_original_string', '_types']
def __init__(self, name, original_string=None, types=None):
"""Create Predicate.
Args:
| name (unicode)
original_string (unicode)
types (tuple[unicode])
"""
self._name = name
self._original_string = original_string
self._types = types or tuple()
def __eq__(self, other):
return (isinstance(other, Predicate)
and s... |
hryamzik/ansible | lib/ansible/modules/windows/win_defrag.py | Python | gpl-3.0 | 2,682 | 0.002237 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: 2017, Dag Wieers (@dagwieers) <d | [email protected]>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'suppo | rted_by': 'community'}
DOCUMENTATION = r'''
---
module: win_defrag
version_added: '2.4'
short_description: Consolidate fragmented files on local volumes
description:
- Locates and consolidates fragmented files on local volumes to improve system performance.
- 'More information regarding C(win_defrag) is available from... |
Johnzero/erp | openerp/addons/fetchmail/fetchmail.py | Python | agpl-3.0 | 12,859 | 0.006766 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... | ingIO
import zipfile
import base64
import ad | dons
import netsvc
from osv import osv, fields
import tools
from tools.translate import _
logger = logging.getLogger('fetchmail')
class fetchmail_server(osv.osv):
"""Incoming POP/IMAP mail server account"""
_name = 'fetchmail.server'
_description = "POP/IMAP Server"
_order = 'priority'
_columns ... |
andrewyoung1991/abjad | abjad/tools/systemtools/Configuration.py | Python | gpl-3.0 | 6,475 | 0.001853 | # -*- encoding: utf-8 -*-
from __future__ import print_function
import abc
import configobj
import os
import time
import validate
from abjad.tools.abctools.AbjadObject import AbjadObject
class Configuration(AbjadObject):
r'''A configuration object.
'''
### CLASS VARIABLES ###
__slots__ = (
'... | stractproperty
def configurat | ion_file_name(self):
r'''Gets configuration file name.
Returns string.
'''
raise NotImplementedError
@property
def configuration_file_path(self):
r'''Gets configuration file path.
Returns string.
'''
return os.path.join(
self.configu... |
wangxiangyu/horizon | openstack_dashboard/dashboards/project/firewalls/forms.py | Python | apache-2.0 | 16,187 | 0 | # Copyright 2013, Big Switch Networks, 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... | 'name': name_or_id, 'reason': e}
LOG.error(msg)
redirect = reverse(self.failure_url)
exceptions.handle(request, msg, redirect=redirect)
class UpdateFirewall(forms.SelfHandlingForm):
name = forms.CharField(max_length=80,
label=_("Name"),
... | label=_("Description"),
required=False)
firewall_policy_id = forms.ChoiceField(label=_("Policy"))
admin_state_up = forms.ChoiceField(choices=[(True, _('UP')),
(False, _('DOWN'))],
label... |
PersianWikipedia/pywikibot-core | pywikibot/families/vikidia_family.py | Python | mit | 661 | 0 | # -*- coding: utf-8 -*-
"""Family module for Vikidia."""
#
# (C) Pywikibot team, 2010-2018
#
# Distributed under the terms of the MIT license.
#
from __futu | re__ import absolute_import, division, unicode_literals
from pywikibot import family
class Family(family.SubdomainFamily):
"""Family class for Vikidia."""
name = 'vikidia'
domain = 'vikidia.org'
codes = ['ca', 'de', 'el', 'en', 'es', 'eu', 'fr', 'hy', 'it', 'ru', 'scn']
# Sites we want to edi... | t not count as real languages
test_codes = ['central', 'test']
def protocol(self, code):
"""Return https as the protocol for this family."""
return 'https'
|
j-towns/pymanopt | pymanopt/tools/autodiff/_tensorflow.py | Python | bsd-3-clause | 2,913 | 0 | """
Module containing functions to differentiate functions using tensorflow.
"""
try:
import tensorflow as tf
from tensorflow.python.ops.gradients import _hessian_vector_product
except ImportError:
tf = None
from ._backend import Backend, assert_backend_available
class TensorflowBackend(Backend):
def... | "
"arguments) with respect to which compilation is to be "
"carried out")
return True
return False
@assert_backend_available
def compile_function(self, objective, argument):
if not isinstance(argument, list):
def func(x):
... | d for i, d in zip(argument, x)}
return self._session.run(objective, feed_dict)
return func
@assert_backend_available
def compute_gradient(self, objective, argument):
"""
Compute the gradient of 'objective' and return as a function.
"""
tfgrad = tf.gradie... |
conklinbd/MovementAnalysis | TemplateInstall/PortalDeploy/StageApp.py | Python | apache-2.0 | 726 | 0.009642 | """
@author: ArcGIS for Intelligence
@contact: [email protected]
@company: Esri
@version: 1.0
@description: Used to stage the apps for Movement Analysis
@requirements: Python 2.7.x, ArcGIS 10.3.1
@copyright: Esri, 2015
"""
import arcresthelper
from arcresthelper import portalautomati... | /DamageAssessment.log'
configFiles= ['./configs/StageApp.json']
globalLoginInfo = './configs/GlobalLoginInfo.json'
dateTimeFormat = '%Y-%m-%d %H:%M'
pa = portalautomation.portalautomation(globalLoginInfo)
pa.setLog(log_file=log_file)
pa.publishfromconfig(config | Files=configFiles,
combinedApp=None,
dateTimeFormat=dateTimeFormat)
del pa |
cortext/crawtextV2 | ~/venvs/crawler/lib/python2.7/site-packages/lxml/html/soupparser.py | Python | mit | 4,360 | 0.002982 | __doc__ = """External interface to the BeautifulSoup HTML parser.
"""
__all__ = ["fromstring", "parse", "convert_tree"]
from lxml import etree, html
from BeautifulSoup import \
BeautifulSoup, Tag, Comment, ProcessingInstruction, NavigableString
def fromstring(data, beautifulsoup=None, makeelement=None, **bsarg... | rough the `makeelement` keyword. By default, the standard
``BeautifulSoup`` class and the default factory of `lxml.html` are
used.
"" | "
if not hasattr(file, 'read'):
file = open(file)
root = _parse(file, beautifulsoup, makeelement, **bsargs)
return etree.ElementTree(root)
def convert_tree(beautiful_soup_tree, makeelement=None):
"""Convert a BeautifulSoup tree to a list of Element trees.
Returns a list instead of a single... |
ijzer/cwbot-ndy | kol/data/Patterns.py | Python | bsd-3-clause | 28,912 | 0.014596 | """
This module holds all of the regular expression patterns that pykol uses. It makes sense
to store them all in the same place since many patterns are used by multiple requests.
The 'patterns' data object is a dictionary mapping patternId to pattern. If pattern is a tuple,
then the first element of the tuple should b... | "inventoryMultipleItems" : r'<img [^>]*descitem\(([0-9]+)[^>]*></td><td[^>]*><b[^>]*>([^<>]+)</b> <span>\(([0-9]+)\)<\/span>',
"itemAutosell" : r'<br>Selling Price: <b>(\d*) Meat\.<\/b>',
"itemImage" : r'<img src="http:\/\/images\.kingdomofloathing\.com\/itemimages\/(.*?)"',
| "itemName" : r'<b>(.+?)<\/b>',
"itemType" : r'<br>Type: <b>([^<]*)<.*\/b><br>',
"tooFull" : r"You're too full to eat that\.",
"tooDrunk" : r"You're way too drunk already\.",
"notBooze" : r"That's not booze\.",
"notFood" : r"That's not something you can eat\.",
"notEquip" : r"That's not someth... |
indirectlylit/kolibri | kolibri/core/content/test/test_content_app.py | Python | mit | 72,718 | 0.001595 | """
To run this test, type this in command line <kolibri manage test -- kolibri.core.content>
"""
import datetime
import unittest
import uuid
import mock
import requests
from django.conf import settings
from django.core.cache import cache
from django.core.urlresolvers import reverse
from django.test import TestCase
fr... | t_tags(self):
root_tag_count = content.ContentNode.objects.get(title="root").tags.count()
self.assertEqual(root_tag_count, 3)
c1_tag_count = content.Con | tentNode.objects.get(title="c1").tags.count()
self.assertEqual(c1_tag_count, 1)
c2_tag_count = content.ContentNode.objects.get(title="c2").tags.count()
self.assertEqual(c2_tag_count, 1)
c2c1_tag_count = content.ContentNode.objects.get(title="c2c1").tags.count()
self.assertEqual... |
bancek/egradebook | src/apps/infosys/admin.py | Python | gpl-3.0 | 6,165 | 0.005515 | from django.contrib import admin
from django.utils.text import truncate_words
from django.core import urlresolvers
from django.utils.html import escape
from infosys.models import *
def uni_tr_10(field_name):
def func(obj):
return truncate_words(unicode(getattr(obj, field_name)), 10)
func.short_de... | 'priimek', 'emso']
raw_id_fields = ['uporabnik', 'stalno_prebivalisce',
'zacasno_prebivalisce', 'oce', 'mati']
list_filter = ['v_dijaskem_domu']
def ime(self, obj):
return obj.uporabnik.first_name
ime.admin_order_field = 'uporabnik__first_name'
def priimek(sel... | priimek.admin_order_field = 'uporabnik__last_name'
class RazredAdmin(admin.ModelAdmin):
search_fields = ['ime']
list_display = ['id', 'ime', uni_fk_tr_10('solsko_leto'), uni_fk_tr_10('smer'), uni_fk_tr_10('razrednik')]
raw_id_fields = ['razrednik']
filter_horizontal = ['dijaki']
class PoucujeAdmin... |
RachellCalhoun/craftsite | accounts/urls.py | Python | gpl-3.0 | 1,059 | 0.00661 | from django.conf.urls import include, url
from . import views
urlpatterns = [
url(r'^register/$', views.register,name="register"),
# url('^logout', views.logout_view,name="logout"),
# url('^login', views.logout_view,name="login"),
url(r'^password_change/$','django.contrib.auth.views.pa... | done',
'django.contrib.auth.views.pas | sword_change_done',
{'template_name':'profiles/password_change_done.html'}),
url(r'^login/$', 'django.contrib.auth.views.login'),
url(r'^logout/$', 'django.contrib.auth.views.logout',
{'next_page': '/'}),
url(r'^', include('django.contrib.auth.urls')),
url(... |
douban/code | vilya/views/m.py | Python | bsd-3-clause | 1,035 | 0 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from vilya.libs.template import st
from vilya.models.feed import get_user_inbox, get_public_feed
MAX_ACT_COUNT = 100
_q_exports = ['actions', 'public_timeline']
def _q_index(request):
return st('/m/feed.html', **locals())
def public_timeline(re... | lic = request.get_form_var('is_public', '')
user = request.user
all_actions = []
if is_public == 'true':
all_actions = get_public_feed().get_actions(0, MAX_ACT_COUNT)
elif user:
all_actions = get_user_inbox(user.username).get_actions(
0, MAX_A | CT_COUNT)
if since_id:
actions = []
for action in all_actions:
if action.get('uid') == since_id:
break
actions.append(action)
else:
actions = all_actions
return st('/m/actions.html', **locals())
|
chepazzo/trigger | trigger/contrib/docommand/__init__.py | Python | bsd-3-clause | 12,051 | 0.001079 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
trigger.contrib.docommand
~~~~~~~~~~~~~~~~~~~~~~~~~
This package provides facilities for running commands on devices using the CLI.
"""
__author__ = 'Jathan McCollum, Mike Biancianello'
__maintainer__ = 'Jathan McCollum'
__email__ = '[email protected]'
__copyright__ =... | ut in enumerate(results):
cmd = self.commands[i]
d = {'cmd': cmd, 'out': out, 'dev': dev | ice}
outs.append(d)
self.data[devname] = outs
return True
def __children_with_namespace(self, ns):
return lambda elt, tag: elt.findall('./' + ns + tag)
def from_juniper(self, data, device, commands=None):
# If we've set foce_cli, use from_base() instead
if s... |
hzlf/openbroadcast | website/apps/abcast/admin/baseadmin.py | Python | gpl-3.0 | 1,860 | 0.017204 | from django.contrib import admin
from abcast.models import *
from django.contrib.auth.models import User
from genericadmin.admin import GenericAdminModelAdmin, GenericTabularInline
class MembersInline(admin.TabularInline):
model = Station.members.through
class ChannelsInline(admin.TabularInline):
model = C... | TabularInline):
exclude = ['description', 'slug', 'processed', 'conversion_status']
model = Jingle
class JingleAdmin(admin.ModelAdmin):
list_display = ('name', 'duration', 'set', 'type' )
list_filter = ('type',)
readonly_fields = ('uuid', 'slug', 'folder')
class JingleSe... | uid', 'slug', )
inlines = [JingleInline, ]
class StreamServerAdmin(admin.ModelAdmin):
list_display = ('name', 'host', 'type' )
list_filter = ('type',)
readonly_fields = ('uuid',)
admin.site.register(Station, StationAdmin)
admin.site.register(Channel, ChannelAdmin)
admi... |
WhiskeyMedia/ella | ella/positions/admin.py | Python | bsd-3-clause | 1,381 | 0.003621 | from django.contrib import admin
from django.utils.translation import ugettext, ugettext_lazy as _
from ella.positions.models import Position
from ella.utils import timezone
class PositionOptions(admin.ModelAdmin):
def show_title(self, obj):
if not obj.target:
| return '-- %s --' % ugettext('empty position')
else:
return u'%s [%s]' % (obj.t | arget.title, ugettext(obj.target_ct.name),)
show_title.short_description = _('Title')
def is_filled(self, obj):
if obj.target:
return True
else:
return False
is_filled.short_description = _('Filled')
is_filled.boolean = True
def is_active(self, obj):
... |
leeopop/2015-CS570-Project | prepare_lda.py | Python | mit | 897 | 0.031215 | from loader import *
from extract_keywords import split_line
from collections import defaultdict
def main():
keyword_data = load_single_file('keyword_table.csv')
paper_data = load_single_file('Paper.csv')
with open('lda_input.txt', 'w', encoding='utf-8') as write_file:
for paper_id in paper_data.keys():
paper... | .strip | ()
if len(line) == 0:
continue
line += '\n'
write_file.write(line)
pass
if __name__ == '__main__':
main() |
vineodd/PIMSim | GEM5Simulation/gem5/src/python/m5/ticks.py | Python | gpl-3.0 | 3,221 | 0.003415 | # Copyright (c) 2007 The Regents of The University of Michigan
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met: redistributions of source code must retain the above copyright
# notice, this list ... | kert
from __future__ import print_function
import sys
from m5.util import warn
# fix the global frequency
def fixGlobalFrequency():
import _m5.core
_m5.core.fixClockFrequency()
def setGlobalFrequency(ticksPerSecond):
from m5.util import convert
import _m5.core
if isinstance(ticksPerSecond, (int... | requency(ticksPerSecond))
else:
raise TypeError, \
"wrong type '%s' for ticksPerSecond" % type(ticksPerSecond)
_m5.core.setClockFrequency(int(tps))
# how big does a rounding error need to be before we warn about it?
frequency_tolerance = 0.001 # 0.1%
def fromSeconds(value):
import _... |
jjiang-mtu/virtual-breast-project | dynamic_SWE/write_FEBio_format_quadratic/vmtkfebiowytet10.py | Python | gpl-2.0 | 1,844 | 0.016269 | #!/usr/bin/env python
## Program: VMTK
## Module: $RCSfile: vmtkfebiowytet10.py,v $
## Language: Python
## Date: $Date: 2016/08/19 09:49:59 $
## Version: $Revision: 1.6 $
## Copyright (c) Jingfeng Jiang, Yu Wang. All rights reserved.
## See LICENCE file | for details.
## This software is distributed WITHOUT ANY WARRANTY; without even
## the i | mplied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
## PURPOSE. See the above copyright notices for more information.
import vtk
import vtkvmtk
import sys
import pypes
vmtkfebiowytet10 = 'vmtkfebiowrite'
class vmtkfebiowrite(pypes.pypeScript):
def __init__(self):
pypes.pypeScript.__in... |
jeremiah-c-leary/vhdl-style-guide | vsg/rules/if_statement/rule_031.py | Python | gpl-3.0 | 988 | 0.001012 |
from vsg.rules import previous_line
from vsg import token
lTokens = []
lTokens.append(token.if_statement.if_keyword)
class rule_031(previous_line):
'''
This rule checks for blank lines or comments above the **if** keyword.
In the case of nested **if** statements, the rule will be enfoced on the first *... | .
|configuring_previous_line_rules_link|
The default style is :code:`no_code`.
**Violation**
.. code-block:: vhdl
C <= '1';
if (A = '1') then
B <= '0';
end if;
-- This is a comment
if (A = '1') then
B <= '0';
end if;
**Fix**
.. ... | C <= '1';
if (A = '1') then
B <= '0';
end if;
-- This is a comment
if (A = '1') then
B <= '0';
end if;
'''
def __init__(self):
previous_line.__init__(self, 'if', '031', lTokens)
self.lHierarchyLimits = [0]
self.style = 'no_code'
|
mattcaldwell/autopylot | autopylot/django/__init__.py | Python | mit | 324 | 0.003086 | # from http://stackoverflow.com/questions/4581789/how-do-i-get-us | er-ip-address-in-django
def get_client_ip(request):
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
ip = x_forwarded_for.split(',')[0].stri | p()
else:
ip = request.META.get('REMOTE_ADDR')
return ip
|
MrReN/django-oscar | oscar/forms/widgets.py | Python | bsd-3-clause | 5,740 | 0 | from django.core.files.uploadedfile import InMemoryUploadedFile
import re
import six
from django import forms
from django.forms.util import flatatt
from django.forms.widgets import FileInput
from django.template import Context
from django.template.loader import render_to_string
from django.utils.encoding import force_... | been previously uploaded. Selecting the image will open the file
dialog and allow for selecting a new or replacing image file.
"""
template_name = 'partials/image_input_widget.html'
attrs = {'accept': 'image/*'}
def render(self, name, value, attrs=None):
"""
Render the ``input`` f... | able relative to ``MEDIA_URL``. Further
attributes for the ``input`` element are provide in ``input_attrs`` and
contain parameters specified in *attrs* and *name*.
If *value* contains no valid image URL an empty string will be provided
in the context.
"""
final_attrs = se... |
ryepdx/account_payment_cim_authdotnet | wizard/__init__.py | Python | agpl-3.0 | 1,222 | 0 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2011 NovaPoint Group LLC (<http://www.novapointgroup.com>)
# Copyright (C) 2004-2010 OpenERP SA (<http://www.openerp.com>)
#
# This program is f... | ###
impor | t create_payment_profile
import make_transaction
import edit_payment_profile
import delete_payment_profile
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
eduNEXT/edunext-platform | common/djangoapps/xblock_django/admin.py | Python | agpl-3.0 | 2,485 | 0.004427 | """
Django admin dashboard configuration.
"""
from config_models.admin import ConfigurationModelAdmin, KeyedConfigurationModelAdmin
from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from common.djangoapps.xblock_django.models import XBlockConfiguration, XBlockStudioConfiguratio... | XBlockStudioConfiguration support state accordingly.'),
'fields': ('enabled',)
}),
('Deprecate XBlock', {
'description': _("Only XBlocks listed in a course's Advanced Module List can be flagged as deprecated. "
"Remember to update XBlockStudioConfigu... | s not impact whether or not new XBlock instances can be created in Studio."),
'fields': ('deprecated',)
}),
)
class XBlockStudioConfigurationAdmin(KeyedConfigurationModelAdmin):
"""
Admin for XBlockStudioConfiguration.
"""
fieldsets = (
('', {
'fields': ('na... |
foosel/OctoPrint | src/octoprint/plugins/tracking/__init__.py | Python | agpl-3.0 | 15,412 | 0.026022 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
import octoprint.pl... | self._plugin_manager.enabled_plugins
plugins_thirdparty = [plugin for plugin in plugins.values() if not plugin.bundled]
payload = dict(plugins=",".join(map(lambda x: "{}:{}".format(x.key.lower(),
| x.version.lower() if x.version else "?"),
plugins_thirdparty)))
self._track("pong", body=True, **payload)
def _track_startup(self):
if not self._settings.get_boolean(["events", "startup"]):
return
payload = dict(version=get_octoprint_ve... |
ctrlaltdel/neutrinator | vendor/openstack/load_balancer/v2/flavor.py | Python | gpl-3.0 | 1,423 | 0 | # Copyright 2019 Rackspace, US Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance wit | h 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, WIT | HOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from openstack import resource
class Flavor(resource.Resource):
resource_key = 'flavor'
resources_key = 'flavors'
base_path = '/lb... |
uclouvain/OSIS-Louvain | education_group/ddd/validators/_copy_check_mini_training_end_date.py | Python | agpl-3.0 | 1,855 | 0.002157 | # ############################################################################
# OSIS stands for Open Student Information System. It's an application
# designed to manage the core business of higher education institutions,
# such as universities, faculties, institutes and professional schools.
# The core business i... | students, teachers,
# courses, programs and so on.
#
# Copyright (C) 2015-2020 Université catholique de Louvain (http://www.uclouvain.be)
#
# This program is free software: you can redistribute it and/or modify
# it under the ter | ms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FI... |
mmaelicke/scikit-gstat | docs/conf.py | Python | mit | 7,252 | 0.000552 | # -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/stable/config
# -- Path setup ------------------------------------------------------------... | HTML output -------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list | of builtin themes.
#
html_theme = 'pydata_sphinx_theme'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#
html_theme_options = {
'github_url': 'https://github.com/mmaelicke/scikit-gstat',
}
html_cont... |
adebray/enumerating_abelian_groups | finite_abelian_groups.py | Python | mit | 5,033 | 0.020481 | #!/usr/bin/env python3.5
# Arun Debray, 24 Dec. 2015
# Given a group order, classifies finite abelian groups of that order.
# ./finite_abelian_groups.py [-tpi] number
# -t formats the output in TeX (as opposed to in the terminal)
# -p chooses the primary components decomposition (default)
# -i chooses the invariant f... | choice in itertools.product(*decomps_at_primes)]
# Uses the partitions in a different way to make a list of all abelian groups of a given order in
# the invariant-factors decomposition.
def invariant_factor_decomp(factors: collections.Counter) -> list:
decomps_at_primes = [partitions(p, factors[p]) for p in factors]... | ue=1))
for choice in itertools.product(*decomps_at_primes)]
# Returns "there are n abelian groups" or "there is one abelian group" depending on the value of n.
def format_plurals(n: int) -> str:
if n == 1:
return 'There is one abelian group'
else:
return 'There are %d abelian groups' % n
# Formats and prints ... |
cmuphillycapstone/ckanext-dictionary | ckanext/dictionary/tests/test_plugin.py | Python | agpl-3.0 | 98 | 0.020408 | """Tests for plugin.py."""
import ckanext.dictionary.plugin as pl | ugin
def t | est_plugin():
pass |
akkana/scripts | dirsneeded.py | Python | gpl-2.0 | 4,269 | 0.001171 | #!/usr/bin/env python3
# What directories are needed to run an app?
# Use strace to find out. Potentially useful for setting up chroots.
# Usage: dirsneeded.py cmd [arg arg ...]
'''
TODO:
> o for anything where access attempt is made in chroot and fails,
> at least by default, only consider it something to pos... | ctories accessed, and if merely accessed, or if also
> read. Likewise, divide and conquer, do any tests fail if read
> access is removed, likewise to then have x removed, or directory
> removed.
'''
import subprocess
from pathlib import Path
from collections import defaultdict
import shlex
import sys
de... | ments)
under strace, and output a list of files and directories opened.
Returns a dict of lists of fileinfo dicts.
{ "dirpath", [ ("filename": "/tmp/foo", "mode": "O_RDONLY", etc... ] }
"""
'''Some sample strace out lines:
openat(AT_FDCWD, "/etc/ld.so.preload", O_RDONLY|O_CLOEXEC) = 3
exe... |
somebody1234/Charcoal | directiondictionaries.py | Python | mit | 2,433 | 0 | from direction import Direction, Pivot
XMovement = {
Direction.left: -1,
Direction.up: 0,
Direction.right: 1,
Direction.down: 0,
Direction.up_left: -1,
Direction.up_right: 1,
Direction.down_left: -1,
Direction.down_right: 1
}
YMovement = {
Direction.left: 0,
Direction.up: -1,
... | _right,
Direction.down_left: Direction.up_left,
Direction.down_right: Direction.down_left
}
NextDirection = {
Direction.left: Direction.up_left,
Direction.up: Direction.up_right,
| Direction.right: Direction.down_right,
Direction.down: Direction.down_left,
Direction.up_left: Direction.up,
Direction.up_right: Direction.right,
Direction.down_left: Direction.left,
Direction.down_right: Direction.down
}
DirectionCharacters = {
Direction.left: "-",
Direction.up: "|",
... |
andrewstephens75/gensite | gensite/siteconfig.py | Python | mit | 1,317 | 0.012908 | import os.path
import json
class Tag:
def __init__(self, tag, title, icon):
self.tag = tag
self.title = title
self.icon = icon
class SiteC | onfig:
def __init__(self, site_dir):
self.site_dir = site_dir
config_file_name = os.path.join(self.site_dir, "config.js")
if not os.path.exists(config_file_name):
raise CommandError("No site config file exists : " + site_config_file)
site_config = {}
with open(config_file_name, "r", enco... | ir"]
self.template = site_config["template"]
self.blog_name = site_config["blog_name"]
self.blog_description = site_config["blog_description"]
self.blog_author = site_config["blog_author"]
self.root_url = site_config["root_url"]
self.relative_index = site_config["re... |
iemejia/coursera-dl | coursera/test/test_api.py | Python | lgpl-3.0 | 4,808 | 0.003536 | """
Test APIs.
"""
import json
import pytest
from mock import patch
from coursera import api
from coursera.test.utils import slurp_fixture
@pytest.fixture
def course():
course = api.CourseraOnDemand(session=None, course_id='0')
return course
@patch('coursera.api.get_page_json')
def test_ondemand_programm... | ply)]
expected_output = json.loads(slurp_fixture('json/supplement-extract-links-from-lectures-output.json'))
assets = ['giAxucdaEeWJTQ5WTi8YJQ']
output = course._extract_links_from_lecture_assets(assets)
output = json.loads(json.dumps(output))
assert expected_output == output
@patch('coursera.api... | ure_assets grabs url
links both from typename == 'asset' and == 'url'.
"""
get_page_json.side_effect = [
json.loads(slurp_fixture('json/supplement-open-course-assets-typename-url-reply-1.json')),
json.loads(slurp_fixture('json/supplement-open-course-assets-typename-url-reply-2.json')),
... |
Azure/azure-batch-apps-python | batchapps/test/unittest_pool.py | Python | mit | 7,440 | 0.007124 | #-------------------------------------------------------------------------
# The Azure Batch Apps Python Client
#
# Copyright (c) Microsoft Corporation. All rights reserved.
#
# The MIT License (MIT)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated docu... | (None, "Test", None)
mock_update.called = False
with self.assertRaises(RestCallException):
pool.resize(1)
self.assertFalse(mock_update.called)
def test_pool_update(self):
"""Test delete"""
api = mock.create_autospec(BatchAppsApi)
pool = Pool(api)
... | utospec(Response)
api.get_pool.return_value.success = True
api.get_pool.return_value.result = {
'targetDedicated':'5',
'currentDedicated':'4',
'state':'active',
'allocationState':'test',
}
self.assertEqual(pool.target_size, 0)
... |
titilambert/home-assistant | homeassistant/components/integration/sensor.py | Python | apache-2.0 | 6,827 | 0.000586 | """Numeric integration of data coming from a source sensor over time."""
from decimal import Decimal, DecimalException
import logging
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (
ATTR_UNIT_OF_MEASUREMENT,
CONF_NAME,
STATE_UNAVAILABL... | vol.Optional(CONF_UNIT_PREFIX, default=None): vol.In(UNIT_PREFIXES),
vol.Optional(CONF_UNIT_TIME, d | efault=TIME_HOURS): vol.In(UNIT_TIME),
vol.Optional(CONF_UNIT_OF_MEASUREMENT): cv.string,
vol.Optional(CONF_METHOD, default=TRAPEZOIDAL_METHOD): vol.In(
INTEGRATION_METHOD
),
}
)
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set u... |
endlessm/chromium-browser | third_party/llvm/lldb/test/API/lang/cpp/trivial_abi/TestTrivialABI.py | Python | bsd-3-clause | 2,923 | 0.004105 | """
Test that we work properly with classes with the trivial_abi attribute
"""
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
class TestTrivialABI(TestBase):
mydir = TestBase.compute_mydir(__file__)
NO_DEBUG_INFO_TESTCASE = Tru... | Out()
outVal_ret = thread.GetStopReturnValue()
self.check_value(outVal_ret, 30)
def expr_test(self, trivial):
(target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint(self,
"Set a breakpo | int here", self.main_source_file)
# Stop in a function that takes a trivial value, and try both frame var & expr to get its value:
if trivial:
self.check_frame(thread)
return
# Now continue to the same thing without the trivial_abi and see if we get that right:
... |
ericchill/gnofract4d | fract4d/test_stdlib.py | Python | bsd-3-clause | 14,992 | 0.014141 | #!/usr/bin/env python
# tests the standard library of math functions
import unittest
import math
import cmath
import string
import commands
import types
import testbase
import absyn
import codegen
import fractparser
import fractlexer
import fsymbol
import translate
class Test(testbase.TestBase):
def setUp(self... | result = self.cpredict(pyfunc,val)
return [ codefrag, lookat, result]
def manufacture_tests(self,myfunc,pyfunc):
vals = [ 0+0j, 0+1j, 1+0j, 1+1j, 3+2j, 1-0j, 0-1j, -3+2j, -2-2j, -1+0j ]
| return map(lambda (x,y) : self.make_test(myfunc,pyfunc,x,y), \
zip(vals,range(1,len(vals))))
def cotantests(self):
def mycotan(z):
return cmath.cos(z)/cmath.sin(z)
tests = self.manufacture_tests("cotan",mycotan)
# CONSIDER: comes out as -0,1.... |
cuijiaxing/nlp | rewriter/rules/rewrite_rule/generator.py | Python | gpl-2.0 | 4,155 | 0.004091 | import nltk
import json
import sys
sys.path.append("../../")
import parser
from entity import Word
class ModelRewriter:
rewriteRules = None
rewriteRuleFileName = "model.txt"
@staticmethod
def loadModel():
inputFile = open("model.txt")
modelJsonString = inputFile.read()
inputF... | Sentence):
print i | nputSentence
sentencePOS = ModelRewriter.getPOSList(inputSentence)
nearestModels = ModelRewriter.getNearestModel(sentencePOS)
questions = []
for model in nearestModels:
tempQuestionList = ModelRewriter.generateQuestionFromModel(model, inputSentence)
questions += t... |
UManPychron/pychron | pychron/hardware/gauges/mks/__init__.py | Python | apache-2.0 | 788 | 0.001269 | # ===============================================================================
# Copyright 2011 Jake Ross
#
# 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/licens... | erning p | ermissions and
# limitations under the License.
# ===============================================================================
'''
Gauges Package contains
G{packagetree }
'''
|
amenonsen/ansible | lib/ansible/modules/network/fortios/fortios_firewall_vip6.py | Python | gpl-3.0 | 46,189 | 0.002728 | #!/usr/bin/python
from __future__ import (absolute_import, division, print_function)
# Copyright 2019 Fortinet, Inc.
#
# 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 Lic... | - present
- absent
version_added: 2.9
firewall_vip6:
description:
- C | onfigure virtual IP for IPv6.
default: null
type: dict
suboptions:
arp_reply:
description:
- Enable to respond to ARP requests for this virtual IP address. Enabled by default.
type: str
choices:
-... |
ByrdOfAFeather/AlphaTrion | Community/migrations/0034_auto_20171121_1316.py | Python | mit | 1,619 | 0.003706 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2017-11-21 18:16
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_depende... | name='SongSuggestions',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('suggestions', models.TextField(help_text="Please list links to songs, we can't play it with just a name")),
('community', m... | n.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
migrations.AlterField(
model_name='communityextraratings',
name='overall_rating',
field=models.PositiveIntegerField(choices=[(1, '1'), (2, '2'), (3, 'e'), (4, '4'), (5, '5'), (6, '6'), (7, '7'), (8, '8'), (9,... |
nash-x/hws | neutron/db/vpn/vpn_validator.py | Python | apache-2.0 | 4,980 | 0.000602 | # Copyright 2014 Cisco Systems, Inc. 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 requir... | self._l3_plugin = manager.NeutronManager.get_service_plugins().get(
constants.L3_ROUTER_NAT)
return self._l3_plugin
@property
def core_plugin(self):
try:
return self._core_plugin
except AttributeError:
self._core_plugin = manager.Neut... | is greater than DPD interval."""
if ipsec_sitecon['dpd_timeout'] <= ipsec_sitecon['dpd_interval']:
raise vpnaas.IPsecSiteConnectionDpdIntervalValueError(
attr='dpd_timeout')
def _check_mtu(self, context, mtu, ip_version):
if mtu < VpnReferenceValidator.IP_MIN_MTU[ip_vers... |
sinotradition/meridian | meridian/acupoints/laogong21.py | Python | apache-2.0 | 241 | 0.034043 | # | !/usr/bin/python
#coding=utf-8
'''
@author: sheng
@license:
'''
SPELL=u'láogōng'
CN=u'劳宫'
NAME=u'laogong21'
CHANNEL='pericardium'
CHANNEL_FULLNAME='PericardiumChannelofHand-Jueyin'
SEQ='PC8'
if __name__ == '__main__ | ':
pass
|
vetscience/Tools | Utils/base.py | Python | bsd-3-clause | 7,040 | 0.014773 | #!/usr/bin/env python
'''
Oct 10, 2017: Pasi Korhonen, The University of Melbourne
Simplifies system calls, logs and pipe interaction.
'''
import sys, os, time #, ConfigParser
import shlex, subprocess, errno
from threading import Timer
###############################################################################
... | ''' Writes a message to the log file
'''
self.log.write("## %s\n" %myStr)
###########################################################################
def shell(self, myStr, doPrint = True, myStdout = False, ignoreFailure = False, log = True):
'''Runs given command in a shell and waits... | yStr)
if doPrint == True:
print("# " + myStr, file=sys.stderr) # is printed as comment line which is easy to remove
if myStdout == True:
p = subprocess.Popen(myStr, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)
else:
p = subprocess.Popen(myStr,... |
AwesomeTurtle/personfinder | app/add_note.py | Python | apache-2.0 | 7,586 | 0.000791 | #!/usr/bin/python2.7
# 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 ... | ort urlparse
# TODO(jessien): Clean up duplicate code here and in create.py.
# https://github.com/ | google/personfinder/issues/157
# how many days left before we warn about imminent expiration.
# Make this at least 1.
EXPIRY_WARNING_THRESHOLD = 7
class Handler(BaseHandler):
def get(self):
# Check the request parameters.
if not self.params.id:
return self.error(404, _('No person id ... |
20c/vaping | src/vaping/plugins/vodka.py | Python | apache-2.0 | 3,075 | 0.000325 | import copy
import confu.sche | ma
import vaping
import vaping.config
import vaping.io
from vaping.plugins import PluginConfigSchema
try:
import vodka
import vodka.data
except ImportError:
pass
try:
import graphsrv
import graphsrv.group
except ImportError:
graphsrv = None
def probe_to_graphsrv(probe):
"""
takes a ... | " in config:
source, group = config["group"].split(".")
group_field = config.get("group_field", "host")
group_value = config[group_field]
graphsrv.group.add(
source, group, {group_value: {group_field: group_value}}, **config
)
return
# automatic group set... |
mattesno1/Sick-Beard | lib/requests/packages/urllib3/util.py | Python | gpl-3.0 | 11,326 | 0.000618 | # urllib3/util.py
# Copyright 2008-2013 Andrey Petrov and contributors (see CONTRIBUTORS.txt)
#
# This module is part of urllib3 and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
from base64 import b64encode
from collections import namedtuple
from socket import error as Socke... | rt
if ':' in url:
_host, port = url.split(':', 1)
if not host:
host = _host
if not port.isdigit():
raise LocationParseError("Failed to parse: %s" % url)
port = | int(port)
elif not host and url:
host = url
if not path:
return Url(scheme, auth, host, port, path, query, fragment)
# Fragment
if '#' in path:
path, fragment = path.split('#', 1)
# Query
if '?' in path:
path, query = path.split('?', 1)
return Url(scheme... |
kawamon/hue | desktop/core/ext-py/cx_Oracle-6.4.1/samples/tutorial/solutions/bind_sdo.py | Python | apache-2.0 | 2,694 | 0.003712 | #------------------------------------------------------------------------------
# bind_sdo.py (Section 4.4)
#--------------------------------------------------------------------------- | ---
#------------------------------------------------------------------------------
# Copyright 2017, 2018, Oracle and/or its affiliates. All rights reserved.
#------------------------------------------------------------------------------
from __future__ import print_function
import cx_Oracle
import db_config
con =... | sor()
# Create table
cur.execute("""begin
execute immediate 'drop table testgeometry';
exception when others then
if sqlcode <> -942 then
raise;
end if;
end;""")
cur.execute("""create table testgeometry (
... |
tensorflow/tensorflow | tensorflow/python/debug/lib/common.py | Python | apache-2.0 | 2,967 | 0.004382 | # Copyright 2017 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... | ing representation of a graph element.
If the graph element has the attribute "name", return name. Otherwise, return
a __str__ representation of the graph element. Certain graph elements, such as
`SparseTensor`s, do not have the attribute "name".
Args:
elem: The graph | element in question.
Returns:
If the attribute 'name' is available, return the name. Otherwise, return
str(fetch).
"""
return elem.name if hasattr(elem, "name") else str(elem)
def get_flattened_names(feeds_or_fetches):
"""Get a flattened list of the names in run() call feeds or fetches.
Args:
... |
pnprog/goreviewpartner | gnugo_analysis.py | Python | gpl-3.0 | 13,115 | 0.060465 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from gtp import gtp
from Tkinter import *
from toolbox import *
from toolbox import _
def get_full_sequence_threaded(worker,current_color,deepness):
sequence=get_full_sequence(worker,current_color,deepness)
threading.current_thread().sequence=sequence
... | color in ('w','W'):
current_color='b'
else:
current_color='w'
else:
gnugo.undo()
#one_move.add_comment_text(additional_comments)
log("Creating the influence map")
black_influence=gnugo.get_gnugo_initial_influence_black()
black_t | erritories_points=[]
black_influence_points=[]
white_influence=gnugo.get_gnugo_initial_influence_white()
white_territories_points=[]
white_influence_points=[]
for i in range(self.size):
for j in range(self.size):
if black_influence[i][j]==-3:
black_territories_points.append([i,j])
if white_inf... |
st-tu-dresden/inloop | tests/testrunner/tests.py | Python | gpl-3.0 | 6,974 | 0.002156 | import signal
import subprocess
import sys
from pathlib import Path
from unittest import TestCase, skipIf
from django.test import tag
from inloop.testrunner.runner import DockerTestRunner, collect_files
BASE_DIR = Path(__file__).resolve().parent
DATA_DIR = str(BASE_DIR.joinpath("data"))
class CollectorTest(TestCas... | nner.check_task("test -d /checker/output/storage", DATA_DIR)
self.ass | ertEqual(result.rc, 0)
def test_output_filedict(self):
"""Test if we can create a file which appears in the files dictionary."""
result = self.runner.check_task("echo -n FOO >/checker/output/storage/bar", DATA_DIR)
self.assertEqual(result.rc, 0)
self.assertEqual("FOO", result.files[... |
mahak/nova | nova/tests/functional/libvirt/base.py | Python | apache-2.0 | 14,789 | 0.000135 | # Copyright (C) 2018 Red Hat, Inc
# 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 applicable ... | elf.assertNotIn(hostname, self.compute_rp_uuids)
self.computes[hostname] = _start_compute(hostname, host_info)
self.compute_rp_uuids[hostname] = self.placement.get(
'/resource_providers?name=%s' % hostname).body[
'resource_providers'][0]['uuid']
return hostname
class... | st class set self.server for the specific test instnace
and self.{src,dest} to indicate the direction of the migration. For any
scenarios more complex than this they should override _migrate_stub with
their own implementation.
"""
def setUp(self):
super().setUp()
self.useFixture(fix... |
cedadev/ndg_oauth | ndg_oauth_server/ndg/oauth/server/lib/authenticate/password_authenticator.py | Python | bsd-3-clause | 2,193 | 0.006384 | """OAuth 2.0 WSGI server middleware providing MyProxy certificates as access tokens
"""
__author__ = "W van Engen"
__date__ = "01/11/12"
__copyright__ = "(C) 2011 F | OM / Nikhef"
__license__ = "BSD | - see LICENSE file in top-level directory"
__contact__ = "[email protected]"
__revision__ = "$Id$"
from base64 import b64decode
from ndg.oauth.server.lib.authenticate.authenticator_interface import AuthenticatorInterface
from ndg.oauth.server.lib.oauth.oauth_exception import OauthException
class PasswordAut... |
meyt/sqlalchemy-dict | setup.py | Python | mit | 1,268 | 0 | import sys
from setuptools import setup, find_packages
package_name = "sqlalchemy_dict"
py_version = sys.version_info[:2]
def read_version(module_name):
f | rom re import match, S
from os.path import join, dirname
f = open(join(dirname(__file__), module_name, "__init__.py"))
return match(r".*__version__ = (\"|')(.*?)('|\")", f.read(), S).group(2)
dependencies = ["sqlalchemy"]
if py_version < (3, 5):
dependencies.append("typing")
setup(
name=package... | chemy extension for interacting models with python dictionary."
),
long_description=open("README.rst").read(),
url="https://github.com/meyt/sqlalchemy-dict",
packages=find_packages(),
install_requires=dependencies,
license="MIT License",
classifiers=[
"Development Status :: 3 - Alpha... |
smartczm/python-learn | Old-day01-10/s13-day1/system.py | Python | gpl-2.0 | 1,313 | 0.012573 | #!/usr/bin/env python3.5
# -*- coding: utf-8 -*-
# Author: ChenLiang
# 执行系统命令
import os
os.system("ls -al")
os.mkdir("pwd")
read = os.popen("df -hT").read()
# 查看系统路径
import sys
print(sys.path)
# 命令行下tab补全命令
# For MAC:
import sys
import readline
import rlcom | pleter
if sys.platform == 'darwin' and sys.version_info[0] == 2:
readline.parse_and_bind("tab: complete") # linux | and python3 on mac
else:
readline.parse_and_bind("bind ^I rl_complete")
# 说明:上面的代码如果在Mac上不好用,可以尝试下面的代码
# https://docs.python.org/2/library/rlcompleter.html
try:
import readline
except ImportError:
print("Module readline not available.")
else:
import rlcompleter
readline.parse_and_bind("tab: comple... |
etherex/pyepm | test/helpers.py | Python | mit | 931 | 0.003222 | from distutils import spawn
import mock
import pytest
import requests
from pyepm import config as c
config = c.get_default_config()
has_solc = spawn.find_executable("solc")
solc = pytest.mark.skipif(not has_solc, reason="solc compiler not found")
COW_ADDRESS = '0xcd2a3d9f938e13cd947ec05abc7fe734df8dd826'
def is_h... | return True
except ValueError:
return False
def mock_json_response(status_code=200, error=None, result=None):
m = mock.MagicMock(spec=requests.Response)
m.status_code = status_code
base_json_response = {u'jsonrpc': u'2.0', u'id': u'c7c427a5-b6e9 | -4dbf-b218-a6f9d4f09246'}
json_response = dict(base_json_response)
if result:
json_response[u'result'] = result
elif error:
json_response[u'error'] = error
if status_code >= 400:
m.reason = 'Error Reason'
m.json.return_value = json_response
return m
|
danielhers/tupa | tests/test_features.py | Python | gpl-3.0 | 5,494 | 0.003276 | """Testing code for the tupa.features package, unit-testing only."""
import os
from collections import OrderedDict
import pytest
from ucca import textutil
from tupa.action import Actions
from tupa.features.dense_features import DenseFeatureExtractor
from tupa.features.sparse_features import SparseFeatureExtractor
fro... | ctors = self.wordvectors
config.args.omit_features = self.omit
return SparseFeatureExtractor(omit_features=self.omit) if self.name == SPARSE else DenseFeatureExtractor(
OrderedDict((p.name, p.create_from_config()) for p in Model(None, c | onfig=config).param_defs()),
indexed=self.indexed, node_dropout=0, omit_features=self.omit)
def feature_extractors(*args, **kwargs):
return [FeatureExtractorCreator(SPARSE, *args, **kwargs), FeatureExtractorCreator(DENSE, *args, **kwargs),
FeatureExtractorCreator(DENSE, *args, indexed=True... |
padraic-padraic/MPHYSG001_CW1 | example.py | Python | gpl-2.0 | 216 | 0.00463 | import greengrap | h
if __name__ == '__main__':
from matplotlib i | mport pyplot as plt
mygraph = greengraph.Greengraph('New York','Chicago')
data = mygraph.green_between(20)
plt.plot(data)
plt.show()
|
mikeckennedy/python-data-driven-nov9 | playground/classdict.py | Python | gpl-3.0 | 121 | 0.008264 | class Person:
def __init | __(self):
self.name = 'jeff'
self.age = 10
p = Per | son()
print(p.__dict__)
|
stevenvanrossem/son-emu | src/emuvim/api/openstack/openstack_dummies/neutron_dummy_api.py | Python | apache-2.0 | 44,105 | 0.002993 | """
Copyright (c) 2017 SONATA-NFV and Paderborn University
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 ap... | air_ | groups",
resource_class_kwargs={'api': self})
self.api.add_resource(SFC.PortPairGroupUpdate, "/v2.0/sfc/port_pair_groups/<group_id>.json",
"/v2.0/sfc/port_pair_groups/<group_id>",
resource_class_kwargs={'api': self})
... |
desihub/fiberassign | old/py/mock.py | Python | bsd-3-clause | 3,161 | 0.008858 | '''
Functions for working with DESI mocks and fiberassignment
TODO (maybe):
This contains hardcoded hacks, especially wrt priorities and
interpretation of object types
'''
from __future__ import print_function, division
import sys, os
import numpy as np
from astropy.table import Table, Column
from fiberassign import... | ype -= 1
assert np.min(itype >= 0)
#- rdzipn has float32 ra, dec, but it should be float64
ra = ra.astype | ('float64') % 360 #- enforce 0 <= ra < 360
dec = dec.astype('float64')
#- Hardcoded in rdzipn format
# 0 : 'QSO', #- QSO-LyA
# 1 : 'QSO', #- QSO-Tracer
# 2 : 'LRG', #- LRG
# 3 : 'ELG', #- ELG
# 4 : 'STAR', #- QSO-Fake
# 5 : 'UNKNOWN', #- LRG-Fake
# 6 : '... |
megarcia/WxCD | setup.py | Python | gpl-3.0 | 18,007 | 0 | """
Python script "setup.py"
by Matthew Garcia, PhD student
Dept. of Forest and Wildlife Ecology
University of Wisconsin - Madison
[email protected]
Copyrig | ht (C) 2015-2016 by Matthew Garcia
Licensed Gnu GPL v3; see 'LICENSE_GnuGPLv3.txt' for complete terms
Send questions, bug reports, any related requests | to [email protected]
See also 'README.md', 'DISCLAIMER.txt', 'CITATION.txt', 'ACKNOWLEDGEMENTS.txt'
Treat others as you would be treated. Pay it forward. Valar dohaeris.
PURPOSE: Verifies sample data, scripts, modules, documents, auxiliary files.
Verifies availability of python dependencies used by var... |
ptroja/spark2014 | testsuite/gnatprove/tests/NB19-026__flow_formal_vectors/test.py | Python | gpl-3.0 | 73 | 0 | fro | m test_support import *
do_flow(opt=["-u", "indefinite_bounded.ad | b"])
|
StegSchreck/RatS | tests/unit/criticker/test_criticker_ratings_inserter.py | Python | agpl-3.0 | 9,321 | 0.001609 | import os
from unittest import TestCase
from unittest.mock import patch
from bs4 import BeautifulSoup
from RatS.criticker.criticker_ratings_inserter import CritickerRatingsInserter
TESTDATA_PATH = os.path.abspath(
os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, "assets")
)
class CritickerRatingsI... | test_find_movie_success_by_imdb(
self, browser_mock, base_init_mock, site_mock, compare_mock
):
site_mock.browser = browser_mock
browser_mock.page_source = self.search_results
inserter = CritickerRatingsInserter(N | one)
inserter.site = site_mock
inserter.site.site_name = "Criticker"
inserter.failed_movies = []
compare_mock.return_value = True
result = inserter._find_movie(self.movie) # pylint: disable=protected-access
self.assertTrue(result)
@patch(
"RatS.criticker.c... |
silvau/Addons_Odoo | module_reload/module.py | Python | gpl-2.0 | 1,349 | 0.008154 | from openerp.modules.registry import RegistryManager
from openerp.netsvc import Service
from osv import fields, osv
from osv.orm import MetaModel
from reimport import reimport
class module(osv.osv):
_inherit = "ir.module.module"
def button_reload(self, cr, uid, ids, context=None):
for module_recor | d in | self.browse(cr, uid, ids, context=context):
#Remove any report parsers registered for this module.
module_path = 'addons/' + module_record.name
for service_name, service in Service._services.items():
template = getattr(service, 'tmpl', '')
if type(temp... |
Alberto-Beralix/Beralix | i386-squashfs-root/usr/share/pyshared/gi/_gobject/constants.py | Python | gpl-3.0 | 3,114 | 0.000321 | # -*- Mode: Python; py-indent-offset: 4 -*-
# pygobject - Python bindings for the GObject library
# Copyright (C) 2006-2007 Johan Dahlin
#
# gobject/constants.py: GObject type constants
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# Lic... | = _gobject.G_MININT32
G_MAXINT32 = _gobject.G_MAXINT32
G_MAXUINT32 = _gobject.G_MAXUINT32
G_MININT64 = _gobject.G_MININT64
G_MAXINT64 = _gobject.G_MAXINT64
G_MAXUINT64 = _gobject.G_MAXUINT64
G_MAXSIZE = _gobject.G_MAXSIZE
G_MAXSSIZE = _gobject.G_MAXSSIZE
G_MINOFFSET = | _gobject.G_MINOFFSET
G_MAXOFFSET = _gobject.G_MAXOFFSET
|
Micronaet/micronaet-mx8 | sale_delivery_partial_B/__init__.py | Python | agpl-3.0 | 1,040 | 0 | # -*- coding: utf-8 -*-
############# | ##################################################################
#
# Copyright (C) 2001-2014 Micronaet SRL (<http://www.micronaet.it>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software... | eful,
# 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 have received a copy of the GNU Affero General Public License
# along with this program. If not, see... |
smmbllsm/aleph | aleph/views/documents_api.py | Python | mit | 5,217 | 0.000192 | import os
import logging
from werkzeug.exceptions import BadRequest, NotFound
from flask import Blueprint, redirect, send_file, request
from apikit import jsonify, Pager, get_limit, get_offset, request_data
from aleph.core import archive, url_for, db
from aleph.model import Document, Entity, Reference, Collection
from... | tion_id.in_(collections))
hashes = request.args.getlist('content_hash')
if len(hashes):
q = q.filter(Document.content_hash.in_(hashes))
return jsonify(Pager(q))
@blueprint.route('/api/1/documents/<int:document_id>')
def view(document_id):
doc = get_document(document_id)
enable_cache()
... | log_event(request, document_id=doc.id)
data['data_url'] = archive.generate_url(doc.meta)
if data['data_url'] is None:
data['data_url'] = url_for('documents_api.file',
document_id=document_id)
if doc.meta.is_pdf:
data['pdf_url'] = data['data_url']
else... |
SevereOverfl0w/Krympa | krympa/__init__.py | Python | mit | 597 | 0.001675 | from pyramid.config import Configurator
from pyramid.renderers import JSONP
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application.
"""
config = Configurator(settings=settings)
config.add_renderer('jsonp', JSONP(param_name='callback'))
config. | include('pyramid_mako')
config.include('pyramid_redis')
config.add_static_view('static', 'static', cache_max_age=3600)
config.add_route('home', '/')
config.add_route('api', '/api')
config.add_route('redirect', '/{shortened | }')
config.scan()
return config.make_wsgi_app()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.