text
stringlengths
38
1.54M
n=int(input()) for i in range(1,n+n+1,2): ls=[] for j in range(i): ls.append(1) print(*ls)
# -*- coding: utf-8 -*- """ Created on Sun Feb 28 11:37:04 2021 @author: Maxi """ # Problem 1 """ Assume s is a string of lower case characters. Write a program that counts up the number of vowels contained in the string s. Valid vowels are: 'a', 'e', 'i', 'o', and 'u'. For example, if s = 'azcbobobegghakl'...
from tkinter import * from tkinter import ttk root_window = Tk() root_window.geometry('+550+350') root_window.title('Temperature converter') root_window.columnconfigure(0, weight=1) root_window.rowconfigure(0, weight=1) root_window.resizable(False, False) celsius_value = StringVar() fahrenheit_value = StringVar() fr...
############################################################################ # Copyright 2018 Anthony Ma & Stanford University # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may no...
import csv import zipfile from io import TextIOWrapper from tempfile import TemporaryDirectory from typing import List, Optional from uuid import UUID from .base import HQBase from .interviews import InterviewsApi from .models import AssignmentWebLink, QuestionnaireDocument class QuestionnairesApi(HQBase): """ S...
def coroutine_decorator(func): def start(*args, **kwargs): cr = func(*args, **kwargs) next(cr) return cr return start def natural_numbers(*targets): try: number = int(input("Enter any natural numer > 1:")) if number < 1: print("Please enter a number great...
#Embedded file name: eve/client/script/ui/station/fitting\fittingLayout.py from eve.client.script.ui.control.themeColored import SpriteThemeColored import uicls import carbonui.const as uiconst import trinity import uiprimitives import uicontrols class FittingLayout(uiprimitives.Container): __guid__ = 'uicls.Fitti...
from flask import Flask, jsonify, g from flask_login import LoginManager import os from flask_cors import CORS import models from resources.users import users from resources.profiles import profiles from resources.jobposts import jobposts from resources.companies import companies from resources.jobapplications import...
from collections import namedtuple Data = namedtuple('Data', ['station', 'timestamp', 'value']) DataComparison = namedtuple('DataComparison', ['timestamp', 'pg_value', 'mongo_value'])
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib.auth.models import User from django.db import models class Contact_types(models.Model): type = models.CharField(verbose_name='Тип контакта', max_length=30) def __unicode__(self): return self.type class Meta: ...
import os import pandas as pd import numpy as np import math from scipy.stats import gmean from fuzzywuzzy import fuzz pd.options.display.max_seq_items = 2000 pd.options.display.max_colwidth = 1000 x =pd.read_csv('/home/mint/my-data/WebScrapingPhase2/Data/test/_main_.csv',encoding = "latin_1") #x = pd.read_csv('...
p=int(input("enter the p value")) t=int(input("enter the t value")) r=int(input("enter the r value")) si=(p*t*r)/100 print("simple intrest",si)
import torch from collections import OrderedDict, Counter from functools import partial from dataclasses import dataclass from typing import Tuple, List from copy import deepcopy from math import prod class StatsCounter: def __init__(self): self._dict = {} def update(self, key, v=None): if ke...
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------...
from netket import legacy as nk # 1D Lattice L = 20 g = nk.graph.Hypercube(length=L, n_dim=1, pbc=True) # Hilbert space of spins on the graph hi = nk.hilbert.Spin(s=1 / 2, N=g.n_nodes, total_sz=0) ha = nk.operator.Ising(hilbert=hi, graph=g, h=1.0) alpha = 1 ma = nk.machine.JaxRbm(hi, alpha, dtype=complex) ma.init_r...
import random import pygame import numpy as np from random import randint class Sudoku(object): def __init__(self,): self.board = np.zeros((9,9), dtype=int) def get_row(self, i): b = self.board row = [] row.append(b[i]) return b[i] def get_col(self, j): ...
# -*- coding: utf-8 -*- __author__ = 'chuter' def string_json(str): sb=[]; for char in str: if char == '\"': sb.append("\\\"") elif char == '\\': sb.append('\\\\') elif char == '/': sb.append('\\/') elif char == '\b': sb.append('\\b'); elif char == '\f': sb.append('\\f') ...
#!/usr/bin/env python3 ## ## generate-ec2-ssh-config.py ## ## EC2 - Boto 3 Docs 1.9.49 documentation ## https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html ## import boto3 client = boto3.client('ec2') response = client.describe_instances() for reservation in response['Reservations']: ...
import data import graph import fileManager import random from NNModel import NNModel as NN dirName = fileManager.get_random_directory() print("New project:", dirName) new_data = data.Data() new_data.generate_data(2, 20) # print(new_data.positions) # print(new_data.types) graph_detail = 20 def randomClass(x, y): ...
#! /usr/bin/env python3 import os import sys import shutil import yaml import subprocess def examineTraceFile(work_dir): try: inputyaml = open(os.path.join(work_dir, 'input.yaml'), 'r') except: print ("FAIL: (ERROR) input.yaml not found! work_dir:", work_dir) return False config_dict = yaml.load(inputyaml) ...
from flask_api import FlaskAPI from debug import debug_app from deeprole import deeprole_app import os import markdown DIR = os.path.abspath(os.path.dirname(__file__)) app = FlaskAPI(__name__) app.config['DEFAULT_RENDERERS'] = [ 'flask_api.renderers.JSONRenderer', ] app.register_blueprint(debug_app, url_prefi...
import re # list of patterns to search for patterns = ['term1', 'term2'] # Text to parse text = 'This is a string with term1, but it does not have the other term.' for pattern in patterns: print('Searching for {} in \n {}'.format(pattern ,text)) # check for match if re.search(pattern, text): print("\t Match f...
#! /usr/bin/env python # # Summary of BX distributions # import sys import optparse import string import os # options parser = optparse.OptionParser() parser.add_option("-d", "--dir", action="store") (opts, args)=parser.parse_args() dataset=opts.dir # ROOT stupidity sys.argv=[] sys.argv.append('-b') from ROOT i...
#from django.conf.urls import patterns, include, url from django.conf.urls.defaults import * from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.views.generic import TemplateView from hmslincs_server.views import * from settings import _djangopath import os.path as op urlpatterns = patter...
# uncompyle6 version 3.7.4 # Python bytecode 2.7 (62211) # Decompiled from: Python 3.8.5 (default, Aug 12 2020, 00:00:00) # [GCC 10.2.1 20200723 (Red Hat 10.2.1-1)] # Embedded file name: c:\Jenkins\live\output\Live\win_64_static\Release\python-bundle\MIDI Remote Scripts\Roland_FA\transport.py # Compiled at: 2020-05-05...
import numpy as np import matplotlib.pyplot as plt from sklearn.metrics import roc_curve import pickle def load_variable(filename): with open(filename, 'rb') as f: var_list = pickle.load(f) return var_list x = np.arange(0.0, 1.1, 0.1) y = x true_y, pred_y, = load_variable("netgan_baseline_ro...
from django.shortcuts import render from django.http import HttpResponse def social_view(request, *args, **kwargs): print(request) return render(request, "home.html", {}) def contact_view(request, *args, **kwargs): print(request) return render(request, "contact.html", {}) def about_view(request, *arg...
#https://leetcode.com/problems/intersection-of-two-arrays/ class Solution: def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: n=set(nums1) m=set(nums2) ans=[] for i in n: if i in m: ans.append(i) return ans
from odoo import api, fields, models, _ from datetime import date,datetime from dateutil.relativedelta import relativedelta import logging _logger = logging.getLogger(__name__) class SchoolStudentModel(models.Model): _name = "school.student" # _description = "School students data" _rec_name = "name" n...
# Generated by Django 3.1.6 on 2021-03-23 19:17 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('response', '0004_auto_20210308_1958'), ] operations = [ migrations.RemoveField( model_name='response', name='profile', ...
import pyautogui as pg import time start_range = int(input('Enter start point: ')) file_x = 470 file_y = 190 for i in range(start_range, 291, -1): print(i) # click on the Add button pg.click(269, 105) time.sleep(1.5) # click on 'select tweet ID file' button pg.click(182, 289) time.sleep(...
import matplotlib.pyplot as plt import numpy as np import csv import sys data = [[] for i in range(int(sys.argv[2]))] colors = ['red','orange','pink','green','blue','black','purple','grey'] num = -1 for index,row in enumerate(csv.reader(open(sys.argv[1],"r"))): if index%15==0: num =num +1 data[num].append(row) f...
from typing import Any from resources.exceptions.error import * def find_key(*objective_key, search_dict: dict = None, error_message: str = "Keys not found in dict") -> Any: """[summary] returns search dict value if objective key is in the dictionary. objective key can be multiple arguments. Args: ...
import math class Umrechnung(object): # Radius der Meccanum-Räder in m __radius = 0.152/2 # Senkrechter Abstand der Räder zur Mittelachse in m = Drehradius bei Rotation um Mittelpunkt (noch nicht ausgemessen!) __abstand = 0.17 ## Konstruktor # Eingabeparameter: # uMax: maxima...
import requests class TestCheckCookies: def test_check(self): url = 'https://playground.learnqa.ru/api/homework_cookie' response = requests.get(url) cookie = dict(response.cookies) cookie_value = response.cookies.get('HomeWork') assert cookie_value == 'hw_value', "Wrong val...
#!/usr/bin/env python import threading from std_msgs.msg import * import rospy import numpy import sys from std_srvs.srv import * from irpos import * import math from transformations import * from visualization_msgs.msg import Marker from visualization_msgs.msg import MarkerArray # mutexy dla zmiennych, do ktorych z...
#!/usr/bin/env python # coding: utf-8 from django.core.context_processors import csrf from django.template import Context, RequestContext from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404, render_to_response from django.contrib.auth.decorators import login_required from djang...
import numpy as np import cv2 start = 1 duration = 10 fps = '30' capture = cv2.VideoCapture('vtest.avi') outfile = 'heatmap.avi' while True: try: _, f = capture.read() f = cv2.cvtColor(f, cv2.COLOR_BGR2GRAY) f = cv2.GaussianBlur(f, (11, 11), 2, 2) cnt = 0 res = 0.05 * f ...
#!/usr/bin/env python import requests import os import subprocess import argparse # 从环境变量中获取OpenAI API密钥 api_key = os.environ.get("OPENAI_API_KEY") if api_key is None: print("错误:未设置OPENAI_API_KEY环境变量。请设置变量并重试。") exit() def text_to_command(text): response = requests.post( "https://api.openai.com/v1...
import datetime import logging import pickle import re import time import urllib from google.appengine.api import memcache from google.appengine.ext import db from google.appengine.ext import search import accounts import provider import system class QuoteException(Exception): pass class InvalidQuoteStateExceptio...
import tensorflow as tf from .piece import Piece class Board: SIZE = 9 ROW_LENGTH = 3 def __init__( self, board_positions, previous=None, next_player=Piece.CROSS ): self._array = board_positions self.previous = previous self._next_player = next_player @staticmetho...
from dataclasses import dataclass @dataclass class Student: name: str age: int li = [Student('小明', 11), Student('小红', 12), Student('小青', 9)] li.sort(key=lambda e: e.age) print(li) li = [Student('小明', 11), Student('小红', 12), Student('小青', 9)] li2 = sorted(li, key=lambda e: e.age) print(li) pri...
import argparse import os from torch.backends import cudnn from data_loader import get_loader from solver import Solver def str2bool(v): return v.lower() in ('true') def main(config): if config.mode == 'gen_mobile_model': solver = Solver(config, None, None) solver.gen_mobile_model() ...
import os import glob import pandas as pd import boto3 import logging from botocore.exceptions import ClientError import sys import threading text_path = str(os.path.abspath(os.path.join('../data/preprocessed'))) csv_path = str(os.path.abspath(os.path.join('../data/text.csv'))) bucket_name = "chang-stt-bucket" cloud_...
from blocks.initialization import IsotropicGaussian, Constant import data from model.mlp_emb import Model, Stream use_cuts_for_training = True dim_embeddings = [ # ('origin_call', data.origin_call_train_size, 100), # ('origin_stand', data.stands_size, 100), # ('week_of_year', 52, 100), # ('day_of_wee...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Mon Mar 9 14:35:11 2020 @author: Ethan """ import rospy from pololu_drv8835_rpi import motors # MAX_SPEED is 480 (hard-coded) ''' Future work: write these in yaml file ''' speed_desired = 0.5 # desired wheel speed in rpm angle_desired = 0.0 # desired a...
from django.contrib.auth.models import User from django.db import models from ckeditor.fields import RichTextField # Create your models here. from django.urls import reverse class ScopeManage(models.Model): SCOPE_TYPES = ( ('Fellowship', 'Fellowship'), ('Internship', 'Internship'), ('Resear...
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys from collections import defaultdict import datetime import logging import unicodedata # pip install python-telegram-bot # https://github.com/python-telegram-bot/python-telegram-bot # https://github.com/python-telegram-bot/python-telegram-bot/blob/master/example...
import makEasy import types,json import meTime as mT import math from pathlib import Path Machine=makEasy.Machine("MAC032","Impianto Taglio Plasma - BBS") makEasy.WORKSET['PlasmaCut'].Machines.append(Machine)# ?????? f = open(Path(makEasy.FOLDER+"/Machines/MAC032")/"MaterialParameters.json", "r") MAC_PARAMETERS=json....
import numpy as np from process_testset import * def levenshteinDistance(s1, s2): if len(s1) > len(s2): s1, s2 = s2, s1 distances = range(len(s1) + 1) for i2, c2 in enumerate(s2): distances_ = [i2+1] for i1, c1 in enumerate(s1): if c1 == c2: ...
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2015-2019 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Handlers for customizing oauthclient endpoints.""" from functools import partial,...
# import libraries from gtts import gTTS import pygame,picamera import pytesseract import os,time from PIL import Image import numpy as np import cv2 import datetime import pyaudio from subprocess import call import speech_recognition as sr import shelve,os #to get foldername for captured image by date dt=datetime...
import sys from os import listdir, makedirs from os.path import join, exists, splitext import numpy as np from sklearn.utils import shuffle from sklearn.externals import joblib from sklearn import linear_model import pickle # Configure train_by_all = False n_trains = 200 # Read command line arguments argv = sys.argv...
"""Selenium Page Adapter.""" import os from pkg_resources import get_distribution, DistributionNotFound from .descriptors import ElementDescriptor, AllElements, AvailableElements from .adapter import PageAdapter try: _dist = get_distribution('selenium_page_adapter') if not __file__.startswith(os.path.join(_di...
from sklearn.datasets import load_iris dane = load_iris() print(dane.keys()) print("ilość danych z rozmiarami płatków: {}".format(dane.data.shape)) print("dane iris zawierają {} cech o nazwach: {}".format(dane.data.shape[1], dane.feature_names)) print("dane iris zawierają {} gatunków o nazwach: {}".format(dane.targe...
#!/usr/bin/python3 import requests from wxpy import * import json import logging logging.basicConfig(level=logging.INFO) # 减少网络层日志的干扰 for m in 'requests', 'urllib3': logging.getLogger(m).setLevel(logging.WARNING) bot = Bot(cache_path=True) # 开启 puid 获取功能,指定 puid 映射数据的保存路径 bot.enable_puid('wxpy_puid.pkl') # 在群中...
from spell_checker.Radix import * class RadixTree(Radix): """Tree of radices, where each path, if final, represents a word. """ def __contains__(self,other,tree=None): """Checks if a word is contained in the CharacterTree. In other words, checks if all characters are present in the object and if the last one i...
from AttackerCalc import AttackerCalc from FeaturesCalc import FeaturesCalc from PacketFilter import PacketFilter from MTADownloader import MTADownloader from NeuralNetwork import NeuralNetwork from LegitimateDownloader import LegitimateDownloader from Agent import Agent from CSV import CSV from scapy.all import * impo...
""" Created on Sat June 06 2020 @author: evadatinez """ from MyAIGuide.data.export_excel import exportParticipantDataframeToExcel from MyAIGuide.data.complaintsData import complaintsData import numpy as np import os.path import pandas as pd from pandas._testing import assert_frame_equal # create empty test datafram...
from sklearn.datasets.samples_generator import make_blobs import matplotlib.pyplot as plt from sklearn.cluster import KMeans data, target = make_blobs(n_samples=400, centers=4, cluster_std=0.95, random_state=0) #obs:the random_state is #it is like a read.csv. We already generate it separated between data and data...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render from django.http import HttpResponse from .models import Book from .models import Rental from .forms import UserForm def index(request): if (request.user.is_authenticated()): books = Book.objects.filte...
import numpy as np from scipy.signal import windows eps = np.finfo(np.float32).eps def median_filter(x, kernel_size): pad = (kernel_size - 1) // 2 x_pad = np.concatenate((np.zeros(pad), x, np.zeros(pad))) y = np.zeros_like(x) for i in range(len(y)): median_arg = np.argsort(np.abs(x_pad[i : i +...
from graph import Graph def f(x): return x**2 g1 = Graph() g1.plot("Linear Function") g2 = Graph(f) g2.plot("Quadratic Function")
# # -*-encoding:gb2312-*- import os import hashlib from twisted.internet import reactor, defer from bitfield import Bitfield from tools import sleep class BTFileError (Exception) : pass class BTHashTestError (Exception): pass class BTFile: def __init__(self, metainfo, index, saveDir): fileinf...
import pandas as pd my_stat = pd.read_csv('my_stat.csv') print(my_stat.head(10)) # В переменную subset_1 сохраните только те наблюдения, у которых значения переменной V1 строго больше 0, # и значение переменной V3 равняется 'A'. subset_1 = my_stat.loc[(my_stat['V1'] > 0) & (my_stat['V3'] == 'A')] print(subset_1) ...
import numpy as np from pvfactors.irradiance.utils import \ perez_diffuse_luminance, breakup_df_inputs, calculate_circumsolar_shading def test_perez_diffuse_luminance(df_perez_luminance): """ Test that the calculation of luminance -- first step in using the vf model with Perez -- is functional """...
import solution import utils import DNA_RNA_REVC class ORF(solution.Solution): def _read(self, f): return utils.read_fasta(f, dna_only=True)[0] def _translate(self, rna): """Translate the RNA block starting with the start codon and without a stop codon.""" return ''.join([u...
from django.test import TestCase from lists.models import Item class HomePageTests(TestCase): def test_uses_home_template(self): response = self.client.get('/') self.assertTemplateUsed(response, 'home.html') def test_can_save_post_request(self): response = self.client.post('/', data...
# -*- coding: utf-8 -*- """ Created on Mon Apr 27 15:37:40 2020 Maker : bychoi@deu.ac.kr @author: Com """ # sample player file which must be made by student from player import * from stone import * from random import * class iot12345_student(player): def __init__(self, clr): super().__init__( clr) ...
from django.contrib import admin from .models import Course, Module, Enrollment, Coupon, Subject, ModuleFile,Payment,Zoom # Register your models here. admin.site.register(Course) admin.site.register(Module) admin.site.register(Enrollment) admin.site.register(Coupon) admin.site.register(Subject) admin.site.register(Mod...
#!/usr/bin/env python3 import argparse import os import re from contextlib import contextmanager from typing import Iterable @contextmanager def working_directory(dir: str): prev_wd = os.getcwd() if not os.path.exists(dir): os.makedirs(dir) os.chdir(dir) try: yield finally: ...
from typedclass.fields.data.f_binary.core import Binary from typedclass.fields.data.f_bool.core import Bool from typedclass.fields.data.f_date.core import Date from typedclass.fields.data.f_datetime.core import DateTime from typedclass.fields.data.f_decimal.core import Decimal from typedclass.fields.data.f_int.core imp...
# coding=utf-8 import sys def solution(long_string, alphabet): # 在这里写你的实现 if len(long_string)<len(alphabet): return "" result=[] for i in range(len(long_string)): array=[] alphabets=list(alphabet) if long_string[i] in alphabets: start=i alphabets...
""" Tests for app news_feed """ from textwrap import dedent from django.test import TestCase from django.db.utils import IntegrityError from django.core.exceptions import ValidationError from news_feed.models import NewsReport DEFAULT_DICT_NEWS = { 'name': 'Test. Test2', 'preview': 'test', 'text': deden...
import json import logging from urllib import urlencode from urllib2 import quote, urlopen, URLError logger = logging.getLogger(__name__) BASE_URL = 'http://api.phila.gov/opa/v1.0/' ADDRESS_ENDPOINT = 'address/' ACCOUNT_ENDPOINT = 'account/' params = { 'format': 'json', } def get_address_data(address): if ...
import os import time from datetime import datetime from shutil import which from urllib.parse import urljoin, urlparse import scrapy from scrapy_selenium import SeleniumRequest from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC class NaverBlogSpider(scrapy.Sp...
import numpy as np from utils.signal_stats import detect_R_peak import random class HeartBeatSegmenter(object): """Split ecg signal into individuals heartbeats. Args: segment_size(tuple or int): Desired segment size. take_average(boolean): average the heartbeats pairs """ def __init__...
# EXERCÍCIO Nº 16- LISTA 04 - LISTAS print('\nVendedoes e comissões') print('#####################\n') faixas_salariais=[(200,299),(300,399),(400,499),(500,599),(600,699),(700,799),(800,899),(900,999),(1000,'em diante')] salarioBase=200 valorvendas=1 vendas = [0, 0, 0, 0, 0, 0, 0, 0, 0] a=0 while valorvendas!...
from SVM import SVM from SVM import * from bagged_forest import build_roots, setToN import numpy as np import dt import copy def data_set_from_roots(roots, X, debug=False): transformed = [] for x in copy.deepcopy(X): predictions = [] for root in roots: prediction = root.predict(x) ...
#!/usr/bin/env python3 # Define function ... def return_video_crop_parameters(fname, /, *, debug = False, dt = 2.0, playlist = -1, timeout = 60.0): # Import standard modules ... import shutil import subprocess # Import sub-functions ... from .return_media_duration import return_media_duration ...
# # 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...
from enum import Enum from enum import auto import pyglet from button import Button from chunkmanager import ChunkManager from scoremanager import ScoreManager from configmanager import ConfigManager class MineField: window_size = ConfigManager.config_dict.get("window_size") score_label = pyglet.text.Labe...
import sys from PyQt5.QtWidgets import * from PyQt5.QtCore import QCoreApplication class MyWindow(QMainWindow): def __init__(self): super().__init__() self.setupUI() def setupUI(self): self.setGeometry(800, 400, 230, 450) # Label label = QLabel("층수", self)...
import torch import gc import os import logging import torch.optim as optim import torch.nn as nn from datetime import datetime """ 5 Fold CV Best Loss: 0.6709386929869652 | 0.6842632591724396 | 0.6594144776463509 | 0.6695199608802795 | 0.6728682070970535 """ # ============================================== # Setup #...
"""Handle the loading of configuration files.""" import yaml def load_config(config_file='/etc/thermopi.yaml'): """Load the configuration file. Parameters ---------- config_file : str Path to the configuration file to load. Returns ------- dict Dict containing the config...
import openpyxl from datetime import datetime from openpyxl import Workbook wb = openpyxl.load_workbook('subbixl.xlsx') sheets = ['Sheet1'] xin = input("P or A") count = 0 yin = str(input("Date")) my = datetime.strptime(yin, "%d-%m-%Y") for sheet in sheets: sh = wb[sheet] # Get a sheet from the workbook....
import numpy as np from numpy.testing import assert_array_equal import pytest from numcodecs.categorize import Categorize from numcodecs.tests.common import (check_encode_decode, check_config, check_backwards_compatibility, check_encode_decode_ar...
# -*- coding: utf-8 -*- import os import json import time worldpath = './server/world' savepath = './savelib' class mcsave(object): def __init__(self, savepath): self.path = savepath def backup(self, meta = {}, writeTime = True): if writeTime: clock = time.strftime('%Y%m%d',time.l...
# -*- coding: utf-8 -*- """ Created on Sat Jul 14 13:22:55 2018 挖掘twitter tweets,找共现词,具体可见machine learning in action 235页 @author: Max Yang """ import twitter from time import sleep import re import pandas as pd import fpGrowth def getLotsofTweets(searchStr): CONSUMER_KEY='4nDxF5gYmarjAcAVCs8B0zSEA' CONSUMER_...
# #=BEGIN # # This file is part of the Bluetooth use-case verification # # Copyright (C) ST-Ericsson SA 2010. All rights reserved. # # This code is ST-Ericsson proprietary and confidential. # Any use of the code for whatever purpose is subject to # specific written permission of ST-Ericsson SA. # #=END # import setup_p...
#!/usr/bin/env python import sqlite3 from dataclasses import fields from jupyterlab_chameleon import db try: with sqlite3.connect("/work/.chameleon/chameleon.db") as conn: cur = conn.cursor() cur.execute("PRAGMA table_info(artifacts);") columns = cur.fetchall() column_names = [c[1]...
import os from .iterators import chunked_iterable def list_s3_prefix(s3_client, *, bucket, prefix=""): """ Lists all the keys in a given S3 bucket/prefix. """ paginator = s3_client.get_paginator("list_objects_v2") for page in paginator.paginate(Bucket=bucket, Prefix=prefix): try: ...
# -*- coding: utf-8 -*- import jieba import sys import matplotlib.pyplot as plt from wordcloud import WordCloud #打开本体TXT文件 text = open('data.txt',encoding='utf-8').read() print(type(text)) #结巴分词 cut_all=True 设置为精准模式 wordlist = jieba.cut(text, cut_all = False) #使用空格连接 进行中文分词 wl_space_split = " ".joi...
# -*- coding: utf-8 -*- __author__ = 'Vit' from bs4 import BeautifulSoup from data_format.url import URL from common.util import _iter, quotes, psp, collect_string from interface.view_manager_interface import ViewManagerFromModelInterface from model.site.parser import BaseSiteParser class PlusoneSite(BaseSiteParse...
import tensorflow as tf import numpy as np class KMeans: def __init__(self, k, n_features, n_classes, sess=tf.Session()): self.k = k self.n_features = n_features self.n_classes = n_classes self.sess = sess self.build_graph() # end constructor def build_graph(self)...
from dataset import Dataset from Model import ConvEncoder, Decoder, SimpleE import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import os from radam import RAdam import numpy as np import scipy.misc from scipy.misc import imsave import torch.autograd as autograd import time ...
#끝나는 시간이 빠른 순으로 정렬 import sys n = int(sys.stdin.readline()) s = [] for i in range(n): first, second = map(int, input().split()) s.append([first, second]) #먼저, 시작 시간을 기준으로 정렬 s = sorted(s, key=lambda a: a[0]) #끝나는 사간을 기준으로 정렬 s = sorted(s, key=lambda a: a[1]) last = 0 cnt = 0 for start, finish in s: if sta...
from collections import defaultdict from tqdm import tqdm from advent import AdventProblem def preprocess(lines): return [int(x) for x in lines[0].split(',')] def part_1(starting_nums, end=2020): nums = defaultdict(list) for i, s in enumerate(starting_nums): nums[s].append(i) last_num = st...
option = input("Enter 1 to add name \nEnter 2 to remove a name from the list \nEnter 3 to view family members\nEnter 4 to exit") listFamily = ["Ala"] while option != "4" : if option == "1" : name = input("Enter a name to add : ") listFamily.append(name) option = input("Enter 1 to add name \n...
# Import necessary libraries import numpy as np # Calculation of the root mean squared error def rmse(y_true, y_pred): return np.sqrt(((y_pred - y_true) ** 2).mean()) # Moving window approach for the nextday models def moving_window_nextday(data, window_size): # Empty list were we will store the result ...