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 |
|---|---|---|---|---|---|---|---|---|
kornai/4lang | src/fourlang/lexicon.py | Python | mit | 15,540 | 0.000193 | import copy
import cPickle
import json
import logging
import os
import sys
from nltk.corpus import stopwords as nltk_stopwords
from pymachine.definition_parser import read_defs
from pymachine.machine import Machine
from pymachine.control import ConceptControl
from pymachine.utils import MachineGraph, MachineTraverser
... | con.dump_machines"""
lexicon = Lexicon(cfg)
lexicon.primitives = primitives
for word, dumped_def_graph in machines_dump.iteritems():
new_machine = Machine(word, ConceptControl())
lexicon.add_def_graph(word, new_machine, dumped_def_graph)
lexicon.add(word, new_... | def_graph(word, new_machine, dumped_def_graph)
lexicon.add(word, new_machine, external=True)
return lexicon
def add_def_graph(self, word, word_machine, dumped_def_graph,
allow_new_base=False, allow_new_ext=False):
node2machine = {}
graph = MachineGraph.fro... |
xdnian/pyml | code/ch02/perceptron.py | Python | mit | 1,571 | 0.000637 | import numpy as np
class Perceptron(object):
"""Perceptron classifier.
Parameters
------------
eta : float
Learning rate (between 0.0 and 1.0)
n_iter : int
Passes over the training dataset.
Attributes
-----------
w_ : 1d-array
Weights after fitting.
errors_... | is the number of samples and
n_features is the number of features.
y : array-like, shape = [n_samples]
Target values.
Returns
-------
self : object
"" | "
self.w_ = np.zeros(1 + X.shape[1])
self.errors_ = []
for _ in range(self.n_iter):
errors = 0
for xi, target in zip(X, y):
update = self.eta * (target - self.predict(xi))
self.w_[1:] += update * xi
self.w_[0] += update
... |
ivanlyon/exercises | test/test_k_hnumbers.py | Python | mit | 1,101 | 0.001817 | import io
import unittest
from unittest.mock import patch
from kattis import k_hnumbers
###############################################################################
class SampleInput(unittest.TestCase):
'''Problem statement sample inputs and outputs'''
def test_sample_input(self):
'''Run and asser... | statement sample input and output.'''
inputs = []
inputs.append('21')
inputs.append('85')
inputs.append('789')
inputs.append('0')
inputs = '\n'.join(inputs) + '\n'
outputs = []
outputs.append('21 0')
outputs.append('85 5')
outputs.append(... | stdout', new_callable=io.StringIO) as stdout:
k_hnumbers.main()
self.assertEqual(stdout.getvalue(), outputs)
self.assertEqual(stdin.read(), '')
###############################################################################
if __name__ == '__main__':
unittest.main()
|
iulian787/spack | var/spack/repos/builtin/packages/kcov/package.py | Python | lgpl-2.1 | 1,192 | 0.001678 | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Kcov(CMakePackage):
"""Code coverage tool for compiled programs, Python and Bash which use... | 9bb2bb0be68b4')
depends_on('cmake@2.8.4:', type='build')
depends_on('zlib')
depends_on('curl')
def cmake_args(self):
# Necessary at least on macOS, fixes linking error to LLDB
# https://github.com/Homebrew/homebrew-core/blob/master/Formula/kcov.r | b
return ['-DSPECIFY_RPATH=ON']
@run_after('install')
@on_package_attributes(run_tests=True)
def test_install(self):
# The help message exits with an exit code of 1
kcov = Executable(self.prefix.bin.kcov)
kcov('-h', ignore_errors=1)
|
xorpaul/shinken | shinken/webui/plugins_skonf/action/action.py | Python | agpl-3.0 | 2,125 | 0.001882 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (C) 2009-2012:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
# Gregory Starck, g.starck@gmail.com
# Hartmut Goebel, h.goebel@goebel-consult.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redis... | ic License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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... | NU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
### Will be populated by the UI with it's own value
app = None
# We will need external commands here
import time
from shink... |
runiq/modeling-clustering | find-correct-cluster-number/clustering_run.py | Python | bsd-2-clause | 6,261 | 0.003035 | # TODO:
# - Figure out when to use previous runs' information
# - merge this module's parse_clustermerging and
# newick.parse_clustermerging
from StringIO import StringIO
from os import remove
import shutil
import os.path as op
import subprocess as sp
import sys
import numpy as np
CM_FILE = 'ClusterMerging.txt'
c... | n_cluster = 1 are not helpful
skip_header=self.n_decoys - 51, skip_footer=1,
dtype=[('n' | , 'i8'), ('rmsd', 'f8'), ('dbi', 'f8'), ('psf', 'f8')],
usecols=(0, 3, 4, 5), invalid_raise=False,
converters={0: lambda s: int(s.rstrip(':')) + self.n_decoys + 1})
if reverse:
step = -1
else:
step = 1
self._n = clustermerging['n'][::step]
... |
the-zebulan/CodeWars | tests/kyu_6_tests/test_write_number_in_expanded_form.py | Python | mit | 394 | 0 | impor | t unittest
from katas.kyu_6.write_number_in_expanded_form import expanded_form
class ExpandedFormTestCase(unittest.TestCase):
def test_equal_1(self):
self.assertEqual(expanded_form(12), '10 + 2')
def test_equal_2(self):
self.assertEqual(expanded_form(42), '40 + 2')
def test_equal_3(self... | |
cschenck/blender_sim | fluid_sim_deps/blender-2.69/2.69/scripts/freestyle/style_modules/nature.py | Python | gpl-3.0 | 1,715 | 0.001749 | # ##### BEGIN GPL LICENSE BLOCK #####
#
# 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 distrib... | 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 with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####
# Filename : nature.py
# Author : Stephane Grab... |
ragarwal6397/sqoot | sqoot/tests/__init__.py | Python | mit | 757 | 0.002642 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
# (c) 2014 Rajat Agarwal
import os, sys
import unittest
import sqoot
if 'PUBLIC_API_KEY' in os.environ and 'PRIVATE_API | _KEY' in os.environ:
PUBLIC_API_KEY = os.environ['PUBLIC_API_KEY']
PRIVATE_API_KEY = os.environ['PRIVATE_API_KEY']
else:
try:
from _creds import *
except ImportError:
print "Please create a creds.py file | in this package, based upon creds.example.py"
TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), 'testdata')
sys.path.append('/home/ragarwal/sqoot')
class BaseEndpointTestCase(unittest.TestCase):
def setUp(self):
self.api = sqoot.Sqoot(
privateApiKey=PRIVATE_API_KEY,
public... |
zielmicha/satori | satori.core/satori/core/wsgi.py | Python | mit | 343 | 0.005831 | import sys
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'satori.core.settings')
application = get_wsgi_applicati | on()
| # initialize thrift server structures - takes a long time and it's better
# to do it on startup than during the first request
import satori.core.thrift_server
|
intel-ctrlsys/actsys | actsys/control/provisioner/provisioner.py | Python | apache-2.0 | 3,948 | 0.001773 | # -*- coding: utf-8 -*-
#
# Copyright (c) 2017 Intel Corp.
#
"""
Interface for all resource control plugins.
"""
from abc import ABCMeta, abstractmethod
from ..plugin import DeclareFramework
@DeclareFramework('provisioner')
class Provisioner(object, metaclass=ABCMeta):
PROVISIONER_KEY = "provisioner"
PROVISIO... | _IMAGE_KEY = "ima | ge"
PROVISIONER_BOOTSTRAP_KEY = "provisioner_bootstrap"
PROVISIONER_FILE_KEY = "provisioner_files"
PROVISIONER_KARGS_KEY = "provisioner_kernel_args"
PROVISIONER_UNSET_KEY = "UNDEF"
@abstractmethod
def add(self, device):
"""
Attempts to add a device to the provisioner. Does noth... |
davideuler/foursquared | util/gen_parser.py | Python | apache-2.0 | 4,392 | 0.006831 | #!/usr/bin/python
import datetime
import sys
import textwrap
import common
from xml.dom import pulldom
PARSER = """\
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquare.parsers;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.error.FoursquareError;
import com.joel... | s.set%(camel_name)s(new %(parser_name)s().parse(parser));
"""
STANZA = """\
} else if ("%(name)s".equals(name)) {
%(top_node_name)s.set%(camel_name)s(parser.nextText());
"""
def main():
type_name, top_node_name, at | tributes = common.WalkNodesForAttributes(
sys.argv[1])
GenerateClass(type_name, top_node_name, attributes)
def GenerateClass(type_name, top_node_name, attributes):
"""generate it.
type_name: the type of object the parser returns
top_node_name: the name of the object the parser returns.
per common.Walk... |
shaded-enmity/feaders | feader/utils.py | Python | mit | 173 | 0.023121 | #!/usr/bin/python -tt
fr | om graph.node import Node, FileNode
def endswith(s, pats):
return any(s.endswith(p) for p in pats) |
def create_graph(files):
return Node(None)
|
wolverineav/neutron | neutron/extensions/external_net.py | Python | apache-2.0 | 2,051 | 0 | # Copyright (c) 2013 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... | fault': False,
'is_visible': True,
'convert_to': attr.convert_to_boolean,
'enforce_policy': True,
'required_by_policy': True}}}
class External_net(extensions.ExtensionDescriptor):
@classmethod
def ... | def get_alias(cls):
return "external-net"
@classmethod
def get_description(cls):
return _("Adds external network attribute to network resource.")
@classmethod
def get_updated(cls):
return "2013-01-14T10:00:00-00:00"
def get_extended_resources(self, version):
if ... |
ShaguptaS/moviepy | setup.py | Python | mit | 419 | 0.016706 | #!/usr/bin/env pytho | n
import ez_setup
ez_setup.use_setuptools()
from setuptools import setup, find_packages
setup(name='moviepy',
version='0.2.1.6.9',
author='Zulko 2013',
description='Module for script-based video editing',
long_description=open('README.rst').read(),
license='LICENSE.txt',
keywords="movie e... | |
Vanuan/gpx_to_road_map | converters/location.py | Python | apache-2.0 | 4,821 | 0.009334 | #
# Location-related classes for simplification of GPS traces.
# Author: James P. Biagioni (jbiagi1@uic.edu)
# Company: University of Illinois at Chicago
# Created: 5/16/11
#
import os
class Location:
def __init__(self, id, latitude, longitude, time):
self.id = id
self.latitude = latitude
... | self.locations = []
def add_location(self, bus_location):
self.loc | ations.append(bus_location)
@property
def num_locations(self):
return len(self.locations)
@property
def start_time(self):
return self.locations[0].time
@property
def end_time(self):
return self.locations[-1].time
@property
def time_span(self):
... |
Programmica/python-gtk3-tutorial | conf.py | Python | cc0-1.0 | 7,069 | 0.006649 | # -*- coding: utf-8 -*-
#
# Python GTK+ 3 Tutorial documentation build configuration file, created by
# sphinx-quickstart on Sun Jan 29 18:42:04 2012.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerate... | ial'
copyright = u'2012, Andrew Steele'
# The version info for the project you're documenting, acts as replacement for
# |version | | and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '1.0'
# The full version, including alpha/beta/rc tags.
release = '1.0'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = N... |
postlund/home-assistant | homeassistant/components/config/entity_registry.py | Python | apache-2.0 | 4,955 | 0.001816 | """HTTP views to interact with the entity registry."""
import voluptuous as vol
from homeassistant.components import websocket_api
from homeassistant.co | mponents.websocket_api.const import ERR_NOT_FOUND
from homeassistant.components.websocket_api.decorators import (
async_response,
require_admin,
)
from homeassistant.core import callback
from homeassistant.helpers import co | nfig_validation as cv
from homeassistant.helpers.entity_registry import async_get_registry
async def async_setup(hass):
"""Enable the Entity Registry views."""
hass.components.websocket_api.async_register_command(websocket_list_entities)
hass.components.websocket_api.async_register_command(websocket_get_e... |
ostrokach/elaspic | elaspic/cli/elaspic_run.py | Python | mit | 7,164 | 0.002233 | """ELASPIC RUN
"""
import os
import os.path as op
import logging
import argparse
from elaspic import conf, pipeline
logger = logging.getLogger(__name__)
def validate_args(args):
if args.config_file and not os.path.isfile(args.config_file):
raise Exception('The configuration file {} does not exist!'.form... | 'blast_db_dir': a | rgs.blast_db_dir,
'archive_dir': args.archive_dir
})
if args.uniprot_id:
# Run database pipeline
if args.uniprot_domain_pair_ids:
logger.debug('uniprot_domain_pair_ids: %s', args.uniprot_domain_pair_ids)
uniprot_domain_pair_ids_asint = (
... |
huntxu/neutron | neutron/tests/fullstack/base.py | Python | apache-2.0 | 4,357 | 0 | # Copyright 2015 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 agre... | lf.client))
def get_name(self):
class_name, test_name = self.id().split(".")[-2:]
return "%s.%s" % (class_name, test_name)
def _assert_ping_durin | g_agents_restart(
self, agents, src_namespace, ips, restart_timeout=10,
ping_timeout=1, count=10):
with net_helpers.async_ping(
src_namespace, ips, timeout=ping_timeout,
count=count) as done:
LOG.debug("Restarting agents")
executor ... |
ovnicraft/server-tools | base_locale_uom_default/tests/test_res_lang.py | Python | agpl-3.0 | 1,605 | 0 | # -*- coding: utf-8 -*-
# Copyright 2017 LasLabs Inc.
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).
from odoo.tests.common import TransactionCase
from odoo.exceptions import ValidationError
class TestResLang(TransactionCase):
def setUp(self):
super(TestResLang, self).setUp()
se... | (6, 0, | self.uom.ids)]
def test_check_default_uom_ids_fail(self):
"""It should not allow multiple UoMs of the same category."""
with self.assertRaises(ValidationError):
self.lang.default_uom_ids = [
(4, self.env.ref('product.product_uom_unit').id),
]
def test_ch... |
Acrisel/acris | acris/acris_example/resource_pool_callback.py | Python | mit | 2,420 | 0.013636 | # -*- encoding: utf-8 -*-
##############################################################################
#
# Acrisel LTD
# Copyright (C) 2008- Acrisel (acrisel.com) . All Rights Reserved
#
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public... | ))
notify_queue=queue.Queue()
callback=Callback(notify_queue)
r=rp.get(callback=callback)
if not r:
print('[ %s ] %s doing work before resource available' % (str(datetime.now()), name,))
print('[ %s ] %s waiting for resources' % (str(datetime.now()), name,))
ticket=notify_q | ueue.get()
r=rp.get(ticket=ticket)
print('[ %s ] %s doing work (%s)' % (str(datetime.now()), name, repr(r)))
time.sleep(2)
print('[ %s ] %s returning (%s)' % (str(datetime.now()), name, repr(r)))
rp.put(*r)
r1=worker_callback('>>> w11-callback', rp1)
r2=worker_callback('>>> w21-callbac... |
djcf/error-reloader-extension | tests/badwebserver_jsonly.py | Python | gpl-2.0 | 4,289 | 0.021217 | import socket, sys, time, argparse
parser = argparse.ArgumentParser(description="This bad server accepts an HTTP connection and replies with a valid HTML document which links to assets. However, attemps to load the assets should result in a net::ERR_EMPTY_RESPONSE.")
parser.add_argument("-p", "--port", type=int, help=... | , 1000);
});
</script>
<style>
input { width: 600px; }
</style>
</head>
<body>
<header>
<h1>About Bad Web Server</h1>
<p>The bad web server will correctly trans | fer a valid HTML5 document to the browser when the browser requests the resource identified as '/'. The page will also request images, stylesheets and javascript resources from the server - but these should all result in the browser encountering a socket error and triggering a net::ERR_EMPTY_RESPONSE. The javascript w... |
miztiik/scrapy-Demos | aCloudGuru/aCloudGuru/settings.py | Python | mit | 3,160 | 0.00981 | # -*- coding: utf-8 -*-
# Scrapy settings for aCloudGuru project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# http://doc.scrapy.org/en/latest/topics/settings.html
# http://scrapy.readthedocs.org/en/lat... | loader-middleware.html
# http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html
BOT_NAME = 'aCloudGuru'
SPIDER_MODULES = ['aCloudGuru.spiders']
NEWSPIDER_MODULE = 'aCloudG | uru.spiders'
# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'aCloudGuru (+http://www.yourdomain.com)'
# Obey robots.txt rules
ROBOTSTXT_OBEY = True
# Configure maximum concurrent requests performed by Scrapy (default: 16)
#CONCURRENT_REQUESTS = 32
# Configure a delay... |
plotly/plotly.py | packages/python/plotly/plotly/validators/choroplethmapbox/_hovertemplate.py | Python | mit | 488 | 0.002049 | import _plotly_u | tils.basevalidators
class HovertemplateValidator(_plotly_utils.basevalidators.StringValidator):
def __init__(
self, plotly_name="hovertemplate", parent_name="choroplethmapbox", **kwargs
):
super(HovertemplateValidator, self).__init__(
plotly_name=plotly_name,
parent_nam... | ("edit_type", "none"),
**kwargs
)
|
cxxgtxy/tensorflow | tensorflow/python/ops/numpy_ops/np_array_ops.py | Python | apache-2.0 | 63,472 | 0.010398 | # Copyright 2020 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... | , dtype=dtype))
@np_utils.np_doc('zeros_like')
def zeros_like(a, dtype=None): # pylint: disable=missing-docstring
if isinstance(a, np_arrays.ndarray):
a = a.data
if dtype is None:
# We need to let np_utils.result_type decide the dtype, not tf.zeros_like
dtype = np_utils.result_type(a)
else:
# T... | ils.result_type(dtype)
dtype = dtypes.as_dtype(dtype) # Work around b/149877262
return np_arrays.tensor_to_ndarray(array_ops.zeros_like(a, dtype))
@np_utils.np_doc('ones')
def ones(shape, dtype=float): # pylint: disable=redefined-outer-name
if dtype:
dtype = np_utils.result_type(dtype)
if isinstance(sha... |
kalyons11/kevin | kevin/playground/gpa.py | Python | mit | 2,017 | 0.000496 | # Quick script to calculate GPA given a class list file.
# Class list file should be a csv with COURSE_ID,NUM_UNITS,GRADE
# GRADE should be LETTER with potential modifiers after that
# registrar.mit.edu/classes-grades-evaluations/grades/calculating-gpa
import argparse
import pandas as pd
def get_parser():
# Get ... | t('-F', '--filename', help='Filename for grades')
return parser
class GPACalculator:
def __init__(self, fname):
# Load file via pandas
self.__data = pd.read_csv(
fname,
header=None,
| names=['course', 'units', 'grade']
)
def calc_gpa(self):
# Map grades to grade points
grade_points = self.__data.grade.apply(self.__grade_point_mapper)
# Multiply pointwise by units
grade_points_weighted = grade_points * self.__data.units
# Sum weighted uni... |
kbrebanov/ansible | lib/ansible/module_utils/network/nxos/nxos.py | Python | gpl-3.0 | 14,622 | 0.001299 | #
# This code is part of Ansible, but is an independent component.
#
# This particular file snippet, and this file snippet only, is BSD licensed.
# Modules you write using this snippet, which is embedded dynamically by Ansible
# still belong to the author of the module, and may assign their own license
# to the complet... | nning-config '
cmd += ' '.join(flags)
cmd = cmd.strip()
try:
return self._device_configs[cmd]
except KeyError:
rc, out, err = self.exec_command(cmd)
if rc != 0:
self._module.fail_json(msg=to_text(err))
try:
| cfg = to_text(out, errors='surrogate_or_strict').strip()
except UnicodeError as e:
self._module.fail_json(msg=u'Failed to decode config: %s' % to_text(out))
self._device_configs[cmd] = cfg
return cfg
def run_commands(self, commands, check_rc=True):
... |
bovee/needletail | bench/benchmark.py | Python | mit | 1,291 | 0.002324 | #!/usr/bin/env python
"""
Unscientific benchmarking of this versus the --release rust
implementation below using the %timeit Ipython magic (times in sec)
n_kmers, py_runtime, rust_runtime
6594204, 14.4, 0.578
Both give identical counts on the files tested (and printing kmers out
and diff'ing the resul... | port print_function
import sys
from Bio.SeqIO import parse
from Bio.Seq import reverse_complement
def slid_win(seq, size=4, overlapping=True):
"""Returns a sliding window along self.seq."""
itr = iter(seq)
if overla | pping:
buf = ''
for _ in range(size):
buf += next(itr)
for l in itr:
yield buf
buf = buf[1:] + l
yield buf
else:
buf = ''
for l in itr:
buf += l
if len(buf) == size:
yield buf
... |
ctasims/Dive-Into-Python-3 | examples/alphameticstest.py | Python | mit | 2,452 | 0.00367 | from alphametics import solve
import unittest
class KnownValues(unittest.TestCase):
def test_out(self):
'''TO + GO == OUT'''
self.assertEqual(solve('TO + GO == OUT'), '21 + 81 == 102')
def test_too(self):
'''I + DID == TOO'''
self.assertEqual(solve('I + DID == TOO'), '9 + 191 =... | list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS'
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABI... | AL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)... |
devilry/devilry-django | devilry/devilry_statistics/tests/test_api/api_test_mixin.py | Python | bsd-3-clause | 2,945 | 0.003056 | from django.conf import settings
from model_bakery import baker
from rest_framework.test import APIRequestFactory, force_authenticate
class ApiTestMixin:
"""
Mixin class for API tests.
Can be used for ViewSets too. Just override :meth:`.get_as_view_kwargs` - se example in the docs
for that method.
... | (method='get', viewkwargs=viewkwargs,
api_url=api_url, data=data,
requestuser=requestuser)
def make_post_request(self, viewkwargs=None, api_url='/test/', data=None, requestuser=None):
return self.make_request(method='post', viewkwargs=viewkw... | api_url='/test/', data=None, requestuser=None):
return self.make_request(method='put', viewkwargs=viewkwargs,
api_url=api_url, data=data,
requestuser=requestuser)
def make_delete_request(self, viewkwargs=None, api_url='/test/', data=None, re... |
a25kk/apm | src/apm.sitetheme/apm/sitetheme/tests/test_setup.py | Python | mit | 1,143 | 0 | # -*- coding: utf-8 -*-
"""Setup/installation tests for this package."""
from apm.buildout.testing import IntegrationTestCase
from plone import api
class TestInstall(IntegrationTestCase):
"""Test installation of apm.buildout into Plone."""
def setUp(self):
"""Custom shared utility setup for tests.""... | ctInstalled('apm.buildout'))
def test_uninstall(self):
"""Test if apm.buildout i | s cleanly uninstalled."""
self.installer.uninstallProducts(['apm.buildout'])
self.assertFalse(self.installer.isProductInstalled('apm.buildout'))
# browserlayer.xml
def test_browserlayer(self):
"""Test that IApmBuildoutLayer is registered."""
from apm.buildout.interfaces import I... |
ProfessionalIT/customers | bambinocampones/src/bambinocampones/website/forms.py | Python | mit | 144 | 0 | from d | jango.forms import ModelForm
from .models import Depoimento
class DepoimentoForm(ModelForm):
class | Meta:
model = Depoimento
|
janelia-flyem/pydvid | pydvid/gui/contents_browser.py | Python | bsd-3-clause | 15,264 | 0.013037 | """
This module implements a simple widget for viewing the list of datasets and nodes in a DVID instance.
Requires PyQt4. To see a demo of it in action, start up your dvid server run this::
$ python pydvid/gui/contents_browser.py localhost:8000
"""
import socket
import httplib
import coll | ections
from PyQt4.QtGui import QPushButton, QDialog, QVBoxLayout, QGroupBox, QTreeWidget, \
QTreeWidgetItem, QSizePolicy, QListWidget, QListWidgetItem, \
QDialogButtonBox, QLineEdit, QLabel, QComboBox, QMessageBox, \
QHBoxLayout
from PyQt4.QtCore... | es/nodes within each dataset.
The user's selected dataset, volume, and node can be accessed via the `get_selection()` method.
If the dialog is constructed with mode='specify_new', then the user is asked to provide a new data name,
and choose the dataset and node to which it will belong.
**TO... |
GoogleCloudPlatform/repo-automation-playground | xunit-autolabeler-v2/ast_parser/core/test_data/cli/additions/additions.py | Python | apache-2.0 | 926 | 0 | # Copyright 2020 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | 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.
# [START main_method]
def main():
return 'main method'
# [END main_method]
# [START not_main]
def not_main():
return 'not main'
# [END not_main]
# [START also_not_main]
def also_not_main():
... |
alexbruy/QGIS | python/plugins/processing/algs/qgis/Intersection.py | Python | gpl-2.0 | 5,707 | 0.002628 | # -*- coding: utf-8 -*-
"""
***************************************************************************
Intersection.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
**************************... | tiPoint25D,),
'LineString': (QgsWkbTypes.LineString, QgsWkbTypes.MultiLineString, QgsWkbTypes.LineString25D, QgsWkbTypes.MultiLineString25D,),
'Polygon': (QgsWkbTypes.Polygon, QgsWkbTypes.MultiPolygon, QgsWkbTypes.Polygon25D, QgsWkbTypes.MultiPolygon25D,),
}
for key, value in wkbTypeGroups.items():
for cons... | bTypeGroups[const] = key
class Intersection(GeoAlgorithm):
INPUT = 'INPUT'
INPUT2 = 'INPUT2'
OUTPUT = 'OUTPUT'
def getIcon(self):
return QIcon(os.path.join(pluginPath, 'images', 'ftools', 'intersect.png'))
def defineCharacteristics(self):
self.name, self.i18n_name = self.trAlgor... |
dfurtado/generator-djangospa | generators/app/templates/root/main/permissions.py | Python | mit | 438 | 0.006849 | fr | om rest_framework import permissions
class IsOwnerOrReadOnly(permissions.BasePermission):
"""
Custom permission to only allow owners of an object to edit it.
"""
def has_object_permissions(self, request, view, obj):
# Read permissions are allowed to any request,
# so we'll always allow... | |
ec2ainun/skripsiTF | DeepLforServer(GPU)/jupyter_notebook_config.py | Python | mit | 290 | 0.003448 | import os
from IPython.lib import passwd
c.NotebookApp.ip = | '*'
c.NotebookApp.port = int(os.getenv('PORT', 8888))
c.NotebookApp.open_browser = False
c.MultiKernelManager.default_kernel_name = 'python3'
c.NotebookApp.password = u'sha1:035a13e895a5:8a3398f1576a32cf | 938f9236db03f5e8668356c5'
|
dims/neutron | neutron/tests/unit/db/test_api.py | Python | apache-2.0 | 1,611 | 0 | #
# 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 the License.
from oslo_db import exception as db_exc
import testtools
fr... | as db_api
from neutron.tests import base
class TestExceptionToRetryContextManager(base.BaseTestCase):
def test_translates_single_exception(self):
with testtools.ExpectedException(db_exc.RetryRequest):
with db_api.exc_to_retry(ValueError):
raise ValueError()
def test_trans... |
setsulla/owanimo | lib/picture/bin/patternmatch.py | Python | mit | 1,439 | 0.007644 | import sys
import os
import time
import numpy
import cv2
import cv2.cv as cv
from PIL import Image
sys.path.insert(0, os.path.join(
os.path.dirname(os.path.dirname(os.path.dirname(__file__)))))
from picture.util import define
from picture.util.system import POINT
from picture.util.log import LOG as L
THRESHOLD =... | ernmatch(self, reference, target):
L.info("reference : %s" % reference)
img_rgb = cv2.imread(reference)
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
template = cv2.imread(target, 0)
| w, h = template.shape[::-1]
res = cv2.matchTemplate(img_gray,template,cv2.TM_CCOEFF_NORMED)
loc = numpy.where( res >= THRESHOLD)
result = None
for pt in zip(*loc[::-1]):
result = POINT(pt[0], pt[1], w, h)
return result
@classmethod
def bool(self, refer... |
arkatebi/SwissProt-stats | Ontology/IO/GoaIO.py | Python | gpl-3.0 | 8,540 | 0.012529 | # Copyright 2013 by Kamil Koziara. 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.
"""
I/O operations for gene annotation files.
"""
from __future__ import ... | raw_records = collections.defaultdict(list)
for row in tsv_iter:
first = row[0]
if not first.startswith('!'):
raw_records[row[self._ID_IDX]].append(row)
return dict([(k, _to_goa(v, version)) for k, v in | raw_records.items()]) # Possible py2 slow down
elif self.assoc_format == "in_mem_sql":
try:
sqla = InSqlAssoc(GAF_VERSION[version], [1,4], lambda x: _to_goa(x, version))
except ImportError:
print("Error: To use in_mem_sql association you need to have sqli... |
sidnarayanan/RedPanda | T3/inputs/pf_tmpl.py | Python | mit | 6,716 | 0.018463 | #!/usr/bin/env python
from re import sub
from sys import argv,exit
from os import system,getenv,path
from time import clock,time
import json
which = int(argv[1])
submit_id = int(argv[2])
sname = argv[0]
argv=[]
import ROOT as root
from PandaCore.Tools.Misc import *
from PandaCore.Tools.Load import *
import PandaCore... | ts")
except:
PError(sname+'.fn','Could not read %s'%input_name)
return F | alse # file open error => xrootd?
if not tree:
PError(sname+'.fn','Could not recover tree in %s'%input_name)
return False
output_name = input_name.replace('input','output')
analyzer.SetOutputFile(output_name)
analyzer.Init(tree)
# run and save output
analyzer.Run()
analyzer... |
shiminasai/mapafinca | clima/migrations/0001_initial.py | Python | mit | 4,223 | 0.002842 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import smart_selects.db_fields
class Migration(migrations.Migration):
dependencies = [
('lugar', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='DiasEfect... | _name': 'Precipitaci\xf3n',
'verbose_name_plural': 'Precipitaci\xf3n',
},
),
migratio | ns.CreateModel(
name='Temperatura',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('mes', models.IntegerField(choices=[(1, b'Enero'), (2, b'Febrero'), (3, b'Marzo'), (4, b'Abril'), (5, b'Mayo'), (6, b'J... |
marlengit/BitcoinUnlimited | qa/rpc-tests/p2p-versionbits-warning.py | Python | mit | 6,299 | 0.002223 | #!/usr/bin/env python3
# Copyright (c) 2016 The Bitcoin Core developers
# Copyright (c) 2016 The Bitcoin Unlimited developers
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
from test_framework.mininode import *
from test_fram... | # Send numblocks blocks via peer with nVersionToUse set.
def send_blocks_with_version(self, peer, numblocks, nVersionToUse):
tip = self.nodes[0].getbestblockhash()
height = self.nodes[0].getblockcount()
block_time = self.nodes[0].getblockheader(tip)["time"]+1
tip = int(tip, 16)
... | nVersion = nVersionToUse
block.solve()
peer.send_message(msg_block(block))
block_time += 1
height += 1
tip = block.sha256
peer.sync_with_ping()
def test_versionbits_in_alert_file(self):
with open(self.alert_filename, 'r') as f:
... |
JShadowMan/package | python/zdl/error_logger/error_logger/adapter/postgresql.py | Python | mit | 412 | 0.002427 | #!/usr/bin/env python
#
# Copyright (C) 2017 DL
#
import psycopg2
from error_logger.adapter import base_adapter
class PostgresqlAdapter(base_adapter.BaseAdapter):
|
def __init__(self, *args, **kwargs):
self._args = args
self._kwargs = kwargs
super(PostgresqlAdapter, self).__init__()
def create_connection(self):
return psycopg2.con | nect(*self._args, **self._kwargs)
|
ibc/MediaSoup | worker/deps/gyp/test/win/gyptest-system-include.py | Python | isc | 476 | 0.010504 | #!/usr/bin/env python
# Copyr | ight (c) 2014 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Checks that m | svs_system_include_dirs works.
"""
import TestGyp
import sys
if sys.platform == 'win32':
test = TestGyp.TestGyp(formats=['msvs', 'ninja'])
CHDIR = 'system-include'
test.run_gyp('test.gyp', chdir=CHDIR)
test.build('test.gyp', test.ALL, chdir=CHDIR)
test.pass_test()
|
kinect110/RPSOM | src/examples/RPSOM_animal.py | Python | mit | 941 | 0.025505 | #!/usr/local/bin python
# -*- coding: utf-8 -*-
from RPSOM import Model
from RPSOM.transition_graph import output_graph
if __name__=='__main__':
# learning rate alpha setup
alpha_max = [0.1, 0.5, 0.7]
alpha_min = [0.01, 0.1, 0.2]
# neighborhood radius sigma setup
sigma_max = [5, 7, 10]
sigma_min = [1, 2, 3]
ep... | _min, log_file="test.log")
#cb = [som.write_BMU for som in rpsom.som]
cb = None
# RPSOM train
rpsom.fit (trainX=rpsom.input_x, epochs=rpsom.epochs, verbose=0, callbacks=cb)
# Output Map
# Output thickness map
rpsom.map_output2wrl_squ(grad=100, filename="test")
# Output grayscale 2D map
filename="example_animal"... | on graph
output_graph(rpsom)
rpsom.weight_output_csv ("rpsom_weight")
|
stharrold/demo | tests/test_app_template/test_app_template__init__.py | Python | mit | 591 | 0.003384 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
r"""Pytests for demo/app_template/__init__.py
"""
# Import standard packages.
import os
import sys
# Import installed packages.
# Import local packages.
sys.path.insert(0, os.path.curdir)
import demo
def test__all__(
ref_all=[
'main',
'template']
... | test_all = demo.app_template.__all__
assert ref_all == test_all
for attr in ref_all:
assert has | attr(demo.app_template, attr)
return None
|
g3rd/django-rszio | rszio/__init__.py | Python | mit | 18 | 0 | ver | sion = '1.1.0' | |
plotly/plotly.py | packages/python/plotly/plotly/validators/histogram2d/colorbar/tickformatstop/_templateitemname.py | Python | mit | 494 | 0 | import _plotly_utils.basevalidators
class TemplateitemnameValidator(_plotly_utils.basevalidators.StringValidator):
def __init__(
| self,
plotly_name="templateitemname",
parent_name="histogram2d.colorbar.tickformatstop",
**kwargs
):
super(TemplateitemnameValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "colo | rbars"),
**kwargs
)
|
dekatzenel/team-k | mds/core/models/__init__.py | Python | bsd-3-clause | 948 | 0.007384 | """
Data models for the core Sana data engine. These should be extended as
required.
:Authors: Sana dev team
:Version: 2.0
"" | "
from .concept import Concept, Relationship, RelationshipCategory
from .device import Device
from .encounter import Encounter
from .events import Event
from .instruction import Instruction
from .location import Location
from .notification import Notification
from .observation import Observation
from .observer import ... | ocedure
from .subject import Subject, SurgicalSubject
__all__ = ['Concept', 'Relationship','RelationshipCategory',
'Device',
'Encounter',
'Event',
'Instruction',
'Location',
'Notification',
'Observation',
'Observer',
... |
qwattash/mpm | mpm/cli/mpm.py | Python | gpl-3.0 | 1,756 | 0.001139 | # -*- coding: utf-8 -*-
import argparse
import six
parser = argparse.ArgumentParser(description="Minecraft Package Manager")
sub = parser.add_subparsers(help="command help")
# package commands
sync_parser = sub.add_parser("sync",
description="Synchronize local mod archive.",
... | help="install --help")
remove_parser = sub.add_parser("remove",
description="Remove mods.",
help="remove --help")
# repo commands
repo_add_parser = sub.add_parser("addrepo",
description="Add mod repository."... | p")
repo_del_parser = sub.add_parser("rmrepo",
description="Remove mod repository.",
help="rmrepo --help")
repo_show_parser = sub.add_parser("lsrepo",
description="Show mod repository informations.",
... |
adarshlx/twitter_nlp | hbc/python/tweets2entityDocs.py | Python | gpl-3.0 | 2,087 | 0.0115 | #!/usr/bin/python
import sys
sys.path.append('/homes/gws/aritter/twitter_nlp/python')
from twokenize import tokenize
from LdaFeatures import LdaFeatures
from Vocab import Vocab
from Dictionaries import Dictionaries
entityDocs = {}
prevText = None
for line in sys.stdin:
line = line.rstrip('\n')
fields = lin... | #####################
if sum(labels) > 0:
lOut.write(' '.join([str(x) for x in labels]) + "\n")
eOut.write("%s\n" % e)
print '\t'.join([' '.join([str(vocab.GetID(x)) for x in f]) for f in entityDocs[e]])
vocab.SaveVocab('vocab')
for d in dictionaries.dictionaries:
dOut | .write(d + "\n")
|
jiajiechen/mxnet | python/mxnet/gluon/model_zoo/vision/densenet.py | Python | apache-2.0 | 7,888 | 0.002789 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | "Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`_ paper.
Parameters
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
ctx : Context, default CPU
The context in which to load the pretrained weights.
root : ... | f densenet161(**kwargs):
r"""Densenet-BC 161-layer model from the
`"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`_ paper.
Parameters
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
ctx : Context, default C... |
Frechdachs/python-mpv | mpv.py | Python | agpl-3.0 | 42,232 | 0.006796 |
from ctypes import *
import ctypes.util
import threading
import os
import sys
from warnings import warn
from functools import partial
import collections
import re
import traceback
# vim: ts=4 sw=4 et
if os.name == 'nt':
backend = CDLL('mpv-1.dll')
fs_enc = 'utf-8'
else:
import locale
lc, enc = locale... | ETADATA_UPDATE, SEEK, PLAYBACK_RESTART, PROPERTY_CHANGE,
CHAPTER_CHANGE )
def __repr__(self):
return ['NONE', 'SHUTDOWN', 'LOG_MESSAGE', 'GET_P | ROPERTY_REPLY', 'SET_PROPERTY_REPLY', 'COMMAND_REPLY',
'START_FILE', 'END_FILE', 'FILE_LOADED', 'TRACKS_CHANGED', 'TRACK_SWITCHED', 'IDLE', 'PAUSE', 'UNPAUSE',
'TICK', 'SCRIPT_INPUT_DISPATCH', 'CLIENT_MESSAGE', 'VIDEO_RECONFIG', 'AUDIO_RECONFIG',
'METADATA_UPDATE', 'SEEK'... |
aurule/npc | tests/commands/listing/templates/sections/test_simple_section_md.py | Python | mit | 991 | 0.005045 | import npc
from mako.template import Template
def template_output(sectioner):
template_path = str(npc.settings.InternalSettings().get('listing.templates.markdown.sections.simple'))
section_template = Template(filename=template_path)
return section_template.render(sectioner=sectioner)
def test_generates_ha... | output(sectioner)
assert '###' in output
def test_includes_current_text(prefs):
sectioner = npc.formatters.sectioners.LastInitialSectioner(3, prefs)
sectioner.current_text = 'test text'
output = template_output(sectioner)
assert 'test text' in output
def test_formatted_output(prefs):
| sectioner = npc.formatters.sectioners.LastInitialSectioner(3, prefs)
sectioner.current_text = 'test text'
output = template_output(sectioner)
assert output == '### test text\n\n'
|
ArchiveTeam/qwiki-discovery | pipeline.py | Python | unlicense | 7,004 | 0.001428 | # encoding=utf8
import datetime
from distutils.version import StrictVersion
import hashlib
import os.path
import shutil
import socket
import sys
import time
import random
import seesaw
from seesaw.config import NumberConfigValue
from seesaw.externalprocess import ExternalProcess
from seesaw.item import ItemInterpolati... | ref="http://archiveteam.org/index.php?title=Qwiki">Wiki</a> ·
</span>
</h2>
<p>Qwiki shuts down. This is phase 1: content discovery.</p>
""",
utc_deadline=datetime.datetime(2014, 11, 1, 23, 59, 0)
)
pipeline = Pipeline(
CheckIP(),
GetItemFromTracker("http://%s/%s" % (TRA... | nalProcess('Scraper', CustomProcessArgs(),
max_tries=2,
accept_on_exit_code=[0],
env={
"item_dir": ItemValue("item_dir")
}
),
PrepareStatsForTracker(
defaults={"downloader": downloader, "version": VERSION},
file_groups={
"data": [
... |
SUSE/azure-sdk-for-python | azure-mgmt-network/azure/mgmt/network/v2017_03_01/models/virtual_network_peering.py | Python | mit | 4,140 | 0.001691 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | am name: The name of the resource that is unique within a resource
group. This name can be used to ac | cess the resource.
:type name: str
:param etag: A unique read-only string that changes whenever the resource
is updated.
:type etag: str
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'allow_virtual_network_access': {'key': 'properties.allowVirtualNetworkAccess', 't... |
rishita/mxnet | example/rcnn/rcnn/processing/roidb.py | Python | apache-2.0 | 3,603 | 0.00111 | """
roidb
basic format [image_index]['boxes', 'gt_classes', 'gt_overlaps', 'flipped']
extended ['image', 'max_classes', 'max_overlaps', 'bbox_targets']
"""
from __future__ import print_function
import cv2
import numpy as np
from bbox_regression import compute_bbox_regression_targets
from rcnn.config import config
d... | :] += (targets[cls_in | dexes, 1:] ** 2).sum(axis=0)
means = sums / class_counts
# var(x) = E(x^2) - E(x)^2
stds = np.sqrt(squared_sums / class_counts - means ** 2)
# normalized targets
for im_i in range(num_images):
targets = roidb[im_i]['bbox_targets']
for cls in range(1, num_classes):
... |
drzoidberg33/plexpy | plexpy/pmsconnect.py | Python | gpl-3.0 | 155,901 | 0.005215 | # This file is part of Tautulli.
#
# Tautulli 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.
#
# Tautulli is distributed in the ... |
Return list of children in requested library item.
Parameters required: rating | _key { ratingKey of parent }
Optional parameters: output_format { dict, json }
Output: array
"""
uri = '/library/metadata/' + rating_key + '/allLeaves'
request = self.request_handler.make_request(uri=uri,
request_type='GET',... |
ets-labs/python-dependency-injector | examples/containers/override.py | Python | bsd-3-clause | 578 | 0 | """Container overriding example."""
fr | om dependency_injector import containers, providers
class Service:
...
class ServiceStub:
...
class Container(containers.DeclarativeContainer):
service = providers.Factory(Service)
class OverridingContainer(containers.DeclarativeContainer):
service = providers.Factory | (ServiceStub)
if __name__ == "__main__":
container = Container()
overriding_container = OverridingContainer()
container.override(overriding_container)
service = container.service()
assert isinstance(service, ServiceStub)
|
khapota/messages-terminal | test.py | Python | mit | 1,064 | 0.003759 | from mes | senger import Skype
import keyring
import utils
token = keyring.get_password('messagesReceiver', 'skypeToken')
registrationToken = keyring.get_password('messagesReceiver', 'skypeRegistrationToken')
username = keyring.get_password('messagesReceiver' | , 'skypeUsername')
password = keyring.get_password('messagesReceiver', 'skypePassword')
s = Skype(token, registrationToken)
if s.token == None:
s.login(username, password)
print "logging in..."
if s.registrationToken == None:
print s.createRegistrationToken()
print s.subcribe()
print "creating endpo... |
JGiola/swift | utils/swift_build_support/swift_build_support/products/llvm.py | Python | apache-2.0 | 2,666 | 0 | # swift_build_support/products/llvm.py --------------------------*- python -*-
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See https://swift.org/LICENSE.tx... | rs
self.cmake_options.extend(self._compiler_vendor_flags)
# Add the cmake options for compiler version information.
self.cmake_options.extend(self._version_flags)
@classmethod
def is_build_script_impl_product(cls):
"""is_build_script_impl_product -> boo | l
Whether this product is produced by build-script-impl.
"""
return True
@classmethod
def is_before_build_script_impl_product(cls):
"""is_before_build_script_impl_product -> bool
Whether this product is build before any build-script-impl products.
"""
r... |
Snesha/azure-linux-extensions | AzureEnhancedMonitor/ext/test/test_aem.py | Python | apache-2.0 | 15,614 | 0.00237 | #!/usr/bin/env python
#
#CustomScript extension
#
# Copyright 2014 Microsoft Corporation
#
# 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
#
#... | tualization Solution"
counter = next((c for c in counters if c.name == name))
self.assertNotEquals(None, counter)
self.assertNotEquals(None, counter.value)
name = "Instance Type"
counter = next((c for c in counters if c.na | me == name))
self.assertNotEquals(None, counter)
self.assertEquals("Small (A1)", counter.value)
name = "Data Sources"
counter = next((c for c in counters if c.name == name))
self.assertNotEquals(None, counter)
self.assertEquals("wad", counter.value)
name = "Data... |
TeppieC/M-ords | mords_backend/mords_api/migrations/0022_auto_20161212_0008.py | Python | mit | 441 | 0 | # -*- codi | ng: utf-8 -*-
# Generated by Django 1.10.2 on 2016-12-12 07:08
from __future__ import unicode_literals
from django.db import migrations
class Migrati | on(migrations.Migration):
dependencies = [
('mords_api', '0021_learningword'),
]
operations = [
migrations.RenameField(
model_name='learningword',
old_name='updated_date',
new_name='update_date',
),
]
|
bgarrels/sky | sky/dbpedia.py | Python | bsd-3-clause | 1,490 | 0 | import os
try:
from nltk.corpus import stopwords
stopset = set(stopwords.words('english'))
except ImportError:
print("Cannot use dbpedia without 'pip install nltk'")
try:
import ujson as json
except ImportError:
import json
def generate_testables(words, stopword_set, n_grams=4):
grams = set(... | set(word_list) & stopword_set:
continue
grams.add((" ".join([x[1] for x in ws]), " ".join(word_list)))
return grams
def get_dbpedia_from_words(pos_tags, db_dict, ok_entities=None):
if ok_entities is None:
ok_ | entities = ['Person', 'Organisation']
ws = generate_testables(pos_tags, stopset)
classes = []
for x in ws:
if x[1] in db_dict:
for y in db_dict[x[1]]:
if y in ok_entities:
classes.append(('db_' + y + '_' + x[0], x))
break
return... |
stefanwebb/tensorflow-models | tensorflow_models/trainers/svb_concrete_np.py | Python | mit | 3,783 | 0.019826 | # MIT License
#
# Copyright (c) 2017, Stefan Webb. All Rights Reserved.
#
# 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 us... | ls as tf_models
from tensorflow_models.trainers import BaseTrainer
class Trainer(BaseTrainer):
def finalize_hook(self):
print('Done trai | ning for {} epochs'.format(self.epoch()))
def learning_hooks(self):
train_op = tf_models.get_inference('elbo')
#train_loss_op = tf_models.get_loss('train/elbo_discrete')
#test_loss_op = tf_models.get_loss('test/elbo_discrete')
train_loss_op = tf_models.get_loss('train/elbo')
test_loss_op = tf_models.get_los... |
bncc/pycore | pycore/conf_handler.py | Python | gpl-3.0 | 660 | 0.037879 | import json_handler
class conf_handler:
__m_conf_path = None
__m_conf = None
def __init__( self, conf_base = "../conf/", conf_name = "configuration.conf" ):
s | elf.__m_conf_path = conf_base + conf_name
self.__m_conf = json_handler.json_handler(self.__m_conf_path)
def re | ad_conf( self, field_name ):
if(self.__m_conf == None):
return None
try:
conf_data = self.__m_conf.object_search(field_name)
except:
return None
return conf_data
|
TouK/vumi | vumi/transports/truteq/__init__.py | Python | bsd-3-clause | 114 | 0 | """TruT | eq transport | ."""
from vumi.transports.truteq.truteq import TruteqTransport
__all__ = ['TruteqTransport']
|
HBClab/xnat_BIDS | xnat_BIDS/xnat_BIDS.py | Python | mit | 16,386 | 0.014219 | #!/usr/bin/env python
from __future__ import absolute_import, division, print_function
import requests
import os
import sys
"""
Purpose:
Download dicoms from xnat and place them into
a BIDs "like" directory structure.
using the xnat rest API to download dicoms.
see here for xnat REST API documentation: ... | kie)
if dicom_query.ok:
dicom_zip = zipfile.ZipFile(BytesIO(dicom_query.content))
for member in dicom_zip.namelist():
filename = o | s.path.basename(member)
if not filename:
|
LamCiuLoeng/fd | rpac/widgets/ordering.py | Python | mit | 1,705 | 0.017009 | # -*- coding: utf-8 -*-
'''
Created on 2014-2-17
@author: CL.lam
'''
from sqlalchemy.sql.expression import and_
from rpac.widgets.components import RPACForm, RPACText, RPACCalendarPicker, \
RPACSelect
from rpac.model import ORDER_NEW, ORDER_INPROCESS, ORDER_COMPLETE, qry, \
PrintShop, ORDER_CANCEL
from rpac.mod... | o", label_text = "Create Date(to)"),
RPACSelect("status", label_text = "Status", options = [("", ""), (str(ORDER_NEW), "New"),
(str(ORDER_INPROCESS), "In Process"),
(st... | (str(ORDER_CANCEL), "Canelled"),
(str(ORDER_MANUAL), "Manual"),
]),
RPACSelect("printShopId", label_text = "Print Shop", options = getPrintShop),
]
o... |
eMerzh/Diamond-1 | src/diamond/handler/g_metric.py | Python | mit | 2,760 | 0 | # coding=utf-8
"""
Emulate a gmetric client for usage with
[Ganglia Monitoring System](http://ganglia.sourceforge.net/)
"""
from Handler import Handler
import logging
try:
import gmetric
except ImportError:
gmetric = None
class GmetricHandler(Handler):
"""
Implements the abstract Handler class, send... | lf, config=None):
"""
Create a new instance of the GmetricHandler class
"""
# Initialize Handler
Handler.__init__(self, config)
if gmetric is None:
logging.error("Failed to load gmetric module")
return
# Initialize Data
self.socke... | otocol']
if not self.protocol:
self.protocol = 'udp'
# Initialize
self.gmetric = gmetric.Gmetric(self.host, self.port, self.protocol)
def get_default_config_help(self):
"""
Returns the help text for the configuration options for this handler
"""
... |
danbradham/shadeset | shadeset/ui/widgets.py | Python | mit | 15,611 | 0 | # -*- coding: utf-8 -*-
from __future__ import print_function
# Standard library imports
import os
from fnmatch import fnmatch
# Local imports
from . import res
from .. import api, lib, utils
# Third party imports
from .Qt import QtCore, QtGui, QtWidgets
class WindowHeader(QtWidgets.QWidget):
def __init__(sel... | self.asset.currentItemChanged.connect(self.on_asset_changed)
self._projects = None
self.update_form()
def state(self):
# Get selected project
project = self.project.currentText()
# Get selected asset
asset_item = self.asset.currentItem()
asset = None... | sset = asset_item.asset
# Get selected shadeset
shadeset_item = self.shadeset.currentItem()
shadeset = None
if shadeset_item:
shadeset = shadeset_item.publish
return dict(
project=project,
asset=asset,
shadeset=shadeset,
... |
zkmake520/ProbabilisticModel | NGram/NGram.py | Python | mit | 7,676 | 0.046769 | #here we can use wrapper to accerlate the whole process, since many text may be same, we can save the intermediate results
import operator
from math import log10
import re
import string
import random
import heapq
"""First Part:
Word Segmentation"""
def memory(f):
#memorize function f
table = {}
def fme... | 2l):
print bigram
b1,b2=bigram
for c in alphabet:
if b1 == b2:
if P2l(c+c) | > P2l(bigram): yield swap(c,b1)
else:
if P2l(c+b2) > P2l(bigram): yield swap(c,b1)
if P2l(b1+c) > P2l(bigram): yield swap(c,b2)
while True:
yield swap(random.choice(alphabet), random.choice(alphabet))
cat = ''.join
"""
Spelling Correction:
Find argmaxcP(c|w) which means type w, c is the candidate... |
mozman/ezdxf | tests/test_00_dxf_low_level_structs/test_054_dxfattr.py | Python | mit | 541 | 0 | # Copyright (c) 2020, Manfred Moitzi
# License: MIT License
import pytest
from ezdxf. | lldxf.attributes import DXFAttr, RETURN_DEFAULT
def test_return_default():
attr = D | XFAttr(
code=62,
default=12,
validator=lambda x: False,
fixer=RETURN_DEFAULT,
)
assert attr.fixer(7) == 12
attr2 = DXFAttr(
code=63,
default=13,
validator=lambda x: False,
fixer=RETURN_DEFAULT,
)
assert attr2.fixer(7) == 13
if __name... |
Ichaelus/Github-Classifier | Application/Models/ClassificationModules/descriptionreponamelstm.py | Python | mit | 3,641 | 0.005774 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from Models.FeatureProcessing import *
from keras.models import Sequential
from keras.layers import Activation, Dense, LSTM
from keras.optimizers import Adam, SGD
import numpy as np
import abc
from ClassificationModule import ClassificationModule
class descriptionreponame... | = self.model.fit(train_samples, train_lables, nb_epoch=nb_epoch, shuffle=shuffle, verbose=verbose, class_weight=getClassWeights())
self.isTrained = True
return train_result
def predictLabel(self, sample):
"""Gibt zurück, wie der Klassifikat | or ein gegebenes Sample klassifizieren würde"""
if not self.isTrained:
return 0
sample = self.formatInputData(sample)
return np.argmax(self.model.predict(sample))
def predictLabelAndProbability(self, sample):
"""Return the probability the module assignes each label""... |
niranjan94/open-event-orga-server | app/models/page.py | Python | gpl-3.0 | 1,304 | 0.000767 | from app.models import db
class Page(db.Model):
"""Page model class"""
__tablename__ = 'pages'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String, nullable=False)
title = db.Column(db.String)
url = db.Column(db.String, nullable=False)
description = db.Column(db.String)... | return '<Page %r>' % self.name
def __s | tr__(self):
return unicode(self).encode('utf-8')
def __unicode__(self):
return self.name
@property
def serialize(self):
"""Return object data in easily serializeable format"""
return {
'id': self.id,
'name': self.name,
'description': self... |
adrn/gala | gala/integrate/tests/test_pyintegrators.py | Python | mit | 3,454 | 0.000579 | """
Test the integrators.
"""
import os
# Third-party
import pytest
import numpy as np
# Project
from .. import (
LeapfrogIntegrator,
RK5Integrator,
DOPRI853Integrator,
Ruth4Integrator,
)
from gala.tests.optional_deps import HAS_TQDM
# Integrators to test
integrator_list = [
RK5Integrator,
... | rator):
integrator = Integrator(sho_F, func_args=(1.0,))
dt = 1e-4
n_steps = 10_000
forw = integrator.run([0.0, 1.0], dt=dt, n_steps=n_steps)
back = integrator.run([0.0, 1.0], dt=-dt, n_steps=n_steps)
assert np.allclose(forw.w()[:, -1], back. | w()[:, -1], atol=1e-6)
@pytest.mark.parametrize("Integrator", integrator_list)
def test_point_mass(Integrator):
q0 = np.array([1.0, 0.0])
p0 = np.array([0.0, 1.0])
integrator = Integrator(ptmass_F)
orbit = integrator.run(np.append(q0, p0), t1=0.0, t2=2 * np.pi, n_steps=1e4)
assert np.allclose(or... |
ngalin/Illumimateys | InterviewPrepScripts/videoCapture.py | Python | mit | 760 | 0.021053 | import numpy as np
import cv2
im | port time
start = time.time()
end = start + 3 #show video for three seconds - I do this to make sure your stream doesn't get stuffed up by a bad exit. Remove in future.
cap = cv2.VideoCapture(0)
#while time.time() < end: #
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
if frame == None:
... | r,(10,10))
out = cv2.merge((b_new,g_new,r_new))
cv2.imshow('frame',out)
if cv2.waitKey(1) & 0xFF == ord('q'):
cap.release()
cv2.destroyAllWindows()
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
|
gzxultra/IM_programming | class_ClientMessage.py | Python | gpl-2.0 | 6,373 | 0.007857 |
# _*_ coding:utf-8 _*_
# Filename:ClientUI.py
# Python在线聊天客户端
from socket import *
from ftplib import FTP
import ftplib |
import socket
import thread
import time
import sys
import codec | s
import os
reload(sys)
sys.setdefaultencoding( "utf-8" )
class ClientMessage():
#设置用户名密码
def setUsrANDPwd(self,usr,pwd):
self.usr=usr
self.pwd=pwd
#设置目标用户
def setToUsr(self,toUsr):
self.toUsr=toUsr
self.ChatFormTitle=toUsr
#设置ip地址和端口号
def setLocalANDPort(self,... |
pisskidney/leetcode | medium/89.py | Python | mit | 385 | 0 | """
89. Gray Code
https://leetcode.com/problems/gray-code/
"""
from typing import List
class Solution:
def grayCode(self, n: int) -> List[int]:
res = [0]
| for i in range(n):
res += [x + 2**i for x in reversed(res)]
return res
def ma | in():
s = Solution()
print(s.grayCode(3))
if __name__ == '__main__':
raise(SystemExit(main()))
|
2uller/LotF | App/Lib/distutils/util.py | Python | gpl-2.0 | 19,215 | 0.002082 | """distutils.util
Miscellaneous utility functions -- anything that doesn't fit into
one of the other *util.py modules.
"""
__revision__ = "$Id$"
import sys, os, string, re
from distutils.errors import DistutilsPlatformError
from distutils.dep_util import newer
from distutils.spawn import spawn
from distu... | (all others - specifically, sys.platform is returned)
For other non-POSIX platforms, currently just returns 'sys.platform'.
"""
if os.name == 'nt':
# sniff sys.version for architecture.
prefix = " bit ("
i = string.find(sys.version, prefix)
if i == -1:
| return sys.platform
j = string.find(sys.version, ")", i)
look = sys.version[i+len(prefix):j].lower()
if look=='amd64':
return 'win-amd64'
if look=='itanium':
return 'win-ia64'
return sys.platform
# Set for cross builds explicitly
if "... |
netjunki/trac-Pygit2 | trac/prefs/api.py | Python | bsd-3-clause | 1,093 | 0.00183 | # -*- coding: utf-8 -*-
#
# Copyright (C)2006-2009 Edgewall Software
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://trac.edgewall.org/wiki/TracLicense.
#
# This software consis... | """
def render_preference_panel(req, panel):
"""Process a request for a preference pa | nel.
This function should return a tuple of the form `(template, data)`,
where `template` is the name of the template to use and `data` is the
data to be passed to the template.
"""
|
quxiaolong1504/cloudmusic | cmmedia/views.py | Python | mpl-2.0 | 1,809 | 0.009913 | # encoding=utf-8
from django.utils.translation import ugettext | _lazy as _
from rest_framework.response import Response
from rest_framework.reverse import reverse
from rest_framework.views import APIView
from rest_framework import generics
from rest_framework.viewsets import ModelViewSet
from cmmedia.models import Image, Artist, Album, Music
f | rom cmmedia.serializers import ImageSerializer, ArtistSerializer, AlbumSerializer, MusicSerializer
class ResourceURLView(APIView):
allowed_methods = ['GET']
def get(self,request,*args,**kwargs):
return Response(self.get_url_dispach())
def get_url_dispach(self,format=None):
return {
... |
joachimmetz/plaso | plaso/analysis/tagging.py | Python | apache-2.0 | 2,057 | 0.006806 | # -*- coding: utf-8 -*-
"""Analysis plugin that labels events according to rules in a tagging file."""
from plaso.analysis import interface
from plaso.analysis import manager
from plaso.engine import tagging_file
class TaggingAnalysisPlugin(interface.AnalysisPlugin):
"""Analysis plugin that labels events according... | supported.
if filter_object.Match(event, event_data, event_data_stream, None):
| matched_label_names.append(label_name)
break
if matched_label_names:
event_tag = self._CreateEventTag(event, matched_label_names)
analysis_mediator.ProduceEventTag(event_tag)
for label_name in matched_label_names:
self._analysis_counter[label_name] += 1
self._analysis_c... |
chrislyon/dj_ds1 | datatable/admin.py | Python | gpl-2.0 | 375 | 0.016 | from d | jango.contrib import admin
# Register your models here.
from datatable.models import Serveur
# Register your models here.
class ServeurAdmin(admin.ModelAdmin):
list_display = ('In_Type', 'In_Nom', 'In_IP', 'statut')
list_filter = ('In_Type', 'In_Nom', 'In_IP', 'statut')
search_fields = ['In_Type', 'In_Nom', 'In_I... | eurAdmin)
|
pombredanne/libming | test/Font/test03.py | Python | lgpl-2.1 | 384 | 0.020833 | #!/usr/bin/python
from ming import *
import sys
srcdir=sys.argv[1]
m = SWFMovie();
font = SWFFont(srcdir + "/../Media/test.ttf") |
text = SWFText(1)
w = font.getStringWidth("The quick brown fox jumps over the lazy dog. 1234567890")
text.setFont(font)
text.setColor(0,0,0,255)
text.setHeight(20)
text.moveTo(w,0)
| text.addString("|")
m.add(text)
m.nextFrame()
m.save("test03.swf")
|
zhengwsh/InplusTrader_Linux | InplusTrader/backtestEngine/model/tick.py | Python | mit | 2,130 | 0 | # -*- coding: utf-8 -*-
#
# Copyright 2017 Ricequant, 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 ... | TIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
class Tick(object):
def __init__(self, order_book_id, dt, snapshot):
self._order_book_id = order_book_id
self._dt = dt
self._sna... | rder_book_id(self):
return self._order_book_id
@property
def datetime(self):
return self._dt
@property
def open(self):
return self._snapshot['open']
@property
def last(self):
return self._snapshot['last']
@property
def high(self):
return self._... |
Jecvay/PyGDB | PyGdbDb.py | Python | mit | 10,962 | 0.003274 | # coding=utf-8
import pymysql
import PyGdbUtil
class PyGdbDb:
# 初始化: 连接数据库
def __init__(self, host, port, dbname, user, passwd):
self.project = None
self.table_prefix = None
try:
self.connection = pymysql.connect(
host=host, port=int(port), user=user, passwor... | table_prefix + "PStackSize(pid INT, tid INT, stackSize INT, pass TINYINT)")
self.create_table(self.table_prefix + "FStackSize(pid INT, tid INT, fid INT, stackSize INT)")
self.create_table(self.table_prefix + "FrameVariable(bid INT, varName CHAR, varValue TEXT, varSize INT)")
self.cre... | elf.table_prefix + "FuncAdjacencyList(pid INT, tid INT, parFid INT, fid INT, cnt INT)")
self.create_table(self.table_prefix + "Function(fid INT, funcName CHAR(30))")
self.create_table(self.table_prefix + "TestCase(tid INT AUTO_INCREMENT primary key, testStr TEXT)")
self.commit()
... |
rkryan/seniordesign | pi/utils/startup_ip.py | Python | gpl-2.0 | 865 | 0.006936 | import subprocess
import smtplib
import socket
from email.mime.text import MIMEText
import datetime
# Change to your own account information
to = 'rk.ryan.king@gmail.com'
gmail_user = 'rk.ryan.king@gmail.com'
gmail_password = 'nzwaahcmdzjchxsz'
smtpserver = smtplib.SMTP('smtp.gmail.com', 587)
smtpserver.ehlo()
smtp | server.starttls()
smtpserver.ehlo
smtpserver.login(gmail_user, gmail_password)
today = datetime.date.today()
# Very Linux Specific
arg='ip route list'
p=subprocess.Popen(arg,shell=True,stdout=subprocess.PIPE)
data = p.communicate()
split_data = data[0].split()
ipaddr = split_data[split_data.index('src')+1]
my_ip = 'You... | berryPi on %s' % today.strftime('%b %d %Y')
msg['From'] = gmail_user
msg['To'] = to
smtpserver.sendmail(gmail_user, [to], msg.as_string())
smtpserver.quit() |
popazerty/beyonwiz-4.1 | lib/python/Components/Converter/EGExtraInfo.py | Python | gpl-2.0 | 10,356 | 0.039784 | # Based on PliExtraInfo
# Recoded for Black Pole by meo.
# Recodded for EGAMI
from enigma import iServiceInformation
from Components.Converter.Converter import Converter
from Components.Element import cached
from Poll import Poll
class EGExtraInfo(Poll, Converter, object):
def __init__(self, type):
Converter.__in... | res += color + caid_entry[3]
res += "\c00??????"
return res
return ""
text = property(getText)
@cached
def getBool(self):
service = | self.source.service
info = service and service.info()
if not info:
return False
if self.type == "CryptoCaidSecaAvailable":
request_caid = "S"
request_selected = False
elif self.type == "CryptoCaidViaAvailable":
request_caid = "V"
request_selected = False
elif self.type == "CryptoCaidIrdetoAv... |
kenshay/ImageScript | Script_Runner/PYTHON/Lib/lib2to3/tests/test_refactor.py | Python | gpl-3.0 | 12,405 | 0.000564 | """
Unit tests for refactor.py.
"""
import sys
import os
import codecs
import io
import re
import tempfile
import shutil
import unittest
from lib2to3 import refactor, pygram, fixer_base
from lib2to3.pgen2 import token
TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), "data")
FIXER_DIR = os.path.join(TEST_DATA... | _" + name for name in contents])
| self.assertEqual(non_prefixed, contents)
self.assertEqual(full_names,
["myfixes.fix_" + name for name in contents])
def test_detect_future_features(self):
run = refactor._detect_future_features
fs = frozenset
empty = fs()
self.assertEqual(run(""), ... |
bowen0701/algorithms_data_structures | lc0124_binary_tree_maximum_path_sum.py | Python | bsd-2-clause | 2,485 | 0.002012 | """Leetcode 124. Binary Tree Maximum Path Sum
Hard
URL: https://leetcode.com/problems/binary-tree-maximum-path-sum/
Given a non-empty binary tree, find the maximum path sum.
For this problem, a path is defined as any sequence of nodes from some starting
node to any node in the tree along the parent-child connections... | (-10)
root.left = TreeNode(9)
root.right = TreeNode(20)
root.right.left = TreeNode(15)
root.right.right = TreeNode(7)
print SolutionLeftRightMaxPathDownSumRecur().maxPathSum(root)
if __nam | e__ == '__main__':
main()
|
rwalk333/straw | src/frontend/app/views.py | Python | mit | 3,744 | 0.00641 | #!/usr/bin/python
'''
Define the views for the straw web app
'''
from flask import render_template, session, request, render_template, jsonify, Flask, make_response
from time import sleep
from kafka.common import FailedPayloadsError, NotLeaderForPartitionError, KafkaUnavailableError
import md5, redis
import json, uuid
... | post_success=True
break
if post_success==True:
# subscribe the user to the query
try:
app.user_channels[qid].add(sid)
except KeyError:
app.user_channels[qid] = set([sid])
app.subscriber.add_qu... | ink the id to the query text
redis_connection.set(qid, " ".join(text))
# add query to the list of things the user has subscribed to
redis_connection.lpush(sid +"-queries", qid)
# update the query list in the view
query_list = session["queries"]
return render... |
andymckay/zamboni | mkt/users/models.py | Python | bsd-3-clause | 9,476 | 0.000106 | from contextlib import contextmanager
from datetime import datetime
from django import forms
from django.conf import settings
from django.contrib.auth.models import AbstractBaseUser
from django.core import validators
from django.db import models
from django.utils import translation
from django.utils.encoding import sm... |
@amo.cached_property
def is_developer(self):
return self.addonuser_set.exists()
@property
def name(self):
return smart_unicode(self.display_name or self.username)
@amo.cached_propert | y
def reviews(self):
"""All reviews that are not dev replies."""
qs = self._reviews_all.filter(reply_to=None)
# Force the query to occur immediately. Several
# reviews-related tests hang if this isn't done.
return qs
def anonymize(self):
log.info(u"User (%s: <%s>... |
montgok/Python_Class | python_test2.py | Python | apache-2.0 | 31 | 0.096774 | for i in range (10):
print | i
| |
vault/bugit | user_manage/views.py | Python | mit | 4,105 | 0.004629 | from django.http import HttpResponse
from django.shortcuts import render_to_response, redirect, get_object_or_404
from django.forms.models import model_to_dict
from django.forms.util import ErrorList
from django.template import RequestContext
from django.db import IntegrityError
from django.core.exceptions import Objec... | commit=False)
key.owner = user
try:
key.save()
ret | urn redirect('user_settings')
except IntegrityError:
form._errors["description"] = ErrorList(["You have a public key with that name already"])
context = get_context(request, {'form' : form})
return render_to_response('user_manage/key_edit.html', context, context_instance=RequestConte... |
ivanhorvath/openshift-tools | openshift/installer/vendored/openshift-ansible-git-2016-04-18/roles/lib_yaml_editor/build/src/yedit.py | Python | apache-2.0 | 6,339 | 0.001735 | # pylint: skip-file
class YeditException(Exception):
''' Exception class for Yedit '''
pass
class Yedit(object):
''' Class to modify yaml files '''
re_valid_key = r"(((\[-?\d+\])|([a-zA-Z-./]+)).?)+$"
re_key = r"(?:\[(-?\d+)\])|([a-zA-Z-./]+)"
def __init__(self, filename=None, content=None, c... | try:
if content_type == 'yaml':
self.yaml_dict = yaml.load(contents)
elif content_type == 'json':
self.yaml_dict = json.loads(contents)
except yaml.YAMLError as _:
# Error loading y | aml or json
return None
return self.yaml_dict
def get(self, key):
''' get a specified key'''
try:
entry = Yedit.get_entry(self.yaml_dict, key)
except KeyError as _:
entry = None
return entry
def delete(self, key):
''' remove... |
google-research/google-research | smu/geometry/topology_from_geom_test.py | Python | apache-2.0 | 8,417 | 0.00202 | # coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# 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 applicab... | try())
geometry.atom_positions[1].x = 1.4 / smu_utils_lib.BOHR_TO_ANGSTROMS
matching_parameters = smu_molecule.MatchingParameters()
matching_parameters.must_match_all_bonds = False
fate = dataset_pb2.Conformer.FATE_SUCCESS
conformer_id = 1001
result = topology_from_geom.bond_topologies_from_geo... | rs)
self.assertIsNotNone(result)
self.assertLen(result.bond_topology, 2)
self.assertLen(result.bond_topology[0].bonds, 1)
self.assertLen(result.bond_topology[1].bonds, 1)
self.assertEqual(result.bond_topology[0].bonds[0].bond_type, single_bond)
self.assertEqual(result.bond_topology[1].bonds[0].b... |
GeoscienceAustralia/sifra | __main__.py | Python | apache-2.0 | 11,130 | 0.001977 | #!/usr/bin/env python
# # -*- coding: utf-8 -*-
"""
title : __main__.py
description : entry point for core sira component
usage : python sira [OPTIONS]
-h Display this usage message
-d [input_directory] Specify the directory with the required
... | after a complete run with `-s` flag
-l Conduct loss analysis. Must be done
after a complete run with `-s` flag
-v [LEVEL] Choose `verbose` mode, or choose logging
level D... | __ import print_function
import sys
import numpy as np
np.seterr(divide='print', invalid='raise')
import time
import re
from colorama import init, Fore, Back, Style
init()
import os
import argparse
from sira.logger import configure_logger
import logging
import logging.config
from sira.configuration import Configura... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.