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 |
|---|---|---|---|---|---|---|---|---|
tatianass/quebra-quebra | html2csv/convert_html_to_csv.py | Python | gpl-3.0 | 12,480 | 0.034818 | #coding=utf-8
#################################################################################
#Author: Italo de Pontes Oliveira #
#Based on Spotipy API #
#created in: 08, july, 2017 #
#e-mail: italooliveira at copin dot ufcg dot edu dot br #
#Github link: github.com/italoPontes/PhdWorks #
#Wh... | .read().splitlines()
dado_servidor = conteudo_arquivo[187]
dado_servidor = dado_servidor.replace("col1tab_resposta", "col1_resposta")
dado_servidor = dado_servidor.replace("col2_resposta\"></td>", "col2_resposta\">0,00</td>")
dado_servidor = dado_servidor.replace | ("<span style=\"padding-left:20px\">", "<td class=\"col1_resposta\">")
tree = html.fromstring(dado_servidor)
servidor = servidor_camara()
servidor.mes = mes
servidor.ano = ano
#Salva identificador unico do servidor
servidor.user_id = user_id
####################################################... |
mbelchin/cargomedia_social_graph | python_mongo/config.py | Python | gpl-2.0 | 391 | 0.023018 | #!/usr/b | in/env python
# -*- coding: utf-8 -*-
#
# Author: Moises Belchin <moisesbelchin@gmail.com>
# Date: February 2015
### Default mongoDB server
MONGO_SERVER = 'localhost'
### Default mongoDB port
MONGO_PORT = 27017
### Default mongoDB database name
MONGO_DB_NAME = 'social-graph'
### Def... | '
|
unicef/un-partner-portal | backend/unpp_api/apps/partner/roles.py | Python | apache-2.0 | 6,282 | 0 | from enum import unique, auto
from partner.permissions import PartnerPermission
from common.enums import AutoNameEnum
@unique
class PartnerRole(AutoNameEnum):
"""
Editing names here WILL break roles saved in DB
"""
ADMIN = auto()
EDITOR = auto()
READER = auto()
@classmethod
def get_c... | PartnerPermission.CFEI_SUBMIT_CONCEPT_NOTE,
PartnerPermission.UCN_DELETE,
PartnerPermission.EDIT_PROFILE,
PartnerPermission.DSR_VIEW,
PartnerPermission.DSR_ANSWER,
]),
PartnerRole.EDITOR: frozenset([
PartnerPermission.VIEW_DASHBOARD,
... | CTION,
PartnerPermission.CFEI_SEND_CLARIFICATION_REQUEST,
PartnerPermission.UCN_VIEW,
PartnerPermission.UCN_DRAFT,
PartnerPermission.UCN_EDIT,
PartnerPermission.RECEIVE_NOTIFICATIONS,
PartnerPermission.UCN_SUBMIT,
PartnerPermission.CFEI... |
coala/corobo | plugins/spam.py | Python | mit | 949 | 0 | from errbot import BotPlugin
from errbot.templating import tenv
from plugins import constants
from utils.mixi | n import DefaultConfigMixin
class SpammingAlert(DefaultConfigMixin, BotPlugin):
"""
A plugin which alerts the user that they might be spamming.
"""
CONFIG_TEMPLATE = {
'MAX_MSG_LEN': constants.MAX_MSG_LEN,
' | MAX_LINES': constants.MAX_LINES
}
def check_configuration(self, configuration):
pass
def callback_message(self, msg):
"""
Alert the user that his/her message is too long or has too
many lines.
"""
if (len(msg.body) > self.config['MAX_MSG_LEN'] or
... |
eduNEXT/edx-platform | pavelib/paver_tests/test_utils.py | Python | agpl-3.0 | 1,586 | 0.001261 | """
Tests for pavelib/utils/test/utils
"""
import unittest
from unittest.mock import patch
import pytest
from pavelib.utils.envs import Env
from pavelib.utils.test.utils import MINIMUM_FIREFOX_VERSION, check_firefox_version
@unittest.skipIf(Env.USING_DOCKER, 'Firefox version check works differently under Docker D... | ock_subprocesss.return_value = "Mozilla Firefox"
with pytest.raises(Exception):
check_firefox_version()
@patch('subprocess.check_output')
def test_firefox_version_bad(self, _mock | _subprocesss):
_mock_subprocesss.return_value = "garbage"
with pytest.raises(Exception):
check_firefox_version()
|
kelseyoo14/Wander | venv_2_7/lib/python2.7/site-packages/pandas/tests/test_frame.py | Python | artistic-2.0 | 638,116 | 0.005919 | # -*- coding: utf-8 -*-
from __future__ import print_function
# pylint: disable-msg=W0612,E1101
from copy import deepcopy
from datetime import datetime, timedelta, time, date
import sys
import operator
import re
import csv
import nose
import functools
import itertools
from itertools import product, permutations
from d... | ypes = dict(A = 'int32', B = 'uint64', C = 'uint8', D = 'int64')
if isinstance(dtype, compat.string_types):
dtypes = d | ict([ (k,dtype) for k, v in dtypes.items() ])
elif isinstance(dtype, dict):
dtypes.update(dtype)
if dtypes.get('A'):
assert(df.dtypes['A'] == dtypes['A'])
if dtypes.get('B'):
assert(df.dtypes['B'] == dtypes['B'])
if dtypes.get('C'):
assert(df.dtypes['C'] == dtypes['C'])
... |
uwkejia/Clean-Energy-Outlook | ceo/test_ridge_prediction.py | Python | mit | 3,043 | 0.005587 | from ceo import ridge_prediction as rp
import ceo
import os
import os.path as op
import pandas as pd
import inspect
data_path = op.join(ceo.__path__[0], 'Data')
data_path = op.join(data_path, 'Cleaned Data')
def test_pred_nuclear():
"""
Function to test pred_nuclear
Input:
None
Returns:
... | , 'pred_hydro incorrect'
return
def test_ridge_predict_all():
"""
Function to test predict_all
Input:
None
Returns:
None
"""
rp.ridge_predict_all()
path= os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
path = op.join(path, 'Data')
... | op.join(path_predict, 'Ridge Regression')
statelist = os.listdir(path_predict)
for i in statelist:
pred = pd.read_csv(path_predict+'\\%s' %i)
assert all(pred['NUETP'][-6:] != None), 'pred_nuclear incorrect'
assert all(pred['NUETP'][-6:] >= 0), 'pred_nuclear incorrect'
assert all... |
jorik041/shmoocon_2014_talk | caravan/caravan/dashboards/infrastructure/bandwidth/tests.py | Python | bsd-2-clause | 171 | 0 | from horizon.test import he | lpers as test
class BandwidthTests(test.TestCase):
# Unit tests for bandwidth.
def test_m | e(self):
self.assertTrue(1 + 1 == 2)
|
citrix-openstack-build/neutron | neutron/plugins/common/constants.py | Python | apache-2.0 | 1,771 | 0.000565 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 OpenStack Foundation.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apac... | se 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.
# service type constants:
CORE = "CORE"
DUMMY = "DUMMY"
LOADBALANCER = "LOADBALANCER"
FIREWAL... | NG = "METERING"
L3_ROUTER_NAT = "L3_ROUTER_NAT"
#maps extension alias to service type
EXT_TO_SERVICE_MAPPING = {
'dummy': DUMMY,
'lbaas': LOADBALANCER,
'fwaas': FIREWALL,
'vpnaas': VPN,
'metering': METERING,
'router': L3_ROUTER_NAT
}
# TODO(salvatore-orlando): Move these (or derive them) from... |
rspavel/spack | var/spack/repos/builtin/packages/r-doparallel/package.py | Python | lgpl-2.1 | 1,029 | 0.004859 | # 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 RDoparallel(RPackage):
"""Provides a parallel backend for the %dopar% function using the p... | rallel
package."""
homepage = "https://cloud.r-project.org/package=doParallel"
url = "https://cloud.r-project.org/src/contrib/doParallel_1.0.10.tar.gz"
list_url = "https://cloud.r-project.org/src/contrib/Archive/doParallel"
version('1.0.15', sha256='71ad7ea69616468996aefdd8d02a4a234759a21ddde... | 024b6950025cc027022ee409f382e5ad3680c0a25bcd404bfc16418be8add5')
depends_on('r@2.14.0:', type=('build', 'run'))
depends_on('r-foreach@1.2.0:', type=('build', 'run'))
depends_on('r-iterators@1.0.0:', type=('build', 'run'))
|
corvorepack/REPOIVAN | plugin.video.movie.ultra.7k/resources/tools/chollotv.py | Python | gpl-2.0 | 9,416 | 0.030361 | # -*- coding: utf-8 -*-
#------------------------------------------------------------
# Movie Ultra 7K
# Version 0.2 (09.01.2016)
#------------------------------------------------------------
# License: GPL (http://www.gnu.org/licenses/gpl-3.0.html)
# Gracias a la librería plugintools de Jesús (www.mimediacenter.info)
... | ui
import xbmcaddon
import xbmcplugin
import plugintools
import requests
from resources.tools.resolvers import *
playlists = xbmc.translatePath(os.path.join('special://userdata/playlists', ''))
temp = xbmc.translatePath(os.p | ath.join('special://userdata/playlists/tmp', ''))
addonName = xbmcaddon.Addon().getAddonInfo("name")
addonVersion = xbmcaddon.Addon().getAddonInfo("version")
addonId = xbmcaddon.Addon().getAddonInfo("id")
addonPath = xbmcaddon.Addon().getAddonInfo("path")
url = 'http://www.ch... |
CGATOxford/CGATPipelines | CGATPipelines/pipeline_docs/pipeline_rnaseqdiffexpression/trackers/Isoform.py | Python | mit | 398 | 0.002513 |
from CGATReport.Tracker import *
from IsoformReport import *
class imagesTracker(TrackerIm | ages):
'''Convience Tracker for globbing images for gallery plot'''
def __init__ | (self, *args, **kwargs):
Tracker.__init__(self, *args, **kwargs)
if "glob" not in kwargs:
raise ValueError("TrackerImages requires a:glob: parameter")
self.glob = kwargs["glob"]
|
ychen820/microblog | y/google-cloud-sdk/lib/googlecloudapis/bigquery/v2/bigquery_v2_client.py | Python | bsd-3-clause | 25,939 | 0.005205 | """Generated client library for bigquery version v2."""
# NOTE: This file is autogenerated and should not be edited by hand.
from googlecloudapis.apitools.base.py import base_api
from googlecloudapis.bigquery.v2 import bigquery_v2_messages as messages
class BigqueryV2(base_api.BaseApiClient):
"""Generated client l... | setList',
supports_download=False,
),
'Patch': base_api.ApiMethodInfo(
http_method=u'PATCH',
method_id=u'bigquery.datasets | .patch',
ordered_params=[u'projectId', u'datasetId'],
path_params=[u'datasetId', u'projectId'],
query_params=[],
relative_path=u'projects/{projectId}/datasets/{datasetId}',
request_field=u'dataset',
request_type_name=u'BigqueryDatasetsP... |
djo938/GPSPythonSharingWithPyro | clientTest.py | Python | gpl-3.0 | 876 | 0.010274 | #!/usr/bin/python
from pysharegps import sharedGpsClient
import logging
if __name__ == "__main__":
logging.basicConfig(format='%(asctime)s %(message)s',level=logging.DEBUG)
client = sharedGpsClient()
if client.isInit():
position = client.getSharedObject().getPosition()
print "latitude... | " ("+str(position[2])+")"
altitude = client.getSharedObject().getAltitude()
print "altitude: "+str(a | ltitude[0])+str(altitude[1])+" ("+str(position[2])+")"
place = client.getSharedObject().getPlace()
if place[4] == None:
print "no defined place near this position"
else:
print "nearest place: "+place[0]+" at "+str(place[1])+str(place[2])+","+str(place[3])+" ("+st... |
ecreall/lagendacommun | lac/views/services_processes/selling_tickets_service/renew_service.py | Python | agpl-3.0 | 2,351 | 0.001276 | # Copyright (c) 2014 by Ecreall under licence AGPL terms
# available on http://www.gnu.org/licenses/agpl.html
# licence: AGPL
# author: Amen Souissi
from pyramid.view import view_config
from dace.processinstance.core import DEFAULTMAPPING_ACTIONS_VIEWS
from pontus.view import BasicView
from pontus.form import Form... | s'] = {self.coordinates: [item]}
return result
class RenewSellingTicketsServiceView(FormView):
title = _('Renew the sellingtickets service')
schema = select(SellingTicketsServiceSchema(factory=SellingTicketsService,
| editable=True),
['title'])
behaviors = [RenewSellingTicketsService, Cancel]
formid = 'formrenewsellingticketsservice'
name = 'renewsellingticketsservice'
validate_behaviors = False
def default_data(self):
return self.context
@view_config(
name='renewse... |
wobh/xpython | wordy/example.py | Python | mit | 1,109 | 0.000902 | import sys
from operator import add, mul, sub
if sys.version_info[0] == 2:
from operator import div
else:
from operator import floordiv as div
VALID_OPERATIONS = {"plus": add, "minus": sub,
"multiplied by": mul, "divided by": div}
def calculate(stmt):
if not (stmt.startswith("What i... | d stmt.endswith("?")):
raise ValueError("Ill-formed question")
l = stmt[8:-1].strip().lower().split()
if not l:
raise ValueError("Ill-formed question")
l.reverse()
try:
op1 = int(l.pop())
except | ValueError:
raise ValueError("Ill-formed question")
while l:
oprt = [l.pop()]
while l:
try:
next_tk = l.pop()
op2 = int(next_tk)
break
except ValueError:
oprt.append(next_tk)
else:
rai... |
alexurquhart/webgis | app/redis_conn.py | Python | mit | 46 | 0.043478 | import redis
Redis = redis.StrictRedis()
| ||
peircej/PsychoEEG | psychoeeg/io.py | Python | mit | 3,894 | 0.011556 | """Some classes to support import of data files
"""
import os, glob
import numpy
import time
try:
import ConfigParser as configparser #gets rename to lowercase in python 3
except:
import configparser
class _BaseDataFile(object):
"""
"""
def __init__(self, filepath):
"""
"""
... | lename)
cfg.readfp(f) #operates in place (doesn't return anything)
f.close()
hdr['channels'] = cfg.items('File Information')
for name, val in cfg.items('File Information'): #reads entries in File In | fo section as a list of tuples
if name.lower()=='number of channels':
hdr['channels']=int(val.replace('"', '')) # convert '"200"' to 200
elif name.lower()=='samples per second':
hdr['rate']=int(val.replace('"', '')) # convert '"200"' to 200
return hdr
... |
baffolobill/mb_test_1 | src/mbtest1/erp_test/urls/properties.py | Python | mit | 878 | 0 | from django.conf.urls import url
from ..views import properties as views
urlpatterns = [
url(r'^$',
views.PropertyList.as_view(),
name='p | roperty-list'),
url(r'^/(?P<pk>\d+)/?$',
views.PropertyDetail.as_view(),
name='property-detail'),
url(r'^/(?P<name>[a-z\._]+)/?$',
views.PropertyDetail.as_view(),
name='property-detail'),
url(r'^/(?P<name>[a-z\._]+)/options/?$',
views.PropertyOption | List.as_view(),
name='property-option-list'),
url(r'^/groups/?$',
views.PropertyGroupList.as_view(),
name='property-group-list'),
url(r'^/groups/(?P<pk>\d+)/?$',
views.PropertyGroupDetail.as_view(),
name='property-group-detail'),
url(r'^/groups/(?P<name>[\w]+)/?$',... |
sassoftware/mint | mint_test/resttest/modellibtest/jsontest.py | Python | apache-2.0 | 4,991 | 0.011421 | #!/usr/bin/python
#
# Copyright (c) SAS Institute 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... | el):
| foo1 = Field1()
foo2 = Field2()
foo3 = Field3()
m = Model(foo1 = 'a', foo2 = 'b')
self.failUnlessEqual(m.foo1, "a")
self.failUnlessEqual(m.foo2, "b")
self.failUnlessEqual(self.toString(m), '{"model": {"foo1": "a", "foo2": "b"}}')
#m = self.fai... |
lferr/charm | charm/schemes/pkenc/pkenc_gm82.py | Python | lgpl-3.0 | 2,619 | 0.001145 | '''
Goldwasser-Micali Public Key Encryption Scheme (Quadratic Residuosity problem)
| From: "S. Goldwasser, S. Micali: Probabilistic encryption and how to play
| mental poker keeping secret all partial information"
| Published in: 14th Symposium on Theory of Computing (1982)
| Available from: http://groups.csai... | sk = (self.group.p, self.group.q)
return (pk, sk)
def encrypt(self, pk, m):
(n, x) = pk
|
y = self.group.random()
while gcd(n, y) != 1:
y = self.group.random()
if m == 0:
return y**2 % n
else:
return y**2 * x % n
def decrypt(self, sk, c):
(p, q) = sk
return 0 if isResidue(c, p, q) else 1
# Homomorphic XOR over ci... |
locarise/locarise-drf-oauth2-support | locarise_drf_oauth2_support/users/models.py | Python | mit | 2,474 | 0.000404 | # -*- coding: utf-8 -*-
from shortuuidfield import ShortUUIDField
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import (
AbstractBaseUser,
PermissionsMixin,
BaseUserManager,
)
from django_extensions.db.fields import ModificationDateTim... | = "email"
history = HistoricalRecords()
__repr__ = sane_repr("email",)
class Meta:
verbose_name = _("user")
verbose_name_plural = _("users")
def get_full_name(self):
"""
Returns th | e first_name plus the last_name, with a space in between.
"""
full_name = "%s %s" % (self.first_name, self.last_name)
return full_name.strip()
def get_short_name(self):
"""
Returns the short name for the user.
"""
return self.first_name
|
GoogleCloudPlatform/datacatalog-connectors-rdbms | google-datacatalog-rdbms-connector/src/google/datacatalog_connectors/rdbms/scrape/metadata_enricher.py | Python | apache-2.0 | 987 | 0 | #!/usr/bin/python
#
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with t | he 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 languag... |
hynek/tnw | setup.py | Python | mit | 425 | 0 | # -*- coding: utf-8 -*-
from setuptools import setup
setup(
name='dan | e_doctor',
version='0.1',
classifiers=["Private :: Do Not Upload"],
entry_points={
'console_scripts': [
'danex = danex.__main__:main',
]
},
packages=[
'danex',
],
install_requires=[
'getdns',
'idna',
'pyopenssl',
'twist | ed',
"txsockjs",
],
)
|
jffm/pyanalyzer | metrics/NumberOfReturns.py | Python | gpl-3.0 | 1,602 | 0.004994 | # Copyright (c) 2008-2009 Junior (Frederic) FLEURIAL MONFILS
#
# This file is part of PyAnalyzer.
#
# PyAnalyzer 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
# (a... | 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 rece | ived a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# or see <http://www.opensource.org/licenses/gpl-3.0.html>
#
# Contact:
# Junior FLEURIAL MONFILS <frederic dot fleurialmonfils at cetic dot be>
__author__ = "Frederic F. MONFILS"
__versio... |
fakedrake/overlay_parse | setup.py | Python | apache-2.0 | 568 | 0 | imp | ort re
from setuptools import setup
init_py = open('overlay_parse/__init__.py').read()
metadata = dict(re.findall("__([a-z]+)__ = '([^']+)'", init_py))
metadata['doc'] = re.findall('"""(.+)"""', init_py)[0]
setup(
name='overlay-parse',
version=metadata['version'],
description=metadata['doc'],
author=m... | True,
install_requires=[
],
test_suite='nose.collector',
license=open('LICENSE').read(),
)
|
uffejakobsen/libsigrokdecode | decoders/tca6408a/pd.py | Python | gpl-3.0 | 4,605 | 0.003478 | ##
## This file is part of the libsigrokdecode project.
##
## Copyright (C) 2012 Uwe Hermann <uwe@hermann-uwe.de>
## Copyright (C) 2013 Matt Ranostay <mranostay@gmail.com>
## Copyright (C) 2014 alberink <alberink@stampfini.org>
##
## This program is free software; you can redistribute it and/or modify
## it under the t... | 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 | uted in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program; ... |
ymorired/s4backup | test/flock_test.py | Python | mit | 585 | 0.001709 | __author__ = 'mori.yuichiro'
import unittest
import os
from flo | ck import SimpleFileLock
class SimpleFileLockTest(unittest.TestCase):
def setup(self):
pass
def teardown(self):
pass
def test_lock(self):
path = 'test/test_lock'
a_lock = SimpleFileLock(path)
b_lock = SimpleFileLock(path)
self.assertTrue(a_lock.aquire_l... | ck.release()
if __name__ == '__main__':
unittest.main()
|
wwitzel3/awx | awx/main/tests/functional/api/test_credential.py | Python | apache-2.0 | 59,080 | 0.001676 | import itertools
import re
import mock # noqa
import pytest
from awx.main.models import (AdHocCommand, Credential, CredentialType, Job, JobTemplate,
Inventory, InventorySource, Project,
WorkflowJobNode)
from awx.main.utils import decrypt_field
from awx.api.ver... | type_ssh, params):
params['user'] = 'asdf'
params['name'] = 'Some name'
response = post(
reverse('api:credential_list', kwargs={'version': version}),
params,
admin
)
assert response.status_code == 400
assert response.data['user'][0] == 'Incorrect type. Expected pk value, ... | 'someusername'}],
['v2', {'credential_type': 1, 'inputs': {'username': 'someusername'}}]
])
def test_create_user_credential_via_user_credentials_list(post, get, alice, credentialtype_ssh, version, params):
params['user'] = alice.id
params['name'] = 'Some name'
response = post(
reverse('api:user... |
nck0405/ChennaiEden | modules/geopy/point.py | Python | mit | 10,655 | 0.005068 | import re
from itertools import islice
#from geopy import util, units, format
import util, units, format
class Point(object):
"""
A geodetic point with latitude, longitude, and altitude.
Latitude and longitude are floating point values in degrees.
Altitude is a floating point value in kilometers. ... | ))?
\s*$
""" % UTIL_PATTERNS, re.X)
def __new__(cls, latitude=None, longitude=None, altitude=None):
single_arg = longitude is None and altitude is None
if single_arg and not isinstance(latitude, util.NUMBER_TYPES):
arg = latitude
if arg i | s None:
pass
elif isinstance(arg, Point):
return cls.from_point(arg)
elif isinstance(arg, basestring):
return cls.from_string(arg)
else:
try:
seq = iter(arg)
except TypeError:
... |
nachandr/cfme_tests | cfme/base/credential.py | Python | gpl-2.0 | 6,916 | 0.000723 | from copy import deepcopy
from cfme.utils import conf
from cf | me.utils.pretty import Pretty
from cfme.utils.update import Updateable
class FromConfigMixin:
@staticmethod
def rename_properties(creds):
"""
helper function to make pr | operties have same names in credential objects.
Args:
creds: dict
Returns: updated dict
"""
creds = deepcopy(creds)
to_rename = [('password', 'secret'), ('username', 'principal')]
for key1, key2 in to_rename:
if key1 in creds:
cred... |
beernarrd/gramps | gramps/gen/filters/rules/family/_regexpfathername.py | Python | gpl-2.0 | 1,866 | 0.005895 | #
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2002-2006 Donald N. Allingham
#
# 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 you... | Boston, MA 02110-1301 USA.
#
#-------------------------------------------------------------------------
#
# Standard Python modules
#
#------------- | ------------------------------------------------------------
from ....const import GRAMPS_LOCALE as glocale
_ = glocale.translation.gettext
#-------------------------------------------------------------------------
#
# Gramps modules
#
#-------------------------------------------------------------------------
from ..p... |
AlbertoAlfredo/exercicios-cursos | Curso-em-video/Python/aulas-python/Desafios/desafio002.py | Python | mit | 188 | 0.021505 | dia=input("Digite seu dia de nascimento: ")
mes=inp | ut("Digite seu mês de nascimento: ")
ano=input("Digite seu ano de nascimento: ")
pr | int("Você nasceu no dia", dia, "de", mes, "de", ano) |
muhammad-ammar/factory_boy | tests/test_mongoengine.py | Python | mit | 3,452 | 0 | # -*- coding: utf-8 -*-
# Copyright (c) 2013 Romain Command&
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, mod... | gine.connect(
db=cls.db_name,
host=cls.db_host,
port=cls.db_port,
# PyMongo>=2.1 requires an explicit read_preference.
read_preference=mongo_rp.ReadPreference.PRIMARY,
# PyMongo>=2.1 has a 20s timeout, use 100ms instead
serverselectiont... | ethod
def tearDownClass(cls):
cls.db.drop_database(cls.db_name)
def setUp(self):
mongoengine.connect('factory_boy_test')
def test_build(self):
std = PersonFactory.build()
self.assertEqual('name0', std.name)
self.assertEqual('street0', std.address.street)
sel... |
tkas/osmose-backend | analysers/analyser_osmosis_building_overlaps.py | Python | gpl-3.0 | 8,802 | 0.015002 | #!/usr/bin/env python
#-*- coding: utf-8 -*-
###########################################################################
## ##
## Copyrights Etienne Chové <chove@crans.org> 2009 ##
## Copyrights Frédéric Rodrigo 2011-2015 ... | # ##
###########################################################################
from modules.OsmoseTranslation import T_
from .Analyser_Osmosis import Analyser_Osmosis
from modules.Stablehash import stablehash64
sql20 = """
CREATE TEMP TABLE bnode... | T NULL AND
NOT relation AND
NOT layer AND
wall
"""
sql21 = """
CREATE INDEX bnodes_point_proj ON bnodes USING GIST(point_proj);
"""
sql30 = """
CREATE TEMP TABLE intersection_{0}_{1} AS
SELECT
b1.id AS id1,
b2.id AS id2,
ST_AsText(ST_Transform(ST_Centroid(ST_Intersection(b1.polygon_proj, b2.po... |
andres-de-castro/scraping | scraper.py | Python | mit | 2,725 | 0.005138 | import sys
from tornado import gen, ioloop
from tornado.httpclient import AsyncHTTPClient, HTTPRequest
from tornado.queues import Queue
class Scraper():
def __init__(
self,
destinations=None,
transform=None,
headers={},
max_clients=5... | t.fetch(request)
def done_callback(future):
body = future.result().body
url = future.result().effective_ur | l
transform(body, url=url)
self.queue.task_done()
try:
future.add_done_callback(done_callback)
except Exception as e:
sys.stderr.write(str(e))
queue.put(url)
|
AppleFairy/CS224n-Natural-Language-Processing-with-Deep-Learning | assignment/assignment3/q2_rnn_cell.py | Python | mit | 4,987 | 0.004411 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Q2(c): Recurrent neural nets for NER
"""
from __future__ import absolute_import
from __future__ import division
import argparse
import logging
import sys
import tensorflow as tf
import numpy as np
logger = logging.getLogger("hw3.q2.1")
logger.setLevel(logging.DEBUG... | e=(None,2))
with tf.variable_scope("rnn"):
tf.get_variable("W_x", initializer=np.array(np.eye(3,2), dtype=np.float32))
tf.get_variable("W_h", initializer=np.array(np.eye(2,2), dtype=np.float32))
tf.get_variable("b", initializer=np.array(np.ones(2), dtype=np.... | = tf.global_variables_initializer()
with tf.Session() as session:
session.run(init)
x = np.array([
[0.4, 0.5, 0.6],
[0.3, -0.2, -0.1]], dtype=np.float32)
h = np.array([
[0.2, 0.5],
... |
cortext/crawtextV2 | ~/venvs/crawler/lib/python2.7/site-packages/yaml/tokens.py | Python | mit | 2,573 | 0.012048 |
class Token(object):
def __init__(self, start_mark, end_mark):
self.start_mark = start_mark
self.end_mark = end_mark
def __repr__(self):
attributes = [key for key in self.__dict__
if not key.endswith('_mark')]
attributes.sort()
arguments = ', '.join(['%s=... | = value
self.start_mark = start_mark
self.end_mark = end_mark
class TagToken(Token):
id = '<tag>'
def __init__(self, value, start_mark, end_mark):
self.value = value
self.start_mark = start_mark
self.end_mark = end_mark
class ScalarToken(Token):
id = '<scalar>'
... | ain = plain
self.start_mark = start_mark
self.end_mark = end_mark
self.style = style
|
vortex-ape/scikit-learn | sklearn/utils/linear_assignment_.py | Python | bsd-3-clause | 9,494 | 0 | """
Solve the unique lowest-cost assignment problem using the
Hungarian algorithm (also known as Munkres algorithm).
"""
# Based on original code by Brain Clapper, adapted to NumPy by Gael Varoquaux.
# Heavily refactored by Lars Buitinck.
#
# TODO: a version of this algorithm has been incorporated in SciPy; use that
#... | rian algorithm.
The problem is also known as maximum weight matching in bipartite graphs.
The method is also known as the Munkres or Kuhn-Munkres algorithm.
Parameters
----------
X : array
The cost matrix of the bipartite graph
Returns
-------
indices : array
The pairs... | 1. http://www.public.iastate.edu/~ddoty/HungarianAlgorithm.html
2. Harold W. Kuhn. The Hungarian Method for the assignment problem.
*Naval Research Logistics Quarterly*, 2:83-97, 1955.
3. Harold W. Kuhn. Variants of the Hungarian method for assignment
problems. *Naval Research Logistics Quarterl... |
keras-team/keras-io | examples/graph/gat_node_classification.py | Python | apache-2.0 | 13,849 | 0.003177 | """
Title: Graph attention network (GAT) for node classification
Author: [akensert](https://github.com/akensert)
Date created: 2021/09/13
Last modified: 2021/12/26
Description: An implementation of a Graph Attention Network (GAT) for node classification.
"""
"""
## Introduction
[Graph neural networks](https://en.wikip... | ges[:, 0]) + 1,
)
attention_scores_sum = tf.repeat(
attention_scores_sum, tf.math.bincount(tf.cast(edges[:, 0], "int32"))
)
attention_scores_norm = attention_scores / attention_scores_sum
# (3) Gather node states of neighbors, apply attention scores and aggregate
... | .gather(node_states_transformed, edges[:, 1])
out = tf.math.unsorted_segment_sum(
data=node_states_neighbors * attention_scores_norm[:, tf.newaxis],
seg |
joerick/pyinstrument | noxfile.py | Python | bsd-3-clause | 151 | 0 | import nox
@nox.session(python=["3.7", "3.8", "3.9"])
def t | est(session):
session.install("-r", "requirements-de | v.txt")
session.run("pytest")
|
YakindanEgitim/malwarez | malwarez/urls.py | Python | gpl-3.0 | 1,882 | 0.008502 | from django.conf.urls import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from socketio import sdjango
from web.api import EventResource, SummaryFeedResource, SummaryFeedByCountryCodeResource
from tastypie.api import Api
# Uncomment the next two li | nes to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
sdjango.autodiscover()
v1_api = Api(api_name='v1')
#ap | i_test = EventResource()
v1_api.register(SummaryFeedResource())
#v1_api.register(SummaryFeedByCountryCodeResource())
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'malwarez.views.home', name='home'),
# url(r'^malwarez/', include('malwarez.foo.urls')),
# Uncomment the admin/doc line below to ena... |
sdu14SoftwareEngineering/GameOfLife_WEB | game/migrations/0001_initial.py | Python | apache-2.0 | 615 | 0.001626 | # -*- coding: | utf-8 -*-
# Generated by Django 1.10.1 on 2016-09-24 05:39
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='User',
f... | ('password', models.CharField(max_length=30)),
],
),
]
|
sdoran35/hate-to-hugs | venv/lib/python3.6/site-packages/nltk/corpus/reader/ipipan.py | Python | mit | 12,717 | 0.002123 | # Natural Language Toolkit: IPI PAN Corpus Reader
#
# Copyright (C) 2001-2017 NLTK Project
# Author: Konrad Goluchowski <kodie@mimuw.edu.pl>
# URL: <http://nltk.org/>
# For license information, see LICENSE.TXT
import functools
from nltk import compat
from nltk.corpus.reader.util import StreamBackedCorpusView, concat
... | iles(fileids):
values_list = self._get_tag(f, tag)
for v in values_list:
values.add(v)
return list(values)
def _list_morph_files_by(self, tag, values, map=None):
fileids = self.fileids()
ret_fileids = set()
for f in fileids:
fp = s... | if map is not None:
value = map(value)
if value in values:
ret_fileids.add(f)
return list(ret_fileids)
def _get_tag(self, f, tag):
tags = []
with open(f, 'r') as infile:
header = infile.read()
tag_end = 0
... |
gdude2002/Health-journals | internal/db.py | Python | agpl-3.0 | 7,267 | 0 | __author__ = 'Gareth Coles'
import datetime
import calendar
import pymongo
from pymongo.collection import ObjectId
from internal.singleton import Singleton
class Db(object):
"""
Very, very simple schema validation. Super simple.
This introduces a singleton for managing the Mongo instance. It exposes
... | )
client = pymongo.MongoClient(uri)
db = client[self.config["db"]]
self.client = client
self.db = db
def stringify(self, _in):
"""
:type _in: dict, list
"""
| if isinstance(_in, dict):
for key in _in.keys():
if isinstance(_in[key], ObjectId):
_in[key] = str(_in[key])
elif isinstance(_in[key], datetime.datetime):
_in[key] = calendar.timegm(_in[key].utctimetuple())
elif isinstan... |
Teekuningas/mne-python | mne/io/edf/tests/test_edf.py | Python | bsd-3-clause | 16,927 | 0 | # -*- coding: utf-8 -*-
# Authors: Teon Brooks <teon.brooks@gmail.com>
# Martin Billinger <martin.billinger@tugraz.at>
# Alan Leggitt <alan.leggitt@ucsf.edu>
# Alexandre Barachant <alexandre.barachant@gmail.com>
# Stefan Appelhoff <stefan.appelhoff@mailbox.org>
# Joan Massic... | te_channel_labels_path, preload=False)
assert raw.ch_names == EXPECTED_CHANNEL_NAMES
def test_parse_annotation(tmpdir):
"""Test parsing the tal channel."""
# test the parser
annot = (b'+180\x14Lights off\x14Close door\x14\x00\x00\x00\x00\x00'
b'+180\x14Lights off\x14\ | x00\x00\x00\x00\x00\x00\x00\x00'
b'+180\x14Close door\x14\x00\x00\x00\x00\x00\x00\x00\x00'
b'+3.14\x1504.20\x14nothing\x14\x00\x00\x00\x00'
b'+1800.2\x1525.5\x14Apnea\x14\x00\x00\x00\x00\x00\x00\x00'
b'+123\x14\x14\x00\x00\x00\x00\x00\x00\x00')
annot_file = tmpdir... |
eonpatapon/contrail-neutron-plugin | neutron_plugin_contrail/plugins/opencontrail/quota/driver.py | Python | apache-2.0 | 9,119 | 0.000439 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
import ConfigParser
from pprint import pformat
try:
from neutron.openstack.common import log as logging
except ImportError:
from oslo_log import log as logging
from neutron.common import exceptions
try:
from neutron.common.config import cfg
except ImportError:... | proj_obj = cls._get_vnc_conn().project_read(id=proj_id)
quota = proj_obj.get_quota()
except vnc_exc.NoIdError:
return {}
except Exception as e:
cgitb.Hook(format="text").handle(sys.exc_info())
raise e
qn2c = cls.quota_neutron_to_contrai... | ne
if quota and resource in qn2c:
quota_res = getattr(quota, qn2c[resource], None)
if quota_res is not None:
has_non_default = True
if quota_res is None and default_quota and resource in qn2c:
quota_res = getattr(default_quota, ... |
ayeowch/bitnodes-hardware | hardware/__init__.py | Python | mit | 1,220 | 0 | #
# Copyright (c) Addy Yeow Chin Heng <ayeowch@gmail.com>
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify... | of the Software, and to
# permi | t persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCL... |
iotile/coretools | transport_plugins/socket_lib/test/unix/conftest.py | Python | gpl-3.0 | 2,316 | 0.001727 | import pytest
import logging
import tempfile
from iotile.core.hw.hwmanager import HardwareManager
from iotile.core.hw.transport.adapter.sync_wrapper import SynchronousLegacyWrapper
from iotile.core.hw.transport import VirtualDeviceAdapter
from iotile.core.utilities import BackgroundEventLoop
from iotile_transport_socke... | .param
tmpdir = tempfile.TemporaryDirectory(dir="/tmp")
socketfile = tmpdir.name+"/s"
if not isinstance(devices, tuple):
devices = (devices,)
logger.info("Parametrizing server with devices: %s", devices)
adapter = VirtualDeviceAdapter(devices=devices, loop=loop)
loop.run_coroutine(ada... | er = UnixSocketDeviceServer(adapter, args, loop=loop)
loop.run_coroutine(dev_server.start())
yield socketfile, adapter
loop.run_coroutine(dev_server.stop())
loop.run_coroutine(adapter.stop())
@pytest.fixture(scope="function")
def hw(server):
path, _ = server
logger.info("Creating HardwareMa... |
ActiveState/code | recipes/Python/114642_Pinhole/recipe-114642.py | Python | mit | 2,454 | 0.035045 | """
usage 'pinhole port host [newport]'
Pinhole forwards the port to the host specified.
The optional newport parameter may be used to
redirect to a different port.
eg. pinhole 80 webserver
Forward all incoming WWW sessions to webserver.
pinhole 23 localhost 2323
Forward all telnet sessions to port 2323 ... | s ' % address )
fwd = socket( AF_INET, SOCK_STREAM )
fwd.connect(( self.newhost, self.newport ))
PipeThread( newsock, fwd ).start()
PipeThread( fwd, newsock ).start()
if __name__ == '__main__':
| print 'Starting Pinhole'
import sys
sys.stdout = open( 'pinhole.log', 'w' )
if len( sys.argv ) > 1:
port = newport = int( sys.argv[1] )
newhost = sys.argv[2]
if len( sys.argv ) == 4: newport = int( sys.argv[3] )
Pinhole( port, newhost, newport ).start()
else:
... |
plotly/python-api | packages/python/plotly/plotly/graph_objs/splom/marker/_line.py | Python | mit | 24,938 | 0.001043 | from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType
import copy as _copy
class Line(_BaseTraceHierarchyType):
# class properties
# --------------------
_parent_path_str = "splom.marker"
_path_str = "splom.marker.line"
_valid_props = {
"autocolorscale",
... | ly i | f in
`marker.line.color`is set to a numerical array. In case
`colorscale` is unspecified or `autocolorscale` is true, the
default palette will be chosen according to whether numbers in
the `color` array are all positive, all negative or mixed.
The 'autocolorscale' property ... |
hassanibi/erpnext | erpnext/accounts/doctype/payment_entry_reference/payment_entry_reference.py | Python | gpl-3.0 | 287 | 0.006969 | # -*- coding: utf- | 8 -*-
# Copyright (c) 2015, Frap | pe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
class PaymentEntryReference(Document):
pass
|
waweber/imapfs | imapfs/file.py | Python | gpl-3.0 | 7,538 | 0.010082 | # IMAPFS - Cloud storage via IMAP
# Copyright (C) 2013 Wes Weber
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# T... |
start_block_id = self.pos / FS_BLOCK_SIZE
end_block_ | id = (self.pos + size) / FS_BLOCK_SIZE + 1
write_offset = 0
# For each block we need to write to
for i in range(start_block_id, end_block_id):
# Find where our write starts in the current block
current_block_offset = self.pos % FS_BLOCK_SIZE
# Figure out how much we can write in this blo... |
nttks/edx-platform | lms/djangoapps/courseware/ga_progress_restriction.py | Python | agpl-3.0 | 6,513 | 0.003685 | """
Progress Restriction
"""
import json
from courseware.models import StudentModuleHistory
PROGRESS_RESTRICTION_TYPE = {
'no-restriction': 'No Restriction',
'correct-answer-rate': 'Correct Answer Rate',
}
UNCONDITIONAL_PASSING = 100
class ProgressRestriction(object):
def __init__(self, course_key, user,... | get_restricted_list_in_same_section(self, vertical_name):
"""
Returns a list of sequence numbers of restricted vertical-blocks
in section including specific vertical-block
"""
return self.get_restricted_list_in_section(self.dict_section_name_by_vertical_name[vertical_name]) if v... | ce numbers, to use to gray out toc
"""
return self.list_restricted_chapter_index
def get_restricted_sections(self):
"""
Returns a dict of chapters' numbers as keys and
list of restricted sections' sequence numbers as values
to use to gray out toc
"""
... |
AnalogJ/lexicon | lexicon/tests/providers/test_transip.py | Python | mit | 3,773 | 0.001855 | """Integration tests for Transip"""
import re
from unittest import TestCase
import pytest
from lexicon.tests.providers.integration_tests import (
IntegrationTestsV2,
vcr_integration_test,
)
FAKE_KEY = """
-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEAxV08IlJRwNq9WyyGO2xRyT0F6XIBD2R5CrwJoP7gIHVU/Mhk
KeK8//+... | om.")
@pytest.fixture(autouse=True)
def _generate_fake_key(self, tmp_path):
self._fake_key = tmp_path / "key.pem"
self | ._fake_key.write_text(FAKE_KEY)
def _filter_headers(self):
return ["Signature", "Authorization"]
def _filter_post_data_parameters(self):
return ["login"]
def _filter_response(self, response):
response["body"]["string"] = re.sub(
rb'"token":"[\w.-]+"',
b'"to... |
Harshs27/Q-Classifier | python/gen_rand_vector.py | Python | mit | 233 | 0.008584 | import random
def Random(n, a, b):
# generates a vector of length n | with values randomly distributed from 'a' to 'b'
x = []
for i in range(0, n):
num = a + (b-a)*random.random()
x.append(num)
retu | rn x
|
renanalencar/hermes | schedule/forms.py | Python | mit | 636 | 0.003145 | __author__ = 'renanalencar'
from django import forms
from .mode | ls import Calendar, CalendarDate
class CalendarForm(forms.ModelForm):
class Meta:
model = Calendar
fields = [
"service_id",
"monday",
"tuesday",
"wednesday",
"thursday",
"friday",
"saturday",
"sunday",
... | s = [
"service_id",
"date",
"exception_type",
]
|
ray-project/ray | python/ray/serve/tests/test_controller.py | Python | apache-2.0 | 842 | 0.002375 | import pytest
import time
import ray
from ray import serve
def test_redeploy_start_time(serve_instance):
"""Check that redeploying a deployment doesn't reset its start time."""
controller = serve.api._global_client._controller
@serve.deployment
| def test(_):
return "1"
test.deploy()
deployment | _info_1, route_1 = ray.get(controller.get_deployment_info.remote("test"))
start_time_ms_1 = deployment_info_1.start_time_ms
time.sleep(0.1)
@serve.deployment
def test(_):
return "2"
test.deploy()
deployment_info_2, route_2 = ray.get(controller.get_deployment_info.remote("test"))
s... |
bruecksen/isimip | isi_mip/climatemodels/migrations/0057_sector_class_name.py | Python | mit | 2,105 | 0.00095 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-01-19 13:23
from __future__ import unicode_literals
from django.db import migrations, models
SECTOR_MAPPING = {
'Agriculture': 'Agriculture',
'Energy': 'Energy',
'Water (global)': 'WaterGlobal',
'Water (regional)': 'WaterRegional',
'Bio... | ):
sector.class_name = SECTOR_MAPPING.get(sector.name)
sector.save()
class Migration(migrations.Migration):
dependencies = [
| ('climatemodels', '0056_remove_outputdata_sector_old'),
]
operations = [
migrations.AddField(
model_name='sector',
name='class_name',
field=models.CharField(choices=[('Generic Sector', 'GenericSector'), ('Agriculture', 'Agriculture'), ('Energy', 'Energy'), ('... |
AtzeDeVries/master-image-retriever | lib/master.py | Python | apache-2.0 | 1,436 | 0.010446 | #import config
#import log
import sys
from . import db
from . import config
from . import log
from datetime import datetime
#import db
import shutil
import os
def get_my_master(image_id):
try:
| ml_db = db.connect(config.get('db_host'),config.get('db_user'),config.get('db_password'),config.get('db_name'))
log.logger.info('Succesfully connected to database on: ' + config.get('db_name') + '@' + config.get('db_host'))
except Exception as e:
log.logger.critical('Could not connect databas... | 'db_name') + '@' + config.get('db_host'))
log.logger.critical(e)
exit(1)
q = 'SELECT master_file FROM media WHERE regno = "' + image_id + '"'
master_file = None
try:
master_file = db.query(ml_db,q)
log.logger.debug('Succesfully queried tha ml database')
except Exception ... |
chassing/QuickSSH | quickssh/main.py | Python | mit | 6,381 | 0.013321 |
import os
import json
from Tkinter import *
from ttk import *
from subprocess import Popen, PIPE
VERSION = "0.1"
# default config
CONFIG = dict(
settings=dict(
terminal="Terminal",
sshbin="/usr/bin/ssh",
window_width=400,
window_height=40,
item_display="%(host)s as user %(user)s"
),
hosts=[... | oot.geometry('%dx%d+%d+%d' % (width, height, x, y))
def main():
CFG = os.path.join(os.environ["HOME"], ".quick_ssh.json | ")
global CONFIG
if not os.path.exists(CFG):
# write default config file
open(CFG, "w").write(json.dumps(CONFIG, indent=2))
error_msg = ""
try:
CONFIG = json.loads(open(CFG).read())
except:
# read config failed
error_msg = "unable to read config file; json decode error"
root = Tk()
... |
romain-dartigues/cf-python-client | integration/python/test_services.py | Python | apache-2.0 | 619 | 0.003231 | from config_test import build_client_from_configuration
import unittest
import logging
_logger = logging.getLogger(__name__)
class TestServices(unittest.TestCase):
def test_list_services(self):
cpt = 0
client = build_client_from_configuration()
for service in client.services.list():
... | ogger.debug('- %s' % service['entity']['label'])
if cpt == 0:
service = client.services.get_first(label=service['entity']['label'])
self.assertIsNotNone(service)
cpt += 1
_lo | gger.debug('test service list - %d found', cpt)
|
pbmanis/acq4 | acq4/util/DirTreeWidget/DirTreeTemplate_pyqt5.py | Python | mit | 4,684 | 0.002135 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'acq4/util/DirTreeWidget/DirTreeTemplate.ui'
#
# Created by: PyQt5 UI code generator 5.8.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
def setupUi(self, Form... | currentLabel.setFont(font)
self.currentLabel.setText("")
self.currentLabel.setObjectName("currentLabel")
self.horizontalLayout.addWidget(self.currentLabel)
self.gridLayout.addLayout(self.horizontalLayout, 8, 0, 1, 3)
self.newDirBtn = QtWidgets.QPushButton(Form)
self.newDi... | ectName("newDirBtn")
self.gridLayout.addWidget(self.newDirBtn, 5, 2, 1, 1)
self.fileTree = DirTreeWidget(Form)
self.fileTree.setAcceptDrops(True)
self.fileTree.setHeaderHidden(True)
self.fileTree.setObjectName("fileTree")
self.fileTree.headerItem().setText(0, "1")
... |
oliverdodd/pheed | pheed/abstractfeedreader.py | Python | mit | 1,014 | 0.054241 | " | "" Abst | ractFeedReader Class - read a subset of information from a feed
"""
import urllib2
import xml.dom.minidom
from pheed import domelement
class AbstractFeedReader:
def fetch(self,url):
""" Fake FeedBurner user agent to bypass feedburner redirection """
req = urllib2.Request(url,headers = {'User-Agent' : ... |
SuperBo/pyMIC | pymic/_misc.py | Python | bsd-3-clause | 4,842 | 0.00062 | # Copyright (c) 2014-2016, Intel Corporation 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 of conditions... | l = os.getenv("PYMIC_DEBUG", None)
try:
self._debug_level = int(_debug_level)
except:
pass
# PYMIC_TRACE
self._trace_level = 0
_trace_level = os.getenv("PYMIC_TRACE", 0)
try:
self._trace_level = int(_trace_level)
except:
... | )
# PYMIC_LIBRARY_PATH
self._search_path = os.getenv("PYMIC_LIBRARY_PATH", "")
_config = pymicConfig()
# determine the integer value for PYMIC_DEBUG
if _config._debug_level is not None:
print("PYMIC: debug level set to {0}".format(_config._debug_level),
file=sys.stderr)
def _debug(l... |
CMPUT404W17T06/CMPUT404-project | dash/migrations/0012_auto_20170327_1808.py | Python | apache-2.0 | 450 | 0 | # | -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-03-27 18:08
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('dash', '0011_auto_20170326_2020'),
]
operations = [
migrations.RenameField(
| model_name='follow',
old_name='requesterDisplayName',
new_name='friendDisplayName',
),
]
|
Twentysix26/Red-DiscordBot | cogs/streams.py | Python | gpl-3.0 | 26,330 | 0.000684 | from discord.ext import commands
from .utils.dataIO import dataIO
from .utils.chat_formatting import escape_mass_mentions
from .utils import checks
from collections import defaultdict
from string import ascii_letters
from random import choice
import discord
import os
import re
import aiohttp
import asyncio
import loggi... | it self.bot.say(embed=embed)
@commands.command(pass_context=True)
async def twitch(self, ctx, stream: str):
"""Checks if twitch stream is online"""
stream = escape_mass_mentions(stream)
r | egex = r'^(https?\:\/\/)?(www\.)?(twitch\.tv\/)'
stream = re.sub(regex, '', stream)
try:
data = await self.fetch_twitch_ids(stream, raise_if_none=True)
embed = await self.twitch_online(data[0]["_id"])
except OfflineStream:
await self.bot.say(stream + " is offl... |
gras/16-ValleyBot | src/drive.py | Python | mit | 2,528 | 0.01068 | # 16-ValleyBot drive.py
'''
Created on Mar 13, 2016
@author: Dead Robot Society
'''
import constants as c
# from sensors import DEBUG
from wallaby import motor
from wallaby import msleep
from wallaby import ao
from wallaby import seconds
from sensors import onBlackFront, onBlackBack
def driveTim... |
# PRIME motor settings
motor(c.LMOTOR, left)
motor(c.RMOTOR, right)
else:
# CLONE motor settings
motor(c.LMOTOR, left)
motor(c.RMOTOR, right)
def testMotors():
drive(-100, -100)
while not onBlackFront(): # wait to see line |
pass
stop()
drive(100, 100)
while not onBlackBack(): # wait to see line
pass
stop()
driveTimed(-70, 0, 1000)
driveTimed(70, 0, 1200)
msleep(1000)
def timedLineFollowLeft(time):
sec = seconds() + time
while seconds() < sec :
... |
lthurlow/Network-Grapher | proj/external/numpy-1.7.0/numpy/lib/__init__.py | Python | mit | 972 | 0.003086 | from info import __doc__
from numpy.version import version as __version__
from type_check import *
from index_tricks import *
from function_base import *
from shape_base import *
from stride_tricks import *
from twodim_base import *
from ufunclike import *
import scimath as emath
from polynomial import *
#import conv... | port *
from arraypad import *
__all__ = ['emath','math']
__all__ += type_check.__all__
__all__ += index_tricks.__all__
__all__ += function_base.__all__
__all__ += shape_base.__all__
__all__ += stride_tricks.__all__
__all__ += twodim_base.__all__
__all__ += ufunclike.__all__
__all__ += arraypad.__all__
__all__ += polyn... | all__ += financial.__all__
from numpy.testing import Tester
test = Tester().test
bench = Tester().bench
|
ebakan/ProCo | ProCo2010/Speed Round/adv01.py | Python | gpl-3.0 | 665 | 0.019549 | '''
Created on May 15, 2010
@author: ebakan
'''
import sys
if __name__ == '__main__':
ints = sys.stdin.readline().split()
for i in range(len(ints)):
ints[i]=int(ints[i])
while ints[0]<=6 and ints[1]<=6 and ints[2]<=6:
| sys.stdout.write("R")
ints[2]+=ints[0]
if ints[2]>6:
sys.stdout.write(" Win")
break
#sys.stdout.write('\r')
#sys.stdout.flush()
string = raw_input("test")
if string=="R":
ints[0]+=ints[2]
else:
ints[0]+=ints[1]
... | write("Lose")
break
sys.stdout.flush() |
mailme/mailme | conftest.py | Python | bsd-3-clause | 734 | 0 | import os
import os.path
import requests
import pytest
from django.conf import settings as django_settings
from | pytest_django.lazy_django import skip_if_no_django
def pytest_configure(config):
if not django_settings.configur | ed:
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mailme.conf.test')
# override a few things with our test specifics
django_settings.INSTALLED_APPS = tuple(django_settings.INSTALLED_APPS) + (
'mailme.tests',
)
@pytest.fixture(scope='function')
def allow_offline(request, settings):
... |
btimby/cloudstrype | web/cloudstrype/ui/urls.py | Python | mit | 792 | 0 | """
URL mapping for user interface.
"""
from django.conf import settings
from django.conf.urls import url
from django.contrib.auth.decorators import login_required
from django.contrib.staticfiles.v | iews import serve
from django.views.generic import TemplateView
from ui.views import HowView
urlpatterns = [
url(r'^$', TemplateView.as_view(template_name='ui/index.html'),
name='home'),
url(r'^how/(?P<step>[0-9]{1})/$', HowView.as_view(), name='how'),
url(r'^app/$',
login_required()(Temp... | url(r'^new/$',
login_required()(TemplateView.as_view(template_name='ui/new.html')),
name='new'),
]
if settings.DEBUG:
urlpatterns += [
url(r'^(?P<path>.*)$', serve),
]
|
harvyv/johnmay | base/migrations/0004_auto_20151223_1440.py | Python | apache-2.0 | 883 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('base', '0003_auto_20151109_2002'),
]
operations = [
migrations.AlterField(
model_name='bodega',
name... | Sucursal', null=True),
preserve_default=True,
),
migrations.AlterField(
model_name='cliente',
name='direccion',
field=models.CharField(max_length=200, null | =True, blank=True),
preserve_default=True,
),
migrations.AlterField(
model_name='cliente',
name='telefono',
field=models.CharField(max_length=30, null=True, blank=True),
preserve_default=True,
),
]
|
bxlab/HiFive_Paper | Scripts/HiCPipe/create_hicpipe_heatmap_h5dict.py | Python | bsd-3-clause | 8,904 | 0.002808 | #!/usr/bin/env python
import sys
import subprocess
import os
from math import floor, ceil
import numpy
try:
from mpi4py import MPI
except:
pass
import h5py
import hifive
import heatmap
def write_heatmap_dict(datafname, modelprefix, outfname, binsize=1000000, includetrans=False, chroms=[]):
# check if M... | ded.append((chroms[j],chroms[i]))
if num_procs == 1:
node_needed | = needed
else:
worker_size = int(ceil(len(needed) / float(num_procs)))
for i in range(1, num_procs):
comm.send(needed[(worker_size * (i - 1)):(worker_size * i)], dest=i, tag=11)
node_needed = needed[(worker_size * (num_procs - 1)):]
else:
node_nee... |
tensorflow/tensorflow | tensorflow/python/keras/legacy_tf_layers/pooling_test.py | Python | apache-2.0 | 8,477 | 0.003303 | # Copyright 2015 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... | (images)
self.assertListEqual(output.get_shape().as_list(),
[5, channels, width // 2])
def testCreateMaxPooling3D(self):
depth, height, | width = 6, 7, 9
images = random_ops.random_uniform((5, depth, height, width, 4))
layer = pooling_layers.MaxPooling3D([2, 2, 2], strides=2)
output = layer.apply(images)
self.assertListEqual(output.get_shape().as_list(), [5, 3, 3, 4, 4])
def testCreateAveragePooling3D(self):
depth, height, width =... |
anisridhar/AudioShop | analysisClass.py | Python | mit | 5,377 | 0.040729 | import pyaudio
import wave
import sys
import time
import cv2
import numpy as np
import os
from Tkinter import *
from pydubtest import play, make_chunks
from pydub import AudioSegment
from threading import Thread
from vidAnalysis import vid2SoundFile
from eventBasedAnimationClass import EventBasedAnimationClass
import i... | es of the program
if self.control == "play":
self.recordingStart += int(round(1000*(time.time() - startTi | me)))
stream.stop_stream()
stream.close()
p.terminate()
return
stream.write(chunk._data)
self.recordingStart = 0
stream.stop_stream()
stream.close()
p.terminate()
def drawStatusLine(self,canvas):
(x0,y0) = (self.trackX,self.cy-self.lineHeight/2)
(x1,y1) = (self.trackX,self.cy+s... |
0rent/0rent | orentapp/migrations/0017_product_step.py | Python | agpl-3.0 | 466 | 0.002146 | # -*- cod | ing: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('orentapp', '0016_auto_20150422_1803'),
]
operations = [
migrations.AddField(
model_name='product',
name='step... | field=models.DecimalField(max_digits=8, null=True, decimal_places=2),
preserve_default=True,
),
]
|
jsj2008/kdegames | kajongg/src/predefined.py | Python | gpl-2.0 | 21,844 | 0.010438 | # -*- coding: utf-8 -*-
"""Copyright (C) 2009,2010 Wolfgang Rohdewald <wolfgang@rohdewald.de>
kajongg is free software you can redistribute it and/or modifys
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... | , doubles=1,
description=m18n('The dead wall is also called kong box: The last 16 tiles of the wall '
'used as source of replacement tiles')))
self.winnerRules.add(Rule('Last Tile is Last Tile of Wall',
'FIsLastTileFromWall||Olastsource=z', doubles=1,
... | nerRules.add(Rule('Last Tile is Last Tile of Wall Discarded',
'FIsLastTileFromWallDiscarded||Olastsource=Z', doubles=1,
description=m18n('Winner said Mah Jong by claiming the last tile taken from the living end of the '
'wall, discarded by another player')))
self.... |
ChristopherMacGown/pynpoint | tests/providers_unittest.py | Python | apache-2.0 | 564 | 0 | import unittest
import platform
|
from pynpoint import exc
import pynpoint.providers as providers
import pynpoint.providers.darwin
class ProvidersTestCase(unittest.TestCase):
| def setUp(self):
self.old_platform_system = platform.system
def tearDown(self):
platform.platform = self.old_platform_system
def test_load_providers(self):
def fake_platform_system(*args, **kwargs):
return "Darwin"
platform.system = fake_platform_system
... |
mdaus/coda-oss | modules/python/math.poly/source/generated/math_poly.py | Python | lgpl-3.0 | 53,586 | 0.004031 | # This file was automatically generated by SWIG (http://www.swig.org).
# Version 4.0.2
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
from sys import version_info as _swig_python_version_info
if _swig_python_version_info < (2, 7, 0):
raise Runtime... | ):
"""Recursive pickling method for SWIG-wrapped Poly1D."""
# Create a dictionary of parameters and values
state = {}
# Use swig_setmethods to get only data we can set later
state[' | coeffs'] = pickle.dumps(self.coeffs())
return state
|
kartiknagpal/urltoimg-heroku | server.py | Python | mit | 1,590 | 0.028302 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
from dependencies import web
from capture import urltoimg
from datetime import datetime
import base64, sys
#import xml.etree.ElementTree as ET
# tree = ET.parse('acess_key.xml')
# root = tree.getroot()
urls = (
'/', 'index',
'/urltoimg', 'get_screenshot'
)
app = web... | true':
getFile = file( 'static'+'/'+ | filename, 'rb' )
web.header('Content-type','application/octet-stream')
web.header('Content-transfer-encoding','base64')
base64data = base64.standard_b64encode(getFile.read())
return base64data
raise web.seeother('static'+'/'+filename)
class index:
def GET(self):
form = my_form()
return ... |
ryanho/ISParser | main.py | Python | bsd-3-clause | 6,603 | 0.003746 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import webapp2
import hinet
import seednet
import StringIO
import PyRSS2Gen
import urllib
import datetime
import hashlib
#from google.appengine.ext import ndb
from google.appengine.api import memcache
HTTP_DATE_FMT = '%a, %d %b %Y %H:%M:%S %Z'
def check_date_fmt(date):
... | rs['If-Modi | fied-Since'], IFMOD_DATE_FMT)
last_modified = datetime.datetime.strptime(mtime, HTTP_DATE_FMT)
if last_seen >= last_modified:
serve = False
if 'If-None-Match' in self.request.headers:
etags = [x.strip('" ') for x in self.request.headers['If-None-Match'].split(... |
askdaddy/PerfKitBenchmarker | perfkitbenchmarker/openstack/utils.py | Python | apache-2.0 | 6,432 | 0.001555 | # Copyright 2015 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | e password itself in $OS_PASSWORD | is also '
'supported.')
class KeystoneAuth(object):
"""
Usage example:
auth = KeystoneAuth(auth_url, auth_tenant, auth_user, auth_password)
token = auth.get_token()
tenant_id = auth.get_tenant_id()
token and tenant_id are required to use all OpenStack ... |
ksmit799/Toontown-Source | otp/login/PrivacyPolicyPanel.py | Python | mit | 5,598 | 0.006074 | from pandac.PandaModules import *
from otp.otpbase.OTPGlobals import *
from direct.gui.DirectGui import *
from MultiPageTextFrame import *
from direct.directnotify import DirectNotifyGlobal
from otp.otpbase import OTPLocalizer
from otp.otpgui import OTPDialog
class PrivacyPolicyTextPanel(getGlobalDialogClass()):
n... | elief=None, text=OTPLocalizer.PrivacyPolicyText_Intro, text_align=TextNode.ALeft, text_wordwrap=28, text_scale=0.09, text_pos=(-0.82, 1.0), textMayChange=0)
textScale = 0.05
buttonF | rame = DirectFrame(self, pos=(0.0, 0.1, 0.0), scale=1.4, relief=None)
DirectButton(buttonFrame, image=moreButtonImage, image_scale=(1.75, 1.0, 1.0), relief=None, text=OTPLocalizer.ActivateChatPrivacyPolicy_Button1A, text_scale=textScale, text_pos=(0, -0.01), textMayChange=0, pos=(-0.45, 0.0, 0.4), command=self.... |
tdlong/YeastRobot | UserPrograms/Sexual_Mating2Treatment_4.py | Python | gpl-3.0 | 1,127 | 0.030169 | import sys
# where RobotControl.py, etc lives
sys.path.append('/home/pi/Desktop/ADL/YeastRobot/PythonLibrary')
from RobotControl import *
#################################
### Define Deck Layout
#################################
deck="""\
DW24P DW24P DW24P DW24P SW24P SW24P SW24P SW24P
DW24P DW24P DW24P D... | TipPosition)
# initial mix
position(row,col)
mi | x(330,97,100,5)
# from DW24 to SW24
position(row,col)
aspirate(140, depth=98, speed=50, mix=0)
position(row,col+4)
dispense(140, depth=90, speed=50)
disposeTips()
position(0,0)
ShutDownRobot()
quit()
|
happykhan/igor | tests/test_advanced.py | Python | gpl-3.0 | 243 | 0 | # -* | - coding: utf-8 -*-
from .context import igor
import unittest
class AdvancedTestSuite(unittest.TestCase):
"""Advanced test cases."""
def test_thoughts(self):
igor.hmm()
if __name__ == '__main__':
unittes | t.main()
|
rs028/mcm-facsimile | facsimile_check.py | Python | gpl-3.0 | 4,674 | 0 | # #################################################################### #
# #
# FACSIMILE CHECK #
# #
# Script to check a FACSIMIL... | tabs instead of spaces :
: - lines longer than 72 characters :
: - variables longer than 10 characters :
:.....................................................:
"""
# input file (script argument or enter manually)
if sys.argv[1:]:
fname = sys.argv[1]
else:... | = open(fname, "r")
# set maximum length of lines
print "\n-> maximum number of characters per line [default=72]:"
llimit = raw_input("-> ")
if llimit == "":
llimit = 73
else:
llimit = int(llimit)
# output file
fout = open("facsimile_check.out", "w")
# read input file into string
facstring = fin.read()
# in... |
imakin/pysar-payments | pysar_payments/cybersource/forms.py | Python | bsd-3-clause | 2,581 | 0 | from __future__ import unicode_literals
from uuid import uuid4
from django import forms
from django.template.loader import render_to_string
from django.utils.translation import ugettext as _
from .. import PaymentError
from ..forms import CreditCardPaymentFormWithName
class FingerprintWidget(forms.HiddenInput):
... | f.provider.fingerprint_url)
def clean(self):
cleaned_data = super(PaymentForm, self).clean()
if not self.errors:
if self.provider.org_id:
fingerprint = cleaned_data['fingerprint']
self.payment.attrs.fingerprint_session_id = fingerprint
if not ... | charge(self.payment, cleaned_data)
except PaymentError as e:
self._errors['__all__'] = self.error_class([e.args[0]])
else:
msg = _('This payment has already been processed.')
self._errors['__all__'] = self.error_class([msg])
return ... |
cloudbase/maas | src/maastesting/tests/test_testcase.py | Python | agpl-3.0 | 2,071 | 0.00338 | # Copyright 2012, 2013 Canonical Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
"""Tests for `MAASTestCase`."""
from __future__ import (
absolute_import,
print_function,
unicode_literals,
)
str = None
__metaclass__ = type
__all__ = []
... | elf, attribu | te_name)
self.assertIs(getattr(self, attribute_name), attribute)
self.assertIsInstance(attribute, MagicMock)
|
0--key/lib | portfolio/Python/scrapy/myotcstore/drugstore.py | Python | apache-2.0 | 3,135 | 0.005423 | import re
import os
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from scrapy.http import Request, HtmlResponse
from scrapy.utils.response import get_base_url
from scrapy.utils.url import urljoin_rfc
from urllib import urlencode
import csv
from product_spiders.items import Produc... | f.parse_product)
def parse_product(self, r | esponse):
if not isinstance(response, HtmlResponse):
return
hxs = HtmlXPathSelector(response)
# pages
next_page = hxs.select(u'//div[@style="float:left;padding-right:8px;"]/a[child::img]/@href').extract()
if next_page:
next_page = urljoin_rfc(get_base_ur... |
mvo5/snapcraft | tests/unit/plugins/test_dotnet.py | Python | gpl-3.0 | 10,579 | 0.000756 | # -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright (C) 2017-2018 Canonical Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in ... | oject,
)
self.assertThat(error.architecture, Equals("non-amd64"))
def test_pull_sdk(self):
plugin = dotnet.DotNetPlugin("test-part", self.options, self.project)
with mock.patch.object(sources.Tar, "download", return_value="test-sdk.tar"):
plugin.pull()
self.... | join("parts", "test-part", "dotnet", "sdk", "test-sdk"),
FileExists(),
)
def test_clean_pull_removes_dotnet_dir(self):
dotnet_dir = os.path.join("parts", "test-part", "dotnet", "sdk")
os.makedirs(dotnet_dir)
plugin = dotnet.DotNetPlugin("test-part", self.options, self.pr... |
andrewgleave/OpenElm | web/openelm/settings.py | Python | mit | 6,211 | 0.001771 | import os
from celery.schedules import crontab
import djcelery
__copyright__ = "Copyright 2011 Red Robot Studios Ltd."
__license__ = "GPL v3.0 http://www.gnu.org/licenses/gpl.html"
djcelery.setup_loader()
DEBUG = False
TEMPLATE_DEBUG = DEBUG
ADMINS = (
('Panic Stations', 'panic@redrobotstudios.com'),
)
MAN... | p://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize yo | ur logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'mail_admins': {
'level': 'ERROR',
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request':{
'handlers': ['mail_ad... |
jayshonzs/ESL | SupervisedBasic/regression_classify.py | Python | mit | 1,587 | 0.012602 | '''
Created on 2014-4-29
@author: xiajie
'''
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
def loaddata():
data1 = np.genfromtxt('sdata1.txt')
data2 = np.genfromtxt('sdata2.txt')
return data1, data2
def cookdata(data1, data2):
X = np.concatenate((data1, data2), axis... | if res >= 0.5:
clss = 1
z.append(clss)
result = np.array(z).reshape(xx1.shape)
plt.contourf(xx1, xx2, result, cmap=mycm)
plt.scatter(X[:,1], X[:,2], s=30, c=Y, cmap=mycm)
plt.show()
if __name__ == '__main__':
data1 | , data2 = loaddata()
X, Y = cookdata(data1, data2)
#print X
#print Y
beta = ls(X, Y)
print beta
drawclass(X, Y, beta, 200) |
muslih/alfanous | src/alfanous-django/wui/templatetags/kwacros.py | Python | agpl-3.0 | 6,082 | 0.002466 | #
# templatetags/kwacros.py - Support for macros in Djan | go templates
#
# Based on snippet by
# Author: Michal Ludvig <michal@logix.cz>
# http://www.logix.cz/michal
#
# modified for args and kwargs by Skylar Saveland http://skyl.org
#
"""
Usage example:
0) Save this file as <yourapp>/templatetags/kwacros.py
1) In your template load the library:
{% load kwacro... | args and a kwarg.
All will be optional.
{% kwacro test2args1kwarg arg1 arg2 baz="Default baz" %}
{% firstof arg1 "default arg1" %}
{% if arg2 %}{{ arg2 }}{% else %}default arg2{% endif %}
{{ baz }}
{% endkwacro %}
3) Use the macro with a string parameters or context variables::
{% usekwacr... |
crateio/carrier | carrier/core.py | Python | bsd-2-clause | 2,194 | 0.002279 | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import logging
import logging.config
import os
import time
import forklift
import redis
import requests
import xmlrpc2.client
from apscheduler.scheduler import Scheduler
from .config import Config, default... | onfig["LOGGING"])
store = redis.StrictRedis(**dict([(k.lower(), v) for k, v in self.config["REDIS"].items()]))
wsession = requests.session(
auth=(
self.config["WAREHOUSE_AUTH"]["USERNAME"],
| self.config["WAREHOUSE_AUTH"]["PASSWORD"],
),
headers={"User-Agent": user_agent()},
)
warehouse = forklift.Forklift(session=wsession)
warehouse.url = self.config["WAREHOUSE_URI"]
psession = requests.session(verify=... |
nextgen-astrodata/DAL | cmake/FindNumpy.py | Python | lgpl-3.0 | 154 | 0.025974 | import numpy
try:
| print(numpy.get_include())
except AttributeError:
# depricated, but used in old numpy versions
print(numpy.get_numpy_ | include())
|
Widukind/widukind-web | widukind_web/admin.py | Python | agpl-3.0 | 9,502 | 0.00884 | # -*- coding: utf-8 -*-
from flask import Blueprint, current_app, request, render_template, abort, url_for, redirect
from pymongo import DESCENDING
import arrow
from widukind_web import constants
from widukind_web.extensions import auth
from widukind_web.extensions import cache
from widukind_web import queries
from ... | required
def change_status_provider(slug):
query = {"slug": slug}
provider = queries.col_providers().find_one(query)
if not provider:
abort(404)
query_update = {}
if provider["enable"]: |
query_update["enable"] = False
else:
query_update["enable"] = True
queries.col_providers().find_one_and_update(query, {"$set": query_update})
datasets_query = {"provider_name": provider["name"]}
queries.col_datasets().update_many(datasets_query, {"$set": query_update})
... |
waartaa/ircb | setup.py | Python | mit | 973 | 0.001028 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup, find_packages
except:
from distutils.core import setup, find_packages
with open('requirements.txt') as f:
requirements = f.read().splitlines()
setup(
name='ircb',
version='0.3.0',
description='A IRC bouncer',
... | ckages(),
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: POSIX :: Linux',
'Programming Lang | uage :: Python :: 3.5',
'Topic :: Internet :: WWW/HTTP :: WSGI :: Application',
],
entry_points={
'console_scripts': ['ircb=ircb.cli.main:cli']
}
)
|
ManiacalLabs/BiblioPixelAnimations | BiblioPixelAnimations/strip/Searchlights.py | Python | mit | 2,221 | 0.001801 | from bibliopixel.colors import COLORS as _COLORS
from bibliopixel.colors.arithmetic import color_scale
from bibliopixel.animation.strip import Strip
import random
class Searchlights(Strip):
"""Three search lights sweeping at different speeds"""
COLORS = [_COLORS.MediumSeaGreen, _COLORS.MediumPurple,
... | # average the colors together so they blend
self._ledcolors[self._currentpos[i]] = list(map(lambda x, y: (x + y) // 2, color, self._ledcolors[self._currentpos[i]]))
for j in range(1, self._tail):
if self._currentpos[i] - j >= 0:
self._ledcolors[self._cur... | currentpos[i] - j], color_scale(color, 255 - (self._fadeAmt * j))))
if self._currentpos[i] + j < self._size:
self._ledcolors[self._currentpos[i] + j] = list(map(lambda x, y: (x + y) // 2, self._ledcolors[self._currentpos[i] + j], color_scale(color, 255 - (self._fadeAmt * j))))
... |
blackball/an-test6 | net/views/album.py | Python | gpl-2.0 | 4,432 | 0.006092 | import shutil
import os, errno
import hashlib
import tempfile
import math
import urllib
import urllib2
from django.http import HttpResponse, HttpResponseRedirect, HttpResponseBadRequest, QueryDict
from django.shortcuts import render_to_response, get_object_or_404, redirect, render
from django.template import Context, ... | _object_or_404(Album, pk=album_id)
redirect_url = req.GET.get('next','/')
if album.user == req.user:
album.delete()
messages.success(req, "A | lbum '%s' successfully deleted." % album.title)
return HttpResponseRedirect(redirect_url)
else:
# render_to_response a "you don't have permission" view
pass
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.