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 |
|---|---|---|---|---|---|---|---|---|
zheguang/voltdb | lib/python/voltcli/voltdb.d/recover.py | Python | agpl-3.0 | 1,849 | 0.002163 | # This file is part of VoltDB.
# Copyright (C) 2008-2014 VoltDB Inc.
#
# This file contains original code and/or modifications of original code.
# Any modifications made by VoltDB Inc. are licensed under the following
# terms and conditions:
#
# Permission is hereby granted, free of charge, to any person obtaining
# a... | SS OR IMPL | IED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWA... |
akkana/pi-zero-w-book | tempsensors/Si7021.py | Python | gpl-2.0 | 3,216 | 0.004042 | #!/usr/bin/env python
# Read temperature and humidity from an Si7021 using I2C on a Raspberry Pi.
# smbus doesn't work for this chip, so try direct I/O to the device.
import time
import array
import io
import fcntl
class Si7021:
ADDRESS = 0x40
I2C_SLAVE=0x0703
READ_TEMP_HOLD = "\xE3"
READ_TEMP_NOHOLD... | bus):
# Open the I2C bus:
self.fread = io.open("/dev/i2c-%d" % bus, "rb", buffering=0)
self.fwrite = io.open("/dev/i2c-%d" % bus, "wb", buffering=0)
# initialize the device as a slave:
fcntl.ioctl(self.fread, self.I2C_SLAVE, self.ADDRESS)
fcntl.ioctl(self.fwrite, self.I... | .close()
self.fwrite.close()
def readI2C(self, cmd):
# These give errors:
# data = self.bus.read_i2c_block_data(self.address, cmd)
# word = self.bus.read_word_data(self.address, cmd)
# This works to read the first byte,
# but the second byte read is just a repeat of ... |
CGATOxford/CGATPipelines | CGATPipelines/pipeline_docs/pipeline_cpg/trackers/macs_intervals.py | Python | mit | 5,417 | 0.001661 |
from CGATReport.Tracker import *
from cpgReport import *
##########################################################################
class IntervalsSummary(cpgTracker):
"""Summary stats of intervals called by the peak finder. """
mPattern = "_macs_intervals$"
def __call__(self, track, slice=None):
... | #####################
##########################################################################
class PeakLocation(cpgTracker):
mPattern = "_macs_merged_intervals$"
def __call__(self, track, slice=None):
data1 = self.getValues(
"SELECT (PeakCenter - start) / CAST( Length as FLOAT) - 0.5 ... | merged_intervals" % locals())
return {"distance": data1 + data2}
##########################################################################
class PeakDistance(cpgTracker):
mPattern = "_macs_merged_intervals$"
def __call__(self, track, slice=None):
data1 = self.getValues(
"SELECT ... |
jamesyli/solum | solum/common/exception.py | Python | apache-2.0 | 6,153 | 0.000325 | # Copyright 2013 - Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses | /LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, 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 th... | um-type exceptions.
"""
import functools
import pecan
import sys
from keystoneclient import exceptions as keystone_exceptions
from oslo.config import cfg
import six
import wsme
from solum.common import safe_utils
from solum.openstack.common import excutils
from solum.openstack.common.gettextutils import _
from solu... |
nschank/latexml | stringutil.py | Python | mit | 2,656 | 0.00753 | # import re
# COMMENT_PATERN = re.compile("([^\\\\])%.*($)", flags=re.MULTILINE)
# REDACT = "%"
# COMMENT_REPLACE = "\\1{}\\2".format(REDACT)
# def strip_comments(document_contents):
# return COMMENT_PATERN.sub(COMMENT_REPLACE, document_contents)
import strip_comm | ents
def strip_latex_comments(document_contents):
return strip_comments.strip_c | omments(document_contents)
test1in = """% Some comment
% Comment w/ escaped percent sign: \%
%%% Comment starting w/ multiple percents
Here's some math: $3 + 3 = 6$ % and here's a comment
% Yes.
Look a percent sign: \\%. Isn't it great?
Hard newline then comment: \\\\%this is a comment.
% p break:
\\begin{verbatim}%
... |
delmic/odemis | src/odemis/gui/test/comp_grid_test.py | Python | gpl-2.0 | 6,048 | 0.002481 | #-*- coding: utf-8 -*-
"""
.. codeauthor:: Rinze de Laat <delaat@delmic.com>
Copyright © 2014-2018 Rinze de Laat, Éric Piel, Delmic
This file is part of Odemis.
.. license::
Odemis is free software: you can redistribute it and/or modify it under the
terms of the GNU General Public License version 2 as publi... | p.hide_viewport(self.frame.blue)
gui_loop(0.2)
self.assertEqual(self.frame.purple.Size, (gp | .grid_layout.bl.size.x, csize.y))
self.assertEqual(self.frame.brown.Size, (gp.grid_layout.br.size.x, csize.y))
gp.show_viewport(self.frame.red)
gp.show_viewport(self.frame.blue)
# Hide right
gp.hide_viewport(self.frame.blue)
gp.hide_viewport(self.frame.brown)
gui... |
PairMhai/Backend | catalog/migrations/0002_image.py | Python | agpl-3.0 | 861 | 0.002323 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-09-24 11:06
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('catalog', '0001_initial'),
]
operations = [
... | ('name', models.CharField(max_length=50)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('material_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='catalog.Material')),
],... | ),
]
|
dufferzafar/picard | picard/coverart/providers/whitelist.py | Python | gpl-2.0 | 1,878 | 0.000533 | # -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
# Copyright (C) 2007 Oliver Charles
# Copyright (C) 2007-2011 Philipp Wolfer
# Copyright (C) 2007, 2010, 2011 Lukáš Lalinský
# Copyright (C) 2011 Michael Wiencek
# Copyright (C) 2011-2012 Wieland Hoffmann
# Copyright (C) 2013-2014 Laurent Monin
... | CoverArtProvider):
"""Use cover art link and has_cover_art_at MusicBrainz relationships to get
cover art"""
NAME = "Whitelist"
TITLE = N_(u'Whitelist')
def enabled(self):
return (super(CoverArtProviderWhitelist, self).enabled()
and not self.coverart.front_image_found)
... | es(self):
self.match_url_relations(('cover art link', 'has_cover_art_at'),
self._queue_from_whitelist)
return CoverArtProvider.FINISHED
def _queue_from_whitelist(self, url):
log.debug("Found cover art link in whitelist")
self.queue_put(CoverArtImage(... |
Aravinthu/odoo | addons/stock/__init__.py | Python | agpl-3.0 | 188 | 0.005319 | # -*- coding: utf-8 -*-
# Part of Odoo. See LI | CENSE file for full copyright and licensing details.
from . import controllers
from . import models
from . import report
from . impor | t wizard |
runfalk/stormspans | stormspans/tests/test_database.py | Python | mit | 10,294 | 0.001651 | from datetime import date, datetime, timedelta
from os import environ
from psycopg2 import ProgrammingError
from spans import *
from storm.expr import State
from storm.locals import *
from storm.variables impo | rt ListVariable
from unittest import TestCase, skipUnless
from .. import *
from ..database import install_range
from ..expr import *
from ..properties import RangeProperty
from ..variables import \
RangeVariable, \
IntRangeVariable, \
FloatRangeVariable, \
DateRangeVariable, \
DateTimeRangeVariable... | ipping database tests")
class TestDatabase(TestCase):
def setUp(self):
self.store = Store(create_database(environ["STORM_POSTGRES_URI"]))
self.create_tables()
self.fill_data()
self.store.commit()
def tearDown(self):
self.store.rollback()
self.drop_tables()
... |
aforren1/toon | demos/animation.py | Python | mit | 2,742 | 0.001094 | from timeit import default_timer
from psychopy import core, event, visual
from psychopy.visual.rect import Rect
from toon.anim.easing import (ELASTIC_IN_OUT, SMOOTHERSTEP, SMOOTHSTEP,
EXPONENTIAL_OUT, LINEAR)
from toon.anim.interpolators import SELECT, LERP
from toon.anim import Track
fr... | ck([(0.0, 0.6),
(0.4, 0.2),
(1.4, 1),
(2.6, -0.2),
(4.0, 0)], easing=EXPONENTIAL_OUT)
# easing doesn't matter here
col2_track = Track([(0, 'black'),
(1.25, 'blue'),
(2.5, 'green'),
... | pos=(-0.3, 0.3), fillColor='red',
edges=8)
elas_cir = visual.Circle(win, radius=0.1,
pos=(-0.3, 0), fillColor=[1, 1, 1],
edges=8)
expand_rect = visual.Rect(win, width=0.1, height=0.15,
pos=(0, -0.3), fil... |
mitdbg/modeldb | client/verta/docs/conf.py | Python | mit | 6,368 | 0.000157 | # -*- coding: utf-8 -*-
# pylint: skip-file
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup ----------------------------------------... | ]
source_suffix = '.rst'
# The master toctree document.
master_doc = 'index'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for ... | f patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# The name of the Pygments (syntax highlighting) style to use.
pygments_style =... |
nynguyen/sprint_zero_demo | main/filesAndForms/migrations/0003_auto_20150322_1638.py | Python | mit | 763 | 0.001311 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import datetime
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('filesAndForms', '0002_inputfile_next_one'),
]
operations = [
migration... | 'name',
field=models.CharField(default=datetime.datetime(2015, 3, 22, 20, 38, 56, 580815, tzinfo=utc), max_length=100),
preserve_default=False,
),
migrations.AddField(
model_name='inputfile',
name='privacy',
| field=models.BooleanField(default=False),
preserve_default=True,
),
]
|
X-DataInitiative/tick | tick/hawkes/model/base/__init__.py | Python | bsd-3-clause | 90 | 0 | # | License: BSD 3 clause
from .model_hawkes import ModelHawkes
__all__ = ["ModelHawkes"]
| |
olemb/dbfread | dbfread/struct_parser.py | Python | mit | 1,188 | 0 | """
Parser that converts (C style) binary structs named tuples.
The struct can be read from a file or a byte string.
"""
import struct
def _make_struct_class(name, names):
class Struct(object):
_names = names
def __init__(self, **kwargs):
vars(self).update(kwargs)
def __rep... | )'.format(self.__class__.__n | ame__, fields)
Struct.__name__ = name
return Struct
class StructParser:
def __init__(self, name, format, names):
self.format = format
self.names = names
self.struct = struct.Struct(format)
self.Class = _make_struct_class(name, names)
self.size = self.struct.size
... |
chenders/deadonfilm | bin/fill_db.py | Python | mit | 2,449 | 0.000408 | #!/usr/bin/env python3
import requests
from tqdm import tqdm
import zlib
import csv
import os.path
import psycopg2.extras
from urllib.parse import urlparse
DOWNLOAD_URL = "https://datasets.imdbws.com/name.basics.tsv.gz"
OUTPUT_FILENAME = "name.basics.tsv"
DB_URL = urlparse(os.environ.get("IMDB_DB", "postgresql://local... | h, name)
VALUES
(%s, %s, %s, %s)
ON CONFLICT (person_id) DO NOTHING """,
| (
(
row["nconst"].replace("nm", ""),
row["birthYear"],
row["deathYear"],
row["primaryName"],
)
),
)
os.remove(OUTPUT_... |
woojing/pairgramming | dj_backend/sock_serv.py | Python | mit | 5,135 | 0.004284 | # -*- coding: utf-8 -*-
"""
Simple sockjs-tornado chat application. By default will listen on port 8080.
"""
import sys
import os
import json
from urllib import urlencode
import tornado.ioloop
import tornado.web
from tornado import gen
from tornado.httpclient import AsyncHTTPClient
import sockjs.tornado
sys.path.... | ND = 'http://localhost:8000'
try:
from .local_sock_settings import *
except ImportError:
pass
class IndexHandler(tornado.web.RequestHandler):
"""Regular HTTP handler to serve the chatroom page"""
def get(self):
self.render('index.html')
class ChatConnection(s | ockjs.tornado.SockJSConnection):
"""Chat connection implementation"""
session_blocks = dict()
session_code_storage = dict()
http_client = AsyncHTTPClient()
def on_open(self, info):
self.joined_session = []
@gen.coroutine
def on_message(self, message):
recv_data = json.loads... |
ashang/calibre | src/calibre/ebooks/docx/settings.py | Python | gpl-3.0 | 670 | 0.004478 | #!/usr/bin/env python2
# vim:fileencoding=utf-8
from __future__ import (unicode_literals, division, absolute_import,
print_function)
__license__ = 'GPL v3'
__copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>' |
class Settings(object):
def __init__(self, namespace):
self.default_tab_stop = 720 / 20
self.namespace = namespace
def __call__(self, root):
for dts in self.namespace.XPath('//w | :defaultTabStop[@w:val]')(root):
try:
self.default_tab_stop = int(self.namespace.get(dts, 'w:val')) / 20
except (ValueError, TypeError, AttributeError):
pass
|
dimagi/commcare-hq | corehq/motech/tests/test_api_settings_migration.py | Python | bsd-3-clause | 1,111 | 0 | from django.test import TestCase
from corehq.motech.const import OAUTH2_PWD
from corehq.motech.models import ConnectionSettings
from corehq.motech.utils import copy_api_auth_settings
class TestApiSettingsMigration(TestCase):
username = 'terry'
password = 'wafer-thin_mint'
def setUp(self):
self.c... | dmin@example.com',
api_auth_settings='dhis2_auth_settings',
)
self.connx_dhis2.plaintext_password = self.password
self.connx_dhis2.save | ()
def test_dhis2_connection_updated(self):
copy_api_auth_settings(self.connx_dhis2)
self.assertEqual(
self.connx_dhis2.token_url,
"https://restaurant.fr/api/uaa/oauth/token"
)
self.assertEqual(
self.connx_dhis2.refresh_url,
"https://r... |
hlin117/statsmodels | statsmodels/tools/tests/test_pca.py | Python | bsd-3-clause | 13,934 | 0.000215 | from __future__ import print_function, division
from unittest import TestCase
import warnings
import numpy as np
from numpy.testing import assert_allclose, assert_equal, assert_raises
from numpy.testing.decorators import skipif
import pandas as pd
try:
import matplotlib.pyplot as plt
missing_matplotlib = Fal... | ot(pc.coeff) + x.mean | (0), x)
assert_allclose(np.abs(pc.coeff), np.abs(ref.coef.T))
assert_allclose(pc.factors.dot(pc.coeff),
ref.factors.dot(ref.coef.T))
pc = PCA(x[:20], normalize=False, standardize=False)
mu = x[:20].mean(0)
ref = princomp2
assert_allclose(np.abs(pc... |
missionpinball/mpf | mpf/platforms/fadecandy.py | Python | mit | 4,250 | 0.001882 | """Contains code for an FadeCandy hardware for RGB LEDs."""
from typing import List
import logging
import json
import struct
from mpf.core.utility_functions import Util
from mpf.platforms.openpixel import OpenPixelClient
from mpf.platforms.openpixel import OpenpixelHardwarePlatform
MYPY = False
if MYPY: # pragma: ... | FadeCandy hardware interface.")
def __repr__(self):
"""Return string representation."""
return '<Platform.FadeCandy>'
async def _setup_opc_client(self):
self.opc_client = FadeCandyOPClient(self.machine, self.machine.c | onfig['open_pixel_control'])
await self.opc_client.connect()
class FadeCandyOPClient(OpenPixelClient):
"""Base class of an OPC client which connects to a FadeCandy server.
This class implements some FadeCandy-specific features that are not
available with generic OPC implementations.
"""
... |
snnn/tensorflow | tensorflow/python/data/experimental/kernel_tests/serialization/dataset_serialization_test_base.py | Python | apache-2.0 | 25,450 | 0.004283 | # 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... | rify_init_before_res | tore(
ds_fn1, num_outputs, sparse_tensors=sparse_tensors)
self.verify_multiple_breaks(
ds_fn1, num_outputs, sparse_tensors=sparse_tensors)
self.verify_reset_restored_iterator(
ds_fn1, num_outputs, sparse_tensors=sparse_tensors)
self.verify_restore_in_empty_graph(
ds_fn1, num_... |
beav/pulp | server/test/unit/test_content_catalog_manager.py | Python | gpl-2.0 | 8,951 | 0.000112 | # Copyright (c) 2013 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public
# License as published by the Free Software Foundation; either version
# 2 of the License (GPLv2) or (at your option) any later version.
# There is NO WARRANTY for this software, express or implied,
# including the impl... | y, url in units:
manager.add_entry(SOURCE_ID, EXPIRATION, TYPE_ID, unit_key, url)
collection = ContentCatalog.get_collection()
self.assertEqual(len(units), c | ollection.find().count())
for unit_key, url in units:
locator = ContentCatalog.get_locator(TYPE_ID, unit_key)
entry = collection.find_one({'locator': locator})
self.assertEqual(entry['type_id'], TYPE_ID)
self.assertEqual(entry['unit_key'], unit_key)
se... |
DailyActie/Surrogate-Model | 01-codes/scikit-learn-master/sklearn/metrics/__init__.py | Python | mit | 3,388 | 0 | """
The :mod:`sklearn.metrics` module includes score functions, performance metrics
and pairwise metrics and distance computations.
"""
from . import cluster
from .classification import accuracy_score
from .classification import brier_score_loss
from .classification import classification_report
from .classification im... | adjusted_ | rand_score
from .cluster import completeness_score
from .cluster import consensus_score
from .cluster import homogeneity_completeness_v_measure
from .cluster import homogeneity_score
from .cluster import mutual_info_score
from .cluster import normalized_mutual_info_score
from .cluster import silhouette_samples
from .cl... |
qusp/orange3 | Orange/widgets/evaluate/owrocanalysis.py | Python | bsd-2-clause | 27,533 | 0.000472 | """
ROC Analysis Widget
--------------- | ----
"""
import operator
from functools import reduce, wraps
from collections import namedtuple, deque
import numpy
import sklearn.metrics as skl_metrics
from PyQt4 import QtGui
from PyQt4.QtGui import QColor, QPen, QBrush
from PyQt4.QtCore import Qt
import pyqtgraph as pg
import Orange
from Orange.widgets import wi... | curve
ROCPoints = namedtuple(
"ROCPoints",
["fpr", # (N,) array of false positive rate coordinates (ascending)
"tpr", # (N,) array of true positive rate coordinates
"thresholds" # (N,) array of thresholds (in descending order)
]
)
ROCPoints.is_valid = property(lambda self: self.fp... |
open-mmlab/mmdetection | configs/nas_fcos/nas_fcos_fcoshead_r50_caffe_fpn_gn-head_4x4_1x_coco.py | Python | apache-2.0 | 3,012 | 0 | _base_ = [
'../_base_/datasets/coco_detection.py',
'../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py'
]
model = dict(
type='NASFCOS',
backbone=dict(
type='ResNet',
depth=50,
num_stages=4,
out_indices=(0, 1, 2, 3),
frozen_stages=1,
norm_c... | n2/resnet50_caffe')),
neck=dict(
type='NASFCOS_FPN',
in_channels=[256, 512, 1024, 2048],
out_channels=256,
start_level=1,
add_extra_convs=True,
num_outs=5,
norm_cfg=dict(type='BN'),
conv_cfg=dict(type='DCNv2', deform_groups=2)),
bbox_head=dict(
... | strides=[8, 16, 32, 64, 128],
norm_cfg=dict(type='GN', num_groups=32),
loss_cls=dict(
type='FocalLoss',
use_sigmoid=True,
gamma=2.0,
alpha=0.25,
loss_weight=1.0),
loss_bbox=dict(type='IoULoss', loss_weight=1.0),
loss_centern... |
nens/raster-tools | raster_tools/roundd.py | Python | gpl-3.0 | 2,683 | 0 | # (c) Nelen & Schuurmans. GPL licensed, see LICENSE.rst.
# -*- coding: utf-8 -*-
"""
Round raster to set decimals.
"""
from os.path import dirname, exists
import argparse
import os
from osgeo import gdal
import numpy as np
from raster_tools import datasets
# output driver and optinos
DRIVER = gdal.GetDriverByName('g... | ound(decimals)
def save(self):
""" Save. """
# prepare dirs
subdir = dirname(self.target_path)
if subdir:
os.makedirs(subdir, exist_ok=True)
# write tiff
array = self.target[np.newaxis]
with datasets.D | ataset(array, **self.kwargs) as dataset:
DRIVER.CreateCopy(self.target_path, dataset, options=OPTIONS)
def roundd(source_path, target_path, decimals):
""" Round decimals. """
# skip existing
if exists(target_path):
print('{} skipped.'.format(target_path))
return
# skip whe... |
jaantollander/CrowdDynamics | scripts/debug.py | Python | gpl-3.0 | 407 | 0 | import os
from crowddynamics.examples.collective_motion import FourExits
from crowddyna | mics.simulation.agents import ThreeCircle, Circular
if __name | __ == '__main__':
# os.environ.update(NUMBA_DISABLE_JIT='1')
simulation = FourExits(agent_type=Circular)
simulation.update()
simulation.update()
simulation.update()
simulation.update()
simulation.update()
simulation.update()
|
olduvaihand/ProjectEuler | src/python/problem416.py | Python | mit | 878 | 0.002283 | # -*- coding: utf-8 -*-
# ProjectEuler/src/python/problem416.py
#
# A frog's trip
# =============
# Published on Saturday, 23rd February 2013, 01:00 pm
#
# A row of n squares contains a frog in the leftmost square. By successive
# jumps the frog goes to the rightmost square and then back to the leftmost
# square. On t... | ip he jumps one, two or three squares to the right,
# and on the homeward trip he jumps to the left in a similar manner. He cannot
# jump outside the squares. He repeats the round-trip travel m times. Let F(m,
# n) be the number of the ways the frog can travel so that at most one s | quare
# remains unvisited. For example, F(1, 3) = 4, F(1, 4) = 15, F(1, 5) = 46,
# F(2, 3) = 16 and F(2, 100) mod 109 = 429619151. Find the last 9 digits of
# F(10, 1012).
import projecteuler as pe
def main():
pass
if __name__ == "__main__":
main()
|
hclivess/Stallion | nuitka/Cryptodome/Hash/SHA3_224.py | Python | gpl-3.0 | 5,302 | 0.001886 | # -*- coding: utf-8 -*-
#
# ===================================================================
# The contents of this file are dedicated to the public domain. To
# the extent that dedication to the public domain is not available,
# everyone is granted a worldwide, perpetual, royalty-free,
# non-exclusive license to e... | func:`new` function.
:iv | ar oid: ASN.1 Object ID
:vartype oid: string
:ivar digest_size: the size in bytes of the resulting hash
:vartype digest_size: integer
"""
# The size of the resulting hash in bytes.
digest_size = 28
# ASN.1 Object ID
oid = "2.16.840.1.101.3.4.2.7"
def __init__(self, data, update_a... |
swannobi/Red-DiscordBot | cogs/utils/sync.py | Python | gpl-3.0 | 1,715 | 0.002332 | import io
try:
import requests
except ImportError:
print("Requests module not installed, sync functions unavailable!")
class ResponseError(BaseException):
pass
class Route:
def __init__(self, base_url, path, cdn_url=None, method="GET", headers=None):
self.base_url = base_url
self.path... | ests.get(self.cdn_url+self.cdn_path)
if 200 <= res | .status_code < 300:
return io.BytesIO(res.content)
else:
raise ResponseError(
"Expected a status code 200-299, got {}"
.format(res.status_code))
def __call__(self):
return self.sync_download()
|
Ganonmaster/sfm-scripts | Met/JapoShit.py | Python | mit | 5,997 | 0.02979 | import bpy
from bpy import context
import string
print("START")
myObject = bpy.context.object
try:
myArmature = myObject.modifiers["Armature"].object.data #Doesn't work if your Armature modifier isn't named Armature. I don't think I care.
except KeyError:
print("Error: Armature is not named 'Armature'.... | Count = myObject.active_shape_key_index
myObject.active_shape_key_index = selectedSK
def skCount(): #counts the number of shapekeys on the mesh.
curIndex = myObject.active_shape_key_index #saving the old index
count = 0
myObject.acti... | ile shapekey isn't a NoneType(so it exists)
count+=1
myObject.active_shape_key_index+=1
myObject.active_shape_key_index = curIndex #setting it back to the old index
return count
removables = []
def newFlex(i1, i2, skName): #combine... |
WZQ1397/automatic-repo | project/excel/excel_read.py | Python | lgpl-3.0 | 633 | 0.007181 | # -*- conding:utf-8 -*-
__author__ = 'mayi'
# How to read from an Excel using xlrd module
import xlrd
| xls_file = "name.xls"
book = xlrd.open_workbook(xls_file)
sheet1 = book.sheet_by_index(0)
# # 获得指定索引的sheet名
# sheet1_name = book.sheet_names()[0]
# print(sheet1_name)
# # 通过sheet名字获得sheet对象
# sheet1 = book.sheet_by_name(sheet1_name)
# 获得行数和列数
# 总行数
nrows = sheet1.nrows
#总列数
| ncols = sheet1.ncols
# 遍历打印表中的内容
for i in range(nrows):
for j in range(ncols):
cell_value = sheet1.cell_value(i, j)
print(cell_value, end = "\t")
print("") |
mikel-egana-aranguren/SADI-Galaxy-Docker | galaxy-dist/eggs/bx_python-0.7.2-py2.7-linux-x86_64-ucs4.egg/EGG-INFO/scripts/wiggle_to_binned_array.py | Python | gpl-3.0 | 1,461 | 0.020534 | #!/afs/bx.psu.edu/project/pythons/py2.7-linux-x86_64-ucs4/bin/python2.7
"""
Convert wiggle data to a binned array. This assumes | the input data is on a
single chromosome and does no sanity checks!
usage: %prog score_fil | e out_file < wiggle_data
-c, --comp=type: compression type (none, zlib, lzo)
"""
from __future__ import division
import sys
import psyco_full
import bx.wiggle
from bx.binned_array import BinnedArray
from bx_extras.fpconst import isNaN
from bx.cookbook import doc_optparse
from bx import misc
def main():
... |
iceflow/aws-demo | sns/sns.py | Python | gpl-3.0 | 1,021 | 0.019589 | #!/usr/bin/python
# -*- coding: utf8 -*-
from pprint import pprint
import sys,os
import random
import json
import gzip
import random
import boto3
se | ssion = boto3.Session(
| region_name='cn-north-1',
aws_access_key_id='xxxxxxxxxxxxxx',
aws_secret_access_key='xxxxxxxxxxxxxxxxxxxxxx'
)
sns = session.resource('sns')
sns_client = session.client('sns')
A=sns.create_topic(Name='abc').arn
#print(A)
#res = sns_client.list_topics()
#pprint(res)
#message={"create-time":"2019-04-23-1... |
pybuilder/pybuilder | src/unittest/python/ci_server_interaction_tests.py | Python | apache-2.0 | 4,938 | 0.002025 | # -*- coding: utf-8 -*-
#
# This file is part of PyBuilder
#
# Copyright 2011-2020 PyBuilder Team
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/l... | Y_VERSION": "1.0.0"}
self.project.set_property('__running_coverage', True)
proxy = test_proxy_for(self.project)
self.assertEqual(type(proxy), TestProxy)
def test_should_use_default_proxy_if_teamcity_in_environment_and_project_property_is_set_but_coverage_is_running(self):
self.moc... | = {"TEAMCITY_VERSION": "1.0.0"}
self.project.set_property('teamcity_output', True)
self.project.set_property('__running_coverage', True)
proxy = test_proxy_for(self.project)
self.assertEqual(type(proxy), TestProxy)
class TeamCityProxyTests(unittest.TestCase):
@patch('pybuilder.... |
ahuarte47/QGIS | python/plugins/processing/algs/qgis/SpatialJoin.py | Python | gpl-2.0 | 12,871 | 0.003574 | # -*- coding: utf-8 -*-
"""
***************************************************************************
SpatialJoin.py
---------------------
Date : October 2013
Copyright : (C) 2013 by Joshua Arnott
Email : josh at snorfalorpagus dot net
*******************... | self.tr('Discard records which could not be joined'),
defaultValue=False))
self.addParameter(Qg | sProcessingParameterString(self.PREFIX,
self.tr('Joined field prefix'), optional=True))
self.addParameter(QgsProcessingParameterFeatureSink(self.OUTPUT,
self.tr('Joined layer'),
... |
elopio/snapcraft | snapcraft/plugins/plainbox_provider.py | Python | gpl-3.0 | 3,098 | 0 | # -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright (C) 2016-2017 Canonical Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in ... | def build(self):
super().build()
env = os.environ.copy()
# Ensure the first provider does not attempt to validate against
# providers installed on the build host by initialising PROVIDERPATH
# to empty
env['PROVIDERPATH'] = ''
provider_stage_dir = os.path.joi... | for provider in os.listdir(provider_stage_dir)]
env['PROVIDERPATH'] = ':'.join(provider_dirs)
self.run(['python3', 'manage.py', 'validate'], env=env)
self.run(['python3', 'manage.py', 'build'])
self.run(['python3', 'manage.py', 'i18n'])
self.run([
... |
hecchi777/S3-SlaacSecuritySolution | impacket-0.9.11/examples/smbrelayx.py | Python | apache-2.0 | 29,341 | 0.009373 | #!/usr/bin/python
# Copyright (c) 2013 CORE Security Technologies
#
# This software is provided under under a slightly modified version
# of the Apache Software License. See the accompanying LICENSE file
# for more information.
#
# $Id: smbrelayx.py 772 2013-07-05 22:25:53Z bethus@gmail.com $
#
# SMB Relay Module
#
# A... | = 2
sessionSetup['Parameters']['VcNumber'] = 1
sessionSetup['Parameters']['SessionKey'] = 0
sessionSetup['Parameters']['Capabilities'] = SMB.CAP_EXTENDED_SECURITY | SMB.CAP_USE_NT_ERRORS | SMB.CAP_UNICODE
# Let's build a NegTokenInit with the NTLMSSP
... | e different providers
blob = SPNEGO_NegTokenInit()
# NTLMSSP
blob['MechTypes'] = [TypesMech['NTLMSSP - Microsoft NTLM Security Support Provider']]
blob['MechToken'] = str(negotiateMessage)
sessionSetup['Parameters']['SecurityBlobLength'] = len(blob)
sessionSetup['Par... |
rf3Studios/anatomy_calc_python | anatomy_calc/lec_func.py | Python | mit | 4,209 | 0.002613 | """
The MIT License (MIT)
Copyright (c)2013 Rich Friedel
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, ... | am, lec_quizzes):
#TODO Finish writing documentation for this function
"""
@todo Write documentation for this function
@param lec_exams: List of the exam grades
@param final_exam: The final exam score
@param lec_quizzes: List of quiz grades
@return: A float of the processed values
"""
... | final_exam)) * 0.75 |
pixeltasim/IRCBot-Pixeltasim | plugins/author.py | Python | unlicense | 2,861 | 0.034254 | from whiffle import wikidotapi
from util import hook
@hook.command
def author(inp):
".author <Author Name> -- Will return details regarding the author"
if firstrefresh == 0:#make sure the cache actually exists
return "Cache has not yet updated, ple | ase wait a minute and search again."
api = wikidotapi.connection()
api.Site = "wanderers-library"
pages = a | pi.refresh_pages()
authpages = []
totalrating = 0
pagetotal = 0
pagerating = 0
author = "None"
multimatch = []
authorpage = ""
for page in pages:
for item in pagecache: #these two for loops iterate through every item within each page dictionary, the proper syntax for accessing a specific item is item[page][it... |
hernandito/SickRage | tests/feedparser_tests.py | Python | gpl-3.0 | 1,284 | 0.005452 | # coding=utf-8
"""
Test Feed Parser
"""
import os.path
import sys
import unittest
sys.path.insert(1, os.path.abspath(os.path.join(os.path.dirname(__file__), '../lib')))
sys.path.insert(1, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from sickbeard.providers.womble import provider as womble
clas... | self.assertTrue('entries' in result)
self.assertTrue('feed' in result)
for item in result['entries'] or []:
title, url = womble._get_title_and_url(item) # pylint: disable=protected-access
self.assertTrue(title and url | )
if __name__ == "__main__":
print "=================="
print "STARTING - FEED PARSER TESTS"
print "=================="
print "######################################################################"
SUITE = unittest.TestLoader().loadTestsFromTestCase(FeedParserTests)
TEST_RESULTS = unittest.Tex... |
KWierso/treeherder | treeherder/extract/extract_jobs.py | Python | mpl-2.0 | 5,395 | 0.000741 | from jx_bigquery import bigquery
from jx_mysql.mysql import (MySQL,
sql_query)
from jx_mysql.mysql_snowflake_extractor import MySqlSnowflakeExtractor
from jx_python import jx
from mo_files import File
from mo_json import (json2value,
value2json)
from mo_logs import (Log,... | fl.message = strings.limit(fl.message, 10000)
destination.extend(acc)
# RECORD THE STATE
last_doc = acc[-1]
last_modified, job_id = last_doc.last_modified, last_doc.id
redis.set(
settings.extractor.key,
... | if len(acc) < settings.extractor.chunk_size:
break
except Exception as e:
Log.warning("problem with extraction", cause=e)
Log.note("done job extraction")
try:
with Timer("merge shards"):
destination.merge_shards()
exce... |
audaciouscode/Books-Mac-OS-X | Versions/Books_3.0b6/OPAC SBN.plugin/Contents/Resources/PyZ3950/CQLParser.py | Python | mit | 33,090 | 0.002931 | #!/usr/bin/python
# Author: Rob Sanderson (azaroth@liv.ac.uk)
# Distributed and Usable under the GPL
# Version: 1.7
# Most Recent Changes: contexts, new modifier style for 1.1
#
# With thanks to Adam from IndexData and Mike Taylor for their valuable input
from shlex import shlex
from xml.sax.saxutils import escape
... | self.boolean.toXCQL(depth+1))
xml.append("%s <leftOperand>\n" % (space))
xml.append(self.leftOperand.toXCQL(depth+2))
xml.append("%s </leftOperand>\n" % (space))
xml.append("%s <rightOperand>\n" % (space))
xml.append(self.rightOperand.toXCQL(depth+2))
xml.append(" | %s </rightOperand>\n" % (space))
xml.append("%s</triple>\n" % (space))
return ''.join(xml)
def toCQL(self):
txt = []
if (self.prefixes):
for p in self.prefixes.keys():
if (p <> ''):
txt.append('>%s="%s"' % (p, self.prefixes[p]))
... |
tvtsoft/odoo8 | addons/stock_account/stock_account.py | Python | agpl-3.0 | 28,260 | 0.005699 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from openerp.osv import fields, osv
from openerp.tools.translate import _
from openerp import SUPERUSER_ID, api, models
import logging
_logger = logging.getLogger(__name__)
class account_invoice_line(osv.osv):
_inh... | t_acct_id)
return invoice_data
class stock_inventory(osv.osv):
_inherit = "stock.inventory"
_columns = {
'date_account': fields.date('Force Valuation Account | Date', help="Choose the accounting period where you want to value the stock moves created by the inventory instead of the default one (chosen by the inventory end date)"),
}
def post_inventory(self, cr, uid, inv, context=None):
if context is None:
context = {}
ctx = context.copy()
... |
Branlala/docker-sickbeardfr | sickbeard/sickbeard/notifiers/libnotify.py | Python | mit | 4,677 | 0.003635 | # Author: Nic Wolfe <nic@wolfeden.ca>
# URL: http://code.google.com/p/sickbeard/
#
# This file is part of Sick Beard.
#
# Sick Beard 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.
#
| # Sick Beard 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along w... |
hryamzik/ansible | lib/ansible/modules/network/meraki/meraki_mx_l3_firewall.py | Python | gpl-3.0 | 11,897 | 0.001933 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2018, Kevin Breit (@kbreit) <kevin.breit@kevinbreit.net>
# 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 = {
... | suboptions:
policy:
description:
- Policy to apply if | rule is hit.
choices: [allow, deny]
protocol:
description:
- Protocol to match against.
choices: [any, icmp, tcp, udp]
dest_port:
description:
- Comma separated list of destination port numbers to mat... |
AustereCuriosity/astropy | astropy/table/tests/test_init_table.py | Python | bsd-3-clause | 18,369 | 0.000817 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
# TEST_UNICODE_LITERALS
from __future__ import print_function # For print debugging with python 2 or 3
from collections import OrderedDict, Mapping
from ...extern import six
import pytest
import numpy as np
from ...table import Column, TableColumns
... | 'c'].dtype.type == np.float64
| assert all(t[name].name == name for name in t.colnames)
def test_bad_data(self, table_type):
self._setup(table_type)
with pytest.raises(ValueError):
table_type([[1, 2],
[3, 4, 5]])
@pytest.mark.usefixtures('table_type')
class TestInitFromListOfDicts(BaseInitFromL... |
epronk/mktoc | src/mktoc/test_disc.py | Python | gpl-3.0 | 3,118 | 0.024054 | # Copyright 2008, Patrick C. McGinty
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distribut... | bject must raise exception if subtract underflows."""
a = _TrackTime('00:00:00')
b = _TrackTime('00:00:01')
self.assertRaises( UnderflowError, _TrackTime.__sub__, a, b )
def time_sub(self,s):
"""Helper function for test cases above."""
self.assertEqual( str(_TrackTime(s[0]) - _TrackTim... | """Execute all test cases define in this file."""
unittest.main()
|
waymo-research/waymo-open-dataset | waymo_open_dataset/utils/keypoint_data.py | Python | apache-2.0 | 16,518 | 0.007325 | # Copyright 2022 The Waymo Open Dataset 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... | """Data structures to represent and tools to parse human keypoint data."""
import dataclasses
import enum
from typing import Collection, Dict, List, Mapping, Optional
import numpy as np
import tensorflow as tf
from waymo_open_dataset import dataset_pb2
from waymo_open_dataset import label_pb2
from waymo_open_dataset.... | isibility flags for all keypoints are
# stored as a single tensor or vector.
_SHARED_TYPES = (KeypointType.KEYPOINT_TYPE_NOSE,
KeypointType.KEYPOINT_TYPE_LEFT_SHOULDER,
KeypointType.KEYPOINT_TYPE_RIGHT_SHOULDER,
KeypointType.KEYPOINT_TYPE_LEFT_ELBOW,
K... |
JulienMcJay/eclock | windows/Python27/Lib/site-packages/Cython/Build/Tests/TestInline.py | Python | gpl-2.0 | 1,719 | 0.005236 | import os, tempfile
from Cython.Shadow import inline
from Cython.Build.Inline import safe_type
from Cython.TestUtils import CythonTest
try:
import numpy
has_numpy = True
except:
has_numpy = False
test_kwds = dict(force=True, quiet=True)
global_value = 100
class TestInline(CythonTest):
def setUp(self... | self.assert | Equals(inline("""
cimport cython
return cython.typeof(a), cython.typeof(b)
""", a=1.0, b=[], **self.test_kwds), ('double', 'list object'))
def test_locals(self):
a = 1
b = 2
self.assertEquals(inline("return a+b", **self.test_kwds), 3)
def test_globals(se... |
joaduo/mepinta | core/python_core/mepinta/plugins_manager/metadata_wrappers/DataTypeMetadataWrapper.py | Python | gpl-3.0 | 1,735 | 0.002305 | # -*- coding: utf-8 -*-
'''
Mepinta
Copyright (c) 2011-2012, Joaquin G. Duo
This file is part of Mepinta.
Mepinta 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 opti... | def manifest(self):
if hasattr(self.module, 'manifest'):
return MetadataWrapperBase.getManifest(self)
else:
#TO | DO: why do we return an object here?
#Do some data types have not .manifest?
return object()
def getManifestType(self):
return DataTypeManifestBase
def smokeTestModule():
# from getDefaultContext import getDefaultContext
# context = getDefaultContext()
raise RuntimeW... |
hkawasaki/kawasaki-aio8-1 | cms/djangoapps/contentstore/features/grading.py | Python | agpl-3.0 | 7,108 | 0.000985 | # pylint: disable=C0111
# pylint: disable=W0621
from lettuce import world, step
from common import *
from terrain.steps import reload_the_page
from selenium.common.exceptions import (
InvalidElementStateException, WebDriverException)
from nose.tools import assert_in, assert_not_in, assert_equal, assert_not_equal ... | te the assignment type "([^"]*)"$')
def delete_assignment_type(step, to_delete):
delete_css = '.remove-grading-data'
world.css_click(delete_css, index=get_type_index(to_delete))
@step(u'I add a new assignment type "([^"]*)"$')
def add_assignment_type(step, new_name):
add_button_css = '.add-grading-data'
... | step(u'I set the assignment weight to "([^"]*)"$')
def set_weight(step, weight):
weight_id = '#course-grading-assignment-gradeweight'
weight_field = world.css_find(weight_id)[-1]
old_weight = world.css_value(weight_id, -1)
for count in range(len(old_weight)):
weight_field._element.send_keys(Keys... |
c00clupea/brew | solution/CommandFlaw.py | Python | gpl-2.0 | 524 | 0.019084 | __author__ = 'sec15334'
from Utils import Flaw as fl
from Utils import FieldSolution as fs
from Utils import MethodHelp as mh
def help():
fileman = mh('fielmanager','Command inject')
print loginhelp.print_help()
def fielmanager():
flaw = fl('command inject','http://localhost:8081/secu/admininternpic.secu... | fs('uri','Not validated','http://localhost:8081/secu/admininternpic.secu?path=/etc/passwd;cat%20/etc/passwd')
flaw.fields.append(field1)
return fl | aw.printFlaw() |
ww9rivers/splunk-sdk-python | tests/test_conf.py | Python | apache-2.0 | 3,799 | 0.001316 | #!/usr/bin/env python
#
# Copyright 2011-2015 Splunk, Inc.
#
# Licensed under the Apache Licens | e, 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
#
# Unles | s required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from __fut... |
rodrigc/fabric | fabric/utils.py | Python | bsd-2-clause | 13,245 | 0.000529 | """
Internal subroutines for e.g. aborting execution with an error message,
or performing indenting on multiline output.
"""
import os
import six
import sys
import textwrap
from traceback import format_exc
def _encode(msg, stream):
if six.PY2 and isinstance(msg, unicode) and hasattr(stream, 'encoding') and not st... | mydict = _AliasD | ict(
{'biz': True, 'baz': False},
aliases={'foo': ['bar', 'biz', 'baz']}
)
Because it is possible for the aliased values to be in a heterogenous
state, reading aliases is not supported -- only writing to them is allowed.
This also means they will not show u |
googleinterns/hw-fuzzing | hw/other/lock/hdl_generator/generate_lock_tb.py | Python | apache-2.0 | 956 | 0.00523 | #!/usr/bin/python3
# Copyright 2020 Timothy Trippel
#
# 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 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 permiss... |
yanaiela/easyEmbed | easyEmbed/easyEmbed.py | Python | mit | 3,380 | 0.004438 | # The interface file
from embeddings import *
class Embeddings(object):
w2v = Word2Vec()
glove = GloVe() |
w2vf = Word2VecF()
# add more here...
def download(emb_type, directory='~/.embeddings'):
"""
Downloads the required pre-trained Embedding
:param emb_type: One of the supported Embedding classes (Word2Vec, GloVe etc..)
:param directory: The directory where | the file will be downloaded
default dir: ~/.embeddings
:return: the full path of the downloaded file
"""
if directory[-1] != SEP:
directory += SEP
if not (os.path.exists(directory) and os.path.isdir(directory)):
print 'directory does not exist.. create one'
os.makedir... |
mcus/SickRage | sickbeard/providers/thepiratebay.py | Python | gpl-3.0 | 5,726 | 0.001746 | # Author: Mr_Orange <mr_orange@hotmail.it>
# URL: http://code.google.com/p/sickbeard/
#
# This file is part of SickRage.
#
# SickRage is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the Lic... | rch', 'rss')[mode is 'RSS']] + '?' + urlencode(self.search_params)
logging.debug("Search URL: %s" % searchURL)
data = self.getURL(searchURL)
# data = self.getURL(self.urls[('search', 'rss')[mode is 'RSS']], params=self.search_params)
if not data:
... | for torrent in matches:
title = torrent.group('title')
download_url = torrent.group('url')
# id = int(torrent.group('id'))
size = self._convertSize(torrent.group('size'))
seeders = int(torrent.group('seeders... |
midgardproject/midgard-python | tests.old/dbus/midgard_client.py | Python | lgpl-2.1 | 450 | 0.035556 | import | sys
import _midgard as midgard
import local_connection
import dbus
import midgard_dbus as mgdbus
def main():
cnc = local_connection.quick_connection()
cnc.connect("midgard")
cnc.set_loglevel("debug")
midgard.dbus.send("/midgard_article", "Hi there!");
topic = midgard.mgdschema.midgard_topic(1)
guid = topic.ge... | .midgard_dbus.send("/midgard_article", guid)
sys.exit()
if __name__ == '__main__':
main()
|
beckastar/django | tests/admin_views/models.py | Python | bsd-3-clause | 20,993 | 0.00062 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import datetime
import tempfile
import os
from django.contrib.auth.models import User
from django.contrib.contenttypes.fields import (
GenericForeignKey, GenericRelation
)
from django.contrib.contenttypes.models import ContentType
from django.core.fi... | models.ForeignKey(Character, limit_choices_to=today_callable_dict, related_name="+")
has_fooled_today = models.ManyToManyField(Character, limit_choices_to=today_callable_q, | related_name="+")
def __str__(self):
return self.variation
class Fabric(models.Model):
NG_CHOICES = (
('Textured', (
('x', 'Horizontal'),
('y', 'Vertical'),
)),
('plain', 'Smooth'),
)
surface = models.CharField(max_length=20, choices=NG_CHOICES)... |
Hironsan/uecda-pyclient | docs/conf.py | Python | mit | 9,234 | 0.006065 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# UECda-PyClient documentation build configuration file, created by
# sphinx-quickstart on Fri Oct 7 17:02:01 2016.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in th... | p_basename = 'UECda-PyClientdoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4pap | er').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
# Latex figure (float) alignment
#'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name... |
gmoyerbrailean/PyRec | Files/BLASTing.py | Python | gpl-2.0 | 5,396 | 0.015196 | ####### LICENSE #######
# This code is part of the Recombineering module, written by Gregory
# Moyerbrailean at Michigan State University, Department of Microbiology
# and Molecular Genetics.
# Copyright (C) 2010 Gregory Moyerbrailean
#
# This program is free software; you can redistribute it and/or modify
# it under... | genome is not available for
a species, the genome of a closely related strain can be used in its place.
When a hit has been found, the parser function will extract and return relevant
information regarding the corresponding gene.
Alternatively, the user may specify to disable the BLAST function. In this case,
the modu... | s not have to have the blast+ command-line tools.
However, the user will also not be able to run organisms such as L. reuteri
against a similar genome, as this method requires exact gene matches.'''
import subprocess
from Bio.Blast.Applications import NcbiblastnCommandline as ncl
from Bio.Blast import NCBIXML as nxml
... |
fake-name/ReadableWebProxy | WebMirror/management/rss_parser_funcs/feed_parse_extractToomtummootstranslationsWordpressCom.py | Python | bsd-3-clause | 588 | 0.032313 |
def extractToomtummootstranslationsWordpressCom(item):
'''
Parser for 'to | omtummootstranslation | s.wordpress.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('PRC', 'PRC', 'translated'),
('Loiterous', 'Loiterous', 'oel'),
]
for tagname, name, ... |
goofwear/raspberry_pwn | src/pentest/sqlmap/plugins/dbms/maxdb/fingerprint.py | Python | gpl-3.0 | 3,799 | 0.001579 | #!/usr/bin/env python
"""
Copyright (c) 2006-2014 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission
"""
from lib.core.agent import agent
from lib.core.common import Backend
from lib.core.common import Format
from lib.core.data import conf
from lib.core.data import kb
from lib.co... | def checkDbms(self):
if not conf.extensiveFp and (Backend.isDbmsWithin(MAXDB_ALIASES) or (conf.dbms or "").lower() in MAXDB_ALIASES):
setDbms(DBMS.MAXDB)
self.getBanner()
return True
infoMsg = "testing %s" % DBMS.MAXDB
logg | er.info(infoMsg)
result = inject.checkBooleanExpression("ALPHA(NULL) IS NULL")
if result:
infoMsg = "confirming %s" % DBMS.MAXDB
logger.info(infoMsg)
result = inject.checkBooleanExpression("MAPCHAR(NULL,1,DEFAULTMAP) IS NULL")
if not result:
... |
bert9bert/statsmodels | statsmodels/tsa/statespace/sarimax.py | Python | bsd-3-clause | 82,327 | 0.000061 | """
SARIMAX Model
Author: Chad Fulton
License: Simplified-BSD
"""
from __future__ import division, absolute_import, print_function
from statsmodels.compat.python import long
from warnings import warn
import numpy as np
import pandas as pd
from .kalman_filter import KalmanFilter
from .mlemodel import MLEModel, MLERes... |
to highest. Initialized with ones, unless a
coefficient is constrained to be zero (in which
case it is zero).
polynomial_trend : array
Array containing trend polynomial coefficients,
ordered from lowest degree to highest. Initialized
with ones, unless a coefficient i... | zero (in which case it is zero).
k_ar : int
Highest autoregressive order in the model, zero-indexed.
k_ar_params : int
Number of autoregressive parameters to be estimated.
k_diff : int
Order of intergration.
k_ma : int
Highest moving average order in the model, ze... |
elliterate/capybara.py | capybara/tests/session/test_assert_all_of_selectors.py | Python | mit | 4,160 | 0.003606 | import pytest
import re
import capybara
from capybara.exceptions import ElementNotFound
class TestAssertAllOfSelectors:
@pytest.fixture(auto | use=True)
def setup_session(self, session):
session.visit("/with_html")
|
def test_does_not_raise_if_the_given_selectors_are_on_the_page(self, session):
session.assert_all_of_selectors("css", "p a#foo", "h2#h2one", "h2#h2two")
def test_raises_if_any_of_the_given_selectors_are_not_on_the_page(self, session):
with pytest.raises(ElementNotFound):
session.as... |
DataONEorg/d1_python | client_onedrive/src/d1_onedrive/impl/resolver/__init__.py | Python | apache-2.0 | 814 | 0 | # This work was created by participants in the DataONE project, and is
# jointly copy | righted by participating institutions in DataONE. For
# more information on DataONE, see our web site at http://dataone.org.
#
# Copyright 2009-2019 DataONE
#
# 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... | istributed 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.
"""ONEDrive resolvers."""
|
sunlightlabs/billy | billy2pupa/nd.py | Python | bsd-3-clause | 110 | 0 | fro | m openstatesapi.jurisdiction import make_jurisdiction
J = make_jurisdiction('nd')
J.url = 'http | ://nd.gov'
|
dilworm/pytest | protobuf/main.py | Python | gpl-2.0 | 380 | 0.007895 | import addressbook_pb2
person = addressbook_pb2.Person()
person.id = 1234
person.name = "John Doe"
person.email = "jdoe@ | example.com"
p1 = person.phones.add()
p1.number = "555-5321"
p2 = person.phones.add() |
p2.number = "555-5322"
p2.type = addressbook_pb2.Person.WORK
#print(person.IsInitialized())
#print(person)
print(person.SerializeToString())
#print('\n'.join(dir(person)))
|
SpheMakh/Stimela | stimela/cargo/cab/casa47_setjy/src/run.py | Python | gpl-2.0 | 1,403 | 0.002138 | import os
import sys
import drivecasa
import logging
import shlex
import shutil
import subprocess
import yaml
import glob
casa = drivecasa.Casapy(log2term=True, echo_to_stdout=True, timeout=24*3600*1 | 0)
CONFIG = os.environ["CONFIG"]
INPUT = os.environ["INPUT"]
OUTPUT = os.environ["OUTPUT"]
MSDIR = os.environ["MSDIR"]
with open(CONFIG, "r") as _std:
cab = yaml.safe_load(_std)
junk = cab["junk"]
args = {}
for param in cab['parameters']:
name = param['name']
value = param['value']
if value is Non... | args[name] = value
script = ['{0}(**{1})'.format(cab['binary'], args)]
def log2term(result):
if result[1]:
err = '\n'.join(result[1] if result[1] else [''])
failed = err.lower().find('an error occurred running task') >= 0
if failed:
raise RuntimeError('CASA Task failed. See... |
smmbllsm/aleph | aleph/ingest/dbf.py | Python | mit | 1,514 | 0 | from __future__ import absolute_import
from dbf.base import DBF
from aleph.text import string_value
from aleph.ingest.tabular import TabularIngestor
# TODO, dbf: https://pypi.python.org/pypi/pyDBF/
class DBFIngestor(TabularIngestor):
MIME_TYPES = []
EXTENSIONS = ['dbf']
BASE_SCORE = 7
def generate_r... | name = columns.get(k)
record[name] = string_value(value)
if len(record):
for name in columns.values():
record[name] = record.get(name, None)
yield record
def inges | t(self, meta, local_path):
with open(local_path, 'rb') as fh:
db = DBF(fh)
document = self.create_document(meta)
tabular = self.create_tabular(0)
columns = [tabular.add_column(h) for h in db.fields.keys()]
if not len(columns):
return
... |
updownlife/multipleK | dependencies/biopython-1.65/build/lib.linux-x86_64-2.7/Bio/Align/Applications/_Dialign.py | Python | gpl-2.0 | 9,793 | 0.004697 | # Copyright 2009 by Cymon J. Cox. All rights reserved.
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
"""Command line wrapper for the multiple alignment program DIALIGN2-2.
"""
from __future__ impo... | aligned.* including a FASTA output file (aligned.fa), use:
>>> from Bio.Align.Applications import DialignCommandli | ne
>>> dialign_cline = DialignCommandline(input="unaligned.fasta",
... fn="aligned", fa=True)
>>> print(dialign_cline)
dialign2-2 -fa -fn aligned unaligned.fasta
You would typically run the command line with dialign_cline() or via
the Python subprocess module,... |
simpkins/avrpp | src/kbd_v1/gen_descriptors.py | Python | bsd-3-clause | 5,688 | 0.006857 | #!/usr/bin/python3 -tt
#
# Copyright (c) 2013, Adam Simpkins
#
import os
import sys
sys.path.insert(0, os.path.dirname(sys.path[0]))
import usb_config
# TODO: Share code with the kbd_v2 gen_descriptors.py program,
# rather than copy-and-pasting most of it.
def gen_config():
ENDPOINT0_SIZE = 32
KEYBOARD_INT... | 0xA1, 0x53, # Collection 0x53
0x75, 0x08, # Report Size = 8 bits
0x15, 0x00, # Logical minimum = 0
0x26, 0xFF, 0x00, # Logical maximum = 255
0x95, DEBUG_SIZE, # Report Count
0x09, 0x75, # Local Usage
... | 0x95, 0x01, # Report Count = 1
0xB1, 0x00, # Feature (variable)
0xC0 # end collection
]))
dbg_endpoint = usb_config.EndpointDescriptor(
address=0x80 | DEBUG_ENDPOINT,
attributes=0x03,
... |
metpy/MetPy | v0.5/_downloads/Find_Natural_Neighbors_Verification.py | Python | bsd-3-clause | 2,746 | 0.002913 | # Copyright (c) 2008-2016 MetPy Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
"""
Find Natural Neighbors Verification
===================================
Finding natural neighbors in a triangulation
A triangle is a natural neighbor of a p | oint if that point is within a circumradius of the
circumcenter of a circumscribed circle containing the triangle.
"""
import matplotlib.pyplo | t as plt
import numpy as np
from scipy.spatial import Delaunay
from metpy.gridding.triangles import find_natural_neighbors
# Create test observations, test points, and plot the triangulation and points.
gx, gy = np.meshgrid(np.arange(0, 20, 4), np.arange(0, 20, 4))
pts = np.vstack([gx.ravel(), gy.ravel()]).T
tri = De... |
wackou/smewt | smewt/test/smewttest.py | Python | gpl-3.0 | 2,192 | 0.009124 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Smewt - A smart collection manager
# Copyright (c) 2008 Nicolas Wack <wackou@smewt.com>
#
# Smewt 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 versio... | as it spits out way too much information
if MAIN_LOGGING_LEVEL == logging.DEBUG | :
logging.getLogger('pygoo').setLevel(logging.INFO)
def currentPath():
'''Returns the path in which the calling file is located.'''
return dirname(join(os.getcwd(), sys._getframe(1).f_globals['__file__']))
def addImportPath(path):
'''Function that adds the specified path to the import path. The path c... |
odesk/python-odesk | odesk/__init__.py | Python | apache-2.0 | 516 | 0.003876 | # Python bindings to oDesk API
# python-odesk version 0.5
# (C) 2010-2015 oDesk
# Updated by the script
"""Main package of the python bindings for oDesk API.
For convenience some most commonly used function | alities are imported here,
so you can use::
from odesk import Client
from odesk import raise_http_error
"""
VERSION = '0.5.8'
def get_version():
return VERSION
from odesk.client import Client
fr | om odesk.http import raise_http_error
__all__ = ["get_version", "Client", "raise_http_error"]
|
mcrute/snakeplan | snakeplan/__init__.py | Python | apache-2.0 | 80 | 0 | fr | om distutils.version import StrictVersion
__version__ = StrictVers | ion('0.1')
|
cirno-baka/Flask_auth_example | app/__init__.py | Python | mit | 301 | 0.006645 | # -*- coding: UTF-8 -*-
from flask import Flask
from flask.ext.sqlalch | emy import SQLAlchemy
app = Flask(__name__)
app.config.from_object('config')
db = SQLAlchemy(app)
from app import views, models, controller
try:
db.session.add(models.validFields())
db.session.commit()
except:
pa | ss
|
thesgc/cbh_core_ws | cbh_core_ws/parser.py | Python | mit | 2,161 | 0.003239 |
from pandas import ExcelFile
import xlrd
from copy import copy
def get_widths(df):
'''Returns a list of the maximum string widths of a the columns in a dataframe in characters'''
widths | = []
for col in df.columns.tolist():
col = unicode(col)
titlewidth = len(col)
try:
w = df[col].values.astype(unicode).str.len().max()
if w > titlewidth:
| widths.append(int(w*1.2))
else:
widths.append(int(titlewidth * 1.2))
except:
widths.append(int(titlewidth * 1.2))
return widths
def is_true(item):
if str(item).lower() in ["y", "true", "yes"]:
return True
else:
return False
def... |
wavefrontHQ/python-client | wavefront_api_client/models/response_container_paged_recent_traces_search.py | Python | apache-2.0 | 4,945 | 0.000202 | # coding: utf-8
"""
Wavefront REST API Documentation
<p>The Wavefront REST API enables you to interact with Wavefront servers using standard REST API tools. You can use the REST API to automate commonly executed operations such as automatically tagging sources.</p><p>When you make REST API calls outside the W... | self._response = None
self._status = None
self.discriminator = None
if response is not None:
self.response = response
self.status = status
@property
def response(self):
"""Gets the response of this ResponseContainerPagedRecentTracesSearch. # noqa: E... | eContainerPagedRecentTracesSearch. # noqa: E501
:rtype: PagedRecentTracesSearch
"""
return self._response
@response.setter
def response(self, response):
"""Sets the response of this ResponseContainerPagedRecentTracesSearch.
:param response: The response of this Respon... |
MithileshCParab/HackerRank-10DaysOfStatistics | Python/Sets/check_subset.py | Python | apache-2.0 | 287 | 0.006969 | # Enter your code here. Read input from STDIN. Print output to STDOUT
t = int(input())
for _ in range(t):
n_A = int(input())
set_A = set(map(int, input().split()))
n_B = int(input())
se | t_B = set(map(int, input().split | ()))
print(set_A.issubset(set_B))
|
MyRobotLab/pyrobotlab | home/Mats/MouthControl.py | Python | apache-2.0 | 796 | 0.021357 | python = Runtime.createAndStart("python","Python")
mouth = Runtime.createAndStart("Mouth","MouthControl")
arduino = mouth.arduino
arduino.connect('COM3')
jaw = mouth.getJaw()
jaw.detach()
jaw.attach(arduino,11)
mouth.setmouth(110,120)
mouth.autoAttach = False |
speech = Runti | me.createAndStart("Speech","MarySpeech")
print ("these are the voices I can have", speech.getVoices())
speech.setVoice('cmu-bdl-hsmm')
mouth.setMouth(speech)
def onEndSpeaking(text):
mouth.setmouth(90,120)
jaw.moveTo(95)
sleep(.5)
mouth.setmouth(110,120)
python.subscribe(speech.getName(),"publishEndSpeaking")
# Sta... |
ozgebarbaros/ab2015PythonKurs | 1.gun/1.ilk_program/verilen_ilk_deger.py | Python | gpl-2.0 | 147 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
ilk_sayisal_deger = 10
i | lk_ondalikli_deger = 3.14
ilk_mantiksal_deger = True
print ilk_sayisal_deger | |
mapio/markovdrummer | setup.py | Python | gpl-3.0 | 2,108 | 0.016129 | from setuptools import setup, find_packages
import codecs
import os
import re
here = os.path.abspa | th(os.path.dirname(__file__))
with codecs.open( 'README.md', encoding = 'utf-8' ) as f:
long_description = f.read()
setup(
name = 'markovdrummer',
version = '0.1a',
description = 'A drum beat analyzer and generator based on Markov chains',
long_description = long_description,
url = 'http://do... | santini@unimi.it',
# Choose your license
license = 'GPLv3',
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Console',
'Intended Audience :: Education',
'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)',
'Operating System :... |
julianghionoiu/tdl-client-python | test/runner/quiet_implementation_runner.py | Python | apache-2.0 | 104 | 0 | class QuietIm | plementationRunner:
def __init__(self):
pass
def run(self):
| pass
|
Sjors/bitcoin | test/fuzz/test_runner.py | Python | mit | 10,859 | 0.00221 | #!/usr/bin/env python3
# Copyright (c) 2019-2020 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Run fuzz test targets.
"""
from concurrent.futures import ThreadPoolExecutor, as_completed
import argp... | to console.",
)
parser.add_argument(
'--valgrind',
action='store_true',
help='If true, run fuzzing binaries under the valgrind memory error detector',
)
parser.add_argument(
'-x',
'--exclude',
help="A comma-separated list of targets to | exclude",
)
parser.add_argument(
'--par',
'-j',
type=int,
default=4,
help='How many targets to merge or execute in parallel.',
)
parser.add_argument(
'seed_dir',
help='The seed corpus to run on (must contain subfolders for each fuzz target).',
... |
Mierzen/Dam-Simulation | simulations/Case_study_3/simulation_CS3.py | Python | gpl-3.0 | 4,643 | 0.004308 | import modules.pumpingsystem as ps
import pandas as pd
import numpy as np
# Pump schedule as per SCADA. rows = pumps, columns 1:=Peak, 2:=Standard, 3:Off-peak
pump_schedule_41 = np.array([[72, 42, 50],
[95, 78, 86],
[110, 110, 110],
... | tial_level_20,
| 171.8, 3821.0, pump_schedule_20, actual_status_20[0],
inflow_20, fed_to_level="IPC", pump_statuses_for_validation=actual_status_20,
n_mode_max_pumps=2, n_mode_control_range=20, n_mode_top_offset=7,
... |
mammique/django | django/core/management/sql.py | Python | bsd-3-clause | 7,924 | 0.00366 | from __future__ import unicode_literals
import codecs
import os
import re
from django.conf import settings
from django.core.management.base import CommandError
from django.db import models
from django.db.models import get_models
from django.utils._os import upath
def sql_create(app, style, connection):
"Returns... | of known_models is harmless, so
# we can be conservative).
app_models = models.get_models(app, include_auto_created=True)
final_output = []
tables = connection.introspection.table_names()
known_models = set([model for model in | connection.introspection.installed_models(tables) if model not in app_models])
pending_references = {}
for model in app_models:
output, references = connection.creation.sql_create_model(model, style, known_models)
final_output.extend(output)
for refto, refs in references.items():
... |
fsinfuhh/Bitpoll | bitpoll/poll/urls.py | Python | gpl-3.0 | 2,082 | 0.007205 | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^([a-zA-Z0-9_\-]+)/$', views.poll, name='poll'),
url(r'^([a-zA-Z0-9_\-]+).csv$', views.poll, {'export': True | }, name='poll_export_csv'),
url(r'^([a-zA-Z0-9_\-]+)/comment/$', views.comment, name='poll_comment'),
url(r'^([a-zA-Z0-9_\-]+)/comment/(\d+)/edit/$', views.comment, name='poll_comment_edit'),
url(r'^([a- | zA-Z0-9_\-]+)/comment/(\d+)/delete/$', views.delete_comment, name='poll_deleteComment'),
url(r'^([a-zA-Z0-9_\-]+)/watch/$', views.watch, name='poll_watch'),
url(r'^([a-zA-Z0-9_\-]+)/settings/$', views.settings, name='poll_settings'),
url(r'^([a-zA-Z0-9_\-]+)/edit/choices/$', views.edit_choice, name='poll_e... |
sibsibsib/pressureNET-server | readings/migrations/0021_auto__del_customer__del_unique_customer_company_name_contact_name_cont.py | Python | gpl-3.0 | 5,747 | 0.007656 | # -*- 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):
# Removing unique constraint on 'Customer', fields ['company_name', 'contact_name', 'contact_mail']
db.delet... | ', self.gf('django.db.models.fields.CharField')(max_length=25, null=True, blank=True)),
))
db.send_create_signal('readings', ['Customer'])
# Adding unique constraint on 'Customer', fields ['company_name', 'contact_name', 'contact_mail']
db.create_unique('readings_customer', ['company_na... | )
# Adding model 'CustomerCallLog'
db.create_table('readings_customercalllog', (
('customer', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['readings.Customer'])),
('max_longitude', self.gf('django.db.models.fields.FloatField')()),
('min_longitude', se... |
antoinecarme/sklearn2sql_heroku | tests/regression/RandomReg_100/ws_RandomReg_100_AdaBoostRegressor_db2_code_gen.py | Python | bsd-3-clause | 135 | 0.014815 | from sklear | n2sql_heroku.tests.regression import generic as reg_gen
reg_gen.test_model("AdaBoostRegressor" , "RandomReg_100" , "db2 | ")
|
chispita/epiwork | apps/pollster/admin.py | Python | agpl-3.0 | 774 | 0.010336 | from django.contrib import admin
from django.contrib.auth.models import User
from .models import RuleType, QuestionDataType, VirtualOptionType, Survey, TranslationSurvey, Chart, ResultsIntake, ResultsMonthly
class ResultsIntake_Admin(admin.ModelAdmin):
list_display = ('id','user', 'timestamp')
search_fields = ... |
class ResultsMonthly_Admin(admin.ModelAdmin):
list_display = ('id','user','timestamp')
#list_display = ('id','timestamp')
admin.site.register(RuleType)
admin.site.register(QuestionDataType)
admin.site.register(VirtualOptionType)
admin.site.register(Survey)
admin.site.register(Tr | anslationSurvey)
admin.site.register(Chart)
admin.site.register(ResultsIntake, ResultsIntake_Admin)
admin.site.register(ResultsMonthly, ResultsMonthly_Admin)
|
asedunov/intellij-community | python/testData/refactoring/changeSignature/keywordParam.before.py | Python | apache-2.0 | 31 | 0.064516 | def func(a):
| pass
func(a | =1)
|
VisTrails/VisTrails | vistrails/packages/tej/__init__.py | Python | bsd-3-clause | 101 | 0 | from __future__ import division
identifier = 'org.vistrails.ext | ra.tej'
name = 'tej'
| version = '0.2'
|
jmmease/pandas | scripts/gen_release_notes.py | Python | bsd-3-clause | 2,434 | 0.000822 | from __future__ import print_function
import sys
import json
from pandas.io.common import urlopen
from datetime import datetime
class Milestone(object):
def __init__(self, title, number):
self.title = title
self.number = number
def __eq__(self, other):
if isinstance(other, Milestone)... | Change', 'Bug']
rs = 'pandas %s' % milestone
rs += '\n' + ('=' * len(rs))
rs += '\n\n **Release date:** %s' % datetime.today().strftime('%B %d, % | Y')
for i, h in enumerate(headers):
rs += '\n\n**%s**\n\n' % h
l = labels[i]
rs += collate_label(issues, l)
return rs
if __name__ == '__main__':
rs = release_notes(sys.argv[1])
print(rs)
|
catcosmo/fragdenstaat_de | fragdenstaat_de/settings.py | Python | mit | 4,056 | 0.003205 | # -*- coding: utf-8 -*-
import os
import re
from froide.settings import Base, ThemeBase, German
rec = lambda x: re.compile(x, re.I | re.U)
class FragDenStaatBase(German, ThemeBase, Base):
gettext = lambda s: s
LANGUAGES = (
('de', gettext('German')),
)
FROIDE_THEME = 'fragdenstaat_de.theme... | END = 'django.core.mail.backends.smtp.EmailBackend'
CELERY_EMAIL_TASK_CONFIG = {
'max_retries': None,
'ignore_result': False,
'acks_late': True,
'store_errors_even_if_ignored': | True
}
# Fig broker setup
if 'BROKER_1_PORT' in os.environ:
BROKER_URL = 'amqp://guest:**@%s/' % os.environ['BROKER_1_PORT'].replace('tcp://', '')
@property
def FROIDE_CONFIG(self):
config = super(FragDenStaatBase, self).FROIDE_CONFIG
config.update(dict(
create... |
mtoshi/airwaveapiclient | airwaveapiclient/tests/test_apdetail.py | Python | mit | 1,068 | 0 | # -*- coding: utf-8 -*-
"""UnitTests for airwaveapiclient."""
import os
import unittest
from | airwaveapiclient import APDetail
from airwaveapiclient.tests import test_utils
class APDetailUnitTests(unittest.TestCase):
"""Class APDetailUnitTests.
Unit test for APDetail.
"""
def setUp(self):
"""Setup."""
self.ap_detail_file = 'test_apdetail.xml'
self.here = os.path.dir... | self.ap_detail = test_utils.read_file(path)
self.obj = APDetail(self.ap_detail)
def tearDown(self):
"""Tear down."""
def test_init(self):
"""Test init."""
self.assertNotEqual(self.obj, None)
def test_radio_type(self):
"""Test radio_type."""
for radio i... |
wangzhe3224/python_data_structure_and_algorithms | chapter2/mySequence.py | Python | mit | 1,458 | 0.003429 | from abc import ABCMeta, abstract | method
class mySequence(object):
"""mySequence"""
__metaclass__ = ABCMeta # Python 2 style
@abstractmethod
def __len__(self):
"""Return the length of the sequence"""
@abstractmethod
def __getitem__(self, j):
"""Return the jth element of the sequence"""
def __conta... | h algorithm here..
"""
for i in range(len(self)):
if self[i] == item:
return True
return False
def __eq__(self, other):
"""Compare element one by one, return True if they are all the same"""
if len(self) != len(other):
return False
... |
jpurma/Kataja | plugins/OrderlessTree/SyntaxAPI.py | Python | gpl-3.0 | 2,752 | 0.001817 | # -*- coding: UTF-8 -*-
# ############################################################################
#
# *** Kataja - Biolinguistic Visualization tool ***
#
# Copyright 2013 Jukka Purma
#
# This file is part of Kataja.
#
# Kataja is free software: you can redistribute it and/or modify
# it under the terms of the GNU ... | ce or tree and with given lexicon. If these are left
out, do or redo parsing with instance's stored sentence, lexicon and semantics.
If a forest is provided, derivation steps are created there.
:return:
"""
old_lexicon = self.lexicon
if input_text:
self.input... | self.parser.forest = forest
if lexicon is not None:
if isinstance(lexicon, str):
lexicon = self.read_lexicon(lexicon)
self.lexicon = lexicon
self.parser.lexicon = lexicon
ctrl.document.lexicon = lexicon
print('parsing from the in... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.