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 |
|---|---|---|---|---|---|---|---|---|
evilsocket/arminject | trace_pid.py | Python | bsd-3-clause | 2,396 | 0.005426 | # Copyright (c) 2015, Simone Margaritelli <evilsocket at gmail dot com>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notic... | ollowing disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of ARM Inject nor the names of its contributors may be used
# to endorse or promote products derived fro | m this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN N... |
uclouvain/osis_louvain | base/migrations/0198_auto_20171130_1602.py | Python | agpl-3.0 | 1,184 | 0.002534 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-11-30 15:02
from __future__ import unicode_literals
from django.db import migrations, utils
from django.db import transaction
def copy_previous_pgrm_to_current_lunit(apps, model):
base = apps.get_app_config('base')
ProgramManager = base.get_model('... | tyError:
print("Duplicated.")
class Migration(migrations.Migration):
dependencies = [
('base', '0197_auto_20171130_0823'),
]
operations = | [
migrations.RunPython(copy_previous_pgrm_to_current_lunit),
]
|
kogotko/carburetor | openstack_dashboard/dashboards/project/security_groups/panel.py | Python | apache-2.0 | 783 | 0 | # Copyright 2017 Cisco Systems, 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 writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# u... | s'
|
algorythmic/bash-completion | test/t/test_pkgconf.py | Python | gpl-2.0 | 548 | 0 | import os
import pytest
@pytest.mark.bashcomp(cmd="pkgconf")
class TestPkgconf:
@pytest.mark.complete("pkgconf ")
def test_1(self, completion):
assert completion
@pytest.mark.complete("pkgconf -", require_cmd=True)
def test_2(self, completion):
assert completion
@pytest.mark.com... | letion.pc --va | riable="
% os.getenv("ABS_TOP_BUILDDIR", "../.."),
require_cmd=True,
)
def test_variable(self, completion):
assert "completionsdir" in completion
|
gppezzi/easybuild-framework | easybuild/tools/build_log.py | Python | gpl-2.0 | 13,380 | 0.00299 | # #
# Copyright 2009-2019 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be),
# Flemish Research Foundation (... | DEVEL_LOG_LEVEL, 'DEVEL')
class EasyBuildError(LoggedException):
"""
EasyBuildError is thrown when EasyBuild runs into something horribly wrong.
"""
LOC_INFO_TOP_PKG_NAMES = ['easybuild', 'vsc']
LOC_INFO_LEVEL = 1
# always include location where error was raised from, even under 'python -O'
... | msg = msg % args
LoggedException.__init__(self, msg)
self.msg = msg
def __str__(self):
"""Return string representation of this EasyBuildError instance."""
return repr(self.msg)
def raise_easybuilderror(msg, *args):
"""Raise EasyBuildError with given message, formatt... |
mr-ping/tornado | tornado/httpclient.py | Python | apache-2.0 | 27,522 | 0.000145 | """Blocking and non-blocking HTTP client interfaces.
This module defines a common interface shared by two implementations,
``simple_httpclient`` and ``curl_httpclient``. Applications may either
instantiate their chosen implementation class directly or use the
`AsyncHTTPClient` class from this module, which selects an... | return response
class AsyncHTTPClient(Configurable):
"""An non-blocking HTTP client.
Example usage::
def handle_response(response):
| if response.error:
print("Error: %s" % response.error)
else:
print(response.body)
http_client = AsyncHTTPClient()
http_client.fetch("http://www.google.com/", handle_response)
The constructor for this class is magic in several respects: It
act... |
linkitspa/l10n-italy | l10n_it_withholding_tax_causali/__manifest__.py | Python | agpl-3.0 | 677 | 0 | # -*- coding: utf-8 -*-
# Copyright 2018 Lorenzo Battistini - Agile Business Group
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl).
{
"name": "Causali pagamento per ritenute d'acconto",
"version": "10.0.1.0.0",
"development_status": "Beta",
"category": "Hidden",
"website | ": "https://github.com/OCA/l10n-italy",
"author": "Agile Business Group, Odoo Community Association (OCA)",
"license": "LGPL-3",
"application": False,
"installable": True,
"depends": [
"l10n_it_wi | thholding_tax",
"l10n_it_causali_pagamento",
],
"data": [
"views/withholding_tax.xml",
],
'auto_install': True,
}
|
srvg/ansible | test/units/galaxy/test_collection.py | Python | gpl-3.0 | 38,071 | 0.002789 | # -*- coding: utf-8 -*-
# Copyright: (c) 2019, Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import json
import os
import pytest
import ... | "test",
"collection"
],
"description": "Test",
"license": [
"MIT"
],
"license_file": None,
"dependencies": {},
"repositor | y": "https://github.com/{0}/{1}".format(namespace, name),
"documentation": None,
"homepage": None,
"issues": None
},
"file_manifest_file": {
"name": "FILES.json",
"ftype": "file",
"chksum_type": "sha2... |
radio-ho0/dotfiles | _vim/plugin/TagHighlight/module/utilities.py | Python | gpl-2.0 | 5,265 | 0.003609 | #!/usr/bin/env python
# Tag Highlighter:
# Author: A. S. Budden <abudden _at_ gmail _dot_ com>
# Copyright: Copyright (C) 2009-2011 A. S. Budden
# Permission is hereby granted to use and distribute this code,
# with or without modifications, provided that this copyright
# notice is c... | it():
rangeTo = int | (fm.group('to'))
else:
rangeTo = ord(fm.group('to'))
validRange = range(rangeFrom, rangeTo+1)
for ch in [chr(i) for i in validRange]:
for i in range(validList.count(ch)):
validList.remove(ch)
elif len(valid) == 1:
... |
creasyw/IMTAphy | framework/library/PyConfig/openwns/probebus.py | Python | gpl-2.0 | 9,523 | 0.006826 | ###############################################################################
# This file is part of openWNS (open Wireless Network Simulator)
# _____________________________________________________________________________
#
# Copyright (C) 2004-2007
# Chair of Communication Networks (ComNets)
# Kopernikusstr. 16, D-... | for a certain time window given by start and end time"""
nameInFactory = "TimeWindowProbeBus"
def __init__(self, start, end):
ProbeBus.__init__(self)
self.start = start
self.end = end
class TimeSeriesProbeBus(ProbeBus):
""" The LogEval ProbeBus ... | ne
valuePrecision = None
name = None
description = None
contextKeys = None
def __init__(self, outputFilename, format, timePrecision, valuePrecision, name, desc, contextKeys):
ProbeBus.__init__(self)
self.outputFilename = outputFilename
self.fo... |
henry-ngo/VIP | vip_hci/stats/cube_stats.py | Python | mit | 9,662 | 0.009004 | #! /usr/bin/env python
"""
Module for stats of a fits-cube.
"""
from __future__ import division
__author__ = 'C. Gomez @ ULg'
__all__ = ['cube_stats_aperture',
'cube_stats_annulus']
import numpy as np
import scipy.stats
from matplotlib import pyplot as plt
from ..var import get_annulus, get_circle, get_... | subplot(3, 1, 2, | sharex=ax1)
ax2.plot(std_dev, '.-', label='std_dev', lw = 0.8, alpha=0.6,
marker='o', color='r')
ax2.legend(loc='best', fancybox=True).get_frame().set_alpha(0.5)
ax2.grid(True)
plt.setp(ax2.get_xticklabels(), visible=False)
ax3 = plt.su... |
attm2x/m2x-demo-heroku-python | stockreport.py | Python | mit | 1,141 | 0.000876 | #!/usr/bin/env python
from requests.exceptions import HTTPError
from datetime import datetime
import ystockquote
from m2x.client import M2XClient
def post_stock_price(symbol, apikey, devicename):
'''
Retrieve the stock price for the g | iven ticker symbol ("T" for | AT&T) and
post it in the correct M2X data stream.
'''
client = M2XClient(key=apikey)
# Find the correct device if it exists, if not create it.
try:
device = [d for d in client.devices(q=devicename) if d.name == devicename][0]
except IndexError:
device = client.create_device(nam... |
alvations/sacremoses | sacremoses/tokenize.py | Python | mit | 31,370 | 0.000893 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import re
from six import text_type
from sacremoses.corpus import Perluniprops
from sacremoses.corpus import NonbreakingPrefixes
from sacremoses.util import is_cjk
from sacremoses.indic import VIRAMAS, NUKTAS
perluniprops = Perluniprops()
nonbreaking_prefixes = Nonbrea... | ect):
"""
This is a Python port of the Moses Tokenizer from
https://github.com/moses-smt/mosesdecoder/blob/master/scripts | /tokenizer/tokenizer.perl
"""
# Perl Unicode Properties character sets.
IsN = text_type("".join(perluniprops.chars("IsN")))
IsAlnum = text_type(
"".join(perluniprops.chars("IsAlnum")) + "".join(VIRAMAS) + "".join(NUKTAS)
)
IsSc = text_type("".join(perluniprops.chars("IsSc")))
IsSo =... |
JNU-Include/CNN | lib/mnist_classifier_del.py | Python | mit | 2,492 | 0.005659 | import matplotlib.pyplot as plt
import tensorflow as tf
from softmax_del import Softmax
from lib import mytool
'''
gildong = MnistClassifier()
gildong.learn(3, 100) # epoch, partial_size
gildong | .evaluate() # for all test data
gildong.classify_random_image() # classify a rando | mly selected image
#gildong.show_errors()
'''
class MnistClassifier (Softmax):
db = None
learning_epoch = None #15
size_of_segment = None #100
def load_mnist(self):
return mytool.load_mnist()
def learn(self, epoch, partial):
self.learning_epoch = epoch
self.size_of_segment... |
Aidturith/python-training | utils/random_pass/random_password.py | Python | mit | 4,858 | 0.005569 | # -*- coding: utf-8 -*-
# tools, 5 juin 2017
import string
import math
import random
import argparse
from argparse import RawTextHelpFormatter
CONSO_MAJ = u"C"
CONSO_MIN = u"c"
VOWEL_MAJ = u"V"
VOWEL_MIN = u"v"
LETTER_MAJ = u"L"
LETTER_MIN = u"l"
NUMBER = u"n"
PONCTION = u"P"
PONCTION_SMA = u"p"
VALID_CHARSET = {
... | def get_passwords(self, pattern, iterations):
passwords = []
for n in range(0, iterations):
passwords.append(self._get_password(pattern))
return passwords
def get_entropy(self, pattern):
try:
self._pattern_validation(pattern)
except LookupError:
... | rset_len, pattern_len), 2)
return round(entropy)
def write_list(self, filepath, liste):
with open(filepath, u'w') as f:
for entry in list: f.write(entry)
parser = argparse.ArgumentParser(description=u"Génération de mots de passe aléatoires.",
forma... |
kubeflow/kfp-tekton-backend | sdk/python/kfp/components_tests/test_structure_model_base.py | Python | apache-2.0 | 9,140 | 0.003392 | # Copyright 2018 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 agreed to in writing, ... | pe_check_for_union_dict_class(self):
val5 = TestModel1(prop_0='value 0')
self.assertEqual(TestModel1(prop_0='', prop_5=val5).prop_5, val5)
self.assertEqual(TestModel1(prop_0='', prop_5=[val5]).prop_5[0], val5)
self.assertEqual(TestModel1(prop_0='', prop_5=None).prop_5, None)
wit... | ises(TypeError):
TestModel1(prop_0='', prop_5='value 5')
with self.assertRaises(TypeError):
TestModel1(prop_0='', prop_5={'key 5': 'value 5'})
with self.assertRaises(TypeError):
TestModel1(prop_0='', prop_5={42: val5})
with self.assertRaises(TypeError):
... |
zknyoyo/chartkick.py | examples/demo/charts/urls.py | Python | mit | 128 | 0.007813 | from django.conf.ur | ls import patterns, url
urlpatterns = patterns('',
url(r' | ^$', 'charts.views.charts', name='charts'),
)
|
lucyzee/plivo_apps | outbound_call.py | Python | mit | 871 | 0.014925 | import plivo, plivoxml
auth_id = "MAODU4MTK1MDC0NTBMMM"
auth_token = "MWVkNWNlZWFlYjRmYmViNDBiZD | AwNjA0NjA5OTQz"
p = plivo.RestAPI(auth_id, auth_token)
params = {
'to': '14153163136', # The phone numer to which the all has to be placed
'from' : '1111111111', # The phone number to be used as the caller id
'answer_url' : "http://morning-ocean-4669.herokuapp.com/speak/", # The URL invoked by Plivo when ... | he method used to call the answer_url
# Example for Asynchrnous request
#'callback_url' : "http://morning-ocean-4669.herokuapp.com/callback/", # The URL notified by the API response is available and to which the response is sent.
#'callback_method' : "GET" # The method used to notify the callback_url.
}
# ... |
huaijiefeng/contact-sync-server | contactsync/urls.py | Python | apache-2.0 | 759 | 0.003953 | from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'ssssss.views.home', name='home'),
# ... | # Uncomment the admin/doc line below to enable admin | documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
url(r'^$', 'contactsync.views.home', name='home'),
)
|
matus-chochlik/various | relfs/relfs/fuse/mount_root.py | Python | mit | 2,188 | 0.003199 | # coding=utf-8
#------------------------------------------------------------------------------#
import os
import time
import fuse
import errno
from .item import RelFuseItem
from .static_dir import StaticDirectory
#------------------------------------------------------------------------------#
class MountRoot(RelFuseIte... | ath[1:])
except KeyError:
pass
# --------------------------------------------------------------------------
def readdir(self, fh):
yield ".."
yield "."
yield ".relfs"
for name in self._repos:
yield name
# -- | ------------------------------------------------------------------------
def _modify_time(self):
return self._mount_time
# --------------------------------------------------------------------------
def access(self, mode):
if mode & os.X_OK:
return 0
return RelFuseItem.ac... |
FSource/Faeris | tool/binpy/libpy/files/Dir.py | Python | mit | 703 | 0.069701 | import os
def Dir_toStdName(path):
if not (path[-1]=="/" or path[-1] == "//"):
path=path+"/"
return path
def Dir_getFiles(path):
path=Dir_toStdName(path)
allfiles=[]
files=os.listdir(path)
for f in files:
abs_path = path + | f
if os.path.isdir(abs_path):
sub_files=Dir_getFiles(abs_path)
sub_files=[ f+'/'+i for i in sub_files ]
allfiles.extend(sub_files)
else:
allfiles.append(f)
return allfiles
class Dir:
def __init__(self,dir_name):
self.m_dir=Dir_toStdName(dir_name)
def listDir(self):
return os.listdir(... | d=Dir("../../")
print d.listFiles()
|
MOOCworkbench/MOOCworkbench | marketplace/migrations/0012_auto_20170604_1335.py | Python | mit | 925 | 0.002162 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2017 | -06-04 13:35
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('marketplace', '0011_auto_20170526_1215'),
]
operations = [
migrations.AlterField(
model_name='externalpackage',
... | model_name='packageresource',
name='resource',
field=models.TextField(help_text='Markdown allowed'),
),
migrations.AlterField(
model_name='packageresource',
name='url',
field=models.URLField(blank=True, help_text='URL to resource (op... |
Tecnativa/website | website_breadcrumb/models/website.py | Python | agpl-3.0 | 1,026 | 0 | # -*- coding: utf | -8 -*-
# © 20 | 15 Grupo ESOC Ingeniería de Servicios, S.L.U. - Jairo Llopis
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
from openerp import api, models
class WebsiteMenu(models.Model):
_inherit = "website.menu"
@api.multi
def get_parents(self, revert=False, include_self=False):
"""Lis... |
vgrem/Office365-REST-Python-Client | examples/directory/delete_groups_batch.py | Python | mit | 289 | 0.00346 | from examples import acqu | ire_token_by_username_password
from office365.graph_client import GraphClient
client = GraphClient(acquire_token_by_username_password)
groups = client.groups.get().top(1).execute_query()
for cur_grp in groups:
| cur_grp.delete_object()
client.execute_batch()
|
johanvdw/Fiona | tests/test_drivers.py | Python | bsd-3-clause | 760 | 0.001316 |
import logging
import os.path
import shutil
import sys
import tempfile
import fiona
def test_options(tmpdir=None):
"""Test that setting CPL_DEBUG=ON works"""
if tmpdir is None:
tempdir = tempfile.mkdtemp()
logfil | e = os.path.join(tempdir, 'example.log')
else:
logfile = str(tmpdir.join('example.log'))
logger = logging.getLogger('Fiona')
logger.setLevel(logging.DEBUG)
fh = logging.FileHandler(logfile)
fh.setLevel(logging.DEBUG)
logger.addHandler(fh)
with fiona.drivers(CPL_DEBUG=True):
... | open(logfile).read()
assert "Option CPL_DEBUG" in log
if tempdir and tmpdir is None:
shutil.rmtree(tempdir)
|
sauloal/cnidaria | scripts/venv/lib/python2.7/site-packages/ete2/__init__.py | Python | mit | 2,644 | 0.008699 | # #START_LICENSE###########################################################
#
#
# This file is part of the Environment for Tree Exploration program
# (ETE). http://etetoolkit.org
#
# ETE is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# t... | ml import Phyloxml, PhyloxmlTree
from nexml import Nexml, NexmlTree
from evol import EvolTree
from coretype.arraytable import *
from clustering.clustertree import *
try:
from phylomedb.phylomeDB3 import *
except ImportError, e:
pass
#warn("MySQLdb module could not be loaded")
#warn(e)
try:
from tr... | view.svg_colors import *
from treeview.main import *
from treeview.faces import *
from treeview import faces
from treeview import layouts
except ImportError, e:
#print e
pass
#warn("Treeview module could not be loaded")
#warn(e)
try:
from version import __version__, __installid_... |
mrustl/flopy | autotest/t004_test.py | Python | bsd-3-clause | 19,118 | 0.004551 | import os
import shutil
import numpy as np
import flopy
from flopy.utils.util_array import Util2d, Util3d, Transient2d
out_dir = "temp"
if os.path.exists(out_dir):
shutil.rmtree(out_dir)
os.mkdir(out_dir)
def test_transient2d():
ml = flopy.modflow.Modflow()
dis = flopy.modflow.ModflowDis(ml, nlay=10, nro... | is(ml,2,10,10)
lpf = flopy.modflow.ModflowLpf(ml,hk=[fname_ascii,fname_bin])
ml.lpf.hk[1].fmtin = "(BINARY)"
assert np.array_equal(lpf.hk[0].array,a1)
assert np.array_equal(lpf.hk[1].array,a1)
# bin read write test
fname = os.path.join(out_dir, 'test.bin')
u2d.write_bin((10, 10), fname, u2d... | ray)
a3 = u2d.load_bin((10, 10), fname, u2d.dtype)[1]
assert np.array_equal(a3, a1)
# ascii read write test
fname = os.path.join(out_dir, 'text.dat')
u2d.write_txt((10, 10), fname, u2d.array)
a4 = u2d.load_txt((10, 10), fname, u2d.dtype, "(FREE)")
assert np.array_equal(a1, a4)
# fixed f... |
pledra/odoo-product-configurator | product_configurator_sale_mrp/models/sale.py | Python | agpl-3.0 | 193 | 0 | from odoo import fields, models
class SaleOrderLine(models.Model):
_inherit = 'sale.order.line'
bom_id | = fields.Many2one(
comodel_name='mrp.bom',
readonly=True
| )
|
eXcomm/gratipay.com | gratipay/elsewhere/google.py | Python | cc0-1.0 | 1,648 | 0.001214 | from __future__ import absolute_import, division, print_function, unicode_literals
from gratipay.elsewhere import PlatformOAuth2
from gratipay.elsewhere._extractors import any_key, key
from gratipay.elsewhere._paginators import query_param_paginator
class Google(PlatformOAuth2):
# Platform att | ributes
name = 'googl | e'
display_name = 'Google'
account_url = 'https://plus.google.com/{user_id}'
optional_user_name = True
# Auth attributes
auth_url = 'https://accounts.google.com/o/oauth2/auth'
access_token_url = 'https://accounts.google.com/o/oauth2/token'
oauth_default_scope = ['https://www.googleapis.com/... |
aymeric-spiga/planetoplot | html/cgi-bin/maincgi.py | Python | gpl-2.0 | 1,620 | 0.025926 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
import cgi, cgitb
import sys
sys.path.insert(0, "../planetoplot/modules")
import ppplot
import ppclass
########################################
import numpy as np
xx = np.arange(25)
yy = 3.*xx
fig = ppplot.figuref(x=8,y=6)
pl = ppplot.plot1d()
pl.fig = fig # have ... | ()
######################################## more sophisticated example
## RETRIEVE DATA
#from | ppclass import pp
#fifi = "/home/aspiga/soft/mcd_python/minimal_server/cgi-bin/wrfout_d01_2024-10-04_06z00z00_zabg"
#ff,xx,yy,zz,tt = pp(file=fifi,var="HGT",z=0,t=0).getfd()
#xx = pp(file=fifi,var="XLONG",z=0,t=0).getf()
#yy = pp(file=fifi,var="XLAT",z=0,t=0).getf()
#uu = pp(file=fifi,var="Um",z=0,t=0).getf()
#vv = pp... |
mitsuhiko/sentry | tests/acceptance/test_auth.py | Python | bsd-3-clause | 1,321 | 0.000757 | from __future__ import absolute_import
from sentry.testutils import AcceptanceTestCase
class AuthTest(AcceptanceTestCase):
def enter_auth(self, username, password):
# disable captcha as it makes these tests flakey (and requires waiting
# on external resources)
with self.settings(RECAPTCHA... | (name='l | ogin')
def test_no_credentials(self):
self.enter_auth('', '')
self.browser.snapshot(name='login fields required')
def test_invalid_credentials(self):
self.enter_auth('bad-username', 'bad-username')
self.browser.snapshot(name='login fields invalid')
def test_success(self):
... |
ardi69/pyload-0.4.10 | pyload/plugin/hoster/BayfilesCom.py | Python | gpl-3.0 | 468 | 0.014957 | # -*- coding: utf-8 -*-
from pyload.plugin.internal.DeadHoster import DeadHoster
| class BayfilesCom(DeadHoster):
__name = "BayfilesCom"
__type = "hoster"
__version = "0.09"
__pattern = r'https?://(?:www\.)?bayfiles\.(com|net)/file/(?P<ID>\w+/\w | +/[^/]+)'
__config = [] #@TODO: Remove in 0.4.10
__description = """Bayfiles.com hoster plugin"""
__license = "GPLv3"
__authors = [("Walter Purcaro", "vuolter@gmail.com")]
|
fotinakis/sentry | src/sentry/utils/auth.py | Python | bsd-3-clause | 6,403 | 0.000156 | """
sentry.utils.auth
~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
import six
import logging
from django.conf import settings
from django.contrib.auth import login as _ | login
from django.contrib.auth.backends import ModelBackend
from django.core.urlresolvers import reverse, resolve
from time import time
from sentry.models import User, Authenticator
logger = logging.getLogger('sen | try.auth')
_LOGIN_URL = None
class AuthUserPasswordExpired(Exception):
def __init__(self, user):
self.user = user
def _make_key_value(val):
return val.strip().split('=', 1)
def parse_auth_header(header):
try:
return dict(map(_make_key_value, header.split(' ', 1)[1].split(',')))
e... |
mobo95/pyload | module/plugins/hooks/AndroidPhoneNotify.py | Python | gpl-3.0 | 2,646 | 0.016251 | # -*- coding: utf-8 -*-
from time import time
from module.network.RequestFactory import getURL
from module.plugins.Hook import Hook
class AndroidPhoneNotify(Hook):
__name__ = "AndroidPhoneNotify"
__type__ = "hook"
__version__ = "0.04"
__config__ = [("apikey" , "str" , "API key" ... | _("Captcha"), _("New | request waiting user input"))
def packageFinished(self, pypack):
if self.getConfig("notifypackage"):
self.notify(_("Package finished"), pypack.name)
def allDownloadsProcessed(self):
if not self.getConfig("notifyprocessed"):
return False
if any(True for pdata ... |
musicpax/funcy | funcy/py2.py | Python | bsd-3-clause | 765 | 0.003922 | import sys
from .calc import *
from .colls imp | ort | *
from .tree import *
from .decorators import *
from .funcolls import *
from .funcs import *
from .seqs import *
from .types import *
from .strings import *
from .flow import *
from .objects import *
from .namespaces import namespace
from .debug import *
from .primitives import *
# Setup __all__
modules = ('calc', '... |
mekolat/manachat | plugins/manaboy.py | Python | gpl-2.0 | 11,836 | 0.004562 | import time
import net.mapserv as mapserv
import net.charserv as charserv
import commands
import walkto
import logicmanager
import status
import plugins
from collections import deque
from net.inventory import get_item_index, get_storage_index
from utils import extends
from actor import find_nearest_being
from chat impo... | rget_s = match.group(1)
try:
target = mapserv.beings_cache[int(target_s)]
except (ValueError, KeyError):
target = find_nearest_being(name=target_s,
| ignored_ids=walkto.unreachable_ids)
if target is not None:
set_npc_owner(nick)
plugins.autofollow.follow = ''
walkto.walkto_and_action(target, 'attack')
def cmd_say(nick, message, is_whisper, match):
if not is_whisper:
return
msg = match.group(1)
whisper(ni... |
zachjanicki/osf.io | website/addons/figshare/model.py | Python | apache-2.0 | 13,145 | 0.000685 | # -*- coding: utf-8 -*-
import markupsafe
from modularodm import fields
from framework.auth.decorators import Auth
from website.models import NodeLog
from website.addons.base import exceptions
from website.addons.base import AddonNodeSettingsBase, AddonUserSettingsBase
from website.addons.base import StorageAddonBas... | f.user_settings is None:
return figshare_settings.API_URL
else:
return figshare_settings.API_OAUTH_URL
@property
def has_auth(self):
return bool(self.user_settings and self.user_settings.has_auth)
@property
def complete(self):
return self.has_auth and se... | ent(self):
return {
'id': self.figshare_id,
'type': self.figshare_type,
'name': self.figshare_title,
}
def authorize(self, user_settings, save=False):
self.user_settings = user_settings
node = self.owner
node.add_log(
action='f... |
nottombrown/rl-teacher | agents/pposgd-mpi/pposgd_mpi/cnn_policy.py | Python | mit | 2,355 | 0.005945 | from pposgd_mpi.common.mpi_running_mean_std import RunningMeanStd
import pposgd_mpi.common.tf_util as U
import tensorflow as tf
import gym
from pposgd_mpi.common.distributions import make_pdtype
class CnnPolicy(object):
recurrent = False
def __init__(self, name, ob_space, ac_space, kind='large'):
with ... | .relu(U.c | onv2d(x, 32, "l2", [4, 4], [2, 2], pad="VALID"))
x = U.flattenallbut0(x)
x = tf.nn.relu(U.dense(x, 256, 'lin', U.normc_initializer(1.0)))
elif kind == 'large': # Nature DQN
x = tf.nn.relu(U.conv2d(x, 32, "l1", [8, 8], [4, 4], pad="VALID"))
x = tf.nn.relu(U.conv2d(... |
jcftang/ansible | lib/ansible/modules/database/misc/kibana_plugin.py | Python | gpl-3.0 | 7,030 | 0.003414 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Ansible module to manage elasticsearch shield role
(c) 2016, Thierno IB. BARRY @barryib
Sponsored by Polyconseil http://polyconseil.fr.
This file is part of Ansible
Ansible is free software: you can redistribute it and/or modify
it under the terms of the GNU General Publ... | nt", "absent"]
default: present
url:
description:
- Set exact URL to download the plugin from.
For local file, prefix its absolute path with file://
required: False
default: None
timeout:
des | cription:
- "Timeout setting: 30s, 1m, 1h..."
required: False
default: 1m
plugin_bin:
description:
- Location of the plugin binary
required: False
default: /opt/kibana/bin/kibana
plugin_dir:
description:
- Your configured plugin... |
ClearCorp/server-tools | external_file_location/tests/test_ftp.py | Python | agpl-3.0 | 3,525 | 0 | # coding: utf-8
# @ 2015 Valentin CHEMIERE @ Akretion
# ©2016 @author Mourad EL HADJ MIMOUNE <mourad.elhadj.mimoune@akretion.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
import logging
from base64 import b64decode
import hashlib
from .common import TestConnection, ContextualStringIO
from .m... | file.seek(0)
task = self.env.ref('external_file_location.ftp_import_task')
task.md5_check = True
with server_mock_ftp(
{'open': MultiResponse({
1: md5_file,
0: self.test_file_ftp}),
'l | istdir': [task.filename]}):
with self.assertRaises(UserError):
task.run_import()
|
antipoachingmap/django-app | antipoaching/models.py | Python | mit | 909 | 0.018702 | from __future__ import unicode_literals
from django.db import models
from jsonfield import JSONField
SEVERITY_CHOICES = [('c', "critical"), ('w', "warning"), ('i', "info")]
| class Event(models.Model):
description = models.TextField(max_length=500, default='')
severity = models.CharField(('severity'), choices=SEVERITY_CHOICES, default='i', max_length=1)
timestamp = models.IntegerField()
lat = models.FloatField(default=0)
long = models.FloatField(default=0)
ext | ra = JSONField(null=True, default="")
class Media(models.Model):
description = models.TextField()
format = models.CharField(blank=False, max_length=3)
timestamp = models.IntegerField()
filename = models.CharField(max_length=255)
filesize = models.BigIntegerField()
event = models.ForeignKey(
Event, null=T... |
oVirt/vdsm | lib/vdsm/metrics/hawkular.py | Python | gpl-2.0 | 2,524 | 0 | #
# Copyright 2016-2017 Red Hat, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foun | dation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that | it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free S... |
agoragames/py-eventsocket | eventsocket.py | Python | bsd-3-clause | 20,384 | 0.01771 | """
A socket wrapper that uses Event IO.
"""
import socket
import event
import time
import logging
import errno
import traceback
import os
from collections import deque
# TODO: Use new io objects from 2.6
# 26 July 10 - I looked into this and a potential problem with io.StringIO is
# that it assumes all text is unico... | e to change the various callbacks.
read_cb = property( fset=_set_read_cb )
accept_cb = property( fset=lambda self,func: setattr(self, '_parent_accept_cb', func ) )
close_cb = property( fset=lambda self,func: setattr(self, '_parent_close_cb', func ) )
error_cb = property( | fset=lambda self,func: setattr(self, '_parent_error_cb', func ) )
output_empty_cb = property( fset=lambda self,func: setattr(self, '_parent_output_empty_cb',func) )
def bind(self, *args):
"""
Bind the socket.
"""
if self._debug:
self._logger.debug( "binding to %s", str(args) )
self._soc... |
luzfcb/cookiecutter | cookiecutter/zipfile.py | Python | bsd-3-clause | 4,640 | 0 | """Utility functions for handling and fetching repo archives in zip format."""
from __future__ import absolute_import
import os
import tempfile
from zipfile import ZipFile
import requests
try:
# BadZipfile was renamed to BadZipFile in Python 3.2.
from zipfile import BadZipFile
except ImportError:
from z... | nvalidZipRepository
from cookiecutter.prompt import read_repo_password
from cookiecutter.utils import make_sure_path_exists, prompt_and_delete
def unzip(zip_uri, is_url, clone_to_dir='.', no_input=False, password=None):
"""Download and unpack a zipfile at a given URI.
Th | is will download the zipfile to the cookiecutter repository,
and unpack into a temporary directory.
:param zip_uri: The URI for the zipfile.
:param is_url: Is the zip URI a URL or a file?
:param clone_to_dir: The cookiecutter repository directory
to put the archive into.
:param no_input: Su... |
unioslo/cerebrum | Cerebrum/modules/dns/__init__.py | Python | gpl-2.0 | 561 | 0.003565 | # -*- coding: utf-8 -*-
import cereconf
__version__ = "1.5"
IP_NUMBER = 'IPNumber'
IPv6_NUMBER = 'IPv6Number'
DNS_OWNER='DnsOwner'
REV_IP_NUMBER = 'IPNumber_rev'
A_RECORD = 'ARecord'
AAAA_RECORD = 'AAAARecord'
HOST_INFO = 'HostInfo'
MX_SET = 'MXSet'
SRV_TARGET = "SRV_target"
SRV_OWNER = "SRV_owner"
GENERAL_DNS_REC | ORD = "GeneralDnsRecord"
CNAME_OWNER = "Cname_owner"
CNAME_TARGET = "Cname_target"
# TODO: This value should not be hardcoded here. Didn't put it in
# cereco | nf as the zone support for dns_owner should be here "real soon
# now"
ZONE='uio.no'
|
k-rister/pbench | server/bin/pbench-base.py | Python | gpl-3.0 | 2,404 | 0.00624 | #!/usr/bin/env python3
# -*- mode: python -*-
import os, sys
if __name__ != '__main__':
sys.exit(1)
from argparse import ArgumentParser
_NAME_ = "pbench-base.py"
parser = ArgumentParser(_NAME_)
parser.add_argument(
"-C", "--config", dest="cfg_name",
help="Specify config file")
parser.set_defaults(cfg_na... | h for those definitions in the PbenchConfig class, but
# still accessible to all pbench bash shell scripts.
from pbench import PbenchConfig, BadConfig
try:
config = PbenchConfig(config_name)
except BadConfig as e:
print("{}: {}".format(_prog, e), file=sys.stderr)
sys.exit(1)
# Exclude the "fi | les" and "conf" attributes from being exported
vars = sorted([ key for key in config.__dict__.keys() \
if key not in ('files', 'conf', 'timestamp', '_unittests', 'get') ])
for att in vars:
try:
os.environ[att] = getattr(config, att)
except AttributeError:
print("{}: Missing internal pben... |
fboers/jumegX | tsvgl/old/jumeg_tsv_wx02.py | Python | bsd-3-clause | 11,636 | 0.019337 | import sys
import numpy as np
#from OpenGL.GL import *
#from OpenGL.GLU import *
try:
import wx
from wx import glcanvas
from wx.glcanvas import GLCanvas
except ImportError:
raise ImportError, "Required dependency wx.glcanvas not present"
try:
from OpenGL.GL import *
from OpenGL.GLU import glu... | nvas.WX_GL_DEPTH_SIZE, 24) # 24 bit
GLCanvas.__init__(self, parent, -1, attribList=attribList)
wx.EVT_PAINT(self, self.OnPaint)
wx.EVT_SIZE(self, self.OnSize)
#wx.EVT_MOTION(self, self.OnMouseMotion)
wx.EVT_LEFT_DOWN(self, self.OnMouseLeftDown)
wx.EVT_LEFT_UP(self, se... | .n_channels=10
self.n_timepoints= 10000
self.SetFocus()
self.GLinitialized = False
self.init = False
self.rotation_y = 0.0
self.rotation_x = 0.0
self.prev_y = 0
self.prev_x = 0
self.mouse_down = False
self.is_on_draw =False
sel... |
openprocurement/openprocurement.auction | openprocurement/auction/design.py | Python | apache-2.0 | 2,643 | 0.001135 | # -*- coding: utf-8 -*-
from couchdb.design import ViewDefinition
from couchdb.http import HTTPError
from time import sleep
from random import randint
import os
def add_index_options(doc):
doc['options'] = {'local_seq': True}
start_date_chronograph = ViewDefinition(
'chronograph',
'start_date',
open... | may change docs.'});
}
}
'''
start_date_filter = '''function(doc, req) {
| var now = new Date();
var start = new Date(((doc.stages||[])[0]||{}).start || '2000');
if (start > now){
return true;
}
return false;
}
'''
if 'validate_doc_update' not in design or \
validate_doc_update != design['v... |
ubic135/odoo-design | addons/website/models/website.py | Python | agpl-3.0 | 36,133 | 0.003709 | # -*- coding: utf-8 -*-
import cStringIO
import contextlib
import datetime
import hashlib
import inspect
import logging
import math
import mimetypes
import unicodedata
import os
import re
import time
import urlparse
from PIL import Image
from sys import maxint
import werkzeug
# optional python-slugify import (https:/... | ar('Website Domain'),
'company_id': fields.many2one('res | .company', string="Company"),
'language_ids': fields.many2many('res.lang', 'website_lang_rel', 'website_id', 'lang_id', 'Languages'),
'default_lang_id': fields.many2one('res.lang', string="Default language"),
'default_lang_code': fields.related('default_lang_id', 'code', type="char", string="Def... |
mikeckennedy/python-jumpstart-course-demos | apps/10_movie_search/final/movie_svc.py | Python | mit | 715 | 0 | import collections
import requests
MovieResult = collections.namedtuple(
'MovieResult',
"imdb_code,title,duration,director,year,rating,imdb_score,keywords,genres")
def find_movies(search_text):
if not search_text or not search_text.strip():
raise ValueError("Search text is required")
| # This URL changed since the recording to support SSL.
url = 'http://movieservice.talkpython.fm/api/search/{}'.format(search_text)
resp = requests.get(url)
resp.raise_for_status()
movie_data = resp.json()
movi | es_list = movie_data.get('hits')
movies = [
MovieResult(**md)
for md in movies_list
]
movies.sort(key=lambda m: -m.year)
return movies
|
AguNnamdi/flask_microblog | app/auth/views.py | Python | mit | 5,982 | 0.003176 | from flask import render_template, redirect, request, url_for, flash
from flask.ext.login import login_user, current_user, logout_user, login_required
from . import auth
from ..models import User, AnonymousUser
from .forms import LoginForm, RegistrationForm, ChangePasswordForm, \
PasswordResetRequestForm, PasswordR... | new confirmation email has been sent to you by email.')
return redirect(url_for('main.index'))
@auth.route('/change_password', methods=['GET', 'POST'])
@login_r | equired
def change_password():
form = ChangePasswordForm()
if form.validate_on_submit():
if current_user.verify_password(form.old_password.data):
current_user.password = form.password.data
db.session.add(current_user)
flash('Your password has been updated.')
... |
bilbeyt/ITURO-Giant_Flat | flat/server.py | Python | mit | 254 | 0 | #!/u | sr/bin/env python
import os
import sys
from swampdragon.swampdragon_server import run_server
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "flat.settings")
host_port = sys.argv[1] if len(sys.argv) > 1 else None
run_server(host_port=host_port) | |
jmaas/cobbler | cobbler/modules/installation/post_puppet.py | Python | gpl-2.0 | 1,712 | 0.002336 | """
This module signs newly installed client puppet certificates if the
puppet master server is running on the same machine as the cobbler
server.
Based on:
http://www.ithiriel.com/content/2010/03/29/writing-install-triggers-cobbler
"""
from builtins import str
import re
import cobbler.utils as utils
def register():... | m["hostname"]
if not re.match(r'[\w-]+\..+', hostname):
search_domains = system['name_servers_search']
if search_domains:
hostname += '.' + searc | h_domains[0]
puppetca_path = settings.puppetca_path
cmd = [puppetca_path, 'cert', 'sign', hostname]
rc = 0
try:
rc = utils.subprocess_call(logger, cmd, shell=False)
except:
if logger is not None:
logger.warning("failed to execute %s" % puppetca_path)
if rc != 0:
... |
tapomayukh/projects_in_python | sandbox_tapo/src/skin_related/BMED_8813_HAP/Features/single_feature/results/cross_validate_categories_BMED_8813_HAP_scaled_method_II_force.py | Python | mit | 4,029 | 0.018119 |
# Principal Component Analysis Code :
from numpy import mean,cov,double,cumsum,dot,linalg,array,rank,size,flipud
from pylab import *
import numpy as np
import matplotlib.pyplot as pp
#from enthought.mayavi import mlab
import scipy.ndimage as ni
import roslib; roslib.load_manifest('sandbox_tapo_darpa_m3')
import ro... | projection matrix, the variance and the mean
return vec,val,mean_X, M, Mcov
if __name__ == '__main__':
Fmat = Fmat_o | riginal[82:123,:]
# Checking the Data-Matrix
m_tot, n_tot = np.shape(Fmat)
print 'Total_Matrix_Shape:',m_tot,n_tot
eigvec_total, eigval_total, mean_data_total, B, C = pca(Fmat)
#print eigvec_total
#print eigval_total
#print mean_data_total
m_eigval_total, n_eigval_total ... |
Bovid/Bovid.python | template.py | Python | mit | 7,644 | 0.039508 | import collections
import re
#imports
class Jison:#extends
symbols = {}
terminals = {}
productions = {}
table = {}
default_actions = {}
version = '0.3.12'
debug = False
action_none = 0
action_shift = 1
action_deduce = 2
action_accept = 3
unput_stack = []
def trace(self):
"""trace"""
def __init__(s... | len = len(next)
if next_len < 20:
next += self.input.to_string()[:20 - next_len]
else:
if next_ | len > 20:
next = next[:-20] + '...'
return next.replace('\n', '')
def show_position(self):
pre = self.past_input()
c = '-' * len(pre)
return pre + self.upcoming_input() + '\n' + c + '^'
def next(self):
if len(self.unput_stack) > 0:
this.yy = yy
if self.done:
return self.eof
if self.inp... |
mducoffe/fuel | docs/conf.py | Python | mit | 9,405 | 0.005853 | # -*- coding: utf-8 -*-
#
# Fuel documentation build configuration file, created by
# sphinx-quickstart2 on Wed Oct 8 17:59:44 2014.
#
# 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... | how_urls = False
# Documents to append as an ap | pendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual sectio |
chengluyu/SDU-Computer-Networks | assignment-2/multiprocesser.py | Python | mit | 185 | 0 | from multiprocessing import Pool
class Process:
| def __init__(self, process | es=8):
self.p = Pool(processes)
def Exec(self, f, data):
return self.p.map(f, data)
|
adazey/Muzez | libs/requests/api.py | Python | gpl-3.0 | 6,115 | 0.005724 | # -*- coding: utf-8 -*-
"""
requests.api
~~~~~~~~~~~~
This module implements the Requests | API.
:copyright: (c) 2012 by Kenneth Reitz.
:license: Apache2, see LICENSE for more details.
"""
from . import sessions
def request(method, url, **kwargs):
"""Constructs and sends a :class:`Request <Request>`.
:param method: method for the new :class:`Request` object.
:param url: URL for ... | object.
:param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.
:param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
:param json: (optional) json data to send in the body of the :class:`Request`.
:... |
tomviner/pytest | src/_pytest/_code/code.py | Python | mit | 36,328 | 0.000853 | import inspect
import re
import sys
import traceback
from inspect import CO_VARARGS
from inspect import CO_VARKEYWORDS
from traceback import format_exception_only
from types import TracebackType
from typing import Generic
from typing import Optional
from typing import Pattern
from typing import Tuple
from typing import... | etfirstlinesource()
try:
astnode, _, end = getstatementrange_ast(
self.lineno, source, astnode=astnode
)
except SyntaxError:
end = self.lineno + 1
else:
if key is not None:
astcache[key] = astnode
return sour... | a var __tracebackhide__
resolving to True.
If __tracebackhide__ is a callable, it gets called with the
ExceptionInfo instance and can decide whether to hide the traceback.
mostly for internal use
"""
f = self.frame
tbh = f.f_locals.get(
... |
ryanolson/CloudApp | cloudapp/identity.py | Python | gpl-3.0 | 3,128 | 0.012148 | # -*- coding: utf-8 -*-
"""
Copyright 2013 Ryan Olson
This file is part of CloudApp.
CloudApp is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later versio... | ):
if current_app.cache is None: return
cached_identity = copy(identity)
cached_identity.user = to_dict(identity.user)
current_app.cache.set(identity.name, cached_identity, timeout=600)
def on_load_identity(sender, identity):
"""
This function is called to load the user's identity from either... | This function should never be triggered unless we have passed
a valid identity; however, we should do a quick double check here
before loading the identity's allowed permissions / needs.
In the future, we may want to avoid the user lookup and utilize
memcache for the storage of the user's base i... |
uthaipon/SkillsWorkshop2017 | Week01/Problem02/chaoyichang_02.py | Python | bsd-3-clause | 76 | 0.197368 | i,j=1,2
sum=0
while j <4000000:
i,j=j,i+j
if i%2==0:
sum=sum+i
pri | nt sum | |
mbauskar/erpnext | erpnext/selling/doctype/sales_order/sales_order.py | Python | gpl-3.0 | 26,900 | 0.027918 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
import json
import frappe.utils
from frappe.utils import cstr, flt, getdate, comma_and, cint
from frappe import _
from frappe.model.utils ... | def update_enquiry_status(self, prevdoc, flag):
enq = frappe.db.sql("select t2.prevdoc_docname from `tabQuotation` t1, `tabQuotation Item` t2 where t2.parent = t1.name and t1.name=%s", prevdoc)
if enq:
frappe.db.sql("update `tabOpportunity` set status = %s where name=%s",(flag,enq[0][0]))
def update_prevdoc_s... | f, flag):
for quotation in list(set([d.prevdoc_docname for d in self.get("items")])):
if quotation:
doc = frappe.get_doc("Quotation", quotation)
if doc.docstatus==2:
frappe.throw(_("Quotation {0} is cancelled").format(quotation))
doc.set_status(update=True)
doc.update_opportunity()
def vali... |
bparzella/secsgem | secsgem/hsms/linktest_rsp_header.py | Python | lgpl-2.1 | 1,587 | 0.00063 | #####################################################################
# linktest_rsp_header.py
#
# (c) Copyright 2021, Benjamin Parzella. All rights reserved.
#
# This library 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... | r(HsmsHeader):
"""
Header for Linktest Response.
Header for message with SType 6.
"""
def __init__(self, system):
"""
Initialize a hsms linktest response.
:param system: message ID
:type system | : integer
**Example**::
>>> import secsgem.hsms
>>>
>>> secsgem.hsms.HsmsLinktestRspHeader(10)
HsmsLinktestRspHeader({sessionID:0xffff, stream:00, function:00, pType:0x00, sType:0x06, \
system:0x0000000a, requireResponse:False})
"""
HsmsHeader.__... |
knuu/competitive-programming | atcoder/corp/caddi2018_e.py | Python | mit | 1,094 | 0.002742 | def main() -> None:
N = int(input())
A = [int(x) for x in input().split()]
rev_A = A[:]
left = [-1] * N
left_cnt = [0] * N
A_left = [A[0]]
for i in range(1, N):
if rev_A[i-1] < rev_A[i]:
cnt = 0
while rev_A[i-1]
pass
elif rev_A[i-1] < rev_A... | while A[j-1] > A[j]:
A[j] *= 4
cnt += 2
print(i, cnt, A)
ans = min(ans, cnt)
print(ans)
if __name__ == '__main__':
main | ()
|
DakRomo/2017Challenges | challenge_1/python/alexmunoz905/main.py | Python | mit | 68 | 0 | # Ale | xMunoz905 | 1/1/17
answer = "Hello 2017! | "[::-1]
print(answer)
|
GbalsaC/bitnamiP | venv/lib/python2.7/site-packages/radon/raw.py | Python | agpl-3.0 | 6,458 | 0 | '''This module contains functions related to raw metrics.
The main function is :func:`~radon.raw.analyze`, and should be the only one
that is used.
'''
import tokenize
import operator
import collections
try:
import StringIO as io
except ImportError: # pragma: no cover
import io
__all__ = ['OP', 'COMMENT', ... | okens, [COMMENT]))
try:
# Verify whether a colon is present among the tokens and that
# it is the last token.
token_pos = _find(processed, OP, ':')
return 2 - (token_pos == len(processed) - 2)
except ValueError:
# The colon is not present
... | s not count as a logical line.
# Otherwise it count as 1.
if not list(_less_tokens(processed, [NL, EM])):
return 0
return 1
return sum(aux(sub) for sub in _split_tokens(tokens, OP, ';'))
def analyze(source):
'''Analyze the source code and return a namedtuple... |
justinmeister/PyTMX-Examples | Make Collideable Rects/main.py | Python | mit | 3,683 | 0.002987 | import sys, os
import pygame as pg
import tilerender
"""Initialize pygame, create a clock, create the window
with a surface to blit the map onto."""
pg.init()
fps_clock = pg.time.Clock()
main_surface = pg.display.set_mode((420, 420))
main_rect = main_surface.get_rect()
"""Load the tmx file from the current directory... | width,
height. Double click objects in Tiled to see these
properties. These properties are used to make rect
objects in Pygame."""
blockers = []
tilewidth = tile_renderer.tmx_data.tilewidth
for tile_object in tile_renderer.tmx_data.getObjects():
properties = tile_object.__dict__
if properties['name'] == 'blo... | ties['y']
width = properties['width']
height = properties['height']
new_rect = pg.Rect(x, y, width, height)
blockers.append(new_rect)
"""
The Player class will be a player-controlled sprite
that will collide with the blockers we just created.
We pass in the blockers as a constructor ar... |
mattseymour/django | tests/validation/models.py | Python | bsd-3-clause | 4,761 | 0.003781 | from datetime import datetime
from django.core.exceptions import ValidationError
from django.db import models
def validate_answer_to_universe(value):
if value != 42:
raise ValidationError('This is not the answer to life, universe and everything!', code='not | 42')
class ModelToValidate(models.Model):
name = models.CharField(max_length=100)
created = models.DateTimeField(default=datetime.now)
number = models.IntegerField(db_column='number_val')
parent = models.ForeignKey(
'self',
models.SET_NULL,
blank=True, null=True,
limit_... | ls.EmailField(blank=True)
ufm = models.ForeignKey(
'UniqueFieldsModel',
models.SET_NULL,
to_field='unique_charfield',
blank=True, null=True,
)
url = models.URLField(blank=True)
f_with_custom_validator = models.IntegerField(blank=True, null=True, validators=[validate_answe... |
projectchrono/chrono | src/demos/python/core/demo_CH_coords.py | Python | bsd-3-clause | 2,825 | 0.024425 | #------------------------------------------------------------------------------
# Name: pychrono example
# Purpose:
#
# Author: Alessandro Tasora
#
# Created: 1/01/2019
# Copyright: (c) ProjectChrono 2019
#------------------------------------------------------------------------------
print ("First tu... | from the list extracted from ChMatrixDynamic
w, v = LA.eig(npmat) # get eigenvalues and eigenvectors using numpy
mb = chrono.ChMatrixDyna | micD(4,4)
prod = v * npmat # you can perform linear algebra operations with numpy and then feed results into a ChMatrixDynamicD using SetMatr
mb.SetMatr(v.tolist()) # create a ChMatrixDynamicD from the numpy eigenvectors
mr = chrono.ChMatrix33D()
mr.SetMatr([[1,2,3], [4,5,6], [7,8,9]])
print (mr*my_vect1);
# T... |
sander76/home-assistant | homeassistant/components/vera/__init__.py | Python | apache-2.0 | 9,850 | 0.000609 | """Support for Vera devices."""
from __future__ import annotations
import asyncio
from collections import defaultdict
import logging
from typing import Any, Generic, TypeVar
import pyvera as veraApi
from requests.exceptions import RequestException
import voluptuous as vol
from homeassistant import config_entries
fro... | er(*tasks)
return True
async def _async_update_listener(hass: HomeAssistant, entry: ConfigEntry):
"""Handle options update."""
await hass.config_entries.async_reload(entry.entry_id)
def map_vera_d | evice(vera_device: veraApi.VeraDevice, remap: list[int]) -> str:
"""Map vera classes to Home Assistant types."""
type_map = {
veraApi.VeraDimmer: "light",
veraApi.VeraBinarySensor: "binary_sensor",
veraApi.VeraSensor: "sensor",
veraApi.VeraArmableDevice: "switch",
veraAp... |
andreaso/ansible | lib/ansible/modules/cloud/amazon/cloudfront_facts.py | Python | gpl-3.0 | 31,932 | 0.005386 | #!/usr/bin/python
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed... | ed: false
default: false
streaming_distribution_configuration:
description:
- Get the configuration information about a specified RTMP distribution.
Requires I(distribution_id) or I(domain_name_alias) to be specified.
required: false
defa | ult: false
list_origin_access_identities:
description:
- Get a list of cloudfront origin access identities. Requires I(origin_access_identity_id) to be set.
required: false
default: false
list_distributions:
description:
- Get a list of cloudfront distribu... |
william-richard/moto | moto/kinesisvideoarchivedmedia/responses.py | Python | apache-2.0 | 3,369 | 0.002671 | from __future__ import unicode_literals
from moto.core.responses import BaseResponse
from .models import kinesisvideoarchivedmedia_backends
import json
class KinesisVideoArchivedMediaResponse(BaseResponse):
SERVICE_NAME = "kinesis-video-archived-media"
@property
def kinesisvideoarchivedmedia_backend(self... | media_backend.get_hls_streaming_session_url(
stream_name=stream_name,
| stream_arn=stream_arn,
playback_mode=playback_mode,
hls_fragment_selector=hls_fragment_selector,
container_format=container_format,
discontinuity_mode=discontinuity_mode,
display_fragment_timestamp=display_fragment_timestamp,
expires=expires,... |
onoga/toolib | toolib/wx/grid/table/TNumberDataLines.py | Python | gpl-2.0 | 844 | 0.043839 |
class TNumberDataLines(object):
"""
Adapter used in
TTableClipboard
Requires:
getNumberDataRows or GetNumberRows
getNumberDataCols or GetNumberCols
Provide | s:
_getNumberDataRows
_getNumberDataCols
_getBaseDataRow
_getBaseDataCol
"""
def _getBaseDataRow(self):
if hasattr(self, 'getBaseDataRow'):
return self.getBaseDataRow()
else:
return 0
def _getBaseDataCo | l(self):
if hasattr(self, 'getBaseDataCol'):
return self.getBaseDataCol()
else:
return 0
def _getNumberDataRows(self):
if hasattr(self, 'getNumberDataRows'):
return self.getNumberDataRows()
else:
return self.GetNumberRows() - self._getBaseDataRow()
def _getNumberDataCols(self):
if hasattr(self... |
Thib17/biggraphite | biggraphite/drivers/_delayed_writer.py | Python | apache-2.0 | 5,350 | 0.000187 | #!/usr/bin/env python
# Copyright 2016 Criteo
#
# 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 agree... | lush=False, now=time.time):
"""Write some points from the queue."""
now = now() * 1000 # convert to ms.
if self._last_write_ms == 0:
self._last_write_ms = now
delta_ms = (now - self._last_write_ms) + 1
if flush:
metrics_to_ | write = len(self._queue)
else:
metrics_to_write = round(delta_ms * self._metrics_per_ms)
if metrics_to_write == 0:
return
i = 0
log.debug("writing low res points for %d metrics" % metrics_to_write)
while self._queue and i < metrics_to_write:
me... |
pomeslab/matplotdash | server/fake_dataserver.py | Python | mit | 2,830 | 0.00318 | """
A fake time series data server used during development to serve up JSON
for live updating plot rendering in the browser. The test datafile has
25000 points and cycles through this entire series every 60 minutes.
Examples
--------
>>> python fake_dataserver.py
>>> import requests; requests.get('http://127.0.0.1:500... | resp = make_response(f(*args, **kwargs))
if not attach_to_all and request.method != 'OPTIONS':
return resp
h = resp.headers
h['Access-Control-Allow-Origin'] = origin
h['Access-Control-Allow-Methods'] = ge | t_methods()
h['Access-Control-Max-Age'] = str(max_age)
if headers is not None:
h['Access-Control-Allow-Headers'] = headers
return resp
f.provide_automatic_options = False
return update_wrapper(wrapped_function, f)
return decorator
# Open local da... |
carmark/vbox | src/VBox/Devices/EFI/Firmware/BaseTools/Source/Python/UPT/Object/Parser/InfPpiObject.py | Python | gpl-2.0 | 12,929 | 0.009204 | ## @file
# This file is used to define class objects of INF file [Ppis] section.
# It will consumed by InfParser.
#
# Copyright (c) 2011, Intel Corporation. All rights reserved.<BR>
#
# This program and the accompanying materials are licensed and made available
# under the terms and conditions of the BSD License whi... | piItemObj = InfPpiItem()
if len(Item) >= 1 and len(Item) <= 2:
#
# Only CName contained
#
if not IsValidCVariableName(Item[0]):
Logger.Error("InfParser",
ToolError.FORMAT_I... | File=CurrentLineOfItem[2],
Line=CurrentLineOfItem[1],
Extr |
mojaves/convirt | tests/xmlfile_test.py | Python | lgpl-2.1 | 3,016 | 0 | #
# Copyright 2015-2016 Red Hat, Inc.
#
# This program 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 2 of the License, or
# (at your option) any later version.
#
# This program is distr... | def test_env(self):
with testlib.named_temp_dir() as tmp_dir:
with testlib.global_conf(run_dir=tmp_dir):
yield convirt.xmlfile.XMLFile(
self.vm_uuid,
convirt.config.environ.current()
)
def test_fails_without_conf(self):
... | None)
def test_path(self):
with self.test_env() as xf:
self.assertTrue(xf.path.endswith('xml'))
self.assertIn(self.vm_uuid, xf.path)
def test_save(self):
root = ET.fromstring(testlib.minimal_dom_xml())
with self.test_env() as xf:
conf... |
alexm92/sentry | src/sentry/options/store.py | Python | bsd-3-clause | 10,280 | 0.000778 | """
sentry.options.store
~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2015 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import, print_function
import logging
import six
from collections import namedtuple
from time import time
from ran... | tually exist,
or if we errored fetching it.
NOTE: This behavior should probably be improved to differentiate
between a miss vs error, but not | worth it now since the value
is limited at the moment.
"""
try:
value = self.model.objects.get(key=key.name).value
except self.model.DoesNotExist:
value = None
except Exception as e:
if not silent:
logger.exception(six.text_typ... |
gav-/Nand2Tetris-Games_and_Demos | bin/pbm2jack.image.py | Python | gpl-3.0 | 6,471 | 0.007418 | #!/usr/bin/env python3
"""pgm2jack
Convert a P1 pbm (monochome ascii, a.k.a. "Plain PBM") file to a
jack array (nand2tetris).
One word is 16bits in jack, so image width must be a multiple!
Copyright 2013-2016 Gavin Stewart.
You are required to give attribution to the author (Gavin Stewart) for any
use of this prog... | = className,
width = parser.width,
height = parser.height))
index = 0
while parser.hasMoreBits():
bitWord = parser.buildWord()
data[index] = formatWord(bitWord);
index += 1
index = 0
while index < len(data):
outfh.write(" do i.push({... | 3},{14},{15});\n".
format(
data[index],
data[index + 1],
data[index + 2],
data[index + 3],
data[index + 4],
data[index + 5],
data[index + 6],
... |
PaddlePaddle/Paddle | python/paddle/fluid/tests/custom_op/custom_relu_setup.py | Python | apache-2.0 | 1,325 | 0 | # Copyright (c) 2021 PaddlePaddle 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 appli... | not a new op, if you want to test only one op, remove this
# source file
setup(
name='custom_relu_module_setup',
ext_modules=Extension( # test for not specific name here.
sources=sources, # test for multi ops
include_dirs=paddle_includes,
ext | ra_compile_args=extra_compile_args))
|
saltstack/salt | doc/_ext/saltrepo.py | Python | apache-2.0 | 498 | 0.002008 | """
saltrepo
~~~~~~~~
SaltStack Repository Sphinx directives
"""
def source_read_handler(app, docname, source):
if "|repo_primary_branch| | " in source[0]:
source[0] = source[0].replace(
"|repo_primary_branch|", app.config.html_context["repo_primary_branch"]
)
def setup(app):
app.connect("source-read", source_read_handler)
return {
"version": "builtin",
"parallel_read_safe": True,
"parallel_wri... | _safe": True,
}
|
ericfourrier/pwnedapi | pwnedapi/__init__.py | Python | mit | 72 | 0 | __al | l__ = ['pwnedapi', 'utils']
from .pwnedapi | import HaveIBeenPwnedApi
|
GarmanGroup/RABDAM | tests/test_bnet_calculation.py | Python | lgpl-3.0 | 8,856 | 0.000452 |
# RABDAM
# Copyright (C) 2020 Garman Group, University of Oxford
# This file is part of RABDAM.
# RABDAM 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... | stCase):
def test_bnet_values(self):
"""
Checks that RABDAM calculates expected Bnet values for a selection of
PDB entries
"""
import os
import requests
import shutil
import pandas as pd
exp_bnet_dict = {'2O2X': 3.300580966,
... | : 3.144130191,
'3NBM': 3.141821366,
'1GW1': 3.105626889,
'4EWE': 3.08241654,
'3F1P': 3.060628186,
'3IV0': 3.054440912,
'4ZWV': 3.017330004,
'1T2I... |
vrooje/gzcandels_datapaper | plotting/plot_mags_z_thresholds.py | Python | mit | 11,858 | 0.00818 | import sys
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import matplotlib.ticker
import numpy as np
#import pandas as pd
import astropy
from astropy.table import Table
from scipy import stats, interpolate, special
from scipy.stats import gaussian_kde
infile = 'candels_restframe_phot_weight... | ured07a]))
colall = '#AAAAAA'
col04 = | '#006e35'
col05 = '#4455CC'
col06 = '#30a0ca'
#col07 = '#00ccaE'
col07 = "#ac0e30"
colclean = "#ac0e30"
sty04 = 'dashed'
sty05 = 'dotted'
sty06 = 'dashdot'
sty07 = 'solid'
styclean = 'solid'
fig = plt.figure(figsize=(10, 4))
gs = gridspec.GridSpec(1,2)
#gs.update(hspace=0.25, wspace=0.001)
zaxis = (0.0, 4.)
Vaxi... |
Outernet-Project/bottle-streamline | tests/sample_apps/base_only.py | Python | bsd-2-clause | 488 | 0 | from streamline import RouteBase
class MyRoute(RouteBase):
path = '/'
def get(self):
self.response.headers['foo'] = 'bar'
return 'Hello world!'
class MyOtherRoute(RouteBase):
path = '/other'
def post(self):
return 'Posted'
def delete(self):
return 'Deleted'
... | def patch(self):
ret | urn 'Patched'
def main():
MyRoute.route()
MyOtherRoute.route()
MyRoute.bottle.run()
if __name__ == '__main__':
main()
|
mmuzila/errata-tool | errata_tool/tests/conftest.py | Python | mit | 2,567 | 0 | import json
import os
from errata_tool import ErrataConnector, Erratum
from errata_tool.products import ProductList
import requests
import pytest
TESTS_DIR = os.path.dirname(os.path.abspath(__file__))
FIXTURES_DIR = os.path.join(TESTS_DIR, 'fixtures')
class Mo | ckResponse(object):
status_code = 200
encoding = 'utf-8'
headers = {'content-type': 'application/json; charset=utf-8'}
def raise_for_status(self):
pass
@property
def _fixture(self):
""" Return pa | th to our static fixture file. """
return self.url.replace('https://errata.devel.redhat.com/',
os.path.join(FIXTURES_DIR,
'errata.devel.redhat.com/'))
def json(self):
try:
with open(self._fixture) as fp:
... |
weixsong/algorithm | leetcode/137.py | Python | mit | 614 | 0.008143 | # -*- encoding: utf-8 -*-
'''
Given an | array of integers, every element appears three times except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
'''
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:... | count[num] += 1
for key in count:
if count[key] != 3:
return key
|
fearthecowboy/pygments | Pygments/pygments-lib/pygments/lexers/_mapping.py | Python | bsd-2-clause | 45,831 | 0.007571 | # -*- coding: utf-8 -*-
"""
pygments.lexers._mapping
~~~~~~~~~~~~~~~~~~~~~~~~
Lexer mapping definitions. This file is generated by itself. Everytime
you change something on a builtin lexer definition, run this script from
the lexers folder to update it.
Do not alter the LEXERS dictionary by ha... | 'CLexer': ('pygments.lexers.c_cpp', 'C', ('c',), ('*.c', '*.h', '*.idc'), ('text/x-chdr', 'text/x-csrc')),
'CMakeLexer': ('pygments.lexers.make', 'CMake', ('cmake',), ('*.cmake', 'CMakeLists.txt'), ('text/x-cmake',)),
'CObjdumpLexer': ('pygments.lexers.asm', 'c-objdump', ('c-objdump',), ('*.c-objdump',), ('tex... | '*.asmx', '*.axd'), ()),
'CSharpLexer': ('pygments.lexers.dotnet', 'C#', ('csharp', 'c#'), ('*.cs',), ('text/x-csharp',)),
'Ca65Lexer': ('pygments.lexers.asm', 'ca65 assembler', ('ca65',), ('*.s',), ()),
'CbmBasicV2Lexer': ('pygments.lexers.basic', 'CBM BASIC V2', ('cbmbas',), ('*.bas',), ()),
'CeylonL... |
yancz1989/lr_semi | common/util.py | Python | mit | 1,092 | 0.016484 | import subprocess
import os
import errno
def download_file(url, local_fname=None, force_write=False):
# requests is not default installed
import requests
if local_fname is None:
local_fname = url.split('/')[-1]
if not force_write and os.pa | th.exists(local_fname):
return local_fname
dir_name = os.path.dirname(local_fname)
if dir_name != "":
if not os.path.exists(dir_name):
try: # try to create the directory if it doesn't exists
os.makedirs(dir_name)
except OSError as exc:
if exc.errn | o != errno.EEXIST:
raise
r = requests.get(url, stream=True)
assert r.status_code == 200, "failed to open %s" % url
with open(local_fname, 'wb') as f:
for chunk in r.iter_content(chunk_size=1024):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
return local_fname
def g... |
vzer/ToughRADIUS | toughradius/radiusd/plugins/auth_user_filter.py | Python | agpl-3.0 | 785 | 0.017834 | #!/usr/bin/env python
#coding=utf-8
from toughradius.radiusd.plugins import error_auth
from toughradius.radiusd import utils
def process(req=None,resp=None,user=None,radiusd=None,**kwargs):
store = radiusd.store
if store.is_white_roster(req.get_mac_addr()):
return resp
if not user:
return... | ser %s not exists'%req.get_user_name())
if store.get_param("radiusd_bypass") == '1': |
if not req.is_valid_pwd(utils.decrypt(user['password'])):
return error_auth(resp, 'user password not match')
if user['status'] == 4:
resp['Framed-Pool'] = store.get_param("expire_addrpool")
return resp
if user['status'] in (0,2,3):
return error_auth(resp,'... |
codingsnippets/Gooey | gooey/gui/containers/application.py | Python | mit | 8,890 | 0.002362 | """
Primary orchestration and control point for Gooey.
"""
import sys
from itertools import chain
import wx
from gooey.gui import events
from gooey.gui.components.header import FrameHeader
from gooey.gui.components.footer import Footer
from gooey.gui.util import wx_util
from gooey.gui.components.config ... | self.header.setImage('settings_img')
self.header.setTitle(_("settings_title"))
self.header.setSubtitle(self.buildSpec['program_description'])
self.footer.showButtons('cancel_button', 'start_button')
self.footer.progress_bar.Show(False)
def showConsole(self):
se... |
self.header.setTitle(_("running_title"))
self.header.setSubtitle(_('running_msg'))
self.footer.showButtons('stop_button')
self.footer.progress_bar.Show(True)
if not self.buildSpec['progress_regex']:
self.footer.progress_bar.Pulse()
def showComplete(sel... |
Tritlo/Stundatafla | StundatofluUtil.py | Python | gpl-2.0 | 246 | 0.00813 | def getLocations(listrep, checkFunc):
t = listrep
locs = []
for i in range(len(t)):
for j in range(len(t[0])):
locs.append((i,j))
places = filter(lambda (i,j): checkFunc(listrep[i][j]), locs)
return place | s
| |
tiberiucorbu/av-website | main/model/__init__.py | Python | mit | 314 | 0 | # coding: utf-8
from .base import Base
from .config_auth import ConfigAuth
from .config import Config
from .user | import User
from .resource import Resource
from .common import VisibilityFlags
from .meta import ItemMeta
from .meta import PageMeta
from .story import Story
from .module_config i | mport ModuleConfig
|
xguse/outspline | src/outspline/info/extensions/organism_alarms.py | Python | gpl-3.0 | 1,392 | 0.000718 | # Outspline - A highly modular and extensible outliner.
# Copyright (C) 2011-2014 Dario Giovannetti <dev@dariogiovannetti.net>
#
# This file is part of Outspline.
#
# Outspline 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 Softw... | tps://kynikos.github.io/outspline/"
affects_database = True
provides_tables = ("AlarmsProperties", "Alarms", "CopyAlarms", "AlarmsOffLog")
dependencies = (("core", 4), ("extensions.organism", 2),
("extens | ions.organism_timer", 1))
optional_dependencies = (("extensions.copypaste", 2), )
database_dependency_group_1 = (("core", 4), ("extensions.organism", 2),
("extensions.organism_timer", 1), ("extensions.organism_alarms", 1))
|
acsone/margin-analysis | product_cost_incl_costs_with_bom/product.py | Python | agpl-3.0 | 2,373 | 0.00295 | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright 2012 Camptocamp SA
# Copyright 2012 Endian Solutions BV
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License ... | fero General Public License for more details.
#
# You sho | uld have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.osv.orm import Model
from openerp.osv import fields
import decimal_precision as dp
... |
cyandterry/Python-Study | Ninja/Concept_Implement/OOD.py | Python | mit | 134 | 0 | # C | C150 8.1
# Design the data structur | e for a generic deck of cards.
class suit():
def __init__(self, v):
self.value = v
|
vgrem/Office365-REST-Python-Client | office365/sharepoint/webs/web_collection.py | Python | mit | 1,240 | 0.004032 | from office365.runtime.queries.service_operation_query import ServiceOperationQuery
from office365.sharepoint.base_entity_collection import BaseEntityCollection
from office365.sharepoint.webs.web import Web
class WebCollection(BaseEntityCollection):
"""Web collection"""
def __init__(self, context, resource_p... | eb = Web(self.context)
self.add_child(target_web)
qry = ServiceOperationQuery(self, "add", None, web_creation_information, "parameters", target_web)
self.context.add_query(qry)
return target_web
@property
def resource_url(self):
val = super(WebCollection, self).resource_... | property("Url")
if parent_web_url is not None:
val = val.replace(self.context.service_root_url(), parent_web_url + '/_api')
return val
|
alonsopg/AuthorProfiling | src/ef_list_punctuation.py | Python | gpl-2.0 | 3,045 | 0.018421 | #! | /usr/bin/env python
# -*- coding: utf-8
from __future__ import print_function
import argparse
import codecs
import cPickle as pickle
import numpy as np
import os
from load_tweets import load_tweets
NAME='ef_list_punctuation'
prefix='list_punctuation'
if __name__ == "__main__":
# Las opciones de línea de comando
... | action="store", help="File with list of emoticons")
p.add_argument("-d", "--dir",
action="store", dest="dir",default="feats",
help="Default directory for features [feats]")
p.add_argument("-p", "--pref",
action="store", dest="pref",default=prefix,
help="Prefix to sav... |
novel/lc-tools | test/__init__.py | Python | apache-2.0 | 212 | 0.004717 | """Test package"""
import os.path
impo | rt sys
def setup_package():
# insert top-level dir to python path
# so we could easily import stuff from
| # tests
sys.path.insert(0, os.path.abspath("../"))
|
sdu14SoftwareEngineering/GameOfLife_WEB | game/tool/room_tool.py | Python | apache-2.0 | 1,016 | 0 | from game.models import User
# 存储在内存中的所有房间
rooms_list = []
class Room(object):
id = int # 房间id
name = str # 房间名
owner = int # 房主id
users = [] # 成员id
users_status = {} # 成员准备状态
status = False # 状态
def __init__(self, id, name):
self.id = id
self.name =... | f get_room_by_id(id):
for room in rooms_list:
if room.id == id:
return ro | om
return None
# 获取某个房间name
def get_room_by_name(name):
for room in rooms_list:
if room.name == name:
return room
return None
# 添加
def add_room(new_room):
rooms_list.append(new_room)
return 1
# 删除
def del_room(id):
for room in rooms_list:
if... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.