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 |
|---|---|---|---|---|---|---|---|---|
konono/equlipse | openstack-install/charm/trusty/charm-keystone/tests/charmhelpers/core/strutils.py | Python | mit | 3,680 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2014-2015 Canonical Limited.
#
# 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
#
# Unl... | ches.group(2)])
class BasicStringComparator(object):
"""Provides a clas | s that will compare strings from an iterator type object.
Used to provide > and < comparisons on strings that may not necessarily be
alphanumerically ordered. e.g. OpenStack or Ubuntu releases AFTER the
z-wrap.
"""
_list = None
def __init__(self, item):
if self._list is None:
... |
noemis-fr/old-custom | e3z_account_export_grouped/account_export.py | Python | agpl-3.0 | 28,581 | 0.006621 | # -*- coding: utf-8 -*-
###############################################################################
#
# Asgard Ledger Export (ALE) module,
# Copyright (C) 2005 - 2013
# Héonium (http://www.heonium.com). All Right Reserved
#
# Asgard Ledger Export (ALE) module
# is free software: you can redistribute it and/or modif... | d:
raise osv.except_os | v(_('No Journal/Period selected !'), _('You have to select Journal/Period before populate line.'))
jp_ids = journal_period_obj.read(cr, uid, map(lambda x:x.id,ale.journal_period_id), ['journal_id','period_id'])
start = time.time()
#suppression des lignes existantes
cr.exe... |
dennissergeev/classcode | lib/equil_run.py | Python | cc0-1.0 | 5,877 | 0.029607 | from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
import sys
#
# use pretty plotting if it can be imported
#
try:
import seaborn
except:
pass
sigma=5.67e-8
def find_tau(tot_trans,num_layers):
"""
# -TD- document using
"""
trans_layer=tot_trans**(1./num_layers)
... | _surf**4.
up_rad[0]=sfc_rad
tot_levs=len(tau_levels)
for index in np.arange(1,tot_levs):
upper_lev=index
lower_lev=index - 1
layer_ | num=index-1
del_tau=tau_levels[upper_lev] - tau_levels[lower_lev]
trans=np.exp(-1.666*del_tau)
emiss=1 - trans
layer_rad=sigma*Temp_layers[layer_num]**4.*emiss
up_rad[upper_lev]=trans*up_rad[lower_lev] + layer_rad
down_rad[tot_levs-1]=0
for index in np.arange(1,tot_levs):... |
SelvorWhim/competitive | Codewars/PlayingWithPassphrases.py | Python | unlicense | 735 | 0.013605 | class PassphraseMapper(object):
| def __init__(self, n):
self.n = n
def __getitem__(self, c):
c = chr(c)
if c.isalpha(): # circular shift for letters
a = ord('a') | if c.islower() else ord('A')
return chr(a + ((ord(c) - a + self.n) % 26))
if c.isdigit(): # complement to 9 for digits
return str(9 - int(c))
return c # leave the rest as is
def play_pass(s, n):
step3 = s.translate(PassphraseMapper(n)) # steps 1-3 (out of context character ... |
vmanoria/bluemix-hue-filebrowser | hue-3.8.1-bluemix/desktop/core/ext-py/pysaml2-2.4.0/doc/conf.py | Python | gpl-2.0 | 6,371 | 0.006749 | # -*- coding: utf-8 -*-
#
# pysaml2 documentation build configuration file, created by
# sphinx-quickstart on Mon Aug 24 08:13:41 2009.
#
# 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... | = 'index'
# General information about the project.
project = u'pysaml2'
copyright = u'2010-2011, Roland Hedberg'
# The version info for the project you're d | ocumenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '1.2'
# The full version, including alpha/beta/rc tags.
release = '1.2.0beta'
# The language for content autogenerated by Sphinx. Refer to documentatio... |
sein-tao/pyBioUtil | tests/test_decorator.py | Python | gpl-2.0 | 850 | 0.004706 | #!/usr/bin/env python3
import unittest
TestCase = unittest.TestCase
from BioUtil.decorator import context_decorator
import inspect
print(__file__)
class TestContextDecorator(TestCase):
def test_no_enter(self):
with self.assertRaises(AttributeError):
class A:
pass
| with A() as input:
pass
def test_decorator_enter(self):
| # test no raise
@context_decorator
class A:
def __init__(self):
pass
with A() as input:
pass
def test_decorator_enter_override(self):
with self.assertRaises(NotImplementedError):
@context_decorator
class A:
... |
tsudmi/json-database | setup.py | Python | mit | 867 | 0 | #!/usr/bin/env python
from setuptools import setup, find_packages
install_requires = [
'antlr4-python2-runtime==4.5',
'click==4.0'
]
setup(
name='json-database',
version='0.4.0',
author='D | mitri Chumak',
author_email='tsudmi@ut.ee',
url='https://github.com/tsudmi/json-database',
description='JSON Database is database which holds data in JSON format.',
long_description=open('README.md').read(),
packages=find_packages(),
install_requires=install_requires,
entry_points={
... | sts",
classifiers=[
'Intended Audience :: Education',
'Intended Audience :: Information Technology',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
],
)
|
yusufm/mobly | mobly/controllers/attenuator_lib/minicircuits.py | Python | apache-2.0 | 5,184 | 0.001157 | #!/usr/bin/env python3.4
#
# Copyright 2016 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable... | given index in the instrument.
Args: |
idx: This zero-based index is the identifier for a particular
attenuator in an instrument.
Raises:
Error is raised if the underlying telnet connection to the
instrument is not open.
Returns:
A float that is the current attenuation value... |
andrej5elin/camera | camera/bfly.py | Python | mit | 32,554 | 0.0184 | """A simple ctypes Wrapper of FlyCapture2_C API. Currently this only works with
graysale cameras in MONO8 or MONO16 pixel format modes.
Use it as follows:
>>> c = Camera()
First you must initialize.. To capture in MONO8 mode and in full resolution
run
>>> c.init( | ) #default to MONO8
Init also turns off all auto features (shutter, exposure, gain..) automatically.
It sets brigtness level to zero and no gamma and sharpness a | djustment (for true raw image capture).
If MONO16 is to be used run:
>>> c.init(pixel_format = FC2_PIXEL_FORMAT_MONO16)
To set ROI (crop mode) do
>>> c.init(shape = (256,256)) #crop 256x256 image located around the sensor center.
Additionaly you can specify offset of the cropped image (from the top lef... |
mostofi/wannier90 | examples/example33/kdotp_plot.py | Python | gpl-2.0 | 6,672 | 0.02473 | import numpy as N
import sys as SYS
import os as OS
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
from matplotlib import rc
rc('text', usetex=True)
font = FontProperties()
font.set_size(20)
#------------------------------------------------------
# ... | *12+index_x*4] ) - (full[index_x*12+index_y*4+3] + full[index_y*12+index_x*4+3] ) )
# a0
a0[2] = N.real(0.5*(full[index_x*(12+4)] + full[index_x*(12+4)+3]))
a0[3] = N.real(0.5*(full[inde | x_y*(12+4)] + full[index_y*(12+4)+3]))
a0[4] = 0.5*N.real( (full[index_x*12+index_y*4]+full[index_y*12+index_x*4] ) + (full[index_x*12+index_y*4+3] + full[index_y*12+index_x*4+3] ) )
# set up k.p band dispersion
# energy is in eV
# linear coefficients are in units of eV*Ang
# quadratic coefficients are in units of e... |
duct-tape/taped-tests | taped_tests/jobs.py | Python | bsd-3-clause | 563 | 0 | import redis
from django_rq import job
import logging
try:
import cPicle as pickle
excep | t ImportError:
im | port pickle
logger = logging.getLogger(__name__)
@job('test')
def test_job(testcase):
result = testcase.defaultTestResult()
logger.info('Invoking {}'.format(testcase))
testcase.run(result)
logger.info('Test result: {}'.format(result))
r = redis.StrictRedis(host='localhost', port=6379, db=0)
... |
mayankjohri/wakka-package-manager | wakkacore/terminal.py | Python | gpl-2.0 | 3,148 | 0.006036 | # This code is part of Wakka.
# Wakka is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
# Wakka is distributed in the hope that it will... | m)s; %(loc)s; exit\n" %{"pac": pacman, "loc": local, "rem": rem_pacs}
else:
| command = "%s; exit\n" %local
self.fork_command()
self.feed_child(command)
def do_upgrade(self):
self.fork_command()
self.feed_child("pacman -Su --noconfirm; exit\n")
def close(self, term, close_button):
close_button.show()
return
|
MBALearnsToCode/PyMathFunc | MathFunc/__init__.py | Python | mit | 13,313 | 0.002704 | from __future__ import print_function
from CompyledFunc import CompyledFunc
from copy import copy as shallowcopy, deepcopy
from frozendict import frozendict
from HelpyFuncs.Dicts import combine_dict_and_kwargs, merge_dicts_ignoring_dup_keys_and_none_values
from HelpyFuncs.SymPy import sympy_allclose, sympy_xreplac... | :
reduce_func = add
if 'rev_transf' in kwargs:
rev_transf_func = kwargs['rev_transf']
else:
rev_transf_func = itself
var_names_and_symbols___dict = self.Vars.copy() # just to be careful
scope = self.Scope.copy() # just to be careful
... | zed_var]
del scope[marginalized_var]
d = {}
for vars_and_values___frozen_dict, func_value in mapping.items():
marginalized_var_value = vars_and_values___frozen_dict[marginalized_var]
fd = frozendict(set(vars_and_values___frozen_dict.items()) -
... |
lertech/extra-addons | network/model/digitalocean/Size.py | Python | gpl-3.0 | 330 | 0 | class Size(object):
def __init__(self, client_id="", api_key=""):
self.client_id = client_id
self.api_key = api_key
self.na | me = None
self.id = None
self.memory = None
self.cpu = None
self.disk = No | ne
self.cost_per_hour = None
self.cost_per_month = None
|
drpjm/udacity-mle-project5 | src/tfhelpers.py | Python | mit | 2,195 | 0.010934 | '''
Created on Oct 4, 2016
@author: pjmartin (but mostly the Google TF tutorial site)
'''
import tensorflow as tf
# variable declaration helper functions
# Make the weight variables be a little noisy around 0.0.
def weight_variable(shape, var_name):
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variabl... | cope(layer_name):
with tf.name_scope('weights'):
| W = tf.Variable(tf.truncated_normal([in_dim, out_dim]))
variable_summaries(W, layer_name + '/weights')
with tf.name_scope('biases'):
b = tf.Variable(tf.random_normal([out_dim]))
variable_summaries(b, layer_name + '/biases')
with tf.name_scope('Wx_plus_b'):
... |
ua-snap/downscale | snap_scripts/old_scripts/tem_iem_older_scripts_april2018/tem_inputs_iem/old_code/crop_mask_resample_to_iem.py | Python | mit | 6,482 | 0.039185 | def resample_to_1km( x, template_raster_mask ):
'''
template_raster_mask should be a mask in in the res/extent/origin/crs of the
existing TEM IEM products.
'''
import rasterio, os
from rasterio.warp import RESAMPLING, reproject
import numpy | as np
fn = os.path.basename( x )
fn_split = fn.split( '.' )[0].split( '_' )
if '_cru_' in fn:
output_path = os.path.dirname( x ).replace( '/cru_ts31/', '/IEM/cru_ts31/' ) # hardwired!
fn_parts = ['variable', 'metric', 'model_1', 'model_2', 'kind', 'month', 'year']
fn_dict = dict( zip( fn_par | ts, fn_split ) )
fn_dict.update( scenario='historical', model='cru_ts31' )
else:
output_path = os.path.dirname( x ).replace( '/ar5/', '/IEM/ar5/' ) # hardwired!
fn_parts = ['variable', 'metric', 'model', 'scenario', 'ensemble', 'month', 'year']
fn_dict = dict( zip( fn_parts, fn_split ) )
try:
if not os.pat... |
lmazuel/azure-sdk-for-python | azure-mgmt-devtestlabs/azure/mgmt/devtestlabs/models/policy_set_result.py | Python | mit | 1,252 | 0.000799 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | {'key': 'hasError', 'type': 'bool'},
'policy_violations': {'key': 'policyViolations', 'type': '[PolicyViolation]'},
}
def __init__(self, has_error=None, policy_violations=None):
super(PolicySetResult, self).__init__()
| self.has_error = has_error
self.policy_violations = policy_violations
|
shaurz/devo | search.py | Python | mit | 3,549 | 0.002254 | import os, re, traceback
from dirtree_node import get_file_info
from util import is_text_file
class SearchAborted(Exception):
pass
def null_filter(info):
return True
class Search(object):
def __init__(self, path, match, output, file_filter=null_filter, dir_filter=null_filter):
self.path = path
... | m, line):
if len(line) > self.max_line_length:
line = line[:self.max_ | line_length] + "..."
self.file.write(" %d: %s\n" % (line_num, line))
def begin_file(self, finder, filepath):
pass
def end_file(self, finder):
self.file.write("\n")
def end_find(self, finder):
pass
def make_matcher(pattern, case_sensitive=True, is_regexp=False):
if not... |
melizalab/mspikes | mspikes/modules/random_sources.py | Python | gpl-3.0 | 1,590 | 0.006918 | # -*- coding: utf-8 -*-
# -*- mode: python -*-
"""Sources of random data
Copyright (C) 2013 Dan Meliza <dmeliza@uchicago.edu>
Created Wed May 29 14:50:02 2013
"""
from mspikes import util
from mspikes.types import DataBlock, Source, Node, tag_set
from numpy.random import RandomState
class rand_samples(Source):
... | data(self, t=0):
"""Generates a data chunk"""
return DataBlock(id=self.channel, offset=t, ds=self.sampling_rate,
data=self._randg.randn(self.chunk_size),
tags=tag_set("samples"))
def __iter__(self):
t = 0
while t < self.nsamples:
... | yield data
t += self.chunk_size
## TODO random_events
# Variables:
# End:
|
Chris7/cutadapt | cutadapt/report.py | Python | mit | 10,176 | 0.025649 | # coding: utf-8
"""
Routines for printing a report.
"""
from __future__ import print_function, division, absolute_import
import sys
from collections import namedtuple
from contextlib import contextmanager
import textwrap
from .adapters import BACK, FRONT, PREFIX, SUFFIX, ANYWHERE
from .modifiers import QualityTrimmer,... | rmat(b, fraction))
if fraction > 0.8 and base != '':
warnbase = b
if total >= 20 and warnbase is not None:
print('WARNING:')
print(' The adapter is preceded by "{0}" extremely often.'.format(warnbase))
print(' The provided adapter seque | nce may be incomplete.')
print(' To fix the problem, add "{0}" to the beginning of the adapter sequence.'.format(warnbase))
print()
return True
print()
return False
@contextmanager
def redirect_standard_output(file):
if file is None:
yield
return
old_stdout = sys.stdout
sys.stdout = file
yield
sys... |
silbertmonaphia/ml | co/20170212/test.py | Python | gpl-3.0 | 5,721 | 0.006817 | #! /usr/bin/env python
# encoding:utf-8
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import logging
import random
import multiprocessing
import numpy as np
import sklearn
from sklearn.naive_bayes import MultinomialNB
from sklearn.cross_validation import train_test_split
from sklearn.feature_... | ', ' | r').readlines()
vec = TfidfVectorizer(tokenizer=part_word, stop_words=stopwords)
vector=vec.fit_transform(data).toarray()
return vector
def delete(datas, vectors):
index = []
for i in range(datas.shape[0]):
for vector in vectors:
if not (vector - datas[i, :]).any():
... |
koodilehto/kryptoradio-xmit-tests | receiver/adapter_info.py | Python | mit | 324 | 0 | import linuxdvb
import fcntl
fefd = open('/dev/dvb/adapter0/frontend0', 'r+')
# Information
feinfo = linuxdvb.dvb_frontend_info()
fcntl.ioctl(fefd, l | inuxdvb.FE_GET_INFO, feinfo)
print feinfo.name
for bit, flag in linuxdvb.fe_caps.items():
if (feinfo.caps & bit) > 0:
print( | "cap = "+flag)
# Close
fefd.close()
|
ethereum/solidity | test/scripts/test_isolate_tests.py | Python | gpl-3.0 | 3,398 | 0.002943 | #!/usr/bin/env python
import unittest
from textwrap import dedent, indent
from unittest_helpers import FIXTURE_DIR, load_fixture
# NOTE: This test file file only works with scripts/ added to PYTHONPATH so pylint can't find the imports
# pragma pylint: disable=import-error
from isolate_tests import extract_solidity_... | }
}
""",
]]
self.assertEqual(extract_yul_docs_cases(CODE_BLOCK_RST_PATH), expected_cases)
def test_yul_block_with_directives(self):
expected_cases = [formatCase(case) for case in [
"""
{
let x := add(1, 5)
}
... | // Yul code wrapped in object
{
let y := mul(3, 5)
}
""",
"""
// Yul code wrapped in named object
object "Test" {
let y := mul(3, 5)
:linenos:
}
""",
]]
self... |
OlegKlimenko/Plamber | api/tests/test_views/test_index.py | Python | apache-2.0 | 8,371 | 0.004778 | # -*- coding: utf-8 -*-
from django.conf import settings
from django.contrib.auth.models import User
from django.shortcuts import reverse
from django.test import TestCase
from rest_framework.test import APIClient
from ...views.index_views import user_login
from app.models import TheUser
# ------------... | --------
def test_user_login_missing_params(self):
response = self.client.post(reverse('user_login_api'), {'app_key': self.api_key, 'username': 'username'})
self.assertEqual(response.resolver_match.func, user_login)
self.assertEqual(response.status_code, 400)
self.assertEqual(... | ['This field is required.']})
# ------------------------------------------------------------------------------------------------------------------
def test_user_login_too_long_username(self):
response = self.client.post(reverse('user_login_api'), {'app_key': self.api_key,
... |
geier/alot | alot/buffers.py | Python | gpl-3.0 | 24,285 | 0 | # Copyright (C) 2011-2012 Patrick Totzke <patricktotzke@gmail.com>
# This file is released under the GNU GPL, version 3 or a later revision.
# For further details see the COPYING file
from __future__ import absolute_import
import logging
import os
import urwid
from urwidtrees import ArrowTree, TreeBox, NestedTree
fr... | linewidget, _ = self.bufferlist.get_focus()
bufferlinewidget = linewidget.get_focus().original_widget
return bufferlinewidget.get_buffer()
def focus_first(self):
"""Focus the first line in the buffer list."""
self.body.set_focus(0)
class EnvelopeBuffer(Buffer):
"""message comp... | ui, envelope):
self.ui = ui
self.envelope = envelope
self.all_headers = False
self.rebuild()
Buffer.__init__(self, ui, self.body)
def __str__(self):
to = self.envelope.get('To', fallback='unset')
return '[envelope] to: %s' % (shorten_author_string(to, 400))
... |
nkgilley/home-assistant | homeassistant/components/verisure/switch.py | Python | apache-2.0 | 2,311 | 0.000433 | """Support for Verisure Smartplugs."""
import logging
from time import monotonic
from homeassistant.components.switch import SwitchEntity
from . import CONF_SMARTPLUGS, HUB as hub
_LOGGER = logging.getLogger(__name__)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Verisure s... | witches.extend(
[
VerisureSmartplug(device_label)
for device_label in hub.get("$.smartPlugs[*].deviceLabel")
]
)
add_entities(switches)
class VerisureSmartplug(SwitchEntity):
"""Representation of a Verisure smartplug.""" |
def __init__(self, device_id):
"""Initialize the Verisure device."""
self._device_label = device_id
self._change_timestamp = 0
self._state = False
@property
def name(self):
"""Return the name or location of the smartplug."""
return hub.get_first(
... |
radical-cybertools/ExTASY | doc/scripts/user_script.py | Python | mit | 1,886 | 0.008484 | from radical.ensemblemd import Kernel
from radical.ensemblemd import Pipeline
from radical.ensemblemd import EnsemblemdError
from radical.ensemblemd import SingleClusterEnvironment
#Used to register user defined kernels
from radical.ensemblemd.engine import get_engine
#Import our new kernel
from new_kernel import MyU... | #
# Execution of the 16 pipeline instances can happen concurrently or
# sequentially, depending on the resources (cores) available in the
# SingleClusterEnvironment.
sleep = Sleep(steps=1,instances=16)
cluster.run(sleep)
cluster.deallocate()
except EnsemblemdEr... | e execption again to get the backtrace
|
liuhong1happy/DockerConsoleApp | views/application.py | Python | apache-2.0 | 6,294 | 0.016378 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from services.application import ApplicationService
from services.application_access import ApplicationAccessService
import tornado.web
from tornado import gen
import tornado.escape
import json
from util.rabbitmq import send_message
from stormed import Message
import settin... | n.find_one(application_id)
app["_id"] = str(app["_id"])
if app is None:
self.render_error(error_code=404,msg="not data")
else:
s | elf.write_result(data=app)
class ApplicationsHandler(AsyncBaseHandler):
s_application = ApplicationService()
fields={
"project_url":True,
"project_name":True,
"app_name":True,
"user_id":True,
"user_name":True,
"status":True,
"logs":True,
"update_t... |
getsentry/sentry-hipchat-ac | sentry_hipchat_ac/migrations/0002_auto__del_mentionedevent.py | Python | apache-2.0 | 9,514 | 0.007988 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting model 'MentionedEvent'
db.delete_table(u'sentry_hipchat_ac_men... | ': '250'}),
'auth_user': ('sentry.db.models.fiel | ds.foreignkey.FlexibleForeignKey', [], {'related_name': "'hipchat_tenant_set'", 'null': 'True', 'to': "orm['sentry.User']"}),
'capabilities_url': ('django.db.models.fields.CharField', [], {' |
npklein/easybuild-easyconfigs | easybuild/easyconfigs/r/RPlus/find_missing_extensions.py | Python | gpl-2.0 | 27,561 | 0.000109 | exts_list = [
('lattice', '0.20-35', cran_options),
('nlme', '3.1-131.1', cran_options),
('Matrix', '1.2-12', cran_options),
('mgcv', '1.8-26', cran_options),
('plotfunctions', '1.3', cran_options),
('itsadug', '2.3', cran_options),
('abind', '1.4-5', cran_options),
('acepack', '1.4.1', ... | ons),
('LearnBayes', '2.15.1', cran_options),
('deldir', '0.1-14', cran_options),
('boot', '1.3-20', cran_options),
('coda', '0.19-1', cran_options),
('gtools', '3.5.0', cran_options),
('gdata', '2.18.0', cran_options),
('gmodels', '2.16.2', cran_options),
('expm', '0.999-2', cran_option... | n', '2.5', cran_options),
('BiocGenerics', '0.24.0', bioconductor_options),
('Biobase', '2.38.0', bioconductor_options),
('S4Vectors', '0.16.0', bioconductor_options),
('IRanges', '2.12.0', bioconductor_options),
('DBI', '0.8', cran_options),
('bit', '1.1-12', cran_options),
('bit64', '0.9-7... |
ebressert/ScipyNumpy_book_examples | python_examples/numpy_231_ex2.py | Python | mit | 420 | 0 | import numpy as np
# Loading and existing file
arr = np.loadtxt('somefile.txt')
# Saving a new file
np.savetxt('somenewfile.txt', arr)
# Opening an existing file with the append option
f = open('existingfile.txt', 'a')
# Creating some random data to append to the existing file
data2append = np.random.rand(100)
# W... | avetxt we replace the file name with the file handle.
np.savetxt(f, data2ap | pend)
f.close()
|
lsbardel/flow | flow/finance/cashflow/cash.py | Python | bsd-3-clause | 1,829 | 0.02187 |
from icash import *
from jflow.utils.observer import lazyvalue
class singlecash(icash):
'''
Simple cash flow.
Date, currency and dummy implementation
'''
def __init__(self, date = None, dummy = False, ccy = None):
self.__date = date
if self.__date == None:
... | ummy
def date(self):
return self.__date
def currency(self):
return self.__ccy
def isdummy(self):
return self.__dummy
class fixcash(singlecash):
'''
Fixed cahs. Notional equal the cash ammount
'''
def __init__(self, value = 0., *arg... | return self.__val
class lazycash(singlecash):
def __init__(self, value = 5.0, *args, **kwargs):
super(lazycash,self).__init__(*args, **kwargs)
self.__val = value
def __get_value(self):
try:
return self.__val.value
except:
ret... |
davidovitch/prepost-wind-dlc | cluster-tools/run-node.py | Python | gpl-3.0 | 843 | 0.003559 | #!python
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 25 22:38:43 2014
@author: dave
"""
import os
#from argparse import ArgumentParser
import argparse
imp | ort paramiko
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("script", help="python script to execute")
parser.add_argument("-n", "--node", default='g-080',
help="gorm node hoste name, between g-001 and g-080")
args = parser.parse_args()
# co... | a node for the post processing
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname='g-080', username=os.environ['USER'])
stdin, stdout, stderr = client.exec_command('python %s' % args.script)
for line in stdout:
print '... ' + ... |
eadgarchen/tensorflow | tensorflow/contrib/estimator/python/estimator/extenders_test.py | Python | apache-2.0 | 10,770 | 0.00585 | # Copyright 2017 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... | r the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""extenders tests."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
i | mport numpy as np
from tensorflow.contrib.data.python.ops import dataset_ops
from tensorflow.contrib.estimator.python.estimator import extenders
from tensorflow.python.estimator import estimator_lib
from tensorflow.python.estimator.canned import linear
from tensorflow.python.feature_column import feature_column as fc
... |
Huyuwei/tvm | python/tvm/hybrid/preprocessor.py | Python | apache-2.0 | 4,765 | 0.005247 | # Licensed to the Apache Software Founda | tion (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 this file except in compliance
# with... | ware distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""Determines the declaration, r/w status, and last use of each vari... |
dekoza/django-getpaid | getpaid/backends/transferuj/models.py | Python | mit | 47 | 0 | d | ef build_models(payment_class):
| return []
|
joaander/hoomd-blue | hoomd/dem/pair.py | Python | bsd-3-clause | 15,876 | 0.001386 | # Copyright (c) 2009-2021 The Regents of the University of Michigan
# This file is part of the HOOMD-blue project, released under the BSD 3-Clause License.
R"""DEM pair potentials.
"""
import hoomd
import hoomd.md
import hoomd.md.nlist as nl
from math import sqrt
import json
from hoomd.dem import _dem
from hoomd.de... | faces=[[0, 1, 2, 3]], center=False)
# 3D system of some conve | x shape specified by vertices
(vertices, faces) = hoomd.dem.utils.convexHull(vertices)
shapes = hoomd.dem.pair.WCA(radius=.5)
shapes.setParams('A', vertices=vertices, faces=faces)
"""
def __init__(self, nlist, radius=1.):
friction = None
self.radius = radius
se... |
mdworks2016/work_development | Python/05_FirstPython/Chapter9_WebApp/fppython_develop/lib/python3.7/site-packages/zope/interface/tests/test_verify.py | Python | apache-2.0 | 19,156 | 0.00047 | ##############################################################################
#
# Copyright (c) 2001, 2002 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# TH... | def test_method_takes_only_positional_args(self):
from zope.interface import Interface
from zope.interface import implementer
class ICurrent(Interface):
def method(a) | :
pass
@implementer(ICurrent)
class Current(object):
def method(self, *args):
raise NotImplementedError()
self._callFUT(ICurrent, Current)
def test_method_takes_only_kwargs(self):
from zope.interface import Interface
from zope.i... |
MauHernandez/cyclope | demo/cyclope_project/locale/dbgettext/articles/article/como-funciona-la-biblioteca-biblioteca-multimedia/summary.py | Python | gpl-3.0 | 312 | 0.003289 | # -*- coding: utf-8 -*-
gettext("""La “Biblioteca Multi | media” es el lugar desde donde se clasifican nuestros contenidos multimedia, es decir, todo lo que es imágenes, audios, videos, documentos, etc. que luego podremos relacionar entre sí y con artículos, y tendrán vistas | HTML en nuestro sitio web.""")
|
Sbalbp/DIRAC | Interfaces/scripts/dirac-admin-get-site-mask.py | Python | gpl-3.0 | 781 | 0.020487 | #!/usr/bin/env python
########################################################################
# $HeadURL$
# File : dirac-admin-get-site-mask
# Author : Stuart Paters | on
########################################################################
__RCSID__ = "$Id$"
from DIRAC.Core.Base import Script
Script.setUsageMessage( """
Get the list of sites enabled in the mask for job submission
Us | age:
%s [options]
""" % Script.scriptName )
Script.parseCommandLine( ignoreErrors = True )
from DIRAC import exit as DIRACExit, gLogger
from DIRAC.Interfaces.API.DiracAdmin import DiracAdmin
diracAdmin = DiracAdmin()
gLogger.setLevel('ALWAYS')
result = diracAdmin.getSiteMask(printOutput=True)
if result['OK']:
... |
ESSS/conda-env | tests/test_print_env.py | Python | bsd-3-clause | 4,520 | 0.002655 | from conda_env.print_env import print_env
import os
import textwrap
import unittest
class EnvironmentAndAliasesTestCase(unittest.TestCase):
ENVIRONMENT = [
{'PATH' : ['mypath1', 'mypath2']},
{'PATH' : ['mypath3']},
{'ANY_LIST_REALLY' : ['something1', 'something2']},
{'SINGLE_VAR' ... | 2;mypath3;C:\\Users\\me\\bin'
| os.environ['SINGLE_VAR'] = 'single_value'
os.environ['ANY_LIST_REALLY'] = 'something1;something2;'
deactivate = print_env('deactivate', self.ENVIRONMENT, self.ALIASES)
assert deactivate == textwrap.dedent(
'''
set ANY_LIST_REALLY=
set P... |
hipnusleo/laserjet | resource/pypi/paramiko-2.1.1/paramiko/kex_group1.py | Python | apache-2.0 | 5,689 | 0.001055 | # Copyright (C) 2003-2007 Robey Pointer <robeypointer@gmail.com>
#
# This file is part of paramiko.
#
# Paramiko is free software; you can redistribute it and/or modify it under the
# terms of the GNU Lesser General Public License as published by the Free
# Sof | tware Foundation; either version 2.1 of the License, or (at your option)
# any later version.
#
# Paramiko 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 Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Paramiko... |
wildchildyn/autism-website | yanni_env/lib/python3.6/site-packages/sqlalchemy/testing/assertsql.py | Python | gpl-3.0 | 12,590 | 0 | # testing/assertsql.py
# Copyright (C) 2005-2017 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
from ..engine.default import DefaultDialect
from .. import util
import re
impor... | params = self.params(context)
else:
params = self.params
if not isinstance(params, list):
params = [params]
return params
else:
return None
def _failure_message(self, expected_params):
return (
'Tes... | ace('%', '%%'), expected_params
)
)
class RegexSQL(CompiledSQL):
def __init__(self, regex, params=None):
SQLMatchRule.__init__(self)
self.regex = re.compile(regex)
self.orig_regex = regex
self.params = params
self.dialect = 'default'
def _failure_me... |
franga2000/django-machina | tests/unit/forum/test_models.py | Python | bsd-3-clause | 5,012 | 0.001197 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import pytest
from django.core.exceptions import ValidationError
from machina.apps.forum.signals import forum_moved
from machina.core.db.models import get_model
from machina.test.context_managers import mock_signal_receiver
from machina.test.factories i... | pic = create_topic(forum=sub_level_forum, poster=self.u1)
PostFactory.create(topic=topic, poster=self.u1)
# Run
topic.delete()
# Check
sub_level_forum.refresh_from_db()
assert sub_level_forum.last_post_on is | None
def test_can_send_a_specific_signal_when_a_forum_is_moved(self):
# Setup
topic = create_topic(forum=self.top_level_forum, poster=self.u1)
PostFactory.create(topic=topic, poster=self.u1)
PostFactory.create(topic=topic, poster=self.u1)
# Run & check
with mock_sign... |
oscarmcm/AlzoMiVoz | alzomivoz/manage.py | Python | mit | 316 | 0 | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS | _MODULE", "config.settings")
os.environ.setdefault("DJANGO_CONFIGURATION", "Production")
from configurations.management import execute_from_command_line
execute_from_command_line(sys.ar | gv)
|
LockScreen/Backend | test.py | Python | mit | 121 | 0.016529 | from auth import authenticate
import sample_upload
def check | ():
asdf = auth.authenticate()
return asdf
|
check()
|
DayGitH/Python-Challenges | DailyProgrammer/DP20171026B.py | Python | mit | 1,315 | 0.006844 | """
[2017-10-26] Challeng | e #337 [Intermediate] Scrambled images
https://www.reddit.com/r/dailyprogrammer/comments/78twyd/20171026_challenge_337_intermediate_scrambled/
#Description
For this challenge you will get a couple of images containing a secret word, you will have to unscramble the images to
be able to read the words.
To unscramble ... | s & Outputs
You get a [scrambled](http://i.imgur.com/rMYBq14.png) image, which you will have to unscramble to get the
[original](http://i.imgur.com/wKaiHpv.png) image.
###Input description
Challenge 1: [input](http://i.imgur.com/F4SlYMn.png)
Challenge 2: [input](http://i.imgur.com/ycDwgXA.png)
Challenge 3: [input]... |
synox/telewall | telewall/telewall/integrationtests/test_InT01.py | Python | gpl-3.0 | 1,091 | 0.007333 | """ Integration test: permit call
"""
import os
import sys
myPath = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, myPath + '/../../')
import logging
import nose
from nose.tools import *
import inte_testutils
from telewall.core.model import TelephoneNumber
from telewall.core.util import sleep_until... | ein, aber es gab | keinen "Ringing" Status.')
call.stop()
if __name__ == '__main__':
nose.runmodule()
|
eliben/llvm-clang-samples | tools/htmlize-ast-dump.py | Python | unlicense | 13,724 | 0.000874 | #-------------------------------------------------------------------------------
# htmlize-ast-dump.py: Turn a Clang AST dump (-ast-dump) into cross-linked HTML.
#
# Run with --help for usage information.
#
# Note: this script requires Python 3.4; earlier versions of Python 3 should
# work if you install the enum34 mod... | color: #000000;
white-space: pre;
}}
.ansi-red {{
color: #d23737;
white-space: pre;
}}
.ansi-green {{
color: #17b217;
white-space: pre;
}}
.ansi-yellow {{
color: #b26717;
white-space: pre;
}}
.ansi-blu | e {{
color: #2727c2;
white-space: pre;
}}
.ansi-magenta {{
color: #b217b2;
white-space: pre;
}}
.ansi-cyan {{
color: #17b2b2;
white-space: pre;
}}
.ansi-white {{
color: #f2f2f2;
white-space: pre;
}}
</style>
</head>
<bod... |
sjdv1982/seamless | docs/archive/0.2-cleanup/3D/test-sphere.py | Python | mit | 7,136 | 0.002522 | from seamless import context, cell, transformer, reactor
from seamless.lib import edit, display, link
from seamless.lib.gui.gl import glprogram, glwindow
import numpy as np
from scipy.spatial.distance import cdist
ctx = context()
ctx.params = context()
ctx.links = context()
ctx.code = context()
#for now, gen_sphere ... | = ctx.gen_sphere = reactor(c)
c = ctx.code.gen_sphere = cell(("text", "code", "python"))
ctx.links.code_gen_sphere = link(c, ".", "cell-gen-sphere.py")
rc.code_start.cell().set("")
c.connect(rc.code_update)
rc.code_stop.cell().set("")
do_scale_params = {
"input":{"pin": "input", "dtype": "array"},
"scale":{"p... | ":{"pin": "output", "dtype": "array"}
}
ctx.subdivisions = cell("int").set(3)
ctx.minimizations = cell("int").set(20)
ctx.scale = cell("float").set(3.5)
ctx.coordinates = cell("array").set_store("GL")
ctx.normals = cell("array").set_store("GL")
ctx.edges = cell("array").set_store("GL")
ctx.triangle_indices = cell("arra... |
MarsZone/DreamLand | muddery/statements/default_statement_func_set.py | Python | bsd-3-clause | 1,790 | 0 | """
Default statement functions.
"""
from muddery.statements.statement_func_set import BaseStatementFuncSet
import muddery.statements.action as action
import muddery.statements.condition as condition
import muddery.statements.attribute as attribute
import muddery.statements.rand as rand
import muddery.statements.skill... | .add(action.FuncTeleportTo)
self.add(action.FuncFightMob)
self.add(action.FuncFightTa | rget)
class ConditionFuncSet(BaseStatementFuncSet):
"""
Statement functions used in conditions.
"""
def at_creation(self):
"""
Load statement functions here.
"""
self.add(condition.FuncIsQuestInProgress)
self.add(condition.FuncCanProvideQuest)
self.add(c... |
ellisonbg/nbgrader | nbgrader/tests/preprocessors/test_saveautogrades.py | Python | bsd-3-clause | 8,576 | 0.001632 | import pytest
from nbformat.v4 import new_notebook, new_output
from ...preprocessors import SaveCells, SaveAutoGrades
from ...api import Gradebook
from ...utils import compute_checksum
from .base import BaseTestPreprocessor
from .. import (
create_grade_cell, create_grade_and_solution_cell, create_solution_cell)
... | = "hello!"
preprocessors[1].preprocess(nb, resources)
comment = gradebook.find_comment("foo", "test", "ps0", "bar")
assert comment.auto_comment is None
def test_comment_unchanged_markdown(self, preprocessors, gradebook, resources):
"""Is an unchanged markdown cell given the correct... | data.nbgrader['checksum'] = compute_checksum(cell)
nb = new_notebook()
nb.cells.append(cell)
preprocessors[0].preprocess(nb, resources)
gradebook.add_submission("ps0", "bar")
preprocessors[1].preprocess(nb, resources)
comment = gradebook.find_comment("foo", "test", "ps0"... |
baallezx/rsp | devtest/q3/3.py | Python | apache-2.0 | 990 | 0.061616 | def creat | e_graph(contents):
"""
if you are given a -1 then it does not point to anything.
"""
d = {}
for i in xrange(len(co | ntents)):
d[i] = int(contents[i])
return d
def _cycle(graph, key, stack, stacks):
# print graph, key, stack
if ( key , graph[key] ) in stack: # you have found a cycle
stacks.append(stack)
return # True
elif graph[key] == -1: # dead end
return None # False
else:
stack.append( ( key , graph[key] ) )
_cy... |
lyw07/kolibri | kolibri/core/content/utils/transfer.py | Python | mit | 6,229 | 0.001284 | import logging
import os
import shutil
import requests
from requests.exceptions import ConnectionError
logger = logging.getLogger(__name__)
class ExistingTransferInProgress(Exception):
pass
class TransferNotYetCompleted(Exception):
pass
class TransferCanceled(Exception):
pass
class TransferNotYetC... | if not self.closed:
raise TransferNotYetClosed(
"Transfer must be closed before it can be finalized."
)
if self.finalized:
return
self._move_tmp_to_dest()
self.finalized = True
def close(self):
self.dest_file_obj.close()
se... | :
# allow an existing requests.Session instance to be passed in, so it can be reused for speed
if "session" in kwargs:
self.session = kwargs.pop("session")
else:
# initialize a fresh requests session, if one wasn't provided
self.session = requests.Session()
... |
draperlaboratory/stout | op_tasks/models.py | Python | apache-2.0 | 5,396 | 0.004818 | from django.db import models
#from django.contrib.auth.models import User
from django.conf import settings
import hashlib
import time, datetime
def _createHash():
hash = hashlib.sha1()
hash.update(str(time.time()))
return hash.hexdigest()[:-10]
# the dataset class stores parameters about the
class Data... | ef _both_complete(self):
"returns whether both task and survey are complete"
return self.exit_complete and self.task_complete
both_complete = property( | _both_complete)
def __unicode__(self): # Python 3: def __str__(self):
return '%s, %s, %s' % (self.userprofile.user.email, self.op_task, self.index)
class Meta:
ordering = ('userprofile', 'index')
# index = models.IntegerField()
class Achievement(models.Model):
name = models.CharFiel... |
masschallenge/impact-api | web/impact/impact/v1/events/user_became_desired_mentor_event.py | Python | mit | 362 | 0 | # MIT Licen | se
# Copyright (c) 2017 MassChallenge, Inc.
from accelerator.models import UserRole
from impact.v1.events.base_user_became_mentor_event import (
BaseUserBecameMentorEvent,
)
class UserBecameDesiredMentorEvent(BaseUserBecameMentorEvent):
EVENT_TYPE = "became desired mentor" |
USER_ROLE = UserRole.DESIRED_MENTOR
ROLE_NAME = USER_ROLE
|
MadManRises/Madgine | shared/bullet3-2.89/examples/pybullet/gym/pybullet_envs/minitaur/actuatornet/proto2csv.py | Python | mit | 1,333 | 0.020255 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
#python proto2csv.py --proto_file=/tmp/logs/minitaur_log_2019-01-27-12-59-31 --csv_file=/tmp/logs/out.csv
#each line in csv contains: angle, velocity, action, torque
import tensorflow as tf
import argparse
imp... | gging = minitaur_logging.MinitaurLogging()
episode = logging.restore_episode(FLAGS.pr | oto_file)
#print(dir (episode))
#print("episode=",episode)
fields = episode.ListFields()
recs = []
for rec in fields[0][1]:
#print(rec.time)
for motorState in rec.motor_states:
#print("motorState.angle=",motorState.angle)
#print("motorState.velocity=",motorState.velocity)
#print("m... |
egtaonline/quiesce | test/test_eosched.py | Python | apache-2.0 | 6,888 | 0.003049 | """Tests for egta online scheduler"""
import asyncio
import contextlib
import random
import numpy as np
import pytest
from egtaonline import api
from egtaonline import mockserver
from gameanalysis import rsgame
from egta import countsched
from egta import eosched
# TODO general setup may be done with a fixture in p... | profiles and verify it works
async with eosched | .eosched(game, egta, egame["id"], 0.1, 1, 10, 0, 0) as sched:
assert str(sched) == str(egame["id"])
assert game == rsgame.empty_copy(sched)
awaited = await asyncio.gather(*[sched.sample_payoffs(p) for p in profs])
pays = np.stack(awaited)
assert np.allclose(pays[profs... |
iamdork/dork | dork/matcher.py | Python | mit | 7,851 | 0.001019 | import config
from git import Repository
import os
import yaml
from fnmatch import fnmatch
class Role:
@classmethod
def tree(cls, repository):
return RoleFactory(repository).tree()
@classmethod
def clear(cls, repository):
return RoleFactory(repository).clear()
def __init__(self, n... | ository
:return:
"""
self.repo = repository
self.name = name
self.factory = RoleFactory(repository)
self.__meta = meta
if 'dork' not in self.__meta:
self.__meta['dork'] = {}
| self.__dependencies = []
self.__services = meta['dork']['services'] if 'services' in meta['dork'] else {}
if 'dependencies' in self.__meta and isinstance(self.__meta['dependencies'], list):
for dep in self.__meta['dependencies']:
if isinstance(dep, str):
... |
wscullin/spack | var/spack/repos/builtin.mock/packages/extendee/package.py | Python | lgpl-2.1 | 1,547 | 0.000646 | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gambli | n, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-647188
#
# For details, see https://github.com/llnl/spack
# Please also see the NOTICE and LICENSE files for our notice and the LGPL.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public Lice... |
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of th... |
firebase/grpc | tools/github/pr_latency.py | Python | apache-2.0 | 6,848 | 0.001606 | #!/usr/bin/env python
# Copyright 2017 gRPC authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | ken {}'.format(TOKEN))
response = urllib2.urlopen( | request)
return response.read()
def print_csv_header():
print('pr,base_time,test_time,latency_seconds,successes,failures,errors')
def output(pr,
base_time,
test_time,
diff_time,
successes,
failures,
errors,
mode='human'):
if mo... |
hoaibang07/Webscrap | sources/xmldemo/xmlcreate.py | Python | gpl-2.0 | 731 | 0.005472 | from xml.etree.ElementTree import ElementTree
from xml.etree.ElementTree import Element
import xml.etree.ElementTree as etree
from xml.dom import minidom
import io
"""
using xml.etree.ElementTree
"""
def pre | ttify(elem):
"""Return a pretty-printed XML string for the Element.
"""
rough_string = etree.tostring(elem, 'utf-8')
reparsed = minidom.parseString(rough_string)
return reparsed.toprettyxml(indent="\t")
root = Element('person')
tree = ElementTree(root)
name = Element('name')
root.append(name)
name.... | ree.write(open('person.xml', 'w'))
f2 = io.open('person2.xml', 'w', encoding = 'utf-8')
f2.write(prettify(root)) |
themoken/canto-next | plugins/sync-rsync.py | Python | gpl-2.0 | 11,388 | 0.005444 | # Canto rsync Plugin
# by Jack Miller
# v1.1
# This implements a lightweight remote sync based around rsync to a remote
# server, or copying to mounted filesystem, etc.
ENABLED = False
#ENABLED = True
# SSH
# For ssh based rsync (remote hosts) you should have key authentication setup
# so it runs without prompting f... | INTERVAL = 5 * 60
# How long, in seconds, we should wait for the initial sync. Setting to 0 will
# cause a sync to occur before any other items can be read from disk, which
# ensures you won't see any old items, but also means a full sync has to occur
# before any items ma | ke it to the client and causes a long delay on startup.
INITIAL_SYNC = 30
#============================================
# Probably won't need to change these.
# rsync
# -a (archive mode) to preserve times / perms
# -v (verbose) to output interesting log info
# -z (compress) to save bandwidth
CMD = [ "rsync", "-a... |
bebox/lhp | source/lhpFunctions.py | Python | unlicense | 6,564 | 0.043419 | import operator
def pozicijaSprite(broj, x_velicina):
#vraca pixel na kojem se sprite nalazi
pixel = broj * (x_velicina + 1) #1 je prazan red izmedu spritova
return(pixel)
#spriteSlova = ["A", "B", "C", "D", "E", "F", "G", "H", "i", "s", "e"]
spriteSlova = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "s", ",",... | ".", "5", "7", "9", "0", "M", "B", "I", "N", "S", "E", "R", "T", " ", "-", "V","U" ,"A", "L", "O", "D", ":", "m", "j", "n", "u", "C", "H", "k", "l", "o", "p", "r", "t", "v", "z", "K", "P", "%", "/"]
def pixel2Ton(pixel):
rezolucija = 90
indent = -12 #extra pixeli
height = 3
broj = ( rezolucija - pixel - inde | nt ) / height
return(int(broj))
predikati = {
0 : 0,
1 : -1,
2 : 1,
3 : 0
}
kljucevi = {
0 : ("d", ",,"),
1 : ("e", ",,"),
2 : ("f", ",,"),
3 : ("g", ",,"),
4 : ("a", ",,"),
5 : ("h", ",,"),
6 : ("c", ","),
7 : ("d", ","),
8 :... |
linglung/ytdl | youtube_dl/extractor/spankbang.py | Python | unlicense | 2,167 | 0.001384 | from __future__ import unicode_literals
import re
from .common import InfoExtractor
class SpankBangIE(InfoExtractor):
_VALID_URL = r'https?://(?:(?:www|[a-z]{2})\.)?spankbang\.com/(?P<id>[\da-z]+)/video'
_TESTS = [{
'url': 'http://spankbang.com/3vvn/video/fantasy+solo',
'md5': '1cc433e1d6aa1... | 'url': 'http://spankbang.com/_%s/%s/title/%sp__mp4' % (video_id, stream_key, height) | ,
'ext': 'mp4',
'format_id': '%sp' % height,
'height': int(height),
} for height in re.findall(r'<(?:span|li|p)[^>]+[qb]_(\d+)p', webpage)]
self._check_formats(formats, video_id)
self._sort_formats(formats)
title = self._html_search_regex(
... |
BigRoy/lucidity | test/unit/test_template.py | Python | apache-2.0 | 12,561 | 0.001672 | # :coding: utf-8
# :copyright: Copyright (c) 2013 Martin Pengelly-Phillips
# :license: See LICENSE.txt.
import pytest
from lucidity import Template, Resolver
from lucidity.error import ParseError, FormatError, ResolveError
class ResolverFixture(Resolver):
'''Example resolver.'''
def __init__(self, template... | @pytest.mark.parametrize(('pattern', 'path'), [
('/{variable}/{variable}', '/a/b'),
('/static/{variable:\d\{4\}}/other/{variable}', '/static/1234/other/2345'),
('/{a.b.c}/static/{a.b.c}', '/c1/static/c2'),
('/{a}/{b}/other/{a}_{b}', '/a/b/other/c | _d'),
('{@nested}/{variable}', '/root/different/value')
], ids=[
'simple duplicate',
'duplicate with one specialised expression',
'structured duplicate',
'multiple duplicates',
'duplicate from reference'
])
def test_invalid_parse_in_strict_mode(pattern, path, template_resolver):
'''Fail to e... |
fishpepper/OpenSky | stylecheck/cpplint_unittest.py | Python | gpl-3.0 | 228,992 | 0.002559 | #!/usr/bin/python
# -*- coding: utf-8; -*-
#
# Copyright (c) 2009 Google Inc. 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 copyrigh... | , we
can't use the normal unittest assert macros. Instead we just exit
when we see | an error. Good thing this test is always run last!
"""
for category in self._ERROR_CATEGORIES:
if category not in self._SEEN_ERROR_CATEGORIES:
sys.exit('FATAL ERROR: There are no tests for category "%s"' % category)
def RemoveIfPresent(self, substr):
for (index, error) in enumerate(self._e... |
kevin2314/TextGame | game/main.py | Python | mit | 4,805 | 0.019771 | from inventory import Inventory
import cmd
from room import get_room
from player import Player
import textwrap
import time
import random
class Controls(cmd.Cmd):
prompt = '> '
def __init__(self):
#-----------------------------------------------------------------------
#Here the game is initialized asking for... | def do_chop(self, args):
self.objects('trees')
def do_name(self, args):
'''Prints the users name if there is one'''
self.player.player_name()
def do_hand(self, args):
'''Prints what is in hand'''
if self.Player.hand() == ' ':
print("You are not holding anythi... | .hand())
def do_next(self, args):
'''Gets the next event'''
self.move('next')
def do_look(self, args):
'''Prints the current area you are in'''
self.look()
def do_inventory(self, args):
'''Checks Inventory'''
self.inventory.bag()
self.look()
de... |
openaid-IATI/OIPA | OIPA/iati/migrations/0031_remove_resultindicatorperiodtargetdimension_result_indicator_period.py | Python | agpl-3.0 | 372 | 0 | # Gene | rated by Django 2.0.6 on 2018-08-31 10:43
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('iati', '0030_auto_20180831_1001'),
]
operations = [
migrations.RemoveField(
model_name='resultindicatorperiodtargetdimension',
nam... | ]
|
darogan/ParticleStats | setup.py | Python | gpl-3.0 | 3,803 | 0.012885 | ###############################################################################
# ____ _ _ _ ____ _ _ #
# | _ \ __ _ _ __| |_(_) ___| | ___/ ___|| |_ __ _| |_ ___ #
# | |_) / _` | '__| __| |/ __| |/ _ \___ \| __/ _` | __/ __| #
... | ########################################
from distutils.core import setup, Extension
module1 = Extension('ParticleStats_linRegressFit',
sources = ['src/ParticleStats_linRegressFit.c'])
setup(
name = 'ParticleStats',
version = '2.0',
author = 'Russell Hamilton',
author_email = 'darogan@gmail.... | = 'GPLv3',
packages = ['ParticleStats'],
#py_modules=[ "ParticleStats_Inputs.py", "ParticleStats_Maths.py", "ParticleStats_Outputs.py", "ParticleStats_Plots.py", "ParticleStats_RandomTrailGenerator.py", "ParticleStats_Vectors.py", "Test_Interactive_OSX_DivideUpLines.py", "Test_Interactive_OSX.py", "Test_Interactive.p... |
harshilasu/GraphicMelon | y/google-cloud-sdk/platform/gsutil/third_party/boto/boto/dynamodb/types.py | Python | gpl-3.0 | 10,121 | 0 | # Copyright (c) 2011 Mitch Garnaat http://garnaat.org/
# Copyright (c) 2011 Amazon.com, Inc. or its affiliates. All Rights Reserved
#
# 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 ... | _(self, value):
if not isinstance(value, basestring):
raise TypeError('Value must be a string of binary data!')
self.value = value
def encode(self):
retur | n base64.b64encode(self.value)
def __eq__(self, other):
if isinstance(other, Binary):
return self.value == other.value
else:
return self.value == other
def __ne__(self, other):
return not self.__eq__(other)
def __repr__(self):
return 'Binary(%s)' % ... |
google-research/language | language/bert_extraction/steal_bert_classifier/utils/preprocess_distill_input_watermark.py | Python | apache-2.0 | 5,277 | 0.006822 | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ... | w string
new_prob_str = "\t".join([str(yy) for yy in new_prob_vector])
output_data.append(x.strip() + "\t" + new_prob_str.strip())
# add the watermarked data for future checks
watermark_data.append(x.strip() + "\t" + new_prob_str.strip() + "\t" +
y.strip())... |
else:
output_data.append(x.strip() + "\t" + y.strip())
elif FLAGS.split_type == "train_argmax":
assert len(sents_data) == len(probs_data)
# Round the probability vectors before adding them to file
output_data = []
watermark_data = []
for i, (x, y) in enumerate(zip(sents_data, prob... |
fraricci/pymatgen | pymatgen/analysis/cost/__init__.py | Python | mit | 300 | 0 | # coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed un | der the terms of the MIT License.
__author__ = 'Anubhav Jain'
__copyright__ = 'Copyright 2014, The Materials Project'
__version__ = | '0.1'
__maintainer__ = 'Anubhav Jain'
__email__ = 'ajain@lbl.gov'
__date__ = 'Oct 03, 2014'
|
buret/pylmflib | pylmflib/morphosyntax/paradigm.py | Python | gpl-2.0 | 3,401 | 0.00147 | #! /usr/bin/env python
"""! @package morphosyntax
"""
from utils.attr import check_attr_type, check_attr_range
from common.range import paradigmLabel_range
from config.mdf import pdl_paradigmLabel
class Paradigm():
"""! Paradigm is a class representing a morphological paradigm.
"""
def __init__(self):
... | aradigm = None
self.language = None
self.morphology = None
# LexicalEntry lexeme
self.targets = None
## Pointer to an existing LexicalEntry
# There is zero or one LexicalEntry pointer per Paradigm instance
self.__lexical_entry = None
def __del__(self):
... | self.__lexical_entry = None
def set_paradigmLabel(self, paradigm_label):
"""! @brief Set paradigm label.
@param paradigm_label The paradigm label to set.
@return Paradigm instance.
"""
error_msg = "Paradigm label value '%s' is not defined" % str(paradigm_label)
... |
ChinaQuants/zipline | tests/pipeline/test_pipeline_algo.py | Python | apache-2.0 | 19,784 | 0.000051 | """
Tests for Algorithms using the Pipeline API.
"""
from unittest import TestCase
from os.path import (
dirname,
join,
realpath,
)
from nose_parameterized import parameterized
from numpy import (
array,
arange,
full_like,
float64,
nan,
uint32,
)
from numpy.testing import assert_alm... | import trading
from zipline.pipeline import Pip | eline
from zipline.pipeline.factors import VWAP
from zipline.pipeline.data import USEquityPricing
from zipline.pipeline.loaders.frame import DataFrameLoader, MULTIPLY
from zipline.pipeline.loaders.equity_pricing_loader import (
USEquityPricingLoader,
)
from zipline.utils.test_utils import (
make_simple_asset_in... |
simplegeo/authorize | authorize/gen_xml.py | Python | mit | 17,930 | 0.004964 | # -*- encoding: utf-8 -*-
import re
import decimal
from xml.etree.cElementTree import fromstring, tostring
from xml.etree.cElementTree import Element, iselement
from authorize import responses
API_SCHEMA = 'https://api.authorize.net/xml/v1/schema/AnetApiSchema.xsd'
API_SCHEMA_NS = "AnetApi/xml/v1/schema/AnetApiSchem... | UTH_CAPTURE = u"prior_auth_capture"
VOID = u"void"
class AuthorizeSystemError(Exception):
"""
I'm a serious kind of exception and I'm raised when something
went really bad at a lower level than the application level, like
when Authorize is down or when they return an unparseable r | esponse
"""
def __init__(self, *args):
self.args = args
def __str__(self):
return "Exception: %s caused by %s" % self.args
def __repr__(self):
# Here we are printing a tuple, the , at the end is _required_
return "AuthorizeSystemError%s" % (self.args,)
c = re.compile(r'(... |
3324fr/spinalcordtoolbox | dev/sct_detect_spinalcord/sct_get_centerline_from_labels.py | Python | mit | 5,974 | 0.01473 | #!/usr/bin/env python
import commands, sys
# Get path of the toolbox
status, path_sct = commands.getstatusoutput('echo $SCT_DIR')
# Append path that contains scripts, to be able to load modules
sys.path.append(path_sct + '/scripts')
from msct_parser import Parser
from nibabel import load, save, Nifti1Image
import ... | ow_length)
# Rename files after processing
if output_file_name != None:
output_file_name = output_file_name
else : output_file_name = "generated_centerline.nii.gz"
os. | rename(fname_output, output_file_name)
path_binary, file_binary, ext_binary = sct.extract_fname(output_file_name)
os.rename('concatenation_file_centerline.txt', file_binary+'.txt')
# Process for a binary file as output:
sct.run('cp '+output_file_name+' ../')
# Process for a text file as output:
... |
zozo123/buildbot | master/buildbot/test/unit/test_db_schedulers.py | Python | gpl-3.0 | 14,846 | 0.000741 | # This file is part of Buildbot. Buildbot 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, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without eve... | chname2')
master14 = fakedb.Master(id=14, name='m2', active=0)
scheduler25master = fakedb.SchedulerMaster(schedulerid=25, masterid=14)
# tests
def test_signature_classifyChanges(self):
@self.assertArgSpecMatches(self.db.schedulers.classifyChanges)
def classifyChanges(self, schedulerid,... | yield self.insertTestData([self.ss92, self.change3, self.change4,
self.scheduler24])
yield self.db.schedulers.classifyChanges(24,
{3: False, 4: True})
res = yield self.db.schedulers.getChangeClassifications(24)
... |
chase-qi/workload-automation | wlauto/instrumentation/misc/__init__.py | Python | apache-2.0 | 17,103 | 0.003859 | # Copyright 2013-2015 ARM Limited
#
# 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 w... | tf:
tf.extractall(context.output_directory)
self.device.delete_file(on_device_tarball + ".gz")
os.remove(on_host_tarball)
for paths in self.device_and_ho | st_paths:
after_dir = paths[self.AFTER_PATH]
dev_dir = paths[self.DEVICE_PATH].strip('*') # remove potential trailing '*'
if (not os.listdir(after_dir) and
self.device.file_exists(dev_dir) and
self.device.listdir(dev_dir)):
|
zhaochao/fuel-web | network_checker/network_checker/net_check/api.py | Python | apache-2.0 | 25,801 | 0.000504 | #!/usr/bin/env python
# Copyright 2014 Mirantis, 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 require... | ge='', level='error'):
getattr(logger, level, logger.error)(message)
super(ActorException, self).__init__(message)
class Actor(object):
def __init__(self, config=None):
self.config = {
'src_mac': None,
'src': '198.18.1.1',
'dst': '198.18.1.2',
... | t': 31337,
'cookie': "Nailgun:",
'pcap_dir': "/var/run/pcap_dir/",
'duration': 5,
'repeat': 1
}
if config:
self.config.update(config)
self.logger.debug("Running with config: %s", json.dumps(self.config))
self._execute(["modprob... |
ploneintranet/ploneintranet.workspace | src/ploneintranet/workspace/tests/test_sidebar.py | Python | gpl-2.0 | 4,580 | 0 | # coding=utf-8
from plone import api
from plone.tiles.interfaces import IBasicTile
from ploneintranet.workspace.browser.tiles.sidebar import Sidebar
from ploneintranet.workspace.browser.tiles.sidebar import \
SidebarSettingsMembers
from ploneintranet.workspace.tests.base import BaseTestCase
from zope.component impo... | ce folder"""
workspace_folder = api.content.create(
self.portal,
'ploneintranet.workspace.workspacefolder | ',
'example-workspace',
title='Welcome to my workspace'
)
return workspace_folder
# return IWorkspace(workspace_folder)
def test_sidebar_existing_users(self):
ws = self.create_workspace()
user = api.user.create(email="newuser@example.org", username="... |
guaka/trust-metrics | trustlet/unittest/testXDiGraph.py | Python | gpl-2.0 | 3,116 | 0.08344 | #!/usr/bin/env python
"""
test cache functions.
- save/load
- mmerge
"""
import unittest
import trustlet.igraphXdigraphMatch as IXD
import networkx as nx
import igraph
import os
#import sys
#import random
#import time
class TestIXD(unittest.TestCase):
def setUp(self):
self.g = IXD.XDiGraph()
self.g.add_edge('da... | e", ('luc','dan',x)
self.assert_(False)
except nx.N | etworkXError:
pass
def testEdges(self):
self.assertEqual( sorted( self.g.edges() ) ,
sorted( [('dan','mas',{'level':'journeyer'}),
('mart','mas',{'level':'journeyer'}),
('luc','mas',{'level':'master'}),
('dan','luc',{'level':'apprentice'})]
)
... |
jirikadlec2/rushvalley | python/clean_logs.py | Python | mit | 964 | 0.030083 | #! /usr/bin/env python
import os
import sys
from dateutil import parser
BACK_LOG_SIZE = 14
if len(sys.argv) > 1:
print "This script deletes all but the " + str(BACK_LOG_SIZE) +" ne | west logs generated by the uploader."
print "It prints this message when run with any parameters. None are required."
sys.exit()
strdates = []
for root, dirs, files in os.walk("logfiles/"):
if len(files) > BACK_LOG_SIZE:
for filename in files:
if len(filename) > 8:
filename = filename.strip()
strDate ... | trDate.replace("_", " ")
strdates.append(strDate)
#sorts the array to reverse rder (i.e. newest first)
strdates.sort( key=parser.parse, reverse=True)
i = -1
for date in strdates:
i = i + 1
if i < BACK_LOG_SIZE : #skips the newest 10
continue
else:
#have to parse the filename back into shape
filename = dat... |
CSIRTUK/TekDefense-Automater | outputs.py | Python | mit | 39,375 | 0.007289 | """
The outputs.py module represents some form of all outputs
from the Automater program to include all variation of
output files. Any addition to the Automater that brings
any other output requirement should be programmed in this module.
Class(es):
SiteDetailOutput -- Wrapper class around all functions that print out... | if isinstance(siteimpprop, basestring):
if "" + site.ReportStringForResult + " " + str(siteimpprop) != laststring:
print "" + site.ReportStringForResult + " " + str(siteimpprop).replace('www.', 'www[.] | ').replace('http', 'hxxp')
laststring = "" + site.ReportStringForResult + " " + str(siteimpprop)
#must be a list since it failed the isinstance check on string
else:
laststring = ""
fo... |
rsepassi/tensor2tensor | tensor2tensor/models/xception.py | Python | apache-2.0 | 5,805 | 0.010336 | # coding=utf-8
# Copyright 2018 The Tensor2Tensor Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable... |
dilations_and_kernels = [((1, 1), k) for _ i | n xrange(3)]
y = common_layers.subseparable_conv_block(
x,
hparams.hidden_size,
dilations_and_kernels,
padding="SAME",
separability=0,
name="residual_block")
x = common_layers.layer_norm(x + y, hparams.hidden_size, name="lnorm")
return tf.nn.dropout(x, 1.0 - hparams.dropout)
... |
yangjiePro/cutout | example.py | Python | mit | 4,408 | 0.030525 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
import os, time
from cutout import cutout
datastr = '''
<html>
<head>
<title>html网页标题</title>
</head>
<body>
<ul id="img">
<li> <p>pic1</p> <img src="/img/pic1.jpg" /> </li>
<li> <p>pic... | 'pic2', '/ | img/pic2.jpg'], ['pic3', '/img/pic3.jpg']]
# 获取的结果数组第一个为 ['', None] 因为以 <li> 分割时 第一段字符为空
exit(0);
from cutout.cache import FileCache
print('\n\n######## cache缓存测试\n')
print("\n## FileCache 文件缓存测试\n")
key = '缓存键 hash key'
c = FileCache('./cache') #指定缓存目录
c.set(key, ['2w3w','agafd'],10)
g = c.get(key)
prin... |
Azure/azure-sdk-for-python | sdk/batchai/azure-mgmt-batchai/azure/mgmt/batchai/aio/operations/_jobs_operations.py | Python | mit | 44,498 | 0.005371 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | if not next_link:
# Construct URL
url = self.list_by_experiment.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', pattern=r'^[-\w\._]+$'),
... | erialize.url("experiment_name", experiment_name, 'str', max_length=64, min_length=1, pattern=r'^[-\w_]+$'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_a... |
hvanwyk/quadmesh | src/mesh.py | Python | mit | 263,904 | 0.010803 | #import matplotlib.pyplot as plt
import numpy as np
from collections import deque
import numbers
"""
Created on Jun 29, 2016
@author: hans-werner
"""
def convert_to_array(x, dim=None, return_is_singleton=False):
"""
Convert point or list of points to a numpy array.
Inputs:
x: (list of)... | ss.'
#
# Add tree to forest
#
forest.add_tree(self)
self._in_forest = True
self._forest = forest
self._node_address = [self.get_node_position()]
else:
... | assert self.get_node_position() is None, \
'Unattached ROOT cell has no position.'
#
# Assign space for children
#
self._children = [None]*n_children
self._n_children = n_children
... |
OCA/vertical-medical | medical_practitioner/models/medical_practitioner.py | Python | gpl-3.0 | 1,734 | 0 | # -*- coding: utf-8 -*-
# Copyright 2017 LasLabs Inc.
# Copyright 2017 Creu Blanca
# Copyright 2017 Eficent Business and IT Consulting Services, S.L.
# License GPL-3.0 or later (http://www.gnu.org/licenses/gpl.html).
from odoo import api, fields, models, modules
class MedicalPractitioner(models.Model):
_name = '... | y'
_sql_constraints = [(
'medical_practitioner_unique_code',
'UNIQUE (code)',
'Internal ID must be unique',
)]
role_ids = fields.Many2many(
string='Roles',
comodel_name='medical.role',
)
practitioner_type = fields.Selection(
string='Entity Type',
... | help='Unique ID for this physician',
required=True,
default=lambda s: s.env['ir.sequence'].next_by_code(s._name + '.code'),
)
specialty_ids = fields.Many2many(
string='Specialties',
comodel_name='medical.specialty',
)
@api.model
def _get_default_image_path(self... |
gridsync/gridsync | scripts/make_appimage.py | Python | gpl-3.0 | 4,585 | 0.000218 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
try:
from configparser import RawConfigParser
except ImportError:
from ConfigParser import RawConfigParser
import glob
import os
import shutil
import subprocess
import sys
config = RawConfigParser(allow_no_value=True)
config... | e "$(readlink -e "$0")")/usr/bin/{}" "$@"
'''.format(name_lower)
)
os.chmod('build/AppDir/AppRun', 0o755)
# Create the .DirIcon symlink here/now to prevent appimagetool from
# doing it later, thereby allowing the atime and mtime of the symlink
# to be overriden along with all of the other files in the AppDir.
try... | sename(icon_filepath), "build/AppDir/.DirIcon")
except OSError:
pass
subprocess.call(["python3", "scripts/update_permissions.py", "build/AppDir"])
subprocess.call(["python3", "scripts/update_timestamps.py", "build/AppDir"])
try:
os.mkdir('dist')
except OSError:
pass
try:
subprocess.call([
'a... |
VillanCh/vscanner | vplugin/nmap/nmap.py | Python | apache-2.0 | 41,045 | 0.004629 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
nmap.py - version and date, see below
Source code : https://bitbucket.org/xael/python-nmap
Author :
* Alexandre Norman - norman at xael.org
Contributors:
* Steve 'Ashcrow' Milner - steve at gnulinux.net
* Brian Bustin - brian at bustin.us
* old.schepperhand
* Joha... | can_result = {}
self._nmap_vers | ion_number = 0 # nmap version number
self._nmap_subversion_number = 0 # nmap subversion number
self._nmap_last_output = '' # last full ascii nmap output
is_nmap_found = False # true if we have found nmap
self.__process = None
# regex used to detect nmap (http or... |
nkhare/rockstor-core | src/rockstor/storageadmin/urls/users.py | Python | gpl-3.0 | 1,027 | 0.000974 | """
Copyright (c) 2012-2013 RockStor, Inc. <http://rockstor.com>
This file is part of Rock | Stor.
RockStor is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published
by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
RockStor is distributed in the hope that it will be useful, but
WITHOUT ANY ... | e 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 django.conf.urls import patterns, url
from storageadmin.views import (UserListView, UserDetailView)
from django.conf import settings
urlpatterns = patterns(
... |
QualiApps/obdlib | tests/test_utils.py | Python | mit | 6,692 | 0.000299 | import unittest
import obdlib.utils as utils
class TestUtils(unittest.TestCase):
def setUp(self):
utils.unit_english = 0
def test_rpm(self):
assert utils.rpm('0000') == 0.0
assert utils.rpm('FFFF') == 16383.75
def test_speed(self):
# unit_english == 0
self.assertE... | tus('04'),
'From the outsid | e atmosphere or off')
self.assertEqual(utils.air_status('08'),
'Pump commanded on for diagnostics')
def test_voltage(self):
self.assertEqual(utils.voltage('00'), 0)
self.assertEqual(utils.voltage('FF'), 1.275)
def test_coolant_temp(self):
self.assertEqu... |
googleapis/python-dialogflow | samples/generated_samples/dialogflow_generated_dialogflow_v2_versions_delete_version_async.py | Python | apache-2.0 | 1,427 | 0.000701 | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | snippet has been automatically generated for illustrative purposes only.
# It may require modifications to work in your environment.
# To install the latest published package dependency, execute the following:
# python3 -m pip install google-cloud-dialogflow
# [START dialogflow_generated_dialogflow_v2_Versions_Del... | yncClient()
# Initialize request argument(s)
request = dialogflow_v2.DeleteVersionRequest(
name="name_value",
)
# Make the request
await client.delete_version(request=request)
# [END dialogflow_generated_dialogflow_v2_Versions_DeleteVersion_async]
|
gems-uff/labsys | labsys/main/__init__.py | Python | mit | 206 | 0 |
import os
from .views import blueprint
@blueprint.app_context_processor
def inje | ct_permissions():
| show_labsys = not os.environ.get('SHOW_LABSYS') == 'False'
return dict(show_labsys=show_labsys)
|
xfxf/veyepar | dj/main/migrations/0007_auto_20160710_1833.py | Python | mit | 560 | 0.001786 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on | 2016-07-10 18:33
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependenci | es = [
('main', '0006_auto_20160616_1640'),
]
operations = [
migrations.AlterField(
model_name='episode',
name='edit_key',
field=models.CharField(blank=True, default='41086227', help_text='key to allow unauthenticated users to edit this item.', max_length=32,... |
foursquare/commons-old | src/python/twitter/pants/base/hash_utils.py | Python | apache-2.0 | 192 | 0.026042 |
import has | hlib
def hash_all(strs):
"""Returns a hash of the concatenation of all the strings in strs."""
sha = hashlib.sha1( | )
for s in strs:
sha.update(s)
return sha.hexdigest()
|
jicruz/heroku-bot | cogs/general.py | Python | gpl-3.0 | 17,226 | 0.002979 | import discord
from discord.ext import commands
from .utils.chat_formatting import escape_mass_mentions, italics, pagify
from random import randint
from random import choice
from enum import Enum
from urllib.parse import quote_plus
import datetime
import time
import aiohttp
import asyncio
settings = {"POLL... | joined_at = self.fetch_joined_at(user, server)
since_created = (ctx.message.timestamp - user.created_at).days
since_joined = (ctx.message.timestamp - joined_at).days
user_joined = joined_at.strftime("%d %b %Y %H:%M")
user_created = user.created_at.strftime("%d %b %Y %H:%M")
... | "{}\n({} days ago)".format(user_created, since_created)
joined_on = "{}\n({} days ago)".format(user_joined, since_joined)
game = "Chilling in {} status".format(user.status)
if user.game is None:
pass
elif user.game.url is None:
game = "Playing {}".forma... |
pferreir/indico | indico/modules/oauth/blueprint.py | Python | mit | 2,547 | 0.006675 | # This file is part of Indico.
# Copyright (C) 2002 - 2021 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
|
from flask import request
from indico.modules.oauth.controllers import (RHO | AuthAdmin, RHOAuthAdminApplication, RHOAuthAdminApplicationDelete,
RHOAuthAdminApplicationNew, RHOAuthAdminApplicationReset,
RHOAuthAdminApplicationRevoke, RHOAuthAuthorize, RHOAuthIntrospect,
... |
mfem/PyMFEM | mfem/_par/eltrans.py | Python | bsd-3-clause | 26,581 | 0.007148 | # This file was automatically generated by SWIG (http://www.swig.org).
# Version 4.0.2
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
from sys import version_info as _swig_python_version_info
if _swig_python_version_info < (2, 7, 0):
raise Runtime... | mation_ElementType_set, doc=r"""ElementType : int""")
mesh = property(_eltrans.ElementTransformation_mesh_get, _eltrans.ElementTransformation_mesh_set, doc=r"""mesh : p.mfem::Mesh""")
def Reset(self):
r"""Reset(ElementTransformation self)"""
return _eltrans.ElementTransformation_Reset(self)
... | lementTransformation_Reset)
def SetIntPoint(self, ip):
r"""SetIntPoint(ElementTransformation self, IntegrationPoint ip)"""
return _eltrans.ElementTransformation_SetIntPoint(self, ip)
SetIntPoint = _swig_new_instance_method(_eltrans.ElementTransformation_SetIntPoint)
def GetIntPoint(self):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.