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 |
|---|---|---|---|---|---|---|---|---|
gem/oq-engine | openquake/hazardlib/gsim/can15/nbcc2015_aa13.py | Python | agpl-3.0 | 7,068 | 0 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Module exports :class:`NBCC2015_AA13`
"""
import io
import os
import numpy as np
from openquake.hazardlib.gsim.gmpe_table import (
GMPETable, _get_mean, _get_stddev)
from openquake.hazardlib.gsim.base import CoeffsTable
from openquake.hazardlib import const
from op... | , 'WinterfaceCombo_%sclC'],
['offsho | re', 'rhypo', 'Offshore', 'Woffshore_%s_clC']]
for key, dist, trt, hdf5 in arguments:
for kind in ('low', 'med', 'high'):
name = f"NBCC2015_AA13_{key}_" + ("central" if kind == "med" else kind)
add_alias(name, NBCC2015_AA13,
REQUIRES_DISTANCES=[dist],
DEFINED_FOR_... |
annafw/python_exploration | rectangle.py | Python | gpl-2.0 | 584 | 0.027397 | import turtle;
import random | ;
bob=turtle.Turtle();
def squareBob():
for i in range(4):
bob.fd(200)
bob.rt(90)
def triangleBob(size | =100):
for i in range(3):
bob.fd(size)
bob.lt(120)
def circleBob(size=100):
for i in range(360):
bob.fd(3)
bob.lt(1)
def spiral(side, angle, steps):
if(steps > 0): # when steps = 0 (or less than) stop
bob.fd(side)
bob.rt(angle)
spiral(side+5,angle,s... |
klahnakoski/jx-sqlite | vendor/jx_base/expressions/is_text_op.py | Python | mpl-2.0 | 1,090 | 0 | # encoding: utf-8
#
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http:# mozilla.org/MPL/2.0/.
#
# Contact: Kyle Lahnakoski (kyle@lahnakoski.com)
#
from __future__ import absolute_import, divis... | f.term.map(map_))
def missing(self, lang):
return self.expr.missing()
def partial_eval(self, lang):
term = self.ter | m.partial_eval(lang)
if term.type is STRING:
return term
else:
return NULL
|
maoy/zknova | nova/api/openstack/compute/contrib/floating_ips_bulk.py | Python | apache-2.0 | 6,057 | 0.000495 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 IBM
# 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/LI... |
def index(self, req):
"""Return a list of all floating ips."""
context = req.environ['nova.context']
authoriz | e(context)
return self._get_floating_ip_info(context)
def show(self, req, id):
"""Return a list of all floating ips for a given host."""
context = req.environ['nova.context']
authorize(context)
return self._get_floating_ip_info(context, id)
def _get_floating_ip_info(s... |
greyhavens/thane | tamarin-central/utils/stitch.py | Python | bsd-2-clause | 19,451 | 0.01784 | # ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla Public License Version
# 1.1 (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.mozilla.org/MPL/
#
# Softwa... | =\"implsection\"><b>Implementation</b>",
"---": "—"
}
currentlevel = 0
es_dir = os.path.abspath("../builtins")
sml_dir = os.path.abspath("..")
# fn is the filename from the INCLUDE tag: it has no directory component.
# Returns a sequence of strings.
#
# Works by looking for the string 'name' at the... | s up to a line with <= n whitespace chars preceding
# non-whitespace chars or up to and including the line with a } in
# position n. Trailing empty lines, if any, are removed.
#
# If it's too slow to process a file every time we want to extract a
# function then this interface can be backed by a simple program that
# ... |
shimpe/expremigen | examples/twovoicewithchords.py | Python | gpl-3.0 | 2,485 | 0.00161 | from expremigen.io.constants import PhraseProperty as PP
from expremigen.io.pat2midi import Pat2Midi
from expremigen.io.phrase import Phrase
from expremigen.musicalmappings.durations import Durations as Dur
from expremigen.musicalmappings.dynamics import Dynamics as Dyn
from expremigen.musicalmappings.note2midi import ... | (increasing_staccato, 0, 0, len(notes), len(notes)),
# volume should l | inearly go up from mp to f, then go down from f to ppp as the phrase progresses
PP.VOL: Ptween(swell_dim, 0, 0, len(notes), len(notes), None),
}
p = Phrase(properties)
pat2mid.set_tempo(60)
pat2mid.add_phrase(p, track=track, channel=channel, start_time=0)
return pat2mid
def add_chords(pat2... |
linuxdeepin/deepin-translator | src/translate_window.py | Python | gpl-3.0 | 4,229 | 0.008513 | #! /usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (C) 2011 ~ 2013 Deepin, Inc.
# 2011 ~ 2013 Wang Yong
#
# Author: Wang Yong <lazycat.manatee@gmail.com>
# Maintainer: Wang Yong <lazycat.manatee@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the t... | elf.setColor(QColor(0, 0, 0, 0))
| self.setResizeMode(QtQuick.QQuickView.SizeRootObjectToView)
self.setFormat(surface_format)
# self.setFlags(QtCore.Qt.Popup)
self.setFlags(QtCore.Qt.Tool | QtCore.Qt.FramelessWindowHint)
self.qml_context = self.rootContext()
self.init_translate_info()
... |
matthiasplappert/keras-rl | rl/common/vec_env/__init__.py | Python | mit | 2,310 | 0.000866 | # Inspired from VecEnv from OpenAI Baselines
class VecEnv(object):
"""
An abstract asynchronous, vectorized environment.
"""
def __init__(self, num_envs, observation_space, action_space):
self.num_envs = num_envs
self.observation_space = observation_space
self.action_space = act... | results of the step.
You should not call this if a step_async run is
already pending.
"""
raise NotImplementedError()
def step_wait(self):
"""
Wait for the step taken with step_async().
Returns (obs, rews, dones, infos):
- obs: an array of observati... | of observations.
- rews: an array of rewards
- dones: an array of "episode done" booleans
- infos: a sequence of info objects
"""
raise NotImplementedError()
def close(self):
"""
Clean up the environments' resources.
"""
raise NotImplemente... |
luchasei/http-log-app | httpLogAnalytics.py | Python | mit | 1,523 | 0.00394 | import threading
import time
from collections import Counter
from httpLogSettings import WAIT_PERIOD_S
class AnalyticsThread(threading.Thread):
'''Background thread to record and aggregate statistics about req | uests'''
def __init__(self, updatePeriod, q, lock):
threading.Thread.__init__(self)
self.updatePeriod = updatePeriod
self.q = q
self.lock = lock
self.overallBytes = 0
self.overallRequests = 0
self.sectionsCount = Counter()
def addEntry(self, entry):
... | es += entry.sizeBytes
self.overallRequests += 1
self.sectionsCount[entry.urlSection] += 1
def printStatistics(self):
print ("\n*********************************")
print ("Overall Requests Counted = %d" % self.overallRequests)
print ("Overall Bytes Downloaded = %d" % self.ove... |
skosukhin/spack | var/spack/repos/builtin/packages/py-macs2/package.py | Python | lgpl-2.1 | 1,863 | 0.00161 | ##############################################################################
# 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 Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | 999.
#
# 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 o... | 0, Boston, MA 02111-1307 USA
##############################################################################
from spack import *
class PyMacs2(PythonPackage):
"""MACS2 Model-based Analysis of ChIP-Seq"""
homepage = "https://github.com/taoliu/MACS"
url = "https://pypi.io/packages/source/M/MACS2/MACS2... |
tethysplatform/tethys | tests/unit_tests/test_tethys_compute/test_scheduler_manager.py | Python | bsd-2-clause | 3,572 | 0.00056 | from unittest import mock
from tethys_sdk.testing import TethysTestCase
from tethys_compute.models import Scheduler
from tethys_compute.scheduler_manager import list_schedulers, get_scheduler, \
create_condor_scheduler, create_dask_scheduler, create_scheduler
class SchedulerManagerTests(TethysTestCase):
def ... | private_key_path=private_key_path,
| private_key_pass=private_key_pass)
@mock.patch('tethys_compute.scheduler_manager.DaskScheduler')
def test_create_dask_scheduler(self, mock_ds):
name = 'foo'
host = 'localhost'
timeout = 10
heartbeat_interval = 5
dashboard = 'test_dashboard'
mock_sch ... |
antoinecarme/sklearn2sql_heroku | tests/classification/BinaryClass_500/ws_BinaryClass_500_SVC_linear_db2_code_gen.py | Python | bsd-3-clause | 138 | 0.014493 | from s | klearn2sql_heroku.tests.classification import generic as class_gen
cla | ss_gen.test_model("SVC_linear" , "BinaryClass_500" , "db2")
|
lcgamboa/sh3dtoblender | old/sh3d_html5_to_blender.py | Python | gpl-2.0 | 16,266 | 0.025023 | # ########################################################################
#
# SweetHome3D HTML5 to Blender importer
#
# ########################################################################
#
# Copyright (c) : 2018 Luis Claudio Gambôa Lopes
#
# This program is free software; you can redistribute it and/or ... | =float(element.get('floorThickness'))))
if objectName == 'furnitureGroup':
for furniture in element:
xmlRoot.append(furniture);
#if objectName in ('doorOrWindow','pieceOfFurniture'):
if 'model' in element.keys():
print(objectName)
... | dimZ = float(element.get('depth'))
locX = float(element.get('x'))*scale
locY = -float(element.get('y'))*scale
lve=0.0;
if 'level' in element.keys():
for lv in levels:
if lv.id == element.get('level'):
lve=(lv.elev)*scale
... |
capitalone/cloud-custodian | tools/c7n_kube/tests/test_labels.py | Python | apache-2.0 | 2,332 | 0.000858 | # Copyright 2019 Capital One Services, LLC
# Copyright The Cloud Custodian Authors.
# SPDX-License-Identifier: Apache-2.0
from common_kube import KubeTest
class TestLabelAction(KubeTest):
def test_label_action(self):
factory = self.replay_flight_data()
p = self.load_policy(
{
... | )
resources = p.run()
self.assertTrue(resources)
client = factory().client(group='Core', version='V | 1')
resources = client.list_service_for_all_namespaces().to_dict()['items']
test_namespace = [r for r in resources if r['metadata']['name'] == 'hello-node']
self.assertEqual(len(test_namespace), 1)
labels = test_namespace[0]['metadata']['labels']
self.assertTrue('test' in labels.... |
siddhika1889/Pydev-Editor | tests/pysrc/extendable/grammar3/relative.py | Python | epl-1.0 | 32 | 0.03125 | class NotFoun | d(object):
pass | |
mosquito/lumper | lumper/worker/build.py | Python | lgpl-3.0 | 8,330 | 0.0012 | #!/usr/bin/env python
# encoding: utf-8
import logging
import json
import os
import shutil
import traceback
import git
import re
import requests
from crew.worker import context, HandlerClass
from uuid import uuid4
from tempfile import gettempdir
log = logging.getLogger("builder")
class TemporaryFolder(object):
... | = ("%s/%s" % (registry, name)).lower()
| try:
self.docker.tag(self.data['id'], repo, tag)
except Exception as e:
log.error(e)
log.info(
"Preparing to push to the registry: %s://%s",
'https' if use_ssl else 'http', registry if registry else 'PUBLIC'
)
response ... |
ufieeehw/IEEE2016 | ros/ieee2016_diagnostics_ported/src/xmega/visualize_imu_output.py | Python | mit | 4,849 | 0.004949 | #!/usr/bin/python
## Input
import argparse
## Display
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import pygame
import time
import threading
## Math
import numpy as np
## Ros
import rospy
from tf import transformations as tf_trans
## Data Structures
from collections import deque, OrderedDic... | item in self.plot_items:
self.plot_dict[item] = deque()
self.state_sub = rospy.Subscriber(topic, Imu, self.got_state)
# Set up and start the plot
fig = plt.figure()
self.ax = fig.add_subplot(1, 1, 1)
ani = animation.FuncAnimation(f | ig, self.draw, interval=100)
plt.show()
def set_plotter(self, fig, ax):
self.fig = fig
self.ax = ax
def get_sub_item(self, msg, attribute):
if '.' in attribute:
return reduce(lambda a, b: getattr(a, b), attribute.split('.'), msg)
else:
re... |
gsarma/PyOpenWorm | tests/ProfileTest.py | Python | mit | 920 | 0 | """
Not actuall | y tests, | but benchmarks.
"""
from __future__ import print_function
from PyOpenWorm.neuron import Neuron
from PyOpenWorm.connection import Connection
from PyOpenWorm import connect, disconnect
def setup():
connect(configFile='tests/data_integrity_test.conf')
def teardown():
disconnect()
def test_adal_connections()... |
isi-nlp/gump | matching/LAPJV.py | Python | mit | 11,287 | 0.002835 | # This function solves the Linear Assignment Problem by implementing the Jonker-Volgenant algorithm
# This code began as an effort to port the matlab code available at:
# http://www.mathworks.com/matlabcentral/fileexchange/26836-lapjv-jonker-volgenant-algorithm-for-linear-assignment-problem-v3-0
#
#
# Reference:
# R. J... | umin > resolution:
| # change the reduction of the minmum column to increase the
# minimum reduced cost in the row to the subminimum.
v[j1] -= (usubmin - umin)
else: # minimum and subminimum equal.
if i0 >= 0: # minimum column j1 is assigned.
# swap colum... |
bandang0/theia | tutos/telescope.py | Python | gpl-3.0 | 1,642 | 0.050548 | '''Tutorial to demonstrate theia.'''
import numpy as np
from theia.running import simulation as sim
from | theia.optics import beam as gbeam
from theia.optics import mirror as mir
from theia.helpers import settings
from theia.helpers.units import *
# initialize globals (necessary to use theia in library form)
dic = {'info': False, 'warning': True, 'text': True, 'cad': True,
'fname' | : 'telescope', 'fclib' : '/usr/lib/freecad/lib',
'antiClip': True, 'short': False}
settings.init(dic)
# Mirrors of telescope
alpha = np.pi/2. - np.arctan(.1)
beta = np.pi/2. + np.arctan(.1)
mirror1 = mir.Mirror(Thickness = 1*cm, Diameter = 5*cm, X = 1*m,
Theta = alpha, Phi = 180.*deg, HRK = 0.90, A... |
RedhawkSDR/framework-codegen | redhawk/codegen/jinja/cpp/component/persona/generator.py | Python | lgpl-3.0 | 3,715 | 0.005384 | #
# This file is protected by Copyright. Please refer to the COPYRIGHT file
# distributed with this source distribution.
#
# This file is part of REDHAWK core.
#
# REDHAWK core 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
... | AutomakeTemplate('Makefile.am'),
AutomakeTemplate('base/Makefile.am.ide', userfile=True),
| AutoconfTemplate('configure.ac'),
ShellTemplate('base/build.sh'),
ShellTemplate('common/reconf')
]
is_device = True
is_executable = False
for superclass in component['superclasses']:
if superclass['name'] == 'Resource_impl':
... |
ujvl/ray-ng | python/ray/experimental/sgd/pytorch/pytorch_runner.py | Python | apache-2.0 | 4,800 | 0 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import logging
import torch
import torch.utils.data
import ray
from ray.experimental.sgd.pytorch import pytorch_utils
from ray.experimental.sgd import utils
logger = logging.getLogger(__name__)
class PyTorc... | is None else config
self.bat | ch_size = batch_size
self.verbose = True
self.epoch = 0
self._timers = {
k: utils.TimerStat(window_size=1)
for k in [
"setup_proc", "setup_model", "get_state", "set_state",
"validation", "training"
]
}
def setup(se... |
AlexanderKaluzhny/instanotifier | instanotifier/fetcher/rss/utils.py | Python | mit | 635 | 0.001575 | import json
from django.core.serializers.json i | mport DjangoJSONEncoder
from instanotifier.fetcher.rss.fetcher import fetch_rss_feed
def fetch_rss_url(url):
result = fetch_rss_feed(url)
return result
def write_to_file(filename, data):
json_data = json.dumps(data, cls=DjangoJSONEncoder)
with open(filename, "w") as f:
f.write(json_data)
... | ification, json.loads deserializes the publisher_parsed field into invalid format
with open(filename, "r") as f:
filedata = f.read()
json_data = json.loads(filedata)
return json_data
|
eayunstack/oslo.messaging | doc/source/conf.py | Python | apache-2.0 | 2,113 | 0 | # -*- coding: utf-8 -*-
import os
import sys
sys.path.insert(0, os.path.absp | ath('../..'))
# -- General configuration ----------------------------------------------------
# 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.autodoc', 'sphinx.ext.intersphinx', 'oslosp | hinx']
# autodoc generation is a bit aggressive and a nuisance when doing heavy
# text edit cycles.
# execute "export SPHINX_DEBUG=1" in your terminal to disable
# Add any paths that contain templates here, relative to this directory.
# templates_path = []
# The suffix of source filenames.
source_suffix = '.rst'
# ... |
GirlsCodePy/girlscode-coursebuilder | modules/courses/courses_integration_tests.py | Python | gpl-3.0 | 1,816 | 0 | # Copyright 2016 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 ... | _availability(
cls=courses_pageobjects.CourseAvailabilityPage
).verify_content_present_no_msgs(
has_triggers=True
).verify_add_trigger_button(
)
empty_course_name = self.create_new_course(login=False)[0]
self.load_dashboard(
empty_course_name
... | ses_pageobjects.CourseAvailabilityPage
).verify_empty_content_msgs(
).verify_no_trigger_button(
)
|
nttks/edx-platform | biz/djangoapps/ga_contract/views.py | Python | agpl-3.0 | 10,301 | 0.002136 | """
Views for contract feature
"""
import json
import logging
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from django.shortcuts import get_object_or_404, redirect
from django.utils.translation import ugettext as _
from djang... | ractor_organization = form.cleaned_data['contractor_organization']
contract.owner_organization = current_org
contract.save()
# add new contract detail info
for detail_info in detail_list:
contract_detail = ContractDetail(contract=contract, course_id=detail_info['course_id'])... | return redirect(reverse('biz:contract:index'))
else:
# validation failed
return render_to_response("ga_contract/detail.html", {
'form': form,
'detail_list': json.dumps(detail_list),
'course_list': _get_course_name_list(current_org.org_code),
})
@req... |
marcosbontempo/inatelos | poky-daisy/scripts/lib/mic/3rdparty/pykickstart/commands/bootloader.py | Python | mit | 9,658 | 0.001864 | #
# Chris Lumens <clumens@redhat.com>
#
# Copyright 2007 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use, modify,
# copy, or redistribute it subject to the terms and conditions of the GNU
# General Public License v.2. This program is distributed in the hope that it
# will be usef... | password != "":
retval += " --password=\"%s\"" % self.password
if self.md5pass != "":
retval += " --md5pass=\"%s\"" % self.md5 | pass
if self.upgrade:
retval += " --upgrade"
if self.useLilo:
retval += " --useLilo"
if len(self.driveorder) > 0:
retval += " --driveorder=\"%s\"" % ",".join(self.driveorder)
return retval
def __str__(self):
retval = KickstartCommand.__st... |
hiepthai/django-activity-stream | actstream/settings.py | Python | bsd-3-clause | 726 | 0.004132 | from django.conf import settings
SETTINGS = getattr(settings, 'ACTSTREAM_SETTINGS', {})
def get_action_manager():
"""
Returns the class of the action m | anager to use from ACTSTREAM_SETTINGS['MANAGER']
"""
mod = SETTINGS.get('MANAGER', 'actstream.managers.ActionManager')
mod_path = mod.split('.')
try:
return getattr(__import__('.'.join(mod_path[:-1]), {}, {},
[mod_path[-1]]), mod_path[-1])()
except ImportErr... | rtError('Cannot import %s try fixing ACTSTREAM_SETTINGS[MANAGER]'
'setting.' % mod)
FETCH_RELATIONS = SETTINGS.get('FETCH_RELATIONS', True)
USE_JSONFIELD = SETTINGS.get('USE_JSONFIELD', False)
|
dstenb/pylaunchr-netflix | tests/parsers/title_test.py | Python | mit | 1,822 | 0.001098 | from os.path import abspath, dirname, join
from unittest.mock import MagicMock, Mock, call
from tests.common import NetflixTestFixture
from netflix.data.genre import NetflixGenre
from netflix.parsers.title import NetflixTitleParser
from netflix.utils import netflix_url
class TestNetflixTitleParser(NetflixTestFixtu... | _string)
self.assertEqual(title.title, "House of Cards")
self.assertEqual(title.title_id, 70178217) |
self.assertEqual(title.year, 2013)
self.assertEqual(title.maturity, "Adult")
self.assertEqual(title.duration, "4 Seasons")
self.assertEqual(title.description, "Foo. Bar. Baz.")
self.assertEqual(title.background_url, "https://scdn.nflximg.net/ipl/29399/578030fdb9fc2b6de6f3d47b2f3... |
makcedward/nlpaug | test/augmenter/audio/test_mask.py | Python | mit | 1,503 | 0.002661 | import unittest
import os
import numpy as np
from dotenv import load_dotenv
import nlpaug.augmenter.audio as naa
from nlpaug.util import AudioLoader
class TestMask(unittest.TestCase):
@classmethod
def setUpClass(cls):
env_config_path = os.path.abspath(os.path.join(
os.path.dirname(__file_... | V50-Rock-Beat-120bpm.wav'
)
cls.audio, cls.sampling_rate = AudioLoader.load_audio(cls.sample_wav_file)
def test_empty_input(self):
audio = np.array([])
aug = naa.MaskAug(sampling_rate=44100)
augmented_audio = aug.augment(audio)
self.assertTrue(np.array_equal(audio, ... | te, mask_with_noise=True)
augmented_audio = aug.augment(self.audio)
self.assertFalse(np.array_equal(self.audio, augmented_audio))
self.assertEqual(len(self.audio), len(augmented_audio))
def test_without_noise(self):
aug = naa.MaskAug(sampling_rate=self.sampling_rate, mask_with_nois... |
QudevETH/PycQED_py3 | pycqed/measurement/sweep_functions.py | Python | mit | 14,291 | 0.00091 | import logging
import time
import numpy as np
from pycqed.measurement import mc_parameter_wrapper
import qcodes
class Sweep_function(object):
'''
sweep_functions class for MeasurementControl(Instrument)
'''
def __init__(self, **kw):
self.set_kw()
def set_kw(self, **kw):
'''
... | eral sweep functions into a single joint sweep functions.
'''
def __init__(self,
sweep_functions: list,
parameter_name=None,
name=None,
**kw):
self.set_kw()
self.swe | ep_functions = [mc_parameter_wrapper.wrap_par_to_swf(s)
if isinstance(s, qcodes.Parameter) else s
for s in sweep_functions]
self.sweep_control = 'soft'
self.name = name or 'multi_sweep'
self.unit = sweep_functions[0].unit
se... |
NTUHEP-Tstar/TstarAnalysis | SignalMCStudy/python/MCResolution.py | Python | mit | 2,760 | 0.014855 | #*******************************************************************************
#
# Filename : MCResolution.py
# Description : Config file for generating tree for resolution calculation
# Author : Yi-Mu "Enoch" Chen [ ensc@hep1.phys.ntu.edu.tw ]
#
#******************************************************... | tions.output )
)
process.mcr | es = cms.EDAnalyzer(
"MCResolution",
jetsrc = cms.InputTag("slimmedJets"),
muonsrc = cms.InputTag("slimmedMuons"),
elecsrc = cms.InputTag("slimmedElectrons"),
gensrc = cms.InputTag("prunedGenParticles")
)
process.p = cms.Path( process.mcres )
print "Finish reading cfg file... Loading main framewor... |
russellmayhew/satchmo | satchmo/apps/payment/modules/giftcertificate/models.py | Python | bsd-3-clause | 6,200 | 0.005968 | from datetime import datetime
from decimal import Decimal
from django.contrib.sites.models import Site
from django.db import models
from django.utils.translation import ugettext_lazy as _
from l10n.utils import moneyfmt
from payment.modules.giftcertificate.utils import generate_certificate_code
from payment.utils impor... | return self.balance
def save(self, **kwargs):
if not self.pk:
self.date_added = datetime.now()
if not self.code:
self.code = generate_certificate_code()
if not self.site:
self.site = Site.objects.get_current()
| super(GiftCertificate, self).save(**kwargs)
def __unicode__(self):
sb = moneyfmt(self.start_balance)
b = moneyfmt(self.balance)
return u"Gift Cert: %s/%s" % (sb, b)
class Meta:
verbose_name = _("Gift Certificate")
verbose_name_plural = _("Gift Certificates")
class ... |
linglung/ytdl | youtube_dl/extractor/cda.py | Python | unlicense | 5,037 | 0.001392 | # coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
ExtractorError,
float_or_none,
int_or_none,
parse_duration,
)
class CDAIE(InfoExtractor):
_VALID_URL = r'https?://(?:(?:www\.)?cda\.pl/video|ebd\.cda\.pl/[0-9]+x[0-9]+)/(?P<i... | son_str, '%s player_dat | a' % version, fatal=False)
if not player_data:
return
video = player_data.get('video')
if not video or 'file' not in video:
self.report_warning('Unable to extract %s version information' % version)
return
f = {
... |
sourlows/pyagricola | src/field/node_item.py | Python | mit | 3,158 | 0.00285 | __author__ = 'djw'
class FieldNodeItem(object):
"""
An item built on a player's field board, held within a node/cell on that board
"""
def __init__(self):
self.cattle = 0
self.boars = 0
self.sheep = 0
self.grain = 0
self.vegetables = 0
def update_animals(s... | """
return
def score(self):
"""
Calculates and returns the current score of this item.
"""
raise NotImplementedError()
def describe(self):
"""
Return the current state of this item as a string that will be drawn
"""
raise NotImplementedE... | ):
"""
A single room on a player's field board
"""
MATERIAL_CHOICES = frozenset(['wood', 'stone', 'clay'])
def __init__(self, material='wood'):
super(RoomItem, self).__init__()
if material not in self.MATERIAL_CHOICES:
raise ValueError('Invalid material %s not in %s' % (... |
sean797/Flexget | flexget/plugins/estimators/est_release_series_internal_db.py | Python | mit | 2,707 | 0.003694 | from __future__ import unicode_literals, division, absolute_import
from builtins import * # noqa pylint: disable=unused-import, redefined-builtin
from datetime import timedelta
import logging
from sqlalchemy import desc, func
from flexget import plugin
from flexget.event import event
from flexget.manager import Ses... | # Estimate next e | pisode comes out about same length as last ep span, with a little leeway
return episodes[0].first_seen + multiply_timedelta(last_diff, 0.9)
@event('plugin.register')
def register_plugin():
plugin.register(EstimatesSeriesInternal, 'est_series_internal', interfaces=['estimate_release'], api_ver=2)
|
damonkelley/pattern-matcher | pattern_matcher/regex.py | Python | mit | 1,449 | 0.00138 | import re
class RegexFactory(object):
"""Generates a compiled regular expression object."""
NODE_GROUP = '({0}|\*)'
SEP = '/'
def _generate_pattern(self, path):
"""Generates a regex pattern.
Parameters:
path: string
A pattern is generated by converting each node ... | se a list of regular expression groups for each node in
# the path.
patterns = (self.NODE_GROUP.format(re.escape(node)) for node in nodes)
# Implode the list into a single regex pattern that will | match
# the path pattern format.
return '^{0}$'.format(('\,').join(patterns))
@classmethod
def create(cls, path):
"""Create a regular expression object from a path.
Parameters:
path: string
"""
rf = cls()
pattern = rf._generate_pattern(path)... |
sebastiandev/clipton | clipton/__init__.py | Python | mit | 598 | 0.003344 | import platform
from .clipboard import Clipbo | ard
__version__ = '1.0.0'
def get_clipboard(handle=None):
system = platform.system().lower()
if 'windows' == system:
from . import win_clipboard
clip = win_clipboard.WinClipboard(handle)
el | if 'darwin' == system:
raise NotImplementedError("Clipboard not available for MacOS yet")
else:
try:
from . import gtk_clipboard
clip = gtk_clipboard.GTKClipboard(handle)
except:
raise NotImplementedError("Clipboard for Qt not available yet")
r... |
ygol/odoo | addons/sale_timesheet/wizard/__init__.py | Python | agpl-3.0 | 262 | 0 | # -*- cod | ing: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from . import project_create_sale_order
from . import project_create_invoice
from . import sale_make_invoice_advance
from . import project_task_create_sale_o | rder
|
DarthMaulware/EquationGroupLeaks | Leak #5 - Lost In Translation/windows/Resources/Dsz/PyScripts/Lib/dsz/mca/status/cmd/uptime/types.py | Python | unlicense | 340 | 0.005882 | # uncompyle6 version 2.9.10
# Python bytecode 2.7 (62211)
# Decompiled from: Python 3.6.0b2 (default, Oct 11 2 | 016, 05:27:10)
# [GCC 6.2.0 20161005]
# Embedded file name: types.py
from types import *
MSG_KEY_PARAMS = 65536
MSG_KEY_PARAMS_TARGET = 65537
MSG_KEY_RESULT = 131072
MSG_KEY_RESULT_UPTIME = 13107 | 3
MSG_KEY_RESULT_IDLETIME = 131074 |
ComputerNetworks-UFRGS/AuroraSDN | sdn/models/base_model.py | Python | gpl-2.0 | 601 | 0 | import logging
from django.db import models
class BaseModel(models.Model):
class Meta:
# Makes django recognize model in split modules
app_label = 'sdn'
# Turns this into an abstract model (does not create table for it)
abstract = True
# Default exception for models in manager... | def __init__(self, msg):
self.msg = msg
self.logger.warning(msg)
def __str__(self):
return repr(self.msg)
| |
telerik/cloudbase-init | cloudbaseinit/tests/test_init.py | Python | apache-2.0 | 6,047 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013 Cloudbase Solutions Srl
#
# 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/LICEN... | gin')
self.osutils.get_config_value.ass | ert_called_once_with(
'fake plugin', self._init._PLUGINS_CONFIG_SECTION)
self.assertTrue(response == 1)
def test_set_plugin_status(self):
self._init._set_plugin_status(self.osutils, 'fake plugin', 'status')
self.osutils.set_config_value.assert_called_once_with(
'fak... |
simple/md-preview | md_preview/__init__.py | Python | mit | 49 | 0 | # -*- c | oding: utf-8 -*-
from md_preview | import *
|
bdmod/extreme-subversion | BinarySourcce/subversion-1.6.17/subversion/bindings/swig/python/tests/trac/test.py | Python | gpl-2.0 | 1,070 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2003, 2004, 2005 Edgewall Software
# Copyright (C) 2003, 2004, 2005 Jonas Borgström <jonas@edgewall.com>
# Copyright (C) 2005 Christopher Lenz <cmlenz@gmx. | de>
#
# This software is licensed as described in the file
# LICENSE_FOR_PYTHON_BINDINGS, which you should have | received as part
# of this distribution. The terms are also available at
# < http://subversion.tigris.org/license-for-python-bindings.html >.
# If newer versions of this license are posted there, you may use a
# newer version instead, at your option.
#
# Author: Jonas Borgström <jonas@edgewall.com>
# Christop... |
silkyar/570_Big_Little | build/ARM/python/m5/internal/param_BaseSimpleCPU.py | Python | bsd-3-clause | 3,817 | 0.019387 | # This file was automatically generated by SWIG (http://www.swig.org).
# Version 1.3.40
#
# 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
if version_info >= (2,6,0):
def swig_import_helper():
from os.path import d... | wig_property = property
except NameError:
pass # Python < 2.2 doesn't have 'property'.
def _swig_setattr_nondynamic(self,class_type,name,value,static=1):
if (name == "thisown"): return self.this.own(value)
if (name == "this"):
if type(value).__name__ == 'SwigPyObject':
self.__dict__[name... | thods__.get(name,None)
if method: return method(self,value)
if (not static) or hasattr(self,name):
self.__dict__[name] = value
else:
raise AttributeError("You cannot add attributes to %s" % self)
def _swig_setattr(self,class_type,name,value):
return _swig_setattr_nondynamic(self,class_t... |
ihacklog/osdlyrics | python/pattern.py | Python | gpl-3.0 | 5,769 | 0.002602 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2011 Tiger Soldier
#
# This file is part of OSD Lyrics.
#
# OSD Lyrics 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... | place holder in the pattern:
- %t: Title of the track. 'title' in metadata
- %p: Performer (artist) of the music. 'artist' in m | etadata
- %a: Album of the music. 'album' in metadata
- %n: Track number of the music. 'tracknumber' in metadata
- %f: Filename without extension of the music. 'location' in metadata.
- %%: The `%' punctuation
Arguments:
- `pattern`: The pattern to expand.
- `metadata`: A dict representing ... |
chazmead/django-clubhouse | clubhouse/core/__init__.py | Python | bsd-2-clause | 551 | 0.009074 | # vim: ai ts=4 sts=4 et sw=4
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
import copy
from importlib import import_module
from django.apps import AppConfig
from django.db.models import options
__all__ = | ['ClubHouseCoreConfig','site']
class ClubHouseCoreConfig(AppConfig):
name = 'clubhouse.core'
verbose_name = 'ClubHouse Core'
label = 'clubhouse_core'
de | fault_app_config = 'clubhouse.core.ClubHouseCoreConfig'
from clubhouse.core.sites import clubhouse
site = clubhouse
|
FakeKane/poke-AI | move.py | Python | mit | 483 | 0.00207 | cl | ass Move(object):
def __init__(self, mname, mtype, mstyle, mdmg, macc, mpp):
self.mname = mname
self.mtype = mtype
| self.mstyle = mstyle
self.mdmg = mdmg
self.macc = macc
self.mpp = mpp
def print_info(self):
print "Name: ", self.mname
print "Type: ", self.mtype
print "Category: ", self.mstyle
print "Damage: ", self.mdmg
print "Accuracy: ", self.macc
... |
ARM-software/bob-build | tests/generate_source/generator.py | Python | apache-2.0 | 1,833 | 0.001091 | #!/bin/python
# Copyright 2018-2020 Arm Limited.
# SPDX-License-Identifier: Apache-2.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
#
# ... | tore', help='Input files')
parser.add_argument('--out', nargs='*', dest='output', action='store', help='Output file')
parser.add_argument("--expect-in", nargs='*', action='store',
help='Basenames of expected input files')
args = parser.parse_args()
if args.expect_in:
received_basenames = sorte... | int("Expected the following files:", ", ".join(expected_basenames))
print("But received these:", ", ".join(received_basenames))
sys.exit(1)
for input_file in args.input:
if not os.path.exists(input_file):
print("Input file doesn't exist: " + input_file)
sys.exit(1)
for out in args.... |
pbs/django-cms | cms/plugins/picture/models.py | Python | bsd-3-clause | 1,579 | 0.005066 |
from django.db import models
from django.utils.translation import ugettext_lazy as _
from cms.models import CMSPlugin, Page, get_plugin_media_path
from os.path import basename
class Picture(CMSPlugin):
"""
A Picture with or without a link
"""
CENTER = "center"
LEFT = "left"
RIGHT = "right"
... | dels.ImageField(_("image"), upload_to=get_plugin_media_path)
url = models.CharField(_("link"), max_length=255, blank=True, null=True, help_text=_("if present image will be clickable"))
page_link = models.ForeignKey(Page, verbose_name=_("page"), null=True, blank=True, help_text=_("if present image will be clicka... | _("alternate text"), max_length=255, blank=True, null=True, help_text=_("textual description of the image"))
longdesc = models.CharField(_("long description"), max_length=255, blank=True, null=True, help_text=_("additional description of the image"))
float = models.CharField(_("side"), max_length=10, blank=True... |
plotly/plotly.py | packages/python/plotly/plotly/validators/barpolar/marker/_showscale.py | Python | mit | 425 | 0 | import | _plotly_utils.basevalidators
class ShowscaleValidator(_plotly_utils.basevalidators.BooleanValidator):
def __init__(
self, plotly_name="showscale", parent_name="barpolar.marker", **kwargs
):
super(ShowscaleValidator, self).__init__(
plotly_name=plotly_name,
parent_name=p... | me,
edit_type=kwargs.pop("edit_type", "calc"),
**kwargs
)
|
jdhp-sap/sap-cta-data-pipeline | datapipe/benchmark/assess.py | Python | mit | 37,422 | 0.003474 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2016,2017,2018 Jérémie DECOCK (http://www.jdhp.org)
# This script is provided under the terms and conditions of the MIT license:
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation... | INGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE O | R OTHER DEALINGS IN
# THE SOFTWARE.
__all__ = ['normalize_array',
'metric_mse',
'metric_nrmse',
'metric1',
'metric2',
'metric3',
'metric4',
'metric_ssim',
'metric_psnr',
'metric_delta_psi',
'metric_hillas_delt... |
Khrotan/alamo | old silly codes/checkMountedDevice.py | Python | gpl-2.0 | 517 | 0.021277 | __author__ = 'root'
import subprocess
from subprocess import check_output
def cmd_output(args, **kwds):
kw | ds.setdefault("stdout", subprocess.PIPE)
kwds.setdefault("stderr", subprocess.STDOUT)
# kwds.setdefault("shell",True)
p = subprocess.Popen(args, **kwds)
return p.communicate()[0]
partition="/dev/sdb3"
output = check_output("mount")
output=str(output)
if output.find(partition) != -1:
print("The partition %s ... | T mounted." %partition) |
transifex/openformats | openformats/formats/pptx.py | Python | gpl-3.0 | 11,708 | 0 | import io
import itertools
import os
import re
import shutil
import tempfile
import uuid
from zipfile import ZIP_DEFLATED, ZipFile
import six
from bs4 import BeautifulSoup
from openformats.handlers import Handler
from openformats.exceptions import MissingParentError
from openformats.formats.office_open_xml.parser impo... | _key
)
return slides
def get_slide(self, slide):
if self.__slides[slide]['slide']['content'] is None:
with io.open(self.__slides[slide]['slide']['path'], 'r') as f:
self.__slides[slide]['slide']['content'] = f.read()
return self.__slides[slide]['slide'][... | ef set_slide(self, slide, content):
self.__slides[slide]['slide']['content'] = content
with io.open(self.__slides[slide]['slide']['path'], 'w') as f:
f.write(content)
def get_slide_rels(self, slide):
if self.__slides[slide]['rels']['content'] is None:
with io.open(s... |
ProjectSWGCore/NGECore2 | scripts/conversation/quests/tatooine/vourk.py | Python | lgpl-3.0 | 6,535 | 0.029839 | from resources.common import ConversationOption
from resources.common import OutOfBand
from resources.common import ProsePackage
from java.util import Vector
import sys
def startConversation(core, actor, npc):
player = actor.getPlayerObject()
if player is None:
return
|
quest = player.getQuest('tatooine_eisley_legacy')
if quest is | None:
endConversation(core, actor, npc)
return
# Check if player finished the main talking quest, if they did then handle mayor and trehla return/not yet started options
if quest.isCompleted() == True:
if player.getQuest('tatooine_eisley_gotoniko') is not None:
core.conversationService.sendStopConversa... |
locationtech/geowave | analytics/pyspark/src/main/python/geowave_pyspark/__init__.py | Python | apache-2.0 | 603 | 0.006633 | ############################################################## | #################
# Copyright (c) 2013-2020 Contributors to the Eclipse Foundation
#
# See the NOTICE file distributed with this work for additional
# information regarding copyright ownership.
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Apache L... | ###########################
import types |
duy/pinax-syncr-delicious | delicious/delicious.py | Python | gpl-3.0 | 8,100 | 0.004691 | # originally from
# http://code.google.com/p/django-syncr/source/browse/trunk/app/delicious.py
# supousse django-syncr should be installed as external app and this code
# inherit from that, but django-syncr have not a setup.py file (so can't be
# added in src/pinax/requirements/external_apps.txt) and is not migrate... | bookmark
else:
print "bookmark_instance_form no es valido"
return
def syncRecent(self, count=15, tag=None):
"""
Synchronize the user's recent bookmarks.
Optional arguments:
count: The number of bookmarks to return, default 15, max 100.
... | s tag.
"""
params = {'count': count}
if tag: params['tag'] = tag
result = self.delicious._request('posts/recent?', params)
root = result.getroot()
for post in list(root):
self._syncPost(post)
def syncAll(self, user, tag=None):
"""
Synchron... |
ngokevin/zamboni | mkt/feed/tests/test_serializers.py | Python | bsd-3-clause | 16,035 | 0.000125 | # -*- coding: utf-8 -*-
from collections import defaultdict
from nose.tools import eq_, ok_
from rest_framework.serializers import ValidationError
import amo
import amo.tests
import mkt
import mkt.feed.constants as feed
from mkt.feed import serializers
from mkt.feed.constants import COLLECTION_LISTING, COLLECTION_PR... | stCase):
def setUp(self):
self.feedapp = self.feed_app_factory(
app_type=feed.FEEDAPP_DESC, description={'en-US': 'test'})
self.feedapp.update(preview=Preview.objects.create(
addon=self.feedapp.app, sizes={'thumbnail': [50, 50]}))
self.data_es = self.feedapp.get_ind... | pIndexer.extract_document(
self.feedapp.app_id)
}
def test_deserialize(self):
data = serializers.FeedAppESSerializer(self.data_es, context={
'app_map': self.app_map,
'request': amo.tests.req_factory_factory('')
}).data
eq_(data['app']['id'], s... |
fossdevil/Assignments | Miscellaneous/services/checkports.py | Python | mit | 2,065 | 0.007748 | import socket
from contextlib import closing
import argparse
import os
import | sys
import pdb
import argparse
sys.path.insert(0, '/scratche/home/ashutosh/services/queue/')
from queue_client import QueueClient
# AVAILABLE SERVERS
SERVERS = {
"idli" : "10.24.28.102",
"momo" : "10.24.28.103",
"dosa" : "10.24.28.104",
"poha" : "10.24.28.105",
"puri" : "10.24.28.106",
"peda"... | QueueClient(S)
def check_socket(host, port):
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
return not (sock.connect_ex((host, port)) == 0)
def checkrange(host, ll=4200, ul=4300):
res = []
for b in range(ll, ul+1):
if check_socket(host, b):
res.append(... |
obmarg/synchg | synchg/remote.py | Python | bsd-3-clause | 484 | 0.002066 | import sys
from plumbum import SshMachine, PuttyMachine
_WIN32 = sys.platform.startswith('win')
def RemoteMachine(*pargs | , **kwargs):
'''
Remote machine constructor function. Forwards all arguments on to the
appropriate constr | uctor for this platform. On windows this is
``plumbum.PuttyMachine`` and on other platforms `plumbum.SshMachine`
'''
if _WIN32:
return PuttyMachine(*pargs, **kwargs)
else:
return SshMachine(*pargs, **kwargs)
|
Ernestyj/PyStudy | DataScience/python/td_query/data_manipulate.py | Python | apache-2.0 | 16,127 | 0.005953 | # -*- coding: utf-8 -*-
import os
import pandas as pd
from teradata.api import DatabaseError
import pickle
from td_query.td_query_base import *
from td_query import ROOT_PATH
class DataManipulate(TeradataQueryBase):
def __init__(self, conf_path=os.path.join(ROOT_PATH, 'conf/conf.json'), teradata_platform='JACKAL... | # select good count from src table (only good)
count_df = self.query(query_string='''select count(*) from {}.{} where has_gloss = 0;'''.format(src_db, src_table))
good_count = float(count_df.iloc[0, 0])
self.logger.info('total good (has_gloss = 0) c | ount={}'.format(good_count))
# cal good sample rate
good_sample_rate = bad_count * 1.0 / bad_scale * good_scale / good_count
self.logger.info('bad_scale={}, good_scale={}, good_sample_rate={}'.format(bad_scale, good_scale, good_sample_rate))
temp_good_table = "temp_good_sample_" + dest_... |
marqh/cartopy | lib/cartopy/tests/mpl/test_shapely_to_mpl.py | Python | gpl-3.0 | 4,821 | 0.007882 | # (C) British Crown Copyright 2011 - 2012, Met Office
#
# This file is part of cartopy.
#
# cartopy is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation, either version 3 of the License, or
# (at your option)... | add_collection(collection)
@image_comparison(baseline_images=['contour_with_interiors'])
def test_contour_interiors():
# ############## produces a polygon with multiple holes:
nx, ny = 10, 10
numlev = 2
lons, lats = np.meshgrid(np.linspace(-50, 50, nx), np.linspace(-45, 45, ny))
data = np.sin(n... | tle("Native projection")
plt.contourf(lons, lats, data, numlev, transform=ccrs.PlateCarree())
ax.coastlines()
plt.subplot(222, projection=ccrs.PlateCarree())
plt.title("Non-native projection")
ax = plt.gca()
ax.set_global()
plt.contourf(lons, lats, data, numlev, transform=ccrs.Geodetic(... |
isaacs/yuidoc | bin/const.py | Python | bsd-3-clause | 1,665 | 0.046847 | '''
Copyright (c) 2009, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.net/yui/license.html
version: 1.0.0b1
'''
ACCESS='access'
ATTRIBUTE='attribute'
BEFORE='before'
BETA='beta'
BUBBLES='bubbles'
CANCELABLE='cancelable'
CHAINABLE='chainable'
CHANGEEVENT='Change'
CLASS='cl... | EVENTS='hasevents'
HOST='host'
IGNORE_PATTERNS = ('*.pyc','CVS','^.git','.svn')
LONGNAME='longname'
LOGCONFIG='yuidoclog.conf' |
METHOD='method'
METHODS='methods'
MAJOR_VERSION='majorversion'
MODULE='module'
MODULE_PREFIX='module_'
MODULES='modules'
NAME='name'
NAMESPACE='namespace'
NAMESPACES='namespaces'
NBWS=' '
OBJECT='object'
OPTIONAL='optional'
PARAM='param'
PARAMS='params'
PRIVATE='private'
PREVENTABLE='preventable'
PROPERTY='proper... |
andersroos/rankedftw | aid/test/base.py | Python | agpl-3.0 | 7,615 | 0.004202 | import inspect
import os
import sys
from datetime import timedelta
from io import StringIO
from unittest.mock import Mock
from urllib.error import HTTPError
import django
import django.db
import django.test.runner
import django.test.testcases
import django.test.utils
from django.test import TestCase
from aid.test.dat... | self.save_to_ranking()
def save_to_ranking(se | lf):
self.cpp.save_data(self.db.ranking.id, self.db.ranking.season_id, to_unix(utcnow()))
@classinstancemethod
def date(self, **kwargs):
return self.today + timedelta(**kwargs)
@classinstancemethod
def datetime(self, **kwargs):
return self.now + timedelta(**kwargs)
@classi... |
verilylifesciences/classifaedes | classifaedes/hparams_lib_test.py | Python | apache-2.0 | 1,292 | 0.001548 | # Copyright 2019 Verily Life Sciences 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | hps2 = hparams_lib.defaults()
hps2.parse_json(serialized)
self.assertDictEqual(hps1.values(), hps2 | .values())
if __name__ == '__main__':
tf.test.main()
|
coffenbacher/neo4django | neo4django/tests/synchronicity_tests.py | Python | gpl-3.0 | 2,374 | 0.004212 | from nose.tools import eq_, with_setup
from threading import Thread
from Queue import Queue
from time import sle | ep
def setup():
global Person, neo4django, gdb, neo4jrestclient, neo_constants, settings, models
from neo4django.tests import Person, neo4django, gdb, neo4jrestclient, \
neo_constants, settings
from neo4django.db import models
def teardown():
gdb.cleandb()
@with_setup(None, teardown)
def... | Queue()
def race():
r = RaceModel()
try:
r.save()
except Exception, e:
exc_queue.put(str(e))
else:
exc_queue.put(True)
num_threads = 5
for i in xrange(num_threads):
thread = Thread(target=race)
thread.start()
for i i... |
repotvsupertuga/tvsupertuga.repository | script.module.cryptolib/lib/cryptopy/cipher/aes_cbc.py | Python | gpl-2.0 | 563 | 0.010657 | """ cryptopy.cipher.aes_cbc
AES_CBC Encryption Algorithm
Copyright (c) 2002 by | Paul A. Lambert
Read LICENSE.txt for license information.
2002-06-14
"""
from cryptopy.cipher.aes import AES
from cryptopy.cipher.cbc import CBC
from cryptopy.cipher.base import BlockCipher, padWithPadLen, noPadding
class AES_CBC(CBC):
""" AES encryption in CBC feedbac | k mode """
def __init__(self, key=None, padding=padWithPadLen(), keySize=16):
CBC.__init__( self, AES(key, noPadding(), keySize), padding)
self.name = 'AES_CBC'
|
stephane-martin/salt-debian-packaging | salt-2016.3.3/tests/integration/modules/hosts.py | Python | apache-2.0 | 6,468 | 0.000309 | # -*- coding: utf-8 -*-
'''
Tes | t the hosts module
'''
# Import python libs
from __future__ import absolute_import
import os
import shutil
# Import Salt Testing libs
from salttesting.helpers import ensure_in_syspath
ensure_in_syspath('../../')
# Import salt libs
import integration
import salt.utils
HFN = os.path.join(integration.TMP, 'hosts')
cl... | ostsModuleTest(integration.ModuleCase):
'''
Test the hosts module
'''
maxDiff = None
def __clean_hosts(self):
'''
Clean out the hosts file
'''
shutil.copyfile(os.path.join(integration.FILES, 'hosts'), HFN)
def __clear_hosts(self):
'''
Delete the... |
iot-factory/synapse | synapse/config/appservice.py | Python | apache-2.0 | 926 | 0.00108 | # Copyright 2015 OpenMarket Ltd
#
# 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 writin... | ig(Config):
def read_config(self, config):
self.app_service_config_files = config.get("app_service_config_files", [])
def default_config(cls, **kwargs):
| return """\
# A list of application service config file to use
app_service_config_files: []
"""
|
smmribeiro/intellij-community | python/testData/inspections/PyDefaultArgumentInspection/test.py | Python | apache-2.0 | 658 | 0.045593 | def f(a, L=<warning descr="Default argument value is mutable">[]</warning>):
L.append(a)
return L
def f(a, L=<warning | descr="Default argument value is mutable">list()</warning>):
L.append(a)
return L
def f(a, L=<warning descr="Default ar | gument value is mutable">set()</warning>):
L.append(a)
return L
def f(a, L=<warning descr="Default argument value is mutable">{}</warning>):
L.append(a)
return L
def f(a, L=<warning descr="Default argument value is mutable">dict()</warning>):
L.append(a)
return L
def f(a, L=<warning descr="D... |
lyarwood/bugwarrior | bugwarrior/services/youtrack.py | Python | gpl-3.0 | 5,955 | 0.00084 | from __future__ import absolute_import
import re
import six
import requests
from jinja2 import Template
from bugwarrior.config import asbool, die
from bugwarrior.services import IssueService, Issue, ServiceClient
import logging
log = logging.getLogger(__name__)
class YoutrackIssue(Issue):
ISSUE = 'youtrackiss... | ase_url,
'import_tags': self.import_tags,
'tag_template': self.tag_template,
}
@classmethod
def validate_config(cls, config, target):
for k in ('youtrack.login', 'youtrack.password', 'youtrack.host'):
if not config.has_option(target, k):
die("... | lf.query, 'max': self.query_limit})
issues = self.json_response(resp)['issue']
log.debug(" Found %i total.", len(issues))
for issue in issues:
yield self.get_issue_for_record(issue)
|
RainbowDinoaur/roxbot | roxbot/scripts/JSONtoDB.py | Python | mit | 6,104 | 0.003768 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# MIT License
#
# Copyright (c) 2017-2018 Roxanne Gibson
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including witho... | ggingSingle` SET `enabled` = {} WHERE `guild_id` = {}".format(settings["enabled"], guild_id))
db.execute('UPDATE `LoggingSingle` SET `logging_channel_id` = "{}" WHERE `guild_id` = {}'.format(settings["ch | annel"], guild_id))
@db_session
def voice_convert(guild_id, settings):
db.execute("UPDATE `VoiceSingle` SET `need_perms` = {} WHERE `guild_id` = {}".format(settings["need_perms"], guild_id))
db.execute("UPDATE `VoiceSingle` SET `skip_voting` = {} WHERE `guild_id` = {}".format(settings["skip_voting"], guild_id... |
JamesMura/yo_payments | docs/conf.py | Python | mit | 978 | 0.001022 | import sys
import os
cwd = os.getcwd()
project_root = os.path.dirname(cwd)
sys.path.insert(0, project_root)
import yo_payments
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode']
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'Yo Payments'
copyright = u'2013, James M... | nts.__version__
release = yo_payments.__version__
exclude_patterns = ['_build']
pygments_style = 'sphinx'
html_theme = 'default'
html_static_path = ['_static']
htmlhelp_basename = 'yo_paymentsdoc'
latex_elements = {
}
latex_documents = [
('index', 'yo_payments.tex', u'Yo Payments Documentation',
u'Jame... | ents Documentation',
u'James Muranga', 'yo_payments', 'One line description of project.',
'Miscellaneous'),
]
|
collmot/ardupilot | Tools/ardupilotwaf/ardupilotwaf.py | Python | gpl-3.0 | 16,193 | 0.004076 | #!/usr/bin/env python
# encoding: utf-8
from __future__ import print_function
from waflib import Build, ConfigSet, Configure, Context, Errors, Logs, Options, Utils
from waflib.Configure import conf
from waflib.Scripting import run_command
from waflib.TaskGen import before_method, feature
import os.path, os
from collec... | AC_Sprayer',
'AC_Fence',
| 'AC_Avoidance',
'AP_LandingGear',
'AP_RobotisServo',
'AP_ToshibaCAN',
'AP_NMEA_Output',
'AP_Filesystem',
'AP_ADSB',
'AC_PID',
'AP_SerialLED',
'AP_EFI',
'AP_Hott_Telem',
'AP_ESC_Telem',
'AP_Stats',
'AP_GyroFFT',
'AP_RCTelemetry',
'AP_Generator',
'AP_MSP'... |
lthurlow/Network-Grapher | proj/external/numpy-1.7.0/numpy/polynomial/tests/test_hermite_e.py | Python | mit | 16,441 | 0.012286 | """Tests for hermite_e module.
"""
from __future__ import division
import numpy as np
import numpy.polynomial.hermite_e as herme
from numpy.polynomial.polynomial import polyval
from numpy.testing import *
He0 = np.array([ 1 ])
He1 = np.array([ 0 , 1 ])
He2 = np.array([ -1 ,0 , 1 ])
He3 = np.array([ 0 , -3 ,0 , 1 ])
... | dd(self) :
for i in range(5) :
for j in range(5) :
msg = "At i=%d, j=%d" % (i,j)
tgt = np.zeros(max(i,j) + 1)
tgt[i] += 1
tgt[j] += 1
res = herme.hermeadd([0]*i + [1], [0]*j + [1])
assert_equal(trim(res),... | j in range(5) :
msg = "At i=%d, j=%d" % (i,j)
tgt = np.zeros(max(i,j) + 1)
tgt[i] += 1
tgt[j] -= 1
res = herme.hermesub([0]*i + [1], [0]*j + [1])
assert_equal(trim(res), trim(tgt), err_msg=msg)
def test_hermemulx(self)... |
DrsExplorer/StickyNotes | src/StickyNoteBook.py | Python | bsd-3-clause | 3,157 | 0.006335 | # -*- coding:utf-8 -*-
import os
import webbrowser
import wx
import wx.richtext as rt
import wx.lib.scrolledpanel as scrolled
import wx.lib.platebtn as platebtn
import StickyNote
class NoteWidget(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent, style = wx.BORDER_THEME)
self.S... | , 1, wx.EXPAND | wx.ALL, 10)
# sizer.AddMany([(p1, 0, wx.EXPAND), (p2, 0, wx.EXPAND),
# (p3, 0, wx.EXPAND)])
# hsizer = wx.BoxSizer(wx.HORIZONTAL)
# hsizer.Add(sizer, 1, wx.EXPAND)
self.SetSizer(sizer)
# e1.GetSizer().Fit(self)
sizer.Fit(self)
... | print "DROPARROW PRESSED"
def OnChildFocus(self, evt):
"""Override ScrolledPanel.OnChildFocus to prevent erratic
scrolling on wxMac.
"""
if wx.Platform != '__WXMAC__':
evt.Skip()
child = evt.GetWindow()
self.ScrollChildIntoView(child)
class Gradie... |
suyashphadtare/sajil-final-erp | erpnext/erpnext/accounts/doctype/c_form/c_form.py | Python | agpl-3.0 | 2,694 | 0.023756 | # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
from frappe.utils import flt
from frappe import _
from frappe.model.document import Document
class CForm(Document):
def validate(self... | invoices"""
self.set_total_invoiced_amount()
def on_submit(self):
self.set_cform_in_sales_invoices()
def before_cancel(self):
# remove cform reference
frappe.db.sql("""update `tabSales Invoice` set c_form_no=null where c_form_no=%s""", | self.name)
def set_cform_in_sales_invoices(self):
inv = [d.invoice_no for d in self.get('invoice_details')]
if inv:
frappe.db.sql("""update `tabSales Invoice` set c_form_no=%s, modified=%s where name in (%s)""" %
('%s', '%s', ', '.join(['%s'] * len(inv))), tuple([self.name, self.modified] + inv))
frap... |
shonenada/flask-bearychat | flask_bearychat/bearychat.py | Python | mit | 2,945 | 0 | # -*- coding: utf-8 -*-
import json
from flask import request, Response
class TokenError(Exception):
pass
class OutgoingResponse(object):
ATTACHMENT_FILEDS = ('title', 'text', 'color', 'images')
def __init__(self):
self.text = None
self._attachments = []
def set_text(self, text):... | d_url_rule(self.bearychat_callback, view_func=self.dispatch)
def command(self, command, **kwargs):
"""A decorator for registering a command handler.
Example::
@bearychat.command('hi')
def hi(**kwargs):
user_name = kwargs.get('user_name')
retu... | m command: the command to register.
:param kwargs: extra args pass to the function.
"""
def wrapper(func):
self._funcs[command] = (func, kwargs)
return func
return wrapper
def dispatch(self):
"""A flask view function which dispath the http request to
... |
roshantha9/AbstractManycoreSim | src/analyse_results/AnalyseResults_ExecutionCosts.py | Python | gpl-3.0 | 14,740 | 0.016486 | import sys, os, csv, pprint, math
from collections import OrderedDict
import numpy as np
import random
import shutil
import math
import matplotlib
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import scipy.stats
import itertools
from matplotlib.colors import ListedColormap, NoNorm
from matplo... | _file_data) |
# get communication costs
FNAME_PREFIX = "Exp_m"+str(m) + "_p"+str(p) + "_"
fname = EXP_DATA_DIR + "/seed_" + str(each_seed) + "/" + FNAME_PREFIX + 'wf'+str(wf)+'_cores'+str(NUM_NODES) + "_flwcompleted.js"
json_data=open(fname)
... |
128technology/yinsolidated | yinsolidated/_error.py | Python | mit | 1,393 | 0.002154 | # Copyright 2020 128 Technology, Inc.
"""Define all the exceptions of yinsolidated."""
class Error(Exception):
"""Base exception for yinsolidate | d."""
class _MissingAttributeError(Error):
"""Could not find an attribute"""
def __init__(self, attr, data_def_element):
message = "No {} attribute found for ancestors of {} '{}'".format(
attr, data_def_element.keyword, data_def_element.name
)
super(_MissingAttributeError... | ributeError):
"""Could not find prefix attribute"""
def __init__(self, data_def_element):
super(MissingPrefixError, self).__init__("prefix", data_def_element)
class MissingModuleNameError(_MissingAttributeError):
"""Could not find module-name attribute"""
def __init__(self, data_def_elemen... |
MiroK/julia-dns | dns.py | Python | mit | 3,428 | 0.007876 | __author__ = "Mikael Mortensen <mikaem@math.uio.no>"
__date__ = "2015-01-02"
__copyright__ = "Copyright (C) 2014-2016 " + __author__
__license__ = "GNU Lesser GPL version 3 or any later version"
from numpy import *
from numpy.fft import fftfreq, fft, ifft, irfft2, rfft2
from mpi4py import MPI
import time
# from pyfft... | url = empty((3, Np, N, N))
kx = fftfreq(N, 1./N)
kz = kx[:(N/2+1)].copy(); kz[-1] *= -1
K = array(meshgrid(kx, kx[rank*Np:(rank+1)*Np], kz, indexing='ij'), dtype=int)
K2 = sum(K*K, 0, dtype=int)
K_over_K | 2 = K.astype(float) / where(K2 == 0, 1, K2).astype(float)
kmax_dealias = 2./3.*(N/2+1)
dealias = array((abs(K[0]) < kmax_dealias)*(abs(K[1]) < kmax_dealias)*
(abs(K[2]) < kmax_dealias), dtype=bool)
a = [1./6., 1./3., 1./3., 1./6.]
b = [0.5, 0.5, 1.]
def fftn_mpi(u, fu):
Uc_hatT[:] = rfft2(u, axes=(... |
grow/grow | grow/templates/jinja_dependency.py | Python | mit | 5,519 | 0.001812 | """Track the jinja2 rendering dependencies using a custom environment.
Trying to track with a custom loader does not work since the templates are cached
by the environment and only triggers the loader the first time the template is used.
By using a modified version of the code generator and environment, the context
i... | 'template.new_context(context.get_all(), True, '
'%s)):' % (loop, self.dump_local_context(frame)))
elif self.environment.is_async:
self.writeline('for event in (await '
'template._get_default_module_async())'
'._body_st... | efault_module()'
'._body_stream')
skip_event_yield = True
else:
self.writeline('for event in template._get_default_module()'
'._body_stream:')
if not skip_event_yield:
self.indent()
... |
laurentb/weboob | modules/cmso/pro/pages.py | Python | lgpl-3.0 | 10,804 | 0.005185 | # -*- coding: utf-8 -*-
# Copyright(C) 2014 smurail
#
# This file is part of a weboob module.
#
# This weboob module is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License... | }
@method
class iter_accounts(ListElement):
item_xpath = '//div[has-class("groupe-comptes")]//li'
class item(ItemElement):
klass = Account
class Type(Filter):
def filter(self, label):
for pattern, actype in AccountsPage.T... | return actype
return Account.TYPE_UNKNOWN
obj__history_url = Link('.//a[1]')
obj_id = CleanText('.//span[has-class("numero-compte")]') & Regexp(pattern=r'(\d{3,}[\w]+)', default='')
obj_label = CleanText('.//span[has-class("libelle")][1]')
obj_c... |
WilsonKiggundu/HospitalManagement_InformationSystem | hospitalmanager/app/models.py | Python | gpl-3.0 | 999 | 0.003003 | from django.contrib.auth.models import *
from django.db import models
# Create your models here.
from django.db.models.signals import post_save
from django.dispatch import receiver
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
bio = models.TextField(max_... |
avatar = models.ImageField(upload_to='', null=True, blank=True)
birth_date = models.DateField(null=True, blank=True, help_text='Optional. Format: YYYY-MM-DD')
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, | **kwargs):
if created:
Profile.objects.create(user=instance)
@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.profile.save()
|
ivanamihalek/progesterone | 02_all_gene_ranges_from_UCSC.py | Python | gpl-2.0 | 2,989 | 0.029107 | #!/usr/bin/python3
#
# This file is part of Progesterone pipeline.
#
# Progesterone pipeline 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, ei | ther version 3 of the License, or
# (at your option) any later version.
#
# Progesterone pipeline 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 PA | RTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Progesterone pipeline. If not, see <https://www.gnu.org/licenses/>.
#
from utils.mysqldb import *
import os
#########################################
def main(... |
TheProjecter/wsgiuseragentmobile | uamobile/ezweb.py | Python | mit | 1,678 | 0.001192 | # -*- coding: utf-8 -*-
from uamobile.base import UserAgent, Display
class EZwebUserAgent(UserAgent):
carrier = 'EZweb'
short_carrier = 'E'
def supports_cookie(self):
return True
def make_display(self):
"""
create a Display object.
"""
env = self.environ
... | f get_serialnumber(self):
"""
return the EZweb subscriber ID.
if no subscriber ID is available, returns None.
"""
try:
return self.environ['HTTP_X_UP_SUBNO']
except KeyError:
return None
serialnumber = property(get_serialnumber)
def is_xht... | r the agent is CDMA 1X WIN or not.
"""
return self.device_id[2:3] == '3'
def is_wap1(self):
return not self.is_wap2()
def is_wap2(self):
return self.xhtml_compliant
|
Percona-Lab/mongodb_consistent_backup | mongodb_consistent_backup/Archive/Tar/TarThread.py | Python | apache-2.0 | 2,555 | 0.006262 | import os
import logging
from mongodb_consistent_backup.Common import LocalCommand
from mongodb_consistent_backup.Pipeline import PoolThread
class TarThread(PoolThread):
def __init__(self, backup_dir, output_file, compression='none | ', verbose=False, binary="tar"):
super(TarThread, self).__init__(self.__class__.__name__, compression)
self.compression_method = compression
self.backup_dir = backup_dir
self.output_file = output_file
self.verbose = verbose
self.binary ... | self._command = None
def close(self, exit_code=None, frame=None):
if self._command and not self.stopped:
logging.debug("Stopping running tar command: %s" % self._command.command)
del exit_code
del frame
self._command.close()
self.stopped = T... |
Chip000/ParkManager | ParkManager/main.py | Python | gpl-3.0 | 683 | 0.001466 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
from PyQt5 import QtWidgets
from python_package.mainwindowex import MainWindowE | x
from python_package.ui.parkmanager_rc import *
rootdir = os.getcwd()
cfgfile = os.path.join(rootdir, "settings.cfg")
if __name__ == "__main__":
# verify if cfgfile exists
try:
with open(cfgfile, 'r') as f:
f.readline()
except IOError:
print(u"Arquivo não existe.")
f =... | e=cfgfile)
mainWindow.showMaximized()
sys.exit(app.exec_())
|
ace02000/pyload | module/plugins/accounts/JunocloudMe.py | Python | gpl-3.0 | 417 | 0.014388 | # -*- coding: utf-8 -*-
from module.plugins.internal.XFSAccount import XFSAcc | ount
class JunocloudMe(XFSAccount):
__name__ = "JunocloudMe"
__type__ = "account"
__version__ = "0.04"
__status__ = "testing"
__description__ = """Junocloud.me account plugin"""
__license__ = "GPLv3"
__authors__ = [("guidobelix", | "guidobelix@hotmail.it")]
PLUGIN_DOMAIN = "junocloud.me"
|
silvau/Addons_Odoo | hr_bulk_period/wizard/__init__.py | Python | gpl-2.0 | 29 | 0 | from . im | port hr_bu | lk_period
|
Eduardogit/HackProjects | python/random-scripts/python course/clase5.py | Python | mit | 505 | 0.021782 | #Functions and Functional Programming
#La programacion funcional es un
#paradigma en el que la programacion
#se basa casi en su tota | lidad en funciones,
def saludar(lang):
def saludar_es():
print "Hola"
def | saludar_en():
print "Hi"
def saludar_fr():
print "Salut"
lang_func = {"es": saludar_es,
"en": saludar_en,
"fr": saludar_fr}
return lang_func[lang]
f = saludar("en")
f()
#Classes, Objects and other OOPS concepts |
Aravinthu/odoo | addons/google_drive/models/res_config_settings.py | Python | agpl-3.0 | 1,634 | 0.00306 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
class ResConfigSettings(models.TransientModel):
_inherit = "res.config.settings"
google_drive_authorization_code = fields.Char(string='Authorization Code')
google_drive... | "The URL to generate the authorization code from Google")
@api.depends('google_drive_authorization_code')
def _compute_drive_uri(self):
google_drive_uri = self.env['google.service']._get_google_token_uri('drive', scope=self.env['google.drive.confi | g'].get_google_scope())
for config in self:
config.google_drive_uri = google_drive_uri
@api.model
def get_values(self):
res = super(ResConfigSettings, self).get_values()
res.update(
google_drive_authorization_code=self.env['ir.config_parameter'].sudo().get_param(... |
liam2/liam2 | liam2/markedyaml.py | Python | gpl-3.0 | 1,201 | 0.003331 | # encoding: utf-8
from __future__ import absolute_import, division, print_function
import yaml
from yaml import Loader, SafeLoader
_marked_classes = {t: type("Marked" + t.__name__.title(), (t,),
{'start': None, 'end': None})
for t in (dict, list, str)}
def _wrap(method_n... | eturn wrapped
def make_marked_loader(name, base):
cls = type(name, (base,), {})
for tag, method_name in [('map', 'construct_mapping'),
('seq', 'construct_sequence'),
('str', 'construct_yaml_str')]:
cls.add_constructor(u'tag:yaml.org,2002:' + ta... | der', Loader)
SafeMarkedLoader = make_marked_loader('SafeMarkedLoader', SafeLoader)
def marked_load(stream):
return yaml.load(stream, MarkedLoader)
def safe_marked_load(stream):
return yaml.load(stream, SafeMarkedLoader)
|
alexoneill/py3status | py3status/modules/github.py | Python | bsd-3-clause | 9,985 | 0.000701 | # -*- coding: utf-8 -*-
"""
Display Github notifications and issue/pull requests for a repo.
To check notifications a Github `username` and `personal access token` are
required. You can create a personal access token at
https://github.com/settings/tokens The only `scope` needed is `notifications`,
which provides read... | ug/py3status'
url_api = 'https://api.github.com'
url_base = 'https://github.com'
username = None
def post_config_hook(self):
self.first = True
self.notification_warning = False
self.repo_warning = False
self._issues = '?'
self._pulls = '?'
self._notify = ... | # remove a trailing slash in the urls
self.url_api = self.url_api.strip('/')
self.url_base = self.url_base.strip('/')
def _init(self):
# Set format if user has not configured it.
if not self.format:
if self.username and self.auth_token:
# include noti... |
APMD/PMD | PMD/parser/parsers.py | Python | mit | 2,980 | 0 | from abc import ABCMeta, abstractmethod
from enum import Enum
class InputType(Enum):
ls = 1
dir = 2
unknown = 3
class ParserBase(metaclass=ABCMeta):
def __init__(self, input_text, extensions):
self.input = input_text.splitlines()
self.extensions = extensions
@abstractmethod
... | pass
@staticmethod
def _parse_line(line, num_word):
words = line.split(None, num_word - 1)
if len(words) < num_word:
return ''
else:
return words[num_word - 1]
def _ch | eck_extension(self, title):
if len(title) > 3 and title[-4] == '.':
for ext in self.extensions:
if title.endswith(ext):
return True
return False
class ParserLS(ParserBase):
def read_directories(self):
return self._read_directories(9)
def... |
gstarnberger/paasta | tests/cli/test_cmds_list.py | Python | apache-2.0 | 1,751 | 0 | # Copyright 2015-2016 Yelp Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | rvice_2\n'
@mock.patch('sys.stdout', new_callable=StringIO)
@mock.patch('paasta_tools.cli.cmds.list.list_service_instances', autospec=True)
def test_list_paasta_list_instances(mock_list_service_instances, mock_stdout):
""" paasta_list print each service.instance """
mock_services = ['service_1.main', 'servic... | _instances.return_value = mock_services
args = mock.MagicMock()
args.print_instances = True
paasta_list(args)
output = mock_stdout.getvalue()
assert output == 'service_1.main\nservice_2.canary\n'
|
sniperyen/MyDjango | restfulapi/models.py | Python | apache-2.0 | 654 | 0.001548 | # coding=utf-8
from django.db import models
class User(models.Model):
name = models.CharField(max_length=32)
mail = models.EmailField()
class Met | a:
db_table = 'user'
class Article(models.Model):
STATUS_SET = (
(0, "草稿"),
(1, "公开"),
)
title = models.CharField(max_length=128)
body = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
... | able = 'article' |
Gumtree/Kookaburra_scripts | Internal/PlotKKB-Tube.py | Python | epl-1.0 | 14,158 | 0.008193 |
__script__.title = 'HMM Tube Export'
__script__.version = '1.0'
from gumpy.nexus.fitting import Fitting, GAUSSIAN_FITTING
from math import exp, fabs
__FOLDER_PATH__ = 'V:/shared/KKB Logbook/Temp Plot Data Repository'
if not os.path.exists(__FOLDER_PATH__):
os.makedirs(__FOLDER_PATH__)
combine_t... | bes
data = zeros(n)
tids = []
if combine_tube0.value:
tids.append(0)
if combine_tube1.value:
tids.append(1)
if combine_tube2.value:
tids.append(2)
if combine_tube3.value:
tids.append(3)
if combine_tube4.value:
tids.append(4)
if c... |
data[:] = GetTubeCounts(ds.hmm, tid)
TimeNormalization(data, ds.time)
if sorting:
AnngleSorting(data, info)
data.var[:] = 0 # total_counts / (ds.time * ds.time)
axis0 = data.axes[0]
... |
thiblahute/hotdoc | hotdoc/extensions/c/clang/cindex.py | Python | lgpl-2.1 | 117,967 | 0.001221 | #===- cindex.py - Python Indexing Library Bindings -----------*- python -*--===#
#
# The LLVM Compiler Infrastructure
#
# This file is distributed under the University of Illinois Open Source
# License. See LICENSE.TXT for details.
#
#===--------------------------------------------------------------... | @staticmethod
def from_position(tu, file, line, column):
"""
Retrieve the source location associated with a given file/line/column in
a particular translation unit.
"""
return conf.lib.clang_getLocation(tu, file, line, column)
@staticmethod
def from_ | offset(tu, file, offset):
"""Retrieve a SourceLocation from a given character offset.
tu -- TranslationUnit file belongs to
file -- File instance to obtain offset from
offset -- Integer character offset within file
"""
return conf.lib.clang_getLocationForOffset(tu, file,... |
TeamTschunk/TschunkView | map1.py | Python | bsd-2-clause | 267 | 0.007491 |
class | TschunkMap1(): #(TschunkMap):
def __init__(self):
self.img = 'img/map1.png'
self.figure = 'todo'
self.rows = 15
self.cols = 7
self.origin_x = 1
self.origin_y = 13
self.initial_direc | tion = (0, -1)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.