repo_name stringlengths 5 104 | path stringlengths 4 248 | content stringlengths 102 99.9k |
|---|---|---|
yuraic/koza4ok | skTMVA/sci_bdt_electron_DecisionTree.py | from array import array
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import AdaBoostClassifier
from sklearn.metrics import classification_report, roc_auc_score, roc_curve
from sklearn import tree
import cPickle
... |
J216/gimp_be | gimp_be/draw/draw.py | import random, math
import gimp_be
#from gimp_be.utils.quick import qL
from gimp_be.image.layer import editLayerMask
from effects import mirror
import numpy as np
import UndrawnTurtle as turtle
def brushSize(size=-1):
""""
Set brush size
"""
image = gimp_be.gimp.image_list()[0]
drawable = gimp_be.p... |
boisde/Greed_Island | business_logic/order_collector/transwarp/orm.py | #!/usr/bin/env python
# coding:utf-8
"""
Database operation module. This module is independent with web module.
"""
import time, logging
import db
class Field(object):
_count = 0
def __init__(self, **kw):
self.name = kw.get('name', None)
self.ddl = kw.get('ddl', '')
self._default =... |
marshmallow-code/marshmallow-jsonapi | tests/conftest.py | import pytest
from tests.base import Author, Post, Comment, Keyword, fake
def make_author():
return Author(
id=fake.random_int(),
first_name=fake.first_name(),
last_name=fake.last_name(),
twitter=fake.domain_word(),
)
def make_post(with_comments=True, with_author=True, with_... |
petterip/exam-archive | test/rest_api_test_course.py | '''
Testing class for database API's course related functions.
Authors: Ari Kairala, Petteri Ponsimaa
Originally adopted from Ivan's exercise 1 test class.
'''
import unittest, hashlib
import re, base64, copy, json, server
from database_api_test_common import BaseTestCase, db
from flask import json, jsonify... |
samvartaka/keyak-python | utils.py | # -*- coding: utf-8 -*-
# Keyak v2 implementation by Jos Wetzels and Wouter Bokslag
# hereby denoted as "the implementer".
# Based on Keccak Python and Keyak v2 C++ implementations
# by the Keccak, Keyak and Ketje Teams, namely, Guido Bertoni,
# Joan Daemen, Michaël Peeters, Gilles Van Assche and Ronny Van Keer
#
# Fo... |
slundberg/shap | shap/explainers/_deep/deep_pytorch.py | import numpy as np
import warnings
from .._explainer import Explainer
from packaging import version
torch = None
class PyTorchDeep(Explainer):
def __init__(self, model, data):
# try and import pytorch
global torch
if torch is None:
import torch
if version.parse(tor... |
shaggytwodope/rtv | rtv/submission_page.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import time
import curses
from . import docs
from .content import SubmissionContent, SubredditContent
from .page import Page, PageController, logged_in
from .objects import Navigator, Color, Command
from .exceptions import TemporaryFileError
class Subm... |
timkrentz/SunTracker | IMU/VTK-6.2.0/IO/MINC/Testing/Python/TestMNITagPoints.py | #!/usr/bin/env python
import os
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()
# Test label reading from an MNI tag file
#
# The current directory must be writeable.
#
try:
fname = "mni-tagtest.tag"
channel = open(fname, "wb")
... |
Pulgama/supriya | supriya/patterns/EventPattern.py | import uuid
from uqbar.objects import new
from supriya.patterns.Pattern import Pattern
class EventPattern(Pattern):
### CLASS VARIABLES ###
__slots__ = ()
### SPECIAL METHODS ###
def _coerce_iterator_output(self, expr, state=None):
import supriya.patterns
if not isinstance(expr,... |
F5Networks/f5-ansible-modules | ansible_collections/f5networks/f5_modules/plugins/modules/bigiq_regkey_license_assignment.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright: (c) 2017, F5 Networks Inc.
# 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
DOCUMENTATION = r'''
---
module: bigiq_regkey_license_as... |
johnnoone/salt-targeting | src/salt/utils/__init__.py | '''
salt.utils
~~~~~~~~~~
'''
class lazy_property(object):
'''
meant to be used for lazy evaluation of an object attribute.
property should represent non-mutable data, as it replaces itself.
http://stackoverflow.com/a/6849299/564003
'''
def __init__(self, fget):
self.fget = fget
... |
tgbugs/pyontutils | librdflib/setup.py | import re
from setuptools import setup
def find_version(filename):
_version_re = re.compile(r"__version__ = '(.*)'")
for line in open(filename):
version_match = _version_re.match(line)
if version_match:
return version_match.group(1)
__version__ = find_version('librdflib/__init__.... |
zatricion/Streams | ExamplesElementaryOperations/ExamplesOpNoState.py | """This module contains examples of the op() function
where:
op(f,x) returns a stream where x is a stream, and f
is an operator on lists, i.e., f is a function from
a list to a list. These lists are of lists of arbitrary
objects other than streams and agents.
Function f must be stateless, i.e., for any lists u, v:
f(u... |
ndt93/tetris | scripts/agent3.py | import random
from datetime import datetime
from multiprocessing import Pool
import numpy as np
from scipy.optimize import minimize
def worker_func(args):
self = args[0]
m = args[1]
k = args[2]
r = args[3]
return (self.eval_func(m, k, r) -
self.eval_func(m, k, self.rt) -
... |
chrisenytc/pydemi | api/controllers/users.py | # -*- coding: utf-8 -*-
""""
ProjectName: pydemi
Repo: https://github.com/chrisenytc/pydemi
Copyright (c) 2014 Christopher EnyTC
Licensed under the MIT license.
"""
# Dependencies
import uuid
from api import app
from hashlib import sha1
from flask import request
from flask import jsonify as JSON
from api.models.user ... |
bairdj/beveridge | src/scrapy/afltables/afltables/common.py | team_mapping = {
"SY": "Sydney",
"WB": "Western Bulldogs",
"WC": "West Coast",
"HW": "Hawthorn",
"GE": "Geelong",
"FR": "Fremantle",
"RI": "Richmond",
"CW": "Collingwood",
"CA": "Carlton",
"GW": "Greater Western Sydney",
"AD": "Adelaide",
"GC": "Gold Coast",
"ES": "Es... |
SlipknotTN/Dogs-Vs-Cats-Playground | deep_learning/keras/lib/preprocess/preprocess.py | from keras.applications import imagenet_utils
from keras.applications import mobilenet
def dummyPreprocessInput(image):
image -= 127.5
return image
def getPreprocessFunction(preprocessType):
if preprocessType == "dummy":
return dummyPreprocessInput
elif preprocessType == "mobilenet":
... |
SummaLabs/DLS | app/backend/core/models-keras-2x-api/lightweight_layers/layers_pooling.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
__author__ = 'ar'
from layers_basic import LW_Layer, default_data_format
from layers_convolutional import conv_output_length
###############################################
class _LW_Pooling1D(LW_Layer):
input_dim = 3
def __init__(self, pool_size=2, strides=None, padd... |
yamaguchiyuto/icwsm15 | tag_follow_disagreement.py | import sys
tagging_filepath = sys.argv[1]
following_filepath = sys.argv[2]
delim = '\t'
if len(sys.argv) > 3:
delim = sys.argv[3]
graph = {}
for line in open(tagging_filepath):
entry = line.rstrip().split('\t')
src = entry[0]
dst = entry[1]
if not src in graph: graph[src] = {}
graph[src][dst]... |
Agnishom/ascii-art-007 | facebook.py | #!/usr/bin/env python
#
# Copyright 2010 Facebook
#
# 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 la... |
jleni/QRL | src/qrl/core/ChainManager.py | # coding=utf-8
# Distributed under the MIT software license, see the accompanying
# file LICENSE or http://www.opensource.org/licenses/mit-license.php.
import threading
from typing import Optional, Tuple
from pyqrllib.pyqrllib import bin2hstr
from pyqryptonight.pyqryptonight import StringToUInt256, UInt256ToString
fr... |
yenliangl/bitcoin | test/functional/test_framework/blocktools.py | #!/usr/bin/env python3
# Copyright (c) 2015-2020 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Utilities for manipulating blocks and transactions."""
import struct
import time
import unittest
from... |
alphagov/govuk-puppet | modules/collectd/files/usr/lib/collectd/python/redis_queues.py | # 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; only version 2 of the License is applicable.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; witho... |
eduardoedson/scp | usuarios/forms.py | from crispy_forms.helper import FormHelper
from crispy_forms.layout import Fieldset, Layout
from django import forms
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth.models import User
from django.contrib.auth.password_validation import validate_password
from django.core.exceptions impo... |
MrLeeh/jsonwatchqt | jsonwatchqt/mainwindow.py | #! python3
"""
GUI for Ultrasonic Temperature Controller
Copyright (c) 2015 by Stefan Lehmann
"""
import os
import datetime
import logging
import json
import serial
from qtpy.QtWidgets import QAction, QDialog, QMainWindow, QMessageBox, \
QDockWidget, QLabel, QFileDialog, QApplication
from qtpy.QtGui imp... |
YoApp/yo-water-tracker | server.py | # -*- coding: utf-8 -*-
"""
"""
from datetime import datetime, timedelta
import os
from flask import request
from flask import Flask
import pytz
import db
from utils import get_remote_addr, get_location_data
app = Flask(__name__)
@app.route('/yo-water/', methods=['POST', 'GET'])
def yowater():
payload = re... |
ctames/conference-host | webApp/urls.py | from django.conf.urls import patterns, include, url
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
admin.autodiscover()
import views
urlpatterns = patterns('',
url(r'^pis', views.pis),
url(r'^words', views.words, { 'titles': False }),
url(r'^p... |
jsargiot/restman | tests/steps/share.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import base64
import json
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from behave import *
@step('I share first element in the history list')
def step_impl(... |
bitmazk/django-libs | runtests.py | #!/usr/bin/env python
"""
This script is used to run tests, create a coverage report and output the
statistics at the end of the tox run.
To run this script just execute ``tox``
"""
import re
from fabric.api import local, warn
from fabric.colors import green, red
if __name__ == '__main__':
# Kept some files for ... |
baroquehq/baroque | baroque/datastructures/counters.py | from baroque.entities.event import Event
class EventCounter:
"""A counter of events."""
def __init__(self):
self.events_count = 0
self.events_count_by_type = dict()
def increment_counting(self, event):
"""Counts an event
Args:
event (:obj:`baroque.entities.ev... |
yangshun/cs4243-project | app/surface.py | import numpy as np
class Surface(object):
def __init__(self, image, edge_points3d, edge_points2d):
"""
Constructor for a surface defined by a texture image and
4 boundary points. Choose the first point as the origin
of the surface's coordinate system.
:param image: image a... |
Royal-Society-of-New-Zealand/NZ-ORCID-Hub | orcid_api/models/contributor_orcid.py | # coding: utf-8
"""
ORCID Member
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: Latest
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import r... |
vollov/i18n-django-api | page/migrations/0001_initial.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Page',
fields=[
('id', models.AutoField(verbose... |
jonrf93/genos | dbservices/tests/functional_tests/steps/user_service_steps.py | from behave import given, when, then
from genosdb.models import User
from genosdb.exceptions import UserNotFound
# 'mongodb://localhost:27017/')
@given('a valid user with values {username}, {password}, {email}, {first_name}, {last_name}')
def step_impl(context, username, password, email, first_name, last_name):
... |
nkoech/trialscompendium | trialscompendium/trials/api/treatment/filters.py | from rest_framework.filters import (
FilterSet
)
from trialscompendium.trials.models import Treatment
class TreatmentListFilter(FilterSet):
"""
Filter query list from treatment database table
"""
class Meta:
model = Treatment
fields = {'id': ['exact', 'in'],
'no_r... |
mooja/ssip3 | app/members/views.py | from io import BytesIO
from django import forms
from django.http import HttpResponse
from django.template import Context, Template
from braces.views import LoginRequiredMixin
from django.views.generic import DetailView, ListView
from django.views.decorators.http import require_http_methods
from django.contrib import... |
wikomega/wikodemo | test.py |
import time
import multiprocessing
from flask import Flask
app = Flask(__name__)
backProc = None
def testFun():
print('Starting')
while True:
time.sleep(3)
print('looping')
time.sleep(3)
print('3 Seconds Later')
@app.route('/')
def root():
return 'Started a background pr... |
orangain/jenkins-docker-sample | tests.py | # coding: utf-8
import unittest
from config_reader import ConfigReader
class TestConfigReader(unittest.TestCase):
def setUp(self):
self.config = ConfigReader("""
<root>
<person>
<name>山田</name>
<age>15</age>
</person>
... |
realpython/flask-skeleton | {{cookiecutter.app_slug}}/project/tests/test_user.py | # project/server/tests/test_user.py
import datetime
import unittest
from flask_login import current_user
from base import BaseTestCase
from project.server import bcrypt
from project.server.models import User
from project.server.user.forms import LoginForm
class TestUserBlueprint(BaseTestCase):
def test_correc... |
jokkebk/euler | p144.py | inside = lambda x, y: 4*x*x+y*y <= 100
def coll(sx, sy, dx, dy):
m = 0
for p in range(32):
m2 = m + 2**(-p)
if inside(sx + dx * m2, sy + dy * m2): m = m2
return (sx + dx*m, sy + dy*m)
def norm(x, y):
l = (x*x + y*y)**0.5
return (x/l, y/l)
sx, sy = 0, 10.1
dx, dy = 1.4, -19.7
for ... |
t-mertz/slurmCompanion | django-web/webcmd/cmdtext.py | import sys
MAX_NUM_STORED_LINES = 200
MAX_NUM_LINES = 10
LINEWIDTH = 80
class CmdText(object):
"""
Represents a command line text device. Text is split into lines
corresponding to the linewidth of the device.
"""
def __init__(self):
"""
Construct empty object.
"""
s... |
cwahbong/onirim-py | tests/test_door.py | """
Tests for a door card.
"""
import pytest
from onirim import card
from onirim import component
from onirim import core
from onirim import agent
class DoorActor(agent.Actor):
"""
"""
def __init__(self, do_open):
self._do_open = do_open
def open_door(self, content, door_card):
retu... |
alvaroribas/modeling_TDs | Herschel_mapmaking/scanamorphos/PACS/general_script_L1_PACS.py | ### This script fetches level-1 PACS imaging data, using a list generated by the
### archive (in the CSV format), attaches sky coordinates and masks to them
### (by calling the convertL1ToScanam task) and save them to disk in the correct
### format for later use by Scanamorphos.
### See important instructions below.
... |
lasote/conan | conans/client/generators/visualstudio_multi.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from conans.model import Generator
from conans.client.generators import VisualStudioGenerator
from xml.dom import minidom
from conans.util.files import load
class VisualStudioMultiGenerator(Generator):
template = """<?xml version="1.0" encoding="utf-8"?>
<P... |
reggieroby/devpack | frameworks/djangoApp/djangoApp/settings.py | """
Django settings for djangoApp project.
Generated by 'django-admin startproject' using Django 1.10.5.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import ... |
seccom-ufsc/hertz | hertz/settings.py | import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/
# SECURITY WARNING: keep t... |
zillow/ctds | tests/test_tds_parameter.py | import re
import warnings
import ctds
from .base import TestExternalDatabase
from .compat import PY3, PY36, unicode_
class TestTdsParameter(TestExternalDatabase):
def test___doc__(self):
self.assertEqual(
ctds.Parameter.__doc__,
'''\
Parameter(value, output=False)
Explicitly de... |
purrcat259/peek | tests/unit/test_line.py | import copy
import pytest
from peek.line import InvalidIpAddressException, Line, InvalidStatusException
# 127.0.0.1 - - [01/Jan/1970:00:00:01 +0000] "GET / HTTP/1.1" 200 193 "-" "Python"
test_line_contents = {
'ip_address': '127.0.0.1',
'timestamp': '[01/Jan/1970:00:00:01 +0000]',
'verb': 'GET',
... |
phildini/logtacts | invitations/consumers.py | import logging
import requests
from django.conf import settings
from django.contrib.sites.models import Site
from django.core.mail import EmailMultiAlternatives
from django.template.loader import get_template
from django.utils import timezone
from invitations.models import Invitation
logger = logging.getLogger('email... |
alneberg/sillymap | sillymap/burrows_wheeler.py |
def burrows_wheeler(text):
"""Calculates the burrows wheeler transform of <text>.
returns the burrows wheeler string and the suffix array indices
The text is assumed to not contain the character $"""
text += "$"
all_permutations = []
for i in range(len(text)):
all_permutations.append(... |
PierreMarchand20/htool | interface/htool/multihmatrix.py | #!/usr/bin/env python
# coding: utf-8
import os,sys
import ctypes
import numpy as np
from .hmatrix import _C_HMatrix, HMatrix
class _C_MultiHMatrix(ctypes.Structure):
"""Holder for the raw data from the C++ code."""
pass
class AbstractMultiHMatrix:
"""Common code for the two actual MultiHMatrix classes... |
ioguntol/NumTy | numty/congruences.py | import primes as py
def lcm(a, b):
return a * b / gcd(a, b)
def gcd(a, b):
while b != 0:
(a, b) = (b, a % b)
return a
# Returns two integers x, y such that gcd(a, b) = ax + by
def egcd(a, b):
if a == 0:
return (0, 1)
else:
y, x = egcd(b % a, a)
return (x - (b ... |
kmod/icbd | icbd/type_analyzer/tests/basic.py | a = a # e 4
a = 1 # 0 int
l = [a] # 0 [int]
d = {a:l} # 0 {int:[int]}
s = "abc"
c = ord(s[2].lower()[0]) # 0 int # 4 (str) -> int
l2 = [range(i) for i in d] # 0 [[int]]
y = [(a,b) for a,b in {1:'2'}.iteritems()] # 0 [(int,str)]
b = 1 # 0 int
if 0:
b = '' # 4 str
else:
b = str(b) # 4 str # 12 int
... |
nVentiveUX/mystartupmanager | mystartupmanager/showcase/apps.py | # Copyright (c) 2016 nVentiveUX
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distri... |
lixxu/sanic | sanic/request.py | import asyncio
import email.utils
import json
import sys
from cgi import parse_header
from collections import namedtuple
from http.cookies import SimpleCookie
from urllib.parse import parse_qs, unquote, urlunparse
from httptools import parse_url
from sanic.exceptions import InvalidUsage
from sanic.log import error_l... |
tailhook/tilenol | tilenol/layout/examples.py | from .tile import Split, Stack, TileStack
class Tile(Split):
class left(Stack):
weight = 3
priority = 0
limit = 1
class right(TileStack):
pass
class Max(Split):
class main(Stack):
tile = False
class InstantMsg(Split):
class left(TileStack): # or maybe no... |
reviewboard/reviewboard | reviewboard/hostingsvcs/bugtracker.py | from djblets.cache.backend import cache_memoize
class BugTracker(object):
"""An interface to a bug tracker.
BugTracker subclasses are used to enable interaction with different
bug trackers.
"""
def get_bug_info(self, repository, bug_id):
"""Get the information for the specified bug.
... |
tylerprete/evaluate-math | postfix.py | import sys
from stack import Stack
def parse_expression_into_parts(expression):
"""
Parse expression into list of parts
:rtype : list
:param expression: str # i.e. "2 * 3 + ( 2 - 3 )"
"""
raise NotImplementedError("complete me!")
def evaluate_expression(a, b, op):
raise NotImplementedErr... |
penzance/ab-testing-tool | ab_tool/tests/test_experiment_pages.py | from ab_tool.tests.common import (SessionTestCase, TEST_COURSE_ID,
TEST_OTHER_COURSE_ID, NONEXISTENT_TRACK_ID, NONEXISTENT_EXPERIMENT_ID,
APIReturn, LIST_MODULES)
from django.core.urlresolvers import reverse
from ab_tool.models import (Experiment, InterventionPointUrl)
from ab_tool.exceptions import (EXPERIMENT... |
moremorefor/Logpot | logpot/admin/setting.py | #-*- coding: utf-8 -*-
from flask import current_app, flash, url_for, request
from flask_admin import expose, BaseView
from logpot.admin.base import AuthenticateView, flash_errors
from logpot.admin.forms import SettingForm
from logpot.utils import ImageUtil, getDirectoryPath, loadSiteConfig, saveSiteConfig
import os... |
leifos/ifind | ifind/search/exceptions.py | # TODO When raising an exception pass a lambda function, the function being the module/path/name thing
ERROR = {'default': "Unknown engine error ({0})",
400: "Bad request sent to search API ({0})",
401: "Incorrect API Key ({0})",
403: "Correct API but request refused ({0})",
404: "B... |
ddm/pcbmode | pcbmode/utils/excellon.py | #!/usr/bin/python
import os
import re
from lxml import etree as et
import pcbmode.config as config
from . import messages as msg
# pcbmode modules
from . import utils
from .point import Point
def makeExcellon(manufacturer='default'):
"""
"""
ns = {'pcbmode':config.cfg['ns']['pcbmode'],
'svg... |
moradology/kmeans | tests/testkmeans.py | """Run tests for the kmeans portion of the kmeans module"""
import kmeans.kmeans.kmeans as kmeans
import numpy as np
import random
def test_1dim_distance():
"""See if this contraption works in 1 dimension"""
num1 = random.random()
num2 = random.random()
assert kmeans.ndim_euclidean_distance(num1, num... |
rossplt/ross-django-utils | ross/settings.py | """
Django settings for ross project.
Generated by 'django-admin startproject' using Django 1.10.6.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import os
#... |
algorithmiaio/algorithmia-python | Algorithmia/util.py | import re
import hashlib
FNAME_MATCH = re.compile(r'/([^/]+)$') # From the last slash to the end of the string
PREFIX = re.compile(r'([^:]+://)(/)?(.+)') # Check for a prefix like data://
def getParentAndBase(path):
match = PREFIX.match(path)
if match is None:
if path.endswith('/'):
st... |
eifuentes/kaggle_whats_cooking | train_word2vec_rf.py | """
train supervised classifier with what's cooking recipe data
objective - determine recipe type categorical value from 20
"""
import time
from features_bow import *
from features_word2vec import *
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import RandomForestClassifier, ExtraTreesClassifie... |
inveniosoftware/invenio-search | invenio_search/config.py | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2015-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Configuration options for Invenio-Search.
The documentation for the configuration... |
adamatan/polycircles | polycircles/test/test_different_outputs.py | import unittest
from polycircles import polycircles
from nose.tools import assert_equal, assert_almost_equal
class TestDifferentOutputs(unittest.TestCase):
"""Tests the various output methods: KML style, WKT, lat-lon and lon-lat."""
def setUp(self):
self.latitude = 32.074322
self.longitude = ... |
abonaca/gary | gary/util.py | # coding: utf-8
""" General utilities. """
from __future__ import division, print_function
__author__ = "adrn <adrn@astro.columbia.edu>"
# Standard library
import collections
import sys
import logging
import multiprocessing
# Third-party
import numpy as np
__all__ = ['get_pool']
# Create logger
logger = logging.... |
jeremiedecock/snippets | python/pygame/hello_text.py | #!/usr/bin/env python
import pygame
pygame.display.init()
pygame.font.init()
modes_list = pygame.display.list_modes()
#screen = pygame.display.set_mode(modes_list[0], pygame.FULLSCREEN) # the highest resolution with fullscreen
screen = pygame.display.set_mode(modes_list[-1]) # the lowest resolu... |
gjcarneiro/yacron | yacron/cron.py | import asyncio
import asyncio.subprocess
import datetime
import logging
from collections import OrderedDict, defaultdict
from typing import Any, Awaitable, Dict, List, Optional, Union # noqa
from urllib.parse import urlparse
from aiohttp import web
import yacron.version
from yacron.config import (
JobConfig,
p... |
ENCODE-DCC/encoded | src/encoded/tests/fixtures/schemas/genetic_modification.py | import pytest
@pytest.fixture
def genetic_modification(testapp, lab, award):
item = {
'award': award['@id'],
'lab': lab['@id'],
'modified_site_by_coordinates': {
'assembly': 'GRCh38',
'chromosome': '11',
'start': 20000,
'end': 21000
}... |
kengz/Unity-Lab | test/env/test_vec_env.py | from slm_lab.env.vec_env import make_gym_venv
import numpy as np
import pytest
@pytest.mark.parametrize('name,state_shape,reward_scale', [
('PongNoFrameskip-v4', (1, 84, 84), 'sign'),
('LunarLander-v2', (8,), None),
('CartPole-v0', (4,), None),
])
@pytest.mark.parametrize('num_envs', (1, 4))
def test_make... |
emanuele/jstsp2015 | classif_and_ktst.py | """Classification-based test and kernel two-sample test.
Author: Sandro Vega-Pons, Emanuele Olivetti.
"""
import os
import numpy as np
from sklearn.metrics import pairwise_distances, confusion_matrix
from sklearn.metrics import pairwise_kernels
from sklearn.svm import SVC
from sklearn.cross_validation import Stratifi... |
cessor/gameoflife | config.py | from collections import namedtuple
Resolution = namedtuple('Resolution', ['x', 'y'])
class Resolutions(object):
resolutions = [
(1920, 1200),
(1920, 1080),
(1680, 1050),
(1440, 900),
(1360, 768),
(1280, 800),
(1024, 640)
]
@classmethod
... |
huyphan/pyyawhois | test/record/parser/test_response_whois_nic_pw_status_available.py |
# This file is autogenerated. Do not edit it manually.
# If you want change the content of this file, edit
#
# spec/fixtures/responses/whois.nic.pw/status_available
#
# and regenerate the tests with the following script
#
# $ scripts/generate_tests.py
#
from nose.tools import *
from dateutil.parser import parse a... |
daicang/Leetcode-solutions | 268-missing-number.py | class Solution(object):
def missingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
xor = len(nums)
for i, n in enumerate(nums):
xor ^= n
xor ^= i
return xor
inputs = [
[0],
[1],
[3,0,1],
[9,6,4,2,3,5,7,0... |
matslindh/codingchallenges | adventofcode2021/day10.py | from math import floor
def score_syntax_errors(program_lines):
points = {')': 3, ']': 57, '}': 1197, '>': 25137}
s = 0
scores_auto = []
for line in program_lines:
corrupted, stack = corrupted_character(line)
if corrupted:
s += points[corrupted]
else:
s... |
IECS/MansOS | tools/lib/tests/configtest.py | #!/usr/bin/python
#
# Config file test app (together with test.cfg file)
#
import os, sys
sys.path.append("..")
import configfile
cfg = configfile.ConfigFile("test.cfg")
cfg.setCfgValue("name1", "value1")
cfg.setCfgValue("name2", "value2")
cfg.selectSection("user")
cfg.setCfgValue("username", "janis")
cfg.setCfgV... |
ernitron/radio-server | radio-server/server.py | #!/usr/bin/env python3
"""
My radio server application
For my eyes only
"""
#CREATE TABLE Radio(id integer primary key autoincrement, radio text, genre text, url text);
uuid='56ty66ba-6kld-9opb-ak29-0t7f5d294686'
# Import CherryPy global namespace
import os
import sys
import time
import socket
import cherrypy
imp... |
babyliynfg/cross | tools/project-creator/Python2.6.6/Lib/test/test_pyclbr.py | '''
Test cases for pyclbr.py
Nick Mathewson
'''
from test.test_support import run_unittest, import_module
import sys
from types import ClassType, FunctionType, MethodType, BuiltinFunctionType
import pyclbr
from unittest import TestCase
StaticMethodType = type(staticmethod(lambda: None))
ClassMethodTyp... |
wikimedia/pywikibot-core | scripts/djvutext.py | #!/usr/bin/python3
"""
This bot uploads text from djvu files onto pages in the "Page" namespace.
It is intended to be used for Wikisource.
The following parameters are supported:
-index:... name of the index page (without the Index: prefix)
-djvu:... path to the djvu file, it shall be:
... |
Azure/azure-sdk-for-python | sdk/sql/azure-mgmt-sql/azure/mgmt/sql/operations/_managed_database_queries_operations.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
MyNameIsMeerkat/skyline | src/webapp/webapp.py | import redis
import logging
import simplejson as json
import sys
from msgpack import Unpacker
from flask import Flask, request, render_template
from daemon import runner
from os.path import dirname, abspath
# add the shared settings file to namespace
sys.path.insert(0, dirname(dirname(abspath(__file__))))
import setti... |
johnrocamora/ImagePy | max_tiff.py | from PIL import Image
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
img1 = Image.open('multipage.tif')
# The following approach seems to be having issue with the
# current TIFF format data
print('The size of each frame is:')
print(img1.size)
# Plots first frame
print('Frame 1'... |
SF-Zhou/LeetCode.Solutions | solutions/regular_expression_matching.py | class R:
def __init__(self, c):
self.c = c
self.is_star = False
def match(self, c):
return self.c == '.' or self.c == c
class Solution(object):
def isMatch(self, s, p):
"""
:type s: str
:type p: str
:rtype: bool
"""
rs = []
"... |
HellerCommaA/flask-material-lite | sample_application/__init__.py | from flask import Flask, render_template, flash
from flask_material_lite import Material_Lite
from flask_appconfig import AppConfig
from flask_wtf import Form, RecaptchaField
from flask_wtf.file import FileField
from wtforms import TextField, HiddenField, ValidationError, RadioField,\
BooleanField, SubmitField, Int... |
tmetsch/graph_stitcher | stitcher/vis.py |
"""
Visualize possible stitches with the outcome of the validator.
"""
import math
import random
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import stitcher
SPACE = 25
TYPE_FORMAT = {'a': '^', 'b': 's', 'c': 'v'}
def show(graphs, request, title... |
DCOD-OpenSource/django-simple-help | simple_help/admin.py | # -*- coding: utf-8 -*-
# django-simple-help
# simple_help/admin.py
from __future__ import unicode_literals
from django.contrib import admin
try: # add modeltranslation
from modeltranslation.translator import translator
from modeltranslation.admin import TabbedDjangoJqueryTranslationAdmin
except ImportErro... |
codeif/crimg | crimg/bin.py | # -*- coding: utf-8 -*-
import sys
from io import BytesIO
import argparse
from PIL import Image
from .api import crop_resize
parser = argparse.ArgumentParser(
description='crop and resize an image without aspect ratio distortion.')
parser.add_argument('image')
parser.add_argument('-w', '-W', '--width', metavar='<... |
MetaPlot/MetaPlot | metaplot/helpers.py | from __future__ import print_function
import os
import sys
import subprocess
import pkg_resources
try:
import pkg_resources
_has_pkg_resources = True
except:
_has_pkg_resources = False
try:
import svn.local
_has_svn_local = True
except:
_has_svn_local = False
def test_helper():
return... |
ExCiteS/geokey-sapelli | geokey_sapelli/migrations/0006_sapelliproject_sapelli_fingerprint.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('geokey_sapelli', '0005_sapellifield_truefalse'),
]
operations = [
migrations.AddField(
model_name='sapelliprojec... |
Who8MyLunch/euler | problem_001.py |
from __future__ import division, print_function #, unicode_literals
"""
Multiples of 3 and 5
If we list all the natural numbers below 10 that are multiples
of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
"""
import numpy as np
# Setup.
nu... |
255BITS/HyperGAN | hypergan/train_hooks/negative_momentum_train_hook.py | import torch
from hypergan.train_hooks.base_train_hook import BaseTrainHook
class NegativeMomentumTrainHook(BaseTrainHook):
def __init__(self, gan=None, config=None, trainer=None):
super().__init__(config=config, gan=gan, trainer=trainer)
self.d_grads = None
self.g_grads = None
def gradients(sel... |
djgagne/hagelslag | hagelslag/evaluation/MulticlassContingencyTable.py | import numpy as np
__author__ = 'David John Gagne <djgagne@ou.edu>'
def main():
# Contingency Table from Wilks (2011) Table 8.3
table = np.array([[50, 91, 71],
[47, 2364, 170],
[54, 205, 3288]])
mct = MulticlassContingencyTable(table, n_classes=table.shape[0],
... |
bcimontreal/bci_workshop | python/extra_stuff/livebargraph.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 25 21:11:45 2017
@author: hubert
"""
import numpy as np
import matplotlib.pyplot as plt
class LiveBarGraph(object):
"""
"""
def __init__(self, band_names=['delta', 'theta', 'alpha', 'beta'],
ch_names=['TP9', 'AF7', 'A... |
KMPSUJ/lego_robot | pilot.py | # -*- coding: utf-8 -*-
from modules import Robot
import time
r = Robot.Robot()
state = [0, 1000, 1500]
(run, move, write) = range(3)
i = run
slowdown = 1
flag_A = 0
flag_C = 0
lock = [0, 0, 0, 0]
while(True):
a = r.Read()
for it in range(len(lock)):
if lock[it]:
lock[it] = lock[it] - 1
... |
arruda/amao | AMAO/apps/Corretor/models/retorno.py | # -*- coding: utf-8 -*-
from django.db import models
from Corretor.base import CorretorException
from Corretor.base import ExecutorException
from Corretor.base import CompiladorException
from Corretor.base import ComparadorException
from Corretor.base import LockException
from model_utils import Choices
class Retorn... |
lmazuel/azure-sdk-for-python | azure-mgmt-network/azure/mgmt/network/v2017_10_01/models/application_gateway_ssl_predefined_policy.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.