content stringlengths 5 1.05M |
|---|
import unittest
import hashlib
import struct
alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
baseCount = len(alphabet)
def formatVarInt(n):
""" Encodes an variable-length integer in Bitcoin's custom integer format for transactions"""
if n < 0xfd:
return struct.pack('<B', n)
... |
# -*- coding: utf-8 -*-
import subprocess
class YomiTokenizer(object):
'''
Japanese Yomi Tokenizer
'''
def __init__(self):
self.vocab = []
def encode(self, sentence):
sentence = sentence.replace("\'", "\"")
f = subprocess.check_output("echo \'" + sentence + "\' | mecab -Oy... |
#!/usr/bin/env python2.3
# -*- coding: utf-8 -*-
#
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# Licensed under the Apache Lice... |
import argparse
import sys
import RunTest
import upload
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--elf", action="store", type=str,
help="The firmware *.elf file to upload")
parser.add_argument("--dev", action="store", type=str,
... |
"""Utility
Utility functions.
"""
import sys
import numpy as np
def peakdet(v, delta, x=None):
"""
Peak picking algorithm.
Converted from MATLAB script at http://billauer.co.il/peakdet.html by
https://github.com/endolith.
Parameters
----------
v : ndarray
1D array, input signal.... |
"""
The `compat` module provides support for backwards compatibility with older
versions of django and python.
"""
# flake8: noqa
from __future__ import unicode_literals
# urlparse in python3 has been renamed to urllib.parse
try:
from urlparse import parse_qs, parse_qsl, urlparse, urlsplit, urlunparse, urlunsplit
... |
import asyncio
import aiohttp
async def send_message():
async with aiohttp.ClientSession() as session:
async with session.ws_connect('http://localhost:8080/ws') as ws:
await ws.send_str('Message')
asyncio.run(send_message())
|
# Copyright The IETF Trust 2021, All Rights Reserved
# -*- coding: utf-8 -*-
"""HedgeDoc API utilities"""
import json
import requests
import subprocess
import debug # pyflakes: ignore
from urllib.parse import urljoin
from django.conf import settings
from ietf.utils.markdown import markdown
class Note:
base_url... |
# Copyright 2016 Open Source Robotics Foundation, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... |
import os
import numpy as np
import matplotlib.pyplot as plt
from mazelib import Maze
from mazelib.generate.DungeonRooms import DungeonRooms
from mazelib.generate.Prims import Prims
from ipywidgets import interact,Dropdown,IntSlider
from PIL import Image
from .image import mesh_to_mask,mask_to_image3d
class Maze... |
"""
@author Leonhard Luecken
@date 2017-04-09
-----------------------------------
SUMO, Simulation of Urban MObility; see http://sumo.dlr.de/
Copyright (C) 2008-2017 DLR (http://www.dlr.de/) and contributors
This file is part of SUMO.
SUMO is free software; you can redistribute it and/or modify
it under the terms o... |
from django.views.generic import CreateView, UpdateView
from django.urls import reverse_lazy
from django.contrib.auth.views import redirect_to_login
from .forms import SignUpForm, SettingsForm
from .models import User
class SignUpView(CreateView):
form_class = SignUpForm
success_url = reverse_lazy('login')
... |
#!/usr/bin/env python
from distutils.core import setup
from catkin_pkg.python_setup import generate_distutils_setup
d = generate_distutils_setup()
d['packages'] = ['intera_interface', 'intera_control', 'intera_dataflow',
'intera_io', 'intera_joint_trajectory_action', 'intera_motion_interface']
d['pack... |
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import glob
import numpy as np
from IPython import embed
for filename in glob.glob("logs/images/*"):
img=mpimg.imread(filename)
plt.imshow(img)
plt.title(filename)
plt.show()
embed()
|
import adal
import requests
import os
from flask import Flask, request, jsonify, url_for
from flask_restful import Resource, Api
from json import dumps
import autentication
from flask import Blueprint
import setting
import json
import logging
import os
import subprocess
import sys
import objectpath
from azure.mgmt.reso... |
from argparse import ArgumentParser
from rdflib import Graph, Namespace
from utils import find_conversions, convert, standardize_namespaces, bump_versions, backup
from logging import getLogger
"""
Argument Parsing:
source: source version (for example '1.0.3')
target: target version (for example '1.1.0')
info: log ope... |
import os
import sys
import random
import pygame
from pygame.locals import *
# 设置窗口长宽
WIDTH, HEIGHT = 640, 480
# 设置背景颜色RGB
BACKGROUND = (255, 255, 255)
# 设置基础文件路径
if getattr(sys, 'frozen', False):
CurrentPath = sys._MEIPASS
else:
CurrentPath = os.path.dirname(__file__)
# 字体文件路径
FONTPATH = os.path.join(Curren... |
# -*- coding:UTF-8 -*-
from bs4 import BeautifulSoup
import requests
if __name__ == "__main__":
target = 'https://www.biqukan.com/99976_99976488/63984700.html'
req = requests.get(url=target)
html = req.text # 获取到html文档
bs = BeautifulSoup(html, "html.parser") # BeautifulSoup用来解析HTML信息,提取我们感兴趣的内容
... |
# See: https://adventofcode.com/2018/day/5#part2
import re
input_file_name = 'input.txt'
with open(input_file_name) as f:
content = f.readlines()
polymer = content[0].strip()
def isSameTypeOpositePolarity(v1, v2):
return (v1 != v2) and (v1.lower() == v2.lower())
def react_polymer(pr):
pos = 0
whil... |
# expose internal modules
from .statuses import HealthStatus
# limited the # of exports
# (do not export Null)
__all__ = ['OK', 'WARNING', 'CRITICAL', 'ERRORED', 'PARTIAL']
# create generic status codes
OK = HealthStatus(0)
WARNING = HealthStatus(1)
CRITICAL= HealthStatus(2)
ERRORED = HealthStatus(3)
PARTIAL = ... |
# SPDX-License-Identifier: MIT
# Copyright (c) 2018-2022 Amano Team
import logging
from pyrogram import Client, filters
from pyrogram.types import Message
from eduu.config import TENOR_API_KEY, prefix
from eduu.utils import commands
from eduu.utils.consts import http
from eduu.utils.localization import use_chat_lang... |
from datetime import date
import random
import re
MODE_DAILY = 0
MODE_RANDOM = 1
DIFFICULTY = {0: (5, 4), 1: (5, 5), 2: (6, 4), 3: (6, 5),
4: (7, 4), 5: (7, 5), 6: (7, 5)}
class Puzzle:
def __init__(self, mode=MODE_DAILY, seed=None, num_letters=5, num_core=4):
self.seed = seed
if no... |
from django.shortcuts import render
# Create your views here.
def tetris(request):
return render(request, 'ui/tetris.html')
|
import numpy as np
import matplotlib.pyplot as plt
from scipy.ndimage.filters import gaussian_filter
from math import factorial
from astar import astar, create_grid, Node
from dijkstras import shortest_path_mat
from scipy import ndimage
def plot_fr_field_2d(f,delay=None):
for i in range(len(f)):
maxval = np.max... |
# -*- coding: utf-8 -*-
# Copyright (c) 2020-2021 Paul Barker <paul@pbarker.dev>
# SPDX-License-Identifier: Apache-2.0
import os
import shutil
import sys
import datetime
from invoke import task
from pelican.server import ComplexHTTPRequestHandler, RootedHTTPServer
from pelican.settings import DEFAULT_CONFIG, get_sett... |
import json
import torch
import numpy as np
from model.build_model import build_chem_clip_model
class ModelInference(object):
def __init__(self, config_path, pretrain_model_path, device):
assert (config_path is not None, "config_path is None")
assert (pretrain_model_path is not None, "pretrain_mod... |
"""define util function and global variable"""
import tensorflow as tf
import os, sys
import time, yaml
from packaging import version
RES_DIR = './res/'
CACHE_DIR = './cache/'
MODEL_DIR = './checkpoint/'
CONFIG_DIR = './config/'
TRAIN_YAML = 'network.yaml'
TRAIN_NUM = './cache/train_num.csv'
EVAL_NUM = '.... |
import os
import discord
import requests
import random
import json
import datetime
import traceback
import constants
import urllib3
from discord.ext import commands
from mediusapi import *
#
def get_dl_skill_level(rank):
i = 0
if rank >= constants.DEADLOCKED_SKILLS_TABLE[9]:
return 10
if r... |
import requests
import json
import pytest
class Alexa_Test(object):
def __init__(self,endpoint, userid, applicationId, apitoken, locale="en-US", path_to_intent_json="src/sample.json"):
self.endpoint = endpoint
self.userid = userid
self.locale = locale
self.applicationId = applicatio... |
"""
Driver scheduling
Example with added work/break policies.
Based on https://developers.google.com/optimization/scheduling/employee_scheduling
"""
from __future__ import division
from __future__ import print_function
from ortools.sat.python import cp_model
from enum import IntEnum, unique
@unique
class State(In... |
from .base import *
from .helper import *
from .input import *
from .dense import *
from .noise import *
from .conv import *
from .local import *
from .pool import *
from .shape import *
from .merge import *
from .normalization import *
from .embedding import *
# from .recurrent import *
from .recurrent_new import *
fr... |
from random import randint
from time import sleep
cont = 0
lista = list()
jogos = list()
menu = '*-' *30
print(menu)
quant = int(input('Quantos jogos você deseje que eu sorteie?'))
tot = 0
while tot <= quant:
cont= 0
while True:
num = randint(1, 60)
if num not in lista:
lista.append... |
from numpy.random import seed
seed(1)
from tensorflow import set_random_seed
set_random_seed(2)
from keras.layers import Input, Dense, Conv2D, MaxPooling2D, UpSampling2D, Dropout, Flatten
from keras.models import Model
from keras import backend as K
from keras.datasets import cifar10
from keras.preprocessing.image im... |
#!/usr/bin/env python3
import sys, re, json
from collections import OrderedDict
data=OrderedDict()
Input_files=sys.argv[1:]
output = open("nuclear_contamination.txt", 'w')
print ("Individual", "Method1_MOM_estimate", "Method1_MOM_SE", "Method1_ML_estimate", "Method1_ML_SE", "Method2_MOM_estimate", "Method2_MOM_SE", ... |
# Copyright (c) 2015-2016, The Authors and Contributors
# <see AUTHORS file>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
# following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright n... |
side = 1080
def listPoints(ran):
points = [
(side * 0.1 + randint(-ran, ran), side * 0.3 + randint(-ran, ran)),
(side * 0.8 + randint(-ran, ran), side * 0.6 + randint(-ran, ran)),
(side * 0.6 + randint(-ran, ran), side * 1.1 + randint(-ran, ran)),
(side * 0.2 + randi... |
import multiprocessing as mp
import os
import pytest
pytestmark = pytest.mark.gpu
pynvml = pytest.importorskip("pynvml")
import dask
from distributed.diagnostics import nvml
from distributed.utils_test import gen_cluster
def test_one_time():
if nvml.device_get_count() < 1:
pytest.skip("No GPUs availa... |
# -*- coding: utf-8 -*-
# Learn more: https://github.com/kennethreitz/setup.py
from setuptools import setup, find_packages
with open('README.md') as f:
readme = f.read()
with open('LICENSE') as f:
license = f.read()
setup(
name='pyheatmy',
version='0.1.0',
description='PyHeat',
long_descri... |
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
combinations = []
def dfs(nums, currSum, i):
if currSum == target:
combinations.append(nums)
elif currSum < target:
for j in range(i, len(... |
from click.testing import CliRunner
from pathlib import Path
from ih.cli import main
from ih import palette
TEST_PNG = "test/images/smile.png"
TEST_JPG = "test/images/aurora.jpg"
TEST_OUTPUT = "test/output"
Path(TEST_OUTPUT).mkdir(exist_ok=True)
def get_test_html(image_src):
return Path(image_src).stem + ".ht... |
# Generated from Sygus.g4 by ANTLR 4.7.1
# encoding: utf-8
from antlr4 import *
from io import StringIO
from typing.io import TextIO
import sys
def serializedATN():
with StringIO() as buf:
buf.write("\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\3%")
buf.write("\u01ca\4\2\t\2\4\3\t\3\4\4\t\4\4... |
from django.contrib.auth import authenticate, login as auth_login, logout as auth_logout;
from django.http import HttpResponse, HttpResponseRedirect
from django.conf import settings
class BasicAuthMiddleware(object):
def process_request(self,request):
authentication = request.META.get('HTTP_AUTHORIZATION'... |
import copy
import json
import os.path
sobject_describes = {}
sobject_list = ["Account", "Contact", "Opportunity", "Task", "Attachment"]
with open(
os.path.join("assets", "test_describes", "sobjects.json"), "r", encoding="utf-8"
) as d:
root_describe = json.load(d)
for sobject in sobject_list:
with open(... |
import os, pytest
from pathlib import Path
from datetime import datetime
from luna_pathology.common.annotation_utils import *
SLIDEVIEWER_API_URL = "http://test-slideviewer-url.com/"
SLIDE_BMP_DIR = "tests/luna_pathology/common/testdata/project/regional_bmps"
SLIDE_NPY_DIR = "tests/luna_pathology/common/testdata/proj... |
from tamcolors.tests.all_tests import tests_main
if __name__ == "__main__":
exit(int(not tests_main()))
|
# Justin Rutherford 20.4.18
# An
# Code from Stackoverflow https://stackoverflow.com/questions/45862223/use-different-colors-in-scatterplot-for-iris-dataset
import matplotlib.pyplot as plt
import seaborn as sns
iris = sns.load_dataset("iris")
iris["ID"] = iris.index
iris["ratio"] = iris["sepal_length"]/iris["s... |
#!/usr/bin/env python2
from app import app
app.run(host='0.0.0.0', port=4326, debug=True)
|
from pypy.tool.pairtype import pairtype
from pypy.annotation import model as annmodel
from pypy.rpython.lltypesystem.lltype import \
Signed, Unsigned, SignedLongLong, Bool, Float, Void, pyobjectptr
from pypy.rpython.error import TyperError
from pypy.rpython.rmodel import FloatRepr
from pypy.rpython.rmodel import I... |
from mars import main_loop
from mars.settings import *
import numpy as np
class Problem:
"""
Synopsis
--------
Problem class for the shock tube.
Args
----
None
Methods
-------
initialise
Set all variables in each cell to initialise the simulation.
internal_bc
... |
#!/usr/bin/env python3
# File name: format.py
# Description: Basic format for Python scripts
# Author: Louis de Bruijn
# Date: 19-05-2020
import argparse
import logging
import sys
from logging import error, info
def parse_arguments():
"""Read arguments from a command line."""
parser = argparse.ArgumentParser... |
import json
from typing import List
import requests
def main(problem_ids: List[str]):
problem_models = requests.get("https://kenkoooo.com/atcoder/resources/problem-models.json").json()
print(f"removing {len(problem_ids)} models")
for problem_id in problem_ids:
model = problem_models.pop(problem_id... |
from registration import CrossCorr
from numpy import meshgrid, linspace, dstack, asarray
from skimage.transform import PiecewiseAffineTransform, warp
def register(data):
"""
Function for registering data. The reference image is computed as the mean of
the provided data.
Parameters
----------
d... |
# ============LICENSE_START=======================================================
# org.onap.dcae
# ================================================================================
# Copyright (c) 2018-2020 AT&T Intellectual Property. All rights reserved.
# =============================================================... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Includes all the test modules from this directory
and runs the tests.
LICENSE:
Braille Grade 2 Translation in Python
Copyright (C) 2016 Antonis Katzourakis
This program is free software: you can redistribute it and/or modify
it under the... |
from os import getenv
from pathlib import Path
BASE_DIR = Path(__file__).parents[2] # go up for 2 parent directories
AUTH_USER_MODEL = 'users.User'
URL_SCHEME = getenv('URL_SCHEME', 'https')
|
#!/usr/bin/env python
import sys
import requests
import re
import pickle
from bs4 import BeautifulSoup
from pprint import pprint
base_url = "http://wiki.webtender.com"
drink_dict = {}
def get_soup(extended_url="", level="all"):
url = base_url + extended_url
response = requests.get(url)
page = response.t... |
import ast
import os
import re
import site
import sys
from collections import namedtuple
from configparser import ConfigParser
from functools import wraps
from logging import getLogger
import flake8
import toml
from pkg_resources import parse_requirements
from pkg_resources import yield_lines
from .modules import KNO... |
import os
import requests
import time
import multiprocess as mp
from bso.server.main.logger import get_logger
AFFILIATION_MATCHER_SERVICE = os.getenv('AFFILIATION_MATCHER_SERVICE')
matcher_endpoint_url = f'{AFFILIATION_MATCHER_SERVICE}/enrich_with_affiliations_id'
logger = get_logger(__name__)
def exception_hand... |
# (c) @XRoiDX
import json
import subprocess
async def get_video_info(filename):
result = subprocess.check_output(
f'ffprobe -v quiet -show_streams -select_streams v:0 -of json "{filename}"',
shell=True).decode()
fields = json.loads(result)['streams'][0]
return fields['duration'], ... |
import web
from web import form
import model.ordergroup
import model.regels
from controller import Controller
from functions import table_string
class Salaris(Controller):
def __init__(self):
Controller.__init__(self)
# subclass specific
self.title = 'Salaris'
self... |
import pandas as pd
import numpy as np
import glob
import pickle
import os
import sklearn
from sklearn.externals import joblib
def compile_data_set(file_dir='./data/lines/', save_name='./data/sdss_df.pkl',
clobber=False):
"""
Compiles the SDSS data set
Parameters
----------
f... |
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
length = len(s)
if length < 2:
return s
r = ""
index = 0
while index < length:
# 中间为该字符的回文数
left, right = index, index... |
import unittest
from django.test import Client
from django.test import TestCase, RequestFactory
from django.contrib.auth.models import User
class InitCase(TestCase):
client = Client()
def setUp(self):
self.factory = RequestFactory()
self.user = User(username="danialkamali",password="123456789"... |
# This file is part of REANA.
# Copyright (C) 2019, 2020, 2021, 2022 CERN.
#
# REANA is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Workflow run manager interface."""
import base64
import json
import logging
import os
from flask i... |
from tqdm import tqdm
import lxml.etree as ET
from itertools import chain, product
import csv
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--drugbankpath', type=str,
help='Set this to the path of your drugbank XML.')
args = parser.parse_args()
tree = ET.parse(args.drug... |
import turtle as t
def canvas(rate):
t.pensize(6)
t.speed(0)
t.hideturtle()
t.forward(66 * rate)
t.right(180)
t.forward(33 * rate)
t.left(90)
t.forward(34 * rate)
t.left(90)
t.forward(33 * rate)
t.left(180)
t.forward(66 * rate)
t.right(180)
t.done()
canvas(9) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from twisted.internet import reactor
from twisted.protocols.basic import LineReceiver
__author__ = 'nacim'
from twisted.internet.protocol import Factory, ClientFactory
class TestProtocol(LineReceiver):
def dataReceived(self, data):
# get process ID... |
# coding: utf-8
#
# Copyright 2019 The Oppia Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... |
import sys, os
path = os.path.dirname(os.path.abspath(__file__))
if path not in sys.path:
sys.path.insert(0, path)
from uliweb.manage import make_application
application = make_application(project_dir=path)
|
from distutils.core import setup
requires_list = [
'hashlib==20081119',
'nose>=1.3.0']
setup(
name='xorcrypt',
description='A simple python XOR encryption/decryption/obfuscation library',
version='0.1',
packages=['xorcrypt',],
license='MIT License',
long_description=open('README.md').... |
# Written by Seonwoo Min, Seoul National University (mswzeus@gmail.com)
from thop import profile
import torch.nn as nn
from src.model.model import CNN
from src.embed import get_embedding_dim
from src.utils import Print
def get_model(model_cfg, run_cfg):
""" get a DeepHSP/DeeperHSP model """
in_channels = g... |
'''
Copyright 2019 Secure Shed Project Dev Team
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in wri... |
# pylint: disable=line-too-long
# pylint: disable=unused-argument
# pylint: disable=redefined-outer-name
import pytest
from helpers.cluster import ClickHouseCluster
cluster = ClickHouseCluster(__file__)
node = cluster.add_instance("node_default", stay_alive=True)
@pytest.fixture(scope="module", autouse=True)
def st... |
from django.db import models
from django.contrib.auth.models import User
from django.db.models import Q
from django.urls import reverse
from django.core.validators import MinValueValidator, MaxValueValidator
# these are game values with corresponding letter.
GAME_STATUS_CHOICES = (
('F', 'First Player To Move'),
('... |
def part1(input):
total = 0
for passport in input:
if len(passport) == 8 or len(passport) == 7 and "cid" not in passport:
total += 1
return total
def part2(input):
def isValid(passport):
if len(passport) == 8 or len(passport) == 7 and "cid" not in passport:
try:
... |
from selenium.webdriver.support.color import Colors
pomidor = 'Pomidor'
class PomidorKeyDoesNotExist(Exception):
"""PomidorCantRunOneBrowserInstanceInParallel Exception"""
def __init__(self, key):
self.key = key
def __repr__(self):
return f'{Colors.FAIL}\n{pomidor}ERROR\nKeyboard key {s... |
import numpy as np
import nibabel as nb
from brainspace import mesh, plotting
def plot_surf_hemi(surface, labels, scalar_map, view=['lateral', 'medial'],
screenshot=False, filename=None,
embed_nb=False, interactive=False,
cmap='Spectral_r', color_bar='right',... |
# https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def add(self, node, val):
... |
# conftest.py
import pytest
import inspect
from py.xml import html
def pytest_html_report_title(report):
report.title = "DuT Report - sample"
def pytest_addoption(parser):
parser.addoption("--make_file", action="store")
parser.addoption("--work_dir", action="store")
parser.addoption("--key_list", ac... |
"""
Test to verify get webhook.
"""
from test_repo.autoscale.fixtures import ScalingGroupWebhookFixture
class GetWebhook(ScalingGroupWebhookFixture):
"""
Verify get webhook
"""
@classmethod
def setUpClass(cls):
"""
Create scaling group with webhook.
"""
cls.wb_meta... |
#!/usr/bin/python3
#
# MIT License
#
# Copyright (c) 2017 Arkadiusz Netczuk <dev.arnet@gmail.com>
#
# 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 limi... |
from django.conf import settings
from django.contrib.sites.models import Site
from django.db.models import Q
from leonardo.module.web.models import Page
class MultiSiteMiddleware(object):
"""activate page filter by request.get_host
"""
last_current = None
def process_request(self, request):
... |
import torch
class ReLU(torch.autograd.Function):
@staticmethod
def forward(ctx, input):
ctx.save_for_backward(input)
return input.clamp(min=0)
@staticmethod
def backward(ctx, grad_output):
input, = ctx.saved_tensors
grad_input = grad_output.clone()
grad_input[i... |
# -*- coding: utf-8 -*-
demet = (1,2,3,4,5,6,7,8,9)
print(type(demet))
print(demet[4])
print(demet[-1])
print(demet[:6])
print(demet[::-1])
print(demet[::2])
print(demet.index(4))
#%%
demet1 = (1,1,1,1,1,5,5,5,5,7,7,7,9,2,4)
print(demet1.count(1))
print(demet1.count(6))
|
"""
utils.py
Maintainer: Theodoros Giannakopoulos {tyiannak@gmail.com}
"""
# -*- coding: utf-8 -*-
import json
def load_config(config_file_path):
with open(config_file_path, mode="r") as j_object:
config_data = json.load(j_object)
return config_data |
from typing import List
import xml.etree.ElementTree as et
from pathlib import Path
# pycharm complains that build_assets is an unresolved ref
# don't worry about it, the script still runs
from build_assets import filehandler, arg_getters, util
def main():
"""
Check the quality of the svgs IF this is an ico... |
# Copyright lowRISC contributors.
# Licensed under the Apache License, Version 2.0, see LICENSE for details.
# SPDX-License-Identifier: Apache-2.0
from typing import List, Optional
from .trace import Trace
class TraceWSR(Trace):
def __init__(self, wsr_name: str, new_value: int):
self.wsr_name = wsr_name... |
from guillotina import configure
from guillotina import schema
from guillotina.addons import Addon
from zope.interface import Interface
class IRegistryData(Interface):
foobar = schema.TextLine()
@configure.addon(name="docaddon", title="Doc addon")
class TestAddon(Addon):
@classmethod
def install(cls, co... |
import numpy as np
import cv2 as cv
import matplotlib.pyplot as plt
img = cv.imread('mann.jpg')
img = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
corner = cv.goodFeaturesToTrack(img,1000,0.01,10)
corner = np.int0(corner)
for i in corner:
x,y = i.ravel()
cv.circle(img,(x,y),5,(122,0,255),-1)
cv.imshow('... |
'''
Created on Oct 22, 2018
@author: casey
'''
class Segment(object):
#
# * Segments make up the tree. There is a base segment, then a root segment, then the tree expands into internal segments, until it gets to leaf segments.
# * These segment types make it easier to traverse the tree during b... |
import pytest
import json
from indy import did
from utilities import common, constant
from utilities import utils
from test_scripts.functional_tests.did.signus_test_base \
import DidTestBase
class TestCreateDidWithCid(DidTestBase):
@pytest.mark.asyncio
async def test(self):
# 1. Create wallet.
... |
# Program no 1
print ("Twinkle, twinkle, little star,\n\tHow I wonder what you are,\n\t\tUp above the world so high!\n\t\tLike a diamond in the sky.\nHow I wonder what you are,\n\tUp above the world so high")
|
from intake.source import base
import json
from . import __version__
try:
from json.decoder import JSONDecodeError
except ImportError:
JSONDecodeError = ValueError
class ElasticSearchSeqSource(base.DataSource):
"""
Data source which executes arbitrary queries on ElasticSearch
This is the tabular ... |
#!/usr/bin/env python
# Copyright 2014-2021 The PySCF Developers. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# U... |
#!/usr/bin/env python -i
import os
from psz.config import DEFAULTS as defaults
os.environ['DJANGO_SETTINGS_MODULE']='settings'
from psz.models import Dnskey
defaults['path_zonedir'] = '/tmp'
TEST_ZONE_NAME = 'psz.test.zone.co.uk'
keynamebit = 'K' + TEST_ZONE_NAME
key = Dnskey.from_dnssec_keygen(zone='psz.test.zone.co.... |
import smtplib
print'''
#################################################
#################################################
########### Ali Ebadi Gmail CracKeR ###########
#################################################
###################################... |
# -*- coding: utf-8 -*-
# This file is part of beets.
# Copyright 2015, Fabrice Laporte
#
# 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 t... |
# -*- coding: utf-8 -*-
'''
:codeauthor: Pedro Algarvio (pedro@algarvio.me)
salt.log.mixins
~~~~~~~~~~~~~~~
.. versionadded:: 0.17.0
Some mix-in classes to be used in salt's logging
'''
from __future__ import absolute_import
# Import python libs
import sys
import logging
class LoggingProfileM... |
#!/usr/bin/python
import pygame as gm
from components.port import Port
class Board:
def __init__ (self, background, wires=[], components=[]):
self.screen = gm.Surface(background.get_size())
self.back = background
self.wires = wires
self.comps = []
self.ports = []
#print("{} objects instanci... |
from __future__ import print_function
import os
import time
from tqdm import tqdm
import lasagne
import numpy as np
import preprocessLipreading
import general_tools
import theano
import logging
logger_train = logging.getLogger('lipreading.train')
logger_train.setLevel(logging.DEBUG)
def load_model(model_path, netwo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.