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 |
|---|---|---|---|---|---|---|---|---|
MatthieuMichon/f24 | src/v1/data_suppliers/cache.py | Python | gpl-2.0 | 2,208 | 0 | #!/usr/bin/python3
"""
f24.data_suppliers.cache
~~~~~~~~~~~~~~~~~~~~~~~~
This module contains the class implementing a simple cache.
"""
import hashlib
import os
import time
import json
from pathlib import Path
class Cache:
CACHE_DIR = 'cache_db'
CACHE_FILENAME_LEN = 40
def __init__(self):
p =... | arg=luzl", ttl=3')
my_dict = {}
my_dic | t['key1'] = 'arg1'
my_dict['key2'] = 'arg2'
c.store('example.com/path/filename?arg=lol', my_dict)
if __name__ == "__main__":
main()
|
memsharded/conan | conans/test/unittests/model/options_test.py | Python | mit | 17,355 | 0.00219 | import sys
import unittest
import six
from conans.errors import ConanException
from conans.model.options import Options, OptionsValues, PackageOptionValues, PackageOptions, \
option_undefined_msg
from conans.model.ref import ConanFileReference
class OptionsTest(unittest.TestCase):
def setUp(self):
... | alse)
bo | ost_values.add_option("path", "FuzzBuzz")
options = {"Boost.*": boost_values}
own_ref = ConanFileReference.loads("Boost.Assert/0.1@diego/testing")
down_ref = ConanFileReference.loads("Consumer/0.1@diego/testing")
self.sut.propagate_upstream(options, down_ref, own_ref)
self.asser... |
melt6457/MMProteinAnalysis | Source/presentation.py | Python | mit | 2,760 | 0.002174 | import ProteinAnalyzer as pa
import fileManager as files
import matplotlib.pyplot as plt
import simulation
print('End of Summer Presentation Files')
simNames = pa.selectMultipleSimulations()
simNames2 = pa.selectMultipleSimulations()
sims = []
sims2 = []
simNames3 = pa.selectMultipleSimulations()
sims3 = []
for coun... | MSD()
sims2.append(sim2)
for num in range(1, len(simNames2)):
sims2[0].combine(sims2[num])
# sims2[0].rmsd.calculateFrameTimes(0, sims2[0].log.getEndTime() - sims2[0].log.getStartTime())
# plt.plot(sims2[0].rmsd.times, sims2[0].rmsd.RMSDs)
plt.plot(sims2[0].log.times, sims2[0].log.pot_energy)
'''for count in... | sim3.loadRMSD()
sims3.append(sim3)
for count in range(1, len(simNames)):
sims3[0].combine(sims[count])
plt.plot(sims3[0].log.times, sims3[0].log.pot_energy)'''
avePotEnergy = sims[0].calcAvePotentialEnergy()
avePotEnergy2 = sims2[0].calcAvePotentialEnergy()
#avePotEnergy3 = sims3[0].calcAvePotentialEnergy... |
qiita-spots/qp-shotgun | qp_shogun/shogun/shogun.py | Python | bsd-3-clause | 10,590 | 0 | # - | ------------------------------------------------------ | ----------------------
# Copyright (c) 2014--, The Qiita Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed with this software.
# -----------------------------------------------------------------------------
from os.path import join
fr... |
kaiweifan/vse-lbaas-plugin-poc | quantum/plugins/bigswitch/plugin.py | Python | apache-2.0 | 52,432 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 Big Switch Networks, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.a... | quantum import policy
LOG = logging.getLogger(__name__ | )
restproxy_opts = [
cfg.StrOpt('servers', default='localhost:8800',
help=_("A comma separated list of servers and port numbers "
"to proxy request to.")),
cfg.StrOpt('server_auth', default='username:password', secret=True,
help=_("Server authentication")),
... |
kevalds51/sympy | sympy/geometry/polygon.py | Python | bsd-3-clause | 62,413 | 0.000417 | from __future__ import division, print_function
from sympy.core import Expr, S, Symbol, oo, pi, sympify
from sympy.core.compatibility import as_int, range
from sympy.functions.elementary.complexes import sign
from sympy.functions.elementary.piecewise import Piecewise
from sympy.functions.elementary.trigonometric impor... | sequence of points
or from a center, radius, number of sides and rotation angle.
Parameters
==========
vertices : sequence of Points
Attributes
==========
area
angles
perimeter
vertices
centroid
sides
Raises
======
GeometryError
If all parameters... |
See Also
========
sympy.geometry.point.Point, sympy.geometry.line.Segment, Triangle
Notes
=====
Polygons are treated as closed paths rather than 2D areas so
some calculations can be be negative or positive (e.g., area)
based on the orientation of the points.
Any consecutive ide... |
klahnakoski/jx-sqlite | vendor/jx_base/expressions/base_inequality_op.py | Python | mpl-2.0 | 1,864 | 0.000536 | # encoding: utf-8
#
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http:# mozilla.org/MPL/2.0/.
#
# Contact: Kyle Lahnakoski ([email protected])
#
from __future__ import absolute_import, divis... | om mo_json.types import T_BOOLEAN
class BaseInequalityOp(Expression):
has_simple_form = True
data_type = T_BOOLEAN
op = None
def __init__(self, terms):
Expression.__init__(self, terms)
self.lhs, self.rhs = terms
@property
def name(self):
return self.op
def __data... | s.value}}
else:
return {self.op: [self.lhs.__data__(), self.rhs.__data__()]}
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return self.op == other.op and self.lhs == other.lhs and self.rhs == other.rhs
def vars(self):
re... |
OmairAJ/Plagia | local/indexMap.py | Python | gpl-2.0 | 4,474 | 0.023469 | #indexMap.py
# python indexMap.py -s -d test.txt
import os
import sys
import math
import string
import argparse
import fileinput
## Casefold text
def casefold(text):
text = text.lower()
text = text.translate(string.maketrans("",""), string.punctuation)
text = text.split()
text = filter(None, text)
return text
... | keys = []
# this code is pretty messed up
# need to clean it and
# fix the words start and end
# positions calculation/processing
for i in range(len(keyList)):
j = 0
k = 0
subKeys = keyPattern(keyList[i + 1:], patternSize - 1, startPosition, endPosition, False)
for subKey in subKeys:
key = ""
key = k... | osition = startPosition + patternSize + j - 1
if flag:
j += 1
k += 1
keyI = [key, startPosition, endPosition, documentFile]
else:
keyI = key
keys.append(keyI)
return keys
## Generate n-grams
def genNGrams(wordList, windowSize, overlapSize, fileName):
nGrams = []
for i in range(len(wordList)... |
rgeorgi/intent | intent/scripts/igt/extract_lang.py | Python | mit | 2,741 | 0.008026 | """
Created on Dec 19, 2014
@author: rgeorgi
This script is used to point at a dump of the ODIN database and extract the specified language from it.
"""
# Built-in imports -------------------------------------------------------------
import argparse, re, logging
import sys
EXTR_LOG = logging.getLogger('LANG_EXTRACT... | p.add_argument('-d', '--dir', help="Path to the ODIN database directory.", required=True)
p.add_argument('-l', '--lang', help="Language to search for.", required=True)
p.add_argument( | '-o', '--outfile', help="Text file which to output the resulting instances to.", required=True, type=writefile)
args = p.parse_args()
extract_lang(args.dir, args.lang, args.outfile) |
bataeves/kaggle | instacart/imba/arboretum_cv.py | Python | unlicense | 18,971 | 0.005587 | import gc
from concurrent.futures import ThreadPoolExecutor
import pandas as pd
import numpy as np
import os
import arboretum
import json
import sklearn.metrics
from sklearn.metrics import f1_score, roc_auc_score
from sklearn.model_selection import train_test_split
from scipy.sparse import dok_matrix, coo_matrix
from ... | ed_prev',
'add_to_cart_order': 'add_to_cart | _order_prev',
'order_dow': 'order_dow_prev',
'order_hour_of_day': 'order_hour_of_day_prev'
}, inplace=True)
products = pd.read_csv(os.path.join(path, "products.csv"), dtype={'product_id': np.uint16,
'aisle_id': np.uint8,
... |
cmdelatorre/roses | roses_project/settings.py | Python | gpl-2.0 | 2,124 | 0 | """
Django settings for roses_project project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, .... | # See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '!5ju*8(7&c3*y2nt$$^r%eecs95uo!237^0ke-$!bgwj)-%u^$'
# SECURITY | WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'djan... |
a2ialabelme/LabelMeAnnotationTool | labelFile.py | Python | gpl-3.0 | 10,321 | 0.024126 | # -*- coding : utf-8 -*-
#
# Copyright (C) 2011 Michael Pitidis, Hussein Abdulwahid.
#
# This file is part of Labelme.
#
# Labelme 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 Licens... | None: # bounding box
top = int(snip.get('Top'))
left = int(snip.get('Left'))
bottom = int( | snip.get('Bottom'))
right = int(snip.get('Right'))
return [[left,top], [right,top], [right,bottom], [left,bottom]]
elif snip.get('polygon') != None:
return [[int(x[0]),int(x[1])] for x in [z.split(',') for z in snip.get('polygon').replace('(', '').replace(')', '').split(';')]]
def polyFromPoints(p... |
google-research/google-research | simulation_research/traffic/random_traffic_generator_test.py | Python | apache-2.0 | 13,728 | 0.002258 | # 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... | ut_output, 21)
def test_setup_shortest_routes(self):
# Test case for freeways.
input_output = self._random_traffic_generator.get_freeway_input_output()
output_file = os.path.join(self._output_dir, 'freeway_routes.xml')
routes = self._random_traffic_generator.setup_shortest_routes(
input_outpu... | t_file,
figures_folder=self._output_dir)
self.assertLen(routes, 3)
routes_length = [routes[0]['route_length'],
routes[1]['route_length'],
routes[2]['route_length']]
routes_length.sort()
self.assertAlmostEqual(routes_length[0], 450.18)
self.assertAlmo... |
OCA/account-analytic | analytic_tag_dimension/models/account_move_line.py | Python | agpl-3.0 | 393 | 0 | # Copyright 2017 PESOL (http://pesol.es) - Angel Moya ([email protected])
# Copyr | ight 2020 Tecnativa - Carlos Dauden
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import models
class AccountMoveLine(models.Model):
_name = "account.move.line"
_inherit = ["analytic.dime | nsion.line", "account.move.line"]
_analytic_tag_field_name = "analytic_tag_ids"
|
Irides-Chromium/python_modules | modules/__init__.py | Python | gpl-3.0 | 71 | 0 | #!/usr/bin/python3
from | scale import scale
from putchar | import putchar
|
mabotech/maboss.py | maboss/motorx/jobexecutor/je_server1.py | Python | mit | 1,138 | 0.018453 |
# -*- coding: utf-8 -*-
import sys
import logging
import logging.handlers
import logging.config
from config import CENTRAL_CONFIG
#from config import LOGGING_CFG_SRV, ENDPOINT
#logging.config.fileConfig(LOGGING_CFG_SRV)
#log = logging.getLogger(__name__)
import time
from time import strftime, localtime
import ... | c.Server):
def __init__(self):
# initialize parent class
super(JobExecutorServer, self).__init__()
def execute(self, name, args, func_type='PY'):
module_path = "c | :/mtp/mabotech/maboss1.1"
log.debug("[%s]%s:%s" % (module_path, func_type, name) )
rtn = py_executor.execute(name, args, module_path)
return rtn
def run():
endpoint = ENDPOINT
srv = JobExecutorServer()
srv.bind(endpoint)
log.... |
noironetworks/neutron | neutron/agent/l2/l2_agent_extensions_manager.py | Python | apache-2.0 | 2,311 | 0.000433 | # 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.or | g/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, so | ftware
# 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_log import log
from neutron.agent import ag... |
tuxfux-hlp-notes/python-batches | archieves/batch-57/debugging/first.py | Python | gpl-3.0 | 954 | 0.041929 | #!/usr/bin/python
# usage: A debugging class
import pdb
version=2.0
def my_add(a,b):
''' This is the function for addition of numbers and strings '''
print "value of a is {}".format(a)
print "value of b is {}".format(b)
return a+b
def my_div(a,b):
''' This is the function for division '''
return a/b
... | on of two numbers - {}".format(my_sub(1,2))
print "division | of two numbers - {}".format(my_div(4,2))
|
simpeg/simpeg | SimPEG/electromagnetics/utils/__init__.py | Python | mit | 212 | 0 | from .waveform_utils | import omega, k, VTEMFun, TriangleFun, SineFun
from .current_utils import (
getStraightLineCurrentIntegral,
getSourceTermLineCurrentPolygon,
segmented_line_current_source_term,
)
| |
getsentry/sentry-auth-github | sentry_auth_github/client.py | Python | apache-2.0 | 1,850 | 0.002703 | from __future__ import absolut | e_import
import six
from r | equests.exceptions import RequestException
from sentry import http
from sentry.utils import json
from .constants import API_DOMAIN
class GitHubApiError(Exception):
def __init__(self, message='', status=0):
super(GitHubApiError, self).__init__(message)
self.status = status
class GitHubClient(obj... |
GbalsaC/bitnamiP | venv/lib/python2.7/site-packages/sklearn/datasets/mldata.py | Python | agpl-3.0 | 6,651 | 0.00015 | """Automatically download MLdata datasets."""
# Copyright (c) 2011 Pietro Berkes
# License: Simplified BSD
import os
from os.path import join, exists
import re
import numpy as np
import scipy as sp
from scipy import io
from shutil import copyfileobj
import urllib2
from .base import get_data_home, Bunch
MLDATA_BASE_... | t with their original name.
Parameters
----------
dataname:
Name of the data set on mldata.org,
e.g.: "leukemi | a", "Whistler Daily Snowfall", etc.
The raw name is automatically converted to a mldata.org URL .
target_name: optional, default: 'label'
Name or index of the column containing the target values.
data_name: optional, default: 'data'
Name or index of the column containing the data.
... |
AutorestCI/azure-sdk-for-python | azure-servicefabric/azure/servicefabric/models/service_type_info.py | Python | mit | 1,980 | 0.00202 | # 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 ... | ---------------------------------------
from msrest.serialization import Model
class ServiceTypeInfo(Model):
"""Information about a service type that is defined in a service manifest of a
provisioned application type.
:param service_type_description:
:type servic | e_type_description: :class:`ServiceTypeDescription
<azure.servicefabric.models.ServiceTypeDescription>`
:param service_manifest_name:
:type service_manifest_name: str
:param service_manifest_version: The version of the service manifest in
which this service type is defined.
:type service_manif... |
zbyte64/django-hyperadmin | hyperadmin/models.py | Python | bsd-3-clause | 1,912 | 0.007845 | """
Helper function for logging all events that come through the API.
"""
# TODO Write logging model
from contextlib import contextmanager |
import logging
from django.utils.encoding import smart_unicode
from django.utils.translation import ugettext_lazy as _
class RelList(list):
"""
A list subclass that allows u | s to use dot notation to search for elements
that match the reltype.
>>> links = RelList([{"rel":"self", "href": "self"}, {"rel":"other", "href":"other"}])
>>> links.self["href"]
'self'
>>> links.other["href"]
'other'
>>> links.foo
"""
def __getattr__(self, name):
f... |
jianajavier/pnc-cli | pnc_cli/swagger_client/models/build_record_set_singleton.py | Python | apache-2.0 | 2,941 | 0 | # coding: utf-8
"""
Copyright 2015 SmartBear Software
Licensed unde | r 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 ... |
bwrsandman/openerp-hr | hr_language/hr_language.py | Python | agpl-3.0 | 1,839 | 0.003263 | # -*- encoding: utf-8 -*-
###############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2013 Savoir-faire Linux (<http://www.savoirfairelinux.com>).
#
# This program is free software: you can redistribute it and/or modify
# it un... | ANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
... | = 'hr.language'
_columns = {
'name': fields.selection(tools.scan_languages(), 'Language', required=True),
'description': fields.char('Description', size=64, required=True, translate=True),
'employee_id': fields.many2one('hr.employee', 'Employee', required=True),
'read': fields.boolea... |
gokudomatic/cobiv | cobiv.py | Python | mit | 78 | 0 | from | cobiv.Mai | nApp import Cobiv
if __name__ == '__main__':
Cobiv().run()
|
t3dev/odoo | addons/crm/models/res_partner.py | Python | gpl-3.0 | 2,508 | 0.00319 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
class Partner(models.Model):
_inherit = 'res.partner'
team_id = fields.Many2one('crm.team', string='Sales Team', oldname='section_id')
opportunity_ids = fields.One2man... | ad'].search_count([('partner_id', operator, partner.id), ('type', '=', 'opportunity')])
@api.multi
def _compute_meeting_count(self):
for partner in self:
partner.meeting_count = len(partner.meeting_ids)
@api.multi
def schedule_meeting(self):
partner_ids = self.ids
p... | 'search_default_partner_ids': self._context['partner_name'],
'default_partner_ids': partner_ids,
}
return action
|
sebastianffx/active_deep_segmentation | save_nus_images.py | Python | gpl-2.0 | 401 | 0.007481 | img_ids = open('chairs_nuswide_imgids.txt','r')
nus_urls | = open('NUS-WIDE-urls.txt', 'r')
dict_urls = {}
for line in nus_urls:
dict_urls[line.split()[0]] = line.split()[3]
chairs_urls = []
count = 0
for line in img_ids:
print('searching url ' + str(count))
count = count +1
if not dict_urls[line.split()[0]] == 'null':
| chairs_urls.append(dict_urls[line.split()[0]])
|
krisrogers/textisbeautiful | manage.py | Python | apache-2.0 | 246 | 0 | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tib.settings")
|
from django.core.management import execute_from_command_line
| execute_from_command_line(sys.argv)
|
maxalbert/bokeh | bokeh/compat/mpl.py | Python | bsd-3-clause | 2,836 | 0.003173 | "Supporting objects and functions to convert Matplotlib objects into Bokeh."
#-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2014, Continuum Analytics, Inc. All rights reserved.
#
# Powered by the Bokeh Development Team.
#
# The full license is in the file LICENSE.t... | ----------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
from __future__ import absolute_import
from warnings import warn
import matplotlib.pyplot as plt
from .bokeh_exporter import Bokeh... | ions
#-----------------------------------------------------------------------------
def to_bokeh(fig=None, name=None, server=None, notebook=None, pd_obj=True, xkcd=False):
""" Uses bokeh to display a Matplotlib Figure.
You can store a bokeh plot in a standalone HTML file, as a document in
a Bokeh plot ser... |
yujikato/DIRAC | .github/workflows/make_release.py | Python | gpl-3.0 | 2,353 | 0.001275 | #!/usr/bin/env python
import argparse
from packaging.version import Version
import requests
from uritemplate import expand as uri_expand
def make_release(version, commit_hash, release_notes=""):
"""Create a new GitHub release using the given data
This function always makes a pre-release first to ensure the ... | prerelease,
},
headers=headers,
)
r.raise_for_status()
release_data = r.json()
print(f"Created draft release at: {release_data['html_url']}")
# Publish the release
r = requests.patch(
release_data["url"],
json={
"draft": False,
},
head... | == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--token", required=True)
parser.add_argument("--owner", default="DIRACGrid")
parser.add_argument("--repo", default="DIRAC")
parser.add_argument("--version", required=True)
parser.add_argument("--rev", required=True)
args... |
lorien/runscript | test/script/foo.py | Python | mit | 41 | 0 | def | main(**kwargs):
print(' | foo foo')
|
datashaman/putio-automator | putio_automator/__init__.py | Python | mit | 1,262 | 0.008716 | """
Initialize the application.
"""
import logging
logger = logging.getLogger(__name__)
import appdirs
import click
import datetime
import distutils.dir_util
import os
import putiopy
import sqlite3
APP_NAME = 'putio-automator'
APP_AUTHOR = 'datashaman'
DIRS = appdirs.AppDirs(APP_NAME, APP_AUTHOR)
from .db import cre... | tance(obj, datetime.date):
return obj.isoformat()
else:
return None
def find_config(verbose=False):
"Search for config on wellknown paths"
search_paths = [
os.path.join(os.getcwd(), 'config.py'),
os.path.join(DIRS.user_data_dir, 'config.py'),
os.path.join(DIRS.site | _data_dir, 'config.py'),
]
config = None
for search_path in search_paths:
message = 'Searching %s' % search_path
logger.debug(message)
if verbose:
click.echo(message)
if os.path.exists(search_path) and not os.path.isdir(search_path):
config = search... |
alejo8591/maker | core/templatetags/administration.py | Python | mit | 2,069 | 0.00725 | # encoding: utf-8
# Copyright 2013 maker
# License
"""
Administration templatetags
"""
from coffin import template
from maker.core.rendering import render_to_string
from jinja2 import contextfunction, Markup
from django.template import RequestContext
register = template.Library()
@contextfunction
def administrati... | nistration_group_list(context, groups, skip_group=False):
"Print a list of g | roups"
request = context['request']
response_format = 'html'
if 'response_format' in context:
response_format = context['response_format']
return Markup(render_to_string('core/administration/tags/group_list',
{'groups': groups, 'skip_group': skip_group},
... |
oso/qgis-etri | qgis_etri/xmcda.py | Python | gpl-3.0 | 12,747 | 0.009022 | import sys #FIXME: useless
import time
from qgis_etri.pysimplesoap.client import SoapClient
from qgis_etri.pysimplesoap.simplexml import SimpleXMLElement, TYPE_MAP
ETRI_BM_URL = 'http://webservices.decision-deck.org/soap/ElectreTriBMInference-PyXMCDA.py'
def format_alternatives(alts):
output = "<alternatives>\n"
... | bmit_problem(url, params):
p = SimpleXMLElement("<submitProblem></submitProblem>")
for k, v in params.items():
child = p.add_child(k, v)
child.add_attribute("xsi:type", "xsd:string")
client = SoapClient(
location = url,
| action = '',
soap_ns = 'soapenv',
namespace = 'http://www.decision-deck.org/2009/XMCDA-2.0.0',
trace = False)
sp = client.call('submitProblem', p)
reply = sp.submitProblemResponse
return str(reply.ticket)
def request_solution(url, ticket_id, timeout=0):
client = SoapClie... |
hip-odoo/odoo | addons/delivery/models/delivery_carrier.py | Python | agpl-3.0 | 13,010 | 0.002998 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
from odoo import api, fields, models, _
from odoo.exceptions import UserError, ValidationError
from odoo.tools.safe_eval import safe_eval
_logger = logging.getLogger(__name__)
class DeliveryCarrier(mod... | dentials are certified for production.")
margin = fields.Integer(help='This percentage will be added to the shipping price.')
_sql_constraints = [
('margin_not_under_100_percent', 'CHECK (margin >= -100)', 'Margin cannot be lower than -100%'),
]
@api.one
def toggle_prod_environment(self):
... | .multi
def install_more_provider(self):
return {
'name': 'New Providers',
'view_mode': 'kanban',
'res_model': 'ir.module.module',
'domain': [['name', 'ilike', 'delivery_']],
'type': 'ir.actions.act_window',
'help': _('''<p class="oe_vie... |
crmccreary/openerp_server | openerp/addons/hr_timesheet/hr_timesheet.py | Python | agpl-3.0 | 8,348 | 0.00563 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... | t = {}
emp_obj = self.pool.get('hr.employee')
emp_id = emp_obj.search(cr, uid, [('user_id', '=', context.get('user_id', uid))], context=context)
ename = ''
if emp_id:
ename = emp_obj.browse(cr, uid, emp_id[0], context=context).name
if not vals.get('journal_id',False):... | urnal!')%(ename,))
if not vals.get('account_id',False):
raise osv.except_osv(_('Warning !'), _('No analytic account defined on the project.\nPlease set one or we can not automatically fill the timesheet.'))
return super(hr_analytic_timesheet, self).create(cr, uid, vals, context=context)
... |
slightstone/SickRage | sickbeard/postProcessor.py | Python | gpl-3.0 | 45,995 | 0.004805 | # Author: Nic Wolfe <[email protected]>
# 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 License,... | e file doesn't exist
EXISTS_LARGER if the file exists and is larger than the file we are post processing
EXISTS_SMALLER if the file exists and is smaller than the file we are post processing
EXISTS_SAME if the file exists and is the same size as the file we are post processing
... | logger.DEBUG)
return PostProcessor.DOESNT_EXIST
# if the new file exists, return the appropriate code depending on the size
if ek.ek(os.path.isfile, existing_file):
# see if it's bigger than our old file
if ek.ek(os.path.getsize, existing_file) > ek.ek(os.path.getsi... |
smallyear/linuxLearn | salt/salt/modules/system.py | Python | apache-2.0 | 1,800 | 0 | # -*- coding: utf-8 -*-
'''
Support for reboot, shutdown, etc
'''
from __future__ import absolute_import
import salt.utils
def __virtual__():
'''
Only supported on POSIX-like systems
'''
if salt.utils.is_windows() or not salt.utils.which('shutdown'):
return False
return True
def halt():... | ill be shutdown.
CLI Example:
.. code-block:: bash
salt '*' system.shutdown 5
'''
cmd = ['shutdown', '-h', ('{0}'.format(at_time) if at_time e | lse 'now')]
ret = __salt__['cmd.run'](cmd, python_shell=False)
return ret
|
Open511/roadcast | travis-ci/travis511/settings.py | Python | agpl-3.0 | 5,239 | 0.002291 | #coding: utf-8
import os
DEBUG = False
TEMPLATE_DEBUG = DEBUG
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'open511', # Or path to database file if using sqlite3.
'US... | E_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True
# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True
PROJ_ROOT = os.path.dirname(os.path.realpath(__file__))
# Absolute filesystem path ... | me/media/media.lawrence.com/media/"
MEDIA_ROOT = os.path.realpath(os.path.join(PROJ_ROOT, '..', 'media'))
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = '/media/'
# Absolute path to the d... |
tuaris/suncoin | contrib/spendfrom/spendfrom.py | Python | mit | 10,053 | 0.005968 | #!/usr/bin/env python
#
# Use the raw transactions API to spend bitcoins received on particular addresses,
# and send any change back to that same address.
#
# Example usage:
# spendfrom.py # Lists available funds
# spendfrom.py --from=ADDRESS --to=ADDRESS --amount=11.00
#
# Assumes it will talk to a bitcoind or Bit... | ger than 1000 bytes")
if total_in < 0.01 and fee < BASE_FEE:
raise FeeError("Rejecting no-fee, tiny-amount transaction")
# Exercise for the reader: compute transaction priority, and
# warn if this is a very-low-priority transaction
except FeeError as err:
sys.stderr.writ... | rt optparse
parser = optparse.OptionParser(usage="%prog [options]")
parser.add_option("--from", dest="fromaddresses", default=None,
help="addresses to get bitcoins from")
parser.add_option("--to", dest="to", default=None,
help="address to get send bitcoins to")
... |
licko/vpp-1701-licko | test/test_vxlan.py | Python | apache-2.0 | 7,549 | 0 | #!/usr/bin/env python
import socket
import unittest
from framework import VppTestCase, VppTestRunner
from template_bd import BridgeDomain
from scapy.layers.l2 import Ether
from scapy.layers.inet import IP, UDP
from scapy.layers.vxlan import VXLAN
from scapy.utils import atol
class TestVxlan(BridgeDomain, VppTestCas... | rbitrary.
self.assertEqual(pkt[UDP].dpor | t, type(self).dport)
# TODO: checksum check
# Verify VNI
self.assertEqual(pkt[VXLAN].vni, vni)
@staticmethod
def ip4_range(ip4n, s=10, e=20):
base = str(bytearray(ip4n)[:3])
return ((base + ip) for ip in str(bytearray(range(s, e))))
@classmethod
def create_vxlan... |
shahbaz17/zamboni | mkt/comm/tests/test_utils_mail.py | Python | bsd-3-clause | 10,981 | 0 | import base64
import os.path
from django.conf import settings
from django.core import mail
import mock
from nose import SkipTest
from nose.tools import eq_, ok_
import mkt
from mkt.comm.models import CommunicationThread, CommunicationThreadToken
from mkt.comm.tests.test_views import CommTestMixin
from mkt.comm.utils... | 'tests', 'emails',
'email.txt')
multi_email = os.path.join(settings.ROOT, 'mkt', 'comm', 'tests', 'emails',
'email_multipart.txt')
quopri_email = os.path.join(settings.ROOT, 'mkt', 'comm', 'tests', 'emails',
'email_quoted_printable.txt')... | os.path.join(settings.ROOT, 'mkt', 'comm', 'tests', 'emails',
'email_attachment.txt')
attach_email2 = os.path.join(settings.ROOT, 'mkt', 'comm', 'tests', 'emails',
'email_attachment2.txt')
class TestSendMailComm(TestCase, CommTestMixin):
def setUp(self):
... |
Distrotech/yum-utils | plugins/refresh-updatesd/refresh-updatesd.py | Python | gpl-2.0 | 1,858 | 0.002691 | # A plugin for yum which notifies yum-updatesd to refresh its data
#
# Written by James Bowes <[email protected]>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundati | on; either version 2 of the License, or
# (at your option) any lat | er version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# version 0.0.5
import os
import dbus
from yum.plugins import... |
MauricioAcosta/Aprendiendo_Python | encriptar/criptografia.py | Python | gpl-3.0 | 2,469 | 0.001623 | #!/usr/bin/env python
# -*- coding: utf-8 -*
KEYS = {
'a': 'w',
'b': 'E',
'c': 'x',
'd': '1',
'e': 'a',
'f': 't',
'g': '0',
'h': 'C',
'i': 'b',
'j': '!',
'k': 'z',
'l': '8',
'm': 'M',
'n': 'I',
'o': 'd',
'p': '.',
'q': 'U',
'r': 'Y',
's': 'i',... | [c]ifrar mensaje
[d]ecifrar mensaje
[s]alir
'''))
if command == 'c':
message = str(raw_input('Escribe tu mensaje: '))
cypher_messager = cypher(message)
print(cypher_messager)
elif command == 'd':
message = str(raw_input(... | break
else:
print('¡Comando no encontrado!')
if __name__ == '__main__':
print('M E N S A J E S C I F R A D O S')
run()
|
pauljohnleonard/pod-world | pod/gui.py | Python | gpl-2.0 | 2,156 | 0.038497 | from math import *
import gui_base
keys=gui_base.keys
display_str=None
display_font_size=14
class SimpleGui:
""" The simulation class is responsible for running the Pod World.
"""
def __init__(self,world,pods,frames_per_sec,title="BraveNewWorld",back_ground=(0,0,0),log_file=None):
#: w... |
dim_world = (w+20,h+20)
self.screen = gui_base.init_surface(dim_world,title)
if log_file != None:
self.log_file=open(log_file,"w")
self.run_name=title
| self.frames_per_sec=frames_per_sec
def check_for_quit(self):
return gui_base.check_for_quit()
def _display_mess(self,pos=(20,20),col=(255,255,0)):
gui_base.draw_string(self.screen,display_str,pos,col,display_font_size)
def clear(self):
self.scr... |
srluge/SickRage | tests/encoding_tests.py | Python | gpl-3.0 | 1,487 | 0.008754 | # coding=utf-8
import sys, os.path
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__), '..')))
import locale
import unittest
import test_lib as test
import sickbeard
from sickbeard.helpers import sanitizeFil... | nitizeFileName(s))
self.assertIsInstance(show_dir, unicode)
if __name__ == "__main__":
print "=================="
print "STARTING - ENCODING TESTS"
print "=================="
print "################################################################# | #####"
suite = unittest.TestLoader().loadTestsFromTestCase(EncodingTests)
unittest.TextTestRunner(verbosity=2).run(suite)
|
grodrigo/django_general | persons/migrations/0003_auto_20161108_1710.py | Python | gpl-3.0 | 550 | 0.001818 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2016-11-0 | 8 20:10
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('persons', '0002_person_is_staff'),
]
operations = [
migrations. | AlterField(
model_name='person',
name='staff_member',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='persons.Person'),
),
]
|
adamalton/django-href-field | hreffield/fields.py | Python | mit | 657 | 0.004566 | from django.db.models import CharField
DEFALT_PROTOCOLS = ('http', 'https', 'mailto', 'tel')
class HrefField(CharField):
def __init__(
self,
protocols=DEFALT_PROTOCOLS,
allow_paths=True,
| allow_fragments=T | rue,
allow_query_strings=True,
max_length=255,
**kwargs):
self.protocols = protocols
self.allow_paths = allow_paths
self.allow_fragments = allow_fragments
self.allow_query_strings = allow_query_strings
kwargs['max_length'] = max_length
... |
xuru/pyvisdk | pyvisdk/enums/datastore_summary_maintenance_mode_state.py | Python | mit | 272 | 0 |
########################################
# Automatically generated, do not edit.
########################################
from pyvisdk.thirdparty import Enum
DatastoreSummaryMainten | anceModeState = Enum(
'enteringMaintenance',
'inMainten | ance',
'normal',
)
|
ychen820/microblog | y/google-cloud-sdk/platform/google_appengine/lib/django-1.2/django/template/debug.py | Python | bsd-3-clause | 3,732 | 0.004019 | from django.template import Lexer, Parser, tag_re, NodeList, VariableNode, TemplateSyntaxError
from django.utils.encoding import force_unicode
from django.utils.html import escape
from django.utils.safestring import SafeData, EscapeData
from django.utils.formats import localize
class DebugLexer(Lexer):
def __init_... | gin)
def tokenize(self):
"Return a list of tokens from a given template_string"
result, upto = [], 0
for match in tag_re.finditer(self.template_string):
start, end = match.span()
if start > upto:
result.append(self.create_token(self.template_string[up... | last_bit = self.template_string[upto:]
if last_bit:
result.append(self.create_token(last_bit, (upto, upto + len(last_bit)), False))
return result
def create_token(self, token_string, source, in_tag):
token = super(DebugLexer, self).create_token(token_string, in_tag)
... |
zepheira/open-science | etc/sitecustomize.py | Python | apache-2.0 | 84 | 0 | import site
site | .addsitedir('/open-science/projectdir/lib/python2.5/site-packa | ges')
|
internetfett/grocerylist | backend/recipes/admin.py | Python | mit | 2,138 | 0.008419 | from django.contrib import admin
from django.db.models import Sum
from recipes.models import Category, Recipe, Ingredient, RecipeIngredient
class RecipeIngredientInline(admin.TabularInline):
model = RecipeIngredient
class CategoryAdmin(admin.ModelAdmin):
list_display = ('name',)
search_fields = ['name']
ord... | klist, ChecklistIngredient, Exclusion, Repeatable
ids = queryset.values_list('id', flat=True)
exclusions = Exclusion.objects.values_list('ingredient', flat=True)
recipe_ingredients = RecipeIngredient.objects.filter(recipe__in=ids) \
.values('ingredient', 'unit').annotate(amount=Sum('... | checklist_ingredient = ChecklistIngredient.objects.create(
checklist = Checklist.objects.get(id=checklist_id),
amount = recipe_ingredient['amount'],
unit = recipe_ingredient['unit'],
ingredient = Ingredient.objects.get(id=reci... |
Contraz/demosys-py | demosys/view/screenshot.py | Python | isc | 1,308 | 0.003058 | import os
from datetime import datetime
from PIL import Image
from demosys import context
from demosys.conf import settings
class Config:
"""Container for screenshot target"""
target = None
alignment = 1
def create(file_format='png', name=None):
"""
Create a scr | eenshot
:param file_format: formats supported by PIL (png, jpeg etc)
"""
dest = ""
if settings.SCREENSHOT_PATH:
if not os. | path.exists(settings.SCREENSHOT_PATH):
print("SCREENSHOT_PATH does not exist. creating: {}".format(settings.SCREENSHOT_PATH))
os.makedirs(settings.SCREENSHOT_PATH)
dest = settings.SCREENSHOT_PATH
else:
print("SCREENSHOT_PATH not defined in settings. Using cwd as fallback.")
... |
maurov/xraysloth | sloth/math/deglitch.py | Python | bsd-3-clause | 5,178 | 0.001738 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Deglitch utilities
=====================
"""
import numpy as np
import logging
_logger = logging.getLogger("sloth.math.deglitch")
def remove_spikes_medfilt1d(y_spiky, backend="silx", kernel_size=3, threshold=0.1):
"""Remove spikes in a 1D array using medfilt fr... | method="ffill")
)
diff = yf.values - y
mean = diff.mean()
sigma = (y - mean) ** 2
| sigma = np.sqrt(sigma.sum() / float(len(sigma)))
ynew = np.where(abs(diff) > threshold * sigma, yf.values, y)
# ynew = np.array(yf.values).reshape(len(x))
return ynew
|
yshlin/tildeslash | tildeslash/blog/utils.py | Python | bsd-3-clause | 787 | 0.003812 | # -*- coding: utf-8 -*-
import re
import unicodedata
# FIXME: these patterns works for English/Chinese mixed content, but not tested among other languages
WORD_COUNT_SPLIT_PATTERN = re.compile(u'[\s\u4e00-\u9fff]')
ASIAN_CHAR_PATTERN = re.compile(u'[\u | 4e00-\u9fff]')
ENDING_CHAR_CATEGORIES = ('Po', 'Cc', 'Zs')
def word_count(content):
return len(re.split(WORD_COUNT_SPLIT_PATTERN, content))
def strip_content(content, length=100):
inde | x = 0
count = 0
for c in content:
if count >= length:
if unicodedata.category(c) in ENDING_CHAR_CATEGORIES:
break
else:
if re.match(ASIAN_CHAR_PATTERN, c):
count += 2
else:
count += 1
index += 1
retur... |
wojab/python_training | check_db_connection.py | Python | apache-2.0 | 276 | 0.01087 | from fixture.orm impo | rt ORMFixture
from model.group import Group
db = ORMFixture(host="127.0.0.1", name="addressbook", user="root", password="")
try:
l = db. | get_contacts_in_group(Group(id="69"))
for item in l:
print(item)
print(len(l))
finally:
pass |
onponomarev/ganeti | lib/query.py | Python | bsd-2-clause | 92,353 | 0.00602 | #
#
# Copyright (C) 2010, 2011, 2012, 2013 Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list ... | aram fielddefs: Field definitions
@type selected: list of strings
@param selected: List of selected fields
"""
result = []
for name in selected:
try:
fdef = fielddefs[name]
except KeyError:
fdef = (_MakeField(name, name, QFT_UNKNOWN, "Unknown field '%s'" % name),
None, 0, _... | efinitions.
@rtype: list of L{objects.QueryFieldDefinition}
"""
return [fdef for (fdef, _, _, _) in fielddefs]
class _FilterHints(object):
"""Class for filter analytics.
When filters are used, the user of the L{Query} class usually doesn't know
exactly which items will be necessary for building the res... |
fdibaldassarre/photo-mosaic | lib/CollageImage.py | Python | gpl-3.0 | 9,160 | 0.016594 | #!/usr/bin/env python3
import os
import sys
from json import JSONEncoder
from json import JSONDecoder
from PIL import Image
from lib import ImageManager
JSON_encoder = JSONEncoder()
JSON_decoder = JSONDecoder()
MAX_IMAGES_MEM = 1 # DO NOT SET LOWER THAN 1
MAX_COLOURS_MEM = 200
DATA_IMAGE_SIZE = 'ImageSize'
DATA_COLO... | idth, height = | size
self.width = width
self.height = height
self.size = size
self.img = Image.new("RGBA", self.size, color=(255, 255, 255, 0))
self.pixelManager = self.img.load()
self.colours = {}
self.colours_size = {}
self.colours_usage = {}
def isPositionEmpty(self, position):
x, y = posit... |
bplower/cssef | WebInterface/WebInterface/modules/competition/views/blueteam.py | Python | gpl-3.0 | 17,106 | 0.032562 | from django.http import HttpResponseRedirect
from django.http import HttpResponseForbidden
from django.http import HttpResponseBadRequest
from django.shortcuts import render_to_response
from django.template.loader import render_to_string
from django.contrib import auth
from django.core.context_processors import csrf
#f... | d = c["comp_obj"].compid)
return render_to_response(templatePathPrefix + 'details.html', c)
def ranking(request, competition = None):
"""
Display team rankings for selected competition
"""
c = getAuthValues(request, {})
c["comp_obj"] = Competition.objects.get(compurl = competition)
# If the view is disabled
if... | _400.html', c))
c["ranks"] = []
team_objs = Team.objects.filter(compid = c["comp_obj"].compid)
for i in team_objs:
scores_objs = Score.objects.filter(compid = c["comp_obj"].compid, teamid = i.teamid)
total = 0
for k in scores_objs:
total += k.value
c["ranks"].append({"team": i.teamname, "score": total, "p... |
pcmoritz/ray-1 | python/ray/client_builder.py | Python | apache-2.0 | 6,749 | 0 | import os
import importlib
import logging
from dataclasses import dataclass
import sys
from typing import Any, Dict, Optional, Tuple
from ray.ray_constants import RAY_ADDRESS_ENVIRONMENT_VARIABLE
from ray.job_config import JobConfig
import ray.util.client_connect
logger = logging.getLogger(__name__)
@dataclass
cla... | ssible as it will shutdown the "
"cluster.")
else:
# This is only a driver connected to an existing cluster.
ray.shutdown()
class ClientBuilder:
"""
Builder for a Ray Client connection. This class can be subclassed by
custom builder classes to modify connect... |
def __init__(self, address: Optional[str]) -> None:
self.address = address
self._job_config = JobConfig()
def env(self, env: Dict[str, Any]) -> "ClientBuilder":
"""
Set an environment for the session.
Args:
env (Dict[st, Any]): A runtime environment to use f... |
Parsl/parsl | parsl/tests/test_python_apps/test_garbage_collect.py | Python | apache-2.0 | 1,044 | 0.002874 | import parsl
import time
from parsl.app.app import python_app
@python_app
def slow_double(x):
import time
time.sleep(0.1)
return x * 2
def test_garbage_coll | ect():
""" Launches an app with a dependency and waits till it's done and asserts that
the internal refs were wiped
"""
x = slow_double(slow_double(10))
if x.done() is False:
assert parsl.dfk().tasks[x.tid]['app_fu'] == x, "Tasks table should have app_fu ref before done"
x.result()
... | not None:
# We explicit call checkpoint if checkpoint_mode is enabled covering
# cases like manual/periodic where checkpointing may be deferred.
parsl.dfk().checkpoint()
time.sleep(0.2) # Give enough time for task wipes to work
assert x.tid not in parsl.dfk().tasks, "Task record should... |
rakanalh/django-pushy | pushy/tasks.py | Python | mit | 4,276 | 0 | import datetime
import logging
import celery
from django.conf import settings
from django.db import transaction
from django.db.utils import IntegrityError
from django.utils import timezone
from .models import (
PushNotification,
Device,
get_filtered_devices_queryset
)
from .exceptions import (
PushIn... | attr(settings, 'PUSHY_QUEUE_DEFAULT_NAME', None)
)
def send_single_push_notification(dev | ice, payload):
# The task can be called in two ways:
# 1) from send_push_notification_group directly with a device instance
# 2) As a task using .delay or apply_async with a device id
if isinstance(device, int):
try:
device = Device.objects.get(pk=device)
except Device.DoesNo... |
ionelmc/python-darkslide | docs/conf.py | Python | apache-2.0 | 1,275 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import sphinx_py3doc_enhanced_theme
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.autosummary',
'sphinx.ext.coverage',
'sphinx.ext.doctest',
'sphinx.ext.extlinks',
'sphinx.ext.ifconfig',
'sphinx.ext.napoleon',
'sphinx.e... | https://github.com/ionelmc/ | python-darkslide/'
}
html_use_smartypants = True
html_last_updated_fmt = '%b %d, %Y'
html_split_index = False
html_sidebars = {
'**': ['searchbox.html', 'globaltoc.html', 'sourcelink.html'],
}
html_short_title = '%s-%s' % (project, version)
napoleon_use_ivar = True
napoleon_use_rtype = False
napoleon_use_param = ... |
ciudadanointeligente/deldichoalhecho-uycheck | promises/migrations/0001_initial.py | Python | gpl-3.0 | 9,083 | 0.007266 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Category'
db.create_table(u'promises_category', (
... | ngo.db.models.fields.CharField', [], {'max_length': '128'}),
'patronymic_name': ('django.db.models.fields.CharField', [], {'max_length': '128', 'blank': 'True'}),
'slug': ('autoslug.fields.AutoSlugField', [], {'unique': 'True', 'max_length': '50', 'populate_from': 'None', 'unique_with': ' | ()'}),
'sort_name': ('django.db.models.fields.CharField', [], {'max_length': '128', 'blank': 'True'}),
'start_date': ('django.db.models.fields.CharField', [], {'max_length': '10', 'null': 'True', 'blank': 'True'}),
'summary': ('django.db.models.fields.CharField', [], {'max_length': '... |
DefaultUser/PyTIBot | lib/channelwatcher/abstract.py | Python | gpl-3.0 | 1,797 | 0 | # -*- coding: utf-8 -*-
# PyTIBot - IRC Bot using python and the twisted library
# Copyright (C) <2017-2021> <Sebastian Schmidt>
# 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... |
def quit(self, user, quitMessage):
pass
@abstractmethod
def kick(self, kickee, kicker, message):
pass
@abstractmethod
def notice(self, user, message):
pass
@abstractmethod
def action(self, user, data):
pass
@abstractmethod
def msg(self, user, mess... | @abstractmethod
def stop(self):
pass
@abstractmethod
def connectionLost(self, reason):
pass
|
endlessm/glib | .gitlab-ci/check-todos.py | Python | lgpl-2.1 | 2,831 | 0.00142 | #!/usr/bin/env python3
#
# Copyright © 2019 Endless Mobile, Inc.
#
# SPDX-License-Identifier: LGPL-2.1-or-later
#
# Original author: Philip Withnall
"""
Checks that a merge request doesn’t add any instances of the string ‘todo’
(in uppercase), or similar keywords. It may remove instances of that keyword,
or move them ... | iff'
print('Saw banned keywords in a {}: {}. '
'This | indicates the branch is a work in progress and should not '
'be merged in its current '
'form.'.format(where, ', '.join(banned_words_seen)))
sys.exit(1)
if __name__ == '__main__':
main()
|
linkedin/WhereHows | metadata-ingestion/src/datahub_provider/operators/datahub.py | Python | apache-2.0 | 1,848 | 0.001082 | from typing import List, Union
from airflow.models import BaseOperator
from airflow.utils.decorators import apply_defaults
from datahub.metadata.com.linkedin.pegasus2avro.mxe import MetadataChangeEvent
from datahub_provider.hooks.datahub import (
DatahubGenericHook,
DatahubKafkaHook,
DatahubRestHook,
)
... | tor):
"""
The DatahubBaseOperator is used as a base operator all DataHub operators.
"""
ui_color = "#4398c8"
hook: Union[DatahubRestHook, DatahubKafkaHook]
# mypy is not a fan of this. Newer versions of Airflow support proper typing for the decorator
# using PEP 612. However, there is not... | e[misc]
def __init__( # type: ignore[no-untyped-def]
self,
*,
datahub_conn_id: str,
**kwargs,
):
super().__init__(**kwargs)
self.datahub_conn_id = datahub_conn_id
self.generic_hook = DatahubGenericHook(datahub_conn_id)
class DatahubEmitterOperator(Data... |
santoshphilip/eppy | tests/sketch.py | Python | mit | 593 | 0.008432 | import glob
import os
from eppy.iddcurrent import iddcurrent
from eppy.modeleditor import IDF
from eppy.pytest_helpers import IDD_FILES
from io import StringIO
import eppy.snippet as snippet
iddsnippet = iddcurrent.iddtxt
idfsnippet = snippet.idfsnippet
iddfhandle = StringIO(iddcurrent.iddtxt)
IDF.setiddname(iddfh... | D_FILES, "Energy+V8_1_0.idd")
OUTPUT_DIR = "C:\EnergyPlusV8-5-0\ExampleFiles\loopdiagrams"
idfs = glob.glob(OUTPUT_DIR + "\*.idf")
dots = glob.glob(OUTPUT_DIR + "\*.dot")
for idf in idfs:
os.remove(idf)
for dot in dots:
os.remove(dot) | |
aecay/weihnachtsgurke | wng/metadata.py | Python | gpl-3.0 | 571 | 0.001751 | # -*- coding: utf-8 -*-
"""Project metadata
Information describing the project.
"""
# The package name, which is also the "UNIX name" for | the project.
package = 'weihnachtsgurke'
project = "PYCCLE-TCP search tool"
project_no_spaces = project.replace(' ', '')
version = '0.3'
description = 'A program for searching for strings of text in the PYCCLE-TCP corpus'
authors = ["Aaron Ecay"]
author | s_string = ', '.join(authors)
emails = ["[email protected]"]
license = 'GPL v3'
copyright = '2016 University of York'
url = "https://weihnachtsgurke.readthedocs.io/en/latest/"
|
blitzagency/flowbee | setup.py | Python | mit | 1,607 | 0.002489 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
from setuptools import setup, find_packages
import flowbee
here = os.path.abspath(os.path.dirname(__file__))
def strip_comments(l):
return l.strip()
# ret | urn l.split('#', 1)[0].strip()
def reqs(*f):
return list(filter(None, [strip_comments(l) for l in open(
os.path.join(os.getcwd(), 'requirements', *f)).readlines()]))
install_requires = reqs('default.txt')
tests_require = []
docs_extras = reqs('docs.txt')
testing_extras = test | s_require + reqs('testing.txt')
readme = open(os.path.join(here, 'README.rst')).read()
history = open(os.path.join(here, 'HISTORY.rst')).read().replace('.. :changelog:', '')
setup(
name='flowbee',
version=flowbee.__version__,
description='',
long_description=readme + '\n\n' + history,
author='Adam... |
SUSE/azure-sdk-for-python | azure-batch/azure/batch/models/account_list_node_agent_skus_options.py | Python | mit | 2,070 | 0.000483 | # 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 ... | onds. The default is 30 seconds. Default value: 30 .
:type timeout: int
:param client_request_id: The caller-generated request identity, in the
form of a GUID with no decoration such as curly braces, e.g.
9C4D50EE-2D56-4CD3-8152-34347DC9F2B0.
:type client_req | uest_id: str
:param return_client_request_id: Whether the server should return the
client-request-id in the response. Default value: False .
:type return_client_request_id: bool
:param ocp_date: The time the request was issued. Client libraries
typically set this to the current system clock time; ... |
HopeFOAM/HopeFOAM | ThirdParty-0.1/ParaView-5.0.1/VTK/Rendering/Volume/Testing/Python/VolumePicker.py | Python | gpl-3.0 | 9,122 | 0.001754 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
=========================================================================
Program: Visualization Toolkit
Module: TestNamedColorsIntegration.py
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.... | ren.AddViewProp(coneActor1)
# Pick the volume
picker.Pick(90, 180, 0, ren)
p = picker.GetPickPosition()
n = picker.GetPickNormal()
coneActor2 = vtk.vtkActor()
coneActor2.PickableOff | ()
coneMapper2 = vtk.vtkDataSetMapper()
coneMapper2.SetInputConnection(coneSource.GetOutputPort())
coneActor2.SetMapper(coneMapper2)
coneActor2.GetProperty().SetColor(1, 0, 0)
coneActor2.SetPosition(p)
PointCone(coneActor2, n)
ren.AddViewProp(coneActor2)
... |
forallsystems/21stbadgepathways | default_site/views.py | Python | gpl-2.0 | 4,452 | 0.010332 | from django.contrib.auth import REDIRECT_FIELD_NAME
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth import views as django_auth_views
from django.http import HttpResponseRedirect, HttpResponse
from django.template import RequestContext
from django.shortcuts import render_to_response
fr... | nt sys.exc_info()
pass
return render(request,'error.html')
@login_required
def dashboard_browse_passport(request):
return dashboard(request,templateName='studentDashboardBrowse.html')
| |
walterbender/followme | rc_skip_last.py | Python | gpl-3.0 | 1,984 | 0 | """
Follow Me activity for Sugar
Copyright (C) 2010 Peter Hewitt
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 late... | s/>.
"""
class RC():
def _ | _init__(self, nr, nc):
self.nr = nr
self.nc = nc
def inc_r(self, ind):
r, c = self.row_col(ind)
r += 1
if r == self.nr:
r = 0
if r == (self.nr - 1) and c == (self.nc - 1):
r = 0
return self.indx(r, c)
def dec_r(self, ind):
... |
benosteen/RDFDatabank | docs/using_databank_api/DatabankDemo.py | Python | mit | 1,544 | 0.005181 | #Databank API demo
import urllib2
import base64
import urllib
from lib.multipartform import MultiPartForm
#===============================================================================
#Using urllib2 to create a package in Databank
url = "http://databank-vm1.oerc.ox.ac.uk/test/datasets"
req = urllib2.Requ... | urllib2.urlopen(req)
ans.read()
ans.msg
ans.code
#===============================================================================
#Using urllib2 to post a file in Databank
#Add a file
form = MultiPartForm()
filename = "solrconfig.xml"
filepath = "data/unicode07.xml"
form.add_file('file', filename, fileHan... | quest(url2)
auth = 'Basic ' + base64.urlsafe_b64encode("admin:test")
req2.add_header('Authorization', auth)
req2.add_header('Accept', 'application/JSON')
body = str(form)
req2.add_header('Content-type', form.get_content_type())
req2.add_header('Content-length', len(body))
req2.add_data(body)
print
print 'OUT... |
teeple/pns_server | work/install/Python-2.7.4/Lib/test/pydoc_mod.py | Python | gpl-2.0 | 439 | 0.006834 | """This is a test module for test_pydoc"""
__author__ = "Ben | jamin Peterson"
__credits__ = "Nobody"
__version__ = "1.2.3.4"
class A:
"""Hello and goodbye"""
def __init__():
| """Wow, I have no function!"""
pass
class B(object):
NO_MEANING = "eggs"
pass
def doc_func():
"""
This function solves all of the world's problems:
hunger
lack of Python
war
"""
def nodoc_func():
pass
|
danielsunzhongyuan/my_leetcode_in_python | sum_of_two_integers_371.py | Python | apache-2.0 | 536 | 0.024254 | """
Calculate the sum of two integers a and b, but you are not allowed to use the operato | r + and -.
Example:
Given a = 1 and b = 2, return 3.
"""
class Solution(object):
def ge | tSum(self, a, b):
"""
:type a: int
:type b: int
:rtype: int
"""
while a != 0 and b != 0:
a, b = a^b, (a&b)<<1
if a > 1<<31 or b > 1<<31:
a %= 1<<31
b %= 1<<31
return a or b
if __name__ == "__main__":
a = So... |
Masood-M/yalih | req/yara-3.9.0/docs/conf.py | Python | apache-2.0 | 8,265 | 0.007018 | # -*- coding: utf-8 -*-
#
# yara documentation build configuration file, created by
# sphinx-quickstart on Tue Jul 8 11:04:03 2014.
#
# This file is execfile()d with the current directory set to its
# co | ntaining dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
# If | extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# -- General configuration -----------------... |
qingshuimonk/bhtsa | demo/electionday_analysis.py | Python | mit | 1,900 | 0.003684 | from nltk.twitter import Query, credsfromfile
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter
import datetime as dt
import os
import pickle
import sys
sys.path.append("../bhtsa")
from twitter_senti_analyzer import senti_score_time
# settings
oauth = credsfromfile()
client ... | tartTime[0], startTime[1], startTime[2], startTime[3], startTime[4])
dates = []
for i in range(step_num):
next_val = origin + dt.timedelta(minutes=step*i)
dates.append(next_val)
hilary_score = senti_ | score_time('hilary clinton', client, NBC, twtNum, startTime, step, step_num, 1)
trump_score = senti_score_time('donald trump', client, NBC, twtNum, startTime, step, step_num, 1)
hilary_mean = np.mean(hilary_score, axis=0)
hilary_upper = hilary_mean + np.std(hilary_score, axis=0)*0.1
hilary_lower = hilary_mean - np.std... |
tensorflow/tensor2tensor | tensor2tensor/data_generators/paraphrase_ms_coco_test.py | Python | apache-2.0 | 3,095 | 0.002585 | # coding=utf-8
# Copyright 2022 The Tensor2Tensor Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in complian | ce 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,
# W | ITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for tensor2tensor.data_generators.paraphrase_ms_coco."""
from __future__ import absolute_import
from __future__ import division
from _... |
hjfreyer/marry-fuck-kill | backend/html_handlers.py | Python | apache-2.0 | 8,480 | 0.007547 | #!/usr/bin/env python
#
# Copyright 2010 Hunter Freyer and Michael Kelly
#
# 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 b... | f-8'),
prev_e2_name=prev_names[1].encode('utf-8'),
prev_e3_name=prev_names[2].encode('utf-8'),
prev_e1_stat_url=prev_urls[0],
prev_e2_stat_url=prev_urls[1],
prev_e3_st | at_url=prev_urls[2])
template_values.update(GetUserData('/vote/' + triple_id))
ezt_util.WriteTemplate('vote.html', template_values, handler.response.out)
class VoteSubmitHandler(RequestHandler):
def post(self):
_LogRequest('Vote', self.request)
action = self.request.get('action')
if action == 'subm... |
chriskiehl/python-stix | stix/extensions/marking/tlp.py | Python | bsd-3-clause | 1,713 | 0.001751 | # Copyright (c) 2015, The MITRE Corporation. All rights reserved.
# See LICENSE.txt for complete terms.
import stix
from stix.data_marking import MarkingStructure
import stix.bindings.extensions.marking.tlp as tlp_binding
@stix.register_extension
class TLPMarkingStructure(MarkingStructure):
_binding = tlp_bindin... | ict(self):
| d = MarkingStructure.to_dict(self)
if self.color:
d['color'] = self.color
return d
@classmethod
def from_obj(cls, obj, return_obj=None):
if not obj:
return None
if not return_obj:
return_obj = cls()
MarkingStructure.from_obj(obj, ... |
openstack/tacker | tacker/tests/unit/api/v1/test_router.py | Python | apache-2.0 | 1,832 | 0 | # Copyright (c) 2014-2018 China Mobile (SuZhou) Software Technology Co.,Ltd.
# 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/... | tations
# under the License.
from unittest import mock
from oslo_serialization import jsonutils
from tacker.api.v1.router import APIRouter
from tacker.api.v1.router import Index
from tacker.tests import base
from tacker import wsgi
class TestIndex(base.BaseTestCase): |
def test_index(self):
request = wsgi.Request.blank(
"/test/", body=b"{'name': 'tacker'}", method='POST',
headers={'Content-Type': "application/json"})
index_cls = Index({"version": "v1"})
result = index_cls(request)
expect_body = {'resources': [
... |
lywen52/quantproject | strategy/__init__.py | Python | apache-2.0 | 109 | 0.009174 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 14 14:11 | :38 2017
@author: | lywen
"""
|
msettles/expHTS | expHTS/extract_unmapped_reads.py | Python | apache-2.0 | 7,685 | 0.001952 | #!/usr/bin/env python
'''
Extract reads which aren't mapped from a SAM or SAM.gz file.
Behavior for PE:
-Write out PE only if both do not map (if either of the pair maps, neither is retained)
Behavior for SE:
-Write out SE if they don't map
Iterate over a SAM or SAM.gz file. take everything where the 3rd and
4th ... | print "@" + ID + "#0/1"
print r1[0]
print '+\n' + r1[1]
# read2
print "@" + ID + "#0/2"
print r2[0]
print '+\n' + r2[1]
else:
# read1
outPE1.write("@" + ID | + "#0/1" '\n')
outPE1.write(r1[0] + '\n')
outPE1.write('+\n' + r1[1] + '\n')
# read2
outPE2.write("@" + ID + "#0/2" '\n')
outPE2.write(r2[0] + '\n')
outPE2.write('+\n' + r2[1] + '\n')
i = 0
PE_written = 0
SE_written = 0
SE_open = False
PE_open = False
line2 = []
for lin... |
ozmartian/vidcutter | vidcutter/__main__.py | Python | gpl-3.0 | 17,036 | 0.002935 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#######################################################################
#
# VidCutter - media cutter & joiner
#
# copyright © 2018 Pete Alexandrou
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public Licen... | pp_confi | g_path()
except AttributeError:
if sys.platform == 'win32':
settings_path = os.path.join(QDir.homePath(), 'AppData', 'Local', qApp.applicationName().lower())
elif sys.platform == 'darwin':
settings_path = os.path.join(QDir.homePath(), 'Library', 'Preferenc... |
fharenheit/template-spark-app | src/main/python/ml/sql_transformer.py | Python | apache-2.0 | 1,382 | 0 | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... | or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from __future__ import print_function
# $example on$
from pyspark.ml.feature import SQLTransformer
# $example off$
from pyspark.sql import SparkSession
if __name__ == "__main__":
spark = SparkSes... | taFrame([
(0, 1.0, 3.0),
(2, 2.0, 5.0)
], ["id", "v1", "v2"])
sqlTrans = SQLTransformer(
statement="SELECT *, (v1 + v2) AS v3, (v1 * v2) AS v4 FROM __THIS__")
sqlTrans.transform(df).show()
# $example off$
spark.stop()
|
chrisdjscott/Atoman | atoman/gui/filterSettings/cropSphereSettingsDialog.py | Python | mit | 4,143 | 0.006034 |
"""
Contains GUI forms for the crop sphere filter.
"""
from __future__ import absolute_import
from __future__ import unicode_literals
import functools
from PySide2 import QtCore, QtWidgets
from . import base
from ...filtering.filters import cropSphereFilter
#######################################################... | y)")
self.yCentreSpinBox.valueChanged.connect(functools.partial(self._settings.updateSetting, "yCentre"))
self.zCentreSpinBox = QtWidgets.QDoubleSpinBox()
self.zCentreSpinBox.setSingleStep(0.01)
self.zCentreSpinBox.setMinimum(-9999.0)
self.zCentreSpinBox.setMaximum( 9999... | crop region (z)")
self.zCentreSpinBox.valueChanged.connect(functools.partial(self._settings.updateSetting, "zCentre"))
self.contentLayout.addRow("Centre (x)", self.xCentreSpinBox)
self.contentLayout.addRow("Centre (y)", self.yCentreSpinBox)
self.contentLayout.addRow("Centre (z)"... |
gnuworldman/verschemes | tests/test_pep440.py | Python | gpl-3.0 | 12,943 | 0.000232 | # -*- coding: utf-8 -*-
"""PEP 440 verschemes tests"""
import unittest
from verschemes.pep440 import Pep440Version
class Pep440VersionTestCase(unittest.TestCase):
def test_one_segment(self):
version = Pep440Version(release1=4)
self.assertEqual("4", str(version))
self.assertEqual(0, vers... | self.assertEqual(36, version.development)
def test_pre_and_post_release_and_development(self):
version = Pep440Version(1, 3, 11, 8, pre_release=('a', 2),
post_release=5, development=74)
self.assertEqual("1!3 | .11.8a2.post5.dev74", str(version))
self.assertEqual(1, version.epoch)
self.assertEqual(3, version.release1)
self.assertEqual(11, version.release2)
self.assertEqual(8, version.release3)
self.assertEqual(0, version.release4)
self.assertEqual(0, version.release5)
se... |
saifuddin779/data-collector | indeed/user_agents.py | Python | mit | 3,965 | 0.017402 | user_agents = [
'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.1 Safari/537.36',
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ch... | .0.2049.0 Safari/537.36',
'Mozilla/5.0 (Windows NT 4.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2049.0 Safari/537.36',
'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.67 Safari/537.36',
'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko)... | Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1944.0 Safari/537.36',
'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.3319.102 Safari/537.36',
'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.93 Safari/5... |
spreg-git/pysal | pysal/esda/mapclassify.py | Python | bsd-3-clause | 50,683 | 0.000572 | """
A module of classification schemes for choropleth mapping.
"""
__author__ = "Sergio J. Rey"
__all__ = ['Map_Classifier', 'quantile', 'Box_Plot', 'Equal_Interval',
'Fisher_Jenks', 'Fisher_Jenks_Sampled', 'Jenks_Caspall',
'Jenks_Caspall_Forced', 'Jenks_Caspall_Sampled',
'Max_P_Classi... | s(values, classes=5, sort=True):
"""
Jenks Optimal (Natural Breaks) algorithm implemented in Python.
The original Python | code comes from here:
http://danieljlewis.org/2010/06/07/jenks-natural-breaks-algorithm-in-python/
and is based on a JAVA and Fortran code available here:
https://stat.ethz.ch/pipermail/r-sig-geo/2006-March/000811.html
Returns class breaks such that classes are internally homogeneous while
assuring... |
jmvrbanac/symantecssl | tests/unit/test_auth.py | Python | apache-2.0 | 926 | 0 | from __future__ import absolute_import, division, print_function
import pretend
import pytest
from symantecssl.auth import SymantecAuth
@pytest.mark.parametrize(
("body", "expected"),
[
("", {}),
("foo=bar", {"foo": ["bar"]}),
("foo=ba | r&wat=yes", {"foo": ["bar"], "wat": ["yes"]}),
],
)
def test_auth_on_post(body, expected):
request = pretend.stub(
method="POST",
body=body,
prepare_b | ody=pretend.call_recorder(lambda data, files: None)
)
auth = SymantecAuth("testuser", "p@ssw0rd")
expected = expected.copy()
expected.update({"username": ["testuser"], "password": ["p@ssw0rd"]})
assert auth(request) is request
assert request.prepare_body.calls == [pretend.call(expected, None)... |
kaka19ace/kkutil | kkutil/config/__init__.py | Python | mit | 77 | 0 | #!/u | sr/bin/env python
# -*- coding: utf-8 -*-
#
fr | om .config import Config
|
daniestevez/gr-satellites | python/hier/rms_agc.py | Python | gpl-3.0 | 2,393 | 0 | # -*- coding: utf-8 -*-
#
# SPDX-License-Identifier: GPL-3.0
#
# GNU Radio Python Flow Graph
# Title: RMS AGC
# Author: Daniel Estevez
# Description: AGC using RMS
# GNU Radio version: 3.8.0.0
from gnuradio import blocks
from gnuradio import gr
from gnuradio.filter import firdes
class rms_agc(gr.hier_block2):
d... |
self.alpha = alpha
self.reference = reference
##################################################
# Blocks
##################################################
self.blocks_rms_xx_0 = blocks.rms_cf(alpha)
self.blocks_multiply_const_vxx_0 = (
blocks.multi... | vxx_0 = blocks.add_const_ff(1e-20)
##################################################
# Connections
##################################################
self.connect(
(self.blocks_add_const_vxx_0, 0),
(self.blocks_float_to_complex_0, 0))
self.connect((self.... |
CivicKnowledge/metaeditor | editor/management/commands/create_roots.py | Python | mit | 1,850 | 0.001622 | # -*- coding: utf-8 -*-
from django.core.management.base import BaseCommand
from editor.models import Source, Format, Category
class Command(BaseCommand):
help = 'Adds root category for Source, Format and Category models.'
def _change_root(self, model_class, verbosity=1):
ROOT_NAME = '!ROOT!'
... | el_class.DoesNotExist:
if verbosity > 0:
self.stdout.write(
'Root node for %s model does not exist. Creati | ng...' % model_class)
source_root = model_class(name=ROOT_NAME)
source_root.save()
if verbosity > 0:
self.stdout.write(
'Move existing roots to children of the global root.')
# move existing source roots to children of just created root
for n... |
JBonsink/GSOC-2013 | experiments/ManualTopoBTExperiment.py | Python | gpl-3.0 | 6,305 | 0.005234 | """
Manual Topology Experiment with Background Traffic
"""
from __future__ import print_function, division
import settings
from core.ns3.NS3Config import BackgroundTrafficConfig
from core.ns3.Topology import ManualTopologyNet
from experiments import experiment_factory
from core.configure import gen_anomaly_dot
import ... | line.rsplit()]
adj_mat = zeros([totnode, totnode])
continue
if i <= totnode: # ignore the position information
continue
_from, _to, _lineBuffer = [s.strip() for s in line.rsplit()]
adj_mat[int(_from)][int(_to)] = 1
fid.close()
return adj_mat
class ... | rotocol list, 'type':priority
routing_helper_list = {
'static':0,
'nix':5,
# 'olsr':10,
}
def initparser(self, parser):
ManualTopoExperiment.initparser(self, parser)
parser.set_defaults(back_traf="net_config/back_traf.py",
)
... |
pedrotari7/advent_of_code | py/2017/1B.py | Python | mit | 142 | 0.021127 | with open(' | 1.in', 'r') as f:
a = f.read()
step = len(a) / 2
print sum([int(d) for i,d in enumerate(a) if d == a[(i+step)%len | (a)]]) |
askalbania/piernik | python/plot_tsl.py | Python | gpl-3.0 | 1,065 | 0.018779 | #!/usr/bin/python
import sys
import re
import numpy as np
import matplotlib.pyplot as plt
import argparse
remove_comments = re.compile("(?!\#)", re.VERBOSE)
parser = argparse.ArgumentParser()
parser.add_argument("-f", nargs=1, default=None)
parser.add_argument("files", nargs='*')
args = parser.parse_args()
if len(... | tsl file")
data = []
for fn in args.files:
f = open(fn,"rb")
tab = [line.strip() for line in f.readlines()]
f.close()
header = np.array(tab[0][1:].split())
if args.f == None:
print ("There are following fields available in %s" % fn)
print header
else:
field = args.f[0]
fno =... | e()
ax = fig.add_subplot(111)
for i, fn in enumerate(data):
ax.plot(fn[:, 1], fn[:, fno], label=args.files[i])
ax.legend()
plt.ylabel(field)
plt.xlabel(header[1])
plt.draw()
plt.show()
|
ngageoint/gamification-server | gamification/core/migrations/0007_auto__add_field_project_url.py | Python | mit | 10,068 | 0.007847 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Project.url'
db.add_column(u'core_project', 'url',
self.gf('django.db.... | th.User']"}),
'value': ('django.db.models.fields.IntegerField', [], {'default': '0'})
},
u'core.project': {
'Meta': {'ordering': "('-created_at',)", 'object_name': 'Project'},
'active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'al... | ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'background_image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank'... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.