text
stringlengths
8
6.05M
#!/usr/bin/env python3 import rospy import numpy as np from sensor_msgs.msg import Image,CameraInfo from cv_bridge import CvBridge, CvBridgeError import tf from std_msgs.msg import String,Int64MultiArray from geometry_msgs.msg import * from vision_msgs.msg import Detection2DArray def objects_callback(data): glob...
import cv2 as cv import matplotlib.pyplot as plt from copy import deepcopy def read_image(img): return cv.imread(img) def create_binary_mask(rgb_image): imgYCrCb = cv.cvtColor(rgb_image, cv.COLOR_RGB2YCrCb) mask = cv.inRange(imgYCrCb, (0, 133, 77), (255, 173, 127)) return mask def fit_ellipse(mask_...
#!/usr/bin/env python # Software License Agreement (BSD License) # # Copyright (c) 2015, Robotnik Automation SLL # 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...
import pytest from aws_lambda_context import LambdaContext from moto import mock_ecs from src.handler import * @mock_ecs def test_that_the_lambda_handler_succeeds_with_context(ecs, sns_event): lambda_context = LambdaContext() lambda_context.function_name = "lambda_handler" lambda_context.aws_request_id =...
# Generated by Django 3.2 on 2021-04-30 22:20 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('movie', '0007_quote'), ] operations = [ migrations.AlterModelOptions( name='quote', options={'verbose_name': 'Киноцита...
#!/usr/bin/env python # # Copyright (c) 2019 Opticks Team. All Rights Reserved. # # This file is part of Opticks # (see https://bitbucket.org/simoncblyth/opticks). # # 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...
hrs = raw_input("Enter Hours:") try: h = float(hrs) except: h = float(raw_input("Enter a numeric hours:")) rate = raw_input("Enter Hourly Rate:") try: r = float(rate) except: r = float(raw_input("Enter a numeric rate:")) if h <= 40: pay = h * r else: pay = 40 * r + (h - 40) * r * 1.5 prin...
print("Or") a="Or " print(a*3) print(a*100)
#!/usr/bin/ipython import GreenF import sys import DensityN import numpy as np import matplotlib.pyplot as plt print("please select variable set:\n") print("1) m=1, alpha=0, beta=0, B0=1") print("2) m=1, alpha=1, beta=0, B0=0") print("3) m=1, alpha=0, beta=1, B0=0") print("4) m=10, alpha=1, beta=0, B0=0") print("5...
import sys from tree import binary_tree input_list = [1, -2, 9, -3, 5, -1, 11]; tree = binary_tree(input_list); #print all the different levels of the tree print("LIST OF ALL LEVELS:"); tree.print_tree();
#!/usr/bin/env python # coding: utf-8 # # # Python Program to check values of Riemann's Zeta-Function # # Powered by: Dr. Hermann Völlinger, DHBW Stuttgart(Germany); September 2020 # # See https://en.wikipedia.org/wiki/Riemann_zeta_function # # YouTube Video: https://www.youtube.com/watch?v=sZhl6PyTfl...
""" Math 560 Project 2 Fall 2021 project2.py Partner 1: QiangQiang Liu Partner 2: Zelin Jin Date: 11/01/2021 """ # Import math and other p2 files. import math from p2tests import * """ BFS/DFS function INPUTS maze: A Maze object representing the maze. alg: A string that is either 'BFS' or 'DF...
#!/usr/bin/env python from collections import namedtuple class Student: def __init__(self, name, number, tb1_experiments, tb2_experiments, pair_number, lang="en"): self.name = name self.number = number self.tb1_experiments = tb1_experiments self.pair_number = pair_number se...
from flask import Flask from flask_restful import Resource, Api app = Flask(__name__) api = Api(app) class product(Resource): def get(self): return { 'products' : ['ice cream', 'chocolate', 'Fruit'] } api.a...
import c4d import random from c4d import gui def main(): obj1 = doc.SearchObject("Cube"); #Where Cube is made editable, Type: c4d.PolygonObject #For each point on "Cube" for x in range(obj1.GetPointCount()): #Set that point with itself minus a random number from 0 to 10 ...
#!/usr/bin/env python # -*- coding: utf-8 -*- __mtime__ = '2019/5/9' from selenium import webdriver from common.base import Base import time class AddBugPage(Base): loc_test=("link text","测试") loc_bug =("xpath",".//*[@id='subNavbar']/ul/li[1]/a") # loc_add =("xpath",".//*[@id='mainContent']/div[2]/div[2]...
queries = ["" for i in range(0, 11)] ### 0. List all airport codes and their cities. Order by the city name in the increasing order. ### Output column order: airportid, city queries[0] = """ select airportid, city from airports order by city; """ ### 1. Write a query to find the names of the customers whose names ar...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Apr 3 17:04:17 2018 @author: daehyun """ from pickle import loads from pymongo import MongoClient from cytoolz import pipe, filter, partial from pandas import DataFrame import matplotlib.pyplot as plt # %% db = MongoClient('lithium.local')['FERMI_20...
import pyeapi from pprint import pprint import yaml from my_funcs import read_yaml from jinja2 import FileSystemLoader, StrictUndefined from jinja2.environment import Environment yaml_devices = read_yaml("devices.yaml") env = Environment(undefined=StrictUndefined) env.loader = FileSystemLoader('.') template_file = '...
#!/usr/local/bin/python # -*- coding: utf-8 -*- from django.conf.urls import url, include, handler404, handler500 from shop import views from django.contrib.auth import views as auth_views urlpatterns = [ # -- Pour les produits url(r'^categorie/(?P<id>\d+)/$', views.categorie, name="categorie"), url(r'^...
from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.utils.translation import ugettext_lazy as _ from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Fieldset class RegistrationForm(Us...
hours=2 minuts=0 seconds=0 import time from turtle import * setup() t=Turtle() while True: t.clear() t.write(str(hours).zfill(2)+":"+str(minuts).zfill(2)+":"+str(seconds).zfill(2), font=("arial",30,"normal")) seconds=seconds+1 time.sleep(1) if seconds==60: seconds=0 minuts=minuts+1 ...
import json from django.shortcuts import render from django.http import JsonResponse,HttpResponse from rest_framework import serializers from .models import Employee from .serializer import EmployeeSerializer,UserSerializer from django.contrib.auth.models import User from django.views.decorators.csrf import csrf_exempt...
from matplotlib.colors import colorConverter import matplotlib.pyplot as plt import numpy as np import matplotlib as mpl # create dummy data zvals = np.ones((100,100))# np.random.rand(100,100)*10-5 zvals2 = np.random.rand(100,100)*10-5 # generate the colors for your colormap color1 = colorConverter.to_rgba('white') c...
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-03-03 10:07 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('KawsWebEnter', '0001_initial'), ] operations = [ migrations.CreateModel( ...
# coding: utf-8 from __future__ import absolute_import import struct from datetime import datetime import logging from celery import signals from celery.task.control import revoke import zmq import gevent.monkey # we need gevent to use 'then' on AsyncResult gevent.monkey.patch_all() from . import worker from .state ...
#!/usr/bin/env python3 # Splits data into training, validation, test and probe sets data_path = 'dataset/um/' with open(data_path + 'all.dta', 'r') as dat, open(data_path + 'all.idx', 'r') as idx: with open(data_path + 'base.dta', 'w') as base, open(data_path + 'valid.dta', 'w') as valid, \ open(data_p...
import yfinance as yf import pandas as pd import numpy as np import pandas_datareader as web import matplotlib.pyplot as plt from datetime import date import datetime as dt #This code can help one see how their stocks have performed compared to the market index. (SPY) ans1 = input("Enter your Ticker symbol:") ans2 = in...
import paramiko ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) #明文实现的ssh连接 ssh.connect(hostname="10.20.220.105",port="22",username="jor",password="123456") stdin,stdout,stderr = ssh.exec_command('df') res,err = stdout.read(),stderr.read() result = res if res else err print(re...
class DataExtractor: def __init__(self,txtFile): self.txtFile = txtFile def parseTextFile(self): with open(self.txtFile) as f: textMessages = f.read() msgs = [] outputs = [] for textMessage in textMessages.split('\n'): if(not(textMe...
def solution(n, m): gcd = 1 for i in range(min(n, m), 0, -1): if n % i == 0 and m % i == 0: gcd = i break lcm = 0 for i in range(max(n, m), n * m + 1): if i % n == 0 and i % m == 0: lcm = i break return [gcd, lcm]
from django.shortcuts import render, redirect from .models import Contact # Create your views here. def contact_form(request): if request.method == 'POST': user_type = request.POST['user_type'] name = request.POST['user_name'] email = request.POST['user_email'] phone_number = request.POST['user_phone'] com...
#!/usr/bin/env python import requests import glob import os import json dv_endpoint = 'http://localhost:8080/dataverse_stub/published' def release_all( data_dir = 'data' ): for fn in glob.glob('%s/*.json' % data_dir ): with open(fn,'r') as inp: x = json.load( inp ) dataset_release...
from .influx_object import InfluxObject from .csv_object import CSVObject from .exporter_object import ExporterObject from .base_object import BaseObject from .__version__ import __version__ from .config_object import Configuration from .command_object import export_csv_to_influx
from mpi4py import MPI comm = MPI.COMM_WORLD rank = comm.Get_rank() if rank == 0: data = {'a': 7, 'b': 3.14} comm.isend(data, dest=1, tag=11) comm.isend(data, dest=2, tag=11) comm.isend(data, dest=3, tag=11) elif rank == 1 or rank == 2 or rank == 3: data = comm.irecv(source=0, tag=11) print("...
#!/usr/bin/env python # -*- coding: cp1252 -*- # AUTHOR # # Daniel Jimenez Martinez (razorbreak@gmail.com) # # DESCRIPTION # # AiMasterMind es un juego en el que dos IAs (Inteligencias Artificiales) se # enfrentan por ver quien de ellas descubre una contraseņa generada # aleatoriamente antes que su rival. # La idea d...
class Solution: def addDigits(self, num: int) -> int: while True: ans = 0 while num: ans += num % 10 num //= 10 if ans < 10: return ans else: num = ans # 进阶 O(1)的时间复杂度? # 差值为9的倍数,%9可得各位和 class ...
from django.contrib.auth.forms import UserCreationForm from django.views.generic import ListView, CreateView, UpdateView, DeleteView, DetailView from .models import Equipo, Ticket, Empleado from .forms import EquipoForm, TicketForm, EmpleadoForm, UserRegisterForm from django.contrib import messages from django.shortcu...
#!/usr/bin/env python from distutils.core import setup setup( name='IPMap', version='1.0', description='Map IPv4 addresses to Hilbert curve', author='Daniel Miller', author_email='bonsaiviking@gmail.com', url='https://github.com/bonsaiviking/IPMap', packages=['ipmap'], ...
from random import choice print "Hi I want to play Rock, Paper Scissiors!" print "Ready? Let's play best out of three!" print "Make your move! (r,p, s, or q to quit)" move = raw_input ("Enter: ") def rock_paper_scissors(move, my_score, your_score): x = choice ("rps") if x == "r" and move == "r": print "I play R...
from django.contrib import admin from .models import Answer, Question, QuestionItem, Result, ResultItem, Test class AnswerAdmin(admin.StackedInline): # model = Answer.answers.through model = Question.answers.through extra = 0 class QuestionItemAdmin(admin.StackedInline): model = QuestionItem ex...
# Write a program that accepts sequence of lines as input and prints the lines after making all characters in the sentence capitalized. # Suppose the following input is supplied to the program: # Hello world # Practice makes perfect # Then, the output should be: # HELLO WORLD # PRACTICE MAKES PERFECT print('Please, wr...
#-*- coding:utf8 -*- # Copyright (c) 2020 barriery # Python release: 3.7.0 # Create time: 2020-03-14 import json from google.protobuf import text_format from . import database from .proto import entity_pb2 from .proto import result_pb2 def parse_json_to_entity(jsonObj, entype): def parse_App(jsonObj): en...
# -*- coding: utf-8 -*- from selenium import webdriver from selenium.webdriver.common.keys import Keys import hashlib import random class ScrapyPages: #网页内容保存目录 contentDir = "D:\\pages\\" #网页链接保存目录 atagsDir = "D:\\atags\\" #保存网页与文件名对应关系的文件 mappingFile = "D:\\mapping" #已处理的链接 handledLin...
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations import logging import shlex from dataclasses import dataclass from pants.backend.shell.subsystems.shell_setup import ShellSetup from pants.backend.shel...
import sys print sys.argv x = sys.argv y = x[1::] print list(y) x=1 for i in y: x = int(i) * int(x) print str(x)
class Memory: def __init__(self,internal, secondary, ram): self.internal=internal self.secondary=secondary self.ram=ram def getinfo(self): print("INTERNAL :{} \n secondary :{} \n and ram :{}\n".format(self.internal,self.secondary,self.ram)) class Properti...
import argparse import numpy as np import torch import torchvision.transforms as transforms from torch.utils.tensorboard import SummaryWriter from load_data import generate_data from trainer import Trainer # Command Line Arguments parser = argparse.ArgumentParser() parser.add_argument("--train-epoch", default=50, ty...
from mesa import Model, Agent from mesa.time import RandomActivation from mesa.space import SingleGrid from mesa.datacollection import DataCollector class SchellingAgent(Agent): ''' Define the Agent One of the core class ''' def __init__(self, pos, model, agent_type): ''' Create a...
#coding:gb2312 #在3.4的基础上,添加一条print语句,指出哪位无法赴约;修改名单,将无法赴约的替换为新的;再次打印一系列信息发出邀请。 Friends=['cby','sch','fjy','lq'] message=", "+"Would You like To Have Dinner With Me"+"?" print(Friends[-1].title()+", "+"Can't Have Dinner With Me"+".") Friends[-1]='ljy' print(Friends[0].title()+message) print(Friends[1].title()+message) pr...
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations import logging from dataclasses import dataclass from itertools import chain from typing import Any from pants.backend.docker.goals.package_image impor...
False #data type, true or false, called boolean True print(1 == 2) #False print(1 < 2) #True print(1 > 2) #False print(1 >= 1) #True print(1 <= 2) #True print(1 != 1) #False a = 1 b = 2 print(a == b) #False name = "Chad" print(name == "Chad") #True print(name != "George") #True b/c this is a true state...
import codecs import http.client import json import ssl import threading from multiprocessing import Pool from urllib.request import urlopen """Script to print the last comments of Hacker News users before they are banned. Reads from the Hacker News API: https://github.com/HackerNews/API) This is my first time writ...
def gcdTwoNumbers(a,b): if(b==1): return b #base case if(a%b==0): return b return gcdTwoNumbers(a,b/2) result1=gcdTwoNumbers(2,1) result2=gcdTwoNumbers(8,4) result3=gcdTwoNumbers(160,8) print ("The results are:",result1,result2,result3)
from pathlib import Path import pandas as pd base_path = Path('.\\code\\') summary = pd.DataFrame(columns=['dice', 'precision', 'recall', 'true_positives', 'true_negatives']) for i in base_path.glob('res*'): name = str(i)[8:-4] with open(str(i)) as f: f.readline() for line in f.readlines...
#!/usr/bin/python import sys import re import urllib import urlparse for line in sys.stdin: regexp = '(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}) (.+) (.+) \[(.+)\] \"([A-Z]+) (.+) HTTP/.\..\" (.+) (.+)' match = re.match(regexp, urllib.unquote(line.strip())) if match: ip, client, username, time, type, fi...
from collections import defaultdict, deque, Counter import sys from decimal import * from heapq import heapify, heappop, heappush import math import random import string from copy import deepcopy from itertools import combinations, permutations, product from operator import mul, itemgetter from functools import reduce,...
import re class Option: ''' ''' def __init__(self, need, limit, name=None, sign=None): ''' ''' self.need = need self.limit = limit self.name = name self.sign = sign self.param = [] def add_param(self, item): ''' 加入参数 '''...
from django.contrib.auth import authenticate from django.shortcuts import render from rest_framework.exceptions import PermissionDenied from rest_framework.permissions import IsAuthenticated, IsAdminUser from rest_framework.response import Response from rest_framework import viewsets, generics, status, parsers, respons...
import requests url = "http://127.0.0.1:5000/pms/dm/v1.0/application/update"
from string import ascii_lowercase def main(): # Shift characters by 2 positions cipher = ('g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc ' 'dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr\'q ufw rfgq rcv' 'r gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lm...
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations import pytest from pants.backend.python.subsystems.setup import PythonSetup from pants.core.goals.generate_lockfiles import UnrecognizedResolveNamesErr...
import pandas as pd from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score from sklearn.metrics import classification_report #데이터 읽어들이기 wine = pd.read_csv("./data/winequality-white.csv", sep=';', encoding='utf-8') #데이터를 레이블과 ...
from mlxtend.plotting import plot_decision_regions from mlxtend.classifier import LogisticRegression import pandas import numpy as np from sklearn import linear_model from sklearn.model_selection import cross_val_score as cvsc set_sizes = [100,500,1000,5000,10000,50000,100000,500000,1000000,5000000,10000000,500000...
import logging from db_objects import Story, User, Task from db_session import session logging.basicConfig() logger = logging.getLogger("db_query") logger.setLevel(logging.DEBUG) # Query one task task = (session.query(Task).join(Story).join(User) .filter(Story.story_title == 'Story 001') .filter(User...
from fnp.baseline.task2.utils import * import pandas as pd import argparse from sklearn.model_selection import train_test_split def write_file(file_name, data): with open(file_name, "w") as f: for sent in data: i = 1 for token, tag in sent: f.write(str(i) + "\t" + ...
l = [1,2,3,4,5,6,7,8,9,10] len(l) l.append(11) cpy = l.copy() count = l.count(11) l.clear() sliced = l[1:4] for i in l: print(i) if 11 in l: print("Found 11")
#!/usr/bin/env python # -*- coding: utf-8 -*- """ remotail.py ~~~~~~~~~~~ Tail multiple remote files on a terminal window :copyright: (c) 2013 by Abhinav Singh. :license: BSD, see LICENSE for more details. """ VERSION = (0, 1, 1) __version__ = '.'.join(map(str, VERSION[0:3])) + ''.join(VERSION[3:]...
"""Treadmill cell checkout. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import collections import logging import sqlite3 import sys import click import pandas as pd from treadmill import cli _LOGGER = logg...
""" Model objects for the CLB mimic. Please see the `Rackspace Cloud Load Balancer API docs <http://docs.rackspace.com/loadbalancers/api/v1.0/clb-devguide/content/API_Operations.html>` for more information. """ from __future__ import absolute_import, division, unicode_literals from copy import deepcopy from random ...
import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg import numpy as np import random import tkinter as Tk from grafica import Grafica import vectorEntrenamiento as vE root = Tk.Tk() root.wm_title("...
# -*- coding: utf-8 -*- """ Created on Wed Aug 4 18:06:21 2021 @author: chanchanchan """ import streamlit as st import pandas as pd from matplotlib import pyplot as plt import plotly.express as px import plotly.graph_objects as go import DissertationPlotwithDataMain as main def app(): ...
import math import time import serial import Frequency_Determination as FD import FECLib as fec def loadCharacterSet(SetName): fullName = 'Source/CharacterSets/'+SetName+'.txt' file = open(fullName,'r') fullSet = file.read() validChars = fullSet.split(',') return (validChars) class InputValidation: # prompts...
from django.conf.urls import url from django.contrib import admin from rest_framework.authtoken import views from .views import ( UserCreateAPIView, UserLoginAPIView ) urlpatterns = [ #url(r'^login/$', UserLoginAPIView.as_view(), name='login'), url(r'^sign-up/$', UserCreateAPIView.as_view(), name...
import class_demo6 d = class_demo6.Demo(12, 13) print(d.do_something()) # 檔名: module_demo.py # 作者: Kaiching Chang # 時間: July, 2014
# rolling-around-a-cube.py # Maulik Doshi + Section F + maulikd # 15-112 Term Project Fall 2014 # Rolling Around a Cube from __future__ import with_statement from visual import * import pygame # Used purely for the music functionality import math, random, os pygame.mixer.init() intromusic = pygame.mixe...
# -*- coding: utf-8 -*- # @Author: Safer # @Date: 2016-08-19 00:55:40 # @Last Modified by: Safer # @Last Modified time: 2016-08-22 23:52:12 import sys from PyQt5.QtWidgets import QApplication, QMessageBox from db import DB if __name__ == '__main__': app = QApplication(sys.argv) db = DB() db.from_('te...
import pandas import time def table(): # today's USD exchange rate trend url = 'https://www.fubon.com/Fubon_Portal/banking/Personal/deposit/exchange_rate/exchange_rate1_photo.jsp?urlParameter=1D&currency=USD' pd = pandas.read_html(url) currency = pd[0] return currency def show_buy_table(buy_...
import sys import numpy as np from matplotlib import pyplot as plt import seaborn as sns import equation6 import conic_parameters sys.path.append('../conic-projection') from conproj_utils import Conic import crw_misc_utils def polar_plot(r, th, ax, **kwargs): ax.plot(r*np.cos(th), r*np.sin(th), **kwargs) def om...
import os import math train_data = '/home/s1459234/data/conll2017_data/Turkic-DEL/train/cleaned-ug-ud-train.conllu' out_train_data = '/home/s1459234/data/conll2017_data/Turkic-DEL/cleaned-ug-ud-train.conllu' out_dev_data = '/home/s1459234/data/conll2017_data/Turkic-DEL/cleaned-ug-ud-dev.conllu' num_sents = 100 trai...
import os import urllib.request from stat import S_ISDIR from json import loads import re import sys import shutil BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) PARTICIIPANTS_DIR = "participants" participantsFolder = "%s/site/_participants"%(BASE_DIR,) solutionsFolder = "%s/site/_solutions"%...
# Submitter: loganw1(Wang, Logan) from collections import defaultdict from goody import type_as_str import prompt class Bag: def __init__(self, *values): d = defaultdict(int) if values !=None: for value in values: for value1 in value: d[value1] +=1 ...
#No Context Bot by @robuyasu#3100 from discord.ext.commands import Bot from discord.ext import commands from itertools import cycle from TwitApi import TwitApi from twitter.error import TwitterError import discord import asyncio import twitter import sys, traceback import os import random Client = discord.Client() cli...
from urllib import request,parse from http import cookiejar # 创建Filecookiejar的实例 filename = "cookie.txt" cookie = cookiejar.MozillaCookieJar(filename) # 生成cookie的管理器 cookie_handler = request.HTTPCookieProcessor(cookie) # 创建一个http请求guanlq http_handler = request.HTTPHandler() # 生成https管理器 https_handler = request.HTTPSH...
import pandas as pd import os class Person(): name = '' address = '' def __init__(self, name, address): self.name = name self.address = address
import os import pandas as pd import filter for fname in os.listdir('prksn_test'): if fname.endswith('.csv'): print(fname) data = filter.filter(f'prksn_test/{fname}') data.sort_values(by=['time', 'part']).to_csv(f'processed_prksn/{fname}', sep=';', header=False, index=False, float_format='%...
__author__ = "Narwhale" import linecache #数据处理 fields=('bid','uid','username','v_class','content','img','time','source','rt_num','cm_num','rt_uid' ,'rt_username','rt_v_class','rt_content','rt_img','src_rt_num','src_cm_num','gender','rt_mid' ,'location','rt_mid','mid','lat','lon','lbs_type','lbs_title','poiid',...
import boto3 import pprint import os import pprint REGION = os.getenv('AWS_REGION', 'us-west-2') def convert_list_to_dict(obj, key='Key', value='Value'): return {e[key]: e[value] for e in obj} def describe_all_instances(client): instances = [] paginator = client.get_paginator('describe_instances') r...
import itertools import numpy as np list1 = np.arange(1,5,1) list2 = [] for i in range(1,len(list1)+1): iter = itertools.combinations(list1,i) list2.append(list(iter)) print(list2)
# from markdown2 import markdown as md2html from markdown import markdown as md2html from IPython.display import HTML, display bg_color = 'background-color:#d8e7ff;' #e2edff;' def show_answer(excercise_tag): TYPE, s = answers[excercise_tag] s = s[1:] # Remove newline if TYPE == "HTML": s = s elif TYP...
s = 'azcbobobegghakl' length = len(s) count = 0 i = 0 for i in range(length): if (i + 2) < length: if s[i] == 'b': if (s[i]+s[i+1]+s[i+2]) == 'bob': count += 1 i += 1 print 'Number of times bob occurs is: ' + str(count)
#!/usr/bin/env python # this is modified csdata.py from __future__ import print_function import fastjet as fj import fjcontrib import fjext import fjtools import tqdm import argparse import os import numpy as np import array import copy import random import uproot import pandas as pd import time from pyjetty.mputi...
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations import textwrap from dataclasses import dataclass from pathlib import Path from typing import Iterable from _pytest.fixtures import FixtureRequest from...
"""Abstraction for dealing with products and the files they contain.""" import os from xml.dom.minidom import parseString from .coda_aware import CODA_Aware class Product(CODA_Aware): """A CODA product, composed mainly of NetCDF files.""" def __init__(self, uuid, work_dir=""): self.files = [] ...
import logging import os from .routes import setup_routes from aiohttp import web async def init(): app = web.Application() setup_routes(app) return app def serve(): logging.basicConfig(level=logging.DEBUG) port = int(os.environ.get("PORT", 8080)) app = init() web.run_app(app, port=po...
import math #Test 5 dimension lists list1 = [5,1,2,6,2,1] list2 = [1,3,5,0,3,2] list3 = [5,1,2,6,2,3] list4 = [99,99,99,99,99,4] list5 = [5,-1,-2,-4,2,5] data = [list1, list2, list3, list4, list5] def similarity(a,b): distance = 0 zipped = zip(a,b) for x, y in zipped: if x < 0 or y < 0: continue distance ...
import asyncio from random import Random from math import ceil from shared.utils import get_time from shared.utils import get_rnd from shared.utils import get_rnd_seed from shared.LogParser import LogParser from shared.LockManager import LockManager from shared.RedisManager import RedisManager # --------------------...
""" Script to read the energy of the prompt signals of preselected events of atmospheric NC neutrino background and calculate the spectrum of atmospheric NC neutrino background as function of the visible energy. 1. Read txt files where the energy of the prompt signals of the preselected events are saved. ...
# -*- coding: utf-8 -*- """ Created on Thu Oct 5 15:41:26 2017 @author: sglusnev """ from flask import Flask, Response, jsonify from flask_restplus import Api, Resource, fields, reqparse from flask_cors import CORS, cross_origin import os # the app app = Flask(__name__) CORS(app) api = Api(app, version='1...
import cv2 import numpy as np import math import time from typing import NamedTuple hsv_lower = np.array([20, 100, 95]) hsv_upper = np.array([90, 255, 255]) #hsv_lower = np.array([20, 50, 180]) #hsv_upper = np.array([90, 170, 255]) def analyze_video(video_path): cap = cv2.VideoCapture(video_path) prev_frame_time =...