text stringlengths 3.07k 22.1k |
|---|
import time
import json
from typing import Tuple, Sequence, Any, Iterable, Dict, MutableSequence, MutableMapping, Union, overload
from coba.random import random
from coba.pipes import Pipes, Source, HttpSource, Drop, ArffReader, ListSource, Structure
from coba.contexts import CobaContext, CobaContext
from coba.except... |
import os, datetime, sys, argparse
import cv2
import numpy as np
import json
import time
import tensorflow as tf
from builder import ModelBuilder
print(tf.__version__)
if tf.__version__ == '1.14.0':
from tensorflow.compat.v1 import ConfigProto
from tensorflow.compat.v1 import InteractiveSession
tf_config... |
from EvaluationGenerator import EvaluationGenerator
from DataAnalyzer import _get_files
import os
import io
import numpy as np
import argparse
import tensorflow as tf
from tqdm import tqdm
from PIL import Image
import hashlib
from hpc_tensorflow.satnet_study.models.research.object_detection.utils import dataset_util
fr... |
import os
import argparse
from solver import Solver
from data_loader import get_loader ####训练时使用这个
from data_loader_test import get_loader_test#####测试时使用这个
from torch.backends import cudnn
import numpy as np
from torchvision import transforms
#import cv2
import tkinter
from tkinter import *
from PIL import Image, Ima... |
import torch
import pyro
import pyro.infer
import pyro.optim
import pyro.distributions as dist
from torch.distributions import constraints
import numpy as np
import sys
from time import time
from pyro.poutine import block, replay, trace
from functools import partial
LR = 1e-3
NUM_PARTICLES = 2
TOTAL_ITS = 100000
GLOB... |
import torch
from torch.utils.data import Dataset, DataLoader
from torch.utils.data import random_split
import torchvision
import numpy as np
import pandas as pd
from projectModels import *
from projectUtilities import *
import matplotlib
matplotlib.use('Agg') # TODO: delete later if you want to use plot i... |
# -*- coding: utf-8 -*-
#
# * Copyright (c) 2009-2017. Authors: see NOTICE file.
# *
# * 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... |
import os
import json
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from collections import OrderedDict
from torchvision import models
def uncertain_logits_to_probs(logits):
"""Convert explicit uncertainty modeling logits to probabilities P(is_abnormal).
Args:
... |
#!/usr/bin/env python3
import click
import numpy as np
from aspics.params import Params
from tqdm import tqdm
from linetimer import CodeTimer
import os
import pathlib
import random
import synthpop_pb2
from collections import namedtuple
# Things to keep in mind:
# - This script isn't deterministic, because it doesn't ... |
import math
import sys
from pathlib import Path
from typing import List, BinaryIO, Union, Optional, TypeVar
from ..utilities.byte_io_mdl import ByteIO
from .blocks.compiled_file_header import CompiledHeader, InfoBlock
from .blocks import DataBlock, DATA
class ValveCompiledFile:
data_block_class = DATA
@clas... |
"""Schedulers are used to run models.
The defaults provided allow model runs to be scheduled as subprocesses,
or individual models to be called in series.
Future implementations may interface with common schedulers to queue
up models to run in parallel and/or distributed.
"""
import itertools
import logging
import su... |
from lxml import etree
from rospit.framework import TestSuite, ConditionEvaluatorPair
from rospit.binary import BinaryCondition, BinaryConditionEvaluator, StaticBooleanEvaluator
from rospit.numeric import Limit, LowerLimitCondition, LowerLimitEvaluator, \
UpperLimitCondition, UpperLimitEvalu... |
import os, logging, os.path
from galaxy import model
from Queue import Queue, Empty
import time
import threading
log = logging.getLogger( __name__ )
class BaseJobRunner( object ):
def build_command_line( self, job_wrapper, include_metadata=False, include_work_dir_outputs=True ):
"""
Compose the s... |
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
raw_csv = 'data/moss_report.csv'
repository_names = ['Github', 'Bitbucket', 'Google_Code', 'GitLab', 'Google_Android', 'Gitorious', 'Fedora_Project']
def group_data_by_repo(df):
# get stats about different repos and group them together
re... |
"""
Max-p regions algorithm
Source: <NAME>, <NAME>, and <NAME> (2020) "Efficient
regionalization for spatially explicit neighborhood delineation." International
Journal of Geographical Information Science. Accepted 2020-04-12.
"""
from ..BaseClass import BaseSpOptHeuristicSolver
from .base import (
w_to... |
from lib import *
class Agent:
def __init__(self, model,
batch_size=32, discount_factor=0.95):
self.model = model
self.batch_size = batch_size
self.discount_factor = discount_factor
self.memory = []
def remember(self, state, action, reward, next_state, done, next_valid_actions):
self.memory.append((s... |
# -*- coding: utf-8 -*-
from app.service.web3_did_adapter import Web3DidAdapter
import base64
import json
from ratelimit import limits, RateLimitException
from backoff import on_exception, expo
from app import log, config
from app.api.common import BaseResource
from app.config import RATE_LIMIT_CREATE_DID, RATE_LIMIT... |
from __future__ import division
import random
import time, os
import pdb
import torch
import torch.nn.functional as F
from torch_geometric.utils import to_dense_adj
from torch import tensor
from torch.optim.lr_scheduler import StepLR
from torch.optim import Adam
from train_edges import train_edges
from val_edges import... |
from tensorflow.keras.preprocessing.image import ImageDataGenerator
import numpy as np
import cv2
import pydicom
import glob
from skimage.restoration import denoise_nl_means, estimate_sigma
__author__ = ['<NAME>']
__email__ = ['<EMAIL>']
def create_segmentation_generator(img_path, mask_path, BATCH_SIZE, IMG_SIZE, S... |
'''
Test challengeutils.utils functions
'''
import json
import re
import tempfile
from unittest import mock
from unittest.mock import Mock, patch
import uuid
import pytest
import synapseclient
from synapseclient.annotations import to_submission_status_annotations
from synapseclient.core.exceptions import SynapseHTTPEr... |
"""
Script that determines what the
closest MHC Class I allele to another
one is based on training data
<NAME>
<EMAIL>
"""
from mhcnuggets.src.dataset import Dataset
from mhcnuggets.src.supertypes import supertype_mhcI_allele, supertype_mhcI_group, supertype_hla_C_allele, supertype_hla_C_allele_clade
import argparse... |
import binascii
import datetime
import logging
import os
import pathlib
import subprocess
import time
from Foundation import (
kCFPreferencesAnyUser,
kCFPreferencesCurrentHost,
CFPreferencesSetValue,
CFPreferencesAppSynchronize,
CFPreferencesCopyAppValue,
CFPreferencesAppValueIsForced,
NSDa... |
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import os
import copy
import logging
import collections
import cv2
import gym
from gym.envs.registration import register
import numpy as np
i... |
#
# Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
#
import sys
import unittest
import vnc_api
from vnc_api import Subnet, IpVer
from vnc_api import SGPeerType, SGPeer, SGDir, SGAction, SGApp, SGAppType
from vnc_api import PortParam, SGRule
from vnc_api import PeEndPt, PeEndPtType, PeAppType, PeAction,... |
import json
import numpy as np
import math
from pyquaternion import Quaternion
from typing import List
from bvh import Bvh
from tqdm import tqdm
class JointInfo:
""" Contains information on a certain joint in the DeepMimic human model as
well as some functions in order to convert joint data from BVH to DeepM... |
import datetime
import platform
import discord
import aiohttp
import time
from psutil import virtual_memory
from discord.ext import commands
from psutil import cpu_percent
from discord import Spotify
from utils import functions
from utils.functions import func
from cogs.Core.Language import Language
config = functi... |
from django.shortcuts import redirect, render
import logging
from django.shortcuts import redirect, render
from django.views.generic import View
from django_comments_xtd.models import Comment
from django.db.models import Count, Sum, Q, Avg
from django.db.models.functions import TruncDate
from django.contrib.auth.mixin... |
# Copyright (c) 2021 Food-X Technologies
#
# This file is part of foodx_devops_tools.
#
# You should have received a copy of the MIT License along with
# foodx_devops_tools. If not, see <https://opensource.org/licenses/MIT>.
"""Azure ARM template parameter generation."""
import copy
import json
import logging
imp... |
# -*- coding:utf-8 -*-
import json
import logging
import numpy as np
from collections import defaultdict
from SimpleWebSocketServer import SimpleWebSocketServer, WebSocket
import dist_train_config
import dist_params
import varserverapi
from dataset_loader import DatasetLoader
from weight_pack import WeightPack
logging... |
import pygame
import pygame_widgets
from pygame_widgets.widget import WidgetBase
from pygame_widgets.mouse import Mouse, MouseState
class Dropdown(WidgetBase):
def __init__(self, win, x, y, width, height, name, choices, isSubWidget=False, **kwargs):
super().__init__(win, x, y, width, height, isSubWidget)... |
__author__ = "<NAME>"
import numpy
import pandas
import copy
import math
from . import Utilities
from . import MultiPrediXcanAssociation, PrediXcanAssociation
from ..expression import HDF5Expression, Expression
##########################################################################################################... |
#!-*- encoding: utf-8 -*-
import datetime
import unittest
from pdl_scraper.pipelines import PdlScraperPipeline
from pdl_scraper.pipelines import ExpedientePipeline
from pdl_scraper.pipelines import SeguimientosPipeline
from pdl_scraper.pipelines import IniciativasPipeline
from pdl_scraper.spiders.proyecto_spider impor... |
import enum
import os
import time
import numpy
import pyopencl as cl
from pyopencl.tools import dtype_to_ctype
from PIL import Image
import pyopencl.array
class SymmetryMode(enum.Enum):
SYMMETRY_OFF = 0
SYMMETRY_ON = 1
SYMMETRY_ON_WITH_OVERLAP = 2
def isqrt(n):
x = n
y = (x + 1) // 2
while y... |
from optparse import OptionParser
from pathlib import Path
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import json
import re
import csv
from matplotlib import rcParams
import collections
rcParams['font.family'] = 'serif'
rcParams['font.sans-serif'] = ['Palatino']
rcParams['font.serif'] = ['Pal... |
##############################################################################
#
# Copyright (c) 2005 Zope Foundation and Contributors.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS I... |
import os
import time
import pickle
from glob import glob
import numpy as np
import cv2
import matplotlib.pyplot as plt
from sklearn.svm import LinearSVC
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from image_processing.vehicles_detect_model import custom_ext... |
#!/usr/bin/env python
# -*- coding: utf-8 -*--
# Copyright (c) 2021, 2022 Oracle and/or its affiliates.
# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/
"""
The module that helps to register custom warnings for the feature types.
Classes
-------
FeatureWarn... |
import configparser
import inspect
import logging
import os
import shutil
import tempfile
from pathlib import Path
from typing import Dict
LOG = logging.getLogger(__name__)
TMP_FILES = []
def parse_config_file(file_or_str: str, single_section: bool = True) -> Dict:
"""Parse the given properties config file/strin... |
# A simple in-memory stats library
#
# Inspired by statsd: http://statsd.readthedocs.io/en/v3.1/types.html#gauges
import collections
import json
import logging
import numbers
import numpy as np
import os
import six
import threading
import time
logger = logging.getLogger(__name__)
BYTES = 'bytes'
SECONDS = 'seconds'
... |
# Author: <NAME>
# Shanghai Jiao Tong University
# Code adapted from PointNetVlad code: https://github.com/jac99/MinkLoc3D.git
import MinkowskiEngine as ME
import numpy as np
import torch
from torch.utils.data import DataLoader
from dataloader.gta5 import GTAV5
from dataloader.oxford import OxfordDataset, TrainTransf... |
import numpy as np
from sklearn.base import BaseEstimator, MetaEstimatorMixin, clone
from sklearn.utils.multiclass import type_of_target
from sklearn.linear_model import LassoCV, LogisticRegressionCV
# Find internal implementations
try: # Version 0.20 - 0.21
from sklearn.feature_selection.base import SelectorMixin... |
"""
Data scraper for Scottish 2011 census Data
"""
import os.path
from pathlib import Path
import urllib.parse
import zipfile
import pandas as pd
import requests
import subprocess
import ukcensusapi.utils as utils
# Geographical area (EW equivalents)
# Council area (LAD)
# Intermediate zone (MSOA) ??
# Data zone (L... |
# -*- coding: utf-8 -*-
import json
import itertools
from hashlib import md5
from math import isnan, ceil
from copy import deepcopy
from datetime import datetime
from flask import current_app
from importlib import import_module
from fastnumbers import isfloat
from flask_mongoengine import DynamicDocument
from mongoeng... |
import os
import sys
import yaml
import yaml
from datatable import common
def init():
global config_yaml_data
global datatable_yaml_data
global excel_file_dict
global tool_file_path
# 设置环境变量
tool_file_path = os.path.dirname(os.path.abspath(sys.argv[0]))
os.chdir(tool_file_path)
# 取... |
#!/usr/bin/env python3
import argparse
import os
import sys
import zipfile
import xml.etree.ElementTree as ET
import subprocess
# Path of eat.py
base_path = os.path.split(os.path.abspath(sys.argv[0]))[0]
os_type = ''
def decode_apk(apk_file):
file_root = os.path.splitext(apk_file)[0]
print('[-] Decoding AP... |
# pylint:disable=missing-docstring,redefined-outer-name
import pytest
import pandas as pd
from pandas.testing import assert_series_equal, assert_frame_equal
from survey_toolkit.core import MultipleChoiceQuestion
@pytest.fixture
def question():
return MultipleChoiceQuestion('favouritePhones', 'What are your favour... |
"""Console script for mlb_statsapi."""
import argparse
import json
import os.path
import sys
import traceback
from mlb_statsapi.model import StatsAPI
from mlb_statsapi.utils.aws import StepFunctions
AWS_STEP_FUNCTIONS_TASK_TOKEN = os.environ.get("AWS_STEP_FUNCTIONS_TASK_TOKEN")
def runTask(run, **kwargs) -> dict:
... |
import numpy as np
from metecho.generalized_matched_filter import xcorr
from metecho.data import raw_data
def test_crosscorrelate_single_delay():
encode = np.array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, 1, 1, 1, 1, -1, -1, 1, 1, -1, -1, 1, 1],
dtype=complex)
sample_signal... |
#!/usr/bin/env python
# ~*~ coding: utf-8 ~*~
# by leoiceo
from __future__ import unicode_literals
import json,uuid
from django.http import HttpResponseRedirect, HttpResponse
from django.views.generic import TemplateView, ListView, View, CreateView, UpdateView, DeleteView, DetailView
from django.conf import sett... |
import torch as T
import torch.nn as nn
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
from data_util import config
import torch.nn.functional as F
from train_util import get_cuda
def init_lstm_wt(lstm):
for name, _ in lstm.named_parameters():
if 'weight' in name:
wt ... |
"""
@Author : <NAME>
"""
import os, sys
from basic.common import add_path,env
import numpy as np
from scipy.linalg import logm, norm
from math import pi, sqrt
from multiprocessing import Pool
from txt_table_v1 import TxtTable
# add_path(env.Home+'/working/eccv18varpose/dataset')
# from PASCAL3D import get_anno_dbs_... |
import logging
from collections import defaultdict
from pathlib import Path
from typing import Sequence, Set, Mapping, Any, DefaultDict, Callable, Iterable
from docopt import docopt
from clutchless.command.add import AddCommand, LinkingAddCommand
from clutchless.command.archive import ArchiveCommand, ErrorArchiveComm... |
#%%
# Import everything we need
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import datetime
from datetime import datetime
from datetime import datetime as dt
from sklearn.model_selection import cross_val_score, TimeSeriesSplit, RandomizedSearchCV, GridSearchC... |
import gettext
import os
from asyncio import TimeoutError
import datetime
import click
import discord
from apscheduler.schedulers.background import BackgroundScheduler
from discord.ext import commands
from discord_birthday_bot import config_util as config
from discord_birthday_bot import database_util
from discord_bi... |
# encoding: utf-8
# module time
# from (built-in)
# by generator 1.147
"""
This module provides various functions to manipulate time values.
There are two standard representations of time. One is the number
of seconds since the Epoch, in UTC (a.k.a. GMT). It may be an integer
or a floating point number (to represent... |
#!/usr/bin/env python3
"""
reme.py
A Discord bot that reminds you of things.
[Exit Codes]
1 - No token found
2 - Unable to login
3 - Unable to connect to the database
4 - Unknown error
5 - Discord.Client error
6 - Asyncio exception thrown
"""
import asyncio
from . import db
import discord
from . import entry
#fro... |
import os
import sys
import torch
from torch.utils.data import Dataset, SubsetRandomSampler, DataLoader
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
from utility import unit_norm
class AwaDataset(Dataset):
def __init__(s... |
#!/usr/bin/env python3
"""
Filters words having multiple transcriptions and writes to file. Also keeps track
on unique words belonging to this file and writes to another file.
Takes a pronunciation dictionary as an input.
"""
import sys
import re
KEEP_BOTH = 'KEEP_BOTH'
NO_CHOICE = 'NO_CHOICE'
def choose_transcri... |
"""
Pipelines experiment.
The code in all experiment files is very ugly, but it I did not see the use in creating beautifull
code for all experiments since it is a 'press enter and rerun them' setup.
"""
from schema_matching import *
from schema_matching.misc_func import *
from sklearn.metrics import accuracy_score
f... |
import bpy
import numpy as np
import mathutils
import config
import collections
# path = os.path.abspath(os.path.dirname(__file__))
# if path not in sys.path:
# sys.path.append(path)
from manimTexHelpers import TEMPLATE, tex_hash, tex_to_svg_file
# Functions for compatability between blender versions
def setAc... |
from selenium import webdriver
from time import sleep
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
course_info_list = []
fail_list = []
course_id = ''
course_name = ''
success_num = 0
fail_num = 0
c... |
import contextlib
import operator
import sqlalchemy as sa
from sqlalchemy.orm import relationship
from sqlalchemy.event import listen, listens_for
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.ext.associationproxy import association_proxy
from sqlalchemy.ext.hybrid import hybrid_property
impor... |
import bpy
import bmesh
import time
from os import chdir, getcwd
from os.path import exists, join
import os
from collections.abc import Iterable
import numpy as np
from math import radians
import struct
import json
"""
Basic
"""
def view_selected_index():
obj = bpy.context.object
bm = bmesh.from_edit_mesh(ob... |
# IMPORTS
import logging as lgg
import tkinter as tk
import tkinter.ttk as ttk
from collections import OrderedDict
import tesliper
from .helpers import WgtStateChanger
# LOGGER
logger = lgg.getLogger(__name__)
# CLASSES
class BoxVar(tk.BooleanVar):
def __init__(self, box, *args, **kwargs):
self.box = ... |
"""sequence/chipseq formats"""
import io
from .util import open_file, chunkify
import numpy
import pandas as pd
import os
import tempfile
import subprocess
def normalize_strand(x):
if x == 1 or x == 0 or x == -1:
return x
if x == "+":
return 1
elif x == "-":
return -1
else:
... |
# -*- coding: utf-8 -*-
# author: peilun
# 匹配跨视频的track
# 19
import numpy as np
import os
import math
import operator
from matplotlib import pyplot as plt
MATCHED = True
NO_MATCHED = False
input_dir = "./aic19-track1-mtmc/train"
INNER_SIMILAR_TH = 10
MOVE_TH = 4 # todo 待修订
ALL_TIME = 210
TIME_TH = 4.5
SCALE = 10.0
c... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright 2020-2022 F4PGA 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
#
# Unl... |
# lint-amnesty, pylint: disable=missing-module-docstring
import datetime
import itertools
import ddt
import pytz
from crum import set_current_request
from capa.tests.response_xml_factory import MultipleChoiceResponseXMLFactory
from common.djangoapps.student.models import CourseEnrollment
from common.djangoapps.studen... |
# -*- coding: utf-8 -*-
"""
:Module: khorosjx.content
:Synopsis: Collection of functions relating to content
:Usage: ``from khorosjx import content``
:Example: ``content_id = content.base.get_content_id(url, 'document')``
:Created By: <NAME>
:Last Modified: <NAME>
:M... |
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 3 16:01:15 2019
@author: Nikos
https://scikit-image.org/docs/dev/user_guide/tutorial_segmentation.html
"""
import tensorflow as tf
gpus = tf.config.experimental.list_physical_devices('GPU')
if gpus:
try:
for gpu in gpus:
tf.config.expe... |
# Program to show the maps of RMSE averaged over time
# Between the shifted and centeral domain
import matplotlib.pyplot as plt
from sklearn.metrics import mean_squared_error
import os
from netCDF4 import Dataset as NetCDFFile
import numpy as np
from CCLM_OUTS import Plot_CCLM
# option == 1 -> shift 4 with default ccl... |
#!/usr/bin/python3
# -*- encoding: utf-8 -*-
# Twitter trending topics analysis
# Topic utilities module
#
# Written by <NAME>
# April 2018
# This file defines several helper functions, including:
# * how to print the human-readable summary files summary.txt (summary)
# * topic sorting functions (sortByTFIDF, sortByVi... |
import torch
from torch import nn
from torch.nn import functional as F
from .utils import _SimpleSegmentationModel
__all__ = ["DeepLabV3"]
class DeepLabV3(_SimpleSegmentationModel):
"""
Implements DeepLabV3 model from
`"Rethinking Atrous Convolution for Semantic Image Segmentation"
<https://arxiv.or... |
#!/usr/bin/env python3
# This file is Copyright (c) 2019 <NAME> <<EMAIL>>
# License: BSD
"""
LitePCIE standalone core generator
LitePCIe aims to be directly used as a python package when the SoC is created using LiteX. However,
for some use cases it could be interesting to generate a standalone verilog file of the c... |
from datetime import datetime
import pickle
import numpy as np
from tqdm import tqdm
import os
import utils
import pandas as pd
def pre_user_cohort_triplet(prescription_taken_by_patient, user_cohort_rx, user_cohort_dx,
save_cohort_outcome, user_cohort_demo, out_file_root,
... |
import logging
import os
import time
import redis
from ..util import HDSFailure
HOST = os.environ.get("REDIS_HOST", "localhost")
PORT = int(os.environ.get("REDIS_PORT", "6379"))
PASSWORD = os.environ.get("REDIS_PASSWORD", None)
logger = logging.getLogger(__name__)
K_TOPICS = "hds/topics"
K_HOSTS = "hds/hosts"
K_TOP... |
import datetime
import decimal
import numpy as np
import pandas as pd
from workalendar.usa import California
from workalendar.usa import Texas
from workalendar.usa import Wisconsin
from .constants import *
from .utils import *
__all__ = [
# Functions for general features
"create_aggregate_features",
"cre... |
import torch
import torch.nn as nn
class DeepLGR(nn.Module):
def __init__(self,
in_channels=2, # channels of each input frame
out_channels=2, # channels of each output frame
n_residuals=9, # number of SE blocks
n_filters=64, # number of filters i... |
#!/usr/bin/env python
"""Credential-related classes and functions for bq cli."""
import argparse
import json
import os
import sys
from absl import app
from absl import flags
from google_reauth.reauth_creds import Oauth2WithReauthCredentials
import httplib2
import oauth2client_4_0
import oauth2client_4_0.contrib
import... |
#!/usr/bin/env python
import argparse, hashlib, os, sys # do not use any other imports/libraries
from pyasn1.codec.der import decoder
# took 7.5 hours (please specify here how much time your solution required)
# parse arguments
parser = argparse.ArgumentParser(description='generate self-signed X.509 CA certificate',... |
#!/usr/bin/python
## Binary Analysis Tool
## Copyright 2009-2016 <NAME> for Tjaldur Software Governance Solutions
## Licensed under Apache 2.0, see LICENSE file for details
'''
This file contains a few methods that check for the presence of marker
strings that are likely to be found in certain programs. It is far fro... |
import CONSTANTS, math
import plotly.express as px
import pygame
import sys
import random
pygame.init()
s_w = 1280
s_h = 720
pi = 3.14159265358
screen = pygame.display.set_mode((s_w, s_h))
pygame.display.set_caption('CAPTION')
class Drop:
def __init__(self, pos):
self.pos = pos
class Edge:
def __... |
# -- coding: utf-8 --
TEST = False # If True, run in test mode. If False, run in live mode
import os
from os.path import basename
from bookings import app
import settings
from google.appengine.ext import db
from models import Booking
from booking_ref_functions import derive
from email_templates import get_booking_co... |
import json
import networkx as nx
import matplotlib.pyplot as plt
import scipy as sp
import numpy as np
import collections
import torch
from collections import defaultdict
from utils.hugging_face import SPECIAL_TOKENS,MODEL_INPUTS, PADDED_INPUTS, PADDED_SPECIAL, get_loader, build_input_from_segments, test_dataloader
fr... |
""" Outliers handling functions
- OutliersEncoding (class) : identify and replace outliers
- get_cat_outliers (funct): identify categorical features containing outliers
- get_num_outliers (func): identify numerical features containing outliers
- replace_category (func): replace categories of a categorical variable... |
from tqdm import tqdm
import numpy as np
from . import VMD
from PyQt5.QtGui import QQuaternion, QVector3D
import copy
import pickle
def euler_to_quaternion(roll, pitch, yaw):
qx = np.sin(roll/2) * np.cos(pitch/2) * np.cos(yaw/2) - np.cos(roll/2) * np.sin(pitch/2) * np.sin(yaw/2)
qy = np.cos(roll/2) * np.sin(pit... |
# Copyright 2022 AI Singapore
#
# 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 writin... |
"""
Documentation here
"""
# ------------------------- modules training -------------------------
# -------------------------------------------------------------------
# import a function from a module
from basic0 import head
from basic0 import comment
from basic0 import title
from basic0 import qoute_str
# n... |
import logging
import re
from pyramid.httpexceptions import HTTPNotFound
from pyramid.registry import Registry
from pyramid.request import Request
from dbas.database import DBDiscussionSession
from dbas.database.discussion_model import Issue, User, Statement
from dbas.handler import history as history_handler, issue ... |
#!/usr/bin/python3
#-*- coding:utf-8 -*-
import os
import platform
import sys
import subprocess
import threading
import time
import json
try:
import requests
except ImportError:
sys.exit("\033[31m[!] Error Requests Module Not Found !")
try:
from bs4 import BeautifulSoup
except ImportError:
sys.exit("... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pytest
from ttree import Tree, Node
from ttree.exceptions import NodeNotFound, LoopError
def test_tree(tree, copytree):
assert isinstance(tree, Tree)
assert isinstance(copytree, Tree)
def test_is_root(tree):
assert tree['hárry'].is_root
assert no... |
import torch
import torch.nn.functional as F
from mmdet.datasets import build_dataloader, DATASETS
from mmdet.models import clip
from tqdm import tqdm
import matplotlib.pyplot as plt
import os
from mmcv.ops import roi_align
import argparse
CLASSES = ('person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus',
... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
from pwn import *
context(arch='amd64', os='linux', aslr=True, terminal=['tmux', 'neww'])
env = {'LD_PRELOAD': './libvtv.so.0'}
if args['GDB']:
io = gdb.debug('./ragnarok.bin', env=env, gdbscript='''\
set follow-fork-mode parent
c
''')
elf, li... |
################################################################################
#
# TWRIdual functional/gradient computation routines (python implementation using devito)
#
################################################################################
### Module loading
import numpy as np
import numpy.linalg as... |
import numpy as np
import math
import copy
class AbstractOperator:
# how many times did operator calls objective function
def costFE(self):
return 1
def set_algorithm(self, algorithm):
self.algorithm = algorithm
def get_candidate(self, i, k):
raise Exception("Should not call ... |
"""API Extractor - Extract Python docstring written in Markdown format"""
import inspect
import re
from pathlib import Path
from types import BuiltinFunctionType, FunctionType, MethodType
from typing import (
Any,
Dict,
Generator,
Iterable,
Optional,
Set,
Tuple,
TypeVar,
Union,
cast,
)
__version__... |
"""Trigger framework"""
import re
import time
import logging
import threading
from enum import Enum
from queue import PriorityQueue, Empty
class TriggerExecutionStatus(Enum):
"""Represent the status of the execution"""
CREATED = 1
PENDING = 2
EXECUTING = 3
FINISHED = 4
REJECTED = 5
class Trig... |
# -*- coding: utf-8 -*-
"""
Created on Mon May 4 21:05:31 2015
@author: J-R
"""
import numpy as np
import ipdb
import scipy.ndimage.interpolation as shiftsub
# permet de faire des plots
import matplotlib.pyplot as plt
from configobj import ConfigObj
from validate import Validator
def subshift(image,shift_x,shift_... |
# Copyright (c) 2006-2009 Sippy Software, Inc. All rights reserved.
#
# This file is part of SIPPY, a free RFC3261 SIP stack and B2BUA.
#
# SIPPY 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 ... |
from gocqhttpbot.botstart.entity import GuildEntity, CQcode
from gocqhttpbot.botstart.util import textToImg, SignUtil
import json, time, os, sys, random
hireTypes = [{
'name': '打工',
'nickname': '恭喜兔宝雇佣成功·对方正在为您在工厂打工赚萝卜(16分钟后结算)',
'pay': 3,
'obtain': 8,
'success': '为您不停的打工·为您赚了8个萝卜',
'lose': '打工... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.