text
stringlengths
8
6.05M
def dig_sum(n): return sum([int(i) for i in str(n)]) s_lst = [] for a in range(100): for b in range(100): s_lst.append(dig_sum(a**b)) def main(): print(max(s_lst)) if __name__=='__main__': main()
# ๅญ—็ฌฆไธฒ str = 'hello' # ๅฎšไน‰ๆ–นๆณ• def function(arg): return arg + arg #่พ“ๅ…ฅ user_input = raw_input() #่พ“ๅ‡บ print user_output # ๆ–‡ไปถๆ“ไฝœ
from django.db import models # __all__ : ์™ธ๋ถ€์—์„œ ๋ชจ๋“ˆ import * ํ•  ๋•Œ *์˜ ๋Œ€์ƒ์ด ๋˜๋Š” ๋ชฉ๋ก. __all__ = ( 'InstagramUser', ) class InstagramUser(models.Model): name = models.CharField( max_length=50, ) # ๋‚ด๊ฐ€ ํŒ”๋กœ์šฐํ•˜๋Š” ์œ ์ € : following # ๋‚˜๋ฅผ ํŒ”๋กœ์šฐํ•˜๋Š” ์œ ์ € : follower # following ํ•„๋“œ๋Š” ๋‚ด๊ฐ€ ํŒ”๋กœ์šฐ ํ•˜๋Š” ์‚ฌ๋žŒ์„ ๋‚˜ํƒ€๋ƒ„. # ํŒ”๋กœ์šฐ ๋‹นํ•˜๋Š” ...
import logging import socket import datetime import time import os import threading import pdb import sys import bisect import traceback """ sys.path.insert(0, "./netfilterlib/") from netfilterqueue import NetfilterQueue sys.path.append("scapy") logging.getLogger("scapy.runtime").setLevel(logging.ERROR) from scapy.all...
import Chapter3.BinaryClassifier_2 def evaluation(sgd_clf): from sklearn.model_selection import cross_val_score result = cross_val_score(sgd_clf, Chapter3.BinaryClassifier_2.X_train, Chapter3.BinaryClassifier_2.y_train_5, #kํด๋“œ ๊ต์ฐจ ๊ฒ€์ฆ ์‚ฌ์šฉ cv=3, scoring="accuracy") #3๊ฐœ์˜ ์„œ๋ธŒ์…‹์œผ๋กœ ๋‚˜๋ˆ”...
# Date: 10/09/2020 # Author: rohith mulumudy # Description: manages the file structure import os class Files: def __init__(self, directory): self.directory = directory def create_file_structure(self, round_num): if not os.path.isdir(self.directory): os.mkdir(self.directory) if not os.path.isdir("{}/{:0...
import argparse from datetime import datetime import torch from torch.optim import Adam from torchsummary import summary # pip install torchsummary from nn import BengaliNet, CrossEntropySumLoss, LabelSmoothingLoss from optim import optimize, ReduceLROnPlateau from utils.data import load_data from utils.tensorboard ...
import numpy as np import pytest import math from sklearn.base import clone from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor import doubleml as dml from ._utils import draw_smpls from ._utils_iivm_manual import fit_iivm, boot_iivm @pytest.fixture(scope='module', params=[[...
import tensorflow as tf import numpy as np import os import sys from PIL import Image, ImageOps path = '/content/base/' def image_preprocessing(filename, x_size, y_size): im = Image.open(filename) if filename.endswith('.png'): im = im.convert('RGB') downsampled_im = ImageOps.fit(im, (x_size, y_si...
import numpy as np from rpy2.robjects import numpy2ri numpy2ri.activate() from rpy2.robjects.packages import importr stepR = importr('stepR') # x : np.ndarray # t : np.ndarray # alpha : float # -> ([x.dtype], [t.dtype], [(t.dtype, t.dtype)]) def smuce_r(x, t, alpha): res = stepR.stepFit(x, x=t, alpha=alpha, jumpint=...
๏ปฟ# coding: utf-8 #################################### #ๆœ€ๅˆใฎไพ‹(MyButtonใ‚’Globalใงๅ…ฑๆœ‰) #################################### if "IronPythonใŒๅ‹•ใใพใ—ใŸ" == MyButton.Parent.Text: MyButton.Text = "Globalsใฎๅˆฉ็”จ ๏ผˆ1st.py๏ผ‰" MyButton.Parent.Text = "IronPython" elif "IronPython" == MyButton.Parent.Text: MyButton.Text = "ใ‚นใ‚ฏใƒชใƒ—ใƒˆใ‚’ๅฎŸ่กŒใ—...
import pandas as pd import numpy as np import glob import datetime sonde = pd.read_csv('All Sonde Output.csv', header=0) GPS = pd.read_csv('Final out.csv', header=0) CO2 = pd.read_csv('Final CO2.csv', header=0) sondeCO2 = pd.merge(sonde, CO2, on='time') print(sondeCO2)
from keras.preprocessing.sequence import pad_sequences from keras.preprocessing.text import Tokenizer from keras.layers.merge import concatenate from keras.models import Sequential, Model from keras.layers import Dense, Embedding, Activation, merge, Input, Lambda, Reshape from keras.layers import Convolution1D, Flatte...
""" realizar la multiplicacion de numeros de una lista Tarea 17 """ def multiplicacion(lista): res = 1 for i in range(len(lista)): res = res * lista[i] return res prueba1 = [1,2,3,4]#24 prueba2 = [1,2]#2 print(multiplicacion(prueba1)) print(multiplicacion(prueba2))
from server import app from flask import jsonify from api.model.signboard import Signboard @app.route('/signboards') def get_signboard(): r = Signboard.query.all() return jsonify({"data": r}) @app.route('/signboard/<string:customer_code>/<string:signboard_code>', methods=['PUT']) def put_signboard(customer_co...
import os from sendgrid import SendGridAPIClient from sendgrid.helpers.mail import Mail def sendEmail(body): message = Mail( from_email='jhalv001@ucr.edu', to_emails='jhalvorson6687@gmail.com', subject='RMailbox Package Notification ', html_content= body) try: sg = SendGridAPIClient(os....
import sys import scikit_posthocs as sp import re import scipy.stats as ss from scipy import stats from numpy import * alpha=0.05 def check_means(file1, file2): mean1 = mean(file1) mean2 = mean(file2) if mean1 > mean2: return 1 elif mean1 < mean2: return -1 else: return 0 def process_ins...
a = input("ะ’ะฒะตะดะธ ัั‚ั€ะพะบัƒ:") if len(a) % 2: a1 = a[len(a) // 2 + 1:] + a[:len(a) // 2 + 1] else: a1 = a[len(a) // 2:] + a[:len(a) // 2] print(a1)
#!/bin/python2.7 # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # ...
import os import re import random import math import torch import torch.nn as nn import numpy as np from torch.autograd.function import Function import cv2 INTER_MODE = {'NEAREST': cv2.INTER_NEAREST, 'BILINEAR': cv2.INTER_LINEAR, 'BICUBIC': cv2.INTER_CUBIC} class CenterLoss(nn.Module): def __init__(self, num_class...
# This file is part of beets. # Copyright 2016, Fabrice Laporte # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Web presentation DataGroup, UserGroupPerm classes""" from django import template #from django import http from django.shortcuts import render_to_response # , redirect, get_object_or_404get_list_or_404, HttpResponse from django.utils.translation import ugettext as _ ...
import networkx as nx import matplotlib.pyplot as plt G=nx.Graph() G.add_node(1) G.add_node(2) G.add_node(3) G.add_edge(1,2) G.add_edge(2,3) G.add_edge(3,1) print(G.nodes) #print the name of edges nx.draw(G) plt.show()
from pyvi import ViTokenizer path = "document1.txt" f = open(path,"r",encoding="utf-8") e = f.read(); s_tt= ViTokenizer.tokenize(e) fo = open("final.txt","w",encoding="utf-8") fo.write(s_tt) f.close() fo.close()
import unittest from katas.kyu_6.simple_sentences import make_sentences class MakeSentencesTestCase(unittest.TestCase): def test_equals(self): self.assertEqual(make_sentences(['hello', 'world']), 'hello world.') def test_equals_2(self): self.assertEqual(make_sentences( ['Quick', ...
import sys import os import math import tempfile sys.path.insert(0, 'scripts') sys.path.insert(0, os.path.join("tools", "trees")) sys.path.insert(0, os.path.join("tools", "print")) sys.path.insert(0, os.path.join("tools", "families")) import saved_metrics import fam import pickle from aligned_printer import AlignedPrin...
import torch import torchvision import torch.nn as nn import numpy as np import torchvision.transforms as transforms # ================================================================== # # Table of Contents # # =========================================================...
from typing import Optional, Tuple from esipy import EsiClient from waitlist.utility import outgate from waitlist.utility.config import banned_by_default from waitlist.utility.sde import add_type_by_id_to_database from waitlist.storage.database import Constellation, SolarSystem, Station,\ InvType, Account, Charac...
from common import * import base64 ####file encrypt part def encrpty_file(file_path, pubkey): log.debug("-------") cipher_text = b'' max_length = int(get_max_length(pubkey)) if pubkey: cipher_public = Crypto.Cipher.PKCS1_v1_5.new(pubkey) with open(file_path, 'r', encoding='UTF-8') as f...
import argparse import os import pandas as pd from utils import download_incidents, create_folder, video_to_frames __author__ = 'roeiherz' VIDEO_PATH = "/data/Accidents1K/Videos" INDEX_PATH = "/data/Accidents1K/accident_index.csv" IMAGE_PATH = "/data/Accidents1K/Images" def get_video_links(index_path): """ ...
#SevenDigitsDrawV2.py import turtle as p import time as t #import turtle,time def drawGap(): #็ป˜ๅˆถๆ•ฐ็ ็ฎก้—ด้š”,ๆฏๆฎตๆ•ฐ็ ็ฎกไน‹้—ดไธ่ฟž็ปญ p.penup() p.fd(5) def drawline(draw): #็ป˜ๅˆถๅ•ๆฎตๆ•ฐ็ ็ฎก drawGap() p.pendown() if draw else p.penup() p.fd(40) drawGap() p.right(90) def drawDigit(digit): #ๆ นๆฎๆ•ฐๅญ—็ป˜ๅˆถไธƒๆฎตๆ•ฐ็ ็ฎกๅนถๅฐ†ๆตท้พŸๅณ็งป20ไธชๅƒ็ด  d...
# coding: utf-8 # $\newcommand{\xv}{\mathbf{x}} # \newcommand{\Xv}{\mathbf{X}} # \newcommand{\yv}{\mathbf{y}} # \newcommand{\zv}{\mathbf{z}} # \newcommand{\av}{\mathbf{a}} # \newcommand{\Wv}{\mathbf{W}} # \newcommand{\wv}{\mathbf{w}} # \newcommand{\tv}{\mathbf{t}} # \newcommand{\Tv}{\mathbf{T}} # \newcommand{\muv}{\b...
for str in open("C:/Users/dinesh kumar/Documents/text1.txt"): print(str,end="")
""" Author : Lily Data : 2018-09-18 QQ : 339600718 ็ง‘้ขœๆฐ Kiehl's Kiehls-s ๆŠ“ๅ–ๆ€่ทฏ๏ผšๅพฎไฟกๅ…ฌไผ—ๅท๏ผŒๆ‹ฟๅˆฐprovince็š„id,ๅšไธบๅ‚ๆ•ฐ๏ผŒ่ฏทๆฑ‚city็š„id,ๆ นๆฎcityid่ฏทๆฑ‚stores็š„ๆ•ฐๆฎ getProvince๏ผˆpost,json๏ผ‰:http://wx.kiehls.com.cn/KStart/GetProvince getCity๏ผˆpost,json,ๅ‚ๆ•ฐ๏ผšproId๏ผ‰:http://wx.kiehls.com.cn/KStart/GetCity getStore๏ผˆpost,json๏ผŒๅ‚ๆ•ฐ๏ผšcity_id: 37,longitude: ,latitude:...
# Enter script code keyboard.send_keys("<f6>8")
from django.contrib.auth.models import User from django.db import models class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) nickname = models.CharField(max_length=20, default='') class Meta: ordering = ['nickname'] def __str__(self): return self...
import keras import pyfor from keras_retinanet import models from keras_retinanet.utils.image import read_image_bgr, preprocess_image, resize_image from keras_retinanet.utils.visualization import draw_box, draw_caption from keras_retinanet.utils.colors import label_color import matplotlib.pyplot as plt import cv2 impor...
import math i = 5 j = 2 * i j = j + 5 print(i) print(j) j = j - i print(j) print(7 / 2) print(7 / 3.5) print(8 + 2.6) print(9 // 5) print(9 % 5) print(3 ** 4) print(math.sqrt(36)) print(math.log2(2)) print(math.log2(4)) i = 5 print(type(i)) i = 7 * 1 print(type(i)) j = i / 3 print(type(i)) print(type(j)) i = 2 * j ...
def addfruit(fruit1,price1): fruit_dict={} i=0 while i!=len(fruit1): try: if fruit1[i].lower() not in fruit_dict: fruit_dict.update({fruit1[i]:price1[i]}) i+=1 else: i+=1 raise ValueError excep...
class Solution: def twoCitySchedCost(self, costs: List[List[int]]) -> int: l = len(costs)//2 costs = sorted(costs, key=lambda i: abs(i[1]-i[0])) n1 = n2 = tcost = 0 for i in range(len(costs)-1,-1,-1): if costs[i][0] < costs[i][1]: if n1<l: ...
# -*- coding: utf-8 -*- from django.contrib import admin from app.customer.models import Customer class CustomerAdmin(admin.ModelAdmin): model = Customer admin.site.register(Customer, CustomerAdmin)
import numpy as np import os import csv Tainan_city_id = '467410' Tainan_city_id2= '467411' Tainan_county_id = '467420' Dataset=[] labellist=['stno','yyyymmdd', 'PS01', 'PS02', 'PS03', 'PS04', 'PS05', 'PS06', 'PS07', 'PS08', 'PS09', 'PS10', 'TX01', 'TX02', 'TX03', 'TX04', 'TX05', 'TX06', 'TD01', 'TD02', 'TD03', 'TD04...
#!/usr/bin/env python # Copyright 2017 Google Inc. # # 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...
url = 'https://opendart.fss.or.kr/api/list.xml'
import pyspark from pyspark import SparkConf, SparkContext import collections conf = SparkConf().setAppName("SalaryAnalysis") sc = SparkContext(conf = conf) # Detroit Open Data file located https://data.detroitmi.gov/Government/Mayoral-Appointee-Salaries/fwu6-4nb5 lines = sc.textFile("hdfs://cluster-b435-m/wsu/Mayora...
import os import sys import pygame import requests from inoutbox import get_key, display_box, ask, main question = 'https://geocode-maps.yandex.ru/1.x/?apikey=40d1649f-0493-4b70-98ba-98533de7710b&geocode=ะะฒัั‚ั€ะฐะปะธั&format=json' resp = requests.get(question) if resp: resp = resp.json() cords = resp["response"][...
from models.data_types import ComplexDataType class Method(ComplexDataType): def __init__(self, name, description, result_type_name=None, deprecated=False): super(Method, self).__init__(name, description, deprecated) self._result_type_name = result_type_name self._permissions = {} @pr...
# -*- coding: utf-8 -*- ''' NAPALM Probes ============= Manages RPM/SLA probes on the network device. :codeauthor: Mircea Ulinic <mircea@cloudflare.com> & Jerome Fleury <jf@cloudflare.com> :maturity: new :depends: napalm :platform: linux Dependencies ------------ - :mod:`napalm proxy minion <salt.proxy.napal...
def add_arguments(parser): parser.add_argument( "-d", "--data_file", required=True, help="file or dir containing training data" ) parser.add_argument( "-o", "--out_file", required=True, help="file where to save training data in rasa format", ) parser.add_arg...
from collections import deque import random import numpy as np class DataMemory(): def __init__(self, max_len=50000): super(DataMemory, self).__init__() self.max_len = max_len self.memory = deque() def add(self, s_t, a_t, r_t, s_n, terminal): self.memory.append((s_t, a_t, r_t...
# -*- coding: utf-8 -*- """ Created on Thu Oct 27 12:48:05 2016 @author: wattai """ import numpy as np import matplotlib.pyplot as plt def gauss_ludgendle(N_iter): a0 = 1. / np.sqrt(2) b0 = 1. s0 = 1. t0 = 4. pis = [] for i in range(N_iter): a1 = np.sqrt(a0*b0) b1 = (a0 + ...
import recommendations from math import sqrt #import pydilicious #import maybe #ไฟฎๆ”น่ฟ‡็š„python3็š„็‰ˆๆœฌไธ”ๅˆ ้™คไบ†ๅบŸ่ฏ็š„ใ€‚ import noway #ๆ„Ÿ่ง‰่ฐƒ็”จget_popularๅ‡ฝๆ•ฐๆ‰€็”จๅˆฐ็š„้ƒจๅˆ†้ƒฝๅœจ่ฟ™ไบ†ใ€‚ ##็ฌฌไบŒ็ซ ๅŽ้ข็š„ๅ†…ๅฎน่ฟ˜ๆ˜ฏๅฏไปฅ็ปง็ปญๅš็š„ใ€‚www ''' print(critics['Lisa Rose']['Lady in the Water']) critics['Toby']['Snakes on a Plane'] = 4.5 print(critics['Toby'])#่พ“ๅ‡บ็š„้กบๅบๆ˜ฏ้šๆœบ็š„ๅ”‰ใ€‚ a = ...
from multiprocessing import Pool from indigox.config import INIT_WITH_GA, NUM_PROCESSES from indigox.exception import IndigoUnfeasibleComputation from indigox.misc import (BondOrderAssignment, graph_to_dist_graph, electron_spots, electrons_to_add, locs_sort, HashBitArray, graph_setup, ...
try: # try/except block raise IndexError # raise the exception except IndexError: # catch the exception print('got the exception') print('continuing')
from unittest import TestCase import search class TestSearch(TestCase): def test_search_by_name_should_return_empty(self): contact_data = [ { "city": "Rennes", "name": "Ivan Riley", "country": "Burkina Faso", "company": "Nonummy...
import logging import aioisotp logging.basicConfig(level=logging.DEBUG) network = aioisotp.SyncISOTPNetwork(channel='vcan0', interface='virtual', receive_own_messages=True) server = network.create_sync_connection(0x456, 0x123) with network.open(): client = network.create_sync_connection(0x123, 0x456) clien...
import twitter from twitter.stream import TwitterStream, Timeout, HeartbeatTimeout, Hangup from twitter.oauth import OAuth from twitter.oauth2 import OAuth2, read_bearer_token_file from twitter.util import printNicely from string import ascii_letters import os import re import string import sys # XXX: Go to http://dev...
# Generated by Django 2.0.7 on 2018-07-31 09:11 from django.db import migrations, models import django.utils.datetime_safe class Migration(migrations.Migration): dependencies = [ ('post_app', '0008_comment_comment'), ] operations = [ migrations.AlterField( model_name='file',...
#!/usr/bin/env python from manimlib.imports import * # To watch one of these scenes, run the following: # python -m manim example_scenes.py SquareToCircle -pl # # Use the flat -l for a faster rendering at a lower # quality. # Use -s to skip to the end and just save the final frame # Use the -p to have the animation (...
from django.conf.urls import include, url from . import views urlpatterns = [ url(r'^$', views.QuestionIndexView.as_view(), name='qa_index'), url(r'^question/(?P<pk>\d+)/$', views.QuestionDetailView.as_view(), name='qa_detail'), url(r'^question/(?P<pk>\d+)/(?P<slug>[-_\w]+)/$', views.Que...
""" Executed from loop_swap_protocol folder """ import loop_align_updates as la import pickle from pyrosetta.rosetta.core.pack.task import TaskFactory from pyrosetta.rosetta.core.pack.task.operation import \ OperateOnResidueSubset, RestrictAbsentCanonicalAASRLT from pyrosetta.rosetta.protocols.grafting import...
# -*- coding: utf-8 -*- """Tests for pyss3.cmd_line.""" from pyss3.cmd_line import SS3Prompt, main from pyss3.server import Server from pyss3.util import Evaluation from pyss3 import SS3 from os import path import pyss3.cmd_line import pyss3.util import pytest import sys MODEL_NAME = "cmd_test" DATASET_FOLDER = "data...
"""Config flow for Toggl integration.""" import logging import voluptuous as vol from homeassistant import config_entries, core, exceptions from .const import DOMAIN # pylint:disable=unused-import _LOGGER = logging.getLogger(__name__) DATA_SCHEMA = vol.Schema({"token": str}) class TogglHub: """Hub for TogglPy ...
import numpy as np def dict_median_scores(dict_list): median_dict = {} for key in dict_list.keys(): value = dict_list[key] value_arr = np.array(value) if np.isnan(value_arr).any() == True: median_dict[key] = np.nan else: #append_low = np.percentile(value...
from django.shortcuts import render , redirect , get_object_or_404 from django.http import HttpResponse, Http404 from django.contrib.auth.models import User from .models import Note from django.contrib import messages from django.template.loader import get_template from django.http import HttpResponse from .script impo...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Feb 7 20:34:37 2020 @author: adeela """
# coding: utf-8 # Python script created by Lucas Hale # Standard Python libraries from typing import Optional # http://www.numpy.org/ import numpy as np # https://github.com/usnistgov/atomman import atomman as am import atomman.lammps as lmp import atomman.unitconvert as uc from atomman.tools import filltemplate, a...
import itertools data = [] """ Process inputData.txt and put it into the data array. """ with open("inputData.txt", "r") as infile: for line in infile: data.append(int(line)) valid_permutations = {} def checkIfValid(permutation): return sum(permutation) == 150 """ Main loop This is the best expla...
from struct import * import numpy as np # I considered using multiprocessing package, but I find this code version is fine. # Welcome for your version with multiprocessing to make the reading faster. # from joblib import Parallel, delayed import multiprocessing import time import os import argparse from open3d import *...
import nltk from nltk.collocations import * from nltk.metrics import BigramAssocMeasures import operator import string import math measures = BigramAssocMeasures() l_ru = [] with open("text_ru.txt", 'r', encoding="utf-8") as f: for line in f: for w in nltk.word_tokenize(line.lower()): if w not in string.punctua...
from django.db.models import Sum from django.utils import timezone from .models import Commission from apps.jobs.models import Jobs class CommissionManager(object): """ Manager for commission calculations """ def getCommUser(self, user): """ Returns commission amount due for the use...
def leiaInt(): red = "\033[1;31m" print('-' * 20) while True: n = str(input('Digite um nรบmero: ')) if n.isnumeric(): n = int(n) print(f'Voce digitou o nรบmero {n}') break else: print(f'\033[0;31;mERRO! Digite um nรบmero inteiro vรกlido\033...
import datetime import hashlib import json import rsa from flask import Flask, jsonify, request import json import requests keys_list = {} threshold_value = 60 class Blockchain: def __init__(self): self.chain = [] self.create_block(proof=1, previous_hash='0', value=0) def create_block(self, ...
from common import * from database import * from format import * from site import *
import stat from typing import Dict from pathlib import Path class FileStat: filename: str relname: str size: int mtime: int FileStatDict = Dict[str, FileStat] class LocalFileStat(FileStat): """ Local filestat """ def __init__(self, root: str, path: Path): stat_output = path....
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'form.ui' # # Created by: PyQt5 UI code generator 5.11.3 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_mainWindow(object): def setupUi(self, mainWindow): mainWindow....
"""@package ScipyMinimize This package implements the minimize optimisers from SciPy. @author Dr Franck P. Vidal, Bangor University @date 5th July 2019 """ ################################################# # import packages ################################################### from scipy import optimize from Solution i...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Oct 23 15:45:45 2017 @author: dgratz """ from readFile import readFile import re from glob import glob import numpy as np import matplotlib.pyplot as plt s = re.compile('/') u = re.compile('_') datadir = 'D:/synchrony-data/AllConnAndRand/' conns = list...
#Created on February 23, 2017 #@author: rspies@lynkertech.com # Python 2.7 # This script creates an horizontal bar chart of station data availability # for precip/temp data sites import os import numpy as np import datetime from datetime import timedelta import matplotlib.pyplot as plt import matplotlib.da...
""" Placeholder for a synthetic field. """ class SyntheticField: """ Placeholder for a synthetic field. """ def __init__(self): """ Store all the parameters for later usage, as well as reference to a synthetic generator. """ def make_sampler(self): """ Create a sampler to generate pseudo-...
import numpy as np e = np.array([11,2,3,4,5,6,12,23,8,21]) print(np.max(e)) print(np.min(e)) print(np.median(e)) print(np.std(e))
l,u=map(int, input().split()) li=[] for i in range(l+1,u): if i%2==0: li.append(str(i)) print(" ".join(li)) #prasad
import math from pyspark import SparkContext, SparkConf import sys import time import multiprocessing from pyspark.mllib.recommendation import ALS, Rating import heapq start_time = time.time() # Model based cf def model_base_cf(rdd, train_rdd, test_rdd, user_enum, bus_enum): # Training ratings_train = train_rdd \ ...
from typing import ( List, Dict, Text, Any, Optional ) from rasa.shared.core.events import Event, UserUttered class UserBotUttered(): def __init__(self, last_message:UserUttered, bot_predict_event:Optional[Text] ) -> None: """ Crea un evento que contiene...
#coding:utf-8 #!/usr/bin/env python from game.routine.pet import pet from game.routine.skill import skill from game.routine.equipment import equipment class luck: @staticmethod def check(usr, card, petConf): """ ๆฃ€ๆต‹็ผ˜ """ petInfo = petConf[card['cardid']] luckid = [] for l in petInfo['...
from fastapi import FastAPI, File, UploadFile from fastapi.responses import FileResponse,Response from pydantic import BaseModel import io from io import BytesIO import numpy as np from PIL import Image import shutil import os os.environ["CUDA_VISIBLE_DEVICES"]="-1" import tensorflow as tf ...
import tensorflow as tf print(tf.__version__) hello = tf.constant("Hello Tensorflow") print(hello) sess = tf.Session() # ์‹คํ–‰ ํ›„ ๊ฒฐ๊ณผ๊ฐ’์ด bytes ํƒ€์ž…์ด๋ฏ€๋กœ decode ํ•„์š” result = sess.run(hello) print(result) print(result.decode()) a = tf.constant(10) b = tf.constant(20) _a, _b = sess.run([a, b]) print(_a, _b)
import json def read_dict(db_name): try: #little ducktyping -- catches both file not found and file empty (incase it was erased) with open(db_name, 'r') as f: print("updating db...db_name") return json.load(f) except (FileNotFoundError, ValueError): print("creating db......
from django.urls import path from jobs.api.views import (JobOfferDetailAPIView, JobOfferListCreateAPIView) urlpatterns = [ path("jobs/", JobOfferListCreateAPIView.as_view(), name="job-list"), path("jobs/<int:pk>/", JobOfferDetailAPIView.as_view(), ...
""" https://leetcode.com/problems/number-of-subarrays-with-bounded-maximum/ We are given an array nums of positive integers, and two positive integers left and right (left <= right). Return the number of (contiguous, non-empty) subarrays such that the value of the maximum array element in that subarray is at least le...
import json import logging import time import certifi import urllib3 class BitbucketApiBindings: """ Wraps Bitbucket API functions. """ def __init__(self, rate_limit: int): self.__rate_limit = rate_limit def form_bitbucket_request(self, url: str) -> urllib3.response: """ C...
import cv2 import random import numpy as np import matplotlib matplotlib.use("TkAgg") from matplotlib import pyplot as plt import os grayscale_max = 255 def load_image(filename): image = cv2.imread(filename, cv2.IMREAD_GRAYSCALE) return image def show_image(title, image): max_val = image.max() # ...
import pandas as pd import sys outf = sys.argv[1] score_df = pd.DataFrame() fids, pids, scores = [], [], [] with open('plink.profile', 'r') as r: lines = r.readlines() for line in lines[1:]: words = line.split() fids.append(words[0]) pids.append(words[1]) scores.append(float(words[-1])) score_df['FID'] = fids...
import random PATTERNS = [ (1000000000000000, 'xxxxx'), (-1000000000000000, 'ooooo'), (10, ' xx '), (-10, ' oo '), (10, ' x x '), (-10, ' o o '), (10, ' x x '), (-10, ' o o '), (100, ' xx '), (-100, ' oo '), (-3300000, ' ooo '), (1100000, ' xxx '), ...
# encoding: utf-8 ''' This application does a simple NVE+Langevin LAMMPS simulation of spherocylinder-like rods (defined in a .cfg file) using the "lammps_multistate_rods" library. The initial locations of the rods are at SC lattice points defined by the input params, and their orientations are randomly determined at e...
from prettytable import PrettyTable from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score import utils class Evaluator(object): @staticmethod def evaluate_multi_class(y_preds, y_truths): pred_labels = set(y_preds) true_labels = set(y_truths) all_labels = ...
# plotting two line diagrams on the same x-axis but different y-axis # especially useful when you want to superimpose ratio/ percentage against absolute numbers import numpy as np import matplotlib.pyplot as plt import pandas from textwrap import wrap from matplotlib.ticker import FuncFormatter import locale locale.set...
import numpy as np import matplotlib.pyplot as plt from sklearn.naive_bayes import MultinomialNB def values_to_bins(data, bins): return np.digitize(data, bins) - 1 train_images = np.loadtxt('data/train_images.txt') # incarcam imaginile # incarcam etichetele avand # tipul de date int train_labels = n...
TESTAPI_ID = 'testapi_id' CSRF_TOKEN = 'csrf_token' ROLE = 'role' TESTAPI_USERS = ['opnfv-testapi-users']
from .models import * from django.shortcuts import * from django.views import View from django.http import HttpResponse, HttpRequest def check_if_int(number): try: return int(number) except Exception: return None def create_person(request): person = Person() name = request.POST.get("...