content stringlengths 5 1.05M |
|---|
import yaml
try:
from yaml import CLoader as Loader
except ImportError:
from yaml import Loader
with open('LINKS.md', 'r') as file_:
config = yaml.load(file_, Loader=Loader)
for link in config['links']:
print("* [{}]({}) - {}".format(link.get('title', 'LINK'), link.get('url', ''), link.get('descript... |
"""
This batch script executes an experiment according to a config file.
"""
if __name__ == "__main__":
pass
|
# sometimes the standard random is overwritten by numpy.random
# so random is renamed as std_random here
import numpy as np
from warp import *
import random as std_random
from scipy.constants import k, m_e
class ParticleReflector:
"""Class that handles particle reflection.
To use:
To define a particle... |
#
# Copyright (c) 2017 Stefan Seefeld
# All rights reserved.
#
# This file is part of Faber. It is made available under the
# Boost Software License, Version 1.0.
# (Consult LICENSE or http://www.boost.org/LICENSE_1_0.txt)
from ..artefact import source
import yaml
class node(object):
"""Convert a (nested) dictio... |
from main import *
from transaction import *
from bci import *
from deterministic import *
# Takes privkey, address, value (satoshis), fee (satoshis)
def send(frm, to, value, fee=1000):
u = unspent(privtoaddr(frm))
u2 = select(u, value+fee)
argz = u2 + [to+':'+str(value), privtoaddr(to), fee]
tx = mks... |
import paho.mqtt.client as mqtt
import cv2
import logging
from von.singleton import Singleton
from von.terminal_font import TerminalFont
class MQTT_ConnectionConfig:
broker = 'voicevon.vicp.io'
port = 1883
uid = ''
password = ''
client_id = ''
class MqttConfigableItem():
topic = ''
type ... |
#!/usr/bin/env python
"""
Example usage of 'print_container', a tool to print
any layout in a non-interactive way.
"""
from prompt_toolkit.shortcuts import print_container
from prompt_toolkit.widgets import Frame, TextArea
print_container(
Frame(
TextArea(text="Hello world!\n"),
title="Stage: parse... |
from abc import ABC
from httpx import Response
from starlette.status import HTTP_200_OK
from app.db.repositories import RefreshSessionsRepository
from app.schemas.authentication import AuthenticationResult
from app.services.authentication.cookie import REFRESH_TOKEN_COOKIE_KEY
from ...base import BaseTestRoute
__al... |
from typing import Union
def get_first_line(o, default_val: str) -> Union[str, None]:
"""
Get first line for a pydoc string
:param o: object which is documented (class or function)
:param default_val: value to return if there is no documentation
:return: the first line which is not whitespace
... |
# --------------------------------------------------------------------------
# This extension generates a customizable string of page navigation links
# for index pages.
#
# The links can be accessed in templates as:
#
# {{ paging }}
#
# Default settings can be overridden by including a 'paging' dictionary in
# the... |
from client import exceptions as ex
from client.sources.common import core
from client.sources.common import interpreter
from client.sources.common import pyconsole
from client.sources.ok_test import models
from client.utils import format
import logging
log = logging.getLogger(__name__)
class DoctestSuite(models.Suit... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Project : MeUtils.
# @File : hydra_demo
# @Time : 2021/1/26 1:28 下午
# @Author : yuanjie
# @Email : [email protected]
# @Software : PyCharm
# @Description : https://github.com/facebookresearch/hydra/tree/1.0_branch/examples/tutorial... |
#!/usr/bin/env python3
import argparse
# command line arguments parser
from db import Database, DatabaseError
from dbhelper import DatabaseHelper
parser = argparse.ArgumentParser(description="Database helper for FSG exam bank.")
parser.add_argument(
"--db", action="store", type=str, dest="db_path", default=".",
... |
#!/usr/bin/env python
import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
x = [21,22,23,4,5,6,77,8,9,10,31,32,33,34,35,36,37,18,49,50,100]
num_bins = 5
n, bins, patches = plt.hist(x, num_bins, facecolor='blue', alpha=0.5)
plt.show()
|
ANYBLOCK_MINUTE_AGG_DATA = {
'minute_bucket': {'buckets': [
{'key_as_string': '2021-10-22 08:21', 'key': 1634890860000, 'doc_count': 129,
'avgGasMin': {'value': 68135881075.89922}},
{'key_as_string': '2021-10-22 08:22', 'key': 1634890920000, 'doc_count': 1431,
'avgGasMin': {'value'... |
# -*- coding: utf-8 -*-
import logging
import os
from astropy.io import fits
from astropy.io.registry import IORegistryError
from astropy.table import Column, Table
from .database import get_filters
logging.basicConfig(level=logging.getLevelName(
os.getenv('LOG_LEVEL', 'WARNING')))
LOGGER = logging.getLogger(__... |
from spikeforest import SFMdaRecordingExtractor, SFMdaSortingExtractor, mdaio
from spikeforest_analysis import bandpass_filter
import mlprocessors as mlpr
from mountaintools import client as mt
import numpy as np
import json
class FilterTimeseries(mlpr.Processor):
NAME = 'FilterTimeseries'
VERSION = '0.1.0'
... |
import scrapy
from baidutie.items import BaidutieItem
class DutieSpider(scrapy.Spider):
name = 'dutie'
# 2、检查修改允许的域
allowed_domains = ['baidu.com']
# 1、修改起始url
start_urls = ['https://tieba.baidu.com/f?kw=%E6%96%B9%E8%88%9F%E7%94%9F%E5%AD%98%E8%BF%9B%E5%8C%96']
def parse(self, response):
... |
import asyncio
import datetime as dt
import random
import typing as t
from enum import Enum
from twitchio.ext import commands
from carberretta import Config
HACK_COST = 100
class GameState(Enum):
__slots__ = ("STOPPED", "WAITING", "RUNNING")
STOPPED = 0
WAITING = 1
RUNNING = 2
class HackGame:
... |
num = [[], []]
for c in range(0, 7):
valor = int(input(f'Digite o {c+1}º valor: '))
if valor % 2 == 0:
num[0].append(valor)
if valor % 2 != 0:
num[1].append(valor)
num[0].sort(), num[1].sort()
print(f'Os números PARES foram: {num[0]}')
print(f'Os números IMPARES foram: {num[1]}')
|
#!/usr/bin/env python
# coding: utf-8
# file="text_euc2.txt"
# dat = open(file, "rb").read()
import sys
#
filename=sys.argv[1]
dat = open(filename).read().encode('euc-jp')
dat=bytes(dat)
l=len(dat)
i=0
put_index=0
imgs=[]
print("const int TEXT_LENGTH = %d;" % (int(l/2)+1))
print("byte[] text_data = {")
while(True)... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'D:\Masterprojekt\03_Production\Maya\scripts\assetIO\assetIOWidget.ui'
#
# Created: Wed May 30 10:05:54 2018
# by: pyside2-uic running on PySide2 2.0.0~alpha0
#
# WARNING! All changes made in this file will be lost!
from PySide2 import... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2021 Idiap Research Institute, http://www.idiap.ch/
# Written by Bastian Schnell <[email protected]>
#
import torch.nn as nn
class Pooling(nn.Module):
def __init__(self, batch_first):
super().__init__()
self.batch_first = batc... |
from discord.ext import commands
import discord
import json
from discord.utils import get
from discord import Embed
import os.path
from os import path
##
# This is a helper function to playlist.py to manage the JSON file I/O
##
def logUpdate(ctx, songName): #automatically logs all songs played by a user in a textfile ... |
"""
GRIB - Contouring with Gradient Shading
"""
# (C) Copyright 2017- ECMWF.
#
# This software is licensed under the terms of the Apache Licence Version 2.0
# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
#
# In applying this licence, ECMWF does not waive the privileges and immunities
# granted ... |
import sys
from faster_solution import run_faster_version
def run():
args = sys.argv
run_faster_version(args)
if __name__ == '__main__':
run()
|
#! /usr/bin/env python
# A tiny framework that makes it easy to write Test Data Builders in Python
# Port of Java make-it-easy by Nat Pryce
# Copyright (C) 2013 Dori Reuveni
# E-mail: dorireuv AT gmail DOT com
from setuptools import setup
import os
import re
__version__ = __author__ = __license__ = ''
fh = open(os... |
''' We parse each document of each file from our data set '''
''' This results in text files with ID name and text content '''
from nltk.corpus import stopwords
from nltk.stem import PorterStemmer
import nltk
import re
from numpy import zeros
import numpy as np
import math
import sys
import os
# Turns xml parsed file... |
# Generated by Django 2.2.5 on 2020-07-11 13:19
import django.contrib.postgres.fields.jsonb
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('authentication', '0003_auto_20200711_1617'),
]
operations = [
migrations.AlterField(
model_n... |
import logging
import ibmsecurity.utilities.tools
logger = logging.getLogger(__name__)
def get(isamAppliance, directory_name, check_mode=False, force=False):
"""
Retrieving the list of suffixes for a particular federated directory
"""
return isamAppliance.invoke_get("Retrieving the list of suffixes f... |
from django import template
from ...product.templatetags.product_prices import BasePriceNode, parse_price_tag
register = template.Library()
class CartItemPriceNode(BasePriceNode):
def get_currency_for_item(self, item):
return item.cart.currency
def get_price(self, cartitem, currency, **kwargs):
... |
import numpy as np
import numba as nb
import warnings
from numba.core.errors import NumbaDeprecationWarning, NumbaPerformanceWarning, NumbaWarning
warnings.simplefilter('ignore', category=NumbaDeprecationWarning)
warnings.simplefilter('ignore', category=NumbaPerformanceWarning)
warnings.simplefilter('ignore', category... |
from time import time
class PID:
def __init__(self, Kp, Ki, Kd, max_integral, min_interval = 0.001, set_point = 0.0, last_time = None):
self._Kp = Kp
self._Ki = Ki
self._Kd = Kd
self._min_interval = min_interval
self._max_integral = max_integral
... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from... |
import logging
from util import unique
class LineupMapList(list):
def __init__(self, *args, **kwargs):
super(LineupMapList, self).__init__(*args, **kwargs)
def unique_channels(self, channel_filter=None):
return unique((channel
for lineup_map in self
... |
# Generated by Django 3.1.5 on 2021-05-01 13:46
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0006_auto_20210501_1930'),
]
operations = [
migrations.RemoveField(
model_name='blog',
name='catagories',
... |
"""
Composition-based decision tree for anomaly detection
-------------------------------
CDT detector.
:authors: Ines Ben Kraiem & Geoffrey Roman-Jimenez
:copyright:
Copyright 2020 SIG Research Group, IRIT, Toulouse-France.
"""
import numpy as np
import uuid
import itertools
import copy
from helper imp... |
from gennav.planners.base import Planner # noqa: F401
from gennav.planners.potential_field import PotentialField # noqa: F401
from gennav.planners.prm import PRM, PRMStar # noqa: F401
from gennav.planners.rrt import RRG, RRT, InformedRRTstar, RRTConnect # noqa: F401
|
from django.urls import path
from . import admin
urlpatterns = [
path("generic_inline_admin/admin/", admin.site.urls),
]
|
#!/usr/local/bin/python3
import sys
import sqlite3
import configparser
# read dbpath from config file
config = configparser.ConfigParser()
config.read('sstt.config')
dbpath = config.get('database','dbpath',fallback='sstt.db')
conn = sqlite3.connect(dbpath)
conn.row_factory = sqlite3.Row
conn.execute("""
create tabl... |
src = Split('''
yts_main.c
''')
component = aos_component('testcase', src)
component.add_global_includes('include')
component.add_comp_deps('test/yunit')
if aos_global_config.compiler == 'gcc':
component.add_cflags( "-Wall" )
component.add_cflags( "-Werror")
|
import struct
import textwrap
import secrets
import logging
from shellerate import encoder;
from binascii import unhexlify, hexlify;
from shellerate import strings;
# First version with clear text decoder stub: https://www.virustotal.com/#/file/7b25b33a1527d2285ebdefd327bc72b6d932c140489e8bfb7424bef115aa2ecd/detectio... |
import caffe
import matplotlib.pyplot as plt
import numpy as np
from collections import defaultdict
plt.rcParams['font.size'] = 20
# plt.rcParams['xtick.labelzie'] = 18
def make_2d(data):
return np.reshape(data, (data.shape[0], -1))
caffe.set_mode_gpu()
caffe.set_device(0)
caffe_root = '/home/moritz/Repositori... |
# -*- coding: utf-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "Lic... |
from django import forms
from django.contrib.auth.forms import AuthenticationForm, ReadOnlyPasswordHashField, UserChangeForm, UserCreationForm
from django.core.exceptions import ValidationError, ObjectDoesNotExist
from django.utils.translation import ugettext, ugettext_lazy as _
from .models import User
class UserLog... |
import sys, os, inspect
from JumpScale import j
home = os.curdir # Default
if 'JSBASE' in os.environ:
home = os.environ['JSBASE']
elif 'JSJAIL' in os.environ:
home = os.environ['JSJAIL']
elif os.name == 'posix':
# home = os.path.expanduser("~/")
home="/opt/jumpscale"
elif os.na... |
from ....Classes.Arc1 import Arc1
from ....Classes.SurfLine import SurfLine
def get_surface_active(self, alpha=0, delta=0):
"""Return the full winding surface
Parameters
----------
self : SlotW22
A SlotW22 object
alpha : float
float number for rotation (Default value = 0) [rad]
... |
def cadena():
while True:
try:
text= input("Ingrese las notas separadas por coma: ")
text = text.split(sep=",")
for i,a in enumerate(text):
text[i]=int(text[i].strip())
break
except:
print("Ingrese solo número... |
import numpy as np
import pandas as pd
import copy
import os
import sklearn
# from scipy.stats import pearsonr
# from sklearn.ensemble import RandomForestClassifier
from sklearn.preprocessing import RobustScaler
from sklearn.impute import SimpleImputer
from sklearn.pipeline import Pipeline
# from sklearn.metrics import... |
#! /usr/bin/env python
# by caozj
# Jun 5, 2019
# 3:42:21 PM
import os
import time
import random
import argparse
import numpy as np
import tensorflow as tf
import Cell_BLAST as cb
import scscope as DeepImpute
import utils
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("-i", "--inpu... |
# Use this command if numpy import fails: sudo apt-get install python-dev libatlas-base-dev
# If this doesn't work, uninstall both numpy and scipy. Thonny will keep an older default version of numpy.
# Install an older version of scipy that corresponds to the correct version of numpy.
from guizero import App, PushButt... |
import roslib; roslib.load_manifest('hrl_fabric_based_tactile_sensor')
import rospy
from hrl_msgs.msg import FloatArray
import hrl_lib.util as ut
import hrl_fabric_based_tactile_sensor.adc_publisher_node as apn
from m3skin_ros.msg import RawTaxelArray
from geometry_msgs.msg import Transform
from m3skin_ros.srv imp... |
import ply.lex as lex
tokens = (
'ID',
'NUM',
'HEXNUM',
'JNS',
'LOAD',
'STORE',
'ADD',
'SUBT',
'SUBTI',
'INPUT',
'OUTPUT',
'HALT',
'SKIPCOND',
'JUMP',
'CLEAR',
'ADDI',
'JUMPI',
'LOADI',
'STOREI',
'PUSH',
'POP',
'INCR',
'DECR',
... |
/anaconda3/lib/python3.7/abc.py |
def shape(A):
num_rows = len(A)
num_cols=len(A[0]) if A else 0
return num_rows, num_cols
A=[
[1,2,3],
[3,4,5],
[4,5,6],
[6,7,8]
]
print(shape(A))
|
class AnsibleHostModel:
def __init__(self, name: str, ip: str):
self.name: str = name
self.ip: str = ip
def __eq__(self, other) -> bool:
return (self.name == other.name and
self.ip == other.ip)
def __lt__(self, other) -> bool:
pass
class AnsibleOrderedHost... |
import os
import unittest
import http.client
import warnings
from google.cloud import firestore
from retirable_resources import RetirableResourceManager
firestore_project = "foo"
firestore_host = "localhost"
firestore_port = 8080
class FirestoreEmulatorTest:
def setUp(self):
self.__set_environ()
... |
from catsleep.cat import config as cfg
if __name__ == '__main__':
conf = cfg.Config()
try:
print('user configurations:')
print(conf.get_user_config())
except Exception as e:
print('default configurations:')
print(conf.get_default_config()) |
'''
Given a string S, you are allowed to convert it to a palindrome by adding characters in front of it. Find and return the shortest palindrome you can find by performing this transformation.
For example:
Given "aacecaaa", return "aaacecaaa".
Given "abcd", return "dcbabcd".
Credits:
Special thanks to @ifanchu for ... |
from django.core.urlresolvers import reverse
from rest_framework import serializers
from django_gravatar.templatetags import gravatar
from profiles.models import Profile
class UserProfileSerializer(serializers.ModelSerializer):
absolute_url = serializers.SerializerMethodField()
avatar = serializers.Serializ... |
# log.py
#
#
""" log module to set standard format of logging. """
from meds.utils.file import cdir
from meds.utils.join import j
import logging.handlers
import logging
import os
LEVELS = {
'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'warn': logg... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import yaml
from ansible.plugins.action import ActionBase
from ansible.errors import AnsibleActionFail
from ansible.utils.vars import isidentifier
from ansible.plugins.filter.core import combine
from ansible.plugins.loader import l... |
"""
One Away
There are three types of edits that can be performed on strings: insert a character, remove a character, or replace a character.
Given two strings, write a function to check if they are one edit (or zero edits) away.
Example:
pale, ple -> true
pales, pale -> true
pale, bale -> true
pale, bake -> fals... |
from unittest import mock
from ... import *
from .common import known_langs, mock_which
from bfg9000 import options as opts
from bfg9000.file_types import (HeaderDirectory, HeaderFile,
MsvcPrecompiledHeader, ObjectFile, SourceFile)
from bfg9000.iterutils import merge_dicts
from bfg9000... |
#!/usr/bin/python
"""
__version__ = "$Revision: 1.27 $"
__date__ = "$Date: 2004/10/03 18:16:55 $"
"""
from PythonCard import dialog, model
import os, sys
import wx
import minimalDialog
class Dialogs(model.Background):
def on_initialize(self, event):
self.fitToComponents(None, 5)
def on_listDialogs_s... |
__author__ = 'demi'
# Question 9: Deep Reverse
# Define a procedure, deep_reverse, that takes as input a list,
# and returns a new list that is the deep reverse of the input list.
# This means it reverses all the elements in the list, and if any
# of those elements are lists themselves, reverses all the elements
# in... |
test_data = [3,4,3,1,2]
data = [3,4,1,2,1,2,5,1,2,1,5,4,3,2,5,1,5,1,2,2,2,3,4,5,2,5,1,3,3,1,3,4,1,5,3,2,2,1,3,2,5,1,1,4,1,4,5,1,3,1,1,5,3,1,1,4,2,2,5,1,5,5,1,5,4,1,5,3,5,1,1,4,1,2,2,1,1,1,4,2,1,3,1,1,4,5,1,1,1,1,1,5,1,1,4,1,1,1,1,2,1,4,2,1,2,4,1,3,1,2,3,2,4,1,1,5,1,1,1,2,5,5,1,1,4,1,2,2,3,5,1,4,5,4,1,3,1,4,1,4,3,2,4,3,... |
import asyncio
from typing import Union, List
from abc import ABCMeta, abstractmethod
__all__ = ["AbstractApp"]
class AbstractApp(metaclass=ABCMeta):
def __init__(
self,
host: Union[str, None] = None,
port: Union[str, int, None] = None,
loop: "asyncio.AbstractEvent... |
#!/usr/bin/python
def rest_server(dummy,state):
from bottle import route, run, get, post, request, static_file, abort
from subprocess import call
from datetime import datetime
import set_time
import config as conf
import os
basedir = os.path.dirname(__file__)
wwwdir = basedir+'/www/'
@route('/')
... |
# Copyright 2018-2021 Jakub Kuczys (https://github.com/jack1142)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... |
import hashlib
from Crypto.Hash import MD2, MD4
from hashlib import md5
class CryptographerMD2:
def __init__(self):
pass
def encrypt(self, plain_text):
if type(plain_text) == str:
plain_text = plain_text.encode('utf-8')
cipher = MD2.new(plain_text)
cipher_text = c... |
import torch
import data as Data
import model as Model
import argparse
import logging
import core.logger as Logger
import core.metrics as Metrics
from tensorboardX import SummaryWriter
import os
import numpy as np
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('-c', '--config... |
__author__ = "Lukas McClelland <[email protected]>"
from unicon.plugins.iosxe.statemachine import IosXESingleRpStateMachine
class IosXECat8kSingleRpStateMachine(IosXESingleRpStateMachine):
def create(self):
super().create()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 3rd party imports
import numpy as np
# Local imports
from .c_4_grad import c_4_grad
from .gradient import gradient
from .avg_4sc import avg_4sc
from .ts_vec_xyz import ts_vec_xyz
__author__ = "Louis Richard"
__email__ = "[email protected]"
__copyright__ = "Copyright 2020-... |
import tensorflow as tf
from tensorflow import keras
from modeling import building_model
def training(model, train_data, train_labels, epochs, early_stop=False, patience=10):
if early_stop:
early_stop = keras.callbacks.EarlyStopping(monitor='val_loss', patience=patience)
history = model.fit(
... |
from pytensor.ops.array_ops import *
from pytensor.ops.embedding_ops import *
from pytensor.ops.loss_ops import *
from pytensor.ops.lstm_ops import *
from pytensor.ops.math_ops import *
from pytensor.ops.rnn_ops import *
from pytensor.ops.rnn_util_ops import * |
class EPL_Team:
def __init__(self,name,slogan="No Slogan",title=0):
self.name = name
self.slogan = slogan
self.title = title
def increaseTitle(self):
self.title += 1
def changeSong(self,song):
self.slogan = song
def showClubInfo(self):
final = ""
f... |
# coding: utf-8
import datetime
import numpy as np
import pytest
from ..tests import test_platform_base
from ...types.state import State
from ...platform import MovingPlatform, FixedPlatform
from ...models.transition.linear import ConstantVelocity, CombinedLinearGaussianTransitionModel
from ...sensor.radar.radar impo... |
#!/usr/bin/env python3
from __future__ import print_function
import argparse
import io
import os
import subprocess
import sys
import tempfile
import time
from contextlib import ExitStack
from functools import partial
from threading import Thread
import pysam
class VariantCallingError (RuntimeError):
"""Exceptio... |
'''
Created on 2021-04-21
see https://stackoverflow.com/a/66110795/1497139
'''
import time
from watchdog.observers import Observer
from watchdog.events import PatternMatchingEventHandler
import sys
class Watcher:
'''
watch the given path with the given callback
'''
def __init__(self, path,patterns=... |
import matplotlib.pyplot as plt
import numpy as np
from bandit import Bandit
if __name__ == '__main__':
k = 5
avg_reward1 = []
estimated_q = []
actual_q = []
action_values = np.random.uniform(low=-10, high=0, size=(k,))
for epsilon in ([0.01, .1, 1, 10]):
bdt = Bandit(k, epsilon, actio... |
import click
from ocrd.cli.ocrd_tool import ocrd_tool_cli
from ocrd.cli.workspace import workspace_cli
from ocrd.cli.generate_swagger import generate_swagger_cli
from ocrd.cli.process import process_cli
# TODO server CLI disabled
# from ocrd.cli.server import server_cli
from ocrd.cli.bashlib import bashlib_cli
@clic... |
# Copyright 2018 Comcast Cable Communications Management, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
"""
Authors: Pratik Bhatu.
Copyright:
Copyright (c) 2021 Microsoft Research
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, co... |
import json
from http import HTTPStatus
from json.decoder import JSONDecodeError
import jwt
import requests
from flask import request, current_app, jsonify, g
from jwt import InvalidSignatureError, DecodeError, InvalidAudienceError
from requests.exceptions import (
SSLError,
ConnectionError,
InvalidURL,
... |
class PPU:
pass
|
# import cv2
import deepul.pytorch_util as ptu
import numpy as np
import scipy.ndimage
import torch.nn as nn
import torch.utils.data
import torchvision
from PIL import Image as PILImage
from torchvision import transforms as transforms
from .hw4_utils.hw4_models import GoogLeNet
from .utils import *
CLASSES = ("plane... |
"""
Copyright (c) 2021, FireEye, Inc.
Copyright (c) 2021 Giorgio Severi
"""
import os
import shap
import joblib
import tensorflow as tf
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from tensorflow.keras.models import Model
from tensorflow.keras.optimizers import SGD
from tensorflow.keras.... |
import os
import unittest
import shutil
from jtalks.Tomcat import Tomcat, TomcatNotFoundException
class TomcatTest(unittest.TestCase):
def setUp(self):
os.mkdir('test_tomcat')
def tearDown(self):
shutil.rmtree('test_tomcat')
def test_move_war_to_webapps_should_actually_moves_it(self):
... |
import time
import json
import asyncio
import websockets
from config import host, port
from config import nginx_log_file_path
from tail_f import tail_f
from handle import handle
# async def handle_server(websocket, path):
@asyncio.coroutine
def handle_server(websocket, path):
request_count = 0
logfile = open(... |
from django.contrib import admin
from .models import Spectacle, Movie, Play, Show
admin.site.register(Spectacle)
admin.site.register(Movie)
admin.site.register(Play)
admin.site.register(Show) |
from flask import Flask, request
from flask_restful import Api, Resource
import sqlite3
app = Flask(__name__)
api = Api(app)
class Paperopoli(Resource):
def get(self):
return {'ciao': 'mondo'}
api.add_resource(Paperopoli, '/personaggi')
if __name__ == '__main__':
app.run(debug=True) |
#!/usr/bin/env python
__author__ = 'Florian Hase'
#========================================================================
import os, uuid
import numpy as np
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
from threading import Thread
from Utilities.file_logger import FileLogger
from Ut... |
import os
from urllib.parse import urlparse
from ruamel import yaml
def get_db_instance_dict(db_url, tags):
url_components = urlparse(db_url)
host = url_components.hostname
port = url_components.port
username = url_components.username
password = url_components.password
database_instance = """\
... |
import config
import os,time
from slack import WebClient
def log(func):
def wrapper(*args, **kw):
start = time.time()
run_func= func(*args, **kw)
end = time.time()
print('%s executed in %s ms' % (func.__name__, (end - start) * 1000))
return run_func
return wrapper
cla... |
"""
Data structure for implementing experience replay
Author: Patrick Emami, Modified by: Sri Ramana
"""
from collections import deque
import random
import numpy as np
from copy import deepcopy
class ReplayBuffer(object):
def __init__(self, buffer_size, min_hlen = 0, random_seed=123):
"""
The ri... |
from __future__ import absolute_import
from lltk.corpus.corpus import Corpus,load_corpus
from lltk.text.text import Text
import os
"""
class LitHist(Corpus):
TEXT_CLASS=Text
PATH_TXT = 'lithist/_txt_lithist'
PATH_XML = 'lithist/_xml_lithist'
PATH_METADATA = 'lithist/corpus-metadata.LitHist.txt'
def __init__(sel... |
#
# Copyright (c) 2019. JetBrains s.r.o.
# Use of this source code is governed by the MIT license that can be found in the LICENSE file.
#
import pytest
from lets_plot.plot.core import FeatureSpecArray, DummySpec
from lets_plot.plot.scale_convenience import *
@pytest.mark.parametrize('scale_spec, expected', [
(x... |
"""Console script for {{cookiecutter.pkg_name}}."""
{% if cookiecutter.command_line_interface|lower == 'y' -%}
import typer
main = typer.Typer()
@main.command()
def run() -> None:
"""Main entrypoint."""
typer.secho("{{ cookiecutter.project_slug }}", fg=typer.colors.BRIGHT_WHITE)
typer.secho("=" * len("{... |
#!/usr/bin/env python3
import argparse
import datetime
import glob
import inspect
import os
import subprocess
import yaml
from collections import defaultdict
class SafeDict(dict):
def __missing__(self, key):
return ''
def get_script_dir():
return os.path.dirname(inspect.getabsfile(get_script_dir))
S... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.