text string | size int64 | token_count int64 |
|---|---|---|
import numpy as np
import cv2
import sys
import json
import os
if (len(sys.argv) != 5):
print('2 arguments required')
exit()
img1 = cv2.imread(sys.argv[1])
img2 = cv2.imread(sys.argv[2])
file = open(sys.argv[4], "r")
points = json.loads(file.read())
dst_pts = np.float32(points['old']).reshape(-1,1,2)
src_p... | 2,309 | 1,055 |
"""
Parameter optimization with optuna for Cpp code
author: Atsushi Sakai
"""
import optuna
import numpy as np
import matplotlib.pyplot as plt
import subprocess
def HimmelblauFunction(x, y):
"""
Himmelblau's function
see Himmelblau's function - Wikipedia, the free encyclopedia
http://en.wikipedia.... | 1,634 | 665 |
# -*- coding: utf-8 -*-
# author: Tac
# contact: gzzhanghuaxiong@corp.netease.com
import os.path
from PyQt6.QtWidgets import QFrame, QVBoxLayout, QPushButton, QSizePolicy, QFileDialog, QMessageBox
from PyQt6.QtCore import Qt, QDir, QModelIndex
from gui.excel_list_view import ExcelListView
from gui.model.excel_list_m... | 5,385 | 1,728 |
from logging import getLogger
from openrazer.client import DeviceManager, constants as razer_constants
from i3razer import config_contants as conf
from i3razer.config_parser import ConfigParser
from i3razer.layout import layouts
from i3razer.pyxhook import HookManager
ERR_DAEMON_OFF = -2 # openrazer is not running
... | 16,359 | 4,622 |
#!/usr/bin/env python
# coding: utf-8
import logging
import asyncio
import xumm
class StorageExample:
def __init__(self):
logging.debug('')
self.sdk = xumm.XummSdk('API_KEY', 'API_SECRET')
self.logger = logging.getLogger(self.__module__)
self.logger.setLevel(level=logging.DEBUG)
... | 1,471 | 457 |
"""
dns_cache.py
Copyright 2006 Andres Riancho
This file is part of w3af, http://w3af.org/ .
w3af 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 of the License.
w3af is distributed in the hope that i... | 2,318 | 797 |
import copy
import attrdict
import svgwrite
import yaml
from .compat import StringIO
from .fretboard import Fretboard
from .utils import dict_merge
CHORD_STYLE = '''
string:
muted_font_color: silver
open_font_color: steelblue
'''
class Chord(object):
default_style = dict_merge(
yaml.safe_load(... | 3,875 | 1,155 |
from keras.datasets import imdb
top_words = 10000
(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=top_words)
#imdb.get_word_index()
word_dict = imdb.get_word_index()
word_dict = { key:(value + 3) for key, value in word_dict.items() }
word_dict[''] = 0 # Padding
word_dict['>'] = 1 # Start
word_dict['?'... | 2,610 | 932 |
from http import HTTPStatus
import simplekml
from flask_jwt_extended import jwt_required
from flask_restful import Resource
from flask_restful import reqparse
from models.pin_location_data import Tracker
class ExportToKML(Resource):
"""
Export Location Data to KML
"""
def __init__(self) -> None:
... | 2,145 | 619 |
import os
import pytest
from datetime import datetime
from .models import (
Article,
Editor,
EmbeddedArticle,
Player,
Reporter,
Child,
ProfessorMetadata,
ProfessorVector,
ChildRegisteredBefore,
ChildRegisteredAfter,
ParentWithRelationship,
CellTower,
Publisher,
)
cu... | 4,658 | 1,664 |
import curses
scr = curses.initscr()
curses.halfdelay(5) # How many tenths of a second are waited, from 1 to 255
curses.noecho() # Wont print the input
while True:
char = scr.getch() # This blocks (waits) until the time has elapsed,
# or there is input to be handled
scr.clear() # Clears the screen
... | 471 | 168 |
from factory import Faker
from .network_node import NetworkNodeFactory
from ..constants.network import ACCOUNT_FILE_HASH_LENGTH, BLOCK_IDENTIFIER_LENGTH, MAX_POINT_VALUE, MIN_POINT_VALUE
from ..models.network_validator import NetworkValidator
class NetworkValidatorFactory(NetworkNodeFactory):
daily_confirmation_... | 669 | 219 |
from menu.models import Menu
from products.models import Product, Category
def get_dashboard_data_summary():
cardapios = Menu.objects.all()
produtos = Product.objects.all()
categorias = Category.objects.all()
return {'total_cardapios': len(cardapios),
'total_produtos': len(produtos),
... | 365 | 109 |
# crawl_drugbank.py
import time
import pickle
import json
import MySQLdb
import httplib
import urllib2 as urllib
from collections import defaultdict
import dbcrawler_util as util
from datetime import datetime
from bs4 import BeautifulSoup as bs
outDir = '/home/tor/robotics/prj/csipb-jamu-prj/dataset/drugbank/drugbank... | 9,954 | 3,605 |
# -*- coding: utf-8 -*-
# flake8: noqa
# -------------- Add path of _k2.so into sys.path --------------
import os as _os
import sys as _sys
_current_module = _sys.modules[__name__]
_k2_dir = _os.path.dirname(_current_module.__file__)
if not hasattr(_current_module, "__path__"):
__path__ = [_k2_dir]
elif _k2_dir... | 1,051 | 357 |
#coding:utf-8
'''
author : linkin
e-mail : yooleak@outlook.com
date : 2018-11-15
'''
import amipy
from amipy.BaseClass import Hub
from amipy.middlewares import MiddleWareManager
from amipy.util.load import load_py
from amipy.log import getLogger
class SpiderHub(Hub):
def __new__(cls, *args, **kwargs... | 3,569 | 1,103 |
from .not_production_settings import * # noqa
DEBUG = True
WEBPACK_LOADER["DEFAULT"][ # noqa
"LOADER_CLASS"
] = "contentcuration.tests.webpack_loader.TestWebpackLoader"
TEST_ENV = True
| 194 | 72 |
import numpy as np
def ratios(pops1, pops2):
totals1 = np.array(pops1[0]) + np.array(pops1[1])
totals2 = np.array(pops2[0]) + np.array(pops2[1])
change_ratio = np.delete(totals2, 0) / np.delete(totals1, -1)
change_ratio = np.delete(change_ratio, -1)
baby_ratio = totals2[0] / np.sum(np.array(pops1... | 1,050 | 466 |
#!/usr/bin/python
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# Google's Python Class
# http://code.google.com/edu/languages/google-python-class/
import sys
import re
import os
import shutil
import subprocess
import zipfile
"""
Copy Speci... | 2,710 | 871 |
import torch.nn as nn
from core.fim_model import ModelFIM
import torch
features = [784,1000,500,250,30]
class Autoencoder(ModelFIM):
def __init__(self, args, init_from_rbm=False, hook_enable=True, logger=None):
super(Autoencoder, self).__init__(args)
self.encoder = nn.Sequential(
nn.L... | 2,054 | 735 |
import os
import sys
CURRENT_PATH = os.path.split(os.path.realpath(__file__))[0]
sys.path.append(os.path.join(CURRENT_PATH, '..'))
from py_proj_init.__main__ import main # noqa
main()
| 188 | 75 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Name: TOFILL\n
Description: TOFILL
"""
"""PySimpleFrame
Author: Miguel Silva
License: Check LICENSE file
"""
## System imports ##
## Library imports ##
import termtables
from colorama import Fore, Back, Style
## Application imports ##
from pysimpleframe... | 4,620 | 1,686 |
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
setup(
name="giraffe",
version="0.1",
package_dir={"giraffe" : ""},
packages=["giraffe"],
cmdclass = {'build_ext': build_ext},
ext_modules = [
Exten... | 458 | 143 |
# -*- coding: utf-8 -*-
############################ Copyrights and license ############################
# #
# Copyright 2016 Sam Corbett <sam.corbett@cloudsoftcorp.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> ... | 2,267 | 528 |
import click
from modules.processor import build_report, print_report
@click.group(invoke_without_command=True)
@click.option('--files', '-f', required=True, type=str, prompt="Provide the path to data files")
@click.pass_context
def cli_root(ctx, files):
ctx.meta['files'] = files
@cli_root.command()
@click.argu... | 921 | 312 |
class SearchResult(object):
"""Class representing a return object for a search query.
Attributes:
path: An array representing the path from a start node to the end node, empty if there is no path.
path_len: The length of the path represented by path, 0 if path is empty.
ele_gain: The cu... | 538 | 156 |
# -*- coding: utf-8 -*-
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from .forms import PictureForm
from .models import Picture
# enable nesting of plugins inside the picture plugin
PICTURE_NE... | 2,531 | 674 |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
# Set fontsize larger for latex plots
matplotlib.rcParams.update({'font.size': 20})
# Generate data from file
x, y = np.genfromtxt("bin/python_Aufgabe2.txt", unpack=True)
m, n = x[-1], y[-1]
# Plotting
plt.figure(figsize=(12,7))
plt.grid()
plt.xla... | 622 | 281 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import editregions.utils.regions
class Migration(migrations.Migration):
dependencies = [
('contenttypes', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='... | 1,350 | 370 |
#Saves a historgram of each variable to png files
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
#read data
data = pd.read_csv("irisDataSet.csv")
#names of variables
names = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'species']
# sepe... | 887 | 338 |
from zipfile import ZipFile
import os
from version import VERSION
base_name = "GameCube File Tools"
base_name_with_version = base_name + " " + VERSION
import struct
if (struct.calcsize("P") * 8) == 64:
base_name_with_version += "_64bit"
base_zip_name = base_name_with_version
else:
base_name_with_version += "_... | 712 | 279 |
#!usr/bin/env python
__author__ = "X Zhang"
__email__ = "xzhang@westwoodrobotics.net"
__copyright__ = "Copyright 2020 Westwood Robotics Corp."
__date__ = "Feb 14, 2020"
__version__ = "0.1.0"
__status__ = "Beta"
from Settings.Constants_DAnTE import *
import math
import numpy as np
class FingerDataStructure(object):
... | 2,894 | 960 |
import json
import requests
import requests.utils
# Fixes some issues with TLS
import os
os.environ['REQUESTS_CA_BUNDLE'] = 'ca.pem';
# --- Debug Purposes Only, Server Config Is Hard Coded ---
#
#
# print "Debug ... " + deployed.ResultUri;
# response = requests.get('https://webhook.site/062e2ea7-5a36-4abb-a2c8-862... | 2,012 | 685 |
#!/usr/bin/env python3
# This script assumes that the non-numerical column headers
# in train and predi files are identical.
# Thus the sm header(s) in the train file must be numeric (day/month/year).
import sys
import numpy as np
import pandas as pd
from sklearn.decomposition import PCA #TruncatedSVD as SVD
from skl... | 4,318 | 1,598 |
class Stats:
writes: int
reads: int
accesses: int
def __init__(self) -> None:
self.reset()
def reset(self) -> None:
self.writes = 0
self.reads = 0
self.accesses = 0
def add_reads(self, count: int = 1) -> None:
self.reads += count
self.accesses +... | 439 | 152 |
from .attribute_classifier import BranchedTinyAttr
from .face_parser import FaceParser
from .stylegan2 import Generator
| 120 | 33 |
"""
Tests for functionality in the utils module
"""
import mock
try:
import unittest2 as unittest
except ImportError:
import unittest
from queries import utils
class GetCurrentUserTests(unittest.TestCase):
@mock.patch('pwd.getpwuid')
def test_get_current_user(self, getpwuid):
"""get_current... | 2,787 | 895 |
# Import modules
import os
from xml.dom import minidom
from base64 import b64decode
# Fetch servers from FileZilla
FileZilla = os.getenv('AppData') + '\\FileZilla\\'
def StealFileZilla():
if not os.path.exists(FileZilla):
return []
RecentServersPath = FileZilla + 'recentservers.xml'
SiteManag... | 1,421 | 515 |
from django.conf.urls.defaults import *
urlpatterns = patterns('oldcontrib.tools.gallery.views',
url(r'^add_to_gallery/$', view='add_to_gallery', name='add_to_gallery'),
url(r'^remove_from_gallery/$', view='remove_from_gallery', name='remove_from_gallery'),
url(r'^create_gallery/$', view='create_gallery', ... | 535 | 191 |
# Copyright (C) 2015 Jeffrey Meyers
#
# This program is released under the "MIT License".
# Please see the file COPYING in this distribution for
# license terms.
import datetime
from flask import Blueprint, request, jsonify
from webargs import Arg
from webargs.flaskparser import use_args
import geoalchemy2.functions... | 4,333 | 1,319 |
'''
Created on April 15, 2018
@author: Alejandro Molina
'''
import numpy as np
import warnings
from scipy.stats import gamma, lognorm
from sklearn.linear_model import ElasticNet
from spn.structure.leaves.conditional.Conditional import Conditional_Gaussian, Conditional_Poisson, \
Conditional_Bernoulli
import stats... | 2,896 | 982 |
# Copyright (c) 2019 Science and Technology Facilities Council
# All rights reserved.
# Modifications made as part of the fparser project are distributed
# under the following license:
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following condi... | 5,077 | 1,660 |
"""
This module contains utility functions used in the conversion of the downloaded
data to TFrecords as well as functions used by the model/training script.
Semantic segmenation evaluations methods were taken from
https://github.com/martinkersner/py_img_seg_eval
"""
import os
import fnmatch
import logging
import cv... | 6,486 | 2,116 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import division
from __future__ import print_function
from NumPyNet.activations import Activations
from NumPyNet.utils import _check_activation
from NumPyNet.utils import check_is_fitted
import numpy as np
from NumPyNet.layers.base import BaseLayer
__aut... | 5,685 | 2,201 |
import unittest
from twisted.internet import reactor, task
class ReactorTestCase(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(ReactorTestCase, self).__init__(*args, **kwargs)
self.done = False
def timeOutAfter(self, seconds):
f = reactor.callLater(seconds, self.timedO... | 843 | 255 |
from oled import TrackerOled
from color_tracker import ColorTracker
import cv2
from threading import Thread
tracker_oled = TrackerOled()
color_tracker = ColorTracker()
def write_fps():
tracker_oled.writeTextCenter("FPS: {:.2f}".format(color_tracker.fps.fps()))
tracker_oled.writeTextCenter("READY")
while True:
... | 1,068 | 383 |
#!/usr/bin/env python
# coding=utf-8
# get a easy way to edit config file
"""
>>> from lightconfig import LightConfig
>>> cfg = LightConfig("config.ini")
>>> cfg.section1.option1 = "value1"
>>> print(cfg.section1.option1)
value1
>>> "section1" in cfg
True
>>> "option1" in cfg.section1
True
"""
import os
import codecs
i... | 6,692 | 1,960 |
"""
This script shows the usage of scikit-learns linear regression functionality.
"""
# %% [markdown]
# # Linear Regression using Scikit-Learn #
# %% [markdown]
# ## Ice Cream Dataset ##
# | Temperature C° | Ice Cream Sales |
# |:--------------:|:---------------:|
# | 15 | 34 |
# | 24 ... | 2,414 | 900 |
from datetime import datetime
import numpy as np
import tensorflow as tf
import tensorflow.keras.backend as K
import tensorflow_probability as tfp
from sklearn.metrics import mean_absolute_error
from tensorflow.python.keras.callbacks import EarlyStopping, ReduceLROnPlateau, ModelCheckpoint
from tensorflow.python.keras... | 9,195 | 2,731 |
from locust import HttpLocust, TaskSet, task
class WebsiteTasks(TaskSet):
@task
def bcrypt(self):
headers = { "Content-type": "application/json" }
payload = '{"message":"hello world"}'
self.client.post("/SHOUTCLOUD", payload, headers = headers)
class WebsiteUser(HttpLocust):
... | 380 | 119 |
colors = ['black', 'white']
sizes = ['S', 'M', 'L']
tshirts = [
(color, size)
for color in colors
for size in sizes
]
print(f"Cartesian products from {colors} and {sizes}: {tshirts}")
| 198 | 76 |
# create this file
# rerouting all requests that have ‘api’ in the url to the <code>apps.core.urls
from django.conf.urls import url
from django.urls import path
from rest_framework import routers
from base.src import views
from base.src.views import InitViewSet
#from base.src.views import UploadFileForm
#upload stuf... | 807 | 262 |
#!/usr/local/bin/python
# -*- coding: utf-8 -*-
'''test_Rainbow_pen
'''
import sys, os
import numpy as np
from matplotlib import pyplot as plt
from PIL import Image
FN_OUT = 'rainbow_pen_320x240.png'
def mk_col(w, h, x, y):
a = 255
i = int(7 * y / h)
if i == 0: c, u, v = (192, 0, 0), (32, 0, 0), (0, 32, 0) # R... | 2,456 | 1,377 |
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 16 17:31:42 2015
This is adapted from the kaggle tutorial for the National Data Science Bowl at
https://www.kaggle.com/c/datasciencebowl/details/tutorial
Any code section lifted from the tutorial will start with # In tutorial [n].
My adaption will start with # Adapted
2/2... | 15,780 | 4,790 |
# k3d.py
#
# Copyright 2020 Alvaro Saurin
#
# 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.
#
# This program is distribu... | 14,810 | 4,364 |
# Create a disc with 50 points in the circumferential direction.
#
import pyvista
mesh = pyvista.Disc(c_res=50)
mesh.plot(show_edges=True, line_width=5)
| 153 | 62 |
import os
from utility import write_to_output, print_board, color_is_black, board_to_list, print_results
from board import Board
import time
from algorithm import minimax, minimax_alpha_beta, minimax_alpha_beta_final, minimax_alpha_beta_rand
from math import sqrt, floor
start = time.time()
# parse input file
with ope... | 7,364 | 2,182 |
from django.db.models import Q
import django_filters
from core.models import ApplicationVersionLicense as ImageVersionLicense
from api.v2.serializers.details import ImageVersionLicenseSerializer
from api.v2.views.base import AuthModelViewSet
class VersionFilter(django_filters.FilterSet):
version_id = django_filt... | 1,407 | 393 |
from __future__ import print_function
from os import getenv
from datetime import datetime
def vprint(*a, **k):
if not getenv('VERBOSE'):
return
print(datetime.now(), ' ', end='')
print(*a, **k)
| 216 | 70 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# C++ version Copyright (c) 2006-2011 Erin Catto http://www.box2d.org
# Python port by Ken Lauer / http://pybox2d.googlecode.com
#
# This software is provided 'as-is', without any express or implied
# warranty. In no event will the authors be held liable for any ... | 1,964 | 677 |
import subprocess
import os
import argparse
import tempfile
def get_parser():
# argument parser
parser = argparse.ArgumentParser(description='Input')
parser.add_argument('--pchk-file', '-p',
action='store',
dest='pchk_file',
type=str,... | 3,939 | 1,063 |
import numpy as np
def R(angle):
rad_angle = (angle)*np.pi/180
return np.array([[np.cos(rad_angle), -np.sin(rad_angle)],
[np.sin(rad_angle), np.cos(rad_angle)]])
if __name__ == "__main__":
a = np.array([0, 1])
print(np.dot(R(180), a))
| 274 | 117 |
from app.factory import create_app
| 35 | 10 |
from darmtbl2 import Bitsize, Rn, Rm, Rt, Rt2
from darmtbl2 import i, imm3, imm4, imm6, imm8, imm4H, imm4L
from darmtbl2 import P, W, D, N, M, cond
Vd = Bitsize('Vd', 4, 'Vector Destination Register')
Vn = Bitsize('Vn', 4, 'Vector Source Register')
Vm = Bitsize('Vm', 4, 'Second Vector Source Register')... | 39,949 | 30,287 |
from talon import Context, Module
ctx = Context()
mod = Module()
mod.tag("code_data_null", desc="Tag for enabling commands relating to null")
@mod.action_class
class Actions:
def code_insert_null():
"""Inserts null"""
def code_insert_is_null():
"""Inserts check for null"""
def code_ins... | 380 | 126 |
from numpy import array as np_array, zeros as np_zeros, sum as np_sum, empty as np_empty, \
amax as np_amax, interp as np_interp, ones as np_ones, tile as np_tile, isnan as np_isnan
import yaml
from seir_model import SEIR_matrix
from common import Window, get_datetime, timesteps_between_dates, get_datetime_arra... | 17,810 | 6,101 |
from body.tests.login_test_case import LoginTestCase
from body.tests.model_helpers import create_ledger_entry, create_medicine
from freezegun import freeze_time
from django.utils.timezone import make_aware, datetime
@freeze_time(make_aware(datetime(2022, 3, 1)))
class MedicineTests(LoginTestCase):
def test_ledger... | 695 | 220 |
from .user_change import UserChangeForm
from .user_creation import UserCreationForm
| 84 | 23 |
"""This module contains functions to generate strategies from annotations."""
from __future__ import annotations
import collections
import inspect
import sys
from itertools import chain
from itertools import combinations
from typing import Any
from typing import Callable
from typing import Iterable
from typing import ... | 20,818 | 6,284 |
# Copyright 2019-2021 Swiss National Supercomputing Centre (CSCS/ETH Zurich)
# HPCTools Project Developers. See the top-level LICENSE file for details.
#
# SPDX-License-Identifier: BSD-3-Clause
import os
import sys
import reframe as rfm
import reframe.utility.sanity as sn
sys.path.append(os.path.abspath(os.path.join(o... | 3,600 | 1,351 |
import torch
from torch.nn import Module, Parameter
from torch.autograd import Function
class Forward_Warp_Python:
@staticmethod
def forward(im0, flow, interpolation_mode):
im1 = torch.zeros_like(im0)
B = im0.shape[0]
H = im0.shape[2]
W = im0.shape[3]
if interpolation_m... | 4,743 | 1,690 |
import itertools
import Partitioning
class Algorithm( object ):
def __init__( self, linv, variant, init, repart, contwith, before, after, updates ):
self.linv = linv
self.variant = variant
if init:
#assert( len(init) == 1 )
self.init = init[0]
else:
... | 10,890 | 3,560 |
import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
import matplotlib.gridspec as gs
import sys
data = np.loadtxt('NbSe2.freq.gp')
symmetryfile = 'plotband.out'
lbd = np.loadtxt("lambda.dat")
lbd_val = np.where(lbd<1 , lbd, 1)
def Symmetries(fstring):
f = open(fstring, 'r')
x = np.... | 939 | 432 |
print(("Multiples of {}: {}\n"*6).format("3",[n for n in range(1,31)if not n%3],"3 squared",[n**2for n in range(1,31)if not n%3],"4 doubled",[n*2for n in range(1,31)if not n%4],"3 or 4",[n for n in range(1,31)if not(n%4and n%3)],"3 and 4",[n for n in range(1,31)if not(n%4or n%3)],"3 replaced",[n%3and n or'X'for n in ra... | 341 | 176 |
"""Python library to connect deCONZ and Home Assistant to work together."""
import logging
from .light import DeconzLightBase
_LOGGER = logging.getLogger(__name__)
class DeconzGroup(DeconzLightBase):
"""deCONZ light group representation.
Dresden Elektroniks documentation of light groups in deCONZ
http... | 5,594 | 1,679 |
# Import the encoding
import nocolon
# Now you can import files with the nocolon encoding:
from nocolon_test import nocolon_function
nocolon_function(4)
| 155 | 53 |
"""
Regression tests for the REINFORCE agent on OpenAI gym environments
"""
import pytest
import numpy as np
import shutil
from yarlp.utils.env_utils import NormalizedGymEnv
from yarlp.agent.ddqn_agent import DDQNAgent
env = NormalizedGymEnv(
'PongNoFrameskip-v4',
is_atari=True
)
def test_ddqn():
a... | 1,033 | 409 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('arbeitsplan', '0008_auto_20141208_1906'),
]
operations = [
migrations.AddField(
model_name='mitglied',
... | 555 | 185 |
''' bring activitypub functions into the namespace '''
from .actor import get_actor
from .book import get_book, get_author, get_shelf
from .create import get_create, get_update
from .follow import get_following, get_followers
from .follow import get_follow_request, get_unfollow, get_accept, get_reject
from .outbox impo... | 789 | 235 |
class Eventseverity(basestring):
"""
EMERGENCY|ALERT|CRITICAL|ERROR|WARNING|NOTICE|INFORMATIONAL|DEBUG
Possible values:
<ul>
<li> "emergency" - System is unusable,
<li> "alert" - Action must be taken immediately,
<li> "critical" - Critical condition,
<li> "error" ... | 645 | 206 |
#!/usr/bin/env python3
import asyncio
import logging
import signal
from pathlib import Path
import psutil
from i3pyblocks import Runner, types, utils
from i3pyblocks.blocks import ( # shell,
datetime,
dbus,
http,
i3ipc,
inotify,
ps,
pulse,
x11,
)
# Configure logging, so we can have ... | 8,110 | 2,555 |
import collections
import logging
import json
import os
import luigi
import gokart
import tqdm
import torch
import sentencepiece as spm
import sacrebleu
import MeCab
from fairseq.models.transformer import TransformerModel
from fairseq.data import LanguagePairDataset
from context_nmt.pipelines.conversation_dataset_mer... | 9,131 | 2,430 |
import logging
from celery._state import get_current_task
class TaskIDFilter(logging.Filter):
"""
Adds celery contextual information to a log record, if appropriate.
https://docs.python.org/2/howto/logging-cookbook.html
#using-filters-to-impart-contextual-information
"""
def filter(self, rec... | 855 | 237 |
#coding=utf-8
import os
from django.db import models
from django.contrib.auth.models import User
from django.conf import settings
from apps.core.models import Customer
CHECK_RESULT = (
('', '--'),
('high_risk', u'高危邮件'),
('sender_blacklist', u'发件黑'),
('keyword_blacklist', u'内容黑'),
('subject_blackl... | 2,295 | 972 |
# SPDX-License-Identifier: BSD-3-Clause
from typing import ClassVar, Mapping, cast
from softfab.ControlPage import ControlPage
from softfab.Page import InvalidRequest, PageProcessor
from softfab.pageargs import DictArg, EnumArg, StrArg
from softfab.pagelinks import TaskIdArgs
from softfab.request import Request
from ... | 2,691 | 716 |
import cv2
class DenseOpticalFlowEstimator(object):
def __init__(self):
self.previous_frame = None
def estimate(self, frame):
if first_frame is None:
return None
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
flow = cv2.calcOpticalFlowFarneback(self.previous_frame,... | 414 | 150 |
import os
from copy import deepcopy
with open(os.path.join(os.path.dirname(__file__), "input.txt"), "r") as file:
lines = [l.strip() for l in file.readlines()]
p1 = list(reversed([int(i) for i in lines[1:26]]))
p2 = list(reversed([int(i) for i in lines[28:]]))
def part1(player1, player2):
while playe... | 2,071 | 742 |
'''
@Date: 2019-11-02 09:19:19
@Author: ywyz
@LastModifiedBy: ywyz
@Github: https://github.com/ywyz
@LastEditors: ywyz
@LastEditTime: 2019-11-02 10:13:44
'''
year = eval(input("Enter the year: "))
day = eval(input("Enter the day of the week: "))
for months in range(1, 13):
if months == 1:
month = "January"... | 2,075 | 805 |
import shutil
from contextlib import contextmanager
from tempfile import NamedTemporaryFile
from s3fs import S3FileSystem
class S3Downloader:
def __init__(self, tmp_dir=None, chunk_size=16 * 1024, **kwargs):
self.tmp_dir = tmp_dir
self.chunk_size = chunk_size
self.fs = S3FileSystem(**kwa... | 587 | 193 |
MAX_SENTENCE = 30
MAX_ALL = 50
MAX_SENT_LENGTH=MAX_SENTENCE
MAX_SENTS=MAX_ALL
max_entity_num = 10
num = 100
num1 = 200
num2 = 100
npratio=4
| 142 | 85 |
import os, json
from PIL import Image
import numpy as np
from skimage import io
basePath = './log/log_joku/'
json_files = [pos_json for pos_json in os.listdir(basePath) if pos_json.endswith('.json')]
for file in json_files:
if file != 'meta.json':
#print(file)
with open(basePath + file) as f:
... | 1,022 | 334 |
__all__ = ["orders"]
| 21 | 9 |
from gym_holdem.holdem.bet_round import BetRound
from gym_holdem.holdem.poker_rule_violation_exception import PokerRuleViolationException
from pokereval_cactus import Card
class Player:
def __init__(self, stakes, table=None, name=None):
self.table = table
self.name = name
self.bet = 0
... | 5,474 | 1,688 |
from flask import Flask, request, send_from_directory, redirect, send_file, render_template
import os,cv2
import neuralStyleProcess
app = Flask(__name__)
APP_ROOT = os.path.dirname(os.path.abspath(__file__))
@app.route("/")
def index():
return render_template("upload.html")
@app.route("/upload", methods=['POST'])
d... | 1,441 | 476 |
# Copyright (c) 2021, MITRE Engenuity. Approved for public release.
# See LICENSE for complete terms.
import argparse
import json
import pathlib
import numpy
import requests
from src.create_mappings import get_sheets, get_sheet_by_name
def get_argparse():
desc = "ATT&CK to VERIS Mappings Validator"
argpars... | 9,678 | 2,839 |
# "constant" paths and values for TNO, regular lat/lon
# for MeteoTest Swiss inventory, use calculated regular domain in the code
import os
import time
from emiproc.grids import COSMOGrid, TNOGrid
# inventory
inventory = 'TNO'
# model either "cosmo-art" or "cosmo-ghg" (affects the output units)
model = 'cosmo-art'
... | 2,015 | 801 |
# This file contains the list of API's for operations on ZTP
# @author : Chaitanya Vella (chaitanya-vella.kumar@broadcom.com)
from spytest import st
import apis.system.basic as basic_obj
import utilities.utils as utils_obj
import apis.system.switch_configuration as switch_conf_obj
import apis.system.interface as intf_o... | 45,876 | 14,828 |
"""Handle for X.509 AlgorithmIdentifier objects
This module understands a minimal number of OIDS, just enough X.509
stuff needed for PKCS 1 & 7.
"""
import types
from pisces import asn1
oid_dsa = asn1.OID((1, 2, 840, 10040, 4, 1))
oid_dsa_sha1 = asn1.OID((1, 2, 840, 10040, 4, 3))
oid_rsa = asn1.OID((1, 2, 840, 1135... | 2,881 | 1,128 |
#Faça um programa que calcule e escreva o valor de S
# S=1/1+3/2+5/3+7/4...99/50
u=1
valores=[]
for c in range(1,100):
if(c%2==1):
valores.append(round(c/u,2))
u+=1
print(valores)
print(f"S = {sum(valores)}")
| 230 | 115 |
from kivy.app import runTouchApp
from kivy.properties import StringProperty
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.gridlayout import GridLayout
from kivy.lang import Builder
from kivyx.uix.drawer import KXDrawer
class Numpad(GridLayout):
def on_kv_post(self, *ar... | 3,138 | 1,006 |