text
stringlengths
8
6.05M
# Attempt to build a program that models and tracks population genetics # Time Tracker & Websites ## 3/31 - 1 hour ## 4/2 - 3 hours ## https://stackoverflow.com/questions/11487049/python-list-of-lists ## https://stackoverflow.com/questions/18265935/python-create-list- ## with-numbers-between-2-values/36002096 ...
from flask import Flask, request, jsonify import db_handler as dh app = Flask(__name__) @app.route("/") def hello(): return "Gym backend" @app.route("/drop_all") def drop_all(): dh.drop_all() return "dropped all" @app.route("/<category>/add", methods=['POST']) def add_entity(category): print...
import pandas as pd import numpy as np import sys from scipy.spatial.distance import jensenshannon from scipy.cluster.hierarchy import dendrogram from matplotlib import pyplot as plt def average_period(period, ts): return ts.loc[:, period[0]:period[-1]].mean(axis=1) def distance_at_place_average(periods, place, t...
class JustCreator: def checkType(ttype): pass def create(con, dni, start, days): pass
__author__ = 'apple' import os from osgeo import ogr shapefile = r"ShapefileTest/GIS_CensusTract_poly.shp" # Path Your Shapefile driver = ogr.GetDriverByName("ESRI Shapefile") dataSource = driver.Open(shapefile, 0) layer = dataSource.GetLayer() for feature in layer: print feature.GetField("SOURCE_3") # Get fiel...
sexo = '' aux = 0 while(aux == 0): sexo = str(input('Digite o sexo [m/f]: ')).lower() if sexo == 'm' or sexo == 'f': aux = 1 else: print('Digitação incorreta, tente novamente.') print('Voce escolher {}.'.format(sexo))
# coding: utf-8 # # VQE Screening # In[1]: scaffold_codeXX = """ const double alpha0 = 3.14159265359; module initialRotations(qbit reg[2]) { Rx(reg[0], alpha0); CNOT(reg[0], reg[1]); H(reg[0]); } module entangler(qbit reg[2]) { H(reg[0]); CNOT(reg[0], reg[1]); H(reg[1]); CNOT(reg[1], reg[0]); } ...
# demo02_dataFrame.py DataFrame示例 import numpy as np import pandas as pd df = pd.DataFrame() print(df) # 通过列表创建DataFrame ary = np.array([1,2,3,4,5]) df = pd.DataFrame(ary) print(df, df.shape) data = [ ['Alex',10],['Bob',12],('Clarke',13) ] df = pd.DataFrame(data, index=['s1', 's2', 's3'], columns...
import numpy as np import torch from torch import nn from torch.nn import functional as F from torch.autograd import Variable class SELayer(nn.Module): def __init__(self, channel, reduction=16): super(SELayer, self).__init__() self.fc = nn.Sequential( nn.Linear(channel, channel // redu...
import csv import json # Constants to make everything easier CSV_PATH = './GEMIDDELDE_NEERSLAG_2016.csv' f = open(CSV_PATH, 'rt') # Reads the file the same way that you did csv_file = csv.reader(f) # Created a list and adds the rows to the list jsonlist = [] for row in csv_file: row = row[0].split(";") # Save ...
#! /usr/bin/env python # -*- coding: utf-8 -*- import os import torch from config import get_args from train_eval import train, evaluate from Utils.utils import get_device, set_seed from Utils.data_utils import load_data, random_dataloader, sequential_dataloader from transformers import ( WEIGHTS_NAME, AdamW, ...
import pandas as pd import matplotlib.pyplot as plt df=pd.read_csv('E:\csvdhf5xlsxurlallfiles\percent-bachelors-degrees-women-usa.csv') print(df.head()) print(df.columns) year=df[['Year']] architecture=df[['Computer Science']] print(architecture) engineering=[['Physical Sciences']] print(engineering) plt.pl...
from bs4 import BeautifulSoup import requests url = "http://www.saramin.co.kr/zf_user/jobs/list/job-category?cat_cd=404&panel_type=&search_optional_item=n&search_done=y&panel_count=y" response = requests.get(url) html = BeautifulSoup(response.text, 'html.parser') ''' company_names = html.select('.company_name') recr...
import os from django.conf import settings from django.http import HttpResponse def get_election_fixture(request): with open( os.path.join(settings.BASE_DIR, "data/elections.json") ).read() as out: return HttpResponse(out, status=200, content_type="application/json")
""" learned from others 2nd approach: hashtable + array - save value: index in hashtable - when delete, swap the target item and the last item in the array, and remove the last item - see ./idea_add.png and ./idea_remove.png Insert Time O(1) Remove Time O(1) GetRandom Time O(1) Space O(n) the ...
# _*_ coding:utf-8 _*_ # choi,judge,player,alien,shoot等都写在这里 # 由于原代码上面几个应用比较乱,改写时要小心且尽量简化 # import random import End room = [[1, 1], [1, 2], [1, 3], [1, 4], [1, 5], [2, 1], [2, 2], [2, 3], [2, 4], [2, 5], [3, 1], [3, 2], [3, 4], [3, 5], [4, 1], [4, 2], [4,...
from typing import Dict, Any class NameItem(object): def __init__(self, data: Dict[str, Any]): self.__data: Dict[str, Any] = data @property def name(self): return self.__data['name'] @property def id(self): return self.__data['id'] @property def category(self): ...
from .APIError import APIError class NoSearchResultsError(APIError): '''Exception thrown when a company cannot be found in the database''' def __init__(self, search): self.search = search self.json_error = self.api_error(self.__repr__()) def __repr__(self): return "No results fo...
from logger import Logger logger_object = Logger("log.txt") logger_object.info("this is FYI") log = Logger("mylog.txt") log.critical("this is a major f up") ''' from singleton import SingletonObject obj1 = SingletonObject() obj1.val = "Hello" print(f"obj1 {obj1}") print("-----") obj2 = SingletonObject() obj2....
from cassandra.cluster import Cluster cluster = Cluster() session = cluster.connect('benchmark') session.execute(""" CREATE TABLE IF NOT EXISTS testing (uid uuid PRIMARY KEY, name text); """) session.execute(""" INSERT INTO testing(uid, name) VALUES(uuid(), 'jon...
test_url = 'https://mercari.com/'
# lesson 1: image classification # export LANG=en_US.utf8 # https://github.com/fastai/course:v3/blob/master/nbs/dl1/lesson1:pets.ipynb import matplotlib import matplotlib.pyplot as plt plt.ion() from fastai import * from fastai.vision import * from fastai.metrics import error_rate path=untar_data(URLs.PETS) print("usin...
import z import math import readchar import csv import buy import os from sortedcontainers import SortedSet import glob import yfinance as yf from pandas_datareader import data as pdr year = "2020" yf.pdr_override() def getDataFromYahoo(astock, cdate): df = None try: print("dl astock: {}".format( asto...
import numpy as np from hilbertcurve.hilbertcurve import HilbertCurve import cloudmetrics def test_hilbert_curve(): """ Test on Hilbert curve (should have fracDim=2) """ mask = np.zeros((512, 512)) p_hil = 8 n_hil = 2 dist = 2 ** (p_hil * n_hil) hilbert_curve = HilbertCurve(p_hil, n_h...
# -*- coding: utf-8 -*- from django.contrib.auth import login from django.shortcuts import redirect, get_object_or_404 from django.contrib.auth.decorators import login_required from django.contrib.auth.decorators import user_passes_test from django.forms.formsets import formset_factory from django.forms.models import ...
from sqlalchemy import TEXT, Column, Integer, String from .database import ENGINE, Base class ArticleOrm(Base): __tablename__ = "ArticleOrm" id = Column("id", Integer, primary_key=True, autoincrement=True, nullable=False) reply_to = Column("reply_to", Integer, nullable=False) assumption_id = Column("...
from spack import * import sys,os sys.path.append(os.path.join(os.path.dirname(__file__), '../../common')) from scrampackage import write_scram_toolfile class CascadeToolfile(Package): url = 'file://' + os.path.dirname(__file__) + '/../../common/junk.xml' version('1.0', '68841b7dcbd130afd7d236afe8fd5b949f017...
#print the index value of every element in the list fr=['bhvaya','komal','khushi','akshuni','divya'] for i in fr: print('Index value of element({}) is:={}'.format(i,fr.index(i)))
# Generated by Django 2.1.5 on 2019-08-05 05:01 from django.db import migrations class Migration(migrations.Migration): atomic = False dependencies = [ ('blog', '0065_auto_20190805_0558'), ] operations = [ migrations.RemoveField( model_name='webgroup', name='a...
#!/usr/bin/python3 import tkinter import random from tkinter import messagebox import math import sys class CalculateNError(Exception): def __init__(self, msg): self.msg = msg gachaProb = [[0, 400000], # R essence [400000, 520000], # SR essence [520000, 560000], # SSR...
import argparse import sys import numpy as np import matplotlib.pyplot as plt import math from orderlib import * from numpy.random import randint from numpy.random import rand from numpy.random import choice from random import randrange from time import perf_counter from math import sqrt from statistics import mean, st...
#!/usr/bin/env python # coding: utf-8 # Copyright (c) Qotto, 2019 from typing import Type # Import BaseEventHandler from tonga.models.handlers.event.event_handler import BaseEventHandler # Import StoreBuilderBase from tonga.stores.manager.kafka_store_manager import KafkaStoreManager # Import BaseProducer from tonga.s...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- def merge_states(states): test_set = set() for state in states: test_set.add(frozenset(state.items())) return [{k: v for k, v in state} for state in test_set]
import datetime date = datetime.datetime.now() print(date) # 2021-09-24 11:22:46.729396 print(date.date()) # 2021-09-24 print(date.time()) # 11:22:46.729396 print( date.year, date.month, date.day, date.hour, date.minute, date.second, date.microsecond, date.weekday(), ) # 2021 9 24 11 22 46 729396 4 customDat...
# -*- coding: utf-8 -*- import pyloco import copy import cartopy import cartopy.util default_projection = "PlateCarree" class EarthPlotTask(pyloco.taskclass("ncplot")): """Create a plot for earth science Examples --------- """ _name_ = "earthplot" _version_ = "0.1.6" _install_requires_ = ["nctools",...
# Copyright 2023 Pulser Development Team # # 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...
# djikstra.py import heapq def relax(graph, costs, node, child): if costs[child] > costs[node] + graph[node][child]: costs[child] = costs[node] + graph[node][child] def dijkstra(graph, source): costs = {} for node in graph: costs[node] = float('Inf') costs[source] = 0 visi...
import numpy as np from numpy.fft import fft, ifft, fftfreq, rfftfreq from astropy.io import ascii,fits from scipy.interpolate import InterpolatedUnivariateSpline, interp1d from scipy.integrate import trapz from scipy.special import j1 import multiprocessing as mp import sys import gc import os import bz2 import h5py ...
import json from datetime import datetime from cryptography.fernet import Fernet from flask import current_app, jsonify, request from flask.views import MethodView from flask_jwt_extended import (create_access_token, create_refresh_token, decode_token, get_jwt_identity, ...
'''class A: def hi(self): print ("Say Hi") class B(A): def hi(self): print ("Say hello") b=B() b.hi() ''' # overriding without inheritance based on object execution happens class A: def hi(self): print ("Say Hi") class B: def hi(self): print ("Say hello") def common(tes...
from __future__ import division from django.shortcuts import render # Create your views here. from django.shortcuts import render, get_object_or_404 from .models import Target from .models import TargetForm from .models import ProbesForm from .models import * from .atlas_request_creation import atlas_api_call from .a...
import dash_bootstrap_components as dbc from dash import html from .util import make_subheading table_header = html.Thead( html.Tr( [ html.Th("#"), html.Th("First name"), html.Th("Last name"), ] ) ) table_body = html.Tbody( [ html.Tr( ...
# -*- coding: utf-8 -*- """ Created on Thu Dec 24 15:37:25 2015 @author: HSH """ class Solution(object): def createLine(self, words, L, start, end, totLen, isLast): result = [] result.append(words[start]) n = end - start + 1 if n == 1 or isLast: for i in range(start+1, ...
w, h = 1050, 600 colors = [(188, 216, 193), (214, 219, 178), (227, 217, 133), (229, 122, 68)] colors = [(219, 177, 188), (211, 196, 227), (143, 149, 211), (137, 218, 255)] colors = [(191, 107, 99), (217, 163, 132), (91, 158, 166), (169, 212, 217)] grid_x = 22 grid_y = 22 grid_x_pixels = 1200 grid_y_pixels = 1200 se...
# -*- coding: utf-8 -*- """mods.py: Module loader for the IRC bot. Loader for commands and listeners. TODO: * Refactor<3 """ import os import sys import time import string import random import imp # Symbian S60 specific compatibility s60 = False if sys.platform == "symbian_s60": s60 = True sys.path.append("...
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations import dataclasses import itertools from dataclasses import dataclass from typing import Any, Iterator, cast from pants.build_graph.address import BANN...
import pygame, sys, time, random from pygame.locals import * import numpy as np import math import joblib # import Parallel, delayed import multiprocessing class Particle: """ @summary: Data class to store particle details i.e. Position, Direction and speed of movement, radius, etc """ def __init...
# -*- coding: utf-8 -*- """ Created on Wed Jun 10 14:47:14 2020 @author: logun """ from scipy import ndimage import matplotlib.pyplot as plt import numpy as np import kernel_function as kf import cv2 img = cv2.imread('ring.png', cv2.IMREAD_GRAYSCALE) plt.figure(dpi=700) dims = img.shape #find start point: def sta...
from math import log from drivingenvs.vehicles.ackermann import AckermannSteeredVehicle from drivingenvs.envs.driving_env_with_vehicles import DrivingEnvWithVehicles from yarp.envs.torchgymenv import TorchGymEnv from yarp.envs.unsupervised_env import UnsupervisedEnv from yarp.policies.tanhgaussianpolicy import TanhGa...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Aug 31 15:13:57 2017 @author: mulugetasemework """ # encoding: UTF-8 # Copyright 2016 Google.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 co...
# coding: utf-8 """ Copyright 2016 SmartBear Software 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 applica...
# # @lc app=leetcode.cn id=188 lang=python3 # # [188] 买卖股票的最佳时机 IV # # @lc code=start class Solution: def maxProfit(self, k: int, prices: List[int]) -> int: """DP table: 最多进行k次交易""" if not prices: return 0 n = len(prices) dp = [[[0, -float("inf")]] * (k+1)] * n f...
import pandas as pd from avg_fun import kde_wavg def agg_itineraries(points_merged, CONFIG): # TODO is this still needed the escape below if points_merged.empty: return None grouped = points_merged.groupby(['mot_segment_id', 'itinerary_id']) diagnostics = grouped.agg({ 'distance': ...
# Chaining class HashTable: def __init__(self, hash_func=None, bucket_size=16): if hash_func is None: self.hash_func = hash else: self.hash_func = hash_func self.bucket_size = bucket_size self.bucket = [None] * bucket_size def set(self, key, valu...
while True: valor = int(input('Qual valor você quer saber a tabuada? ')) if valor >= 0: print(10*'=-=') for i in range(1,11): print(f'{valor} x {i} = {valor * i}') print(10*'=-=') else: break print('Obrigado por acessar')
import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers import load_text embedding_dim = 300 inputs = keras.Input(shape=(54,), name="input_text") embedding_layer = layers.Embedding(load_text.vocab_size, embedding_dim, name="embedding")(inputs) conv_3_layer = layers.Conv1D(100, 3, acti...
from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy import Column, Integer, String from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class People(Base): __tablename__ = 'people' id = Column(Integer, primary_key=True) person_identif...
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Category' db.create_table('product_category', ( ('id', self.gf('django.db.models...
# deployment #DIRECTORY_ADDRESS = 'tcp://127.0.0.1:10001' import sys import os import fabric.api as fabi # sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../..'))) # import config_main as cfg # import config_private as private CONTRACT_GAS = "0x1000000000" # TRANSACTION_GAS = "0x1000000"...
from gym_tic_tac_toe.envs.tic_tac_toe_env import TicTacToeEnv # from gym_tic_tac_toe.envs.gym_tic_tac_toe_extrahard_env import TicTacToeExtraHardEnv
from Server import flask if __name__ == '__main__': # Main method flask.run(port=8088, debug=False, threaded=True, host="127.0.0.1") # Starts server
from pyspark.sql.functions import udf from pyspark.sql.types import ArrayType, StringType import json def regist_udf_str2arr(ss,logger): logger.info("注册str2arr UDF", event="regist_udf") def string2array(str): if len(str) : return ','.join(json.loads(str)) # arr = str.replace('\...
import config_readers import os from unittest.mock import Mock from mock import patch class TestReader: def test_local_reading_config(self): reader = config_readers.LocalUserConfigReader('./tests/fixtures/test_user_configs/') res = reader.get_config_files() assert len(res) == 2 def te...
# _compat.py - Python 2/3 compatibility import sys PY2 = sys.version_info[0] == 2 if PY2: # pragma: no cover text_type = unicode def iteritems(d): return d.iteritems() else: # pragma: no cover text_type = str def iteritems(d): return iter(d.items())
from mpl_toolkits.mplot3d import Axes3D import numpy as np import matplotlib.pyplot as plt import cv2 from sklearn.cluster import DBSCAN from extra_functions import cluster_gen import pcl import numpy as np import matplotlib.cm as cm def DBScan(): # Load Point Cloud file cloud = pcl.load_XYZRGB('./test_rgb.pcd') #...
#Created on 1/22/2015 #@author: Ryan Spies (rspies@lynkertech.com) # Python 2.7 # This script reads CHPS csv file from QIN plot display and finds the start and end # of the observed hourly QIN record, # of valid data points, and % of total available. # Outputs summary data to csv file import os import pandas ...
# -*- coding: utf-8 -*- """ Created on Thu Apr 18 12:43:31 2019 @author: hi """ from tkinter import * import csv import pandas as pd import numpy as np import sklearn as sk import keras from keras.models import Sequential from keras.layers import Dense from sklearn.model_selection import train_test_spl...
from .dry_plugin_quart import ( test_quart_doc, test_quart_no_response, test_quart_return_model, test_quart_skip_validation, test_quart_validate, test_quart_validation_error_response_status_code, ) __all__ = [ "test_quart_return_model", "test_quart_skip_validation", "test_quart_vali...
table = ['a', 'b', 'c', 'd', 'e'] space = ' ' print(space.join(table))
import numpy as np import json import pickle from ELMo.ELMoForManyLangs.elmoformanylangs import embedder from ELMo.sent2elmo import sent2elmo class Embedder: """ The class responsible for loading a pre-trained ELMo model and provide the ``embed`` functionality for downstream BCN model. You can modify...
from rest_framework import serializers from .models import Stock class StockSerializer(serializers.ModelSerializer): is_tracking = serializers.SerializerMethodField(read_only=True) class Meta: model = Stock fields = ['ticker', 'company_name', 'is_tracking'] def get_is_tracking(self, obj...
# -*- coding: utf-8 -*- # Generated by Django 1.9.8 on 2016-08-03 13:12 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('products', '0003_auto_20160803_1249'), ] operations = [ migrations.AlterFiel...
#!/bin/python3 import math import os import random import re import sys # Complete the plusMinus function below. def plusMinus(arr): myArr = {0:0, 1:0, -1:0} for i in arr: if i == 0: myArr[0]+=1 elif i <0: myArr[-1]+=1 else: myArr[1]+=1 positiv...
from pynput import keyboard import os from random import choice from colorama import init, Fore, Back, Style # colorama init init(autoreset=True) NEW_ELEMENTS_CHOICE = [1, 1, 2] COLORS = { '.': Fore.WHITE, 0: Fore.WHITE, 1: Fore.WHITE, 2: Fore.BLUE, 4: Fore.CYAN, 8: Fore.GREEN, 16: Fore....
from .torchvggish import * from .vggish_input import * from .vggish_params import * name = "torchvggish"
from PikaObj import * class Operator(TinyObj): def plusInt(self, num1: int, num2: int) -> int: ... def plusFloat(self, num1: float, num2: float) -> float: ... def minusInt(self, num1: int, num2: int) -> int: ... def minusFloat(self, num1: float, num2: float) -> float: ... def equalInt(self, num1: ...
import glob, os, sys import numpy as np from random import* import matplotlib.pyplot as plt import matplotlib.cm as cmx import matplotlib.colors as colors def get_rand_color(val): h,s,v = random()*6, 0.5, 243.2 colors = [] for i in range(val): h += 3.75#3.708 tmp = ((v, v-v*s*abs(1-h%2), v-...
import traceback import numpy as np import cv2,random,os,sys from time import sleep as tmSleep import logging import time from moviepy.audio.io.AudioFileClip import AudioFileClip import xlrd from openpyxl import load_workbook from datetime import datetime from moviepy.video.io.VideoFileClip import VideoF...
# -*- coding: utf-8 -*- from __future__ import unicode_literals __author__ = 'avasilyev2' import db_work import pymongo from pymongo import MongoClient client = MongoClient('mongodb://admin:pass@ds062807.mongolab.com:62807/games') db = client['games'] collection = db['general_collection'] collection.remove({"shop":...
#! /usr/bin/env python # -*- coding: utf-8 -*- # According to: http://liangjiabin.com/blog/2015/04/leetcode-best-time-to-buy-and-sell-stock.html class Solution(object): def maxProfit(self, prices): if not prices: return 0 max_profit = 0 for i in range(1, len(prices)): ...
script_game_start = 0 script_game_get_use_string = 1 script_game_quick_start = 2 script_get_army_size_from_slider_value = 3 script_spawn_quick_battle_army = 4 script_player_arrived = 5 script_game_set_multiplayer_mission_end = 6 script_game_enable_cheat_menu = 7 script_game_get_console_command = 8 script_game_event_par...
import dicom import os import numpy as np from matplotlib import pyplot as plt from matplotlib import cm import csv # indicate path to image data PathDicom = "C:\\Users\\David\\Documents\\CT\\CT_data\Images" lstFilesDICOM = [] # read all images in path for dirName, subdirList, fileList in os.walk(PathDicom): for fil...
s=input() l=len(s) c=0 w='' lw=0 for i in range(l): if(s[i]==''): c=c+1 else: w=w+s[i] if(w[0]=='a' or w[0]=='e' or w[0]=='i' or w[0]=='o' or w[0]=='u'): print(w)
from django.db import models from django.conf import settings # Create your models here. class Message(models.Model) : message = models.TextField() sender = models.ForeignKey(settings.AUTH_USER_MODEL,related_name="messages",on_delete=models.CASCADE,null=True) timestamp = models.DateT...
# -*- coding: utf-8 -*- """ Created on Tue Dec 22 22:37:22 2015 @author: HSH """ """ # DP solution # Time Limite Exceeded class Solution(object): """ class Solution: # DP solution # Time Limite Exceeded def isMatch_v1(self, s, p): m = len(s) n = len(p) dp = [[False] * (m + 1...
# Random Forest Regression
import math p,q = map(int,input().split()) if p%q != 0: print(p) pass
import os import re def __main__(): """One time utility script ran for changes in attribute instantiation. This script performs the below, one-time conversion on all attributes of SpotiBot classes - this is done so that the same codes can instantiate json API responses and serialized objects stored ...
import pandas as pd import matplotlib.pyplot as plt ######### def SO(max_so=7,start_so=1,last_so=0,so=.02, so_step=1.1): if start_so == 1: last_so = so else: last_so = so + last_so*so_step if start_so < max_so: start_so+=1 return SO(max_so=max_so,start_so=start_so,last_so=l...
#!/usr/bin/env python import rospy import tf from sensor_msgs.msg import Imu def callbackIMU(data): br = tf.TransformBroadcaster() br.sendTransform((0, 0, 2), (data.orientation.x,data.orientation.y,data.orientation.z,data.orientation.w), rospy.Time.now(), "cns5000_frame", "map") ''' br2 = tf.T...
import urllib.request from numpy.core.fromnumeric import searchsorted import pandas as pd from datetime import datetime,timedelta import requests import xmltodict import openpyxl url_base = 'http://openapi.data.go.kr/openapi/service/rest/Covid19/getCovid19SidoInfStateJson?serviceKey=' url_serviceKey = 'XK5R2J%2B6nCIWN...
from __future__ import absolute_import, division, unicode_literals from six.moves.urllib.parse import urlencode from twisted.trial.unittest import SynchronousTestCase from twisted.internet.task import Clock from mimic.core import MimicCore from mimic.resource import MimicRoot from mimic.test.helpers import json_requ...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse from functools import partial import json import traceback import imlib as im import numpy as np import pylib import tensorflow as tf import tflib as tl import data import models # ========...
# write by yqyao # import os import pickle import os.path import sys import torch import torch.utils.data as data import torchvision.transforms as transforms import cv2 import numpy as np from PIL import Image from data.config import mydataset as cfg from sklearn.preprocessing import LabelEncoder, OneHotEncoder class...
from .AssetBrowser import AssetBrowser from bsp.leveleditor import MaterialPool from PyQt5 import QtCore, QtGui class MaterialBrowser(AssetBrowser): FileExtensions = ["mat"] Thumbnails = {} def getThumbnail(self, filename, context): # Delay the thumbnail loading so we don't freeze the applicati...
def coin_problem(value, coin_list): coin_list = sorted(coin_list, reverse = True) count_coin = [0 for _ in range(len(coin_list))] for idx, coin in enumerate(coin_list): num_coin = int(value // coin) count_coin[idx] = num_coin value -= coin * num_coin return count_coin def fracti...
x = fetch.Msidset(['PM3THV1T','PM3THV2T','PM4THV1T','PM4THV2T'], '2013:002:05:00:00.000','2013:002:07:00:00.000') close('all') subplot(2,1,1) x['PM3THV1T'].plot('b', label='PM3THV1T') x['PM3THV2T'].plot('r', label='PM3THV2T') title('Sample MUPS-3 Temperatures during Heater Cycles') legend() subplot(2,1,2) x['PM4THV...
__author__ = 'sudoz' import mymodule mymodule.say_hi() print('version is', mymodule.__version__)
# Sean Kim # Unit 3 Review Problem 4 def mean (my_list): sum = 0 for num in list: sum += num return sum list = []
import copy import sys INPUT = "1,0,0,3,1,1,2,3,1,3,4,3,1,5,0,3,2,1,10,19,1,6,19,23,1,10,23,27,2,27,13,31,1,31,6,35,2,6,35,39,1,39,5,43,1,6,43,47,2,6,47,51,1,51,5,55,2,55,9,59,1,6,59,63,1,9,63,67,1,67,10,71,2,9,71,75,1,6,75,79,1,5,79,83,2,83,10,87,1,87,5,91,1,91,9,95,1,6,95,99,2,99,10,103,1,103,5,107,2,107,6,111,1,111...