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 |
|---|---|---|---|---|---|---|---|---|
bburan/psiexperiment | psi/experiment/workbench.py | Python | mit | 4,641 | 0.001077 | import logging
log = logging.getLogger(__name__)
import enaml
from enaml.application import deferred_call
from enaml.workbench.api import Workbench
with enaml.imports():
from enaml.stdlib.message_box import critical
from . import error_style
from psi import set_config
from psi.core.enaml.api import load_mani... | e. It's essentially a global variable.
set_config('EXPERIMENT', experiment_name)
ui = self.get_plugin('enaml.workbench.ui')
core = self.get_plugin('enaml. | workbench.core')
# Load preferences
if load_preferences and preferences_file is not None:
deferred_call(core.invoke_command, 'psi.load_preferences',
{'filename': preferences_file})
elif load_preferences and preferences_file is None:
deferred_cal... |
radio-astro/radiopadre | radiopadre/js9/__init__.py | Python | mit | 2,243 | 0.004904 | import os
import os.path
import traceback
# init JS9 configuration
# js9 source directory
DIRNAME = os.path.dirname(__file__)
JS9_ERROR = os.environ.get("RADIOPADRE_JS9_ERROR") or None
def init_js9():
global radiopadre
import radiopadre
from radiopadre.render import render_status_message
global JS9... | "])
except:
JS9_ERROR = "invalid RADIOPADRE_JS9_HELPER_PORT setting, integer value expected"
# get init code, substitute global variables into it
if not JS9_ERROR:
try:
with open(os.path.join(DIRNAME, "js9-init-template.html")) as inp:
source = inp.read()
... | ck.print_exc()
JS9_ERROR = "Error reading init templates: {}".format(str(exc))
# on error, init code replaced by error message
if JS9_ERROR:
JS9_INIT_HTML_HTTP = render_status_message("Error initializing JS9: {}".format(JS9_ERROR), bgcolor='yellow')
radiopadre.add_startup_warning(""... |
dan4ik95dv/housemanagement | tsj/fixtures/origins/export_companies.py | Python | mit | 2,898 | 0.002761 | #!/usr/bin/python
from json import dumps as jdumps
from sys import stdin, argv
from itertools import count
from pprint import PrettyPrinter
from collections import OrderedDict
def order_dict(keys, d):
return OrderedDict([(k, d[k]) for k in keys])
ENTITY_ORDER = ("model", "pk", "fields")
USER_ORDER = (
"userna... | 17T19:40:08.944Z"
})
})
entity = order_dict(ENTITY | _ORDER, {
"model": "tsj.company",
"pk": i,
"fields": {
"kpp": "12345654321",
"bank_name": "12343543",
"kor_schet": "2342342343",
"orgn_date": "2014-10-10",
"bik": "3424234324",
"boss_fio": "\u0419\u0446\u0443\u043a \u0415\u0... |
JoProvost/calbum | calbum/sources/exiftool.py | Python | apache-2.0 | 3,192 | 0.000627 | # Copyright 2015 Jonathan Provost.
#
# 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 wri... | T WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import loggi | ng
import subprocess
from calbum.core.model import Media, string_to_datetime
exiftool_path = 'exiftool'
class ExifToolMedia(Media):
file_extensions = ()
timestamp_tags = (
'Creation Date',
'Date/Time Original',
'Track Create Date',
'Media Create Date',
'Create Date'... |
priyankarani/trytond-shipping-dpd | carrier.py | Python | bsd-3-clause | 4,946 | 0.000202 | # -*- coding: utf-8 -*-
"""
carrier
"""
from decimal import Decimal
from suds import WebFault
from trytond.transaction import Transaction
from trytond.pool import PoolMeta, Pool
from trytond.model import fields, ModelView
from trytond.pyson import Eval
from trytond.wizard import Wizard, StateView, Button
from dpd_... | len(carriers) != 1:
cls.raise_user_error('Only one carrier can be tested at a time.')
client = carriers[0].get_dpd_client()
try:
client.get_auth()
except WebFault, exc:
cls.raise_user_error(exc.faul | t)
def get_sale_price(self):
"""Estimates the shipment rate for the current shipment
DPD dont provide and shipping cost, so here shipping_cost will be 0
returns a tuple of (value, currency_id)
:returns: A tuple of (value, currency_id which in this case is USD)
"""
Cu... |
cloudbase/lis-tempest | tempest/api/compute/admin/test_simple_tenant_usage_negative.py | Python | apache-2.0 | 2,648 | 0 | # Copyright 2013 NEC Corporation
# 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 ... | w - datetime.timedelta(days=1))
cls.end = cls._parse_strtime(now + datetime.timede | lta(days=1))
@classmethod
def _parse_strtime(cls, at):
# Returns formatted datetime
return at.strftime('%Y-%m-%dT%H:%M:%S.%f')
@test.attr(type=['negative', 'gate'])
def test_get_usage_tenant_with_empty_tenant_id(self):
# Get usage for a specific tenant empty
params = {'... |
stsievert/swix | swix/speed/speed.py | Python | mit | 1,179 | 0.017812 | from __future__ import division
from pylab import *
from timeit import timeit
def pe1():
N = 1e6
x = arange(N)
i = argwhere((abs(x%3) < 1e-9) * (abs(x%5) < 1e-9))
def pe10():
N = 2e6
primes = arange(N)
for i in arange(2, sqrt(N)):
j = arange(2, N/i) * i
j = asarray(j, dtype=in... |
f = n / d
f = unique(f)
i = (f > 1/3) & (f < 1/2)
def soft_threshold():
N = 1e2
j = linspace(-1, 1, num=N)
(x, y) = meshgrid(j | , j)
z = pow(x, 2) + pow(y, 2)
i = abs(z) < 0.5
z[argwhere(i)] *= 0
z[argwhere(~i)] -= 0.5
def pi_approx():
N = 1e6
k = arange(N, dtype=int)
pi_approx = 1 / (2*k + 1)
pi_approx[2*k[:N/2]+1] *= -1
print "pe1_time : ", timeit(pe1 ,number=10)
print "pe10_time : ", timeit(pe10 ,n... |
cs-hse-projects/profanity-filter | profanity_filter/ui_progress_bar.py | Python | mit | 1,153 | 0.001735 | """
Progress bar encapsulation
"""
# Copyright (c) Timur Iskhakov.
# Distributed under the terms of the MIT License.
import progressbar
class | UIProgressBar:
__widgets = [' ', progressbar.Percentage(), ' ', progressbar.Bar(), ' ', progressbar.ETA()]
def __init__(self, message):
"""
:param message: :class:`str` Message to print
"""
self.message = message
self.progress_bar = None
self.value = 0
def... | x_value):
"""Initiates and starts the progress bar.
:param max_value: :class:`int`, Number of steps for bar
"""
self.progress_bar = progressbar.ProgressBar(widgets=[self.message] + UIProgressBar.__widgets,
maxval=max_value)
se... |
lhupfeldt/jenkinsflow | demo/jobs/calculated_flow_jobs.py | Python | bsd-3-clause | 1,296 | 0.003086 | # Copyright (c) 2012 - 2015 Lars Hupfeldt Nielsen, Hupfeldt IT
# All rights reserved. This work is under a BSD license, see LICENSE.TXT.
from collections import OrderedDict
from framework im | port api_select
def create_jobs(api_type):
g1_components = range(1)
g2_components = range(2)
g3_components = range(2)
component_groups = OrderedDict((('g1', g1_components), ('g2', g2_components), ('g3', g3_components)))
api = api_select.api(__file__, api_type)
def job(name, expect_order, para... | t_invocations=1, expect_order=expect_order, params=params)
api.flow_job()
job('prepare', 1)
for gname, group in component_groups.items():
for component in group:
job('deploy_component_' + gname + '_' + str(component), 2)
job('report_deploy', 3)
job('prepare_tests', 3)
job('t... |
bruecksen/isimip | isi_mip/sciencepaper/admin.py | Python | mit | 107 | 0.009346 | from django.contrib import admin
from isi_mip.sciencepaper.models i | mport Paper
admin.site.register(Pap | er) |
killabytenow/chirribackup | chirribackup/storage/Local.py | Python | gpl-3.0 | 5,284 | 0.006625 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
###############################################################################
# chirribackup/storage/Local.py
#
# Local backup storage -- backup is organized in a local folder
#
# -----------------------------------------------------------------------------
# Chirri Bac... | ile):
"""upload a file"""
target_file = self.__build_ls_path(remote_file, True)
shutil.copyfile(local_file, target_file)
|
def upload_data(self, remote_file, data):
"""post a file"""
target_file = self.__build_ls_path(remote_file, True)
with open(target_file, "wb", 0660) as ofile:
ofile.write(data)
def __get_listing(self, path = ""):
l = []
try:
for f in os.listdir... |
Zlash65/erpnext | erpnext/projects/doctype/project_template_task/project_template_task.py | Python | gpl-3.0 | 287 | 0.006969 | # -*- coding: utf-8 -*-
# Copyright (c) 2019 | , Frappe Technologies Pvt. Ltd. and contributors
# Fo | r license information, please see license.txt
from __future__ import unicode_literals
# import frappe
from frappe.model.document import Document
class ProjectTemplateTask(Document):
pass
|
Brainbuster/openpli-buildumgebung | bitbake/lib/toaster/bldcontrol/localhostbecontroller.py | Python | gpl-2.0 | 14,870 | 0.005783 | #
# ex:ts=4:sw=4:sts=4:et
# -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
#
# BitBake Toaster Implementation
#
# Copyright (C) 2014 Intel Corporation
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# pub... | ui_log = open(os.path.join(self.be.builddir, "toaster_ui.log"), "r").read()
toaster_server_log = open(os.path.join(self.be.builddir, "toaster_server.log") | , "r").read()
raise BuildSetupException("localhostbecontroller: Bitbake server did not start in 5 seconds, aborting (Error: '%s' '%s')" % (toaster_ui_log, toaster_server_log))
logger.debug("localhostbecontroller: Started bitbake server")
while port == "-1":
# the port specifica... |
YosefLab/scVI | scvi/core/models/__init__.py | Python | bsd-3-clause | 207 | 0 | from .archesmixin import ArchesMixin
from .base import BaseModelClass
from .rnamixin import RNASeqMixin
from .vaemixin import VAEMixin
__all__ = ["ArchesMixin", "BaseModelClass", "RN | ASeqMixi | n", "VAEMixin"]
|
craig5/python-samples | root_script/{{cookiecutter.proj_name}}/setup.py | Python | gpl-3.0 | 158 | 0 | #!/usr/bin/env python3
"""
Setup for root_script.
"""
# core python libaries
import setuptool | s
# third party libaries
# custom libraries
setuptools.setup()
| |
litoeknee/byteNet-tensorflow | utils.py | Python | mit | 271 | 0.03321 | import numpy as np
def weigh | ted_pick(weights):
t = np.cumsum(weights)
s = np.sum(weights)
return(int(np.searchsorted(t, np.random.rand(1)*s)))
def list_to_string(ascii_list):
res = u""
for a in ascii_list:
if a >= 0 and | a < 256:
res += unichr(a)
return res
|
voidrank/django-chunked-upload | chunked_upload/exceptions.py | Python | mit | 262 | 0 | """
Exc | eptions raised by django-chunked-upload.
"""
class ChunkedUploadError(Exception):
"""
Exception raised if errors in the reque | st/process.
"""
def __init__(self, status, **data):
self.status_code = status
self.data = data
|
ghchinoy/tensorflow | tensorflow/python/compiler/tensorrt/test/reshape_transpose_test.py | Python | apache-2.0 | 5,407 | 0.002404 | # Copyright 2018 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... | inference which then cause conversion to fail.
# TODO(laigd): support shape inference, make TRT optimizer run only
# once, and fix this.
incompatible_transpose = array_ops.transpose(
bridge, [2, 1, 0, 3], name="transpose-2 | ")
excluded_transpose = array_ops.transpose(
incompatible_transpose, [0, 2, 3, 1], name="transpose-3")
return array_ops.identity(excluded_transpose, name="output_0")
def GetParams(self):
return self.BuildParams(self.GraphFn, dtypes.float32, [[100, 24, 24, 2]],
[[24, 10... |
indianajohn/ycmd | ycmd/tests/clang/diagnostics_test.py | Python | gpl-3.0 | 7,250 | 0.026207 | # Copyright (C) 2015 ycmd contributors
#
# This file is part of ycmd.
#
# ycmd 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.
#
# ycmd... | diag_data = self._BuildRequest( compilation_flags = [ '-x', 'c++' ],
line_num = 7,
contents = contents,
f | iletype = 'cpp' )
event_data = diag_data.copy()
event_data.update( {
'event_name': 'FileReadyToParse',
} )
self._app.post_json( '/event_notification', event_data )
results = self._app.post_json( '/detailed_diagnostic', diag_data ).json
assert_that( results,
has_entry( 'm... |
ysung-pivotal/incubator-hawq | tools/bin/gppylib/pgconf.py | Python | apache-2.0 | 10,433 | 0.001821 | #!/usr/bin/env python
# $Id: $
"""
postgresql.conf configuration file reader
Module contents:
readfile() - Read postgresql.conf file
class gucdict - Container for postgresql.conf settings
class setting - Holds one setting
class ConfigurationError - a subclass of EnvironmentError
Example:
import li... | f 1024 bytes, or default if absent.
"""
v = self.get(name)
if v:
return v.kB()
else:
return default
def time(self, name, unit='s', default=None):
"""
Return time setting, or default if absent.
Specify desired unit as 'ms', 's', or 'min... | ""
Holds a GUC setting from a postgresql.conf file.
The str(), bool(), int(), float(), kB(), and time() methods return the
value converted to the requested internal form. pgconf.ConfigurationError
is raised if the conversion fails, i.e. the value does not conform to the
expected syntax.
"""
... |
shirleyChou/zhihu_crawler | zhihu.py | Python | mit | 19,263 | 0.000537 | #!/usr/bin/env python
# encoding: utf-8
import sys
import os
import re
import time
import json
import functools
import requests
from bs4 import BeautifulSoup
import html2text
reload(sys)
sys.setdefaultencoding('utf8')
# global var
_cookies_name = 'cookies.json'
_session = None
_headers = {'Host': 'www.zhihu.com',
... | profession = self.soup.find('sp | an', class_='business item') \
.get('title')
employment = self.soup.find('span', class_='employment item') \
.get('title')
position = self.soup.find('span', class_='position item').get('title')
return '行业: ' + profession \
+ '\n' + '公司: ' + empl |
deliarusu/text-annotation | knowledgebase/kbgraph.py | Python | apache-2.0 | 8,665 | 0.013964 |
'''
Graph representation of the knowledge base
'''
import networkx as nx
import math
import sys
from util import exception
MAXLOGDEG = 'maxlogdeg'
SQRTLOGDEG = 'sqrtlogdeg'
MAX_LEVEL = 5
EQUAL_WEIGHT = 'equal_weight'
LEVEL_WEIGHT = 'level_weight'
EPSILON = sys.float_info.epsilon
class Graph(object):
'''
... | maxd = d2
self.max_dist = maxd
except:
raise exception.GraphException(self.max_dist, \
| 'Error computing maximum distance')
def connected_concepts(self, node, level, weight_type = None):
'''
Connected concepts for a node in the graph
:param node: the node for which connected concepts are retrieved
:param level: d... |
hideoussquid/aureus-12-bitcore | qa/rpc-tests/getblocktemplate_longpoll.py | Python | mit | 3,620 | 0.005249 | #!/usr/bin/env python2
# Copyright (c) 2014-2015 The Aureus Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
from test_framework.test_framework import AureusTestFramework
from test_framework.util import *
def chec... | self.nodes[0])
thr.start()
# generate a random transaction and submit it
(txid, txhex, fee) = random_transaction(self.nodes, Decimal("1.1"), Decimal("0.0"), Decimal("0.001"), 20)
# after one minute, every 10 seconds the mempool is p | robed, so in 80 seconds it should have returned
thr.join(60 + 20)
assert(not thr.is_alive())
if __name__ == '__main__':
GetBlockTemplateLPTest().main()
|
gwpy/gwpy.github.io | docs/0.9.0/examples/frequencyseries/rayleigh-3.py | Python | gpl-3.0 | 409 | 0.002445 | asd = gwdata.asd(2, 1)
plot = asd.plot(figsize=(8, 6))
plot.add_frequ | encyseries(rayleigh, newax=True, sharex=plot.axes[0])
asdax, rayax = plot.axes
asdax.set_xlabel('')
asdax.set_xlim(30, 1500)
asdax.set_ylim(5e-24, 1e-21)
asdax.set_ylabel(r'[strain/\rtHz]')
rayax.set_ylim(0, 2)
rayax.set_ylabel('Rayleigh statistic')
asdax.set_title('Sensitivity of LIGO-Livingston around GW | 151226', fontsize=20)
plot.show() |
JarbasAI/JarbasAI | jarbas_skills/service_client_manager/__init__.py | Python | gpl-3.0 | 21,611 | 0.000555 | # Copyright 2016 Mycroft AI, Inc.
#
# This file is part of Mycroft Core.
#
# Mycroft Core 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 versio... | = self.settings[self.client_id].get(
"forbidden_messages", self.default_forbidden_messages)
self.forbidden_intents = self.settings[self.client_id].get(
"forbidden_intents", self.default_forbidden_intents)
self.last_seen = self.settings[self.client_id].get("last_seen",
... | ttings[self.client_id].get("last_ts", 0)
self.known_ips = self.settings[self.client_id].get("known_ips", [])
self.timestamp_history = self.settings[self.client_id].get(
"timestamp_history", [])
self.photo = self.settings[self.client_id].get("photo")
self.user_type = self.sett... |
alxgu/ansible | lib/ansible/modules/packaging/os/dpkg_selections.py | Python | gpl-3.0 | 2,174 | 0.00276 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright: Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
... | out.split()[1]
changed = current != selection
if module.check_mode or not changed:
module.exit_json(changed=changed, | before=current, after=selection)
module.run_command([dpkg, '--set-selections'], data="%s %s" % (name, selection), check_rc=True)
module.exit_json(changed=changed, before=current, after=selection)
if __name__ == '__main__':
main()
|
e-koch/ewky_scripts | multiprocess.py | Python | mit | 606 | 0.00165 |
'''
Wrap a given function into a pool
'''
from multiprocessing import Pool
from itertools import izip, repeat
def pool_process(func, args=None, ncores=1):
def single_ | input(a):
return func(*a)
# Check for inputs which need to be repeated.
for arg in args:
try:
if len(arg) == 1:
repeat_it | = True
except TypeError:
repeat_it = True
if repeat_it:
arg = repeat(arg)
pool = Pool(pool_process=ncores)
output = pool.map(single_input, izip(*args))
pool.close()
pool.join()
return output
|
boutiques/schema | tools/python/boutiques/bosh.py | Python | gpl-2.0 | 26,811 | 0.000298 | #!/usr/bin/env python
import jsonschema
import json
import os
import sys
import os.path as op
import tempfile
import pytest
from argparse import ArgumentParser, RawTextHelpFormatter
from jsonschema import ValidationError
from boutiques.validator import DescriptorValidationError
from boutiques.publisher import ZenodoEr... | {"forcePathType": True,
"destroyTempScripts": True,
"changeUser": True})
if not inp:
executor.generateRandomParams(1)
if results.json:
sout = [json.dumps(executor.in_dict, indent=4, sort_keys=True)]
... | executor.printCmdLine()
sout = executor.cmd_line
# for consistency with execute
# Adding hide to "container location" field since it's an invalid
# value, can parse that to hide the summary print
return ExecutorOutput(os.linesep.join(sout), "",
... |
scottrice/Ice | ice/backups.py | Python | mit | 1,971 | 0.014206 | # encoding: utf-8
import datetime
import os
from pysteam import shortcuts
import paths
from logs import logger
def default_backups_directory():
return os.path.join(paths.application_data_directory(), 'Backups')
def backup_filename(user, timestamp_format):
timestamp = datetime.datetime.now().strftime('%Y%m%d%H... | rtcuts." + timestamp + ".vdf"
def shortcuts_backup_path(directory, user, timestamp_ | format="%Y%m%d%H%M%S"):
"""
Returns the path for a shortcuts.vdf backup file.
This path is in the designated backup directory, and includes a timestamp
before the extension to allow many backups to exist at once.
"""
assert(directory is not None)
return os.path.join(
directory,
str(user.user_... |
jatinmistry13/BasicNeuralNetwork | two_layer_neural_network.py | Python | mit | 877 | 0.023945 | import sys
import numpy as np
# sigmoid function
def nonlin(x, deriv=False):
if(deriv==True):
return x*(1-x)
return 1/(1+np. | exp(-x))
# input dataset
X = np.array([[0,0,1],
[0,1,1],
| [1,0,1],
[1,1,1]])
# output dataset
y = np.array([[0,0,1,1]]).T
# seed random numbers to make calculation
# deterministic (just a good practice)
np.random.seed(1)
# initialize weights randomly with mean 0
syn0 = 2*np.random.random((3,1)) - 1
for iter in xrange(10000):
# forwar... |
elioth010/lugama | venv/lib/python2.7/site-packages/mongoengine/queryset/visitor.py | Python | gpl-2.0 | 4,434 | 0 | import copy
from mongoengine.errors import InvalidQueryError
from mongoengine.queryset import transform
__all__ = ('Q',)
class QNodeVisitor(object):
"""Base visitor class for visiting Q-object nodes in a query tree.
"""
def visit_combination(self, combination):
"""Called by QCombination objects... | , visitor):
for i in range(len(self.children)):
if isinstance(self.children[i], QNode):
self.children[i] = self.children[i].accept(visitor)
return visitor.visit_combination(self)
| @property
def empty(self):
return not bool(self.children)
class Q(QNode):
"""A simple query object, used in a query tree to build up more complex
query structures.
"""
def __init__(self, **query):
self.query = query
def accept(self, visitor):
return visitor.visit_... |
laysakura/relshell | relshell/test/test_record.py | Python | apache-2.0 | 461 | 0 | # -*- coding: utf | -8 -*-
from nose.tools import *
from relshell.record import Record
def test_record_usage():
rec = Record('good evening')
eq_(len(rec), 1)
rec = Record(' | Hello', 'World')
eq_(len(rec), 2)
rec = Record('lucky', 777, 'number')
eq_(len(rec), 3)
# get column by index
eq_(rec[0], 'lucky')
# iterate all columns
cols = []
for col in rec:
cols.append(col)
eq_(cols, ['lucky', 777, 'number'])
|
Lind-Project/native_client | build/directory_storage_test.py | Python | bsd-3-clause | 3,028 | 0.010568 | #!/usr/bin/python2
# Copyright (c) 2012 The Native Client Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Tests of directory storage adapter."""
import os
import unittest
import directory_storage
import fake_storage
import gsd_sto... | , url1)
def test_BadWrite(self):
def call(cmd):
return 1
storage = gsd_storage.GSDStorage(
gsutil=['mygsutil'],
write_bucket='mybucket',
read_buckets=[],
call=call)
dir_storage = directory_storage.DirectoryStorageAdapter(storage) |
# Check that storage exceptions come thru on failure.
with working_directory.TemporaryWorkingDirectory() as work_dir:
temp1 = os.path.join(work_dir, 'temp1')
hashing_tools_test.GenerateTestTree('bad_write', temp1)
self.assertRaises(gsd_storage.GSDStorageError,
dir_stor... |
GabrielNicolasAvellaneda/dd-agent | tests/checks/mock/test_wmi_check.py | Python | bsd-3-clause | 6,955 | 0.00115 | # project
from tests.checks.common import AgentCheckTest
Win32_OperatingSystem_attr = {
'BootDevice': "\\Device\\HarddiskVolume1",
'BuildNumber': "9600",
'BuildType': "Multiprocessor Free",
'Caption': "Microsoft Windows Server 2012 R2 Standard Evaluation",
'CodeSet': "1252",
'CountryCode': "1"... | ': [self.CONFIG]
}
self.run_check(config)
# Test metrics
for _, mname, _ in self.CONFIG['metrics']:
self.assertMetric(mname, tags=self.CONFIG['constant_tags'], count=1)
self.coverage_report()
def test_filter_and_tagging(self):
"""
Test `filters... | elf.FILTER_CONFIG]
}
self.run_check(config)
# Test metrics
for _, mname, _ in self.FILTER_CONFIG['metrics']:
self.assertMetric(mname, tags=["name:chrome"], count=1)
self.coverage_report()
def test_tag_queries(self):
"""
Test `tag_queries` parame... |
penzance/canvas_python_sdk | static_methods/users.py | Python | mit | 2,009 | 0.001991 | def list_users_in_account(request_ctx, account_id, search_term=None,
include=None, per_page=None, **request_kwargs):
"""
Retrieve the list of users associated with this account.
@example_request
curl https://<canvas>/api/v1/accounts/self/users?search_term=<search value> \
... | has
a numeric form. It will only search against other fields if non-numeric
in form, or if the numeric value doesn't yield any matches. Queries by
administrative users will search on SIS ID, name, or email address; non-
administrative queries will only be compared against name.
:type search_term: string or None... | results canvas should return, defaults to config.LIMIT_PER_PAGE
:type per_page: integer or None
:return: List users in account
:rtype: requests.Response (with array data)
"""
if per_page is None:
per_page = request_ctx.per_page
include_types = ('avatar_url', 'email', 'last_... |
pudo/nomenklatura | nomenklatura/dataset.py | Python | mit | 662 | 0 | from typing import Any
clas | s Dataset(object):
"""A unit of entities. A dataset is a set of data, sez W3C."""
def __init__(self, name: str, title: str) -> None:
self.name = name
self.title = title
def __eq__(self, other: Any | ) -> bool:
try:
return not not self.name == other.name
except AttributeError:
return False
def __lt__(self, other: "Dataset") -> bool:
return self.name.__lt__(other.name)
def __hash__(self) -> int:
return hash((self.__class__.__name__, self.name))
d... |
antoinecarme/pyaf | tests/neuralnet/test_ozone_rnn_only_LSTM.py | Python | bsd-3-clause | 1,418 | 0.019746 | import pandas as pd
import numpy as np
import pyaf.ForecastEngine as autof
import pyaf.Bench.TS_datasets as tsds
import logging
import logging.config
#logging.config.fileConfig('logging.conf')
logging.basicConfig(level=logging.INFO)
#get_ipython().magic('matplotlib inline')
b1 = tsds.load_ozone()
df = b1.mPastDa... | sts\n" , For | ecast_DF.tail(H));
print("\n\n<ModelInfo>")
print(lEngine.to_json());
print("</ModelInfo>\n\n")
print("\n\n<Forecast>")
print(Forecast_DF.tail(2*H).to_json(date_format='iso'))
print("</Forecast>\n\n")
|
osrf/rosbook | code/basics/src/message_publisher.py | Python | apache-2.0 | 344 | 0.002907 | #!/usr/bin/env python
import rospy
from basics.msg | import Complex
from random import random
rospy.init_node('message_publisher')
pub = rospy.Publisher('complex', Complex)
rate = rospy.Rate(2)
while not rospy.is_shutdown():
msg = Complex()
msg.real = random()
msg.imaginary = random()
pub.publish(msg)
| rate.sleep()
|
ijat/Hotspot-PUTRA-Auto-login | PyInstaller-3.2/PyInstaller/hooks/hook-wx.lib.activex.py | Python | gpl-3.0 | 571 | 0.005254 | #-----------------------------------------------------------------------------
# C | opyright (c) 2013-2016, PyInstaller Development Team.
#
# Distributed under the terms of the GNU General Public License with exception
# for distributing bootloader.
#
# The full license is in the file COPYING.txt, distributed with this software.
#------------------------------------------------------- | ----------------------
from PyInstaller.utils.hooks import exec_statement
# This needed because comtypes wx.lib.activex generates some stuff.
exec_statement("import wx.lib.activex")
|
mccorkle/seds-utils | KnownUsers.py | Python | gpl-3.0 | 4,260 | 0.004225 | class KnownUsers:
"""
This deals with both the dedicated server log AND the xml "user" file, as related to the known users.
TODO: refactor this to have a distinct class for the dedicatedLog and the users.xml
"""
def __init__(self, existing_users_filename):
"""Setup init variables parsing t... | e'], user['logoutTime']))
userLogins[user['loginName']] = user
del user
return userLogins
def getExistingUsers(self):
return self.existingUsers
# return self.knownUsersRoot.findall("./user")
def getNewUsers(self, playersDict):
newUsers = {}
for player ... | Root.findall("./user"):
if knownUser.get('inGameID') == playersDict[player]["inGameID"]:
foundKnownUser = 1
# childBranch = knownUser
if foundKnownUser == 0:
# print ("** NEW USER")
newUsers[playersDict[player]["inGameI... |
RossMeikleham/Numerical-Methods | tests/vandermonde_tests.py | Python | mit | 742 | 0.040431 |
import unittest
from numericalmethods.vandermonde import *
class TestsVandermonde(unittest.TestCase):
#Test generating Vandermonde matrix
def test_matrix(self):
v = vandermonde_matrix([1,2,3,4])
self.assertEqual(v.tolist(), [[1,1,1,1],[1,2,4,8],[1,3,9,27],[1,4,16,64] | ])
#Test determinant of Vandermonde matrix with more than 1 element
def test_det_multi(self):
d = vandermonde_det(vandermonde_matrix([1,2,3,4]))
self.assertEqual(d, 12)
#Tes | t determinant of Vandermonde matrix with exactly 1 element
def test_det_single(self):
d = vandermonde_det(vandermonde_matrix([1]))
self.assertEqual(d, 1)
#vandermonde_det
if __name__ == '__main__':
unittest.main()
|
riquito/Baobab | doc/source/conf.py | Python | apache-2.0 | 7,266 | 0.006744 | # -*- coding: utf-8 -*-
#
# Baobab documentation build configuration file, created by
# sphinx-quickstart on Tue Dec 7 00:44:28 2010.
#
# 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.
#
# All ... | les to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath('..'))
# -- General configuration ------------------------------------... | al Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.todo','jsonext']
# Add any paths that contain templates here, relative to this directory.
... |
chainer/chainercv | chainercv/extensions/evaluator/instance_segmentation_coco_evaluator.py | Python | mit | 7,737 | 0.000258 | import copy
import numpy as np
from chainer import reporter
import chainer.training.extensions
from chainercv.evaluations import eval_instance_segmentation_coco
from chainercv.utils import apply_to_iterator
try:
import pycocotools.coco # NOQA
_available = True
except ImportError:
_available = False
cl... | [#coco_ins_ext_3]_ [#coco_ins_ext_5]_
map/iou=0.50:0.95/area=large/max_dets=100, \
[#coco_ins_ext_3]_ [#coco_ins_ext_5]_
ar/iou=0.50:0.95/area=all/max_dets=1, \
[#coco_ins_ext_4]_
ar/iou=0.50/area=all/max_dets=10, \
[#coco_ins_ext_4]_
ar/iou=0.75/ar... | _ [#coco_ins_ext_5]_
ar/iou=0.50:0.95/area=medium/max_dets=100, \
[#coco_ins_ext_4]_ [#coco_ins_ext_5]_
ar/iou=0.50:0.95/area=large/max_dets=100, \
[#coco_ins_ext_4]_ [#coco_ins_ext_5]_
.. [#coco_ins_ext_1] Average precision for class \
:obj:`label_names[l]`, where :... |
StructuralNeurobiologyLab/SyConnFS | syconnfs/representations/segmentation_helper.py | Python | gpl-2.0 | 9,628 | 0.001246 | import cPickle as pkl
import networkx as nx
import numpy as np
import os
import scipy.spatial
from ..handler.basics import chunkify
from ..processing.general import single_conn_comp_img
from syconnmp.shared_mem import start_multiprocess_obj, start_multiprocess
from ..handler.compression import VoxelDict, AttributeDict... | f "mapping_ids" in so.attr_dict:
ids = so.attr_dict["mapping_ids"]
id_ratios = so.attr_dict["mapping_ratios"]
for i_id in range(len(ids)):
| if ids[i_id] in sv_id_dict:
sv_id_dict[ids[i_id]][so_id] = id_ratios[i_id]
else:
sv_id_dict[ids[i_id]] = {so_id: id_ratios[i_id]}
else:
if np.product(so.shape) > 1e8:
co... |
jmd-dk/concept | test/fluid_pressure/gen_ic.py | Python | gpl-3.0 | 976 | 0.004171 | # This file has to be run in pure Python mode!
# Imports from the CO𝘕CEPT code
from commons import *
from species import Component
from snapshot import save
# Create stationary, homogeneous matter distribution,
# perturbed with global, stationary sine wave along
# the x-direction.
w = user_params['_w']
ρ0 = user_pa... | nt = Component('test fluid', 'matter', gridsize=gridsize, boltzmann_order=2)
ρ = empty([gridsize]*3, dtype=float)
for i in range(gridsize):
x = boxsize*i/gridsize
ρ[i, :, :] = ρ0 + A*sin(x/boxsize*2*π)
component.populate(ρ, 'ϱ')
for multi_index in component.J.multi_indices:
component.populate(zer | os([gridsize]*3, dtype=float), 'J', multi_index)
for multi_index in component.ς.multi_indices:
component.populate(ones([gridsize]*3)*ρ*(1 + w)*σ, 'ς', multi_index)
# Save snapshot
save(component, initial_conditions)
|
thumbor-community/shortener | vows/generators/short_generator_vows.py | Python | mit | 1,326 | 0.002262 | # -*- coding: utf-8 -*-
# Copyright (c) 2015, thumbor-community
# Use of this source code is governed by the MIT license that can be
# found in the LICENSE file.
from pyvows import Vows, expect
from tc_shortener.generators.short_generator import Generator
from tc_core.context import Context
from thumbor.config impo... | mbor.importer import Importer
@Vows.batch
class ShortGeneratorVows(Vows.Context):
| class AShortGenerator(Vows.Context):
def topic(self):
config = Config()
importer = Importer(config)
context = Context(None, config, importer)
return Generator(context)
class WithIncorrectUrl(Vows.Context):
@Vows.capture_error
... |
haohaibo/tutorial | python/web-dev/server.py | Python | mit | 303 | 0 | # impo | rt module from wsgifref
from wsgiref.simple_server import make_server
# import our application
from hello import application
# create a server,IP NULL, port 8000
httpd = make_server('', 8000, application)
print "Serving HTTP on port 8000..."
# st | art listening HTTP request
httpd.serve_forever()
|
joberreiter/pyload | module/plugins/hooks/AntiStandby.py | Python | gpl-3.0 | 4,700 | 0.009574 | # -*- coding: utf-8 -*-
from __future__ import with_statement
import os
import time
import subprocess
import sys
try:
import caffeine
except ImportError:
pass
from module.plugins.internal.Addon import Addon, Expose
from module.utils import fs_encode, save_join as fs_join
class Kernel32(object):
ES_AWA... | s", 25 )]
__description__ = """Prevent OS, HDD and display standby"""
__license__ = "GPLv3"
__authors__ = [("Walter Purcaro", "vuolter@gmail.com")]
TMP_FILE = ".antistandby"
PERIODICAL_INTERVAL = 5
def init(self):
self.pid = None
self.mtime | = 0
def activate(self):
hdd = self.get_config('hdd')
system = not self.get_config('system')
display = not self.get_config('display')
if hdd:
self.start_periodical(self.get_config('interval'), threaded=True)
if os.name is "nt":
self.win_standby... |
paulsheridan/data-structures | src/deque.py | Python | mit | 964 | 0 | # -*- coding: utf-8 -*-
from double_linked import DoubleLinkedList
class Deque(object):
'''Deque is a composition of Double Linked List'''
def __init__(self, in | put=None):
'''create doubly linked list'''
self.deque = DoubleLinkedList(input)
def append(self, val):
self.deque.append(val)
def append_left(self, val):
self.deque.insert(val)
def pop(self):
return self.deque.pop()
def pop_left(self):
return self.dequ... | try:
return self.deque.tail.data
except AttributeError:
return None
def size(self):
size = 0
current_spot = self.deque.head
while current_spot:
size += 1
current_spot = current_spot.toward_tail
return size
|
lilchurro/vent | vent/menus/main.py | Python | apache-2.0 | 30,458 | 0.000328 | import npyscreen
import os
import re
import sys
import time
from docker.errors import DockerException
from npyscreen import notify_confirm
from threading import Thread
from vent.api.actions import Action
from vent.api.menu_helpers import MenuHelper
from vent.helpers.meta import Containers
from vent.helpers.meta impor... | ng is happening """
# give a little extra time for file descriptors to close
time.sleep(0.1)
self.addfield.value = Timestamp()
self.addfield.display()
self.addfield2.value = Uptime()
self.addfield2.display()
self.addfield3.value = str(len(Containers()))+" running... | eld3.display()
# update core tool status
self.addfield5.value, values = MainForm.t_status(True)
if values[0] + values[1] == 0:
color = "DANGER"
self.addfield4.labelColor = "CAUTION"
self.addfield4.value = "Idle"
elif values[0] >= int(values[2]):
... |
StackStorm/st2 | st2actions/setup.py | Python | apache-2.0 | 1,772 | 0.000564 | # -*- coding: utf-8 -*-
# Copyright | 2020 The StackStorm Authors.
# Copyright 2019 Extreme Networks, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... | is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import
import os.path
from setuptools import setup, find_packages
from... |
rtx3/deyun.io | smwds/api/models.py | Python | mit | 8,469 | 0.002634 | # -*- coding: utf-8 -*-
from sqlalchemy import Column, desc, func
from sqlalchemy.orm import backref
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import UserMixin
from extensions import db, cache
from utils import get_current_time
from constants import USER, USER_ROLE, ... | lt="")
#location_id = Column(UUIDType(binary=False), db.ForeignKey(
# 'location.id'), nullable=False, default="", info={'verbose_name': u'提供商', })
#location = db.relationship('Location', backref='nodes')
bio = Column(db.Text, default="", info={'verbose_name': u'备注', })
ssh_key = Column(db.String(... | =get_current_time, info={
'verbose_name': u'创建时间', })
update_at = Column(db.DateTime, info={'verbose_name': u'更新时间', })
master_id = Column(UUIDType(binary=False), db.ForeignKey(
'masterdb.id'), nullable=False, default="", info={'verbose_name': u'Master', })
master = db.relatio... |
dewtx29/python_ann | project/num/c++/testGraph.py | Python | gpl-3.0 | 277 | 0.021661 | import matplotlib.pyplot as plt
import random
dotList = []
xMax = 100
yMax | = 100
for i in range (0,xMax):
y = random.random()*yMax
y = i * 2
bb = [y]
dotList.append(bb)
print | dotList
plt.plot(dotList, 'ro')
#plt.axis([0, xMax, 0, yMax])
plt.show()
|
5monkeys/reqlice | reqlice/requirement.py | Python | mit | 926 | 0 | from pip.req import parse_requirements as pip_parse_requirements
from pip.req import InstallRequirement
def is_pypi_requirement(requirement):
return r | equirement.req and not requirement.link
def parse_requirements(path_to_requirements):
""" Parse requirements
:param path_to_requirements: path/to/requirements.txt
:return: ['package name', ..]
"""
parsed_reqs = []
for requirement in pip_parse_requirements(path_to_requirements,
... | if not is_pypi_requirement(requirement):
continue
parsed_reqs.append(requirement.req.project_name)
return parsed_reqs
def get_valid_pypi_requirement(line):
try:
requirement = InstallRequirement.from_line(line)
if not is_pypi_requirement(requirement):
r... |
OptimalPayments/Python_SDK | src/PythonNetBanxSDK/CardPayments/Pagination.py | Python | mit | 1,081 | 0.007401 | '''
Created on 17-Feb-2015
@author: Asawari.Vaidya
'''
from PythonNetBanxSDK.common.DomainObject import DomainObject
class Pagination(DomainObject):
'''
classdocs
'''
def __init__(self,obj):
'''
Constructor
'''
# Handler dictionary
handler = dict()
han... | ty Limit
'''
def limit(self, limit):
self.__dict__['limit'] = limit
'''
Property Offset
'''
def offset(self, offset):
self.__dict__['offset'] = offset
'''
Property Start Date
'''
def startDate(self, startDate):
self.__dict__['startDate'] ... | e'] = endDate
|
alfa-addon/addon | plugin.video.alfa/lib/cloudscraper/interpreters/native.py | Python | gpl-3.0 | 8,626 | 0.004521 | from __future__ import absolute_import
import ast
import re
import operator as op
import pyparsing
from ..exceptions import CloudflareSolveError
from . import JavaScriptInterpreter
# ------------------------------------------------------------------------------- #
_OP_MAP = {
ast.Add: op.add,
... | ery Parser for Math
stack = []
bstack = []
| for i in flatten(pyparsing.nestedExpr().parseString(jsFuck).asList()):
if i == '+':
stack.append(bstack)
bstack = []
continue
bstack.append(i)
stack.append(bstack)
return int(''.join(... |
rouxcode/django-cms-plugins | cmsplugins/headers/migrations/0001_initial.py | Python | mit | 2,379 | 0.005885 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.9 on 2016-09-26 08:54
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import filer.fields.image
class Migration(migrations.Migration):
initial = True
dependencies = [
('cms', '0016_au... | to='cms.CMSPlugin')),
('css_class', models.CharField(blank=True, default='', max_length=200, verbose_name='css class')),
('in_navigation', models.BooleanField(default=False, verbose_name='i | n navigation')),
('is_visible', models.BooleanField(default=True, verbose_name='visible')),
('height', models.CharField(blank=True, default='', max_length=100, verbose_name='height')),
('width', models.CharField(blank=True, default='', max_length=50, verbose_name='width')... |
njr0/abouttag | abouttag/location.py | Python | mit | 840 | 0 | # -*- coding: utf-8 -*-
"""
abouttag.location
Standard about tags for URIs and URLs
Copyright 2010 AUTHORS (see AUTH | ORS file)
License: MIT, see LICENSE for more information
"""
from abouttag import about
def GEOnet(fli, fni, normalize=False, convention=u'geonet-1'):
"""Usage:
from abouttag.uri import GEOnet
normalURL = URI(-2601490, -3577649)
"""
assert convention.lower() == u'geonet-1'
return... | ):
def testFluidDBBadConvention(self):
self.assertRaises(AssertionError, GEOnet, 1, 2, convention='unknown')
def testFluidDBNormalize(self):
expected = (
((1, 2), u'GEOnet1_2'),
((-99999, -77777), u'GEOnet-99999_-77777')
)
self.vectorTest(expected, GEOnet... |
mostateresnet/keyformproject | keyformproject/wsgi.py | Python | mit | 405 | 0 | """
WSGI config for keyformproject project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this | file, see
https://docs.djangoproject.com/en/dev/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "keyformproject.settings")
applica | tion = get_wsgi_application()
|
opendatateam/udata | udata/tests/test_uris.py | Python | agpl-3.0 | 8,266 | 0.000122 | import pytest
from udata import uris
from udata.settings import Defaults
PUBLIC_HOSTS = [
'http://foo.com/blah_blah',
'http://foo.com/blah_blah/',
'http://foo.com/blah_blah_(wikipedia)',
'http://foo.com/blah_blah_(wikipedia)_(again)',
'http://www.example.com/wpstyle/?p=364',
'https://www.exam... | m_tlds_should_not_validate_defaults(tl | d):
url = 'http://somewhere.{0}'.format(tld)
with pytest.raises(uris.ValidationError):
uris.validate(url, tlds=CUSTOM_TLDS)
@pytest.mark.parametrize('url', WITH_CREDENTIALS)
def test_with_credentials(url):
assert uris.validate(url) == url
@pytest.mark.parametrize('url', WITH_CREDENTIALS)
def tes... |
Xobb/fabric-bolt | src/fabric_bolt/accounts/tables.py | Python | mit | 1,653 | 0.005445 | """
Tables for the account app
"""
from django.contrib.auth import get_user_model
import django_tables2 as tables
from fabric_bolt.core.mixins.tables import ActionsColumn, PaginateTable
class UserListTable(Pa | ginateTable):
"""
Table for displaying users.
"""
actions = ActionsColumn([
{'title': '<i class="glyphicon glyphicon-file"></i>', 'url': 'accounts_user_view', 'args': [tables.A('pk')],
'attrs':{'data-toggle': 'tooltip', 'title': 'View User', 'data-delay': '{ "show": 300, "hide": 0 }'}}... | r', 'data-delay': '{ "show": 300, "hide": 0 }'}},
{'title': '<i class="glyphicon glyphicon-trash"></i>', 'url': 'accounts_user_delete', 'args': [tables.A('pk')],
'attrs':{'data-toggle': 'tooltip', 'title': 'Delete User', 'data-delay': '{ "show": 300, "hide": 0 }', 'class': 'js-delete'}},
], delimit... |
nop33/indico | indico/core/db/sqlalchemy/custom/greatest.py | Python | gpl-3.0 | 1,227 | 0.000815 | # This file is part of Indico.
# Copyright (C) 2002 - 2017 European Organization for Nuclear Research (CERN).
#
# Indico 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 Found | ation; either version 3 of the
# License, or (at your option) any la | ter version.
#
# Indico 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... |
Unofficial-Extend-Project-Mirror/openfoam-extend-Breeder-other-scripting-PyFoam | PyFoam/RunDictionary/MeshInformation.py | Python | gpl-2.0 | 2,537 | 0.016161 | """Gets information about the mesh of a case. Makes no attempt to manipulate
the mesh, because this is better left to the OpenFOAM-utilities"""
from PyFoam.RunDictionary.SolutionDirectory import SolutionDirectory
from PyFoam.RunDictionary.ListFile import ListFile
from PyFoam.Error import PyFoamException
from PyFoam.Ru... | der
from os import path
import re
class MeshInformation:
"""Reads Information about the mesh on demand"""
def __init__(self,
case,
time="constant",
processor=None,
region=None):
""":param case: Path to t | he case-directory
:param time: Time for which the mesh should be looked at
:param processor: Name of the processor directory for decomposed cases"""
self.sol=SolutionDirectory(case,paraviewLink=False,archive=None,region=region)
self.time=time
self.processor=processor
... |
gebn/nibble | nibble/information.py | Python | mit | 13,259 | 0.000754 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, division
from collections import OrderedDict
from decimal import Decimal
import re
import math
import six
from nibble import util, decorators
@decorators.python_2_div_compatible
@decorators.python_2_nonzero_compatible
@six.python_2_unicode_compatible
c... | ymbol):
"""
Find whether a symbol is a valid unit of information.
:param symbol: The symbol to check.
:return: True if the symbol is a valid unit, false otherwise.
"""
return symbol in cls._SYMBOLS
@classmethod
def is_valid_category(cls, category):
"""
... | e if the category is valid, false otherwise.
"""
return category in cls._CATEGORY_MAPS
def at_speed(self, speed):
"""
Find how long it would take to process this amount of data at a certain
speed.
:param speed: The speed of processing.
:return: The time take... |
arskom/JsQt | src/jsqt/il/qt/gui.py | Python | gpl-2.0 | 7,372 | 0.003798 | # encoding: utf8
#
# This file is part of JsQt.
#
# Copyright (C) Arskom Ltd. www.arskom.com.tr
#
# 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 o... | tmp = {}
for e in elt[0]:
tmp[e.tag]=e
self.__min_width = tmp['width']
self.__min_height = tmp['height']
| self.simple_prop_data['geometry.width'] = self.__min_width
self.simple_prop_data['geometry.height'] = self.__min_height
else:
jsqt.debug_print("\t\t", "WARNING: property 'minimumSize' doesn't "
"have a 'size' tag")
... |
nmiranda/dedupe | dedupe/datamodel.py | Python | mit | 4,180 | 0.010048 | import pkgutil
from collections import OrderedDict
import dedupe.variables
import dedupe.variables.base as base
from dedupe.variables.base import MissingDataType
from dedupe.variables.interaction import InteractionType
for _, module, _ in pkgutil.iter_modules(dedupe.variables.__path__,
... | ames.index(interaction_field))
indices.append(interaction_indices)
return indices
def typifyFields(fields) :
primary_fields = []
data_model = []
for definition in fields :
try :
field_type = definition['type']
except TypeError :
... | "include a type definition, ex. "
"{'field' : 'Phone', type: 'String'}")
except KeyError :
raise KeyError("Missing field type: fields "
"specifications are dictionaries that must "
"include a type defin... |
ephracis/hermes | utilities/lists.py | Python | mit | 1,117 | 0.048344 | """ This file contains code for working on lists and dictionaries. """ |
def moreThanOne(dict, key):
""" Checks if a key in a dictionary has a value more than one.
Arguments:
dict -- the dictionary
key -- the key
Returns:
True if | the key exists in the dictionary and the value is at least one, otherwise false
"""
return key in dict and dict[key] > 0
def anyMoreThanOne(dict, keys):
""" Checks if any of a list of keys in a dictionary has a value more than one.
Arguments:
dict -- the dictionary
keys -- the keys
Returns:
True if... |
iglpdc/nipype | nipype/interfaces/fsl/tests/test_auto_WarpPointsToStd.py | Python | bsd-3-clause | 1,546 | 0.021992 | # AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from ....testing import assert_equal
from ..utils import WarpPointsToStd
def test_WarpPointsToStd_inputs():
input_map = dict(args=dict(argstr='%s',
),
coord_mm=dict(argstr='-mm',
xor=['coord_vox'],
),
coord_vox=dict(argstr='-vox',
xor=[... | out_file=dict(name_source='in_coords',
| name_template='%s_warped',
output_name='out_file',
),
premat_file=dict(argstr='-premat %s',
),
std_file=dict(argstr='-std %s',
mandatory=True,
),
terminal_output=dict(nohash=True,
),
warp_file=dict(argstr='-warp %s',
xor=['xfm_file'],
),
xfm_file=dict(argstr='-xfm %s... |
zitryss/Design-Patterns-in-Python | behavioral/null_object.py | Python | mit | 965 | 0 | """
Encapsulate the absence of an object by providing a substitutable
alternative that offers suitable default do nothing behavior.
"""
import abc
class AbstractObject(metaclass=abc.ABCMeta):
"""
Declare the interface for Client's collaborator.
Implement default behavior for the interface common to all c... | def request(self):
pass
class NullObject(AbstractObject):
"""
Provide an interface identical to AbstractObject's so that a null
object can be substituted for a real object.
Implement its interface to do nothing. What exactly it means to do
nothing depends on what sort of behavior Client is... | :
pass
|
mit-ll/python-keylime | keylime/revocation_notifier.py | Python | bsd-2-clause | 5,242 | 0.001145 | '''
SPDX-License-Identifier: Apache-2.0
Copyright 2017 Massachusetts Institute of Technology.
'''
from multiprocessing import Process
import threading
import functools
import time
import os
import sys
import signal
import simplejson as json
import zmq
from keylime import config
from keylime import crypto
from keylim... | frontend, backend)
global broker_proc
broker_proc = Process(target=worker)
broker_proc.start()
def stop_broker():
global broker_proc
if broker_proc is not None:
# Remove the socket file before we kill the process
if os.path.exists("/tmp/keylime | .verifier.ipc"):
os.remove("/tmp/keylime.verifier.ipc")
os.kill(broker_proc.pid, signal.SIGKILL)
def notify(tosend):
def worker(tosend):
context = zmq.Context()
mysock = context.socket(zmq.PUB)
mysock.connect("ipc:///tmp/keylime.verifier.ipc")
# wait 100ms for c... |
andrewseidl/chrono | src/demos/python/demo_solidworks_irrlicht.py | Python | bsd-3-clause | 2,784 | 0.015445 | #-------------------------------------------------------------------------------
# Name: modulo1
# Purpose:
#
# Author: tasora
#
# Created: 14/02/2012
# Copyright: (c) tasora 2012
# Licence: <your licence>
#-------------------------------------------------------------------------------
#!/usr/bin/... | ---------------------------------------------------------
#
# load the file generated by the SolidWorks CAD plugin
# and add it to the ChSystem
#
print ("L | oading C::E scene...");
exported_items = chrono.ImportSolidWorksSystem('../../../data/solid_works/swiss_escapement')
print ("...done!");
# Print exported items
for my_item in exported_items:
print (my_item.GetName())
# Add items to the physical system
for my_item in exported_items:
my_system.Add(my_item)
... |
taogeT/livetv_mining | crawler/gather/daily_spiders/douyu.py | Python | apache-2.0 | 2,933 | 0.002728 | # -*- coding: utf-8 -*-
from scrapy import Spider, Request
from sqlalchemy import create_engine, func
from sqlalchemy.orm import sessionmaker
from datetime import datetime, timedelta
from ..models import LiveTVSite, LiveTVRoom, LiveTVRoomPresent, DAILY_DATE_FORMAT
from ..items import DailyItem
import numpy
import jso... | followers'],
'description': '',
'announcement': room_info['show_details'],
'fallback': True
| })
|
megapctr/Yak | tests/projects/querysets.py | Python | mit | 382 | 0 | from model_mommy.mommy import make
from yak.projects.models import Project
def test_accessible_to(me):
my_project = make(Project, owner=me)
their | _project = make(Project, team_members=[me])
foreign_project = make(Project)
qs = Project.objects.accessible_to(me)
| assert set(qs) == {my_project, their_project}
assert foreign_project in Project.objects.all()
|
theatlantic/python-active-directory | tut/tutorial2.py | Python | mit | 356 | 0.002809 | from activedirectory import Client, Creds, activate
domain = 'freeadi.org'
creds = Creds(domain)
creds.load()
activate(creds)
client = Client(domain)
users = client.search('(objectClass=user)', schem | e='gc')
for dn,attrs in users:
name = attrs['sAMAccountName'][0]
| domain = client.domain_name_from_dn(dn)
print('-> %s (%s)' % (name, domain))
|
kyamagu/psd2svg | tests/test_convert.py | Python | mit | 1,077 | 0.000929 | from __future__ import absolute_import, unicode_literals
from builtins import str
import os
import pytest
import io
from glob import glob
from psd_tools import PSDImage
from psd2svg import psd2svg
FIXTURES = [
p for p in glob(
os.path.join(os.path.dirname(__file__), 'fixtures', '*.psd'))
]
@pytest.ma... | as f:
assert isinstance(psd2svg(f), str)
@pytest.mark.parametrize('psd_file', FIXTURES[0:1])
def test_input_psd(tmpdir, psd_file):
psd = PSDImage.open(psd_file)
psd2svg(psd)
@pytest.mark.parametrize('psd_file', FIXTURES[2:3])
def test_input_layer(tmpdir, psd_file):
psd = PSDImage.open(psd_file)... | )
@pytest.mark.parametrize('psd_file', FIXTURES[0:1])
def test_output_io(tmpdir, psd_file):
with io.StringIO() as f:
assert f == psd2svg(psd_file, f)
|
paylogic/atilla | atilla/pagination.py | Python | mit | 3,235 | 0.002473 | """ | Helperfunctions for paginat | ion."""
import collections
import math
from six.moves import http_client
from six.moves.urllib import parse as urlparse
from flask import url_for, current_app
from atilla import exceptions
PageResponse = collections.namedtuple('PageResponse', 'content,count')
def parse_current_page(page):
"""Get page number fr... |
biosustain/optlang | slow_tests/test_miplib_gurobi_interface.py | Python | apache-2.0 | 3,070 | 0.002606 | # Copyright 2014 Novo Nordisk Foundation Center for Biosustainability, DTU.
# 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 ... | ributed 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.
import gzip
import json
import os
import tempfile
import unittest
from functools import partial
import nose
try:
import gurobipy
except ImportError as e:
raise nose.SkipTest('Skipping MILP tests because gurobi is not available.')
else:
from optlang.gurobi_interface import Model
# proble... |
mozman/ezdxf | examples/addons/r12writer.py | Python | mit | 2,030 | 0 | # Copyright (c) 2020 Manfred Moitzi
# License: MIT License
from pathlib import Path
from time import perf_counter
import math
from ezdxf.addons import MengerSponge
from ezdxf.addons import r12writer
from ezdxf.render.forms import sphere, circle, translate
DIR = Path("~/Desktop/Outbox").expanduser()
def menger_sponge... | 0, 0.2, 0.000001), (12, 4)],
format="xybse",
start_width=0.1,
end_width=0.1,
color=5,
)
print(f'saved as "{filename}".')
if __name__ == "__main__":
menger_sponge(DIR / "menger_sponge_r12.dxf", level=2)
polymesh(DIR / "polymesh.dxf", size=(20, 10))
... | .dxf")
|
aldian/tensorflow | tensorflow/python/ops/image_ops_impl.py | Python | apache-2.0 | 217,245 | 0.003701 | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | : >= 3-D Tensor of size [*, height, width, depth]
| require_static: If `True`, requires that all dimensions of `image` are known
and non-zero.
Raises:
ValueError: if image.shape is not a [>= 3] vector.
Returns:
An empty list, if `image` has fully defined dimensions. Otherwise, a list
containing an assert op is returned.
"""
try:
if image... |
s3ql/main | src/s3ql/parse_args.py | Python | gpl-3.0 | 14,648 | 0.003687 | '''
argparse.py - this file is part of S3QL.
Copyright © 2008 Nikolaus Rath <Nikolaus@rath.org>
This work can be distributed under the terms of the GNU GPLv3.
This module provides a customized ArgumentParser class. Differences
are:
* a --version argument is added by default
* convenience functions are availabl... | oup(2)
if alg not in ('none', 'zlib', 'bzip2', 'lzma'):
raise argparse.ArgumentTypeError('Invalid compression algorithm: %s' % alg)
if lvl is None:
lvl = 6
else:
lvl = int(lvl)
if alg == 'none':
alg = None
... | return (alg, lvl)
self.add_argument("--compress", action="store", default='lzma-6',
metavar='<algorithm-lvl>', type=compression_type,
help="Compression algorithm and compression level to use when "
"storing new data. *a... |
jcberquist/SublimeText-Lucee | src/modelcompletions/documentation.py | Python | mit | 1,258 | 0.023847 | STYLES = {
"side_color": "#4C9BB0",
"header_color": "#306B7B",
"header_bg_color": "#E4EEF1",
"text_color": "#272B33"
}
def get_documentation(bean_name, file_path, function_name, function_metadata):
model_doc = dict(STYLES)
model_doc["links"] = [{"href": "go_to_definition", "text": "Go to Definition"}]
model_do... | ader"] = "<em>" + function_metadata["access"] + "</em> " + model_doc["header"]
if len(function_metadata["returntype"]) > 0:
model_doc["header"] += ":" + function_metadata["returntype"]
model_doc["description"] = "<small>" + file_path + "</small>"
model_doc["body"] = ""
if len(function_metadata["arguments"]) > 0... | ody"] += "required "
if arg_params["type"]:
model_doc["body"] += "<em>" + arg_params["type"] + "</em> "
model_doc["body"] += "<strong>" + arg_name + "</strong>"
if arg_params["default"]:
model_doc["body"] += " = " + arg_params["default"]
model_doc["body"] += "</li>"
model_doc["body"] += "</ul>"
... |
zephyrproject-rtos/zephyr | doc/_extensions/zephyr/vcs_link.py | Python | apache-2.0 | 2,232 | 0.000896 | """
VCS Link
########
Copyright (c) 2021 Nordic Semiconductor ASA
SPDX-License-Identifier: Apache-2.0
Introduction
============
This Sphinx extension can be used to obtain the VCS URL for a given Sphinx page.
This is useful, for example, when adding features like "Open on GitHub" on top
of pages. The extension insta... | path).
Returns:
VCS URL if applicable, None otherwise.
"""
if not os.path.isfile(app.env.project.doc2path(pagename)):
return None
for exclude in app.config.vcs_link_exclude:
if re.match(exclude, pagename):
return None
found_prefix = ""
for pattern, prefix ... | pp.config.vcs_link_base_url,
found_prefix,
app.env.project.doc2path(pagename, basedir=False),
]
)
def add_jinja_filter(app: Sphinx):
if app.builder.name != "html":
return
app.builder.templates.environment.filters["vcs_link_get_url"] = partial(
vcs_link_get_... |
jvrsantacruz/XlsxWriter | xlsxwriter/test/comparison/test_chart_data_labels11.py | Python | bsd-2-clause | 1,503 | 0.000665 | ###############################################################################
#
# Tests for XlsxWriter.
#
# Copyright (c), 2013-2015, John McNamara, jmcnamara@cpan.org
#
from ..excel_comparsion_test import ExcelComparisonTest
from ...workbook import Wor | kbook
class TestCompareXLSXFiles(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
| self.maxDiff = None
filename = 'chart_data_labels11.xlsx'
test_dir = 'xlsxwriter/test/comparison/'
self.got_filename = test_dir + '_test_' + filename
self.exp_filename = test_dir + 'xlsx_files/' + filename
self.ignore_files = []
self.ignore_elements = {}
def ... |
eharney/nova | nova/tests/api/openstack/compute/test_image_metadata.py | Python | apache-2.0 | 9,569 | 0 | # Copyright 2011 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... | bad', body)
def test_delete(self):
req = fakes.HTTPRequest.blank('/v2/fake/images/123/metadata/key1')
req.method = 'DELETE'
res = self.controller.delete(req, '123', 'key1')
self.assertIsNone(res)
def test_delete_not_found(self):
req = fakes.HTTPRequest.blank('/v2/fake/... | self.assertRaises(webob.exc.HTTPNotFound,
self.controller.delete, req, '123', 'blah')
def test_delete_image_not_found(self):
req = fakes.HTTPRequest.blank('/v2/fake/images/100/metadata/key1')
req.method = 'DELETE'
self.assertRaises(webob.exc.HTTPNotFound,
... |
mscuthbert/abjad | abjad/tools/pitchtools/test/test_pitchtools_PitchSegment___min__.py | Python | gpl-3.0 | 214 | 0.004673 | # -*- encoding: utf-8 -*-
from abjad import *
def test | _pitchtools_PitchSegment___min___01():
pitch_segment = pitchtools.PitchSegment([-2, -1.5, 6, 7, -1.5, 7])
assert min(pitch_segment) == | NamedPitch(-2) |
plotly/python-api | packages/python/plotly/plotly/validators/sankey/_hoverlabel.py | Python | mit | 2,055 | 0.000487 | import _plotly_utils.basevalidators
class HoverlabelValidator(_plotly_utils.basevalidators.CompoundValidator):
def __init__(self, plotly_name="hoverlabel", parent_name="sankey", **kwargs):
super(HoverlabelValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... | o or
more lines
alignsrc
| Sets the source reference on Chart Studio Cloud
for align .
bgcolor
Sets the background color of the hover labels
for this trace
bgcolorsrc
Sets the source reference on Chart Studio Cloud
for bgcolor .
... |
OpenEye-Contrib/OEMicroservices | oemicroservices/common/__init__.py | Python | apache-2.0 | 74 | 0 | # Initia | lization for oemicros | ervices.common
__all__ = ('functor', 'util')
|
PAIR-code/saliency | saliency/core/grad_cam_test.py | Python | apache-2.0 | 7,486 | 0.002939 | # Copyright 2021 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | UT_HEIGHT_WIDTH, INPUT_HEIGHT_WIDTH])
img[1:-1, 1:-1] = 1
img = img.reshape([INPUT_HEIGHT_WIDTH, INPUT_HEIGHT_WIDTH, 1])
expected_error = SHAPE_ERROR_MESSAGE[CONVOLUTION_LAYER_VALUES].format('1', '5')
with self.assertRaisesRegex(ValueError, expected_error):
self.grad_cam_instance.GetMask(
... | hould_resize=True,
three_dims=False)
if __name__ == '__main__':
unittest.main()
|
snipsco/ntm-lasagne | examples/associative-recall-task.py | Python | mit | 4,480 | 0.00558 | import theano
import theano.tensor as T
import numpy as np
import matplotlib.pyplot as plt
from lasagne.layers import InputLayer, DenseLayer, ReshapeLayer
import lasagne.layers
import lasagne.nonlinearities
import lasagne.updates
import lasagne.objectives
import lasagne.init
from ntm.layers import NTMLayer
from ntm.m... | 1-layer Neural Turing Machine)
l_output, l_ntm = model(input_var, batch_size=generator.batch_size,
size=generator.size, num_units=100, memory_shape=(128, 20))
# The generated output variable and the loss function
pred_var = T.clip(lasagne.layers.get_output(l_output), 1e-6, 1. - 1e-6)
loss = T.me... | ry_crossentropy(pred_var, target_var))
# Create the update expressions
params = lasagne.layers.get_all_params(l_output, trainable=True)
learning_rate = theano.shared(1e-4)
updates = lasagne.updates.adam(loss, params, learning_rate=learning_rate)
# Compile the function for a training step, as well as... |
CSC301H-Fall2013/JuakStore | Storefront/Storefront/settings.py | Python | mit | 5,847 | 0.001197 | import os
# Django settings for Storefront project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NA... | hat know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contri | b.staticfiles.finders.DefaultStorageFinder',
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = '5ff9b-_!8o66m+4dq!v!u3lq*5o)$oqgj1o#byi_j1l^koeko_'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'd... |
LorenzSelv/pinned | pinned/settings.py | Python | mit | 5,525 | 0.001448 | """
Django settings for pinned project.
Generated by 'django-admin startproject' using Django 1.11.6.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import os
... | 'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'social_django',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfVie... | 'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'pinned.urls'
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.AllowAny',
],
'DEFAULT_RENDERER_CLASSES': (
'rest_framew... |
evanbiederstedt/RRBSfun | scripts/repeat_finder_scripts/repeat_finder_RRBS_NormalBCD19pCD27mcell23_44_GTAGAGGA.A.py | Python | mit | 706 | 0.009915 | import glob
import numpy as np
import pandas as pd
from numpy import nan
import os
os.chdir("/gpfs/commons/home/biederstedte-934/evan_projects/RRBS_anno_clean")
repeats = pd.read_csv("repeats_hg19.csv")
annofiles = glob.glob("RRBS_NormalBCD19pCD27mcell23_44_GTAGAGGA.A*")
def between_range(row):
subset = repeats.... | oc[(row["chr"] == repeats.chr) & (row.start >= repeats.start) & (row.start <= repeats.end), :]
if subset.empty:
return np.nan
return subset.repeat_class
#newdf1 = pd.DataFrame()
for filename in annofiles:
df = pd.read_table(filename)
| df["hg19_repeats"] = df.apply(between_range, axis = 1)
df.to_csv(str("repeatregions_") + filename + ".csv", index=False)
|
COCS4950G7/COSC4950 | Source/demoCrack3.py | Python | gpl-3.0 | 6,305 | 0.005234 | # Chris Bugg
# 10/1/14
# NOTE: Runs on Python 2.7.6
# UPDATE:
# 10/10/14
# -> Now runs with 8 sub-processes using
# the [a-z,A-Z,0-9] alphabet
#
# 10/12/2014 UPDATE: Ubuntu 14.04, OS X, and Windows 7 have commited to this project by Chris H
# Ubuntu GUI ran 1.71 million hashe... | parentPipe, childPipe = Pipe()
children = []
for i in range( | 0, self.number_of_processes):
children.append(Process(target=self.subProcess, args=(childPipe, lock, )))
children[i].start()
for chunk in self.chunks:
parentPipe.send("6")
parentPipe.send(chunk)
count = 0
done = False
rec = 0
w... |
michaelBenin/Django-facebook | django_facebook/urls.py | Python | bsd-3-clause | 2,316 | 0.000864 | try:
from django.conf.urls import patterns, url
except ImportError:
from django.conf.urls.defaults import patterns, url
from django.conf import settings
urlpatterns = patterns(
'django_facebook.views',
url(r'^connect/$', 'connect', name='facebook_ | connect'),
url(r'^disconnect/$',
'disconnect', name='facebook_disconnect'),
url(r'^example/$', 'example', name='facebook_example'),
)
dev_patterns = patterns(
'django_facebook.example_views',
url(
r'^lazy_decorator_example/$', 'lazy_decorator_example',
name='facebook_lazy_decora... | r_example',
name='facebook_decorator_example'),
url(
r'^decorator_example_scope/$', 'decorator_example_scope',
name='facebook_decorator_example_scope'),
url(r'^wall_post/$',
'wall_post', name='facebook_wall_post'),
url(r'^checkins/$',
'checkins', name='facebook_checki... |
iver56/trondheim.kodeklubben.no | backend/wsgi/courses/views.py | Python | gpl-3.0 | 4,033 | 0 | from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.views.generic import View
from .models import \
Course, Registration, Task, TaskSubmission, ScoreProfile
from .forms import TaskSubmissionForm
class Course... | course=course).delete()
else:
return
if request.POST['sign_up'] == u'master':
Registration(user=request.user,
| course=course,
granted=False,
code_master=True,
role=Registration.CODE_MASTER).save()
elif request.POST['sign_up'] == u'kid':
Registration(user=request.user,
course=course,
... |
ibelikov/jimmy | jimmy/modules/throttle/__init__.py | Python | apache-2.0 | 43 | 0 | # -*- coding: utf-8 -*-
f | rom impl | import *
|
ellmetha/django-parler | parler/tests/test_admin.py | Python | apache-2.0 | 1,318 | 0.00607 | from __future__ import unicode_literals
from django.contrib.admin.util import label_for_field
from .utils import AppTestCase
from .testapp.models import SimpleModel, ConcreteModel, AbstractModel
class AdminTests(AppTestCase):
"""
Test admin features
"""
def test_list_label(self):
# Ensure mod... | TranslatedFieldDescriptor.short_description
self.assertEqual(label_for_field('tr_title', SimpleModel), "Translated Title")
d | ef test_list_label_abc(self):
# Ensure model data is correct
self.assertEqual(ConcreteModel._parler_meta.root_model._meta.get_field_by_name('tr_title')[0].verbose_name, "Translated Title")
# See that the TranslatedFieldDescriptor of the concrete model properly routes to the proper model
... |
ppeczek/Politikon | accounts/pipeline.py | Python | gpl-2.0 | 358 | 0 | from social.pipeli | ne.partial import partial
import logging
logger = logging.getLogger(__name__)
@partial
def save_profile(backend, user, response, *args, **kwargs):
print 'test2'
logger(backend)
logger(user)
logger(response | )
if backend.name == 'facebook':
print backend
if backend.name == 'twitter':
print backend
|
Alzon/senlin | senlin/tests/unit/engine/service/test_triggers.py | Python | apache-2.0 | 13,447 | 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
# distributed unde... | spec)
t1 = self.eng.trigger_ | create(self.ctx, 't-1', spec)
t2 = self.eng.trigger_create(self.ctx, 't-2', spec)
result = self.eng.trigger_list(self.ctx, limit=0)
self.assertEqual(0, len(result))
result = self.eng.trigger_list(self.ctx, limit=1)
self.assertEqual(1, len(result))
result = self.eng.trig... |
alexey4petrov/pythonFlu | Foam/helper.py | Python | gpl-3.0 | 2,152 | 0.032063 | ## pythonFlu - Python wrapping for OpenFOAM C++ API
## Copyright (C) 2010- Alexey Petrov
## Copyright (C) 2009-2010 Pebble Bed Modular Reactor (Pty) Limited (PBMR)
##
## 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 F... | ]
#print an_interface
an_interface_path = ".".join( a_result.split( "." )[ :-1 ] )
#print an_interface_path
exe | c "from %s import %s as a_result" %( an_interface_path, an_interface )
pass
exec "self.%s = a_result" %the_attr
return a_result
pass
#--------------------------------------------------------------------------------------
class TManLoadHelper( TLoadHelper ):
def __c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.