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 |
|---|---|---|---|---|---|---|---|---|
Johnetordoff/osf.io | osf/management/utils.py | Python | apache-2.0 | 457 | 0 | from django.utils.six.moves import input
# From https://stackoverflo | w.com/a/39257511/1157536
def ask_for_confirmation(question, default=None):
"""Ask for confirmation before proceeding.
"""
result = input('{} '.format(question))
if not result and default is not None:
return default
while len(result) < | 1 or result[0].lower() not in 'yn':
result = input('Please answer yes or no: ')
return result[0].lower() == 'y'
|
co-ment/comt | setup.py | Python | agpl-3.0 | 441 | 0 | from setuptools import setup, find_packages
setup( |
name="comt",
use_scm_version=True,
url='http://www.co-ment.org',
license='AGPL3',
description="Web-based Text Annotation Application.",
long_description=open('ABOUT.r | st').read(),
author='Abilian SAS',
author_email='[email protected]',
packages=find_packages('src'),
package_dir={'': 'src'},
install_requires=['setuptools'],
zip_safe=False,
)
|
gokmen/Rasta | rasta_lib/rasta.py | Python | gpl-2.0 | 16,437 | 0.002799 | #!/usr/bin/python
# -*- coding: utf-8 -*-
''' Rasta RST Editor
2010 - Gökmen Göksel <gokmeng:gmail.com> '''
# 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,... | % (add, selection, (header * len(selection))))
cursor.endEditBlock()
if marker:
cursor.beginEditBlock()
cursor.removeSelectedText()
cursor.insertText("%s%s%s" % (marker, selection, marker))
cursor.endEditBlock()
## File O... | ons
def newFile(self):
''' Create new file '''
if self.checkModified():
self.ui.textEdit.clear()
self.file_name = TMPFILE
self.setWindowTitle('Rasta - %s' % self.file_name)
def fileOpen(self):
''' It shows Open File dialog '''
if self.checkModifi... |
drcgw/bass | modules/__init__.py | Python | gpl-3.0 | 44 | 0.022727 | __ | all__ = ['pleth_analysis', 'ekg_analysi | s'] |
cernops/neutron | neutron/db/migration/alembic_migrations/versions/4eba2f05c2f4_correct_vxlan_endpoint_primary_key.py | Python | apache-2.0 | 1,254 | 0.000797 | # Copyright (c) 2014 Thales Services SAS
#
# 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 l... | 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.
#
"""correct Vxlan En | dpoint primary key
Revision ID: 4eba2f05c2f4
Revises: 884573acbf1c
Create Date: 2014-07-07 22:48:38.544323
"""
# revision identifiers, used by Alembic.
revision = '4eba2f05c2f4'
down_revision = '884573acbf1c'
from alembic import op
TABLE_NAME = 'ml2_vxlan_endpoints'
PK_NAME = 'ml2_vxlan_endpoints_pkey'
def upg... |
darkryder/django | django/contrib/admin/sites.py | Python | bsd-3-clause | 19,712 | 0.001268 | from functools import update_wrapper
from django.apps import apps
from django.conf import settings
from django.contrib.admin import ModelAdmin, actions
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.core.exceptions import ImproperlyConfigured, PermissionDenied
from django.db.models.base import ModelBa... | f._registry:
raise AlreadyRegistered('The model %s is already registered' % model.__name__)
# Ignore the registration if the model has been
# swapped out.
if not model._meta.swapped:
# If we got **op | tions then dynamically construct a subclass of
# admin_class with those **options.
if options:
# For reasons I don't quite understand, without a __module__
# the created class appears to "live" in the wrong place,
# which causes... |
artemsok/sockeye | sockeye/rnn_attention.py | Python | apache-2.0 | 36,524 | 0.00345 | # Copyright 2017 Amazon.com, Inc. or its affiliates. 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. A copy of the License
# is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file acc... | encoding is initialized with zeros.
:param source_length: Source length. Shape: (batch_size,).
:param source_seq_len: Maximum leng | th of source sequences.
"""
dynamic_source = mx.sym.reshape(mx.sym.zeros_like(source_length), shape=(-1, 1, 1))
# dynamic_source: (batch_size, source_seq_len, num_hidden_dynamic_source)
dynamic_source = mx.sym.broadcast_to(dynamic_source, shape=(0, source_seq_len, self.dynamic_source_num... |
gemagomez/os-reststack-manager | os_reststack_manager/app/tenant_manager.py | Python | apache-2.0 | 2,958 | 0.000676 | #!/usr/bin/env python
from __future__ import print_function
from flask import Blueprint, Flask, jsonify, json, abort, request, g
from os_reststack_manager.app import credentials, db, Tenant, logging
from lib.setup_tenant import tenant_create, extract_keys
from lib.erase_tenant import tenant_delete
import re
import j... | ery.fil | ter_by(machine_id=machine_id).first_or_404()
tenant.status = 'READY'
db.session.commit()
return "", 200
|
elbruno/Blog | 20200610 Camera/01Camera.py | Python | gpl-2.0 | 567 | 0.010582 | # Bruno Capuano 2020
# display the camera feed using OpenCV
import time
import cv2
# Camera Settings
camera_Width = 640 # 1024 # 1280 # 640
camera_Heigth = 480 # 780 # 960 # 480
frameSize = (camera_Width, camera_Heigth)
video_capture = cv2.VideoCapture(1)
time.sleep(1.0)
while True | :
ret, frameOrig = video_capture.read()
frame = cv2.resize(frameOrig, frameSize)
cv2.imshow('@elbruno - Camera', frame)
# key controller
key = cv2.waitKey(1) & 0xFF
if key == ord("q"):
break
video_capture.release()
cv2.destroyAl | lWindows() |
thedespicableknight/web_crawlers | youtube/youtube_videos_2.py | Python | mit | 766 | 0.006527 | import requests
import pafy
from bs4 import BeautifulSoup
def trade_spider(max_video_number):
video_number = 1
url = 'https://w | ww.youtube.com'
source_code = requests.get(url)
plain_text = source_code.text
soup = BeautifulSoup(plain_text, "lxml")
for link in soup.findAll('a', {'class': 'yt-uix-sessionlink yt-ui-ell | ipsis yt-ui-ellipsis-2 spf-link '}):
if link['href']:
href = link['href']
video = pafy.new(url + href)
best_video = video.getbest()
best_video.download(filepath="/home/mihir/PycharmProjects/web_crawlers/")
else:
print(link.string + ': FAILURE')... |
anhstudios/swganh | data/scripts/templates/object/static/particle/shared_pt_light_streetlamp_green.py | Python | mit | 454 | 0.048458 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from s | wgpy.object import *
def create(kernel):
result = Static()
result.template = "object/static/particle/shared_pt_light_streetlamp_green.iff"
result.attribute_templ | ate_id = -1
result.stfName("obj_n","unknown_object")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
lukw00/spaCy | tests/parser/test_base_nps.py | Python | mit | 1,273 | 0.001571 | from __future__ import unicode_literals
import pytest
@pytest.mark.models
def test_nsubj(EN):
sent = EN(u'A base phrase should be recognized.')
base_nps = list(sent.noun_chunks)
assert len(base_nps) == 1
assert base_nps[0].string == 'A base phrase '
@pytest.mark.models
def test_coord(EN):
sent =... | curs')
base_nps = list(sent.noun_chunks)
assert len(base_nps) == 2
assert base_nps[0].string == 'A phrase '
assert base_nps[1].string == 'another phrase '
@pytes | t.mark.models
def test_merge_pp(EN):
sent = EN(u'A phrase with another phrase occurs')
nps = [(np[0].idx, np[-1].idx + len(np[-1]), np.lemma_, np[0].ent_type_) for np in sent.noun_chunks]
for start, end, lemma, ent_type in nps:
sent.merge(start, end, u'NP', lemma, ent_type)
assert sent[0].strin... |
erudit/zenon | eruditorg/apps/public/journal/apps.py | Python | gpl-3.0 | 155 | 0 | # -*- | coding: utf-8 -*-
from django.apps impor | t AppConfig
class JournalConfig(AppConfig):
label = 'public_journal'
name = 'apps.public.journal'
|
ShiZhan/newspapers | utils/import-to-mongodb.py | Python | bsd-3-clause | 637 | 0 | #!/usr/bin/env python
import sys
import pymongo
import json
print "import crawled json file into mongodb 'newspapers' database."
i | f len(sys.argv) < 3:
print "input as [collection] [json_file]"
exit(1)
connection = pymongo.Connection("localhost", 27017)
news_database = connection.newspapers
news_collection = news_database[sys.argv[1]]
json_file_name = sys.argv[2]
try:
with open(json_file_name, mode='r') as json_file:
items = ... | |
arthurio/site_heroku | perso/settings/prod.py | Python | mit | 278 | 0.007194 | from perso.settings import *
# Parse datab | ase configuration from $DATABASE_URL
import dj_database_url
DATABASES['default'] = dj_ | database_url.config()
# Honor the 'X-Forwarded-Proto' header for request.is_secure()
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
|
RPGOne/Skynet | scikit-learn-0.18.1/examples/cluster/plot_cluster_comparison.py | Python | bsd-3-clause | 4,681 | 0.001282 | """
=========================================================
Comparing different clustering algorithms on toy datasets
=========================================================
This example aims at showing characteristics of different
clustering algorithms on datasets that are "interesting"
but still in 2D. The last ... | ge = cluster.AgglomerativeClustering(
linkage="averag | e", affinity="cityblock", n_clusters=2,
connectivity=connectivity)
birch = cluster.Birch(n_clusters=2)
clustering_algorithms = [
two_means, affinity_propagation, ms, spectral, ward, average_linkage,
dbscan, birch]
for name, algorithm in zip(clustering_names, clustering_algorithms):... |
sandeepdsouza93/TensorFlow-15712 | tensorflow/python/kernel_tests/io_ops_test.py | Python | apache-2.0 | 3,819 | 0.007113 | # -*- coding: utf-8 -*-
# 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
#
# U... | tCase):
def testReadFile(self):
cases = ['', 'Some contents', 'Неки садржаји на српском']
for contents in cases:
contents = tf.compat.as_bytes(contents)
with tempfile.NamedTemporaryFile(prefix='ReadFileTest',
| dir=self.get_temp_dir(),
delete=False) as temp:
temp.write(contents)
with self.test_session():
read = tf.read_file(temp.name)
self.assertEqual([], read.get_shape())
self.assertEqual(read.eval(), contents)
os.remove(temp.name)
def t... |
csira/wallace | tests/cases/config/decos.py | Python | bsd-3-clause | 1,193 | 0 | from tests.utils import should_throw
from tests.utils.registry import register
from wallace.config import App, get_app, get_connection
from wallace.config import GetApp, GetDBConn, GetParameter
from wallace.errors import ConfigError
@register
def test_get_app():
app = App()
class Test(object):
app =... | @should_throw(ConfigError, 102)
def test_get_conn2():
App()
class Test(object):
| db_name = 'my_redis_conn'
db = GetDBConn()
Test.db
@register
def test_get_param():
App(x=1)
class Test(object):
my_param = GetParameter('x')
assert Test.my_param == 1
@register
@should_throw(ConfigError, 101)
def test_get_param2():
App()
class Test(object):
my_... |
noemis-fr/custom | add_button_sale/__openerp__.py | Python | gpl-3.0 | 358 | 0.013966 | {
'name': 'add button on sa | le order',
'version': '7.0',
'category': '',
'author': "Mind And Go",
'website': "http://www.mind-and-go.com",
'summary': ' ',
'sequence':99,
'depends': ['base','sale'],
'data': ['views/sale_order_view.xml',
],
'qweb': [
],
'installable': True,
| 'auto_install': False,
} |
fengbohello/practice | python/func/multi-return.py | Python | lgpl-3.0 | 277 | 0.01083 | #! | /bin/env python
import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/../libs/")
from var_dump import var_dump
def func(a):
return 1, 2, 3
print func(10)
var_dump(func(10))
x = func(10)
var_dump(x)
a, b, _ = func(10)
var_dump(a, b | )
|
EmreAtes/spack | lib/spack/spack/cmd/use.py | Python | lgpl-2.1 | 1,713 | 0 | ##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, [email protected], All rights reserved.
# LLNL-CODE-64... | int_module_placeholder_help
description = "add package to environment using dotkit"
section = "environment"
level = "long"
def setup_parser(subparser):
"""Parser is only constructed so that this prints a nice help
message with -h. """
subparser.add_argument(
'spec', nargs=argparse.REMAINDER,
... | ceholder_help()
|
ksmaheshkumar/grr | lib/data_stores/mysql_advanced_data_store_test.py | Python | apache-2.0 | 2,003 | 0.008987 | #!/usr/bin/env python
"""Tests the mysql data store."""
import unittest
# pylint: disable=unused-import,g-bad-import-order
from grr.lib import server_plugins
# pylint: enable=unused-import,g-bad-import-order
import logging
from grr.lib import access_control
from grr.lib import config_lib
from grr.lib import data_st... | they can be run in parallel.
config_lib.CONFIG.Set("Mysql.database_name", "grr_test_%s" %
| self.__class__.__name__)
try:
data_store.DB = mysql_advanced_data_store.MySQLAdvancedDataStore()
data_store.DB.security_manager = test_lib.MockSecurityManager()
data_store.DB.RecreateTables()
except Exception as e:
logging.debug("Error while connecting to MySQL db: %s.", e)
rais... |
laffra/pava | pava/implementation/natives/sun/misc/VMSupport.py | Python | mit | 190 | 0.010526 | def add_native_methods(clazz):
def getVMTemporaryDirecto | ry____():
raise NotImplementedError()
clazz.getVMTemporaryDirec | tory____ = staticmethod(getVMTemporaryDirectory____)
|
lbeltrame/danbooru-client | danbooru/danboorupostwidget.py | Python | gpl-2.0 | 8,348 | 0.000839 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2011 Luca Beltrame <[email protected]>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License, under
# version 2 of the License, or (at your option) any later version.
#
# ... | self.layout.addStretch()
self.layout.addWidget(self.url_label)
if label_text is not None:
self.__text_label.setText(label_text)
self.layout.addWidget(self.__text_label)
self.checkbox = QtGui.QCheckBox()
self.checkbox.setChecked(False)
self.checkb... | i18n("Select"))
# Remove the accelerator, we don't want it
kdeui.KAcceleratorManager.setNoAccel(self.checkbox)
self.checkbox.setSizePolicy(QtGui.QSizePolicy.Fixed,
QtGui.QSizePolicy.Fixed)
self.layout.addWidget(self.checkbox)
# FIXME: Hack t... |
Pakketeretet2/lammps | tools/python/pizza/gnu.py | Python | gpl-2.0 | 12,570 | 0.015831 | # Pizza.py toolkit, www.cs.sandia.gov/~sjplimp/pizza.html
# Steve Plimpton, [email protected], Sandia National Laboratories
#
# Copyright (2005) Sandia Corporation. Under the terms of Contract
# DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains
# certain rights in this software. This software is... | -------------------------------
def xrange(self,*values):
if len(values) == | 0:
self.figures[self.current-1].xlimit = 0
else:
self.figures[self.current-1].xlimit = (values[0],values[1])
s |
ruymanengithub/vison | vison/datamodel/fpa_dm.py | Python | gpl-3.0 | 11,944 | 0.004689 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
FPA Data Model.
LE1 FITS files.
Created on Thu Aug 1 17:05:12 2019
@author: raf
"""
# IMPORT STUFF
from pdb import set_trace as stop
from astropy.io import fits as fts
import os
import copy
import numpy as np
from collections import OrderedDict
from vison.fpa imp... | f.fillval.
Used when building synthetic data of LE1 format using as input
images from the VGCC that only h | ave 20 columns of serial
overscan (FPA images have 29)."""
pQdata = np.zeros((self.QNAXIS1, self.QNAXIS2), dtype=Qdata.dtype)+self.fillval
pQdata[0:Qdata.shape[0], 0:Qdata.shape[1]] = Qdata.copy()
return pQdata
def set_ccdobj(self, ccdobj, CCDID, inextension=-1):
"""Sets th... |
climapulse/dj-labeler | runtests.py | Python | bsd-3-clause | 999 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import
from django.conf import settings
from django.core.management import | execu | te_from_command_line
import sys
if not settings.configured:
test_runners_args = {}
settings.configure(
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
},
},
INSTALLED_APPS=(
'django... |
sauloal/PiCastPy | werkzeug/contrib/lint.py | Python | mit | 12,238 | 0.000817 | # -*- coding: utf-8 -*-
"""
werkzeug.contrib.lint
~~~~~~~~~~~~~~~~~~~~~
.. versionadded:: 0.5
This module provides a middleware that performs sanity checks of the WSGI
application. It checks that :pep:`333` is properly implemented and warns
on some common HTTP errors such as non-empty respons... | if type(obj) is not str:
warn(WSGIWarning('%s requires bytestrings, got %s' %
(context, obj.__class__.__name__)))
class InputStream(object):
def __init__(self, stream):
se | lf._stream = stream
def read(self, *args):
if len(args) == 0:
warn(WSGIWarning('wsgi does not guarantee an EOF marker on the '
'input stream, thus making calls to '
'wsgi.input.read() unsafe. Conforming servers '
... |
droidsec-cn/FuzzLabs | requests/network_TEST.py | Python | gpl-2.0 | 288 | 0 | # ============================= | ================================================
# Basic TEST
# This file is part of the FuzzLabs Fuzzing Framework
# =============================================================================
from sulley import *
s_initializ | e("TEST")
s_string("TEST")
|
teejaydub/khet | simpleSound.py | Python | gpl-2.0 | 1,290 | 0.007752 | # simpleSound.py
# Plays audio files on Linux and Windows.
# Written Jan-2008 by Timothy Weber.
# Based on (reconstituted) co | de posted by Bill Dandreta at <http://www.velocityreviews.com/forums/t337346-how-to-play-sound-in-python.html>.
import platform
if platform.system().startswith('Win'):
from winsound import PlaySo | und, SND_FILENAME, SND_ASYNC
elif platform.system().startswith('Linux'):
from wave import open as waveOpen
from ossaudiodev import open as ossOpen
try:
from ossaudiodev import AFMT_S16_NE
except ImportError:
if byteorder == "little":
AFMT_S16_NE = ossaudiodev.AFMT_S16_LE
... |
ssssam/calliope | tests/conftest.py | Python | gpl-2.0 | 872 | 0 | # Calliope
# Copyright (C) 2017, 2018 Sam Thursfield <[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 Foundation, either version 3 of the License, or
# (at your option) any later versio... | for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http | ://www.gnu.org/licenses/>.
import pytest
import testutils
@pytest.fixture()
def cli():
'''Fixture for testing through the `cpe` commandline interface.'''
return testutils.Cli()
|
asterix24/GestionaleCaldaie | main/views.py | Python | gpl-2.0 | 9,759 | 0.0083 | #!/usr/bmport settings
# -*- coding: utf-8 -*-
from django import http
from django.shortcuts import render
from main import models
from main import myforms
from main import cfg
from main import tools
from main import data_render
from main import database_manager
from main import scripts
from main import errors
from m... | turn l
import xlwt
def __export_xls(data_table, filename="tabella"):
# Create the HttpResponse object with the appropriate CSV header.
response = http.HttpResponse(mimetype='application/ms-excel; charset=utf-8')
response['Content-Disposition'] = 'attachment; filename="%s_%s.xls"' % (filename, datetime.date... | (encoding='utf-8')
sheet = book.add_sheet('Elenco')
#Add header
export_list = user_settings.settings_columView('export_table')
for colum,j in enumerate(export_list):
sheet.write(0, colum, "%s" % j.replace('_', ' ').capitalize())
#Write table
for row,i in enumerate(data_table):
... |
Farbod909/parking-app-server | parking/apps.py | Python | mit | 89 | 0 | from d | jango.apps import AppConfig
class ParkingConfig(AppConfig):
name = 'parking' | |
bethesirius/ChosunTruck | linux/tensorbox/utils/train_utils.py | Python | gpl-3.0 | 10,836 | 0.00526 | import numpy as np
import random
import json
import os
import cv2
import itertools
from scipy.misc import imread, imresize
import tensorflow as tf
from data_utils import (annotation_jitter, annotation_to_h5)
from utils.annolist import AnnotationLib as al
from rect import Rect
from utils import tf_concat
def rescale_b... | all_rects_r = [r for row in all_rects for cell in row for r in cell]
if use_stitching:
from stitch_wrapper import stitch_rects
acc_rects = stitch_rects(all_rects, tau)
else:
acc_rects = all_rects_r
if show_suppressed:
pairs = [(all_rects_r, (255, 0, 0))]
else:
... | rect_set:
if rect.confidence > min_conf:
cv2.rectangle(image,
(rect.cx-int(rect.width/2), rect.cy-int(rect.height/2)),
(rect.cx+int(rect.width/2), rect.cy+int(rect.height/2)),
color,
2)
rects = []
for re... |
arruda/bgarena_analysis | bgarena_gatherer/bgarena_gatherer/spiders/bgarena_race_for_galaxy_moves.py | Python | mit | 9,774 | 0.003172 | # -*- coding: utf-8 -*-
import os
import datetime
from functools import partial
import json
import scrapy
from scrapy_splash import SplashRequest
from sqlalchemy.orm import sessionmaker
from bgarena_gatherer.items import GameTableItem
from bgarena_gatherer.models import GameTable, GameTableMoveAction, db_connect
AC... | turn splash:html()
end
"""
script_login_cookies = """
function main(splash)
local url = splash.args.url
assert(splash:go(url))
assert(splash:wait(5.0)) |
assert(splash:runjs("document.getElementById('username_input').value = '%s';"))
assert(splash:runjs("document.getElementById('password_input').value = '%s';"))
local get_dimensions = splash:jsfunc([[
function () {
var rect = document.getElementById('login_button').getBoundingClientRect... |
Minkov/site | judge/templatetags/counter.py | Python | agpl-3.0 | 575 | 0.001739 | from itertools import count
from django import temp | late
register = template.Library()
class GetCounterNode(template.Node):
def __init__(self, var_name, start=1):
self.var_name = var_name
self.start = start
def render(self, context):
context[self.var_name] = count(self.start).next
return ''
@register.tag
def get_counter(pars... | eError:
raise template.TemplateSyntaxError('%r tag requires arguments' % token.contents.split()[0])
|
mzdaniel/oh-mainline | vendor/packages/mechanize/test-tools/unittest/__init__.py | Python | agpl-3.0 | 2,508 | 0.002392 | """
Python unit testing framework, based on Erich Gamma's JUnit and Kent Beck's
Smalltalk testing framework.
This module contains the core framework classes that form the basis of
specific test cases and suites (TestCase, TestSuite etc.), and also a
text-based utility class for running the tests and reporting the resu... | ader', 'SkipTest', 'skip', 'skipIf', 'skipUnless',
'expectedFailure']
# Expose obsolete functions for backwards compatibility
__all__.extend(['getTestCaseNames', 'makeSuite', 'findTestCases'])
from unittest.result import TestResult
from unittest.case import (TestCase, FunctionTestCase, SkipTest, skip, ski... | getTestCaseNames, findTestCases)
from unittest.main import TestProgram, main
from unittest.runner import TextTestRunner
|
mscuthbert/abjad | abjad/tools/developerscripttools/RenameModulesScript.py | Python | gpl-3.0 | 13,078 | 0.003594 | # -*- encoding: utf-8 -*-
import os
from abjad.tools import documentationtools
from abjad.tools import systemtools
from abjad.tools.developerscripttools.DeveloperScript import DeveloperScript
from abjad.tools.developerscripttools.ReplaceInFilesScript \
import ReplaceInFilesScript
class RenameModulesScript(Develop... | se_tools_path(codebase)
path = os.path.join(tools_path, tools_package_name)
if kind == 'class':
| generator = documentationtools.yield_all_classes(
code_root=path,
include_private_objects=True,
)
elif kind == 'function':
generator = documentationtools.yield_all_functions(
code_root=path,
include_private_objec... |
zacharydenton/bard | tests/test_generators_markov.py | Python | gpl-3.0 | 1,503 | 0.005323 | import unittest
import nltk
from bard.generators import markov
class TestMarkov(unittest.TestCase):
def setUp(self):
self.to | kens = nltk.corpus.brown.words(categories='science_fiction')
| self.tagged_tokens = nltk.corpus.brown.tagged_words(categories='science_fiction')
self.generator = markov.MarkovGenerator(self.tokens)
self.tagged_generator = markov.MarkovGenerator(self.tagged_tokens)
def test_generator(self):
random_tokens = self.generator.generate(length=100)
... |
hahnicity/mesclan | mesclan/controllers.py | Python | unlicense | 3,754 | 0.000799 | """
mesclan.controllers
~~~~~~~~~~~~~~~~~
"""
from functools import wraps
from hashlib import sha256
import logging
from urlparse import urljoin
from flask import request, Response
import requests
from sqlalchemy.orm.exc import NoResultFound
from ujson import dumps
from mesclan import exceptions
from mesclan.cache im... | token"])
appsecret_proof.update(oauth.SECRET)
hash_ = appsecret_proof.digest()
response = _validate_response(requests.get(
"{}/age_range?access_token={}".format(
urljoin(FACEBOOK_URL, re | quest.form["user_id"]), request.form["token"]
),
headers={"appsecret_proof", hash_}
))
# validate age, must be 21 in USA. Because we are making a liquor app...
if response.json()["min"] != "21":
raise exceptions.UserUnderageError()
|
halonsecurity/halonctl | halonctl/models.py | Python | bsd-3-clause | 6,898 | 0.042621 | from __future__ import print_function
import six
import socket
import keyring
import requests
from threading import Lock
from suds.client import Client
from suds.transport.http import HttpAuthenticated
from .proxies import *
from .util import async_dispatch, nodesort, to_base64, from_base64
from . import cache
@six.... | s, rows), defaults to (80,24)
* ``cols``, ``rows`` - individual components of ``size``
'''
# Allow calls as command("cmd", "arg1", "arg2") or command("cmd arg1 arg2")
parts = [command] + list(args) if args else command.split(' ')
# Allow size to be specified as size=(cols,rows) or cols=,rows=
size = k... | rts]}, cols=size[0], rows=size[1])
return (200, CommandProxy(self, cid)) if code == 200 else (code, None)
def __str__(self):
s = u"{name} ({host})".format(name=self.name, host=self.host)
if self.cluster.name:
s = u"{cluster}/{s}".format(cluster=self.cluster.name, s=s)
return s
def __repr__(self):
ret... |
ZoranPavlovic/kombu | t/unit/test_messaging.py | Python | bsd-3-clause | 24,456 | 0 | import pickle
import pytest
import sys
from collections import defaultdict
from unittest.mock import Mock, patch
from kombu import Connection, Consumer, Producer, Exchange, Queue
from kombu.exceptions import MessageStateError
from kombu.utils import json
from kombu.utils.functional import ChannelPromise
from t.mock... | n.Producer()
q = Queue('foo')
p.maybe_declare(q)
maybe_declare.assert_called_with(q, p.channel, False)
@patch('kombu.common.maybe_declare')
def test_maybe_declare_when_entity_false(self, maybe_declare):
p = self.connection.Producer()
p.maybe_declare(None)
maybe_d... | assert_not_called()
def test_auto_declare(self):
channel = self.connection.channel()
p = Producer(channel, self.exchange, auto_declare=True)
# creates Exchange clone at bind
assert p.exchange is not self.exchange
assert p.exchange.is_bound
# auto_declare declares exc... |
magic0704/oslo.messaging | oslo_messaging/_drivers/protocols/amqp/opts.py | Python | apache-2.0 | 3,495 | 0 | # Copyright 2014, Red Hat, 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 ... | pt('username',
default='',
deprecated_group='amqp1',
help='User name for message broker authentication'),
cfg.StrOpt('password',
defaul | t='',
deprecated_group='amqp1',
help='Password for message broker authentication')
]
|
DjangoQuilla/pollstutorial | polls/models.py | Python | mit | 767 | 0.023468 | import datetime
from django.db import models
from django.utils import timezone
# Create your models here.
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __unicode__(self):
return self.question_text
| def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
was_published_recently.admin_order_field = 'pub_date'
was_published_recently.boolean = True
was_published_recently.short_description = 'Published recently?'
class Choice(models.Model):
question = models.Foreign... | uestion)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __unicode__(self):
return self.choice_text |
sdss/marvin | python/marvin/contrib/vacs/hi.py | Python | bsd-3-clause | 9,230 | 0.006934 | # !usr/bin/env python
# -*- coding: utf-8 -*-
#
# Licensed under a 3-clause BSD license.
#
# @Author: Brian Cherinka
# @Date: 2018-10-11 17:51:43
# @Last modified by: Brian Cherinka
# @Last Modified time: 2018-11-29 17:23:15
from __future__ import print_function, division, absolute_import
import numpy as np
impor... | get any parameters you need from the parent object
plateifu = parent_object.plateifu
self.update_path_params({'plateifu': plateifu})
if parent_object.release in | ['DR17', 'MPL-11']:
self.set_program(plateifu)
specfile = self.get_path('mangahispectra', path_params=self.path_params)
# create container for more complex return data
hidata = HITarget(plateifu, vacfile=self.summary_file, specfile=specfile)
# get the spectral dat... |
jpmml/jpmml-sklearn | pmml-sklearn-extension/src/test/resources/extensions/category_encoders.py | Python | agpl-3.0 | 6,809 | 0.035688 | from sklearn.experimental import enable_hist_gradient_boosting
from category_encoders import BaseNEncoder, BinaryEncoder, CatBoostEncoder, CountEncoder, LeaveOneOutEncoder, OneHotEncoder, OrdinalEncoder, TargetEncoder, WOEEncoder
from mlxtend.preprocessing import DenseTransformer
from pandas import DataFrame
from skle... | neHotEncoder())]), "passthrough", clone(classifier), "Base3EncoderAudit")
build_audit(Pipeline([("basen", BaseNEnc | oder(base = 3, handle_missing = "value", handle_unknown = "value")), ("ohe", SkLearnOneHotEncoder(handle_unknown = "ignore"))]), SimpleImputer(), clone(classifier), "Base3EncoderAuditNA")
classifier = HistGradientBoostingClassifier(random_state = 13)
build_audit(BaseNEncoder(base = 4, drop_invariant = True, handle_... |
plotly/plotly.py | packages/python/plotly/plotly/validators/scatterpolargl/marker/colorbar/title/_side.py | Python | mit | 527 | 0 | import _plotly_utils.basevalidators
class SideValidator(_plotly_utils.basevalidators.EnumeratedValidator):
def __init__ | (
se | lf,
plotly_name="side",
parent_name="scatterpolargl.marker.colorbar.title",
**kwargs
):
super(SideValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "calc"),
values=kwargs.pop(... |
stewartadam/audio-convert-mod | src/audio_convert_mod/acmlogger.py | Python | gpl-2.0 | 3,746 | 0.010144 | # -*- coding: utf-8 -*-
# Copyright (C) 2005, 2006, 2007, 2008, 2009 Stewart Adam
# This file is part of audio-convert-mod.
# audio-convert-mod 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 vers... | details.
# You should have received a copy of the GNU General Public License
# along with audio-convert-mod; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""
The audio-convert-mod logger
Based on fwbackups's fwlogger.py file (2009-07-29)
"""
import... | tetime
import logging
import types
from audio_convert_mod.const import *
from audio_convert_mod.i18n import _
L_DEBUG = logging.DEBUG
L_INFO = logging.INFO
L_WARNING = logging.WARNING
L_ERROR = logging.ERROR
L_CRITICAL = logging.CRITICAL
LOGGERS = {'main': 'acm-main'}
LEVELS = {'debug': 10,
'info': 20,
... |
eunchong/build | third_party/buildbot_8_4p1/buildbot/locks.py | Python | bsd-3-clause | 10,720 | 0.001772 | # This file is part of Buildbot. Buildbot 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 program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without eve... | else:
num_excl = num_excl + 1
del self.waiting[0]
reactor.callLater(0, d.callback, self)
def waitUntilMaybeAvailable(self, owner, access):
| """Fire when the lock *might* be available. The caller will need to
check with isAvailable() when the deferred fires. This loose form is
used to avoid deadlocks. If we were interested in a stronger form,
this would be named 'waitUntilAvailable', and the deferred would fire
after the lock... |
whitepages/nova | nova/tests/functional/api_sample_tests/test_flavor_access.py | Python | apache-2.0 | 4,391 | 0 | # Copyright 2013 IBM Corp.
#
# 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 t... | _add_tenant()
flavor_id = 10
response = self._do_get('flavors/%s/os-flavor-access' % flavor_id)
subs = {
'flavor_id': flavor_id,
'tenant_id': 'fake_tenant',
}
self._verify_response('flavor-access-list-resp', subs, response, 200)
def test_flavor_access... | subs.update(self._get_regexes())
self._verify_response('flavor-access-show-resp', subs, response, 200)
def test_flavor_access_add_tenant(self):
self._create_flavor()
self._add_tenant()
def test_flavor_access_remove_tenant(self):
self._create_flavor()
self._add_te... |
MeteorKepler/RICGA | ricga/reference/ssd.py | Python | apache-2.0 | 11,963 | 0.002842 | #!/usr/bin/env python3
# encoding: utf-8
# Author: MeteorsHub
# License: BSD | Licence
# Contact: [email protected]
# Site: http://www.meteorshub.com
# File: ssd.py
# Time: 2017/4/24 10:17
'''
"""Keras implementation of SSD."""
'''
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import keras.backend as K
from keras.layers im... | from keras.layers import Input
from keras.layers import MaxPooling2D
from keras.layers import Reshape
from keras.layers import ZeroPadding2D
from keras.layers.merge import Concatenate
from keras.models import Model
from ricga.reference.ssd_layers import Normalize
from ricga.reference.ssd_layers import PriorBox
def S... |
GiulioGx/RNNs | sources/datasets/LupusDataset.py | Python | lgpl-3.0 | 25,918 | 0.00355 | import abc
import math
import numpy
from scipy.io import loadmat
from Configs import Configs
from Paths import Paths
from datasets.LupusFilter import VisitsFilter, \
NullFIlter, TemporalSpanFilter
from infos.Info import Info, NullInfo
from infos.InfoElement import SimpleDescription, PrintableInfoElement
from info... | :] = feats[-2, :] - feats[0, :]
outputs[0, :] = targets[-2, :]
mask = numpy.zeros_like(outputs)
| mask[0, :] = 1
return inputs, outputs, mask
class LastAndFirstVisitsTargets(BuildBatchStrategy):
def n_in(self, num_pat_feats):
return num_pat_feats * 2
def keys(self) -> list:
return ['neg', 'late_pos']
def build_batch(self, patience):
feats = patience['features']... |
courtarro/gnuradio | gr-utils/python/modtool/gr-newmod/docs/doxygen/swig_doc.py | Python | gpl-3.0 | 11,634 | 0.003008 | #
# Copyright 2010-2012 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 version 3, or (at your option)
# any later version... | se
# along with GNU Radio; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
#
"""
Creates the swig_doc.i SWIG interface file.
Execute using: python swig_doc.py xml_path outputfilename
The file instructs SWIG to transfer the doxygen comments... | "
import sys, time
from doxyxml import DoxyIndex, DoxyClass, DoxyFriend, DoxyFunction, DoxyFile
from doxyxml import DoxyOther, base
def py_name(name):
bits = name.split('_')
return '_'.join(bits[1:])
def make_name(name):
bits = name.split('_')
return bits[0] + '_make_' + '_'.join(bits[1:])
class B... |
overdev/PythonOS-1.01-cp2-cp3 | apps/calculator/__init__.py | Python | mit | 9,834 | 0.01444 | import pyos
import math
ans = 0
def sqrt(n):
return math.sqrt(n)
def nrt(r, n):
return n**(1.0/r)
def onStart(s, a):
global state, app
state = s
app = a
calc = Calculator()
class Calculator(object):
def __init__(self):
app.ui.clearChildren()
self.input = ""
s... | ,
| width=40, height=40, onClick=self.addInput, onClickData=(0,),
border=1, borderColor=(200,200,200)))
self.numBtns.append(pyos.GUI.Button((40, 200), ",", state.getColorPalette().getColor("background"), state.getColorPalette().getColor("item"), 24,
... |
west2554/fofix | src/SongChoosingScene.py | Python | gpl-2.0 | 43,169 | 0.020501 | #####################################################################
# -*- coding: iso-8859-1 -*- #
# #
# Frets on Fire #
# Copyright (C) 2006 Sami Kyöstilä ... | #
# 2008 evilynux <[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 Fre | e Software Foundation; either version 2 #
# of the License, or (at your option) any later version. #
# #
# This program is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of ... |
aperigault/ansible | test/units/executor/test_task_executor.py | Python | gpl-3.0 | 18,912 | 0.001533 | # (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... | 'c')])
res = te.run()
te._get_loop_items = MagicMock(side_effect=AnsibleError(""))
res = te.run()
self.assertIn("failed", res)
def test_task_executor_get_loop_items(self):
fake_loader = DictDataLoader({})
mock_host = MagicMock()
mock_task = MagicMock()
... | ck()
mock_shared_loader = MagicMock()
mock_shared_loader.lookup_loader = lookup_loader
new_stdin = None
job_vars = dict()
mock_queue = MagicMock()
te = TaskExecutor(
host=mock_host,
task=mock_task,
job_vars=job_vars,
play... |
qu0zl/pfss | pfss/migrations/0029_auto_20150518_1019.py | Python | mit | 731 | 0.001368 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('pfss', '0028_specialability_isstat'),
]
operations = [
migrations.AddField(
model_name='at | tack',
name='bonusToHit',
field=models.IntegerField(default=0),
preserve_default=True,
),
migrations.AlterField(
model_name='attack',
name='attackClass',
field=models.IntegerField(default=0, choices=[(0, b'Primary'), (1, b'Secondary... | , b'Light'), (3, b'One Handed'), (4, b'Two Handed')]),
preserve_default=True,
),
]
|
heracek/django-nonrel | tests/regressiontests/datatypes/tests.py | Python | bsd-3-clause | 4,241 | 0.005187 | import datetime
from django.conf import settings
from django.db import DEFAULT_DB_ALIAS
from django.test import TestCase, skipIfDBFeature
from django.utils import tzinfo
from models import Donut, RumBaba
class DataTypesTestCase(TestCase):
def test_boolean_type(self):
d = Donut(name='Apple Fritter')
... | ime"""
b = RumBaba.objects.create()
# Verify we didn't break DateTimeField behavior
self.assert_(isinstance(b. | baked_timestamp, datetime.datetime))
# We need to test this this way because datetime.datetime inherits
# from datetime.date:
self.assert_(isinstance(b.baked_date, datetime.date) and not isinstance(b.baked_date, datetime.datetime))
|
AxelMatstoms/rpg | world/entities/components/position.py | Python | gpl-3.0 | 308 | 0.006494 | from world.entities.components.compone | nt import Component
class Position(Component):
def __init__(self, entity, x, y):
super().__init__(entity)
self.x = x |
self.y = y
def pos(self):
return (self.x, self.y)
def cpos(self):
return (self.y, self.x)
|
miumok98/weblate | weblate/trans/models/dictionary.py | Python | gpl-3.0 | 6,786 | 0 | # -*- coding: utf-8 -*-
#
# Copyright © 2012 - 2015 Michal Čihař <[email protected]>
#
# This file is part of Weblate <http://weblate.org/>
#
# 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, eithe... | rget = target
self.save()
Change.objects.create(
action=Change.ACTION_DICTIONARY_EDIT,
| dictionary=self,
user=request.user,
target=self.target,
)
|
Flyingfox646/flyingfox | src/custom/rewards.py | Python | mit | 1,025 | 0 | """
examples:
# Tour awards
# available parameters stats/models.py/class Player
# streak 100 or more
def fighter_ace(player):
return player.streak_max >= 100
# total air kills 20 or more
def example_2(player):
if player.ak_total >= 20:
return True
# 20 air kills and 200 ground kills
def example_3... | return player.ak_total >= 20 and player.gk_total >= 200
# Sortie awards
# available parameters stats/models.py/class Sortie
# 5 air kills in one sortie
def fighter_hero(sortie):
return sortie.ak_total >= 5
# Mission awards
# available parameters stats/models.py/class PlayerMission
# 10 air kills in one ... | return player_mission.ak_total >= 15
"""
# streak 100 or more
def fighter_ace(player):
return player.streak_max >= 100
# 5 air kills in one sortie
def fighter_hero(sortie):
return sortie.ak_total >= 5
# 10 air kills in one mission
def mission_hero(player_mission):
return player_mission.ak_total >=... |
jeffbryner/MozDef | alerts/ldap_add.py | Python | mpl-2.0 | 1,114 | 0.001795 | #!/usr/bin/env python
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
# Copyright (c) 2014 Mozilla Corporation
from lib.alerttask import AlertTask
from mozdef_util.qu... | .changetype', 'add')
])
self.filtersManual(search_query)
# Search events
self.searchEventsSimple()
self.walkEvents()
# Set alert properties
def onEvent(self, event):
category = 'ldap'
tags = ['ldap']
severity = 'INFO'
summary='{0} added ... | ails']['actor'], event['_source']['details']['dn'])
# Create the alert object based on these properties
return self.createAlertDict(summary, category, tags, [event], severity)
|
fugwenna/bunkbot | src/rpg/duel_result.py | Python | mit | 623 | 0.00321 | from ..core.bunk_user import BunkUser
"""
Metadata class for easy embeds when a duel has completed
"""
class DuelResult:
def __init__(self, chal: BunkUser, opnt: BunkUser, winner: BunkUser, loser: BunkUser):
| self.challenger: BunkUser = chal
self.opponent: BunkUser = opnt
self.winner: BunkUser = winner
self.loser: BunkUser = loser
self.challenger_roll: int = 0
| self.opponent_roll: int = 0
self.challenger.is_dueling = False
self.challenger.challenged_by_id = None
self.opponent.is_dueling = False
self.opponent.challenged_by_id = None
|
cjcjameson/gpdb | src/test/tinc/tincrepo/mpp/gpdb/tests/storage/access_methods/ao_memory.py | Python | apache-2.0 | 2,282 | 0.009641 | #!/usr/bin/env python
"""
Copyright (c) 2004-Present Pivotal Software, Inc.
This program and the accompanying materials are made available under
the terms of the 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... | rom mpp.models import MPPTestCase
import os
import re
import socket
import time
import shutil
import sys
import signal
class aoreadmemory | (MPPTestCase):
def tearDown(self):
gpfaultinjector = Command('fault injector',
'source $GPHOME/greenplum_path.sh; '
'gpfaultinjector -f malloc_failure '
'-y reset -H ALL -r primary')
gpfaultinjector.run()... |
muisit/freezer | gui/createvaultdialog.py | Python | gpl-3.0 | 1,774 | 0.006764 | #
# Copyright Muis IT 2011 - 2016
#
# This file is part of AWS Freezer
#
# AWS Freezer is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as p | ublished by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# AWS Freezer 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 ... | COPYING file).
# If not, see <http://www.gnu.org/licenses/>.
import globals
import guiobj
class CreateVaultDialog(guiobj.GUIObj):
def __init__(self,builder):
globals.GUI.createvaultdialog=self
self.window = builder.get_object('dialog_create_vault')
handlers ={
"createvault_bu... |
imsparsh/python-social-auth | social/backends/email.py | Python | bsd-3-clause | 251 | 0 | """
Legacy Email backend, docs at:
http://psa.matiasaguirre.net/docs/backends/email.html
"""
from social.backends.legacy import LegacyAuth
class EmailAuth(LegacyAuth):
name = 'email'
| ID_KEY = 'email'
REQUIRES_ | EMAIL_VALIDATION = True
|
cathywu/Sentiment-Analysis | PyML-0.7.9/PyML/classifiers/ext/csvmodel.py | Python | gpl-2.0 | 14,618 | 0.011903 | # This file was automatically generated by SWIG (http://www.swig.org).
# Version 2.0.1
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
# This file is compatible with both classic and new-style classes.
from sys import version_info
if version_info >= (2... | _(self)
def __len__(self): return _csvmodel.IntVector___len__(self)
def pop(self): retur | n _csvmodel.IntVector_pop(self)
def __getslice__(self, *args): return _csvmodel.IntVector___getslice__(self, *args)
def __setslice__(self, *args): return _csvmodel.IntVector___setslice__(self, *args)
def __delslice__(self, *args): return _csvmodel.IntVector___delslice__(self, *args)
def __delitem__(self... |
DeppSRL/open-partecipate | project/open_partecipate/management/commands/fix_provincie_autonome.py | Python | bsd-3-clause | 995 | 0.00402 | # -*- coding: utf-8 -*-
from django.core.management.base import BaseCommand
from ...territori.models import Territorio
class Command(BaseCommand):
help = 'Fix for provincie autonome'
def handle(self, *args, **options):
Territorio.objects.regioni().get(denominazione='TRENTINO-ALTO ADIGE/S | UDTIROL').delete()
for name in ['BOLZANO', 'TRENTO']:
territorio = Territorio.objects.provincie().get(denominazione__istartswith=name)
territorio.pk = None
territorio | .tipo = Territorio.TIPO.R
territorio.cod_reg = territorio.cod_prov
territorio.cod_prov = None
territorio.denominazione = 'P.A. DI {}'.format(name)
territorio.slug = None
territorio.save()
Territorio.objects.provincie().filter(cod_prov=territorio.... |
indico/indico | indico/modules/users/models/suggestions.py | Python | mit | 2,202 | 0.002725 | # This file is part of Indico.
# Copyright (C) 2002 - 2022 CERN
#
# Indico | is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from indico.core.db import db
from indico.util.string import format_repr
class SuggestedCategory(db.Model):
__tablename__ = 'suggested_categories'
__table_args__ = {'schem... |
autoincrement=False
)
category_id = db.Column(
db.Integer,
db.ForeignKey('categories.categories.id'),
primary_key=True,
index=True,
autoincrement=False
)
is_ignored = db.Column(
db.Boolean,
nullable=False,
default=False
)
s... |
alonho/pql | setup.py | Python | bsd-3-clause | 929 | 0.004306 | from setuptools import setup
__version__ = '0.5.0'
setup(name='pql',
version=__version__,
description='A python expression to MongoDB query translator',
author='Alon Horev',
author_email='[email protected]',
url='https://github.com/alonho/pql',
classifiers = ["Development Sta | tus :: 3 - Alpha",
"Intended Audience :: Developers",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.5",
"Operating System :: POSIX :: Linux",
"Operating System :: MacOS :: Mac | OS X"],
license='BSD',
# I know it's bad practice to not specify a pymongo version, but we only
# require the bson.ObjectId type, It's safe to assume it won't change (famous last words)
install_requires=['pymongo',
'python-dateutil'],
packages=['pql']) |
kkopachev/thumbor | thumbor/server.py | Python | mit | 4,551 | 0.00022 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# thumbor imaging service
# https://github.com/thumbor/thumbor/wiki
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2011 globo.com [email protected]
import logging
import logging.config
import os
import socket
import ... | idate_config(config, server_parameters)
importer = get_importer(config)
with get_context(server_parameters, config, importer) as context:
application = get_application(context)
server = run_server( | application, context)
setup_signal_handler(server, config)
tornado.ioloop.IOLoop.instance().start()
if __name__ == "__main__":
main(sys.argv[1:])
|
mozilla-b2g/fxos-certsuite | mcts/certsuite/test_cert.py | Python | mpl-2.0 | 2,006 | 0.006979 | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can | obtain one at http:/ | /mozilla.org/MPL/2.0/.
import unittest
from cert import test_user_agent
class Logger(object):
"""Dummy logger"""
def test_status(this, *args):
pass
class TestCert(unittest.TestCase):
def setUp(self):
self.logger = Logger()
def test_test_user_agent(self):
self.assertFalse(tes... |
chubbymaggie/angr | angr/procedures/win32/dynamic_loading.py | Python | bsd-2-clause | 3,321 | 0.003613 | import angr
import claripy
import logging
l = logging.getLogger('angr.procedures.win32.dynamic_loading')
class LoadLibraryA(angr.SimProcedure):
def run(self, lib_ptr):
lib = self.state.mem[lib_ptr].string.concrete
return self.load(lib)
def load(self, lib):
if '.' not in lib:
... | adLibraryA):
def run(self, lib_ptr, flag1, flag2):
lib = self.state.mem[lib_ptr].wstring.concrete
return self.load(lib)
# if you subclass LoadLibraryA to provide register, you can implement LoadLibraryExW by making an empty class that just
# subclasses your special procedure | and LoadLibraryExW
class GetProcAddress(angr.SimProcedure):
def run(self, lib_handle, name_addr):
if lib_handle.symbolic:
raise angr.errors.SimValueError("GetProcAddress called with symbolic library handle %s" % lib_handle)
lib_handle = self.state.se.eval(lib_handle)
if lib_ha... |
wimberosa/samba | source4/scripting/devel/repl_cleartext_pwd.py | Python | gpl-3.0 | 15,156 | 0.006796 | #!/usr/bin/env python
#
# Copyright Stefan Metzmacher 2011-2012
#
# 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 3 of the License, or
# (at your option) any later version.
#
# Th... | RTED_EXTENSION_GET_MEMBERSHIPS2
bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V6
bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_NONDOMAIN_NCS
bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPO | RTED_EXTENSION_GETCHGREQ_V8
bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_GETCHGREPLY_V5
bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_GETCHGREPLY_V6
bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_ADDENTRYREPLY_V3
bind... |
mlavin/tincan | shoestring/app.py | Python | bsd-2-clause | 1,584 | 0.004419 | import os
import time
from importlib import import_module
from tornado.ioloop import IOLoop
from tornado.web import Application
from .handlers import CreateRoomHandler, GetRoomHandler, SocketHandler, IndexHandler
class ShoestringApplication(Application):
def __init__(self, **kwargs):
backend_name = kw... | 'template_path': os.path.join(os.path.dirname(__file__), os.pardir, 'templates'),
'static_path': os.path.join(os.path.dirname(__file__), os.pardir, 'static'),
'static_url_prefix': '/static/',
'secret': os.environ.get('SHOESTRING_SECRET_KEY', str(os.urandom(75))),
}
... | the application server. Might be immediate or graceful."""
self.backend.shutdown(graceful=graceful)
|
martinahogg/machinelearning | tools/numpy-examples.py | Python | apache-2.0 | 1,533 | 0.02544 | import numpy as np
# Inner (or dot) product
a = np.array([1,2])
b = np.array([3,4])
np | .inner(a, b)
a.dot(b)
# Outer product
a = np.array([1,2])
b = np.array([3,4])
np.outer(a, b)
# Inverse
m = np.array([[1,2], [3,4]])
np.linalg.inv(m)
# Inner (or dot) product
m = np.array([[1,2], [3,4]])
minv = np.li | nalg.inv(m)
m.dot(minv)
# Diagonal
m = np.array([[1,2], [3,4]])
np.diag(m)
m = np.array([1,2])
np.diag(m)
# Determinant
m = np.array([[1,2], [3,4]])
np.linalg.det(m)
# Trace - sum of elements of the diagonal
m = np.array([[1,2], [3,4]])
np.diag(m)
np.diag(m).sum()
np.trace(m)
# Transpose
m = np.array([ [1,2], [... |
zestyr/lbry | lbrynet/core/PaymentRateManager.py | Python | mit | 4,661 | 0.001287 | from lbrynet.core.Strategy import get_default_strategy, OnlyFreeStrategy
from lbrynet import conf
from decimal import Decimal
class BasePaymentRateManager(object):
def __init__(self, rate=None, info_rate=None):
self.min_blob_data_payment_rate = rate if rate is not None else conf.settings['data_rate']
... | b_data_payment_rate()
def accept_rate_blob_data(self, peer, payment_rate):
return payment_rate >= self.get_effective_min_blob_data_payment_rate()
def get_effective_min_blob_data_payment_rate(self):
if self.min_blob_data_payment_rate is None:
return self.base.min_blob_data_payment_r... | er(object):
def __init__(self, base, availability_tracker, generous=None):
"""
@param base: a BasePaymentRateManager
@param availability_tracker: a BlobAvailabilityTracker
@param rate: the min blob data payment rate
"""
self.base = base
self.min_blob_data_pay... |
ahmedaljazzar/edx-platform | cms/djangoapps/contentstore/features/advanced_settings.py | Python | agpl-3.0 | 769 | 0.0013 | # pylint: disable=missing-docstring
# pylint: disable=red | efined-outer-name
from lettuce import step, world
from cms.djangoapps.contentstore.features.common import press_the_notification_button, type_in_codemirror
KEY_CSS = '.key h3.title'
ADVANCED_MODULES_KEY = "Advanced Module List"
def get_index_of(expected_key):
for i, element in enumerate(world.css_find(KEY_CSS))... | on to the array of elements
key = world.css_value(KEY_CSS, index=i)
if key == expected_key:
return i
return -1
def change_value(step, key, new_value):
index = get_index_of(key)
type_in_codemirror(index, new_value)
press_the_notification_button(step, "Save")
world.wait_... |
rbirger/OxfordHCVNonSpatial | Non-Spatial Model Outline and Code_old.py | Python | bsd-2-clause | 44,084 | 0.022684 | # -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# <markdowncell>
# ###Description and preliminary code for Continuous-Time Markov Chain Model
#
# This model will test the importance of including a spatial component in the system. We will use ODEs to describe the dynamics of each lineage and competition between li... | t}& =& \phi_{DT} D_T + (1-\kappa)\phi_{DI} D_I - (\lambda_{virions} + \lambda_{local} +\nu_T) T\\
# \frac{dE}{dt}& =& (1-\eta)(\lambda_{virions} + \lambda_{local} )T - (\alpha +\nu_T)E\\
# \frac{dEX}{dt}& =& \eta(\lambda_{virions} + \lambda_{local} )T - (\alpha_X +\nu_T)E\\
# \frac{dI}{dt}& =& \kappa\phi_{DI} D_I+ \al... | & \nu_T(T+E+EX) - \phi_{DT} D_T\\
# \frac{dD_I}{dt}& =& \nu_I I - \phi_{DI} D_I\\\
# \end{eqnarray*}$
#
# To translate these equations into a continuous-time Markov Chain model, we can calculate the transition probabilities from the parameters above. Let $\vec{X(t)} = [T(t), E(t), EX(t) I(t), D_T(t), D_I(t)]$, so the ... |
ahmadiga/min_edx | lms/envs/devstack.py | Python | agpl-3.0 | 7,967 | 0.004017 | """
Specific overrides to the base prod settings to make development easier.
"""
from os.path import abspath, dirname, join
from .aws import * # pylint: disable=wildcard-import, unused-wildcard-import
# Don't use S3 in devstack, fall back to filesystem
del DEFAULT_FILE_STORAGE
MEDIA_ROOT = "/edx/var/edxapp/uploads"
... |
################################ DEBUG TOOLBAR ################################
INSTALLED_APPS += ('debug_toolbar', 'debug_toolbar_mongo')
MIDDLEWARE_CLASSES += ( |
'django_comment_client.utils.QueryCountDebugMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware',
)
INTERNAL_IPS = ('127.0.0.1',)
DEBUG_TOOLBAR_PANELS = (
'debug_toolbar.panels.versions.VersionsPanel',
'debug_toolbar.panels.timer.TimerPanel',
'debug_toolbar.panels.settings.SettingsPanel'... |
jhseu/tensorflow | tensorflow/python/compiler/tensorrt/trt_convert_windows.py | Python | apache-2.0 | 5,368 | 0.002608 | # Copyright 2019 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... | integration is not available on Windows.")
@tf_export("experimental.tensorrt.Converter", v1=[])
class TrtConverterWindows(object):
"""An offline converter for TF-TRT transformation for TF 2.0 SavedModels.
Currently this is not available on W | indows platform.
"""
def __init__(self,
input_saved_model_dir=None,
input_saved_model_tags=None,
input_saved_model_signature_key=None,
conversion_params=None):
"""Initialize the converter.
Args:
input_saved_model_dir: the directory to load ... |
StefanRijnhart/odoo | addons/analytic/models/analytic.py | Python | agpl-3.0 | 19,270 | 0.005812 | # -*- 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 = {}
res = {}
for elmt in self.browse(cr, uid, ids, context=context):
res[elmt.i | d] = self._get_one_full_name(elmt)
return res
def _get_one_full_name(self, elmt, level=6):
if level<=0:
return '...'
if elmt.parent_id and not elmt.type == 'template':
parent_path = self._get_one_full_name(elmt.parent_id, level-1) + " / "
else:
pa... |
cslansing/shaft | shaft/settings/base.py | Python | mit | 4,489 | 0.000891 | import os
import django
from secret_key import *
# calculated paths for django and the site
# used as starting points for various other paths
DJANGO_ROOT = os.path.dirname(os.path.realpath(django.__file__))
# project root is same as current directory when being called from manage.py
PROJECT_ROOT = os.path.abspath('./'... | CT_APPS]
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING ... | 'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
'... |
yafeunteun/wikipedia-spam-classifier | revscoring/revscoring/features/meta/aggregators.py | Python | mit | 2,017 | 0 | """
These Meta-Features apply an aggregate function t | o
:class:`~revscoring.Data | source` that return lists of values.
.. autoclass revscoring.features.meta.aggregators.sum
.. autoclass revscoring.features.meta.aggregators.len
.. autoclass revscoring.features.meta.aggregators.max
.. autoclass revscoring.features.meta.aggregators.min
"""
from ..feature import Feature
len_builtin = len
sum_built... |
JulyKikuAkita/PythonPrac | cs15211/EvaluateDivision.py | Python | apache-2.0 | 9,882 | 0.004351 | __source__ = 'https://leetcode.com/problems/evaluate-division/description/'
# https://github.com/kamyu104/LeetCode/blob/master/Python/evaluate-division.py
# Time: O(e + q * |V|!), |V| is the number of variables
# Space: O(e)
#
# Description: Leetcode # 399. Evaluate Division
#
# Equations are given in the format A / B... | p[1] if tmp[0] else -1)
return result
# A variation of Floyd-Warshall, computing quotients instead of shortest paths.
# An equation A/B=k is like a graph edge A->B, and (A/B)*(B/C)*(C/D)
# is like the path A->B->C->D. Submitted once, accepted in 35 ms.
# 20ms 99.20%
def calcEquation(self, equations, values, q... | n][num] = 1 / val
for k, i, j in itertools.permutations(quot, 3):
if k in quot[i] and j in quot[k]:
quot[i][j] = quot[i][k] * quot[k][j]
return [quot[num].get(den, -1.0) for num, den in queries]
class TestMethods(unittest.TestCase):
def test_Local(self):
self.assertEqual(1, 1)
... |
912/M-new | virtualenvironment/experimental/lib/python2.7/site-packages/django/conf/locale/bg/formats.py | Python | gpl-2.0 | 772 | 0 | # -*- encoding: utf-8 -*-
# This file is distributed under the same license as the Django package.
#
from __future__ import unicode_literals
# The *_FORMAT strings use the Django date format syntax,
# see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
DATE_FORMAT | = 'd F Y' |
TIME_FORMAT = 'H:i:s'
# DATETIME_FORMAT =
# YEAR_MONTH_FORMAT =
MONTH_DAY_FORMAT = 'j F'
SHORT_DATE_FORMAT = 'd.m.Y'
# SHORT_DATETIME_FORMAT =
# FIRST_DAY_OF_WEEK =
# The *_INPUT_FORMATS strings use the Python strftime format syntax,
# see http://docs.python.org/library/datetime.html#strftime-strptime-behavior
# DATE... |
keiserlab/e3fp | e3fp/fingerprint/array_ops.py | Python | lgpl-3.0 | 9,285 | 0.000539 | """Various array operations.
Author: Seth Axen
E-mail: [email protected]
"""
import numpy as np
from scipy.spatial.distance import pdist, squareform
QUATERNION_DTYPE = np.float64
X_AXIS, Y_AXIS, Z_AXIS = np.identity(3, dtype=np.float64)
EPS = 1e-12 # epsilon, a number close to 0
# Vector Algebra Methods
def as_u... | ype=np.float64)
rotate[:3, :3] = make_rotation_matrix(y, Y_AXIS)
else:
z = np.atleast_2d(z)
rotate_norm = np.identity(4, dtype=np.float64)
x_unit = as_unit(np.cross(y, z))
rotate_norm[:3, :3] = make_rotation_matrix(x_unit, X_AXIS)
new_y = n... | rotate_y = np.identity(4, dtype=np.float64)
rotate_y[:3, :3] = make_rotation_matrix(new_y.flatten(), Y_AXIS)
rotate = np.dot(rotate_y, rotate_norm)
transform = np.dot(rotate, translate)
else:
transform = translate
return transform
def make_rotation_matrix(v0, v1)... |
browniebroke/deezer-python | src/deezer/pagination.py | Python | mit | 3,359 | 0.000298 | from __future__ import annotations
from typing import Generator, Generic, TypeVar, overload
from urllib.parse import parse_qs, urlparse
import deezer
ResourceType = TypeVar("ResourceType")
class PaginatedList(Generic[ResourceType]):
"""Abstract paginated response from the API and make them more Pythonic."""
... | def _fetch_to_index(self, index: int):
while len(self.__elements) <= index and self._could_grow():
| self._grow()
@property
def total(self) -> int:
"""The total number of items in the list, mirroring what Deezer returns."""
if self.__total is None:
params = self.__base_params.copy()
params["limit"] = 1
response_payload = self.__client.request(
... |
DTOcean/dtocean-core | tests/test_data_definitions_pointdict.py | Python | gpl-3.0 | 6,319 | 0.011869 | import pytest
import matplotlib.pyplot as plt
from geoalchemy2.elements import WKTElement
from aneris.control.factory import InterfaceFactory
from dtocean_core.core import (AutoFileInput,
AutoFileOutput,
AutoPlot,
AutoQuery,
... | lt is None
@pytest.mark.parametrize("fext", [".csv", ".xls", ".xlsx"])
def test_PointDict_auto_file(tmpdir, fext):
test_path = tmpdir.mkdir("sub").join("test{}".format(fext))
test_path_str = str(test_path)
raws = [{"one" : (0., 0.),
"two" : (1., 1.),
"three" ... |
for raw, ztest in zip(raws, ztests):
meta = CoreMetaData({"identifier": "test",
"structure": "test",
"title": "test"})
test = PointDict()
fout_factory = InterfaceFactory(AutoFileOutput)
FOutCls = fout_fact... |
bitlair/synlogistics | ajax/views.py | Python | agpl-3.0 | 2,831 | 0.003179 | """
SynLogistics AJAX JSON server interaction for common search boxes and
generic interactive componen | ts.
"""
#
# Copyright (C) by Wilco Baan Hofman <[email protected]> 2011
#
# This program is free software; you can red | istribute 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 option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even ... |
pandas-dev/pandas | pandas/core/window/expanding.py | Python | bsd-3-clause | 23,648 | 0.000634 | from __future__ import annotations
from textwrap import dedent
from typing impor | t (
TYPE_CHECKING,
Any,
Callable,
)
from pandas._typing import (
Axis,
WindowingRankType,
)
if TYPE_CHECKING:
from pandas import DataFrame, Series
from pandas.core.generic import NDFrame
from pandas.compat.numpy import function as nv
from pandas.util._decorators import doc
from pandas.co... | header,
kwargs_compat,
numba_notes,
template_header,
template_returns,
template_see_also,
window_agg_numba_parameters,
window_apply_parameters,
)
from pandas.core.window.rolling import (
BaseWindowGroupby,
RollingAndExpandingMixin,
)
class Expanding(RollingAndExpandingMixin):
"... |
mganeva/mantid | scripts/test/MultiPlotting/MultiPlottingContext_test.py | Python | gpl-3.0 | 2,543 | 0.009438 | # Mantid Repository : https://github.com/mantidproject/mantid
#
# Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
# NScD Oak Ridge National Laboratory, European Spallation Source
# & Institut Laue - Langevin
# SPDX - License - Identifier: GPL - 3.0 +
import unittest
from mantid.py3compat import | mock
from MultiPlotting.multi_plotting_context import PlottingContext
from MultiPlotting.subplot.subplot_context i | mport subplotContext
class gen_ws(object):
def __init__(self,mock):
self._input = "in"
self._OutputWorkspace = mock
def __len__(self):
return 2
@property
def OutputWorkspace(self):
return self._OutputWorkspace
class MultiPlottingContextTest(unittest.TestCase):
def... |
Spiderlover/Toontown | toontown/cogdominium/CogdoFlyingGameGuis.py | Python | mit | 8,010 | 0.001998 | from direct.interval.IntervalGlobal import LerpFunctionInterval
from direct.gui.DirectGui import DirectLabel, DirectFrame, DGG
from dire | ct.showbase.PythonUtil import bound as clamp
from pandac.PandaModules import TextNode, NodePath
from toontown.toonbase import ToontownGlobals
import CogdoUtil
import CogdoFlyingGameGlobals as Globals
class CogdoFlyingProgressG | ui(DirectFrame):
def __init__(self, parent, level, pos2d = Globals.Gui.ProgressPos2D):
DirectFrame.__init__(self, relief=None, state=DGG.NORMAL, sortOrder=DGG.BACKGROUND_SORT_INDEX)
self._parent = parent
self._level = level
self.reparentTo(self._parent)
self.setPos(pos2d[0],... |
li-yuntao/SiliconLives | PytorchModels/tutorials/advanced_tutorial.py | Python | gpl-3.0 | 15,958 | 0.000251 | # -*- coding: utf-8 -*-
r"""
Advanced: Making Dynamic Decisions and the Bi-LSTM CRF
======================================================
Dynamic versus Static Deep Learning Toolkits
--------------------------------------------
Pytorch is a *dynamic* neural network kit. Another example of a dynamic
kit is `Dynet <ht... | decode.
Backpropagation will compute the gradients automatically for us. We
don't have to do anything by hand.
The implementation is not optimized. If you understand what is going on,
you'll probably quickly see that iterating over the next tag in the
forward algorithm could probably be done in one big operation. I w... | d probably use this tagger for real tasks.
"""
# Author: Robert Guthrie
import torch
import torch.autograd as autograd
import torch.nn as nn
import torch.optim as optim
torch.manual_seed(1)
#####################################################################
# Helper functions to make the code more readable.
def ... |
KristianOellegaard/python-nagios-frontend | balbec/balbec_twisted.py | Python | agpl-3.0 | 1,355 | 0.008118 | import argparse
from twisted.internet import reactor
from twisted.web.server import Site
from twisted.web.resource import Resource
import os
from balbec.jsonhandler import JSONHandler
from balbec.xmlhandler import XmlHandler
ROOT = lambda base : os.path.join(os.path.dirname(__file__), base).replace('\\','/')
class St... | config_dir = None
def render_GET(self, request):
if request.received_headers["accept"] == "text/xml":
handler = XmlHandler(self.config_dir)
output = handler.xml()
elif request.received_headers["accept"] == "application/json":
handler = JSONHandler(self.config_dir)... | return output
def main():
parser = argparse.ArgumentParser(description='Run an instance of python-nagios-frontend.')
parser.add_argument('--port', dest='www_port', default=8880, help='Port for the webserver')
parser.add_argument('--configdir', dest='config_dir', default="/etc/python-nagios-frontend/", hel... |
DFEC-R2D2/r2d2 | pygecko/library/battery.py | Python | mit | 1,763 | 0.038003 |
from __future__ import division
from __future__ import print_function
import time
class BatteryLED(object):
def __init__(self, led_matrix):
"""
Handles the battery LED matrix display
"""
self.led = led_matrix
def display(self, value):
"""
Display a value to the LED matrix
"""
battled = self.led
... | d batt <= 103.94:
battled.clear()
for i in range(3, 8):
for j in range(0, 8):
battled.set(i, j, 1)
# 50 Battery
elif batt > 103.56 and batt <= 103.75:
battled.clear()
for i in range(4, 8):
for j in range(0, 8):
| battled.set(i, j, 3)
# 37.5 Battery
elif batt > 103.40 and batt <= 103.56:
battled.clear()
for i in range(5, 8):
for j in range(0, 8):
battled.set(i, j, 3)
# 25 Battery
elif batt > 103.19 and batt <= 103.40:
battled.clear()
for i in range(6, 8):
for j in range(0, 8):
battled.set(... |
CZ-NIC/knot | tests-extra/tests/dnssec/offline_ksk/test.py | Python | gpl-3.0 | 9,849 | 0.003148 | #!/usr/bin/env python3
"""
Test of offline signing using KSR and SKR with pre-planned KSK rollover and automatic ZSK rollover.
"""
import collections
import os
import shutil
import datetime
import subprocess
import time
import random
from subprocess import check_call
from dnstest.utils import *
from dnstest.keys imp... | with | open(skr_out, "w") as fout:
for linein in fin:
lineout = linein
linesplit = linein.split()
if len(linesplit) > 2 and linesplit[2] == "RRSIG":
after_rrsig = 0
rrsig_now += 1
else:
afte... |
arturh85/projecteuler | python/src/problem040.py | Python | mit | 1,911 | 0.002616 | '''
Problem 40
28 March 2003
An irrational decimal fraction is created by concatenating the positive integers:
0.123456789101112131415161718192021...
It can be seen that the 12th digit of the fractional part is 1.
If dn represents the nth digit of the fractional part, find the value of the following expre... | --------------------------------------
Created on 30.01.2015
@author: ahallmann
'''
import unittest
import timeit
import operator
def generate_problem_fraction():
i = 1
while True:
digits = list | (str(i))
for digit in digits:
yield digit
i += 1
def find_generated_values_at(generator, positions):
i = 1
last_position = max(positions)
values = []
for value in generator():
if value is None:
break
if i in positions:
v... |
ronhanson/python-jobmanager-api | jobmanager/api.py | Python | mit | 16,531 | 0.004174 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ai ts=4 sts=4 et sw=4 nu
"""
(c) 2015 Ronan Delacroix
Python Job Manager Server API
:author: Ronan Delacroix
"""
from flask import Flask | , request, Response, render_template, url_for
from functools import wraps
import json
from flask.views import MethodView
import mongoengine.base.common
import mongoengine.errors
import mongoengine.connection
from jobmanager.common as common
from jobmanager.common.job import Job
from jobmana | ger.common.host import Host, HostStatus
import tbx
import tbx.text
import tbx.code
import logging
import arrow
import traceback
from bson.code import Code
from collections import defaultdict
from datetime import datetime, timedelta
# Flask
app = Flask(__name__, static_folder='static', static_url_path='/static', templ... |
the-packet-thrower/pynet | Week02/snmp-test.py | Python | gpl-3.0 | 281 | 0.003559 | from snmp_helper import snmp_ | get_oid,snmp_extract
COMMU | NITY_STRING = 'galileo'
SNMP_PORT = 161
IP = '184.105.247.70'
a_device = (IP, COMMUNITY_STRING, SNMP_PORT)
OID = '1.3.6.1.2.1.1.1.0'
snmp_data = snmp_get_oid(a_device, oid=OID)
output = snmp_extract(snmp_data)
print output
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.