text stringlengths 3.07k 12.6k |
|---|
# Copyright (c) 2013 <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, so... |
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean CLI v1.0. Copyright 2021 QuantConnect Corporation.
#
# 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... |
import os
import configobj
import pytest
from mock import call
from dvc.cli import parse_args
from dvc.command.machine import (
CmdMachineAdd,
CmdMachineCreate,
CmdMachineDestroy,
CmdMachineList,
CmdMachineModify,
CmdMachineRemove,
CmdMachineRename,
CmdMachineSsh,
CmdMachineStatus,... |
#!/usr/bin/python3
import requests
import sys
import json
import getpass
class linkedInClient():
def __init__(self):
self.session = requests.session()
self.outFile = ""
self.apiHeaders = {
"X-Li-User-Agent": "LIAuthLibrary:3.2.4 com.linkedin.LinkedIn:8.8.1 iPhone:8.3",
"User-Agent": "LinkedIn/8.8.1 CFNetw... |
"""
Shortcuts for common tasks.
"""
import math
from ballistics.linearmath import Vector3, Transform, Quaternion
from ballistics.linearmath.motion_state import DefaultMotionState
from ballistics.collision.broadphase import DbvtBroadphase
from ballistics.collision.dispatch import (DefaultCollisionConfiguration,
... |
#!/usr/bin/env python
#
# Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
# Copyright (c) 2013 OpenStack Foundation
#
# 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://... |
import pathlib
from bs4 import BeautifulSoup
from mutagen.mp4 import MP4
from dailyblink.settings import BASE_URL, COVER_FILE_NAME
def _safe_index(a, b):
return "" if not a else a[b]
def _create_blink_info(response_text):
def safe_strip(a):
return "" if not a else a.text.strip()
soup = Beauti... |
import argparse
import os
import pdb
import subprocess
import sys
import traceback
import unittest
from testcase import get_cli_base_cmd
from testcase import CT_API_KEY, CT_URL
from testcase import CT_TEST_JOB_ID, CT_TEST_LOG_COMMANDS, CT_TEST_LOG_OUTPUT
def parse_args(*args) -> argparse.Namespace:
parser = argp... |
"""
Python 3 Object-Oriented Programming
Chapter 11. Common Design Patterns
"""
from __future__ import annotations
from typing import Optional, Iterable, Iterator, cast
class NMEA_State:
def __init__(self, message: "Message") -> None:
self.message = message
def feed_byte(self, input: int) -> "NMEA_S... |
import time
import uuid
import json
import os
import cv2
import numpy as np
from threading import Thread
class Subject(Object):
"""Class representation of a subject"""
def __init__(self):
self.name = ''
self.details = {}
def __repr__(self):
return self.name
def update(self)... |
# this import statement is needed if you want to use the AWS Lambda Layer called "pytorch-v1-py36"
# it unzips all of the pytorch & dependency packages when the script is loaded to avoid the 250 MB unpacked limit in AWS Lambda
try:
import unzip_requirements
except ImportError:
pass
import os
import io
import j... |
import sys
import os
class Individual(object):
def __init__(self, raw_error, generation, parent_id, pop0_error, median_error, code, cx_mut_init):
self.raw_error = raw_error
self.generation = generation
self.parent_id = parent_id
self.pop0_error = pop0_error
self.median_erro... |
"""Module to scrape job postings."""
import csv
import datetime
import os
from bs4 import BeautifulSoup
import requests
import yagmail
def indeed_search(query, cities, pref_titles):
"""Find jobs that match query passed on indeed."""
holder = []
for city in cities:
indeed_url = (r'https://www.... |
import yaml
import json
import sqlite3
from functools import reduce
import operator
import time
def f():
return None
def load(path):
t0 = time.time()
s=open(path, "r", encoding="utf-8").read()
result = yaml.load(s, yaml.CLoader)
if isinstance(result, dict):
result = result#.items()
t... |
#!/usr/bin/env python2
# coding: utf8
from __future__ import unicode_literals
import random
import threading
import base64
import hashlib
import datetime
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from django.views imp... |
import time , os ,cv2
from options.train_options import TrainOptions
from data.data_loader import CreateDataLoader
from models.models import create_model
import ntpath
import numpy as np
import skvideo.io
import time
output_video = False
opt = TrainOptions().parse()
data_loader = CreateDataLoader(opt)
dataset = data_... |
from itertools import product
from math import prod
from typing import Tuple, Optional, Union
import numpy
from sklearn.feature_extraction.image import _extract_patches
from sklearn.utils import check_random_state
from aydin.util.array.outer import outer_sum
def extract_patches_nd(
image,
patch_size: Union[i... |
# coding: utf-8
# # Algorithmic Methods of Data Mining
# ## Homework 4
# ### Group 23: <NAME>, <NAME>, <NAME>
import itertools
import json
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
dictionary={}
authors_dict = {}
publications_dict = {}
conferences_dict = {}
def read_json(filename):
... |
import os, sys, time
import traceback
from functools import partial
from datetime import datetime
from threading import Thread, Lock, get_ident
from queue import Queue, Empty
def log(*msgs):
print('[{}] {}'.format(str(datetime.utcnow()), ' '.join([ str(m) for m in msgs ])))
def oid(o):
if not o:
r... |
import re
import pickle
import joblib
import json
import hjson
import numpy as np
import unicodedata
from pathlib import Path
from typing import Tuple
from pprint import pprint
from string import punctuation
from collections import Counter
REGULAR = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' \
'012345... |
import sys
from tkinter import font
from tkinter import ttk
from tkinter import *
from PIL import ImageTk, Image
import cv2
sys.path.append("..")
# from shole import QURY, SRCE, cam_process, GreedyProcessHost
from constants import QURY, SRCE
from drones import cam_process
from managers import GreedyProcessHost
ROOTOM... |
from starling_sim.model_simulator import launch_simulation
from starling_sim.model_simulator import model_codes
from starling_sim.utils.simulation_logging import TEST_LOGGER
from starling_sim.utils.utils import gz_decompression
from starling_sim.utils import paths
from starling_sim.utils.config import config
import os... |
#! /usr/bin/env python
from math import cos, sin, atan, pi, copysign
from PyQt4 import QtCore, QtGui
import emulator
DEGTORAD = pi /180
RADTODEG = 1.0 / DEGTORAD
class LineSensor():
"""This module detect the black line draw on the ground
The IO (only used as a output) from io_callback is
composed o... |
import os
import dill as pickle
import fnmatch
import logging
import pandas as pd
import numpy as np
from astropy.table import Table
def load_fits(directory, N_Rvir=10.0):
"""
:return:
"""
fits = []
for file in os.listdir(directory):
#TODO: change back
if fnmatch.fnmatch(file,
... |
import servo
import logging
import time
import Adafruit_PCA9685
import RPi.GPIO as GPIO
from evdev import InputDevice, categorize, ecodes, ff
import vg_motor_control
from sh import bluetoothctl
import asyncio
import sys
def grab():
try:
pos_input = 0
OUT = 1
while 1:
a=input()
if OUT == 1:
if pos_in... |
import torch
import torch.nn as nn
import torch.autograd as autograd
import torch.nn.functional as F
class DiversityRegularization(nn.Module):
def __init__(self, l=10, eps=1.0e-5, max=10):
super(DiversityRegularization, self).__init__()
self.l = l
self.eps = eps
self.max = max
... |
#
# Created by pSkateboard (Lee_Dohyeon)
#
import re
import requests
import bs4
headers = {}
session = requests.session()
def setup(user_agent, cookie):
global headers
headers = {
"user-agent": user_agent,
"cookie": cookie
}
session.headers = headers
def get_ca... |
# -*- coding: utf-8 -*-
import json
import os
from django.db import models
from jsonfield import JSONField
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from procyon.starsystemmaker.math_helpers import check_requirements
import uuid
class SnippetBase(models.Model):
"""
... |
"""Custom install scripts for CloudMan environment.
From <NAME>: https://bitbucket.org/afgane/mi-deployment
"""
import os, contextlib
from fabric.api import sudo, run, env, cd, put, local
from fabric.contrib.console import confirm
from fabric.contrib.files import exists, settings, hide, contains, append, sed
from cl... |
import logging
import pathlib
from typing import Dict, List, Tuple, Union
logger = logging.getLogger(__name__)
class Defaults:
"""Primarily used to share the location of the site directory 'path_site'
across modules as well as default/valid configuration values."""
# Path to /repo/src/easel
APP_ROO... |
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
# developed by <NAME> | github.com/dtemir | as a part of the RosettaCommons Summer Internship
import seq_des.common as common
import re
def read_resfile(filename):
"""
read a resfile and return a dictionary of constraints for each residue id
the constraints is a dictionary where the keys are residue... |
import os
import config
os.environ['CUDA_VISIBLE_DEVICES'] = config.gpu_id
import shutil
from torch import nn
from torch.utils.data import DataLoader
import torch.backends.cudnn as cudnn
from tensorboardX import SummaryWriter
from model.model import East
from model.loss import EastLoss
from dataset.data_utils import ... |
# -*- coding: UTF-8 -*-
################################################################################
#
# Copyright (c) 2020 Baidu, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"
# you may not use this file except in compliance with the License.
# You may obtain a copy... |
"""Example Tweet."""
import logging
from utils import timex, twitter
from covid19 import lk_data
from covid19.plots_lk import (MW, POPULATION, _plot_simple,
_plot_with_time_window)
logging.basicConfig(level=logging.INFO)
log = logging.getLogger('covid19.twitter')
def _get_tweet_text()... |
import json
from bs4 import BeautifulSoup
import pymysql
import requests
import js2xml
import lxml
id=100001
videoid=100001
headers = {
'authority': 'api.bilibili.com',
'sec-ch-ua': '"Google Chrome";v="87", " Not;A Brand";v="99", "Chromium";v="87"',
'accept': 'application/json, text/plain, */*',
'user-... |
# Copyright FMR LLC <<EMAIL>>
# SPDX-License-Identifer: Apache-2.0
import re
import nltk
import numpy as np
import pandas as pd
from utility import is_number
from textrank import TextRank_WindowSize
from nltk.probability import MLEProbDist
from textrank import TextRank_WordEmbeddings
def sort_phrases(phrases_dict):... |
# -*- coding:utf-8 -*-
# @time :2019.03.15
# @IDE : pycharm
# @author :lxztju
# @github : https://github.com/lxztju
import torch
import os
from PIL import Image
import pandas as pd
from tqdm import tqdm
import numpy as np
from collections import Counter
import cfg
import matplotlib.pyplot as plt
from data import tta_t... |
import argparse
import os
import sys
import time
import logging
from torch.multiprocessing import Process
sys.path.append("../../")
from data_loader.libsvm_dataset import SparseDatasetWithLines
def dist_is_initialized():
if dist.is_available():
if dist.is_initialized():
return... |
# -*- coding: utf-8 -*-
"""
renoir.parsing.lexers
---------------------
Provides lexers for templates parsing.
:copyright: 2014 <NAME>
:license: BSD-3-Clause
"""
from typing import Optional
from .stack import Context
class Lexer:
evaluate: bool = False
remove_line: bool = False
de... |
import numpy as np
import matplotlib.animation as animation
import matplotlib.pyplot as plt
from presentation.fabrik import fabrik
import math
__author__ = '<NAME>'
def f(x):
conds = [(x > -2) & (x < 2), x >= 2, x <= -2]
funcs = [-0.5, lambda x: 0.5 * x - 1.5, lambda x: -0.5 * x - 1.5]
return np.piecewise... |
#coding=utf-8
# Copyright (c) 2018 Baidu, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required ... |
import errno
import os
import os.path as path
import re
import requests
from .decryption import decrypt_file, decrypt_security_token
from .tagger import FeaturingFormat
from .tidal_api import TidalApi, TidalRequestError
COVER_FILE = 'Cover.jpg'
chunck_size = 1024
def _mkdir_p(path):
try:
os.makedirs(pat... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
===================================
SBPy Imageanalysis Module Utilities
===================================
created on July 02, 2017
"""
def rarray(shape, yx=None, subsample=0):
"""2D array of distances from a point.
Parameters
--------... |
from __future__ import print_function
import numpy as np
from ortools.algorithms import pywrapknapsack_solver
from dnl.Params import KNAPSACK
from dnl.PredictPlustOptimizeUtils import compute_C_k, compute_F_k
def knapsack_solver(values, weights, capacities):
solver = pywrapknapsack_solver.KnapsackSolver(
... |
# Copyright 2021 (David) <NAME>. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... |
import os
import requests
import json
import sys
PY2 = sys.version_info[0] == 2
from contextlib import contextmanager
from django.core.management.base import BaseCommand
URL = 'https://django.datamodeling.online'
# URL = 'http://localhost:5001'
@contextmanager
def debugme():
if not os.environ.get('DEBUG'):
... |
import string
# LEER ESTO
#
# manual:
# http://users.telenet.be/d.rijmenants/Enigma%20Sim%20Manual.pdf
# sobre todo el apartado 3. Technical details of the Enigma Machine
# y The Rotor Stepping Mechanism
#
# simulador:
# https://people.physik.hu-berlin.de/~palloks/js/enigma/enigma-u_v20_en.html
#
class... |
# Author: <NAME>
# More info at https://github.com/abhabongse/pyfnfn
"""Given a function which expects a file object as one of the input
arguments, the decorator in this module will modify the function input
entry point so that it additionally accepts file names without modifying
the implementation of the original func... |
from django.contrib import admin
from import_export import resources
from .models import Student, PlistCutoff, Grade, LoggedAction
from import_export.admin import ImportExportModelAdmin, ImportMixin
from django.dispatch import receiver
from import_export.signals import post_import, post_export
from import_export.format... |
import unittest
from openmtc.exc import SCLConflict
from openmtc_ngsi.ngsi import NGSI_9
from openmtc_ngsi.exc import NGSIError
from openmtc_ngsi.tests.xml import registerContextRequestXML
from openmtc_ngsi.requests import RegisterContextRequest
from openmtc_ngsi.ngsi_json import NGSIJSONWriter
from futile.StringIO imp... |
import torch
import detectron2.data.transforms as T
from detectron2.structures import Instances
from detectron2.layers import paste_masks_in_image
from detectron2.modeling import build_model
from detectron2.checkpoint import DetectionCheckpointer
from detectron2.data import MetadataCatalog
from detectron2.checkpoint i... |
import numpy as np
from scipy.spatial.transform import Rotation as R
import random
class AugmentParams(object):
def __init__(self, p_flipx=0., p_flipy=0.,
p_transx=0., trans_xmin=0., trans_xmax=0.,
p_transy=0., trans_ymin=0., trans_ymax=0.,
p_transz=0., trans_zmi... |
# Copyright Contributors to the Pyro project.
# SPDX-License-Identifier: Apache-2.0
import numpy as np
import torch
from torch.utils.data import Dataset
alphabets = {
"amino-acid": np.array(
[
"R",
"H",
"K",
"D",
"E",
"S",
... |
# Copyright 2018, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... |
# Copyright (c) 2020 Siemens AG
#
# 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, publish, dis... |
import plac
import os
import pandas as pd
def df2dict (df, key, val):
keys = df[key].values
vals = df[val].values
assert (len(keys) == len (vals))
return {keys[i]: vals[i] for i in range (len(keys))}
def readCaseFile (filename, key, value):
df = pd.read_csv (filename, sep=",", header=None, names=["word", "lower... |
from pathlib import Path
from antarest.study.storage.rawstudy.model.filesystem.config.files import (
ConfigPathBuilder,
)
from antarest.study.storage.rawstudy.model.filesystem.config.model import (
FileStudyTreeConfig,
Area,
Link,
Simulation,
Set,
Cluster,
)
def build_empty_files(tmp: Pat... |
import os
import sys
import json
import logging
import argparse
import cloudinary.api
from imagekitio import ImageKit
from concurrent.futures import ThreadPoolExecutor, as_completed
BATCH_SIZE=500
TOMIGRATE="tomigrate.log"
LOG_FILE="migration.log"
WORKERS=5
logging.basicConfig(filename=LOG_FILE, format='%(message)s',... |
import pandas as pd
import math
import operator
import gvgen
from graphviz import Source
def entropy_func(q):
return -(q * math.log2(q))
def B_func(q):
if q == 0 or q == 1:
return 0
return entropy_func(q) + entropy_func(1 - q)
def remainder(df: pd.DataFrame, col_name, res_name):
all_p_coun... |
# 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
# distributed under the... |
"""
Recallable per-channel lists of text items.
Dependencies:
:class:`.AsyncDatabaseHook`
Commands:
note-add <text>:
Add a new note for this channel.
note-edit <num> <text>:
Update an existing note from this channel with new text.
note-remove <num>:
Delete an existing note from... |
import click
import json
import pytest
import shutil
from click.testing import CliRunner
from pathlib import Path
from pprint import pprint
from ..cli import cli
from ..prov import Provenance, load_prov
ADD_OPTIONS_LIST = (
(["--agent", "testagent"], 1),
(["--comment", "test"], 1),
(["--activity", "testin... |
# Copyright 2021 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, ... |
## Henderson.py
## calculate a Henderson moving average
import pandas as pd
import numpy as np
def hmaSymmetricWeights(n):
""" derive an n-term array of symmetric 'Henderson Moving Average' weights
formula from ABS (2003), 'A Guide to Interpreting Time Series', page 41.
returns a numpy array of s... |
###########################################
#
# authors: <EMAIL>
# <EMAIL>.Garzon<EMAIL>
# <EMAIL>
#
# DESCRIPTION:
# Python library implementing utilities to manipulate Knowledge Bases
# based on the tomasys metamodel (Tbox), using the owlready2 library
##########################################... |
# Copyright (c) 2011-2013 <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# - Redistributions of source code must retain the above copyright
# notice, this list of conditions and th... |
import numpy as np
import psutil
import os
import warnings
import time
from pystreamfs.utils import fscr_score, classify
from pystreamfs.plots import plot
def prepare_data(data, target, shuffle):
"""Extract the target and features
:param numpy.nparray data: dataset
:param int target: index of the target ... |
from math import gcd, ceil
from operator import mul
from functools import reduce
# This function takes as input two integers in non-increasing order
# And returns the corresponding Bezout's coefficients and the gcd
# in that order
# The algorithm has been adapted from Pseudocode from Wikipedia article
def extended_eu... |
#!/usr/bin/env python
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# ... |
# -*- coding: utf-8 -*-
import os
import sys
import logging
from logging import config as logging_config
from typing import Union
LOGGER_NAME_RECC = "recc"
LOGGER_NAME_CORE_RECC = "recc.core"
LOGGER_NAME_RECC_HTTP = "recc.http"
LOGGER_NAME_RECC_RPC = "recc.rpc"
LOGGER_NAME_DAEMON_RPC = "recc.daemon"
LOGGER_NAME_RECC_... |
#!/bin/python3
# For simplicity reasons, this script will only run with Python3.
# If Python3 is not installed, you can use this script:
# https://github.com/cervoise/linuxprivcheck/blob/master/linuxprivchecker3.py
import subprocess as s
import sys
class Color:
YELLOW = '\033[0;33m'
GREEN = '\033[0;32m'
... |
#!/usr/bin/env python
#! -*- coding: utf-8 -*-
"""Includes the base-class for all commands of any service."""
from __future__ import unicode_literals
import ecstasy
import requests
import threading
import sys
try:
from Queue import Queue
except ImportError:
from queue import Queue
import lnk.config
import lnk.er... |
"""Interface and Implementation for generating plots and charts.
The default implementation of :py:class:`.AbstractPlot` is the
:py:class:`.Plot` class which internally uses the matplotlib library
to generate the plots. If you want to use another library to generate
your plots you can add a new `CustomPlot` class whic... |
import os
from xml.dom.minidom import parse
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
def readvocxml(xml_path, image_dir):
"""
The function can read single xml file and transform information of xml file into a list containing:
the filename of the xml indicates(str)... |
"""
Created on Tue Jun 18 21:28:56 2019
@author: fergal
"""
from __future__ import print_function
from __future__ import division
from pdb import set_trace as debug
import matplotlib.pyplot as plt
import matplotlib.patches as mpatch
import matplotlib as mpl
import pandas as pd
import numpy as np
import scipy.optim... |
import tensorflow.compat.v1 as tf
from detector import KeypointSubnet
from detector.backbones import mobilenet_v1
def model_fn(features, labels, mode, params):
assert mode != tf.estimator.ModeKeys.PREDICT
is_training = mode == tf.estimator.ModeKeys.TRAIN
images = features['images']
# it has shape [b... |
import cv2
from PIL import Image,ImageDraw,ImageFont
import numpy as np
from matplotlib import pyplot as plt
import os,shutil,glob
default_font=None
default_font_path=None
def set_font_path(path):
global default_font_path
default_font_path=path
def set_font(path,size=32):
global default_font
default_fo... |
#coding=utf-8
# Copyright 2019 Xilinx Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed ... |
# -*- coding: utf-8 -*-
"""Functions for building node predicates."""
from collections import Iterable
from six import string_types
from ...constants import NAME, NAMESPACE
from ...dsl import BaseEntity
__all__ = [
'function_inclusion_filter_builder',
'data_missing_key_builder',
'build_node_data_search... |
import open3d as o3d
import numpy as np
import os
import copy
import time
import matplotlib.pyplot as plt
def create_pcd(xyz, color):
# n x 3
n = xyz.shape[0]
pcd = o3d.geometry.PointCloud()
pcd.points = o3d.utility.Vector3dVector(xyz)
pcd.colors = o3d.utility.Vector3dVector(np.tile(color, (n, 1)))
pcd.estimate... |
# Copyright 2018 SunSpec Alliance
# 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,... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Various functions for heatmaps and other Pick This tricks.
:copyright: 2015 Agile Geoscience
:license: Apache 2.0
"""
import numpy as np
import json
import itertools
from io import StringIO
# For image manipulation
from PIL import Image
from mmorph import dilate, sedi... |
"""
Plot results of one or multiple scenario runner evaluations
"""
import argparse
import os
import re
import statistics
import sys
import xml.etree.cElementTree as ET
import matplotlib.pyplot as plt
import numpy as np
class ScenarioResult:
"""
Collection of multiple results for the same scenario
"""
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/8/7 10:23
# @Author : bxf
# @File : GROUP_OPT.py
# @Software: PyCharm
'''
需求:
对新增数据进行权限控制,通过数据增加group_id
'''
from model.util.TMP_DB_OPT import *
from model.util.PUB_DATABASEOPT import *
from model.util.PUB_RESP import *
from itsdangero... |
import numpy as np
import matplotlib.pyplot as plt
from scipy.constants import h, c, k, pi
def planck_energy_density(wavelength, temperature):
"""Spectral energy density according to Planck's law.
Uses the SI unit system, so the wavelength must be in meters (m) and the
temperature must be in Kelvin (K). R... |
# https://github.com/tidyverse/dplyr/blob/master/tests/testthat/test-count-tally.r
from datar.core.grouped import DataFrameGroupBy
from pandas.testing import assert_frame_equal
from pandas.core.frame import DataFrame
import pytest
from datar.all import *
def test_informs_if_n_column_already_present_unless_overridden(... |
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 04 22:18:20 2018
@author0: MIUK
@author1: FS
Generate datasets for ANN training testing.
TODO: Ensure compatibility with ANN scripts
TODO: Look at shape of Nuke's input file
"""
from ..utility import bipartite
import numpy as np
def gen_dataset(nb_train, nb_test, nb_m,... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from sklearn.utils.validation import check_random_state, check_array
from numpy.linalg import solve
import numpy as np
from packtml.recommendation.base import RecommenderMixin
from packtml.base import BaseSimpleEstimator
__all__ = [
'ALS'
]
try:
... |
import os
import pytest
from aioresponses import aioresponses
from rasa.core import utils
from rasa.core.utils import EndpointConfig
from tests.core.utilities import latest_request, json_of_latest_request
@pytest.fixture(scope="session")
def loop():
from pytest_sanic.plugin import loop as sanic_loop
return u... |
import math
import random
import argparse
# Расчет модульных инверсий a и b
def extendedEuclidean(a, b):
if a == 0:
return (b, 0, 1)
else:
gcd, x, y = extendedEuclidean(b % a, a)
return (gcd, y - b//a * x, x)
# Encrypt every symbol
def crypt(message, e, n):
cr = []
for c in message:
cr.append(pow(ord(... |
#coding=utf-8
# Download a classified album like https://www.nvshens.com/gallery/ysweb/
#Usage:
# python3 spider.py https://www.nvshens.com/gallery/ysweb/ beginIndex endIndex
# note: If you just want to download the content of a web page, such as the second page, the 'beginIndex' and 'endIndex' should be '2'
impor... |
import os
import cv2
import numpy as np
from keras.callbacks import TensorBoard
from keras.layers import BatchNormalization, Activation
from keras.layers import Conv2D, Input, UpSampling2D, MaxPooling2D, Dropout, Dense, Reshape, Flatten
from keras.layers.merge import Add
from keras.models import Model
from matplotlib i... |
from mcpi.minecraft import mc
from mcpi.minecraft import mcDrawing
from mcpi.block import *
import math
from mcpi.minecraftstuff import MinecraftTurtle, Vec3
def move_persion(position_x,y,postion_y):
mc.setPlayerPosition("babyYao521",position_x,y,postion_y)
def mapping_place(position_x,position_y):
mc.setBl... |
import typing
from pathlib import Path
from collections import OrderedDict, defaultdict
from CMake import CMakeInterpreter
from ..distros.debian import Debian
from ..utils.ReprMixin import ReprMixin
from ClassDictMeta import ClassDictMeta
from ..distros.debian.utils import debianPackageRelationKwargs
from .debhelper... |
# 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
# distributed under the ... |
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 17 15:18:25 2013
@author: ash
"""
import numpy as np
import scipy as sp
import scipy.linalg as la
import scipy.sparse.linalg as las
import tdvp_common as tm
import matmul as m
import logging
log = logging.getLogger(__name__)
class PinvOp:
def __init__(self, p, ... |
# Copyright (c) 2019 <NAME>.
# Uranium is released under the terms of the LGPLv3 or higher.
from typing import Any, Dict, List, Optional, Set, TYPE_CHECKING
import UM.Decorators
from UM.Logger import Logger
from UM.Signal import Signal
from UM.Settings.PropertyEvaluationContext import PropertyEvaluationContext
if TY... |
import os, time, re
import sublime
import sublime_plugin
import glob
import os
from xml.etree import ElementTree
current_path = None
#
class CreatePolicyFromTemplateCommand(sublime_plugin.WindowCommand):
ROOT_DIR_PREFIX = '[root: '
ROOT_DIR_SUFFIX = ']'
INPUT_PANEL_CAPTION = 'File name:'
def run(self... |
# Using some code from https://github.com/ProfAvery/cpsc449/tree/master/flaskapi-pugsql
import sys
import flask_api
from flask import request
from flask_api import status, exceptions
import pugsql
import uuid
from cassandra.cluster import Cluster
from flask_cassandra import CassandraCluster # pip3 install flask-cassan... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.