text stringlengths 3.07k 12.6k |
|---|
from Actions import *
from MathFunc import puck_angle
from Constants import *
from model.ActionType import *
def go_def(move, me, game, x, y, const: WorldConstants):
safe_move(move, me, game, x, y, 1)
push_opp = 0
for h in const.world.hockeyists:
if not h.teammate and\
me.get_distance_... |
# Copyright 2014 Mirantis, 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 or agreed to in writing... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import hashlib
import json
import os
import random
import signal
import time
import urllib.parse as url_parse
from http.server import HTTPServer, BaseHTTPRequestHandler
from socketserver import ThreadingMixIn
try:
from PIL import Image
except ImportError:
print("Plea... |
import torch
import torch.nn.functional as F
import numpy as np
from advbias.augmentor.adv_bias import AdvBias
"""
Create a 3d bspline kernel matrix
"""
def bspline_kernel_3d(sigma=[1, 1, 1], order=2, asTensor=False, dtype=torch.float32, device='gpu'):
kernel_ones = torch.ones(1, 1, *sigma)
kernel = ke... |
#!/usr/local/bin/env python3.7
# -*- coding: utf-8; py-indent-offset:4 -*-
###############################################################################
#
# The MIT License (MIT)
# Copyright (c) 2020 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and ass... |
import pygame
import app.Views.Checkers as Checkers
def open_menu_screen(game):
window = game.get_window()
window.get_window().fill((0, 0, 0))
pygame.init()
title_font = pygame.font.Font(None, 100)
menu_font = pygame.font.Font(None, 50)
draw_text(title_font, "Checkers", window, ((window.get_dim... |
#!/usr/bin/env python3
from datetime import datetime
import random
import re
import sys
class MineSweeperGame():
"""
Minesweeper Game
"""
def __init__(self, *args):
"""
initializes MineSweeper game solver
"""
self.init_vals_and_verify_game_inputs(args[0])
def tokeni... |
# -*- coding: utf-8 -*-
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
### Alias : PosServer.network.application & Last Modded : 2021.11.07. ###
Coded with Python 3.10 Grammar by IRACK000
* <์์ฉ ๊ณ์ธต>
* ๋ฐ์ดํฐ ๊ฐ๊ณต ๋งค์๋ ํธ์ถ.
* qr ์์ ํ
์ด๋ธ ๋ฒํธ ๋ฐ๊ธฐ -> ๋ก๊ทธ์ธ ์์ฒญ -> ํ
์ด๋ธ ๋ฒํธ์ ๋ํด ๋น๋ฐ ๋ฒํธ ๋ฑ๋ก ์ฌ๋ถ ํ์ธ
* send to server ... |
''' a one-line description of the city'''
import random
from utilities import format_text, get_latin
def slogan(data):
''' describe the cup tea is drunk from '''
options = [
urban_garden,
wow_old,
beacon_of,
beacon_of,
regional_gem,
regional_gem,
activity... |
# Provides basic mapping for all physical keyboard keys using logical, though possibly verbose, Rule phrases
# Also supports all holdable modifier key combinations for use as keyboard-based shortcuts
# This, combined with other scripts, is my replacement for the Voice Commands in std.py
from talon.voice import Word, C... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Created : 2021/08/23 6:20 ์คํ
# @Author : <NAME>
# @Site :
# @File : plot_utils.py
# @Software : PyCharm
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from torchvision.utils import make_grid
import cv2
def plot_3channel():
... |
#!/usr/bin/env python
from __future__ import print_function
import sys, finalexam
import linersock.test_helpers
from linersock import Host, Server, Client
from linersock.test_helpers import Message, Inbox, Outbox
wrapper_suite = finalexam.Suite("Testing the socket wrappers...")
class Token (object):
def __init... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author: houzhiwei
# time: 2019/9/14
from owlready2 import *
import json
from JSON2OWL.OwlConvert.OwlUtils import OWLUtils
from JSON2OWL.OwlConvert.Preprocessor import Preprocessor
module_uri = 'http://www.egc.org/ont/process/gdal'
onto = get_ontology(module_uri)
onto, s... |
"""
gurgle base objects
"""
from functools import wraps
import numpy as np
from sklearn.base import TransformerMixin, BaseEstimator
from sklearn.exceptions import NotFittedError
# TODO: Make identity_func "identifiable". If we use the following one,
# we can use == to detect it's use,
# TODO: ... but there may be ... |
'''
Main processor for v2 of the collocation between CALIOP and Himawari-8.
'''
import os
import sys
import traceback
from datetime import datetime
from pyhdf.SD import SD, SDC
def log_w_message(message):
dt_now = datetime.now().strftime("%d/%m/%Y %H:%M:%S.%f")
dt_message = f'{dt_now} - {message}'
print(... |
import re
import boto3
from django.conf import settings
from base.exceptions import DoesNotExist
from fields import AVAILABLE_FIELDS, AVAILABLE_KEY_FIELDS
# Get the service resource.
dynamodb = boto3.resource(
'dynamodb',
region_name=settings.AWS_REGION_NAME,
aws_access_key_id=settings.AWS_ACCESS_KEY_ID... |
from dict_riv import generate_riv
from dict_riv import RIV
import re
import functools
import itertools
import random
from decimal import getcontext
getcontext().prec = 8
DEF_SENTENCE_PATTERN = re.compile(r"\.\s+")
DEF_WORD_PATTERN = re.compile(r"\s+")
def similarity(riva, rivb):
mag = riva.magnitude() * rivb.ma... |
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import numpy as np
import tensorflow as tf
import tensorflow.keras as keras
import pandas as pd
import itertools
import time
import argparse
from models import bciDecoder
# functions
def r_square(pred:np.ndarray, true:np.ndarray) -> np.ndarray:
ss_tot = np.sum((t... |
from __future__ import print_function, division, absolute_import
from collections import OrderedDict
import numpy as np
from typing import List, Union, Tuple
from time import time
import collections
try:
from itertools import izip_longest
except Exception:
from itertools import zip_longest as izip_longest
def ... |
from __future__ import absolute_import
import numpy as np
from keras import backend as K
from keras.layers import Layer
from keras import initializers, regularizers, constraints
def _softmax(x, dim):
"""Computes softmax along a specified dim. Keras currently lacks this feature.
"""
if K.backend() == 'te... |
#!/usr/bin/env python
# Copyright 2013, <NAME>, <NAME> CNRS
from numpy import eye
from dynamic_graph import plug
from dynamic_graph.sot.core.feature_generic import FeatureGeneric
from dynamic_graph.sot.core.joint_limitator import JointLimitator
from dynamic_graph.sot.core.matrix_util import matrixToTuple
from dynami... |
#! /usr/bin/env python3
# encoding: utf-8
# <<BEGIN-copyright>>
# Copyright 2021, Lawrence Livermore National Security, LLC.
# See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: BSD-3-Clause
# <<END-copyright>>
"""
test fudge/covariances/
dbrown, 12/5/2012
"""
import unittest, os
from fudge.... |
"""
264. Ugly Number II
Medium
An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5.
Given an integer n, return the nth ugly number.
Example 1:
Input: n = 10
Output: 12
Explanation: [1, 2, 3, 4, 5, 6, 8, 9, 10, 12] is the sequence of the first 10 ugly numbers.
Example 2:
Input: n... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os, sys
import win32security
import pywintypes
import winerror
from winsys import constants, core, exc, utils, accounts
from winsys._security.core import REVISION
from winsys._security import _aces
__all__ = ['x_acl', 'ACL', 'DACL', 'SACL', 'acl... |
# -*- coding: utf-8 -*-
'''
@author: <NAME>
@email: <EMAIL>
@date: Jan. 28th 2021
'''
import random
import numpy as np
np.set_printoptions(suppress=True)
class MSolver(object):
'''
Matrix solver to find the solution
'''
def __init__(self):
super(MSolver, self).__init__()
def parse_... |
import numpy as np
import pandas as pd
from mm_utils import oneHot, read_genome
from models import pearson
from mm_gen import GenScan
from tensorflow.keras.models import load_model
import argparse
import re
import tensorflow.keras.backend as K
import tensorflow as tf
def user_input():
parser = argparse.ArgumentPa... |
import numpy as np
import pandas as pd
def get_best_param_dist(model_dict):
"""Computes mean and variance of the best fit params accross different runs
Args:
model_dict (dict): Dict containing the predictions dict for all the runs for a given
scenario, config setting
Returns:
... |
import os
import argparse
from os import environ
from pathlib import Path
# Orders of saved paths are consistent with paths.txt.
PROJECT_DIR = os.path.dirname(os.path.abspath(__file__))
def register():
parser = argparse.ArgumentParser("advanced cd manipulator")
parser.add_argument('num', nargs='?', default=... |
import pandas as pd
from sqlalchemy import create_engine
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.orm.session import Session
from tqdm.notebook import tqdm
import datetime as dt
from couchers.config import config
from couchers.db import session_scope
from couchers.models import (
Cluster,
C... |
"""
This module has the routines and data structures necessary to allow one to
generate visualizations of a atomic systems.
"""
class VSimVisualizer():
def __init__(self, filename, xsize=600, ysize=600):
from gi.repository import v_sim, GLib, Gtk
self.win = v_sim.UiRenderingWindow.new(xsize, ysiz... |
import tensorflow as tf
k= int(tf.__version__.split('.')[0])
if k >=2:
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
import tensornets as nets
import cv2
import numpy as np
import time
import argparse
import sys
from create_folder import createFolder
tf.disable_v2_behavior()
class YoloObjectDe... |
import sqlite3
import dash
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
import numpy as np
import pandas as pd
from dash.dependencies import Input, Output
from components import card, tweet
from utils import human_format, get_color_from_score
from pathl... |
import pandas as pd
num_words = 8000 # number of words we consider as features
maxlen = 20 # length of each message
# The dataset we use is known as "SMS Spam Collection v.1" (https://www.dt.fee.unicamp.br/~tiago/smsspamcollection/)
# and is a public set composed by 5,574 English, real and non-enconded messages, ta... |
import math
import hydrostats.data
import pandas as pd
import numpy as np
__all__ = ['compute_daily_average', 'compute_daily_variance', 'compute_monthly_average', 'compute_return_periods',
'compute_anomaly', 'compute_daily_statistics', 'compute_low_return_periods']
def gumbel1(rp: int, xbar: float, std: ... |
from django.shortcuts import render
# Create your views here.
from .serializers import UserRegSerializer, SmsSerializer, UserDetailSerializer, LogSerializer, EmailSerializer, \
UserUpdateSerializer
from .models import UserProfile, VerifyCode, UserLoginLog
from rest_framework import mixins, generics, permissions
... |
from __future__ import unicode_literals
from operator import itemgetter
import os
from django import forms
from django.conf import settings
from django.contrib.auth import get_user_model
from django.db import models
from django.utils.translation import ugettext_lazy as _
from .classes import Filter, Package
from .mo... |
#!/usr/bin/env python3
# Copyright (c) 2020 <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, mod... |
from .utils import rmdir, run, cleanup
from slurm.files import rm, mkdir, find
import os # make directories, change current dir, etc
import shutil # move and delete files/folders
from collections import OrderedDict # put toc in alphebetical order
from glob import glob # get contents of folder
... |
#!/usr/bin/env python3
import os
import time
import re
import subprocess
RE_LICENSE = r"(.*?\n?\r?)[/#;-]?[/#;-]\sCopyright .* The Defold Foundation.*specific language governing permissions and limitations under the License.(.*)"
YEAR = str(time.localtime().tm_year)
LICENSE = ('''Copyright 2020-%s The Defold Foundati... |
"""Support Home Assistant entities to be used as PlayerControl for Music Assistant."""
from functools import partial
from typing import Any, Dict, List
from homeassistant.components.input_boolean import DOMAIN as INPUT_BOOLEAN_DOMAIN
from homeassistant.components.media_player.const import (
ATTR_INPUT_SOURCE,
... |
"""
Caching of blob data.
(This test is adapted from ZEO/tests/zeo_blob_cache.test in ZODB3.)
We support 2 modes for providing clients access to blob data:
shared
Blob data are shared via a network file system. The client shares
a common blob directory with the server.
non-shared
Blob data are loaded f... |
#!/usr/bin/env python36
from termcolor import colored
from pathlib import Path
import contextlib, docker, io, os, plac, sys, tarfile
__version__ = '0.1'
IMAGE_DIST_LABEL = 'ddb-image-dist'
IMAGE_VER_LABEL = 'ddb-version'
DDB_VER = '0'
ROOT = Path(__file__).parent.absolute()
def note(s): return colored(s, 'cyan... |
# -*- coding: utf-8 -*-
"""
detect
~~~~~~
Code for automatically detecting a transliteration scheme.
:license: MIT and BSD
Example usage:
::
from indic_transliteration import detect
detect.detect('pitRRIn') == Scheme.ITRANS
detect.detect('pitRRn') == Scheme.HK
When handling a Sanskrit ... |
import enum
import numpy as np
class EnvType(enum.Enum):
Normal = 0
Joint_Malfunction = 1
Wind = 2
Velocity = 3
Joint_Malfunction_Drift = 4
Wind_Drift = 5
Velocity_Drift = 6
class SimType(enum.Enum):
HalfCheetah = {"action_dim": 6, "observation_dim": 17}
Hopper = {"action_dim": 0... |
import datetime
import sqlparse
from redash.query_runner import (
NotSupported,
register,
BaseSQLQueryRunner,
TYPE_STRING,
TYPE_BOOLEAN,
TYPE_DATE,
TYPE_DATETIME,
TYPE_INTEGER,
TYPE_FLOAT,
)
from redash.utils import json_dumps, json_loads
from redash import __version__
try:
impo... |
from electronics_abstract_parts import *
@abstract_block
class UsbConnector(Connector):
"""USB connector of any generation / type."""
USB2_VOLTAGE_RANGE = (4.75, 5.25)*Volt
USB2_CURRENT_LIMITS = (0, 0.5)*Amp
class UsbAReceptacle(UsbConnector, FootprintBlock):
def __init__(self) -> None:
super().__init__... |
import imp
import logging
import os
import re
from datetime import datetime
logger = logging.getLogger(__name__)
class MigrationFile(object):
PATTERN = '^(?P<id>[0-9]+)_[a-z0-9_]+\.py$'
def __init__(self, id, filename):
self.id = int(id)
self.filename = filename
def __str__(self):
... |
import pyworld as pw
import torch
import torchaudio
import soundfile as sf
import numpy as np
import math
import argparse
import pickle
import os
from scipy.interpolate import interp1d
import matplotlib.pyplot as plt
def readWavFileList(listFileName,data_path_prefix):
fileList = list()
f = open(listFileName,... |
"""Views module for model reviews."""
from typing import List, Optional
from django.http import HttpResponseRedirect
from django.utils.translation import gettext_lazy as _
from django.views import View
from django.views.generic import DetailView, FormView
from django.views.generic.base import TemplateView
from django.... |
import RPi.GPIO as GPIO
import time
import argparse
import sys
import atexit
class Motor():
def __init__(self, motor_id, direction_pin, step_pin, enable_pin, switch_pin,
max_angle, rewind_angle, debug=False):
self.motor_id = motor_id
self.direction_pin = direction_pin
self... |
__author__ = 'elubin'
import abc
import logging
import subprocess
import tempfile
import os
from utils.utils import rm_rf, list_all_files_and_folders, generate_regexp
from include import RESULTS_LOGGER
class FilesystemDiffTool(object):
__metaclass__ = abc.ABCMeta
def __enter__(self):
return self
... |
import os
import logging
import ArgoQueries
import MongoQueries
import PJsonQueries
from bench_utils import TestSuite
from Settings import (
RESULTS_FILENAME,
DATA_SIZE,
NUM_BENCH_ITERATIONS,
)
logging.basicConfig(level=logging.INFO)
log = logging.getLogger(__name__)
###
# Wipe out JSON Documents generat... |
from collections import namedtuple
import random
from typing import List
from objects import AreaManager
import numpy as np
import torch
from torch import nn
from torch import optim
import torch.nn.functional as F
random.seed(1234)
np.random.seed(1234)
torch.manual_seed(1234)
torch.cuda.manual_seed_all(1234)
torch.b... |
#!/usr/bin/env python3
import numpy as np
import math
import matplotlib.pyplot as plt
import heapq
from pprint import pprint
class Node(object):
def __init__(self, x, y, cost):
self.x = x
self.y = y
self.cost = cost
self.rhs = math.inf
self.g = math.inf
def __repr__(s... |
import asyncio
import pickle
import codecs
import socket
import zmq
import zmq.asyncio
from zmq.auth.asyncio import AsyncioAuthenticator
class Context:
def __init__(self, global_whitelist=None, global_pubkeys_dir=None):
self._auth = AsyncioAuthenticator()
self._callbacks = {}
self._dicts =... |
import csv
import datetime
import os
import string
import random
import time
import json
import pandas as pd
import requests
from flask import (
Blueprint, flash, Flask, g, redirect, render_template, request, url_for, jsonify, Response, make_response
)
from werkzeug.contrib.securecookie import SecureCookie
fro... |
from .decoration import login_wrapper
import datetime
import os
import uuid
from .. import home
from flask import render_template, request, flash, session
from app.utils import db_helper
def check_upload():
"""
ๅคๆญไปๅคฉ็ไปฃ็ ๆฏๅฆไธไผ
:return:
"""
ctime = datetime.date.today() # ๅฝๅๆฅๆ
data = db_helper.fe... |
# pylint: disable=invalid-name
# Softmax example in TF using the classical Iris dataset
# Download iris.data from https://archive.ics.uci.edu/ml/datasets/Iris
import os
import tensorflow as tf
DATA_FILE = "data/IrisDataSet.csv"
LOG_FILE = "logs/p3_iris"
DEBUG = True
sess = tf.InteractiveSession()
def combine_inpu... |
import os
from typing import Tuple
from d3m import cli
from submission.utils import check_pipeline_run_was_successful, gzip_file
from submission import config
from submission.problems import ProblemReference
def run_pipeline(
pipeline_path: str,
problem: ProblemReference,
output_dir: str,
output_nam... |
from typing import Tuple, List
import torch
import torch.nn as nn
import torch.nn.functional as F
from .pytorch_modules import SharedMLP
from .pu_utils import square_distance, index_points, farthest_point_sample, \
QueryAndGroup, GroupAll
class _PointnetSAModuleBase(nn.Module):
def __init__(self):
... |
# coding: utf-8
# # Travelling Salesman Problem
#
# This is an homework of Artificial inteligence.
#
# The homework is to code the travelling salesman problem using genetic algorithm.
#
# Group:
# - <NAME>
#
# Id: 1510081
#
# **Homework by Professor <NAME>**
#
#
#
# ### Definitions and auxiliar variables
# ... |
from typing import Optional, Union, List
from swift_cloud_py.common.errors import SafetyViolation
from swift_cloud_py.entities.intersection.intersection import Intersection
from swift_cloud_py.entities.control_output.fixed_time_schedule import FixedTimeSchedule
from swift_cloud_py.entities.intersection.sg_relations im... |
#!/usr/bin/env python
#-*- coding:utf-8 -*-
##
## dlist.py
##
## Created on: Feb 2, 2021
## Author: <NAME>
## E-mail: <EMAIL>
##
# imported modules
#==============================================================================
import collections
#
#========================================================... |
'''
Created: 2020.06.24
@license: CC0 https://creativecommons.org/publicdomain/zero/1.0
@author: hm
'''
# coding=utf8
import json
import urllib3
import base.Logger
class HttpClient:
'''Implements a HTTP or HTTPS client.
'''
def __init__(self, logger, timeout=10):
'''Constructor.
@param ... |
# warning nothing works as expected
# temp commit
import _setup
import scipy.stats
import math
import numpy as np
from sklearn.covariance import ShrunkCovariance
from sklearn.covariance import LedoitWolf
from sklearn.covariance import OAS
import sir
import world
from simulator import Simulator, State
"""
param_list ... |
#!/usr/bin/env python
import copy
import logging
import optparse
import os
import sys
import time
from multiprocessing import Process, Lock, Queue, Condition
from pnr_read import read_pnr
from pnr_parse import parse_pnr
from pnr_telegram import make_telegram
# from pnr_csv import make_csv
from pnr_types import *
... |
from functools import total_ordering
import json
import os
from random import SystemRandom
import shutil
from uuid import UUID
from ethereum.slogging import get_logger
from ethereum.tools import keys
from ethereum.utils import privtopub
from ethereum.utils import sha3, is_string, encode_hex, checksum_encode, to_string,... |
# Copyright 2018-2021 Xanadu Quantum Technologies 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 applicabl... |
from __future__ import division
from __future__ import print_function
import argparse
import collections
import datetime
import itertools
import os.path
import time
from scipy.stats import entropy
BK_ENTROPY_CUTOFF = 2.5
LFM_ENTROPY_CUTOFF = 3.0
MIN_OCCURRENCES = 10
MIN_VALID_SEQ_LEN = 3
MAX_VALID_SEQ_LEN = 500
... |
# Copyright (c) 2022 PaddlePaddle 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 appli... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from nasws.rnn.darts_policy.genotypes import PRIMITIVES, Genotype
from torch.autograd import Variable
from nasws.rnn.darts_policy.darts_model import DARTSCell, RNNModel
class DARTSCellSearch(DARTSCell):
def __init__(self, ninp, nhid, dropouth, dr... |
import json
import logging
import os
import pickle
import shutil
import sys
from copy import deepcopy
from multiprocessing.dummy import Pool
from pathlib import Path
from typing import Callable, Dict, List, Optional, Tuple, Union, cast
import cv2
import numpy as np
import pandas as pd
from decord import VideoReader, c... |
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 11 19:05:02 2020
@author: O_Mazur
"""
#libs
import pandas as pd
import numpy as np
import sys
#functions
"""
function: save_result
params:
- file_name with tsv format
- pandas DF
returns: status(int) 0 - success, 1 - failure
"""
def save_result(file_pat... |
# Copyright (c) 2020 AllSeeingEyeTolledEweSew
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
# REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERC... |
"""
Bootstrap's user's development environment by creating cloud resources required by SAM CLI
"""
import logging
from collections.abc import Collection
from typing import cast, Dict, List, Optional, Union
import boto3
import click
from botocore.config import Config
from botocore.exceptions import ClientError, BotoCor... |
"""
Copyright (c) 2018 Intel Corporation
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 writin... |
import os
import sys
import pytest
import numpy as np
from subprocess import Popen
from scipy.spatial import distance_matrix
from autode import Molecule
from molfunc.molfunc import main
from molfunc import (print_combined_molecule,
print_all_combined_molecules,
fragment_names)
... |
# =============================================================================
#
# EZID :: ezidapp/models/store_group.py
#
# Database model for groups in the store database.
#
# Author:
# <NAME> <<EMAIL>>
#
# License:
# Copyright (c) 2016, Regents of the University of California
# http://creativecommons.org/lice... |
def fill_nall_with_mode(x):
return x.fillna(x.mode(dropna=False)[0])
def fill_nall_with_median(x):
return x.fillna(x.median())
def cleaning(df):
###########################################
#Fill missing values
###########################################
#For WheelTypeID we have applied a recu... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
from sklearn.naive_bayes import GaussianNB
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score, precision_score, recall_score
DROP_METRICS = ['class_Runtime Rules',
'interface_Runtime Rule... |
import openpyxl
import os
import datetime
import subprocess
import json
import shelve
import requests
import math
import random
today = str(datetime.date.today())
os.chdir("your_working_directory")
backup_i = shelve.open('backup_' + today + '_i')
output_file_path = 'your_excel_filepath'
output_file = openpyxl.load_wo... |
#!/usr/bin/env python3
from collections import OrderedDict
import re
import glob
from PIL import Image
import os
import shutil
import math
nbits = None
imw = None
imh = None
imbits = None
def load_jed(fn):
"""
JEDEC file generated by 1410/84 from PALCE20V8H-15 06/28/20 22:42:11*
DM AMD*
DD PALCE20V8H... |
import json
import random
import re
import string
import time
from django.db import models
from hackerspace.git import add_issue
from hackerspace.notify import notify
# define what to do when an error occures, on the website (backend) or in one of the cronjobs
def getErrorName(error_log):
# get error name
... |
import random
import math
import pareto
from itertools import compress
from bs4 import BeautifulSoup
from shapely.geometry import Polygon, LineString
from shapely.affinity import translate
from shapely.geometry.point import Point
from simpleai.search.local import genetic
try:
import importlib.resources as pkg_... |
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
class Conv1DBuilder(object):
@staticmethod
def build(
in_channels,
out_channels,
kernel_size,
stride=1,
padding=0,
use_kaiming_normal=False,
):
conv = nn.Conv1d(
in_... |
import re
from torch.utils.data import (DataLoader, RandomSampler, SequentialSampler, TensorDataset)
from keras.preprocessing.sequence import pad_sequences
from sklearn.metrics import confusion_matrix, roc_curve, precision_recall_fscore_support
import matplotlib.pyplot as plt
import re
import numpy as np
import torc... |
# script with function to prepare and support evaluation
import glob
import yaml
import pandas as pd
import os
# load simulation results and calculate RTT
# network and algorithm name are used to filter the results
def sim_delays(network, algorithm):
sim_results = glob.glob('../eval/{}/{}/{}*.yaml'.format(network... |
"""
Created on Sat Dec 5 21:39:37 2020
@author: T.Nishiyama
"""
import numpy as np
import matplotlib.pyplot as plt
#Definitions of parameters.
sigma=0.5*np.log(3)
v=0.5*np.log(0.75)/sigma
s=0.5*np.log(3)/sigma
alpha=4.5*s**2-sigma*(3*s-v)
beta=2*s**2
def collatz(n):
count=0
while (n > 1):
... |
import logging
import os
import re
import tempfile
import zipfile
from typing import List, Optional
import yara # type: ignore
from karton.core import Config, Karton, Task # type: ignore
from .__version__ import __version__
log = logging.getLogger(__name__)
def normalize_rule_name(match: str) -> str:
"""Malp... |
from axis_fifo import AXIS_FIFO
from devices import fifo_devices
from axi_gpio import AXI_GPIO
from devices import gpio_devices
from dac81416 import DAC81416
import struct
import soft_trigger
import reset_all
from getSeqGPIOWords import getSeqGPIOWords
class GPIO_seq_point:
def __init__(self, address, time, outpu... |
# -*- coding: utf-8 -*-
"""
@Time ๏ผ 2022/1/11 14:28
@Auth ๏ผ ๅไผๅบท
@File ๏ผDiag_oscillgraph_circleconfig.py
"""
import numpy as np
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtCore import QAbstractItemModel, QModelIndex
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QColor
class CircleConfigTableM... |
import os
import sys
sys.path.append(os.getcwd())
import time
import numpy as np
from torch import nn
from torch.nn import functional as F
from psypose.MEVA.meva.khrylib.models.mlp import MLP
from psypose.MEVA.meva.khrylib.models.rnn import RNN
from psypose.MEVA.meva.khrylib.utils.torch import *
from psypose.MEVA.me... |
import io
import csv
import string
import logging
from banal import as_bool, ensure_dict, is_mapping, is_listish
from normality import stringify
from flask import Response, request, render_template
from flask_babel import gettext
from werkzeug.urls import url_parse
from werkzeug.exceptions import Forbidden
from werkzeu... |
"""Test a 2 module sequence on a short video of cars
1) object detector
2) make-model classifier after filtering only for car detections
TEST WHERE THERE IS NO PREV PROPERTIES OF INTEREST
"""
import os
import sys
import json
import glog as log
import requests
import boto3
import zipfile
from multivitamin.applicat... |
#!/usr/bin/env python
""" MultiQC som.py plugin module """
from __future__ import print_function
from collections import OrderedDict, defaultdict
import logging
import os
import re
from multiqc import config
from multiqc.plots import table
from multiqc.modules.base_module import BaseMultiqcModule
# Initialise the m... |
import hashlib
import os
from django.shortcuts import render, redirect
from django.contrib import messages, auth
from django.contrib.auth.decorators import login_required
from django.core.files.storage import FileSystemStorage
from users.forms import RegistrationForm, TeamRegistrationForm
from users.models import Fil... |
# Storage Package
# Released under MIT License
# Copyright (c) 2020 TytusDb Team
# Developers: SG#16
from .handler import Handler
from ..path import *
class Database:
def __init__(self, name, mode, encoding):
self.name = str(name)
self.mode = mode
self.encoding = encoding
self.tab... |
from __future__ import division
import random
import numpy as np
from PIL import Image
import torchvision.transforms as transforms
from . import co_transforms
def has_file_allowed_extension(filename, extensions):
"""Checks if a file is an allowed extension.
Args:
filename (string): pa... |
# From https://github.com/The-OpenROAD-Project/OpenROAD-flow-scripts
# The OpenROAD-flow repository (build and run scripts) has a BSD 3-Clause License with its text below.
# The flow relies on several tools, platforms and designs that each have their own licenses.
#
# The license below applies ***only*** to the build... |
import os
import time
import random
import copy
import multiprocessing as mp
import numpy as np
from .world import World
from .qlearn import QLearn
from .cell import CasualCell
from .environment import Environment
class Agent:
def __setattr__(self, key, val):
if key == 'cell':
# transfer the... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.