text
stringlengths
3.07k
22.1k
from ultrasonic import steph distanceFromStart=0 possibleDogLocations=[True, True, True, False] oldDistances=[] def moveForward(distance): global distanceFromStart global moved moved=True distanceFromStart+=distance input() print(distanceFromStart) #this is the value that will be returned when added to the...
import functools import time import numpy as np from numba import jit np_nanmean = np.nanmean np_nansum = np.nansum def timer(func): @functools.wraps(func) def wrapper_timer(*args, **kwargs): tic = time.perf_counter() value = func(*args, **kwargs) toc = time.perf_counter() ...
import numpy as np import functools from tempfile import mkdtemp import sys sys.setrecursionlimit(100000) from joblib.memory import Memory cache_dir = mkdtemp() memory = Memory(location=cache_dir, verbose=0) # Old solution # @memory.cache def cut_rope(cs, T): # print("-" *8 + "\nT: {}.".format(T)) # print("...
""" Capstone Project. Code to run on a LAPTOP (NOT the robot). Displays the Graphical User Interface (GUI) and communicates with the robot. Authors: Your professors (for the framework) and <NAME>. Winter term, 2018-2019. """ import mqtt_remote_method_calls as com import tkinter from tkinter import ttk i...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Aug 22 21:31:09 2019 App: I-Spy-P Use: Search IP within .txt documents, identify IPv4, allow user to find particular IP, get GeoID from IP, and RDAP/WhoIS from IP based on Queries @author: beehive """ #/home/beehive/Documents/I-Spy-P/data/list_of_ip...
#----------------------------------------------------------------------*/influxdb_client # 2022.03.11 UECS # sudo apt-get install python3-pip -y # sudo apt-get install python3-pandas -y # sudo apt-get install python3-influxdb -y # sudo pip3 install influxdb-client # sudo pip3 install xmltodict #-----------------------...
""" Name - <NAME> Lab Assignment 3 Roll No - B19130 Mobile No - +91-9351159849 """ import numpy as np import pandas as pd from matplotlib import pyplot as plt from sklearn.metrics import mean_squared_error from sklearn import decomposition # import data = pd.read_csv('landslide_data3.csv') # loading d...
import torch import json from torch.utils.data import DataLoader, Dataset import os import sys sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../'))) from data_retriever import MentionSet from reader import get_predicts import math def proc...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Documentation Build Configuration Django Improved User documentation build configuration file, created by sphinx-quickstart on Thu Aug 17 10:44:16 2017. This file is execfile()d with the current directory set to its containing dir. Note that not all possible configur...
""" This script contains functions needed for the core functionality of gitcrawl """ import os import sys import re import subprocess import yaml import json from tqdm import tqdm import time import pickle from .helpers import extract_keys, enumerate_installation_candidates, menu, choose_custom_name def findimports_to...
#import AYS_Environment as ays_env import c_global.cG_LAGTPKS_Environment as c_global import numpy as np import pandas as pd import sys,os import matplotlib.pyplot as plt from matplotlib.offsetbox import AnchoredText pars=dict( Sigma = 1.5 * 1e8, Cstar=5500, a0=0.03, aT=3.2*1e3, ...
""" Modifed from the original STM code https://github.com/seoungwugoh/STM """ import math import torch import torch.nn as nn import torch.nn.functional as F from model.propagation.modules import * class Decoder(nn.Module): def __init__(self): super().__init__() self.compress = ResBlock(1024, 512...
import torch import torch.nn as nn import torch.nn.init as init import torch.nn.functional as F from torch.nn.parameter import Parameter class BatchMultiHeadGraphAttention(nn.Module): def __init__(self, n_head, f_in, f_out, attn_dropout, attn_mask=True, bias=True, attn_type="aa"): super(BatchMultiHeadGrap...
#!/usr/bin/env python #=============================================================================== # @file pompcli.py # # @author <EMAIL> # # Copyright (c) 2014 Parrot S.A. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the ...
from __future__ import annotations import unittest from unittest.mock import patch from typing import Dict, Optional from app import app from geopy.exc import GeopyError, ConfigurationError, GeocoderServiceError from mkad_blueprint.geo_functions import ( default_geocoder, yandex_geocoder, geopy_geocoder, ...
import subprocess import os.path import shutil import time import json from gii.core import * from gii.qt import * from gii.qt.IconCache import getIcon from gii.qt.helpers import addWidgetWithLayout, QColorF, unpackQColor from gii.qt.dialogs import requestString, alertMessage, requestColor from ...
import numpy as np from matlearn.evaluation import * from matlearn._errors import NotTrainingError from matlearn.preprocessing import split_train_test,polynomial ######################################################################################################### def activation_function(z, type, derivative=False)...
#!/bin/env python # # Advent of Code 2020 # Day 16 # # author: <NAME> # e-mail: <EMAIL> # import sys from argparse import ArgumentParser from pathlib import Path import numpy as np from scipy.optimize import linear_sum_assignment import pytest @pytest.fixture def example_data(): test_data = """class: 1-3 or 5...
from typing import Optional, Tuple import numpy as np import matplotlib.pyplot as plt from matplotlib.axes import Axes from matplotlib.figure import Figure __all__ = ["reliability_diagram", "reliability_curve"] def reliability_diagram( accs: np.array, confs: np.array, left_bins: np.array, num_classe...
import glob import numpy as np import sys import pandas as pd sys.path.append('./support_files/') import summarise_bins def load_individual_bin_summaries(): return pd.read_csv('support_files/bin_summary.csv') def load_bin_length_summary(): return pd.read_csv('support_files/bin_stats.tsv', sep ='\t') def...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Chapter 8: Variational Autoencoders Github directory: https://github.com/jgvfwstone/DeepLearningEngines/tree/master/DeepLearningEnginesCode/Python/Ch08_VariationalAutoencoder Author: <NAME>, most comments by authors, with a few added comments by JVStone Date created: 2...
import helper from PIL import Image from torchvision import datasets, transforms, models import torch import matplotlib.pyplot as plt import numpy as np from torch import optim import time import json def get_train_valid_test_loader(data_dir, gpu): train_dir = data_dir + '/train' valid_dir = data_dir + '/val...
import heapq import wx import os from numpy import * HuffAlphabeth = [] LZWAlphabeth = "" class Example(wx.Frame): def __init__(self, *args, **kwargs): super(Example, self).__init__(*args, **kwargs) self.args = args self.kwargs = kwargs self.fname="" self.InitUI() ...
""" Algorithms and containers mimicking FORTRAN-style behaviour. This allows interoperability with - or straightforward implementation of - algorithms originally written using Fortran or MATLAB. Examples -------- Create a 4x4 array using Fibonacci numbers: >>> fib_mat = fortran_array([[1, 1, 2, 3], ... ...
# -*- coding: utf-8 -*- """ Zegami Ltd. Apache 2.0 """ from io import BytesIO import pandas as pd from PIL import Image from time import time from concurrent.futures import ThreadPoolExecutor, as_completed from .source import Source class Collection(): @staticmethod def _construct_collection(client, wo...
""" ROS Code Commands This file contains all the commands in ROS Code """ import warnings import keyword import importlib import string import pprint import loremipsum import colour from.roserrors import* def shellinput(initialtext='>> ',splitpart=' '): try: str(initialtext) except BaseException: raise Conversion...
""" SDFG nesting transformation. """ from copy import deepcopy as dc import networkx as nx import dace from dace import data as dt, memlet, sdfg as sd, subsets, Memlet, EmptyMemlet from dace.graph import edges, nodes, nxutil from dace.transformation import pattern_matching from dace.properties import make_properties,...
import os import argparse import random import time import numpy as np import scipy.sparse as sp import torch import torch.nn as nn import torch.optim as optim from script import dataloader, utility, earlystopping from model import models import nni def set_env(seed): # Set available CUDA devices # This o...
import numpy as np """ Mapping SIP to Bin """ #Mapping of SIP ensemble onto a bin grid #SIP ensemble (of one realisation) with nr_SIPs SIP defined by nEK_sip and mEK_sip #Properties of the bin grid are specified by n10_plot, r10_plot, min10_plot def MapSIPBin(nEK_sip,mEK_sip,nr_SIPs,n10,r10,min10): n= n10 * r10 ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Sorting gr3 output from SCHISM in pythonic way. The script is intended to sort a lot of max elevation results and sorting them at node based on the inundation value. This script was developed to tackle the problem of sorting the storm track developed in Kerry Hydro sim...
import math import taichi as ti import numpy as np objects = [] springs = [] l_thigh_init_ang = 10 l_calf_init_ang = -10 r_thigh_init_ang = 10 r_calf_init_ang = -10 initHeight = 0.15 hip_pos = [0.3, 0.5 + initHeight] thigh_half_length = 0.11 calf_half_length = 0.11 foot_half_length = 0.08 half_hip_length = 0.08 d...
#!/usr/bin/python DOCUMENTATION = """ --- module: comware_ospf short_description: Manage ospf description: - version_added: 1.0 category: Feature (RW) author: hanyangyang notes: options: ospfname: description: - Instance name.(1~65535) required: true default: null ...
# Copyright (C) GRyCAP - I3M - UPV # # 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...
# -*- coding: utf-8 -*- # MIT License # Copyright (c) 2021 Arthur # 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...
import numpy as np import os def vol(ftraj='atoms.traj'): from ase.io import read a=read(ftraj,':') v=a[-1].get_volume() with open('vol','w') as f: f.write(str(v)) return v # do eos fitting and Debye model for one functional and save results in files def eos_gpaw(ev='e-v.dat',struc='rel....
#!/usr/bin/env python """ A tool to analyze files of shape (16, 1, 67108864) or similarly short-but-very-wide dimensions. Reports which columns are "interesting". """ import cp import json import os import random import sys import time from h5_file import H5File from hit_info import group_hit_windows from hit_map imp...
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2018 Huawei # GNU General Public License v3.0+ (see COPYING or # https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type #################################################################...
from numpy.core.fromnumeric import size import pandas as pd import numpy as np import torch #file = "conceptnet-5.7.0-rel.csv" def conceptnet_to_dict(csv_path): data = pd.read_csv(csv_path, delimiter=',') data['start'] = data['start'].apply(lambda str: str.split("en/")[1].split("/")[0]) data['end']...
import socket from datetime import timedelta from email.utils import parsedate_to_datetime import requests from azure.identity import ClientSecretCredential from azure.mgmt.cdn import CdnManagementClient from azure.mgmt.cdn.models import PurgeParameters from celery.utils.log import get_task_logger from django.conf imp...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # from "Starfield" (<NAME>) # Video: https://youtu.be/17WoOqgXsRM import sys import os from PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * import random def mapFromTo(x, a, b, c, d): """map() function of javascript""" y = (float(x...
import numpy as np from constants import cgs_constants from numpy import exp, sin, einsum pi = np.pi q = cgs_constants['q'] c = cgs_constants['c'] ## Convert units to cgs from mks class field_solver_2D(object): def __init__(self): self.name = '2-d electrostatic field solver' def compute_mode_coefficients(s...
#Begin Imports import sys import math #End Imports #Begin Util Code def log(x): print(x, file=sys.stderr) # Cells FLOOR_CELL = "." EMPTY_TABLE = "#" DISHWASHER = "D" WINDOW = "W" BLUEBERRIES_CRATE = "B" ICE_CREAM_CRATE = "I" STRAWBERRIES_CRATE = "S" DOUGH_CRATE = "H" CHOPPED_BOARD = "C" OVEN = "O" # Items NO...
# Copyright (c) 2012, GPy authors (see AUTHORS.txt). # Licensed under the BSD 3-clause license (see LICENSE.txt) import numpy as np from ..core.parameterization import Parameterized, Param from paramz.transformations import Logexp import sys class WarpingFunction(Parameterized): """ abstract function for war...
import sys import toml import collections import math from dataclasses import dataclass sys.path.insert(0, "../wrapper") from wave import Wave from asv import Asv_propeller, Asv_specification, Asv_dynamics, Asv from geometry import Dimensions from rudder_controller_pid import Rudder_controller from cyclone import Cyclo...
"""Create a tessellation from a list of qubits.""" from __future__ import annotations from typing import List, Callable, Tuple, Iterable import itertools import functools from . import exceptions from .vector import Vector class Tessellation: """Describes how to partition the lattice into cells. This is a l...
# -*- coding: utf-8 -*- ########################################################################### ## Python code generated with wxFormBuilder (version Oct 26 2018) ## http://www.wxformbuilder.org/ ## ## PLEASE DO *NOT* EDIT THIS FILE! ########################################################################### impor...
# coding: utf-8 """ サービスを実装する """ import datetime from repository import openweathermap from service import graph_creator from service import slack_uploader from service import slack_messenger from service import os_manager import json def make_help_message(): attachments = [{ 'fallback': 'tenkibot', ...
from __future__ import division, print_function, absolute_import import time import datetime import sys import traceback import socket import threading import os import signal import atexit import platform import random import math from .runtime import min_version, runtime_info, register_signal from .utils import tim...
from __future__ import division, print_function, unicode_literals import functools import tensorflow as tf tf.logging.set_verbosity(tf.logging.ERROR) # Remove tf warnings import numpy as np from time import time import os, shutil, random NUM_CLASSES = 10 def CNN_withnoise(images, param_placeholders, scopes_list,laye...
import sys from argparse import ArgumentParser from importlib import import_module from typing import Any from .recorder import TestRecorder, DefaultTestRecorder from .runner import TestRunner, DefaultTestRunner, StopStrategy, RetryStrategy from .task import TestTask, DefaultTestTask class TestAuto: def __init_...
from typing import Dict from typing import List from typing import Optional from typing import Tuple import torch import torch.nn as nn import torch.nn.functional as F from tkdet.config import configurable from tkdet.layers import ShapeSpec from tkdet.layers import cat from tkdet.layers import smooth_l1_loss from tkd...
from tkinter import * from copy import deepcopy import random class Move: def __init__(self, x, y, p): self.x = x self.y = y self.p = p class Moves: def __init__(self): self.moves = [] def add(self, move: Move): self.moves.append(move) def getMoves(self): ...
import numpy as np import pandas as pd from pandasgui import show class CO2_Simulation(object): def __init__(self, *args, **kwargs): self.name = kwargs.get('name', f'Unnamed Simulation') # zone volume in m³ self.volume = kwargs.get('volume', 5 * 5 * 3) # zone...
from collections import OrderedDict import torch from torchvision import models from torchvision.ops import FeaturePyramidNetwork from dvmvs.config import Config from dvmvs.convlstm import MVSLayernormConvLSTMCell from dvmvs.layers import conv_layer, depth_layer_3x3 fpn_output_channels = 32 hyper_channels = 32 cla...
import tensorflow as tf import tensorflow.contrib.slim as slim import tensorflow.contrib.slim.nets as nets import numpy as np import os import PIL import matplotlib.pyplot as plt os.environ["CUDA_VISIBLE_DEVICES"] = "3,2" plt.switch_backend('agg') _BATCH_SIZE = 50 X = tf.placeholder(tf.float32, [_BATCH_SIZE, 299, 299...
#!/usr/bin/env python3 # Copyright (c) 2019 Cisco and/or its affiliates. # 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...
""" Copyright 2017-2018 yhenon (https://github.com/yhenon/) Copyright 2017-2018 Fizyr (https://fizyr.com) 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-...
#!/usr/bin/env python # coding: utf-8 (see https://www.python.org/dev/peps/pep-0263/) from __future__ import unicode_literals from __future__ import print_function import argparse import sys import os from operator import itemgetter # Django imports from django.core.management.base import BaseCommand, CommandError fr...
from typing import Tuple, Union, Iterable, List, Callable, Dict, Optional import time from abc import abstractmethod import numpy as np from tqdm import tqdm from nnuncert.models.dnnc._sampling import genbeta, genbeta2, gentau, gentau2, genlambda from nnuncert.models.dnnc._func_deriv import compdS, compdS2 from nnun...
import bpy import os import re from . import utils from itertools import chain from importlib import import_module # (Pattern, Prefix, Fade, Outline, DoubleSided, Normal) def gen_mat_pattern(pattern, fade=False, outline=False, doubleSided=False, prefix=None, normal=False): return (re.compile(pattern), prefix, fade, ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Nov 2 15:25:17 2018 @author: chris """ #%% import os base_path = 'C:\\Users\\sheld\\Desktop\\比赛\\knowledge_graph' file_path = os.path.join(base_path, 'rawdata', 'ruijin_round1_train2_20181022', '0.txt') file_ano_path = os.path.join(base_path, 'rawdata...
# Copyright (c) 2015 OpenStack Foundation. # 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...
import maml_rl.envs import gym import numpy as np import torch import json import sys import pickle import time import timeit from maml_rl.metalearner import MetaLearner from maml_rl.policies import CategoricalMLPPolicy, NormalMLPPolicy from maml_rl.baseline import LinearFeatureBaseline from maml_rl.sampler import Batc...
from flask import (Flask, Response, request, render_template, make_response, redirect) from flask_restful import Api, Resource, reqparse, abort import json import string import random # from functools import wraps from datetime import datetime # parse new archive post request archives_parser = reqp...
from os import environ from copy import deepcopy from pytest import fixture, raises from time import sleep from time import time import docker from .brain import r from .brain.controller import plugins CLIENT = docker.from_env() HARNESS_ID = "111-AAA" HARNESS_NAME = "Harness" TEST_PLUGIN_DATA = { "id": HARNESS_I...
import logging import sys from collections import OrderedDict import torch import torchvision.models as models from torch.utils import model_zoo from torchvision.models.resnet import BasicBlock, model_urls, Bottleneck import torch.nn.functional as F import skeleton import torch.nn as nn import math import pdb from to...
import torch from torch import Tensor from torch.nn import Linear, BatchNorm1d, Module, Sequential, ReLU from torch_geometric.nn import MessagePassing, global_mean_pool from torch_geometric.utils import dense_to_sparse, remove_self_loops import torch_geometric.transforms as T from torch_geometric.datasets import QM9 fr...
import OpenGL.GL as GL import pygame import numpy import math vertex_shader = """ #version 330 in vec2 position; in vec2 coord; uniform mat4 model; uniform mat4 view; uniform mat4 projection; out vec2 texcoord; void main() { vec4 pos = vec4(position.xy, 1.0f, 1.0f); gl_Position = projection * view * model ...
from base import * def analyse_performance_with_stimuli_tonefreq(analysis, estimator, tonefreqkey='tonefreq', fraction=1.0): sn_level_range = analysis.moresettings['sn_level_range'] bins = analysis.moresettings['tonefre...
# parser for Structure_Info.txt files # author: <NAME> # # i'm calling sections and headers ('---...---' and '[...]') as contexts (ctx) # every context is given a unique name (heading, unique id among headings) # useful info is available in: # 1. ctx_dict: a dict from context name to a dict of feature names and values ...
import re import os import sys import json import shlex import logging import argparse from evaluators import SomeEvaluator as Some from evaluators import AllEvaluator as All from comparers import * logging.basicConfig() class Queue: def __init__(self, init=None): self._items = init if init is not None ...
#!/usr/bin/python3 # first pass assembles everything but does not resolve labels # second pass just adds in the label vales # # must throw an error on all errors with a useful error message (file, lineno, line) # ## currently used # lab: # var[n]: # var[]: 1 2 3 4 # var[n]: 1 2 3 4 # :const # ## required extensions # ...
# Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # import numpy as np import math, os, pdb, sys, glob from os import path as osp from pathlib import Path lib_dir = (Path(__f...
# From notion.collection from typing import Callable, List import re from notion.block import CollectionViewBlock, TextBlock TAB = 2 class PageBaseBlock: def __init__(self, _id="unknown", _type="unknown", _children=[]): self.id = _id self.type = _type self.children: List[PageBaseBlock] =...
# -*- coding: utf-8 -*- # # This file is part of Karesansui. # # Copyright (C) 2009-2012 HDE, Inc. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without lim...
import hmac import base64 import re import string import json import logging from urllib.parse import urlparse from time import sleep from ulauncher.api.client.Extension import Extension from ulauncher.api.client.EventListener import EventListener from ulauncher.api.shared.action.CopyToClipboardAction import CopyToClip...
import gym import numpy as np from vel.exceptions import VelException def take_along_axis(large_array, indexes): """ Take along axis """ # Reshape indexes into the right shape if len(large_array.shape) > len(indexes.shape): indexes = indexes.reshape(indexes.shape + tuple([1] * (len(large_array.sh...
"""optimize over a network structure.""" import argparse import logging import os import copy import matplotlib.pyplot as plt import numpy as np import open3d as o3d import pandas as pd import torch from torch.utils.data import DataLoader from tqdm import tqdm from model import Neural_Prior import config from data i...
from django.contrib.auth import get_user_model from django.db.models import Prefetch, Q from django.http import HttpResponseForbidden from django.shortcuts import get_object_or_404 from django_filters.rest_framework import DjangoFilterBackend from rest_framework import generics, viewsets from rest_framework.decorators ...
import sys import pprint import cProfile import matplotlib.pyplot as plt import numpy as np import radical.utils as ru import radical.pilot as rp import radical.analytics as ra from radical.utils.profile import * from radical.pilot.states import * # -----------------------------------------...
from django.db.models.fields.related import ManyToManyField from django.forms.models import ModelMultipleChoiceField from _helpers.models import areas_ar_en, areas_en from typing import Any, List, Optional, Sequence, Tuple from django import forms from django.contrib import admin from django.contrib.admin.options impor...
r''' In practice, :class:`~pyop.linop.LinearOperator` instances composed of distinct sub-blocks are common. In general, access to both the constituent operators and larger operators is desired. The :mod:`~pyop.block` module provides several functions to help build block instances of :class:`~pyop.linop.LinearOperator`...
import yaml import argparse import os from os import path as osp import argparse import joblib from time import sleep import numpy as np import rlkit.torch.pytorch_util as ptu from rlkit.launchers.launcher_util import setup_logger, set_seed from rlkit.torch.sac.policies import PostCondMLPPolicyWrapper from rlkit.dat...
import unittest from simulator.rate_player import SinglePlayerRating from simulator.game_simulation import GameSimulation from simulator.playoff_simulation import * from simulator.rank_teams import rank_team_all, ranking_teams, sort_win_data from simulator.season_simulation import run_simulation, initialize_playoff ...
import os import os.path as osp import pickle import json import matplotlib.pyplot as plt from scipy.ndimage import gaussian_filter1d import copy import numpy as np from eval import voc_eval sourcedir = '/grogu/user/jianrenw/data/OAK_LABEL_N' annodir = '/grogu/user/jianrenw/data/OAK_TEST/Label' config...