text stringlengths 3.07k 22.1k |
|---|
#!/usr/bin/env python
from __future__ import with_statement
from suds.plugin import MessagePlugin
from lxml import etree
from suds.bindings.binding import envns
from suds.wsse import wsuns, dsns, wssens
from libxml2_wrapper import LibXML2ParsedDocument
from xmlsec_wrapper import XmlSecSignatureContext, init_xmlsec, de... |
#!/usr/bin/python3
"""
AUTHOR: <NAME> - <EMAIL>
"""
# Imports
import json
import maxminddb
import redis
import re
import random
import io
from const import META, PORTMAP
from argparse import ArgumentParser, RawDescriptionHelpFormatter
from sys import exit
from time import localtime, sleep, strftime
from os import ge... |
# Author: <NAME>
# Datetime: 2021/9/14
# Copyright belongs to the author.
# Please indicate the source for reprinting.
import sys
import webbrowser
import time
from typing import List
import tkinter
from tkinter import ttk
from tkinter.scrolledtext import ScrolledText
from qgui.manager import BLACK, FONT
from qgui.... |
import os
import warnings
import torch.backends.cudnn as cudnn
warnings.filterwarnings("ignore")
from torch.utils.data import DataLoader
from decaps import CapsuleNet
from torch.optim import Adam
import numpy as np
from config import options
import torch
import torch.nn.functional as F
from utils.eval_utils import bina... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Take a list of genome positions and return the dinucleotides around it.
For each position, will generate a list of + strand dinucleotides and - strand
dinucleotides.
Created: 2017-07-27 12:02
Last modified: 2017-10-18 00:17
"""
from __future__ import print_fun... |
#!/usr/bin/env python3
import base64
import os
import sys
import datetime
import dotenv
import requests
from flask import Flask, render_template, session, redirect, url_for, request, flash
sys.path.append(os.path.abspath('src'))
from utils import utc_to_local
from client import Client
import runner
os.chdir(os.pat... |
# coding = UTF-8
import time
import re
import js2py
import requests
import json
import KuGou
from KuGou.Requirement import Header
class MusicList(object):
"""从酷狗获取要查询的歌曲的结果列表"""
def __init__(self, MusicName: str) -> None:
"""初始化该类:
检查参数正确性,创建时间戳,初始化签名和数据容器,初始化JS命名空间(初始化命名空间并添加签名创建函数)。
... |
#!/usr/bin/env python
# coding: utf-8
"""script that generates source data csvs for searchstims experiment figures"""
from argparse import ArgumentParser
from collections import defaultdict
from pathlib import Path
import pandas as pd
import pyprojroot
import searchnets
def main(results_gz_root,
source_dat... |
import os
import datetime
import gym
import numpy as np
import matplotlib.pyplot as plt
from es import CMAES
import pandas as pd
import string
def sigmoid(x):
return 1 / (1 + np.exp(-x))
class Agent:
def __init__(self, x, y, layer1_nodes, layer2_nodes):
self.input = np.zeros(x, dtype=np.float128)
... |
""" This file contains quantum code in support of Shor's Algorithm
"""
""" Imports from qiskit"""
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
import sys
import math
import numpy as np
""" ********* QFT Functions *** """
""" Function to create QFT """
def create_QFT(circuit,up_reg,n,with_sw... |
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Name: sorting.py
# Purpose: Music21 class for sorting
#
# Authors: <NAME>
#
# Copyright: Copyright © 2014-2015 <NAME> and the music21
# Project
# License: BSD, see license.tx... |
"""
Some notes:
HDI: Highest Density Interval.
ROPE: Region of Practical Equivalence.
"""
import numpy as np
from matplotlib import pyplot as plt
def ch01_01():
"""
"""
thetas = np.linspace(0, 1, 1001)
print(thetas)
likelihood = lambda r: thetas if r else (1 - thetas)
def posterio... |
import sys
from Quartz import *
import Utilities
import array
def doColorSpaceFillAndStroke(context):
theColorSpace = Utilities.getTheCalibratedRGBColorSpace()
opaqueRed = ( 0.663, 0.0, 0.031, 1.0 ) # red,green,blue,alpha
aBlue = ( 0.482, 0.62, 0.871, 1.0 ) # red,green,blue,alpha
# Set the fill ... |
# -*- coding: utf-8 -*-
from datetime import date
from flask import render_template, redirect, url_for, flash, request, make_response
from werkzeug.urls import url_unquote
from fibra import app
from fibra.models import db, Customer, Contact, Invoice, Payment, STATES
from fibra.forms import (
CustomerForm, Co... |
import tkinter as tk
import psycopg2
import pickle
import time, calendar, requests, datetime
try:
conn = psycopg2.connect(database="postgres", user="postgres", password="<PASSWORD>", host="10.10.100.120")
print("connected")
except:
print ("I am unable to connect to the database")
motions = []
stationMotions = {}... |
# Importing all required libraries for the code to function
import tkinter
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg)
from matplotlib import pyplot as plt, animation
from mpl_toolkits import mplot3d
from stl import mesh
import numpy as np
import serial
from serial.tools import list_ports
import t... |
import logging
import os
import shutil
from os import path
import numpy as np
import nvtabular as nvt
import pandas as pd
from nvtabular import ops
import merlin.io
# Get dataframe library - cudf or pandas
from merlin.core.dispatch import get_lib
from merlin.core.utils import download_file
df_lib = get_lib()
loggi... |
from math import floor
import scipy.io as sio
from bokeh.plotting import figure, show, output_file, save, ColumnDataSource
from bokeh.models import HoverTool, CrosshairTool, PanTool, WheelZoomTool, ResetTool, SaveTool, CustomJS
from bokeh.models.widgets import Button
from bokeh.layouts import widgetbox, row, column, ... |
#basic components: Embedding Layer, Scaled Dot-Product Attention, Dense Layer
import numpy as np
import torch.nn.functional as F
from torch import nn
import torch
class Embed(nn.Module):
def __init__(self, length, emb_dim,
embeddings=None, trainable=False, dropout=.1):
super(Embed, self... |
import typing
from pathlib import PurePath
from typing import Optional, List, Union, Tuple, Dict
from lab.internal.logger.store.artifacts import Artifact
from lab.internal.logger.store.indicators import Indicator
from lab.internal.util.colors import StyleCode
from .destinations.factory import create_destination
from .... |
# Copyright 2021 UW-IT, University of Washington
# SPDX-License-Identifier: Apache-2.0
"""
Generates the booleans to determine card visibility,
based on dates in either the current, next, or previous term.
https://docs.google.com/document/d/14q26auOLPU34KFtkUmC_bkoo5dAwegRzgpwmZEQMhaU
"""
import logging
import traceb... |
import re
from datetime import datetime
from typing import List, Optional, Match, AnyStr, Dict
import logging
import pandas as pd
from PyPDF2 import PdfFileReader
from nltk.tokenize import word_tokenize
from pandas import DataFrame
from avicena.models.MergeAddress import MergeAddress
from avicena.models.RevenueRate im... |
#!/usr/bin/env python3
import sqlite3
import argparse
###############################################################################
#
# Super simple (and probably not very efficient) way to query sqlite file and
# produce a python list of dictionaries with the result of that query
#
################################... |
import mysql.connector
from asyncore import read
from PyQt5 import uic
from PyQt5 import QtWidgets
from numpy import save
from reportlab.pdfgen import canvas
c = 0
# Conectando com o banco de dados
con = mysql.connector.connect(
host='localhost', database='cadastro_estoque', user='andre2', password='<PASSWORD>')... |
import sqlite3
from typing import List, Iterable, Any
from ticket.models.user import User
# TODO: when we have a couple more errors, put in seperate file
class UserAssignViolationError(Exception):
pass
class TicketNotFoundError(Exception):
pass
class Ticket:
ticket_id: int= 0
user_id: int = 0
tit... |
"""
Derived from keras-yolo3 train.py (https://github.com/qqwweee/keras-yolo3),
with additions from https://github.com/AntonMu/TrainYourOwnYOLO.
"""
import os
import sys
import argparse
import pickle
import numpy as np
import keras.backend as K
from keras.layers import Input, Lambda
from keras.models import Model
fr... |
#!/usr/bin/env python
'''
Created by Seria at 02/11/2018 3:38 PM
Email: <EMAIL>
_ooOoo_
o888888888o
o88`_ . _`88o
(| 0 0 |)
O \ 。 / O
_____/`-----‘\_____
.’ \|| _ _ ||/ `.
| _ |... |
'''
original implementation credit: https://github.com/openai/baselines
heavily adapted to suit our needs.
'''
import argparse
import tempfile
import os.path as osp
import gym
import logging
from tqdm import tqdm
import tensorflow as tf
import numpy as np
import os
import sys
import glob
file_path = os.path.dirnam... |
# coding: utf-8
import cv2
import os,sys
import time
import os.path
import math
sys.path.insert(0, '../facealign')
sys.path.insert(0, '../util')
from fileutil import *
from MtcnnPycaffe import MtcnnDetector, draw_and_show
from alignment import *
from logfile import *
import json
import argparse
def IoU(bbox1, bbo... |
import asyncio
import argparse
import http
import json
import os
import time
import subprocess
import sys
import websockets
def check(rm_hostname):
try:
model = subprocess.run(
[
"ssh",
"-o",
"ConnectTimeout=2",
rm_hostname,
... |
'''This module extends PTPDevice for Sony devices.
Use it in a master module that determines the vendor and automatically uses its
extension. This is why inheritance is not explicit.
'''
from contextlib import contextmanager
from construct import Container, Struct, Range, Computed, Enum, Array, PrefixedArray, Pass, Ex... |
import functools
import itertools
from typing import Callable, Dict, Iterable, List, Union
from omegaconf import DictConfig, MissingMandatoryValue, OmegaConf
class InvalidArgumentError(Exception):
"""Invalid argument on command line"""
pass
class OptionHandler:
"""Handling an option"""
arg: List[... |
import socket
import select
import time
import datetime
import random
from collections import deque, namedtuple
BOARD_LENGTH = 32
OFFSET = 16
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
DIRECTIONS = namedtuple('DIRECTIONS',
['Up', 'Down', 'Left', 'Right'])(0, 1, 2, 3)
SNAKE... |
#! /usr/bin/env python3
"""
Stein PPO: Sample-efficient Policy Optimization with Stein Control Variate
Motivated by the Stein’s identity, Stein PPO extends the previous
control variate methods used in REINFORCE and advantage actor-critic
by introducing more general action-dependent baseline functions.
Details see th... |
import multiprocessing as mp
import os
import re
import string
from collections import OrderedDict
from typing import Callable, List, Optional, Union
import spacy
import vaex
from pandas.core.frame import DataFrame
from pandas.core.series import Series
from textacy.preprocessing import make_pipeline, normalize, remove... |
import datetime
import hashlib
import logging
import os
import tarfile
from azure.storage.blob import BlockBlobService
from boto.s3.connection import S3Connection
from boto.s3.bucket import Bucket
from boto.s3.key import Key
import dj_database_url
import django # Provides django.setup()
from django.apps import apps a... |
import bisect
import math
import operator
from datetime import timedelta
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import matplotlib.cm as cm
import matplotlib.font_manager as font_manager
import matplotlib.patheff... |
"""
game.py
Game class which contains the player, target, and all the walls.
"""
from math import cos, sin
import matplotlib.collections as mc
import pylab as plt
from numpy import asarray, pi
from config import Config
from environment.robot import Robot
from utils.dictionary import *
from utils.myutils import load_... |
# Simple single neuron network to model a regression task
from __future__ import print_function
import numpy as np
#np.random.seed(1337) # for reproducibility
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation
from keras.optimizers import SGD,... |
import types
import sqlite3
from collections import namedtuple
from functools import reduce
import numpy
from glue.lal import LIGOTimeGPS
from glue.ligolw import ligolw, lsctables, table, ilwd
from glue.ligolw.utils import process
def assign_id(row, i):
row.simulation_id = ilwd.ilwdchar("sim_inspiral_table:sim_... |
import requests
import pandas as pd
import pandas.io.json
import json
import ast
city_name = '深圳市'
# city_name = '成都市'
# city_name = '北京市'
# anyone using this code needs to get their own keys from amap.com
api_key_web_service = open('../api_key_web_service.txt', encoding='utf-8').read() # Web Service (Web服务)
api_key_... |
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, Http404
from django.core.exceptions import PermissionDenied
from django.db import transaction
from django.db.models import Count, Sum, F, Func
from datetime import date... |
from flask import Flask, render_template, jsonify, request, session, Blueprint, redirect, flash
from flask_restful import reqparse, abort, Api, Resource
from flask_login import login_required, logout_user, current_user, login_user, LoginManager
from google.cloud import datastore
import datetime
from flask_admin import ... |
# GPLv3 License
#
# Copyright (C) 2020 Ubisoft
#
# This program 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, either version 2 of the License, or
# (at your option) any later version.
#
# This program is dis... |
"""
File: sample_generator.py
Author: Nrupatunga
Email: <EMAIL>
Github: https://github.com/nrupatunga
Description: Generating samples from single frame
"""
import sys
import cv2
import numpy as np
from loguru import logger
try:
from goturn.helper.BoundingBox import BoundingBox
from goturn.helper.image_proc i... |
"""System utilities."""
import socket
import sys
import os
import csv
import yaml
import torch
import torchvision
import random
import numpy as np
import datetime
import hydra
from omegaconf import OmegaConf, open_dict
import logging
def system_startup(process_idx, local_group_size, cfg):
"""Decide and prin... |
import os
import sys
from keystone import *
sys.path.append("./../../util/script/")
import shellcode
def gen_oepinit_code32():
ks = Ks(KS_ARCH_X86, KS_MODE_32)
code_str = f"""
// for relative address, get the base of addr
push ebx;
call getip;
lea ebx, [eax-6];
// get the ... |
from morle.utils.files import full_path
import morle.shared as shared
from collections import defaultdict
import hfst
import os.path
import sys
import tqdm
import types
def seq_to_transducer(alignment, weight=0.0, type=None, alphabet=None):
if type is None:
type=shared.config['FST'].getint('transducer_typ... |
"""
Modified from https://github.com/microsoft/Swin-Transformer/blob/main/main.py
"""
import os
import time
import argparse
import datetime
import numpy as np
import oneflow as flow
import oneflow.backends.cudnn as cudnn
from flowvision.loss.cross_entropy import (
LabelSmoothingCrossEntropy,
SoftTargetCrossEn... |
"""Tests for the logix_driver.py file.
The Logix Driver is beholden to the CIPDriver interface. Only tests
which bind it to that interface should be allowed here. Tests binding
to another interface such as Socket are an anti-pattern.
There are quite a few methods in the LogixDriver which are difficult to
read or test... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Using CNN to create descriptors and neural layer to predict
object recognition in images.
By: <NAME>, <NAME>, and <NAME>.
MLDM Master's Year 2
Fall Semester 2017
"""
import os
###############################################################################
#Set Params... |
from typing import List,Dict
import torch
from torch import nn
import numpy as np
from torch.nn import functional as F
from functools import partial
from detectron2.config import configurable
from detectron2.layers import Conv2d, ConvTranspose2d, cat, interpolate, DeformConv
from detectron2.structures import ... |
#!/usr/bin/env python
"""Functions to replace variables in a string with their values from a dict.
"""
import copy
import re
from astropy.io import fits
import despymisc.miscutils as miscutils
import intgutils.intgdefs as intgdefs
import despyfitsutils.fitsutils as fitsutils
def replace_vars_single(instr, valdict,... |
import numpy as np
import sys
import qoi as qoi
import parallel as par
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !
# ~~~~ Selection without replacement
# ~~~~ Sample K numbers from an array 0...N-1 and output them
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~... |
"""
IP socket address
"""
import sys
import socket
import threading
import time
import socket
import lib_util
import lib_common
from lib_properties import pc
def EntityOntology():
return ( ["Id"],)
# TODO: Add the network card.
# This returns a nice name given the parameter of the object.
def EntityName(entity_ids... |
from .. import Utils
from SimPEG.EM.Base import BaseEMProblem
from .SurveyDC import Survey
from .FieldsDC import FieldsDC, Fields_CC, Fields_N
import numpy as np
import scipy as sp
from SimPEG.Utils import Zero
from .BoundaryUtils import getxBCyBC_CC
class BaseDCProblem(BaseEMProblem):
"""
Base DC Problem
... |
from googlefinance import getQuotes
from yahoo_finance import Share
from dateutil.parser import parse
import datetime
import csv
import os
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
MONGO_DB = 'tomastocks'
GOOGLE_TYPE = 'goog'
GOOGLE_FINAL_PRICE_FIELD = 'LastTra... |
# Copyright (c) OpenMMLab. All rights reserved.
import os
import os.path as osp
import sys
import tempfile
from unittest.mock import MagicMock, patch
import pytest
import mmcv
from mmcv.fileio.file_client import HTTPBackend, PetrelBackend
sys.modules['petrel_client'] = MagicMock()
sys.modules['petrel_client.client']... |
import os,sys
import numpy as np
import random
import matplotlib.pyplot as plt
import seaborn as sns
from copy import deepcopy
import math
import torch
import torch.nn as nn
from tqdm import tqdm
from torch._six import inf
import pandas as pd
from PIL import Image
from sklearn.feature_extraction import image
from argum... |
import os;
import abc;
import math;
import multiprocessing;
import psutil;
import numpy as np;
import matplotlib.pyplot as plt;
from Errors import *;
from KMeans import *;
from UnaryLinearRegression import *;
class _Node:
def __init__(self, samplesCount, featureIndex = None, featureValue = None, leftChild = None... |
import pulpcore.client.pulp_rpm as pulp_rpm
import pulpcore.client.pulpcore as pulpcore
import yaml
import sys
import json
import colorama
from colorama import Fore
from colorama import Style
from time import sleep
from datetime import date, datetime
class RpmCherryPick:
"""Class used for cherry picking rpm packa... |
import os
import sys
from mininet.node import RemoteController
from mininet.net import Mininet
import dc_gym.utils as dc_utils
import logging
log = logging.getLogger(__name__)
cwd = os.getcwd()
FILE_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, FILE_DIR)
def get_congestion_control():
prev_... |
# -*- coding: utf-8 -*-
"""Flask app models."""
import os.path
import datetime
from flask import url_for
from flask_login import UserMixin
from sqlalchemy.sql.expression import and_
from werkzeug.security import generate_password_hash, check_password_hash
import hashlib
import qrcode
from app import db, login, whooshee... |
import numpy as np
import os, sys, re
import mpi4py
import time
from mpi4py import MPI
# Paths
MACHINE_NAME = 'tmp'
TUNER_NAME = 'tmp'
ROOTDIR = os.path.abspath(os.path.join(os.path.realpath(__file__), os.pardir, os.pardir))
EXPDIR = os.path.abspath(os.path.join(ROOTDIR, "hypre-driver/exp", MACHINE_NAME + '/' + TUNER_... |
"""
This module contains all that methods that determine if user provided details
are correct.
"""
from AllDBFields import BaseFields
from AllDBFields import AuthenticationFields
import CryptKeeper
import DatabaseLayer
import re
import cherrypy
def is_login_taken(login):
"""
checks the database to dete... |
import json
import jieba
import pickle
import csv, h5py
import pandas as pd
import numpy as np
from tqdm import *
import torch
from torch import Tensor
from torch.autograd import Variable
import torch.utils.data as data
from main import Hyperparameters
from collections import Counter
STOP_TAG = "#stop#"
UNK_TAG = "... |
#########
# GLOBALS
#########
from itertools import islice
import pandas as pd
import dateutil.parser as dp
from scipy.stats import boxcox
from realtime_talib import Indicator
#from nltk import word_tokenize
#from nltk.corpus import stopwords
#from nltk.stem.porter import *
#from scipy.integrate import simps
#from sk... |
#!/usr/bin/env python
# coding: utf-8
"""
Script to train a resnet
to determine if a Stokes-I radio cutout
contains a giant radio galaxy candidate.
Copyright (c) 2022 <NAME>
See LICENSE.md in root directory for full BSD-3 license.
Adapted from
Author: <NAME>
License: BSD
Source: https://pytorch.org/tutorials/beginner... |
import matplotlib.pyplot as plt
import numpy as np
from sklearn.metrics import mean_squared_error
from sklearn.metrics import r2_score, roc_auc_score
from sklearn.preprocessing import RobustScaler
from sklearn.linear_model import LogisticRegression
from sklearn.linear_model import LinearRegression
from sklearn.model_se... |
# Copyright (c) 2017 <NAME> <<EMAIL>>
#
# MIT License
#
# 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, me... |
import glob
import inspect
import logging
import os
import shutil
import sys
import yaml
from pathlib import Path
from typing import List
import multiply_data_access.data_access_component
from multiply_core.models import get_forward_models
from multiply_core.observations import INPUT_TYPES
from multiply_core.variables... |
import csv
import os
from botocore.exceptions import ClientError
from django import forms
from django.conf import settings
from django.contrib import messages
from django.contrib.admin import helpers
from django.contrib.auth.mixins import UserPassesTestMixin
from django.core.exceptions import ValidationError
from dja... |
import os
import sys
import logging
file_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(1, f"{file_dir}/../")
from db import session, Protein, SequenceAlign, StructureValidation
from utils import download_cif
from sqlalchemy import or_
import requests
logging.basicConfig(format="%(levelname)s: %(mes... |
"""Easily convert RGB video data (e.g. .avi) to the TensorFlow tfrecords file format with the provided 3 color channels.
Allows to subsequently train a neural network in TensorFlow with the generated tfrecords.
Due to common hardware/GPU RAM limitations, this implementation allows to limit the number of frames per
v... |
import numpy as np
import SimpleITK as sitk
def reference_image_build(spacing, size, direction, template_size, dim):
#template size: image(array) dimension to resize to: a list of three elements
reference_spacing = np.array(size)/np.array(template_size)*np.array(spacing)
reference_spacing[0] = 1.2
reference_... |
"""
The script expects the MViT (MDef-DETR or MDETR) detections in .txt format. For example, there should be,
One .txt file for each image and each line in the file represents a detection.
The format of a single detection should be "<label> <confidence> <x1> <y1> <x2> <y2>
Please see the 'mvit_detections' for referenc... |
import os
import imutils
import pickle
import time
import cv2
import threading
import numpy as np
from PIL import ImageFont, ImageDraw, Image
import json
import datetime
import requests
from faced import FaceDetector
from faced.utils import annotate_image
from config_reader import read_config
ZM_URL = 'http://18.179... |
#! /usr/bin/env python
"""Make history files into timeseries"""
import os
import sys
from subprocess import check_call, Popen, PIPE
from glob import glob
import re
import click
import yaml
import tempfile
import logging
import cftime
import xarray as xr
import numpy as np
import globus
from workflow import task_man... |
from typing import Tuple
class EmptyTreeError(Exception):
"""因为是空树,而无法执行某些操作"""
pass
class BinaryTreeNode(object):
def __init__(self):
"""按照定义,初始化为空树"""
self.value = None
self.left = None
self.right = None
self.parent = None
def __repr__(self):
retur... |
import csv
import gzip
import json
import re
import sys
from ast import literal_eval
from collections import Counter
from math import exp
import numpy as np
from nltk.stem.porter import PorterStemmer
from nltk.tokenize import word_tokenize
OPINION_EXP = re.compile(r"(.*)<o>(.*?)</o>(.*)")
ASPECT_EXP = re.compile(r"(.... |
from dataclasses import dataclass, field
from typing import Dict, List, Union
import pygamehack.struct_parser as struct_parser
from .struct_parser import tuples_to_classes, classes_to_string, Comment
from .struct_file import PythonStructSourceGenerator
__all__ = ['ReClassNet']
# TODO: ReClassNet all types
#region ... |
# -*- coding: utf-8 -*-
"""
main program for IMRT QA PDF report parser
Created on Thu May 30 2019
@author: <NAME>, PhD
"""
from os.path import isdir, join, splitext, normpath
from os import walk, listdir
import zipfile
from datetime import datetime
from dateutil.parser import parse as date_parser
import numpy as np
im... |
#!/usr/bin/env python3
"""Algorithms for determining connected components of graphs.
Edges must be symmetric (u, v) <==> (v, u).
TODOS
-----
- Allow user input 'seed' labels
- Create generic `concomp` method (maybe use fast_sv for a few iterations then
seed that to bfs_lp_rs).
"""
__all__ = ["bfs_lp", "bfs_lp_rs", ... |
import matplotlib.pyplot as plt
import numpy as np
import os
import pandas as pd
from pathlib import Path
import ptitprince as pt
# ----------
# Loss Plots
# ----------
def save_loss_plot(path, loss_function, v_path=None, show=True):
df = pd.read_csv(path)
if v_path is not None:
vdf = pd.read_csv(v_pa... |
from torch import nn
from torch.nn import functional as F
from .norm_module import *
# adopted from https://github.com/rosinality/stylegan2-pytorch/blob/master/model.py#L280
class NoiseInjection(nn.Module):
def __init__(self, full=False):
super().__init__()
self.noise_weight_seed = nn.Parameter(tor... |
#!/usr/bin/env python2.7
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Unit test suite for common.cros.chromite."""
import test_env
import base64
import json
import unittest
from common import cros... |
import torch
import torch.nn as nn
from lightconvpoint.nn.deprecated.module import Module as LCPModule
from lightconvpoint.nn.deprecated.convolutions import FKAConv
from lightconvpoint.nn.deprecated.pooling import max_pool
from lightconvpoint.spatial.deprecated import sampling_quantized, knn, upsample_nearest
from ligh... |
"""
This instrument description contains information
that is instrument-specific and abstracts out how we obtain
information from the data file
"""
#pylint: disable=invalid-name, too-many-instance-attributes, line-too-long, bare-except
from __future__ import absolute_import, division, print_function
import ... |
# Copyright DST Group. Licensed under the MIT license.
import datetime
from ipaddress import IPv4Address, IPv4Network
import CybORG.Shared.Enums as CyEnums
class NetworkInterface:
"""A class for storing network interface information """
def __init__(self,
hostid: str = None,
... |
# -*- coding: utf-8 -*-
# Copyright (c) 2020, LEAM Technology System and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.integrations.utils import make_post_request
from frappe.model.naming import make_autoname
from renovation_core.utils... |
from textwrap import dedent
import os
import subprocess
import numpy
import pandas
from wqio.tests import helpers
from wqio.utils import numutils
def _sig_figs(x):
""" Wrapper around `utils.sigFig` (n=3, tex=True) requiring only
argument for the purpose of easily "apply"-ing it to a pandas
dataframe.
... |
import adwords_pull
import analytics_pull
import process_xml
import match_maker
import csv_parser
import pandas
import pandasql
import datetime
import google_auth
from google.cloud import bigquery
from datetime import date
from dateutil.relativedelta import relativedelta, SU,MO,TU,WE,TH,FR,SA
import pprint
from currenc... |
"""mockfs: A simple mock filesystem for unit tests."""
import copy
import errno
import fnmatch
import glob
import os
import shutil
import sys
from . import compat
from . import util
# Python functions to replace
builtins = {
'glob.glob': glob.glob,
'os.chdir': os.chdir,
'os.getcwd': os.getcwd,
'os.p... |
# The MIT License
#
# Copyright (c) 2008 <NAME>
#
# 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,... |
from argparse import ArgumentParser
from diary.database import connect
from diary.presenter import display_entries
from diary.utils import custom_date
from diary.generator import generate_command
import logging
import re
import os
__version__ = '2.2.0'
try:
# Strip non- word or dash characters from device name
... |
###############################################################################
#
# The MIT License (MIT)
#
# Copyright (c) Crossbar.io Technologies GmbH
#
# 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 ... |
#!/usr/bin/env python
# coding: utf-8
# In[99]:
class TreeNode:
def __init__(self, val = None, par = None):
self.left = None
self.right = None
self.value = val
self.parent = par
def left_child(self):
return self.left
def right_child(self):
return self... |
import os
import torch
import argparse
import datetime
import numpy as np
import torch.optim as optim
from models.resnet import resnet50, Model, resnet50_1d
from losses.loss import ContrastiveLoss_
from torch.optim import lr_scheduler
from torch.utils.data import DataLoader
from dataset.industry_dataset_identify import... |
"""
This script was modified from https://github.com/ZhaoJ9014/face.evoLVe.PyTorch
"""
import os
import cv2
import bcolz
import numpy as np
import tqdm
from sklearn.model_selection import KFold
from scipy import interpolate
import math
from .utils import l2_norm
def get_val_pair(path, name):
carray = bcolz.carray... |
# Copyright 2016 <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
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.