text
stringlengths
3.07k
12.6k
""" Interface for Tar format """ # disable import outside top-level warnings # pylint: disable=C0415 # disable spelling warnings # pylint: disable=C0401 import tarfile from collections.abc import Mapping from contextlib import contextmanager from os import listdir from os.path import exists, splitext, basename from i...
#!/bin/env python #Header from pyfiglet import Figlet f = Figlet(font='slant') print('Script Created by : ') print(f.renderText('gaurav')) sound = int(input("Do you want sound : 1 for yes , 2 for no : ")) sound = 0 if sound == 2 else 1 print('****************************************************') if sound : print(...
from dataclasses import dataclass, field from datetime import datetime from notion.client import NotionClient from notion.collection import CollectionView, CollectionRowBlock, NotionDate from utils import MetaSingleton from typing import Dict, List, Set import logging logger = logging.getLogger(__name__) def check_a...
from urllib import parse from celery import shared_task, states from celery.canvas import group from django.conf import settings from django.db import transaction from extras.tasks import CurrentUserTaskMixin from registry.models import CatalougeService, WebFeatureService, WebMapService from registry.models.metadata i...
from ninja import NinjaAPI,Form,Router from ninja import Schema, Path import datetime from django.contrib.auth.models import User router= Router(tags=["app_api"]) @router.get("/add") def add(request,a:int,b:int,c:int): return {"resutlt": a+b} #相同接口多种方法 @router.api_operation(["GET","POST","DELETE"],"/user/{user_...
# Copyright 2014, 2015 SAP SE. # # 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, #...
## /elf/search_by_text.py # Built-ins import os import warnings import datetime import threading # Package import __init__ from elf import utils from elf.webio import get_soup from elf.webio import download_page from elf.parsing import parsetable warnings.warn('EDGAR search-by-text can only search 3 years back. Use...
import typing from pathlib import Path from UniGrammarRuntime.backends.python.parglare import ParglareParserFactory, toolGitRepo from UniGrammarRuntime.DSLMetadata import DSLMetadata from UniGrammarRuntime.grammarClasses import GLR, LR from UniGrammarRuntime.ParserBundle import InMemoryGrammarResources from UniGrammar...
#!/usr/bin/env python import sys from prose2poetry.corpora import ProseCorpus, GutenbergCouplets, PFCouplets, pairs from prose2poetry.couplet_score import CoupletScorer from prose2poetry.generators import MarkovChainGenerator, LSTMModel1 from prose2poetry.vector_models import FasttextModel import argparse import numpy...
# NEON AI (TM) SOFTWARE, Software Development Kit & Application Framework # All trademark and other rights reserved by their respective owners # Copyright 2008-2022 Neongecko.com Inc. # Contributors: <NAME>, <NAME>, <NAME>, <NAME>, # <NAME>, <NAME>, <NAME>, <NAME> # BSD-3 License # Redistribution and use in source and ...
# Switching to python... sorry. Haskell was too much to handle. import re import copy # 11573 for A too low # 17734 for A too low # 17738 for A was right # 17739 for A too high def parse(text): battle = [] faction = None counter = dict() for line in text.splitlines(): if line == "": continue if line =...
from functools import lru_cache from django.core.exceptions import ObjectDoesNotExist from django.db import models from django.db.models.constants import LOOKUP_SEP from treebeard.mp_tree import MP_Node from wagtail.core import hooks from wagtail.core.models import Page from .field_adapters import adapter_registry fr...
# SPDX-License-Identifier: MIT # Copyright (c) 2021 anvilistas from uuid import UUID, uuid4 import anvil.users from anvil.tables import app_tables, in_transaction, order_by from anvil_extras import logging from ..historic.events import Change, Creation from ..historic.exceptions import ( AuthorizationError, ...
#!/user/bin/env python """Python binary to train COVID-19 epidemic model with single CPU.""" from typing import Text from absl import app from absl import flags import io_utils import json import logging import numpy as np import os import resample # pylint: disable=import-not-at-top os.environ["TF_CPP_MIN_LOG_LEVEL"] ...
#!/usr/bin/env python3 #-*- coding: utf-8 -*- # Copyright 2017, National University of Ireland and The James Hutton Insitute # Author: <NAME> # # This code is part of the riboSeed package, and is governed by its licence. # Please see the LICENSE file that should have been included as part of # this package. import pkg...
import numpy as np import pandas as pd import matplotlib.pyplot as plt from scipy.io import loadmat #Be careful with the file path! data = loadmat('data/hw4.mat') from sklearn.preprocessing import OneHotEncoder encoder = OneHotEncoder(sparse=False, categories='auto') y_onehot = encoder.fit_transform(data['y']) def s...
""" Module about Pauli (and I) matrices. """ import numpy as np from numpy import zeros_like from scipy.linalg import svd s0 = np.array([[1, 0], [0, 1]]) s1 = np.array([[0, 1], [1, 0]]) s2 = np.array([[0, -1j], [1j, 0]]) s3 = np.array([[1, 0], [0, -1]]) s0T = s0.T s1T = s1.T s2T = s2.T s3T = s3.T pauli_dict = {0: s...
import json import torch import pandas as pd import numpy as np from pathlib import Path from itertools import repeat from collections import OrderedDict from PIL import Image from scipy.special import softmax def stat_cuda(msg): print('--', msg) print('allocated: %dM, max allocated: %dM, cached: %dM, max cac...
import json import re import subprocess import yaml import typer from pathlib import Path from typing import Optional, Dict, List from textwrap import dedent from .console import console def create_initial_env_specs( env_name: str, channel: Optional[str] = None, packages: Optional[List[str]] = None ) -> Dict: ...
import os import requests import json from rich import print from rich.console import Console import webbrowser from tqdm import tqdm def clear(): if os.name == 'nt': os.system("cls") else: os.system("clear") def strip(x): return x.strip() def manually_filter(publications): con...
# -*- coding: utf-8 -*- import os import base64 import random import string import functools from datetime import datetime, timedelta import jinja2 import jsonschema from pony.orm import db_session from werkzeug.exceptions import HTTPException, Forbidden, UnprocessableEntity from flask import request, current_app, js...
#!/usr/bin/python3 """ Get prior probabilities for event type and language links. Query Wikidata using SPARQL. 1) Prior probability of event type P(Et): # events of type T / total # of events 2) Prior probability of lanugage link P(Ll): # ll to language L / total # of language links to all language Also need: ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import argparse, os, glob, tqdm, zipfile, webrtcvad import soundfile as sf from get_vad import * class segmentor(): def __init__(self,merge_margin,cut_margin,res_path,vad_setting=0): self.merge_margin=merge_margin self.cut_margin=cut_margin s...
import weakref from AppKit import * from vanillaBase import VanillaBaseObject, _breakCycles from nsSubclasses import getNSSubclass _edgeMap = { "left" : NSMinXEdge, "right" : NSMaxXEdge, "top" : NSMinYEdge, "bottom" : NSMaxYEdge } try: NSPopoverBehaviorApplicationDefined except NameError: NSPo...
import atexit import copy import json import logging import os import select import signal import subprocess import sys import threading DEFAULT_OPTIONS = { 'formatid': 'gen7randombattle', 'p1': { 'name': 'p1', }, 'p2': { 'name': 'p2', }, } def _timeout(): sys.stderr.write('Timeout occurred while...
import os from os.path import join as pjoin, abspath import grp import pwd import sys from distutils.util import spawn from distutils.version import StrictVersion, LooseVersion from distutils.dir_util import mkpath from distutils.file_util import copy_file import distutils.core from tempfile import mkdtemp from .tmpdi...
import math import os # os.environ['TL_BACKEND'] = 'torch' # os.environ['CUDA_VISIBLE_DEVICES'] = '5' from gammagl.utils import add_self_loops, calc_gcn_norm, mask_to_index, remove_self_loops import argparse from tqdm import tqdm from gammagl.datasets import Planetoid import tensorlayerx as tlx from tensorlayerx.mod...
import torch import torch.nn as nn from torch.autograd import Variable class ConvLSTMCell(nn.Module): def __init__(self, input_channels, hidden_channels, kernel_size): super(ConvLSTMCell, self).__init__() assert hidden_channels % 2 == 0 self.input_channels = input_channels self.h...
# type: ignore import ast import functools import re from copy import deepcopy from inspect import stack from pathlib import Path import executing import mat2py.config from mat2py.common.backends import numpy as np from mat2py.common.logger import logger from mat2py.common.utils import Singleton from .array import M...
# kim/roles.py # Copyright (C) 2014-2015 the Kim authors and contributors # <see AUTHORS file> # # This module is part of Kim and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php from kim.exception import RoleError class Role(set): """Roles are a fundamental feature of Kim....
from django import forms from django.core.files.images import get_image_dimensions from django.core.validators import MinValueValidator, MaxValueValidator from taggit.forms import TagField from .models import UserProfile class SignupForm(forms.Form): first_name = forms.CharField( widget=forms.TextInput(attrs={'pl...
""" Object localization with ResNet50 architecture. Uses pre-trained features from imagenet (transfer learning). Input is a color image. The network has two outputs, object class ([1, 0] for person and [0, 1] for background) and its bounding box coordinates (xmin, xmax, ymin, ymax). Class output (two neurons) uses bin...
from itertools import combinations rows = 'ABCDEFGHI' cols = '123456789' digits = '123456789' assignments = [] def assign_value(values, box, value): """ Please use this function to update your values dictionary! Assigns a value to a given box. If it updates the board record it. """ ...
'''connector for Simio, dependent on python for .net (pythonnet) ''' import os import sys import clr # @UnresolvedImport # TODO:: do some auto discovery here analogue to netlogo? sys.path.append('C:/Program Files (x86)/Simio') clr.AddReference('SimioDLL') clr.AddReference('SimioAPI') import SimioAPI # @Unresolved...
import mxnet as mx import net_symbols as syms def create_block(data, name, num_filter, kernel, pad=0, stride=1, dilate=1, workspace=512, use_global_stats=True, lr_type="alex"): res = syms.conv(data=data, name="res" + name, num_filter=num_filter, pad=pad, kernel=kernel, stride=stride, ...
import threading from peewee import * from playhouse.kv import JSONKeyStore from playhouse.kv import KeyStore from playhouse.kv import PickledKeyStore from playhouse.tests.base import PeeweeTestCase from playhouse.tests.base import skip_if class TestKeyStore(PeeweeTestCase): def setUp(self): super(TestKe...
import numpy as np from os import listdir from matplotlib import pyplot as plt def apply_spectrum(data, pca, numinput=256, power=1.0): colored = data.dot(np.diag(np.power(pca.sValues[:numinput], power))) return colored/colored.std() def get_params_and_errors(net, toy, nunits=256, folder='.', ...
#!/usr/bin/python # -*- encoding: utf-8 -*- ''' @Time : 2021/07/16 14:44:21 @Author : Camille @Version : 1.0 ''' import sys import os sys.path.append(os.getcwd()) import json import time from threading import Thread, Event from scripts.prettyCode.prettyPrint import PrettyPrint from scripts.windows.windows im...
import tensorflow as tf import numpy as np from imgaug import augmenters as iaa import matplotlib.pyplot as plt def plot_sample_images(images, labels, num_classes, samples_per_class, mean=None, std=None, dtype='uint8'): print(images[0].shape) if mean is not None and std is not None: images = images * ...
"""Pytorch implementation of Class-Balanced-Loss Reference: "Class-Balanced Loss Based on Effective Number of Samples" Authors: <NAME> and <NAME> and <NAME> and <NAME> and <NAME> https://arxiv.org/abs/1901.05555, CVPR'19. """ import numpy as np imp...
import csv import requests import time import re from bs4 import BeautifulSoup def crawl_content(url): http_header = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36', 'Accept': 'text/html,application/xhtml+xml,applicat...
ANSIBLE_METADATA = { 'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community' } DOCUMENTATION = ''' --- module: tetration_scope_query short_description: Search the scope api for scope id's or details version_added: '2.9' description: - "Search the Scope API by a variety of metho...
# -*- encoding:utf8 -*- import sys from collections import namedtuple # b:begin, m: middle, e: end LR = namedtuple('LR', 'l l_tag r r_tag b m e') class BaseTemplateMatcher: def generate(self, token): raise NotImplementedError class EojeolTemplateMatcher(BaseTemplateMatcher): def __init__(self, dictio...
import numpy as np import tensorflow as tf from sklearn.ensemble import AdaBoostClassifier from sklearn.ensemble import RandomForestClassifier, VotingClassifier from sklearn.linear_model import LogisticRegression from sklearn.svm import SVC __author__ = "<NAME>" __version__ = "1.0" __email__ = "<EMAIL>" class Ensemb...
""" File : deploy_flask.py Author : <NAME> Date Created : 03-07-2020 Date Modified : 29-08-2020 """ import os from getpass import getuser import subprocess class Deploy: """ Class to manage the major deployment tasks """ def __init__(self, project_...
# -*- coding: utf-8 -*- import networkx as nx import numpy as np from random import choice, choices, sample from torch.optim import SGD, Adam from model.skipgram import SkipGram from copy import deepcopy from gensim.models import word2vec from concurrent.futures import ProcessPoolExecutor, as_completed def random_wal...
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: # Copyright 2014-2021 <NAME> (The Compiler) <<EMAIL>> # # This file is part of qutebrowser. # # qutebrowser is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, e...
import os import json import enum import uproot import flatbuffers import dask.delayed import pyarrow as pa from pyarrow import csv from os import listdir from os.path import isfile, join from dask.distributed import Client from skyhookdmdriver import FB_Meta class SkyFormatType(enum.Enum): SFT_FLATBUF_FLEX_ROW ...
from __future__ import absolute_import, division, print_function, unicode_literals import matplotlib.pyplot as plt import matplotlib.cm as cm # not compatible with matplotlib-2.2.3, matplotlib-2.0.2 required import math import numpy as np import time import threading import ast from six import iteritems, itervalues de...
#!/usr/bin/env python """ vlanhost.py: Host subclass that uses a VLAN tag for the default interface. Dependencies: This class depends on the "vlan" package $ sudo apt-get install vlan Usage (example uses VLAN ID=1000): From the command line: sudo mn --custom vlanhost.py --host vlan,vlan=1000 ...
#!/usr/bin/env python # # Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file # except in compliance with the License. A copy of the License is located at # # http://aws.amazon.com/apache2.0/ # # or in...
import sys import code import re from typing import Callable from contextlib import redirect_stdout, redirect_stderr from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * class LineEdit(QLineEdit): """QLIneEdit with a history buffer for recalling previous lines. I also accept ta...
import torch from torch import nn class BatchNormConv1d(nn.Module): r"""A wrapper for Conv1d with BatchNorm. It sets the activation function between Conv and BatchNorm layers. BatchNorm layer is initialized with the TF default values for momentum and eps. Args: in_channels: size of each input...
# <NAME> - last edit: 4/23/2020 @3PM import pygame, sys, random, math, time import constants from buttons import draw_rect from buttons import button_hover from buttons import button_press from buttons import text # Randomly generates obstacles - draws them red and returns the coordinates of them def rand...
from __future__ import annotations import enum import logging import ssl from collections.abc import Sequence from dataclasses import dataclass, field from datetime import datetime from pathlib import Path from types import TracebackType from typing import Any import aiohttp from dateutil.parser import parse from neu...
import torch import argparse import torchvision import torch.nn as nn from torch.autograd import Function from model.base_model import Base_Model class CIBHash(Base_Model): def __init__(self, hparams): super().__init__(hparams=hparams) def define_parameters(self): self.vgg = torc...
from enum import Enum from typing import Tuple, Union import geopandas as gpd import triangle from .common import ( FloatArray, IntArray, check_geodataframe, invalid_option, repr, separate, to_ugrid, ) from .triangle_geometry import collect_geometry, polygon_holes class DelaunayAlgorithm...
""" ONS Address Index - Probabilistic Parser ======================================== This file defines the calling mechanism for a trained probabilistic parser model. It also implements a simple test. Note that the results are model dependent, so the assertions will fail if a new model is trained. Requirements ----...
import numpy as np import cv2 import os from keras.layers import Conv2D from keras.layers.pooling import MaxPooling2D from keras.layers.core import Dropout, Flatten, Dense from keras.optimizers import Adam from sklearn.model_selection import train_test_split import matplotlib.pylab as plt from keras.preprocessing.image...
import re from discord import Member from typing import Union, List, Dict, Pattern # Type hints """ Constants split into classes. Admin roles have extra information for rank comparison. Channels are combined into lists in the Section class. """ class RePattern: RP_NAME = re.compile("^[A-Z][a-z]+_[A-Z]{1,2}([a-z...
# -*- coding: utf-8 -*- """ Support for using :mod:`BTrees` with ZODB. This module is primarily concerned with making BTrees even more efficient, especially at large scale and high concurrency. .. rubric:: family64LargeBuckets This is a BTree family that's useful for high-concurrency or large applications by increas...
def get_2away_pairs(local_index_to_kmer, k): """local_index_to_kmer is a dictionary where the value is a kmer portion, and the key is the index of the original kmer in which the kmer portion is found. get_2away_pairs returns a list of pairs where each pair of indices corresponds to a pair of kmers different in exactl...
#!/usr/bin/python # Copyright (c) 2014 <NAME> # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. ''' Run this script from the root of the repository to update all translations from transifex. It will do the following automatically: -...
import os import os.path import copy import hashlib import errno import numpy as np from numpy.testing import assert_array_almost_equal def check_integrity(fpath, md5): if not os.path.isfile(fpath): return False md5o = hashlib.md5() with open(fpath, 'rb') as f: # read in 1MB chunks ...
# MADE ONLY FOR EDUCATIONAL PURPOSES, DO NOT USE AS SCRAPING DATA MAY BE ILLEGAL! # The program works fine however headline() is still being implemeted. # make it so it can grab more than 10 request by going to page 2 from urllib.request import urlopen, Request from urllib.parse import urlencode, quote_plus from bs4 im...
#!/usr/bin/env python import numpy as np import scipy.special _POISSON = .25 _N_PROCS = 4 def get_flexure_parameter(h, E, n_dim, gamma_mantle=33000.): """ Calculate the flexure parameter based on some physical constants. *h* is the Effective elastic thickness of Earth's crust (m), *E* is Young's Mo...
from flask import redirect, url_for, request, session , jsonify , current_app from model import User , UserSchema # from app.auth.forms import LoginForm, RegistrationForm # from app.model import UserSchema from app import app, db, jwt from config import UPLOAD_FOLDER from flask_jwt_extended import jwt_required, get_jwt...
import io import time import dh.utils import dh.image import dh.network class CameraServer(dh.network.SocketServer): # command bytes COMMAND_PING = 0x0 COMMAND_GET = 0x1 COMMAND_SET = 0x2 COMMAND_CAPTURE = 0x3 # response bytes corresponding to the commands are identical to the com...
# Copyright (c) 2015 Uber Technologies, Inc. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publ...
# # The ElementTree toolkit is # # Copyright (c) 1999-2007 by <NAME> # 2008-2010 <NAME> <<EMAIL>> # # By obtaining, using, and/or copying this software and/or its # associated documentation, you agree that you have read, understood, # and will comply with the following terms and conditions: # # Permission...
import py from pypy.lang.smalltalk import squeakimage from pypy.lang.smalltalk.squeakimage import chrs2int from pypy.lang.smalltalk import objspace space = objspace.ObjSpace() # ----- helpers ---------------------------------------------- def ints2str(*ints): import struct return struct.pack(">" + "i" * len(...
""" Pony-ORM database backend. """ from fatartifacts.database import base from datetime import datetime from pony import orm from typing import * import threading def declare_entities(db): class Location(db.Entity): name = orm.Optional(str) parent = orm.Optional('Location', reverse='children') childre...
import json from typing import Union from flask import Blueprint, request from parse import parse from anubis.models import AssignmentTest, Submission, SubmissionTestResult, db from anubis.utils.http import success_response from anubis.utils.data import MYSQL_TEXT_MAX_LENGTH from anubis.utils.http.decorators import j...
import random from rest_framework import serializers from .payments import flutter_wave from django.contrib.auth.models import update_last_login from .models import Wallet, TransactionHistory from django.contrib.auth import get_user_model, authenticate from rest_framework_jwt.settings import api_settings from django.sh...
class Student: def __init__(self, student_id, fname, lname, enroll_date): self.student_id = student_id self.fname = fname self.lname = lname self.enroll_date = enroll_date class Course: def __init__(self, course_id, title, cred_hr): self.course_id = course_id ...
#test_model.py from pathlib import Path import sys root_dir = Path(Path.cwd()).parent sys.path.append(str(root_dir))#+'/src/') import pytest from src.sloth.model import Model from src.sloth.problem import Problem from src.sloth.simulation import Simulation from src.sloth.core.equation_operators import * from src....
# Copyright 2021 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to...
# Non-local block using embedded gaussian # Code from # https://github.com/AlexHex7/Non-local_pytorch/blob/master/Non-Local_pytorch_0.3.1/lib/non_local_embedded_gaussian.py import torch from torch import nn from torch.nn import functional as F class _NonLocalBlockND(nn.Module): def __init__(self, in_channels, int...
import torch import numpy as np import os import sys # sys.path.append(os.path.dirname(os.path.abspath(__file__))) # noqa: E402 # from utils.reranking import re_ranking def euclidean_distance(qf, gf): m = qf.shape[0] n = gf.shape[0] dist_mat = torch.pow(qf, 2).sum(dim=1, keepdim=True).expand(m, n) + \ ...
# Copyright 2020 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
# Copyright 2018 The Magenta 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in ...
# #!/usr/bin/env python # -*- coding: utf-8 -*- # <HTTPretty - HTTP client mock for Python> # Copyright (C) <2011-2013> <NAME> <<EMAIL>> # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation # files (the "Software"), to deal in the Software wi...
# This file is part of Indico. # Copyright (C) 2002 - 2021 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from sqlalchemy.dialects.postgresql import JSONB from sqlalchemy.event import listens_for from indico.cor...
import argparse import os import random import shutil import time import warnings import torch import torch.nn as nn import torch.nn.functional as F import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.distributed as dist import torch.optim import torch.multiprocessing as mp import torch.utils.da...
import cv2 import numpy as np import os # from sys import argv import time # main direction (program) def get_parent_dir(n=1): """returns the n-th parent directory of the current working directory""" current_path = os.path.dirname(os.path.abspath(__file__)) for _ in range(n): current_path = os...
# coding: utf-8 # In[5]: import pickle import tensorflow as tf import numpy as np import tf_util import gym import load_policy import torch from torch.autograd import Variable import torch.nn as nn import torch.nn.functional as F import matplotlib.pyplot as plt from torch.optim.lr_scheduler import StepLR class CN...
# Copyright (c) 2015, Baidu.com, Inc. All Rights Reserved # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. #!/usr/bin/env pythons class CONF: def __init__(self): self.TABLE_NAME = 'table_name' self.TABLET_NUM = 'tablet_number' ...
''' Python GL Wrapper for opengl, gives cleaner access to the opengl api. Aims to be similar PyOpenGL where it makes sense. ''' import ctypes as ct from ed2d.opengl import gl from ed2d import typeutils def glGetInteger(pname): # because this function can return differant amounts of data # we need to work a...
""" Copyright 2020, <NAME> <<EMAIL>> This file is the main driver of rrap, a bionformatics pipeline that runs read recruitment and rpkm visualization given reference genome and metagenome directories. """ import os import argparse import subprocess from pathlib import Path from rrap import concatenator from rra...
import pymongo import csvHandler as fiHandl import pandas as pd import numpy as np from pymongo import MongoClient import pandasCleaning as pdClean import hashlib import pickle from datetime import datetime # To setup a local db for testing use # docker run -d -p 27017-27019:27017-27019 --name mongodb mongo # To stop ...
# Copyright 2017 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...
from typing import Set, List, Dict, Tuple import requests import datetime as dt from bs4 import BeautifulSoup as bs import re import calendar from selenium.common.exceptions import TimeoutException import config as conf import pickle as pk import os.path from selenium import webdriver from selenium.webdriver.firefox....
#!/usr/bin/env python from numpy import ceil try: import pulp except Exception: pulp = None from mapel.voting.objects.ApprovalElection import ApprovalElection from math import ceil import itertools from collections import defaultdict def count_number_of_cohesive_groups_brute(election: ApprovalElection, l:...
# # 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 us...
# coding=utf-8 # 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 ...
# -*- coding: utf-8 -*- ### Python imports import pathlib ### Third Party imports import numpy as np import pandas as pd import pytest ### Project imports from t4.formats import FormatRegistry from t4.util import QuiltException ### Constants ### Code def test_buggy_parquet(): """ Test that T4 avoids cras...
#!/usr/bin/env python3 """ ** Allows you to format the text color. ** ------------------------------------------ Specifically allows you to choose from a reduced list, the highlighting color and the text color. """ import colorama from context_printer.memory import get_lifo colorama.init() # for windows def _st...
""" Copyright 2019 <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, software distribut...
# 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 from ... import _utilities, _tables from...
""" PodmanList - command ``/usr/bin/podman (images|ps)`` ==================================================== Parse the output of command "podman_list_images" and "podman_list_containers", which have very similar formats. The header line is parsed and used as the names for the remaining columns. All fields in both he...