text stringlengths 3.07k 12.6k |
|---|
import torch
try:
from torch.utils.tensorboard import SummaryWriter
except ImportError:
from tensorboardX import SummaryWriter
from transformers import (
RobertaConfig,
BertPreTrainedModel,
ROBERTA_PRETRAINED_MODEL_ARCHIVE_MAP,
RobertaModel
)
from transformers.modeling_roberta import (
ROB... |
# Copyright (c) 2013, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
def execute(filters=None):
columns, data = [], []
columns=get_columns()
data=get_data(filters,columns)
return columns, ... |
from __future__ import print_function
import peri.util
import peri.models
import peri.states
import peri.comp.comp
from peri.fft import fft, fftkwargs, fftnorm
from peri.comp.comp import GlobalScalar
from peri.opt import optimize as opt
import numpy as np
import matplotlib.pyplot as pl
class GaussianDiscModel(peri.... |
# Copyright 2018 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
# Adapted from
# https://github.com/lace/lace/blob/a19d14eeca37a66af442c5a73c3934987d2d7d9a/lace/intersection.py
# https://github.com/lace/lace/blob/a19d14eeca37a66af442c5a73c3934987d2d7d9a/lace/test_intersection.py
# By Body Labs & Metabolize, BSD License
import numpy as np
from polliwog import Polyline
from scipy.sp... |
import os
import fabric.api as fab_api
import fabric.contrib.files as fab_files
import fabric.exceptions as fab_exceptions
import fabric.state
import fabric.network
import logging
from io import BytesIO
from . import utils, threadbare
THREADBARE = 'threadbare'
FABRIC = 'fabric'
#DEFAULT_BACKEND = THREADBARE
DEFAULT_B... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Introduction builder."""
from pathlib import Path
import pickle
from abc import ABC
from base64 import b64decode, b64encode
from typing import Any, Callable, Dict, List
from jinja2 import Template
from rich import box
from rich import print as bprint
from rich.align im... |
import pandas as pd
import yaml
import warnings
import json
from metDataModel.core import EmpiricalCompound
def read_metadata_file(input_file_path):
'''
Read a metadata YAML file.
Input
=====
the input file path
An example of a qualified YAML file
======================
ion_relations... |
# _core/_affine/test_base.py
"""Tests for rom_operator_inference._core._affine._base."""
import pytest
import numpy as np
from scipy import linalg as la
import rom_operator_inference as opinf
from .. import _get_data, _get_operators
# Affine operator (public) ====================================================
cl... |
#!/usr/bin/python3
import argparse
import urllib.request
import html5lib
import json
# satisfy ST
if 0:
FileNotFoundError = None
MTGS_URL = "http://www.mtgsalvation.com/spoilers/filter?SetID=%d&Page=0&IncludeUnconfirmed=false&CardsPerRequest=1000"
ICONS = {
"chaos": "C",
"mana-colorless-00": "0",
"mana-colorless... |
import re
import unicodedata
contractions = {
r"(?<![\w.])no(s)?(?![$\w])": r"em o\g<1>",
r"(?<![\w.])na(s)?(?![$\w])": r"em a\g<1>",
r"(?<![\w.])da(s)?(?![$\w])": r"de a\g<1>",
r"(?<![\w.])do(s)?(?![$\w])": r"de o\g<1>",
r"(?<![\w.])ao(s)?(?![$\w])": r"a o\g<1>",
r"(?<![\w.])à(s)?(?![$\w])": r... |
# -*- coding: utf-8 -*-
"""
Histogram Property
==================
"""
# %% IMPORTS
# Package imports
from matplotlib import rcParams
from qtpy import QtCore as QC
# GuiPy imports
from guipy import layouts as GL, widgets as GW
from guipy.plugins.figure.widgets.types.props import BasePlotProp
from guipy.plugins.figu... |
# -*- coding: utf-8 -*-
"""Models that used in more than one place.
"""
from typing import Optional, Mapping, Iterator
from pydantic import BaseModel
from omoide import domain
from omoide.domain import utils
__all__ = [
'Item',
'PositionedItem',
'PositionedByUserItem',
'Location',
'AccessStatus',... |
#!/usr/bin/env python3
"""
DAG generator for a specific taskset
Usage:
dag_generator [-t FILE] [options]
Options:
--taskset FILE, -t FILE taskset csv file [default: taskset-0.csv]
--root=N, -r N number of root node in graph [default: 5]
--branch=N, -b N ... |
# Implementations of our imputation models.
import torch
import numpy as np
from scipy.sparse import lil_matrix, csc_matrix
from scipy.sparse.linalg import spsolve
class BaseImputer():
def __call__(self, img: torch.Tensor, mask: torch.Tensor)-> torch.Tensor:
""" Call the Imputation function to fill the masked pixe... |
# Copyright 2021 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
import asyncio
import discord
from discord.ext import commands
from core import checks, utils
from core.models import PermissionLevel
class logviewer2companion(commands.Cog):
"""
Companion plugin for https://github.com/hackerjef/logviewer2
"""
def __init__(self, bot):
self.bot = bot
... |
from django.db.models.signals import pre_save, post_delete, post_save
from django.dispatch import receiver
from django.conf import settings as django_settings
from .models import ScheduleModel, ResponseModel, StatusModel, SettingsModel, SessionModel
from .tasks import async_comms_update, async_scale_update
from django_... |
import asyncpg
import os
from nextcord.ext import commands
from typing_extensions import TYPE_CHECKING
from typing import Optional, Union
if TYPE_CHECKING:
from index import Friday as Bot
class Database(commands.Cog):
"""Database Stuffs and Tings"""
def __init__(self, bot: "Bot"):
self.bot = bot
self... |
import numpy as np
import tensorflow as tf
def session(graph=None,
allow_soft_placement=True,
log_device_placement=False,
allow_growth=True):
"""Return a Session with simple config."""
config = tf.ConfigProto(allow_soft_placement=allow_soft_placement,
... |
from lib.Service import Service
import requests
import logging
import zipfile
from io import BytesIO
import os
import threading
from RDS import FileTransferMode, LoginMode
from .Util import threadsafe_iter
logger = logging.getLogger()
class Research:
def __init__(self, userId=None, researchIndex=None, researchId... |
from os import name, system, remove, path
import time
from colorama import Fore, Style
import shutil
import requests
from datetime import datetime
import subprocess
def centered(s):
print(s.center(shutil.get_terminal_size().columns))
#just a cool looking ascii
def logo():
centered("SUPER TELEPHONE BOOK")
cen... |
import json
from threading import Thread
from queue import Queue
import tqdm
import requests
from bs4 import BeautifulSoup
from app.thirdparty.oneforall.common import utils
from app.thirdparty.oneforall.config.log import logger
from app.thirdparty.oneforall.common.database import Database
from app.thirdparty.oneforal... |
from torch.utils.data import Dataset, DataLoader
from albumentations import (ShiftScaleRotate, Compose, PadIfNeeded, RandomCrop, HorizontalFlip, OneOf, ElasticTransform,
OpticalDistortion, RandomGamma, Resize, GaussNoise, VerticalFlip, RandomBrightnessContrast)
import cv2
import os
imp... |
#!/usr/bin/env python
"""
Convert MCD43A1 HDF4 files to HDF5.
"""
from pathlib import Path
from subprocess import check_call
import tempfile
import numpy
import rasterio
import h5py
from wagl.hdf5 import write_h5_image, attach_attributes, attach_image_attributes
from wagl.hdf5.compression import H5CompressionFilter
... |
import logging
import sys
import time
import threading
import arrow
from . import db, socketio, process_data
from .models import Setting
from .hardware import HdwRaspberry, HdwSimulator
from .controllers import TempController, PWM_DC
from .sequence import Sequence
logger = logging.getLogger('pibrew.brewcontroller')
... |
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import datetime
import requests
import re
import time
import os
from glob import glob
from scipy.stats import norm
from bs4 import BeautifulSoup
from collections import Counter
from bs4 import BeautifulSoup
##############get info from seeking alph... |
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
This module is capable of transforming arabic number to roman
and in reverse; it takes advantage of the roman apostrophe-system
to operate on big numbers
"""
from math import ceil
# user data
# better not to make this range too large
# time complexity is O(too much)
s... |
# This file is part of PyOP2
#
# PyOP2 is Copyright (c) 2012, Imperial College London and
# others. Please see the AUTHORS file in the main source directory for
# a full list of copyright holders. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted ... |
import os
import time
import numpy as np
from ..engine.base_service import BaseService
from ..utils.generic_utils import Resource
from ..utils import backend_utils as backend
from ..utils.generic_utils import log
import cv2
if backend._USING_RASPBERRYPI_CAMERA:
import picamera
import picamera.array
class Em... |
# -*- coding: utf-8 -*-
"""
Created on Sun Aug 3 15:18:38 2014
@author: <NAME> and <NAME>
Modified by: <NAME>
Loads .continuous, .events, and .spikes files saved from the Open Ephys GUI
Usage:
import OpenEphys
data = OpenEphys.load(pathToFile) # returns a dict with data, timestamps, etc.
"""
import os
fr... |
# 176 39f5eecbfb2470846666a748bda83f67
# 41753 a58f8f1bd61094b3ff2c92c2a4f65876
# 2603 27c00ec2b6ec279958e80128fd34c2b1
# 37247 484f0070df7d5375492d9da2668ec34c
# 36881 4231883e92a3c1a21c62d11641ffbd35
import json
import numpy as np
import os, sys
import torch
import torch.backends.cudnn
import torch.utils.da... |
import socket
import string
import os, sys
import logging, coloredlogs
from threading import Thread
from random import choice
from time import sleep
from modules.commandmanager import CommandManager
from modules.command import Command
from modules.timer import Timer
from modules.config import *
from modules.commandtex... |
import numpy as np
from datetime import datetime
import time
import re
import pandas as pd
import math
def get_gender(gender):
if gender == 'male':
qc_gender = 'male'
return qc_gender
elif gender == 'female':
qc_gender = 'female'
return qc_gender
elif gender == '':
... |
if __name__ == "__main__":
'''
This if statement is needed for testing, to locate the modules needed
if we are running the file directly.
'''
import sys
from os import path
sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
from dalek import settings
from dalek impor... |
import os
import boto3
from botocore.exceptions import ClientError
import avm_common
import time
import json
import sys
# This script will setup GuardDuty on the master account and invite a member account.
# Contributed by <NAME>, <EMAIL>
#
# Run this script using master account access-key and secret-access key
#
# ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# @Author: <NAME> (<EMAIL>)
# @Date: 2019-11-23
# @Filename: test_fps.py
# @License: BSD 3-clause (http://www.opensource.org/licenses/BSD-3-Clause)
import asyncio
import pathlib
import pytest
from drift import Relay
import jaeger
from jaeger.can import JaegerCAN
from ... |
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright 2016-2018 by ExopyPulses Authors, see AUTHORS for more details.
#
# Distributed under the terms of the BSD license.
#
# The full license is in the file LICENCE, distributed with this software.
# ---------... |
from django.utils.deprecation import MiddlewareMixin
import re
import threading
FLAVOURS = ("full", "mobile")
FLAVOURS_SESSION_KEY = "flavour"
FLAVOURS_GET_PARAMETER = "flavour"
DEFAULT_MOBILE_FLAVOUR = "mobile"
_local = threading.local()
class SessionBackend:
@staticmethod
def get(request, default=None):
... |
import argparse
import json
import os
import re
from glob import glob
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
sns.set_style("dark")
def parse_args():
description = """Measure how you spend time by tracking key presses and
changes to window focus or title."""
p = argpars... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013 Rackspace
# 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/licen... |
import torch
import torch.nn as nn
import torch.optim as optim
import matplotlib.pyplot as plt
from collections import deque
import os
from tqdm import tqdm
import datetime
from agent import PPOAgent
from unityagents import UnityEnvironment
import numpy as np
def test_agent(env, brain_name, agent, device, real_time=... |
from __future__ import annotations
import asyncio
import aiohttp
from itertools import chain, zip_longest
import inspect
from datetime import datetime
class Alert:
"""Class to show a type of alert."""
__slots__ = ('coordinates', 'areas_affected', 'affected_zones', 'start_time', 'end_time', 'cwa_issued',
... |
import hashlib
import logging
import os
import re
from xml.dom import minidom
import six
import requests
from bs4 import BeautifulSoup
from pyquery import PyQuery
logger = logging.getLogger(__name__)
uri_scheme = 'https'
api_uri = 'wikipedia.org/w/api.php'
article_uri = 'wikipedia.org/wiki/'
# common sub sections t... |
# The file is used for traffic of dynamic show
# For ubuntu 18.04 install
#1. sudo apt-get install tk-dev
#2. sudo apt-get install python-tk
#Example
#Demo with client : iperf / ib_write_bw
#script: start.traffic.sh in the PC
#Demo 6 client
import datetime
import time
import re
import matplotlib.pyplot as plt
impo... |
################################################################################
##
## CAN with Flexible Data-Rate IP Core
##
## Copyright (C) 2017 <NAME> <<EMAIL>>
##
## Script for generation of VHDL register map entity from IP-XACT
## specification... |
"""Helper to validate/evaluate pipelines and Optimize."""
from typing import Any, Callable, Dict, Iterator, List, Optional, Tuple, Union
import numpy as np
from joblib import delayed
from sklearn.model_selection import BaseCrossValidator, check_cv
from tqdm.auto import tqdm
from tpcp import Dataset
from tpcp._optimi... |
"""File copied from isidentical.
https://github.com/plaguss/syntax_test_suite
"""
import json
import os
import tarfile
import traceback
import zipfile
from argparse import ArgumentParser
from concurrent.futures import ThreadPoolExecutor
from functools import partial
from pathlib import Path
from typing import Generato... |
import os
import re
import shutil
import subprocess
import sys
from itertools import chain
from os import path
from typing import List
import torch
from model.model_runner import ModelRunner, Model, add_features
from utils.file_system import save_temp, temp_name, listdir, temp_dir, save_temp_bin
from utils.levenshtei... |
from collections import OrderedDict
from django import forms
from django.core.urlresolvers import reverse
def get_organiser_menu(city):
"""
Get menu entries for organiser-visible pages
"""
menu = [
{
'title': 'Applications',
'url': reverse('applications:applications', ... |
'''
Created on Oct 5, 2010
@author: Mark V Systems Limited
(c) Copyright 2010 Mark V Systems Limited, All rights reserved.
'''
from arelle import ViewWinTree, XbrlConst
from arelle.ModelDtsObject import ModelRelationship
from arelle.ModelInstanceObject import ModelFact
from collections import defaultdict
def viewConc... |
import os
import decimal
from datetime import datetime, timedelta
import logging
from flask_lambda import FlaskLambda
from flask import jsonify, request
import psycopg2
import boto3
from flask_cors import CORS, cross_origin
logger = logging.getLogger()
logger.setLevel(logging.INFO)
app = FlaskLambda(__name__)
cors ... |
"""
This repeats tons of code from django's implementation
just to overide the ModelState class that is used for each model
so we can change db table for VersionViews to the BasePost for
related fields. It is pretty sucky, and needs a better solution
that will be supported by django long term.
Other options that were ... |
from __future__ import print_function
import time
from sr.robot import *
a_th = 2.0
""" float: Threshold for the control of the orientation"""
d_th = 0.4
""" float: Threshold for the control of the linear distance"""
R = Robot()
""" instance of the class Robot"""
def drive(speed, seconds):
"""
Function for setti... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import struct
import os
# Flag values
NLM_F_REQUEST = 1
NLM_F_MULTI = 2
NLM_F_ACK = 4
NLM_F_ECHO = 8
NLM_F_DUMP_INTR = 16
# Modifiers to GET request
NLM_F_ROOT = 0x100
NLM_F_MATCH = 0x200
NLM_F_ATOMIC = 0x400
NLM_F_DUMP = (NLM_F_ROOT | ... |
import kindred
from collections import Counter
def test_corpus_split():
mainCorpus = kindred.Corpus()
for i in range(100):
doc = kindred.Document(text=str(i))
mainCorpus.addDocument(doc)
corpusA,corpusB = mainCorpus.split(0.75)
assert len(corpusA.documents) == 75
assert len(corpusB.documents) == 25
seen ... |
import numpy as np
import torch
import torch.nn as nn
# this class is taken from https://github.com/naver/r2d2/blob/master/nets/ap_loss.py
class APLoss (nn.Module):
""" differentiable AP loss, through quantization.
Input: (N, M) values in [min, max]
label: (N, M) values in {0, 1}
Ret... |
import os
import random
from collections import Counter
from itertools import cycle
from typing import List
import torch
from torch import nn
from efficient.char_cnn_lstm import CharCNNLSTM
from efficient.torch_model_base import TorchModelBase
class CharCNNLSTMModel(TorchModelBase):
def __init__(
self,
... |
"""Nox for python task automation.
nox.option.sessions is default run for 'nox' on command line inc:
* lint: python linting
* mypy^: strict variable type checking
* pytype:
* tests (pytest^): runs our test suite
Additional options:
* autoflake^: remove unused imports and variables
* black^: co... |
# -*- Mode: Python; tab-width: 4 -*-
#
# Author: <NAME> <<EMAIL>>
# Copyright 1997 by <NAME>
# All Rights Reserved.
# standard python modules
import re
import stat
import string
# medusa modules
from . import http_date
from . import http_server
from . import mime_type_table
from . import status_handler
from . import ... |
import numpy as np
import pandas as pd
import pytest
from fairlens.metrics.distance import BinomialDistance, MeanDistance
from fairlens.metrics.significance import binominal_proportion_p_value as bin_prop
from fairlens.metrics.significance import bootstrap_binned_statistic as bootstrap_binned
from fairlens.metrics.sig... |
#
# 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
# "License"); you may not... |
from django.db import models
from bmcore.models.branch import Branch
from bmcore.models.inventory import Inventory
from bmcore.models.pack import Pack
# Batch Manager
class BatchManager(models.Manager):
def create(self, pack, branch, **kwargs):
instance = self.model()
instance.name = kwargs.... |
# -*- coding: utf-8 -*-
# Copyright (c) 2013, <NAME>
#
# 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
# notice, this list of conditions and ... |
'''
A Framework of Back Propagation Neural Network(BP) model
dependency:
- numpy.
author: <NAME>
github : https://github.com/RiptideBo
2017.11.23
'''
import numpy as np
import matplotlib.pyplot as plt
def sigmoid(x):
return 1 / (1 + np.exp(-1 * x))
def relu(x):
return np.where(x > 0, x, 0)
def softmax(... |
import unittest
import numpy as np
import pandas as pd
import xarray as xr
from xcube.core.tile import get_var_valid_range
from xcube.core.tile import parse_non_spatial_labels
from xcube.core.tile import _ensure_time_compatible
class GetVarValidRangeTest(unittest.TestCase):
def test_from_valid_range(self):
... |
import os
import re
import urllib
import requests
import bs4
import pandas as pd
import numpy as np
from ..season.season_extract import season_url
from ..helpers.db_funcs import get_ep_id, get_season_id
from ..helpers.extract_helpers import search_for_new_seasons
def parse_quote_table(quote_table):
tbl = quot... |
"""
The MIT License (MIT)
Copyright (c) 2016 <NAME> (Stanford University)
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 moviepy.editor as mpy
import gizeh as gz
from math import pi
import textwrap
import requests
from bs4 import BeautifulSoup
from gtts import gTTS
import os
import uuid
from datetime import datetime
import logging
import threading
import time
def process_video(
url_str=None, vid_wid=1920, vid_hig=1080,
... |
# This code and much of the comments are heavily inspired by the book "An Introduction to Raytracing" edited by <NAME>
# It is provided under this license https://creativecommons.org/licenses/by/4.0/
#from PIL import Image
#from numpy import asarray
#img = Image.new(mode = "RGB", size = (3, 4), color = 'red')
#img2 = ... |
import numpy as np
import pandas as pd
def rand_design_matrix(experiments, features) -> pd.DataFrame:
"""
:param int experiments: Number of Experiments to design
:param int features: Number of features to include in the design
Generate a random starting design matrix
"""
df = pd.DataFrame(np... |
""" This module acts as collection for the datakeys and its datatypes and several status codes
"""
# constants that represent the different contexts that a reader should be active in
CONTEXT_LOGFILE = 1 # the log file of a solver which most readers are reading from
CONTEXT_ERRFILE = 2 # the error file of a solver
C... |
# Copyright 2019 Open Source Robotics Foundation, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... |
import json
import requests
import logging
# import os
import re
from django.http import HttpResponse
from django.shortcuts import render
from django.conf import settings
import atlas.deftcore.api.client as deft
_logger = logging.getLogger('prodtaskwebui')
_deft_client = deft.Client(auth_user=settings.DEFT_AUTH_USE... |
"""
Utility definitions to wrap a model with losses, metrics and logs
"""
import copy
import torch.nn.functional as F
from collections import OrderedDict
from mixmo.networks import get_network
from mixmo.core import (
loss, optimizer, temperature_scaling, scheduler,
metrics_wrapper)
from mixmo.utils import lo... |
# -*- coding:utf-8 -*-
# email:<EMAIL>
# create: 2021/1/12
import torch
import torch.nn as nn
from networks.components.rasc import RASC
import functools
class MinimalUnetV2(nn.Module):
"""docstring for MinimalUnet"""
def __init__(self, down=None, up=None, submodule=None, attention=None, withoutskip=False, **... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os.path
from functools import partial as set_parameter
import tensorflow as tf
from tensorflow.python.ops import image_ops
# Basic model parameters as external flags.
FLAGS = None
# Constants used for... |
# -*- coding: utf-8 -*-
"""Demonstration / usage example for the new features.
Created on Fri Mar 24 13:58:36 2017
@author: <NAME>, <EMAIL>
"""
from __future__ import division, print_function, absolute_import
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm
import matplotlib.colors
import b... |
from catalog.models import *
from datetime import datetime
class NonReleasedDataToRemove:
def __init__(self):
self.scores2del = {}
self.perfs2del = {}
self.pss2del = {}
self.traits2del = {}
self.publications = []
def fetch_non_released_publications(self):
s... |
"""
General purpose utilities
"""
import base64
import copy
import logging
import re
import time
import sys
from functools import lru_cache
from functools import wraps
from html.parser import HTMLParser
from pkg_resources import parse_version
import yaml
from koris.util.hue import red # pylint: disable=no-name-in-... |
import argparse
import csv
import os
import random
import string
import numpy as np
import skimage.measure
from os.path import join
from image_class import image_class
# Returns a dictionary with new names like aa.jpg
def rename(shuffled_keys):
# Create the dictionary
# key is real image name (e.g. "real/no_a... |
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 16 16:00:41 2020
@author: <NAME> Microscopy B.V.
This software is an example of how the data from a camera can be captured,
filtered/processed, and displayed using openCV, while the work is done on
multiple processes. For this we use the mproc library from LPM, w... |
#!/usr/bin/env python3
###############################################################################################################
## [Title]: privcheckerserver.py -- a Linux Privilege Escalation Check Script Server
## [Author]: <NAME> (linted) -- https://github.com/linted
##----------------------------------------... |
from youtubesearchpython import *
from datetime import datetime
from collections import Counter
from multiprocessing import Pool
import init_database as db_helper
import pprint as pp
import json
import collections
import logging
import logging.config
import pandas as pd
import traceback
import re
import sy... |
#-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: saad.bendaoud
#
# Created: 09/08/2019
# Copyright: (c) saad.bendaoud 2019
# Licence: <your licence>
#--------------------------------------------------------------------... |
from io import StringIO
from pathlib import Path
from time import time
from unittest import TestCase
from kirby_transform.processor import (ProcessedData, Processor, make_data,
make_meta_data_level,
make_meta_report_level)
from kirby_transfo... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
-----------------------------------------
@Author: zhaocy
@Email: <EMAIL>
@Created: 2020/6/22
------------------------------------------
@Modify: 2020/6/22
------------------------------------------
@Description:
"""
import random
from definitions import DATA_DIR
de... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
fro... |
import mediapipe as mp
import numpy as np
import math
import cv2
mp_pose = mp.solutions.pose
mp_drawing_styles = mp.solutions.drawing_styles
mp_drawing = mp.solutions.drawing_utils
pose = mp_pose.Pose(static_image_mode=False,
model_complexity=1,
enable_segmentation=False,
min_detection_confide... |
import argparse
import datetime
import json
import sys
import colorlog
import requests
# Configuration
CONFIG = {'config': {'url': 'http://config.int.janelia.org/'}}
def call_responder(server, endpoint, payload=''):
""" Call a responder
Keyword arguments:
server: server
endpoint: REST en... |
import torch
import torch.nn as nn
# from .utils import load_state_dict_from_url
from typing import Union, List, Dict, Any, cast
from CIFAR.models.spiking_layer import SpikeModule
from CIFAR.models.vgg import AvgPoolConv
from collections import OrderedDict
__all__ = [
'VGG', 'vgg16', 'vgg16_bn'
]
model_urls = {
... |
#!/usr/bin/env python
import datetime, time, os
from optparse import OptionParser
from multiprocessing.pool import ThreadPool
import zkclient
from zkclient import ZKClient, CountingWatcher, zookeeper
SESSIONS_NUM = 12
total_writes = 0
usage = "usage: %prog [options]"
parser = OptionParser(usage=usage)
... |
from django.test import TestCase
from django.test import Client
# from django.contrib.auth.models import User
from leads.models import Lead
from common.models import Address, User
from accounts.models import Account
class TestLeadModel(object):
def setUp(self):
self.user = User.objects.create(username='ud... |
# To add a new cell, type '# %%'
# To add a new markdown cell, type '# %% [markdown]'
# %%
from IPython import get_ipython
# %%
import torch
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from torch.distributions import MultivariateNormal
import torch.nn as nn
get_ipython().run_line_magic('matpl... |
#! /usr/bin/env python
# coding=utf-8
#================================================================
# Copyright (C) 2019 * Ltd. All rights reserved.
#
# Editor : VIM
# File name : backbone.py
# Author : YunYang1994
# Created date: 2019-02-17 11:03:35
# Description :
#
#======================... |
'''
Contains Methods classes for the Exam Application.
EXAM APPLICATION LAUNCHER developed by Mr <NAME>
Nov. 2019
SAMROIYOD, <NAME>, THAILAND
[See license.txt file]
'''
__author__ = '<NAME>'
__version__ = '1.0'
import os
import datetime
import time
from contextlib import contextmanager
from PyQt5 import QtC... |
import glob
from torch.utils.data import Dataset
import torchvision.transforms.functional as TF
import torchvision as tv
import numpy as np
import random
import os
import re
from PIL import Image, ImageDraw, ImageFont
from transformers import BertTokenizer
from .utils import nested_tensor_from_tensor_list
MAX_DIM =... |
import ConfigSpace as CS
def decode_config_name(config_name):
def raise_format_error():
msg = (
'expected `config_name` of format '
'`(w | n)_sm.(w | n)_perm` but got '
f'`{config_name}`.')
raise ValueError(msg)
s = config_name.split('.')
if len(s) != 2... |
#!/usr/bin/env python
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from builtins import open
from builtins import dict
from builtins import zip
from builtins import int
from builtins import map
from future import sta... |
import pandas as pd
import joblib
import copy
from sklearn.ensemble import RandomForestClassifier
model = joblib.load("./model/tictactoemaster.joblib")
board_columns = ['tl_x', 'tl_o', 'tm_x', 'tm_o', 'tr_x', 'tr_o', 'ml_x', 'ml_o',
'mm_x','mm_o', 'mr_x', 'mr_o', 'nl_x', 'nl_o', 'bm_x', 'bm_o',
'br_x', 'br_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.