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 |
|---|---|---|---|---|---|---|---|---|
saltstack/salt | tests/integration/files/file/base/_executors/arg.py | Python | apache-2.0 | 185 | 0 | def __virtual__():
return True
def execute(*args, **kwargs):
# we use the dunder to assert the loader is pro | vided minionmods
return __salt__["test.arg | "]("test.arg fired")
|
hirokiky/wraptools | wraptools/context.py | Python | mit | 630 | 0 | from functools import wraps
def context(*context_funcs):
""" Decorator to inject additional arguments taken by :param context_funcs:
>>> data = {1: "user1", 2: "user2"}
>>> @context(
... lambda r, i: data.get(i),
... )
... def some_view(request, user_id, username):
... print(usern... | # says user1
"""
def dec(func):
@wraps(func)
def wrapped(*args, **kwargs):
contexts = tuple(f(*args, **kwargs) for f in context_func | s)
return func(*(args + contexts), **kwargs)
return wrapped
return dec
|
arth-co/shoop | shoop/front/views/payment.py | Python | agpl-3.0 | 2,387 | 0.002933 | # -*- coding: utf-8 -*-
# This file is part of Shoop.
#
# Copyright (c) 2012-2015, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import unicode_literals, with_statement
from django.core.ex... | reverse
from django.shortcuts import get_object_or_404, redirect
from django.views.generic import DetailView
from shoop.core.models import Order
def get_payment_urls(request, order):
kwargs = dict(pk=order.pk, key=order.key)
return {
"payment": request.build_absolute_uri(reverse("shoop:or | der_process_payment", kwargs=kwargs)),
"return": request.build_absolute_uri(reverse("shoop:order_process_payment_return", kwargs=kwargs)),
"cancel": request.build_absolute_uri(reverse("shoop:order_payment_canceled", kwargs=kwargs))
}
class ProcessPaymentView(DetailView):
model = Order
cont... |
spicyramen/sipLocator | tools/testSmS.py | Python | gpl-2.0 | 471 | 0.012739 | from twilio.rest import TwilioRestClient
# Your Account Sid and Auth Token from twilio.com/user/account
account_sid = "AC433e7b0bec93dc5996e4fb80b1e56eec"
auth_token = "9cc9267fe09dab362d3be160f711a09d"
client = TwilioRestClient(account_sid, auth_token)
message = client. | sms.messages.create(body="Jenny please?! I love you <3",
| to="+14082186575", # Replace with your phone number
from_="++1415-795-2944") # Replace with your Twilio number
print message.sid |
backupManager/pyflag | src/pyflag/TEXTUI.py | Python | gpl-2.0 | 8,684 | 0.019691 | #!/usr/bin/env python
# ******************************************************
# Copyright 2004: Commonwealth of Australia.
#
# Developed by the Computer Network Vulnerability Team,
# Information Security Group.
# Department of Defence.
#
# Michael Cohen <scudette@users.sourceforge.net>
#
# ****************************... | ept KeyError:
try:
self.sort=[self.defaults['dorder'],'dorder']
except KeyError:
self.sort=[0,'order']
self.filter_conditions=[]
self.filter_text=[]
try:
if not gr | oupby:
groupby=self.defaults['group_by']
except KeyError:
groupby=None
# Get a new SQL generator for building the table with.
generator,new_query,names,columns,links = self._make_sql(sql=sql,columns=columns,names=names,links=links,table=table,where=where,groupby = gr... |
oourfali/cloud-init-fedora | cloudinit/netinfo.py | Python | gpl-3.0 | 3,816 | 0.000786 | #!/usr/bin/python
# vi: ts=4 expandtab
#
# Copyright (C) 2012 Canonical Ltd.
# Copyright (C) 2012 Hewlett-Packard Development Company, L.P.
#
# Author: Scott Moser <scott.moser@canonical.com>
# Author: Juerg Haefliger <juerg.haefliger@hp.com>
#
# This program is free software: you can redistribute it and... |
dev[field] = empty
return(devs)
def route_info():
route_out = str(check_output([" | route", "-n"]))
routes = []
for line in route_out.splitlines()[1:]:
if not line:
continue
toks = line.split()
if toks[0] == "Kernel" or toks[0] == "Destination":
continue
routes.append(toks)
return(routes)
def getgateway():
for r in route_info():... |
fake-name/ReadableWebProxy | WebMirror/management/rss_parser_funcs/feed_parse_extractMionline657939096WordpressCom.py | Python | bsd-3-clause | 574 | 0.033101 |
def ext | ractMionline657939096WordpressCom(item):
'''
Parser for 'mionline65 | 7939096.wordpress.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('PRC', 'PRC', 'translated'),
('Loiterous', 'Loiterous', 'oel'),
]
for tagname, ... |
veragluscevic/dmdd | dmdd/tests/test.py | Python | mit | 8,718 | 0.016059 | import os,os.path,shutil
import numpy as np
import pickle
import dmdd
import dmdd_efficiencies as eff
def check_min_mass(element='fluorine', Qmin=1., v_esc=544., v_lag=220., mx_guess=1.):
experiment = dmdd.Experiment('test',element,Qmin, 40.,100., eff.efficiency_unit)
res = experiment.find_min_mass(v_esc=v_e... | =experiment.Qmin, Qmax=experiment.Qmax,
exposu | re=experiment.exposure,en |
scieloorg/Logger | tests/test_inspector.py | Python | bsd-2-clause | 2,902 | 0 | try:
from unittest.mock import patch
except ImportError:
from mock import patch
from logger.inspector import Inspector
from unittest import TestCase
class MockCollection(object):
def __init__(self, website_id, collection_id, website_acron_in_filename):
self.website_id = website_id
self.c... | y_false_1(self):
insp = Inspector('/var/www/scielo.br/2015-12-30_sciel.br.log.gz')
self.assertFalse(insp._is_valid_source_directory())
def test_is_valid_source_directory_false_2(self):
insp = Inspector('/var/www/scielo.pepsic/2015 | -12-30_scielo.br.log.gz')
self.assertFalse(insp._is_valid_source_directory())
|
xray7224/CimCity | cim/items/civics.py | Python | gpl-3.0 | 1,199 | 0.000834 | ##
# Copyright (C) 2014, 2015 Matt Molyneaux
#
# This file is part of CimCity.
#
# CimCity 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 versi... | THOUT 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 CimCity. If not, see <http://www.gnu.org/licenses/>.
##
from __futu... | PoliceStation(CivicBuilding):
@property
def healthiness(self):
return int(random.gauss(super(PoliceStation, self).healthiness, 10))
class FireStation(CivicBuilding):
pass
class Hospital(CivicBuilding):
@property
def healthiness(self):
return int(random.gauss(super(Hospital, self... |
frederica07/Dragon_Programming_Process | PyOpenGL-3.0.2/OpenGL/raw/GL/AMD/shader_stencil_export.py | Python | bsd-2-clause | 372 | 0.008065 | '''Autogenera | ted by get_gl_extensions script, do not edit!'''
from OpenGL import platform as _p
from OpenGL.GL import glget
EXTENSION_NAME = 'GL_AMD_shader_stencil_export'
def glInitShaderStencilExportAMD():
'''Return boolean indicating whether this extension is available'''
from OpenGL import extensions
return exten... | Extension( EXTENSION_NAME )
|
JConwayAWT/PGSS14CC | lib/python/multimetallics/ase/test/castep/castep_interface.py | Python | gpl-2.0 | 3,656 | 0.003829 | #!/usr/bin/python
"""Simple shallow test of the CASTEP interface"""
import os
import shutil
import tempfile
import traceback
from ase.test import NotAvailable
# check if CASTEP_COMMAND is set a environment variable
if not os.environ.has_key('CASTEP_COMMAND'):
print("WARNING: Environment variable CASTEP_COMMAND ... | tmp_dir, 'myParam.param')
param = open(param_fn,'w')
param.write('XC_FUNCTIONAL : PBE #comment\n')
param.write('XC_FUNCTIONAL : PBE #comment\n')
param.write('#comment\n')
param.write('CUT_OFF_ENERGY : 450.\n')
param.close()
try:
c.merge_param(param_fn)
except Exception, e:
traceback.print_exc()
print(e)
... | merge_param_filename, go figure"
# check if the CastepOpt, CastepCell comparison mechanism works
p1 = CastepParam()
p2 = CastepParam()
assert p1._options == p2._options, "Print two newly created CastepParams are not the same"
p1._options['xc_functional'].value = 'PBE'
p1.xc_functional = 'PBE'
assert not p1._option... |
sburnett/seattle | seattlegeni/lockserver/tests/unit/ut_lockserverunit_user_and_node_locks.py | Python | mit | 6,231 | 0.002889 | import unittest
import lockserver_daemon as lockserver
class TheTestCase(unittest.TestCase):
def setUp(self):
# Reset the lockserver's global variables between each test.
lockserver.init_globals()
def testUserAndNodeLockContention_one(self):
# Start three sessions.
sess = []
sess.append(lo... | ]: {'heldlocks': {'user': [], 'node': []},
'neededlocks': {'user': [], 'node': []},
'acquirelocksproceedeventset': True}}
|
status = lockserver.do_get_status()
self.assertEqual(expected_heldlockdict, status["heldlockdict"])
self.assertEqual(expected_sessiondict, status["sessiondict"])
|
uclapi/uclapi | backend/uclapi/oauth/scoping.py | Python | mit | 4,517 | 0 | # Storage of the scope map
# The purpose of this setup is that the OAuth scope of any app can be stored
# in a single field. This way, we can easily add more scopes later.
# We have a BigIntegerField to work with, which means 64 bits of storage.
# This translates into 64 types of scope, each of which can be checked wit... | ry with the scope information. Example:
# {
# "roombookings": True,
# "timetable": False,
# ...
# }
def scope_dict(self, current, pretty_print=True):
scopes = []
for x in self.SCOPE_MAP.keys():
if self.check_scope(current, x):
if pretty_print:... | }
else:
scope = {
"id": self.SCOPE_MAP[x][0],
"name": x
}
scopes.append(scope)
return scopes
# Same as above, but list all possible scopes along with whether they are
# inclu... |
jaredkerim/stompy | app/settings.py | Python | mit | 3,293 | 0.001215 | """
Django settings for stompy project.
Generated by 'django-admin startproject' using Django 1.9.5.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os
# ... | 'USER': os.environ['DB_USER'],
'PASSWORD': os.environ['DB_PASS'],
'HOST': os.environ['DB_HOST'],
'PORT': '5432',
}
}
# Password validation
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.au... | ion.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValid... |
archf/ansible | test/runner/shippable.py | Python | gpl-3.0 | 2,577 | 0.000776 | #!/usr/bin/env python
# PYTHON_ARGCOMPLETE_OK
"""Verify the current Shippable run has the required number of jobs."""
from __future__ import absolute_import, print_function
# noinspection PyCompatibility
import argparse
import errno
import os
import sys
from lib.http import (
HttpClient,
)
from lib.util import ... | com/jobs?runIds=%s' % run_id)
jobs = response.json()
if len(jobs) == 1:
raise Applicat | ionError('Shippable run %s has only one job. Did you use the "Rebuild with SSH" option?' % run_id)
except ApplicationWarning as ex:
display.warning(str(ex))
exit(0)
except ApplicationError as ex:
display.error(str(ex))
exit(1)
except KeyboardInterrupt:
exit(2)
exc... |
ericyue/mooncake_utils | setup.py | Python | apache-2.0 | 646 | 0.041796 | # -*- coding:utf-8 -*-
# |
# Copyright (c) 2017 mooncake. All Rights Reserved
####
# @brief
# @author Eric Yue ( hi.moonlight@gmail.com )
# @version 0.0.1
from distut | ils.core import setup
V = "0.7"
setup(
name = 'mooncake_utils',
packages = ['mooncake_utils'],
version = V,
description = 'just a useful utils for mooncake personal project.',
author = 'mooncake',
author_email = 'hi.moonlight@gmail.com',
url = 'https://github.com/ericyue/mooncake_utils',
download_ur... |
Distrotech/PyQt-x11 | examples/graphicsview/dragdroprobot/dragdroprobot_rc2.py | Python | gpl-2.0 | 62,689 | 0.00008 | # -*- coding: utf-8 -*-
# Resource object code
#
# Created: Wed Mar 20 13:39:06 2013
# by: The Resource Compiler for PyQt (Qt v4.8.4)
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore
qt_resource_data = "\
\x00\x00\x3a\x7c\
\x89\
\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x... | xd3\
\xa1\x70\x24\xc4\x40\x4b\xcd\x16\x45\xc1\x15\x57\x5c\x72\x83\xad\
\x9b\x32\x23\x57\x26\xa4\xdd\xdf\xdb\x10\xee\ | xe0\x4f\x1d\x4b\xf7\
\x90\xaf\xd8\x52\x52\xb3\xe6\x92\x15\x0d\x1b\x6a\x1a\x1a\xc9\x03\
\x0d\xa7\x28\x62\x46\xc4\x94\x5c\xb0\x22\xc6\x04\xef\x5d\xd3\xb0\
\x25\x66\xcc\x86\x46\x70\x06\x45\x43\x85\x21\x26\xc6\xa0\x59\x89\
\xd9\xb7\x8c\x88\xe9\xe8\xd8\xd2\x90\xd1\x52\xe1\xe4\xcd\xbb\x41\
\x4d\x33\x25\x92\xef\xdc\xd0\x70\xc... |
Curlybear/Socrates | battle.py | Python | gpl-3.0 | 23,254 | 0.001978 | import configparser
import json
from os.path import join
import discord
import requests
from discord.ext import commands
import ereputils
# Config reader
config = configparser.ConfigParser()
config.read("config.ini")
# API Key
apiKey = config["DEFAULT"]["api_key"]
apiVersion = config["DEFAULT"]["api_version"]
cla... | )
embed.add_field(name="Occupied by", value=occupied_text, inline=True)
await ctx.message.channel.send("", embed=embed)
except:
raise c | ommands.ArgumentParsingError(
"Country ***" + in_country + "*** not recognized"
)
@commands.command(pass_context=True, aliases=["SH"])
async def sh(self, ctx):
"""Returns the list of the upcoming air rounds as well as air rounds with limited damage done."""
r = reque... |
ipwnponies/youtube-sort-playlist | playlist_updates.py | Python | unlicense | 13,622 | 0.002936 | #! /usr/bin/env python
import argparse
import operator
import os
import sys
from collections import namedtuple
from functools import lru_cache
from functools import reduce
from pathlib import Path
from typing import Any
from typing import Dict
from typing import List
import addict
import arrow
import googleapiclient.e... | laylist_videos: | List[JsonType]) -> Dict[str, VideoInfo]:
'''Returns a dict of VideoInfo for each video
The key is video id and the value is VideoInfo.
'''
result = {}
videos = [i['snippet']['resourceId']['videoId'] for i in playlist_videos]
# Partition videos due to max number of vide... |
gcq/pyth | server.py | Python | mit | 2,516 | 0.006757 | #!venv/bin/python
from flask import Flask, render_template, request, Response
import os
import time
import subprocess
app = Flask(__name__, template_folder='.', static_folder='.')
@app.route('/')
def root():
time_in_secs = os.path.getmtime('pyth.py')
time_in_python = time.gmtime(time_in_secs)
formatted_t... | _code = '\n'.join(code_message.split("\r\n"))
pyth_process = \
subprocess. | Popen(['/usr/bin/env',
'python3',
'pyth.py',
'-csd' if debug_on else '-cs',
pyth_code],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr... |
unt-libraries/catalog-api | django/sierra/shelflist/tests/test_api.py | Python | bsd-3-clause | 37,869 | 0.003116 | """
Tests API features applicable to the `shelflist` app.
"""
import pytest
import ujson
import jsonpatch
from datetime import datetime
from shelflist.exporters import ItemsToSolr
from shelflist.search_indexes import ShelflistItemIndex
from shelflist.serializers import ShelflistItemSerializer
# FIXTURES AND TEST DAT... | T1', {'status_code': '-',
'due_date': datetime(2019, 6, 30, 00, 00, 00)}),
('TEST2', {'status_code': '-', 'due_date': None}),
), 'status_code=-&dueDate[isnull]=true', ['TEST2']),
}, { 'status NOT CHECKED OUT and st | atus code a | one match': ((
('TEST1', {'status_code': '-',
'due_date': datetime(2019, 6, 30, 00, 00, 00)}),
('TEST2', {'status_code': 'a', 'due_date': None}),
), 'status_code=a&dueDate[isnull]=true', ['TEST2']),
}, { 'status NOT CHECKED OUT and status code a, b | multiple ma... |
jhgoebbert/cvl-fabric-launcher | wsgidav/server/run_reloading_server.py | Python | gpl-3.0 | 1,415 | 0.013428 | # (c) 2009-2011 Martin Wendt and contributors; see WsgiDAV http://wsgidav.googlecode.com/
# Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
"""
Wrapper for ``run_server``, that restarts the server when source code is
modified.
"""
import os
import sys
from subprocess import P... | # | preexec_fn, close_fds, shell, cwd, env, universal_newlines, startupinfo, creationflags
)
sys.stdout = p.stdout
sys.stderr = p.stderr
p.wait()
sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__
if p... |
DevinDewitt/pyqt5 | examples/mainwindows/sdi/sdi_rc.py | Python | gpl-3.0 | 36,524 | 0.000137 | # -*- coding: utf-8 -*-
# Resource object code
#
# Created: Sun May 12 18:04:51 2013
# by: The Resource Compiler for PyQt (Qt v5.0.2)
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore
qt_resource_data = b"\
\x00\x00\x03\x54\
\x89\
\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\... | x0e\x90\xaf\x85\xde\xb7\xc2\x92\
\x3d\x4f\xa6\xb3\xde\xa3\xb1\x71\xeb\xda\xd0\xf5\x15\x98\xb3\x6e\
\xa9\x00\x6c\x34\xa4\x6b\x18\xff\xe0\x11\x7f\x5a\x17\x53\xd4\x13\
\x0b\x59\x6f\xe4\xee\xbd\xe2\xa5\xc1\xcb\x4b\x7c\x6d\x8c\x75\x87\
\x35\xa | 8\xfa\xb7\x1c\xdd\x65\xd9\x3c\x8f\x1f\x19\xfe\x9e\xcf\x1e\
\x37\xbd\xc9\xba\x78\x26\x6f\x46\x00\x68\xf2\xff\x81\x99\x94\x9e\
\xe9\x3f\xbf\x19\x01\x42\xd3\xf4\xfc\xbd\x9c\x9e\xa5\x7e\x03\x51\
\x6c\x25\xa1\x92\x95\x0a\x77\x00\x00\x00\x00\x49\x45\x4e\x44\xae\
\x42\x60\x82\
\x00\x00\x06\x6d\
\x89\
\x50\x4e\x47\x0d\x0a\x1a\... |
hiaselhans/OpenGlider | tests/test_patterns.py | Python | gpl-3.0 | 1,407 | 0.003554 | import unittest
import tempfile
import os
import op | englider
import openglider.plots
import openglider.plots.glider
from common import TestCase
TEMPDIR = tempfile.gettempdir()
class TestPlots(TestCase):
def setUp(self, complete=True):
self.glider_2d = self.im | port_glider_2d()
self.glider_3d = self.glider_2d.get_glider_3d()
self.plotmaker = openglider.plots.PlotMaker(self.glider_3d)
@unittest.skip("not working")
def test_patterns_panels(self):
self.plotmaker.get_panels()
dwg = self.plotmaker.get_all_stacked()["panels"]
dwg.exp... |
sgordon007/jcvi_062915 | apps/gmap.py | Python | bsd-2-clause | 5,206 | 0.000192 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
Run GMAP/GSNAP commands. GMAP/GSNAP manual:
<http://research-pub.gene.com/gmap/src/README>
"""
import os.path as op
import sys
import logging
from jcvi.formats.sam import get_prefix
from jcvi.apps.base import OptionParser, ActionDispatcher, need_update, sh, \
... | -npaths", default=0, type="int",
help="Maximum number of paths to show."
" If set to 0, prints two paths if chimera"
" detected, else one.")
p.set_cpus()
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
dbfile, f... | t need_update((dbfile, fastafile), gmapfile):
logging.error("`{0}` exists. `gmap` already run.".format(gmapfile))
else:
dbdir, dbname = check_index(dbfile)
cmd = "gmap -D {0} -d {1}".format(dbdir, dbname)
cmd += " -f 2 --intronlength=100000" # Output format 2
cmd += " -t {0}... |
hogarthww/django-rest-test-data | rest_test_data/tests/test_base.py | Python | gpl-2.0 | 4,061 | 0 | from django.core.serializers import json
from django.http import HttpResponseNotFound, HttpResponse
from django.views.generic import View
from rest_test_data.models import Simple
from rest_test_data.views import BaseTestDataRestView
from nose.tools import assert_equal, assert_is_instance
from mock import Mock, patch
... | 'get_object')
@patch.object(View, 'dispatch')
def test_dispatch_get_object(dispatch, get_object):
dispatch.return_value = ''
view = BaseTestDataRestView()
result = view.dispatch(
create_request(),
app='rest_test_data',
model='simple',
pk='1'
)
get_object.assert_calle... | nse)
assert_equal(dispatch.call_count, 1)
@patch.object(BaseTestDataRestView, 'get_object')
def test_dispatch_get_object_failure(get_object):
get_object.side_effect = Exception
view = BaseTestDataRestView()
result = view.dispatch(None, app='rest_test_data', model='simple', pk='1')
get_object.asser... |
foursquare/pants | tests/python/pants_test/backend/python/tasks/test_python_run_integration.py | Python | apache-2.0 | 8,737 | 0.008699 | # coding=utf-8
# Copyright 2017 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import absolute_import, division, print_function, unicode_literals
import os
import sys
from pex.pex_bootstrapper import get_pex_info
from pants.util.cont... | _3(self):
if self.skip_if_no_python('2.7') or self.skip_if_no_python('3'):
| return
with temporary_dir() as interpreters_cache:
pants_ini_config = {'python-setup': {'interpreter_cache_dir': interpreters_cache}}
pants_run_27 = self.run_pants(
command=['run', '{}:echo_interpreter_version_2.7'.format(self.testproject)],
config=pants_ini_config
)
self.a... |
Og192/Python | theano/Loop/loopForShareVariable.py | Python | gpl-2.0 | 683 | 0.014641 | import theano
from theano import tensor as T
w = thenao.shared(W_values)
bvis | = theano.shared(bvis_values)
bhid = theano.shared(b | hid_values)
trng = T.shared_randomstreams.RandomStreams(1234)
def OneStep(vsample) :
hmean = T.nnet.sigmoid(theano.dot(vsample, W) + bhid)
hsample = trng.binomial(size=hmean.shape, n=1, p=hmean)
vmean = T.nnet.sigmoid(theano.dot(hsample, W.T) + bvis)
return trng.binomial(size=vsample.shape, n=1, p=vme... |
sasha-gitg/python-aiplatform | .sample_configs/param_handlers/create_hyperparameter_tuning_job_python_package_sample.py | Python | apache-2.0 | 3,158 | 0.0019 | # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | t_discrete_values": {"values": [4, 8, 16]},
}
parameter = {
"parameter_id": "batch_size",
"discrete_value_spec": {"values": [4, 8, 16, 32, 64, 128]},
"scale_type": aiplatform.gapic.StudySpec.Paramete | rSpec.ScaleType.UNIT_LINEAR_SCALE,
"conditional_parameter_specs": [
conditional_parameter_decay,
conditional_parameter_learning_rate,
],
}
# trial_job_spec
machine_spec = {
"machine_type": "n1-standard-4",
"accelerator_type": aiplatform.gapic.Accelera... |
ARM-software/lisa | lisa/tests/base.py | Python | apache-2.0 | 77,167 | 0.001089 | # SPDX-License-Identifier: Apache-2.0
#
# Copyright (C) 2018, Arm Limited and contributors.
#
# 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
#
# ... | r(data)
return out
else:
def format_data(data):
# Handle recursive mappings, like metrics of AggregatedResultBundle
if isinstance(data, Mapping):
data = sort_mapping(data)
return '{' + ', '.join(
f'{key}={format_data(da... | tric:
"""
A storage class for metrics used by tests
:param data: The data to store. Can be any base type or dict(TestMetric)
:param units: The data units
:type units: str
"""
def __init__(self, data, units=None):
self.data = data
self.units = units
def __str__(self):
... |
botswana-harvard/bcvp | bcvp/bcvp_subject/admin/subject_locator_admin.py | Python | gpl-2.0 | 1,944 | 0.002058 | from django.contrib import admin
from edc_registration.models import RegisteredSubject
from edc_locator.admin import BaseLocatorModelAdmin
from ..forms import SubjectLocatorForm
from ..models import SubjectLocator
class SubjectLocatorAdmin(BaseLocatorModelAdmin):
form = SubjectLocatorForm
fields = (
... | ssful_mode_of_contact')
list_display = ('may_follow_up', 'may_call_work')
list_filter = ('may_follow_up', 'may_call_work')
search_fields = (
| 'registered_subject__subject_identifier', 'subject_cell', 'subject_cell_alt',
'subject_phone', 'subject_phone_alt', 'subject_work_place', 'subject_work_phone')
radio_fields = {"home_visit_permission": admin.VERTICAL,
"may_follow_up": admin.VERTICAL,
"may_call_work": ... |
chenfengyuan/download-youku-video | main.py | Python | mit | 2,621 | 0.002289 | #!/usr/bin/env python3
# coding=utf-8
__author__ = 'chenfengyuan'
import tornado.gen
import re
import tornado.log
import tornado.ioloop
import tornado.options
import youku
import sys
import os
import utils
import tqdm
import math
import decimal
import tornado.httpclient
import shutil
import argparse
def main():
p... | n urls', default=0)
args = parser.parse_args()
tornado.options.parse_config_file('/dev/null')
tornado.httpclient.AsyncHTTPClient.configure("tornado.curl_httpclient.CurlAsyncHTTPClient")
io = tornado.ioloop.IOLoop.instance()
@tornado.gen.coroutine
def dummy():
skipped = 0
for ra... | gs.urls:
for url in (yield youku.Youku.get_videos(raw_url)):
print(url)
continue
skipped += 1
if skipped <= args.skip:
continue
data = yield youku.Youku.get_video_name_and_download_urls(url)
d... |
rkk09c/Flask_Boilerplate | db_create.py | Python | mit | 484 | 0.008264 | #!flask/bin/python
from migrate.versioning import api
from config import SQLALCHEMY_DATABASE_URI
from config import SQLALCHEMY_MIGRATE_REPO |
from app import db
import os.path
db.create_all()
if not os.path.exists(SQLALCHEMY_MIGRATE_REPO):
api.create(SQLALCHEMY_MIGRATE_REPO, 'database repository')
api.version_control(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
else:
api.version_control(SQLALCHEMY_DATABA | SE_URI, SQLALCHEMY_MIGRATE_REPO, api.version(SQLALCHEMY_MIGRATE_REPO))
|
aldebaran/qibuild | python/qibuild/actions/__init__.py | Python | bsd-3-clause | 365 | 0.00274 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2012-2021 SoftBank Robotic | s. All rights reserved.
# Use of this source code is governed by a BSD-style licens | e (see the COPYING file).
""" This package contains the qibuild actions. """
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
|
ccqpein/Arithmetic-Exercises | Add-Digits/add_digits.py | Python | apache-2.0 | 260 | 0.015385 | #! /usr/bin/env python
# -*- coding=utf-8 -*-
d | ef addDigits(num):
while(1):
sum= 0
for i in xrange(len(str(num))):
sum+= int(str(num)[i])
if len(str(sum))== 1:
return sum
| else:
num= sum
|
activityworkshop/Murmeli | murmeli/pages/messages.py | Python | gpl-2.0 | 4,728 | 0.005076 | '''Module for the messages pageset'''
from murmeli.pages.base import PageSet
from murmeli.pagetemplate import PageTemplate
from murmeli import dbutils
from murmeli.contactmgr import ContactManager
from murmeli.messageutils import MessageTree
from murmeli import inbox
class MessagesPageSet(PageSet):
'''Messages p... | em.COMPNAME_DATABASE)
dbutils.export_all_avatars(database, self.get_web_cache_dir())
self._process_command(url, params)
# Make dictionary to convert ids to names
conta | ct_names = {cont['torid']:cont['displayName'] for cont in database.get_profiles()}
unknown_sender = self.i18n("messages.sender.unknown")
unknown_recpt = self.i18n("messages.recpt.unknown")
message_list = database.get_inbox() if database else []
conreqs = []
conresps = []
... |
jaggu303619/asylum | openerp/addons/l10n_in_hr_payroll/report/report_payslip_details.py | Python | agpl-3.0 | 1,644 | 0.00365 | #-*- coding:utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2011 OpenERP SA (<http://openerp.com>). All Rights Reserved
#
# This program is free software: you can redistribute it and/or modify
# it under th... | d, name, context):
super(payslip_details_report_in, self).__init__(cr, uid, name, context)
self.localcontext.update({
'get_details_by_rule_category': self.get_details_by_rule_category,
})
report_sxw.report_sxw('report.paylip.details.in', 'hr.pa | yslip', 'l10n_in_hr_payroll/report/report_payslip_details.rml', parser=payslip_details_report_in)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
feredean/cs313 | notes/7_puzzle.py | Python | mit | 2,458 | 0.004882 | """
UNIT 2: Logic Puzzle
You will write code to solve the following logic puzzle:
1. The person who arrived on Wednesday bought the laptop.
2. The programmer is not Wilkes.
3. Of the programmer and the person who bought the droid,
one is Wilkes and the other is Hamming.
4. The writer is not Minsky.
5. Neither Knu... | mon)
if (Wilkes == monday and laptop == writer) or (laptop == monday and Wilkes == writer)
if iphone == tuesd | ay or tablet == tuesday
)
result = []
print order
for pers in range(5):
result.append(people[order[pers]])
return result
print logic_puzzle() |
jason-weirather/IDP-fusion-release-1 | bin/Bfile.py | Python | apache-2.0 | 4,958 | 0.015934 | #!/usr/bin/python
import sys
import os
from numpy import *
from scipy import stats
if len(sys.argv) >= 4 :
ref_filename = sys.argv[1]
tag_filename =sys.argv[2]
Npt = int(sys.argv[3])
Nbin = int(sys.argv[4])
else:
print("usage: ~/3seq/bin/exp_len_density.py multiexon_refFlat.txt_positive_known_inta... | ls[:Npt]
else:
result.extend(right_iso_ls)
result.extend(left_iso_ls[:Npt-len_right_iso_ls])
return result
n = len(result)
while len(result)<Npt:
if r_left_L < r_right_L:
while r_left_L < r_right_L and len(result)<Npt:
... | result.extend(left_iso_ls)
left_index -= 1
left_L = len_ls[left_index]
if left_L > smallnum:
left_iso_ls =len_dt[left_L]
r_left_L = L - left_L
else:
while r_left_L >= r_right_L and len(result)<Npt:
r... |
N3MIS15/maraschino-webcam | maraschino/tools.py | Python | mit | 8,552 | 0.00573 | # -*- coding: utf-8 -*-
"""Util functions for different things. For example: format time or bytesize correct."""
from flask import request, Response
from functools import wraps
from jinja2.filters import FILTERS
import os
import maraschino
from maraschino import app, logger
from maraschino.models import Setting, XbmcS... | eturn | filelist
def convert_bytes(bytes, with_extension=True):
bytes = float(bytes)
if bytes >= 1099511627776:
terabytes = bytes / 1099511627776
size = '%.2f' % terabytes
extension = 'TB'
elif bytes >= 1073741824:
gigabytes = bytes / 1073741824
size = '%.2f' % gigabytes
... |
hfaran/progressive | progressive/cursor.py | Python | mit | 1,718 | 0 | import os
from blessings import Terminal
class Cursor(object):
"""Common methods for cursor manipulation
:type term: NoneType|blessings.Terminal
:param term: Terminal instance; if not given, will be created by the class
"""
def __init__(self, term=None):
self.term = Terminal() if term ... | saved = False
def write(self, s):
"""Writes ``s`` to the terminal output stream
Writes can be disabled by setting the environment variable
`PROGRESSIVE_NOWRITE` to `'True'`
"""
should_write_s = os.getenv('PROGRESSIVE_NOWRITE') != "True"
if should_write_s:
... | True
def restore(self):
"""Restores cursor to the previously saved location
Cursor position will only be restored IF it was previously saved
by this instance (and not by any external force)
"""
if self._saved:
self.write(self.term.restore)
def flush(se... |
venetay/Photo-Competition | attachments/forms.py | Python | mit | 212 | 0.009434 | from mpc.settings import CATEGORY
from django import forms
class UploadPhotoForm(forms.Form):
photo_file = forms.FileField(label='Select | a file')
photo_category = forms.C | hoiceField(choices=CATEGORY)
|
cschnei3/forseti-security | tests/scanner/audit/data/__init__.py | Python | apache-2.0 | 610 | 0 | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# ht | tp://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 expr | ess or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Data for scanner unit tests."""
|
asif-mahmud/Pyramid-Apps | pethouse/alembic/versions/0c431867c679_pets_now_have_a_description.py | Python | gpl-2.0 | 659 | 0.007587 | """Pets now have a description
Revision ID: 0c431867c679
Revises: 5b1bdc1f3125
Create Date: 2016-11-07 18:36:25.912155
"""
from alembic import op
import sqlalchemy as sa
# revision identifi | ers, used by Alembic.
revision = '0c431867c679'
down_revision = '5b1bdc1f3125'
branch_labels = None
depends_on = None
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.add_column('pet', sa.Column('description', sa.Text(), nullable=False))
### end Alembic commands ###
def downg... | se adjust! ###
op.drop_column('pet', 'description')
### end Alembic commands ###
|
michaelrosejr/pyaos6 | netmiko/f5/__init__.py | Python | mit | 107 | 0 | from __fu | ture__ import unicode_literals
f | rom netmiko.f5.f5_ltm_ssh import F5LtmSSH
__all__ = ['F5LtmSSH']
|
rohitranjan1991/home-assistant | homeassistant/components/hassio/__init__.py | Python | mit | 23,541 | 0.000935 | """Support for Hass.io."""
from __future__ import annotations
import asyncio
from datetime import timedelta
import logging
import os
from typing import Any, NamedTuple
import voluptuous as vol
from homeassistant.auth.const import GROUP_ID_ADMIN
from homeassistant.components import panel_custom, persistent_notificati... | "hassio_os_info"
DATA_SUPERVISOR_INFO | = "hassio_supervisor_info"
DATA_ADDONS_STATS = "hassio_addons_stats"
HASSIO_UPDATE_INTERVAL = timedelta(minutes=5)
ADDONS_COORDINATOR = "hassio_addons_coordinator"
SERVICE_ADDON_START = "addon_start"
SERVICE_ADDON_STOP = "addon_stop"
SERVICE_ADDON_RESTART = "addon_restart"
SERVICE_ADDON_UPDATE = "addon_update"
SERVI... |
JohanComparat/pySU | spm/bin_SMF/smf_plot.py | Python | cc0-1.0 | 15,194 | 0.025536 | import astropy.cosmology as co
aa=co.Planck15
import astropy.io.fits as fits
import matplotlib
import matplotlib
matplotlib.rcParams['agg.path.chunksize'] = 2000000
matplotlib.rcParams.update({'font.size': 12})
matplotlib.use('Agg')
import matplotlib.pyplot as p
import numpy as n
import os
import sys
# global cosmo ... | ghts)[0]
xx = (mbins[1:] + mbins[:-1])/2.
return xx, NW, NN**(-0.5)*NW
def plotMF_raw(prefix="Chabrier_ELODIE_"):
deep2_sel, deep2_m, deep2_w, deep2_o2, deep2_o3, deep2_hb = get_basic_stat(deep2, 'ZBEST', 'ZQUALITY', 'DEEP2', 3., prefix)
#vvdsD_sel, vvdsD_m, vvdsD_w, vvdsD_o2, vvdsD_o3, vvdsD_hb = get_... | , 2., prefix)
#vvdsW_sel, vvdsW_m, vvdsW_w, vvdsW_o2, vvdsW_o3, vvdsW_hb = get_basic_stat(vvdsW, 'Z', 'ZFLAGS', 'VVDS Wide', 2., prefix)
#vipers_sel, vipers_m, vipers_w, vipers_o2, vipers_o3, vipers_hb = get_basic_stat(vipers, 'zspec', 'zflg', 'VIPERS', 1., prefix)
lbins = n.arange(40.5,44,0.25)
x_lum ... |
rohandavidg/CONCORD-VCF | bin/do_logging.py | Python | mit | 668 | 0.001497 | #!/dlmp/sandbox/cgslIS/rohan/Python-2.7.11/python
"""
setting up logging
"""
import logging
import time
import datetime
def main(filename):
logger = configure_logger(filename)
def configure_logger(filename):
| """
s | etting up logging
"""
logger = logging.getLogger(filename)
logger.setLevel(logging.DEBUG)
handler = logging.FileHandler(time.strftime(filename+"-%Y%m%d.log"))
handler.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s'\t'%(name)s'\t'%(levelname)s'\t'%(message)s")
handler.setF... |
ffmmjj/desafio-dados-2016 | data_preparation_pipeline/run_all_data_tasks.py | Python | apache-2.0 | 356 | 0.005618 | import luigi |
from preprocess_data import ScaleDirectorFeatureValues, ScaleTeacherFeatureValues
from split_data import SplitAvgSchoolData, SplitOutstandingSchoolData
class AllDataTasks(luigi.WrapperTask):
def requires(self):
return SplitAvgSchoolData(), SplitOutstan | dingSchoolData(), ScaleTeacherFeatureValues(), ScaleDirectorFeatureValues()
|
nicostephan/pypuf | pypuf/experiments/experimenter.py | Python | gpl-3.0 | 1,942 | 0.00206 | import multiprocessing
import logging
class Experimenter(object):
"""
Coordinated, parallel execution of Experiments with logging.
"""
def __init__(self, log_name, experiments, cpu_limit=2**16):
"""
:param experiments: A list of pypuf.experiments.experiment.base.Experiment
:pa... | ler(stream_handler)
# Setup parallel execution l | imit
self.cpu_limit = min(cpu_limit, multiprocessing.cpu_count())
self.semaphore = multiprocessing.BoundedSemaphore(self.cpu_limit)
def run(self):
"""
Runs all experiments.
"""
jobs = []
for exp in self.experiments:
# define experiment process
... |
while519/SME | WN/WN_TransE.py | Python | bsd-3-clause | 604 | 0.006623 | #! /usr/bin/python
from WN_exp import *
from WN_evaluation import *
if theano.config.fl | oatX == 'float32':
sys.stderr.write("""WARNING: Detected floatX=float32 in the configuration.
This might result in NaN in embeddings after several epochs.
""")
launch(op='TransE', dataset='WN', simfn='L1' | , ndim=20, nhid=20, marge=2., lremb=0.01, lrparam=1.,
nbatches=100, totepochs=1000, test_all=10, neval=1000, savepath='WN_TransE',
datapath='../data/', Nent=40961, Nsyn=40943, Nrel=18)
print "\n##### EVALUATION #####\n"
RankingEval(datapath='../data/', loadmodel='WN_TransE/best_valid_model.pkl')
|
car3oon/saleor | saleor/userprofile/models.py | Python | bsd-3-clause | 5,495 | 0.000182 | from __future__ import unicode_literals
from django.contrib.auth.models import (
AbstractBaseUser, BaseUserManager, PermissionsMixin)
from django.db import models
from django.forms.models import model_to_dict
from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible
from djang... | return '%s - %s' % | (self.company_name, self.full_name)
return self.full_name
def __repr__(self):
return (
'Address(first_name=%r, last_name=%r, company_name=%r, '
'street_address_1=%r, street_address_2=%r, city=%r, '
'postal_code=%r, country=%r, country_area=%r, phone=%r)' % (
... |
alexmilowski/python-hadoop-rest-api | pyox/apps/tracker/api.py | Python | apache-2.0 | 22,821 | 0.034836 | from flask import Blueprint, g, current_app, request, Response, jsonify, copy_current_request_context
import json
import functools
import sys
import traceback
import logging
from redis import Redis
from time import sleep
from uuid import uuid4
from io import StringIO
from datetime import datetime
from pyox.apps.tracke... |
}
def error_respon | se(status_code,message,**kwargs):
obj = {'message':message,'status_code':status_code}
for name in kwargs:
obj[name] = kwargs[name]
headers = nocache_headers()
if status_code==401:
headers['WWW-Authenticate'] = 'Basic realm="KNOX Credentials"'
return Response(status=status_code,response=json.d... |
damsonn/django-docker-compose | proj/settings/__init__.py | Python | mit | 211 | 0 | """ Settings for proj """
from .base imp | ort *
try:
from .local import *
except ImportError as exc:
exc.args = tuple(
['%s (did you rename settings/local-dist.py?)' % exc.args[0]])
raise exc
| |
gaberger/pybvc | samples/sampleopenflow/demos/demo8.py | Python | bsd-3-clause | 7,431 | 0.004979 | #!/usr/bin/python
# Copyright (c) 2015, BROCADE COMMUNICATIONS SYSTEMS, INC
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright n... | ddress
# Ethernet Destination Address
# IPv4 Source Address
# IPv4 Destination Address
# IP Protocol Number
# IP DSCP
# | Input Port
match = Match()
match.set_eth_type(eth_type)
match.set_eth_src(eth_src)
match.set_eth_dst(eth_dst)
match.set_ipv4_src(ipv4_src)
match.set_ipv4_dst(ipv4_dst)
match.set_ip_proto(ip_proto)
match.set_ip_dscp(ip_dscp)
match.set_in_port(input_port)
flow_entry.add_... |
stonelake/pyoptimization | pyopt/discrete/randomsearch.py | Python | apache-2.0 | 6,894 | 0.002756 | __author__ = "Alex Baranov"
from inequalities import chernikov as c
from permutations import *
import numpy as np
def find_minimum(goal_func,
constraints_system,
combinatorial_set,
add_constraints=True,
series_count=3,
e... | :
"""
Checks whether the point is the solution for a given constraints system.
"""
a = np.array(system)
|
# get the left part
left = a[:, :-1] * point
left = sum(left.T)
# get the right part
right = (-1) * a[:, -1]
return np.all(left <= right)
if __name__ == '__main__':
s = [[1, -2, 3, 0], [-4, 1, 1, 2]]
func = (-1, 1, 2)
pset = PermutationSet((1, 2, 3))
point, func_... |
ffledgling/Senbonzakura | senbonzakura/frontend/api.py | Python | mpl-2.0 | 10,807 | 0.006107 | #from flask import Flask, request, Response
import argparse
import ConfigParser
import flask
import logging
import os
import shutil
import sys
import tempfile
import time
import senbonzakura.backend.core as core
import senbonzakura.cache.cache as cache
import senbonzakura.database.db as db
import senbonzakura.backend.... | tifier)
partial = dbo.lookup(identifier=identifier)
except oddity.DBError:
logging.warning('Record lookup for identifier %s failed' % identifier)
resp = flask.Response("{'result':'partial does not exist'}", status=404)
else:
logging.debug('Record ID: %s' % identifier)
st... | if status == db.status_code['COMPLETED']:
logging.info('Record found, status: COMPLETED')
# Lookup DB and return blob
# We'll want to stream the data to the client eventually, right now,
# we can just throw it at the client just like that.
# See -- http://sta... |
edisonlz/fruit | web_project/base/site-packages/south/db/oracle.py | Python | apache-2.0 | 12,431 | 0.005712 | import os.path
import sys
import re
import warnings
import cx_Oracle
from django.db import connection, models
from django.db.backends.util import truncate_name
from django.core.management.color import no_style
from django.db.models.fields import NOT_PROVIDED
from django.db.utils import DatabaseError
# I... | )s DEFAULT %(default)s;'
add_co | lumn_string = 'ALTER TABLE %s ADD %s;'
delete_column_string = 'ALTER TABLE %s DROP COLUMN %s;'
add_constraint_string = 'ALTER TABLE %(table_name)s ADD CONSTRAINT %(constraint)s %(clause)s'
allows_combined_alters = False
has_booleans = False
constraints_dict = {
... |
DinoV/PTVS | Python/Templates/Samples/ProjectTemplates/Python/Samples/PollsDjango/app/views.py | Python | apache-2.0 | 3,472 | 0.004032 | """
Definition of views.
"""
from app.models import Choice, Poll
from datetime import datetime
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from django.http import HttpRequest, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from dja... | pp/details.html', {
'title': 'Poll',
'year': datetime.now().year,
'poll': poll,
'error_message': "Please make a selection.",
})
else:
selected_choice.votes += 1
selected_choice.save()
return HttpResponseRedirect(reverse('app:results', args=... | polls."""
samples_path = path.join(path.dirname(__file__), 'samples.json')
with open(samples_path, 'r') as samples_file:
samples_polls = json.load(samples_file)
for sample_poll in samples_polls:
poll = Poll()
poll.text = sample_poll['text']
poll.pub_date = timezone.now()
... |
practo/r5d4 | r5d4/publisher.py | Python | mit | 1,023 | 0 | from __future__ import absolute_import
from werkzeug.exceptions import ServiceUnavailable, NotFound
from r5d4.flask_redis import get_conf_db
def publish_transaction(channel, tr_type, payload):
conf_db = get_conf_db()
if tr_type not in ["insert", "delete"]:
raise ValueError("Unknown transaction type", ... | pe + '", '
' "payload" : ' + payload +
'}'
)
if listened != subsc | ribed:
raise ServiceUnavailable((
"Subscription-Listened mismatch",
"Listened count = %d doesn't match Subscribed count = %d" % (
listened,
subscribed
)
))
|
ashang/calibre | setup/installer/linux/__init__.py | Python | gpl-3.0 | 792 | 0.006313 | #!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import with_statement
__license__ = 'GPL v3'
__copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.n | et>'
__docformat__ = 'restructuredtext en'
from setup.installer import VMInstaller
from setup import Command
class Linux32(VMInstaller):
description = 'Build 32bit linux binary installer'
INSTALLER_EXT = 'txz'
VM_NAME = 'linux32-build'
| FREEZE_COMMAND = 'linux_freeze'
FREEZE_TEMPLATE = 'python -OO setup.py {freeze_command}'
class Linux64(Linux32):
description = 'Build 64bit linux binary installer'
VM_NAME = 'linux64-build'
IS_64_BIT = True
class Linux(Command):
description = 'Build linux binary installers'
sub_command... |
mikewrock/phd_backup_full | src/wrock/vs060/scripts/moveit_canceler.py | Python | apache-2.0 | 1,094 | 0.008227 | #!/usr/bin/env python
import rospy
import os
import roslib
roslib.load_manifest("denso_pendant_publisher")
roslib.load_manifest("actionlib_msgs")
import denso_pendant_publisher.msg
import std_msgs.msg
import actionlib_msgs.msg
rospy.init_node("moveit_canceler")
g_runnable = True
g_prev_status = None
def pendantC... | = False
# here we should send cancel
cancel = actionlib_msgs.msg.GoalID()
cancel.id = ""
cancel_pub.publish(cancel)
rospy.loginfo("cancel")
g_prev_status = msg
sub = rospy.Subscriber("/denso_pendant_publisher/status", denso_pendant_publ | isher.msg.PendantStatus, pendantCB)
cancel_pub = rospy.Publisher("/arm_controller/follow_joint_trajectory/cancel", actionlib_msgs.msg.GoalID);
# cancel_pub = rospy.Publisher("/move_group/cancel", actionlib_msgs.msg.GoalID);
rospy.spin()
|
belokop/indico_bare | indico/modules/events/timetable/controllers/legacy.py | Python | gpl-3.0 | 26,827 | 0.0041 | # This file is part of Indico.
# Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (a... | event_new.get_session(request.args['session_id'])
| if not self.session:
raise NotFound
def _process(self):
defaults = self._get_form_defaults(location_parent=self.session)
form = SessionBlockEntryForm(obj=defaults, **self._get_form_params())
if form.validate_on_submit():
with track_time_changes(auto_extend=T... |
DarkLotus/OakCore | tools/esptool.py | Python | lgpl-2.1 | 28,767 | 0.011506 | #!/usr/bin/env python
#
# ESP8266 ROM Bootloader Utility
# https://github.com/themadinventor/esptool
#
# Copyright (C) 2014 Fredrik Ahlberg
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; eith... | 100
while retries > 0:
(op_ret, val, body) = self.receive_response()
if op is None or op_ret == op:
return val, body # valid response received
retries = retries - 1
raise FatalError("Response doesn't match request")
""" Receive a response to a c... | # Read header of response and parse
if self._port.read(1) != '\xc0':
raise FatalError('Invalid head of packet')
hdr = self.read(8)
(resp, op_ret, len_ret, val) = struct.unpack('<BBHI', hdr)
if resp != 0x01:
raise FatalError('Invalid response 0x%02x" to comm... |
FrankSalad/django-memcache-status | memcache_status/tests/__init__.py | Python | bsd-3-clause | 24 | 0.041667 | f | rom test_adm | in import * |
joelchelliah/diy-lisp | tests/test_provided_code.py | Python | bsd-3-clause | 2,580 | 0.001163 | # -*- coding: utf-8 -*-
from no | se.tools import assert_equals, assert_raises_regexp, assert_raises
from diylang.parser import unparse, find_matching_paren
from diylang.types import DiyLangError
"""
This module contains a few tests for the code provided for part 1.
All tests here should already pass, and should be of no concern to
you as a workshop ... | ching_paren():
source = "(foo (bar) '(this ((is)) quoted))"
assert_equals(32, find_matching_paren(source, 0))
assert_equals(9, find_matching_paren(source, 5))
def test_find_matching_empty_parens():
assert_equals(1, find_matching_paren("()", 0))
def test_find_matching_paren_throws_exception_on_bad_in... |
arhik/nupic | examples/opf/experiments/spatial_classification/scalar_1/description.py | Python | agpl-3.0 | 2,144 | 0.004664 | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2013, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This progra... | ',
'w': 21
},
'classification': {
'classifierOnly': True,
'clipInput': True,
'fieldname': u'classification',
'maxval': 50.0,
'minval': 0.0,
'n': 600,
'name': u'classification',
'type': 'ScalarEncoder',
'... | = importBaseDescription('../base/description.py', config)
locals().update(mod.__dict__)
|
elielprado/ESOF | Programa em Python/Esof Python/Login.py | Python | gpl-3.0 | 3,192 | 0.001255 | # -*- coding: utf-8 -*-
from DataBase import *
from Professor import *
from Aluno import *
from Cadastro import *
class Login:
def logInAluno(self, username, senha):
connect.execute('SELECT * FROM alunos WHERE nome="%s" AND senha="%s"' % (username, senha))
row = connect.fetchone()
if row is... | == 3:
prof.acompanharDesempenho()
elif opt == 4:
cad = Cadastro()
| username = raw_input('User: ')
senha = raw_input('Senha: ')
cad.cadastrarAluno(username, senha, pEscola, pName)
elif opt == 5:
print('\nCadastrar professor:\n')
username = raw_input('nome: ')
sen... |
Snuggert/moda | project/app/__init__.py | Python | mit | 1,446 | 0.000692 | from flask import Flask, jsonify, request
from btree import Tree
from asteval_wrapper import Script
# Startup stuff
app = Flask(__name__)
app.config.from_object('config')
# Jinja initialization to use PyJade
app.jinja_env.add_extension('pyjade.ext.jinja.PyJadeExtension') |
# Global jinja functions
app.jinja_env.globals.update(str=str)
app.jinja_env.globals.update(enumerate=enumerate)
app.jinja_env.globals.update(len=len)
app.jinja_env.globals.update(int=int)
app.jinja_env.globals.update(getattr=getattr)
app.jinja_env.globals.update(hasattr=hasattr)
app.jinja_env.globals.update(isinstan... | globals.update(zip=zip)
# Import routes
from app import single, multiple
app.register_blueprint(single.bp)
app.register_blueprint(multiple.bp)
@app.route('/compact/', methods=['GET'])
def compact():
Tree.from_file().compact()
return jsonify(success='compacted')
@app.route('/map/', methods=['POST'])
def ma... |
lispc/Paddle | python/paddle/v2/framework/tests/test_scale_and_identity_op.py | Python | apache-2.0 | 1,273 | 0 | import unittest
from op_test_util import OpTestMeta
from gradient_checker import GradientChecker, create_op
import numpy as np
from paddle.v2.framework.op import Operator
class IdentityTest(unittest.TestCase):
__metaclass__ = OpTestMeta
def setUp(self):
self.type = "identity"
self.inputs = {'... | self.check_grad(op, inputs, set("X"), "Out")
class ScaleTest(unittest.TestCase):
__metaclass__ = OpTestMeta
def setUp(self):
self.type = "scale"
self.inputs = {'X': np.random.random((32, 784)).astype("float32")}
self.attrs = {'scale': -2.3}
| self.outputs = {'Out': self.inputs['X'] * self.attrs['scale']}
class ScaleGradTest(GradientChecker):
def test_normal(self):
op = Operator("scale", X="X", Out="Out", scale=3.2)
self.check_grad(op,
{"X": np.random.random((10, 10)).astype("float32")},
... |
lhfei/spark-in-action | spark-3.x/src/main/python/mllib/pca_rowmatrix_example.py | Python | apache-2.0 | 1,712 | 0.000584 | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... | omponents.
projected = mat.multiply(pc)
# $example off$
collected = projected.ro | ws.collect()
print("Projected Row Matrix of principal component:")
for vector in collected:
print(vector)
sc.stop()
|
Enyruas/Kitux | setup.py | Python | apache-2.0 | 2,354 | 0.012319 | import os
from setuptools import setup
README = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='cpdir',
version='0.1',
packages=['sellrobots'... | 'License :: OSI Approved :: BSD License', # example license
'Operating System :: OS Independent',
'Programming Language :: Python',
... | 'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
... |
Dylan-halls/Network-Exploitation-Toolkit | Unpacking/DNS.py | Python | mit | 1,603 | 0.027449 | from scapy.all import *
from termcolor import colored
def pkthandler(pkt):
try:
ip = pkt[IP]
except IndexError:
pass
try:
src = ip.src
dst = ip.dst
except UnboundLocalError:
pass
if pkt.haslayer(DNS):
dns = pkt[DNS]
query = dns[DNSQR]
qtype = dnsqtypes.g... | print(" ")
print(" \033[1;36mSource IP:\033[00m | {} \033[1;36mDestination IP:\033[00m {}".format(src, dst))
print(" \033[1;36mDomain: \033[00m {}".format(query.qname))
print(" \033[1;36mQuery Type \033[00m {}".format(qtype))
print(" \033[1;36mId:\033[00m {}".format(dns.id))
print(" \033[1;36mOpcode: \033[00m {}".format(dns.opcode))
... |
evensonbryan/yocto-autobuilder | lib/python2.7/site-packages/sqlalchemy_migrate-0.6-py2.6.egg/migrate/versioning/shell.py | Python | gpl-2.0 | 6,390 | 0.001721 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""The migrate command-line tool."""
import sys
import inspect
import logging
from optparse import OptionParser, BadOptionError
from migrate.versioning import api, exceptions
from migrate.versioning.config import *
from migrate.versioning.util import asbool
alias = dic... | some_option as command line option
:param disable_logging: Let migrate configure logging
:type disable_logging: bool
"""
argv = argv or list(sys.argv[1:])
commands = list(api.__all__)
commands.sort()
usage = """%%prog COMMAND ...
Available commands:
%s
Enter "%%prog help ... | % '\n\t'.join(["%s - %s" % (command.ljust(28), api.command_desc.get(command)) for command in commands])
parser = PassiveOptionParser(usage=usage)
parser.add_option("-d", "--debug",
action="store_true",
dest="debug",
default=False,
... |
jrg365/gpytorch | gpytorch/functions/rbf_covariance.py | Python | mit | 1,186 | 0.004216 | import torch
class RBFCovariance(torch.autograd.Function):
@staticmethod
def forward(ctx, x1, x2, lengthscale, sq_dist_func):
if any(ctx.needs_input_grad[:2]):
raise RuntimeError("RBFCovariance cannot compute gradients with " "respect to x1 and x2")
if lengthscale.size(-1) > 1:
... | ad else unitless_sq_dist
covar_mat = unitless_sq_dist_.div_(-2.0).exp_()
if needs_grad:
d_output_d_input = unitless_sq_dist.mul_(covar_mat).div_(lengthscale)
ctx.save_for_backward(d_output_d_input)
return covar_mat
@staticmethod
def backward(ctx, grad_output):
... | cale_grad, None
|
dflemin3/ICgen | backup03/calc_velocity.py | Python | mit | 6,220 | 0.01254 | # -*- coding: utf-8 -*-
"""
Created on Wed Apr 9 15:39:28 2014
@author: ibackus
"""
import numpy as np
import pynbody
SimArray = pynbody.array.SimArray
import isaac
import subprocess
import os
import glob
import time
def v_xy(f, param, changbin=None, nr=50, min_per_bin=100):
"""
Attempts to calculate the... | H
command = 'charmrun ++local ' + changb | in + ' +gas -n 0 ' + p_name
p = subprocess.Popen(command.split(), stdout=subprocess.PIPE)
while p.poll() is None:
time.sleep(0.1)
# Load accelerations
acc_name = f_prefix + '.000000.acc2'
a_total = isaac.load_acc(acc_name)
# Clean-up
for fname in glob... |
mlperf/training_results_v0.5 | v0.5.0/google/research_v3.32/gnmt-tpuv3-32/code/gnmt/model/t2t/tensor2tensor/bin/t2t_trainer_test.py | Python | apache-2.0 | 1,357 | 0.002948 | # coding=utf-8
# Copyright 2018 The Tensor2Tensor Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable... |
class TrainerTest(tf.test.TestCase):
@classmethod
def setUpClass(cls):
trainer_lib_test.TrainerLibTest.setUpClass()
def testTrain(self):
FLAGS.problem = "tiny_algo"
FLAGS.model = "transformer"
FLAGS.hparams_set = "tran | sformer_tiny"
FLAGS.train_steps = 1
FLAGS.eval_steps = 1
FLAGS.output_dir = tf.test.get_temp_dir()
FLAGS.data_dir = tf.test.get_temp_dir()
t2t_trainer.main(None)
if __name__ == "__main__":
tf.test.main()
|
josenavas/qiime | scripts/count_seqs.py | Python | gpl-2.0 | 3,211 | 0.001246 | #!/usr/bin/env python
# File created on 29 May 2011
from __future__ import division
__author__ = "Greg Caporaso"
__copyright__ = "Copyright 2011, The QIIME project"
__credits__ = ["Greg Caporaso", "Jose Antonio Navas Molina"]
__license__ = "GPL"
__version__ = "1.9.1-dev"
__maintainer__ = "Greg Caporaso"
__email__ = "g... | ript_info['required_options'] = [
make_option('-i', '--input_fps', type='existing_filepaths' | ,
help='the input filepaths (comma-separated)'),
]
script_info['optional_options'] = [
# Example optional option
make_option('-o', '--output_fp', type="new_filepath",
help='the output filepath [default: write to stdout]'),
make_option('--suppress_errors', action='store_true',... |
jonguan/cmpe275-proj1-windrose | run_reduce.py | Python | mit | 242 | 0.020661 | import sys
import windrosebin
for x in sys.argv:
print x
pr | int type(sys.argv)
windrosebin.allocate()
windrosebin.check(sys.argv[1],sys.argv[2],len(sys.arg | v))
windrosebin.calc(sys.argv[1],sys.argv[3],len(sys.argv))
windrosebin.printLines() |
xmnlab/pywim | docs/conf.py | Python | mit | 8,369 | 0.005377 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# pywim documentation build configuration file, created by
# sphinx-quickstart on Tue Jul 9 22:26:36 2013.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autog... | coding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'PyWIM'
copyright = u"2016, Ivan Ogasawara"
# The version info for the project you're documenting, acts as replacement
# for |version| and |release|, also used in various other places througho... | cluding alpha/beta/rc tags.
release = pywim.__version__
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to
# some non-false value, then it is used:
#today = ''
# Else, ... |
dperpeet/cockpit | test/verify/storagelib.py | Python | lgpl-2.1 | 12,449 | 0.002089 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# This file is part of Cockpit.
#
# Copyright (C) 2015 Red Hat, Inc.
#
# Cockpit 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.1 of the Lice... | else:
self.mount_root = "/run/media"
def inode(s | elf, f):
return self.machine.execute("stat -L '%s' -c %%i" % f)
def retry(self, setup, check, teardown):
b = self.browser
b.arm_timeout()
while True:
if setup:
setup()
if check():
break
if teardown:
... |
att-comdev/drydock | drydock_provisioner/cli/task/actions.py | Python | apache-2.0 | 5,257 | 0.000761 | # Copyright 2017 AT&T Intellectual Property. All other 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... | task
task_id = task.get('task_id')
while True:
time.sleep(self.poll_interval)
task = self.api_client.get_task(task_id=task_id)
if task.status in [TaskStatus.Complete, TaskStatus.Terminated]:
| return task
|
Jeff-Wang93/vent | vent/core/network_tap/ncontrol/prestart.py | Python | apache-2.0 | 230 | 0 | #!/usr/bin/env python3
import docker
def pull_ncapture():
d_c | lient = docker.from_env()
d_client.images.pull('cyb | erreboot/vent-ncapture', tag='master')
if __name__ == '__main__': # pragma: no cover
pull_ncapture()
|
chrxr/wagtail | wagtail/contrib/wagtailapi/utils.py | Python | bsd-3-clause | 807 | 0.001239 | from __future__ import absolute_import, unicode_literals
from django.conf import settings
from django.utils.six.moves.urllib.parse import urlparse
from wagtail.wagtailcore.models import Page
class BadRequestError(Exception):
pass
def get_base_url(request=None):
base_url = getattr(setting | s, 'WAGTAILAPI_BASE_URL', request.site.root_url if request else None)
if base_url:
# We only want the scheme and netloc
base_url_parsed = urlparse(base_url)
return base_url_parsed.scheme + '://' + base_url_parsed.netloc
def get_full_url(request, path):
base_url = get_base_url(request... | .root_page, inclusive=True)
return pages
|
mortbauer/openfoam-extend-Breeder-other-scripting-PyFoam | examples/compactOutput.py | Python | gpl-2.0 | 1,329 | 0.017306 | #! /usr/bin/python
""" Runs an OpenFOAM solver and captures the output. Extracts information
about the linear solvers (initial residual) and outputs it in a "Fluentish"
way (one line per timestep).Called:
compactOutput.py interFoam . damBreak
"""
import re,sys
from PyFoam.LogAnalysis.LogLineAnalyzer import LogLineA... | No Iterations (.+)$")
def doAnalysis(self,line):
m=self.exp.match(line)
if m!=None:
name=m.groups()[1]
resid=m.groups()[2]
time=self.getTime()
if time!=self.told:
self.told=time
print "\n t = %6g : " % ( float(time) ),... | oundingLogAnalyzer.__init__(self)
self.addAnalyzer("Compact",CompactLineAnalyzer())
run=AnalyzedRunner(CompactAnalyzer(),silent=True)
run.start()
|
aldian/tensorflow | tensorflow/python/keras/engine/training_v1.py | Python | apache-2.0 | 138,190 | 0.005065 | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | flow.python.types import core
from tensorflow.python.util import deprecation
from tensorflow.python.util import nest
from tensorflow.python.util import tf_inspect
from tensorflow. | python.util.compat import collections_abc
try:
from scipy.sparse import issparse # pylint: disable=g-import-not-at-top
except ImportError:
issparse = None
class Model(training_lib.Model):
"""`Model` groups layers into an object with training and inference features.
There are two ways to instantiate a `Mode... |
taedori81/shoop | shoop/admin/modules/contacts/views/list.py | Python | agpl-3.0 | 2,134 | 0.001406 | # -*- coding: utf-8 -*-
# This file is part of Shoop.
#
# Copyright (c) 2012-2015, Shoop Ltd. All rights reserved.
#
# This source code is li | censed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import unicode_literals
from django.db.models import Count
from django.utils.translation import ugettext as _
from shoop.admin.utils.picotable import (
Column, RangeFilter, TextFilter, true_or_fa... | s.views import PicotableListView
from shoop.core.models import CompanyContact, Contact, PersonContact
class ContactListView(PicotableListView):
model = Contact
columns = [
Column("name", _(u"Name"), linked=True, filter_config=TextFilter()),
Column("type", _(u"Type"), display="get_type_display"... |
NeuroanatomyAndConnectivity/pipelines | src/clustering/clustering/create_input_surface.py | Python | mit | 833 | 0.010804 | import nibabel as nb
from nipype.utils.filemanip import split_filename
sxfmout = nb.load('/scr/schweiz1/Data/results/sxfmout/_session_session1/_subject_id_9630905/_fwhm_0/_hemi_lh/lh.afni_corr_rest_roi_dtype_t | shift_detrended_regfilt_gms_filt.fsaverage4.nii').get_data()
##from mask_surface import MaskSurface
data = nb.load(sxfmout).get_data()
origdata = data.shape
affine = nb.spatialimages.SpatialImage.get_affine(nb.load(sxfmout))
data.resize(data.shape[0]*data.shape[2],1,1,data.shape[3])
mask = np.zeros_like(data)
if hemi ... | resize(origdata)
maskImg = nb.Nifti1Image(mask, affine)
_, base, _ = split_filename(sxfmout)
nb.save(maskImg, os.path.abspath(base + '_mask.nii'))
|
p12tic/awn-extras | applets/maintained/calendar/calendarprefs.py | Python | gpl-2.0 | 9,376 | 0.00288 | #!/usr/bin/python
# -*- coding: iso-8859-15 -*-
#
# Copyright (c) 2007 Mike (mosburger) Desjardins <desjardinsmike@gmail.com>
# Please do not email the above person for support. The
# email address is only there for license/copyright purposes.
#
# This is the preferences dialog for a calendar applet for Avant W... | ance_index = \
self.applet.get_int_config('cal_appearance_index')
clock_appearance_index = \
self.applet.get_int_config('clock_appearance_index')
self.twelve_hour_checkbox = gtk.CheckButton(_("Twelve Hour Clock"))
self.twelve_hour_checkbox.set_active(applet.twelve_hour_c... | .pack_start(self.twelve_hour_checkbox, True, False, 0)
vbox.pack_start(hbox0, False, False, 0)
# self.blink_checkbox = gtk.CheckButton(_("Blinking Colon"))
# if applet.blinky_colon == True:
# self.blink_checkbox.set_active(True)
# else:
# self.blink_checkbox.set_activ... |
Endika/website-addons | website_sale_stock_status/__openerp__.py | Python | lgpl-3.0 | 408 | 0.017157 | {
'name' : 'Product status at website shop',
'version' : '1.0.1',
'author' : 'IT-Projects LLC, Ivan Yelizariev',
'license': 'GPL-3',
'category' : 'Sale',
'website | ' : 'https://yelizariev.github.io',
'depends' : ['website_sale | ', 'stock'],
'data':[
'website_sale_stock_status_views.xml',
'website_sale_stock_status_data.xml',
],
'installable': True
}
|
igor-rangel7l/igorrangel.repository | plugin.video.SportsDevil/service/oscrypto/_win/_kernel32_cffi.py | Python | gpl-2.0 | 1,029 | 0.000972 | # coding: utf-8
f | rom __future__ import unicode_literals, division, absolute_import, print_function
from .._ffi import FFIEngineError, register_ffi
from .._types import str_cls
from ..errors import LibraryNotFoundError
try:
import cffi
except (ImportError):
raise FFIEngineError('Error importing cffi')
__all__ = [
'get_e... | = (0, 9):
ffi.set_unicode(True)
ffi.cdef("""
typedef long long LARGE_INTEGER;
BOOL QueryPerformanceCounter(LARGE_INTEGER *lpPerformanceCount);
typedef struct _FILETIME {
DWORD dwLowDateTime;
DWORD dwHighDateTime;
} FILETIME;
void GetSystemTimeAsFileTime(FILETIME *lpSystemTimeAs... |
rienafairefr/pynYNAB | docs/conf.py | Python | mit | 4,876 | 0.000205 | # -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/stable/config
# -- Path setup ------------------------------------------------------------... | for documents that don't match any pattern) are
# defined by theme itself. Builtin themes are using these templates by
# default: ``['localtoc.html', 'relations.html', 'sourcelink.html',
# 'searchbox.html']``.
#
# html_s | idebars = {}
# -- Options for HTMLHelp output ---------------------------------------------
# Output file base name for HTML help builder.
htmlhelp_basename = 'pynYNABdoc'
# -- Options for LaTeX output ------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4pa... |
rogerthat-platform/rogerthat-backend | src/facebook/version.py | Python | apache-2.0 | 625 | 0 | #!/usr/bin/env python
#
# Copyright 2015 Mobolic
#
# 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
#
# | ERROR: type should be string, got " https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See " | the
# License for the specific language governing permissions and limitations
# under the License.
__version__ = "3.0.0-alpha"
|
rad08d/rssreader_flask | flask_rss/rssapp/rss.py | Python | apache-2.0 | 4,065 | 0.005412 | import sys
import urllib2
import HTMLParser
import xml.etree.ElementTree as ET
from logging import getLogger
class Rss(object):
"""A class for handling RSS feeds"""
def __init__(self,url=None):
if not url:
self.url = ''
self.articles = ''
else:
self.url = url
... | self.is_start_sp = True
elif self.is_start_p and tag == 'a':
| self.is_start_p = True
elif self.is_start_p and tag == 'img' or self.is_start_sp and tag == 'img':
for attr in attrs:
if attr[0] == 'src':
self.img_links.append(attr[1])
else:
self.is_start_p = False
self.is_start_sp = False
... |
gangadhar-kadam/sapphire_app | patches/january_2013/update_closed_on.py | Python | agpl-3.0 | 1,386 | 0.034632 | # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd.
# License: GNU General Public License v3. See license.txt
import webnotes
def execute():
webnotes.reload_doc("core", "doctype", "docfield")
webnotes.reload_doc("support", "doctype", "support_ticket")
# customer issue resolved_by should be Profile
if webnote... | eation %s limit 1""" % ("%s", sort_order),
support_ticket)
return tmp and tmp[0][0] or None
# update in support ticket
webnotes.conn.auto_commit_on_many_writes = True
for st in webnotes.conn.sql("""select name, modified, status fro | m
`tabSupport Ticket`""", as_dict=1):
webnotes.conn.sql("""update `tabSupport Ticket` set first_responded_on=%s where
name=%s""", (get_communication_time(st.name) or st.modified, st.name))
if st.status=="Closed":
webnotes.conn.sql("""update `tabSupport Ticket` set resolution_date=%s where
name=%s"... |
stoman/CompetitiveProgramming | problems/pythonsetdifference/submissions/accepted/stefan.py | Python | mit | 214 | 0.004673 | #!/usr/bin/e | nv python3
#Author: Stefan Toman
if __name__ == '__main__':
n = int(input())
a = set(map(int, input().split()))
m = int(input())
| b = set(map(int, input().split()))
print(len(a-b))
|
Astrophilic/Algorithms_Example | AStarSearch/python/astar.py | Python | apache-2.0 | 5,569 | 0 | # Copyright (c) 2008 Mikael Lind
#
# 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 without limitation the rights
# to use, copy, modify, merge, publish, distrib... | ion.
# Instead we mark the neighbor as invalid and | make an
# updated copy of it.
neighbor[VALID] = False
nodes[neighbor_pos] = neighbor = neighbor[:]
neighbor[F] = neighbor_g + neighbor[H]
neighbor[NUM] = nums.next()
neighbor[G] = neighbor_g
... |
FrodeSolheim/fs-uae-launcher | fsgamesys/platforms/zxspectrum/zxspectrummamedriver.py | Python | gpl-2.0 | 37 | 0 | clas | s ZXSpectrumMameDriver:
| pass
|
pytroll/satpy | satpy/tests/reader_tests/test_safe_sar_l2_ocn.py | Python | gpl-3.0 | 3,887 | 0.002058 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2019 Satpy developers
#
# This file is part of satpy.
#
# satpy 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... | e reader believe all abstract methods have been implemented.
self.reader = SAFENC(filename='dummy',
filename_info={'start_time': 0,
'end_time': 0,
'fstart_time': 0,
... | 'polarization': 'vv'},
filetype_info={})
def test_init(self):
"""Test reader initialization."""
self.assertEqual(self.reader.start_time, 0)
self.assertEqual(self.reader.end_time, 0)
self.assertEqual(self.reader... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.