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 |
|---|---|---|---|---|---|---|---|---|
newsapps/cloud-commander | cloud_commander/assets.py | Python | mit | 1,248 | 0.007212 | """
Asset upload and deletion
# from http://django-command-extensions.googlecode.com/svn/trunk/django_extensions/management/commands/sync_media_s3.py
"""
import boto
import subprocess
def push_assets(settings):
"""
Push the assets directory to s3
"""
print "Stashing assets folder someplace safe..."
... | ame):
"""
Open a connection to S3 and return a bucket and a key
"""
conn = boto.connect_s3(settings['access_key'], settings['secret_key'])
bucket = conn.get_bucket(bucket_name)
key = boto.s3.key.Key(bucket, key_name)
return bucket, key
def remove_assets(settings):
"""
Remove the tem... | s.tgz")
key.delete()
|
girving/tensorflow | tensorflow/python/ops/special_math_ops_test.py | Python | apache-2.0 | 14,571 | 0.007687 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | .]
x_one_half = [2, 1.]
with self.session(use_gpu=True):
ph = array_ops.placeholder(dtypes.float32)
beta_ph = math_ops.exp(special_math_ops.lbeta(ph))
self.assertAllClose(1, beta_ph.eval(feed_dict={ph: x_one}))
self.assertAllClose(0.5,
beta_ph.eval(feed_dict={ph... | 1
# Gamma(1 + 1 + 1 + 1) = Gamma(4) = 3! = 6
# ==> Beta([1, 1, 1, 1])
# = Gamma(1) * Gamma(1) * Gamma(1) * Gamma(1) / Gamma(1 + 1 + 1 + 1)
# = 1 / 6
expected_beta_x = 1 / 6 * np.ones((3, 2, 3))
with self.session(use_gpu=True):
x_ph = array_ops.placeholder(dtypes.float32, [3, 2, 3,... |
blakev/sowing-seasons | summer/forms/blog.py | Python | mit | 1,095 | 0.004566 | import json
from wtforms.fields import StringField, HiddenField, TextAreaField, FileField, BooleanField
from wtforms.validators import DataRequired
from wtforms_tornado import Form
class BlogPostForm(Form):
topic = StringField('General topic')
keywords = StringField('Keywords')
title = StringField('Title... | author = StringField('Author', validators=[DataRequired()], default='Blake VandeMerwe')
pmeta = TextAreaField('Meta', validators=[DataRequired()], default='{}')
summary = TextAreaField('Summary', validators=[DataRequired()])
content = TextAreaField('Content', validators=[DataRequired()])
banner = Fil... | clear_statics = BooleanField('Clear statics?')
clear_banner = BooleanField('Clear banner?')
def validate_pmeta(form, field):
try:
if field.data is not None and len(field.data) > 0:
json.loads(field.data)
except Exception as e:
raise e
|
weka-io/easypy | easypy/predicates.py | Python | bsd-3-clause | 3,401 | 0.001764 | class Predicate(object):
def test(self, obj):
raise NotImplementedError()
def __call__(self, obj):
return self.test(obj)
def __eq__(self, obj):
return self.test(obj)
def __ne__(self, obj):
return not self == obj
def __and__(self, other):
return And(self, ... | cribe(self, variable="X"):
| return self._describe(variable) + "?"
def _describe(self, variable):
raise NotImplementedError()
class FunctionPredicate(Predicate):
def __init__(self, func, description=None):
super(FunctionPredicate, self).__init__()
self.func = func
if description is None:
... |
blue-yonder/tsfresh | tests/units/feature_extraction/test_feature_calculations.py | Python | mit | 83,172 | 0.001816 | # -*- coding: utf-8 -*-
# This file as well as the whole tsfresh package are licenced under the MIT licence (see the LICENCE.txt)
# Maximilian Christ (maximilianchrist.com), Blue Yonder Gmbh, 2016
import math
import warnings
from random import shuffle
from unittest import TestCase
from matrixprofile.exceptions import... | _result, result
| ),
)
expected_result = f(pd.Series(input_to_f, dtype="float64"), *args, **kwargs)
self.assertAlmostEqual(
expected_result,
result,
msg="Not almost equal for pandas.Series: {} != {}".format(
expected_result, result
),
... |
armstrong/armstrong.utils.backends | setup.py | Python | apache-2.0 | 1,307 | 0.000765 | # Nothing in this file should need to be edited.
# Use package.json to adjust metadata about this package.
# Use MANIFEST.in to include package-specific data files.
import os
import json
from setuptools import setup, find_packages
info = json.load(open(" | ./package.json"))
def generate_namespaces(package):
i = package.count("." | )
while i:
yield package.rsplit(".", i)[0]
i -= 1
NAMESPACE_PACKAGES = list(generate_namespaces(info['name']))
if os.path.exists("MANIFEST"):
os.unlink("MANIFEST")
setup_kwargs = {
"author": "Bay Citizen & Texas Tribune",
"author_email": "dev@armstrongcms.org",
"url": "http://githu... |
katakumpo/noscrapy | noscrapy/tests/test_queue.py | Python | mit | 587 | 0.003407 | from noscrapy i | mport Job, Queue
def test_add_jobs():
q = Queue()
job = Job('http://test.lv/', {})
q.add(job)
assert 1 == q.get_queue_size()
assert 'http://test.lv/' == q.jobs[0].url
def test_mark_urls_scraped():
| q = Queue()
job = Job('http://test.lv/', {})
q.add(job)
q.get_next_job()
assert 0 == q.get_queue_size()
# try add this job again
q.add(job)
assert 0 == q.get_queue_size()
def test_reject_documents():
q = Queue()
job = Job('http://test.lv/test.doc')
assert not q.add(job)
a... |
andela-sjames/Django-ReactJS-Library-App | reactlibapp/libraryapp/admin.py | Python | mit | 145 | 0 | # from django.contrib import admin
# from libraryapp.models import Author, Bo | ok, Interest, History, G | oogleUser, \
# Category, Ratings, Quote
|
bourneagain/pythonBytes | socketProgramming/socketSelect.py | Python | mit | 410 | 0.002439 | __author__ = 'sam'
import select
import socket
import sys
import Queue
# Creat | e a TCP/IP socket
server = socket.soc | ket(socket.AF_INET, socket.SOCK_STREAM)
server.setblocking(0)
# Bind the socket to the port
server_address = ('localhost', 12345)
print >>sys.stderr, 'starting up on %s port %s' % server_address
server.bind(server_address)
# Listen for incoming connections
while True:
server.listen(5)
|
konieboy/Seng_403 | Gender Computer/nameparser/parser.py | Python | gpl-3.0 | 26,481 | 0.00827 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import sys
from nameparser.util import u
from nameparser.util import text_types, binary_type
from nameparser.util import lc
from nameparser.util import log
from nameparser.config import CONSTANTS
from nameparser.config import Constants
ENCODING = 'utf-8... | lower case unicode representation is the same.
| """
return (u(self)).lower() == (u(other)).lower()
def __ne__(self, other):
return not (u(self)).lower() == (u(other)).lower()
def __getitem__(self, key):
if isinstance(key, slice):
return [getattr(self, x) for x in self._members[key]]
else:
... |
popazerty/enigma2 | lib/python/Screens/CronTimer.py | Python | gpl-2.0 | 18,099 | 0.028455 | from Components.ActionMap import ActionMap
from Components.config import getConfigListEntry, config, ConfigSubsection, ConfigText, ConfigSelection, ConfigInteger, ConfigClock, NoSave
from Components.ConfigList import ConfigListScreen
from Components.Console import Console
from Components.Label import Label
from Compone... | 'crond')).strip('[]')
self['labrun'].hide()
self['labstop'].hide()
self['labactive'].hide()
self['labdisabled'].hide()
self.my_cr | ond_active = False
self.my_crond_run = False
if path.exists('/etc/rc3.d/S20busybox-cron'):
self['labdisabled'].hide()
self['labactive'].show()
self.my_crond_active = True
else:
self['labactive'].hide()
self['labdisabled'].show()
if crond_process:
self.my_crond_run = True
if self.my_crond_run... |
LyleMi/Trafficker | Trafficker/handlers/tcp.py | Python | mit | 575 | 0.001739 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from Trafficker.handlers.tc | pflow import TCPFlow
def tcpHandler(packetNum, packet, glob):
tcp = None
for l in packet.layers:
if l.name == "TCP":
tcp = l
if tcp is None:
return glob
# print(repr(tcp))
if 'tcpflow' not in glob:
glob['tcpflow'] = []
if tcp.syn and not tcp.ack:
glo... | (tcp)
break
return glob
|
darkfoxprime/foxCAT | src/commonLib.py | Python | isc | 2,350 | 0.016596 |
# flgLib is needed for StateMachine
from flgLib import *
# common superclass for flg and fpg drivers to implement the expression
# handling functions
class commonLib(object):
# exprXYZ() functions return ExprXYZ() objects invoked with the same
# arguments.
def exprOper(self, *args):
__ret = tuple(args)... | turn __ret
def exprNumber(self, *args):
__ret = int(args[0])
return __ret
def exprPosParam(self, *args):
__ret = (u'$', int(args[0][1:]))
return __ret
def exprFuncCall(self, *args):
__ret = (u'(', args[0], list(arg | s[1]))
return __ret
# handle processDirective. Expects to find 'allowed_directives' declared in 'self'.
def processDirective(self, directive, value):
if directive not in self.allowed_directives:
raise ActionFailedException("Unknown directive %s %s" % (directive, repr(value)))
elif directive == u... |
econchick/tissue | docs/conf.py | Python | mit | 8,249 | 0.006061 | # -*- coding: utf-8 -*-
#
# tissue documentation build configuration file, created by
# sphinx-quickstart on Wed Sep 25 14:35:35 2013.
#
# 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... | es = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# If | true, do not generate a |
fengyunsixing/Android | lib/andbug/log.py | Python | gpl-3.0 | 6,290 | 0.016209 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
## Copyright 2011, IOActive, Inc. All rights reserved.
##
## AndBug is free software: you can redistribute it and/or modify it under
## the terms of version 3 of the GNU Lesser General Public License as
## published by the Free Software Foundation.
##
## AndBug is distr... | f.readEvent() # Again..
tag, time, meta = line.split(' ', 3)
time = int(time)
data = []
while True:
line = self.readLine()
if line.startswit | h( ' ' ):
data.append(line)
else:
self.pushLine(line)
break
if data:
data = parse_hex('\n'.join(data))
else:
data = ''
return LogEvent(time, tag, meta, data)
def cur_file_dir():
#获取脚本路径
... |
aadithpm/code-a-day | py/String Incrementer.py | Python | unlicense | 744 | 0.009409 | """
Your job is to write a function which increments a string, to create a new string. If the string already ends with a number, the number should be incremented | by 1. If the string does not end with a number the number 1 should be appended to the new string.
Examples:
foo -> foo1
foobar23 -> foobar24
foo0042 -> foo0043
foo9 -> foo10
foo099 -> foo100
Attention: If the number has leading zeros the amount of digits should be considered.
"""
import re
def increment_string... | atch.group(1)
number = match.group(2)
if not number:
return string + '1'
else:
return string + str(int(number)+1).zfill(len(number))
|
fim/keymaker | keymaker/core/forms.py | Python | bsd-2-clause | 1,379 | 0.007977 | from django import forms
from django.forms.models import inlineformset_factory
from keymaker.core.models import CSR, PrivateKey, Certificate, Subject
import M2Crypto
class PrivateKeyForm(forms.ModelForm):
class Meta:
model = PrivateKey
exclude = ['data']
class CSRForm(forms.Mode | lForm):
class Meta:
model = CSR
exclude = ['data']
class SubjectForm(forms.ModelForm):
class Meta:
model = Subject
exclude = []
class CertificateForm(forms.ModelForm):
| password = forms.CharField(widget=forms.PasswordInput(), label="Password", required=False)
password2 = forms.CharField(widget=forms.PasswordInput(), label="Password (again)", required=False)
signing_ca = forms.ModelChoiceField(queryset=Certificate.objects.filter(is_ca=True),
required=False, label="... |
golismero/golismero | thirdparty_libs/dns/query.py | Python | gpl-2.0 | 17,913 | 0.001842 | # Copyright (C) 2003-2007, 2009-2011 Nominum, Inc.
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose with or without fee is hereby granted,
# provided that the above copyright notice and this permission notice
# appear in all copies.
#
# THE SOFTWARE IS PROVIDED "... | timeout: float
@return True on success, False on timeo | ut
"""
event_mask = 0
if readable:
event_mask |= select.POLLIN
if writable:
event_mask |= select.POLLOUT
if error:
event_mask |= select.POLLERR
pollable = select.poll()
pollable.register(fd, event_mask)
if timeout:
event_list = pollable.poll(long(timeout... |
chienlieu2017/it_management | odoo/addons/stock_landed_costs/tests/__init__.py | Python | gpl-3.0 | 72 | 0 | # | -*- coding: utf-8 -*-
from . import tes | t_stock_landed_costs_purchase
|
gfarnadi/FairPSL | debug/compare_map/compare.py | Python | mit | 2,282 | 0.007888 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from os.path import join as ojoin
import numpy as np
import sys
def read_accept(path):
outdict = dict()
with open(path) as f:
for line in f:
line = line.strip()
if not line: continue
line = line.split()
pape... | d_present(path):
outdict | = dict()
with open(path) as f:
for line in f:
line = line.strip()
if not line: continue
line = line.split()
author = line[0][1:-1]
truth = float(line[1])
outdict[author] = truth
return outdict
def read_review(path):
outdict = ... |
shashidharatd/test-infra | gubernator/view_pr.py | Python | apache-2.0 | 8,659 | 0.002656 | # Copyright 2016 The Kubernetes 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 obt | ain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the... |
alfa-jor/addon | plugin.video.alfa/core/tmdb.py | Python | gpl-3.0 | 77,962 | 0.004122 | # -*- coding: utf-8 -*-
import copy
import re
import sqlite3
import time, urllib
from core import filetools
from core import httptools
from core import jsontools
from core import scrapertools
from core.item import InfoLabels
from platformcode import config
from platformcode import logger
# -----------... | b.sqlite")
| tmdb_langs = ['es', 'en', 'it', 'pt', 'fr', 'de']
langs = config.get_setting('tmdb_lang', default=0)
tmdb_lang = tmdb_langs[langs]
def create_bd():
conn = sqlite3.connect(fname)
c = conn.cursor()
c.execute('CREATE TABLE IF NOT EXISTS tmdb_cache (url TEXT PRIMARY KEY, response TEXT, added TEXT)')
... |
khchine5/lino | lino/modlib/checkdata/models.py | Python | bsd-2-clause | 10,733 | 0.001118 | # Copyright 2015-2017 Luc Saffre
# License: BSD (see file COPYING for details)
"""
Database models for `lino.modlib.checkdata`.
.. autosummary::
"""
from __future__ import unicode_literals, print_function
import six
from builtins import object
from builtins import str
from collections import OrderedDict
from djang... | k = obj.checker
owner = obj.owner
if owner is None:
# A problem where owner is None means that the owner
# has been deleted.
obj.delete()
else:
qs = Problem.objects.filter(
**gfk2loo | kup(Problem.owner, owner, checker=chk))
qs.delete()
chk.update_problems(owner, False, fix)
ar.set_response(refresh_all=True)
class FixProblem(UpdateProblem):
label = _("Fix data problems")
fix_them = True
sort_index = 91
class UpdateProblemsByController(dd.Action)... |
rimusz/helm-charts | stable/prometheus-operator/hack/sync_grafana_dashboards.py | Python | apache-2.0 | 4,533 | 0.001765 | #!/usr/bin/env python3
"""Fetch dashboards from provided urls into this chart."""
import json
import textwrap
from os import makedirs, path
import requests
import yaml
from yaml.representer import SafeRepresenter
# https://stackoverflow.com/a/20863889/961092
class LiteralStr(str):
pass
def change_style(style, ... | n': condition_map.get(r | esource_name, ''),
}
filename_struct = {resource_name + '.json': (LiteralStr(content))}
# rules themselves
lines += yaml_str_repr(filename_struct)
# footer
lines += '{{- end }}'
filename = resource_name + '.yaml'
new_filename = "%s/%s" % (destination, filename)
# make sure direct... |
hhstore/tornado-annotated | src/tornado-1.0.0/tornado/web.py | Python | mit | 66,814 | 0.000453 | #!/usr/bin/env python
# -*- coding: utf8 -*-
"""The Tornado web framework.
核心模块, 参考示例使用代码:
- 重要模块:
- tornado.web
- tornado.ioloop # 根据示例,可知入口在此.参看: ioloop.py
- tornado.httpserver
The Tornado web framework looks a bit like web.py (http://webpy.org/) or
Google's webapp (http://cod... | connection_close() 调用时机
@property
def settings(self):
return self.application.settings
# 如下这部分, 默认的接口定义, 如果子类没有覆写这些方法,就直接抛出异常.
# 也就是说: 这些接口, 必须要 覆写,才可以用
def | head(self, *args, **kwargs):
raise HTTPError(405)
def get(self, *args, **kwargs):
raise HTTPError(405)
def post(self, *args, **kwargs):
raise HTTPError(405)
def delete(self, *args, **kwargs):
raise HTTPError(405)
def put(self, *args, **kwargs):
raise HTTPErro... |
aerospike/aerospike-client-python | examples/client/get_nodes.py | Python | apache-2.0 | 3,660 | 0.000273 | # -*- coding: utf-8 -*-
##########################################################################
# Copyright 2013-2021 Aerospike, 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
#
# ... | ---------------
# Perform Operation
# ----------------------------------------------------------------------------
try:
response = client.get_nodes()
if response is not None:
print(response)
print("---")
else:
print('error: Not Found.', file=sys.... | ----------------------------------------------
# Close Connection to Cluster
# ----------------------------------------------------------------------------
client.close()
except Exception as eargs:
print("error: {0}".format(eargs), file=sys.stderr)
exitCode = 3
###################################... |
bthirion/nipy | examples/tissue_classification.py | Python | bsd-3-clause | 3,308 | 0.00393 | #!/usr/bin/env python
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
""" Script example of tissue classification
"""
from __future__ import print_function # Python 2/3 compatibility
import numpy as np
from nipy import load_image, save_image
from nipy.... | return dices
for k in range(3):
pk = gold_ppm[mask][:, k]
qk = ppm[mask][:, k]
PQ = np.sum(np.sqrt(np.maximum(pk * qk, 0)))
P = np.sum(pk)
Q = np.sum(qk)
dices[k] = 2 * PQ / float(P + Q)
return dices
# | Parse command line
description = 'Perform brain tissue classification from skull stripped T1 \
image in CSF, GM and WM. If no mask image is provided, the mask is defined by \
thresholding the input image above zero (strictly).'
parser = ArgumentParser(description=description)
parser.add_argument('img', metavar='img',... |
OpenUpgrade-dev/OpenUpgrade | addons/fleet/migrations/8.0.0.1/post_migration.py | Python | agpl-3.0 | 1,304 | 0 | # -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# This module copyright (C) 2014 Akretion
# (<http://www.akretion.com>).
#
# This program is free software: you can redistribute it and/or modify
# it unde... | 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 Affero General Public License for more details.
#
# You should have received a copy o | f the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp import pooler, SUPERUSER_ID
from openerp.openupgrade import openupgrade, openupgrade_80
@openupgrade.migrate... |
molmod/hipart | hipart/gint/tests/test_gaux.py | Python | gpl-3.0 | 1,117 | 0.000895 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# HiPart is a program to analyze the electronic structure of molecules with
# f | uzzy-atom partitioning methods.
# Copyright (C) 2007 - 2012 Toon Verstraelen <Toon.Verstraelen@UGent.be>
#
# This file is part of HiPart.
#
# HiPart 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 versi... | mplied 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/>
#
#--
from hipart.gint.gint_ext import gaux
impo... |
jordanemedlock/psychtruths | temboo/core/Library/Zendesk/Organizations/DeleteOrganization.py | Python | apache-2.0 | 4,028 | 0.004965 | # -*- coding: utf-8 -*-
###############################################################################
#
# DeleteOrganization
# Deletes an existing organization.
#
# Python versions 2.6, 2.7, 3.x
#
# Copyright 2014, Temboo Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this... | ooSession object, containing a valid
set of Temboo credentials, must be supplied.
"""
super(DeleteOrganization, self).__init__(temboo_session, '/Library/Zendesk/Organizations/DeleteOrganization')
def new_input_set(self):
return DeleteOrganizationInputSet()
def _make_result_set... | n DeleteOrganizationChoreographyExecution(session, exec_id, path)
class DeleteOrganizationInputSet(InputSet):
"""
An InputSet with methods appropriate for specifying the inputs to the DeleteOrganization
Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
"""
... |
grantcolasurdo/geras | age/die.py | Python | gpl-2.0 | 666 | 0 | """The die rolls are what makes the world go round"""
import random
import re
__author__ = "Grant Colasurdo"
class DieString:
def __init__(self, string: st | r):
self.string = string
self.die_list = []
number_of_die = string[:string.find('d')]
sides_on_die = int(string[string.find('d')+1:])
self.die_list = int(number_of_die) * [Die(sides_on_die)]
def roll(self) -> int:
return sum(die. | roll() for die in self.die_list)
class Die:
def __init__(self, sides: int):
self.sides = sides
def roll(self) -> int:
return random.randint(1, self.sides)
def make_roll(string: str):
pass
|
fbudin69500/SlicerPythonPlayground | test/CreateSamples/CreateSamples.py | Python | apache-2.0 | 9,951 | 0.008642 | import os
import unittest
from __main__ import vtk, qt, ctk, slicer
from slicer.ScriptedLoadableModule import *
import logging
#
# CreateSamples
#
class CreateSamples(ScriptedLoadableModule):
"""Uses ScriptedLoadableModule base class, available at:
https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/S... | llapsibleButton()
generalParametersCollapsibleButton.text = "General parameters"
self.layout.addWidget(generalParametersCollapsibleButton)
# Layout within the dummy collapsible button
hlayout = qt.QHBoxLayout(generalParametersCollapsibleButton)
self.label=qt.QLabel("Volume Name:")
| hlayout.addWidget(self.label)
self.volumeNameLine=qt.QLineEdit()
hlayout.addWidget(self.volumeNameLine)
self.volumeNameLine.connect('textChanged(QString)', self.onLabelChanged)
#
# Parameters Area
#
parametersCollapsibleButton = ctk.ctkCollapsibleButton()
parametersCollapsibleButton... |
ypersyntelykos/GitSavvy | common/util/debug.py | Python | mit | 893 | 0 | import json
_log = []
enabled = False
def start_logging():
global _log
global enabled
_log = []
enabled = True
def stop_logging():
global enabled
enabled = False
def get_log():
return json.dumps(_log, indent=2)
def add_to_log(obj):
if enabled:
| _log | .append(obj)
def log_git(command, stdin, stdout, stderr):
add_to_log({
"type": "git",
"command": command,
"stdin": stdin,
"stdout": stdout,
"stderr": stderr
})
def log_error(err):
add_to_log({
"type": "error",
"error": repr(err)
})
de... |
angr/angr | angr/procedures/win32/InterlockedExchange.py | Python | bsd-2-clause | 525 | 0.009524 | import angr
class InterlockedExchange(angr.SimProcedure):
def run(self, target, value): #pylint:disable=arguments-differ
if not self.state.solver.symbolic(target):
old_value = self.state.memory.load(target, 4, en | dness=self.state.arch.memory_endness)
self.state.memory.store(target, value)
else:
old_value = self.state.solver.Unconstrained("unconstrained_ret_%s" % self.display_name, self.state.arch.bits, k | ey=('api', 'InterlockedExchange'))
return old_value
|
yafeunteun/wikipedia-spam-classifier | revscoring/revscoring/languages/italian.py | Python | mit | 3,540 | 0 | from .features import Dictionary, RegexMatches, Stemmed, Stopwords
name = "italian"
try:
import enchant
dictionary = enchant.Dict("it")
except enchant.errors.DictNotFoundError:
raise ImportError("No enchant-compatible dictionary found for 'it'. " +
"Consider installing 'myspell-it'.... | or("Could not load stemmer for {0}. ".format(__name__))
stemmed = Stemmed(name + ".stemmed", stemmer.stem)
"""
:class:`~revscoring.languages.features.Stemmed` word features via
:class:`nltk.stem.snowball.SnowballStemmer` "italian"
"""
badword_regexes = [
r"anale",
r"ano",
r"basta | rd[io]",
r"buttana",
r"cac(a|are|ata)",
r"cacc(a|he|ol[ae])",
r"caga(re|t[aeo])?",
r"cavolat[ae]",
r"cazz(at[ae]|[io]|on[ei])?",
r"cesso",
r"ciccione",
r"ciuccia",
r"coglion[ei]",
r"cojone",
r"cretin[io]",
r"culo",
r"deficent[ei]",
r"fancazzista",
r"fancul... |
google/grr | grr/test_lib/db_test_lib_test.py | Python | apache-2.0 | 3,039 | 0.008885 | #!/usr/bin/env python
from absl.testing import absltest
from typing import Text
from grr_response_core.lib import rdfvalue
from grr_response_server import blob_store
from grr_response_server.databases import db as abstract_db
from grr.test_lib import db_test_lib
class WithDatabaseTest(absltest.TestCase):
def tes... | e.BlobStore)
| TestMethod() # pylint: disable=no-value-for-parameter
@db_test_lib.WithDatabase
def testBlobstoreWorks(self, db: abstract_db.Database):
del db # Unused.
@db_test_lib.WithDatabaseBlobstore
def TestMethod(bs: blob_store.BlobStore):
blob_id = bs.WriteBlobWithUnknownHash(b"foobarbaz")
self... |
jezjestem/digitalhoryzont | munin/DHT11.py | Python | bsd-3-clause | 689 | 0.039187 | #!/usr/bin/env /usr/bin/python2.7
# -*- coding:utf-8 -*-
import os, sys, string, glob, socket, json
import syslog
import dhtreader
plugin_name = list(os.path.split(sys.argv[0]))[1]
arg = sys.argv[1] if len(sys.argv) == 2 else None
if arg == "config":
print("graph_title Humidity/temperature from DHT11");
print("gra... | print("graph_category environmental");
print("h.label humidity");
print("h.draw AREA");
else:
dhtreader.init()
read_loop = True
while read_loop:
try:
t, h = dhtreader.read(11, 25)
except Exception as e:
syslog.syslog(syslog.LOG_E | RR, "read exception: %s" %(e));
else:
read_loop = False
print("h.value {0}".format(h))
sys.exit(0)
|
sniemi/SamPy | smnIO/sextutils.py | Python | bsd-2-clause | 15,984 | 0.003003 | """
Utilities for parseing SExtractor files.
H. Ferguson - revised 4/23/03 to promote ints to floats if a value
with a decimal point appears somewhere in the column originally thought
to be integers
version::
v2.1 - fails gracefully when the catalog has no sources
v3.0 - added gettypes to return column types... | bug in creating extra column names when last is a vector
v4.4vl - V. Laidler added new methods:
__len__ returns number of objects in catalog
__iter__ returns the index of the next row in the catalog
line(self,i) returns a constructed string containing the ith line
... | Added new attribute self.header: contains the header as read in
from the catalog.
Lines that start with '#' but are not followed by an integer are
now assumed to be comment lines, which are added to the
header but otherwise skipped.
v4.5 - V. Laidler removed ... |
cmaxwe/SabnzbdSendTweet | send_standalone_tweet.py | Python | gpl-2.0 | 160 | 0.0125 | #Script to use if you are not launching the tweet from another script
import sys
imp | ort send_ | tweet
if len(sys.argv) == 8:
send_tweet.send_tweet(sys.argv[3])
|
t0mk/ansible | lib/ansible/modules/windows/win_stat.py | Python | gpl-3.0 | 7,000 | 0.001571 | #!/usr/bin/python
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed... | added: "2.1"
checksum_algorithm:
description:
- Algorithm to determine checksum of file. Will throw an error if
the host is unable to use specified algorithm.
required: no
default: sha1
choices: ['md5', 'sha1', 'sha256', 'sha384', 'sha512']
version_a... | rch (@cchurch)"
'''
EXAMPLES = r'''
- name: Obtain information about a file
win_stat:
path: C:\foo.ini
register: file_info
# Obtain information about a folder
- win_stat:
path: C:\bar
register: folder_info
# Get MD5 checksum of a file
- win_stat:
path: C:\foo.ini
get_checksum: yes
checksum_... |
nlesc-sherlock/analyzing-corpora | corpora/load_archive.py | Python | apache-2.0 | 1,507 | 0 | #!/usr/bin/env python
# SIM-CITY client
#
# Copyright 2015 Netherlands eScience Center <info@esciencecenter.nl>
#
# 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/l... | ('enron_mail_clean.tar.gz')
import pdb
pdb.set_trace()
if __name__ == "__main__":
| main()
|
fireeye/flare-floss | scripts/render-binja-import-script.py | Python | apache-2.0 | 5,046 | 0.002576 | #!/usr/bin/env python3
"""
render-binja-import-script.py
Translate a floss result document into an Binary Ninja script
that marks up the current workspace.
Usage:
$ floss suspicious.exe -j > floss-results.json
$ python render-binja-import-script.py floss-results.json > apply_floss.py
# now run `apply_floss.py`... | b64 = base64.b64encode(ss.string.encode("utf-8")).decode("ascii")
b64 = 'base64.b64decode("%s").decode("utf-8")' % (b64)
main_commands.append('AppendLvarComment(%d, "FLOSS stackstring: " + %s)' % (ss.function, b64))
ss_len += 1
main_com | mands.append('print("Imported stackstrings from FLOSS")')
script_content = """import base64
import binaryninja as bn
def AppendComment(ea, s):
s = s.encode('ascii')
refAddrs = []
for ref in bv.get_code_refs(ea):
refAddrs.append(ref)
for addr in refAddrs:
fnc = bv.get_functions_... |
jimporter/mettle | scripts/vendorize_bencode.py | Python | bsd-3-clause | 1,150 | 0 | #!/usr/bin/env python
# A simple script for copying bencode.hpp to mettle's include directory. This
# eliminates the need for users to manually download bencode.hpp if they don't
# want to.
import os
import shutil
import tarfile
from io import BytesIO
try:
from urllib.request import urlopen
except ImportError:
... | path.join(__file__, '..', '..'))
commit = 'fd1b6d1e76affd0 | 2dcc89b1bbcf2feef95e969da'
bencode_name = 'bencode.hpp-{}'.format(commit)
bencode_url = ('https://github.com/jimporter/bencode.hpp/archive/{}.tar.gz'
.format(commit))
if __name__ == '__main__':
print('Fetching {}'.format(bencode_url))
f = urlopen(bencode_url)
with tarfile.open(mode='r:gz', ... |
huntcsg/slackly | tests/unit_tests/client/test_response_factory.py | Python | mit | 3,632 | 0.002203 | from unittest import TestCase
import os
import json
class TestResponseObjectFactory(TestCase):
def setUp(self):
from slackly import SlackAPIDictResponse, SlackAPIObjectResponse
from slackly.schema.types import List
self.list = List
self.dict_response = SlackAPIDictResponse
... | for endpoint in os.listdir(endpoints_data_dir):
endpoint_dir = os.path.join(endpoints_data_dir, endpoint)
for file in os.listdir(endpoint_dir):
def test_func(self, endpoint_dir=endpoint_dir, file=file, endpoint=endpoint):
with open(os.path.join(endpoint_dir, file), 'rb') as f... | ult = self.callFUT(endpoint, response_data)
if self.endpoint_is_registered(endpoint):
if isinstance(result, list):
test_object = result[0]
else:
test_object = result
self.... |
plotly/plotly.py | packages/python/plotly/plotly/validators/funnel/marker/_colorsrc.py | Python | mit | 402 | 0.002488 | import _plotly_utils.basevalidators
class ColorsrcValidator(_plotly_utils. | basevalidators.SrcValidator):
def __init__(self, plotly_name="colorsrc", parent_name="funnel.marker", **kwargs):
super(ColorsrcValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "none"),
**kwargs
... | )
|
peterbartha/ImmunoMod | res_mods/mods/packages/xvm_sounds/python/ammoBay.py | Python | mit | 1,412 | 0.002833 | """ XVM (c) www.modxvm.com 2013-2017 """
#####################################################################
# imports
import SoundGroups
from helpers import dependency
from skeletons.gui.battle_session import IBattleSessionProvider
from gui.Scaleform.daapi.view.battle.shared.damage_panel import DamagePanel
from x... | module, state, _ = value
if module == 'ammoBay' and state == 'critical':
SoundGr | oups.g_instance.playSound2D(XVM_SOUND_EVENT.AMMO_BAY)
except:
err(traceback.format_exc())
|
MaximeBiset/care4care | branch/widgets.py | Python | agpl-3.0 | 332 | 0.006024 | from django.forms.widgets import RadioSelect
class OneJobSelect(RadioSelect):
def value_from_datadict(self, data, files, name):
"""
Given a dictionary of data and | this widget's name, returns the value
of this widget. Returns None if | it's not provided.
"""
return [data.get(name, None)]
|
ddurieux/alignak | test/test_bad_timeperiods.py | Python | agpl-3.0 | 2,376 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2015-2015: Alignak team, see AUTHORS.txt file for contributors
#
# This file is part of Alignak.
#
# Alignak is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free So... | oux@free.fr
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken is di... | of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test reading and processi... |
duomarket/openbazaar-test-nodes | qa/dispute_close_split.py | Python | mit | 14,747 | 0.004272 | import requests
import json
import time
from collections import OrderedDict
from test_framework.test_framework import OpenBazaarTestFramework, TestFailure
class DisputeCloseSplitTest(OpenBazaarTestFramework):
def __init__(self):
super().__init__()
self.num_nodes = 3
def run_test(self):
... | Spend post endpoint not found")
elif r.status_code != 200:
resp = json.loads(r.text)
raise TestFailure("DisputeCloseSplitTest - FAIL: Spend POST failed. Reason: %s", resp["reason"])
time.sleep(20)
# check bob detected payment
api_url = bob["gateway_url"] + "ob/o... | Bob")
resp = json.loads(r.text)
if resp["state"] != "AWAITING_FULFILLMENT":
raise TestFailure("DisputeCloseSplitTest - FAIL: Bob failed to detect his payment")
if resp["funded"] == False:
raise TestFailure("DisputeCloseSplitTest - FAIL: Bob incorrectly saved as unfunded")... |
uni-halle/python-redmine-tools | topic_index.py | Python | apache-2.0 | 11,227 | 0.014792 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#---
#--- Python
import sys
import StringIO
import argparse
#---
#--- 3rd party
from redmine import Redmine
from redmine import exceptions as redmine_exceptions
#---
class ProjectTree(object) :
def __init__(self, allProjects ) :
self._projects = list(allProje... | list(_iterAncestors(page))))
def getAncestorsAndPage(self, page) :
return self.getAncestorPages(page) + [page]
def _insert(self, page) :
#self._pages.append(page)
#if parentPage is None :
# self.pagesWithParent[page] = []
return
def iter_dfs(self) :
for ... | iterGlobaleTopicIndexLines(redmineHandle, topicParentPage) :
lineCount += 1
print line
return lineCount
def iterGlobaleTopicIndexLines(redmineHandle, topicParentPage, **keywords) :
"""
Iterates over the lines of the target document line by line.
@keyword printProgress: If True progres... |
ESOedX/edx-platform | cms/envs/openstack.py | Python | agpl-3.0 | 1,452 | 0.002066 | """
Settings for OpenStack deployments.
"""
from .production import * # pylint: disable=wildcard-import, unused-wildcard-import
SWIFT_AUTH_URL = AUTH_TOKENS.get('SWIFT_AUTH_URL')
SWIFT_AUTH_VERSION = AUTH_TOKENS.get('SWIFT_AUTH_VERSION', 1)
SWIFT_USERNAME = AUTH_TOKENS.get('SWIFT_USERNAME')
SWIFT_KEY = AUTH_TOKENS.g... | TENT_LENGTH_FROM_FD', False)
SWIFT_LAZY_CONNECT = AUTH_TOKENS.get('SWIFT_LAZY_CONNECT', True)
if AUTH_TOKENS.get('SWIFT_REGION_NAME'):
SWIFT_EXTRA_OPTIONS = {'region_name': AUTH_TOKENS['SWIFT_REGION_NAME']}
if AUTH_TOKENS.get('DEFAULT_FILE_STORAGE'):
DEFAULT_FILE_STORAGE = AUTH_TOKENS.get('DEFAULT_FILE_STORAG... | ango.core.files.storage.FileSystemStorage'
# Use default file storage class set above for course import/export
COURSE_IMPORT_EXPORT_STORAGE = DEFAULT_FILE_STORAGE
|
andreadean5/python-hpOneView | tests/unit/test_servers.py | Python | mit | 10,216 | 0.002056 | # -*- coding: utf-8 -*-
###
# (C) Copyright (2012-2016) Hewlett Packard Enterprise Development LP
#
# 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 withou | t limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copi... | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETH... |
c-PRIMED/puq | examples/correlated/c2_prog.py | Python | mit | 341 | 0 | #!/usr/bin/env python
import optparse |
from puqutil import dump_hdf5
import time
usage = "usage: %prog --f f --g g"
parser = optparse.OptionParser(usage)
parser.add_option("--g", type=float)
parser.add_option("--f", type=fl | oat)
(options, args) = parser.parse_args()
f = options.f
g = options.g
k = f * g
dump_hdf5('k', k, "$k(f,g)=f*g$")
|
EndyKaufman/django-postgres-angularjs-blog | app/account/resource.py | Python | mit | 5,164 | 0.000968 | # -*- coding: utf-8 -*-
from project import helpers
from django.db.models import Q
from django.contrib import auth
from project import settings
from django.template.loader import render_to_string
from django.utils.translation import ugettext, get_language
from models import User, Code
def get_fields():
return [f.... | if data['password'] is not None:
user.set_password(data['password'])
user.backend = 'django.contrib.auth.backends.ModelBackend'
u | ser.save()
return {'code': 'ok', 'data': [user.get_user_data()]}, 200, user
def delete(request):
"""Update record"""
user = helpers.get_user(request)
user.backend = 'django.contrib.auth.backends.ModelBackend'
user.delete()
auth.logout(request)
return {'code': 'ok'}, 200
def login(req... |
Webcampak/v2.0 | src/bin/webcampak.py | Python | gpl-3.0 | 11,254 | 0.022836 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright 2010-2012 Infracom & Eurotechnia (support@webcampak.com)
# This file is part of the Webcampak project.
# Webcampak 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 Fo... | n file available for your language")
#languages = []
#languages.append("en_US")
#t = gettext.translation(g.getConfig('cfggettextdomain'), g.getConfig('cfgbasedir') + g.getConfig('cfglocaledir'), languages)
#_ = t.ugettext
#t.install()
# Source config or "c" is a set of configuration parameters speci... | = Config(CmdSourceConfig)
elif os.path.isfile("/home/" + pwd.getpwuid(os.getuid())[0] + "/webcampak/etc/config-source" + cfgcurrentsource + ".cfg"):
c = Config("/home/" + pwd.getpwuid(os.getuid())[0] + "/webcampak/etc/config-source" + cfgcurrentsource + ".cfg")
else:
if os.path.isfile("/home/" + pwd.getpwuid(... |
mickem/nscp | build/python/VersionHandler.py | Python | gpl-2.0 | 2,824 | 0.049929 | #!/bin/python
import re
import sys
import os
from datetime import date
class VersionHandler:
def __init__(self, file):
self.file = file
self.major = 0
self.minor = 0
self.revision = 0
self.build = 1
self.touch()
def read(self):
try:
f = open(self.file, 'r')
lines = f.readlines()
f.close()
... | s\n'%name)
f.write('#define %s\n'%name)
f.write('#define PRODUCTVER %d,%d,%d,%d\n'%(self.major, self.minor, self.revision, self.build))
f.write('#define STRPRODUCTVER "%d.%d.%d.%d"\n'%(self.major, self.minor, self.revision, self.build) | )
f.write('#define STRPRODUCTDATE "%s"\n'%(self.date))
f.write('#endif // %s\n'%name)
f.close()
|
hugovk/pylast | tests/test_track.py | Python | apache-2.0 | 6,969 | 0.000287 | #!/usr/bin/env python
"""
Integration (not unit) tests for pylast.py
"""
import unittest
import pylast
from .test_pylast import TestPyLastWithLastFm
class TestPyLastTrack(TestPyLastWithLastFm):
def test_love(self):
# Arrange
artist = "Test Artist"
title = "test title"
track = sel... | nt = track.get_listener_count()
# Assert
self.assertGreater(count, 21)
def test_album_tracks(self):
# Arrange
album = pylast.Album("Test Artist", "Test", self.network)
# Act
tracks = album.get_tracks() |
url = tracks[0].get_url()
# Assert
self.assertIsInstance(tracks, list)
self.assertIsInstance(tracks[0], pylast.Track)
self.assertEqual(len(tracks), 1)
self.assertTrue(url.startswith("https://www.last.fm/music/test"))
def test_track_eq_none_is_false(self):
#... |
santisiri/popego | envs/ALPHA-POPEGO/lib/python2.5/site-packages/SQLAlchemy-0.4.5-py2.5.egg/sqlalchemy/sql/visitors.py | Python | bsd-3-clause | 6,337 | 0.007417 | from sqlalchemy import util
class ClauseVisitor(object):
"""Traverses and visits ``ClauseElement`` structures.
Calls visit_XXX() methods for each particular
``ClauseElement`` subclass encountered. Traversal of a
hierarchy of ``ClauseElements`` is achieved via the
``traverse()`` method, which ... | return self._cloned_traversal(obj)
else: |
return self._non_cloned_traversal(obj)
def copy_and_process(self, list_):
"""Apply cloned traversal to the given list of elements, and return the new list."""
return [self._cloned_traversal(x) for x in list_]
def before_clone(self, elem):
"""receive pre-copied elements du... |
yzxsunshine/SoCBirrt | examples/python/cbirrt_benchmark.py | Python | bsd-2-clause | 5,542 | 0.015518 | # Copyright (c) 2010 Carnegie Mellon University and Intel Corporation
# Author: Dmitry Berenson <dberenso@cs.cmu.edu>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must r... | ence frame at the object's frame relative to world frame
T0_w = T0_object
#get the TSR's offset frame in w coordinates
Tw_e1 = MakeTransform(rodrigues([pi/2, 0, 0]),mat([0, 0.22, 0.1]).T)
#define bounds to only allow rotation of the hand about z axis and a small deviation in | translation along the z axis
Bw = mat([0, 0, 0, 0, -0.02, 0.02, 0, 0, 0, 0, -pi, pi])
TSRstring1 = SerializeTSR(0,'NULL',T0_w,Tw_e1,Bw)
TSRChainString1 = SerializeTSRChain(0,1,0,1,TSRstring1,'NULL',[])
#now define the second TSR chain
#it is the same as the first TSR Chain except Tw_e ... |
materialsvirtuallab/veidt | veidt/describer/structural_describer.py | Python | bsd-3-clause | 5,390 | 0.001299 | from pymatgen.symmetry.analyzer import SpacegroupAnalyzer
from ..abstract import Describer
import pandas as pd
import numpy as np
class DistinctSiteProperty(Describer):
"""
Constructs a describer based on properties of distinct sites in a
structure. For now, this assumes that there is only one type of spe... | .norm(c, axis=1)
rng = np.random.RandomState(self.random_seed)
e = rng.normal(size=row_norms.size)
p = np.argsort(row_norms + e)
return c[p][:, p]
def describe(self, structure):
"""
Args:
structure(Structure): input structure
Returns:
... | olumn is index of the structure, which is 0 for single input
df[0] returns the serials of coulomb_mat raval
"""
if self.sorted:
c = self.sorted_coulomb_mat(structure)
if self.randomized:
c = self.randomized_coulomb_mat(structure)
if np.all([not self.so... |
joshua-cogliati-inl/raven | framework/utils/randomUtils.py | Python | apache-2.0 | 15,561 | 0.016002 | # Copyright 2017 Battelle Energy Alliance, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | Function to get a random integer
@ In, low, int, low boundary
@ In, high, int, upper boundary
@ In, caller, instance, optional, object requesting the random integers
@ In, engine, instance, optional, optional, random number generator
@ Out, rawInt, int, random int
"""
engine = getEngine(engine)... | om.RandomState):
return engine.randint(low, high=high+1)
elif isinstance(engine, findCrowModule('randomENG').RandomClass):
intRange = high - low + 1.0
rawNum = low + random(engine=engine)*intRange
rawInt = math.floor(rawNum)
if rawInt < low or rawInt > high:
if caller:
caller.raiseAM... |
arcivanov/karellen-kombu-ext | src/main/python/karellen/kombu/transport/django/models.py | Python | apache-2.0 | 1,161 | 0 | from __future__ import absolute_import, unicode_literals
import django
from django.db import models
from django.utils.translation import ugettext_lazy as _
from .managers import QueueManager, MessageManager
class Queue(models.Model):
name = models.CharField(_('name'), max_length=200, unique=True)
objects ... | ):
app_label = | 'karellen_kombu_transport_django'
db_table = 'djkombu_queue'
verbose_name = _('queue')
verbose_name_plural = _('queues')
class Message(models.Model):
visible = models.BooleanField(default=True, db_index=True)
sent_at = models.DateTimeField(null=True, blank=True, db_index=True,
... |
w-gao/py-mcpe-query | src/mcquery/query.py | Python | mit | 5,863 | 0.002047 | #
# Copyright (c) 2017-2021 w-gao
#
import argparse
import logging
import struct
import sys
import socket
from contextlib import contextmanager
from random import randint
from typing import Generator
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.WARNING)
# constants
MC_QUERY_MAGIC = b'\xFE\... | dd_argument("-d", "--debug", action='store_true', help="Enable debug logging.")
options = parser.parse_args(args)
if options.debug:
logging.basicConfig(level=logging.DEBUG)
host = options.host
port = options.port
timeout = options.timeout
try:
with mcquery(host, port=port, tim... | : {v}" for k, v in data.__dict__.items())
print(stdout)
except Exception as e:
print(f"An error occurred during query: {e}")
if __name__ == "__main__":
main(sys.argv[1:])
|
eduNEXT/edunext-platform | import_shims/studio/xblock_django/tests/test_user_service.py | Python | agpl-3.0 | 440 | 0.009091 | """Deprecated import support. Auto-generated by import_shims/generate_shims.sh."""
# pylint: disable=redefined-builtin,wrong-import-position,wildcard-import,useless-suppression,line-too-long
from import_shims.warn import warn_deprecat | ed_import
warn_deprecated_import('xblock_django.tests.test_user_service', 'common.djangoapps.xblock_django.tests.test_user_servic | e')
from common.djangoapps.xblock_django.tests.test_user_service import *
|
uogbuji/versa | tools/py/serial/ntriples.py | Python | apache-2.0 | 4,115 | 0.005103 | # versa.serial.ntriples
'''
Serialize and deserialize between a Versa model and NTriples
https://www.w3.org/TR/rdf-testcases/#ntriples
'''
import re
from amara3 import iri
from versa import I, VERSA_BASEIRI, ORIGIN, RELATIONSHIP, TARGET
from versa.terms import VERSA_BASEIRI, RDF_NS, RDFS_NS, VTYPE_REL, RDF_TYPE_REL... | ipped', line)
continue
else:
if p_iri in exclude_rel:
| continue
if _add(I(s_iri), p_iri, I(o_iri) if o_iri else o_str):
new_origins.add(I(s_iri))
return
def parse_iter(nt_fp, model_fact=newmodel):
raise NotImplementedError
def strconv(item):
'''
Prepare a statement into a triple ready for rdflib
'''
if isin... |
tangochin/django-seo | djangoseo/systemviews.py | Python | bsd-3-clause | 835 | 0.001198 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
import importlib
from django.apps import apps
def get_seo_views(metadata_class):
return get_view_names(metadata_class._meta.seo_views)
def get_view_names(seo_views):
output = []
for name in seo_views:
try:
app = apps.get_app_config(name)... | urls = importlib.import_module(".".join(app_name)).urlpatterns
except (ImportError, AttributeError): |
output.append(name)
else:
for url in urls:
if getattr(url, 'name', None):
output.append(url.name)
return output
|
ehein6/stinger | util/flask/test/test_algorithms.py | Python | bsd-3-clause | 6,389 | 0.008765 | import argparse
import cPickle as pickle
import colorama as color
import csv
import json
import os
import requests
import sys
import time
from time import gmtime, strftime
# test_algorithms has two modes of operation:
# 1. Create reference output of algorithms
# 2. Validate current algorithm results against refere... | args()
def stingerRPC(payload):
urlstr = 'http://{}:{}/jsonrpc'.format(args.stinger_host,args.stinger_port)
try:
r = requests.post(urlstr, data=json.dumps(payload))
except:
print color.Fore.RED + "Cannot connect to STI | NGER RPC" + color.Style.RESET_ALL
sys.exit(1)
return r.json()
def get_algorithms():
payload = {"jsonrpc": "2.0", "method": "get_algorithms", "id": 1}
r = stingerRPC(payload)
assert 'result' in r
algs = r['result']['algorithms']
algs.remove('stinger')
return algs
def get_results():
... |
noironetworks/group-based-policy | gbpservice/tests/contrib/gbpfunctests/testcases/tc_gbp_ri_func_1.py | Python | apache-2.0 | 7,687 | 0 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... | self.cleanup(objs, names, fail=1)
######
self._log.info("\n## Step 3: Create Policy Rule ##\n")
rule_uuid = self.gbpcfg.gbp_policy_cfg_all(
1, 'rule', s | elf.rule_name, classifier=self.class_name,
action=self.act_name)
objs, names = [
'rule', 'classifier', 'action'], [
rule_uuid, cls_uuid, act_uuid]
if rule_uuid == 0:
self._log.info("# Step 3: Create Policy Rule == Failed")
self.cleanup(objs, na... |
Cartocite/osmada | osmdata/parsers.py | Python | agpl-3.0 | 8,389 | 0.001669 | import datetime
import xml.dom.minidom
import pytz
from .models import (
Action, Bounds, Diff, Node, OSMElement, Relation,
RelationMember, Tag, Way, WayNode)
class FileFormatError(Exception):
pass
zulu_tz = pytz.timezone('Zulu')
def parse_iso8601(s):
return zulu_tz.localize(datetime.datetime.strpti... | y, node=node, order=index)
self.parse_tags(way)
return way
# Here to avoid cyclic dependecies
AbstractXMLParser.PARSER_MA | P = {
OSMElement.NODE: NodeParser,
OSMElement.WAY: WayParser,
OSMElement.RELATION: RelationParser,
}
class ActionParser(AbstractXMLParser):
""" <action> parser
"""
def _get_old_new(self):
for i in ('old', 'new'):
try:
tag = self.node.getElementsByTagName(i)[... |
GPCsolutions/gandi.cli | setup.py | Python | gpl-3.0 | 1,870 | 0 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import re
import os
import sys
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.md')).read()
CHANGES = open(os.path.join(here, 'CHANGES.rst')).read()
with open(os.path.join(here, 'gandi',... | re.S).match(v_file.read()).group(1)
requires = ['setuptools', 'pyyaml', 'click<=4.0', 'requests', 'IPy']
tests_require = ['nose', 'coverage', 'tox', 'h | ttpretty==0.8.6']
if sys.version_info < (2, 7):
tests_require += ['unittest2', 'importlib']
if sys.version_info < (3, 3):
tests_require.append('mock')
extras_require = {'test': tests_require,
}
setup(name='gandi.cli',
namespace_packages=['gandi'],
version=version,
descript... |
theheros/kbengine | kbe/res/scripts/common/Lib/test/test_pipes.py | Python | lgpl-3.0 | 7,386 | 0.002166 | import pipes
import os
import string
import unittest
from test.support import TESTFN, run_unittest, unlink, reap_children
if os.name != 'posix':
raise unittest.SkipTest('pipes module only works on posix')
TESTFN2 = TESTFN + "2"
# tr a-z A-Z is not portable, so m | ake the ranges explicit
s_command = 'tr %s %s' % (string.ascii_lowercase, string.ascii_uppercase)
class SimplePipeTests(unittest.TestCase):
def tearDown(self):
for f in (TESTFN, TESTFN2):
unlink(f)
def testSimplePipe1(self):
t = pipes.Template()
t.append(s_command... | o world #1')
f.close()
with open(TESTFN) as f:
self.assertEqual(f.read(), 'HELLO WORLD #1')
def testSimplePipe2(self):
with open(TESTFN, 'w') as f:
f.write('hello world #2')
t = pipes.Template()
t.append(s_command + ' < $IN > $OUT', pipes.FIL... |
lukacu/django-gallery | gallery/urls.py | Python | bsd-3-clause | 434 | 0.009217 | # -*- Mode: python; indent-tabs-mode: nil; c-basic-offset: 2; tab-width: 2 -*-
from django.conf.urls.defaults import *
from gallery.feeds import GalleryFeed, | AlbumFeed
urlpatterns = patterns('',
url(r'^f | eed/gallery/$', GalleryFeed(), name="gallery-feed"),
url(r'^feed/album/(?P<album_id>[0-9]+)/$', AlbumFeed(), name="gallery-album-feed"),
url(r'^(?P<path>[a-z\-_0-9\/]*)$', 'gallery.views.resolve', name="gallery"),
)
|
shanot/imp | modules/example/test/test_constraint.py | Python | gpl-3.0 | 1,035 | 0.001932 | from __future__ import print_function
import IMP
import IMP.test
import IMP.algebra
import IMP.core
import IMP.example
class Tests(IMP.test.TestCase):
def test_constraint(self):
"""Test example Constraint"""
k = IMP.IntKey("Constraint key")
# Test both implementations: C++ and Python
... | = typ(p)
self.assertEqual(p.get_value(k), 0)
m.update()
self.assertEqual(p.get_value(k), 1)
m.update()
self.assertEqual(p.get_ | value(k), 2)
self.assertIn("ExampleConstraint", str(c))
self.assertIn("ExampleConstraint", repr(c))
self.assertIn("example", c.get_version_info().get_module())
self.assertEqual(len(c.get_inputs()), 1)
self.assertEqual(len(c.get_outputs()), 1)
if __name__ == '... |
shailr/vms | django_http_api/settings.py | Python | gpl-2.0 | 6,509 | 0.000154 | # Django settings for django_http_api project.
import os
import dj_database_url
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': dj_database_url.config(
defaul... | I_APPLICATION = 'django_http_api.wsgi.application'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates"
# or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget t | o use absolute paths, not relative paths.
os.path.join(BASE_DIR, 'templates'),
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'co... |
MediaKraken/MediaKraken_Deployment | source/web_app_sanic/blueprint/user/bp_user_hardware.py | Python | gpl-3.0 | 982 | 0.003055 | from common import common_global
from sanic import Blueprint
blueprint_user_hardware = Blueprint('name_blueprint_user_hardware', url_prefix='/user')
@blueprint_user_hardware.route('/user_hardware', methods=['GET'])
@common_global.jinja_template.template('bss_user/hardware/bss_user_hardware.html')
@common_global.auth... | .db_pool.acquire()
phue_hardware = await request.app.db_functions.db_hardware_device_count(
hardware_manufacturer='Phue', db_connection=db_connection)
await request.app.db_pool.release(db_connection)
return {
'phue': phue_hardware
}
@blueprint_user_hardware.route('/user_hardware_phue',... | ds=['GET'])
@common_global.jinja_template.template('bss_user/hardware/bss_user_hardware_phue.html')
@common_global.auth.login_required
async def url_bp_user_hardware_phue(request):
return {
}
|
xiaoyongaa/ALL | 网络编程第四周/11.py | Python | apache-2.0 | 60 | 0.116667 | u={"1":"1","2":"2"}
u=u. | get("1")
g=u["1"]
print(g)
print | (u) |
111pontes/ydk-py | cisco-ios-xr/ydk/models/cisco_ios_xr/_meta/_Cisco_IOS_XR_aaa_aaacore_cfg.py | Python | apache-2.0 | 2,032 | 0.018701 |
import re
import collections
from enum import Enum
from ydk._core._dm_meta_info import _MetaInfoClassMember, _MetaInfoClass, _MetaInfoEnum
from ydk.types import Empty, YList, YLeafList, DELETE, Decimal64, FixedBitsDict
from ydk._core._dm_meta_info import ATTRIBUTE, REFERENCE_CLASS, REFERENCE_LIST, REFERENCE_LEAFLI... | g', _yang_ns._namespaces['Cisco-IOS-XR-aaa-aaacore-cfg']),
'AaaServiceAccountingEnum' : _MetaInfoEnum('AaaServiceAccountingEnum', 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_aaa_aaacore_cfg',
{
'none':'none',
'extended':'extended',
'brief':'brief',
}, 'Cisco-IOS-XR-aaa-... | a-aaacore-cfg']),
}
|
zardosht/strucWrite | test/__init__.py | Python | gpl-3.0 | 24 | 0 | _ | _auth | or__ = 'zardosht'
|
sviehb/binwalk | src/binwalk/plugins/ubivalid.py | Python | mit | 2,142 | 0.003735 | import struct
import binascii
import binwalk.core.plugin
class UBIValidPlugin(binwalk.core.plugin.Plugin):
'''
Helps validate UBI erase count signature results.
Checks header CRC and calculates jump value
'''
MODULES = ['Signature']
current_file=None
last_ec_hdr_offset = None
peb_size... | et:
# Calculate PEB size | by subtracting last EC block offset
self.peb_size = result.offset - self.last_ec_hdr_offset
else:
# First time plugin is called on file, save EC block offset
self.last_ec_hdr_offset = result.offset
if self.peb_size:
# If PEB size has been determined jump ... |
hasteur/g13bot_tools_new | pywikibot/families/wikinews_family.py | Python | mit | 1,385 | 0 | # -*- coding: utf-8 -*-
"""Family module for Wikinews."""
#
# (C) Pywikibot team, 2005-2017
#
# Distributed under the terms of the MIT license.
#
from __future__ import absolute_import, unicode | _literals
from pywikibot import family
__version__ = '$Id$'
# The Wikimedia family that is known as Wikinews
class Family(family.SubdomainFamily, family.WikimediaFamily):
"""Family class for Wikinews."""
name = 'wikinews'
closed_wikis = [
# https://noc.wikimedia.org/conf/highlight.php?file=cl... | _size = [
'sr', 'en', 'fr', 'de', 'ru', 'pl', 'pt', 'es', 'it', 'zh', 'cs',
'ca', 'ar', 'ta', 'el', 'sv', 'fa', 'uk', 'ro', 'tr', 'ja', 'sq',
'no', 'eo', 'fi', 'bs', 'he', 'ko', 'bg',
]
super(Family, self).__init__()
# Global bot allowed languages on
... |
SOM-st/PySOM | tests/test_som.py | Python | mit | 964 | 0.001037 | import os
import pytest
from som.vm.current import current_universe
@pytest.mark.parametrize(
"test_name",
[
"Array",
"Block",
"ClassLoading",
"ClassStructure",
| "Closure",
"Coercion",
"CompilerReturn",
"DoesNotUnderstand",
"Double",
"Empty",
"Global",
"Hash",
"Integer",
"Preliminary",
"Reflecti | on",
"SelfBlock",
"SpecialSelectors",
"Super",
"Set",
"String",
"Symbol",
"System",
"Vector",
],
)
def test_som(test_name):
current_universe.reset(True)
core_lib_path = os.path.dirname(os.path.abspath(__file__)) + "/../core-lib/"
args = [
... |
histogrammar/histogrammar-python | histogrammar/plot/vega/nodejs.py | Python | apache-2.0 | 3,370 | 0.002967 | #!/usr/bin/env python
# Copyright 2016 DIANA-HEP
#
# 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 a... | r None): None (default) guesses format from outputFile extension
"""
if format is None and outputFile is None:
format = "svg"
elif format is None and outputFile.endswith(".svg"):
format = "svg"
elif format is None and outputFile.endswith(".png"):
format = "png"
else:
... | cmd = "vg2png"
elif format == "svg":
cmd = "vg2svg"
else:
raise IOError("Only 'png' and 'svg' output is supported.")
npmbin = subprocess.Popen(["npm", "bin"], stdout=subprocess.PIPE)
if npmbin.wait() == 0:
npmbin = npmbin.stdout.read().strip()
else:
raise IOError("N... |
carsongee/edx-platform | common/djangoapps/course_modes/tests/test_views.py | Python | agpl-3.0 | 3,754 | 0.002397 | import ddt
import unittest
from django.test import TestCase
from django.conf import settings
from django.core.urlresolvers import reverse
from mock import patch, Mock
from course_modes.tests.factories import CourseModeFactory
from student.tests.factories import CourseEnrollmentFactory, UserFactory
from opaque_keys.edx... | ('course_modes.views.modulestore', Mock())
def test_reregister_redirect(self, is_active, enrollment_mode, upgrade, redirect):
enrollment = CourseEnrollmentFactory(
is_active=is_active,
mode=enrollment_mode,
course_id=self.course_id
)
self.client.login(
... | et_params = {'upgrade': True}
else:
get_params = {}
response = self.client.get(
reverse('course_modes_choose', args=[self.course_id.to_deprecated_string()]),
get_params,
follow=False,
)
if redirect:
self.assertEquals(response.... |
datamachine/twx | setup.py | Python | mit | 1,804 | 0.019401 | from setuptools import setup
import sys
revision = None
# must match PEP 440
_MAJOR_VERSION = 0
_MINOR_VERSION = 5
_MICRO_VERSION = None
_PRE_RELEASE_TYPE = 'a' # a | b | rc
_PRE_RELEASE_VERSION = 5
_DEV_RELEASE_VERSION = None
version = '{}.{}'.format(_MAJOR_VERSION, _MINOR_VERSION... | p(
name = 'twx',
packages = ['twx'],
version = version,
description = "Abstraction Layer Over Telegram's Bot API and MTProto Chat Potocols",
long_description = open("README.rst").read(),
author = 'Vince Castellano, Phillip Lopo',
author_email = 'surye80@gmail.com, philliplopo@gmail.com',
... | twx',
download_url = download_url,
install_requires=['requests', 'twx.botapi'],
platforms = ['Linux', 'Unix', 'MacOsX', 'Windows'],
classifiers = [
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :... |
iModels/ffci | github/tests/CommitStatus.py | Python | mit | 2,894 | 0.008984 | # -*- coding: utf-8 -*-
# ########################## Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> ... | 0].created_at, datetime.dat | etime(2012, 9, 8, 11, 30, 56))
self.assertEqual(self.statuses[0].updated_at, datetime.datetime(2012, 9, 8, 11, 30, 56))
self.assertEqual(self.statuses[0].creator.login, "jacquev6")
self.assertEqual(self.statuses[0].description, "Status successfuly created by PyGithub")
self.assertEqual(s... |
huiyiqun/check_mk | tests/conftest.py | Python | gpl-2.0 | 7,643 | 0.002748 | # This file initializes the py.test environment
import os
import pwd
import pytest
import _pytest.monkeypatch
import sys
import glob
import testlib
import tempfile
import shutil
import errno
from collections import OrderedDict
#
# Each test is of one of the following types.
#
# The tests are marked using the marker py... | ", ".join(test_types.keys()))
def pytest_collection_m | odifyitems(items):
"""Mark collected test types based on their location"""
for item in items:
type_marker = item.get_marker("type")
if type_marker and type_marker.args:
continue # Do not modify manually set marks
file_path = "%s" % item.reportinfo()[0]
if "tests/unit... |
UnbDroid/robomagellan | Codigos/Raspberry/desenvolvimentoRos/devel/lib/python2.7/dist-packages/diagnostic_msgs/msg/_DiagnosticArray.py | Python | gpl-3.0 | 14,346 | 0.016032 | # This Python file uses the following encoding: utf-8
"""autogenerated by genpy from diagnostic_msgs/DiagnosticArray.msg. Do not edit."""
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct
import diagnostic_msgs.msg
import std_msgs.msg
class DiagnosticArray(genpy.Message):
... | += 4
(length,) = _struct_I.unpack(str[start:end])
val1.values = []
for i in range(0, length):
val2 = diagnostic_msgs.msg.KeyValue()
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
i... | else:
val2.key |
gileno/sofia | sofia/apps/learn/admin.py | Python | mit | 2,179 | 0 | from django.contrib import admin
from | suit.admin import SortableModelAdmin
from .models import (
Area, Project, Enrollment, Announcement, Module, Lesson, Material
) |
class AreaAdmin(admin.ModelAdmin):
list_display = ['name', 'slug', 'created', 'modified']
search_fields = ['name']
prepopulated_fields = {'slug': ['name']}
class ProjectAdmin(admin.ModelAdmin):
list_display = ['name', 'leader', 'level', 'created', 'modified']
search_fields = ['name', 'leader_... |
lastweek/gem5 | tests/configs/tsunami-simple-timing-dual.py | Python | bsd-3-clause | 3,357 | 0.006553 | # Copyright (c) 2006-2007 The Regents of The University of Michigan
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met: redistributions of source code must retain the above copyright
# notice, this ... | ntributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILIT... | ORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABIL... |
cloudera/hue | desktop/core/ext-py/phoenixdb-1.1.0/phoenixdb/tests/test_types.py | Python | apache-2.0 | 22,726 | 0.005588 | # 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 use ... | f.checkIntType("unsigned_tinyint", 0, 127)
|
def test_smallint(self):
self.checkIntType("smallint", -32768, 32767)
def test_unsigned_smallint(self):
self.checkIntType("unsigned_smallint", 0, 32767)
def checkFloatType(self, type_name, min_value, max_value):
self.createTable("phoenixdb_test_tbl1", "CREATE TABLE {table} (id int... |
zackw/pelican | pelican/log.py | Python | agpl-3.0 | 7,578 | 0 | # -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals
import locale
import logging
import os
import sys
from collections import Mapping, defaultdict
import six
__all__ = [
'init'
]
class BaseFormatter(logging.Formatter):
def __init__(self, fmt=None, datefmt=None):
FORMAT =... | ts_color():
| """
Returns True if the running system's terminal supports color,
and False otherwise.
from django.core.management.color
"""
plat = sys.platform
supported_platform = plat != 'Pocket PC' and \
(plat != 'win32' or 'ANSICON' in os.environ)
# isatty is not always implemented, #6223.
... |
exa-analytics/exatomic | exatomic/molcas/tests/test_output.py | Python | apache-2.0 | 8,381 | 0.000716 | # -*- coding: utf-8 -*-
# Copyright (c) 2015-2022, Exa Analytics Development Team
# Distributed under the terms of the Apache License 2.0
from unittest import TestCase
import numpy as np
import pandas as pd
import h5py
from exatomic import Universe
from exatomic.base import resource
from exatomic.molcas.output import O... | rtTrue('diffocc' in self.mamcart.orbital.columns)
uni = self.mamcart.to_universe()
self.assertTrue(hasat | tr(uni, 'momatrix'))
self.assertTrue(hasattr(uni, 'orbital'))
def test_add_overlap(self):
"""Test adding an overlap matrix."""
self.cdz.add_overlap(resource('mol-carbon-dz.overlap'))
self.assertTrue(hasattr(self.cdz, 'overlap'))
uni = self.cdz.to_universe()
self.ass... |
turbokongen/home-assistant | homeassistant/components/xiaomi_miio/__init__.py | Python | apache-2.0 | 3,934 | 0.000763 | """Support for Xiaomi Miio."""
from datetime import timedelta
import logging
from miio.gateway import GatewayException
from homeassistant import config_entries, core
from homeassistant.const import CONF_HOST, CONF_TOKEN
from homeassistant.helpers import device_registry as dr
from homeassistant.helpers.update_coordina... | y_model,
sw_version=gateway_info.firmware_version,
)
async def async_update_data():
"""Fetch data from the subdevice."""
try:
for sub_device in gateway.gateway_device.devices.values():
await hass.async_add_executor_job(sub_device.update)
except Gatewa... | ption as ex:
raise UpdateFailed("Got exception while fetching the state") from ex
# Create update coordinator
coordinator = DataUpdateCoordinator(
hass,
_LOGGER,
# Name of the data. For logging purposes.
name=name,
update_method=async_update_data,
# P... |
MPIBGC-TEE/CompartmentalSystems | tests/Test_BlockIvp.py | Python | mit | 2,477 | 0.03149 | import unittest
from testinfrastructure.InDirTest import InDirTest
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from CompartmentalSystems.BlockIvp import BlockIvp
class TestBlockIvp(InDirTest):
@unittest.skip
def test_solution(self):
x1_shape=(5,5)
... | x1'][-1],ref['x1'],rtol=1e-2 | ))
self.assertTrue(np.allclose(res['x2'][-1],ref['x2'],rtol=1e-2))
# here we describe time by a variable with constant derivative
# amd use it in the derivative of the second variable
# to simulate a coupled system without feedback (skew product)
x1_shape=(1,)
x2_shape=(... |
tridvaodin/Assignments-Valya-Maskaliova | project/page/views.py | Python | gpl-2.0 | 469 | 0.031983 | from django.shortcuts impo | rt render, get_object_or_404
from page.models import Post
def index(request):
#get the blog posts that are published
posts = Post.objects.filter(published=True)
#now return the rendered template
return render(request, 'page/index.html', {'posts': posts})
def post(request, slug):
#get the Post object
post = get_... | g)
#now return the rendered template
return render(request, 'page/post.html', {'post':post})
|
kronas/Flask-Imagine | setup.py | Python | mit | 1,027 | 0.001947 | try:
import multiprocessing
except ImportError:
pass
from setuptools import setup
setup(
name='Flask-Imagine',
version='0.5',
description='Extension which provides easy image manipulation support in Flask applications.',
url='https://github.com/FlaskGuys/Flask-Imagine',
author='Kronas',
... | ',
'six>=1.10.0',
],
classifiers=[
| 'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Topic :: Software Development :: Libraries :: Py... |
Hernanarce/pelisalacarta | python/main-classic/channels/youpeliculas.py | Python | gpl-3.0 | 11,272 | 0.020769 | # -*- coding: utf-8 -*-
#------------------------------------------------------------
# Canal YouPeliculas.co by EpNiebla
# http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/
#------------------------------------------------------------
import urlparse,urllib2,urllib,re
import os, sys
from core | import config
from core import logger
from core import httptools
from core import scrapertools
from core.item import Item
from core import servertools
from core import jsontools
host = 'http://youpeliculas.co'
def mainlist(item):
logger.info()
itemlist = []
itemlist.append(item.clone(title="[Peliculas]",... | sta", extra={'post':'type=series', 'page_current':0, 'max_pages':1}))
itemlist.append(item.clone(title="[Anime] Novedades/Actualizadas", action="lista", extra={'post':'type=anime', 'page_current':0, 'max_pages':1}))
itemlist.append(item.clone(title="[Infantiles] Novedades/Actualizadas", action="lista", extra={'... |
TouK/vumi | vumi/components/tests/test_message_store_api.py | Python | bsd-3-clause | 11,045 | 0.001811 | import json
from datetime import datetime, timedelta
from twisted.internet import reactor
from twisted.internet.defer import inlineCallbacks, returnValue, Deferred
from vumi.utils import http_request_full
from vumi.message import TransportUserMessage
from vumi.tests.helpers import (
VumiTestCase, MessageHelper, ... | self.assertEqual(token, expected_token)
self.assertEqual(response.code, 200)
returnValue(token)
def assertResultCount(self, response, count):
self.assertEqual(
response.headers.getRawHeaders(
self.match_resource.RESP_COUNT_HEADER),
[str(count)]... | the list of messages provided.
There are easier ways to do this by comparing bigger JSON blogs
but then debugging the huge strings would be a pain.
"""
dictionaries = json.loads(json_blob)
self.assertEqual(len(dictionaries), len(messages),
'Unequal amount of dictio... |
josiah-wolf-oberholtzer/supriya | dev/etc/pending_ugens/InRect.py | Python | mit | 3,439 | 0.002035 | import collections
from supriya.enums import CalculationRate
from supriya.synthdefs import UGen
class InRect(UGen):
"""
::
>>> in_rect = supriya.ugens.InRect.ar(
... rect=rect,
... x=0,
... y=0,
... )
>>> in_rect
InRect.ar()
"""
... | tion_rate = supriya.CalculationRate.AUDIO
ugen = cls._new_expanded(
calculation_rate=calculation_rate,
rect=rect,
x=x,
y=y,
)
return ugen
@classmethod
def kr(
cls,
rect=None,
x=0,
y=0,
):
... | Constructs a control-rate InRect.
::
>>> in_rect = supriya.ugens.InRect.kr(
... rect=rect,
... x=0,
... y=0,
... )
>>> in_rect
InRect.kr()
Returns ugen graph.
"""
import supriya.synt... |
ujvl/ray-ng | python/ray/projects/__init__.py | Python | apache-2.0 | 202 | 0 | from __future__ import absolute_import
from | __future__ import division
from __future__ import print_function
from ray.projects.projects import Pr | ojectDefinition
__all__ = [
"ProjectDefinition",
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.