prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
__val[:50], __val[-50:]))
if __attr == self.textProperty:
# restore spaces that have been replaced
__val = __val.replace(WS, ' ')
attrs[__attr + __parens] = __val
else:
m = hashRE.match(attr)
if m:
... | ak
attrs = self.__splitAttrs(v)
if not self.root:
if v[0] == ' ':
raise Exception("Unexpected root element starting with ' '.")
self.root = View.facto | ry(attrs, self.device, self.build[VERSION_SDK_PROPERTY], self.forceViewServerUse, windowId)
if DEBUG: self.root.raw = v
treeLevel = 0
newLevel = 0
lastView = self.root
parent = self.root
parents.append(parent)
el... |
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... | roups.all()) | Q(groups__isnull=True)).distinct()
def get_context_data(self, **kwargs):
# Temporar | y message for testing
from django.contrib import messages
# Call the base implementation first to get a context
context = super(SpringBoard, self).get_context_data(**kwargs)
# Get all the alerts for the user
context['alerts'] = Alert.objects.filter(sent_to = self.request.user)
... |
# -*- coding: utf-8 -*-
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and contributors
# For license i | nformation, please see license.t | xt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
class GoogleAppSetup(Document):
pass
|
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__)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(... | D': '',
'HOST': '',
'PORT': '',
}
}
SECRET_KEY = %(default_key)r
"""
def generate_settings():
output = CONFIG_TEMPLATE % dict(
default_key=base64.b64encode(os.urandom(KEY_LENGTH)),
)
return output
def configure():
configure_app(
project='fabric-bolt',
d... | 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',
default_config_path='~/.fabric-bolt/settin... |
# -*- 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, ... | o options for replacing |today|: either, you set t | oday to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of documents that shouldn't be included in the build.
#unused_docs = []
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parenthe... |
# -*- 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)
... | f.lista.pop()
except IndexError:
raise PilhaVaziaErro
def esta_balanceada(expressao):
"""
Função que calcula se expressão | possui parenteses, colchetes e chaves balanceados
O Aluno deverá informar a complexidade de tempo e espaço da função
Deverá ser usada como estrutura de dados apenas a pilha feita na aula anterior
:param expressao: string com expressao a ser balanceada
:return: boleano verdadeiro se expressao está bal... |
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
... | .joyce@realkinetic.com',
url='https://github.com/njoyce/sockjs-gevent',
license=' | MIT',
install_requires=get_install_requires(),
tests_require=get_tests_requires(),
setup_requires=['nose>=1.0'],
test_suite='nose.collector',
include_package_data = True,
packages=find_packages(exclude=["examples", "tests"]),
zip_safe = False,
)
|
############################### | # 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;... | abel(ylab)
plt.xlabel(xlab); |
# 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... | lf.client = current_app.test_client()
def test_load_config(self):
""" Test that we can load our config properly """
self.assertTrue(1)
def test_get_test(self):
""" Test hitting /test and that we get a correct HTTP response """
self.assertTrue(1)
def test_get_form(self):
... | 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()
|
s have a default; values that are commented out
# serve to show the default.
import sys
import os
import sphinx_rtd_theme
html_theme = 'sphinx_rtd_theme'
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories ... | l templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_spl | it_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
... |
# 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 publis | hed by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but | WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, see <http://www.gnu.org/licenses/>.
fro... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Скрипт извлекает слова из текстового файла и сортирует их по частоте.
# С помощью модуля pymorphy2 можно привести слова к начальной форме | (единственное | число, именительный падеж).
# Нужен pymorphy2 и русскоязычный словарь для него!
# pip install --user pymorphy2
# Примеры:
# ./wordfreq-morph.py ./text-file.txt | less
# xclip -o | ./wordfreq-morph.py -m
# Проверялся на интерпретаторе:
# Python 3.6.1 on linux
import sys
import sqlite3
import os
import re
import argp... |
_data['request_uri'] = 'https://example.com/testing'
self.assertEqual(url + '/testing', OneLogin_Saml2_Utils.get_self_url(request_data))
def testGetSelfURLNoQuery(self):
"""
Tests the get_self_url_no_query method of the OneLogin_Saml2_Utils
"""
request_data = {
'... | 6 = OneLogin_Saml2_Utils.get_self_url_host(request_data_6) + '/example1/route/test/'
self.assertEqual(url_6, OneLogin_Saml2_Utils.get_self_routed_url_no_query( | request_data_6))
def testGetStatus(self):
"""
Gets the status of a message
"""
xml = self.file_contents(join(self.data_path, 'responses', 'response1.xml.base64'))
xml = b64decode(xml)
dom = etree.fromstring(xml)
status = OneLogin_Saml2_Utils.get_status(dom)
... |
# -*- 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... | ssible payment modes.
"""
class PaymentMode(proto.Enum):
r"""Enum describing possible payment modes."""
UNSPECIFIED = 0
UNKNOWN = | 1
CLICKS = 4
CONVERSION_VALUE = 5
CONVERSIONS = 6
GUEST_STAY = 7
__all__ = tuple(sorted(__protobuf__.manifest))
|
# -*- 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... | RequestCount,
self.currentRequestCount)
# Calculate Request rate
countDiff = self.totalRequestCount - self._lastRequestCount
newReqRate = float(countDiff) / updateDelta
# Calculate average request rate
meanReqRate = self._updateAverage(s... | # Calculate current bitrate
bytesDiff = (self.totalBytesSent - self._lastBytesSent) * 8
newBitrate = bytesDiff / updateDelta
# calculate average bitrate
meanBitrate = self._updateAverage(self._lastUpdateTime, now,
self.currentBitrate, new... |
# -*- 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... | _from_db(ip):
obj = Range.objects.select_related().filter(
start_ip__lte=ip, end_ip__gte=ip
).order_by('end_ip', '-start_ip')[:1][0]
if REDIS_TYPE == 'pk':
return map(lambda k: str(getattr(obj, k).pk), _REC | ORDS_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'].split(',')[0]... |
(k_vars)[k]).pvalue
for k in range(k_vars)]
assert_allclose(pvals, res.pvalues, rtol=5e-10, atol=1e-25)
# label for pvalues in summary
string_use_t = 'P>|z|' if use_t is False else 'P>|t|'
summ = str(res.summary())
assert_(strin... | x = self.exog
np.random.seed(987689)
y = x.sum(1) + np.random.randn(x.shape[0])
self.results = sm.GLM(y, self.exog).fit()
class TestGenericGEEPoisson(CheckGenericMixin):
def setup(self):
#fit for each test, because results will be changed by test
x = s | elf.exog
np.random.seed(987689)
y_count = np.random.poisson(np.exp(x.sum(1) - x.mean()))
groups = np.random.randint(0, 4, size=x.shape[0])
# use start_params to speed up test, difficult convergence not tested
start_params = np.array([0., 1., 1., 1.])
# no sm. import
... |
e)
else:
cache_misses = cachemissarchive.CacheMissArchive(
options.cache_miss_file)
if options.server:
AddDnsForward(server_manager, options.server)
else:
host = platformsettings.get_server_ip_address(options.server_mode)
real_dns_lookup = dnsproxy.RealDnsLookup(
name_servers... | AddDnsProxy(server_manager, options, host, real_dns_lookup, http_archive)
if options.ssl and options.certfile is None:
options.certfile = os.path.join(os.path.dirname(__file__), 'wpr_cert.pem')
AddWebProxy(server_manager, options, host, real_dns_lookup,
http_archive, cache_misses)
Ad... | pt KeyboardInterrupt:
logging.info('Shutting down.')
except (dnsproxy.DnsProxyException,
trafficshaper.TrafficShaperException,
platformsettings.NotAdministratorError,
platformsettings.DnsUpdateError) as e:
logging.critical('%s: %s', e.__class__.__name__, e)
exit_status = 1
... |
Rtn.append((Prepend + FlInf[0], FlInf[1]))
for Dir in self.Dirs.values():
Rtn.extend(Dir.GfeInfCache(LstExts, BegDots, Prepend + Dir.Name + "/"))
return Rtn
def GfeCheckCache(self, Func, Cmd, Path, LstExts, BegDots = False):
TheDir = None
Rtn = None
... | Rtn, | NoEncDat, EncDat = Iface.Prot.Recv()
if NoEncDat[0] != '\0': raise Exception(NoEncDat[1:])
CurStr = NoEncDat[1:]
if Cur.AddInfo[1]:
CurStr = EncDat
NumElem = GetLongStrBytes(CurStr[0:2])
CurStr = Cu |
)
# Consider only x.y.z versions
versions = filter(lambda x: re.match('\d+\.\d+\.\d+', x.name), versions)
default_fix_versions = map(lambda x: fix_version_from_branch(x, versions).name, merge_branches)
for v in default_fix_versions:
# Handles the case where we have forked a release branch but n... | to the master branch and the release branch, we
# only consider the release branch to be the fix version. E.g. it is not valid to have
# both 1.1.0 and 1.0.0 as fix versions.
(major, | minor, patch) = v.split(".")
if patch == "0":
previous = "%s.%s.%s" % (major, int(minor) - 1, 0)
if previous in default_fix_versions:
default_fix_versions = filter(lambda x: x != v, default_fix_versions)
default_fix_versions = ",".join(default_fix_versions)
fix_... |
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
... | elf, test):
print("\n<PASSED::>Test Passed")
super().addSuccess(test)
def addError(self, test, err):
print("\n<ERROR::>Unhandled Exception")
print("\n<LOG:ESC:Error>" + esc(''.join(traceback.format_exception_only(err[0], err[1]))))
print("\n<LOG:ESC:Traceback>" + esc(self._e... | print("\n<LOG:ESC:Failure>" + esc(''.join(traceback.format_exception_only(err[0], err[1]))))
super().addFailure(test, err)
# from unittest/result.py
def _exc_info_to_string(self, err, test):
exctype, value, tb = err
# Skip test runner traceback levels
while tb and self._is_... |
# 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,... | 'PGL_OK':
config['PGL_OK'] = True
# Make sure our git dir and toplevel are fully-qualified
if 'GIT_DIR' in config and not os.path.isabs(config['GIT_DIR']):
git_dir = os.path.join(config['GIT_TOPLEVEL'], config['GIT_DIR'])
config['GIT_DIR'] = os.path.abspath(git_dir)
def warn(msg):
... | sys.stderr.write('%s\n' % (msg,))
def die(msg):
"""Print an error message and exit the program
"""
sys.stderr.write('%s\n' % (msg,))
sys.exit(1)
def do_checks():
"""Check to ensure we've got everything we expect
"""
try:
import argparse
except:
die('Your python must ... |
#!/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... | e given value
:param items: A list of ORM objects to search
:param value: The value to search for, in this case
value can be a username or an email, or an id
"""
foundUser = []
for user in items:
if user.email == value \
| or user.username == value \
or user.id == value:
foundUser.append(user)
if not foundUser:
return None
if len(foundUser)>1:
raise multipleUsersError("Multiple Users", value)
else:
user = foundUser[0]
user.formated... |
from rsk_mind.datasource import *
from rsk_mind.classifier import *
from transformer import CustomTransformer
PROJECT_NAME = 'test'
DATASOURCE= {
'IN' : {
'class' : CSVDataSource,
'params' : ('in.csv', )
},
'OUT' : {
'class' : CSVDataSource,
'params' : ('out.csv', )
}
... | tomTransformer
TRAINING = {
'algorithms' : [
{
'classifier': XGBoostClassifier,
'parameters' : {
'bst:max_depth': 7,
'bst:eta': 0.3,
'bst:subsample': 0.5,
| 'silent': 0,
'objective': 'binary:logistic',
'nthread': 4,
'eval_metric': 'auc'
},
'dataset': DATASOURCE['IN']
}
],
'ensemble': 'max',
'dataset': DATASOURCE['IN']
}
ENGINE = {
} |
np.arange(10), transform=my_trans + ax.transData)
plt.draw()
# enable the transform to raise an exception if it's non-affine transform
# method is triggered again.
my_trans.raise_on_transform = True
ax.transAxes.invalidate()
plt.draw()
def test_external_transform_api():
class ScaledBy(obje... | .axes()
times10 = mtransforms.Affine2D().scale(10)
ax.contourf(np.arange(48).reshape(6, 8), transform=times10 + ax.transData)
ax.pcolormesh(np.linspace(0, 4, 7),
np.linspace(5.5, 8, 9),
np.arange(48).reshape(8, 6),
transform=times10 + ax.transData)
... | ce(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**... |
"""
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 connectio... | flow.client_conn.ssl_established:
# TLS SNI or Host header
flow.request.host = flow.client_conn.connection.get_servername(
) or flow.request.pr | etty_host(hostheader=True)
# If you use a https2http location as default destination, these
# attributes need to be corrected as well:
flow.request.port = 443
flow.request.scheme = "https"
else:
# Host header
flow.request.host = flow.request.pretty_host(hostheader=Tr... |
ew_models_to_pull = build_pullable_view_models_from_data_models(
self.domain, upstream_link, downstream_apps, downstream_fixtures, downstream_reports,
downstream_keywords, timezone, is_superuser=is_superuser
)
view_models_to_push = build_view_models_from_data_models(
... | _pull(type_, self.request.couch_user._id, model_detail=model_detail)
except (DomainLinkError, UnsupportedActionError) as e:
error = str(e)
track_workflow(
self.request.couch_user.username,
"Linked domain: pulled data model",
{"data_model": type_}
... | link.last_pull, timezone)
}
@allow_remote_invocation
def delete_domain_link(self, in_data):
linked_domain = in_data['linked_domain']
link = DomainLink.objects.filter(linked_domain=linked_domain, master_domain=self.domain).first()
link.deleted = True
link.save()
... |
# 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... | izer is not None
class BaseVisualizer(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:
... | else:
raise ValueError("Trying to use stream operator without a tuple (key, value)")
class EmptyVisualizer(BaseVisualizer):
""" A boilerplate visualizer that does nothing """
def add_entry(self, index, key, result, **kwargs):
pass
class ConsoleVisualizer(BaseVisualizer):
""" Prin... |
dient_tape.gradient(microbatch_loss, var_list)
sample_state = self._dp_sum_query.accumulate_record(
sample_params, sample_state, grads)
return sample_state
for idx in range(self._num_microbatches):
sample_state = process_microbatch(idx, sample_state)
grad_su... | if
# we sampled each microbatch from the appropriate binomial distribution,
# although that still wouldn't be quite correct because it would be
# sampling from the dataset without | 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_microb... |
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),
... | self.startDatePicker = wx.DatePickerCtrl(middle_panel, id=wx.ID_ANY, dt=self.start_date)
self.endDateText = wx.StaticText(middle_panel, id=wx.ID_ANY, label="End")
self.endDatePicker = wx.DatePickerCtrl(middle_panel, id=wx.ID_ANY, dt=self.end_date)
self.exportBtn = wx.Button(middle_panel, id=wx... | label="Preview")
self.line_style_combo = wx.ComboBox(middle_panel, value="Line style")
self.line_style_options = ["Line", "Scatter"]
self.line_style_combo.AppendItems(self.line_style_options)
hboxMidPanel.Add(self.startDateText, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL)
hboxMidPan... |
#-*- coding: utf-8 -*-
from openerp.osv import fields, osv
class finance_contract_rachat(osv.osv_memory):
_name = "finance.contract.rachat"
_columns = {
'date': field | s.date('Date de rachat'),
'date_dem': fields.date('Dat | e 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('finance.contract', 'Contrat')
}
def set_rachat(self, cr, uid, ids, context=Non... |
# 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['de | fault']['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'),
},
}
"""
|
from core.serializers import | ProjectSerializer
from rest_framework import generics
from core.models import Project
class ProjectList(generics.ListCreateAPIView):
queryset = Project.objects.all()
serializer_class = ProjectSerializer
class ProjectDetai | l(generics.RetrieveUpdateDestroyAPIView):
queryset = Project.objects.all()
serializer_class = ProjectSerializer
|
# 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... | dency.specs[0]
if required_version:
dependencies_up_to_date.append(dependency)
if latest_version > required_version:
logger.info("There is a new version of %s: %s",
dependency.project_name, latest_version)
elif latest_ve | rsion < required_version:
logger.warning("The requested version for %s is greater "
"than latest found in PyPI: %s",
dependency.project_name, latest_version)
else:
logger.info("The requested version for %s is the l... |
s) to instance ID
self.index = {}
# Boto profile to use (if any)
self.boto_profile = None
# Read settings and parse CLI arguments
self.parse_cli_args()
self.read_settings()
# Make sure that profile_name is not passed at all if not set
# as pre 2.24 boto... | config.has_option('ec2', 'destination_format_tags'):
self.destination_format = config.ge | t('ec2', 'destination_format')
self.destination_format_tags = config.get('ec2', 'destination_format_tags').split(',')
else:
self.destination_format = None
self.destination_format_tags = None
# Route53
self.route53_enabled = config.getboolean('ec2', 'route53')... |
raise GDALException('Unable to read raster source input "{}"'.format(ds_input))
try:
# GDALOpen will auto-detect the data source type.
self._ptr = capi.open_ds(force_bytes(ds_input), self._write)
except GDALException as err:
raise GDALExc... | perty
def skew(self):
"""
Skew of pixels (rotation pa | rameters).
"""
return TransformPoint(self, 'skew')
@property
def extent(self):
"""
Returns the extent as a 4-tuple (xmin, ymin, xmax, ymax).
"""
# Calculate boundary values based on scale and size
xval = self.origin.x + self.scale.x * self.width
y... |
icenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations u... | int(keymd.group('day')),
)
def read(self, ostream=sys | .stdout):
"""Read self into the ostream"""
decompressor = zlib.decompressobj(31)
# Python 2 works with string, python 3 with bytes
remainder = "" if six.PY2 else b""
if self.key.name.endswith(".gz"):
for data in self.key:
remainder += data
... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# v | im: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 i | mport reverse
|
#!/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... | hemes')
# THEME = os.path.join(THEME_DIR, 'Flex')
THEME = 'themes/Flex'
USE_FOLDER_AS_CATEGORY = True
PATH = 'con | tent'
PAGE_PATHS = ['pages']
ARTICLE_PATHS = ['articles']
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
... |
.show3(col=col,Id=[Id,k])
# filebox = b.show3(col=col[k],Id=[Id,k])
chaine = "{<"+filebox+"}\n"
fd.write(chaine)
#chaine = "{<cloud.list}\n"
#fd.write(chaine)
fd.close()
if self.parmsh['display']:
chaine = "geomview -nopanel -b 1 1 1 " + f... | ,self.bd[1,1],self.bd[0,2]],
[self.bd[1,0],self.bd[0,1],self.bd[0,2]],
[self.bd[0,0],self.bd[0,1],self.bd[1,2]],
[self.bd[0,0],self.bd[1,1],self.bd[1,2]],
[self.bd[1,0],self.bd[1,1],self.bd[1,2]],
[self.bd[1,0],self.bd[0,1],self.bd[1,2]]))
... |
if self.ndim == 2:
P=np.array(([self.bd[0,0],self.bd[0,1]],
[self.bd[0,0],self.bd[1,1]],
[self.bd[1,0],self.bd[1,1]],
[self.bd[1,0],self.bd[0,1]]))
return(P)
def coord2bd(self,coord):
"""
Coordinates to boundary
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from datetime import date
from django.conf import settings
def settings_context(request):
"""
M | akes 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 = settings.TAGS_PER_PAGE
except AttributeError:
TAGS_PER_PAGE = ... | PER_PAGE} |
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;"),
migrations.RunSQL("UPDATE django_content_type SET app_label='boo... |
'''
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.... | """
print ("CloudHasher:")
j=getJsonData(url)
if not j:
return False
# pprint.pprint (j)
# climb down into the one branch with all the interesting data:
j=j [HASHER_JSON_PATH[0]] [HASHER_JSON_PATH[1]] [HASHER | _JSON_PATH[2]]
# pprint.pprint (j)
for Jkey, Jfn in HASHER_JSON:
print (Jfn(j[Jkey]), "(%s)" % Jkey)
estimate = (float(j['btc_avail']) / ( float(j['price'])*float(j['accepted_speed'])) )
print ("%.2f days" % estimate, end='')
print ("(remaining btc / order price / hashr... |
#!/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... | 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 = OfflinePredictor(cfg)
NR_PROC = min(multiprocessing.cpu_count() // 2, 8)
... |
# 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:5672/web_develop'
hub = Hub()
def on_message(body, message):
print("Body:'%s', Heade... | ssage.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:
exit(1)
|
#!/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... | er(po)
new = po.header.replace(SOURCE_WARN, new_header)
po.header = new
po.save()
def get_new_header(po):
team = po.metadata.get('Language-Team', None)
if not team:
return TRANSIFEX_HEADER % TRANSIFEX_URL
else:
return TRANSIFEX_HEADER % t | eam
if __name__ == '__main__':
if len(sys.argv)<2:
raise Exception("missing argument: push or pull")
arg = sys.argv[1]
if arg == 'push':
push()
elif arg == 'pull':
pull()
else:
raise Exception("unknown argument: (%s)" % arg)
|
from django.db import migrations, models
class Migration(migrations.Migration):
dependen | cies = [
('organizations', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name | ='organization',
name='logo',
field=models.ImageField(help_text='Please add only .PNG files for logo images. This logo will be used on certificates.', max_length=255, null=True, upload_to='organization_logos', blank=True),
),
]
|
: "22"},
)
def test_eintr_retry(self):
self.assertEqual("foo", paramiko.util.retry_on_signal(lambda: "foo"))
# Variables that are set by raises_intr
intr_errors_remaining = [3]
call_count = [0]
def raises_intr():
call_count[0] += 1
if intr_e... | bug regresses
def test_clamp_value(self):
self.assertEqual(32768, paramiko.util.clamp_value(32767, 32768, 32769))
self.assertEqual(32767, paramiko.util.clamp_value(32767, 32765, 32769))
self.assertEqual(32769, | paramiko.util.clamp_value(32767, 32770, 32769))
def test_config_dos_crlf_succeeds(self):
config_file = StringIO("host abcqwerty\r\nHostName 127.0.0.1\r\n")
config = paramiko.SSHConfig()
config.parse(config_file)
self.assertEqual(config.lookup("abcqwerty")["hostname"], "127.0.0.1")
... |
Some toplevel things are sadly types, and those have an
# isInterface that doesn't mean the same thing as IDLObject's
# isInterface()...
if not isinstance(thing, IDLInterface):
continue
| iface = thing
self.interfaces[iface.identifier.name] = iface
if iface.identifier.name not in config:
# | Completely skip consequential interfaces with no descriptor
# if they have no interface object because chances are we
# don't need to do anything interesting with them.
if iface.isConsequential() and not iface.hasInterfaceObject():
continue
... |
imgPatch = img[row:row+patchSize, col:col+patchSize]
annPatch = ann[row:row+patchSize, col:col+patchSize]
print 'sample#:', counter
print 'original'
print np.unique(annPatch)
print annPatch.flatten()
if random.r... | img_search_string_membraneImages = pathPrefix + 'labels/membranes/' + purpose + '/*.tif'
img_search_string_labelImages = pathPrefix + 'labels/' + purpose + '/*.tif'
img_search_string_grayImages = pathPrefix + 'images/' + purpose + '/*.tif'
#</felix-addition>
img_files_gray = sorted( glob.glob( img_s... | mg_search_string_membraneImages ) )
img_files_labels = sorted( glob.glob( img_search_string_labelImages ) )
print len(img_files_gray)
print len(img_files_membrane)
print len(img_files_labels)
whole_set_patches = np.zeros((nsamples, patchSize**2), dtype=np.float)
whole_set_labels = np.zeros((ns... |
"""
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... | 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 ... | turn ans
t0 = time.time()
print(count_ways(10 ** 25))
t1 = time.time()
print('Total time:', (t1 - t0) * 1000, 'ms')
|
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):
... | y(self.WARNING, *args)
def error(self, *args):
""" Adds a new error to the log """
self._add_entry(self.ERROR, *args)
def _add_entry(self, severity, *args):
"" | " Internal method to append a new entry to the message queue """
content = ' '.join([str(i) for i in args])
self._message_queue.append((severity, content))
print(severity + ":", content, file=sys.stderr)
def report(self):
""" Shows a dialog with all warnings and errors, but only in ... |
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 ... | 'POST':
f | orm = SignupForm(request.POST)
if form.is_valid():
user = form.save()
Player.objects.get_or_create(user=user,
defaults={'date_of_birth': form.cleaned_data.get('date_of_birth'),
'gender': form.cleaned_data.get('gender')})
messages.success(... |
c | lass RegMagic:
fixed_registers = []
regmagic = RegMagic()
__all__ = ['regmagic']
| |
1))
assert ((Create(hs=hs1) * Destroy(hs=hs1)) * BasisKet(1, hs=hs1) ==
BasisKet(1, hs=hs1))
assert (
(Create(hs=hs1) * Destroy(hs=hs1)) * BasisKet(0, hs=hs1) ==
ZeroKet)
def test_expand_ketbra():
"""Test expansion of KetBra"""
hs = LocalSpace('0', basis... | isKet('0', hs=hs), BasisKet('1', hs=hs)),
KetBra(BasisKet('1', hs=hs), BasisKet('0', hs=hs)),
KetBra(BasisKet('1', hs=hs), BasisKet('1', hs=hs)))
def test_orthonormality_fock():
"""Test orthonormality of Fock space BasisKets (including symbo | lic)"""
hs = LocalSpace('tls', basis=('g', 'e'))
i = IdxSym('i')
j = IdxSym('j')
ket_0 = BasisKet(0, hs=hs)
bra_0 = ket_0.dag()
ket_1 = BasisKet(1, hs=hs)
ket_g = BasisKet('g', hs=hs)
bra_g = ket_g.dag()
ket_e = BasisKet('e', hs=hs)
ket_i = BasisKet(FockIndex(i), hs=hs)
ket_j... |
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... | if (a is not None):
ac += ([ALIGN_RIGHT] if ((int is type(k)) or (float is type(k)) or (long is type(k))) else [ALIGN_LEFT])
r += [c]
if (a is not None):
a += [ac]
return (r, (a if (a is not None) else align))
def calcSize(data, header):
widths = range(len(d... | [i])
if (r > widths[i]):
widths[i] = r
r = header[i].count('%')
if (r > percents[i]):
percents[i] = r
for d in data:
for i in range(len(d)):
r = len(d[i])
if (r > widths[i]):
widths[i] = r
... |
# 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... | 'view': 'warehouse.backup.views.import_gz',
'title': 'Импорт',
'text': 'Позволяет восстановить данные из файла. Внимание! Все существующие записи будут безвозвратно утеряны!',
'cls': 'large-4',
},
] |
##### HOME #####
@login_required
def home(request):
return render_to_response('backup/home.html', {'breadcrumbs': breadcrumbs, 'info': info}, RequestContext(request))
##### EXPORT #####
@login_required
def export_gz(request):
filename = 'skill__%s' % time.strftime('%Y%m%d_%H%M%S.gz')
response = Htt... |
#!/usr/bin/env python
import os
from slackclient import SlackClient
BOT_NAME = 'chopbot3000'
s | lack_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')
for user in users:
if 'name' in user and ... | E:
print("Bot ID for '" + user['name'] + "' is " + user.get('id'))
else:
print("could not find bot user with the name " + BOT_NAME)
|
Iterator of :class:`~google.api_core.operation.Operation`
resources within the current instance.
"""
database_filter = _DATABASE_METADATA_FILTER.format(self.name)
if filter_:
database_filter = "({0}) AND ({1})".format(filter_, database_filter)
return self._i... | get_snapshot()
return {
"session_id": session._session_id,
"transaction_id": snapshot._transaction_id,
}
def _get_session(self):
"""Create session as needed.
.. note::
Caller is responsible for cleaning up the session after
all partiti... | e:
session = self._session = self._database.session()
session.create()
return self._session
def _get_snapshot(self):
"""Create snapshot if needed."""
if self._snapshot is None:
self._snapshot = self._get_session().snapshot(
read_timestamp=... |
# 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... | nticate'
conn = HTTPSConnection(host=self.host, port=self.port)
# Send negotiation message
headers[req_header] = (
'NTLM %s' % ntlm.create_NTLM_NEGOTIATE_MESSAGE(self.rawuser))
log.debug('Request headers: %s' % headers)
conn.request('GET', self.authurl, None, header... | ers())
log.debug('Response status: %s %s' % (res.status, res.reason))
log.debug('Response headers: %s' % reshdr)
log.debug('Response data: %s [...]' % res.read(100))
# Remove the reference to the socket, so that it can not be closed by
# the response object (we want to keep the ... |
"""
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... | ebug_toolbar.panels.logger.LoggingPanel',
'debug_toolbar_mongo.panel.MongoDebugPanel' | ,
# Enabling the profiler has a weird bug as of django-debug-toolbar==0.9.4 and
# Django=1.3.1/1.4 where requests to views get duplicated (your method gets
# hit twice). So you can uncomment when you need to diagnose performance
# problems, but you shouldn't leave it on.
# 'debug_toolbar.panel... |
"""
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 imported as a main module.
import __init__
from fabmetheus_utilities.geometry.creation import lineation
from fabmetheus_utili... | eturn modulo
if flo | atValue >= 0:
return floatValue
return floatValue % modulo
def processXMLElement(xmlElement):
"Process the xml element."
lineation.processXMLElementByGeometry(getGeometryOutput(xmlElement), xmlElement)
|
edPoint = np.zeros(2)
rotatedPoint[1] = pivot[1] + np.cos(angle) * (point[1] - pivot[1]) - np.sin(angle) * (point[0] - pivot[0])
rotatedPoint[0] = pivot[0] + np.sin(angle) * (point[1] - pivot[1]) + np.cos(angle) * (point[0] - pivot[0])
return rotatedPoint
# =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
d... | min( int((1.-Mw[2])*Rxdims[0]+1), Rxdims[0]-1 )
Bi[1]= Rxdims[0 | ]
Ti[0]= 0
Ti[1]= max( int( np.ceil(Mw[3]*Rxdims[0]-1) ), 1 ) # These can never be -1.
return Li, Ri, Bi, Ti
# =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
def applyMargins( Rx, Mw, Mr, Mh ):
Rxdims = np.shape(Rx)
if( Mw.count(None) == 0 ):
print(' Zero (or non-zero) margins: L={}, R={}, B={... |
#!/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 | erforms 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')... |
# 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 physic | al values
need to be input for BurnMan to calculate :math:`V_P, V_\Phi, V_S` and density at depth.
*Specifically uses:*
* :class:`burnman.mineral.Mineral`
*Demonstr | ates:*
* how to create your own minerals
"""
import os, sys, numpy as np, matplotlib.pyplot as plt
#hack to allow scripts to be placed in subdirectories next to burnman:
if not os.path.exists('burnman') and os.path.exists('../burnman'):
sys.path.insert(1,os.path.abspath('..'))
import burnman
# A note about uni... |
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"}
... | subtype):
subtype_prefix = self.sSubtypeToCladePrefix[subtype]
names = sorted(name for name in self.mapi_settings.names() if name.startswith(subtype_prefix))
return names
def chart_draw_modify(self, *args, **kw):
self.mapi_settings.chart_draw_modify(*args, **kw)
def chart_draw_... | a"] = CladeData()
# ======================================================================
|
d})
return newword
class Vectorizer(object):
def __init__(self):
self.fit_done = False
def fit(self, input_text, input_scores, max_features=100, min_features=3):
self.spell_corrector = SpellCorrector()
self.stemmer = PorterStemmer()
new_text = self.batch_generate_new_te... | all_token_dict = self.batch_apply(all_token_dict, self.stemmer.stem)
all_token_dict = self.batch_apply | (all_token_dict, self.stemmer.stem)
for i in xrange(0,len(t_tokens)):
for j in xrange(0,len(t_tokens[i])):
t_tokens[i][j] = all_token_dict.get(t_tokens[i][j], t_tokens[i][j])
new_text = [" ".join(t) for t in t_tokens]
return new_text
def generate_new_text(self, t... |
# 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 HardAdjective
else:
return Word
class Adjective(Word):
def _ | _init__(self, word):
self.root = word
_interesting_categories = 'gender number case'.split()
gender = 'm'
case = 1
number = 'sg'
def inflect(self, **props):
gender = props.get('gender', self.gender)
case = int(props.get('case', self.case))
number = props.get('numbe... |
pickler.persistent_id = self.persistent_id
pickler.dump(val)
val = file.getvalue()
lv = len(val)
# We should try to compress if min_compress_len > 0 and we could
# import zlib and this string is longer than our min threshold.
if min_compress_len and _supports_... | server.expect("END")
except (_Error, socket.error), msg:
if isinstance(msg, tuple): msg = msg[1]
server.mark_dead(msg)
return None
return value
try:
| return _unsafe_get()
except _ConnectionDeadError:
# retry once
try:
if server.connect():
return _unsafe_get()
return None
except (_ConnectionDeadError, socket.error), msg:
server.mark_dead(msg)
... |
#!/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... |
class Canvas:
"""Canvas API helper class"""
def __init__(self, parent, width, height, context = "ctx"):
self.obj = context
self.code = [] #stores the code
self.style = {}
self.styleCache = {} #stor | es the previous style applied
self.parent = parent
self.width = width
self.height = height
def write(self, text):
self.code.append("\t" + text.replace("ctx", self.obj) + "\n")
def output(self):
from textwrap import dedent
html = """
<!DOCTYPE html>
... |
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.... | earn>=0.2.4',
'GPy>=1.0.7']
setup(
name='connectopic_mapping',
version='0.3.0',
description='Connectopic mapping',
long_description=long_description,
author='Michele Damian',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Science/Res... | 'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
],
keywords='neuroscience connectopic mapping research',
packages=['... |
ons(self):
return {}
req = Dummy()
req.uri = '/somepath/'
request = ModPythonRequest(req)
request._get = {u'get-key': u'get-value'}
request._post = {u'post-key': u'post-value'}
request._cookies = {u'post-key': u'post-value'}
request._meta = {u'post... | compat cookie may be in use -- check that it has worked
# both as an output string, and using the cookie attributes
self.assertTrue('; httponly' in str(example_cookie))
self.assertTrue(example_cookie['httponly'])
def test_limited_stream(self):
# Read all of a limited stream
... | again returns nothing.
self.assertEqual(stream.read(), '')
# Read a number of characters greater than the stream has to offer
stream = LimitedStream(StringIO('test'), 2)
self.assertEqual(stream.read(5), 'te')
# Reading again returns nothing.
self.assertEqual(stream.readl... |
# -*- 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.]*)/... | if not isinstance(req, six.string_types):
req = req.text
try:
regex = REG | EX % {'name': project.name.replace('+', '\+')}
versions = get_versions_by_regex_for_text(
req, url, regex, project)
except AnityaPluginException:
versions = get_versions_by_regex_for_text(
req, url, DEFAULT_REGEX, project)
return versions
|
#!/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 * ep | silon))
#--- challenge 2
class Rating(Enum):
OXYGEN = 0
CO2 = 1
def get_val(diags, rating):
for i in range(0, len(diags[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_va... |
__(self, *args, **kwargs):
for key, value in kwargs.items():
setattr(self, key, value)
class Publication(BaseObject):
pass
class Issue(BaseObject):
pass
class Location(BaseObject):
def __repr__(self):
return "%s(%s, %s)" % (self.__class__.__name__, str(getattr(self, 'issue_id',... | ne_page_mapper,
polymorphic_identity='c',
primary_key=[page_table.c.id])
session = create_session()
pub = Publication(name='Test')
issu | e = Issue(issue=46,publication=pub)
location = Location(ref='ABC',name='London',issue=issue)
page_size = PageSize(name='A4',width=210,height=297)
magazine = Magazine(location=location,size=page_size)
page = ClassifiedPage(magazine=magazine,page_no=1)
page2 = MagazinePage(magaz... |
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:
... | return ''
def suspend():
import signal
with SuspendCurses():
os.kill(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__(No... |
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,
edit_type=kwargs.pop("edit_type", "colorbars"),
role=kwargs.pop("role", "data") | ,
**kwargs
)
|
# -*- 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 ... | copy.deepcopy(data)
if data['form']['used_context'] is None:
data['form']['used_context'] = {}
data['form']['used_context'].update(
account_financial_report_horizontal_side=side)
return su | per(report_account_common_horizontal, self).get_lines(
data)
def get_left_lines(self, data):
return self.get_lines(data, side='left')
def get_right_lines(self, data):
return self.get_lines(data, side='right')
class ReportFinancial(models.AbstractModel):
_inherit = 'report.acc... |
# coding:utf-8
import 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.route('/list'... | * 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, %s)" % (name, passwd)
cur.execute(sql)
return "ok"
if __name__ == "__main__":
app.run(host="0.0.0.0", debug=True, port=9092) |
"""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... | if seconds > 0:
result += "%d %s " % (seconds, "Second" if (seconds == 1) else "Seconds")
return result.strip()
def get_datetime_from_timestamp(timestamp):
"""Return datetime from unix timestamp"""
try:
return datetime.fromtimestamp(int(timestamp))
except:
return None
def g... | esponse.headers['X-RateLimit-Period']
if not periods:
return []
rate_limits = []
periods = periods.split(',')
limits = response.headers['X-RateLimit-Limit'].split(',')
remaining = response.headers['X-RateLimit-Remaining'].split(',')
reset = response.headers['X-RateLimit-Reset'].split('... |
from .manager import Manag | er
__v | ersion__ = '0.2.4'
|
#
# 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... | applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""
MsSQL to GCS opera... | viders.microsoft.mssql.hooks.mssql import MsSqlHook
from airflow.utils.decorators import apply_defaults
class MSSQLToGCSOperator(BaseSQLToGCSOperator):
"""Copy data from Microsoft SQL Server to Google Cloud Storage
in JSON or CSV format.
:param mssql_conn_id: Reference to a specific MSSQL hook.
:type... |
#!/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")... | rtResourceCalledIgnoreEarlier('Execute',
('ambari-python-wrap', '/usr/bin/hdp-select', 'set', 'kafka-broker', version), sudo=True,)
self.assertResourceCalled("Link", "/etc/kafka/conf", to="/usr/hdp/current/kafka-broker/conf")
self.assertNoMoreResources()
self.assertEquals(1, ... | als(1, mocks_dict['checked_call'].call_count)
self.assertEquals(
('ambari-python-wrap', '/usr/bin/conf-select', 'set-conf-dir', '--package', 'kafka', '--stack-version', '2.3.0.0-1234', '--conf-version', '0'),
mocks_dict['checked_call'].call_args_list[0][0][0])
self.assertEquals(
('ambari-pyth... |
"""
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):
... | elif host:
kwargs['host'] = host
if password:
kwargs['password'] = password
return PostgreSQLDriver, [], kwargs
else:
raise ValueError('Unknown driver %s' % dsn_string)
|
def get_driver(dsn_string):
driver, args, kwargs = parse_dsn(dsn_string)
return driver(*args, **kwargs)
|
#!/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[... | oot.name")
submitCmd += " %s" % nuke.Root.firstFrame(nuke.root())
submitCmd += " %s" % nuke.Root.lastFrame(nuke.root())
writeNodes = [i for i in nuke.allNodes() if i.Class() == "Write"]
for i in wri | teNodes:
submitCmd += " %s %s" % (i['name'].value(), nuke.filename(i))
print( "nukeStub(): %s" % submitCmd )
os.system(submitCmd)
menubar = nuke.menu("Nuke")
m = menubar.addMenu("&Render")
m.addCommand("Submit to Farm", "nukeStub.launchSubmit()", "Up")
|
from extractors.extract_website import ExtractWebsite
from datawakestreams.extractors.extractor_bolt import ExtractorBolt
class WebsiteBolt(ExtractorBolt):
name | ='website_extractor'
def __init__(self):
ExtractorBolt.__init__(self)
self.extractor = ExtractW | ebsite()
|
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):
... | (dump_only=True)
amount = fields.Float(required=True)
source_account = fields.Nested(AccountSchema, dump_only=True, only=('id', 'name'))
source_account_id = fields.Int(required=True, load_only=True, load_from='source_account')
target_account = fields.Nested(AccountSchema, dump_only=True, only=('id', '... | 'last_name', 'email')
)
currency = fields.Nested(GroupCurrencySchema, dump_only=True, only=('id', 'name'))
currency_id = fields.Int(required=True, load_only=True, load_from='currency')
description = fields.Str()
date = fields.DateTime()
class RecordSchema(Schema):
id = fields.Int(dump_only=... |
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(... | a4fc12f4813d459bc75228b64ad08617c7'))
self.assertTrue(is_hash256_str('2A5C3F4062E4F2FCCE7A1C7B4310CB647B327409F580F4ED72CB8FC0B1804DFA'))
self.assertTrue(is_hash256_str('00' * 32))
self.assertFalse(is_hash256_str('00' * 33))
self.assertFalse(is_hash256_str('qweqwe'))
self.assert... | rtFalse(is_hash256_str(7))
def test_chunks(self):
self.assertEqual([[1, 2], [3, 4], [5]],
list(chunks([1, 2, 3, 4, 5], 2)))
with self.assertRaises(ValueError):
list(chunks([1, 2, 3], 0))
|
User-Agent': get_user_agent(),
'Cache-Control': 'no-cache',
})
self.multipart_session.auth = fetch_credentials(auth_id, auth_token)
self.proxies = proxies
self.timeout = timeout
self.account = Accounts(self)
self.subaccounts = Subaccounts(self)
self.ap... | f.numbers = Numbers(self)
self.powerpacks = Powerpacks(self)
self.brand = Brand(self)
self.campaign = Campaign(self)
self.media = Media(self)
self.pricing = Pricings(self)
self.recordings = Recordings(self)
self.addresses = Addresses(self)
self.identities ... | self)
self.compliance_document_types = ComplianceDocumentTypes(self)
self.compliance_documents = ComplianceDocuments(self)
self.compliance_requirements = ComplianceRequirements(self)
self.compliance_applications = ComplianceApplications(self)
self.multi_party_calls = MultiPartyCa... |
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... | # the time at which last tick occured
def tick():
# Alternate positive and negative pulses
global positive_polarity
if positive_polarity:
pu | lse(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.outp... |
htsteelblue, lightyellow, lime, limegreen,
linen, magenta, maroon, mediumaquamarine,
mediumblue, mediumorchid, mediumpurple,
mediumseagreen, mediumslateblue, mediumspringgreen,
mediumturquoise, mediumvioletred, midnightblue,
mintcream, mist... | "Open Sans", "Overpass", "PT Sans
Narrow", "Raleway", "Times New Roman".
familysrc
Sets the source reference on Chart Studio Cloud
for family .
size
sizesrc
Sets the source reference on ... | Returns
-------
plotly.graph_objs.area.hoverlabel.Font
"""
return self["font"]
@font.setter
def font(self, val):
self["font"] = val
# namelength
# ----------
@property
def namelength(self):
"""
Sets the default length (in number of ... |
# 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... | nQuery(instance_id, predicted_proba,
suggested_label, suggested_family, confidence=confidence)
def getPredictedProbabilities(self):
models_conf = self.iteration.conf.models_conf
if 'binary' in models_conf:
classifier = self.iteration.update_model.models['b... | lse:
test_instances = self.iteration.datasets.getTestInstances()
num_instances = test_instances.numInstances()
predictions = pd.DataFrame(
np.zeros((num_instances, 4)),
index=test_instances.ids.getIds(),
columns=['predicted_proba', 'pre... |
che['slopes']
except AttributeError:
self._cache = {}
self._cache['slopes'] = self.betas[1:] * self.scale
except KeyError:
self._cache['slopes'] = self.betas[1:] * self.scale
return self._cache['slopes']
@slopes.setter
def slopes(self, val):
... | P * np.log(P) + (1 - P) * np.log(1 - P)) - self.logl))
self._cache['LR'] = (LR, chisqprob(LR, self.k))
return self._cache['LR']
@LR.setter
def LR(self, val):
try:
| self._cache['LR'] = val
except AttributeError:
self._cache = {}
self._cache['LR'] = val
@property
def u_naive(self):
try:
return self._cache['u_naive']
except AttributeError:
self._cache = {}
self._cache['u_naive']... |
se, None, {})
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'ddosCustomPolicyName': self._serialize.url("ddos_custom_policy_name", ddos_custom_policy_name, 'str'),
'subscriptionId': self._serialize.url(... | : Parameters supplied to the create or update operation.
:type parameters: ~azure.mgmt.network.v2020_07_01.models.DdosCustomPolicy
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller fr... | itialized polling object for a personal polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling |
from .MidiOutFile import MidiOutFile
from .MidiInFile import MidiInFile
"""
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 > 1 | 27:
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, velocity=0x40):
note = self._trans... |
# 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 ... | ror_text(self._nmap_scan_result)
nmap_report = ET.parse(self._nmap_scan_result)
root_tree = nmap_report.getroot()
for element in root_tree:
try:
assert element.tag == 'host'
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.attrib['addr']
if address.attrib['addrtype'] == 'mac'... |
# -*- 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... | as core_exceptions # type: ignore
from google.api_core import gapic_v1 # type: ignore
from google.api_core | import retry as retries # type: ignore
from google.auth import credentials as ga_credentials # type: ignore
from google.oauth2 import service_account # type: ignore
from google.ads.googleads.v10.services.types import remarketing_action_service
try:
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
... |
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: str, key: str) -> str:
msg = sanitize(msg)
key = sanitize(key)
repeat = int(math... | g: str, 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,... | d in Movies 1
encrypted_msg = 'oape dhzoawx cz hny'
guessed_key = 'plum scarlett green mustard'
print(decrypt(encrypted_msg, guessed_key))
# Used in Movies 3
# decrypted_msg = 'metropolis'
# film_key = 'Close Encounters Of The Third Kind'
# print(encrypt(decrypted_msg, film_key)) |
#!/usr/bin/env python
# pylint: disable=invalid-name
"""
2520 is th | e smallest number that can be divided by each of the numbers from 1 t | o 10 without any remainder.
What is the smallest positive number 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):
... |
lambda: 0)
self.add_words(word_list)
self.widgets = set()
def add_widget(self, widget):
"""Add a widget to the list of widgets to do auto-completion for."""
if widget in self.widgets:
return # Widget already added
if isinstance(widget, TextBox):
self... | ile you type')
display_name = _('AutoCompletor')
version = 0.1
# INITIALIZERS #
def __init__(self, internal_name, main_controller):
self.internal_name = internal_name
self.main_controller = main_controller
self._init_plugin()
def _init_plugin(self):
from virtaal.co... | self.autocomp = AutoCompletor(self.main_controller)
self._store_loaded_id = self.main_controller.store_controller.connect('store-loaded', self._on_store_loaded)
if self.main_controller.store_controller.get_store():
# Connect to already loaded store. This happens when the plug-in is enabl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.