text stringlengths 3.07k 12.6k |
|---|
from django.shortcuts import render
from . import models as loginmodels
from favorite import models
from django.http import HttpResponseRedirect
from django.shortcuts import redirect
from favorite import models as FavModels
from products import models as Products
from products.forms import NewProductForm, NewProductIma... |
#!python2.7
# !/usr/bin/env python
from __future__ import print_function
import json
import naoqi
import argparse
from flask import Flask, request
from naoVision import NaoVision
from naoActions import NaoPosture, NaoJoints, NaoSpeak, NaoHeadTouch, NaoSpeechRecognition
# The Flask app is the nao_server
nao_server =... |
from utils import mapping_dict
from utils import parse_file
import re
import string
def word_normalize(conversation):
result = list()
for sentence in conversation:
new_sentence = re.sub("tha+nks ", ' thanks ', sentence.lower())
new_sentence = re.sub("Tha+nks ", ' Thanks ', new_sentence.lower()... |
import flask
import random
import string
import json
import time
import functools
import memcache
from flask.ext.sqlalchemy import SQLAlchemy
app = flask.Flask(__name__)
app.config.from_object('config.RunningConfig')
db = SQLAlchemy(app)
mc = memcache.Client(['127.0.0.1:11211'], debug=0)
import model
import games
i... |
from IMLearn.learners.classifiers import *
import numpy as np
from typing import Tuple
import plotly.io as pio
pio.templates.default = "simple_white"
from IMLearn.metrics import *
import plotly.graph_objects as go
from plotly.subplots import make_subplots
from math import atan2, pi
def load_dataset(filename: str) ->... |
from io import open
import argparse
import json
import sys
import os
import re
from pprint import pprint
try:
# Python 3
from configparser import ConfigParser
from io import StringIO
base_string = str
except ImportError:
# Python 2
from ConfigParser import ConfigParser
from StringIO import ... |
# adata.main
''' Main Adata application initialize
'''
from .window.main import *
import flask
import jinja2
class App(Application):
''' The Adata main application is a text console window.
'''
Name = "Adata"
Title = "Adata Automation Framework"
Version = "0.0.1"
WebSite = "http://www.nabla.... |
"""
Copyright 2014 Planet Labs, 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, softwa... |
'''
Copyright (c) 2021, <NAME>
The purpose of this script is to make input data for Triplet Networks out of
provided images. Currently generates triplets randomly, while maintaning the data ratio.
Currently uses low dim images for triplets.
Creates three datasets, for testing purposes, to test the role of randomness... |
import os, sys, time
import glob
import h5py
import argparse
import subprocess
import pickle
import numpy as np
import soundfile as sf
from tqdm import tqdm
from librosa.core import resample
from SRDataGenerator import DataGenerator
def verify_words(words, datadir):
for word in words:
if not os.path.isdir... |
import os
import sys
import time
import io
import numpy as np
from picamera import PiCamera
from picamera.array import PiRGBArray
from dbr import *
import cv2
# you can change the following variables' value to your own value.
license_key = "Input your own license"
json_file = r"Please input your own template path"
re... |
import sys
from sets import Set
import yaml
import json
from SPARQLWrapper import SPARQLWrapper, JSON
from pymongo import MongoClient
import networkx as nx
import numpy as np
client = MongoClient()
db = client.seiyuuData
seiyuuCollection = db.seiyuu
animeCollection = db.anime
def querySPARQLEndpoint(query):
spar... |
#!/usr/bin/env python
#
# Author: <NAME> <<EMAIL>>
#
import time
import ctypes
import tempfile
import numpy
import h5py
from pyscf import lib
from pyscf.lib import logger
from pyscf.cc import ccsd
from pyscf.cc import _ccsd
from pyscf.cc import ccsd_lambda_incore as ccsd_lambda
# t2,l2 as ijab
def kernel(mycc, eris=... |
#!/usr/bin/env python
import math
import json
import Queue
import threading
FRAME_LOCAL_NED = 1
MAV_CMD_CONDITION_YAW = 115
MAV_CMD_DO_SET_ROI = 201
downloaded = False
q = Queue.Queue()
def print_json():
while True:
msg = q.get()
print(json.dumps(msg))
t = threading.Thread(target=print_json,args=())... |
#!/usr/bin/python
# Copyright (c) 2017, 2021 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 d... |
from typing import List
import time
lines: List[int] = []
with open('example.txt', 'r') as file:
for line in file.readlines():
lines.append(int(line))
lines.append(0)
lines.sort()
lines.append(max(lines) + 3)
differences: {int, int} = {1: 0, 2: 0, 3: 0}
diffs: List[int] = []
input: int = 0
output: int ... |
import io
import json
import os
from typing import Any, Dict, IO, Iterator, Tuple
import altair as alt
import pandas as pd
import pytest
from PIL import Image
from selenium.common.exceptions import WebDriverException
from _pytest.monkeypatch import MonkeyPatch
from altair_saver import SeleniumSaver, JavascriptError
f... |
import sublime
import sublime_plugin
import subprocess
import os
import os.path
# Used for output suppression when calling subprocess functions; see
# http://stackoverflow.com/questions/10251391/suppressing-output-in-python-subprocess-call
DEV_NULL = open(os.devnull, 'w')
STARTUP_INFO = None
# Used to prevent a new ... |
import time
import threading
from collections import OrderedDict
from lbryum import commands, wallet, transaction, bip32, network, blockchain, lbrycrd, contacts
from lbryum.constants import TYPE_ADDRESS, TYPE_CLAIM, TYPE_SUPPORT, TYPE_SCRIPT
from test_data import PUBKEY
class MocStore(dict):
def __init__(self):... |
from time import time, sleep
import pandas as pd
import requests
from io import BytesIO
def table_head(df):
return df.head()
class Vizual:
def __init__(self, server_ip='http://0.0.0.0:8080', live_post=False):
sleep(1)
self._ip = server_ip
self._channel_context = ''
self._co... |
#!/usr/bin/env python3
from os import path
from multiprocessing.pool import ThreadPool
import multiprocessing
import os
import signal
import logging
import argparse
from os import path
import subprocess
import re
import glob
import time
import sys
OVERRIDE_FIELDS = ['verifiers', 'memory', 'time-limit', 'skip', 'expec... |
import collections
import json
import time
from threading import Lock, Thread
from websocket import WebSocketApp
from scclient.channel import Channel
from scclient.event_listener import EventListener
class ChannelsRepository(collections.Mapping):
def __init__(self, new_channel_function):
self._channels ... |
import functools
import torch
import torch.nn as nn
import torch.optim as optim
from torch.autograd import grad, Variable
from torch.cuda.amp import autocast, GradScaler
from tqdm import tqdm
from ..StyleGAN2.model import Generator, Discriminator, init_weight_N01
from ..general import YearAnimeFaceDataset, to_loader... |
from __future__ import print_function, division, absolute_import
''' V1.2 Robofont Script for stem weight calculation
based on Family Stem Weight Calculator by <NAME>
this script expects to have 2 fonts open with a reference glyph e.g. n'''
from mojo.tools import IntersectGlyphWithLine
## OPTIONS
s = 9 # Interpolati... |
import os.path
from typing import Tuple, List, Optional, Dict, Union
import dask.dataframe as dd
import pandas as pd
import yaml
def extension_from_path(path: Union[str, List[str]]) -> str:
"""Helper method to get file extension
Parameters
----------
path
A string or a list of strings.
... |
from __future__ import print_function
import math
import numpy as np
import torch
import torchFI as tfi
from torchFI.injection import FI
def loadData(args, dataset_name, normalize_data):
from torchvision import datasets, transforms
data_class = {'CIFAR10':datasets.CIFAR10,
'MNIST':dat... |
import requests
from requests.exceptions import ConnectionError, HTTPError, Timeout, SSLError
import json
import uuid
import sys
import traceback
import time
import logging
import random
import logging
log = logging.getLogger()
log.addHandler(logging.NullHandler())
log.setLevel(logging.DEBUG)
_DEFAULT_CREATE_TIMEOUT... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Interpreter version: brython (http://brython.info) (like python3)
#
# Imports =====================================================================
from browser import html
from browser import alert
from browser import window
from browser import document
from virtual_... |
#!/usr/bin/python3
## author: <EMAIL>
from ._tree_traversers import traverse_pre_order, traverse_in_order
from queue import Queue
from math import inf
def assertEqualTreeTopologies(tree, nodes_in_preorder, nodes_in_inorder):
''' this tree topology comparison works only with tree with unique values '''
actua... |
""" A collection of example tests. """
import warnings
from hypothesis import given
from hypothesis.strategies import permutations
from matching import Player
from matching.algorithms import stable_roommates
from matching.exceptions import NoStableMatchingWarning
from matching.games.stable_roommates import _make_play... |
# -*- coding: utf-8 -*-
# Copyright 2021 Tampere University and VTT Technical Research Centre of Finland
# This software was developed as a part of the ProCemPlus project: https://www.senecc.fi/projects/procemplus
# This source code is licensed under the MIT license. See LICENSE in the repository root directory.
# Auth... |
import torch
import torch.nn as nn
import numpy as np
class FusionLoss(nn.Module):
def __init__(self, w_l1=1., w_mse=1., w_sign=1., w_grad=1., reduction="mean"):
super().__init__()
self.reduction = reduction
self.w_1 = w_l1
self.w_2 = w_mse
self.w_3 = w_sign
self.... |
"""
modelinfo.py
A tool to print summary data about an n88model file.
Copyright (c) 2010-2016, Numerics88 Solutions Ltd.
http://www.numerics88.com/
See LICENSE for details.
"""
from __future__ import division
import sys
from .N88ReportedError import N88ReportedError
def modelinfo():
import os
import argpar... |
#!/usr/bin/python
#
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... |
'''
Copyright 2011 <NAME> <<EMAIL>>
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,... |
import sys
prefix=["es","cs","ss","ds","fs","gs","opsize","adsize","lock","repne","rep","repz"]
def format(f_name):
file=open(f_name)
lines = file.readlines()
data=[]
for line in lines:
data.append(line.split('\t'))
return data
def print_dic(data):
data=dict(sorted(data.items(), key=l... |
import torch.nn.functional as F
import torch
from torch.autograd import Function # import Function to create custom activations
from torch.nn.parameter import Parameter # import Parameter to create custom activations with learnable parameters
from parse_config import ConfigParser
import torch.nn as nn
import pdb
#... |
# -*- coding: utf-8 -*-
import json
from six import add_metaclass
from copy import deepcopy
from importlib import import_module
from flask import current_app
from ldap3 import ObjectDef
from ldap3.core.exceptions import LDAPAttributeError
from ldap3.utils.dn import safe_dn
from ldap3.utils.conv import check_json_dict... |
import numpy as np
import ecqacd
import lcra
def subtiles(npix_rc,n_rc):
'''Return indices of sub-tiles of a tile,
if an image img has size (npixr,npixc),
return an index tuple irlo,irhi,iclo,ichi
such that img[irlo:irhi,iclo:ichi] is a sub-tile of img.
(nr,nc) is the number of rows and columns of... |
import time
import ctypes as ct
import shutil
import os
import glob
import numpy as np
import math
import logging
import glm
import json
import cv2
import utm
import statistics
import random
from PIL import Image
#import png
from pathlib import Path
import sys
import asyncio
import aiohttp
import aiofiles
# to find ... |
"""
Connect to each one of the DBs (3 copies) & create their tables.
It does it for both data_logs and system_logs.
"""
import time
import sqlite3
import sys
sys.path.insert(0, '/root/csdc3/src/sensors')
from sensor_constants import *
sys.path.insert(0, '/root/csdc3/src/logs/config_setup')
from config_setup_cons... |
import dgl
import numpy as np
import random
import torch
import torch.nn.functional as F
from dgl import model_zoo
from dgl.data.chem import PDBBind, RandomSplitter, ScaffoldSplitter, SingleTaskStratifiedSplitter
from dgl.data.utils import Subset
from itertools import accumulate
from scipy.stats import pearsonr
def s... |
import torch
def forward_rate_constants_func(self):
"""Update forward_rate_constants
"""
ln10 = torch.log(torch.Tensor([10.0])).to(self.device)
self.forward_rate_constants = self.Arrhenius_A * \
torch.exp(self.Arrhenius_b * torch.log(self.T) - \
... |
import re
import os
from abc import abstractmethod
from contextlib import contextmanager
from threading import Lock
from typing import Dict, Generator
import docker
from docker.errors import DockerException
from pyjackson.core import Comparable
from pyjackson.decorators import type_field
from pyjackson.utils import g... |
import datetime
import requests
import urllib
from decimal import Decimal
from botocore.exceptions import ClientError
from ..util.formSubmit.emailer import send_confirmation_email
from chalicelib.models import PaymentTrailItem, UpdateTrailItem, PaymentStatusDetailItem, EmailTrailItem, Form, Response
from bson.objectid ... |
import os
import datetime
from typing import Tuple
import msal
import flask
class Oauth2:
"""Oauth2 authorization Code grant flow"""
def __init__(self, app: flask.app.Flask):
self._app = app
# Azure AD app registration info (currently the values are taken from environment variables)
... |
import typing
import datetime
from .utils import try_int
from .enums import ChannelType
class Emoji:
def __init__(self, data: typing.Dict[str, typing.Any]):
self.raw = data.copy()
self.id: int = try_int(data.get('id'))
self.name: str = data.get('name')
class WelcomeChannel:
def __init... |
from ads.models import Ad, Comment, Fav
from ads.owner import OwnerListView, OwnerDetailView, OwnerCreateView, OwnerUpdateView, OwnerDeleteView
from ads.forms import CreateForm, CommentForm
from django.views import View ... |
import time
import logging
from abc import ABCMeta, abstractmethod
from appium.webdriver.webdriver import WebDriver as AppiumDriver
from selenium.webdriver.remote.webdriver import WebDriver as SeleniumDriver
from .sylphsession import SylphSessionConfig
from .wrappers import WebTestWrapper
from .wrappers import Mobile... |
# -- ; {{{1
#
# File : stream_spec.py
# Maintainer : <NAME> <<EMAIL>>
# Date : 2015-03-09
#
# Copyright : Copyright (C) 2015 <NAME>
# Licence : LGPLv3+
#
# -- ; }}}1
import httpon... |
from collections import defaultdict
from datetime import date
from django import forms
from django.contrib import messages
from django.contrib.auth.models import User
from django.db.models import Q, Sum
from django.shortcuts import redirect
from django.utils.translation import ugettext as _
from towel import resource... |
import os
import numpy as np
import pandas as pd
def get_PID(clinical_file, mutation_file, symbol):
clinical_data = pd.read_excel(clinical_file)
with_WES = np.array([clinical_data['Project_ID'][clinical_data['Exome_Seqencing'] == 'YES']])
mutation_data = pd.read_excel(mutation_file)
mutated_I... |
# import pytest
from zyglrox.core.hamiltonians import Hamiltonian, TFI, HeisenbergXXZ
from zyglrox.core.topologies import *
import matplotlib.pyplot as plt
def kagome():
model_graph = graph_kagome_12()
inter = {'zz': model_graph, 'x': dict(zip(range(12), [[[i, ]] for i in range(12)]))}
h = Hamiltonian(to... |
from io import BytesIO
from PIL import Image
from bayescmd.steady_state import RunSteadyState
import os
import distutils
import json
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
from datetime import datetime
import matplotlib as mpl
""" Generate various steady state data sets."""
mpl.rc(... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import time
import argparse
from collections import OrderedDict
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
import torchvision.models as t... |
from django.db.models.fields.files import ImageField
from django.db.models import signals
from django.conf import settings
from django.core.files.storage import FileSystemStorage
from widgets import DelAdminFileWidget
from forms import StdImageFormField
import os, shutil
class ThumbnailField:
'''
Instances of ... |
from typing import Optional
import pytest
from copy import deepcopy
from src.hw4.treap.node import Node
from src.hw4.treap.treap import Treap, _split, _merge
#
# (7, 10)
# / \
# (5, 8) (8, 9)
# / \
... |
# Author: <NAME> Poznan
# Comment: Helper script for validating data created from the simulation
import pickle
import matplotlib.pyplot as plt
import numpy as np
# path = "./data/dataset/final_ds/real/real_train.pickle"
paths = ["./data/dataset/final_ds/real/real_train.pickle",
"./data/dataset/final_ds/real... |
import discord, datetime, time
from discord.ext import commands
import sys
import datetime
import random
import platform
import time
from ago import human
import collections
from discord.ext.commands import bot
import discord.utils
start_time = time.time()
class SPIKE(commands.Cog, name='SPIKE'):
def __init__(se... |
from abc import ABC, abstractmethod
from typing import List
from app import PropertyError
from app.controller.engines import Engine
from app.model.bullet import Bullet
from app.model.character import Trump, Character
from app.model.images import ScreenImages, GameImages
from app.model.navigation import Navigation
from ... |
from pathlib import Path
import numpy as np
import pandas as pd
DATA = Path(__file__).parent.parent / 'datasets'
COARSE_INDEX = (
'0-9', '10-19', '20-29', '30-39', '40-49', '50-59', '60-69',
'70-79', '80+',
)
# Contact matrix information
CONTACT_MATRIX_COUNTRIES = [
'Belgium', 'Finland', 'Germany', 'Grea... |
from tensorflow.python.keras.losses import binary_crossentropy
import tensorflow.python.keras.backend as K
import tensorflow as tf
from config import conf
# METRICS
def dice_coef(y_true, y_pred, smooth=1.):
"""
Dice coefficient only on masks labels:
:param y_true:
:param y_pred:
:param smooth:
... |
from io import BytesIO
import enum
import textwrap
from pathlib import Path
from urllib.request import urlopen
from PIL import Image, ImageDraw, ImageFont
import httpx
import error
class Type(enum.Enum):
UNKNOWN = None
YES = True
NO = False
class MemeGenerator:
def __init__(self):
resource ... |
import numpy as np
import open3d as o3d
# ---------------------------------------------------------------------------- #
# Convert in opne3d
# ---------------------------------------------------------------------------- #
def merge_mesh(meshes):
# Merge without color and normal
vertices = np.zeros((0, 3))
... |
#!/usr/bin/env python
# coding: utf-8
import torch
import torch.nn.functional as F
from torch import Tensor
from typing import Callable, Optional
from torch.nn.modules.loss import _Loss
class MarginCalibratedCELoss(_Loss):
r"""This criterion computes the cross entropy loss between input and target.
It is us... |
# import some common libraries
import numpy as np
import torch
import matplotlib.pyplot as plt
import os, json, cv2, random, sys, traceback
import multiprocessing as mp
import pickle as pkl
from tqdm import tqdm
import pdb
from profilehooks import profile
def fix_randomness(seed=0):
np.random.seed(seed=seed)
... |
import pandas as pd
import category_encoders as ce
#FUNCTION TO GET BUSINESSES IN SAME CATEGORIES AND SAME STATE (OUTPUT TO BE USED IN V1 OF GET COMPETITORS FUNCTION)
# The DF input needs the business_id column to be the index; df = set_index('business_id)
# this function will be used by the next function.
def g... |
"""Belinsky PhraseFinder nlp worker."""
import subprocess
import sys
from dataclasses import dataclass
import typing as t
import spacy
from spacy_langdetect import LanguageDetector
from ..utils import UnknownLanguageError
@dataclass(slots=True, frozen=True)
class Token:
"""Word token structure."""
word: st... |
import numpy as np
import mne
from scipy.signal import butter, sosfiltfilt
from scipy.spatial import cKDTree
from pebm.ebm.FiducialPoints import FiducialPoints
from pebm._ErrorHandler import _check_shape_, WrongParameter
class Preprocessing:
def __init__(self, signal: np.array, fs: int):
"""
... |
import numpy as np
import tensorflow as tf
def running_avg(avg, new, update_rate=0.1):
if avg is None:
avg = new
else:
avg = (1 - update_rate) * avg + update_rate * new
return avg
class Agent(object):
def __init__(self, sess, pred_net, target_net, experience,
eps=0.... |
import requests
from data.models import Player, Champion, PlayerChampionMastery
from datetime import datetime,timedelta
from data.helper import *
import sys
import environ
env = environ.Env()
RIOT_API_KEY = env.str('MASTERY_KEY')
REGION = "na"
def get_masters(region):
REGION = region
print("getting challengers... |
import numpy as np
import pandas as pd
class RegressionTree:
def __init__(self, col_names):
self.train_data, self.test_data = RegressionTree.get_data(col_names)
full_data = pd.concat([self.train_data, self.test_data])
self.train_data, self.test_data = RegressionTree.normalize(full_data, l... |
#!/usr/bin/env python3
"""Generate the mapping of dtype to xknx class."""
import logging
import sys
from typing import Dict, List
from xknx import dpt
from . import DST_DIR, LOGGER
DTYPE_MATCHER_PATH = DST_DIR / "dtype_matcher.py"
def get_mapping() -> Dict[str, str]:
"""Map all existing xknx dpt classes agai... |
# coding=utf-8
"""
This is a slightly unusual 'collector'. It collects and uploads stats to a
app engine instance run by <NAME>. The stats collected are:
* Per collector enabled or not
* Per collector interval time
* Global collector reload interval
* Global handlers
* Any custom collector set stats
These stat... |
"""DataManager manages the shared memory"""
import os
from typing import List, Dict
from multiprocessing.shared_memory import SharedMemory
from multiprocessing.managers import SharedMemoryManager
from importlib import import_module
import numpy as np
import pandas as pd
from frds.typing import TableID, SharedMemoryInf... |
import os
from typing import Callable
import csbuilder
from hks_pylib.done import Done
from hks_pylib.hksenum import HKSEnum
from csbuilder.scheme import Scheme
from csbuilder.scheme.result import SchemeResult
from csbuilder.cspacket.cspacket import CSPacket
from sft.file import FileReader
from sft.protocol import D... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from cmiputil import convoc
import unittest
from pathlib import Path
import os
class test_ConVoc(unittest.TestCase):
def setUp(self):
self.cvpath_test = (
'.:./non-existent-path/:'
'$HOME:$HOME/non-existent-path')
self.cvlist_... |
import numpy as np
from overrides import overrides
from env import Node
from planners.rrtPlanner import RRTPlanner
from utils import planner_registry
# noinspection PyAttributeOutsideInit
class BiRRTPlanner(RRTPlanner):
r"""The bidrectional RRT* planner, or sometimes it's also referred to as the
*RRT-Connect... |
"""
Script for thresholding GraphMCF instances according to its properties
Input: - File with a GraphMCF (.pkl)
Output: - Output view (interactive window or .pdf file)
"""
__author__ = '<NAME>'
# ################ Package import
import sys
import time
import getopt
from pyseg.globals import *
from p... |
from abc import ABCMeta, abstractmethod
from deeppavlov.core.common.chainer import Chainer
from gensim.models import Doc2Vec
from itertools import groupby
from lru import LRU
from methodtools import lru_cache
import nltk
import numpy as np
from typing import Any, Callable, List, Tuple
class Stat:
def ... |
"""Command line tool for encrypting/decrypting Splunk passwords"""
from __future__ import print_function
import argparse
import base64
import getpass
import itertools
import os
import pcrypt
import six
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryp... |
"""This file implements functionality that is shared among all plotting scripts."""
from warnings import warn
import matplotlib as mpl
import numpy as np
from matplotlib import pyplot as plt
from utils_shared import get_case_label
def get_config_title(config):
"""Turn configuration into a title (for a matplotli... |
import sys
sys.path.append("..")
import numpy as np
from utils.utils import get_h
# Konstanter for indeksering
x = 0
y = 1
z = 2
# Informasjon om håndtaket
M_1 = 8.0 * np.pi * 6.7 # g
L_1 = 8.0 # centimeter
R_1 = 1.0 # centimeter
# Informasjon om sylinderen festet på håndtaket
M_2 = 4.0 * np.pi * 6.7 # kg
L_2 =... |
# coding=utf-8
# Copyright 2021 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed ... |
# [파이썬 크롤러 만들기](https://jione-e.tistory.com/28)
# [Source Code for Package lxml.html](https://lxml.de/api/lxml.html-pysrc.html)
import os, sys
import json
import time
import re
import requests
import lxml.html as etree
import lxml.etree as et
sys.path.append('../_public') ## Note: 현재 디렉토리 기준 상대 경로 설정
from scrap_requ... |
from sklearn.model_selection import train_test_split
import argparse
import jsonlines
import json
import pandas as pd
from collections import Counter
import random
parser = argparse.ArgumentParser()
parser.add_argument('--dataset', type=str, default='climate-fever-dataset-r1.jsonl')
parser.add_argument('--pool_size', ... |
"""Load dispatches from plain text files with TOML dispatch configuration.
"""
import copy
import pathlib
import collections
import json
import logging
import toml
from nsdu import info
from nsdu import exceptions
from nsdu import loader_api
from nsdu import utils
DEFAULT_ID_STORE_FILENAME = 'dispatch_id.json'
DEFAU... |
import pandas as pd
import pkg_resources
from . import models
from warnings import warn
def load_test_data(name='vaccinium', phenophase='all'):
"""Pre-loaded phenology data
Datasets are available with the package. They include multiple phenophases
and associated daily mean temperature data derived from t... |
# gc9a01_dial_knob.py -- Demonstrate round LCD as a gauge, controlled by a pot knob
#
# 2021 - <NAME> - to<EMAIL>
#
# Tested on QTPy RP2040, ItsyBitsy M4,
# Raspberry Pi Pico (RP2040) running CircuitPython 7
#
# You'll need to install 'adafruit_display_text', 'adafruit_imageload'
# and 'gc9a01' library.
# Easiest way t... |
import json
import random
import time
import redis
from redis.exceptions import LockError
from redis.lock import LuaLock as lock
from pybloom.src import BloomFilterException
from pybloom.src.backends import SharedBackend
def retry(retries, exceptions, max_retry_wait=30):
skip = retries == 0
retries = 1 if r... |
from flask import Flask, request, g, render_template, redirect, session, flash
from flask_sqlalchemy import SQLAlchemy
from werkzeug.utils import secure_filename
import hashlib
import os, sys
from database import DB
from datetime import timedelta
app = Flask(__name__, template_folder='templates')
app.config['SQLALCHE... |
# encoding:utf-8
from collections import Iterable
class C():
def __init__(self, *args):
if len(args) == 1 and isinstance(args[0], int):
self.r = self.g = self.b = self.__check(args[0])
elif len(args) == 1 and isinstance(args[0], Iterable):
self.r = self.__check(args[0][0])
self.g = self.__check(args[0][1... |
#
# Copyright 2019 Xilinx 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 writi... |
from distutils.core import setup
import os, sys, cv2, tempfile, pytesseract, tika, re, requests, urllib.parse,uuid
from flask import Flask, render_template, request,jsonify
from PIL import Image
from pdf2image import convert_from_path
from tika import parser
import constants
# Credentials are stored on the local envir... |
import gym
from keras.optimizers import Adam
import traceback
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '../'))
from src.r2d3 import R2D3
from src.rainbow import Rainbow
from src.callbacks import Logger2Stage, ModelIntervalCheckpoint, MovieLogger, ConvLayerView
from src.r2d3_callba... |
import curses
import socket
import struct
import threading
from manager.base import (
CONNECT_MAGIC,
CONNECTION_TYPE_STATUS,
PACKAGE_TYPE_RESPONSE,
PACKAGE_TYPE_STATUS,
connection_timeout,
host,
port,
)
from manager.command import CommandManager
from manager.commands import BashCommand
from... |
# Copyright 2016 VMware, 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 a... |
import asyncio
import typing
from datetime import datetime
from functools import cached_property, lru_cache
from hashlib import sha256
from typing import Hashable
from cryptography.fernet import Fernet, InvalidToken
from fastapi import Request, Response
from .encryptors import AES_SIV_Encryptor
from .exceptions impor... |
##############################################################################
#
# Copyright (c) 2007 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SO... |
from tqdm import tqdm
import pickle as pkl
import numpy as np
np.random.seed(124)
import torch
import torch.nn as nn
torch.manual_seed(124)
from torch.utils.data import DataLoader
from .extractor import MFCCVadCMVNPadBatch as PadBatch
from sklearn.metrics import accuracy_score
def compile_adv(model, loss_functio... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.