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 |
|---|---|---|---|---|---|---|---|---|
khchine5/atelier | atelier/sphinxconf/dirtables.py | Python | bsd-2-clause | 6,048 | 0.001819 | # -*- coding: utf-8 -*-
# Copyright 2016 by Luc Saffre.
# License: BSD, see LICENSE for more details.
"""Defines the :rst:dir:`directory`, :rst:dir:`tickets_table` and
:rst:dir:`entry_intro` directives.
.. rst:directive:: directory
Inserts a table containing three columns 'title', 'author' and | 'date',
and one row for each `.rst` file found in this directory (except for
the calling file).
.. rst:directive:: tickets_table
This is used e.g. to build
http://lino-framework.org/tickets
.. rst:directive:: entry_intro
This doesn't yet work unfortunately.
"""
from __future__ import print_function
from __future... | from builtins import object
import logging
logger = logging.getLogger(__name__)
from os.path import abspath, dirname, join
from docutils.parsers.rst import directives
from sphinx.util import docname_join
from sphinx.util.matching import patfilter
from atelier import rstgen
from .insert_input import InsertInputDi... |
mathspace/django-two-factor-auth | two_factor/management/commands/two_factor_disable.py | Python | mit | 998 | 0 | from django.core.management.base import BaseCommand, CommandError
try:
from django.contrib.auth import get_user_model
except ImportError:
from django.contrib.auth.models import User
else:
User | = get_user_model()
from django_otp import devices_for_user
class Command(BaseCommand):
"""
Command for disabling two-factor authentication for certain users.
The command accepts any number of usernames, and will remove all OTP
devices for those users | .
Example usage::
manage.py disable bouke steve
"""
args = '<username username ...>'
help = 'Disables two-factor authentication for the given users'
def handle(self, *args, **options):
for username in args:
try:
user = User.objects.get_by_natural_key(us... |
russell/fairy-slipper | fairy_slipper/cmd/wadl_to_swagger.py | Python | apache-2.0 | 37,276 | 0.000054 | # Copyright (c) 2015 Russell Sim <[email protected]>
#
# 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 ... | eapi:string': 'string',
'imageapi:imagestatus': 'string',
'imageapi:uuid': 'string',
'csapi:uuid': 'string',
'csapi:serverforcreate': 'string',
'csapi:blockdevicemapping': 'string',
'csapi:serverswithonlyidsnameslinks': 'string',
'csapi:serverstatus': 'string',
'csapi:dict': 'object',
... | items
# "tags": {
# "type": "array",
# "items": {
# "type": "string"
'xsd:list': 'array',
'array': 'array',
}
FORMAT_MAP = {
'xsd:anyURI': 'uri',
'xsd:datetime': 'date-time',
'xsd:ip': 'ipv4',
'regexp': 'regexp',
'xsd:timestamp': 'timestamp',
}
STYLE_MAP = {
... |
UK992/servo | components/script/dom/bindings/codegen/parser/tests/test_error_lineno.py | Python | mpl-2.0 | 907 | 0.005513 | import WebIDL
def WebIDLTest(parser, harness):
# Check that error messages put the '^' in the right place.
threw = False
input = """\
// This is a comment.
interface Foo {
};
/* This is also a comment. */
interface ?"""
try:
parser.parse(input)
results = parser | .finish()
except WebIDL.WebIDLError as e:
threw = True
lines = str(e).split('\n')
harness.check(len(lines), 3, 'Expected number of lines in error message')
harness.ok(lines[0].endswith('line 6:10'), 'First line of error should end with "line 6:10", but was "%s".' % lines[0])
... | ' * (len('interface ?') - 1) + '^',
'Correct column pointer in error message.')
harness.ok(threw, "Should have thrown.")
|
srinath-chakravarthy/ovito | tests/scripts/test_suite/import_file.py | Python | gpl-3.0 | 1,809 | 0.007739 | import ovito
from ovito.io import import_file
test_data_dir = "../../files/"
node1 = import_file(test_data_dir + "LAMMPS/animation.dump.gz")
assert(len(ovito.dataset.scene_nodes) == 0)
import_file(test_data_dir + "CFG/fcc_coherent_twin.0.cfg")
import_file(test_data_dir + "CFG/shear.void.120.cfg")
import_file(test_dat... | columns = ["Particle Identifier", "Particle Type", "Position.X", "Position.Y", "Position.Z", "ExtraProperty"])
assert False
except RuntimeError:
pass
node = import_file(test_data_dir + "LAMMPS/animation*.dump")
assert(ovito.dataset.anim.last_frame == 0)
node = import_file(test_data_dir + "LAMMPS/animation*.... | True)
assert(ovito.dataset.anim.last_frame == 10)
|
adriano-arce/Interview-Problems | Array-Problems/Find-Equilibrium/Find-Equilibrium.py | Python | mit | 778 | 0.002571 | def find_equilibrium(arr):
left_sum = 0
right_sum = sum(arr[1:]) # List slicing copies references to each value.
if left_sum | == right_sum and arr: # Don't return 0 if arr is empty.
return 0
for i in range(1, len(arr)):
left_sum += arr[i - 1]
right_sum -= arr[i]
if left_sum == right_sum:
return i
return -1
def main():
test_arrs = [
[],
[-7, 1, 5, 2, -4, 3, 0],
... | 6, -5, -8, 9]
]
for i, test_arr in enumerate(test_arrs):
print("Test Case #{}: {}".format(i + 1, test_arr))
print(" Equilibrium Index: {}".format(find_equilibrium(test_arr)))
if __name__ == "__main__":
main() |
mgood7123/UPM | Sources/PyOpenGL-Demo-3.0.1b1/PyOpenGL-Demo/GLUT/shader_test.py | Python | gpl-3.0 | 5,525 | 0.012489 | #! /usr/bin/env python
'''Tests rendering using shader objects from core GL or extensions
Uses the:
Lighthouse 3D Tutorial toon shader
http://www.lighthouse3d.com/opengl/glsl/index.php?toon2
By way of:
http://www.pygame.org/wiki/GLSLExample
'''
import OpenGL
OpenGL.ERROR_ON_COPY = True
from OpenGL.G... |
# Uncomment this line to get full screen.
#glutFullScreen()
# When we are doing nothing, redraw the scene.
glutIdleFunc(DrawGLScene)
# Register the function called when our window is resized.
glutReshapeFunc(ReSizeGLScene)
# Register the function called when the keyboard is press... | k off the main to get it rolling.
if __name__ == "__main__":
print "Hit ESC key to quit."
main()
|
drufat/pybindcpp | pybindcpp/api.py | Python | gpl-3.0 | 790 | 0.002532 | import ctypes as ct
class Box(ct.Structure):
_fields_ = [
('tid', ct.c_size_t),
('ptr', ct.c_void_p),
('deleter', ct.CFUNCTYPE(None, ct.c_void_p)),
]
class TypeSystem(ct.Structure):
_fields_ = [
('type_counter', ct.c_size_t),
('add_type', ct.CFUNCTYPE(ct.c_size_t... |
('add_box', ct.CFUNCT | YPE(None, ct.py_object, ct.c_char_p, Box)),
('import_func', ct.CFUNCTYPE(None, ct.c_char_p, ct.c_char_p, ct.c_size_t, ct.POINTER(Box))),
]
|
erinspace/osf.io | osf_tests/test_guid_auto_include.py | Python | apache-2.0 | 7,146 | 0.001539 | from django.utils import timezone
import pytest
from django_bulk_update.helper import bulk_update
from django.db.models import DateTimeField
from osf_tests.factories import UserFactory, PreprintFactory, NodeFactory
@pytest.mark.django_db
class TestGuidAutoInclude:
guid_factories = [
UserFactory,
... | for x in wut:
assert len(x) == 1, 'Too many keys in values'
@pytest.mark.parametrize('Factory', guid_factories)
@pytest.mark.django_assert_num_queries
def test_exclude(self, Factory, django_assert_num_queries):
objects = []
for _ in range(0, 5):
objects... | jects[0]._meta.get_fields() if isinstance(x, DateTimeField)][0]
except IndexError:
pytest.skip('Thing doesn\'t have a DateTimeField')
with django_assert_num_queries(1):
wut = Factory._meta.model.objects.exclude(**{dtfield: timezone.now()})
for x in wut:
... |
foua-pps/atrain_match | atrain_match/utils/runutils.py | Python | gpl-3.0 | 9,928 | 0.000806 | # -*- coding: utf-8 -*-
# Copyright (c) 2009-2019 atrain_match developers
#
# This file is part of atrain_match.
#
# atrain_match 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... | datetime, orbit
def parse_scenesfile_v2014(filename):
"""
Parse pps file =S_NWC_CT_{satellite}_{orbit}_%Y%m%dT%H%M%S?Z_*.h5 or .nc
"""
from datetime import datet | ime
import re
filename = os.path.basename(filename)
if not filename:
raise ValueError("No file %r" % filename)
match = re.match(r"S_NWC_.+_([^_]+)_\d+_(\d+)T(\d\d\d\d\d\d).+", filename)
if not match:
raise ValueError("Couldn't parse pps file %r" % filename)
satname, date_s, time_... |
danielyule/naya | naya/json.py | Python | mit | 24,396 | 0.001435 | from io import StringIO
class TOKEN_TYPE:
OPERATOR = 0
STRING = 1
NUMBER = 2
BOOLEAN = 3
NULL = 4
class __TOKENIZER_STATE:
WHITESPACE = 0
INTEGER_0 = 1
INTEGER_SIGN = 2
INTEGER = 3
INTEGER_EXP = 4
INTEGER_EXP_0 = 5
FLOATING_POINT_0 = 6
FLOATING_POINT = 8
STRIN... | == "e" or char == 'E':
next_state = __TOKENIZER_STATE.INTEGER_EXP_0
add_char = True
elif is_delimiter(char):
next_state = __TOKENIZER_STATE.WHITESPACE
completed = True
now_token = (TOKEN_TYPE.NUMBER, 0)
advance ... | llowed by a '.' or a 'e'. Got '{0}'".format(char))
elif state == __TOKENIZER_STATE.INTEGER_SIGN:
if char == "0":
next_state = __TOKENIZER_STATE.INTEGER_0
add_char = True
elif char in "123456789":
next_state = __TOKENIZER_STATE.INTEGER
... |
valentin-krasontovitsch/ansible | lib/ansible/playbook/__init__.py | Python | gpl-3.0 | 4,859 | 0.00247 | # (c) 2012-2014, Michael DeHaan <[email protected]>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) an... | pb._load_playbook_data(file_name=file_name, variable_manager=variable_manager)
return pb
def _load_playbook_data(self, file_name, variable_manager, vars=None):
if os.path.isabs(file_name):
self._basedir = os.path.dirname(file_name)
else:
| self._basedir = os.path.normpath(os.path.join(self._basedir, os.path.dirname(file_name)))
# set the loaders basedir
cur_basedir = self._loader.get_basedir()
self._loader.set_basedir(self._basedir)
self._file_name = file_name
# dynamically load any plugins from the playbook d... |
bioidiap/bob.ip.facedetect | doc/plot/detect_faces_tinyface.py | Python | gpl-3.0 | 1,124 | 0.00089 | import matplotlib.pyplot as plt
from bob.io.base import load
from bob.io.base.test_utils import datafile
from bob.io.image import imshow
from bob.ip.facedetect.tinyface import TinyFacesDetector
from matplotlib.patches import Rectangle
# load colored test image
color_image = load(datafile("test_image_mult | i_face.png", "bob.ip.facedetect"))
is_mxnet_available = True
try:
import mxnet
except Exception:
is_mxnet_available = False
if not is_mxnet_available:
imshow(color_image)
else:
# detect all faces
detector = TinyFacesDetector()
detections = detector.detect(color_image)
imshow(color_image)
... | ght = annotations["bottomright"]
size = bottomright[0] - topleft[0], bottomright[1] - topleft[1]
# draw bounding boxes
plt.gca().add_patch(
Rectangle(
topleft[::-1],
size[1],
size[0],
edgecolor="b",
facec... |
ultmaster/eoj3 | backstage/server/views.py | Python | mit | 8,676 | 0.010489 | import logging
import multiprocessing
import threading
import traceback
from datetime import datetime
from django.contrib import messages
from django.core.cache import cache
from django.db import transaction
from django.db.models import F
from django.shortcuts import HttpResponseRedirect, reverse, get_object_or_404
fr... | ssion_count'] = Submission.objects.filter(status=SubmissionStatus.SYSTEM_ERROR).count()
return data
class ServerRefresh(BaseBackstageMixin, View):
def post(self, request, pk):
server = Server.objects.get(pk=pk)
server.serverproblemstatus_set.all().delete()
messages.success(request, "Server status h... | = Server.objects.get(pk=pk)
server.enabled = not server.enabled
server.save(update_fields=['enabled'])
try:
Semaphore(get_redis_connection("judge")).reset()
except:
pass
return HttpResponseRedirect(reverse('backstage:server'))
class ServerDelete(BaseBackstageMixin, View):
def post(... |
pkmital/CADL | session-5/libs/celeb_vaegan.py | Python | apache-2.0 | 2,738 | 0.001096 | """
Creative Applications of Deep Learning w/ Tensorflow.
Kadenze, Inc.
Copyright Parag K. Mital, June 2016.
"""
import numpy as np
import tensorflow as tf
from tensorflow.python.platform import gfile
from .utils import download
from skimage.transform import resize as imresize
def celeb_vaegan_download():
"""Down... | 'to environment. e.g.:\n' +
'PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=python ipython\n' +
'See here for info: ' +
'https://github.com/tensorflow/tensorflow/iss | ues/582')
net = {
'graph_def': graph_def,
'labels': labels,
'attributes': attributes,
'preprocess': preprocess,
}
return net
def preprocess(img, crop_factor=0.8):
"""Replicate the preprocessing we did on the VAE/GAN.
This model used a crop_factor of 0.8 and crop si... |
viniciuschiele/flask-webapi | tests/test_status.py | Python | mit | 1,233 | 0 | from flask_webapi import status
from unittest import TestCase
class TestStatus(TestCase):
def test_is_informational(self):
self.assertFalse(status.is_informational(99))
self.assertFalse(status.is_informational(200))
for i in range(100, 199):
self.assertTrue(status.is_informati... | ssertFals | e(status.is_server_error(600))
for i in range(500, 599):
self.assertTrue(status.is_server_error(i))
|
anton-golubkov/Garland | src/ipf/ipftype/ipfsmoothingtype.py | Python | lgpl-2.1 | 1,155 | 0.012121 | #------------------------------------------------------------- | ------------------
# Copyright (c) 2011 Anton Golubkov.
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the GNU Lesser Public License v2.1
# which accompanies this distribution, and is available at
# http://www.gnu.or | g/licenses/old-licenses/gpl-2.0.html
#
# Contributors:
# Anton Golubkov - initial API and implementation
#-------------------------------------------------------------------------------
# -*- coding: utf-8 -*-
import ipfdicttype
import cv
class IPFSmoothingType(ipfdicttype.IPFDictType):
""" Smoothing type di... |
makaimc/txt2react | core/models.py | Python | mit | 292 | 0.003425 | from django.contrib.auth.models import User
from django.db import m | odels
from .utils import create_slug
class BaseModel(models.Model):
created = models.DateTimeField(auto_now_add=True)
last_updated = models.DateTimeField(auto_now=True)
class Meta( | ):
abstract = True
|
tectronics/passwdmanager | setup.py | Python | gpl-3.0 | 280 | 0.035714 | from distutils.core import setup
import glob
import py2exe
setup(windows=[{"script":"passwdManager.py","icon_resources": | [(1,"icons/pm.ico")]},"upgrade.py"],
data_files=[("data",glob.glob("data/*.*")),
| ("icons",glob.glob("icons/*.png"))]
)
|
IAlwaysBeCoding/mrq | tests/fixtures/config-retry1.py | Python | mit | 105 | 0 |
TASKS = {
"tests.tasks.general.Retry": {
"max_retries" | : 1,
"retry_del | ay": 1
}
}
|
zhreshold/mxnet | tests/python/unittest/common.py | Python | apache-2.0 | 13,748 | 0.003782 | # 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 u... | np.random.seed()
seed = np.random.randint(0, np.ii | nfo(np.int32).max)
logger = default_logger()
logger.debug('Setting np, mx and python random seeds = %s', seed)
np.random.seed(seed)
mx.random.seed(seed)
random.seed(seed)
yield
finally:
# Reinstate prior state of np.random and other generators
np.rando... |
atodorov/anaconda | pyanaconda/modules/payloads/source/hmc/initialization.py | Python | gpl-2.0 | 2,546 | 0.000786 | #
# Copyright (C) 2020 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be ... | lic License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or repli... | from pyanaconda.anaconda_loggers import get_module_logger
from pyanaconda.core.util import execWithRedirect
from pyanaconda.payload.utils import unmount
from pyanaconda.modules.common.errors.payload import SourceSetupError
from pyanaconda.modules.common.task import Task
log = get_module_logger(__name__)
__all__ = ["T... |
DBuildService/atomic-reactor | tests/plugins/test_store_metadata.py | Python | bsd-3-clause | 28,357 | 0.000846 | """
Copyright (c) 2015, 2019 Red Hat, Inc
All rights reserved.
This software may be modified and distributed under the terms
of the BSD license. See the LICENSE file for details.
"""
import os
import json
from datetime import datetime, timedelta
from copy import deepcopy
from textwrap import dedent
from flexmock imp... | PLUGIN_VERIFY_MEDIA_KEY,
| PLUGIN_FETCH_SOURCES_KEY)
from atomic_reactor.build import BuildResult
from atomic_reactor.inner import DockerBuildWorkflow
from atomic_reactor.plugin import ExitPluginsRunner, PluginFailedException
from atomic_reactor.plugins.pre_add_help import AddHelpPlugin
from atomic_reactor.plugins.post_rpm... |
renestvs/data_structure_project | data_structure/first_bim/data_structures.py | Python | mit | 4,324 | 0.007863 | from math import floor
from pip._vendor.requests.packages.urllib3.connectionpool import xrange
__author__ = 'rene_'
v = []
aux = []
size = []
############################################################
####################### HeapSort #########################
#####################################################... | v[j] = aux
aux = v[i+1]
v[i+1] = v[right]
v[right] = aux
return i+1
############################################################
###################### MergeSort #########################
############################################################
def mergesort(i, f):
print("====MergeSort====")... |
merge(i, m, f)
print("====merge01====")
print("i,m,f", i, m, f)
print("====MergeSort02====")
mergesort(m+1, f)
print("====merge02====")
print("i,m,f", i,m,f)
def merge(i, m, f):
i1 = i
i2 = i
i3 = m+1
while i2 <= m and i3 <= f:
if v[i2] ... |
davidwhogg/LensTractor | LensTractor.py | Python | gpl-2.0 | 14,549 | 0.017871 | #!/usr/bin/env python
# ============================================================================
'''
This file is part of the lenstractor project.
Copyright 2012 David W. Hogg (NYU) and Phil Marshall (Oxford).
'''
# ============================================================================
if __name__ == '__main... | nts, latex:
matplotlib.rc('font',**{'family':'serif', 'serif':['TimesNewRoman'], 'size':18.0})
matplotlib.rc('text', usetex=True)
import os
import logging
im | port numpy as np
import pyfits
import time
import string
from astrometry.util import util
import tractor
import lenstractor
# ============================================================================
def main():
"""
NAME
LensTractor.py
PURPOSE
Run the Tractor on a deck of single object cutout... |
BhallaLab/moose-examples | tutorials/ChemicalOscillators/repressillator.py | Python | gpl-2.0 | 3,118 | 0.018281 | #########################################################################
## This program is part of 'MOOSE', the
## Messaging Object Oriented Simulation Environment.
## Copyright (C) 2014 Upinder S. Bhalla. and NCBS
## It is made available under the terms of the
## GNU Lesser General Public License version 2... | g' )
fig = plt.figure( figsize=(12, 10 ) )
png = fig.add_subplot( 211 )
imgplot = plt.imshow( img )
ax = fig.add_subplot( 212 )
x = moose.wildcardFind( '/model/#graphs/conc#/#' )
plt.ylabel( 'Conc (mM)' )
plt.xlabel( 'Time (seconds)' )
for x in moose.wildcardFind( '/model/#graphs/conc#/#... | .arange( 0, x.vector.size, 1 ) * dt
pylab.plot( t, x.vector, label=x.name )
pylab.legend()
pylab.show()
# Run the 'main' if this script is executed standalone.
if __name__ == '__main__':
main()
|
ajaniv/django-core-models | django_core_models/core/urls.py | Python | mit | 908 | 0 | """
.. module:: django_core_models.core.urls
:synopsis: django_core_models core application urls module
django_core_models *core* application urls module.
"""
from __future__ import absolute_import
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^annotations/$',
views.Anno... | s_view(),
name='annotation-list'),
url(r'^annotations/(?P<pk>[0-9]+)/$',
views.AnnotationDetail.as_view(),
name='annotation-detail'),
url(r'^categories/$', views.CategoryList.as_view(),
name='category-list'),
url(r'^categories/(?P<pk>[0-9]+)/$',
views.CategoryDetail.... | r'^currencies/$',
views.CurrencyList.as_view(),
name='currency-list'),
url(r'^currencies/(?P<pk>[0-9]+)/$',
views.CurrencyDetail.as_view(),
name='currency-detail'),
]
|
sunqm/pyscf | examples/grad/12-excited_state_casscf_grad.py | Python | apache-2.0 | 3,547 | 0.015788 | #!/usr/bin/env python
#
# Author: Qiming Sun <[email protected]>
#
'''
Analytical nuclear gradients of CASCI excited state.
'''
from pyscf import gto
from pyscf import scf
from pyscf import mcscf
from pyscf import lib
import inspect
mol = gto.M(
atom = [
["O" , (0. , 0. , 0.)],
[1 , (0. ... | excited state')
print(g3_nosymm)
# The active orbitals | here should be O atom 2py (b2) and 2pz (a1) and
# two OH antibonding orbitals (a1 and b1). The four states in order
# are singlet A1, triplet B2, singlet B2, and triplet A1.
#
# Use gradients scanner.
#
# Note the returned gradients are based on atomic unit.
#
g_scanner = mc.nuc_grad_method().as_scanner(state=2)
e2_no... |
NESCent/dplace | dplace_app/tests/test_api.py | Python | mit | 14,228 | 0.003093 | # coding: utf8
from __future__ import unicode_literals
import json
from django.core.urlresolvers import reverse
from rest_framework import status
from rest_framework.test import APITestCase
from clldutils.path import Path
from dplace_app.models import *
from dplace_app.load import load
from dplace_app.loader import s... | ects.get(name='Rainfall').id))})
self.assertIsInstance(response, dict)
self.assertIn('min', response)
self.assertIn('max', response)
def test_cont_variable(self):
response = self.client.get('cont_variable')
self.assertEqual(response.status_code, 404)
response = self.... | iable', {'query': '[]'})
self.assertEqual(response.status_code, 404)
response = self.get_json(
'cont_variable',
{'query': json.dumps(dict(bf_id=Variable.objects.get(label='2').id))})
self.assertIsInstance(response, list)
def test_geo_api(self):
response = sel... |
vladan-m/ggrc-core | src/ggrc_workflows/migrations/versions/20140725082539_468290d5494f_add_sort_index_to_task_groups_and_cycle_.py | Python | apache-2.0 | 2,077 | 0.008666 |
"""Add sort index to task_groups and cycle_task_groups
Revision ID: 468290d5494f
Revises: 1f1ab1d371b6
Create Date: 2014-07-25 08:25:39.074611
"""
# revision identifiers, used by Alembic.
revision = '468290d5494f'
down_revision = '1f1ab1d371b6'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.sql imp... | table, column, select
def _set_sort_index(table_1, table_1_id, table_2):
connection = op.get_bind()
rows_1 = connection.execute(
select([table_1.c.id])
)
for row_1 in rows_1:
rows_2 = connection.execute(
select([table_2.c.id, table_2.c.sort_index])
.where(table_2.c[table_1_id] ==... | date()
.values(sort_index=str(current_index))
.where(table_2.c.id == row_2.id)
)
current_index = (current_index + max_index) / 2
def upgrade():
op.add_column('task_groups', sa.Column('sort_index',
sa.String(length=250), nullable=False))
op.add_column('cycle_task_gro... |
PyThaiNLP/pythainlp | pythainlp/util/keyboard.py | Python | apache-2.0 | 6,583 | 0 | # -*- coding: utf-8 -*-
"""
Functions related to keyboard layout.
"""
EN_TH_KEYB_PAIRS = {
"Z": "(",
"z": "ผ",
"X": ")",
"x": "ป",
"C": "ฉ",
"c": "แ",
"V": "ฮ",
"v": "อ",
"B": "\u0e3a", # พินทุ
"b": "\u0e34", # สระอุ
"N": "\u0e4c", # การันต์
"n": "\u0e37", # สระอือ
... | ", "ก", "ด", "เ", "้", "่", "า", "ส", "ว", "ง"],
["ผ", "ป", "แ", "อ", "ิ", "ื", "ท", "ม", "ใ", "ฝ"],
]
TIS_820_2531_MOD_SHIFT = [
["%", "+", "๑", "๒", "๓", "๔", "ู", "฿", "๕", "๖", "๗", "๘", "๙"],
["๐", "\"", "ฎ", "ฑ", "ธ", "ํ", "๊", "ณ", "ฯ", "ญ", "ฐ", ",", "ฅ"],
["ฤ", "ฆ", "ฏ", "โ", "ฌ", "็", | "๋", "ษ", "ศ", "ซ", "."],
["(", ")", "ฉ", "ฮ", "ฺ", "์", "?", "ฒ", "ฬ", "ฦ"],
]
def eng_to_thai(text: str) -> str:
"""
Corrects the given text that was incorrectly typed using English-US
Qwerty keyboard layout to the originally intended keyboard layout
that is the Thai Kedmanee keyboard.
:para... |
sserrot/champion_relationships | venv/Lib/site-packages/win32comext/shell/demos/servers/copy_hook.py | Python | mit | 2,881 | 0.009372 | # A sample shell copy hook.
# To demostrate:
# * Execute this script to register the context menu.
# * Open Windows Explorer
# * Attempt to move or copy a directory.
# * Note our hook's dialog is displayed.
import sys, os
import pythoncom
from win32com.shell import shell, shellcon
import win32gui
import win32con
impor... | sion.CopyHook"
| _reg_desc_ = "Python Sample Shell Extension (copy hook)"
_reg_clsid_ = "{1845b6ba-2bbd-4197-b930-46d8651497c1}"
_com_interfaces_ = [shell.IID_ICopyHook]
_public_methods_ = ["CopyCallBack"]
def CopyCallBack(self, hwnd, func, flags,
srcName, srcAttr, destName, destAttr):
... |
bigfootproject/pyostack | pyostack/metering.py | Python | apache-2.0 | 712 | 0.001404 | import ceilometerclient.client as clclient
import logging
log = logging.getLogger(__name__)
class Metering:
'''Wrapper for the OpenStack MEtering service (Ceilometer)'''
def __init__(self, conf):
creds = self._get_creds(conf)
self.ceilo = clclient.get_client(2, **creds)
def _get_creds(sel... | d['os_username'] = conf.get("environment", "OS_USERNAME")
d['os_password'] = conf.get("environment", "OS_PASSWORD")
d['os_auth_url'] = conf.get("environment", "OS_AUTH_URL")
| d['os_tenant_name'] = conf.get("environment", "OS_TENANT_NAME")
return d
def meter_list(self, query=None):
return self.ceilo.meters.list()
|
pradeeppanga/dcos-universe | docs/tutorial/helloworld.py | Python | apache-2.0 | 1,033 | 0.00484 | import time
import http.server
import os
HOST_NAME = '0.0.0.0' # Host name of the http server
# Gets the port number from $PORT0 environment variable
| PORT_NUMBER = int(os.environ['PORT0'])
class MyHandler(http.server.BaseHTTPRequestHandler):
def do_GET(s):
"""Respond to a GET request."""
s.send_response(200)
s.send_header("Content-type" | , "text/html")
s.end_headers()
s.wfile.write("<html><head><title>Time Server</title></head>".encode())
s.wfile.write("<body><p>The current time is {}</p>".format(time.asctime()).encode())
s.wfile.write("</body></html>".encode())
if __name__ == '__main__':
server_class = http.server.... |
javierLiarte/tdd-goat-python | lists/views.py | Python | gpl-2.0 | 687 | 0.021834 | from django.http import HttpResponse
from django.shortcuts import redirect, render
from lists.models import Item, List
# Create your views here.
def home_page(request):
return render(request, 'home.html')
def view_list(request, list_id):
list_ = List.objects.get(id=list_id)
return render(request, 'list.html', ... | e()
Item.objects.create(text=request.POST['item_text'], list=list_)
return redirect('/lists/%d/' % (list_.i | d))
def add_item(request, list_id):
list_ = List.objects.get(id=list_id)
Item.objects.create(text=request.POST['item_text'], list=list_)
return redirect('/lists/%d/' % (list_.id)) |
lwiss/Hackathon_Satellite_Imagery | FCN.py | Python | mit | 10,362 | 0.004053 | from __futur | e__ import print_function
import tensorflow as tf
import numpy as np
import TensorflowUtils as utils
import read_MITSceneParsingData as scene_parsing
import datetime
import BatchDatsetReader as dataset
from six.moves import xrange
import readAerialDataset
FLAGS = tf.flags.FLAGS
tf.flags.DEFINE_integer("batch_size", ... | )
tf.flags.DEFINE_string("logs_dir", "logs/", "path to logs directory")
tf.flags.DEFINE_string("data_dir", "data/", "path to dataset")
tf.flags.DEFINE_float("learning_rate", "1e-3", "Learning rate for Adam Optimizer")
tf.flags.DEFINE_string("model_dir", "Model_zoo/", "Path to vgg model mat")
tf.flags.DEFINE_bool('debug... |
stavinsky/lsshipper | lsshipper/reader_aio.py | Python | mit | 777 | 0 | import os
import aiofiles
async def get_line(name, offset=0, sep=b'\r\n', chunk_size=4096):
name = os.path.abspath(name)
async with a | iofiles.open(name, 'r+b') as f:
await f.seek(offset)
tmp_line = b""
chunk = await f.read(chunk_size)
while chunk:
if len(tmp_line):
chunk = tmp_line + chunk
tmp_line = b''
while chunk:
line, s, chunk = chunk.partitio... |
if s is sep:
offset = offset + len(line) + len(sep)
yield (line, offset)
if s is b'':
tmp_line = tmp_line + line
chunk = await f.read(chunk_size)
|
Lorze/recipe | Old_and_obsolete/startme.py | Python | mit | 5,028 | 0.044749 | #!/usr/bin/env python
import pyforms
from pyforms import BaseWidget
from pyforms.Controls import ControlText
from pyforms.Controls import ControlButton
from pyforms.Controls import ControlList
import subprocess
import codecs
import glob
import re
import sys
import os
#i think, i have a problem with t... | ns'))
self._button = ControlButton('Kompilieren')
self._set = ControlButton('Speichern')
self._allbutton = ControlButton('alle Kompilieren')
self._rebutton = ControlButton('reload')
self._newbutton = ControlButton('Rezept erstellen')
self._openbutton = ControlButton('open')
self._filelist = ControlList()
... | ', 'Kompilieren',' ']
self.sumtitle=[]
for name in files:
title =openfile(name)
persons = personnr(title)
comp = compil(title)
self.sumtitle.append(title)
self._filelist += [title, persons, comp]
#Define the button action
self._button.value = self.__buttonAction
self._allbutton.value = self._... |
EnEff-BIM/EnEffBIM-Framework | MapAPI/mapapi/molibs/MSL/Blocks/Sources/BooleanPulse.py | Python | mit | 694 | 0 | # -*- coding: utf-8 -*-
"""
Created on Wed Nov 25 12:10:45 2015
@author: pre
"""
import random
import mapapi.MapClasses as MapHierarchy
class Boolean | Pulse(MapHierarchy.MapComponent):
"""Representation of AixLib.Fluid.Movers.Pump
"""
def init_me(self):
self.target_location = "Modelica.Blocks.Sources.BooleanPulse"
self.target_name = "booleanPulse"+str(random.randint(1, 100))
self.width = self.add_parameter(name="width", value=50)
... | er(name="startTime", value=0)
self.y = self.add_connector(name='y', type='Boolean')
return True
|
JanlizWorldlet/FeelUOwn | src/base/utils.py | Python | mit | 1,039 | 0.000962 | # -*- coding:utf-8 -*-
import platform
imp | ort asyncio
import json
from base.logger import LOG
def singleton(cls, *args, **kw):
instances = {}
def _singleton(*args, **kw):
if cls not in instances:
instances[cls] = cls(*args, **kw)
return instances[cls]
return _singleton
def func_coroutine(func):
"""make the deco... | args, **kwargs):
LOG.debug("In func_coroutine: before call ")
LOG.debug("function name is : " + func.__name__)
APP_EVENT_LOOP = asyncio.get_event_loop()
APP_EVENT_LOOP.call_soon(func, *args)
LOG.debug("In func_coroutine: after call ")
return wrapper
def write_json_into_file... |
unicon-pte-ltd/funnel | funnel/testing.py | Python | apache-2.0 | 4,075 | 0.002209 | # -*- coding: utf-8 -*-
#
# Copyright 2013 Unicon Pte. Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... | ting import AsyncTestCase
try:
from unittest2 import TextT | estRunner
except ImportError:
from unittest import TextTestRunner
import types
HOST = '127.0.0.1'
class AsyncWorkerTestCase(AsyncTestCase):
def setUp(self):
super(AsyncWorkerTestCase, self).setUp()
self.publisher = self.get_publisher()
self.publisher.connect(host=HOST)
self.pub... |
caterinaurban/Lyra | src/lyra/unittests/numerical/interval/forward/indexing3/list_of_range1.py | Python | mpl-2.0 | 104 | 0.009615 |
L: List[in | t] = list(range(10))
# FINAL: L -> 0@[0, | 0], 1@[1, 1], 2@[2, 2], _@[3, 9]; len(L) -> [10, 10] |
baskiotisn/soccersimulator | soccersimulator/events.py | Python | gpl-2.0 | 1,862 | 0.004834 | # -*- coding: utf-8 -*-
class Events(object):
def __init__(self):
for e in self.__events__:
self.__getattr__(e)
def __getattr__(self, name):
if hasattr(self.__class__, '__events__'):
assert name in self.__class__.__events__, \
"Event '%s' is not declared... | ', 'end_round', 'end_match', 'is_ready','send_strategy')
def __iadd__(self, f):
for e in self:
try:
e += getattr(f, str(e))
except:
pass
return self
def __isub__(self, f):
for e in self:
try:
| while getattr(f, str(e)) in e.targets: e.targets.remove(getattr(f, str(e)))
except:
pass
return self
|
lgbouma/astrobase | astrobase/lcmodels/__init__.py | Python | mit | 763 | 0.002621 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# lcmodels - Waqas Bhatti ([email protected]) - Oc | t 2017
# License: MIT. See the LICENSE file for more details.
'''This contains various light curve models for variable stars. Useful for
first order fits to distinguish between variable types, and for generating these
variables' light curves for a recovery simulation.
- :py:mod:`astrobase.lcmodels.transits`: trapezoi... | od:`astrobase.lcmodels.flares`: stellar flare model from Pitkin+ 2014.
- :py:mod:`astrobase.lcmodels.sinusoidal`: sinusoidal light curve generation for
pulsating variables.
'''
|
DevicePilot/synth | synth/analysis/mergejson.py | Python | mit | 3,010 | 0.002658 | """
MERGEJSON - command-line utility
Given a set of .json files, this merges them in time order.
Each file must contain a JSON list of messages, of the form:
[
{ "$id" : 123, "$ts" : 456, "other" : "stuff" },
{ "$id" : 234, "$ts" : 567, "more" : "stuff" }
]
... | er message.
"""
#
#
# Copyright (c) 2019 DevicePilot Ltd.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Softwa | re"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyri... |
minimaxir/keras-cntk-docker | lstm_benchmark.py | Python | mit | 2,306 | 0.000434 | '''Compare LSTM implementations on the IMDB sentiment classification task.
implementation=0 preprocesses input to the LSTM which typically results in
faster computations at the expense of increased peak memory usage as the
preprocessed input must be kept in memory.
implementation=1 does away with the preprocessing, m... |
results = []
for mode in modes:
print('Testing mode: implementation={}'.f | ormat(mode))
model = Sequential()
model.add(Embedding(max_features, embedding_dim,
input_length=max_length))
model.add(Dropout(0.2))
model.add(LSTM(embedding_dim,
dropout=0.2,
recurrent_dropout=0.2,
implementation=mode))
... |
taylorhutchison/ShapefileReaderPy | ShapefileIndexReader.py | Python | mit | 1,778 | 0.004499 | """
This script exposes a class used to read the Shapefile Index format
used in conjunction with a shapefile. The Index file gives the record
number and content length for every record stored in the main shapefile.
This is useful if you need to extract | specific features from a shapefile
without reading the entire file.
How to use:
from ShapefileIndexReader import ShapefileIndex
shx = ShapefileIndex(Path/To/index.shx)
shx.read()
The 'shx' object will expose three properties
1) Path - the path given to the shapefile, if it exists
2) Offsets - an a... | d in the main shapefile
3) Lengths - an array of 16-bit word lengths for each record in the main shapefile
"""
import os
__author__ = 'Sean Taylor Hutchison'
__license__ = 'MIT'
__version__ = '0.1.0'
__maintainer__ = 'Sean Taylor Hutchison'
__email__ = '[email protected]'
__status__ = 'Development'
class... |
amaxwell/datatank_py | datatank_py/DTStructuredMesh2D.py | Python | bsd-3-clause | 4,176 | 0.010297 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# This software is under a BSD license. See LICENSE.txt for details.
from datatank_py.DTStructuredGrid2D import DTStructuredGrid2D, _squeeze2d
import numpy as np
class DTStructuredMesh2D(object):
"""2D structured mesh object.
This class corresponds to DataT... | ifferent time
values of a variable.
:param datafile: a :class:`datatank_py.DTDataFile.DTDataFile` open for writing
:param name: the mesh variable's name
:param grid_name: the grid name to be shared (will not be visible in DataTank)
:param time: the time value for this st... | a significant space savings in
a data file. It's not widely implemented, since it's not clear yet if this
is the best API.
"""
if grid_name not in datafile:
datafile.write_anonymous(self._grid, grid_name)
datafile.write_anonymous(self.__dt_type__(), "Seq_... |
xfleckx/BeMoBI_Tools | analytics/BeMoBI_PyAnalytics/BeMoBI_PyAnalytics.py | Python | mit | 682 | 0.013196 | import os
import pandas as pd
import seaborn as sns
dataDir = '..\\Test_Data\\'
pilotMarkerDataFile = 'Pilot.csv'
df = pd.read_csv( dataDir + '\\' + pilotMarkerDataFile,sep='\t', engine='python')
repr(df.head())
# TODO times per position
# plotting a heatmap http://stanford.edu/~mwaskom/software/seaborn/examples... | e(220, 10, as_cmap=True)
# Draw the heatmap with the mask and correct aspect ratio
#sns.heatmap(timesAtPositions, mask=mask, cmap=cmap, vmax=.3,
# square=True, xticklabels=5, yticklabels=5,
# | linewidths=.5, cbar_kws={"shrink": .5}, ax=ax) |
thenenadx/forseti-security | google/cloud/security/common/gcp_api/bigquery.py | Python | apache-2.0 | 4,496 | 0.000222 | # 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, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License... | nt
from google.cloud.security.common.util import log_util
# TODO: The next editor must remove this disable and correct issues.
# pylint: disable=missing-type-doc,missing-return-type-doc,missing-return-doc
FLAGS = flags.FLAGS
flags.DEFINE_integer('max_bigquery_api_calls_per_100_seconds', 17000,
... |
sander76/home-assistant | tests/components/template/test_select.py | Python | apache-2.0 | 8,099 | 0.00037 | """The tests for the Template select platform."""
import pytest
from homeassistant import setup
from homeassistant.components.input_select import (
ATTR_OPTION as INPUT_SELECT_ATTR_OPTION,
ATTR_OPTIONS as INPUT_SELECT_ATTR_OPTIONS,
DOMAIN | as INPUT_SELECT_DOMAIN,
SERVICE_SELECT_OPTION as INPUT_SELECT_SERVICE_SELECT_OPTION,
SERVICE_SET_OPTIONS,
)
from homeassistant.components.select.const import (
ATTR_OPTION as SELECT_ATTR_OPTION,
ATTR_OPTIONS as SELECT_ATTR_OPTIONS,
DOMAIN as SELECT_DOMAIN,
SERVICE_SELECT_OPTION as SELECT_SERVICE... | assistant.helpers.entity_registry import async_get
from tests.common import (
assert_setup_component,
async_capture_events,
async_mock_service,
)
_TEST_SELECT = "select.template_select"
# Represent for select's current_option
_OPTION_INPUT_SELECT = "input_select.option"
@pytest.fixture
def calls(hass):
... |
deliveryhero/lymph-sqlalchemy | lymph/sqlalchemy/utils.py | Python | apache-2.0 | 878 | 0 |
class BulkInsert(object):
"""
Usage:
user_insert = BulkInsert(session)
address_insert = BulkInsert(session, dependencies=[user_insert])
for user in users:
user_insert.add(user)
from address in user_addresses:
address_insert.add(address)
addres... |
def __init__(self, session, count=250, depe | ndencies=None):
self.session = session
self.count = count
self._objects = []
self.dependencies = dependencies or []
def add(self, obj):
self._objects.append(obj)
if len(self._objects) >= self.count:
self.flush()
def flush(self):
for dependenc... |
RoozbehFarhoodi/McNeuron | data_transforms.py | Python | mit | 6,699 | 0.000149 | """Collection of useful data transforms."""
# Imports
import numpy as np
from McNeuron import Neuron
import scipy
import scipy.linalg # SciPy Linear Algebra Library
from numpy.linalg import inv
def get_leaves(nodes, parents):
"""
Compute the list of leaf nodes.
Parameters
----------
nodes: li... | :
# Recalculate a | ll the leaves
leaves = get_leaves(nodes, parents)
if verbose:
print 'leaves', leaves
# Add the parent of the lowest numbered leaf to the sequence
leaf_idx = np.where(nodes == leaves[0])[0][0]
prufer.append(parents[leaf_idx])
if verbose:
print 'pru... |
callowayproject/django-snippets | snippets/models.py | Python | apache-2.0 | 321 | 0.012461 | from django.db import models
class Snippet(models.Model):
"""A text snippet. Not meant for use by anyone other than a designer"""
name = m | ode | ls.CharField(max_length=255)
snippet = models.TextField(blank=True)
class Meta:
pass
def __unicode__(self):
return self.snippet
|
Wei1234c/Elastic_Network_of_Things_with_MQTT_and_MicroPython | codes/node/asynch_result.py | Python | gpl-3.0 | 1,312 | 0.007622 | # coding: utf-8
import time
import config_mqtt
class Asynch_result:
def __init__(self, correlation_id, requests, yield_to):
self.correlation_id = correlation_id
self._requests_need_result = requests
self.yield_to = yield_to
def get(self, timeout = config_mq... | result = request.get('result')
# self._requests_need_result.pop(self.correlation_id)
return result
else:
if current_time - start_time > timeout: # timeout
# self._requests_need | _result.pop(self.correlation_id)
raise Exception('Timeout: no result returned for request with correlation_id {}'.format(self.correlation_id))
else:
self.yield_to()
else:
raise Exception('No such request for request with correlation... |
yu4u/age-gender-estimation | demo.py | Python | mit | 4,936 | 0.003039 | from pathlib import Path
import cv2
import dlib
import numpy as np
import argparse
from contextlib import contextmanager
from omegaconf import OmegaConf
from tensorflow.keras.utils import get_file
from src.factory import get_model
pretrained_model = "https://github.com/yu4u/age-gender-estimation/releases/download/v0.... | generator:
input_img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img_h, img_w, _ = np.shape(input_img)
# detect faces using dlib detector
detected = detector(input_img, 1)
faces = np.empty((len(dete | cted), img_size, img_size, 3))
if len(detected) > 0:
for i, d in enumerate(detected):
x1, y1, x2, y2, w, h = d.left(), d.top(), d.right() + 1, d.bottom() + 1, d.width(), d.height()
xw1 = max(int(x1 - margin * w), 0)
yw1 = max(int(y1 - margin * h), 0)
... |
MatthewJohn/vacker | vacker/media/__init__.py | Python | apache-2.0 | 1,105 | 0.000905 |
from bson.objectid import ObjectId
import datetime
import vacker.database
import vacker.config
class File(object):
def __init__(self, file_id, document=None):
self._id = file_id
self._document = self._get_document() if document is None else document
def _get_document(self):
pass
... | ):
return self._document['g_sha1'], self._document['g_sha512']
def delete(self):
database_connection = vacker.database.Database.get_database()
database_connection.media.remove({'_id': ObjectId(self.get_id())})
def _get_thumbnail_path(self):
return '{0}/{1}'.format(
... | '),
self._document['g_sha512'])
def get(self, attr, default_val=None):
return self._document.get(attr, default_val)
def get_thumbnail(self):
return self._get_thumbnail_path()
|
sputnick-dev/weboob | modules/allrecipes/module.py | Python | agpl-3.0 | 2,008 | 0 | # -*- coding: utf-8 -*-
# Copyright(C) 2013 Julien Veyssier
#
# This file is part of weboob.
#
# weboob is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your op... | weboob.capabilities.recipe import CapRecipe, Recipe
from weboob.tools.backend import Module
from .browser import AllrecipesBrowser
from urllib import quote_plus
__all__ = ['AllrecipesModule']
class AllrecipesModule(Module, CapRecipe):
NAME = 'allrecipes'
MAINT | AINER = u'Julien Veyssier'
EMAIL = '[email protected]'
VERSION = '1.1'
DESCRIPTION = u'Allrecipes English recipe website'
LICENSE = 'AGPLv3+'
BROWSER = AllrecipesBrowser
def get_recipe(self, id):
return self.browser.get_recipe(id)
def iter_recipes(self, pattern):
retu... |
camilonova/sentry | src/sentry/api/endpoints/team_groups_new.py | Python | bsd-3-clause | 1,628 | 0.001229 | from __future__ import absolute_import
from datetime import timedelta
from django.utils import timezone
from rest_framework.response import Response
from sentry.api.base import Endpoint
from sentry.api.permissions import assert_perm
from sentry.api.serializers import serialize
from sentry.models import Group, GroupSt... | 'minutes', 15))
limit = min(100, int(request.REQUEST.get('limit', 10)))
project_list = Project.objects.get_for_user(user=request.user, team=team)
project_dict = dict((p.id, p) for p in project_list)
cutoff = timedelta(minutes=minutes)
| cutoff_dt = timezone.now() - cutoff
group_list = list(Group.objects.filter(
project__in=project_dict.keys(),
status=GroupStatus.UNRESOLVED,
active_at__gte=cutoff_dt,
).extra(
select={'sort_value': 'score'},
).order_by('-score', '-first_seen')[:li... |
softlayer/softlayer-python | SoftLayer/CLI/block/access/password.py | Python | mit | 849 | 0.002356 | """Modifies a password for a volume's access"""
# :license: MIT, see LICENSE for more details.
import click
import SoftLayer
from SoftLayer.CLI import environment
@click.command()
@click.argument('access_id')
@click.option('--password', '-p', multiple=False, |
help='Password you want to set, this command will fail if the password is not strong')
@environment.pass_env
def cli(env, access_id, password):
"""Changes a password for a volume's access.
access id is the allowed_host_id from slcli block access-list
"""
block_manager = SoftLayer.BlockS... |
if result:
click.echo('Password updated for %s' % access_id)
else:
click.echo('FAILED updating password for %s' % access_id)
|
sjschmidt44/django-imager | imagersite/imager_images/migrations/0003_face.py | Python | mit | 822 | 0.002433 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('imager_images', '0002_auto_20150730_2342'),
]
operations = [
migrations.CreateModel(
name='Face',
fi... | ', serialize=False, auto_created=True, primary_key=True)),
('x', models.IntegerField()),
('y', models.IntegerField()),
('width', models.IntegerField()),
| ('height', models.IntegerField()),
('name', models.CharField(max_length=256)),
('photo', models.ForeignKey(related_name='faces', to='imager_images.Photos')),
],
),
]
|
mozilla/popcorn_maker | vendor-local/lib/python/mock.py | Python | bsd-3-clause | 73,348 | 0.001541 | # mock.py
# Test tools for mocking and patching.
# Copyright (C) 2007-2012 Michael Foord & the mock team
# E-mail | : fuzzyman AT voidspace DOT org DOT uk
# mock 0.8.0
# http://www.voidspace.org.uk/python/mock/
# Released subject to the BSD License
# Please see http://www.voidspace.org.uk/python/license.shtml
# Scripts maintained at http://www.voidspace.org.uk/python/index.shtml
# Comments, suggestions and bug reports welcome.
... |
'NonCallableMock',
'NonCallableMagicMock',
)
__version__ = '0.8.0'
import pprint
import sys
try:
import inspect
except ImportError:
# for alternative platforms that
# may not have inspect
inspect = None
try:
from functools import wraps
except ImportError:
# Python 2.4 compatibilit... |
poojavade/Genomics_Docker | Dockerfiles/gedlab-khmer-filter-abund/pymodules/python2.7/lib/python/nexus/__init__.py | Python | apache-2.0 | 56 | 0 | fro | m nexus.go_rest_client import GlobusOnlineRestClien | t
|
ppanczyk/ansible | lib/ansible/modules/source_control/git.py | Python | gpl-3.0 | 44,717 | 0.002236 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2012, Michael DeHaan <[email protected]>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '... | = '''
---
module: git
author:
- "Ansible Core Team"
- "Michael DeHaan"
version_added: "0.0.1"
short_description: Deploy software (or files) from git checkouts
description:
- Manage I(git) che | ckouts of repositories to deploy files or software.
options:
repo:
required: true
aliases: [ name ]
description:
- git, SSH, or HTTP(S) protocol address of the git repository.
dest:
required: true
description:
- The path of where the repository sho... |
BurtBiel/azure-cli | src/command_modules/azure-cli-network/azure/cli/command_modules/network/zone_file/exceptions.py | Python | mit | 1,506 | 0.015936 | #---------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license informatio | n.
#---------------------------------------------------------------------------------------------
#The MIT License (MIT)
#Copyright (c) 2016 Blockstack
#Permission is hereby granted, free of charge, to a | ny 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, distribute, sublicense, and/or sell
#copies of the Software, and to permit persons to whom the So... |
dallascard/guac | core/experiment/rerun.py | Python | apache-2.0 | 1,879 | 0.007451 | import experiment
from ..util import dirs
from ..util import file_handling as fh
from optparse import OptionParser
import sys
def main():
usage = "%prog project logfile "
parser = OptionParser(usage=usage)
parser.add_option('-n', dest='new_name', default=None,
help='New name for e... | ions, args) = parser.parse_args()
project = args[0]
log_filename = args[1]
new_name = options.new_name
log = fh.read_json(log_filename)
if new_name is None:
new_name = log['name'] + '_rerun'
log['name'] = new_name
float_vars = ['best_alpha', 'alpha_exp_base', 'max_alpha_exp', 'min... | if v in log:
if log[v] is not None:
log[v] = float(log[v])
else:
log[v] = None
#if log['reuse'] == 'False':
# log['reuse'] = False
#else:
# log['reuse'] = True
# convert list stirng to list
#list_vars = ['feature_list', 'additional_la... |
yafraorg/yapki | server-admin/model/user.py | Python | apache-2.0 | 261 | 0 | from typing import List
from pydantic import BaseModel
class UserBase(BaseModel):
email: str
name: str
class UserCreate(UserBase):
password: str
| class User(UserBase):
id: int
is_active: bool
class Config:
| orm_mode = True
|
mindbender-studio/config | polly/plugins/maya/publish/extract_model.py | Python | mit | 2,116 | 0 | import pyblish.api
class ExtractMindbenderModel(pyblish.api.InstancePlugin):
"""Produce a stripped down Maya file from instance
This plug-in takes into account only nodes relevant to models
and discards anything else, especially deformers along with
their intermediate nodes.
"""
label = "Mo... | o("Performing extraction..")
with maya.maintained_selection(), maya.without_extension():
self.log.info("Extracting %s" % str(list(instance)))
cmds.select(instance, noExpand=True)
cmds.file(path,
force=True,
typ="mayaAscii",
... | for animators, and lookdev, for rendering.
shader=False,
# Construction history inherited from collection
# This enables a selective export of nodes relevant
# to this particular plug-in.
constructionHistory=F... |
songmonit/CTTMSONLINE | openerp/addons/base/ir/ir_translation.py | Python | agpl-3.0 | 23,442 | 0.0061 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... | cr, uid, lang_ids, ['code', 'name'], context=context)
return [(d['code'], d['name']) for d in lang_data]
def _get_src(self, cr, uid, ids, name, arg, context=None):
''' Get source name for the translation. If object type is model then
return the value store in db. Otherwise return value stor... | for record in self.browse(cr, uid, ids, context=context):
if record.type != 'model':
res[record.id] = record.src
else:
model_name, field = record.name.split(',')
model = self.pool.get(model_name)
if model is not None:
... |
OpenNingia/l5r-character-manager | l5rcm/api/insight.py | Python | gpl-3.0 | 3,390 | 0.003835 | # -*- coding: utf-8 -*-
# Copyright (C) 2014 Daniele Simonetti
#
# 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; either version 2 of the License, or
# (at your option) any later version.
#
# Thi... | ght_plus_7')
return n
def insight_calculation_2(model):
'''Another insight calculation method. Similar to 1, but ignoring
rank 1 skills
'''
model = self.model
n = 0
for r, v in model.iter_rings():
n += v *10
for s in model.get_skills(... | n += 7*model.cnt_rule('ma_insight_plus_7')
return n
def insight_calculation_3(model):
'''Another insight calculation method. Similar to 2, but
school skill are counted even if rank 1
'''
model = self.model
school_skills = model.get_school_skills()
... |
profxj/xastropy | xastropy/igm/setup_package.py | Python | bsd-3-clause | 206 | 0 | def get_package_data():
# Installs the testing data files. Unable to get package_data
# to deal with a directory hierarchy of files, so just explicitly list.
| return {'xastropy.igm': ['fN/*. | p']}
|
alxgu/ansible | lib/ansible/modules/system/iptables.py | Python | gpl-3.0 | 26,931 | 0.00156 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2015, Linus Unnebäck <[email protected]>
# Copyright: (c) 2017, Sébastien DA ROCHA <[email protected]>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_... | ay and work in short-circuit
fashion, i.e. if one extension yields false, evaluation will stop.
type: list
default: []
jump:
description:
- This specifie | s the target of the rule; i.e., what to do if the packet matches it.
- The target can be a user-defined chain (other than the one
this rule is in), one of the special builtin targets which decide the
fate of the packet immediately, or an extension (see EXTENSIONS
below).
- If this op... |
cherbib/fofix | src/Svg.py | Python | gpl-2.0 | 7,545 | 0.016965 | #####################################################################
# -*- coding: iso-8859-1 -*- #
# #
# Frets on Fire X #
# Copyright (C) 2006 Sami Kyöstilä ... | == str:
self.texture = Texture(ImgData)
elif isinstance(ImgData, Image.Image): #stump: let a PIL image be passed in
self.texture = Texture()
self.texture.loadImage(ImgData)
# Make sure we have a valid texture
if not self.texture:
if type(ImgData) == str:
e = "Unable to load... | e = "Unable to load texture for SVG file."
Log.error(e)
raise RuntimeError(e)
self.pixelSize = self.texture.pixelSize
self.position = [0.0,0.0]
self.scale = [1.0,1.0]
self.angle = 0
self.color = (1.0,1.0,1.0)
self.rect = (0,1,0,1)
self.shift = -.5
self.cre... |
rvosa/peyotl | peyotl/test/test_oti.py | Python | bsd-2-clause | 2,232 | 0.006272 | #! /usr/bin/env python
from peyotl.api import OTI
from peyotl.test.support.pathmap import get_test_ot_service_domains
from peyotl.utility import get_logger
import unittest
import os
_LOG = get_logger(__name__)
@unittest.skipIf('RUN_WEB_SERVICE_TESTS' not in os.environ,
'RUN_WEB_SERVICE_TESTS is not in ... | qd = {'bogus key': 'Aponogeoton ulvaceus 1 2'}
self.assertRaises(ValueError, self.oti.find_nodes, qd)
def testTreeTerms(self):
qd = {'ot:ottTaxonName': 'Aponogeton ulvaceus'}
if self.oti.use_v1:
nl = self.oti.find_trees(qd)
self.assertTrue(len(nl) > 0)
... | self.assertTrue(len(t) > 0)
def testBadTreeTerms(self):
qd = {'bogus key': 'Aponogeoton ulvaceus 1 2'}
self.assertRaises(ValueError, self.oti.find_trees, qd)
if __name__ == "__main__":
unittest.main(verbosity=5)
|
rvianello/rdkit | Code/DataManip/MetricMatrixCalc/test_list.py | Python | bsd-3-clause | 221 | 0.0181 | tests = [("testExecs/testMatCalc.exe", "", {})]
longTests = []
if __na | me__ == '__main__':
import sys
from rdkit import TestRunner
failed, tests = TestRunner.RunScript('test_list.py', 0, 1)
sys.exit(len(failed))
| |
jdavisp3/twisted-intro | twisted-server-1/poetry-proxy.py | Python | mit | 3,478 | 0.000288 | # This is the Twisted Poetry Proxy, version 1.0
import optparse
from twisted.internet.defer import Deferred, maybeDeferred
from twisted.internet.protocol import ClientFactory, ServerFactory, Protocol
def parse_args():
usage = """usage: %prog [options] [hostname]:port
This is the Poetry Proxy, version 1.0.
p... | ptions, parse_address(args[0])
class PoetryProxyProtocol(Protocol):
def connectionMade(self):
d = maybeDeferred(self.factory.service.get_poem)
d.addCallback(self.transport.write)
d.addBoth(lambda r: self.transport.loseConnection())
class PoetryProxyFactory(ServerFactory):
protocol ... |
self.service = service
class PoetryClientProtocol(Protocol):
poem = b''
def dataReceived(self, data):
self.poem += data
def connectionLost(self, reason):
self.poemReceived(self.poem)
def poemReceived(self, poem):
self.factory.poem_finished(poem)
class PoetryClien... |
xpansa/pmis | analytic_schedule/__init__.py | Python | agpl-3.0 | 984 | 0.001016 | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2014 Eficent (<http://www.eficent.com/>)
# <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero... | ersion 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General | Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import model |
r3c/cottle | docs/conf.py | Python | mit | 2,382 | 0.00126 | # -*- coding: utf-8 -*-
"""
Resources:
https://pythonhosted.org/an_example_pypi_project/sphinx.html
https://github.com/djungelorm/sphinx-csharp
https://sublime-and-sphinx-guide.readthedocs.io/en/latest/code_blocks.html
https://docutils.sourceforge.net/docs/user/rst/quickref.html
"""
import sys
import os
extensions ... | that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Cottle Documentation'
copyright = u'2019, Rémi Caput'
# The shor... | tterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'default'
# See: https://sphinx-rtd-theme.readthedocs.io/en/stable/configuring.html
html_theme... |
algorythmic/bash-completion | test/t/unit/test_unit_tilde.py | Python | gpl-2.0 | 1,246 | 0 | import pytest
from conftest import assert_bash_exec
@pytest.mark.bashcomp(cmd=None, ignore_env=r"^\+COMPREPLY=")
class TestUnitTilde:
def test_1(self, bash):
assert_bash_exec(bash, | "_tilde >/dev/null")
def test_2(self, bash):
"""Test environment non-pollution, detected at te | ardown."""
assert_bash_exec(
bash, 'foo() { local aa="~"; _tilde "$aa"; }; foo; unset foo'
)
def test_3(self, bash):
"""Test for https://bugs.debian.org/766163"""
assert_bash_exec(bash, "_tilde ~-o")
def _test_part_full(self, bash, part, full):
res = (
... |
rgbconsulting/rgb-addons | hw_serial/drivers/serial_driver.py | Python | agpl-3.0 | 2,035 | 0.001474 | # -*- coding: utf-8 -*-
# See README file for full copyright and licensing details.
import os
import logging
_logger = logging.getLogger(__name__)
try:
import serial
except ImportError:
_logger.error('Odoo module hw_serial depends on the pyserial python module')
serial = None
class SerialDriver(object)... | esult
def serial_open(self, params):
try:
p | ort = params.get('port', '/dev/ttyUSB0')
if not os.path.exists(port):
_logger.error('Serial port not found')
return None
return serial.Serial(port,
baudrate=int(params.get('baudrate', 9600)),
bytesi... |
MarkAWard/optunity | notebooks/sklearn-svr.py | Python | bsd-3-clause | 6,245 | 0.003363 | {
"metadata": {},
"nbformat": 3,
"nbformat_minor": 0,
"worksheets": [
{
"cells": [
{
"cell_type": "code",
"collapsed": false,
"input": [
"# Example of tuning an SVR model in scikit-learn with Optunity\n",
"# This example requires sklearn\n",
"import math\n",
"import i... | ned_model = sklearn.svm.SVR(**optimal_pars).fit(x_train, y_train)\n",
" return tuned_model.predict(x_test).tolist()\n",
"\n",
"svr_untuned_predictions = outer_cv(svr_untuned_predictions)\n",
"svr_tu | ned_predictions = outer_cv(svr_tuned_predictions)\n",
"\n",
"untuned_preds = svr_untuned_predictions()\n",
"tuned_preds = svr_tuned_predictions()\n",
"\n",
"true_targets = [targets[i] for i in itertools.chain(*folds)]\n",
"untuned = list(itertools.chain(*untuned_preds))\n",
"tu... |
ZuckermanLab/NMpathAnalysis | nmpath/nmm.py | Python | gpl-3.0 | 21,745 | 0.000276 | '''
Created on Jul 28, 2016
'''
import numpy as np
from auxfunctions import map_to_integers, normalize_markov_matrix
from auxfunctions import pops_from_nm_tmatrix, pops_from_tmatrix
from auxfunctions import pseudo_nm_tmatrix, weighted_choice
from mfpt import direct_mfpts, non_markov_mfpts, fpt_distribution
from mfpt ... | :])
discrete_traj.append(next_state // 2)
current_state = next_state
return cls([np.array(discrete_traj)], stateA, stateB, clean_traj=True)
@property
def | lag_time(self):
return self._lag_time
@lag_time.setter
def lag_time(self, lag_time):
self._lag_time = lag_time
self.fit()
def mfpts(self):
if self.markovian:
return markov_mfpts(self.markov_tmatrix, self.stateA, self.stateB,
lag_... |
Teamxrtc/webrtc-streaming-node | third_party/webrtc/src/chromium/src/third_party/webdriver/pylib/selenium/webdriver/remote/remote_connection.py | Python | mit | 17,659 | 0.000963 | # Copyright 2008-2009 WebDriver committers
# Copyright 2008-2009 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 requ... |
Command.FIND_CHILD_ELEMENTS:
('POST', '/session/$sessionId/element/$id/elements'),
Command.CLICK_ELEMENT: ('POST', '/session/$sessionId/element/$id/click'),
Command.CLEAR_ELEMENT: ('POST', '/session/$sessionId/element/$id/clear'),
Command.SUBMIT_ELEMENT: ... | sionId/element/$id/submit'),
Command.GET_ELEMENT_TEXT: ('GET', '/session/$sessionId/element/$id/text'),
Command.SEND_KEYS_TO_ELEMENT:
('POST', '/session/$sessionId/element/$id/value'),
Command.SEND_KEYS_TO_ACTIVE_ELEMENT:
('POST', '/session/$sessionId/... |
ionelmc/django-uni-form | test_project/urls.py | Python | mit | 605 | 0.008264 | from django.conf.url | s.defaults import *
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
# Example:
url(r'^$', "test_app.views.basic_test", name='test_index'),
(r'^more/', include('test_app.urls')),
# Uncomment the admin/do... | ation:
# (r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
# (r'^admin/(.*)', admin.site.root),
)
|
mitchellrj/touchdown | touchdown/core/goals.py | Python | apache-2.0 | 3,341 | 0.000299 | # Copyright 2015 Isotoma Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... | ributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import division
import os
from . import dependencies, plan, ma... |
def __init__(self):
self.goals = {}
def register(self, cls):
self.goals[cls.name] = cls
def registered(self):
return self.goals.items()
def create(self, name, workspace, ui, map=map.ParallelMap):
try:
goal_class = self.goals[name]
except KeyError:... |
bvernoux/micropython | ports/esp32/boards/manifest_release.py | Python | mit | 283 | 0 | include("manifest.py")
freeze("$(MPY_LIB_DIR)/python-ecosys/urequests", "urequests.py")
freeze("$(MPY_LIB_DIR)/micropython/upysh", "upysh.py")
freeze("$(MPY_LIB_DIR)/micropython/umqtt.simple", "umqt | t/simple.py")
freeze("$(MPY_LIB_DIR)/micropython/umqtt.robust", | "umqtt/robust.py")
|
LouisPlisso/analysis_tools | add_ASN_geoip.py | Python | gpl-3.0 | 2,116 | 0.016541 | """Retrieve As information out of GeoIP (MaxMind) binding.
Beware: database location is hardcoded!"""
import GeoIP
import re
import numpy as np
import INDEX_VALUES
#WARNING: hard coded
GAS=GeoIP.open('/home/louis/streaming/flows/AS/GeoIPASNum.dat',
GeoIP.GEOIP_STANDARD)
#ugly but more efficient: compile only... | src = GAS.org_by_addr(d['srcAddr'])
if src != None:
fields.extend(list(REGEXP.match(src).group(2,1)))
else:
fields.extend([0, 'Not found'])
dst = GAS.org_by_addr(d['dstAddr'])
if dst != None:
fields.extend(list(REGEXP.match(dst).group(2,1)))
else:
fields.extend([0... | f extend_array_AS(flows_array):
"Return a new array with AS information on both sides."
return np.array([extend_fields_AS(d) for d in flows_array],
dtype=INDEX_VALUES.dtype_GVB_AS)
def extend_array_BGP_AS(flows_array):
"Return a new array with AS information on both sides."
return np.array([exten... |
wanqizhu/mtg-python-engine | MTG/player.py | Python | mit | 26,315 | 0.002356 | import pdb
import traceback
import random
from copy import deepcopy
from collections import defaultdict
from MTG import mana
from MTG import zone
from MTG import play
from MTG import gamesteps
from MTG import cards
from MTG import triggers
from MTG import token
from MTG.exceptions import *
class Player():
is_pla... | do? {}{}, {}\n".format(
self.name,
'*' if self.is_active else '',
self.game.step))
if self.game.test:
print("\t" + self.name + ", " +
| str(self.game.step) + ": " + answer + "\n")
if answer == '':
break
try:
if answer == 'print':
self.game.print_game_state()
elif answer == 'hand':
print(self.hand)
elif... |
zycdragonball/tensorflow | tensorflow/python/kernel_tests/cwise_ops_test.py | Python | apache-2.0 | 79,648 | 0.007546 | # 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... | t_session(use_gpu=True):
result = tf_func(ops.convert_to_tensor(x))
tf_gpu = result.eval()
if x.dtype == np.float16:
self.assertAllClose(np_ans, tf_gpu, rtol=1e-3, atol=1e-3)
else:
se | lf.assertAllClose(np_ans, tf_gpu)
# TODO(zhifengc/ke): make gradient checker work on GPU.
def _compareSparseGpu(self, x, np_func, tf_func, tol):
x_sp, x_sp_vals = _sparsify(x)
res_np = np_func(x_sp_vals)
with self.test_session(use_gpu=True):
self._check(tf_func(x_sp), res_np, x_sp, tol)
def ... |
JioEducation/edx-platform | common/lib/xmodule/xmodule/tests/test_video.py | Python | agpl-3.0 | 42,276 | 0.001443 | # -*- coding: utf-8 -*-
# pylint: disable=protected-access
"""Test for Video Xmodule functional logic.
These test data read from xml, not from mongo.
We have a ModuleStoreTestCase class defined in
common/lib/xmodule/xmodule/modulestore/tests/django_utils.py. You can
search for usages of this in the cms and lms tests f... | aptioning button in order to make it go away"
" or reappear. Now that you know about the video player, I want to point out the sequence navigator."
" Right now you're in a lecture sequence, which interweaves many videos and practice exercises. You"
" can see how far you are in a particular sequence by obser... | u can"
" navigate directly to any video or exercise by clicking on the appropriate tab. You can also"
" progress to the next element by pressing the Arrow button, or by clicking on the next tab. Try"
" that now. The tutorial will continue in the next video."
)
def instantiate_descriptor(**field_data):
... |
OuterDeepSpace/OuterDeepSpace | messager/setup.py | Python | gpl-2.0 | 6,455 | 0.009605 | # A setup script showing how to extend py2exe.
#
# In this case, the py2exe command is subclassed to create an installation
# script for InnoSetup, which can be compiled with the InnoSetup compiler
# to a single file windows installer.
#
# By default, the installer will be created as dist\Output\setup.exe.
from distut... | ############################################
setup(
options = options,
# The lib directory contains everything except the executables and the python dll.
zipfile = zipfile,
windows = [msg_wx],
# use out build_installer class a | s extended py2exe build command
cmdclass = {"py2exe": build_installer},
data_files = [('res/techspec',
['../server/lib/ige/ospace/Rules/Tech.spf',
'../server/lib/ige/ospace/Rules/techs.spf']
)]
)
|
bhaisaab/ipmisim | setup.py | Python | apache-2.0 | 2,011 | 0.013923 | # 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 u... | 2',
'pycrypto==2.6.1',
]
setup | (
name = 'ipmisim',
version = '0.10',
maintainer = 'Rohit Yadav',
maintainer_email = '[email protected]',
url = 'https://github.com/shapeblue/ipmisim',
description = "ipmisim is a fake ipmi server",
long_description = "ipmisim is a fake ipmi server",
platforms = ("Any",),
license = 'A... |
opensvn/python | mymovies.py | Python | gpl-2.0 | 877 | 0.003421 | #!/usr/bin/env python
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import moviedata
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
se | lf.movies = moviedata.MovieContainer()
self.table = QTableWidget()
self.setCentralWidget(self.table)
def updateTable(self, current=None):
| self.table.clear()
self.table.setRowCount(len(self.movies))
self.table.setColumnCount(5)
self.table.setHorizontalHeaderLabels(['Title',
'Year', 'Mins', 'Acquired', 'Notes'])
self.table.setAlternatingRowColors(True)
self.table.setEditTriggers(QTableWidget.NoEditT... |
deandunbar/html2bwml | venv/lib/python2.7/site-packages/cryptography/hazmat/primitives/padding.py | Python | mit | 3,948 | 0 | # This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from __future__ import absolute_import, division, print_function
import abc
import os
import six
from cryptography import utils
from cr... | Error("block_size must be a multiple of 8.")
self.block_size = block_size
def padder(self):
return _PKCS7PaddingContext(self.block_size)
def unpadder(self):
return _PKCS7UnpaddingContext(self.block_size)
@utils.register_interface(PaddingContext)
class | _PKCS7PaddingContext(object):
def __init__(self, block_size):
self.block_size = block_size
# TODO: more copies than necessary, we should use zero-buffer (#193)
self._buffer = b""
def update(self, data):
if self._buffer is None:
raise AlreadyFinalized("Context was al... |
jmesteve/saas3 | openerp/addons/crm_partner_assign/crm_partner_assign.py | Python | agpl-3.0 | 11,290 | 0.006466 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... | , context=context)
if partner.user_id:
salesteam_id = partner | .section_id and partner.section_id.id or False
for lead_id in ids:
self.allocate_salesman(cr, uid, [lead_id], [partner.user_id.id], team_id=salesteam_id, context=context)
self.write(cr, uid, [lead.id], {'date_assign': fields.date.context_today(self,cr,uid,context=context)... |
knightzero/AutoClicker | autoclicker.py | Python | mit | 2,779 | 0.013314 | import wx
import win32api
import win32con #for the VK keycodes
from threading import *
import time
EVT_RESULT_ID = wx.NewId()
def mouseClick(timer):
print "Click!"
x,y = win32api.GetCursorPos()
win32api.SetCursorPos((x, y))
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,x,y,0,0)
time.sleep(tim... | unc)
class ResultEvent(wx.PyEvent):
"""Simple event to carry arbitrary result data."""
def __init__(self, data):
"""Init Result Event."""
wx.PyEvent.__init__(self)
self.SetEventType(EVT_RESULT_ID)
self.data = data
class WorkerThread(Thread):
'''Worker Thread Cla... | self)
self._notify_window = notify_window
self._want_abort = False
self.timer = timer
self.start()
def run(self):
while True:
if self._want_abort:
wx.PostEvent(self._notify_window, ResultEvent(None))
return
mous... |
YuHongJun/python-training | work_one/mydict2.py | Python | mit | 854 | 0 | class Dict(dict):
'''
Simple dict but also support access as x.y style.
>>> d1=Dict()
>>> d1['x']=100
>>> d1.x
100
| >>> d1.y=200
>>> d1['y']
200
>>> d2 = Dict(a=1, b=2, c='3')
>>> d2.c
'3'
>>> d2['empty']
Traceback (most recent call last):
...
KeyError: 'empty'
>>> d2.empty
| Traceback (most recent call last):
...
AttributeError: 'Dict' object has no attribute 'empty'
'''
def __int__(self, **kw):
super(Dict, self).__init__(**kw)
def __getattr__(self, key):
try:
return self[key]
except KeyError:
raise AttributeError(r... |
yotamfr/prot2vec | src/python/dingo_net1.py | Python | mit | 13,615 | 0.001469 | # import os
# os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
# os.environ["CUDA_VISIBLE_DEVICES"] = "1"
import torch
import torch.nn as nn
from torch import optim
from torch.autograd import Variable
import torch.nn.functional as F
from src.python.dingo_utils2 import *
from src.python.preprocess2 import *
from src.p... | _seq)
outputs = self.embedding_dropout | (outputs)
batch_size = outputs.size(0)
protein_length = outputs.size(2)
prot_section_size = self.prot_section_size
new_prot_length = protein_length // prot_section_size
remainder = protein_length % prot_section_size
head = remainder // 2
tail = protein_length - (r... |
sahat/bokeh | sphinx/source/tutorial/exercises/stocks.py | Python | bsd-3-clause | 1,939 | 0.004126 |
import numpy as np
import pandas as pd
from bokeh.plotting import *
# Here is some code to read in some stock data from the Yahoo Finance API
AAPL = pd.read_csv(
"http://ichart.yahoo.com/table.csv?s=AAPL&a=0&b=1&c=2000",
parse_dates=['Date'])
GOOG = pd.read_csv(
"http://ichart.yahoo.com/table.csv?s=GOOG&... | lot, set a title, lighten the gridlines, etc.
# EXERCISE: start a new figure
# Here is some code to compute the 30-day moving average for AAPL
aapl = AAPL['Adj Close']
aapl_dates = AAPL['Date']
window_size = 30
window = np.ones(window_size)/float(window_s | ize)
aapl_avg = np.convolve(aapl, window, 'same')
# EXERCISE: plot a scatter of circles for the individual AAPL prices with legend
# 'close'. Remember to set the x axis type and tools on the first renderer.
# EXERCISE: plot a line of the AAPL moving average data with the legeng 'avg'
# EXERCISE: style the plot, set ... |
minhphung171093/GreenERP | openerp/addons/product_uos/models/product_uos.py | Python | gpl-3.0 | 1,586 | 0.005044 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from openerp import api, fields, models
import openerp.addons.decimal_precision as dp
class ProductTemplate(models.Model):
_inherit = "product.template"
uos_id = fields.Many2one('product.uom', 'Unit of Sale',
... | ring='Quantity', digits_compute=dp.get_precision('Product Unit of Measure'),
compute='_compute_uos', inverse='_set_uos', readonly=False)
product_uos = fields.Many2one('product.uom', string='Unit of Measure', required=True,
| related='product_id.uos_id', readonly=True)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.