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 |
|---|---|---|---|---|---|---|---|---|
akimo12345/AndroidViewClient | src/com/dtmilano/android/viewclient.py | Python | apache-2.0 | 183,943 | 0.007245 | # -*- coding: utf-8 -*-
'''
Copyright (C) 2012-2015 Diego Torres Milano
Created on Feb 2, 2012
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
Un... | he C{attr},C{value} pairs '''
self.device = device
''' The AdbClient '''
self.children = []
''' The children of this View '''
self.parent = None
''' The parent of this View '''
self.windows = {}
self.currentFocus = None
''' The current focus '''
... | self.build = {}
''' Build properties '''
self.version = version
|
instituteofdesign/django-lms | apps/springboard/views.py | Python | bsd-3-clause | 1,051 | 0.005709 | from django.conf import settings
from django.db.models import Q
from libs.django_utils import render_to_response
from django.views.generic import ListView
from springboard.models import IntranetApplication
from django.contrib.auth.decorators import login_required
from alerts.models import Alert
class SpringBoard(List... | me = "springboard/springboard.html"
def get_queryset(self):
# Check the groups the user is allowed to see
return IntranetApplication.objects.filter(Q(groups__in = self.request.user.groups.all()) | Q(groups__isnull=True)).distinct()
def get_context_data(self, **kwargs):
# Temporary mes... | ta(**kwargs)
# Get all the alerts for the user
context['alerts'] = Alert.objects.filter(sent_to = self.request.user)
return context
|
saurabh6790/google_integration | google_integration/google_connect/doctype/google_app_setup/google_app_setup.py | Python | mit | 280 | 0.007143 | # -*- coding: utf-8 -*-
# Copyright (c) 2015, Frappe Techn | ologies 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 GoogleAppSetup | (Document):
pass
|
brajput24/fabric-bolt | fabric_bolt/utils/runner.py | Python | mit | 1,251 | 0.000799 | from logan.runner import run_app, configure_app
import sys
import base64
import os
KEY_LENGTH = 40
CONFIG_TEMPLATE = """
from fabric_bolt.core.settings.base import *
CONF_ROOT = os.path.dirname(__file__)
DATA | BASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(CONF_ROOT, 'fabric-bolt.db'),
'USER': 'sqlite3',
'PASSWORD': '',
'HOST': '',
'PORT': '',
}
}
SECRET_KEY = %(default_key)r
"""
def generate_settings():
output = CONFIG_TEMP... | project='fabric-bolt',
default_config_path='~/.fabric-bolt/settings.py',
default_settings='fabric_bolt.core.settings.base',
settings_initializer=generate_settings,
settings_envvar='FABRIC_BOLT_CONF',
)
def main(progname=sys.argv[0]):
run_app(
project='fabric-bolt... |
zetaops/SpiffWorkflow | doc/conf.py | Python | lgpl-3.0 | 5,907 | 0.003894 | # -*- coding: utf-8 -*-
from __future__ import division
# -*- coding: utf-8 -*-
#
# Sphinx documentation build configuration file, created by
# sphinx-quickstart.py on Sat Mar 8 21:47:50 2008.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# The contents of this file are pickled, ... | , target name, title, author, document class [howto/manual]).
latex_documents = [('contents', 'sphinx.tex', 'Sphinx Documentation',
'Georg Brandl', 'manual', 1)]
latex_logo = '_static/sphinx.png'
#latex_use_parts = True
# Additional stuff for the LaTeX preamble.
latex_elements = {
'fontpkg': ... | # Documents to append as an appendix to all manuals.
#latex_appendices = []
# Extension interface
# -------------------
from sphinx import addnodes
dir_sig_re = re.compile(r'\.\. ([^:]+)::(.*)$')
def parse_directive(env, sig, signode):
if not sig.startswith('.'):
dec_sig = '.. %s::' % sig
signo... |
trgomes/estrutura-de-dados | Exercicios/5-balanceamento.py | Python | mit | 3,019 | 0.002659 | # -*- coding: utf-8 -*-
import unittest
class PilhaVaziaErro(Exception):
pass
class Pilha():
def __init__(self):
self.lista = []
def topo(self):
if self.lista:
return self.lista[-1]
raise PilhaVaziaErro()
def vazia(self):
return not bool(self.lista)
... | self):
self.assertFalse(esta_balanceada('('))
| def test_chave_nao_aberta(self):
self.assertFalse(esta_balanceada('}{'))
def test_colchete_nao_aberto(self):
self.assertFalse(esta_balanceada(']['))
def test_parentese_nao_aberto(self):
self.assertFalse(esta_balanceada(')('))
def test_falta_de_caracter_de_fechamento(self):
... |
njoyce/sockjs-gevent | setup.py | Python | mit | 2,151 | 0.00186 | import os
import sys
from setuptools import setup, find_packages
version = '0.3.3'
def get_package_manifest(filename):
packages = []
with open(filename) as package_file:
for line in package_file.readlines():
line = line.strip()
if not line:
continue
... | info[:2] < (2, 7):
packages.append('unittest2')
return packages
def read(f):
with open(os.path.join(os.path.dirname(__file__), f)) as f:
return f.read().strip()
setup(
name='sockjs-gevent',
version=version,
description=('gevent base sockjs server'),
long_description='\n\n'.j... | g Language :: Python",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: Implementation :: CPython",
"Topic :: Internet :: WWW/HTTP",
'Topic :: Internet :: WWW/HTTP :: WSGI'
],
author='Nick Joyce',
aut... |
vberthiaume/digitalFilters | ch2/freqplot.py | Python | gpl-3.0 | 469 | 0.01919 | ################################ FIG J.2 P.683 ################################
import matplotlib.pyplot as plt
def freqplot(fdata, ydata, symbol='', ttl='', xlab='Frequency (Hz)', ylab | =''):
""" FREQPLOT - Plot a function of frequency. See myplot for more features."""
#not sure what | this means
#if nargin<2, fdata=0:length(ydata)-1; end
plt.plot(fdata, ydata, symbol);
plt.grid()
plt.title(ttl)
plt.ylabel(ylab)
plt.xlabel(xlab); |
baida21/py-flask-signup | tests/application-tests.py | Python | apache-2.0 | 1,642 | 0.004263 | # Copyright 2013. Amazon Web Services, 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 a... | """ Test that we can get a signup form """
self.assertTrue(1)
def test_get_user(self):
""" Test that we can get a user context """
self.assertTrue(1)
def test_login(self):
| """ Test that we can authenticate as a user """
self.assertTrue(1)
if __name__ == '__main__':
unittest.main()
|
hepochen/hoedown_misaka | docs/conf.py | Python | mit | 9,639 | 0.005602 | # -*- coding: utf-8 -*-
#
# Misaka documentation build configuration file, created by
# sphinx-quickstart on Sun Jul 12 11:37:42 2015.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# Al... | sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this direct | ory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typ... |
wingtk/gvsbuild | gvsbuild/projects/graphene.py | Python | gpl-2.0 | 1,663 | 0.001203 | # Copyright (C) 2016 - Yevgen Muntyan
# Copyright (C) 2016 - Ignacio Casal Quinteiro
# Copyright (C) 2016 - Arnavion
#
# 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 t... | ed a copy of the GNU General Public License
# along with this program; if not, see <http://www.gn | u.org/licenses/>.
from gvsbuild.utils.base_builders import Meson
from gvsbuild.utils.base_expanders import Tarball
from gvsbuild.utils.base_project import project_add
@project_add
class Graphene(Tarball, Meson):
def __init__(self):
Meson.__init__(
self,
"graphene",
arc... |
Shadybloom/synch-profiler | wordfreq-morph.py | Python | mit | 7,594 | 0.006508 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Скрипт извлекает слова из текстового файла и сортирует их по частоте.
# С помощью модуля pymorphy2 можно привести слова к начальной форме (единственное число, именительный падеж).
# Нужен pymorphy2 и русскоязычный словарь для него!
# pip install --user pymorphy2
# Прим... | def metadict_path (metadict_dir):
"""Возвращает абсолютный путь к каталогу словарей."""
# Получаем абсолютный путь к каталогу скрипта:
script_path = os.path.dirname(os.path.abspath(__file__))
# Добавляем к пути каталог словарей:
metadict_path = script_path + '/' + metadict_dir
return metadict_pa... | звращает список путей ко всем файлам каталога, включая подкаталоги."""
path_f = []
for d, dirs, files in os.walk(directory):
for f in files:
# Формирование адреса:
path = os.path.join(d,f)
# Добавление адреса в список:
path_f.append(path)
... |
pitbulk/python3-saml | tests/src/OneLogin/saml2_tests/utils_test.py | Python | bsd-3-clause | 40,950 | 0.004274 | # -*- coding: utf-8 -*-
# Copyright (c) 2014, OneLogin, Inc.
# All rights reserved.
from base64 import b64decode
import json
from lxml import etree
from os.path import dirname, join, exists
import unittest
from xml.dom.minidom import parseString
from onelogin.saml2 import compat
from onelogin.saml2.constants import ... | gV6VpTwez4dkpU/xCHKoReedAEJhXucTNGpiIqu+TDgIz9aRbrgnUKkS1s06UJhcDRTl/+pCSRRt/CA2VAkBkPw4pn1hNwvK1S8t9OJQD+5xcKjZcvIFtKoqonAi7GUGL3OQSDVFw4q1K2iSk40aM+06wJ/WfeR+3z2ISrGBxAkAJ20YiF1QpcQlASbHNCl0vs7uKOlDyUAerR3mjFPf6e6kzQdi815MTZGIPxK3vWmMlPymgvgYPYTO1A4t5myulAkEA1QioAWcJoO26qhUlFRBCR8BMJoVPImV7ndVHE7usHdJvP7V2P9RyuRcMCTV... | gin_Saml2_Utils.format_private_key(key_3, True)
self.assertIn('-----BEGIN RSA PRIVATE KEY-----', formated_key_3)
self.assertIn('-----END RSA PRIVATE KEY-----', formated_key_3)
self.assertEqual(len(formated_key_3), 924)
formated_key_3 = OneLogin_Saml2_Utils.format_private_key(key_3, Fals... |
googleads/google-ads-python | google/ads/googleads/v10/enums/types/payment_mode.py | Python | apache-2.0 | 1,172 | 0.000853 | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import proto # type: ignore
__protobuf__ = proto.module(
package="google.ads.googleads.v10.enums",
marshal="google.ads.googl | eads.v10",
manifest={"PaymentModeEnum",},
)
class PaymentModeEnum(proto.Message):
r"""Container for enum describing possible payment modes.
"""
class PaymentMode(proto.Enum):
r"""Enum describing possible payment modes."""
UNSPECIFIED = 0
UNKNOWN = 1
CLICKS = 4
... |
flumotion-mirror/flumotion | flumotion/component/misc/httpserver/serverstats.py | Python | lgpl-2.1 | 7,784 | 0 | # -*- Mode: Python; test-case-name: -*-
# vi:si:et:sw=4:sts=4:ts=4
# Flumotion - a streaming media server
# Copyright (C) 2004,2005,2006,2007,2008,2009 Fluendo, S.L.
# Copyright (C) 2010,2011 Flumotion Services, S.A.
# All rights reserved.
#
# This file may be distributed and/or modified under the terms of
# the GNU L... | self.requestRatePeakTime = now
# update statistic keys
self._set("request-rate-peak", newReqRate)
self._set("request-rate-peak-time", now)
# Update bitrate peak
if newBitrate > self.bitratePeak:
self.bitratePeak = newBitrate
self | .bitratePeakTime = now
# update statistic keys
self._set("bitrate-peak", newBitrate)
self._set("bitrate-peak-time", now)
# Update bytes read statistic key too
self._set("total-bytes-sent", self.totalBytesSent)
self._lastRequestCount = self.totalRequestCount
... |
gotlium/django-geoip-redis | geoip/geo.py | Python | gpl-3.0 | 1,723 | 0 | # -*- coding: utf-8 -*-
__all__ = ["inet_aton", "record_by_ip", "record_by_request", "get_ip",
"record_by_ip_as_dict", "record_by_request_as_dict"]
import struct
import socket
from geoip.defaults import BACKEND, REDIS_TYPE
from geoip.redis_wrapper import RedisClient
from geoip.models import Range
_RECOR... | d_ip', '-start_ip')[:1][0]
if REDIS_TYPE == 'pk':
return map(lambda k: str(getattr(obj, | k).pk), _RECORDS_KEYS)
return map(lambda k: str(getattr(obj, k)), _RECORDS_KEYS)
def inet_aton(ip):
return struct.unpack('!L', socket.inet_aton(ip))[0]
def get_ip(request):
ip = request.META['REMOTE_ADDR']
if 'HTTP_X_FORWARDED_FOR' in request.META:
ip = request.META['HTTP_X_FORWARDED_FOR'].... |
rgommers/statsmodels | statsmodels/base/tests/test_generic_methods.py | Python | bsd-3-clause | 12,158 | 0.003208 | # -*- coding: utf-8 -*-
"""Tests that use cross-checks for generic methods
Should be easy to check consistency across models
Does not cover tsa
Initial cases copied from test_shrink_pickle
Created on Wed Oct 30 14:01:27 2013
Author: Josef Perktold
"""
from statsmodels.compat.python import range
import numpy as np
i... | # squeeze to make 1d for single regressor test case
p_exog = np.squeeze(np.asarray(res.m | odel.exog[:2]))
# ignore wrapper for isinstance check
from statsmodels.genmod.generalized_linear_model import GLMResults
from statsmodels.discrete.discrete_model import DiscreteResults
# FIXME: work around GEE has no wrapper
if hasattr(self.results, '_results'):
res... |
leighpauls/k2cro4 | third_party/webpagereplay/replay.py | Python | bsd-3-clause | 20,951 | 0.011503 | #!/usr/bin/env python
# Copyright 2010 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... | cc-broadband-data
_NET_CONFIGS = (
# key --down --up --delay_ms
('dsl', ('1536Kbit/s', '384Kbit/s', '50')),
('cable', ( '5Mbit/s', '1Mbit/s', '28')),
('fios', ( '20Mbit/s', '5Mbit/s', '4')),
)
NET_CHOICES = [key for key, values in _NET_CONFIG... | ser = parser
self._nondefaults = set([
name for name, value in parser.defaults.items()
if getattr(options, name) != value])
self._CheckConflicts()
self._MassageValues()
def _CheckConflicts(self):
"""Give an error if mutually exclusive options are used."""
for option, bad_options i... |
KyleTen2/ReFiSys | FlSys.py | Python | mit | 13,483 | 0.011941 | from RemoteFlSys import *
class gfeReader:#GetFilesExts Reader
def __init__(self, Reader, Params, AddInfo, OneTime = True):
self.Params = Params
self.Reader = Reader
self.AddInfo = AddInfo
self.Once = OneTime
class fsDirInf:
def __init__(self, SuperDir, Name, DictFlInfs, ... | llDrv.has_key(DrvName): return False
return FileDrv.AllDrv | [DrvName].IsFile(Path)
def GetFilesExts(Path, LstExt, Invert = False, RtnBegDots = False):
DrvName, Path = EvalPath(Path)
return FileDrv.AllDrv[DrvName].GetFilesExts(Path, LstExt, Invert, RtnBegDots)
def GetInfGfe(Cmd, Path, LstExts = None, BegDots = False):#Warning BegDots functionality is in question
... |
snowflakedb/spark-snowflake | legacy/dev/merge_pr.py | Python | apache-2.0 | 18,840 | 0.004299 | #!/usr/bin/env python
#
# 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 "Li... | except urllib2.HTTPError as e:
if "X-RateLimit-Remaining" in e.headers and e.headers["X-RateLimit-Remaining"] == '0':
print "Exceeded the GitHub API rate limit; see the instructions in " + \
"dev/merge_spark_pr.py to configur | e an OAuth token for making authenticated " + \
"GitHub requests."
else:
print "Unable to fetch URL, exiting: %s" % url
sys.exit(-1)
def fail(msg):
print msg
clean_up()
sys.exit(-1)
def run_cmd(cmd):
print cmd
if isinstance(cmd, list):
return... |
Codewars/codewars-runner | frameworks/python/codewars.py | Python | mit | 2,284 | 0.004816 | import unittest
import traceback
from time import perf_counter
class CodewarsTestRunner(object):
def __init__(self): pass
def run(self, test):
r = CodewarsTestResult()
s = perf_counter()
print("\n<DESCRIBE::>Tests")
try:
test(r)
finally:
pass
... | = True
class CodewarsTestResul | t(unittest.TestResult):
def __init__(self):
super().__init__()
self.start = 0.0
def startTest(self, test):
print("\n<IT::>" + test._testMethodName)
super().startTest(test)
self.start = perf_counter()
def stopTest(self, test):
print("\n<COMPLETEDIN::>{:.4f}".... |
todesschaf/pgl | pgl.py | Python | gpl-2.0 | 4,786 | 0.002925 | # Copyright (c) 2011 Nick Hurley <hurley at todesschaf dot org>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of version 2 of the GNU General Public License as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,... | -exes live
gitexec = subprocess.Popen(['git', '--exec-path'], stdout=subprocess.PIPE,
stderr=devnull)
config['GIT_LIBEXEC'] = gitexec.stdout.readlines()[0].strip()
gitexec.wait()
| # Figure out the git dir in our repo, if applicable
gitdir = subprocess.Popen(['git', 'rev-parse', '--git-dir'],
stdout=subprocess.PIPE, stderr=devnull)
lines = gitdir.stdout.readlines()
if gitdir.wait() == 0:
config['GIT_DIR'] = lines[0].strip()
# Figure out the top level of our repo... |
JoshAshby/Fla.gr | app/models/couch/user/userModel.py | Python | mit | 3,412 | 0.001758 | #!/usr/bin/env python
"""
fla.gr user model
Given a userID or a username or a email, return the users couchc.database ORM
http://xkcd.com/353/
Josh Ashby
2013
http://joshashby.com
joshuaashby@joshashby.com
"""
from couchdb.mapping import Document, TextField, DateTimeField, \
BooleanField, IntegerField
impor... | od
def new(cls, username, password):
"""
Make a new user, checking for username conflicts. If no conflicts are
found the password is encryp | ted with bcrypt and the resulting `userORM` returned.
:param username: The username that should be used for the new user
:param password: The plain text password that should be used for the password.
:return: `userORM` if the username is available,
"""
if password == "":
... |
rsk-mind/rsk-mind-framework | test/setting.py | Python | mit | 927 | 0.010787 | from rsk_mind.datasource import *
from rsk_mind.classifier import *
from transformer import CustomTransformer
PR | OJECT_NAME = 'test'
DATASOURCE= {
'IN' : {
'class' : CSVDataSource,
'params' : ('in.csv', )
},
'OUT' : {
'class' : CSVDataSource,
'params' : ('out.csv', )
}
| }
ANALYSIS = {
'persist': True,
'out': 'info.json'
}
TRANSFORMER = CustomTransformer
TRAINING = {
'algorithms' : [
{
'classifier': XGBoostClassifier,
'parameters' : {
'bst:max_depth': 7,
'bst:eta': 0.3,
'bst:subsample': 0.5,
... |
jonyroda97/redbot-amigosprovaveis | lib/matplotlib/tests/test_transforms.py | Python | gpl-3.0 | 24,823 | 0.000081 | from __future__ import (absolute_import, division, print_function,
unicode_literals)
from six.moves import zip
import unittest
import numpy as np
from numpy.testing import (assert_allclose, assert_almost_equal,
assert_array_equal, assert_array_almost_equal)
import p... | Data)
ax.scatter(np.linspace(0, 10), np.linspace(10, 0),
transform=times10 + ax.transData)
x = np.linspace(8, 10, 20)
y = np.linspace(1, 5, 20)
u = 2*np.sin(x) + np.cos(y[:, np.newaxis])
v = np.sin(x) - np.cos(y[:, np.newaxis]) |
df = 25. / 30. # Compatibility factor for old test image
ax.streamplot(x, y, u, v, transform=times10 + ax.transData,
density=(df, df), linewidth=u**2 + v**2)
# reduce the vector data down a bit for barb and quiver plotting
x, y = x[::3], y[::3]
u, v = u[::3, ::3], v[::3, ::3]
... |
noikiy/mitmproxy | examples/dns_spoofing.py | Python | mit | 1,652 | 0.004843 | """
This inline scripts makes it possible to use mitmproxy in scenarios where IP spoofing has been used to redirect
connections to mitmproxy. The way this works is that we rely on either the | TLS Server Name Indication (SNI) or the
Host header of the HTTP request.
Of course, this is not foolproof - if an HTTPS connection comes without SNI, we don't
know the actual target and cannot construct a certificate that looks valid.
Similarly, if there's no Host header or a spoofed Host header, we're out of luck as w... | roxy
-p 80
-R http://example.com/ // Used as the target location if no Host header is present
mitmproxy
-p 443
-R https://example.com/ // Used as the target locaction if neither SNI nor host header are present.
mitmproxy will always connect to the default location first, so it must... |
dimagi/commcare-hq | corehq/apps/linked_domain/views.py | Python | bsd-3-clause | 22,021 | 0.002089 | from datetime import datetime
from django.contrib import messages
from django.http import Http404, HttpResponseRedirect, JsonResponse
from django.urls import reverse
from django.utils.decorators import method_decorator
from django.utils.translation import ugettext, ugettext_lazy
from django.views import View
from cou... |
from corehq.apps.linked_domain.remote_accessors import get_remote_linkable_ucr
from corehq.apps.linked_domain.tasks import (
pull_missing_multime | dia_for_app_and_notify_task,
push_models,
)
from corehq.apps.linked_domain.ucr import create_linked_ucr
from corehq.apps.linked_domain.updates import update_model_type
from corehq.apps.linked_domain.util import (
convert_app_for_remote_linking,
pull_missing_multimedia_for_app,
server_to_user_time,
u... |
village-people/flying-pig | malmopy/visualization/visualizer.py | Python | mit | 4,199 | 0.00381 | # Copyright (c) 2017 Microsoft Corporation.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
# documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publis... | isualizer(object): |
""" Provide a unified interface for observing the training progress """
def add_entry(self, index, key, result, **kwargs):
raise NotImplementedError()
def __lshift__(self, other):
if isinstance(other, tuple):
if len(other) >= 3:
self.add_entry(other[0], str(oth... |
tensorflow/privacy | tensorflow_privacy/privacy/optimizers/dp_optimizer.py | Python | apache-2.0 | 15,920 | 0.005339 | # Copyright 2020, The TensorFlow 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 applicable law or agreed t... | t replacement.
if self._num_microbatches is None:
self._num_microbatches = tf.shape(input=loss)[0]
microbatches_losses = tf.reshape(loss, [self._num_microbatches, -1]) |
sample_params = (
self._dp_sum_query.derive_sample_params(self._global_state))
def process_microbatch(i, sample_state):
"""Process one microbatch (record) with privacy helper."""
self_super = super(DPOptimizerClass, self)
mean_loss = tf.reduce_mean(
... |
Castronova/EMIT | gui/views/WofSitesView.py | Python | gpl-2.0 | 3,111 | 0.002893 | import wx
from gui.controller.CustomListCtrl import CustomListCtrl
from gui.controller.PlotCtrl import PlotCtrl
class WofSitesView(wx.Frame):
def __init__(self, parent, title, table_columns):
wx.Frame.__init__(self, parent=parent, id=-1, title=title, pos=wx.DefaultPosition, size=(680, 700),
... | _BOX)
self.start_date = wx.DateTime_Now() - 7 * wx.DateSpan_Day()
| self.end_date = wx.DateTime_Now()
self.parent = parent
self._data = None
panel = wx.Panel(self)
top_panel = wx.Panel(panel)
middle_panel = wx.Panel(panel, size=(-1, 30))
lower_panel = wx.Panel(panel)
hboxTopPanel = wx.BoxSizer(wx.HORIZONTAL)
self.p... |
ATSTI/administra | open_corretora/brokerage/wizard/end_contract.py | Python | gpl-2.0 | 1,064 | 0.005639 | #-*- coding: utf-8 -*-
from openerp.osv import fields, osv
class finance_contract_rachat(osv.osv_memory):
_name = "finance.contract.rachat"
_columns = { |
'date': fields.date('Date de rachat'),
'date_dem': fields.date('Date de la demande'),
'motif': fields.text('Motif'),
'memo': fields.text('Memo'),
'act_rachat': fields.boolean('Rachat'),
'act_res': fields.boolean('Resiliation'),
'contract_id': fields.many2one('fin... | r, uid, ids[0], context=context)
vals = {
'res_reason': obj.motif and obj.motif or False,
'res_memo': obj.memo and obj.memo or False,
'res_date': obj.date and obj.date or False,
'res_dated': obj.date_dem and obj.date_dem or False,
'res': obj.act_res,
... |
simonemurzilli/geonode | geonode/contrib/geosites/site_template/local_settings_template.py | Python | gpl-3.0 | 597 | 0 | # flake8: noqa
# -*- coding: utf-8 -*-
###############################################
# Geosite local settings
###############################################
import os
# Outside URL
SITEURL = 'http://$DOMAIN'
OGC_SERVER['default']['LOCATION'] = os.path. | join(GEOSERVER_URL, 'geoserver/')
OGC_SERVER['default']['PUBLIC_LOCATION'] = os.path.join(SITEURL, 'geoserver/')
# databases unique to site if not defined in site settings
"""
SITE_DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': | os.path.join(PROJECT_ROOT, '../development.db'),
},
}
"""
|
wathsalav/xos | xos/core/views/projects.py | Python | apache-2.0 | 382 | 0.007853 | from core.serializers import ProjectSerializer
from rest_framework import generics
from core.models import Project
class ProjectList(generics.ListCreateAPIView):
queryset = Project.objec | ts.all()
serializer_class = ProjectSerializer
class Pro | jectDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Project.objects.all()
serializer_class = ProjectSerializer
|
arielrossanigo/fades | fades/helpers.py | Python | gpl-3.0 | 7,161 | 0.001397 | # Copyright 2014-2015 Facundo Batista, Nicolás Demarchi
#
# 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 the hope that it will be useful, but
# WIT... | put to the log."""
logger = logging.getLogger('fades.exec')
| logger.debug("Executing external command: %r", cmd)
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
stdout = []
for line in p.stdout:
line = line[:-1].decode("utf8")
stdout.append(line)
logger.debug(STDOUT_LOG_PREFIX + line)
retcode = p.wait()
if... |
appuio/ansible-role-openshift-zabbix-monitoring | vendor/openshift-tools/ansible/inventory/aws/ec2.py | Python | apache-2.0 | 55,406 | 0.002978 | #!/usr/bin/env python2
'''
EC2 external inventory script
=================================
Generates inventory that Ansible can understand by making API request to
AWS EC2 using the Boto library.
NOTE: This script assumes Ansible is being executed where the environment
variables needed for Boto have already been set... | s_name
- ec2_eventsSe | t
- ec2_group_name
- ec2_hypervisor
- ec2_id
- ec2_image_id
- ec2_instanceState
- ec2_instance_type
- ec2_ipOwnerId
- ec2_ip_address
- ec2_item
- ec2_kernel
- ec2_key_name
- ec2_launch_time
- ec2_monitored
- ec2_monitoring
- ec2_networkInterfaceId
- ec2_ownerId
- ec2_persistent
- ec2_placement
- ec2_... |
Vvucinic/Wander | venv_2_7/lib/python2.7/site-packages/Django-1.9-py2.7.egg/django/contrib/gis/gdal/raster/source.py | Python | artistic-2.0 | 13,274 | 0.000904 | import json
import os
from ctypes import addressof, byref, c_double, c_void_p
from django.contrib.gis.gdal.base import GDALBase
from django.contrib.gis.gdal.driver import Driver
from django.contrib.gis.gdal.error import GDALException
from django.contrib.gis.gdal.prototypes import raster as capi
from django.contrib.gis... | data_values and pixel values. This function will be called
automaticall | y wherever it is needed.
"""
# Raise an Exception if the value is being changed in read mode.
if not self._write:
raise GDALException('Raster needs to be opened in write mode to change values.')
capi.flush_ds(self._ptr)
@property
def name(self):
"""
R... |
Yelp/yelp_clog | clog/scribe_net.py | Python | apache-2.0 | 8,613 | 0.001974 | # Copyright 2015 Yelp Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, so... | ed format" % (self.keytype, self.key)
class ScribeFile(object):
"""Base class for Scribe file objects. These represent a single log chunk,
and can be read or listed. Scribe File objects are equal if the combination of
their date, stream name, and aggregator are the same. This allows you to, for | example,
create a set of files from both s3 and a local cache without reading the same
chunk twice.
Important methods:
read: adds a file's contents to the stream ostream, transparently handling gzip'd data
Properties:
sort_key: A key to sort or compare with
size: The length of ... |
hellowebbooks/hellowebbooks-website | blog/urls.py | Python | mit | 237 | 0 | #! /usr/bin/env python
# -*- | coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2017-06-27 michael_yin
#
"""
"""
from django.conf import settings
from django.conf.urls import include, url
from django.core.urlresolvers im | port reverse
|
jdstemmler/jdstemmler.github.io | pelicanconf.py | Python | mit | 2,048 | 0.001953 | #!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
import os
import datetime
AUTHOR = u'Jayson Stemmler'
SITENAME = u'Jayson Stemmler'
SITEURL = ''
SITENAME = "Jayson Stemmler's Blog"
SITETITLE = 'Jayson Stemmler'
SITESUBTITLE = 'Research / Data Scientist'
SITEDESCRIPTION = ''
# SI... | cles']
TIMEZONE = 'America/Los_Angeles'
DEFAULT_LANG = u'en'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = None
CATEGORY_FEED_ATOM = None
TRANSLATION_FEED_ATOM = None
AUTHOR_FEED_ATOM = None
AUTHOR_FEED_RSS = None
DEFAULT_PAGINATION = 10
# Uncomment following line if you | want document-relative URLs when developing
#RELATIVE_URLS = True
STATIC_PATHS = ['images', 'extra/CNAME']
EXTRA_PATH_METADATA = {'extra/CNAME': {'path': 'CNAME'},}
ARTICLE_URL = 'posts/{date:%Y}/{date:%b}/{slug}'
ARTICLE_SAVE_AS = 'posts/{date:%Y}/{date:%b}/{slug}.html'
PAGE_URL = 'pages/{slug}'
PAGE_SAVE_AS = 'pag... |
pylayers/pylayers | pylayers/location/geometric/util/boxn.py | Python | mit | 27,884 | 0.029373 | # -*- coding:Utf-8 -*-
#####################################################################
#This file is part of RGPA.
#Foobar 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, ... | R[range(1,len(R),2)]=R[range(1,len(R),2)]+1
if self.ndim == 3:
RZ=np.repeat(range(0,dimm1*lbd,dim),dimm1)+(lbd/2)*range(0,dimm1,1)
# aller chercher dans self.bd
R2a=np.repeat(self.bd[range(0,lbd,2), | :],dimm1,axis=0)
R2b=np.repeat(self.bd[range(1,lbd,2),:],dimm1,axis=0)
# # X
# P[R,0]=R2a[:,0]#np.repeat(L.bd[range(0,lbd,2),0],4)
# P[R+2,0]=R2b[:,0]#np.repeat(L.bd[range(1,lbd,2),0],4)
# # Y
# P[np.sort(np.mod(R+3,4*lbd) |
matagus/django-jamendo | apps/jamendo/context_processors.py | Python | bsd-3-clause | 558 | 0.005376 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from datetime import date
from django | .conf import settings
def settings_context(request):
"""
Makes available a template var for some interesting var in settings.py
"""
try:
ITEMS_PER_PAGE = settings.ITEMS_PER_PAGE
except AttributeError:
print "oooo"
ITEMS_PER_PAGE = 20
try:
TAGS_PER_PAGE = setting... | PER_PAGE": TAGS_PER_PAGE} |
tom-henderson/bookmarks | bookmarks/bookmarks/migrations/0005_rename_app.py | Python | mit | 431 | 0.006961 | from d | jango.db import migrations
class Migration(migrations.Migration):
dependencies = [
('bookmarks', '0004_auto_20160901_2322'),
]
operations = [
migrations.RunSQL("DROP TABLE bookmarks_bookmark;"),
migrations.RunSQL("ALTER TABLE core_bookmark RENAME TO bookmarks_bookmark;"),
... | s.RunSQL("UPDATE django_content_type SET app_label='bookmarks' WHERE app_label='core';"),
] |
drandreaskrueger/cloudminingstatus | cloudminingstatus.py | Python | agpl-3.0 | 5,999 | 0.015503 | '''
cloudminingstatus.py
@summary: Show selected API data from cloudhasher and miningpool.
@author: Andreas Krueger
@since: 12 Feb 2017
@contact: https://github.com/drandreaskrueger
@copyright: @author @since @license
@license: Donationware, see README.md. Plus see LICENSE.
@version: v0.1.... |
('id', (lambda x: x)),
('pool_host', (lambda x: x)),
('pool_user', (lambda x: x)),
('limit_speed', (lambda x: "%6.2f MHash/s" % (float(x)*1000))),
('accepted_speed', (lambda x: "%6.2f MHash/s" % (float(x)*1000))),
('btc_paid'... | ice', (lambda x: "%s BTC/GH/Day" % x)),
('end', (lambda x: "%4.2f days order lifetime" % (x/1000.0/60/60/24))),
]
def getJsonData(url):
"""
get url, check for status_code==200, return as json
"""
try:
r=requests.get(url)
except Exception as e:... |
haamoon/tensorpack | examples/DeepQNetwork/common.py | Python | apache-2.0 | 3,829 | 0.000261 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: common.py
# Author: Yuxin Wu <ppwwyyxxc@gmail.com>
import random
import time
import threading
import multiprocessing
import numpy as np
from tqdm import tqdm
from six.moves import queue
from tensorpack import *
from tensorpack.utils.concurrency import *
from tensor... | in tqdm(range(nr_eval), **get_tqdm_kwargs()):
r = q.get()
stat.feed(r)
logger.info("Waiting for all the workers to finish the last run...")
for k in threads:
k.stop()
for k in threads:
| k.join()
while q.qsize():
r = q.get()
stat.feed(r)
except:
logger.exception("Eval")
finally:
if stat.count > 0:
return (stat.average, stat.max)
return (0, 0)
def eval_model_multithread(cfg, nr_eval, get_player_fn):
func = Offlin... |
dongweiming/web_develop | chapter9/section4/kombu_consumer.py | Python | gpl-3.0 | 761 | 0.001314 | # coding=utf-8
from kombu import Connection, Exchange, Queue, Consumer
from kombu.async import Hub
web_exchange = Exchange('web_develop', 'direct', durable=True)
standard_queue = Queue('standard', exchange=web_exchange,
routing_key='web.develop')
URI = 'librabbitmq://dongwm:123456@localhost:567... | "Body:'%s', Headers:'%s', Payload:'%s'" | % (
body, message.content_encoding, message.payload))
message.ack()
with Connection(URI) as connection:
connection.register_with_event_loop(hub)
with Consumer(connection, standard_queue, callbacks=[on_message]):
try:
hub.run_forever()
except KeyboardInterrupt:
... |
praveen-pal/edx-platform | i18n/transifex.py | Python | agpl-3.0 | 2,066 | 0.005808 | #!/usr/bin/env python
import os, sys
from polib import pofile
from config import CONFIGURATION
from extract import SOURCE_WARN
from execute import execute
TRANSIFEX_HEADER = 'Translations in this file have been downloaded from %s'
TRANSIFEX_URL = 'https://www.transifex.com/projects/p/edx-studio/'
def push():
exe... | ated_locales()
def clean_translated_locales():
"""
Strips out the warning from all translated po files
about being an English source file.
"""
fo | r locale in CONFIGURATION.locales:
if locale != CONFIGURATION.source_locale:
clean_locale(locale)
def clean_locale(locale):
"""
Strips out the warning from all of a locale's translated po files
about being an English source file.
Iterates over machine-generated files.
""... |
edx/edx-organizations | organizations/migrations/0002_auto_20170117_1434.py | Python | agpl-3.0 | 490 | 0.002041 | from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('organizations', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='organization',
name='logo',
field=models.ImageField(help_tex | t='Please add only .PNG files for logo images. This logo will be used on certificates.', max_length=255, null=True, upload_to='organizat | ion_logos', blank=True),
),
]
|
mirrorcoder/paramiko | tests/test_util.py | Python | lgpl-2.1 | 19,156 | 0.000104 | # Copyright (C) 2003-2009 Robey Pointer <robeypointer@gmail.com>
#
# This file is part of paramiko.
#
# Paramiko is free software; you can redistribute it and/or modify it under the
# terms of the GNU Lesser General Public License as published by the Free
# Software Foundation; either version 2.1 of the License, or (a... | lf.assertEqual(0, intr_errors_remaining[0])
self.asse | rtEqual(4, call_count[0])
def raises_ioerror_not_eintr():
raise IOError(errno.ENOENT, "file", "file not found")
self.assertRaises(
IOError,
lambda: paramiko.util.retry_on_signal(raises_ioerror_not_eintr),
)
def |
nikkisquared/servo | components/script/dom/bindings/codegen/Configuration.py | Python | mpl-2.0 | 15,248 | 0.000787 | # 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/.
from WebIDL import IDLExternalInterface, IDLInterface, WebIDLError
class Configuration:
"""
Represents global ... | # Read the desc, and fill in the relevant defaults.
ifaceName = self.interface.identifier.name
# Callback types do not use JS smart pointers, so we should not use the
# built-in rooting mechanisms for them.
if self.interface.isCallback():
self.needsRooting = False
... | |
fegonda/icon_demo | code/model/unet/ff.py | Python | mit | 36,759 | 0.014935 | import os
import sys
import skimage.transform
import skimage.exposure
import time
import glob
import numpy as np
import mahotas
import random
import matplotlib
import matplotlib.pyplot as plt
import scipy
import scipy.ndimage
import json
from scipy.ndimage.filters import maximum_filter
base_path = os.path.dirname(__fi... | image1 = np.uint8(image1*255)
image2 = np.uint8(image2*255)
if not image3 is None:
image3 = np.uint8(image3*255)
displacement_x = np.random.normal(size=image1.shape, scale=10)
displacement_y = np.random.normal(size=image1.shape, scale=10)
# smooth over image
coords_x,... | hape[0]), np.arange(0,image1.shape[1]), indexing='ij')
displacement_x = coords_x.flatten() + scipy.ndimage.gaussian_filter(displacement_x, sigma=5).flatten()
displacement_y = coords_y.flatten() + scipy.ndimage.gaussian_filter(displacement_y, sigma=5).flatten()
coordinates = np.vstack([displacement_x, ... |
simonolander/euler | euler-169-sum-of-powers-of-2.py | Python | mit | 1,172 | 0 | """
sum(2 * 2**i for i in range(i)) == 2 * (2**i - 1) == n
i == log_2(n // 2 + 1)
"""
from math import ceil, log
import time
def count_ways(n, current_power=None, memo=None):
if memo is None:
memo = {}
if current_power is None:
current_power = ceil(log(n // 2 + 1, 2))
key = (n, current_po... | t_term:
if n == 2 * current_term:
ans += 1
else:
ans += count_ways(n - 2 * current_term, current_power - 1, memo)
if n >= current_term:
| if n == current_term:
ans += 1
elif n - current_term <= next_max_available:
ans += count_ways(n - current_term, current_power - 1, memo)
if n <= next_max_available:
ans += count_ways(n, current_power - 1, memo)
memo[key] = ans
return ans
t0 = time.time()
pr... |
tobspr/Panda3D-Bam-Exporter | src/ExportLog.py | Python | mit | 2,156 | 0.004174 |
import sys
import bpy
from bpy.props import StringProperty
class ExportLog(object):
""" Class which tracks warnings and errors during export """
WARNING = "Warning"
ERROR = "Error"
MESSAGE_SEPERATOR = "\n"
SEVERITY_DIVIDER = "|#|"
EXPORTED_MESSAGE_QUEUE = []
def __init__(self):
... | row = self.layout.row()
message = message.replace("\n", "")
row.label(message, icon="CANCEL" if severity == ExportLog.ERROR else "ERROR")
self.layout.row()
def register():
bpy.utils.register_class(OperatorExportStatus)
#bpy.utils.register_class(OperatorExportStatusOk)
d... | py.utils.unregister_class(OperatorExportStatusOk)
|
rdonnelly/ultimate-league-app | src/ultimate/user/views.py | Python | bsd-3-clause | 4,712 | 0.004032 | from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from django.db.models import Q
from django.db.transaction import atomic
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.template import ... | r=user,
defaults={'date_of_birth': form.cleaned_data.get('date_of_birth'),
'gender': form.cleaned_data.get('gender')})
messages.success(request, 'Your account was created. You may now log in.')
return HttpResponseRedirect(reverse('user'))
else:
... |
return render(request, 'user/signup.html',
{'form': form})
@login_required
def editprofile(request):
try:
player = Player.objects.get(user=request.user)
except Player.DoesNotExist:
player = Player(user=request.user)
if request.method == 'POST':
form = EditProfileForm... |
svp-dev/slcore | slc/tools/slc/mt/mipsel/regdefs.py | Python | gpl-3.0 | 87 | 0.034483 |
class RegMagic:
fixed_registers = []
|
regmagic = RegMagic | ()
__all__ = ['regmagic']
|
mabuchilab/QNET | tests/algebra/test_state_algebra.py | Python | mit | 18,851 | 0.000265 | import unittest
from sympy import sqrt, exp, I, pi, IndexedBase, symbols, factorial
from qnet.algebra.core.abstract_algebra import _apply_rules
from qnet.algebra.core.scalar_algebra import (
ScalarValue, KroneckerDelta, Zero, One)
from qnet.algebra.toolbox.core import temporary_rules
from qnet.algebra.core.operat... | hs1 = LocalSpace(1)
assert (Displace(5 + 6j, hs=hs1) * CoherentStateKet(3., hs=hs1) ==
exp(I * ((5+6j)*3).imag) * CoherentStateKet(8 + 6j, hs=hs1))
assert (Displace(5 + 6j, hs=hs1) * BasisKet(0, hs=hs1) ==
CoherentStateKet(5+6j, hs=hs1))
def testLocalSigma | Pi(self):
assert (LocalSigma(0, 1, hs=1) * BasisKet(1, hs=1) ==
BasisKet(0, hs=1))
assert (LocalSigma(0, 0, hs=1) * BasisKet(1, hs=1) ==
ZeroKet)
def testActLocally(self):
hs1 = LocalSpace(1)
hs2 = LocalSpace(2)
assert ((Create(hs=hs1) * Destr... |
DarthMaulware/EquationGroupLeaks | Leak #5 - Lost In Translation/windows/Resources/Ops/PyScripts/windows/sentinel/table_print.py | Python | unlicense | 3,527 | 0.004536 |
from __future__ import print_function
from __future__ import division
ALIGN_LEFT = '<'
ALIGN_CENTER = '_'
ALIGN_RIGHT = '>'
def pprint(data, header=None, dictorder=None, align=None, output_file=None):
if ((dict is type(data[0])) and (dictorder is None)):
dictorder = data[0].keys()
if ((dict is type(da... | output += ' '
else:
output += (('| ' + d[i]) + (' ' * ((widths[i] - len(d[i])) + 1)))
if percents[i]:
output += (' ' * (percents[i] - d[i].count('%')))
output += '|'
output += '\n'
if output_file: |
with open(output_file, 'wb') as output_handle:
output_handle.write(output)
else:
print(output, end='')
def makeStrings(data, dictOrder, align):
r = []
a = ([] if (align is None) else None)
for i in data:
c = []
ac = []
if dictOrder:
for k... |
hva/warehouse | warehouse/backup/views.py | Python | mit | 3,061 | 0.003495 | # coding=utf-8
import os
import time
from gzip import GzipFile
from StringIO import StringIO
from django.shortcuts import render_to_response, redirect
from django.template import RequestContext
from django.http import HttpResponse
from django.core.management import call_command
from django.views.decorators.csrf impor... | data', 'auth', 'skill', stdout=gz_stream, natural=True, indent=2)
return response
##### IMPORT #####
@log | in_required
@csrf_exempt
def import_gz(request):
# changing suffix to '.gz' for temp file names
request.upload_handlers = [TemporaryGzipFileUploadHandler()]
return _import_gz(request)
@csrf_protect
def _import_gz(request):
if request.method == 'POST':
form = BackupImportForm(request.POST, requ... |
baylesj/chopBot3000 | scripts/print_bot_id.py | Python | mit | 604 | 0 | #!/usr/bin/env python
import os
f | rom slackclient import SlackClient
BOT_NAME = 'chopbot3000'
slack_client = SlackClient(os.environ.get('SLACK_BOT_TOKEN'))
if __name__ == "__main__":
api_call = slack_client.api_call("users.list")
if api_call.get('ok'):
# retrieve all users so we can find our bot
users = api_call.get('members'... | ' is " + user.get('id'))
else:
print("could not find bot user with the name " + BOT_NAME)
|
googleapis/python-spanner | google/cloud/spanner_v1/database.py | Python | apache-2.0 | 45,568 | 0.000812 | # Copyright 2016 Google LLC All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | 0}/operations/"
_LIST_TABLES_QUERY = """SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE SPANNER_STATE = 'COMMITTED'
"""
DEFAULT_RETRY_BACKOFF = Retry(initial=0.02, maximum=32, multiplier=1.3)
class Database(object):
"""Representation of a Cloud Spanner Database.
We can use a :class:`Database` to:
... | abase
* :meth:`drop` the database
:type database_id: str
:param database_id: The ID of the database.
:type instance: :class:`~google.cloud.spanner_v1.instance.Instance`
:param instance: The instance that owns the database.
:type ddl_statements: list of string
:param ddl_statements: (Optio... |
kristerhedfors/xnet | xnet/packages/urllib3/contrib/ntlmpool.py | Python | bsd-3-clause | 4,740 | 0 | # urllib3/contrib/ntlmpool.py
# Copyright 2008-2013 Andrey Petrov and contributors (see CONTRIBUTORS.txt)
#
# This module is part of urllib3 and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""
NTLM authenticating pool, contributed by erikcederstran
Issue #10, see: http://co... | ponse object (we want to keep the socket open)
res.fp = None
# Server should respond with a challenge message
auth_header_values = reshdr[resp_header].split(', ')
auth_header_value = None
for s in auth_header_values:
if s[:5] == 'NTLM ':
auth_header_v... | sp_header, reshdr[resp_header]))
# Send authentication message
ServerChallenge, NegotiateFlags = \
ntlm.parse_NTLM_CHALLENGE_MESSAGE(auth_header_value)
auth_msg = ntlm.create_NTLM_AUTHENTICATE_MESSAGE(ServerChallenge,
self.use... |
IITBinterns13/edx-platform-dev | cms/envs/dev.py | Python | agpl-3.0 | 6,301 | 0.002063 | """
This config file runs the simplest dev environment"""
# We intentionally define lots of variables that aren't used, and
# want to import all variables from base settings files
# pylint: disable=W0401, W0614
from .common import *
from logsettings import get_logger_config
DEBUG = True
TEMPLATE_DEBUG = DEBUG
LOGGIN... | ithub.com:MITx/3.091x.git',
},
}
CACHES = {
# This is the cache used for most things. Askbot will not work without a
# functioning cache -- it relies on caching to load its settings in places.
# In staging/prod envs, the sessions also live here.
'default': {
'BACKEND': 'django.core.cache.ba... |
# The general cache is what you get if you use our util.cache. It's used for
# things like caching the course.xml file for different A/B test groups.
# We set it to be a DummyCache to force reloading of course.xml in dev.
# In staging environments, we would grab VERSION from data uploaded by the
#... |
natetrue/ReplicatorG | skein_engines/skeinforge-31/fabmetheus_utilities/geometry/creation/circle.py | Python | gpl-2.0 | 2,658 | 0.017682 | """
Polygon path.
"""
from __future__ import absolute_import
#Init has to be imported first because it has code to workaround the python bug where relative imports don't work if the module is i | mported as a main module.
import __init__
from fabmetheus_utilities.geometry.creation import lineation
from fabmetheus_utilities.geometry.geometry_utilities import evaluate
from fabmetheus_utilities.vector3 import Vector3
from fabmetheus_utilities import euclidean
import math
__author__ = 'Enrique Perez (perez_enriq... | e__ = "$Date: 2008/02/05 $"
__license__ = 'GPL 3.0'
def getGeometryOutput(xmlElement):
"Get vector3 vertexes from attribute dictionary."
radius = lineation.getRadiusComplex(complex(1.0, 1.0), xmlElement)
sides = evaluate.getSidesMinimumThreeBasedOnPrecisionSides(max(radius.real, radius.imag), xmlElement)
loop = [... |
mjsauvinen/P4UL | pyLib/mapTools.py | Python | mit | 23,790 | 0.042917 | import operator
import numpy as np
import sys
'''
Description:
Author: Mikko Auvinen
mikko.auvinen@fmi.fi
Finnish Meteorological Institute
'''
# =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
def readAsciiGridHeader( filename, nHeaderEntries, idx=0 ):
fl = open( filename , 'r')
name = file... | id, irow, jcol
return ijList, XO_TL, imax, jmax
# =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
def minMaxCoords( xdict , fileTypes ):
asc = fileTypes[0]; npz = fileTypes[1]
if( asc ):
xn = xdict['xllcorner']
yx = xdict['yllcorner']
| xx = xdict['xllcorner']+xdict['ncols']*xdict['cellsize']
yn = xdict['yllcorner']-xdict['nrows']*xdict['cellsize']
else:
xn = xdict['xtlcorner']
yx = xdict['ytlcorner']
xx = xdict['xtlcorner']
yn = xdict['ytlcorner']
return xn, xx, yn, yx
# =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=... |
Nitr4x/whichCDN | plugins/ErrorServerDetection/behaviors.py | Python | mit | 907 | 0.00882 | #!/usr/bin/env python
from __future__ import print_function
import sys
import re
from utils import CDNEngine
from utils import request
if sys.version_info >= (3, 0):
import subprocess as commands
import urllib.parse as urlparse
else:
import commands
import urlparse
def detect(hostname):
"""
P... | ms CDN detection thanks to information disclosure from server error.
Parameters
----------
hostname : str
Hostname to assess
"""
print('[+] Error server detection\n')
hostname = urlparse.urlparse(hostname).netloc
regexp = re.compile('\\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\\b')
... | f res is not None and res.status_code == 500:
CDNEngine.find(res.text.lower())
|
QuLogic/burnman | examples/example_user_input_material.py | Python | gpl-2.0 | 4,958 | 0.013312 | # BurnMan - a lower mantle toolkit
# Copyright (C) 2012, 2013, Heister, T., Unterborn, C., Rose, I. and Cottaar, S.
# Released under GPL v2 or later.
"""
example_user_input_material
---------------------------
Shows user how to input a mineral of his/her choice without usint the library and which physical values... | elf.params = {
'name': 'myownmineral',
'equation_of_st | ate': method,
'V_0': 10.844e-6, #Molar volume [m^3/(mole molecules)]
#at room pressure/temperature
'K_0': 135.19e9, #Reference bulk modulus [Pa]
#at room pressure/temperature
'Kprime_0': 6.04, #pressure derivative of bulk modulus
... |
acorg/acmacs-whocc | web/chains-202105/py/directories.py | Python | mit | 1,044 | 0.004789 | import sys, os, json
from pathlib import Path
from acmacs_py.mapi_utils import MapiSettings
# ======================================================================
class CladeData:
sSubtypeToCladePrefix = {"h1pdm": "clades-A(H1N1)2009pdm", "h3": "clades-A(H3N2)", "bvic": "clades-B/Vic", "byam": "clades-B/Yam"}
... | deData()
# =================================================================== | ===
|
VikParuchuri/simpsons-scripts | tasks/train.py | Python | apache-2.0 | 16,847 | 0.008429 | from __future__ import division
from itertools import chain
from sklearn.feature_extraction.text import CountVectorizer
import numpy as np
import pandas as pd
from fisher import pvalue
import re
import collections
from nltk.stem.porter import PorterStemmer
import math
from percept.tasks.base import Task
from percept.fi... | i<=input_score_med else 1 for i in input_scores]
ind_max_features = math.floor(max_features/max(input_scores))
all_vocab = []
all_cols = [np.asarray(train_mat.getcol(i).todense().transpose())[0] for i in x | range(0,train_mat.shape[1])]
for s in xrange(0,max(input_scores)):
sel_inds = [i for i in xrange(0,len(input_scores)) if input_scores[i]==s]
out_inds = [i for i in xrange(0,len(input_scores)) if input_scores[i]!=s]
pvalues = []
for i in xrange(0,len(all_cols)):
... |
veekun/spline | spline/i18n/cs/__init__.py | Python | mit | 2,365 | 0.002668 | # Encoding: UTF-8
"""Czech conjugation
"""
from spline.i18n.formatter import Formatter, BaseWord, parse_bool
class Word(BaseWord):
@classmethod
def guess_type(cls, word, **props):
if word.endswith(u'í'):
return SoftAdjective
elif word.endswith(u'ý'):
return HardAdjecti... | self.gender)
case = int(props.get('case', self.case)) |
number = props.get('number', self.number)
case_no = (case - 1) + (7 if (number == 'pl') else 0)
if gender == 'm':
if parse_bool(props.get('animate', True)):
return self.root + self.endings_ma[case_no]
else:
return self.root + self.endings_... |
pouyana/teireader | webui/gluon/contrib/memcache/memcache.py | Python | mit | 49,300 | 0.004138 | #!/usr/bin/env python
"""
client module for memcached (memory cache daemon)
Overview
========
See U{the MemCached homepage<http://www.danga.com/memcached>} for more about memcached.
Usage summary
=============
This should give you a feel for how this module operates::
import memcache
mc = memcache.Client(... | ):
"""
Object representing a pool of memcache servers.
See L{memcache} for an overview.
|
In all cases where a key is used, the key can be either:
1. A simple hashable type (string, integer, etc.).
2. A tuple of C{(hashvalue, key)}. This is useful if you want to avoid
making this module calculate a hash value. You may prefer, for
example, to keep all of a given user's ... |
yaii/yai | share/extensions/ink2canvas/canvas.py | Python | gpl-2.0 | 6,499 | 0.002462 | #!/usr/bin/env python
'''
Copyright (C) 2011 Karlisson Bezerra <contact@hacktoon.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later ve... | def createRadialGradient(self, href, cx1, cy1, rx, cx2, cy2, ry):
data = (href, cx1, cy1, rx, cx2, cy2, ry)
self.write("var %s = ctx.createRadialGradient\
(%f,%f,%f,%f,%f,%f);" % data)
def addColorStop(self, href, pos, color):
self.write("%s.addColorStop(%f, %s);" % (... | return "'rgba(%d, %d, %d, %.1f)'" % (r, g, b, a)
else:
return "'rgb(%d, %d, %d)'" % (r, g, b)
def setGradient(self, href):
"""
for stop in gstops:
style = simplestyle.parseStyle(stop.get("style"))
stop_color = style["stop-color"]
opacity = sty... |
MicheleDamian/ConnectopicMapping | setup.py | Python | apache-2.0 | 1,540 | 0.001299 | from | codecs import open
from os import path
from setuptools import setup, Extension
from Cython.Distutils import build_ext
import numpy
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open | (path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
# Requirements
install_requires=['cython>=0.24.1',
'numpy>=1.6.1',
'scipy>=0.16',
'matplotlib>=1.5.1',
'scikit-learn>=0.17.1',
'nibabel>=2.0.... |
mitsuhiko/django | tests/regressiontests/requests/tests.py | Python | bsd-3-clause | 15,031 | 0.002329 | import time
from datetime import datetime, timedelta
from StringIO import StringIO
from django.core.handlers.modpython import ModPythonRequest
from django.core.handlers.wsgi import WSGIRequest, LimitedStream
from django.http import HttpRequest, HttpResponse, parse_cookie, build_request_repr
from django.utils import un... | st), repr(request))
self.assertEqual(build_request_repr(request, path_override='/otherpath/', GET_override={u'a': u'b'}, POST_override={u'c': u'd'}, COOKIES_override={u'e': u'f'}, META_override={u'g' | : u'h'}),
u"<HttpRequest\npath:/otherpath/,\nGET:{u'a': u'b'},\nPOST:{u'c': u'd'},\nCOOKIES:{u'e': u'f'},\nMETA:{u'g': u'h'}>")
def test_wsgirequest(self):
request = WSGIRequest({'PATH_INFO': 'bogus', 'REQUEST_METHOD': 'bogus', 'wsgi.input': StringIO('')})
self.assertEqual(... |
pombredanne/anitya | anitya/lib/backends/folder.py | Python | gpl-2.0 | 2,702 | 0.00037 | # -*- coding: utf-8 -*-
"""
(c) 2014 - Copyright Red Hat Inc
Authors:
Pierre-Yves Chibon <pingou@pingoured.fr>
"""
from anitya.lib.backends import (
BaseBackend, get_versions_by_regex_for_text, REGEX)
from anitya.lib.exceptions import AnityaPluginException
import six
DEFAULT_REGEX = 'href="([0-9][0-9.]*)/... | 'http://ftp.gnu.org/pub/gnu/gnash/',
'http://subsurface.hohndel.org/downloads/',
]
@classmethod
def get_version(cls, project):
| ''' Method called to retrieve the latest version of the projects
provided, project that relies on the backend of this plugin.
:arg Project project: a :class:`model.Project` object whose backend
corresponds to the current plugin.
:return: the latest version found upstream
... |
jekhokie/scriptbox | python--advent-of-code/2021/3/solve.py | Python | mit | 1,039 | 0.014437 | #!/usr/bin/env python3
import re
from enum import Enum
diags = []
with open('input.txt', 'r') as f:
diags = f.read().splitlines()
#--- challenge 1
gamma = ""
for i in range(0, len(diags[0])):
zeros = len([x for | x in diags if x[i] == "0"])
ones = len([x for x in diags if x[i] == "1"])
gamma += "0" if zeros > ones else "1"
gamma = int(gamma, 2)
epsilon = gamma ^ 0b111111111111
print("Solution to challenge 1: {}".format(gamma * epsilon))
#--- challenge 2
class Rating(Enum):
OXYGEN = 0
CO2 = 1
def get_val(diags, ra... | gs[0])):
zeros = len([x for x in diags if x[i] == "0"])
ones = len(diags) - zeros
if rating == Rating.OXYGEN:
check_val = "0" if zeros > ones else "1"
else:
check_val = "0" if zeros <= ones else "1"
diags = [x for x in diags if x[i] != check_val]
if len(diags) == 1:
return in... |
itkovian/sqlalchemy | test/orm/inheritance/test_magazine.py | Python | mit | 9,316 | 0.008695 | from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy import testing
from sqlalchemy.testing.util import function_named
from sqlalchemy.testing import fixtures
from sqlalchemy.testing.schema import Table, Column
class BaseObject(object):
def __init__(self, *args, **kwargs):
for key, value ... | urn "%s(%s)" % (self.__class__.__name__, str(self.page_no))
class MagazinePage(Page):
def __repr__(self):
return "%s(%s, %s)" % (self.__class__.__ | name__, str(self.page_no), repr(self.magazine))
class ClassifiedPage(MagazinePage):
pass
class MagazineTest(fixtures.MappedTest):
@classmethod
def define_tables(cls, metadata):
global publication_table, issue_table, location_table, location_name_table, magazine_table, \
page_table, magazi... |
saulpw/visidata | visidata/editor.py | Python | gpl-3.0 | 2,699 | 0.002594 | import os
import sys
import signal
import subprocess
import tempfile
import curses
import visidata
visidata.vd.tstp_signal = None
class SuspendCurses:
'Context manager to leave windowed mode on enter and restore it on exit.'
def __enter__(self):
curses.endwin()
if visidata.vd.tstp_signal:
... | ill(os.getpid(), signal.SIGSTOP)
def _breakpoint(*args, **kwargs):
import pdb
class VisiDataPdb(pdb.Pdb):
def precmd(self, line):
r = super().precmd(line)
| if not r:
SuspendCurses.__exit__(None, None, None, None)
return r
def postcmd(self, stop, line):
if stop:
SuspendCurses.__enter__(None)
return super().postcmd(stop, line)
SuspendCurses.__enter__(None)
VisiDataPdb(nosigint=True... |
plotly/python-api | packages/python/plotly/plotly/validators/scatterternary/marker/colorbar/_tickvals.py | Python | mit | 513 | 0 | import _plotly_utils.basevalidators
class TickvalsValidator( | _plotly_utils.basevalidators.DataArrayValidator):
def __init__(
self,
plotly_name="tickvals",
parent_name="scatterternary.marker.colorbar",
**kwargs
):
super(TickvalsValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... | **kwargs
)
|
Ehtaga/account-financial-reporting | account_financial_report_horizontal/report/report_financial.py | Python | agpl-3.0 | 2,192 | 0 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# This module copyright (C) 2015 Therp BV (<http://therp.nl>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of ... | 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License... | ###############
import copy
from openerp import models
from openerp.addons.account.report.account_financial_report import\
report_account_common
class report_account_common_horizontal(report_account_common):
def __init__(self, cr, uid, name, context=None):
super(report_account_common_horizontal, self)... |
seerjk/reboot06 | 09/homework08/flask_web.py | Python | mit | 768 | 0.002604 | # coding:utf-8
impo | rt MySQLdb as mysql
from flask import Flask, request, render_template
import json
app = Flask(__name__)
con = mysql.connect(user="root", passwd="redhat", db="jiangkun")
con.autocommit(True)
cur = con.cursor()
@app.route('/')
def index():
return render_template("index.html")
@app.ro | ute('/list')
def list():
sql = "select * from user"
cur.execute(sql)
res_json = json.dumps(cur.fetchall())
print res_json
return res_json
@app.route('/add')
def add():
name = request.args.get('name')
passwd = request.args.get('passwd')
sql = "insert into user (name, passwd) values (%s,... |
housecanary/hc-api-python | housecanary/utilities.py | Python | mit | 2,345 | 0.002132 | """Utility functions for hc-api-python"""
from datetime import datetime
def get_readable_time_string(seconds):
"""Returns human readable string from number of seconds"""
seconds = int(seconds)
minutes = seconds // 60
seconds = seconds % 60
hours = minutes // 60
minutes = minutes % 60
days... | Reset'].split(',')
for idx, period in enumerate(periods):
rate_limit = {}
limit_period = get_readable_time_string(period)
rate_limit["peri | od"] = limit_period
rate_limit["period_seconds"] = period
rate_limit["request_limit"] = limits[idx]
rate_limit["requests_remaining"] = remaining[idx]
reset_datetime = get_datetime_from_timestamp(reset[idx])
rate_limit["reset"] = reset_datetime
right_now = datetime.now()... |
chendx79/Python3HandlerSocket | pyhs/__init__.py | Python | mit | 51 | 0 | from .m | anager impor | t Manager
__version__ = '0.2.4'
|
mtagle/airflow | airflow/providers/google/cloud/operators/mssql_to_gcs.py | Python | apache-2.0 | 3,144 | 0.000318 | #
# 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... | gle_cloud_default',
dag=dag
)
"""
ui_color = '#e0a98c'
type_map = {
3: 'INTEGER',
4: 'TIMESTAMP',
5: 'NUMERIC'
}
@apply_defaults
def __init__(self,
mssql_conn_id='mssql_default',
*args,
**kwa... | mssql_conn_id
def query(self):
"""
Queries MSSQL and returns a cursor of results.
:return: mssql cursor
"""
mssql = MsSqlHook(mssql_conn_id=self.mssql_conn_id)
conn = mssql.get_conn()
cursor = conn.cursor()
cursor.execute(self.sql)
return cur... |
alexryndin/ambari | ambari-server/src/test/python/stacks/2.2/KAFKA/test_kafka_broker.py | Python | apache-2.0 | 7,652 | 0.023523 | #!/usr/bin/env python
'''
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")... | group = 'hadoop',
create_parents = True,
mode = 0755,
cd_access = 'a',
recursive_ownership = True,
)
self.assertResourceCalled('D | irectory', '/tmp/log/dir',
owner = 'kafka',
create_parents = True,
group = 'hadoop',
mode = 0755,
cd_access = 'a',
recursive_ownership = Tru... |
chriso/gauged | gauged/drivers/__init__.py | Python | mit | 1,960 | 0 | """
Gauged
https://github.com/chriso/gauged (MIT Licensed)
Copyright 2014 (c) Chris O'Hara <cohara87@gmail.com>
"""
from urlparse import urlparse, parse_qsl
from urllib import unquote
from .mysql import MySQLDriver
from .sqlite import SQLiteDriver
from .postgresql import PostgreSQLDriver
def parse_dsn(dsn_string):
... | dsn.scheme.split('+')[0]
username = password = host = port = None
host = dsn.netloc
if '@' in host:
username, host = host.split('@')
if ':' in username:
username, password = username.split(':')
password = unquote(password)
username = unquote(username)
if '... | ?' in dsn.path else dsn.query
kwargs = dict(parse_qsl(query, True))
if scheme == 'sqlite':
return SQLiteDriver, [dsn.path], {}
elif scheme == 'mysql':
kwargs['user'] = username or 'root'
kwargs['db'] = database
if port:
kwargs['port'] = port
if host:
... |
kurikaesu/arsenalsuite | cpp/apps/absubmit/nukesubmit/nukeStub.py | Python | gpl-2.0 | 877 | 0.019384 | #!/usr/bin/python2.5
import sys
import time
import os
import nuke
def launchSubmit():
print("nukeStub(): launch submitter dialog")
submitCmd = "/drd/software/int/bin/launcher.sh -p %s -d %s --launchBlocking farm -o EPA_CMDLINE python2.5 --arg '$ABSUBMIT/nukesubmit/nuke2AB.py'" % (os.environ['DRD_JOB'], os.environ[... | %s" % nuke.Root.lastFrame(nuke.root())
writeNodes = [i for i in nuke.allNodes() if i.Class() == "Write"]
for i in writeNodes:
submitCmd += " %s %s" % (i['name'].value(), nuke.filename(i))
print( "nukeStub(): %s" % submitCmd )
os.system(sub | mitCmd)
menubar = nuke.menu("Nuke")
m = menubar.addMenu("&Render")
m.addCommand("Submit to Farm", "nukeStub.launchSubmit()", "Up")
|
Sotera/Datawake-Legacy | memex-datawake-stream/src/datawakestreams/extractors/website_bolt.py | Python | apache-2.0 | 293 | 0.010239 | from extractors.extract_website import Ex | tractWebsite
from datawakestreams.extractors.extractor_bolt import ExtractorBolt
class WebsiteBolt(Extracto | rBolt):
name ='website_extractor'
def __init__(self):
ExtractorBolt.__init__(self)
self.extractor = ExtractWebsite()
|
monetario/core | monetario/serializers.py | Python | bsd-3-clause | 5,724 | 0.002271 | import pycountry
from marshmallow import Schema, fields, ValidationError
def validate_currency_symbol(val):
if val not in [x.letter for x in pycountry.currencies.objects]:
raise ValidationError('Symbol is not valid')
class CategoryTypeField(fields.Field):
def _serialize(self, value, attr, obj):
... | Str(required=True)
logo = fields.Str(required=True)
class GroupCurrencySchema(Schema): |
id = fields.Int(dump_only=True)
name = fields.Str(required=True)
symbol = fields.Str(
required=True,
validate=validate_currency_symbol
)
date_modified = fields.DateTime()
group = fields.Nested(GroupSchema, dump_only=True)
class AccountSchema(Schema):
id = fields.Int(dump_... |
fujicoin/electrum-fjc | electrum/tests/test_util.py | Python | mit | 5,385 | 0.003714 | from decimal import Decimal
from electrum.util import | (format_satoshis, format_fee_satoshis, parse_URI,
is_hash256_str, chunks)
from . import SequentialTestCase
class TestUtil(SequentialTestCase):
def test_format_satoshis(self):
self.assertEqual("0.00001234", format_satoshis(1234))
def test_format_satoshis_negative(self):
... | _fee_decimal(self):
self.assertEqual("1.7", format_fee_satoshis(Decimal("1.7")))
def test_format_fee_precision(self):
self.assertEqual("1.666",
format_fee_satoshis(1666/1000, precision=6))
self.assertEqual("1.7",
format_fee_satoshis(1666/100... |
plivo/plivo-python | plivo/rest/client.py | Python | mit | 13,434 | 0.001265 | # -*- coding: utf-8 -*-
"""
Core client, used for all API requests.
"""
import os
import platform
from collections import namedtuple
from plivo.base import ResponseObject
from plivo.exceptions import (AuthenticationError, InvalidRequestError,
PlivoRestError, PlivoServerError,
... | h credentials.')
if not (is_valid_mainaccount(au | th_id) or is_valid_subaccount(auth_id)):
raise AuthenticationError('Invalid auth_id supplied: %s' % auth_id)
return AuthenticationCredentials(auth_id=auth_id, auth_token=auth_token)
class Client(object):
def __init__(self, auth_id=None, auth_token=None, proxies=None, timeout=5):
"""
T... |
simonmonk/pi_magazine | 04_analog_clock/analog_clock_24.py | Python | mit | 1,066 | 0.025328 | import time
import RPi.GPIO as GPIO
# Constants
PULSE_LEN = 0.03 # length of clock motor pulse
A_PIN = 18 # one motor drive pin
B_PIN = 23 # second motor drive pin
# Configure the GPIO pins
GPIO.setmode(GPIO.BCM)
GPIO.setup(A_PIN, GPIO.OUT)
GPIO.setup(B_PIN, GPIO.OUT)
# Glogal variables
positive_polarity... | ositive and negative pulses
global positive_polarity
if positive_polarity:
pulse(A_PIN, B_PIN)
else:
pulse(B_PIN, A_PIN)
# Flip the polarity ready for the next tick
positive_polarity = not positive_polarity
def pulse(pos_pin, neg_pin):
# Turn on the pulse
GPIO.output(pos | _pin, True)
GPIO.output(neg_pin, False)
time.sleep(PULSE_LEN)
# Turn the power off until the next tick
GPIO.output(pos_pin, False)
try:
while True:
t = time.time()
if t > last_tick_time + period:
# its time for the next tick
tick()
last_tick_time = t
finally:
print('Cleaning up GPIO')
GPIO.cl... |
plotly/python-api | packages/python/plotly/plotly/graph_objs/area/_hoverlabel.py | Python | mit | 17,818 | 0.000954 | from plotly | .basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType
import copy as _copy
class Hoverlabel(_BaseTraceHierarchyType):
# class properties
# --------------------
_parent_path_str = "area"
_path_str = "area.hoverlabel"
_valid_props = {
"align",
"alignsrc",
| "bgcolor",
"bgcolorsrc",
"bordercolor",
"bordercolorsrc",
"font",
"namelength",
"namelengthsrc",
}
# align
# -----
@property
def align(self):
"""
Sets the horizontal alignment of the text content within hover
label box. ... |
ah-anssi/SecuML | SecuML/core/ActiveLearning/QueryStrategies/AnnotationQueries/AnnotationQueries.py | Python | gpl-2.0 | 3,837 | 0.001303 | # SecuML
# Copyright (C) 2016-2017 ANSSI
#
# SecuML is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# SecuML is distributed in the h... | return predictions
def exportAnnotationQueries(self):
iteration_dir = self.iteration.iteration_dir
if iteration_dir is None:
return
filename = path.join(iteration_dir,
'toannotate_' + | self.label + '.csv')
with open(filename, 'w') as f:
for i, annotation_query in enumerate(self.annotation_queries):
if i == 0:
annotation_query.displayHeader(f)
annotation_query.export(f)
def annotateAuto(self):
for annotation_query in... |
pastephens/pysal | pysal/spreg/probit.py | Python | bsd-3-clause | 34,383 | 0.002501 | """Probit regression class and diagnostics."""
__author__ = "Luc Anselin luc.anselin@asu.edu, Pedro V. Amaral pedro.amaral@asu.edu"
import numpy as np
import numpy.linalg as la
import scipy.optimize as op
from scipy.stats import norm, chisqprob
import scipy.sparse as SP
import user_output as USER
import sum... | r[0],model.PS_error[0]]])
>>> pvalue = np.array([[model.Pinkse_error[1],model.KP_error[1],model.PS_error[1]]])
>>> print np.hstack((tests.T,np.around(np.hstack((stats.T,pvalue.T)),6)))
[['Pinkse_error' '3.131719' '0.076783']
['KP_error' '1.721312' '0.085194']
['PS_error' '2.558166' | '0.109726']]
"""
def __init__(self, y, x, w=None, optim='newton', scalem='phimean', maxiter=100):
self.y = y
self.x = x
self.n, self.k = x.shape
self.optim = optim
self.scalem = scalem
self.w = w
self.maxiter = maxiter
par_est, self.war... |
Azure/azure-sdk-for-python | sdk/network/azure-mgmt-network/azure/mgmt/network/v2020_07_01/aio/operations/_ddos_custom_policies_operations.py | Python | mit | 20,544 | 0.004965 | # 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 may ... | raise HttpResponseError(response=response, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_i | nitial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ddosCustomPolicies/{ddosCustomPolicyName}'} # type: ignore
async def begin_delete(
self,
resource_group_name: str,
ddos_custom_policy_name: str,
**kwargs: Any
... |
JonathanRaiman/Dali | data/score_informed_transcription/midi/example_transpose_octave.py | Python | mit | 1,038 | 0.010597 | from .MidiOutFile import MidiOutFile
from .MidiInFile import MidiI | nFile
"""
This is an example of the smallest possible type 0 midi file, where
all the midi events are in the same track.
"""
class Transposer(MidiOutFile):
"Transposes all notes by 1 octave"
def _transp(self, ch, note):
if ch != 9: # not the drums!
| note += 12
if note > 127:
note = 127
return note
def note_on(self, channel=0, note=0x40, velocity=0x40):
note = self._transp(channel, note)
MidiOutFile.note_on(self, channel, note, velocity)
def note_off(self, channel=0, note=0x40, velo... |
Vladimir-Ivanov-Git/raw-packet | raw_packet/Scanners/nmap_scanner.py | Python | mit | 5,743 | 0.002438 | # region Description
"""
nmap_scanner.py: Scan local network with NMAP
Author: Vladimir Ivanov
License: MIT
Copyright 2020, Raw-packet Project
"""
# endregion
# region Import
from raw_packet.Utils.base import Base
import xml.etree.ElementTree as ET
import subprocess as sub
from tempfile import gettempdir
from os.path ... | state = element.find('status').attrib['state']
assert state == 'up'
# region Address
for address in element.findall('address'):
if address.attrib['addrtype'] == 'ipv4':
ipv4_address = address... | ttrib['addr']
if address.attrib['addrtype'] == 'mac':
mac_address = address.attrib['addr'].lower()
try:
vendor = address.attrib['vendor']
except KeyError:
... |
googleads/google-ads-python | google/ads/googleads/v10/services/services/remarketing_action_service/transports/base.py | Python | apache-2.0 | 6,058 | 0.000495 | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | leapis.com/auth/adwords",)
DEFAULT_HOST: str = "googleads.googleapis.com"
def __init__(
self,
*,
host: str = DEFAULT_HOST,
credentials: ga_credentials.Credentials = None,
| credentials_file: Optional[str] = None,
scopes: Optional[Sequence[str]] = None,
quota_project_id: Optional[str] = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
always_use_jwt_access: Optional[bool] = False,
**kwargs,
) -> None:
"""Instantia... |
physicalattraction/kerstpuzzel | src/Conundrum/key_cipher.py | Python | mit | 1,290 | 0.000775 | import math
import string
from Conundrum.utils import sanitize
letter_to_value = dict(zip('z' + string.ascii_lowercase, range(0, 27)))
value_to_letter = dict(zip(range(0, 27), 'z' + string.ascii_lowercase))
def encrypt(msg: s | tr, key: str) -> str:
msg = sanitize(msg)
key = sanitize(key)
repeat = int(math.ceil(len(msg) / len(key)))
key = key * repeat
return ''.join([value_to_letter[(letter_to_value[msg_letter] +
letter_to_value[key_letter]) % 26]
for msg_letter, key... | itize(key)
repeat = int(math.ceil(len(msg) / len(key)))
key = key * repeat
return ''.join([value_to_letter[(letter_to_value[msg_letter] -
letter_to_value[key_letter]) % 26]
for msg_letter, key_letter in zip(msg, key)])
if __name__ == '__main__':
... |
jakubczaplicki/projecteuler | problem005.py | Python | mit | 1,000 | 0.008 | #!/usr/bin/env python
# pylint: disable=invalid-name
"""
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive num | ber that is evenly divisible by all of the numbers from 1 to 20?
"""
import sys
from problembaseclass import ProblemBaseClass
class Problem5(ProblemBaseClass):
"""
@class Solution for Problem 5
@brief
"""
def __init__(self, range):
self.result = None
self.range = range
def com... | ge):
if (val % n):
notfound = True
self.result = val
if __name__ == '__main__':
problem = Problem5(10)
problem.compute()
print problem.result
del problem
problem = Problem5(20)
problem.compute()
print problem.result #232792560
del problem
|
elric/virtaal-debian-snapshots | virtaal/plugins/autocompletor.py | Python | gpl-2.0 | 10,937 | 0.002834 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2008-2010 Zuza Software Foundation
#
# This file is part of Virtaal.
#
# 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 ... | pass
def _add_text_box(self, textbox):
"""Add the given L{TextBox} to the list of widgets to do auto-
correction on."""
if not hasattr(self, '_textbox_insert_ids'):
self._textbox_insert_ids = {}
handler_id = textbox.connect('text-inserted', self._on_insert... | x, text, offset, elem):
if not isinstance(text, basestring) or self.wordsep_re.match(text):
return
# We are only interested in single character insertions, otherwise we
# react similarly for paste and similar events
if len(text.decode('utf-8')) > 1:
return
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.