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 |
|---|---|---|---|---|---|---|---|---|
google/automl-video-ondevice | automl_video_ondevice/object_tracking/mediapipe_track_validator.py | Python | apache-2.0 | 5,835 | 0.005484 | # Lint as: python3
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | ======================================================================
"""Validates generated tracks and filters out invalidated tracks."""
import dataclasses
from automl_video_ondevice.types import ObjectTrackingAnnotation
def calculate_iou(bbox1, bbox2):
""" | Calculates the Intersection-Over-Union of two bounding boxes.
IOU is a ratio for determining how much two bounding boxes match.
Args:
bbox1: The first bounding box.
bbox2: The bounding box to compare with.
Returns:
The IOU as a float from 0.0 to 1.0 (1.0 being a perfect match.)
"""
x_overlap = ... |
MayukhSobo/EnronFraud | feature_engineering/feature_importance.py | Python | mit | 7,787 | 0.001284 | import numpy as np
from feature_loader import FeatureExtract
import operator
from collections import OrderedDict
class Importance:
def __init__(self, algo, fObj):
if algo.lower() not in ['xgboost', 'random_forest', 'k_best', '*']:
raise NotImplementedError("Algorithm support not implemented")... | xgboost model if save=True. It also can
perform parameter tuning if cv=True.
:param k: Number of features
:param file_path: image file to save
:param save: True for saving as image
:param cv: True for | XGBoost's param tuning
:return: None for save=True, list of features inf save=False
"""
import xgboost as xgb
if self.algo not in ['*', 'xgboost']:
raise ValueError('class obj is not created with the {} algorithm support'.format(self.algo))
if k < 1 or k > len(self.f... |
dtudares/hello-world | yardstick/tests/unit/benchmark/scenarios/networking/test_netperf_node.py | Python | apache-2.0 | 3,858 | 0.000259 | #!/usr/bin/env python
##############################################################################
# Copyright (c) 2015 Huawei Technologies Co.,Ltd and others.
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompan... | (0, '', '')
p.host = mock_ssh.SSH()
mock_ssh.SSH().execute.return_value = (1, '', 'FOOBAR')
self.assertRaises(RuntimeError, p.run, result)
def _read_sample_output(self):
curr_path = os.path.dirname(os.path.abspath(__file__))
output = os.path.join(curr_path, 'netperf_sample... | sample_output = f.read()
return sample_output
def main():
unittest.main()
if __name__ == '__main__':
main()
|
sserrot/champion_relationships | venv/Lib/site-packages/IPython/core/tests/test_ultratb.py | Python | mit | 13,550 | 0.002438 | # encoding: utf-8
"""Tests for IPython.core.ultratb
"""
import io
import logging
import sys
import os.path
from textwrap import dedent
import traceback
import unittest
from unittest import mock
import IPython.core.ultratb as ultratb
from IPython.core.ultratb import ColorTB, VerboseTB, find_recursion
from IPython.tes... | """
)
with tt | .AssertPrints('SpecificException: Success!', suppress=False):
ip.run_cell(code)
indentationerror_file = """if True:
zoon()
"""
class IndentationErrorTest(unittest.TestCase):
def test_indentationerror_shows_line(self):
# See issue gh-2398
with tt.AssertPrints("IndentationError"):
... |
netpie/peewee-async | tests.py | Python | mit | 6,651 | 0.001504 | import asyncio
import configparser
import sys
import unittest
import peewee
# Testing module
import peewee_async
# Shortcuts
execute = peewee_async.execute
count = peewee_async.count
scalar = peewee_async.scalar
get_object = peewee_async.get_object
create_object = peewee_async.create_object
delete_object = peewee_asy... | sults should be the same
self.assertEqual(len1, len2)
for o1, o2 in zip(q1, q2):
self.assertEqual(o1, o2)
def test_update_query(self):
# Sync create
obj1 = TestModel.create(text='[sync] [test_update_obj]')
self.assertEqual(obj1.text, '[syn | c] [test_update_obj]')
# Sync update
upd1 = (TestModel.update(text='[sync] [test_update_obj] [update]')
.where(TestModel.id == obj1.id).execute())
self.assertEqual(upd1, 1)
# Async update
@asyncio.coroutine
def test():
query = (TestM... |
sebrandon1/neutron | neutron/services/metering/agents/metering_agent.py | Python | apache-2.0 | 11,182 | 0 | # Copyright (C) 2013 eNovance SAS <licensing@enovance.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 applicabl... | ontext, routers=None):
if not routers:
routers = self._get_sync_data_metering(self.context)
if not routers:
return
self._update_routers(context, routers)
def _update_routers(self, context, routers):
for router in routers:
| self.routers[router['id']] = router
return self._invoke_driver(context, routers,
'update_routers')
def _get_traffic_counters(self, context, routers):
LOG.debug("Get router traffic counters")
return self._invoke_driver(context, routers, 'get_traffic_... |
xkmato/casepro | casepro/msgs/migrations/0003_message_case.py | Python | bsd-3-clause | 692 | 0.00289 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migra | tions.Migration):
dependencies = [
('cases', '0018_delete_outgoing'),
('msgs', '0002_outgoing'),
]
operations = [
migrations.AddField(
model_name='message',
name='case',
field=models.ForeignKey(related_name='incoming_messages', to='cases.Case', n... | name='org',
field=models.ForeignKey(related_name='incoming_messages', verbose_name='Organization', to='orgs.Org'),
),
]
|
wlerin/streamlink | src/streamlink/plugins/powerapp.py | Python | bsd-2-clause | 979 | 0.002043 | from __ | future__ import print_function
import re
from streamlink.plugin import Plugin
from streamlink.plugin.api import validate
from streamlink.stream import HLSStream
class PowerApp(Plugin):
url_re = re.compile(r"https?://(?:www.)?powerapp.com.tr/tvs?/(\w+)")
api_url = "http://api.powergroup.com.tr/Channels/{0}/?a... | e": 0,
"response": {
"channel_stream_url": validate.url()
}
}, validate.get("response")))
@classmethod
def can_handle_url(cls, url):
return cls.url_re.match(url) is not None
def _get_streams(self):
channel = self.url_re.match(self.url).group(1)
res ... |
be1be1/appinventor-polyu | appinventor/lib/blockly/src/i18n/xliff_to_json.py | Python | apache-2.0 | 8,544 | 0.001287 | #!/usr/bin/python
# Converts .xlf files into .json files for use at http://translatewiki.net.
#
# Copyright 2013 Google Inc.
# https://blockly.googlecode.com/
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in co | mpliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab | le 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 argparse
import os... |
wbwseeker/spaCy | spacy/munge/read_ner.py | Python | mit | 3,728 | 0.001878 | from __future__ import unicode_literals
import os
from os import path
import re
def split(text):
"""Split an annotation file by sentence. Each sentence's annotation should
be a single string."""
return text.strip().split('\n')[1:-1]
def parse(string, strip_bad_periods=False):
"""Given a sentence... | ">little</ENAMEX> drain</ENAMEX>', 'l | ittle drain')
for substr in string.strip().split():
substr = _fix_inner_entities(substr)
tokens.append(_get_text(substr))
try:
tag, open_tag = _get_tag(substr, open_tag)
except:
raise
tags.append(tag)
return tokens, tags
tag_re = re.compile(r'<EN... |
c11/yatsm | yatsm/structural_break/_cusum.py | Python | mit | 6,887 | 0.001743 | # -*- coding: utf-8 -*-
""" Methods for estimating structural breaks in time series regressions
TODO: extract and move Chow test from "commission test" over to here
"""
from __future__ import division
from collections import namedtuple
import logging
import numpy as np
import pandas as pd
from scipy.optimize import ... | , y)[0]
resid = np.dot(X, beta) - y
process = _cusum(resid, p)
_process = np.abs(process)
idx = _process.argmax()
sc | ore = _process[idx]
return process, score, idx
def cusum_OLS(X, y, alpha=0.05):
ur""" OLS-CUSUM test for structural breaks
Tested against R's ``strucchange`` package and is faster than
the equivalent function in the ``statsmodels`` Python package when
Numba is installed.
The OLS-CUSUM test ... |
ArturoDeza/Piranhas | python/create_Piranha.py | Python | bsd-3-clause | 4,106 | 0.01924 | # Python Script to initialize a Peripheral Architecture:
# Developed by Arturo Deza as part of the Piranhas Toolkit
# Questions & bugs: deza @ dyns.ucsb.edu
import numpy as np
import piranhas as pir
import math
# Start Computer parameters:
pixel_res_width = 800 # in pixels
pixel_res_height = 600 # in pixels
mon_widt... | #########################
# Compute Perip | heral Mask Stream #
##################################
#This should probably be a function inside piranhas
# size might have changed after removing peripheral regions inside fovea
param_check = np.shape(peripheral_filters.regions)
N_theta = param_check[0]
N_e = param_check[1]
peri_height = param_check[2]
peri_width ... |
kshahar/pylaunchy | plugins/PyDiry/pydiry.py | Python | gpl-2.0 | 4,461 | 0.038574 | # Copyright (c) 2008 Shahar Kosti
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; either version 2 of the License, or (at your option) any later
# version.
#
# This program is distribu... | etResults(self, inputDataList, resultsList):
inputs = len(inputDataList)
if inputs != 2:
return
firstText = inputDataList[0].getText()
if not self.dirs.has_key(firstText):
return
path = self.dirs[firstText]
query = inputDataList[1].getText()
if query == '':
# Default que... | y = '*'
elif not query.startswith('*') and not query.endswith('*'):
# Add * at both sides to ease searching
query = '*%s*' % query
pathContents = glob.glob(os.path.join(path, query))
pathContents.sort()
for itemPath in pathContents:
resultsList.append( launchy.CatItem(itemPath, self.__ma... |
hguochen/mediapop | mediapop/manage.py | Python | mit | 257 | 0 | #!/usr/bin/env python
import os
import sys
if __name__ == | "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mediapop.settings.local")
from django.core.management import execute_from_command_line
execute_from_ | command_line(sys.argv)
|
jcsp/manila | manila/api/auth.py | Python | apache-2.0 | 1,414 | 0 | # Copyright (c) 2013 OpenStack, LLC.
#
# 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 law or agreed to in writing, software
# distributed under the License is distri... | pecific language governing permissions and limitations
# under the License.
from oslo_log import log
from manila.api.middleware import auth
from manila.i18n import _LW
LOG = log.getLogger(__name__)
class ManilaKeystoneContext(auth.ManilaKeystoneContext):
def __init__(self, application):
LOG.warn(_LW... |
Kirembu/django-helpline-faq | faq/tests/__init__.py | Python | bsd-3-clause | 148 | 0 | fr | om faq.tests.test_admin import *
from faq.tests.test_models import *
from faq.tests.test_templatetags import *
from faq.tests.test_views imp | ort *
|
HIPS/autograd | autograd/__init__.py | Python | mit | 504 | 0 | from __future__ import absolute_import
from .differential_operators import (
make_vjp, grad, multigrad_dict, elementwise_grad, value_and_grad,
grad_and_aux, hessian_tensor_product, hessian_vector_ | product, hessian,
jacobian, tensor_jacobian_product, vector_jacobian_product, grad_named,
checkpoint, | make_hvp, make_jvp, make_ggnvp, deriv, holomorphic_grad)
from .builtins import isinstance, type, tuple, list, dict
from autograd.core import primitive_with_deprecation_warnings as primitive
|
eike-welk/clair | src/clairweb/common/views.py | Python | gpl-3.0 | 109 | 0.009174 | from django.shortcuts import rende | r
| def index(request):
return render(request, 'common/index.html', {}) |
silly-wacky-3-town-toon/SOURCE-COD | otp/nametag/NametagGroup.py | Python | apache-2.0 | 9,754 | 0.001948 | from panda3d.core import *
from panda3d.direct import *
from NametagConstants import *
from Nametag3d import *
from Nametag2d import *
class NametagGroup:
CCNormal = CCNormal
CCNoChat = CCNoChat
CCNonPlayer = CCNonPlayer
CCSuit = CCSuit
CCToonBuilding = CCToonBuilding
CCSuitBuilding = CCSuitBui... | ask)
def getChat(self):
if self.chatPage >= len(self.chatPages):
| return ''
else:
return self.chatPages[self.chatPage]
def getStompText(self):
return self.stompText
def getStompDelay(self):
return 0.2
def getUniqueId(self):
return 'Nametag-%d' % id(self)
def hasButton(self):
return bool(self.getButtons(... |
dayongxie/zeroc-ice-androidndk | js/allTests.py | Python | gpl-2.0 | 1,643 | 0.003652 | #!/usr/bin/env python
# **********************************************************************
#
# Copyright (c) 2003-2014 ZeroC, Inc. All rights reserved.
#
# This copy of Ice is licensed to you under the terms described in the
# ICE_LICENSE file included in this distribution.
#
# *************************************... | e/inheritance", ["once"]),
("Ice/inheritanceBidir", ["once"]),
("Ice/location", ["once"]),
("Ice/objects", ["core"]),
("Ice/operations", ["core"]),
("Ice/operationsBidir", ["once"]),
("Ice/optional", ["core"]),
("Ice/optionalBidir", ["once"]),
("Ice/promise", ["once"]),
("Ice/proxy",... | "core"]),
("Ice/slicing/objects", ["core"]),
("Ice/timeout", ["core"]),
("Glacier2/router", ["service"]),
]
if __name__ == "__main__":
TestUtil.run(tests)
|
tranhuucuong91/coclib | coclib/alert/__init__.py | Python | mit | 220 | 0.004545 | #-*- coding: utf-8 -*-
# alert
| #
# Copyright (C) 20012-2014 coclib
# Authors: Tran Huu Cuong <tranhuucuong91@gmail.com>
# URL: http://tranhuucuong91.wordpress.com/
# License: BSD
fr | om .send_alert import send_alert
|
mvesper/invenio | modules/websearch/lib/search_engine_unit_tests.py | Python | gpl-2.0 | 12,575 | 0.001431 | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 CERN.
#
# Invenio is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either ver... | def test_parsing_exact_phrase_query_unbalanced(self):
| "search engine - parsing unbalanced exact phrase"
self._check('"the word', 'title', None,
[['+', '"the', 'title', 'w'],
['+', 'word', 'title', 'w']])
def test_parsing_exact_phrase_query_in_any_field(self):
"search engine - parsing exact phrase in any fi... |
sailfish-sdk/sailfish-qtcreator | tests/system/suite_HELP/tst_HELP02/test.py | Python | gpl-3.0 | 6,908 | 0.005935 | ############################################################################
#
# Copyright (C) 2016 The Qt Company Ltd.
# Contact: https://www.qt.io/licensing/
#
# This file is part of Qt Creator.
#
# Commercial License Usage
# Licensees holding valid commercial Qt licenses may use this file in
# accordance with the co... | cordance with the terms contained in
# a written agreement between you and The Qt Company. For licensing terms
# and conditions see https://www.qt.io/terms-conditions. For further
# | information use the contact form at https://www.qt.io/contact-us.
#
# GNU General Public License Usage
# Alternatively, this file may be used under the terms of the GNU
# General Public License version 3 as published by the Free Software
# Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
# inclu... |
gviejo/ThalamusPhysio | python/main_make_SWS_scalar_product.py | Python | gpl-3.0 | 14,308 | 0.034736 | #!/usr/bin/env python
'''
File name: main_ripp_mod.py
Author: Guillaume Viejo
Date created: 16/08/2017
Python Version: 3.5.2
'''
import sys
import numpy as np
import pandas as pd
import scipy.io
from functions import *
# from pylab import *
from multiprocessing import Pool
import os
import neurose... | ex//len(sws_ep))) for i in sws_ep.index])))
####################################################################################################################
# MEA | N AND STD SWS
####################################################################################################################
# # mean and standard deviation during SWS
# mean_sws = pd.DataFrame(index = np.sort(list(spikes.keys())), columns = ['min', 'max'])
# for n in spikes.keys():
# r = []
# for e in sw... |
batermj/algorithm-challenger | code-analysis/programming_anguage/python/source_codes/Python3.5.9/Python-3.5.9/Lib/test/test__locale.py | Python | apache-2.0 | 7,909 | 0.003793 | from _locale import (setlocale, LC_ALL, LC_CTYPE, LC_NUMERIC, localeconv, Error)
try:
from _locale import (RADIXCHAR, THOUSEP, nl_langinfo)
except ImportErro | r:
nl_langinfo = None
import codecs
import locale
import sys
import unittest
from platform import uname
if uname().system == "Darwin":
maj, min, mic = [int(part) for part in uname().release.split(".")]
if (maj, min, mic) < (8, 0, 0):
raise unittest.SkipTest("locale support broken for OS X < 10.4")... | es_PY', 'no_NO', 'nl_NL', 'lv_LV', 'el_GR', 'be_BY', 'fr_BE',
'ro_RO', 'ru_UA', 'ru_RU', 'es_VE', 'ca_ES', 'se_NO', 'es_EC', 'id_ID',
'ka_GE', 'es_CL', 'wa_BE', 'hu_HU', 'lt_LT', 'sl_SI', 'hr_HR', 'es_AR',
'es_ES', 'oc_FR', 'gl_ES', 'bg_BG', 'is_IS', 'mk_MK', 'de_AT', 'pt_BR',
'da_DK', 'nn_NO', 'cs_CZ',... |
khoanguyen0791/cs170 | CS170_homework/Circles.py | Python | apache-2.0 | 579 | 0.017271 | import turtle
kay = turtle.Turtle()
kay.penup()
kay.goto(-125,0)
kay.pendown()
kay.width(5)
kay.color()
kay.color('blue','yellow')
kay.circle(50)
kay.penup()
kay.goto(0,0)
kay.pendown()
kay.color()
kay.color('black','yellow')
kay.circle(50)
kay.penup()
kay.goto(125,0)
kay.pendown()
kay.color()
| kay.color('red','yellow')
kay.circle(50)
|
kay.penup()
kay.goto(-62.5,-50)
kay.pendown()
kay.color()
kay.color('yellow','yellow')
kay.circle(50)
kay.penup()
kay.goto(62.5,-50)
kay.pendown()
kay.color()
kay.color('green','yellow')
kay.circle(50)
kay.getscreen().exitonclick()
|
vadimshchukin/zsublime | ISPF/ISPF.py | Python | gpl-3.0 | 1,523 | 0.00394 | # -*- coding: utf-8 -*-
import re
import sublime, sublime_plugin
class IspfShiftRightCommand(sublime_plugin.TextCommand):
def run(self, edit):
selection = self.view.sel()
for region in selection:
region_text = self.view.substr(region)
shifted_lines = []
for lin... | shifted_lines = []
for line in region_text.split('\n'):
shifted_lines.append(self.shift_text_left(line, 2))
self.view.replace(edit, region, '\n'.join(shifted_lines))
def shift_text_left(self, text, factor=1):
for index in range(factor):
match = re.search(... | \W+(\w).*?( )', text)
if match:
text = text[:match.span(1)[0] - 1] + text[match.span(1)[0]:match.span(2)[0]] + ' ' + text[match.span(2)[0]:]
return text
|
googleapis/python-aiplatform | samples/snippets/model_service/get_model_evaluation_text_classification_sample.py | Python | apache-2.0 | 2,069 | 0.00145 | # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | can be reused for multiple requests.
client = aiplatform.gapic.ModelServiceClient(client_options=client_options)
name = client.model_evaluation_path(
project=project, location=location, model=model_id, evaluation=evaluation_id
)
response = clien | t.get_model_evaluation(name=name)
print("response:", response)
# [END aiplatform_get_model_evaluation_text_classification_sample]
|
FZambia/reborn | server/core/urls.py | Python | mit | 739 | 0.001353 | from core import views
from django.conf.urls import url, include
from rest_framework.routers import DefaultRouter
from rest_framework.authtoken import views as authtoken_views
router = DefaultRouter()
router.register(r'category', views.Cat | egoryViewSet)
router.register(r'provider', views.ProviderViewSet)
router.register(r'subscription', views.SubscriptionViewSet)
router.register(r'entry', views.EntryViewSet)
urlpatterns = [
url(r'^v1/', include(router.urls)),
url(r'^v1/upload/$', views.UploadView.as_view()),
url(r'^v1/sources/$', views.Sourc... | ew())
]
|
kdwink/intellij-community | python/helpers/pydev/pydev_runfiles_pytest2.py | Python | apache-2.0 | 8,780 | 0.005239 | import pickle, zlib, base64, os
import py
from py._code import code # @UnresolvedImport
import pydev_runfiles_xml_rpc
from pydevd_file_utils import _NormFile
import pytest
import sys
import time
#===================================================================================================
# Load filters with t... | ================================================================================================
def _MockFileRepresentation():
code.ReprFileLocation._original_toterminal = code.ReprFileLocation.toterminal
def toterminal(self, tw):
# filename and lineno output for each entry,
# using an output ... | if PY2:
if not isinstance(path, unicode): # Note: it usually is NOT unicode...
path = path.decode(sys.getfilesystemencoding(), 'replace')
if not isinstance(msg, unicode): # Note: it usually is unicode...
msg = msg.decode('utf-8', 'replace')
uni... |
svieira/Flask-HipPocket | flask_hippocket/tasks.py | Python | mit | 3,301 | 0.004544 | # -*- coding: utf-8 -*-
"""
flask.ext.hippocket.tasks
~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2013 by Sean Vieira.
:license: MIT, see LICENSE for more details.
"""
from flask import Blueprint, Markup, request, render_template
from itertools import chain
from os import path
from pkgutil import walk_p... | symbol=blueprint_name)
#: Autoloaded apps must be Python packages
#: The root of the package is also inspected for a routing file
package_contents = chain([[None, root, True]],
walk_packages(path=package_paths, prefix=apps_package, onerror=on_error))
f | or _, sub_app_name, is_pkg in package_contents:
if not is_pkg:
continue
sub_app_import_path = import_template(base=sub_app_name)
sub_app = import_string(sub_app_import_path)
if isinstance(sub_app, Blueprint):
app.register_blueprint(sub_app)
else:
... |
thecodinghub/news-for-good | news/Lib/random.py | Python | bsd-3-clause | 27,228 | 0.002424 | """Random variable generators.
integers
--------
uniform within range
sequences
---------
pick random element
pick random sample
pick weighted random sample
generate random permutation
distributions on the real line:
---------------------... | dom.Random):
"""Random number generator base class used by bound module functions.
Used to instantiate instances of Random to get generators that don't
share state.
Cla | ss Random can also be subclassed if you want to use a different basic
generator of your own devising: in that case, override the following
methods: random(), seed(), getstate(), and setstate().
Optionally, implement a getrandbits() method so that randrange()
can cover arbitrarily large ranges.
"""... |
Simclass/EDXD_Analysis | pyxe/fitting_functions.py | Python | mit | 3,690 | 0.001355 | # -*- coding: utf-8 -*-
"""
Created on Wed Jul 15 08:28:46 2015
@author: Chris Simpson
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np
def plane_strain(e_xx, e_yy, E, v):
""" Stress calcul... | tion
"""
# return (E / (1 - v ** 2)) * (e_xx + v * e_yy)
E_ = E / (1 - v**2)
v_ = v / (1-v)
return (E_ / (1 - v_ **2)) * (e_xx + v_ * e_yy)
# return (E / (1 + v)) * (e_xx + (v / (1 - 2 * v)) * (e_xx + e_yy))
def plane_stress(e_xx, e_yy, E, v):
""" Stress calculation (from strain) in a plan... | oat, ndarray): Strain/stress in x orientation
e_yy (float, ndarray): Strain/stress in x orientation
E (float): Young's modulus (MPa)
v (float): Poisson's ratio
Returns:
float, ndarray: Stress for each e_xx, e_yy combination
"""
return (E / (1 - v **2)) * (e_xx + v * e_yy) # s... |
project-rig/spalloc | spalloc/scripts/support.py | Python | gpl-2.0 | 4,226 | 0 | # Copyright (c) 2016-2019 The University of Manchester
#
# 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 progra... | a client has been\
obtained and verified to be compatible.
"""
def build_server_arg_group(self, server_args, cfg):
server_args.add_argument(
"--hostname", "-H", default=cfg["hostname"],
help="hostname or IP of the spalloc server (default: %(default)s)")
... | g["port"], type=int,
help="port number of the spalloc server (default: %(default)s)")
server_args.add_argument(
"--timeout", default=cfg["timeout"], type=float, metavar="SECONDS",
help="seconds to wait for a response from the server (default: "
"%(default)s)")
... |
yifans/HLS-II-SIS | src/core/config_parse.py | Python | gpl-3.0 | 1,385 | 0.000722 | #!/usr/bin/python
# -*- coding:utf-8 -*-
# ******************************************************
# Author : Yifan Song
# Last modified: 2017.01.02
# Email : yifans@mail.ustc.edu.cn
# Filename : config_parse.py
# Description : parse the configuration file, and return the interlock tree list
# *******... | nfig_parse(config_content):
if config_content["node_type"] == "trunk_node":
t_node = trunk_node.TrunkNode(config_content)
for i in config_content["child"]:
node = config_parse(i)
t_node.child.append(node)
if "action_list" in c | onfig_content:
for i in config_content["action_list"]:
a_unit = action_unit.ActionUnit(i)
t_node.action.append(a_unit)
return t_node
elif config_content['node_type'] == "leaf_node":
l_node = leaf_node.LeafNode(config_content)
return l_node
|
underdogio/tld | src/tld/update.py | Python | gpl-2.0 | 414 | 0.004831 | from __future__ import print_function
"""
Deprecated. Use ``update-tld-names`` command instead.
"""
__title__ = 'tld.update'
_ | _author__ = 'Artur Barseghyan'
__copyright__ = '2013-2015 Artur Barsegh | yan'
__license__ = 'GPL 2.0/LGPL 2.1'
from tld.utils import update_tld_names
_ = lambda x: x
if __name__ == '__main__':
update_tld_names()
print(_("Local TLD names file has been successfully updated!"))
|
goddardl/gaffer | python/GafferUI/DotUI.py | Python | bsd-3-clause | 4,789 | 0.022969 | ##########################################################################
#
# Copyright (c) 2014, Image Engine Design 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:
#
# * Redistrib... | DING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCU... | ITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
#############################################... |
google/aiyprojects-raspbian | src/examples/voice/cloudspeech_demo.py | Python | apache-2.0 | 2,336 | 0.001284 | #!/usr/bin/env python3
# Copyright 2017 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... | y.cloudspeech import CloudSpeechClient
def get_hints(language_code):
if language_code.startswith('en_'):
return ('turn on the | light',
'turn off the light',
'blink the light',
'goodbye')
return None
def locale_language():
language, _ = locale.getdefaultlocale()
return language
def main():
logging.basicConfig(level=logging.DEBUG)
parser = argparse.ArgumentParser(description... |
odahoda/noisicaa | noisicaa/value_types/key_signature_test.py | Python | gpl-2.0 | 1,559 | 0.000641 | #!/usr/bin/python3
# @begin:license
#
# Copyright (c) 2015-2019, Benjamin Niemann <pink@odahoda.de>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at y... | program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 | USA.
#
# @end:license
from noisidev import unittest
from .key_signature import KeySignature
class KeySignatureTest(unittest.TestCase):
def test_equal(self):
self.assertEqual(KeySignature(name='C major'),
KeySignature(name='C major'))
self.assertNotEqual(KeySignature(name... |
KohlsTechnology/ansible | lib/ansible/modules/network/aci/aci_interface_policy_fc.py | Python | gpl-3.0 | 6,314 | 0.001901 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
... | "ownerKey": "",
"ownerT | ag": ""
}
}
}
]
proposed:
description: The assembled configuration from the user-provided parameters
returned: info
type: dict
sample:
{
"fvTenant": {
"attributes": {
"descr": "Production environment",
"name": "produ... |
eBay/cronus-agent | agent/agent/config/middleware.py | Python | apache-2.0 | 3,424 | 0.004965 | #pylint: disable=W0142,W0105
'''
Copyright 2014 eBay Software 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 applicabl... | mport CronusPylonApp
from beaker.middleware import SessionMiddleware
from paste.cascade import | Cascade
from paste.deploy.converters import asbool
from paste.registry import RegistryManager
from paste.urlparser import StaticURLParser
from pylons.middleware import ErrorHandler, StatusCodeRedirect
from routes.middleware import RoutesMiddleware
from agent.config import gzipmiddelware
def make_app(global_conf, full... |
miurahr/seahub | seahub/utils/file_tags.py | Python | apache-2.0 | 2,647 | 0.001889 | # -*- coding: utf-8 -*-
im | port logging
import posixpath
from collections import defaultdict
from seaserv | import seafile_api
from seahub.base.templatetags.seahub_tags import email2nickname, email2contact_email
from seahub.utils.timeutils import timestamp_to_isoformat_timestr
from seahub.file_tags.models import FileTags
# Get an instance of a logger
logger = logging.getLogger(__name__)
def get_files_tags_in_dir(repo_id... |
Darkdadaah/pywikibot-core | tests/http_tests.py | Python | mit | 23,399 | 0.001069 | # -*- coding: utf-8 -*-
"""Tests for http module."""
#
# (C) Pywikibot team, 2014-2017
#
# Distributed under the terms of the MIT license.
#
from __future__ import absolute_import, unicode_literals
import json
import re
import warnings
import requests
import pywikibot
from pywikibot import config2 as config
from py... | thenticationConfig, se | lf).tearDown()
config.authenticate = self._authenticate
def test_url_based_authentication(self):
"""Test url-based authentication info."""
pairs = {
'https://zh.wikipedia.beta.wmflabs.org': ('1', '2'),
'https://en.wikipedia.beta.wmflabs.org': ('3', '4', '3', '4'),
... |
MikkCZ/kitsune | kitsune/wiki/tasks.py | Python | bsd-3-clause | 10,622 | 0.000094 | import logging
import time
from datetime import date
from django.conf import settings
from django.contrib.sites.models import Site
from django.core.cache import cache
from django.core.exceptions import ValidationError
from django.core.mail import mail_admins
from django.core.urlresolvers import reverse as django_rever... | has been approved: {title}')
else:
subject = _(u'Your revision has been reviewed: {title}')
subject = subject.format(title=document.title)
mail = email_utils.make_mail(
subject=subject,
text_template='wiki/email/re | viewed.ltxt',
html_template='wiki/email/reviewed.html',
context_vars=c,
from_email=settings.TIDINGS_FROM_ADDRESS,
to_email=user.email)
msgs.append(mail)
for user in [revision.creator, revision.reviewer]:
if hasattr(user, 'profile'):
local... |
NightShadeNeko/HentaiBot | data/__init__.py | Python | mit | 103 | 0 | from .config import | Config, HentaiHavenConfig, HAnimeConfig, Section
from .las | t_entry import LastEntry
|
IvanaXu/Test_Class_GOF | tPatterns/Creational_Patterns/test_Abstract_Factory_Pattern.py | Python | gpl-3.0 | 2,597 | 0.00077 | # -*- coding:utf-8 -*-
| # @auth ivan
# @time 2016-10-14 16:36:15
# @goal | test Abstract Factory Pattern
class Shape:
def __init__(self):
return
def draw(self):
return
# Circle Rectangle Square
class Circle(Shape):
def draw(self):
print("Inside Circle::draw() method.")
class Rectangle(Shape):
def draw(self):
print("Inside Rectangle::draw... |
shakamunyi/tensorflow | tensorflow/python/kernel_tests/iterator_ops_cluster_test.py | Python | apache-2.0 | 4,391 | 0.005693 | # 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... | n(h):
remote_iterator = iterator_ops.Iterator.from_string_handle(
h, dataset_3.output_types, dataset_3.output_shapes)
return remote_iterator.get_next()
with ops.device("/job:worker/replica:0/task:0/cpu:0"):
target_placeholder = array_ops.placeholder(dtypes.string, shape=[])
remote... | target=target_placeholder)
with session.Session(worker[0].target) as sess:
elem = sess.run(
remote_op,
feed_dict={target_placeholder: "/job:worker/replica:0/task:0/cpu:1"})
self.assertEqual(elem, [1])
# Fails when target is cpu:0 where the resource is not located.
... |
Juniper/nova | nova/console/websocketproxy.py | Python | apache-2.0 | 7,594 | 0.000263 | # Copyright (c) 2012 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 ... | # wss which correspond to http and https r | espectively in terms of
# security.
if 'ws' in expected_protos:
expected_protos.append('http')
if 'wss' in expected_protos:
expected_protos.append('https')
return origin_proto in expected_protos
def new_websocket_client(self):
"""Called after a new W... |
Nukesor/spacesurvival | server/app.py | Python | mit | 109 | 0 | """App modul | e. Mainly for debugging purposes."""
from server import create_app
app = create_app('dev | elop')
|
dholm/voidwalker | voidwalker/framework/platform/cpu.py | Python | gpl-3.0 | 3,778 | 0.000265 | # (void)walker hardware platform support
# Copyright (C) 2012-2013 David Holm <dholmster@gmail.com>
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at you... | def get_cpu(self, architecture):
if architecture in self._cpus:
return self._cpus[arch | itecture]
cpu = self._cpu_factory.create_cpu(architecture)
self._cpus[architecture] = cpu
return cpu
def register_cpu(cls):
_cpu_map[cls.architecture()] = cls
return cls
_cpu_map = {}
|
ivelum/djangoql | test_project/core/tests/test_admin.py | Python | mit | 4,169 | 0.00048 | import json
from django.contrib.auth.models import User
from django.test import TestCase
try:
from django.core.urlresolvers import reverse
except ImportError: # Django 2.0
from django.urls import reverse
class DjangoQLAdminTest(TestCase):
def setUp(self):
self.credentials = {'username': 'test'... | book_djangoql_suggestions')
# unauthorized request should be redirected
response = self.c | lient.get(url)
self.assertEqual(302, response.status_code)
# authorize for the next checks
self.assertTrue(self.client.login(**self.credentials))
# field parameter is mandatory
r = self.get_json(url, status=400)
self.assertEqual(r.get('error'), '"field" parameter is requ... |
schulmanworks/pySiteUtils | config.py | Python | gpl-2.0 | 90 | 0.011111 | __author__ | = 'ryan'
WTF_CSRF_ENABLED = True
SECRET_KEY='WmSH67P70mM89PuTMawZE06PWvWH0034' | |
bilke/OpenSG-1.8 | SConsLocal/scons-local-0.96.1/SCons/SConf.py | Python | lgpl-2.1 | 27,625 | 0.007891 | """SCons.SConf
Autoconf-like configuration support.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, ... | an call any tests. After finished with your
tests, be sure to | call the Finish() method, which returns the modified
environment.
Some words about caching: In most cases, it is not necessary to cache
Test results explicitely. Instead, we use the scons dependency checking
mechanism. For example, if one wants to compile a test program
(SConf.TryLink), the compile... |
jquacinella/pyIsbnScanner | scan.py | Python | gpl-2.0 | 317 | 0 | #!/usr/bin/python
import cv
if __name__ == "__main__":
capture = cv.CaptureFromCAM(-1)
cv.NamedWindow("image")
while True:
frame | = cv.QueryFrame(capture)
cv.ShowImage("im | age", frame)
k = cv.WaitKey(10)
if k % 256 == 27:
break
cv.DestroyWindow("image")
|
googleapis/python-grafeas | grafeas/grafeas_v1/types/intoto_provenance.py | Python | apache-2.0 | 7,148 | 0.00056 | # -*- 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... | If true, the builder claims that running the
recipe on materials will produce bit-for-bit
identical output.
"""
build_invocation_id = proto.Field(proto.STRING, number=1,)
build_started_on = proto.Field(
proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp,
... | message=timestamp_pb2.Timestamp,
)
completeness = proto.Field(proto.MESSAGE, number=4, message="Completeness",)
reproducible = proto.Field(proto.BOOL, number=5,)
class BuilderConfig(proto.Message):
r"""
Attributes:
id (str):
"""
id = proto.Field(proto.STRING, number=1,)
class ... |
ngageoint/scale | scale/storage/brokers/broker.py | Python | apache-2.0 | 11,848 | 0.005571 | """Defines the base broker class"""
from abc import ABCMeta
from collections import namedtuple
"""
FileDownload tuple contains an additional partial flag for defining whether the file
is allowed to be accessed directly or must be copied into running container. This is
currently only applicable to the S3Broker and requ... | FileUpload = namedtuple('FileUpload', ['file', 'local_path'])
FileDetails = namedtuple('FileDetails', ['file', 'size'])
class Broker(object):
"""Abstract class for a broker that can download and upload files for a given storage backend
"""
__metaclass__ = ABCMeta
def _ | _init__(self, broker_type):
"""Constructor
:param broker_type: The type of this broker
:type broker_type: string
"""
self._broker_type = broker_type
self._volume = None
@property
def broker_type(self):
"""The type of this broker
:returns: The b... |
DanielSank/observed | observed_test.py | Python | mit | 10,795 | 0.001575 | import itertools
import observed
from observed import observable_function, observable_method
import pytest
def get_caller_name(caller):
"""Find the name of a calling (i.e. observed) object.
Args:
caller: The observed object which is calling an observer.
Returns:
The name of the caller. ... | servable.__name__
elif isinstance(observable, observed.ObservableFunction):
final = observable.__name__
for observer, caller_id in observer_set:
expected_buf.append(get_buff_data(observable, observer, caller_id))
expected_buf.insert(0, final)
| expected_buf.sort()
items.append((observable, observer_set, expected_buf, [final]))
return items
class TestBasics:
"""Test that observers are called when the observed object is called."""
@classmethod
def setup_method(self):
self.buf = []
@classmethod
def teardown_cla... |
PolySlug/polyslug | sons/son.py | Python | mit | 836 | 0.009569 | import pygame
pygame.mixer.init()
sons = []
#Initialisation
def sonSaut():
son = pygame.mixer.Sound('sons/saut.ogg')
son.play()
sons.append(sons)
def sonMort():
son = pygame.mixer.Sound('sons/mort.ogg')
son.play()
sons.append(sons)
def sonBlessureEnnemi():
son = pygame.mixer.Sound('sons... | ns)
def sonBlessureJoueur():
son = pygame.mixer.Sound('sons/blessureJoueur.ogg')
son.play()
sons.append(sons)
def sonTir():
son = pygame.mixer.Sound('sons/tir.ogg')
son.set_volume(0.5)
son.play()
sons.append(sons)
def sonVictoire():
son = pygame.mixer.Sound('sons/victory.ogg')
son... | xer.Sound('sons/checkpoint.ogg')
son.play()
sons.append(sons)
|
nlsdfnbch/bitex | bitex/interfaces/bitfinex.py | Python | mit | 5,442 | 0.000735 | """
http://docs.bitfinex.com/
"""
# Import Built-Ins
import logging
# Import Third-Party
# Import Homebrew
from bitex.api.REST import BitfinexREST
from bitex.api.WSS.bitfinex import BitfinexWSS
from bitex.utils import return_api_response
from bitex.formatters.bitfinex import BtfxFormatter as fmt
# Init Logging Facil... | BitEx Standardized Methods
"""
@return_api_response(fmt.order_book)
def order_book(self, pair, **kwargs):
return self.public_query('b | ook/%s' % pair, params=kwargs)
@return_api_response(fmt.ticker)
def ticker(self, pair, **kwargs):
return self.public_query('pubticker/%s' % pair, params=kwargs)
@return_api_response(fmt.trades)
def trades(self, pair, **kwargs):
return self.public_query('trades/%s' % pair, params=kwargs... |
michalbachowski/pyspd | src/pyspd/__init__.py | Python | mit | 839 | 0 | #!/us | r/bin/env python
# -*- coding: utf-8 -*-
class MountPoint(type):
"""Base mount-poin | t for every plugin.
See: http://martyalchin.com/2008/jan/10/simple-plugin-framework/
"""
def __init__(cls, name, bases, attrs):
if not hasattr(cls, 'plugins'):
# This branch only executes when processing the mount point itself.
# So, since this is a new plugin type, not an ... |
mupif/mupif | mupif/lookuptable.py | Python | lgpl-3.0 | 2,296 | 0.001307 | from . import mupifobject
import Pyro5.api
import typing
import pydantic
from .units import Quantity
from .units import Unit
@Pyro5.api.expose
class LookupTable(mupifobject.MupifObject):
"""
.. automethod:: __init__
"""
def __init__(self, *, metadata={}, **kw):
super().__init__(metadata=met... | ta={}, **kw):
super().__init__(metadata=metadata, **kw)
self.n_records = len(self.data)
self.n_params = len(self.data[0])-1
def _setData(self, data):
if len(data):
len_check = len(data[0])
for record in data:
if len(record) != len_check:
... | alueError("All data must have the same length!")
self.data = data
def evaluate(self, params):
"""
Returns the value for given parameters.
:param: Quantity[] params:
:rtype: Quantity
"""
if len(params) != self.n_params:
raise ValueError("Unexpe... |
eBay/restcommander | play-1.2.4/python/Lib/site-packages/Rpyc/Connection.py | Python | apache-2.0 | 6,944 | 0.003024 | import sys
from Boxing import Box, dump_exception, load_exception
from ModuleNetProxy import RootImporter
from Lib import raise_exception, AttrFrontend
FRAME_REQUEST = 1
FRAME_RESULT = 2
FRAME_EXCEPTION = 3
class Connection(object):
"""
the rpyc connection layer (protocol and APIs). generally speaking, the o... | t in self.sync_replies:
self.serve()
return self.sync_replies.pop(seq)
def async_request(self, callback, handlername, *args):
| """performs an asynchronous (non-blocking) request"""
seq = self.send_request(handlername, *args)
self.async_replies[seq] = callback
#
# root requests (not through NetProxies)
#
def rimport(self, modulename):
"""imports a module by name (as a string)"""
if module... |
Chasego/nie | proj/libdemo/django/mysite/polls/models.py | Python | gpl-3.0 | 910 | 0.003297 | from __future__ import unicode_literals
import datetime
from django.db import models
from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible
# Create your models here.
@python_2_unicode_compatible # only if you need to support Python 2
class Question(models.Model):
questio... | ength=200)
pub_date = models.DateTimeField('date published')
def __str__(self):
return self.question_text
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
@python_2_unicode_compatible # only if you need to support Python 2
class Ch... | eld(max_length=200)
votes = models.IntegerField(default=0)
def __str__(self):
return self.choice_text
|
SekoiaLab/Fastir_Collector | dump/windows8Dump.py | Python | gpl-3.0 | 327 | 0.012232 | from __futu | re__ import unicode_literals
from dump import _Dump
from utils.vss import _VSS
import os
class Windows8Dump(_Dump):
def __init__(self, params):
super(Windows8Dump, self).__init__(params)
self.root_reg = os.path.join(_VSS._get_instance(params)._return_root(), 'Windows\System32\config')
| |
lpakula/django-oscar-paypal | tests/unit/payflow/gateway_tests.py | Python | bsd-3-clause | 3,147 | 0.000953 | from decimal import Decimal as D
from unittest import mock
from django.test import TestCase
from paypal.payflow import gateway
class TestAuthorizeFunction(TestCase):
def test_returns_a_txn_instance(self):
with mock.patch('paypal.gateway.post') as mock_post:
mock_post.return_value = {
... | xpiry_date='0113',
amt=D('10.8000'))
class TestReferenceTransaction(TestCase):
def test_for_smoke(self):
with mock.patch('paypal. | gateway.post') as mock_post:
mock_post.return_value = {
'RESULT': '1',
'RESPMSG': '',
'_raw_request': '',
'_raw_response': '',
'_response_time': 1000
}
gateway.reference_transaction(order_number='12345',
... |
maraujop/django-crispy-forms | crispy_forms/templatetags/crispy_forms_utils.py | Python | mit | 888 | 0 | impo | rt re
from django import template
from django.utils.encoding import force_str
from django.utils.functional import keep_lazy
register = template.Library()
@keep_lazy(str)
def remove_spaces(value):
html = re.sub(r">\s{3,}<", "> <", force_str(value))
return re.sub(r"/><", r"/> <", force_str(html))
class Spec... | alSpacelessNode(template.Node):
def __init__(self, nodelist):
self.nodelist = nodelist
def render(self, context):
return remove_spaces(self.nodelist.render(context).strip())
@register.tag
def specialspaceless(parser, token):
"""
Removes whitespace between HTML tags, and introduces a w... |
greggian/TapdIn | django/templatetags/__init__.py | Python | apache-2.0 | 235 | 0 | from django.conf import | settings
from django.utils import importlib
for a in settings.INSTALLED_APPS:
try:
__path__.extend(importlib.import_module('.templatetags', a).__path__)
except ImportError:
pass | |
aydemir/pardus-magic | openttd-opensfx/actions.py | Python | bsd-3-clause | 419 | 0.011933 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Licensed under the GNU General Public Li | cense, version 3.
# See the file http://www.gnu.org/copyleft/gpl.txt
from pisi.actionsapi import autot | ools
from pisi.actionsapi import pisitools
from pisi.actionsapi import get
#def setup():
def build():
autotools.make()
def install():
autotools.rawInstall("INSTALL_DIR=%s" % get.installDIR() + "/usr/share/openttd/data") |
destijl/grr | grr/lib/flows/general/find.py | Python | apache-2.0 | 4,185 | 0.007407 | #!/usr/bin/env python
# Copyright 2012 Google Inc. All Rights Reserved.
"""Find files on the client."""
import stat
from grr.client.client_actions import searching as searching_actions
from grr.lib import aff4
from grr.lib import flow
from grr.lib.aff4_objects import aff4_grr
from grr.lib.aff4_objects import standard
... | state.received_count += len(responses)
# Exit if we hit the max result count we wanted or we're finished. Note that
# we may exceed the max_results if the iteration yielded too many results,
# we simply will not return to the client for another iteration.
if (self.state.received_count < self.args.max_r... | responses.iterator.State.FINISHED):
self.args.findspec.iterator = responses.iterator
# If we are close to max_results reduce the iterator.
self.args.findspec.iterator.number = min(
self.args.findspec.iterator.number,
self.args.max_results - self.state.received_count)
self... |
boblefrag/lolyx | lolyx/resume/models.py | Python | gpl-3.0 | 1,603 | 0.000624 | # -*- coding: utf-8 -*-
#
# Copyright (c) 2013 Rodolphe Quiédeville <rodolphe@quiedeville.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
#... | _updated = models.DateTimeField(auto_now=True)
def __str__(self):
return self.title
class PeopleRessource(models.Model):
resume = models.ForeignKey(Resume)
website = models.ForeignKey(Website)
login = models.CharField(max_length | =300)
|
cloudpassage-community/halo_api_examples | app/test/unit/test_config_helper.py | Python | bsd-2-clause | 773 | 0 | import os
import sys
import imp
import unittest
# import modules
here_dir = os.path.dirname(os.path.abspath(__file__))
module_name = 'config_helper'
module_path = os.path.join(here_dir, '../../h | alo_api_examples')
sys.path.append(module_path)
fp, pathname, description = imp.find_module(module_name)
config = imp.load_module(module_name, fp, pathname, description)
class TestConfigHelper(unittest.TestCase):
'''
Test the configuration
'''
def set | Up(self):
pass
def test_server_group_config(self):
'''
Test if the variable is set
'''
# error if the configuration is not set
with self.assertRaises(SystemExit):
config.ConfigHelper()
if __name__ == '__main__':
unittest.main()
|
snakecon/AI_Lab | spider/book/book/spiders/comment.py | Python | apache-2.0 | 3,658 | 0.001093 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import string
import random
import book.database as db
from scrapy import Spider
from book.items import Comment
class CommentSpider(Spider):
name = 'comment'
allowed_domains = ['book.douban.com']
books = db.conn.query('SELECT douban_id FROM books WHERE douba... | /span[@class="comment-info"]/a/@href'
matches = response.xpath(regx).extract()
if matches:
comment['douban_user_url'] = matches[0]
else:
comment['douban_user_url'] = ''
return comment
def get_douban_us | er_avatar(self, comment, response):
regx = 'div[@class="avatar"]/a/img/@src'
matches = response.xpath(regx).extract()
if matches:
comment['douban_user_avatar'] = matches[0]
else:
comment['douban_user_avatar'] = ''
return comment
def parse(self, respon... |
GbalsaC/bitnamiP | venv/lib/python2.7/site-packages/gunicorn/workers/async.py | Python | agpl-3.0 | 4,307 | 0.000232 | # -*- coding: utf-8 -
#
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
from datetime import datetime
import errno
import socket
import ssl
import gunicorn.http as http
import gunicorn.http.wsgi as wsgi
import gunicorn.util as util
import gunicorn.workers.base as... | request(self, req)
resp, environ = wsgi.create(req, sock, addr,
listener.getsockname(), self.cfg)
self.nr += 1
if self.alive and self.nr >= self.max_requests:
self.log.info("Autorestarting worker after current request.")
resp.force_... | epalive:
resp.force_close()
respiter = self.wsgi(environ, resp.start_response)
if respiter == ALREADY_HANDLED:
return False
try:
for item in respiter:
resp.write(item)
resp.close()
re... |
ramusus/django-vkontakte-board | settings_test.py | Python | bsd-3-clause | 124 | 0 | INSTALLED_APPS = | (
'vkontakte_places',
'vkontakte_users',
'vkontakte_ | groups',
)
SOCIAL_API_TOKENS_STORAGES = []
|
AusTac/parma | b3/lib/runsnakerun/memdumploader.py | Python | gpl-2.0 | 9,715 | 0.023366 | """Module to load py_mem_dump records into RunSnakeRun
memory_dump:
https://launchpad.net/pymemorydump
Produces memory overviews very similar to the run-time overviews
of cProfile. This module maps the memory-dump information into
the recursive records that RunSnakeRun needs to display properly.
"""
import psta... | current = directories.get( child.directory )
directory, filename = child.directory, child.filename
if current is None:
if directory == '':
current = root
else:
current = PStatLocation( directory, '' )
... | s[ current.key ] = current
directories[ directory ] = current
if filename == '~':
filename = '<built-in>'
file_current = files.get( (directory,filename) )
if file_current is None:
file_current = PStatLocation( directory, filename )
... |
Qwaz/solved-hacking-problem | SCTF/2018 Finals/poly_pkc/problem.py | Python | gpl-2.0 | 2,099 | 0.00667 | from Crypto.Util import number
class PubKey(object):
def __init__(self, poly, order, n):
self.poly = poly
self.order = order
self.N = n
def poly_rand(self):
return [number.getRandomRange(0, self.N) for i in range(0, self.order)]
def poly_mul(self, p, q):
res = [0 ... | 1,order):
fin += pub_poly[i] * pow(t, i, N) % N
fin %= N
pub_poly[0] = N - fin
self.pubKey = PubKey(pub_poly, order, N)
self.privKey = PrivKey(t, N)
key = KeyGenerator( 51, 512 )
with open('flag','r') as fp:
m = int(fp.read().encode('hex'), 16)
with open('enc','w')... |
fp.write('order : %d\n' % key.pubKey.order)
fp.write('public key : %s\n' % str(key.pubKey.poly))
fp.write('N : %d\n' % key.pubKey.N)
fp.write('encrypted message : %s\n' % str(key.pubKey.encrypt(m)))
|
daspecster/google-cloud-python | spanner/unit_tests/test_streamed.py | Python | apache-2.0 | 36,966 | 0 | # Copyright 2016 Google 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 law or a... | lf._makeValue(u'Na')
chunk = self._makeValue(u'N')
merged = streamed._merge_chunk(ch | unk)
self.assertEqual(merged.string_value, u'NaN')
def test__merge_chunk_float64_w_empty(self):
iterator = _MockCancellableIterator()
streamed = self._make_one(iterator)
FIELDS = [
self._makeScalarField('weight', 'FLOAT64'),
]
streamed._metadata = _Result... |
y-usuzumi/survive-the-course | leetcode/10.Regular_Expression_Matching/main.py | Python | bsd-3-clause | 2,097 | 0.000954 | class Solution:
def get_stm(self, p:str) -> dict:
start = {}
idx = 0
l = len(p)
curr_state = start
while idx < l:
ch = p[idx]
if ch in curr_state:
next_state = {}
curr_state[''] = next_state
elif idx+1 < l an... | tms) == 1:
stm, idx = next_stms[0]
continue
else:
for xstm, next_idx in next_stms:
result = self._run_stm(xstm, s, next_idx)
if result:
return True
return False
if '_FIN' ... | n stm:
stm = stm['']
if '_FIN' in stm:
return True
return False
def isMatch(self, s: str, p: str) -> bool:
stm = self.get_stm(p)
return self._run_stm(stm, s, 0)
if __name__ == '__main__':
sol = Solution()
print(sol.isMatch("aa", "a")) # Fa... |
ad-m/claw | claw/quotations.py | Python | apache-2.0 | 13,506 | 0.002519 | # -*- coding: utf-8 -*-
"""
The module's functions operate on message bodies trying to extract
original messages (without quoted messages)
"""
import regex as re
import logging
from copy import deepcopy
from lxml import html, etree
import html2text
from claw.constants import RE_DELIMITER
from claw.utils import rand... | # Norwegian, Swedish
'skrev',
))
))
# Special case for languages where text is translated like this: 'on {date} wrote {somebody}:'
RE_ON_DATE_WROTE_SMB = re.compile(
'(-*[>]?[ ]?({0})[ ].*(.*\n){{0,2}}.*({1})[ ].*:)'.format(
| '|'.join((
# Beginning of the line
# Dutch
'Op',
# German
'Am'
)),
# Ending of the line
'|'.join((
# Dutch
'schreef','verzond','geschreven',
# German
'schrieb'
))
)
... |
samtstern/FirebaseUI-Android | scripts/translations/fix_typography.py | Python | apache-2.0 | 1,375 | 0.001465 | # coding=UTF-8
import sys
from base_string_script import BaseStringScript
BAD_ELLIPSIS = "..."
GOOD_ELLIPSIS = "…"
BAD_ELLIPSIS_SPACING = " …"
GOOD_ELLIPSIS_SPACING = "…"
BAD_SINGLE_QUOTE = "\\\'%1$s\\\'"
BAD_DOUBLE_QUOTE = "\\\"%1$s\\\""
GOOD_DOUBLE_QUOTE = "“%1$s”"
class FixTypographyScript(BaseStringScript):
... | == " " and char == " " and "<" in minimizedWhitespaceLine:
pass
else:
minimizedWhitespaceLine.append(char)
return ''.join(minimizedWhitespaceLine).split("(?!^)")
# Process all files
for file_name in s | ys.argv[1:]:
rnts = FixTypographyScript()
rnts.ProcessFile(file_name)
|
Donkyhotay/MoonPy | zope/app/onlinehelp/onlinehelp.py | Python | gpl-3.0 | 5,638 | 0.000709 | ##############################################################################
#
# Copyright (c) 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SO... | "Help Topic definition %s does not exist" % doc_path
)
if class_ is None:
class_ = OnlineHelpTopic
# Create topic base on the custom class or OnlinHelpTopic
topic = class_(id, title, doc_path, parent_path, interface, view)
# add resources to topic
... | rse(self, parent_path)
parent[id] = topic
except KeyError:
pass
for t in zapi.getUtilitiesFor(IOnlineHelpTopic):
if parent is None:
if t[1].getTopicPath() == parent_path:
t[1][id] = topic
if topic.getTopicPath() == t[1]... |
yuanming-hu/taichi | python/taichi/lang/matrix.py | Python | mit | 54,017 | 0.001296 | import numbers
from collections.abc import Iterable
import numpy as np
from taichi._lib import core as ti_core
from taichi.lang import expr, impl
from taichi.lang import ops as ops_mod
from taichi.lang import runtime_ops
from taichi.lang._ndarray import Ndarray, NdarrayHostAccess
from taichi.lang.common_ops import Tai... | )
if dt is None:
if isinstance(n[0], (int, np.integer)):
dt = impl.get_runtime().default_ip
elif isinstance(n[0], float):
| dt = impl.get_runtime().default_fp
elif isinstance(n[0], expr.Expr):
dt = n[0].ptr.get_ret_type()
if dt == ti_core.DataType_unknown:
raise TypeError(
... |
chubbymaggie/afl-crash-analyzer | AflCrashAnalyzer.py | Python | gpl-3.0 | 9,878 | 0.010225 | #!/usr/bin/env python2.7
'''
AFL crash analyzer, crash triage for the American Fuzzy Lop fuzzer
Copyright (C) 2015 floyd
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 ve... | "[+] disassemble $rip, $rip+16 | :\n"
disassemble $rip, $rip+16
"""
gdb_script_32bit = r"""printf "[+] Disabling verbose and complaints\n"
set verbose off
set complaints 0
printf "[+] Backtrace:\n"
bt
printf "[+] info reg:\n"
info reg
printf "[+] exploitable:\n"
exploitable
printf "[+] disassemble $eip, $eip+16:\n"
disassemble $eip, $eip+16
"""
... |
stephane-martin/salt-debian-packaging | salt-2016.3.3/tests/unit/states/openstack_config_test.py | Python | apache-2.0 | 3,668 | 0.000273 | # -*- coding: utf-8 -*-
'''
:codeauthor: :email:`Jayesh Kariya <jayeshk@saltstack.com>`
'''
# Import Python libs
from __future__ import absolute_import
# Import Salt Testing Libs
from salttesting import skipIf, TestCase
from salttesting.mock import (
NO_MOCK,
NO_MOCK_REASON,
MagicMock,
patch)
from... | has been deleted')
ret.update({'comment': comt, 'changes': {'Value': 'Deleted'}})
self.assertDictEqual(openstack_config.absent(name, filename,
section), ret)
if __name__ == '__main_ | _':
from integration import run_tests
run_tests(OpenstackConfigTestCase, needs_daemon=False)
|
Karaage-Cluster/karaage-debian | karaage/plugins/kgapplications/views/base.py | Python | gpl-3.0 | 12,381 | 0 | # Copyright 2015 VPAC
#
# This file is part of Karaage.
#
# Karaage 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.
#
# Karaage is dist... | LIC METHODS #
##################
def __init__(self):
self._first_state = None
self._states = {}
super(StateMachine, self).__init__()
def add_state(self, state, state_id, actions):
""" Add a state to the list. The first state added becomes the initial
| state. """
self._states[state_id] = state, actions
def set_first_state(self, state_id):
self._first_state = state_id
def get_state(self, application):
if application.state not in self._states:
raise RuntimeError("Invalid state '%s'" % application.state)
state, _ = s... |
Pragmatismo/Pigrow | scripts/gui/test/start_pnl.py | Python | gpl-3.0 | 1,283 | 0.028059 | import wx
class ctrl_pnl(wx.Panel):
#
#
def __init__( self, parent ):
shared_data = parent.shared_data
wx.Panel.__init__ ( self, parent, id = wx.ID_ANY, style = wx.TAB_TRAVERSAL )
self.SetBackgroundColour((100,150,170))
self.l_ip = wx.StaticText(self, label=' Start \n'*5)
... | class info_pnl(wx.Panel):
#
# This displays the welcome message on start up
# this explains how to get started
#
def __init__( self, parent ):
shared_data = parent.shared_data
wx.Panel.__init__ ( self, parent, id = wx.ID_ANY, pos = (285, 0), size = wx.Size( 910,800 ), style = wx... | SE_BACKGROUND, self.OnEraseBackground)
def OnEraseBackground(self, evt):
# yanked from ColourDB.py #then from https://www.blog.pythonlibrary.org/2010/03/18/wxpython-putting-a-background-image-on-a-panel/
dc = evt.GetDC()
if not dc:
dc = wx.ClientDC(self)
rect = self.... |
goelakash/retriever | scripts/vertnet_mammals.py | Python | mit | 10,514 | 0.000476 | # -*- coding: latin-1 -*-
#retriever
"""Retriever script for direct download of vertnet-mammals data"""
from builtins import str
from retriever.lib.models import Table
from retriever.lib.templates import Script
import os
from pkg_resources import parse_version
try:
from retriever.lib.defaults import VERSION
except... | cordingto", ("char",)),
("locationid", ("char",)),
("locationremarks", ("char",)),
("lowestbiostratigraphiczone", ("char",)),
("materialsampleid", ("char",)),
("maximumdepthinmeters", ("char",)),
("maximumdistanceabovesurfaceinmeters", ("char",)),
... | mumelevationinmeters", ("char",)),
("member", ("char",)),
("minimumdepthinmeters", ("char",)),
("minimumdistanceabovesurfaceinmeters", ("char",)),
("minimumelevationinmeters", ("char",)),
("month", ("char",)),
("municipality", ("char",)),
... |
Fokko/incubator-airflow | airflow/contrib/sensors/redis_pub_sub_sensor.py | Python | apache-2.0 | 2,594 | 0.001928 | # -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
#... | edis_conn_id
self.pubsub = RedisHook(redis_conn_id=self.redis_conn_id).get_conn().pubsub()
self.pubsub.subscribe(self.channels)
def poke(self, context):
"""
Check for message on subscribed channels and write to xcom the message with key ``message``
|
An example of message ``{'type': 'message', 'pattern': None, 'channel': b'test', 'data': b'hello'}``
:param context: the context object
:type context: dict
:return: ``True`` if message (with type 'message') is available or ``False`` if not
"""
self.log.info('RedisPubSub... |
google/grr | grr/client/grr_response_client/client_actions/admin.py | Python | apache-2.0 | 11,600 | 0.008103 | #!/usr/bin/env python
"""Client actions related to administrating the client and its configuration."""
import logging
import os
import platform
import socket
import traceback
import cryptography
from cryptography.hazmat.backends import openssl
import pkg_resources
import psutil
import pytsk3
import yara
from grr_res... | "Client.max_post_size",
"Client.max_out_queue",
"Client.poll_min",
"Client.poll_max",
"Client.rss_max"} # pyformat: disable
def _UpdateConfig(self, filtered_arg, config_obj):
for field, value in filtered... | Error, OSError):
pass
def Run(self, arg):
"""Does the actual work."""
try:
if self.grr_worker.client.FleetspeakEnabled():
raise ValueError("Not supported on Fleetspeak enabled clients.")
except AttributeError:
pass
smart_arg = {str(field): value for field, value in arg.item... |
WSCU/crazyflie_ros | src/crazyflie/msg/__init__.py | Python | gpl-2.0 | 102 | 0 | from ._StabData import *
from ._AccelData import *
from | ._MotorData import *
from ._GyroData | import *
|
JRock007/boxxy | dist/Boxxy server.app/Contents/Resources/__boot__.py | Python | mit | 1,863 | 0.008052 | def _reset_sys_path():
# Clear generic sys.path[0]
import sys, os
resources = os.environ['RESOURCEPATH']
while sys.path[0] == resources:
del sys.path[0]
_reset_sys_path()
def _chdir_resource():
import os
os.chdir(os.environ['RESOURCEPATH'])
_chdir_resource()
def _disable_linecache():... | e__ = path
if sys.version_info[0] == 2:
with open(path, 'rU') as fp:
source = fp.read() + "\n"
else:
with open(path, 'rb') as fp:
encoding = guess_encoding(fp)
with open(path, 'r', encoding=encoding) as fp:
source = fp.read() + '\n'
exec(compile(s... | .', 'Frameworks')
dyld.DEFAULT_FRAMEWORK_FALLBACK.insert(0, frameworks)
dyld.DEFAULT_LIBRARY_FALLBACK.insert(0, frameworks)
_setup_ctypes()
DEFAULT_SCRIPT='server.py'
SCRIPT_MAP={}
_run()
|
gdreid/job-salary-prediction | code/models/lasoo.py | Python | gpl-3.0 | 3,087 | 0.006479 | '''
Created on 2013-03-22
@author: Graham Reid
'''
import scipy as sp
import sys
import pickle
from sklearn.linear_model import Lasso
from sklearn.linear_model import LinearRegression
from sklearn.cross_validation import train_test_split
import numpy as np
from scipy.sparse import *
import matplotlib.py... |
plt.pause(0.001)
fig.savefig('../../plots/lasoo_model_' + str(alpha) + '_' + str(error) + '.pdf')
print 'it: ', i, 'average error: ', error, " alpha: ", alpha, " non zero: ", \
np.count_nonzero(coeff)
sys.stdout.flush()
if error < min_error | :
min_error = error
it_since_min = 0
output_path = '../../models/lasoo_model_' + str(alpha) + '_' + str(error) + '.pk'
with open (output_path, 'wb') as output:
pickle.dump(feature_selector, output, pickle.HIGHEST_PROTOCOL)
else :
it_since_min += 1
|
sandeepdsouza93/TensorFlow-15712 | tensorflow/contrib/training/python/training/evaluation.py | Python | apache-2.0 | 21,638 | 0.004437 | # 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 applicable ... | test checkpoint files as they arrive. Stops yielding only
if/when waiting for a checkpoint times out.
"""
checkpoint_path = None
while True:
checkpoint_path = wait_for_new_checkpoint(
checkpoint_dir, checkpoint_path, timeout=timeout)
if checkpoint_path is None:
# timed out
retur | n
start = time.time()
yield checkpoint_path
time_to_next_eval = start + min_interval_secs - time.time()
if time_to_next_e |
plotly/plotly.py | packages/python/plotly/plotly/validators/scattercarpet/_hoverlabel.py | Python | mit | 2,062 | 0.000485 | import _plotly_utils.basevalidators
class HoverlabelValidator(_plotly_utils.basevalidators.CompoundValidator):
def __init__(self, plotly_name="hoverlabel", parent_name="scattercarpet", **kwargs):
super(HoverlabelValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent... | this trace.
bordercolorsrc
Sets the source reference on Chart Studio Cloud
for `bordercolor`.
font
Sets the font used in hover labels.
namelength
Sets the default length (in number of
characters)... | aces. -1 shows the whole name
regardless of length. 0-3 shows the first 0-3
characters, and an integer >3 will show the
whole name if it is less than that many
characters, but if it is longer, will truncate
to `namelength - 3` characters an... |
frnsys/broca | tests/test_tokenize.py | Python | mit | 3,072 | 0 | import unittest
from broca.tokenize import keyword, util, LemmaTokenizer
class KeywordTokenizeTests(unittest.TestCase):
def setUp(self):
self.docs = [
'This cat dog is running happy.',
'This cat dog runs sad.'
]
def test_overkill(self):
expected_t_docs = [
... | og', 'running happy'],
['cat dog runs sad']
]
t_docs = keyword.RAKETokenizer().tokenize(self.docs)
# Order | not necessarily preserved
for i, output in enumerate(t_docs):
self.assertEqual(set(output), set(expected_t_docs[i]))
def test_apriori(self):
expected_t_docs = [
['cat dog'],
['cat dog']
]
t_docs = keyword.AprioriTokenizer().tokenize(self.docs)
... |
t-hey/QGIS-Original | python/plugins/processing/algs/qgis/HubDistanceLines.py | Python | gpl-2.0 | 6,322 | 0.001898 | # -*- coding: utf-8 -*-
"""
***************************************************************************
HubDistanceLines.py
---------------------
Date : May 2010
Copyright : (C) 2010 by Michael Minn
Email : pyqgis at michaelminn dot com
********************... | ]
fields = point_source.fields()
fields.append(QgsField('HubName', QVariant.String))
fields.append(QgsField('HubDist', QVariant.Double))
(sink, dest_id) = self.parameterAsSink(parameters, self.OUTPUT, context,
fields, QgsWkbTypes.LineStrin... | ource.sourceCrs())
index = QgsSpatialIndex(hub_source.getFeatures(QgsFeatureRequest().setSubsetOfAttributes([]).setDestinationCrs(point_source.sourceCrs())))
distance = QgsDistanceArea()
distance.setSourceCrs(point_source.sourceCrs())
distance.setEllipsoid(context.project().ellipsoid()... |
gujiawen/flask_web | venv/lib/python2.7/site-packages/sqlalchemy/sql/__init__.py | Python | mit | 1,109 | 0.000902 | # sql/__init__.py
# Copyright (C) 2005-2013 the SQLAlchemy authors and contributors <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
from .expression import (
Alias,
| ClauseElement,
ColumnCollection,
ColumnElement,
CompoundSelect,
Delete,
FromClause,
Inser | t,
Join,
Select,
Selectable,
TableClause,
Update,
alias,
and_,
asc,
between,
bindparam,
case,
cast,
collate,
column,
delete,
desc,
distinct,
except_,
except_all,
exists,
extract,
false,
func,
insert,
intersect,
inter... |
grafgustav/accessmail | src/GUI/EmailItem.py | Python | mit | 3,341 | 0.003592 | __author__ = 'grafgustav'
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import StringProperty, ObjectProperty, BooleanProperty
from kivy.uix.popup import Popup
from src.database import Database
from src.Controller.CommunicationContr | oller import CommunicationController
from kivy.graphics import Color
import string
Builder.load_file("GUI/EmailItem.kv")
Builder.load_file("GUI/deletePopup.kv")
class EmailItem(BoxLayout):
"""
This class manages the corresponding controller level for e-mails. Single e-mails c | an be displayed in
the inbox and in the outbox. The necessary data is transferred through the email parameter.
:param email: The email to be displayed.
:param kwargs:
"""
display_name = StringProperty()
subject = StringProperty()
root = ObjectProperty()
oMail = ObjectProperty()
grey... |
ibm-watson-iot/iot-python | src/wiotp/sdk/api/lec/__init__.py | Python | epl-1.0 | 2,624 | 0.003049 | # *****************************************************************************
# Copyright (c) 2018 IBM Corporation and other Contributors.
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0
# which accompanies this distribution,... | not set(["deviceId", "typeId", "eventId", "format", "timestamp", "payload"]).issubset(kwargs):
raise Exception("Missing required attributes to construct a LastEvent object")
dict.__init__(self, **kwargs)
@property
def typeId(self):
return self["typeId"]
@property
def devic... | at"]
@property
def timestamp(self):
return iso8601.parse_date(self["timestamp"])
@property
def payload(self):
return self["payload"]
class LEC:
def __init__(self, apiClient):
self._apiClient = apiClient
def get(self, deviceUid, eventId):
"""
Retrieves... |
mvaled/sentry | src/sentry/api/endpoints/group_tombstone_details.py | Python | bsd-3-clause | 1,278 | 0.002347 | from __future__ import absolute_import
from rest_framework.response import Response
from sentry.api.bases import ProjectEndpoint
from sentry.api.exceptions import ResourceDoesNotExist
from sentry.models import GroupHash, GroupTombst | one
class GroupTombstoneDetailsEndpoint( | ProjectEndpoint):
def delete(self, request, project, tombstone_id):
"""
Remove a GroupTombstone
```````````````````````
Undiscards a group such that new events in that group will be captured.
This does not restore any previous data.
:pparam string organization_slug:... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.