text
stringlengths
8
6.05M
#!/usr/bin/env python def McNuggets(n): res = False for a in range(n/6+1): for b in range(n/9+1): for c in range(n/20+1): if (6*a + 9*b + 20*c) == n: res = True return res print McNuggets(15) print McNuggets(16) print McNuggets(6) print McNuggets(9) print McNuggets(20) print McNuggets(35) #print McNu...
#!/usr/bin/env python """ pyjld.system: various system level utilities (e.g. daemon, cross-platform registry, command-line tools) This package contains various system level utilities. ========= Changelog ========= *0.5* * command.ui: ref_options are now optional *0.4* * Added ''proxy'' module * Corrected "cmd_re...
import logging import sys import inject sys.path.insert(0,'../../../python') from model.config import Config logging.getLogger().setLevel(logging.DEBUG) from autobahn.asyncio.wamp import ApplicationSession from asyncio import coroutine ''' python3 getOvertimeRequestsByState.py userId #retorna los requerimientos de ...
def validate_row(row): return len(row) == 9 and len(set(row)) == 9 and all(1 <= e <= 9 for e in row) def validate_rows(matrix): result = True for row in matrix: result = result and validate_row(row) return result def validate_columns(matrix): return validate_rows(list(zip(*matrix))) de...
# Driver code my_list = [56,345,78,23,98,34,65,85] for i in range(1, len(my_list)): #The first value after the sorted array key = my_list[i] # Values that are greater than the key value ... # .. move one index forward j = i - 1 while j>=0 and key<=my_list[j]: my_list[j + 1]...
# -*- coding: utf-8 -*- # @Time : 2019/10/14 12:25 # @Author : Weiyang # @File : Segmentation.py #================================================================================================================== # 分词器:隐马尔可夫模型和字典匹配两种方式,其中,隐马尔可夫模型又分为 监督学习模型 和 无监督学习模型 #============================================...
# Copyright 2023 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations import argparse import logging import os import shutil import subprocess from dataclasses import dataclass from textwrap import dedent from typing impor...
import time from math import sqrt, tan, sin, cos, pi, ceil, floor, acos, atan, asin, degrees, radians, log, atan2, acos, asin from random import * import numpy from pymclevel import alphaMaterials, MCSchematic, MCLevel, BoundingBox from mcplatform import * import Queue import utilityFunctions from helper import * from...
#!/usr/bin/env python3 class PinholeCamera(object): def __init__(self, width, height, fx, fy, cx, cy, k1=0.0, k2=0.0, p1=0.0, p2=0.0, k3=0.0): self.width = width self.height = height self.fx = fx self.fy = fy self.cx = cx self.cy = cy self.di...
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^snap/', views.snap, name='snap'), url(r'^jupyter/', views.jupyter, name='jupyter'), url(r'^monitor/', views.monitor, name='monitor'), url(r'^rest/$', views.rest, name='rest'), url(r'^rest/raw/$'...
#Sidharth Peri #HW 5 Question 1 #Honor Code: I pledge in my honor that I have abided by the Stevens Honor System #A program that uses a function to accept a list and returns a modified list with the elements squared #function that takes in a list as a parameter and returns the list with each element squared def squar...
CODE SHARED edit edit edit
#!/usr/bin/python3 -u ### Install: # apt-get install python3-pip # pip3 install netifaces import sys import os import subprocess import time import netifaces INTERFACES = ['eth1','eth2','eth3','eth4','eth5','eth6'] ACTIONS = ['up','down'] ### CHANGE HERE TO YOUR INTERFACE ADDRESS MAIN_NETWORK = '10.55...
import os import requests s = "https://api.covid19india.org/csv/latest/state_wise.csv" def getdata(): return(requests.get(s).content)
import pytest from mitmproxy.test import taddons from mitmproxy.test import tflow from mitmproxy import io from mitmproxy import exceptions from mitmproxy import options from mitmproxy.addons import streamfile def test_configure(tmpdir): sa = streamfile.StreamFile() with taddons.context(options=options.Opti...
import cv2 import tensorflow as tf import constants as c def prepare(filepath, width, height): img_array = cv2.imread(filepath, cv2.IMREAD_GRAYSCALE) img_array = img_array/255.0 new_array = cv2.resize(img_array, (width, height)) return new_array.reshape(-1, width, height, 1) def predict(filepath, mo...
import json with open('group3_data.json', 'r', encoding='utf8')as fp: json_data = json.load(fp) userlist=[] for user in json_data: userlist.append(user) print(userlist) print(len(userlist))
import math class GeoLocation: ''' Class representing a coordinate on a sphere, most likely Earth. This class is based from the code smaple in this paper: http://janmatuschek.de/LatitudeLongitudeBoundingCoordinates The owner of that website, Jan Philip Matuschek, is the full ow...
n = 0 qt = 0 s = 0 while(n != 999): n = int(input('Digite um número [999 finaliza]: ')) if(n != 999): qt += 1 s += n print('Foram digitados {} números, cuja soma é {}.'.format(qt, s))
import filecmp import logging import os import tempfile import unittest import xarray as xr from labop.data import serialize_sample_format from labop.strings import Strings from labop.utils.helpers import file_diff, initialize_protocol from labop_convert import MarkdownSpecialization from labop_convert.behavior_speci...
#!/usr/bin/env python3 """fix_fits.py A script to undo the compression on HDUs as implemented in the .fz file format. It will not overwirte an existing file. Requires: astropy docopt Usage: fix_fits.py INPUT [ -o OUTPUT ] Options: -h --help Show this message. -o OUTPUT if not specified then nam...
import numpy as np def start_config(N,M): '''Start config.''' return np.random.randint(2,size=N*M).reshape((N,M)) def grab_neighbors(i,j,config): '''Grab neighbors with PBCs''' confsh=config.shape N,M=confsh[0],confsh[1] top = [i-1 if i-1>=0 else N-1, j ] bottom = [(i+1)%N,j] le...
# -*- coding: utf-8 -*- import unittest from minecraft_dynmap_timemachine import dynmap from minecraft_dynmap_timemachine import projection class TestDynMapClassMethods(unittest.TestCase): def test_dynmap_parse_config_urls(self): config_urls = dynmap.DynMap.parse_config_urls_string("var config = { url : ...
# Create a program that pulls data from OpenWeatherMap.org that prints out information about the current weather, such as the high, the low, and the amount of rain for wherever you live. Depending on how skilled you are, you can actually do some neat stuff with this project. # # Subgoals # # Print out data for the ...
import bs4 from bs4 import BeautifulSoup as soup from urllib.request import urlopen as uReq import os myurl = ( "https://www.newegg.com/Video-Cards-Video-Devices/Category/ID-38?Tpk=graphics+cards" ) # opening a connection and grabbing the page uClient = uReq(myurl) page_html = uClient.read() # storing the html p...
# Verifique se um inteiro positivo n é primo #se o % = 0 não é primo n = int(input('Digite um número inteiro positivo para saber se é primo: ')) total = 0 for c in range(1, n + 1): if n % c == 0: total += 1 if total == 2: print(f'O número {n} foi divisível {total} vezes. Ele é primo') else: prin...
# Write a Python program to get unique values from a list def uniqueValues(listprovided): unique = [] for i in range(len(listprovided)): if listprovided[i] not in unique: unique.append(listprovided[i]) return unique listprovided = [10, 20, 30, 40, 20, 50, 60, 40] output = uniqueValues...
n = input() s = set(map(int, input().split())) for _ in range(int(input())): x = list(input().split()) try: int(x[1]) except IndexError: eval('s.%s' % x[0]) else: eval('s.%s(%d)' % (x[0], int(x[1]))) print(sum(s))
from panda3d.core import Vec3, Point3 from bsp.bspbase import BSPUtils from .Line import Line from . import PlaneClassification from .Plane import Plane class Winding: def __init__(self, vertices, plane): self.vertices = vertices self.plane = plane @staticmethod def fromVertices(vertice...
#!/usr/bin/python3 def multiply_by_2(a_dictionary): key_list = sorted(a_dictionary.keys()) new_dict = {key: a_dictionary[key] * 2 for key in key_list} return new_dict
""" 19. Palindrome Number Question: Determine whether an integer is a palindrome. Do this without extra space. Example Questions Candidate Might Ask: Q: Does negative integer such as –1 qualify as a palindrome? A: For the purpose of discussion here, we define negative integers as non-palindrome. """ class Solution: ...
"""Tests for Doof""" import asyncio from contextlib import asynccontextmanager from datetime import datetime, timedelta import pytest import pytz from bot import ( CommandArgs, Bot, FINISH_RELEASE_ID, NEW_RELEASE_ID, ) from conftest import ( ANNOUNCEMENTS_CHANNEL, LIBRARY_TEST_REPO_INFO, W...
from customers.Aurora.surgery.surgery_mappings import PROC_NM from lib.master_fake_data_generator import FakeDataGenerator class AURORASurgeryFakeDataGenerator(FakeDataGenerator): def generate_pipeline_row(self, row: str, file_size: int) -> dict: f = self._faker r = self._random start, en...
import psycopg2 from setup import * from connection import Connection from pprint import pprint class RegisteredCustomer(Connection): def __init__(self, first_name, last_name, city, email, password): self.first_name = first_name self.last_name = last_name self.city = city self.log...
from . import views from django.urls import path urlpatterns = [ path('' , views.home, name = "home"), path('addDirector', views.addDirector, name = "addDirector") ]
#-*- coding:utf-8 -*- from sys import argv script, user_name = argv prompt = ' uhm.. ' print "Hi %s, I'm the %s script." % (user_name, script) print "I'd like to ask you a few questions." print "Do you like me %s?" % user_name likes = raw_input(prompt) print "Where do you l...
# Copyright 2023 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). import argparse import json import os from pants_release.common import VERSION_PATH, sorted_contributors from pants_release.git import git from pants.util.dirutil import safe_mkdir from ...
#!/usr/bin/env /proj/sot/ska/bin/python ################################################################################################################# # # # compute_bias_data.py: extract bias ...
# utils.py: utility functions import numpy as np import math # seconds to blocks def seconds_to_blocks(stream, secs): return int(math.ceil( float(secs) * stream.sample_rate / stream.block_size )) # hertz to index in fft def hz_to_fft(stream, hz): return np.clip( int(float(hz) * stream.block_size / stream.sample_ra...
from typing import Generator import logging import boto3 import os SSM_PATH_FORMAT = '/bastion/{environment}/instance_id' def list_to_dict(obj, key="Key", value="Value"): return {e[key]: e[value] for e in obj} def update_ssm_params(asg_names): updater = UpdateSSMParamStore() for asg_name in asg_names: ...
from compilador.objects.quadruple import Quadruple from router_solver import * import compilador.objects.function_table import compilador.objects.symbol from compilador.objects.symbol import Symbol from compilador.objects.function_table import * from compilador.objects.symbol import * import sys import re # ARCHIVO C...
import unittest import sys, os, inspect currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir = os.path.dirname(currentdir) sys.path.insert(0, parentdir) import grok correct_examples = [ ("%{NUMBER}", "1"), ("%{NUMBER}", "-1"), ("%{NUMBER}", "1.0"),...
# #placeholder for general utility functions # def default_dic(defaults,actual,inplace=False,clobber=False): """ return a composit of defaults and actual dictionaries """ #make a copy of actual if inplace: if clobber: defaults.clear() defaults.update(actual) else: ...
# Вы решили написать преобразователь кода на Python в код на Java. Так как на Java принят стандарт наименования CamelCase, то вы решили научиться преобразовывать имена из underscore в этот формат. # Для начала напишите программу, которая переводит имена переменных из стиля написания underscore в стиль UpperCamelCase. ...
m = int(input()) for c in range(1, m + 1): print(c, c ** 2, c ** 3) print(c, c ** 2 + 1, c ** 3 + 1)
import sys, string, math u = input() L = list(u) for i in range(0,len(L),2) : L[i],L[i+1] = L[i+1],L[i] re = ''.join(L) print(re)
import hashlib f = open("rainbowtable.txt",'w') for i in range(10000000, 100000000): session = "%dsalt_for_you" % i h = session for j in range(0,500): h = hashlib.sha1(h.encode('utf-8')).hexdigest() data = session + " - " + h + "\n" f.write(data) f.close()
from ..model import Conference, Room, Speaker, Event, SimpleTZ import re import logging from datetime import date, datetime try: from lxml import etree except ImportError: import xml.etree.ElementTree as etree RE_DATE = re.compile(r'(\d{4})-(\d\d)-(\d\d)') RE_MINUTE = re.compile(r'^(\d+):(\d+)(?: ([AP]M))?$')...
# Generated by Django 3.1 on 2020-08-10 10:04 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('record_label', '0004_auto_20200810_0947'), ] operations = [ migrations.AlterField( model_name='release', name='descrip...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Tue Mar 22 16:40:50 2018 @author: thomas """ import os dir_path = os.path.dirname(os.path.realpath(__file__)) + '/' cwd = os.getcwd() St = os.path.basename(cwd) Re = os.path.split(os.path.dirname(cwd))[-1] print('Re = ',Re) start=0 end=19 OpenDatabase("...
import json from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponse @csrf_exempt def index(request): return HttpResponse("Hello API!")
# General transport settings which can be added to any UnknownQuantity import numpy as np from .. DREAMException import DREAMException TRANSPORT_NONE = 1 TRANSPORT_PRESCRIBED = 2 TRANSPORT_RECHESTER_ROSENBLUTH = 3 TRANSPORT_SVENSSON = 4 INTERP3D_NEAREST = 0 INTERP3D_LINEAR = 1 INTERP1D_NEAREST = 0 INTERP1D_LINEA...
# Definitions of enums and slices used throughout the code from enum import Enum class Met(Enum): """Enum of the metrics/coordinate systems supported by HARM""" MINKOWSKI = 0 MKS = 1 #MMKS = 2 # TODO put back support? FMKS = 3 # Exotic metrics from KORAL et al EKS = 4 MKS3 = 5 # F...
#coding: utf-8 import numpy as np import jieba from gensim import corpora, models, similarities from sklearn.feature_extraction.text import CountVectorizer,TfidfVectorizer, TfidfTransformer from sklearn import metrics from sklearn.naive_bayes import MultinomialNB # #获取文本矢量 # def get_text_vector(docts): # #分词 # ...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui_error.ui' # # Created by: PyQt5 UI code generator 5.15.2 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. from PyQt5 import QtCore, QtG...
# Help Commands class help_command(object): def __init__(self): s = self end = '\r\n' s.help_msg = " FrankerZ What would you like help with? !socialCmds, !miscCmds, !infoCmds FrankerZ " + end class help_command_social(object): def __init__(self): s = self end = '\r\n' s.help_social = "Commands are: !In...
import matplotlib.pyplot as plt import numpy as np plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False labels = 'Frogs','Hogs','Dogs','Logs' sizes = [15,20,45,20] colors = ['red','blue','yellow','pink'] explode = (0,0.1,0,0) plt.pie(sizes, explode=explode, colors=colors, labels=lab...
print('==== EXERCICIO 022 =====') print('- Crie um programa que leia o nome completo de uma pessoa e mostre: -') print('-> O nome com todas as letras maiúsculas') print('-> O nome com todas minúsculas') print('-> Quantas letras ao todo (Sem considerar espaços)') print('-> Quantas letras tem o primeiro nome') nome = in...
#!/usr/bin/python from datetime import datetime limit = int(input("Enter the limit for the primes you want to find: ")) start = datetime.now() arr = [True] * (limit + 61) if limit < 5: exit() if limit >= 2: print(2) if limit >= 3: print(3) if limit >= 5: print(5) list1 = [1, 13, 17, 29, 37, 41, 49, 5...
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations import json from dataclasses import dataclass from pathlib import PurePath from pants.backend.docker.target_types import DockerImageSourceField from pa...
from collections import namedtuple TOKEN = '576701434:AAFxQLWEp4HqxaTvNXFLoS4NHMl6jHrZlmA' DB = 'd1l38h8lqhilvc' SERVER = 'ec2-54-221-212-15.compute-1.amazonaws.com' USER = 'gziqyxvqktbptx' field = namedtuple('reg', ('name', 'translate', 'func', 'ars')) field.__new__.__defaults__ = (None,) * 4 user = { 'url_foto':...
import scrapy class CitySpider(scrapy.Spider): name = "city" def start_requests(self): urls = [ 'https://www.lianjia.com/' ] for url in urls: yield scrapy.Request(url=url, callback=self.parse) def parse(self, response): for ul in response.css('ul.c...
import contextlib from datetime import datetime from election_snooper.models import SnoopedElection from .base import BaseSnooper class ALDCScraper(BaseSnooper): snooper_name = "ALDC" base_url = "https://www.aldc.org/" def get_all(self): url = "{}category/forthcoming-by-elections/".format(self....
import xmltodict import cPickle as pickle import sys,os import re class ForumPost(object): def __init__(self,xml_file_name): with open(xml_file_name,'r') as data: parsed_data = xmltodict.parse(data.read()) self.post_type = parsed_data.keys()[0] self.message_type = parsed_data[self.post_type][u'message']...
import numpy as np def _raw_moment(data, i_order, j_order): nrows, ncols = data.shape y_indices, x_indicies = np.mgrid[:nrows, :ncols] return (data * x_indicies**i_order * y_indices**j_order).sum() def _moments_cov(data): data_sum = data.sum() m10 = _raw_moment(data, 1, 0) m01 = _raw_moment(...
# Generated by Django 2.2.4 on 2019-08-24 11:51 from django.db import migrations, models import phonenumber_field.modelfields class Migration(migrations.Migration): dependencies = [ ('visitors', '0001_initial'), ] operations = [ migrations.AlterField( model_name='track_entry...
""" * Copyright 2020, Departamento de sistemas y Computación * Universidad de Los Andes * * * Desarrolado para el curso ISIS1225 - Estructuras de Datos y Algoritmos * * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by ...
from settings import * from Helper import Utils import pickle from PIL import Image class Test(object): def __init__(self): pass def date(self): now = Utils().get_current_date() print(now) def visualize_images(self): image_information = global_path_to_other_results + '...
# Generated by Django 3.0.4 on 2020-03-13 10:24 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('work', '0102_auto_20200313_1551'), ] operations = [ migrations.AddField( model_name='boq', name='nature', ...
# Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param A : root node of tree # @return the root node in the tree def recursive_invert(self, node): if node: nod...
#!/usr/bin/env python import rospy from std_msgs.msg import Int32 def result(msg): pub1 = rospy.Publisher('result', Int32, queue_size=10) rate1 = rospy.Rate(20) pub1.publish(msg) rate1.sleep() def callback(data): msg = (data.data)/0.15 rospy.loginfo(msg) result(msg) def receive(): ro...
# Edge Detection using Canny edge detector # Edges are set of points(lines), where image brightness changes sharply # Import Computer Vision package - cv2 import cv2 # Import Numerical Python package - numpy as np import numpy as np # Read the image using imread built-in function image = cv2.imread('image_...
from django.urls import path, include from sample1.views import HomePageView urlpatterns = [ path('', HomePageView.as_view(), name='home') ]
# This file tests lib.py. import unittest from lib import * class TestGoogleAPI(unittest.TestCase): def setUp(self): pass def test_time_in_hours_between_locations(self): # TODO(youness) start = "Carlsbad, California" stop = "San Francisco, California" hours = time_in...
# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-08-10 05:40 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.Creat...
#!/usr/bin/env python ################################################################### # This script works for any applications. # It creates a new file (line 21) containing only the last # concentration group and everything else needed to restart Xolotl. # This is useful when restarting the simulation often and w...
from common.run_method import RunMethod import allure @allure.step("极运营/营销中心/业绩归属/修改介绍人") def web_performance_change_employee_id_post(params=None, body=None, header=None, return_json=True, **kwargs): ''' :param: url地址后面的参数 :body: 请求体 :return_json: 是否返回json格式的响应(默认是) :header: 请求的header :host: ...
#!/usr/bin/env python # Copyright (c) 2019-present, HuggingFace Inc. # All rights reserved. This source code is licensed under the BSD-style license # found in the LICENSE file in the root directory of this source tree. import json import os import logging import shutil from tqdm import tqdm import torch import torch....
from django.contrib.auth import authenticate, login from django.contrib.auth.models import Permission from django.db import transaction from django.forms import PasswordInput from django.shortcuts import redirect from rest_framework import serializers from rest_framework.authtoken.models import Token from rest_framew...
from django.apps import AppConfig class WeeklyPlannerConfig(AppConfig): name = 'weekly_planner'
"""Testing Unicode basics.""" # -*- coding: UTF-8 -*- from dnstwister import dnstwist, tools def test_encode_ascii_domain(): assert tools.encode_domain('www.example.com') == '7777772e6578616d706c652e636f6d' def test_encode_unicode_domain(): unicode_domain = u'www.\u0454xampl\u0454.com' # www.xn--xampl-...
from keras.models import model_from_json import librosa import librosa.feature import glob import numpy as np def load_model(): json_file = open('model.json', 'r') loaded_model_json = json_file.read() json_file.close() loaded_model = model_from_json(loaded_model_json) loaded_model.load_weights("m...
from adminapp.models import Exhibit, Exhibit_Notification, Question, User, User_Profile, Subscription, Faq from django.contrib import admin # Register your models here. admin.site.register(Exhibit) admin.site.register(Question) admin.site.register(User_Profile) admin.site.register(User) admin.site.register(Exhibit_Not...
import imaplib import base64 import re import time from pynput.keyboard import Controller, KeyCode keyboardControl = Controller() def server(): email_user = "notifymelocalhost@gmail.com" email_pass = "elhuevo591" print("----------------------------------------------------------------------------...
# Enter your code here. Read input from STDIN. Print output to STDOUT var = list(map(int, input().split())) #print(var) n = var[0] q = var[1] nodes = [] sets = [] for i in range(n-1): nodes.append(list(map(int, input().split()))) #print(nodes) for i in range(q): a = int(input()) b = list(map(int, input(...
# -*- coding: utf-8 -*- # Generated by Django 1.11.29 on 2021-02-09 11:57 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrati...
import torch.utils.data as data import os import os.path import numpy as np def npy_loader(dir,file_name): path = os.path.join(dir,file_name) output = np.load(path) return output class ListDataset(data.Dataset): def __init__(self, input_root, path_list, co_transforms = None, input_transforms = None,...
import pandas as pd import networkx as nx import matplotlib.pyplot as plt def read_tweets(): """ 读取twitter生成user列表 :return: user列表 """ user_tweet_list = [] with open('Tweets/R_DeodorantCancer.txt') as f2: for line, column in enumerate(f2): column = column.replace('\n', '') ...
version = '0.0.0' def main(): from datetime import datetime from dateutil.relativedelta import relativedelta return datetime.now() + relativedelta(day=32, months=-1)
from abc import ABC # import all autoencoder versions from models.unsupervised import linear_vae as lv_py from models.unsupervised import vae_conv-train_load as cv_k class Encoder(ABC): def __init__(self, latent_size): """ Parameters: ---------- latent_size : int ...
#-*-coding:utf-8-*- class Solution(object): def __init__(self): self.word = None self.board = None self.tag = None def clean_tag(self): self.tag = [[False]*len(self.board[0]) for row in range(len(self.board))] def deep_search(self,board, word, x, y): direction = [[0,1...
#!/usr/bin/env /data/mta/Script/Python3.8/envs/ska3-shiny/bin/python import os import sys import re import string import math import sqlite3 # #--- reading directory list # path = '/data/mta/Script/MSID_limit/Scripts/house_keeping/dir_list' with open(path, 'r') as f: data = [line.strip() for line in f.readlines(...
import nltk import os from nltk.corpus import stopwords def f1(): stoplist = stopwords.words('english') print(stoplist) text = '' for root,dirs,files in os.walk('./script/'): for file in files: with open('./script/{0}'.format(file),'r') as fr: for line in fr: ...
import sqlite3 import re from Travel.models.User import User from werkzeug.security import generate_password_hash class Repository(object): def __init__(self, connectionString): self.__conn = sqlite3.connect(connectionString, check_same_thread=False) # self.__conn = sqlite3.connect(r'C:\Users\jun...
''' Iterable is a sequence of data, one can iterate over using a loop. An iterator is an object adhering to the iterator portocol. Basically this means that it has a "next" method, which, when called returns the next item in the sequence, and when there's nothing to return, raise the StopIteration exception. ''' ''' Wh...
from itertools import chain,combinations def powerset(iterable): s = list(iterable) return chain.from_iterable(combinations(s,r) for r in range(len(s)+1)) def transicion(estado,sigma): global delta print(estado,sigma) estado_siguiente = delta[(estado,sigma)] print("transicion(",estado,",",sigm...
from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from .models import Audit # Forms # Inlines # djstackedinline, djtabinline # Models @admin.register(Audit) class AuditAdmin(admin.ModelAdmin): pass
from tfcgp.problem import Problem from tfcgp.chromosome import Chromosome import numpy as np import os class LearnEvolver: def __init__(self, problem, config, logname='test', root_dir='.'): self.config = config self.problem = problem self.epochs = 1*self.problem.epochs self.max_lea...
""" Programmer: Chris Tralie / IDS 301 Class Purpose: To load in Trump's tweets since 11/1/2016, and to do some data wrangling on them """ import pickle import numpy as np import matplotlib.pyplot as plt import seaborn as sns import pandas as pd # A dictionary for converting from the 3 letter months # that T...
import requests import base64 import json import cv2 import numpy as np classes = ["cat","dog"] #image = r"12498.jpg" # dog #image = r"89.jpg" # cat image = r"12500.jpg" # cat URL = "http://127.0.0.1:8501/v1/models/model/versions/1:predict" headers = {"content-type": "application/json"} headers = {"content-type": "ap...