text stringlengths 3.07k 12.6k |
|---|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
configfile.py
handle YAML and JSON configuration files
"""
import argparse
import datetime
import difflib
import json
import os
import sys
try:
import yaml
YAML_SUPPORTED = True
except ImportError:
YAML_SUPPORTED = False
#
#
# Constants
#
SCRIPT_NAME... |
import os
from flask import Flask, g, jsonify, request
from src.storage import Storage
from src.algo import (
create_dict,
create_weighted_dict,
breadth_first_search,
depth_first_search,
dijkstra,
export_to_matrix,
)
from src.importsfn import import_data_from_matrix
from src.gpsparser import imp... |
import subprocess
import logging
from subprocess import PIPE
import tempfile
import json, os, re
from github import Github, GithubException
"""
private-www Integration Test CI Hook for Uncle Archie
This hook should be installed into all submodules of private-www.
When a pull request in any of these submodules is upda... |
# Copyright 2011 Google Inc. All Rights Reserved.
#
__author__ = '<EMAIL> (<NAME>)'
from collections import namedtuple
import glob
import gzip
import os.path
import pickle
import time
import xmlrpclib
from django import forms
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_respons... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from collections import Counter
def imprimirSalida(archivo,salida, datos, etiquetas, actual, metricas, verbose):
d = str("%.3f" % (float(metricas['errores_T'])/float(metricas['numero_T']) * 100))
d1 = d.replace('.', ',')
d = str("%.3f" % (float(metricas['erro... |
# Advent of code Year 2021 Day 4 solution
# Author = <NAME>
# Date = December 2021
ROWS_COLUMNS = 5 # number of rows and columns on a board
class Board(list):
def __init__(self, aList, rows_columns: int = ROWS_COLUMNS):
list.__init__(self, aList)
self.rows_columns = rows_columns
def __st... |
import math
import dgl
import numpy as np
import torch as th
import torch.nn as nn
import torch.nn.functional as F
from dgl import function as fn
from torch.nn import init
__all__ = ['PotentialNet']
def sum_ligand_features(h, batch_num_nodes):
"""Computes the sum of ligand features h from batch_num_nodes"""
n... |
import os
import torch
import torchvision.transforms as tfs
import numpy as np
from torch.utils.data.dataset import Dataset
from torch.utils.data import DataLoader
from PIL import Image
from .utils import extract_episode
_SHAPENET_ID2NAME = {
'02691156': 'airplane',
'02880940': 'bowl',
'02942699': 'came... |
# -*- coding: utf-8 -*-
"""
SolarX Command Line Interface
"""
import click
import logging
import os
from rex.resource_extraction import NSRDBX, SolarX, MultiFileNSRDBX
from rex.resource_cli import dataset as dataset_cmd
from rex.resource_cli import multi_site as multi_site_grp
from rex.resource_cli import region as re... |
import requests
import json
# import related models here
from .models import CarDealer, DealerReview, CarModel
from requests.auth import HTTPBasicAuth
# Create a `get_request` to make HTTP GET requests
# e.g., response = requests.get(url, params=params, headers={'Content-Type': 'application/json'},
# ... |
#!/usr/bin/python
#
# This file is part of Ansible
#
# Ansible 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 3 of the License, or
# (at your option) any later version.
#
# Ansible is distribut... |
# --------------------------------------------------------
# CRPN
# Written by <NAME>
# --------------------------------------------------------
import numpy as np
from quad_convert import quad_2_aabb
from sort_points import sort_points
def quad_transform(ex_rois, gt_rois):
ex_rois = sort_points(ex_rois)
ex... |
#!/usr/bin/env python
"""
@package mi.dataset.parser
@file marine-integrations/mi/dataset/parser/flord_l_wfp_sio.py
@author <NAME>, <NAME>
@brief Parser for the flord_l_wfp_sio_mule dataset driver
Release notes:
Initial Release
"""
import re
import struct
import ntplib
from mi.core.log import get_logger
from mi.cor... |
import decimal
import numpy as np
from collections import deque
import torch
from config import cfg
from utils.timer import Timer
from utils.logger import logger_info
import utils.distributed as dist
from utils.distributed import sum_tensor
def accuracy(output, target, topk=(1,)):
"""Computes the accuracy over th... |
# import os
# os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" # see issue #152
# os.environ["CUDA_VISIBLE_DEVICES"] = ""
import keras.layers
import keras.layers.convolutional
from math import prod
from quaternion.qconv import *
class DummyLayer(Layer):
def __init__(self, **kwargs):
super().__init__(**kwa... |
import os
import logging
from datetime import datetime
from lxml import etree
class DdiFileProvider(object):
"""
Metadata provider for DDI Codebook XML files.
This provider scans a directory for XML files and converts them from
DDI Codebook to OAI DC.
"""
def __init__(self, dom... |
from collections import defaultdict
from jedi.evaluate.utils import PushBackIterator
from jedi.evaluate import analysis
from jedi.evaluate.lazy_context import LazyKnownContext, \
LazyTreeContext, LazyUnknownContext
from jedi.evaluate import docstrings
from jedi.evaluate import pep0484
from jedi.evaluate.co... |
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 23 16:00:13 2018
@author: bokorn
"""
import torch
import torch.nn as nn
import torch.utils.model_zoo as model_zoo
import torchvision.models.vgg as vgg
#import torchvision.models.alexnet as alexnet
import torchvision.models.resnet as resnet
from functools import partial
f... |
# Copyright 2020 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
import logging
import time
from signal import SIGTERM
from subprocess import PIPE, Popen
from threading import Thread
logger = logging.getLogger(__name__)
def is_fileobj_open(fileobj):
return fileobj and not getattr(fileobj, 'closed', False)
class NBSubprocThread(Thread):
DEFAULT_POLL_INTERVAL_SEC = 0.01
... |
from typing import Dict, List
import itertools
from mypy.errors import Errors
from mypy.errorcodes import ErrorCode
from mypy.options import Options
from mypy.plugin import FunctionContext, Plugin, CheckerPluginInterface
from mypy.types import Instance, Type, CallableType, TypeVarType
from mypy.nodes import Expression,... |
# Copyright 2014 Cloudbase Solutions Srl
#
# 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 l... |
from datetime import datetime
from flask import Blueprint, request, abort, send_file, current_app, jsonify
from sqlalchemy.orm.exc import NoResultFound
from commandment.models import db, Device, Certificate, RSAPrivateKey
from commandment.pki import serialization
from cryptography.x509.oid import NameOID
from cryptogr... |
import boto3
import urllib3
import json
from io import BytesIO
import constants
import time
import base64
import os
def upload_model(options):
model_url = options["modelURL"]
model_name = options['modelName']
model_type = options['modelType']
#TODO make call to ML API
http = urllib3.PoolManager()
req_url = 'h... |
from matplotlib import animation
import math
import matplotlib.pyplot as plt
import numpy as np
def distance(point1: tuple, point2: tuple) -> bool:
return math.sqrt(sum((x - y) ** 2 for x, y in zip(point1, point2)))
class TwoPointsAverageDistanceEstimation:
def __init__(self, display: "Display"):
self.display =... |
"""
Question:
Determine if a Sudoku is valid: according to https://sudoku.com/au/TheRules.aspx
The Sudoku board could be partially filled, where empty cells are filled with the character '.'
[ 5 ][ 3 ][ ]#[ ][ 7 ][ ]#[ ][ ][ ]
[ 6 ][ ][ ]#[ 1 ][ 9 ][ 5 ]#[ ][ ][ ]
[ ][... |
import base64
from django.contrib.auth import get_user_model
from django.contrib.auth.hashers import make_password
from rest_framework import status
from rest_framework.reverse import reverse
from rest_framework.test import APITestCase
from ..models import Tinylink, TinylinkLog
from .factories import TinylinkFactory,... |
"""
API endpoints for the courses app.
"""
from django.conf import settings
from django.db.models import Q
from cms import signals as cms_signals
from cms.models import Page
from rest_framework.decorators import api_view
from rest_framework.permissions import BasePermission
from rest_framework.response import Response... |
"""
Evia fault plots
MDH
"""
#import modules
#import numpy as np
#import matplotlib.ticker as ticker
#import pandas as pd
#from matplotlib import colors
#import math
#import subprocess
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib import rcParams
import sys, os
import LSD... |
# idel_utils.py
import os
import json
# Constants
STR_CFN = 'cfn'
STR_AWS = 'aws'
STR_DEPLOY = 'deploy'
STR_DELETE = 'delete'
CHANGE_MODE_CHANGE = 'change'
CHANGE_MODE_PROVISION = 'provision'
CHANGE_MODE_DESTROY = 'destroy'
CHANGE_MODE_ON = 'on'
CHANGE_MODE_OFF = 'off'
# Sample continuationToken
"""
{
"StackName... |
import mediapipe as mp
import cv2
import numpy as np
import time
#contants
ml = 150
max_x, max_y = 250+ml, 50
curr_tool = "select tool"
time_init = True
rad = 40
var_inits = False
thick = 4
prevx, prevy = 0,0
#get tools function
def getTool(x):
if x < 50 + ml:
return "line"
elif x<100 + ml:
return "rectangle"
... |
from __future__ import print_function
import time
from collections import defaultdict
import random
import math
import sys
import argparse
import dynet as dy
import numpy as np
#the parameters from mixer
NXENT = 40
NXER = 20
delta = 2
# format of files: each line is "word1|tag1 word2|tag2 ..."
tra... |
##Gladiator Arena 2.0
##<NAME>
##10-12-17
##A remake of Gladiator Arena in python
from random import randint
########################
def deathScreen():
print("You died!!")
playAgain=input("Would you like to play again? (yes/no)\n")
if playAgain=="yes":
fight()
else:
quit()
######... |
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright © Climate Data Preprocessing Tool Project Contributors
# https://github.com/cgq-qgc/climate-data-preprocessing-tool
#
# This file is part of Climate Data Preprocessing Tool.
# Licensed under the terms of ... |
import pytest
from meltano.core.plugin import PluginRef, PluginType, PluginInstall
from meltano.core.plugin.setting import PluginSetting
from meltano.core.plugin.settings_service import (
PluginSettingValueSource,
REDACTED_VALUE,
)
def test_create(session):
setting = PluginSetting(
name="api_key.... |
from typing import List, Optional, Union, cast
import requests
from eip712_structs import make_domain
from eth_account import Account
from eth_account.messages import encode_defunct
from eth_typing import AnyAddress, ChecksumAddress, HexStr
from hexbytes import HexBytes
from web3 import Web3
from gnosis.eth import Et... |
import os
import json
import random
META = "../../important_data/"
N = 10000
def load_metadata(filename):
print("Start reading " + filename)
with open(os.path.join(META, filename)) as f:
data = json.load(f)
return data
def remove_version_ending(arxiv_id):
return arxiv_id.rsplit("v", 1)[0]
... |
import socket
import logging
import re
# All the HTTP header types that should be converted to integers
NUMBER_TYPES = ["content-length"]
# The size of the byte buffers used to recv
BUFSIZE = 4096
RE_REQLINE = re.compile("(.+?)(?: )(.+?)(?: )(.+?)(?:\r\n)")
RE_HEADERS = re.compile("(.+?)(?::\s*)(.+?)(?:\r\n)")
clas... |
# -*- coding: utf-8 -*-
# @Time : 2019/3/4 20:25
# @Author : Mr.Robot
# @Site :
# @File : extract_core.py
# @Software: PyCharm
import pynlpir
import jieba
import jieba.posseg as pseg
import json
import os
from datetime import date
WORD_MAP_NLPIR = {
"noun": "n",
# 人名
"personal name": "... |
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework import viewsets, mixins
from rest_framework.authentication import TokenAuthentication
from rest_framework import filters
from rest_framework.authtoken.views import ObtainAuthToken
... |
import torch
import numpy as np
from torch.utils.data import Dataset, DataLoader
import config as cfg
import soundfile as sf
import glob
import pandas as pd
import random
from sklearn.model_selection import train_test_split
def create_dataloader(mode,type=0, snr=0):
if mode == 'train':
return DataLoader(
... |
from flask import Blueprint, current_app, request, abort, json
import pusher as _pusher
from pusher.signature import sign, verify
try:
import flask_jsonpify
except ImportError: # pragma: no cover
from flask import jsonify
else:
jsonify = flask_jsonpify.jsonify
flask_jsonpify__dumps = flask_jsonpify.__... |
import datetime
import logging
import traceback
from typing import Callable, Dict, List, TYPE_CHECKING
from telegram import MessageEntity, ParseMode
from telegram.ext import CallbackQueryHandler, CommandHandler, Defaults, Filters, MessageHandler, Updater
import api
import chat_management
import dev
import links
from ... |
#!/usr/bin/env python3.7
"""
"""
from time import time
from datetime import datetime
from asyncio import (
sleep, get_event_loop, create_subprocess_exec, Event,
ensure_future,
)
from subprocess import PIPE
from aiohttp import ClientSession
from psutil import Process
class SynchronizedTime(object):
def __init__(s... |
import os
import requests
import dotenv
from terminaltables import AsciiTable
def get_vacancy_sample_hh(vacancy):
hh_api_url = 'https://api.hh.ru/vacancies'
vacancies_per_page = 100
vacancy_area = 1
payload = {
'text': vacancy,
'area': vacancy_area,
'per_page': vacancies_pe... |
import numpy as np
import torch
from torch.utils.data import Dataset
from tqdm import trange
import os
from pycocotools.coco import COCO
from pycocotools import mask
from torchvision import transforms
from dataloaders import custom_transforms as tr
from PIL import Image, ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True... |
__source__ = 'https://leetcode.com/problems/sum-of-distances-in-tree/'
# Time: O()
# Space: O()
#
# Description: Leetcode # 834. Sum of Distances in Tree
#
# An undirected, connected tree with N nodes labelled 0...N-1 and N-1 edges are given.
#
# The ith edge connects nodes edges[i][0] and edges[i][1] together.
#
# Re... |
#!/usr/bin/env python
import sympy as sym
import model
def test_symbolic_constraints():
states = sym.symbols('q0, q1, u0, u1', cls=sym.Function)
inputs = sym.symbols('T0, T1', cls=sym.Function)
t = sym.symbols('t')
states = [s(t) for s in states]
inputs = [i(t) for i in inputs]
q0, q1, u0... |
import tempfile
import os
from PIL import Image
from django.contrib.auth import get_user_model
from django.urls import reverse
from django.test import TestCase
from rest_framework.test import APIClient
from rest_framework import status
from core.models import GalleryItem, Gallery
from gallery.serializers import Ga... |
# Copyright (c) 2021, Parallel Systems Architecture Laboratory (PARSA), EPFL &
# Machine Learning and Optimization Laboratory (MLO), EPFL. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Red... |
import copy
import numpy as _np
import inspect
import warnings
from pyemma._ext import six
from pyemma._ext.sklearn.base import _pprint
from pyemma.util.statistics import confidence_interval
from pyemma.util.reflection import call_member
__author__ = 'noe'
class Model(object):
""" Base class for pyEMMA models
... |
import sys
from pathlib import Path
import h5py
import minydra
import numpy as np
from tqdm import tqdm
sys.path.append(str(Path(__file__).resolve().parent.parent))
from aiphysim.utils import dat_to_array, new_unique_path, resolve # noqa: E402
def label_file(file_path, delay_fs=0.2):
delay_path = file_path.p... |
# -*- coding: utf-8 -*-
#
# Copyright © 2017 <NAME> <<EMAIL>>
# Distributed under terms of the MIT license.
"""
"""
import pandas as pd
import pysam
from .annotate_intersection import annotate_intersection
from .classify_effect import classify_effect
from .nearest_tss import annotate_nearest_tss
import svtk.utils as... |
import os
import typing
from functools import lru_cache
from aocd import get_data, submit
from dotenv import load_dotenv
from utils import generate_readme, profile
def get_session() -> str:
load_dotenv()
return os.getenv('SESSION_COOKIE')
type_cost = {'A': 1,
'B': 10,
'C': 100,
... |
import random
import math
import matplotlib.pyplot as plt
from util import City, read_cities, path_cost, print_iteration_data
# class Particle for PSO
class Particle:
# each particle has a route, personal best (route), current cost, personal best cost, velocity
def __init__(self, route, cost=None):
se... |
import pandas as pd
import os
from os import listdir
from os.path import isfile,join
def _get_reference():
import os.path
current_dir = os.path.dirname(os.path.realpath(__file__))
parent_dir = os.path.abspath(os.path.join(current_dir, os.pardir))
file_path = os.path.join(parent_dir, 'data/cog2003-2014.... |
# -*- coding: utf-8 -*-
"""Structuring of research fields.
This module investigates concept used by Vinck in Sociology of Scientific work.
It contains four functions that investigate whether research field can be
considered as having one type of structuring. It looks for four types of
structuring: polycentric oligarc... |
import copy
import collections
from functools import wraps
from cache_dependencies import interfaces, utils
class DeferredNode(interfaces.IDeferred):
"""Defers query execution for aggregation purpose.
Used mainly to reduce count of cache.get_many().
"""
def __init__(self, executor, iterator_factory, ... |
#! /usr/bin/python3
# -*- coding: utf-8 -*-
#--------------------------------------------------------------------------------------------------
# Script to count parallel phrases by the domain
#
# Usage:
# extract_para_domain_trans.py [--data_prefix str]
# (It reads the standard input and makes files in the data di... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import sys
from new_layers._3dgcn import Model_3dgcn
from new_layers.gru import GRUModel
def get_xt_from_x(x):
'''
TO DO
get it from dataset.py in 3dgcn
'''
return
class nconv(nn.Module):... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author: lazydog <<EMAIL>ago at gmail dot com>
import asyncio
import aiodns
import functools
import pycares
import string
import random
query_type_map = {'A' : pycares.QUERY_TYPE_A,
'AAAA' : pycares.QUERY_TYPE_AAAA,
'CNAME' : pyca... |
from lxml import etree as ET
import re
from pprint import pprint
dummy_path = r'sample.twb'
regex_xml_formatter = re.compile('\\n\s+\w')
class TableauObjectParser:
@staticmethod
def _parse_name(name):
"""
Converts a xml attribute to be used as a reference to snake case
:param name:
... |
from templates import *
class MetaRunTypeFrame(EcceFrame):
def __init__(self, parent, title, app, helpURL=""):
EcceFrame.__init__(self, parent, title)
panel = MetaRunTypePanel(self, helpURL)
self.Finalize()
class MetaRunTypePanel(EccePanel):
def __init__(self, parent, helpURL):
... |
import setpath # noqa:F401, must come before 'import mechanicalsoup'
import mechanicalsoup
import sys
from bs4 import BeautifulSoup
import tempfile
from requests.cookies import RequestsCookieJar
import pytest
def test_submit_online():
"""Complete and submit the pizza form at http://httpbin.org/forms/post """
... |
#!/usr/bin/python3
# Copyright 2015 <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 i... |
from typing import List
import requests
from fastapi import FastAPI
from fastapi.openapi.utils import get_openapi
from snakesist.exist_client import ExistClient
from starlette.responses import Response, JSONResponse, PlainTextResponse
from starlette.requests import Request
from random import choice
from string import ... |
import json
import logging
import os
from collections import Counter
import tornado.ioloop
import tornado.web
import tornado.websocket
from src.beer.beer import Beer
from src.beer.beerdb import BeerDB
from src.helpers.exceptions import UnValidVolumeError, NotFoundException
from src.helpers.logger import init_logger
f... |
# 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
# https://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, sof... |
# from labels import default_labeler
import numpy as np
from six import string_types
class unitsDict(dict):
"""
A dictionary sub-class for tracking units.
unitsDict instances support simple math operations (multiply,
divide, power)
The *key* of unitsDicts objects are the units, the values
r... |
import re
from config import Config
from login import Login
from genshin import Genshin
import setting
import mihoyobbs
import utils
import urllib3
from loader import logger
import requests
import platform
import glob
from argparse import ArgumentParser, RawDescriptionHelpFormatter
urllib3.disable_warnings(urllib3.exc... |
################################################################################
# Utility folder for collecting data
#
################################################################################
import os
import hashlib
import requests
import subprocess
import zipfile
##########################################... |
#
# Copyright 2020 Delphix
#
# 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, so... |
import pandas as pd
import numpy as np
import cv2
import skimage.io
import os
import config
from sklearn.model_selection import StratifiedKFold
from tqdm import tqdm
import multiprocessing
import dataset
import glob
def crop_white(image: np.ndarray) -> np.ndarray:
assert image.shape[2] == 3
assert image... |
import numpy as np
import matplotlib.pyplot as plt
import simpy
import math
STATES = 25 # state in ((,-1], [0, 1], [2, 3], ..., [46,))
ACTIONS = 10 # action in (0, 3, 6, 9, 12, 15, 18, 21, 24, 25)
ORDER_COST = 1
STOCK_COST = 0.025
PENALTY = 0.1
DISCOUNT = 0.9
LEARNING = 0.2
class CustomContainer(simpy.Container):
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""This module contains the XML reading and writing utilities.
All the text is stored in an XML file and the images are referenced
in the file.
"""
import os
import xml.etree.cElementTree as elTree
from typing import Tuple, Optional
import wx
from story_time import util... |
import os
import numpy as np
import pandas as pd
import pickle
import statsmodels.api as sm
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
import lightgbm as lgb
from sklearn.linear_model import LogisticRegression, LinearRegression
input_path = "/Users/christia... |
# Drakkar-Software ginit
# Copyright (c) Drakkar-Software, All rights reserved.
# 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 li... |
import logging
from .client import client
log = logging.getLogger(__name__)
""" derive_status is used to determine the application status from a set of unit
status values.
:param statues: list of known unit workload statues
"""
def derive_status(statues):
current = 'unknown'
for status in statues:
... |
from typing import Iterator, Optional, Union as TypingUnion
from genpy import (
Function as FunctionOriginal,
Generable,
Suite,
Class as BrokenClass,
FromImport,
Assign,
)
class Class(BrokenClass):
def generate(self) -> Iterator[str]:
bases = self.bases
if not bases:
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Usage: program.py <customer>
"""
import copy
import gzip
import json
import logging
import os.path
import re
import sys
import yaml
import app.settings as settings
import app.utils as utils
entity_type_conversion = {
"A": "Abundance",
"B": "BiologicalProce... |
import cv2
import cv2.aruco as aruco
import numpy as np
import os
from pathlib import Path
import math
def findArucoMarkers(img, arucoDict, arucoParam, intrinsics, distortion):
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
bboxs, ids, rejected = aruco.detectMarkers(gray, arucoDict, parameters=arucoParam,
... |
import io
import functools
# import soundfile as sf
import numpy as np
import matplotlib
import matplotlib.pylab as plt
from IPython.display import display, Audio
from nara_wpe.utils import stft, istft
from pb_bss.distribution import CACGMMTrainer
from pb_bss.evaluation import InputMetrics, OutputMetrics
from datacla... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import re
import os
import subprocess
import textwrap
import platform
if platform.mac_ver()[0] == '' or int(
platform.mac_ver()[0].split('.')[1]) < 12:
print("This tool requires macOS >= 10.12")
exit(1)
keys = ("a b c d e f g h i j k l m n o p q r s t ... |
import numpy as np
import os, sys, csv, cv2, time, random, keras, h5py
import skimage.feature
import matplotlib.pyplot as plt
from sklearn.externals import joblib
from keras.models import Model
from keras.layers import Input, Conv2D, BatchNormalization, concatenate
from keras.optimizers import Adam, RMSprop
def _sh... |
import torch
import torchvision
import torch.nn as nn
import torch.nn.functional as F
import os
from torch.autograd import Variable
class FrameSeedGenerator(nn.Module):
# Generate exactly 16 latent vectors starting from 1
def __init__(self, z_slow_dim, z_fast_dim):
super().__init__()
self.z_slo... |
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 13 11:18:26 2013
This module is used for downloading the PDB file from RCSB PDB web and
extract its amino acid sequence.
This is written by <NAME>
@author: <NAME>
"""
import os, ftplib, gzip
HOSTNAME = "ftp.wwpdb.org"
DIRECTORY = "/pub/pdb/data/structures/all/pdb/"
... |
# Import relevant packages
import numpy as np
from scipy import optimize
import matplotlib.pyplot as plt
# Utility function
def u_func(h, c, par):
"""
Cobb-Douglas utility function for consumption and housing quality
Args:
h (float): housing quality and equal to housing price
c (float): o... |
"""
Outil de lecture des fichiers IPE
"""
import logging
import zipfile
from pathlib import Path
from typing import IO
from typing import List
from typing import Optional
from typing import Union
import pandas as pd
import tqdm
from .. import pathtools as pth
from .. import misc
logger = logging.getLogger(__name__)
... |
# mypy: disallow-untyped-defs
"""
Implementation of .crc to CUDA converter using many copies of
the same array (# copies = # stages).
Assumes the .crc is the first argument.
"""
from typing import List, Set, Dict, Tuple
import sys
import re
ALLOWED_OPERATIONS = ["=", "+=", "-=", "*=", "/="]
"""
A line describes a c... |
import time
from colors import *
from enum import Enum
class direction(Enum):
north = 1
south = 2
east = 3
west = 4
class World:
""" Wrapper to hold the state of all the rooms and objects in the world (world_state) """
def __init__(self, world_state):
self.world_state = world_state ... |
from matplotlib import pyplot
from oscillator_snap import *
# Roessler system
a = 0.2
b = 0.0
c = 5.7
def dx(state,I):
return -state[1] - state[2]
def dy(state,I):
return state[0] + a*state[1]
def dz(state,I):
return I + state[2]*(state[0]-c)
ders = [dx,dy,dz]
# parameters
DATA_DIM_IN = 2
DATA_DIM_OUT = 1
PAST ... |
import os
import random
import logging
import ray
from pathlib import Path
from tqdm import tqdm
from .io.video_io import VideoFrameReader, write_img_files_to_vid_ffmpeg, \
resize_and_write_video_ffmpeg, convert_vid_ffmpeg
from .utils.serialization_utils import save_json
from .dataset import GluonCVMotionDataset, ... |
"""A script to create a plot of the number of issues in a project.
Uses GitHub's API v4 which uses graphql
https://developer.github.com/v4/
For more instructions see the the corresponding Jupyter notebook:
project_stats.ipynb
"""
import argparse
import datetime
from dateutil import parser as date_parser
import json
i... |
from typing import List, Deque, Dict
from collections import deque
from enum import Enum, auto
import Expr
import Token
import lox
import Stmt
import Environment
import LoxCallable
import LoxFunction
import Interpreter
class ClassType(Enum):
NONE = auto()
CLASS = auto()
SUBCLASS = auto()
class Res... |
import numpy
import scipy.ndimage as ndimage
import scipy.optimize as optimize
from . import pyramid
# Image comparison metrics
def abs_diff(i1, i2):
'''Return the absolute differences between two images.'''
return numpy.abs(i1 - i2)
def square_diff(i1, i2):
'''Return the squared differences between two ... |
import argparse
import numpy as np
import pandas as pd
import pyproj
from netCDF4 import Dataset
from make_proj_grids import read_ncar_map_file, make_proj_grids
def main():
parser = argparse.ArgumentParser()
parser.add_argument("-s", "--start_date", required=True, help="Start date in YYYY-MM-DD format")
... |
import sys
import oneflow as flow
import oneflow.typing as tp
import argparse
import numpy as np
import os
import shutil
import json
from typing import Tuple
from textcnn import TextCNN
sys.path.append("../..")
from text_classification.utils import pad_sequences, load_imdb_data
parser = argparse.ArgumentParser()
par... |
from typing import List
from musictree.quarterduration import QuarterDuration
from musicxml.xmlelement.xmlelement import XMLTime, XMLBeats, XMLBeatType
from musictree.xmlwrapper import XMLWrapper
__all__ = ['Time', 'flatten_times']
class Time(XMLWrapper):
_ATTRIBUTES = {'signatures', 'actual_signatures', 'paren... |
"""
In memory mockup implementation of essential parts of boto3 SQS objects.
Used for faster and more predictable processing in tests.
Lacks some features of "real sqs", and some other features implemented
ineffectively.
- Redrive policy doesn't work
- There is no differences between standard and FIFO queues
- FIFO ... |
# To be removed, 1 brick = 1 actor, inefficient.
import numpy as np
from fury import window, actor, ui
import itertools
import pybullet as p
# Instantiate Pybullet client.
client = p.connect(p.DIRECT)
# Apply gravity to the scene.
p.setGravity(0, 0, -10, physicsClientId=client)
# Creating BALL
# Ball actor
ball_acto... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.