text stringlengths 3.07k 22.1k |
|---|
import sqlite3
import time
import random
from tqdm import tqdm
# Setup
dbFile = 'ISC/Rasp-main/Database.db'
DBDelay = 2 # seconds
# Data
general = dict()
charger = dict()
sevcon = dict()
bms1 = dict()
bms2 = dict()
bms3 = dict()
bms = [bms1, bms2, bms3]
def init_dict():
'''
Initializes internal dictionaries... |
import pygame
from pygame.locals import *
from .const import *
from . import widget
from . import table
from . import basic
from . import pguglobals
_SLIDER_HORIZONTAL = 0
_SLIDER_VERTICAL = 1
class _slider(widget.Widget):
_value = None
def __init__(self,value,orient,min,max,size,step=1,**params):
p... |
#!/opt/workflow/bin/python2.7
#
# Copyright 2013-2016 Edico Genome Corporation. All rights reserved.
#
# This file contains confidential and proprietary information of the Edico Genome
# Corporation and is protected under the U.S. and international copyright and other
# intellectual property laws.
#
# $Id$
# $Author$
#... |
import numpy as np
import pytest
import pandas.util._test_decorators as td
from pandas import (
DataFrame,
NaT,
Series,
Timestamp,
date_range,
period_range,
)
import pandas._testing as tm
class TestDataFrameValues:
@td.skip_array_manager_invalid_test
def test_values(self, float_frame... |
# Copyright 2019 The OpenRadar Authors. All Rights Reserved.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law... |
"""
Water buckets problem (generalized) in cpmpy.
From http://www.dis.uniroma1.it/~tmancini/index.php?currItem=research.publications.webappendices.csplib2x.problemDetails&problemid=018
'''
Problem description
This is a generalization of the CSPLib specification, which is as follows:
Given an 8 pint bucket of water, a... |
import datetime
from django.db.models import Case, Max, When
from django.db.models import CharField
from django.db.models.functions import Cast
from elasticsearch_dsl.query import (
Bool,
Exists,
Range,
Term,
)
from datahub.core.constants import InvestmentProjectStage
from datahub.core.query_utils imp... |
import hashlib
import logging
import unittest
from blockchain_constants import MSGS_PER_BLOCK
from key import Keys
from objects import parse_block, parse_message
private = "tests/key_data/private_keys.pem"
public = "tests/key_data/public_keys.pem"
directory = "tests/key_data/key_directory.pem"
class TestBlockParsin... |
# -*- coding: utf-8 -*-
# source code: https://github.com/laihuiyuan/pre-trained-formality-transfer/blob/main/classifier/textcnn.py
import os
import sys
import time
import argparse
import torch
import torch.nn as nn
from torch import cuda
import torch.nn.functional as F
from transformers import T5Tokenizer
sys.path.a... |
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... |
from transformers import AutoConfig, GPT2Tokenizer, BertTokenizer
from os.path import isdir
from dataset import *
from transformer import *
from torch.utils.data import DataLoader
from datetime import date
import argparse
import os
import sys
from time import time
from huggingface_modeling_gpt2 import *
import logging
... |
"""
High-level source extraction interface.
:func:`~extract_sources()`: a wrapper around `~sep` background estimation and
source extraction functions.
"""
from __future__ import absolute_import, division, print_function
from typing import Any, Dict, Optional, Tuple, Union
from numpy import ceil, isfinite, ndarray, ... |
import urllib.request
import shutil
import os.path
import zipfile
import time
import sys
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
from bs4 import BeautifulSoup
import uuid
def find_between(file):
f = open(file, "r", encoding = "utf8")
soup = BeautifulSoup(f, 'html.parser')
... |
# This code was based on https://github.com/Octavian-ai/english2cypher
# Octavian.ai developed.
import tensorflow as tf
from .input import get_constants, load_inverse_vocab_hashtable
dtype = tf.float32
def basic_cell(args, i, unit_mul):
""" Construct the basic cell. """
c = tf.contrib.rnn.LSTMCell(
... |
import ctypes
import mmap
MAX_PLAYERS = 10
MAX_NAME_LENGTH = 32
MAX_BOOSTS = 50
SHARED_MEMORY_TAG = 'Local\\RLBotOutput'
class Vector3(ctypes.Structure):
_fields_ = [("X", ctypes.c_float),
("Y", ctypes.c_float),
("Z", ctypes.c_float)]
class Rotator(ctypes.Structure):
_fields... |
import pygame
import random
from enemy import *
from terrain import *
from constants import *
from framework import *
class room:
def __init__(self):
self.directions = {"left":False, "right":False, "up":False, "down":False}
self.enemies = []
self.items = []
self.projectiles = []
... |
from ply.lex import TOKEN
from be_typing import TYPE_CHECKING
t_ignore = ' \t'
keywords = (
# header
'source_filename',
'target',
'datalayout',
'triple',
'attributes',
# structs
'type',
'opaque',
'addrspace'... |
from jumpscale import j
# TODO: P2 S4 :eduard TextLineEditor tool does not work any more, is a
# pitty because ideal to parse config files on a filesystem (id:83)
JSBASE = j.application.jsbase_get_class()
class TextLineEditor(JSBASE):
"""
represents a piece of text but broken appart in blocks/tokens
thi... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
Hazel v2.0
Hazel synthesis and inversion code. It can invert both photospheric lines and chromospheric lines.
For more information see: https://github.com/aasensio/hazel2
::
Main Changes in 0.1
---------------------
* Working version
:copyright:
<NAME... |
#!/usr/bin/env python3
import argparse
import click
import itertools
import json
import numpy as np
ITERATORS = ["i", "j", "k"]
def make_field_name(index, name="a"):
return f"{name}{index}"
def make_stage_name(index):
return "b{}".format(index)
def make_extent_accesses(size, extent, stencil_shape):
i... |
# -*- coding: utf-8 -*-
"""
.. codeauthor:: <NAME> <<EMAIL>>
"""
# Modifications:
# - input shapes = (126, 48), (96, 96), (48, 48)
# - 128x48: common size in person detection
# - 96x96: square size with regard to smallest possible size in mobilenet2
# - 48x48: square size with regard to original beye... |
'''
Given a folder of .log files, outputs a summarization file of those logs in table form.
'''
import argparse
import json
import os
import re
import sys
import glob
import math
import loggerconstants as constants
## Utility
def _flatten_dict(d: dict):
"""
Flattens a nested dictionary, not in-place
"""
... |
"""
This its the main file
Check out README.md for instructions
"""
import csv
import os
from fractions import Fraction
from typing import List
class Reader:
"""Main class of the program"""
filename = ""
course = ""
work = []
scales = []
grade = []
def __init__(self, filename):
se... |
def get_column(matrix, n):
col = []
for row in matrix:
col.append(row[n])
col = [x for x in col if x != 0]
col.sort()
return col
def get_row(matrix, n):
row = []
row = matrix[n]
row = [x for x in row if x != 0]
row.sort()
return row
def get_sub_grid_coo... |
import itertools
import logging
import os
import tempfile
import hnswlib
import numpy
from implicit.als import AlternatingLeastSquares
from implicit.approximate_als import augment_inner_product_matrix
log = logging.getLogger("hnsw_als")
def _safe_len(index) -> int:
if index is None:
return 0
return ... |
"""
Target State Module
Class of thermal states used for our learning tasks.
"""
from itertools import product
from numpy.linalg import norm
from numpy.random import normal as N
from numpy.random import randn
from numpy.random import seed
from qutip.operators import sigmax, sigmay, sigmaz, identity
from qutip.tensor... |
#!/usr/bin/env python
#
# Copyright 2017 Confluent 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... |
#!/usr/bin/env python3
'''
Intérprete de texto
'''
import sys
from solver import solver
from utils import variables, random_lim, variables_string
from numpy import inf
from CoolProp.CoolProp import PropsSI as prop
from CoolProp.CoolProp import HAPropsSI as haprop
from time import time
import optparse
import os
from exp... |
import pygame as pg
from time import time
class BaseElement:
def __init__(self, name, window, pos=None, size=None, border=True, grid_pos=None, grid_size=None):
"""
Using grid size and grid rects is a lot easier than using pos and size directly. Just set a window size
to a certain g... |
from django.test import TestCase
from .models import Question, Answer
from users.models import Profile
from .models import Question, Answer
from django.contrib.auth.models import User
from django.core.files.uploadedfile import SimpleUploadedFile
from django.db import IntegrityError
from django.conf import settings
from... |
"""
Autopsy Forensic Browser
Copyright 2019-2020 Basis Technology Corp.
Contact: carrier <at> sleuthkit <dot> org
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... |
from django import forms
from django.forms.models import inlineformset_factory, BaseInlineFormSet
from django.db.models import get_model
from django.template.defaultfilters import slugify
from django.utils.translation import ugettext_lazy as _
from treebeard.forms import MoveNodeForm
from oscar.forms.widgets import I... |
import scipy as sp
import numpy as np
from scipy.sparse import csr_matrix, diags
from scipy.sparse.linalg import spsolve
from scipy.linalg import det, eigh, qr
from scipy.misc import comb
import pickle
from src import utils
# Import error handling
#from utils import ControlledError
from src.utils import ControlledErr... |
import argparse
import binascii
import logging
import os
import random
#os.environ["CUDA_VISIBLE_DEVICES"] = "0"
import sys
from pathlib import Path
from typing import Optional
import pdb
import numpy as np
import torch
import torch.nn.functional as F # noqa
import torch.optim as optim
import tqdm
from ignite.contrib... |
#!/usr/bin/python3
import sys, os
import os.path
import argparse
import shlex
import subprocess as pr
from multiprocessing import Process, Queue, JoinableQueue, Lock, Value
from scipy.stats import beta
# from statsmodels.stats.proportion import *
from . import ProgressBar as pb
from . import ArgParsing as ap
from .S... |
# Copyright (c) 2021, eQualit.ie inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import logging
import random
import string
import sys
import traceback
from concurrent.futures.thread import ThreadPoolExecutor... |
import random
import pygame as pg
import environment, config
class Sub:
def __init__(self, game, width, height):
self.game = game
self.w = width
self.h = height
pixelw = (self.w + config.TILE_GAP) * config.ROOM_SCALE
pixelh = (self.h + config.TILE_GAP) * config.ROOM_SCALE
... |
"""
Tools for managing and manipulating tables on disk.
Most users will need TableTools and not TableManagementTools.
"""
#
# Copyright (c) 2016-2021 Deephaven Data Labs and Patent Pending
#
##############################################################################
# This code is auto generated.... |
# -*- coding: utf-8 -*-
from itertools import chain, tee
from .utils import cached_property, uniq
from . import native
class Item(object):
'''Immutable wrapper class for VCALENDAR (VEVENT, VTODO) and
VCARD'''
def __init__(self, raw, _native=None):
if raw is None:
assert _native
... |
import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(__file__)))
import numpy as np
from data import get_loader
from utils import update_state, save_ckpt_file
from utils import joint_transforms as jnt_trnsf
from utils import summarize_model
from networks import get_network
import torch
import torchvi... |
#!/usr/bin/python3
# copy from https://github.com/Jittor/gan-jittor/models/gan/gan.py
import jittor as jt
from jittor import init
from jittor import nn
from jittor.dataset.dataset import ImageFolder
# from jittor.dataset.mnist import MNIST
import jittor.transform as transform
import argparse
import os
import numpy as n... |
from __future__ import annotations
import enum
from typing import Any, List
from numlab.compiler import AST
# pylint: disable=too-few-public-methods
# pylint: disable=missing-class-docstring
class ExprCtx(enum.Enum):
LOAD = enum.auto()
STORE = enum.auto()
DEL = enum.auto()
class Operator(enum.Enum):
... |
import os
import posixpath
import ntpath
from os import environ as env
from subprocess import Popen, PIPE
from shlex import quote
import re
import pathlib
from tempfile import TemporaryDirectory
import json
import distutils.spawn
import yaml
from vsi.tools.diff import dict_diff
from vsi.tools.python import nested_pat... |
import collections.abc
import enum
import random
import lark
try:
import stix2.parsing as mappings
except ImportError:
import stix2.core as mappings
def is_tree(node, rule_name=None):
"""
Determine whether the given parse tree node is a Tree node, and optionally
verify its type.
:param node:... |
# Copyright 2020 <NAME>
#
# 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, softw... |
# -*- coding:utf-8 -*-
# /usr/bin/env python
"""
Date: 2020/09/07 16:58
Desc: 获取各合约展期收益率, 日线数据从 daily_bar 函数获取
"""
import datetime
import re
import warnings
import matplotlib.dates as mdate
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from pandas.plotting import register_matplotlib_converters... |
# encoding: utf-8
"""
Copyright (c) 2020, salesforce.com, inc.
All rights reserved.
SPDX-License-Identifier: BSD-3-Clause
For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
"""
# This Source Code Form is subject to the terms of the Mozilla Public
# License... |
import json
from abc import ABC, abstractmethod
import hashlib
import re
from typing import List
from datetime import datetime
class BaseMeta(ABC):
_meta_name = 'BASE'
def __init__(self, metadata, meta_version):
self._version = meta_version
self._metadata = metadata
@property
def d... |
#!/usr/bin/env python3
# Author: <NAME>
# License: Apache License Version 2.0
import argparse
import hashlib
import os
import pwd
import subprocess
import sys
from abc import abstractmethod, ABCMeta
import re
def md5_sum(plain_text: str):
md5 = hashlib.md5()
md5.update(plain_text.encode('utf-8'))
return ... |
'''Challenge model module'''
import enum
import model.scoring
from datetime import datetime, timezone
from sqlalchemy import Table, Column,Integer, String, Enum, DateTime
from sqlalchemy.sql.expression import func, text
from sqlalchemy.dialects.postgresql import JSONB
from model.user import UserModel
from model.prose... |
# -*- coding:utf-8 -*-
import logging
from collections import OrderedDict
import sqlalchemy.types as t
from sqlalchemy.inspection import inspect
from sqlalchemy.orm.properties import ColumnProperty
from sqlalchemy.orm.relationships import RelationshipProperty
from sqlalchemy.sql.visitors import VisitableType
from sqlal... |
# 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 agreed to in writing, ... |
from asyncio import Future
from typing import List, Optional
import asyncio
import pytest
import logging
import canopy
import integration_tests
logger = logging.getLogger(__name__)
default_car_name = 'Canopy F1 Car 2019'
default_weather_name = '25 deg, dry'
default_exploration_name = 'Automated Test Monte Carlo'
te... |
import numpy as np
import os, sys
from tqdm import tqdm
import paddle
from paddle.vision.transforms import functional as F
from ..common.paddle_utils import FeatureExtractor, extract_superpixel_features, get_pre_models
from ..data_processor.readers import load_pickle_file
from .lime import LIMECVInterpreter, LIMENLPIn... |
import logging
import os
import itertools
import pandas
import regex
from bs4 import BeautifulSoup
from curation_utils import file_helper
from doc_curation import text_data
from doc_curation.md import library, get_md_with_pandoc
import roman_numerals
from doc_curation.md.file import MdFile
from doc_curation.scraping... |
"""
This example demonstrates how to write an analogue of the ``matplotlib.mlab.specgram``
function using Reikna. The main difficulty here is to split the task into transformations
and computation cores and assemble them into a single computation.
To map the task to the transformation/computation model, one needs to s... |
import os
import re
import subprocess
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from .helpers import determine_tag_value, figs_assert, initiate_figs, plot_helper_settings
def get_lobster(bond=0, filepath='COHPCAR.lobster', ISPIN=None, plot=False, xlim=None, ylim=None,
on_... |
__author__ = 'hadyelsahar'
import numpy as np
from sklearn.base import BaseEstimator, ClassifierMixin
from sklearn.metrics import accuracy_score
import tensorflow as tf
from sklearn.metrics import classification_report
import pickle as pk
import sys
sys.path.append("/data")
class CNN(BaseEstimator, ClassifierMixin)... |
# -*- python -*-
# This software was produced by NIST, an agency of the U.S. government,
# and by statute is not subject to copyright in the United States.
# Recipients of this software assume all responsibilities associated
# with its operation, modification and maintenance. However, to
# facilitate maintenance we as... |
import math
from repartition_experiments.algorithms.utils import Volume, get_file_manager, get_blocks_shape
from repartition_experiments.file_formats.hdf5 import HDF5_manager
from repartition_experiments.algorithms.utils import get_opened_files
def get_entity_sizes(cs, bytes_per_voxel, partition):
bs = cs[0] * cs... |
# noqa: D100
import functools
import logging
import operator
from typing import Dict, List, Optional, Union
import hail as hl
from gnomad.resources.resource_utils import DataException
from gnomad.utils.annotations import annotate_adj
from gnomad.utils.reference_genome import get_reference_genome
logging.basicConfig(... |
# 14 July 2018 <NAME>
# Python bootcamp, lesson 40: Image processing practice with Python
# Import numerical modules
import numpy as np
import scipy.optimize
# Import modules for plotting
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
# Modules for image processing
import skimage.io
import skimage.m... |
"""DAB script"""
__author__ = 'Vardë'
import os
import shlex
import subprocess
from acsuite import eztrim
from adptvgrnMod import adptvgrnMod
import vardefunc as vdf
import havsfunc as hvf
import mvsfunc as mvf
import G41Fun as gf
import lvsfunc as lvf
from fake_rescale import fake_rescale
from init_source import In... |
#!/usr/bin/python3
"""
Program: daily_weather_obs_chart
Author: <NAME>
Purpose: To take NOAA weather csv and display current day data
Command args:
"""
import logging
import sys
import os
import argparse
import csv
import re
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
im... |
import json
import urllib.request as request
import hashlib
import os
import pathlib
import random
import fasteners
import base64
from datetime import datetime as dt
class PairioClient():
def __init__(self):
self._config = dict(
user='', # logged in user for setting remote pairs
t... |
import os
import shutil
import argparse
import itertools
from typing import List
import radical.utils as ru
from radical.entk import AppManager, Pipeline, Stage, Task
from deepdrivemd.config import ExperimentConfig, BaseStageConfig
from deepdrivemd.data.api import DeepDriveMD_API
def generate_task(cfg: BaseStageConfi... |
import os
import uproot3 as uproot
import torch
import torch.nn as nn
import numpy as np
from torch.utils.data import Dataset, DataLoader, Sampler
from datetime import datetime
from tqdm import tqdm
data_dir = 'data/'
node_features_list = ['trk_d0', 'trk_z0', 'trk_phi', 'trk_ctgtheta', 'trk_pt', 'trk_charge']
jet_feat... |
# 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 agreed to in writing, ... |
import torch
from torch.nn import Parameter
from .base import FunctionalModule
from ..data import DataPointer
from ..functions import structuredSigmoid
from ..trees import SumTree, ProdTree, OperatorTree
from ..types import TypeSpec, LitSpec, ProdSpec, VarSpec, ExtSpec, create_tuple_type, create_unit_type
from ..error... |
#
# Usage Record representation and generation.
#
# Module for the SGAS Batch system Reporting Tool (BaRT).
# Some code copied from the arc-ur-logger in ARC.
#
# Author: <NAME> <<EMAIL>>
# Copyright: Nordic Data Grid Facility (2009, 2010)
import time
from bart import __version__
from bart.usagerecord import urelement... |
""" NormalizeStaticIf adds support for static guards. """
from pythran.analyses import (ImportedIds, IsAssigned, HasReturn,
HasBreak, HasContinue,
StaticExpressions, HasStaticExpression)
from pythran.passmanager import Transformation
from pythran.syntax impor... |
# Author: <NAME> <<EMAIL>>
# Contributors: <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>,
# Copyright (c) 2017, Stanford University and the Authors
# All rights reserved.
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from torch.autograd import V... |
from copy import deepcopy
from typing import Optional, Tuple, Any, List, Dict
from safitty.types import Storage, Status, Strategy, \
Transform, Key, Relative, \
star, dstar
# Checkers
def is_container(storage: Storage) -> bool:
return hasattr(storage, "__setitem__")
def need_last_value(status: int, val... |
from modules.basemodule import BaseModule
import pprint
import random
import re
import time
import urllib.request
def nothingToForage(mud, _):
dir = random.choice(list(mud.gmcp['room']['info']['exits'].keys()))
if mud.gmcp['room']['info']['exits'][dir] == -565511086:
return 'run 5e\nforage'
else:... |
# Tests based on the content of "Learn Prolog Now"
# http://www.learnprolognow.org/
from nose.tools import assert_true, assert_false, assert_equal
from swilite.prolog import (Functor, Term, Predicate, Query, Frame)
# Common terms
happy = Functor('happy', 1)
jealous = Functor('jealous', 2)
listens_2_music = Functor('... |
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, Float, Boolean, ForeignKey, Table, Date, DateTime
from sqlalchemy.orm import sessionmaker, relationship
import os
# The absolute path to the dotabase Python package
dotabase_dir ... |
import csv
import sqlalchemy as sa
import datetime
import pprint
import time
import os
import sqlparse
def load_csv_files_into_db(connection_string, data_dict, schema_ddl=None, indices_ddl=None, schema=None, delimiter=",",
lower_case_keys=True, i_print_update=10000, truncate=False, truncate... |
from __future__ import print_function, division
# pytorch imports
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import datasets, models, transforms
from torchvision import transforms, utils
from tensorboardX import SummaryWriter
# general imports
import os
import time
from shutil imp... |
"""Common libraries for plugins"""
import copy
import logging
from kheops.utils import schema_validate
from pprint import pprint
log = logging.getLogger(__name__)
# Vocabulary:
# Key Rules
# ConfPlugin[1]
# StrategyPlugin[1]
# OutPlugin[N]
# Lookup Hierarchy
# ConfPlugin[1]
# ScopePlugin[N]
# BackendPlugin[1]
# G... |
import datetime
import re
import empyrical as em
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pyfolio as pf
import pymongo
import QUANTAXIS as QA
from qaenv import mongo_ip
#mongo_ip = '127.0.0.1'
def mergex(dict1, dict2):
dict1.update(dict2)
return dict1
def promise_list(... |
# 8/13/18
# chenyong
# call plant height
"""
call plant height from predicted images
"""
import os
import sys
import cv2
import numpy as np
import pandas as pd
import os.path as op
import scipy.misc as sm
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib import rcParams
from PIL import Image
fro... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
try: # Python3
from itertools import zip_longest
except ImportError: # Python2
from itertools import izip_longest as zip_longest
from itertools import tee
from xml.sax.saxutils import escape, unescape
from joblib import Parallel, delayed
from tqdm import tqdm
... |
# 要添加一个新单元,输入 '# %%'
# 要添加一个新的标记单元,输入 '# %% [markdown]'
# %%
from __future__ import print_function, division
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim as optim
from torch.utils.data import Dataset, DataLoader, ConcatD... |
# Copyright (c) 2021 PPViT Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable... |
'''
========================
Performance measurement and analysis module
========================
Created on Feb.2, 2022
@author: <NAME>
@Email: <EMAIL>
@TaskDescription: This module provide performance measurement utilities.
'''
import sys
import logging
import argparse
import matplotlib
import matplotlib.pyplot as ... |
import argparse
import math
import json
import logging
import os
import requests
from pathlib import Path
from osgeo import ogr
logger = logging.getLogger(__name__)
def is_dir_check(path):
if os.path.isdir(path):
return path
else:
raise argparse.ArgumentTypeError(f"readable_dir:{path} is not... |
#!/usr/bin/python3.6
from __future__ import print_function
from googleapiclient.discovery import build
from googleapiclient import errors
from httplib2 import Http
from oauth2client import file, client, tools
from pytz import timezone
from datetime import datetime
from re import match
from netmiko import ConnectHandler... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from lib.layers import *
class FSSD(nn.Module):
# (self, base, extras, head, features, feature_layer, num_classes)
# FSSD(phase, cfg, base_, extras_, head_, features_, extras[str(size)])
def __init__(sel... |
# Copyright (c) 2020 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 packages
import streamlit as st
import numpy as np
import pandas as pd
import re
# Functions
def string_replace(x):
new_string = re.sub(' {2,}', ' ', x).replace(" ", ';').replace("\n", ";").replace("; ;", ";")
# new_string = new_string.split(';')
return(new_string)
def get_ingredients (x):
in... |
import os
from random import choice
from git import Repo
from github import Github
from github.GithubException import GithubException
from github.Organization import Organization
from github.Team import Team
import github
import conda_build.api
from conda_smithy.utils import get_feedstock_name_from_meta
def gh_tok... |
#! /usr/bin/env python3
"""
The MIT License
Copyright (c) 2019 by <NAME>, University of New Hampshire <<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 wit... |
# Script para jogar com o bot no BGA
# Executar bot da pasta anterior:
# $ python3 main.py play 0
from selenium import webdriver
from time import sleep
import bs4
import json
import sys
# Cartas na ordem do BGA
CARDS = ['Stone Pit', 'Clay Pool', 'Ore Vein', 'Tree Farm', 'Excavation',
'Clay Pit', 'Timber Yard... |
# coding=utf-8
# Copyright (C) 2020 NumS Development Team.
#
# 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... |
# 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... |
# Copyright 2020 The Pigweed Authors
#
# 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 ... |
r"""
``editquality extract_damaging -h``
::
Gathers the reverted status for a set of revisions and
prints a TSV to stdout of the format:
<rev_id>\t<reverted>\t<reason>
Usage:
extract_damaging -h | --help
extract_damaging <dump-file>... [--host=<url>]
... |
"""CSC148 Lab 11: More on sorting
=== CSC148 Fall 2017 ===
<NAME> and <NAME>
Department of Computer Science,
University of Toronto
=== Module description ===
This file contains an *in-place* implementation of mergesort,
and a skeleton implementation of Timsort that you will work through
during this lab.
""... |
# Main Application
# - Run it command line.
#
#
# @auth Steve (<EMAIL>)
#
import argparse
import pprint
from time import sleep
'''
------------------------------------------------------------------------------------
-- Main Application.
자세한 실행 모드는 아래 각 함수 참고...
------------------------------------------------------... |
import numpy as np
import tensorflow as tf
from groupLasso import groupLasso
from timeit import default_timer as timer
def test():
labels = tf.constant([[1,0,1,0,1,1,0,0,1],[0,1,1,0,1,0,0,1,1]])
labels_float = tf.constant([[1.,0.,1.,0.,1.,1.,0.,0.,1.],[0.,1.,1.,0.,1.,0.,0.,1.,1.]])
labels2 = tf.con... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.