text stringlengths 3.07k 12.6k |
|---|
import datetime as dt
import json
import logging
import os
import shutil
from typing import Any, Dict, List, Optional, Tuple, Union
import pandas as pd
from extra_model._adjectives import adjective_info
from extra_model._aspects import generate_aspects
from extra_model._filter import filter
from extra_model._summariz... |
# Copyright 2018 BLEMUNDSBURY AI LIMITED
#
# 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 ... |
import os
import typing
from stringcase import camelcase, snakecase
import click
from dictdiffer import diff
from swagger_spec_validator import validator20, SwaggerValidationError
from .model import SpecDir, Path, Operation, Definition, create_spec_dict
from .utils import file_path_to_dict, str_to_dict
from .walker i... |
import logging
import asyncio
import weakref
import functools
L = logging.getLogger(__name__)
class PubSub(object):
def __init__(self, app):
self.Subscribers = {}
self.Loop = app.Loop
def subscribe(self, message_type, callback):
"""
Subscribe a subscriber to the an message type.
It could be even pla... |
# -*- coding: utf-8 -*-
#
# Copyright (c) 2015, Alcatel-Lucent Inc
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# no... |
import numpy as np
from methods_project_old import MaximumIterationError
from robot_arm import RobotArm
def test_point_outside_outer_circle(lengths, n, plot_initial=True, plot_minimizer=True, animate=False):
print('---- Test with destination outside configuration space ----')
analytical_tests('ooc', lengths, n... |
#
# -*- coding: utf-8 -*-
#
# Copyright © 2013 <NAME> <<EMAIL>>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, ... |
import argparse
import os
import re
import yaml
_ENV_EXPAND = {}
def nested_set(dic, keys, value, existed=False):
for key in keys[:-1]:
dic = dic[key]
if existed:
if keys[-1] not in dic:
raise RuntimeError('{} does not exist in the dict'.format(keys[-1]))
value = type(dic[... |
import random
from matplotlib import pyplot as plt
from algorithms import crossover_mutation
import main
# from src.wall import Wall
from model import rooms
from view.gui import GFX
from algorithms.neuralnet import *
from model.robot import Robot
NUM_THREADS = 4
# NUM_THREADS = 1 # Set to 1 to disable multiprocessi... |
#!/usr/bin/python
from subprocess import check_output, call, CalledProcessError
from re import split as regx_split
import argparse
def main():
args = process_args()
output = check_output(['git', 'status', '--porcelain', '-uno'])
filelist = output.split('\n')
for staged_file in filelist:
if stag... |
#! /usr/bin/python3
import SnnBase
import Stdp
import DopamineStdp
import random
class TogglePulsar:
def __init__(self, magnitude, frequency):
self.magnitude = magnitude
self.frequency = frequency # not used after construction at present
self.delay = 1.0 / frequency
self.remainin... |
"""
Cyberpunk Configuration Module
"""
import os
from typing import Optional
class CyberpunkConfigException(Exception):
pass
class CyberpunkConfig:
"""Global configuration object for Cyberpunk"""
def __init__(
self,
audio_path: str = "local",
local_storage_base_dir: Optional[st... |
import torch
import pickle
import gzip
from torchtext import data
from slt.signjoey.model import build_model
from slt.signjoey.batch import Batch
from slt.signjoey.data import make_data_iter
from slt.signjoey.vocabulary import PAD_TOKEN
from slt.signjoey.dataset import SignTranslationDataset
from slt.signjoey.phoenix_... |
# Copyright 2020 Huawei Technologies Co., Ltd
#
# 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... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import logging
import torch
import torch.nn as nn
BN_MOMENTUM = 0.1
logger = logging.getLogger(__name__)
def conv3x3(in_planes, out_planes, stride=1):
"""3x3 convolution wit... |
# -*- encoding: utf-8 -*-
'''
Copyright 2016 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 "l... |
import re
# FIXME: depends on builtin_signed
######## COMMON API ##########
E_INTEGER = 'INT'
E_STRING = 'STR'
E_BIN_RAW = 'RAW'
E_BLOCK = 'BLK'
E_BUILTIN_FUNC = 'BUILTIN'
E_NEEDS_WORK = 'NEEDS_WORK'
def e_needs_work(length=None):
return {'len': length, 'final': False, 'type':E_NEEDS_WORK, 'data': None}
... |
#!/usr/bin/env python3
import os
import re
import cv2
import keras
import numpy as np
import pandas as pd
DATA_PATH = 'cage/images/'
LEFT_PATH = 'data/left.h5'
RIGHT_PATH = 'data/right.h5'
NUM_PATH = 'data/numbers.csv'
DataSet = (np.ndarray, np.ndarray, np.ndarray)
def extract() -> (list, list):
l_data, r_data... |
import random
import h5py
import numpy as np
import torch
import torch.utils.data as udata
import glob
import os
from PIL import Image
import torchvision.transforms as transforms
# import torch.nn.functional as F
def normalize():
return transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
def norm(data, max_v... |
import discord
import os
import json
import datetime
import asyncio
import time
import traceback
import sys
from discord.ext import commands
cwd = os.path.dirname(__file__)
jsonPath = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "config2.json")
config = json.loads(open(jsonPath, "r").read())
roleD... |
#!/usr/bin/env python3
import http.cookiejar
import requests.utils
from mylib.easy import *
from mylib.easy import fstk
class Constants:
netscape_http_cookie_file_header_string = '# Netscape HTTP Cookie File'
class UserAgentExamples:
"""https://www.networkinghowtos.com/howto/common-user-agent-list/"""
... |
"""
train_model.py
Description: code used to train neural network over UrbanSound8k processed data.
Takes three arguments: --epochs (int > 0)
Ex: python train_model.py --epochs 5
"""
#######################################
# Import modules
from data_utils import *
import copy
import argparse
import os
from glob im... |
#
# Work in progress: Backend interface for salami
#
from __future__ import print_function
# Prefix for screen output
prefix = "salami_gambit:"
# # This will run when this backend is first loaded, i.e. during GAMBIT startup
# print(prefix, "Starting up...")
import salami
KPREDS = {}
SLHA = None
#
# Import SLHA con... |
import numpy as np
import os
import cv2
class VideoStartOrEndOutOfBoundsException(RuntimeError):
'''Invalid start or end location in VideoFile'''
class VideoNotFoundException(RuntimeError):
'''Raise when local video file could not be found'''
class VideoCouldNotBeOpenedException(RuntimeError):
'''Raise wh... |
#!/usr/bin/env python
# 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
# "L... |
# Copyright (c) 2020 freedesktop-sdk
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, dis... |
import pandas as pd
from tqdm import tqdm
tqdm.pandas()
import os
import glob
import json
import sys
import gzip
from helpers import create_folder_path, write_csv_file, write_list_to_txt, save_pk_file
def read_jsonl_file( file_name, columns):
"""
Read jsonl file and create a data frame of the requi... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
PLOTTREE - Plot a phylogenetic tree with just a single line of code.
Usage: plottree TREE [options]
positional arguments:
TREE A tree in NEWCIK format file or string (surrounded by
double quotes).
optional arguments:
-h, ... |
# -*- coding: utf-8 -*-
#
# Helper functions for frontend test design
#
# The runner signatures take a callable,
# the `method_call`, as 1st argument
#
# 3rd party imports
import itertools
import numpy as np
from syncopy.shared.errors import SPYValueError, SPYTypeError
# fix random generators
np.random.seed(40203)
... |
import requests
from . import scrape_leafly as sl
from bs4 import BeautifulSoup as bs
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
import re
from fake_useragent import UserAgent
import multiprocessing as mp
import os
import time
import pickle as pk
ua = ... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import re
import subprocess
import sys
from pathlib import Path
from dateutil.parser import parse
DIRNAME = Path(__file__).parent.absolute()
PATTERN = "::error file={},line={}::{}"
rc = 0
def log_error(file, line, message):
global rc
print(PATTERN.format(file.rel... |
#_*_ coding: UTF-8 _*_
from flask import request, redirect, render_template
from application import app
import datetime
import wtforms
import logging
import db
import data_models
import renderers
import properties
import views
import custom_fields
from role_types import RoleType
import urls
from . import grants
from... |
# @author lucasmiranda42
# encoding: utf-8
# module deepof
"""
Testing module for deepof.train_utils
"""
import os
import numpy as np
import tensorflow as tf
from hypothesis import HealthCheck
from hypothesis import given
from hypothesis import settings
from hypothesis import strategies as st
from hypothesis.extra... |
import os
import re
re_class = re.compile((
r'class\s+(\w+)(?:\s*<[\w\.,\s]+>)?'
r'(?:\s+implements\s+(?:[\w\.]+)(?:\s*<[\w\.,\s]+>)?)*'
r'(?:\s+extends\s+([\w\.]+)(?:\s*<[\w\.,\s]+>)?)?'
r'(?:\s+implements\s+(?:[\w\.]+)(?:\s*<[\w\.,\s]+>)?)*'
), re.M)
re_comments = re.compile(
r'(//[^\n\r]*?[\... |
"""
Exsiting machine example.
Uses DND_Harry_CentosVM (10.51.152.238)
"""
import json
from calm.dsl.builtins import ref, basic_cred, action
from calm.dsl.builtins import CalmTask, CalmVariable
from calm.dsl.builtins import Service, Package, Substrate
from calm.dsl.builtins import Deployment, Profile, Blueprint
from c... |
"""Prepares and verifies specific fcs text section parameters to be used in
data extraction.
Required FCS primary TEXT segment keywords:
$BEGINANALYSIS $BEGINDATA $BEGINSTEXT $BYTEORD $DATATYPE $ENDANALYSIS $ENDDATA
$ENDSTEXT $MODE $NEXTDATA $PAR $TOT $PnB $PnE $PnN $PnR
"""
from collections import namedtuple
import... |
# -*- coding: utf-8 -*-
import errno
import logging
import io
import itertools
import nfc
import os
import threading
import time
from config import Config
from .record import BalanceRecord, HistoryRecord
FELICA_SERVICE_BALANCE = 0x008b
FELICA_SERVICE_HISTORY = 0x090f
FELICA_SERVICE_IN_OUT = 0x108f
BUFFER_SIZE = 1024
... |
from itertools import cycle
import pygame as pg
from .. import prepare, tools
import string
LOADED_FONTS = {}
BUTTON_DEFAULTS = {"call" : None,
"args" : None,
"call_on_up" : True,
"font" : None,
... |
# Copyright (c) 2018, 2019 Oracle and/or its affiliates.
# This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Apache License v2.0
# See LICENSE.TXT for details.
from nose... |
#------------------------------------------------------------------------------
# Create side by side trajectories on video frame and sat image
#------------------------------------------------------------------------------
#------------------------------------------------------------------------------
# Settings and... |
import numpy as np
import tensorflow as tf
from patchy_san import *
from progress.bar import IncrementalBar
import sys
# Default parameters
C1 = 152
SMALL_EMBEDDING_SIZE = 30
FINAL_EMBEDDING_SIZE = 25
def make_network(params = parameters_PS):
"""
Makes a network taking as input the Patchy-San transformation d... |
'''
Job request creation and manipulation library for the Voxel51 Platform API.
| Copyright 2017-2019, Voxel51, Inc.
| `voxel51.com <https://voxel51.com/>`_
|
'''
# pragma pylint: disable=redefined-builtin
# pragma pylint: disable=unused-wildcard-import
# pragma pylint: disable=wildcard-import
from __future__ import a... |
import scipy.io as sio
from pathlib import Path
import numpy as np
import pyqtgraph as pg
from pyqtgraph.Qt import QtGui
mask = np.array([np.ones(32), np.ones(32), np.ones(32),np.concatenate((np.zeros(14), np.ones(18))),
np.concatenate((np.zeros(14), np.ones(18))),
np.concat... |
#!/usr/bin/env python
import sys
import rospy
import rosbag
from scipy.interpolate import interp1d
import matplotlib
import matplotlib.pylab as plt
matplotlib.rcParams['mathtext.fontset'] = 'custom'
matplotlib.rcParams['mathtext.rm'] = 'Bitstream Vera Sans'
matplotlib.rcParams['mathtext.it'] = 'Bitstream Vera Sans:i... |
# -*- coding: utf-8 -*-
"""
"""
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
dtype = torch.float
class RNN(nn.Module):
def __init__(self, input_size, hidden_size, num_layers, device=torch.device("cpu")):
super(RNN, self).__init__()... |
#!/usr/bin/env python3
#
# Copyright (c) 2021 @marbocub <<EMAIL>>
# Released under the MIT license
#
import os, pathlib, hashlib, time, sys, re
from typing import Callable, List, Tuple
import dotenv
from database import FileBase, File, Dir, DatabaseInterface, DatabasePostgreSQL
#-------------------------... |
# -*- coding: utf-8 -*-
#
# spacegame.py
#
# Copyright (C) 2014 <NAME> <<EMAIL>>
#
# Based partially on PyGletSpace.py
# Copyright (C) 2007 <NAME> <<EMAIL>>
# http://www.learningpython.com
#
# SpaceGame is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public Lic... |
#!/usr/bin/env python3
import datetime
import glob
import json
import multiprocessing
import os
import requests
import sys
import tempfile
# Describes whether or not existing files will be overwritten
OVERWRITE = True
# How many threads to use to download GTFS feeds in parallel (use 1 for no
# multiprocessing)
THREA... |
"""Views for generating reports."""
from django.contrib.auth import get_user_model
from django.db.models import Count, Sum, Q
from django.http import HttpResponse
from django.views.generic import ListView
from pure_pagination import PaginationMixin
from tablib import Dataset
from open_connect.accounts.views import Sup... |
import numpy as np
from evtol import eVTOL
import matplotlib.pyplot as plt
# OTHER STUFF STORED HERE FOR NOW
def unique(list1):
# initialize a null list
unique_list = []
unique_indices = []
# traverse for all elements
i = 0
for x in list1:
# check if exists in unique_list or not
... |
import exifread
import os
import uuid
from PIL import Image
from photomanager.lib.pmconst import SUPPORT_EXTS, SKIP_LIST, PATH_SEP
from photomanager.lib.helper import get_file_md5, get_timestamp_from_str
from photomanager.utils.logger import logger
class ImageInfo:
def __init__(self, filename):
self.fil... |
"""Run >> python -m spacy download en << to obtain the English collection of spacy."""
from nltk.corpus import stopwords
from nltk.stem import SnowballStemmer
from autocorrect import spell
from lib.utils.contractions import *
from lib.utils.timer import Timer
import unidecode
import spacy
from spacy_langdetect import ... |
"""Module extending :class:`discopy.biclosed.Diagram` with a functor into
:class:`discopy.cartesian.Function` categories
"""
from discopy.biclosed import Box, Diagram, Functor
from discopy.cartesian import Function
from discopy.cat import Arrow
from discopy.rigid import PRO
from . import unification
class CallableBo... |
import json
from libsaas import http, parsers
from libsaas.services import base
from . import (applications, application_hosts, application_instances,
key_transactions, servers, alert_policies,
notification_channels, users, plugins, components)
class NewRelic(base.Resource):
"""
... |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# Copyright (c) Megvii, Inc. and its affiliates.
import itertools
from typing import Optional
import numpy as np
import math
import paddle.distributed as dist
from paddle.io import Sampler, BatchSampler
class DistributedBatchSampler(BatchSampler):
def __init__(self,... |
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE file in the project root for
# full license information.
import time
import base64
import sys
sys.path.insert(0, "..")
import asyncio
from azure.iot.device.aio import IoTHubModuleClient
from azure.iot.device import MethodRespo... |
import numpy as np
import sympy as sp
from scipy.misc import derivative
from prettytable import PrettyTable
import math
from math import *
def nuevosValoresa(ecua, derivadas, Ecuaciones, variables,var):
valor_ini = []
func_numerica = []
derv_numerica = []
funcs = vars(math)
for i in range(0, Ecuac... |
import os.path as osp
import mmcv
import math
from copy import deepcopy
from mmcv.runner import Hook
from mmcv.runner.dist_utils import master_only, get_dist_info
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from mmcv.runner.checkpoint import save_checkpoint, load_checkpoint
class EvalHo... |
# -- encoding: utf-8 --
"""
Turns audio files (whatever you can throw at ffmpeg)
into video files with a cover image.
"""
from __future__ import with_statement, print_function
import argparse
import json
import os
import subprocess
import sys
NEED_SHELL = (sys.platform == "win32")
FFMPEG_PATH = os.environ.get("FFMPEG_... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import random
import numpy as np
import torch
from torch import nn
from typing import Dict
def mem2str(num_bytes):
assert num_bytes >= 0
if num_bytes >= 2 ** 30: # GB
val = float(num_bytes) / (2 ** 30)
result = "%.3f GB"... |
import numpy as np
import torch.nn as nn
from torch.nn.modules.loss import _Loss
from torch.optim.optimizer import Optimizer
import torch.optim as optim
class ProgressBar(object):
def __init__(self,
max_iter: int = 1,
verbose: int = 1,
bar_nums: int = 20,
... |
"""
MIT License
Copyright (c) 2022 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distri... |
# -*- coding: utf-8 -*-
"""
renoir.parsing.stack
--------------------
Provides stack helpers for templates parsing.
:copyright: 2014 <NAME>
:license: BSD-3-Clause
"""
import uuid
from collections import namedtuple
from pathlib import Path
from .contents import Content, Elements, Node, NodeGroup... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import sys
from collections import OrderedDict
from django_excel_tools import exceptions
from django_excel_tools.fields import (
BooleanField, CharField, IntegerField, DateField,
DateTimeField
)
from django_excel_tools.utils import error_trans
try:
... |
"""
The "device statuses" component.
"""
import asyncio
import logging
import os
import json
from datetime import timedelta
from homeassistant.config import load_yaml_config_file
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.entity_component import EntityComponent
from homeassistant.core ... |
import os
import re
import bpy
import logging
import json
from . import bpy_helper
from . import ifc_helper
from . import io
from . import exporter
def create(project, ifc_type=None, group_name='', prefix='', **kwargs):
i = 0
if ifc_type:
for elem in ifc_helper.elements_by_type(project, ifc_type):
... |
__version__ = "1.1.1"
#Import standard elements
import re
import os
import sys
import warnings
import traceback
import threading
import subprocess
# #Import communication elements for talking to other devices such as printers, the internet, a raspberry pi, etc.
import usb
import types
import bisect
import select
impo... |
# -*- coding: utf-8 -*-
"""
* Created by PyCharm.
* Project: restaurant-menu
* Author name: <NAME>
* Author login: pma007
* File: webserver_restaurants
* Date: 2/4/16
* Time: 10:46
* To change this template use File | Settings | File Templates.
"""
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
i... |
"""
``utils`` module with utility parsing functions.
"""
__all__ = [
'split_msg',
'get_newline_type',
'get_headers',
'parse_status_line',
'parse_request_line',
'parse_header_line',
]
import collections
import re
from . import constants, errors
SplitMessage = collections.named... |
"""Views for the irodsbackend app"""
import logging
from django.conf import settings
from django.http import JsonResponse
from rest_framework.exceptions import NotAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from sodar.users.auth import fallback_to_auth_basic
... |
"""Uses Mk4py, aka metakit.
Python bindings are native-compiled: http://equi4.com/metakit/python.html
"""
from __future__ import print_function, absolute_import
import Mk4py
import numpy as np
import os
import struct
import zlib
from argparse import ArgumentParser
from construct import (
Struct, Int64ul, Array, Con... |
# mypy: ignore-errors
"""
This file implements the distillator to distill the information of the provided dataset in the
weights of a neural network.
"""
import itertools
import math
from typing import Optional, Union
from rlo import analytics
from rlo.dataset import PolicyNetDataset, StateValueDataset
from rlo.tf_mod... |
"""
.. module:: magneticSensor
:synopsis: Magnetic sensor reader
.. moduleauthor:: <NAME> <<EMAIL>>
Data reader for Arduino controlled magnetic field sensor
"""
__author__ = '<NAME>'
import time
import numpy as np
from serial.serialutil import SerialException
from labtools.log import create_logger
from labtools... |
import subprocess, re, sys,os, os.path, shutil, time, glob
ROOT="/home/blackie/dump/KDABViewer"
BUILDROOT=ROOT+"/build"
ITERATIONS=5
FOREAL=1
CCACHE="/usr/lib/ccache"
def runCommand(cmd):
print(" ".join(cmd))
if FOREAL:
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
... |
"""
This example schedules a large number of dynamic tasks and then runs them (in multiple processes)
as a way to gauge the total throughput of Pyncette for a particular backend.
To run this example, configure the selected backend in the Pyncette constructor, then run populate the database.
python examples/benchm... |
"""Implementation of sequence subpackage"""
__all__ = [
"AbstractSequence",
"TrivialSequence",
"FiniteSequence",
"OrderedLoopingSequence",
"ShuffledLoopingSequence",
"WithPeek",
]
from collections.abc import Iterable, Iterator
from abc import abstractmethod
import random
from nextsong.sample ... |
from matrixLibrary import Matrix
import random, copy
from car import Car
from NeuralNetwork import NeuralNetwork
from parameters import *
def crossover(MatA, MatB):
childA = Matrix(MatA.rows,MatA.cols)
childB = Matrix(MatA.rows,MatA.cols)
childA.matrix = copy.deepcopy(MatB.matrix)
childB.matrix... |
# -*- coding: utf-8 -*-
"""
Main class for wrangling data.
One single method for to manage the files.
:copyright: © 2020 Associazione Codice Viola
:license: Apache2, see LICENSE for more details.
"""
import pandas
PREPOSITIONS = [
"il",
"lo",
"la",
"i",
"gli",
"le",
"di",
"del",
"... |
import json
import random
import click
import tensorflow as tf
from noisemaker.util import save, load
import noisemaker.constants as constants
import noisemaker.effects as effects
import noisemaker.generators as generators
import noisemaker.presets as presets
import noisemaker.recipes as recipes
SMALL_X = 512
SMALL... |
import pandas as pd
import numpy as np
import plotly.graph_objects as go
import plotly.io as pio
import os
import math
np.set_printoptions(precision=3, suppress=False)
if not os.path.exists("Slike"):
os.mkdir("Slike")
def line_fit(x, k, l):
return k*x + l
def rolling_median(mase, br_dana):
br_mj = int(l... |
import os.path as osp
from data_generator.object_detection_2d_data_generator import DataGenerator
from data_generator.data_augmentation_chain_constant_input_size import DataAugmentationConstantInputSize
from ssd_encoder_decoder.ssd_input_encoder import SSDInputEncoder
from bounding_box_utils.bounding_box_utils import c... |
import sys
import hashlib
import os.path as path
from PIL import Image, ImageFont, ImageDraw, ImageColor, ImageFilter
from random import choice, randint
def md5(s:str):
h = hashlib.md5()
h.update(s.encode(encoding='utf-8'))
return h.hexdigest()
DEFAULT_FILENAME = 'default.png'
class Generator(object):
... |
import os
import numpy as np
from glob import glob
import skimage.measure as meas
from skimage.util import pad
import xml.etree.ElementTree as ET
from skimage import draw
from class_data import options, BaseData
mapping_dict = {
"TCGA-55-1594": "lung",
"TCGA-69-7760": "lung",
"TCGA-69-A59K": "lung",
... |
#!/usr/bin/env python
"""
Copyright (c) 2020-End_Of_Life
See the file 'LICENSE' for copying permission
"""
# import standard library required
import argparse
import sys
# import tool required
from route.route import route
from route.execute import execute
from chemsynth.chemsynth import Chemsynth, Chem... |
import random
import math
# A window is a list of any 4 consecutive positions in the board (horizontal, vertical, diagonal(+ve and -ve))
# red is 1
# yellow is 2
ROWS = 6
COLS = 7
EMPTY = 0
PLAYER_PIECE = 1
AI_PIECE = 2
LENGTH = 4
def is_valid_column(board, col):
""" Check if a piece can be dropped in that co... |
import torch
from torch import nn, Tensor
from typing import Iterable, Dict
from sentence_transformers import SentenceTransformer, util
from torch.nn.modules import loss
from .. import InputExample
import numpy as np
import torch.nn.functional as F
from BertBase.SentenceTransfo.Supervised.utils_colbert import *
d... |
import sys
from django.urls import reverse
from django.utils.functional import cached_property
from django.utils.html import strip_tags
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from selenium.webdriver.remote.webelement import WebElement
DATA = {
'da... |
import numpy as np
import scipy.sparse as sp
import warnings
#import pdb
# Matrix-vector product wrapper
# A is a numpy 2d array or matrix, or a scipy matrix or sparse matrix.
# x is a numpy vector only.
# Compute A.dot(x) if t is False,
# A.transpose().dot(x) otherwise.
def mult(A, x, t=False):
if sp.isspa... |
#!/usr/bin/python3.5
#coding: utf-8
#EXEMPLO PARA EXECUTAR O ARQUIVO -- ./elimin_Gauss.py 1 entrada4.txt
#1 - Significa que ele pega do arquivo
#2 - Recebe por meio de INPUTS
import sys
class CorDeFundo(object):
vermelho = '\033[41m'
verde = '\033[42m'
azul = '\033[44m'
ciano = '\033[46m'
magenta ... |
'''
Compute classification metrics for the preference learning models. Plot the predictions.
Created on 21 Oct 2016
@author: simpson
'''
import logging
import numpy as np
from matplotlib import pyplot as plt
from sklearn.metrics import f1_score, roc_auc_score, log_loss, accuracy_score
from scipy.stats import kendallt... |
import base64
import random
import string
from itertools import compress
import yaml
from loguru import logger
from .git_database import create_commit, create_ref, get_contents, get_ref
from .github_api import create_pr, find_existing_pr
from .http_requests import get_request
from .parse_image_tags import get_image_t... |
from tkinter import Tk, Label, Button, StringVar, Entry, BooleanVar, \
Checkbutton, E, W, END, TclError, messagebox
import genpw
genpw.TEXFRIENDLY = False
genpw.RECURSIVE = True
fenstarr = []
def fkt(event=None):
global t1, myfont, mycolor, v1, v2, v3, v4
try:
if v1.get() == v2.get() == v3.get(... |
"""Module about the selector element."""
import enum
import numpy as np
from .element import ElementId, Element
@enum.unique
class Symmetry(enum.Enum):
"""List the available kind of symmetry."""
SYMMETRY_NONE = enum.auto()
SYMMETRY_X = enum.auto()
SYMMETRY_Y = enum.auto()
SYMMETRY_XY = enum.auto... |
# Copyright 2021 The Forte 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 applicable ... |
import io
import os
import re
import time
import gevent
from gevent import monkey
monkey.patch_all()
import requests
#网站自带的函数封装了一个类,改变了一下保存路径,发现一个bug:zipfile没有open属性
class Pdf2TableAPI:
def invoke_api(self, api, filename, company_name, file_name_without_pdf):
# 异步执行
output_format = 'zip' # or json... |
import argparse
import json
from typing import Any, cast, Dict
from ..lib import api, args as _args, errors, reporting, utils, workflows as _workflows
from ..lib.parsing import parse_workflow_inputs
async def call(args: Dict[str, Any], cromwell: api.CromwellAPI) -> None:
"""Execute the subcommand.
Args:
... |
"""" A crawler for the data-science-jobs.com website. """
from logging import getLogger
from scrapy.spiders import Rule, CrawlSpider
from scrapy.linkextractors import LinkExtractor
from joby.items import JobLoader, Job
from joby.utilities import Parser
log = getLogger(__name__)
class DataScienceJobsSpider(CrawlSp... |
# System libs
import os
import argparse
from distutils.version import LooseVersion
# Numerical libs
import numpy as np
import torch
import torch.nn as nn
from scipy.io import loadmat
import csv
# Our data
from dataset import TestDataset
from models import ModelBuilder, SegmentationModule
from utils import colorEncode, ... |
'''
排序算法汇总:
bucket sort 桶排序
插入排序 insertion:
1. insertion sort 直接插入排序 stable
2. shell sort 希尔排序/分组插入排序 unstable
选择排序 selection:
1. selection sort 简单选择排序 unstable
2. heap sort 堆排序 unstable
交换排序 swap:
1. bubble sort 冒泡排序 stable
2. quick sort 快排 unstable
归并排序 merge sort
快速排序 quick sort
'''
def bucket_sort(nums):
... |
# (c) 2021 Amazon Web Services, Inc. or its affiliates. All Rights Reserved.
# This AWS Content is provided subject to the terms of the AWS Customer Agreement available at
# https://aws.amazon.com/agreement/ or other written agreement between Customer
# and Amazon Web Services, Inc.
"""Key Action Handler.
This module... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.