content stringlengths 5 1.05M |
|---|
import glob
import os
import signal
#import resource
import logging
import re
import shutil
import tempfile
import shlex
import fnmatch
import platform
import subprocess
import threading
import traceback
from time import clock
def locate_program(candidatePaths):
for p in candidatePaths:
if os.path.isfile(p... |
#!/usr/bin/env python
"""
Build script for the shared library providing the C ABI bridge to LLVM.
"""
from __future__ import print_function
from ctypes.util import find_library
import os
import subprocess
import shutil
import sys
import tempfile
here_dir = os.path.abspath(os.path.dirname(__file__))
build_dir = os.p... |
# pylint: disable=no-member
import json
import urllib
import signal
import time
import pycurl
POST_PARAMS = {}
class Client:
def __init__(self, sensor, api_url, api_user, api_password):
if sensor is not None:
self._sensor = sensor
else:
self._sensor = None
self.con... |
import sys
import time
import numpy as np
from gym import spaces
from ..game.constants import Constants
"""
Implements the base class for a training Agent
"""
class Agent:
def __init__(self) -> None:
"""
Implements an agent opponent
"""
self.team = None
self.match_controlle... |
import typing
import fastapi
import sqlalchemy.orm
from wod_board import config
from wod_board import exceptions
from wod_board.crud import goal_crud
from wod_board.models import get_db
from wod_board.models import goal
from wod_board.schemas import goal_schemas
from wod_board.schemas import user_schemas
from wod_boa... |
import ast
from requests import HTTPError
from zoho_subscriptions.client.client import Client
from zoho_subscriptions.subscriptions.addon import Addon
from zoho_subscriptions.subscriptions.customer import Customer
from zoho_subscriptions.subscriptions.hostedpage import HostedPage
from zoho_subscriptions.subscriptions.... |
from .FileInfo import FileInfo
class generic_file(FileInfo):
"""
Class for generic files that do not need much to happen with them
(ie. just view, whatever...)
"""
def __init__(self, id_=None, file=None, parent=None):
super(generic_file, self).__init__(id_, file, parent)
self._type... |
"""Django REST Framework views"""
from django.conf import settings
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_page
from flipt_pb2 import ListFlagRequest
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from rest_framew... |
import ply.lex as lex
import ply.yacc as yacc
import sys
tokens = ["NUM", "PAL"]
literals = ["[","]", ","]
t_NUM = r"\d+"
t_PAL = r"[a-zA-Z]+"
t_ignore = " \n\t\r"
def t_error(t):
print("Illegal character " + t.value[0])
lexer = lex.lex()
#analisador léxico
#for line in sys.stdin:
# lexer.input(line)
# ... |
#!/usr/bin/env python
#
# notifier.py
#
# Copyright (c) 2014-2015 Junpei Kawamoto
#
# This software is released under the MIT License.
#
# http://opensource.org/licenses/mit-license.php
#
import argparse
import fnmatch
import json
import re
import sys
from docker import Docker
from pushover import Pushover
__APPLICATI... |
#!/usr/bin/env python3
#-*- coding: utf-8 -*-
#=======================================================================================
# Imports
#=======================================================================================
import argparse
import configparser
from lib.base import *
from lib.cappconfig impor... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
"""Test for Transformer decoder."""
import argparse
import importlib
import numpy as np
import pytest
import torch
from neural_sp.datasets.token_converter.character import Idx2char
from neural_sp.models.torch_utils import np2tensor
from neural_sp.models.torch_utils imp... |
import os
DEFAULT = {
"LOCAL_PATH": os.path.expanduser("~/data/"),
"FEEDSTOCK_PATH": os.path.expanduser("~/feedstock/"),
"SERVICE_DATA": os.path.expanduser("~/integrations/"),
"CURATION_DATA": os.path.expanduser("~/curation/"),
"SCHEMA_PATH": os.path.abspath(os.path.join(os.path.dirname(__file__)... |
"""rio-tiler-crs tile server."""
import logging
import os
from enum import Enum
from typing import Any, Dict, List
import morecantile
import uvicorn
from fastapi import FastAPI, Path, Query
from rasterio.crs import CRS
from starlette.background import BackgroundTask
from starlette.middleware.cors import CORSMiddlewar... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 15 09:03:59 2020
@author: edward
dataset for pytorchd dataloading
"""
import torch
import os, glob, itertools, random
from torch.utils.data import Dataset, DataLoader
import numpy as np
#from tqdm import tqdm
import pprint
pp = pprint.PrettyPrinte... |
import numpy as np
import torch.utils.data as data
import torch
import os, glob
from six.moves import xrange # pylint: disable=redefined-builtin
import PIL.Image as Image
import random
import numpy as np
import cv2
import time
class DatasetReader_fullvid(data.Dataset):
def __init__(self, video_path):
self... |
# Copyright 2020 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
# -*- coding: utf-8 -*-
"""
Copyright [2009-current] EMBL-European Bioinformatics Institute
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... |
from fastapi import APIRouter
from example_app.core.models.output import OutputExample
from example_app.core.models.input import InputExample
router = APIRouter()
@router.get("/example", tags=["example get"])
def example_get():
"""
Say hej!
This will greet you properly
And this path operation will... |
import asyncio
from predcrash_utils.commons import get_asset_root, get_file_content
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import conda
import os
from logzero import logger as LOGGER
conda_file_dir = conda.__file__
conda_dir = conda_file_dir.split('lib')[0]
proj_lib = os.path.join(os.pa... |
#pragma error
#pragma repy
fro = open("h:lo","r")
fro.close()
|
from collections import defaultdict, deque
from copy import deepcopy
from random import Random
from string import ascii_lowercase as lowercase
import sys
import traceback
from snakegame.colour import hash_colour
from snakegame import common
class Engine(object):
def __init__(
self,
rows, columns, ... |
from peewee import *
db = SqliteDatabase('movie.db')
class User(Model):
id = IntegerField(primary_key=True)
gender = CharField()
age = IntegerField()
occupation = IntegerField()
zip_code = CharField()
class Meta:
database = db
def __str__(self):
return 'User {}, gender: ... |
white = (255,255,255)
blue = (0, 0, 255)
red = (255, 0, 0)
green = (0, 255, 0)
orange = (255, 165, 0)
yellow = (255, 255, 0)
cyan = (0, 255, 255)
magenta = (255, 0, 255)
brown = (165, 42, 42)
grey = (190, 190, 190)
color_count = 10
max_color_index = 9
min_color_index = 0
color_presets = [white, red, green, blue, oran... |
from lxml.html.clean import Cleaner
class SafeHTML(object):
def __init__(self):
self.cleaner = Cleaner(
scripts=True,
javascript=True,
style=True,
page_structure=True,
annoying_tags=True,
remove_unknown_tags=True)
def render(self, src):
return self.cleaner.clean_html(src)
|
# from .mobilenet_model_im import mobilenet
from .mobilenetv2 import MobileNet_V2
from .mobilenetv3 import MobileNet_V3
|
import time
import grove_i2c_color_sensor
# Open connection to sensor
color_sensor = grove_i2c_color_sensor.GroveI2CColorSensor()
# Perform continuous integration with predefined duration of 100ms
color_sensor.use_continuous_integration(100)
# Set gain to 16x
color_sensor.set_gain_and_prescaler(16)
# Start integratio... |
import os
import numpy as np
import shutil
from skimage import data, color, exposure, io
from skimage.feature import hog
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import numpy as np
from sklearn.metrics import classification_report,accuracy_score
from skimage.transform import rescale, resize
... |
# Imports
import os
from ..utils.blender import add_group
from .Constraint import ObConstraint, CamConstraint
from .MappedClass import MappedClass
# Should be moved, along with test below
#from .Object import Object
#from .Camera import Camera
#from .Scene import Scene
#from .Sky import Sky
try:
import bpy
imp... |
import os
import dj_database_url
### Basic config
BASE = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
DEBUG = TEMPLATE_DEBUG = True
SITE_ID = 1
SECRET_KEY = 'its-a-secret-to-everybody'
# Until Sentry works on Py3, do errors the old-fashioned way.
ADMINS = []
# General project information
# T... |
#===============================================================================
""" Configurações Opcionais """
#===============================================================================
# Digite o e-mail abaixo para receber alertas de e-mail em tempo real
# por exemplo, 'email@gmail.com'
MAIL = ''
# Insira o UR... |
# Copyright (c) OpenMMLab. All rights reserved.
import os
import os.path as osp
from typing import List, Optional, Sequence, Union
import mmcv
import numpy as np
from mmcls.datasets.builder import DATASETS
from typing_extensions import Literal
from .base import BaseFewShotDataset
TRAIN_CLASSES = [
'n02074367', '... |
from .command import cmd
from .files import *
from .flags import flag
from .config import local_config
import os.path
import json
import re
def input_older_than_output(rule_config):
return max_modify_time(rule_config['in']+[rule_config['__config_fn']]) > min_modify_time(rule_config['out'])
def needs_to_run(rule_co... |
from pymclevel import alphaMaterials, MCSchematic, MCLevel, BoundingBox
from pymclevel.box import Vector
from mcplatform import *
inputs = (
("Better Nuke", "label"),
("Creator: Colan Biemer", "label")
)
def draw_block(level, x, y, z, material):
level.setBlockAt(x, y, z, material.ID)
level.setBlockDataAt(x, y, z,... |
#
# 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 writing, software
# distributed under t... |
from flask import Flask, jsonify, abort, render_template, request, redirect, url_for, g, send_from_directory
import subprocess
import os
import psutil
import socket
import signal
import RPi.GPIO as GPIO
import csv
import Adafruit_DHT
import threading
from collections import deque
import datetime
import tele... |
from pyautodiff.dual import Dual as Dual
import numpy as np
def sin(x):
"""Calculate sine of the input
Keyword arguments:
x -- a real number or a dual number
Return:
the sine value
"""
if (isinstance(x,Dual)):
x.der = np.cos(x.val)*x.der
x.val = np.sin(x.va... |
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import cv2
import os
def grayscale(img):
"""Applies the Grayscale transform
This will return an image with only one color channel
but NOTE: to see the returned image as grayscale
(assuming your grayscaled image is calle... |
# Filename: Controller.py
# Written by: Niranjan Bhujel
# Description: Contains controller such as LQR, MPC, etc.
from math import inf, isinf
from pynlcontrol.BasicUtils import Integrate, nlp2GGN, casadi2List, directSum, __SXname__
import casadi as ca
def LQR(A, B, C, D, Q, R, Qt, Ts, horizon=inf, reftrack=F... |
# Generated by Django 2.2.5 on 2020-10-12 12:01
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('nsp_project_app', '0024_notification_status'),
]
operations = [
migrations.AlterField(
model_name='notification',
na... |
class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
event = []
for i in range(len(trips)):
nums, from_ , to_ = trips[i]
event.append([from_, nums])
event.append([to_, -nums])
event.sort()
cnt = 0
for i in ra... |
"""Contains a cog that fetches colors."""
# pylint: disable=C0103
import colorsys
import secrets
import colour
from sailor import commands
from sailor.exceptions import UserInputError
import webcolors
from sailor_fox.helpers import FancyMessage
BASE_URL_COLOR_API = "https://www.colourlovers.com/img/{0}/{1}/{2}/"
B... |
# Variáveis
num_cont = num = val_maior = val_menor = media = val_media = 0
fim = 'S'
# Repetição
while fim != 'N':
# Variáveis int e string
num = int(input('Digite um valor: '))
fim = str(input('Você quer continuar? [S/N] ').upper())
# Variáveis média
# Ele vai ser o valor que vai dividir com o val... |
# Copyright 2017-2020 by the Viziphant team, see `doc/authors.rst`.
# License: Modified BSD, see LICENSE.txt for details.
from elephant.utils import check_same_units as check_same_units_single
def check_same_units(spiketrains):
if isinstance(spiketrains[0], (list, tuple)):
for sts in spiketrains:
... |
import torch
from torch import nn
from torchdrug import core, layers
from torchdrug.layers import functional
from torchdrug.core import Registry as R
@R.register("models.GraphAF")
class GraphAutoregressiveFlow(nn.Module, core.Configurable):
"""
Graph autoregressive flow proposed in `GraphAF: a Flow-based Aut... |
'''
we need to
1-do something
2-save it to database
3-log all these process
instead of doing this everytime, we simply define a facade class that has a method to do it'''
class SomeBusiness():
def DoSomething(self):
pass
class SomeRepository():
def SaveSomething(self, thing):
pass
class SomeLogger:
... |
# AUTOGENERATED! DO NOT EDIT! File to edit: source_nbs/11_modeling.ipynb (unless otherwise specified).
__all__ = ['MultiModalBertModel']
# Cell
# nbdev_comment from __future__ import absolute_import, division, print_function
import json
import tensorflow as tf
import transformers
from loguru import logger
from .par... |
# Copyright 2015 Michael DeHaan <michael.dehaan/gmail>
#
# 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... |
#!/usr/bin/env python
# Code for Brian Corteil's Tiny 4WD robot, based on his original code,
# but using appproxeng libraries to allow genuine PS3 support
# (see https://github.com/ApproxEng/approxeng.input.git)
# Imported from https://github.com/EmmaNorling/Tiny4WD/blob/master/TinyPirate.py
# Load library functions ... |
'''
Author: flwfdd
Date: 2022-01-03 13:44:03
LastEditTime: 2022-01-20 23:39:25
Description: 配置文件
_(:з」∠)_
'''
header = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36 Edg/80.0.361.66',
}
api_base_url = {
"C": "http://x.x.x.x:3... |
from copy import copy
import os
import numpy as np
import scipy.signal as _signal
import scipy.interpolate as _interp
from scipy.signal import hilbert as analytic
from scipy import ndimage
def gauss2(X, Y, mu, sigma, normalize=True):
""" Evaluates Gaussian over points of X,Y
"""
# evaluates Gaussian ov... |
from databricks_cli.runs.api import RunsApi
from databricks_cli.workspace.api import WorkspaceApi
import os
import time
import base64
class PipelineRun:
def __init__(self, waiter, run_id):
self._waiter = waiter
self._run_id = run_id
def wait_for_completion(self, show_output=True, timeout_seco... |
#!/usr/bin/env python
try:
from setuptools import setup
except ImportError as err:
from distutils.core import setup
import os
def find_version():
for line in open(os.path.join('sgc', '__init__.py')):
if line.startswith('__version__'):
return line.split('=')[1].strip().strip('"').strip("... |
# Import modules.
import boto3
# Initiate AWS session with ec2-admin profile.
aws_session = boto3.session.Session(profile_name="inderpalaws02-ec2-admin")
# Initiate EC2 resource because collections exist for service resource.
ec2_resource = aws_session.resource(service_name="ec2",region_name="us-east-1")
# Initia... |
import vtk
import numpy as np
# Create points and cells for the spiral
nV = 256
nCyc = 10
rT1 = 0.2
rT2 = 0.5
rS = 4
h = 10
nTv = 8
points = vtk.vtkPoints()
for i in range(0, nV):
# Spiral coordinates
vX = rS * np.cos(2 * np.pi * nCyc * i / (nV - 1))
vY = rS * np.sin(2 * np.pi * nCyc * i / (nV - 1))
#... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#Author: Tim Henderson
#Email: tim.tadh@gmail.com
#For licensing see the LICENSE file in the top level directory.
import os
from random import seed
from zss import (
simple_distance,
Node,
)
seed(os.urandom(15))
def test_empty_tree_distance():
assert simpl... |
import sys
from XenServer import XenServer
import traceback
try:
xs_session = XenServer().make_session()
pool = xs_session.xenapi.pool.get_all()[0]
pool_record = xs_session.xenapi.pool.get_record(pool)
sys.stdout.write("Successfully connected to pool: " + pool_record["name_label"]+'\n')
except Exce... |
import torch.nn as nn
import torch.nn.functional as F
class Fpn(nn.Module):
def __init__(self):
super(Fpn, self).__init__()
self.upLayer1=nn.Sequential(
nn.Conv2d(512,256,1,1,0),
nn.BatchNorm2d(256),
nn.ReLU(inplace=True),
)
self.upLaye... |
#!/usr/bin/env python
# By Chris Paxton
# (c) 2017 The Johns Hopkins University
# See license for more details
import rospy
from costar_task_plan.robotics.tom.config import TOM_RIGHT_CONFIG as CONFIG
from sensor_msgs.msg import JointState
import tf
import tf_conversions.posemath as pm
from pykdl_utils.kdl_parser im... |
import sys
import pyvisa
import visa
from PyQt4 import QtGui, QtCore
from cmw500auto import Ui_CMW500AutomationTool
from cellPowerManager import CellPowerTest
class AttenuationManager(QtGui.QMainWindow):
def __init__(self):
QtGui.QWidget.__init__(self)
self.uiAM = Ui_CMW500AutomationT... |
from cauldron import environ
from cauldron.session import projects
from cauldron.session.caching import SharedCache
class StepTestRunResult:
"""
This class contains information returned from running a step during testing.
"""
def __init__(
self,
step: 'projects.ProjectStep',
... |
from typing import Dict
from ray.rllib.agents.callbacks import DefaultCallbacks
from ray.rllib.env import BaseEnv
from ray.rllib.evaluation import MultiAgentEpisode, RolloutWorker
from ray.rllib.policy import Policy
def get_callback():
class Callbacks(DefaultCallbacks):
def on_episode_start(
... |
# Copyright (C) 2015 Cisco, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
# 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 writing, software
# d... |
"""
Formatting of UML model elements into text tests.
"""
import pytest
import gaphor.UML.uml2 as UML
from gaphor.services.eventmanager import EventManager
from gaphor.UML import model
from gaphor.UML.elementfactory import ElementFactory
from gaphor.UML.umlfmt import format
from gaphor.UML.umllex import parse
@pyte... |
# -*- coding: utf-8 -*-
"""Tests for `mq_api`."""
import os
import sys
import unittest
from unittest.mock import patch
from modules.mq_api import (
run_mq_command,
check_not_empty_list,
add_annotation)
sys.path.append(os.getcwd())
def mock_execute_command(command):
"""Mock for `execute_command` functi... |
import os
import glob
import pathlib
import itertools
from functools import wraps
import inspect
from parse import parse as parse_
from pformat import *
__all__ = ['Paths', 'Path', 'tree', 'UnderspecifiedError']
def tree(root='.', paths=None, data=None):
'''Build paths from a directory spec.
Arguments:
... |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: src/training_game.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection... |
# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You may
# not use this file except in compliance with the License. A copy of the
# License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# copyright Julien TREBOSC 2012-2013
# calculates (S-S0)/S0 of a 2D dataset
# dataset must be series of 1D spectra alternated S/S0
# if a point of S0 spectrum is below the defined threshold
# then set S0 point to threshold if S0 below threshold
from __future__ import division... |
from functools import partial
import numpy as np
import pytest
import torch
from nnrl.utils import convert_to_tensor
from raylab.envs import get_env_creator
DECELERATION_ZONES = (
{"center": [[0.0, 0.0]], "decay": [2.0]},
{"center": [[5.0, 4.5], [1.5, 3.0]], "decay": [1.15, 1.2]},
)
@pytest.fixture(params=... |
# coding: utf-8
# Copyright 2020 IBM All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... |
# coding=utf-8
from flask import (render_template, flash, redirect, url_for, request,
current_app)
from flask.ext.login import login_user, logout_user, login_required
from ..models import User
from . import auth
from .forms import LoginForm
@auth.route('/login', methods=['GET', 'POST'])
def login(... |
""" A package with several SQL related helpers. """
|
from mrjob.job import MRJob
from mrjob.step import MRStep
import time
# Couldn/t use class objects as intermediate values of mapper and reducer steps since it is not serializable ,
# Also using namedtuple didnt work since it gets converted to list by default for serializability(Reason assumed)
# class day_temp_stats... |
#!/usr/bin/env python
# Copyright 2014, Rob Lyon <nosignsoflifehere@gmail.com>
#
# 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 req... |
from keyring.testing.backend import BackendBasicTests
from sagecipher.keyring import Keyring
class TestKeyring(BackendBasicTests):
def init_keyring(self):
return Keyring()
|
#!/usr/bin/python
# @marekq
# www.marek.rocks
import base64, botocore, boto3, csv, feedparser
import gzip, json, os, re, readability, requests
import queue, sys, threading, time
from aws_lambda_powertools import Logger, Tracer
from boto3.dynamodb.conditions import Key, Attr
from datetime import date, datetime, timede... |
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
from PyQt5 import QtGui
import cv2
def qimage_of_item(item_name: str) -> QtGui.QImage:
"""Get item picture"""
# If item has 'ENCHANTED' in the name, give the normal picture because
# im too lazy to get the enchanted pictures
if 'ENCHANTED' in item_name:
item_name_split = item_name.split('_')[... |
import pandas as pd
import plotly.graph_objects as go
print('\tStarting /home/duck/scripts/reproduce_historical_sales_data_diagram.py…')
path = '/home/duck/data'
csv_file_path = path + '/basedata/historical_sales_data_csv_format.csv'
image_path = path + '/images'
df = pd.read_csv(csv_file_path, index_col=0)
print('R... |
import scrapy
from scrapy import signals
from scrapy.shell import inspect_response
from ids import QUEST_IDS
from utils import Merger
from utils.formatter import Formatter
from lang_data import get_filter_list_by_lang
import re
import json
class QuestSpider(scrapy.Spider):
name = "quest_scraper"
start_urls... |
# General imports
import numpy as np
from torch.nn.functional import softmax
from scipy.stats.mstats import mquantiles
import matplotlib.pyplot as plt
from torchvision.utils import save_image
import pickle
import random
import seaborn as sns
import torch
import sys
import torchvision
from torchvision import transforms,... |
''' Define the Transformer model '''
import torch
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
###################################
#### different attention types ####
###################################
class ScaledDotProductAttention(nn.Module):
''' Scaled Dot-Product Attention '''
... |
#!/usr/bin/env python3
import argparse
import subprocess
def main():
parser = argparse.ArgumentParser()
parser.add_argument('ldd')
parser.add_argument('bin')
args = parser.parse_args()
p, o, _ = subprocess.run([args.ldd, args.bin], stdout=subprocess.PIPE)
assert p == 0
o = o.decode()
... |
# Generated by Django 3.2.3 on 2021-07-03 09:13
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('wanted', '0016_review'),
]
operations = [
migrations.RemoveField(
model_name='quest',
name='tags',
),
... |
import os
from pathlib import Path
def is_root() -> bool:
"""
Checks whether the current user is root (or, on Windows, an administrator).
"""
if os.name == 'nt':
try:
_dummy = list((Path(os.environ.get('SystemRoot', 'C:\\Windows')) / 'Temp').iterdir())
return True
... |
#!/usr/bin/env python3
import sys
import pickle as pk
def print_pickle(pickle_fn):
with open(pickle_fn,'rb') as pkl:
stat=pk.load(pkl)
stat.keys()
print(stat['creation_stats'])
print(f"Output has {len(stat['Random_pokes'])} measurements.")
for pkl in stat['Random_pokes']:
print(f"input size = {pkl['m']:.... |
#coding:utf-8
#
# id: bugs.core_6279
# title: Put options in user management statements in any order
# decription:
# According to new syntax that is described in doc\\sql.extensions\\README.user_management, any statement that
# creates or modifies user, must now ... |
import sys
import typing
def main() -> typing.NoReturn:
n = int(input())
s = [x == 'AND' for x in sys.stdin.read().split()]
cnts = []
cnt = 1
for x in s:
if x:
cnt += 1
continue
cnts.append(cnt)
cnt = 1
cnts.append(cnt)
p = ... |
from django import forms
from PIL import Image
from django.utils.translation import ugettext_lazy as _
from . import models
class CategoryFrom(forms.ModelForm):
'''
Form for item's category
'''
class Meta:
model = models.Category
fields = ['name', ]
def __init__(self, *args, **kw... |
lst1=[['*','*','*','*','1'],['*','*','*','1','2'],['*','*','1','2','3'],['*','1','2','3','4'],['1','2','3','4','5']]
for i in lst1:
print(*i)
|
#!/usr/bin/env python
# coding: utf-8
import os
from PIL import Image
from numpy import *
from pylab import *
def process_image(imagename,resultname,params="--edge-thresh 10 --peak-thresh 5"):
""" Process an image and save the results in a file. """
if imagename[-3:] != 'pgm':
# create a pgm file
... |
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2007 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistribu... |
import sys
import math
import pytest
from sdl2 import endian
class TestSDLEndian(object):
__tags__ = ["sdl"]
def test_SDL_BYTEORDER(self):
if sys.byteorder == "little":
assert endian.SDL_BYTEORDER == endian.SDL_LIL_ENDIAN
else:
assert endian.SDL_BYTEORDER == endian.SDL... |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云(BlueKing) available.
Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may obt... |
#!/usr/bin/python3
# coding=utf8
import sys
import import_path
import kinematics as kinematics
import HiwonderSDK.Board as Board
HWSONAR = None
ik = kinematics.IK()
if sys.version_info.major == 2:
print('Please run this program with python3!')
sys.exit(0)
# Initial position
def initMove():
HWSONAR.setRGB... |
__author__ = 'gpratt'
'''
Created on Jun 21, 2013
@author: gabrielp
'''
import unittest
import tests
from gscripts.clipseq.demux_paired_end import reformat_read, read_has_barcode
class Test(unittest.TestCase):
def test_read_has_barcode(self):
"""
Test hamming distance with hamming of 0
:... |
from ptrlib import *
# 3XPL01717
# _H4CK3R_
sock = Socket("lazy.chal.seccon.jp", 33333)
# login
for i in range(3):
sock.recvline()
sock.sendline("2")
#sock.sendlineafter(": ", "A" * 31)
sock.sendlineafter(": ", "_H4CK3R_")
sock.sendlineafter(": ", "3XPL01717")
# manage
sock.sendline("4")
sock.sendlineafter(": ",... |
import argparse
import pandas as pd
from traffic_counter import TrafficCounter
# source : https://github.com/andresberejnoi/ComputerVision
def CLI():
# Define default values here to make documentation self-updating
minArea_default = 50 # todo 200 A4 300
direction_default = ['H', '0.5']
numCount_default... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.