text
stringlengths
38
1.54M
import six import unittest from os.path import os from parserutils.collections import wrap_value from parserutils.elements import element_exists, element_to_dict, element_to_string from parserutils.elements import clear_element, get_element_text, get_elements, get_remote_element from parserutils.elements import inser...
import socket soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) soc.connect((socket.gethostname(), 2905)) recmsg = soc.recv(1024) soc.close() print("The time got from the server is %s" % recmsg.decode("ascii"))
import yfinance as yf #finance data from yahoo api import streamlit as st #streamlit for building a data-driven web app import pandas as pd #pandas for manipulate data # st.write can read markdown style and pass the string to the web app st.write(""" ## Simple streamlit app * Show the stock closing price and volume o...
# -*- coding: utf-8 -*- import sys import logging import json from decimal import * from quant.core.Spider import * class StockSpider(SpiderEngine): ''' 更新指数 ''' def __init__(self): SpiderEngine.__init__(self) self.today = sys.argv[2] def run(self): self.tools.setup_loggin...
from .base import ApiBase import logging from ..internal.utils import PaginatedSearch logger = logging.getLogger(__name__) class ExpenseReports(ApiBase): """ ExpenseReports are not directly searchable - only via as employees """ def __init__(self, ns_client): ApiBase.__init__(self, ns_client=...
import pytest from ..__main__ import birthday_cake_candles def test_case_1(): result = birthday_cake_candles(4, [3, 2, 1, 3]) assert result == 2 def test_more_age(): result = birthday_cake_candles(2, [3, 3, 3, 3, 3]) assert result == 2 def test_not_as_many_as_age(): result = birthday_cake_cand...
import math import numpy as np import tensorflow as tf from tensorflow.python.framework import ops from tensorflow.contrib.layers.python.layers import batch_norm def batchnorm(inputT, is_training=False, scope=None): # return inputT # Note: is_training is tf.placeholder(tf.bool) type is_training = tf....
import requests import os from redis.exceptions import RedisError from redis_util.redis_connection import ping_redis from elasticsearch import ElasticsearchException from elasticsearch_util.elasticsearch_connection import get_es_health def parse_args(sub_parser): subparser = sub_parser.add_parser("status", help=...
from pyspark.sql import SparkSession from pyspark.sql.functions import col, min, max # Cria objeto da Spark Session spark = (SparkSession.builder.appName("DeltaExercise") .getOrCreate() ) # Leitura de dados enem = ( spark.read.format("csv") .option("inferSchema", True) .option("header", True) .op...
# open(fileName, 'wb') as f: # while f: """ 二进制文件的存储(音频,视频......) 1. 获取到下载文件的url 二进制方式下载 2.使用urllib模块的urlretrieve()可以进行音频文件下载 也支持远程下载到本地 urlretrieve(url, filename=None, reporthook=None, data=None) url: 文件地址 filename: 存储路径/文件名 reporthook: 回调函数,连接上服务器时或相应数据下载完成后触发该函数 一般用来显示当前下载进度 data: (filename, ...
# A simple lambda translator and evaluator # - Converts a lambda-expression into SKI-expression (translate) # and then reduce it using a combinator graph reduction engine (evaluate) # - Lambda to SKI-expression conversion is done according to bracket abstraction from functools import reduce # Abstract Syntax for La...
# 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 # "License"); you may not u...
""" Day 9 - add relative mode - 2 - add rel_base - add opcode 9 - jump rel_base """ import common from computer import Computer ########## if __name__ == "__main__": program = [int(n) for n in common.listify_input_string('09-input.txt')] # Part 1 -- answer 2662308295 comp = Computer() ...
hours_worked = float(input("Hours worked: ")) ot_hours = hours_worked - 40 straight_pay = 15.00 #this is a constant. overtime_rate = straight_pay * 1.5 after_tax = 0.75 #35% removed for taxes, etc., conservative result if ot_hours > 0: net_pay = ((straight_pay * 40) + (ot_hours * overtime_rate)) * after_tax else: ...
import numpy as np import pandas as pd import os def get_AIS_csv_data(f): if not os.path.exists(f): from import_csv import get_csv_data get_csv_data() df = pd.read_csv(f, usecols=[0, 1, 2, 3], parse_dates=['BaseDateTime'], ...
# -*- coding: utf-8 -*- import logging from flask import current_app as app from flask import request from agroutils.restful.resource import patch_response_data, ok_response, error_response, Resource as AgroutilResource from agroutils.session.auth import AuthenticationError from eventtracker.utils.client import curre...
#!/usr/bin/env python # encoding: utf-8 import ConfigParser from wxpy import * import logging import time import smtplib import time import os from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.header import Header logging.basicConfig(filename='/tmp/sendmail.log', level=lo...
import sqlite3 import time ############### Settings #################### #DB Name DB_NAME = "mandal_sensor.db" #SQL File with Table Schema and Initialization Data SQL_File_Name = "voltage_current.sql" ############################################## #Connect or Create DB File conn = sqlite3.connect(DB_NAME) #Read Tabl...
dagen = "ma", "di", "wo", "do", "vr", "za", "zo" vraag = input("Welke dag van de week kiest u? {} ".format(dagen)) i=0 while i < dagen.index(vraag)+1: print(dagen[i]) i+=1
import thread, time, datetime, csv import requests, json session = requests.Session() global totalBadRequests totalBadRequests = 0 def input_thread(L): raw_input() L.append(None) def do_rec(): global totalBadRequests L = [] thread.start_new_thread(input_thread, (L,)) bad_requests = 0 good_requests = 0 while l...
from game import Game alpha = 0.60 gamma = 0.75 epsilon = 0.01 results = Game(alpha=alpha, gamma=gamma, epsilon=epsilon).run( epochs=10, episodes=100) with open(f'results_a{alpha}_{gamma}.md', 'w') as file: file.write(''.join(results))
import math, collections, copy from nltk.corpus import brown BACKOFF_COEFFICIENT = .9 DISCOUNT = .35 STRIP_CHARS = "<>.\",?! " class KneserBigramModel: """Kneser-Ney Backoff language model - Implements the Kneser-Ney model with bigrams and backoffs to laplace unigram if the given bigram does not exist in ...
33.Write a program to input all sides of a triangle and check whether triangle is valid or not. SOL: side1=int(input('Enter 1st angle of a triangle:')) side2=int(input('Enter 2nd angle of a triangle:')) sidle3=int(input('Enter 3rd angle of a triangle:')) if side1**2==(side2**2+sidle3**2) or side2**2==(side1**2+sidle...
#!/usr/bin/env python3 from datetime import datetime from random import randint from dateutil.relativedelta import relativedelta # relativedelta由第三方库提供, 第三方的日期处理库: python-dateutil # pip3 install python-dateutil class Date: """ 随机日期时间: 时间戳: 从1970年1月1号0点0分0秒到现在有多少秒(格林) """ CMD = {'y': 'y...
from abc import abstractmethod from typing import overload, _T, Sequence, Generic, MutableSequence, Iterable class people(Sequence[_T], Generic[_T]): @abstractmethod def insert(self, index: int, object: _T) -> None: ... @overload @abstractmethod def __getitem__(self, i: int) -> _T: ... @overload...
from cycloauth.storage import BaseStorage, BaseToken, BaseConsumer, key_secret_generator from txmongo import MongoConnectionPool from cyclone.web import HTTPError from twisted.internet import defer class MongoToken(BaseToken): m_id = None def to_dict(self): ret = { 'key': self.key, 'secret': se...
# Generated by Django 3.1.1 on 2020-09-13 12:19 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('restauracja_app', '0004_typ'), ] operations = [ migrations.RenameModel( old_name='Typ', ...
import random import os from art import logo, vs from game_data import data clear = lambda: os.system('cls') def choose_person(data): accountA = random.choice(data) accountB = random.choice(data) while accountA == accountB: accountB = random.choice(data) print(accountA) print(accountB) # personA = ...
from random import randint import random class Playground(object): size = (20, 20) rows = size[0] cols = size[1] length = rows * cols def __init__(self, size=size): self.dim = size self.borders = [(-1, i) for i in range(self.dim[1])] # top self.borders += [(size[0],...
class Variables: """ Methods for Part A. Contains the methods required to complete Part A. Author: Connor McDermid Date: 2019.10.15 """ def get_name(self): name = input("Please input your name: ") return name def get_age(self): age = int(input("Please input your age: ")) return age ...
import numpy as np import cv2 from graphics import * class Postprocessor: def postprocess(self, image): #image = cv2.blur(image, (3,3)) _, image = cv2.threshold(image, 230, 255, cv2.THRESH_TOZERO) if np.random.randint(0, 2) == 0: image = cv2.erode(image, (1,1), iterations=np.ra...
# REFERENCE: https://github.com/seungeunrho/minimalRL " import gym import collections import random import torch import torch.nn as nn import numpy as np import math import torch.nn.functional as F import torch.optim as optim from collections import namedtuple device = torch.device("cuda" if torch.cuda.is_available()...
import pytest from expects import * from os import walk from pmp.experiments import Experiment, ExperimentConfig from pmp.experiments.election_config import ElectionConfig from pmp.rules import Bloc @pytest.fixture def experiment_config(approval_profile): config = ExperimentConfig() config.add_candidates(ap...
"""Analyse tweets""" import webhandler import numpy as np def edit_dist(a,b): # hack to avoid recognising these as same if a == 'Entertainment' and b == 'Oystertainment': return 10 elif a == 'Oystertainment' and b == 'Entertainment': return 10 sol=np.zeros((len(a),len(b))) for ...
employee_dict = { 'employee':{ 'first_name':'John', 'last_name':'Doe', 'email':'john_doe@fake.com', 'phone':'123456789' }, 'devices': [ {'model':'HP Laptop', 'serial':'123', 'asset_tag':'456'}, {'model':'Surface Tablet', 'serial':'789', 'asset_tag':'000'} ] } # employee_dict =...
# coding: utf-8 import os import sys import random import math import json ROOT_DIR = os.getcwd() with open('C0026_2.json', 'a') as outfile: json_decode = json.load(outfile) for i in json_decode: print("key: ", i) print("value: ", dict[i]) if i == "x": print("value: ", dict[i]) print...
from __future__ import division, print_function, absolute_import import tensorflow as tf import tensorflow.contrib.slim as slim from tensorflow.contrib.layers.python.layers import initializers import math def get_num_params(): from functools import reduce from operator import mul num_params = 0 print(...
import math import os import random import re import sys def countBinaryOnes(n): # Converting number to binary # Python's bin functions returns binary starting with '0b' # [2:] removes the first two characters of the string binary_n = str(bin(n))[2:] countOnes = 0 consecOnes = 0...
#!/usr/bin/env python3 # # The Qubes OS Project, http://www.qubes-os.org # # Copyright (C) 2017 Bahtiar `kalkin-` Gadimov <bahtiar@gadimov.de> # Copyright (C) 2017 itinerarium <code@0n0e.com> # Copyright (C) 2016 Jean-Philippe Ouellet <jpo@vt.edu> # # This program is free software; you can redistribute it and/or modify...
def ghj(y): if y > 0 : return y else: return y**2 print(ghj(99-588)) if 14 <= 18: pass def pto(): pass
#!/usr/bin/env python3 import sys import pycalculix as pyc # Model of a pinned plate with 3 pins # one will be force, the others will be fixed proj_name = 'pinned-plate' model = pyc.FeaModel(proj_name) model.set_units('in') # set whether or not to show gui plots show_gui = True if '-nogui' in sys.argv: show_gui ...
import uuid from django.db import models from django.contrib.auth.models import User class Movie(models.Model): uuid = models.UUIDField(primary_key=True, editable=True) title = models.CharField(max_length=256) description = models.TextField() genres = models.CharField(max_length=256, null=True, blank=...
# coding: utf-8 # In[94]: graph = { 'A':{'B':5, 'C':1}, 'B':{'A':5, 'C':2, 'D':1}, 'C':{'A':1, 'B':2, 'D':4, 'E':8}, 'D':{'B':1, 'C':4, 'E':3, 'F':6}, 'E':{'C':8, 'D':3}, 'F':{'D':6} } # In[104]: import heapq parent_dict = {} start_node = 'A' visited = set() pqueue = [] heapq.heappush(pq...
from wpilib.command import TimedCommand class AutoBallIntake(TimedCommand): ''' ball intake command that can be used for autonomous. ''' def __init__(self, motorspeed, timeoutInSeconds): super().__init__("AutoBallIntake", timeoutInSeconds) self.requires(self.getRobot().doublemotor) ...
# 문제 설명 # 정수 배열 numbers가 주어집니다. numbers에서 서로 다른 인덱스에 있는 두 개의 수를 뽑아 더해서 # 만들 수 있는 모든 수를 배열에 오름차순으로 담아 return 하도록 solution 함수를 완성해주세요. # 제한사항 # numbers의 길이는 2 이상 100 이하입니다. # numbers의 모든 수는 0 이상 100 이하입니다. # 입출력 예 # numbers result # [2,1,3,4,1] [2,3,4,5,6,7] # [5,0,2,7] [2,5,7,9,12] # 입출력 예 설명 # 입출력 예 #1 # 2 = 1 + 1 입...
from django.urls import path from orders.views import OrdertListView,OrderUpdateView,OrderDetailView app_name = 'products' urlpatterns = [ path('', OrdertListView.as_view(), name='index'), path('update-order/<int:pk>/', OrderUpdateView.as_view(), name='update_order'), path('detail/<int:pk>/', OrderDet...
import data_utils from config.Deconfig import Deconfig import pickle ll = data_utils.get_some_captions(5000) max = 0 for l in ll: h = l.split() if max < len(h): max = len(h) print(max)
from __future__ import annotations from typing import Sequence, Optional, Any import numpy as np import tensorflow as tf from sknlp.vocab import Vocab from .nlp_dataset import NLPDataset from .bert_mixin import BertDatasetMixin from .utils import serialize_example class ClassificationDataset(NLPDataset): def __...
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
from yumi.modulecontext import ModuleContext from yumi.modulebase import Module from yumi.api import init_global class Initializer(Module): @staticmethod def do(args: list, context: ModuleContext): return init_global(context.working_dir) Modules = { "init": Initializer }
from eod import tm_utils, trmm import numpy as np from numpy.testing import assert_array_equal, assert_allclose import xarray as xr import unittest from utils import u_arrays as ua class TestTMUtils(unittest.TestCase): def test_minute_delta(self): tt = [59, 0, 15, 13, 9, 2, 31, 27, 43, 45] result...
import apiclient.discovery import googleapiclient.http import httplib2 import oauth2client.client import oauth2client.file import oauth2client.tools import threading from . import util, config _api_name = 'youtube' _api_version = 'v3' _auth_scope = 'https://www.googleapis.com/auth/youtube.readonly' _client_secrets_...
""" Author: Reinaldo Mateus R J, Test version: 0.1 """ import time from selenium.webdriver.support.ui import WebDriverWait # available since 2.4.0 from settings.variables_test import * from classes import common_functions class project_test(common_functions.functions,object): def setProject(self,t...
from datetime import datetime, timedelta from pyrogram import Client, filters import config from vk_bot import VKBot tg_client = Client("kispython-translator", api_id=config.TG_API_ID, api_hash=config.TG_API_HASH) def make_message_header(author, msg_time, edit=False): """ Создание заголовка сообщения для VK. "...
import math class Math: def __init__(self, eq): self.equation = eq self.equation_list = None def print_equation(self): print(self.equation) def remove_spaces(self): self.equation = self.equation.replace(" ", "") def split_equation(self): self.equation_list = self.equation.split(" ") def is_ope...
import json from home_run.models import ScikitLearnModel # Create the flask app from flask import Flask, request app = Flask(__name__) from sklearn.externals import joblib # Load in options form disk with open('options.json') as fp: options = json.load(fp) # Instantiate a HRModel for sklearn type ml = ScikitLea...
#coding:utf-8 ''' Created on 2016-1-4 @author: description: ''' from subject.models import Activity, User import time from django.utils import timezone def select_activity(req): dao = Activity.objects.order_by("-id")[:req] rsp = [] for v in dao: rsp.append('\t'.join([timezone.local...
class Solution(object): def threeSum(self, nums): if not nums: return [] if len(set(nums))==1 and nums[0]==0 and len(nums)>2: return [[0,0,0]] output=[] target=0 nums.sort() for i in range(len(nums)-1): if nums[i]==nums[i-1]: ...
import numpy as np from scipy.signal import correlate import matplotlib.pyplot as plt # load datasets period = 1.0 # period of oscillations (seconds) w = 50 t_min = 0 t_max = 0.1 t_step = 0.001 t = np.arange(t_min, t_max, t_step, dtype=np.float) fai = np.pi / 4 A = np.sin(2 * np.pi * w * t) B = np.sin(2 * np.pi * w *...
import postfix_conf import re class SpaceConf(postfix_conf.PostfixConf): def parse_row(self, row): items = re.split('\s+', row) row = Row() row.key = items[0] row.items = items[1:] return row def append_kv(self, key, value): r = Row() r.key = key ...
from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse, HttpResponseRedirect from django.contrib import auth from django.contrib.auth.decorators import login_required from sign.models import Event, Guest from django.db.models import Q from django.core.paginator import Paginator, Emp...
from django.shortcuts import render, redirect from django.contrib.auth.hashers import check_password from store.models.customer import Customer from django.views import View from store.models.product import Product from store.models.orders import Order from store.middlewares.auth import auth_middleware class OrderVi...
import hashlib import logging import requests import time from irodsManager.irodsUtils import get_bag_generator, bag_generator_faker, ExporterClient, ExporterState as Status from http import HTTPStatus from multiprocessing import Pool from xml.etree import ElementTree logger = logging.getLogger('iRODS to Dataverse') ...
from flask_restplus import Resource import app.main.service.user_service as user_service from app.main.response.user_response import UserResponse from app.main.controller.rest_plus_api import Api api = Api.api _userResponseType = UserResponse.user @api.route('/<id>') @api.doc(params={'id': 'The users heatmap id'}) c...
import socket,sys client = socket.socket() client.connect(('localhost',9999)) while True: msg = input(">>>>").strip() if len(msg)==0: continue client.send(msg.encode('utf-8')) res_return_size = client.recv(1024) #接收的命令结果的大小 print('接收的数据的大小:',res_return_size) total_res_size = int(res_retu...
import torch import torchvision from torch.utils.data import Dataset, DataLoader from PIL import Image class FacesDataset(Dataset): def __init__(self, root_dir, size, n, total): self.root_dir = root_dir self.size = size self.n_celebs = n self.total = total def __len__(self): return self.n_celebs*self.size...
from telegram import Update from telegram.ext import Updater, CommandHandler, CallbackContext def start(update: Update, context: CallbackContext) -> None: update.message.reply_text(f'Hello {update.effective_user.first_name}') updater = Updater('1766280930:AAHtKtuWbjSx_vpQmO1UNR4g_QkBqR6zd6I') updater.dispatche...
#프로그래머스 같은 곳에서는 def solution 안에서 작업해야 하기 때문에, global variable설정이 어렵다. def solution(n,m, g): #변수와 데이터 입력구간 graph=[] n,m= n,m for _ in range(n): graph.append(g[_]) print(graph[_]) # 본격적인 알고리즘 구간 inner function 으로 정의하기.#이렇게 nested function 으로 정의하면, outer function에 접근할 수 있다. def ...
#!/usr/bin/env python3 #this script defines the variables and they can't be changed when the script is run #unless you change the variables name in the script name=("Nathalia") origin=("Brazil") color=("green") activity=("sports") animal=("dog") breed=("corgi") dog_name=("Noel") print("My name is", name, ".", "I'm f...
import spacy import warnings from medspacy.common.regex_matcher import RegexMatcher nlp = spacy.load("en_core_web_sm") class TestTargetMatcher: def test_initiate(self): assert RegexMatcher(nlp.vocab) def test_add(self): matcher = RegexMatcher(nlp.vocab) matcher.add("my_rule", ["my_p...
#!/usr/bin/python import socket import sys import os from subprocess import Popen socket_address = ('localhost', 8888) #TODO get freedback def sendMessage(message): # Create a UDS socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Connect the socket to the port where the server is listenin...
# Generated by Django 2.0.7 on 2019-09-19 15:27 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('paintings', '0016_auto_20190919_0221'), ] operations = [ migrations.AddField( model_name='painting', name='series', ...
#!/usr/bin/env python # coding: utf-8 import pandas as pd from collections import Counter import numpy as np import nltk from nltk.corpus import stopwords from nltk.sentiment.vader import SentimentIntensityAnalyzer from nltk.stem import PorterStemmer #nltk.download('vader_lexicon') import sklearn from sklearn.neural_n...
from django.shortcuts import render from django.http import HttpResponse from rest_framework.views import APIView from rest_framework.response import Response from django.contrib.auth.models import User, Group from rest_framework.generics import ( RetrieveUpdateDestroyAPIView, CreateAPIView ) from .models impo...
import rdkit from rdkit import Chem from rdkit.Chem import rdmolops import numpy import chainer.datasets as D import chainer.datasets.tuple_dataset as Tuple filename_train = 'tox21_10k_data_all.sdf' filename_val = 'tox21_10k_challenge_test.sdf' label_names = ['NR-AR', 'NR-AR-LBD', 'NR-AhR', 'NR-Aromatase', 'NR-ER', ...
######################################################## # desc : deep neural network model for CTR prediction. # # @author : qiangz2012@yeah.net # ######################################################## import tensorflow as tf import numpy as np class Dnn_Mlp(object): def __init__(self, epoch, batch_size, \...
import sys def hash(): args = sys.argv arg_length = len(args)-1 if arg_length == 1: if args[1] == "-h" or args[1] == "-help" or args[1] == "--help": print("detect-a-hash: detect.py <hash>") else: hash_length = (len(args[1])) if hash_length == 32: ...
''' @author: Kaiwen Luo (k0l06rk) this file holds the code for the main/experiments of tote merge. ''' import random import time from MaxToteUtilAlgos.runnableHelpers import ReadSimulation from MaxToteUtilAlgos.runnableHelpers import partition from MaxToteUtilAlgos.runnableHelpers import Box from MaxTote...
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (c) 2017 Telenav, Inc. All rights reserved. import md5, os, re, subprocess, urllib import cacheutils def parseurl(cmd): print 'cmd:', cmd cmd = urllib.unquote(cmd) print 'ucmd:', cmd # mo = re.search(r'(http[s]://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\...
import couchbase from couchbase.bucket import Bucket import json from random import randint import requests import threading import time SLEEP_DURATION = 3 v8_debug_endpoint = "http://localhost:6061/v8debug/" conn_str = "couchbase://localhost/default" cb = Bucket(conn_str) def populate_one_doc(): ssn1 = str(rand...
""" This simulates when multiple balls in a container where collisions are perfectly elastic""" from ball import Ball import pygame from pygame import Vector2 from itertools import combinations from random import randint, randrange """ Create a pygame window """ pygame.init() width, height = 400, 400 win = pygame.dis...
# -*-coding:utf-8-*- ''' Tip 6_2. binary-coded decimal - Decimalism exchange ''' print(int("30", 20))
from django.contrib.auth.mixins import LoginRequiredMixin from django.shortcuts import render, redirect, reverse from django.http import HttpResponse, JsonResponse from django.core import serializers from django.views.generic import ListView, CreateView, UpdateView, DeleteView, TemplateView, FormView from .models impor...
import torch import spacy from spacy.lang.en.stop_words import STOP_WORDS from fuzzywuzzy import fuzz import json, re, random, os from copy import deepcopy from tqdm import tqdm flatten = lambda l: [item for sublist in l for item in sublist] nlp = spacy.load('en_core_web_sm') def remove_stop(input): # input: list...
from agents.simpleAgent import simpleAgent from agents.markovAgent import markovAgent from json import dump,load from heuristics import * class markovSimpleAgent(markovAgent,simpleAgent): '''Not implemented''' pass
""" Divides the dataset_readers into training, development, and test split. """ import random from pathlib import Path from absl import app, flags, logging from tqdm import tqdm FLAGS = flags.FLAGS flags.DEFINE_string('input_path', default=None, help='Path to the input data') flags.DEFINE_string(...
import random as rd import time import cv2 from detection.opencv_dnn.detector import Detector from tracking.deep_sort import generate_detections as gdet from tracking.deep_sort import nn_matching, preprocessing from tracking.deep_sort.detection import Detection from tracking.deep_sort.tracker import Tracker from util...
################### PDF uncertainty calculator ################# ## Edited by Raymond ## Edited on 4/16/14 ## A better version! #!/usr/bin/python import re import os import math import ROOT import numpy from ROOT import * from array import array from optparse import OptionParser # MC truth of fitted vars afb_mc = '0.0...
model_name = "spice_self" pre_model = "./results/stl10/moco/checkpoint_0999.pth.tar" embedding = "./results/stl10/embedding/feas_moco_512_l2.npy" resume = "./results/stl10/{}/checkpoint_last.pth.tar".format(model_name) model_type = "clusterresnet" num_head = 10 num_workers = 4 device_id = 0 num_train = 5 num_cluster = ...
import pandas as pd def download_scalabrino(): df = pd.read_csv("https://dibt.unimol.it/reports/clap/downloads/rq3-manually-classified-implemented-reviews.csv") df = df.rename(columns = {"body": "text", "category": "label"}) df["app"] = df["App-name"] df["sublabel"] = df["rating"] return df
import os def add_supported_project(project_name): if not __project_folder_has_dir(project_name): raise Exception("Could not find Project with name {} in Projects folder. \n Will not add it to supported projects!".format(project_name)) __write_to_supported_projects(project_name) print("Added {} to...
import cv2 import os import numpy as np from PIL import Image from keras.models import load_model from keras.preprocessing.image import load_img from keras.preprocessing.image import img_to_array font = cv2.FONT_HERSHEY_SIMPLEX def generate_gesture(ges_name, num_train_samples, save=True): cam = cv2.VideoCapture(0)...
import FWCore.ParameterSet.Config as cms ####### Ecal Iso hltEgammaEcalPFClusterIso = cms.EDProducer( "EgammaHLTEcalPFClusterIsolationProducer", energyEndcap = cms.double( 0.0 ), effectiveAreaBarrel = cms.double( 0.149 ), etaStripBarrel = cms.double( 0.01 ), rhoProducer = cms.InputTag( "hltFixedGridRh...
from src.MOOA.NSGA_II import nsga_ii from src.ea_nas.moo_operators import architectural as moo from src.ea_nas.evolutionary_operations.mutation_for_operators import mutate def optimize(population, selection, steps, config): for i in range(steps): # Preparation: children = [] # Mutation: ...
import requests import urllib.parse def get_usernames_from_names(name_file): usernames = [] with open(name_file, mode='r', encoding='utf-8') as names_file: for line in names_file: query = line.strip() query_encoded = urllib.parse.quote(query) search_url = f'https:...
from distutils.core import setup setup(name='vacationlibrery', version='1.1', author='Mateusz Wojcik', author_email='226611@student.pwr.edu.pl', url='https://github.com/BombaGR', packages=['myPackage'], )
# standard library import json import argparse # third-party libraries import torch # project libraries from decoder import GreedyDecoder from test import evaluate from data.data_loader import AudioDataLoader, SpectrogramDataset from model import DeepSpeech parser = argparse.ArgumentParser(description="evaluates mod...
class employee: def __init__(self,name,dob): self.name = name self.dob = dob self.salary = 50 def salary_review(self,review): self.salary = self.salary*(1+review*0.01) emp1 = employee("Nguyen Van A", 15022019) print(emp1.name,emp1.dob,emp1.salary) emp1.salary_review(...
# 평균값 구하기 f = open("sample.txt", 'r', encoding='UTF-8') data = f.readlines() f.close() sum=0 for i in range(len(data)): sum += int(data[i]) # print(sum) average = sum / len(data) # print("average = ", sum / len(data)) if len(data) > 0: with open('result.txt', 'w', encoding='UTF-8') as f: f.write(str(a...
#main code to do classification import torch, torchvision from torchvision import datasets, models, transforms import torch.nn as nn import torch.optim as optim from torch.utils.data import DataLoader import time from torchsummary import summary import numpy as np import matplotlib.pyplot as plt import os from PIL imp...