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 |
|---|---|---|---|---|---|---|---|---|
prasanna08/oppia | core/domain/action_registry_test.py | Python | apache-2.0 | 1,192 | 0 | # coding: utf-8
#
# Copyright 2018 The Oppia 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 requi... | "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either expr | ess or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for methods in the action registry."""
from __future__ import absolute_import # pylint: disable=import-only-modules
from __future__ import unicode_literals # pylint: disable=import-only-mo... |
fabricematrat/py-macaroon-bakery | macaroonbakery/tests/test_time.py | Python | lgpl-3.0 | 4,747 | 0 | # Copyright 2017 Canonical Ltd.
# Licensed under the LGPLv3, see LICENCE file for details.
from datetime import timedelta
from unittest import TestCase
from collections import namedtuple
import pyrfc3339
import pymacaroons
from pymacaroons import Macaroon
import macaroonbakery.checkers as checkers
t1 = pyrfc3339.par... | t(t3).condition,
checkers.time_before_caveat(t1).condition,
]),
newMacaroon([
checkers.time_before_caveat(t3).condition,
| checkers.time_before_caveat(t1).condition,
]),
],
expectTime=t1,
),
]
for test in tests:
print('test ', test.about)
t = checkers.macaroons_expiry_time(checkers.Namespace(),
... |
umitproject/site-status | status_cron/urls.py | Python | agpl-3.0 | 1,731 | 0.016176 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
##
## Author: Adriano Monteiro Marques <[email protected]>
##
## Copyright (C) 2011 S2S Network Consultoria e Tecnologia da Informacao LTDA
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU Affero General Publi... | of the
## License, | or (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU Affero General Public License for more details.
##
## You should have re... |
jjangsangy/python-matlab-bridge | pymatbridge/pymatbridge.py | Python | bsd-3-clause | 19,627 | 0.000713 | """
pymatbridge
===========
This is a module for communicating and running Matlab from within python
Example
-------
>>> import pymatbridge
>>> m = pymatbridge.Matlab()
>>> m.start()
Starting MATLAB on ZMQ socket ipc:///tmp/pymatbridge
Send 'exit' command to kill the server
.MATLAB started and connected!
True
>>> m.... | ion (optional,
Default is 10 sec)
platform : string
The OS of the machine on which this is running. Per default this
will be taken from sys.platform.
startup_options : string
Command line options | to include in the executable's invocation.
Optional; sensible defaults are used if this is not provided.
"""
self.started = False
self.executable = executable
self.socket_addr = socket_addr
self.id = id
self.log = log
self.maxtime = maxtime
sel... |
googleapis/python-dialogflow-cx | google/cloud/dialogflowcx_v3beta1/types/fulfillment.py | Python | apache-2.0 | 7,518 | 0.001995 | # -*- coding: utf-8 -*-
# Copyright 2022 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... | om google.protobuf import struct_pb2 # type: ignore
__protobuf__ = proto.module(
package="google.cloud.dialogflow.cx.v3beta1", manifest={"Fulfillment",},
)
class Fulfillment(proto.Message):
r"""A fulfillment can do one or more of the following actions at the
same time:
- Generate rich message res... | e
[Page][google.cloud.dialogflow.cx.v3beta1.Page] or
[Form][google.cloud.dialogflow.cx.v3beta1.Form] lifecycle. For
example, when a
[DetectIntentRequest][google.cloud.dialogflow.cx.v3beta1.DetectIntentRequest]
drives a session to enter a new page, the page's entry fulfillment
can add a static re... |
michaelBenin/django-oscar | oscar/apps/order/utils.py | Python | bsd-3-clause | 10,663 | 0.001501 | from django.contrib.sites.models import Site
from django.conf import settings
from django.db.models import get_model
from django.utils.translation import ugettext_lazy as _
from oscar.apps.shipping.methods import Free
from oscar.apps.order.exceptions import UnableToPlaceOrder
from oscar.core.loading import get_class
... | = Free()
if total_incl_tax is None or total_excl_tax is None:
total_incl_tax = basket.total_incl_tax + shipping_method.basket_charge_incl_tax()
total_excl_tax = basket.total_excl_tax + shipping_method.basket_charge_excl_tax()
if not order_number:
generator = OrderNumb... | generator.order_number(basket)
if not status and hasattr(settings, 'OSCAR_INITIAL_ORDER_STATUS'):
status = getattr(settings, 'OSCAR_INITIAL_ORDER_STATUS')
try:
Order._default_manager.get(number=order_number)
except Order.DoesNotExist:
pass
else:
... |
OCA/l10n-italy | l10n_it_vat_statement_split_payment/models/account.py | Python | agpl-3.0 | 670 | 0 | # Copyright 2018 Silvio Gregorini ([email protected])
# Copyright (c) 2018 Openforce Srls Unipersonale (www.openforce.it)
# Copyright (c) 2019 Matteo Bilotta
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl | ).
from odoo import models
class AccountMoveLi | ne(models.Model):
_inherit = "account.move.line"
def group_by_account_and_tax(self):
grouped_lines = {}
for line in self:
group_key = (line.account_id, line.tax_line_id)
if group_key not in grouped_lines:
grouped_lines.update({group_key: []})
... |
ComputationalPsychiatry/fitr | tests/test_gradients.py | Python | gpl-3.0 | 21,659 | 0.008264 | import autograd.numpy as np
from autograd import grad as gradient
from autograd import elementwise_grad, jacobian, hessian
from fitr import utils
from fitr import gradients as grad
from fitr import hessians as hess
from fitr.environments import TwoArmedBandit
from fitr.environments import DawTwoStep
from fitr.agents im... | = R@x_
q._update_noderivatives(x, u, r, x_, None)
u_ = U2[i]; x = x_; u = u_; x_ = X3[i]; r = R@x_
q._update_noderivatives(x, u, r, x_, None)
return q.Q
def agf_dc(dc):
X1, X2, U1, U2, X3, R = make_mdp_trials()
q = QLearner(DawTwoStep(), learning_rate=0.1... | cay=0.95)
for i in range(ntrials):
q.etrace = np.zeros((2, 5))
x = X1[i]; u = U1[i]; x_= X2[i]; r = R@x_
q._update_noderivatives(x, u, r, x_, None)
u_ = U2[i]; x = x_; u = u_; x_ = X3[i]; r = R@x_
q._update_noderivatives(x, u, r, x_, None)
retu... |
yuriyminin/leap-gesture | machineLearning.py | Python | mit | 3,079 | 0.034102 | #!/usr/bin/env python
import sys
import tensorflow as tf
import numpy as np
from numpy import genfromtxt
import requests
import csv
from sklearn import datasets
from sklearn.cross_validation import train_test_split
import sklearn
from scipy import stats
import getopt
from StringIO import StringIO
import requests
# C... |
prediction=tf.argmax(tf_softmax,1)
guess = prediction.eval(feed_dict={tf_in: x_test}, session=sess)
# calculate most common gesture ID
print int(stats.mode(guess)[0][0])
#r = requests.post("http://localhost:3000/api/receiveAnswer", data = {"prediction": | int(stats.mode(guess)[0][0])})
return 0
if __name__ == "__main__":
main()
|
tinkerinestudio/Tinkerine-Suite | TinkerineSuite/Cura/cura_sf/skeinforge_application/skeinforge_plugins/profile_plugins/cutting.py | Python | agpl-3.0 | 2,099 | 0.011434 | """
This page is in the table of contents.
Cutting is a script to set the cutting profile for the skeinforge chain.
The displayed craft sequence is the sequence in which the tools craft the model and export the output.
On the cutting dialog, clicking the 'Add Profile' button will duplicate the selected profile and gi... | e the cutting profile, in a shell in the profile_plugins folder type:
> python cutting.py
"""
from __future__ import absolute_import
from fabmetheus_utilities import settings
from skeinforge_application.skeinforge_utilities import skeinforge_profile
import sys
__author__ = 'Enrique Perez ([email protected] | om)'
__date__ = '$Date: 2008/21/04 $'
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
def getCraftSequence():
"Get the cutting craft sequence."
return 'chop preface outset multiply whittle drill lift flow feed home lash fillet limit unpause alteration export'.split()
def get... |
ARMmbed/yotta_osx_installer | workspace/lib/python2.7/site-packages/cryptography/hazmat/backends/commoncrypto/backend.py | Python | apache-2.0 | 8,577 | 0 | # This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from __future__ import absolute_import, division, print_function
from collections import namedtuple
from cryptography import utils
from c... | self._lib.kCCAlgorithmR | C4,
type(None),
self._lib.kCCModeRC4
)
def _check_cipher_response(self, response):
if response == self._lib.kCCSuccess:
return
elif response == self._lib.kCCAlignmentError:
# This error is not currently triggered due to a bug filed as
... |
DantestyleXD/MVM5B_BOT | plugins/log.py | Python | gpl-2.0 | 763 | 0.001311 | # -*- co | ding: utf-8 -*-
from config import *
print(Color(
'{autored}[{/red}{autoyellow}+{/yellow}{autored}]{/red} {autocyan} log.py importado.{/cyan}'))
@bot.message_handler(commands=['log'])
def command_log(m):
cid = m.chat.id
uid = m.from_user.id
try:
send_udp('log')
except Exception as e:
... | extra["log"] = False
bot.send_message(cid, "Log desactivado")
else:
extra["log"] = True
bot.send_message(cid, "Log activado")
with open("extra_data/extra.json", "w") as f:
json.dump(extra, f)
|
juhgiyo/pyserver3 | pyserver/network/async_multicast.py | Python | mit | 8,329 | 0.001921 | #!/usr/bin/python
"""
@file async_multicast.py
@author Woong Gyu La a.k.a Chris. <[email protected]>
<http://github.com/juhgiyo/pyserver>
@date March 10, 2016
@brief AsyncMulticast Interface
@version 0.1
@section LICENSE
The MIT License (MIT)
Copyright (c) 2016 Woong Gyu La <[email protected]>
Permission is... | ulticast(asyncio.Protocol):
# enable_loopback : 1 enable loopback / 0 disable loopback
# ttl: 0 - restricted to the same host
# 1 - restricted to the same subnet
# 32 - restricted to the same site
# 64 - restricted to the same region
# 128 - restricted to the same continent
#... | Lock()
self.MAX_MTU = 1500
self.callback_obj = None
self.port = port
self.multicastSet = set([])
self.lock = threading.RLock()
self.ttl = ttl
self.enable_loopback = enable_loopback
if callback_obj is not None and isinstance(callback_obj, IUdpCallback):
... |
BitcoinUnlimited/BitcoinUnlimited | qa/rpc-tests/electrum_subscriptions.py | Python | mit | 7,420 | 0.007951 | #!/usr/bin/env python3
# Copyright (c) 2019-2020 The Bitcoin Unlimited developers
import asyncio
import time
from test_framework.util import assert_equal, assert_raises
from test_framework.test_framework import BitcoinTestFramework
from test_framework.loginit import logging
from test_framework.electrumutil import (Ele... | t a notification
[ n.se | ndtoaddress(addresses[i], 1) for i in range(0, num_clients) ]
for i in range(0, num_clients):
q = queues[i]
old_statushash = statushashes[i]
scripthash, new_statushash = await asyncio.wait_for(q.get(), timeout = 10)
assert_equal(scripthash, address_to_scripthash... |
wolverineav/neutron | neutron/db/migration/alembic_migrations/dvr_init_opts.py | Python | apache-2.0 | 2,619 | 0 | # Copyright 2015 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... | =False),
sa.Column('mac_address', sa.String(length=32),
nullable=False, unique=True),
sa.PrimaryKeyConstraint('host')
)
op.create_table(
'ml2_dvr_port_bindings',
sa.Column('port_id', sa.String(length=36), nullable=False),
sa.Column('host', | sa.String(length=255), nullable=False),
sa.Column('router_id', sa.String(length=36), nullable=True),
sa.Column('vif_type', sa.String(length=64), nullable=False),
sa.Column('vif_details', sa.String(length=4095),
nullable=False, server_default=''),
sa.Column('vnic_type', ... |
rodrigolucianocosta/ControleEstoque | rOne/Storage101/django-localflavor/django-localflavor-1.3/docs/conf.py | Python | gpl-3.0 | 10,708 | 0.007097 | # -*- coding: utf-8 -*-
#
# django-localflavor documentation build configuration file, created by
# sphinx-quickstart on Sun Jun 2 17:56:28 2013.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated fi... | ames.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# | If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..... |
lmazuel/azure-sdk-for-python | azure-mgmt-compute/azure/mgmt/compute/v2016_04_30_preview/models/upgrade_policy_py3.py | Python | mit | 1,372 | 0 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microso | ft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# -------------------------------------... | automatic or manual.
:param mode: Specifies the mode of an upgrade to virtual machines in the
scale set.<br /><br /> Possible values are:<br /><br /> **Manual** - You
control the application of updates to virtual machines in the scale set.
You do this by using the manualUpgrade action.<br /><br /> ... |
zentralopensource/zentral | zentral/contrib/simplemdm/views.py | Python | apache-2.0 | 8,061 | 0.002233 | import logging
from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import Http404, HttpResponseRedirect
from django.shortcuts import get_object_or_404
from django.urls import reverse, reverse_lazy
from django.views.generic import CreateView, DeleteView, DetailV... | ctx = super().get_context_data(**kwargs)
ctx["setup"] = True
simplemdm_instances_count = len(ctx["object_list"])
if simplemdm_instances_count == 0 or simplemdm_instances_count > 1:
suffix = "s"
else:
suffix = ""
ctx["title"] = "{} SimpleMDM instance{}".... | MInstanceView(LoginRequiredMixin, CreateView):
model = SimpleMDMInstance
form_class = SimpleMDMInstanceForm
success_url = reverse_lazy("simplemdm:simplemdm_instances")
def get_context_data(self, **kwargs):
ctx = super().get_context_data(**kwargs)
ctx["setup"] = True
ctx["title"]... |
hsarmiento/people_finder_chile | tools/validate_merge.py | Python | apache-2.0 | 2,793 | 0.006803 | #!/usr/bin/python2.7
# Copyright 2010 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 agree... | e .po file:
find_missing_translations --format=po
This will generate a .po | file with just the translated messages in order.
2. Use the english person_finder.xml file and the template from step 1 to
'merge' the english translations into the english .po file. This should
generate a .po file with the msg string set to the msg id value for each
newly tran... |
CodeMill/cmsplugin-hoverimage | cmsplugin_hoverimage/migrations/0001_initial.py | Python | mit | 7,784 | 0.008222 | # -*- 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 model 'HoverImagePlugin'
db.create_table('cmsplugin_hoverimageplugin', (
('cmsplugin_pt... | arField', [], {'db_index': 'True', 'max_length': '80', 'null': 'True', 'blank': 'True'}),
'parent': ('django.db.models.fields.related.ForeignKey', [ | ], {'blank': 'True', 'related_name': "'children'", 'null': 'True', 'to': "orm['cms.Page']"}),
'placeholders': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['cms.Placeholder']", 'symmetrical': 'False'}),
'publication_date': ('django.db.models.fields.DateTimeField', [], {'db_... |
kdudkov/tiny-home-automation | core/context.py | Python | gpl-3.0 | 2,873 | 0.000348 | import asyncio
import collections
import functools
import logging
from .items import Items
from .rules import AbstractRule
CB_ONCHANGE = 'onchange'
CB_ONCHECK = 'oncheck'
LOG = logging.getLogger('mahno.' + __name__)
class Context(object):
def __init__(self):
self.config = {}
self.items = Items(... | cb):
self.callbacks.setdefault(name, []).append(cb)
def command(self, name, cmd):
LOG.info('external command %s', name)
self.commands.append((name, cmd))
def item_comma | nd(self, name, cmd):
item = self.items.get_item(name)
if not item:
LOG.error('no item %s', name)
return
if item.config.get('output'):
for actor in self.actors.values():
if actor.name == item.config['output'].get('channel'):
... |
sumihai-tekindo/account_sicepat | asset_tetap/models/asset_tetap.py | Python | gpl-3.0 | 1,140 | 0.023684 | from openerp import models, fields, api, _
class asset_tetap(models.TransientModel):
_name="asset.tetap"
start_date = fields.Date(string="Start Date", required=True)
end_date = fields.Date(string="End Date", required=True)
state = fields.Selection(string="State", selection=[("draft","Draft"... | if state=="all":
state=["draft","open"]
else:
state=[self.state]
ass_ids = self.env['account.asset.asset'].search([("state","in",state)])
# ass_ids = self.env['account.asset.asset'].search([])
list_ass = [ass.id for ass in ass_ids]
| datas={
'model' : 'account.asset.asset',
"ids" : list_ass,
'start_date':self.start_date,
'end_date':self.end_date,
}
return{
'type': 'ir.actions.report.xml',
'report_name': 'report.asset.tetap.xls',
'd... |
j0lly/Odin | odin/utils.py | Python | mit | 3,748 | 0 | # -*- coding: utf-8 -*-
"""collection of helpers for Miner module."""
import ipaddress
import json
import odin
from odin.store import ThreadedModel
# Default logging capabilities (logging nowhere)
log = odin.get_logger()
def findip(string):
"""calculate hosts to be scanned; it's just an helper.
:param str... | ry: a pynamo query that returned a generator
:type query: generator
:param output: format of the utput, for now just json or byte format
:type output: str
:returns: a dictionary generator of serialized pynamodb objects
:rtype: generator
"""
for result in query:
obj = result.serialize... | put == 'json':
yield '{}\n'.format(json.dumps(obj, indent=4))
elif output == 'bytes':
yield '{}\n'.format(json.dumps(obj, indent=4)).encode('utf-8')
elif output is None:
yield obj
def assembler(string):
"""get a str with class a, b or c range in the form:
... |
ebu/PlugIt | examples/standalone_proxy/plugIt/management/commands/check_mail.py | Python | bsd-3-clause | 58 | 0 | from plugit_proxy.management.comm | ands.check_mail impor | t *
|
nimadini/Teammate | handlers/stat.py | Python | apache-2.0 | 1,093 | 0.002745 | __author__ = 'stanley'
import webapp2
from domain.statistics.statistics import *
from domain.statistics.entity import Entity
import json
from domain.doc_ | index import *
class StatHandler(webapp2.RequestHandler):
def get(self):
qry = Statistics.query(Statistics.id == 'Teammate_Statistics')
#delete()
if qry.get() is not None:
self.response.headers['Content-Type'] = 'application/json'
result = json.dumps({'First Access':... | self.response.write(result)
return
statistics = Statistics(key=statistics_key('my_stat'))
statistics.id = 'Teammate_Statistics'
statistics.BS = Entity(price=0.0, number=0)
statistics.BA = Entity(price=0.0, number=0)
statistics.MS = Entity(price=0.0, number=0)
... |
clever-crow-consulting/otm-core | opentreemap/treemap/search.py | Python | agpl-3.0 | 15,113 | 0.000066 | # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from json import loads
from datetime import datetime
from functools import partial
from django.db.models import Q
from django.contrib.gis.measure import Distance
from django.contrib.g... | init__(self, message):
super(Exception, self).__init__(message)
self.message = message
class ModelParseException(ParseException):
pass
DEFAULT_MAPPING = {'plot': '',
'bioswale': '',
'rainGarden': '',
'rainBarrel': '',
't... | tree__treephoto__',
'mapFeaturePhoto': 'mapfeaturephoto__',
'mapFeature': ''}
TREE_MAPPING = {'plot': 'plot__',
'tree': '',
'species': 'species__',
'treePhoto': 'treephoto__',
'mapFeaturePhoto': 'treephoto__',
... |
tethysplatform/TethysCluster | tethyscluster/azureutils.py | Python | lgpl-3.0 | 56,078 | 0.002782 | # Copyright 2009-2014 Justin Riley
#
# This file is part of TethysCluster.
#
# TethysCluster 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 License, or (at your option) any
# la... | e, location='West US', **kwargs):
kwds = dict(request_session=request_sessi | on)
super(EasySMS, self).__init__(subscription_id, certificate_path,
azure.servicemanagement.ServiceManagementService, **kwds)
self._conn = kwargs.get('connection')
# kwds = dict(aws_s3_host=aws_s3_host, aws_s3_path=aws_s3_path,
# aws_por... |
jhseu/tensorflow | tensorflow/python/kernel_tests/lookup_ops_test.py | Python | apache-2.0 | 133,760 | 0.010167 | # 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... | size()))
input_string = constant_op.constant(["brain", "salad", "tank"])
output = table.lookup(input_string)
self.assertAllEqual([3], output.get_shape())
result = self.evaluate(output)
self.assertAllEqual([0, 1, -1], result)
exported_keys_tensor, exported_values_tensor = table.export()
s... | es_tensor))
def testStaticHashTableFindHighRank(self):
default_val = -1
keys = constant_op.constant(["brain", "salad", "surgery"])
values = constant_op.constant([0, 1, 2], dtypes.int64)
table = self.getHashTable()(
lookup_ops.KeyValueTensorInitializer(keys, values), default_val)
self.init... |
makinacorpus/Geotrek | geotrek/trekking/tests/test_filters.py | Python | bsd-2-clause | 618 | 0.001618 | from geotrek.land.tests.test_filters import LandFiltersTest
from geotrek.trekking.filters import TrekFilterSet
from geotrek.trekking.factories import TrekFactory
class TrekFilterLandTest(LandFiltersTest):
filterclass = TrekFilterSet
def test_land_filters_are_well_setup(self):
filterset = TrekFilter... | ertIn('work', filterset.filters)
def create_pair_of_distinct_path(self):
useless_path, seek_path = super().create_pair_of_distinct_path()
self.create_pair_of_distinct_topologies(TrekFactory, | useless_path, seek_path)
return useless_path, seek_path
|
plotly/python-api | packages/python/plotly/plotly/graph_objs/bar/marker/_colorbar.py | Python | mit | 69,490 | 0.000964 | from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType
import copy as _copy
class ColorBar(_BaseTraceHierarchyType):
# class properties
# --------------------
_parent_path_str = "bar.marker"
_path_str = "bar.marker.colorbar"
_valid_props = {
"bgcolor",
... | darkslateblue, d | arkslategray, darkslategrey,
darkturquoise, darkviolet, deeppink, deepskyblue,
dimgray, dimgrey, dodgerblue, firebrick,
floralwhite, forestgreen, fuchsia, gainsboro,
ghostwhite, gold, goldenrod, gray, grey, green,
greenyellow, honeydew, hot... |
deepmind/open_spiel | open_spiel/python/environments/cliff_walking.py | Python | apache-2.0 | 6,127 | 0.004244 | # Copyright 2019 DeepMind Technologies Limited
#
# 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 agr... | timestep, or None
if step_type is `rl_environment.StepType.FIRST`.
discount: singleton list containing the discount in the range [0, 1], or
None if step_type is `rl_environment.StepType.FIRST`.
step_type: A `rl_environment.StepType` value.
"""
if self._should_reset:
... | lse:
raise ValueError("Action not supported.", actions)
dx = 0
dy = 0
if action == LEFT:
dx -= 1
elif action == RIGHT:
dx += 1
if action == UP:
dy -= 1
elif action == DOWN:
dy += 1
self._state += np.array([dy, dx])
self._state = self._state.clip(0, [self.... |
ojengwa/migrate | ibu/schema.py | Python | mit | 12,646 | 0.001502 | from __future__ import unicode_literals
import keyword
import re
from collections import OrderedDict
from click import BaseCommand, B | aseException
from config import DEFAULT_DB_ALIAS
from ibu import connection as connections
class Command(BaseCommand):
help = "Introspects the database tables in the given database and outputs a Django model module."
requires_system_checks = False
db_module = 'ibu.backends'
def add_argumen | ts(self, parser):
parser.add_argument('--database', action='store', dest='database',
default=DEFAULT_DB_ALIAS, help='Nominates a database to '
'introspect. Defaults to using the "default" database.')
def handle(self, **options):
try:
... |
ajaniv/django-core-models | django_core_models/social_media/views.py | Python | mit | 7,262 | 0 | """
.. module:: django_core_models.social_media.views
:synopsis: django_core_models social_media application views module.
*django_core | _models* social_media application views module.
"""
from __future__ import absolute_import
from django_core_utils.views import ObjectListView, ObjectDetailView
from . import models
from . import serializers
class EmailMixin(object):
"""Email mixin class."""
queryset = | models.Email.objects.all()
serializer_class = serializers.EmailSerializer
class EmailList(EmailMixin, ObjectListView):
"""Class to list all Email instances,
or create new Email instance."""
pass
class EmailDetail(EmailMixin, ObjectDetailView):
"""
Class to retrieve, update or delete Email ... |
amondot/RasterDisplayComposer | RasterDisplayComposer.py | Python | gpl-3.0 | 19,263 | 0.00135 | # -*- coding: utf-8 -*-
"""
/***************************************************************************
RasterDisplayComposer
A QGIS plugin
Compose RGB image display from different bands
-------------------
begin : 2016-02-13
... | his is not None:
action.setWhatsThis(whats_this)
if add_to_toolbar:
| self.toolbar.addAction(action)
if add_to_menu:
self.iface.addPlug |
Moonshile/goondream | src/desserts/models.py | Python | apache-2.0 | 376 | 0.007979 | #coding=utf-8
from django.db import mod | els
from django.contrib.auth.models import User
class Activity(models.Model):
owner = models.ForeignKey(User, null=False)
text = models.CharField(max_length=20, unique=True)
class Dessert | (models.Model):
activity = models.ForeignKey(Activity, null=False)
description = models.TextField()
photo = models.ImageField()
|
npuichigo/ttsflow | third_party/tensorflow/tensorflow/contrib/tensor_forest/hybrid/python/layers/decisions_to_data_test.py | Python | apache-2.0 | 2,506 | 0.002793 | # Copyright 2016 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... | m_leaves = 2**(self.params.hybrid_tree_depth - 1)
# pylint: disable=W0612
self.input_data = constant_op.constant(
[[random.uniform(-1, 1) for i in range(self.params.num_features)]
for _ in range(100)])
def testInferenceConstruction(self):
with variable_scope.variable_scope(
"Dec... | None)
unused_graph = graph_builder.inference_graph(self.input_data)
if __name__ == "__main__":
googletest.main()
|
vhf/kwak_cli | commands.py | Python | mit | 1,182 | 0.00846 | def dbg(ui, client, rest):
ui.redraw_userlist()
client.client.call('setOnline', [])
def hot(ui, client, rest):
ui.chatbuffer_add(', '.join(client.hot_channels_name))
client.client.call('getHotChannels', [], client.set_hot_channels_name)
def invt(ui, client, rest):
if (rest == None):
return... | '.join(client.all_channels_name))
client.client.call('channelList', [], client.set_all_channels_name)
ui.redraw_ui()
def quit(ui, client, rest):
exit(0)
commands = {
'dbg': [dbg, 'SYNOPSYS: lala', 'USAGE: lala'],
'hot': [hot, 'SYNOPSYS: lala', 'USAGE: lala'],
'invite': [invt, 'SYN... | : lala'],
'j': [join, 'SYNOPSYS: lala', 'USAGE: lala'],
'join': [join, 'SYNOPSYS: lala', 'USAGE: lala'],
'list': [lst, 'SYNOPSYS: lala', 'USAGE: lala'],
'quit': [quit, 'SYNOPSYS: lala', 'USAGE: lala'],
}
|
phrocker/sharkbite | examples/jsoncombiner.py | Python | apache-2.0 | 850 | 0.021176 | class ExampleCombiner:
## This example iterator assumes the CQ contains a field name
## and value pair separated by a null delimiter
def onNext(iterator):
if (iterator.hasTop()):
mapping = {}
| key = iterator.getTopKey()
cf = key.getColumnFamily()
while (iterator.hasTop() and cf == key.getColumnFamily()):
## FN and FV in cq
fieldn | ame = key.getColumnQualifier().split('\x00')[0];
fieldvalue = key.getColumnQualifier().split('\x00')[1];
mapping[fieldname]=fieldvalue
iterator.next();
if (iterator.hasTop()):
key = iterator.getTopKey()
json_data = json.dumps(mapping,indent=4, sort... |
dwhswenson/contact_map | contact_map/__init__.py | Python | lgpl-2.1 | 746 | 0 | try:
from . import version
except ImportError: # pragma: no cover
from . import _version as version
__version__ = version.version
from .contact_map import (
ContactMap, ContactFrequency, ContactDifferen | ce,
AtomMismatchedContactDifference, ResidueMismatchedContactDifference,
OverrideTopologyContactDifference
)
from .contact_count import ContactCount
from .contact_trajectory import ContactTrajectory, RollingContactFrequency
from .min_dist import NearestAtoms, MinimumDistanceCounter
from .concurrence import ... | cy, DaskContactTrajectory
from . import plot_utils
|
ardinusawan/Sistem_Terdistribusi | Web-Service/RESTful/referensi/restful-hudan/tasks-2.py | Python | gpl-3.0 | 881 | 0.00681 | # Source: http://blog.miguelgrinberg.com/post/designing-a-restful-api-with-python-and-flask
from flask import Flask, jsonify, abort, make_response
app = Flask(__name__)
tasks = [
{
'id': 1,
'title': u'Buy groceries',
'description': u'Milk, Cheese, Pizza, Fruit, Tylenol',
'done': ... | 'title': u'Learn Python',
'description': u'Need to find a good Python tutorial on the web',
'done': False
}
]
@app.route('/todo/api/v1.0/tasks/<int:task_id>', methods=['GET'])
def get_task(task_id):
task = filter(lambda t: t['id'] == task_id, tasks)
if len(task) == 0:
abort(404)
... | error': 'Not found'}), 404)
if __name__ == '__main__':
app.run(debug=True)
|
cmorgan/zipline | tests/test_sources.py | Python | apache-2.0 | 7,041 | 0 | #
# Copyright 2013 Quantopian, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... | ace(minute=0, hour=0),
calendar_nyse.trading_days)
self.assertGreater(event.dt, start)
self.assertLess(event.dt, end)
self.assertGreater(event.price, 0,
"price should never go negative.")
self.assertTrue(13 <= event... | s." % event.dt.hour)
def test_day(self):
np.random.seed(123)
start_prices = {0: 100,
1: 500}
start = pd.Timestamp('1990-01-01', tz='UTC')
end = pd.Timestamp('1992-01-01', tz='UTC')
source = RandomWalkSource(start_prices=start_prices,
... |
Tsumiki-Chan/Neko-Chan | commands/userinfo.py | Python | gpl-3.0 | 3,277 | 0.007019 | from functions import logger,search, messagestorage, search
import pprint
import datetime
DESC="Tells you something about yourself or a user"
USAGE="userinfo"
async def init(bot):
chat=bot.message.channel
try:
user = bot.message.author
| if len(bot.args) > 0:
if len(bot.message.raw_mentions)>0:
user = await search.user(chat, bot.message.raw_mentions[0])
else:
user = await search.user(chat, " ".join(bot.args))
data = "Could not find any user matching {}".format(" ".join(bot.args))
... | append(["<!-- User information -->"])
data.append(["ID", user.id])
data.append(["Nickname", user.display_name])
data.append(["Name", user.name])
data.append(["Discriminator", user.discriminator])
data.append(["Created on", user.created_at])
if user... |
jakbob/guitarlegend | slask/readwav.py | Python | gpl-3.0 | 1,131 | 0.01061 | #!/usr/bin/env python
# Disect the wav data and plot it using pylab.
import pylab
import wave # Contains reference to struct. No point in importing it twice
FORMAT = { "11" : "1b", # Mono, 8-bit sound
"12" : "1h", # Mono, 16-bit sound
"21" : "2b", # Stereo, 8-bit sound
"22" : "2h",... | )
# Ti | me to unpack
python_data = []
for i in range(0, params[3]):
size = wave.struct.calcsize(fmt)
data = wave.struct.unpack(fmt, wavdata[i:i+size]) # Little endian
python_data.append(data[0]) # The above function returns 1-tuples
assert(len(wavdata) == params[0]*params[1]*len(python_data))
x = pylab.arange(0... |
jorgealmerio/QEsg | core/ezdxf/pp/__init__.py | Python | gpl-3.0 | 150 | 0 | # Purpose: DXF Pretty Printer
# Created: 1 | 6.07.2015
# Copyright (C) 2015, Manfred Moitzi
# License: MIT License
_ | _author__ = "mozman <[email protected]>"
|
ptosco/rdkit | rdkit/Chem/Pharm2D/UnitTestLazyGenerator.py | Python | bsd-3-clause | 2,437 | 0.009027 | #
# Copyright (C) 2003-2006 greg Landrum and Rational Discovery LLC
#
# @@ All Rights Reserved @@
# This file is part of the RDKit.
# The contents are covered by the terms of the BSD license
# which is included in the file license.txt, found at the root
# of the RDKit source tree.
#
"""unit testing code for the... | ()}'
tgt = (1, 5, 48)
for bit in tgt:
assert gen[bit], f'bit {bit} not properly set' |
assert gen.GetBit(bit), f'bit {bit} not properly set'
assert not gen[bit + 50], f'bit {bit + 100} improperly set'
sig = factory.GetSignature()
assert sig.GetSize() == 105, f'bad signature size: {sig.GetSize()}'
sig.SetIncludeBondOrder(1)
gen = LazyGenerator.Generator(sig, mol)
assert l... |
redanexis/keysmash | main.py | Python | apache-2.0 | 632 | 0.001582 | #!/usr/bin/env python
# wipflag{todo}
from threading import Thread
from game import Ga | me
from bytekeeper import ByteKeeper
from broker import Broker # todo
class Main:
def __init__(self):
print('starting main...\n')
self.running = True
self.bytekeeper = ByteKeeper()
self.game = Game(self, self.bytekeeper)
# self.broker = Broker(self, self.bytekeeper)
... | hread = Thread(target=self.broker.run)
self.gamethread.start()
# self.brokerthread.start()
if __name__ == "__main__":
main = Main()
|
figlief/ctx | setup.py | Python | mit | 1,330 | 0 | from __future__ import unicode_literals
import os
import codecs
from setuptools import setup
import ctx
def read(*paths):
"""Build a file path from *paths* and return the contents."""
path = os.path.join(*paths)
with codecs.open(path, mode='rb', encoding='utf-8') as f:
return f.read()
long_de... | ],
install_requires=[],
license="MIT",
zip_safe=False,
keywords='ctx',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Programming Language :: Pyt... | .7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
anythingrandom/eclcli | eclcli/dh/v2/license.py | Python | apache-2.0 | 3,173 | 0.011346 | import copy
import six
from eclcli.common import command
from eclcli.common import utils
class ListLicense(command.Lister):
def get_parser(self, prog_name):
parser = super(ListLicense, self).get_parser(prog_name)
parser.add_argument(
"--license-type",
help="License ty... | (utils.get_item_properties(
s, columns
) for s in data))
class ListLicenseType(command.Lister):
def get_parser(self, prog_name):
parser = super(ListLicenseType, self).get_parser(prog_name)
return parser
def take_action(self, parsed_args):
... | 'Has License Key', 'Unit', 'Description'
]
column_headers = columns
data = dh_client.licenses.list_license_types()
return (column_headers,
(utils.get_item_properties(
s, columns
) for s in data))
class CreateLic... |
LukasBoersma/pyowm | pyowm/webapi25/weather.py | Python | mit | 18,912 | 0.000529 | """
Module containing weather data classes and data structures.
"""
import json
import xml.etree.ElementTree as ET
from pyowm.webapi25.xsd.xmlnsconfig import (
WEATHER_XMLNS_PREFIX, WEATHER_XMLNS_URL)
from pyowm.utils import timeformatutils, temputils, xmlutils
class Weather(object):
"""
A class encapsul... | nd humidex < 0:
raise ValueError("'humidex' must be greater than 0")
self._humidex = humidex
if heat_index is not None and heat_index < 0:
raise ValueError("'heat index' must be grater than 0")
self._heat_index = heat_index
def get_reference_time(self, timeformat='un... |
'*unix*' (default) for UNIX time or '*iso*' for ISO8601-formatted
string in the format ``YYYY-MM-DD HH:MM:SS+00``
:type timeformat: str
:returns: an int or a str
:raises: ValueError when negative values are provided
"""
return timeformatutils.timeformat(... |
beni55/jieba | test/extract_topic.py | Python | mit | 1,456 | 0.010989 | import sys
sys.path.append("../")
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn import decomposition
import jieba
import time
import glob
import sys
import os
import random
if len(sys.argv)<2:
print "usage: extract_topic.py di... | ormer().fit_transform(counts)
print tfidf.shape
t0 = time.time()
print "training..."
nmf = decomposition.NMF(n_components=n_topic).fit(tfidf)
print("done in %0.3fs." % (time.time() - t0))
# Inverse the vectorizer vocabulary to be able
feature_names = count_vect.get_feature_names()
f | or topic_idx, topic in enumerate(nmf.components_):
print("Topic #%d:" % topic_idx)
print(" ".join([feature_names[i]
for i in topic.argsort()[:-n_top_words - 1:-1]]))
print("")
|
kisel/trex-core | scripts/automation/regression/hltapi_playground.py | Python | apache-2.0 | 10,579 | 0.032328 | #!/router/bin/python
import outer_packages
#from trex_stl_lib.trex_stl_hltapi import CTRexHltApi, CStreamsPerPort
from trex_stl_lib.trex_stl_hltapi import *
import traceback
import sys, time
from pprint import pprint
import argparse
def error(err = None):
if not err:
raise Exception('Unknown exception, lo... | hlt_client.traffic | _control(action = 'stop')
print hlt_client.traffic_control(action = 'poll')
print hlt_client.traffic_stats(mode = 'aggregate')
print hlt_client.traffic_control(action = 'clear_stats')
wait_with_progress(1)
print hlt_client.traffic_stats(mode = 'aggregate')
wait_w... |
litobro/fbbot | fbchat/stickers.py | Python | mit | 177 | 0.011299 | L | IKES={
'l': '369239383222810',
'm': '369239343222814',
's': '369239263222822'
}
LIKES['large'] = LIKES['l']
LIKES['medium'] =LIKES['m']
LIKES['small'] = LIKES['s' | ]
|
stephane-martin/salt-debian-packaging | salt-2016.3.3/tests/unit/modules/moosefs_test.py | Python | apache-2.0 | 2,122 | 0.001414 | # -*- coding: utf-8 -*-
'''
:codeauthor: :email:`Jayesh Kariya <[email protected]>`
'''
# Import Python Libs
from __future__ import absolute_import
# Import Salt Testing Libs
from salttesting import TestCase, skipIf
from salttesting.mock import (
MagicMock,
patch,
NO_MOCK,
NO_MOCK_REASON
)
fro... | ck = MagicMock(return_value={'stdout': 'Salt:salt'})
with patch.dict(moosefs.__salt__, {'cmd.run_all': mock}):
self.assert | DictEqual(moosefs.dirinfo('/tmp/salt'), {'Salt': 'salt'})
# 'fileinfo' function tests: 1
def test_fileinfo(self):
'''
Test if it returns information on a file located on the Moose
'''
mock = MagicMock(return_value={'stdout': ''})
with patch.dict(moosefs.__salt__, {'cmd.... |
arpruss/plucker | parser/python/PyPlucker/ConversionParser.py | Python | gpl-2.0 | 2,897 | 0.007594 | #!/usr/bin/env python
"""
ConversionParser.py $Id: ConversionParser.py,v 1.5 2004/10/20 01:44:53 chrish Exp $
Copyright 2003 Bill Nalen <[email protected]>
Distributable under the GNU General Public License Version 2 or newer.
Provides methods to wrap external convertors to return PluckerTextDocument... | er = config.get_string('worddoc_converter')
if worddoc_converter is None:
message(0, "Could not find Word conversion command")
return None
check = os.path.basename (worddoc_converter)
(check, ext) = os.path.splitext (check)
check = string.lower (check)
if check == 'wvware'... | tempdoc = os.path.join(tempfile.tempdir, tempbase + ".doc")
try:
file = open (tempdoc, "wb")
file.write (data)
file.close ()
except IOError, text:
message(0, "Error saving temporary file %s" % tempdoc)
os.unlink(tempdoc)
re... |
acuriel/Nixtla | nixtla/core/tools/database_parser.py | Python | gpl-2.0 | 9,452 | 0.006771 | # -*- coding: utf-8 -*-
'''
Created on Nov 18, 2014
@author: Arturo Curiel
'''
import ply.yacc as yacc
import ply.lex as lex
import ply.ctokens as ctokens
import ConfigParser
import StringIO
from nixtla.core.tools.pdlsl import Atom, AtomAction
from nixtla.core.tools import pdlsl
class PDLSLLexer(object):
... | omaction(p[3])
p[0] = self.calculate_action(p[2], p[1], p[3])
def p_articulator_uniaction_pi(self, p):
'''action : ARTICULATOR PI_UNIOPERATOR'''
if 'ART' in p[1]:
p[1] = self.get_articulator_atomaction(p[1])
p[0] = self.calculate_action(p[2], p... | '''action : action PI_BINOPERATOR action'''
p[0] = self.calculate_action(p[2], p[1], p[3])
def p_action_group(self, p):
'''action : LPAREN action RPAREN'''
p[0] = p[2]
def calculate_formula(self, operator, *args):
if operator == '||':
return pdls... |
Qwertycal/19520-Eye-Tracker | GUI and Mouse/myVidInGUI.py | Python | gpl-2.0 | 2,428 | 0.053954 | from Tkinter import *
import cv2
from PIL import Image, ImageTk
import pyautogui
width, height = 302, 270
screenwidth, screenheight = pyautogui.size()
cap = cv2.VideoCapture(0)
cap.set(cv2.cv.CV_CAP_PROP_FRAME_WIDTH, width)
cap.set(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT, height)
root = Tk()
root.title("Testing Mode")
root.b... | 0)
userButtonFrame = Frame(userViewFrame, width = 500)
desktopViewFrame = Frame(userViewFrame, bg = "red", width = 500, height = 650)
#Create Buttons
mode = IntVar()
devModeB = Radiobutton(devButtonFrame,text="Developer Mode",variable=mod | e,value=1)
userModeB = Radiobutton(devButtonFrame,text="User Mode",variable=mode,value=2)
recordB = Button(userButtonFrame, text = "Record")
stopB = Button(userButtonFrame, text = "Stop")
#for Text width is mesaured in the number of characters, height is the number of lines displayed
outputCoOrds = Text(coordsFrame, w... |
googleapis/python-resource-manager | samples/generated_samples/cloudresourcemanager_v3_generated_folders_delete_folder_async.py | Python | apache-2.0 | 1,580 | 0.000633 | # -*- coding: utf-8 -*-
# Copyright 2022 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... | generated_Folders_DeleteFolder_async]
from google.cloud import resourcemanager_v3
async def sample_delet | e_folder():
# Create a client
client = resourcemanager_v3.FoldersAsyncClient()
# Initialize request argument(s)
request = resourcemanager_v3.DeleteFolderRequest(
name="name_value",
)
# Make the request
operation = client.delete_folder(request=request)
print("Waiting for operat... |
koehlma/pygrooveshark | examples/django_webapp/django_webapp/wsgi.py | Python | lgpl-3.0 | 401 | 0.002494 | """
WSGI confi | g for django_webapp 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/1.6/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_webapp.settings")
from django.core.wsg... | ication()
|
luisgg/iteexe | exe/export/websiteexport.py | Python | gpl-2.0 | 8,267 | 0.006169 | # ===========================================================================
# eXe
# Copyright 2004-2005, University of Auckland
# Copyright 2004-2008 eXe Project, http://eXeLearning.org/
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as... | tyleFiles = [self.stylesDir/'..'/'base.css']
styleFiles += [self.stylesDir/'..'/'popup_bg.gif']
styleFiles += self.stylesDir.files("*.css")
styleFiles | += self.stylesDir.files("*.jpg")
styleFiles += self.stylesDir.files("*.gif")
styleFiles += self.stylesDir.files("*.png")
styleFiles += self.stylesDir.files("*.js")
styleFiles += self.stylesDir.files("*.html")
styleFiles += self.stylesDir.files("*.ico")
self.stylesDir.c... |
Hawker65/deploycron | deploycron/__init__.py | Python | mit | 5,288 | 0 | # coding: utf-8
import subprocess
import os
def deploycron(filename="", content="", override=False):
"""install crontabs into the system if it's not installed.
This will not remove the other crontabs installed in the system if not
specified as override. It just merge the new one with the existing one.
... | ption as e:
raise ValueError("cannot open the file: % | s" % str(e))
if override:
installed_content = ""
else:
installed_content = _get_installed_content()
installed_content = installed_content.rstrip("\n")
installed_crontabs = installed_content.split("\n")
for crontab in content.split("\n"):
if crontab and crontab not in inst... |
ccbrandenburg/financialanalyticsproject | iembdfa/DataCleaning.py | Python | mit | 1,698 | 0.008245 | # -*- coding: utf-8 -*-
"""
Created on Wed Jun 15 11:39:04 2016
@author: rahulmehra
"""
# Import the modules
import pandas as pd
from sklearn.preprocessing import LabelEncoder
import numpy as np
# Define a function to autoclean the pandas dataframe
def autoclean(x):
for column in x.columns:
# Replace ... | column].values)
x[column] = colum | n_encoder.transform(x[column].values)
return(x)
|
mozilla/addons-server | src/olympia/addons/tests/test_tasks.py | Python | bsd-3-clause | 8,920 | 0.001121 | from unittest import mock
import os
import pytest
from django.conf import settings
from waffle.testutils import override_switch
from olympia import amo
from olympia.addons.tasks import (
recreate_theme_previews,
update_addon_average_daily_users,
update_addon_hotness,
update_addon_weekly_downloads,
)
... | assert gen_preview.call_count == 0 # not called
assert resize.call_count == 2
amo_preview.reload()
assert amo_preview.thumbnail_dimensions == [720, 92]
firefox_preview.reload()
assert firefox_ | preview.get_format('thumbnail') == 'png'
assert VersionPreview.objects.count() == 3
@pytest.mark.django_db
def test_update_addon_average_daily_users():
addon = addon_factory(average_daily_users=0)
count = 123
data = [(addon.guid, count)]
assert addon.average_daily_users == 0
update_addon... |
mrkm4ntr/incubator-airflow | airflow/cli/cli_parser.py | Python | apache-2.0 | 53,687 | 0.003241 | #!/usr/bin/env python
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "... | KFILL = Arg(
("--no-backfill",), help="filter all the backfill dagruns given the dag id", action="store_true"
)
ARG_STATE = Arg(("--state",), help="Only list the dag runs corresponding to the state")
# list_jobs
ARG_LIMIT = Arg(("--limit",), help="Return a limited number of records")
# next_execution
ARG_NUM_EXEC... | -num-executions"),
default=1,
type=positive_int,
help="The number of next execution datetimes to show",
)
# backfill
ARG_MARK_SUCCESS = Arg(
("-m", "--mark-success"), help="Mark jobs as succeeded without running them", action="store_true"
)
ARG_VERBOSE = Arg(("-v", "--verbose"), help="Make logging outp... |
wyrdmeister/OnlineAnalysis | OAGui/src/Control/OAAttrModel.py | Python | gpl-3.0 | 18,589 | 0.00199 | # -*- coding: utf-8 -*-
"""
Online Analysis Configuration Control - TANGO attribute model
Version 1.0
Michele Devetta (c) 2013
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 t... | ""
import re
import h5py as h5
import numpy as np
# PyQt4
from PyQt4 import QtCore
from PyQt4 import QtGui
# PyTango
import PyTango as PT
# GuiBase
from OAGui.GuiBase import GuiBase
from OAGui.GuiBase import declare_trUtf8
_trUtf8 = declare_trUtf8("OAControl")
# Plot dialog
from OAGui.OAMultiplot import PlotDialog... |
# Signal to refresh attribute list
refresh = QtCore.pyqtSignal()
def __init__(self, device, parent=None):
""" Constructor. """
# Parent constructor
QtCore.QAbstractTableModel.__init__(self, parent)
GuiBase.__init__(self, "OAControl")
# Store parent
self._pa... |
fredriklindberg/chromesthesia | chromesthesia_app/chromesthesia.py | Python | gpl-2.0 | 5,919 | 0.004224 | #!/usr/bin/env python
# Copyright (C) 2013-2015 Fredrik Lindberg <[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; version 2 of the License.
#
# This program is distributed... | self.name = "help"
def execute(self):
cmds = command_root.commands
return [
"chromesthesia {0}".format(__version__),
"",
"Begin with any of the following commands " + ", ".join(cmds)
]
def main(config):
print("This is chromesthesia {0}".format(__... | sp = SoundProxy(None)
settings = Settings()
def reinit_sa(key, value):
sp.sa = SoundAnalyzer(settings["freq"], settings["fps"])
settings.create("fps", 60, reinit_sa)
settings.create("freq", 44100, reinit_sa)
reinit_sa(None, None)
def debug(key, value):
logger.del_level(log.DE... |
priorknowledge/loom | loom/format.py | Python | bsd-3-clause | 18,525 | 0.000108 | # Copyright (c) 2014, Salesforce.com, Inc. 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 of conditions... | build(self):
return {
| 'name': self.name,
'model': self.model,
}
class CategoricalEncoderBuilder(object):
def __init__(self, name, model):
self.name = name
self.model = model
self.counts = defaultdict(lambda: 0)
def add_value(self, value):
self.counts[value] += 1
de... |
pdyba/lunch-app | src/lunch_app/tests.py | Python | mit | 35,088 | 0 | # -*- coding: utf-8 -*-
"""
Presence analyzer unit tests.
"""
# pylint: disable=maybe-no-member, too-many-public-methods, invalid-name
from datetime import datetime, date, timedelta
import os.path
import unittest
from unittest.mock import patch
from .main import app, db, mail
from . import main, utils
from .fixtures ... | artswith('Lunch | order'))
self.assertIn('To jest TESTow zamowienie dla emaila', msg.body)
self.assertIn('Pod Koziołkiem', msg.body)
self.assertIn('13.0 PLN', msg.body)
self.assertIn('at 13:00', msg.body)
self.assertEqual(msg.recipients, ['[email protected]'])
@patch('lunch_a... |
Mlieou/oj_solutions | leetcode/python/ex_484.py | Python | mit | 366 | 0.008197 | class Solution(object):
def findPermutation | (self, s):
"""
:type s: str
:rtype: List[int]
"""
if not s: return []
res = []
i = 1
for c in s:
if c == 'I':
res.extend(range(i, len(res), -1))
i += 1
res.extend(range(i, len(r | es), -1))
return res |
zhengbomo/python_practice | project/Lagou/Analyzer.py | Python | mit | 1,396 | 0 | #!/usr/bin/python
# -*- coding:utf-8 -*-
from LagouDb import LagouDb
class Analyzer(object):
def __init__(self):
self.db = LagouDb()
# 统计最受欢迎的工作
@staticmethod
def get_popular_jobs(since=None):
if since:
pass
else:
pass
# 统计职位在不同城市的薪资情况
def get_... | alary_jobs(self, city, count, mincount=10):
result = self.db.high_salary(city, count, mincount=mincount)
kv = {}
for i in result:
k = '{0} ({1})'.format(i['key'], i['count'])
kv[k] = i['salary']
return kv
# 关键字搜索结果比例
def key_persent(self, city, count):
... | for i in result:
k = '{0} ({1})'.format(i['key'], i['count'])
kv[k] = i['count']
return kv
|
DailyActie/Surrogate-Model | 01-codes/scipy-master/scipy/odr/setup.py | Python | mit | 1,419 | 0 | #!/usr/bin/env python
from __future__ import division, print_function, absolute_import
from os.path import join
def configuration(parent | _package='', top_path=None):
import warnings
from numpy.distutils.misc_util import Configuration
from numpy.distutils.system_info import get_info, BlasNotFoundError
config = Configuration('odr', parent_package, top_path)
libodr_files = ['d_odr.f',
'd_mprec.f',
... | as_opt')
if blas_info:
libodr_files.append('d_lpk.f')
else:
warnings.warn(BlasNotFoundError.__doc__)
libodr_files.append('d_lpkbls.f')
odrpack_src = [join('odrpack', x) for x in libodr_files]
config.add_library('odrpack', sources=odrpack_src)
sources = ['__odrpack.c']
l... |
lxki/pjsip | tests/pjsua/scripts-sendto/201_ice_mismatch_1.py | Python | gpl-2.0 | 650 | 0.016923 | # $Id: 201_ice_mismatch_1.py 2392 2008-12-22 18:54:58Z bennylp $
import inc_sip as sip
import inc_sdp as sdp
sdp = \
"""
v=0
o | =- 0 0 IN IP4 127.0.0.1
s=pjmedia
c=IN IP4 127.0.0.1
t=0 0
m=audio 4000 RTP/AVP 0 101
a=ice-ufrag:1234
a=ice-pwd:5678
a=rtpmap:0 PCMU/8000
a=sendrecv
a=rtpmap:101 telephone-event/8000
a=fmtp:101 0-15
a=candidate:XX 1 UDP 1 1.1.1.1 2222 typ host
"""
args = "--null-audio --use-ice --auto-answer 200 --max-calls 1"
includ... | fer for comp 1",
pjsua_args=args, sdp=sdp, resp_code=200,
resp_inc=include, resp_exc=exclude)
|
LockScreen/Backend | venv/lib/python2.7/site-packages/awscli/customizations/cloudtrail/utils.py | Python | mit | 1,641 | 0 | # Copyright 2012-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "Li | cense"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2. | 0/
#
# or in the "license" file accompanying this file. This file 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.
def get_account_id_from_arn(trail_arn)... |
hanul93/kicomav | Engine/kavcore/k2file.py | Python | gpl-2.0 | 10,886 | 0.000532 | # -*- coding:utf-8 -*-
# Author: Kei Choi([email protected])
import os
import re
import glob
import shutil
import tempfile
# import psutil
# ---------------------------------------------------------------------
# K2Tempfile 클래스
# ---------------------------------------------------------------------
class K2Tempfile... | l_filename(self, filename):
self.__fs['additional_filename'] = filename
# ----------------------------------------------- | ----------------------
# is_modify(self)
# 악성코드 치료로 인해 파일이 수정됨 여부를 확인한다.
# 리턴값 : True or False
# ---------------------------------------------------------------------
def is_modify(self): # 수정 여부
return self.__fs['is_modify']
# ----------------------------------------------------------... |
jaap-karssenberg/zim-desktop-wiki | tests/config.py | Python | gpl-2.0 | 22,669 | 0.0251 |
# Copyright 2008-2013 Jaap Karssenberg <[email protected]>
import tests
from tests import os_native_path
import os
from zim.config import *
from zim.fs import adapt_from_oldfs
from zim.newfs import File, Folder, LocalFolder
from zim.notebook import Path
import zim.config
# Check result of lookup funct... | .assertFalse(mydict.modified)
mydict | ['bar'] = 'dus'
self.assertTrue(mydict.modified)
mydict.set_modified(False)
mydict['section'] = ControlledDict()
mydict['section']['dus'] = 'ja'
self.assertTrue(mydict['section'].modified)
self.assertTrue(mydict.modified)
mydict.set_modified(False)
self.assertFalse(mydict.modified)
mydict['section'... |
leifos/tar | scripts/convert_qrels_to_binary_qrels.py | Python | mit | 1,186 | 0.009275 | import sys
import os
def main(qrelFile, threshold):
curr_topic_id = None
with open(qrelFile, "r") as f:
while f:
line = f.readline()
if not line:
break
(topic_id, blank, doc_id, judgement) = li | ne.split()
v= int(judgement)
if v > 0 and v < threshold:
v = 1
print("{0}\t{1}\t{2}\t{3}".format(topic_id, "0", doc_id, v))
if v <= 0:
v = 0
print("{0}\t{1}\t{2}\t{3}".format(topic_id, "0", doc_id, v))
def usage(arg... | elfile> is in TREC qrel format")
print("<relthreshold> reduces graded relevance scores below the threshold to 1 (binary), if above it is removed, else 0.")
print(" defaults to 3")
if __name__ == "__main__":
threshold = 3
if len(sys.argv)==3:
try:
threshold = int(sys.ar... |
synw/django-mogo | djangomogo/__main__.py | Python | mit | 2,304 | 0 | from __future__ import print_function
import sys
import os
import subprocess
path = os.path.abspath(__file__)
modpath = os.path.dirname(path)
base_dir = os.getcwd()
install_mode = 'normal'
plus = False
mon = False
venv = "y"
if len(sys.argv) > 1:
if '-django' in sys.argv:
install_mode = 'django'
elif '... | [bscript, project_name, base_dir, install_mode, modpath])
if mon is True:
bscript = modpath + '/install/mon/install.sh'
subprocess.call(
[bscript, project_name, base_dir, install_mode, m | odpath])
# end
bscript = modpath + '/install/end/install.sh'
subprocess.call([bscript, project_name, base_dir, install_mode, modpath, rt])
|
VishvajitP/readthedocs.org | readthedocs/cdn/purge.py | Python | mit | 645 | 0.00155 | import logging
from django.conf import settings
log = logging.getLogger(__name__)
CDN_SERVICE = getattr(settings, 'CDN_SERVICE', None)
CDN_USERNAME = getattr(settings, 'CDN_USERNAME', None)
CDN_KEY = getattr(settings, 'CDN_KEY', None)
CDN_SECET = getattr(settings, 'CDN_SECET', None)
CDN_ID = getattr(settings, 'CDN_I... | xcdn':
from maxcdn import MaxCDN
api = MaxCDN(CDN_USERNAME, CDN_KEY, CDN_SECET)
def purge(files):
return api.purge(CDN_ID, files)
else:
def purge( | files):
log.error("CDN not configured, can't purge files")
|
magarcia/python-producteev | producteev/utils.py | Python | mit | 1,036 | 0.000965 | # Copyright (c) 2012 Martin Garcia <[email protected]>
#
# This file is part of python-producteev, and is made available under
# MIT license. | See LICENSE for the full details.
import re
import htmlentitydefs
def unescape(text):
"""
Removes HTML or XML character references and entities from a text string.
text -- The HTML (or XML) source text.
return -- The plain text, as a Unicode string, if necessary.
| """
def fixup(m):
text = m.group(0)
if text[:2] == "&#":
# character reference
try:
if text[:3] == "&#x":
return unichr(int(text[3:-1], 16))
else:
return unichr(int(text[2:-1]))
except Valu... |
mmnelemane/nova | nova/tests/unit/api/openstack/compute/test_security_groups.py | Python | apache-2.0 | 67,497 | 0.000133 | # Copyright 2011 OpenStack Foundation
# Copyright 2012 Justin Santa Barbara
#
# 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
#
#... | (TestSecurityGroupsV21, self).setUp()
| self.controller = self.secgrp_ctl_cls()
self.server_controller = self.server_secgrp_ctl_cls()
self.manager = self.secgrp_act_ctl_cls()
# This needs to be done here to set fake_id because the derived
# class needs to be called first if it wants to set
# 'security_group_api' an... |
nocarryr/rtlsdr-wwb-scanner | wwb_scanner/ui/plots.py | Python | gpl-2.0 | 3,912 | 0.006646 | import numpy as np
import matplotlib.pyplot as plt
from wwb_scanner.scan_objects.spectrum import compare_spectra
from wwb_scanner.file_handlers import BaseImporter
class BasePlot(object):
def __init__(self, **kwargs):
self.filename = kwargs.get('filename')
if self.filename is not None:
... | @y.setter
def y(self, value):
self._y = value
@property
def figure(self):
return getattr(self, '_figure', None)
@figure.setter
def figure(self, figure):
self._figure = figure
#self.timer = figure.canvas.new_timer(interval=100)
#self.timer.add_callba | ck(self.on_timer)
def on_timer(self):
print('timer')
spectrum = self.spectrum
with spectrum.data_update_lock:
if spectrum.data_updated.is_set():
print('update plot')
self.update_plot()
spectrum.data_updated.clear()
def build_dat... |
pombredanne/django-fluent-contents | fluent_contents/plugins/oembeditem/fields.py | Python | apache-2.0 | 1,167 | 0.005998 | from django.core.exceptions import ValidationError
from django.db.models import URLField
from django.utils.translation import ugettext_lazy as _
from fluent_contents.plugins.oembeditem import backend
class OEmbedUrlField(URLField):
"""
URL Field which validates whether the URL is supported by the OEmbed provi... | **kwargs)
if not backend.has_provider_for_url(url):
raise ValidationError(_("The URL is not valid for embedding content")) # or is not configured as provider.
return url
try:
from south.modelsinspector import add_introspection_rules
except ImportErr | or:
pass
else:
add_introspection_rules([], ["^" + __name__.replace(".", "\.") + "\.OEmbedUrlField"])
|
parksandwildlife/wastd | conservation/migrations/0002_auto_20180926_1147.py | Python | mit | 646 | 0.001548 | # Generated by Django 2.0.8 on 2018-09-26 03:47
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migra | tion):
dependencies = [
('conservation', '0 | 001_squashed_0027_auto_20180509_1048'),
]
operations = [
migrations.AlterField(
model_name='fileattachment',
name='author',
field=models.ForeignKey(blank=True, help_text='The person who authored and endorsed this file.', null=True, on_delete=django.db.models.deletion... |
cisco/xr-telemetry-m2m-web | src/m2m_demo/__init__.py | Python | apache-2.0 | 285 | 0 | # =============================================================================
# __init__.py
#
# M2M demo init file.
#
# December 20 | 15
#
# Copyright (c) 2015 b | y cisco Systems, Inc.
# All rights reserved.
# =============================================================================
|
opensyllabus/osp-api | taskrefresh.py | Python | mit | 2,540 | 0.000394 | """AWS ECS: Update cluster servic | e to utilize a cloned task definition.
Clone latest task and register it in order to update the image
used on tasks in the service. It will take a while becau | se it
needs to drain connections and some other stuff.
"""
import sys
import os
import subprocess
import json
# we don't want to accidentally reveal any passwords on travis ci
sys.stdout = open(os.devnull, 'w')
# Get a list of task definition ARNs and find
# the latest task.
list_task_definitions_output = subproce... |
tsuru/varnishapi | run_instance_starter.py | Python | bsd-3-clause | 697 | 0.002869 | # Copyright 2014 va | rnishapi authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# | license that can be found in the LICENSE file.
import argparse
from feaas import api
from feaas.runners import instance_starter
def run(manager):
parser = argparse.ArgumentParser("Instance starter runner")
parser.add_argument("-i", "--interval",
help="Interval for running InstanceSt... |
CospanDesign/python | pyqt/threading/example1.py | Python | mit | 1,752 | 0.006279 | #! /usr/bin/python
import sys
import time
from PyQt4 import QtCore
from PyQt4 import QtGui
class WorkThread(QtCore.QThread):
def __init__(self):
QtCore.QThread.__init__(self)
def __del__(self):
self.wait()
def run(self):
for i in range (6):
print " | .",
time.sleep(0.3)
self.emit(QtCore.SIGNAL("Update(QString)"), "from worker thread " + str(i))
| return
class MyApp(QtGui.QWidget):
def __init__(self, parent = None):
QtGui.QWidget.__init__(self, parent)
self.setGeometry(300, 300, 280, 600)
self.setWindowTitle("Threads")
self.layout= QtGui.QVBoxLayout(self)
self.testButton = QtGui.QPushButton("test")
self.co... |
rspavel/spack | lib/spack/spack/filesystem_view.py | Python | lgpl-2.1 | 26,567 | 0.000038 | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import functools as ft
import os
import re
import shutil
import sys
from llnl.util.link_tree import LinkTree, MergeConfli... | iew. Does not add dependenci | es.
"""
raise NotImplementedError
def add_standalone(self, spec):
"""
Add (link) a standalone package into this view.
"""
raise NotImplementedError
def check_added(self, spec):
"""
Check if the given concrete spec is active in this view.
... |
anhstudios/swganh | data/scripts/templates/object/tangible/lair/base/shared_poi_all_lair_mound_large_evil_fire_green.py | Python | mit | 466 | 0.04721 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = | Tangible()
result.template = "object/tangible/lair/base/shared_poi_all_lair_mound_large_evil_fire_green.iff"
result.attribute_template_id = -1
result.stfName("lair_n","mound")
#### BEGIN MODIFICATIONS ####
| #### END MODIFICATIONS ####
return result |
Pikecillo/genna | external/4Suite-XML-1.0.2/test/Xml/Xslt/Core/test_call_template.py | Python | gpl-2.0 | 1,488 | 0.001344 | from Xml.Xslt import test_harness
sheet_str = """<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="/">
<root>
<xsl:apply-templates/>
</root>
</xsl:template>
<xsl:template name="do-the-rest">
<xsl:param name="start"/>
<xsl:param name="count... | ;=$start and position()<$start+$count]">
<td>
<xsl:value-of select="."/>
</td>
</xsl:for-each>
</tr>
<xsl:if test="$start + $count - 1 < count(child::item)">
<xsl:call-template name="do-the-rest">
<xsl:with-param name="st | art" select="$start + $count"/>
<xsl:with-param name="count" select="$count"/>
</xsl:call-template>
</xsl:if>
</xsl:template>
<xsl:template match="data">
<xsl:call-template name="do-the-rest">
<xsl:with-param name="start" select="1"/>
<xsl:with-param name="count" select="2"/>
</xsl:call-template>... |
quanvm009/codev7 | openerp/addons_quan/lifestyle/wizard/create_po_wizard.py | Python | agpl-3.0 | 7,812 | 0.006144 | # -*- coding: utf-8 -*-
# #####################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2011 OpenERP s.a. (<http://openerp.com>).
# Copyright (C) 2013 INIT Tech Co., Ltd (http://init.vn).
# This program is free software: you can redistribute it a... | 'sale_line_id': fields.many2one('sale.order.line', 'Sale Order Line'),
'material_id_wizard': fields.many2one | ('create.po.wizard', 'Material'),
'price_unit': fields.float('Unit Price', required=True, digits_compute=dp.get_precision('Product Price')),
}
_defaults = {
'quantity': 0,
'qty_kg': 0,
}
def onchange_product_id(self, cr, uid, ids, prod_id=False, context=None):
""" On cha... |
OCA/l10n-netherlands | l10n_nl_xaf_auditfile_export/tests/__init__.py | Python | agpl-3.0 | 118 | 0 | # L | icense AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from . import test_l10n_nl_xaf_auditfile_export | |
cpieloth/BackBacker | setup_commands.py | Python | gpl-3.0 | 8,386 | 0.002385 | """Custom commands for setup.py"""
import abc
import distutils.cmd
import os
import re
__author__ = 'Christof Pieloth'
working_dir = os.path.abspath(os.path.dirname(__file__))
build_dir = os.path.join(working_dir, 'build')
api_name = 'backbacker'
project_name = re.search('^__project_name__\s*=\s*\'(.*)\'',
... | 'check_style_doc'
@classmethod
def clean_folders(cls):
return []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
import pep257
import sys
ignores = list()
ignores.append('D105') # Missing docstring in ma... | ignores.append('D203') # 1 blank line required before class docstring
sys.argv = ['pep257', '--ignore={}'.format(','.join(ignores)), os.path.join(working_dir, api_name)]
return pep257.run_pep257()
class CheckStyleCustomCmd(CustomCommand):
"""Run style checkers."""
description = CustomComman... |
renegelinas/mi-instrument | mi/dataset/parser/test/test_zplsc_c_echogram.py | Python | bsd-2-clause | 1,302 | 0 | #!/usr/bin/env python
import os
from mi.logging import log
from mi.dataset.parser.zplsc_c import ZplscCParser
from mi.dataset.dataset_parser import DataSetDriverConfigKeys
from mi.dataset.driver.zplsc_c.resource import RESOURCE_PATH
__author__ = 'Rene Gelinas'
MODULE_NAME = 'mi.dataset.parser.zplsc_c'
CLASS_NAME = ... | te_zplsc_c_par | ser(file_handle):
"""
This function creates a zplsc-c parser for recovered data.
@param file_handle - File handle of the ZPLSC_C raw data.
"""
return ZplscCParser(config, file_handle, rec_exception_callback)
def file_path(filename):
log.debug('resource path = %s, file name = %s', RESOURCE_PATH... |
StellarCN/py-stellar-base | stellar_sdk/xdr/int32.py | Python | apache-2.0 | 1,398 | 0 | # This is an automatically generated file.
# DO NOT EDIT or your changes may be overwritten
import base64
from xdrlib import Packer, Unpacker
from ..type_checked import type_checked
from .base import Integer
__all__ = ["Int32"]
@type_checked
class Int32:
"""
XDR Source Code::
typedef int int32;
... | self, packer: Packer) -> None:
Integer(self.int32).pack(packer)
@classmethod
def unpack(cls, unpacker: Unpacker) -> "Int32":
int32 = Integer.unpack(unpacker)
| return cls(int32)
def to_xdr_bytes(self) -> bytes:
packer = Packer()
self.pack(packer)
return packer.get_buffer()
@classmethod
def from_xdr_bytes(cls, xdr: bytes) -> "Int32":
unpacker = Unpacker(xdr)
return cls.unpack(unpacker)
def to_xdr(self) -> str:
... |
homeworkprod/byceps | byceps/services/email/service.py | Python | bsd-3-clause | 4,293 | 0 | """
byceps.services.email.service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from __future__ import annotations
from typing import Optional
from sqlalchemy.exc import IntegrityError
from ...database import db, upsert
from ... i... | _name: Optional[str] = | None,
contact_address: Optional[str] = None,
) -> EmailConfig:
"""Create a configuration."""
config = DbEmailConfig(
brand_id,
sender_address,
sender_name=sender_name,
contact_address=contact_address,
)
db.session.add(config)
db.session.commit()
return _db_... |
jamesp/jpy | jpy/maths/derive.py | Python | mit | 2,080 | 0.006747 | #!/usr/bin/env pyt | hon
# -*- coding: utf-8 -*-
"""Numerical differentiation."""
import numpy as np
from jpy.maths.matrix import tridiag
def make_stencil(n, i, i_, _i):
"""Create a tridiagonal stencil matrix of size n.
Creates a matrix to dot with a vector for performing discrete spatial computations.
i, i_ and _i are multi... | i-1 values of the vector respectively.
e.g. to calculate an average at position i based on neighbouring values:
>>> s = make_stencil(N, 0, 0.5, 0.5)
>>> avg_v = np.dot(s, v)
The stencil has periodic boundaries.
Returns an nxn matrix.
"""
m = tridiag(n, i, i_, _i)
m[-1,0] = i_
m[0,-1... |
mercycorps/TolaActivity | indicators/migrations/0060_ind_level_fields_unique_together.py | Python | apache-2.0 | 436 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.21 on 2019-06-13 15:38
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Mi | gration):
dependencies | = [
('indicators', '0059_require_level_name'),
]
operations = [
migrations.AlterUniqueTogether(
name='indicator',
unique_together=set([('level', 'level_order')]),
),
]
|
marios-zindilis/musicbrainz-django-models | musicbrainz_django_models/models/instrument_alias_type.py | Python | gpl-2.0 | 2,427 | 0.002472 | """
.. module:: instrument_alias_type
The **Instrum | ent Alias Type** Model. Here's a complete table of values, from the
MusicBrainz database dump of 2017-07-22:
+----+-----------------+--------+-------------+-------------+--------------------------------------+
| id | name | parent | child_order | description | gid |
+====+==... | aa5ec8d14fcd |
+----+-----------------+--------+-------------+-------------+--------------------------------------+
| 2 | Search hint | | | | 7d5ef40f-4856-3000-8667-aa13b9db547d |
+----+-----------------+--------+-------------+-------------+--------------------------------------+
P... |
hfp/tensorflow-xsmm | tensorflow/contrib/distributions/python/ops/bijectors/reshape.py | Python | apache-2.0 | 13,771 | 0.005882 | # 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... | imension_value(shape.shape.with_rank_at_least(1)[0])
@deprecation.deprecated(
"2018-10-01",
"The TensorFlow Distributions library has moved to "
"TensorFlow Probability "
"(https://github.com/tensorflow/probability). You "
"should update all ref | erences to use `tfp.distributions` "
"instead of `tfp.distributions`.",
warn_once=True)
def _ndims_from_shape(shape):
return array_ops.shape(shape)[0]
class Reshape(bijector.Bijector):
"""Reshapes the `event_shape` of a `Tensor`.
The semantics generally follow that of `tf.reshape()`, with
a few diffe... |
lukecwik/incubator-beam | sdks/python/apache_beam/runners/dataflow/internal/apiclient_test.py | Python | apache-2.0 | 47,214 | 0.003558 | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... | dataflow.internal import apiclient
except ImportError:
apiclient = None # type: ignore
# pylint: enable=wrong-import-order, wrong-import-position
FAKE_PIPELINE_URL = "gs://invalid-bucket/anywhere"
_LOGGER = logging.getLogger(__name__)
@unittest.skipIf(apiclient is None, 'GCP dependencies are not installed')
class... | st_create_application_client(self):
pipeline_options = PipelineOptions()
apiclient.DataflowApplicationClient(pipeline_options)
def test_pipeline_url(self):
pipeline_options = PipelineOptions([
'--subnetwork',
'/regions/MY/subnetworks/SUBNETWORK',
'--temp_location',
'gs://a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.