text
stringlengths
38
1.54M
##################################### ##| |## ##| |## ##| Rocky Vargas |## ##| |## ##| |## ##################################### from random import randint #Car Ge...
########### #FILE: hmk_new_3.py #AUTHOR(S): Kelsey Herndon & Rebekke Muench #EMAIL: keh0023@uah.edu #ORGANIZATION: UAH #CREATION DATE: March 22, 2017 #LAST MOD DATE: March 29, 2017 #PURPOSE: Compare the relationship between NDVI and three census variables for 2006 and 2016 #DEPENDENCIES: arcpy, numpy ########### #Imp...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Usage: # # # Example: # '/passport/user/resetPassword' # # Reference: # https://docs.python.org/2/library/httplib.html import httplib import urllib import json default_domain = 'passport.qatest.didichuxing.com' def passport_api_request(path, params, method='POST',...
#!/usr/bin/env python """ Description: Node that performs primary vision operations for pick and place operation including: - Camera stream thresholding - Calculates image moments to locate objects - Publishes necessary information for other nodes Help from: opencv-srf.blogspot.ro/2010/09/object-detection-using-c...
__author__ = 'Mona Jalal' ''' Uses user's left mouse click to annotate the fingertips Guide from the original CVAR dataset is shown to user and user should left click on a point close to the fingertip that is visible to her. ''' import cv2 import itertools import math import os import sys try: CVAR_dataset_path...
from flask import Flask, redirect, request, url_for, send_from_directory, Blueprint saga_routes = Blueprint("saga_routes", __name__) @saga_routes.route("/<path>") def send_saga_page(path): return send_from_directory("saga/0.1.0/docs/html", path) @saga_routes.route("/_static/<path>") def send_static_stuff(path...
import random def Guessing_Game_One(): try: userInput = int(input('Guess the number between 1 and 9: ')) random_number = random.randint(1, 9) if userInput == random_number: print('Congratulations! You guessed correct!') elif userInput < random_number: print(f'You guessed to low! The correct answer is...
from collections import defaultdict from random import uniform from math import sqrt def read_points(): dataset=[] with open('鸢尾花.txt','r') as file: for line in file: if line =='\n': continue dataset.append(list(map(float,line.split(' ')))) file.close() return dataset def write_re...
import numpy as np import cv2 as cv import matplotlib.pyplot as plt import math as m import time import serial def phsv(img): HSV = cv.cvtColor(img, cv.COLOR_BGR2HSV) return HSV def col_r(image): red = (0, 0, 255) blue = (255,0,0) #gray = cv.cvtColor(blurred, cv.COLOR_RGB2GRAY) Lower1 ...
import requests import json def get_forecast_by_lat_long(latitude, longitude, no_of_days=7): output = '' parameters = { 'key': '6a95b306f1334a3a87c190139212005', 'q': str(latitude) + ',' + str(longitude), 'aqi': 'no', 'alerts': 'no', 'days': no_of_days } url1 = ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2019-05-13 20:51:13 # @Author : Mage # @Link : http://fengmm521.taobao.com # @Version : $Id$ import os,sys from magetool import urltool import json import time bilibiliID = 166287840 fansUrl = 'https://api.bilibili.com/x/relation/stat?vmid=%d&jsonp=json...
import lasagne import theano.tensor as tt import numpy as np import theano def sfunc(bias, sat_func, *args, **kwargs): return sat_func(*args, **kwargs) + bias def gSin(m, v, i=None, e=None): D = m.shape[0] if i is None: i = tt.arange(D) if e is None: e = tt.ones((D,)) elif e.__clas...
from django.contrib.auth.models import User from rest_framework import serializers from posts.models import Channel class ChannelUserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username') class BaseChannelSerializer(serializers.ModelSerializer): class...
import argparse import logging from operatorcert import iib, utils from typing import Any, List import time import os from datetime import datetime, timedelta LOGGER = logging.getLogger("operator-cert") def setup_argparser() -> argparse.ArgumentParser: """ Setup argument parser Returns: Any: I...
import numpy as np from numpy import exp, log from scipy.special import digamma, gamma, loggamma, polygamma, logsumexp from math import pi from collections import Counter, OrderedDict import pickle import time from _online_lda_fast import _dirichlet_expectation_2d, _dirichlet_expectation_1d_ from sklearn.feature_extrac...
# coding:utf8 import os import random from configparser import ConfigParser class RandomProxyMiddleware(object): def __init__(self): self.proxy = self.proxy_generator() def proxy_generator(self): # read config file parser = ConfigParser() parser.read(os.path.dirname(os.path.r...
from django.db import models from django.conf import settings from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin class Personel(models.Model): """Şirkette çalışan personel listesi""" personel_adi = models.CharField(max_length=50) def __str__(sel...
#!/usr/bin/env python PACKAGE = "ocular" from dynamic_reconfigure.parameter_generator_catkin import * gen = ParameterGenerator() gen.add("scan_frame", int_t, 0, "Update every 'scan_frame'", 2, 1, 10) exit(gen.generate(PACKAGE, "ocular", "ocularconf"))
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-02-16 08:24 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('course', '0004_auto_20170216_0811'), ] operations = [ migrations.DeleteMode...
#!/usr/bin/env python3 # Converts a list of hosts to my usual config snippet # Usage: host_to_config [host1 fqdn] ([host2 fqdn] (…)) import socket import sys template = """ ++ {t_short} title = {t_fqdn} IPv4 menu = {t_short} IPv4 probe = FPing host = {t_fqdn}""" template_v6 = """ ++ {t_short}_v6 title = {t_fqdn} IPv6 ...
#Google Colabでやっているので少し違うかもしれない !git clone https://github.com/neubig/nlptutorial.git #gitからCloneする def word_count(inputs): dicts = {} for line in inputs: line = line.strip() words = line.split(" ") for word in words: if word in dicts.keys(): dicts[word] += 1 else: dicts[word...
''' 1. 模拟'斗地主'发牌 牌共54张 花色: 黑桃('\u2660'), 梅花('\u2663'), 方块('\u2665'), 红桃('\u2666') 大小王 数字: A0~10JQK 1) 生成54张片 2) 三个人玩牌,每人发17张,底牌留三张 输入回车, 打印第1个人的17张牌 输入回车, 打印第2个人的17张牌 输入回车, 打印第3个人的17张牌 输入回车, 打印3张底牌 ''' import random color = ['\u2660','\u2663','\u2665...
from .AbsRetrievalTask import AbsRetrievalTask class QuoraRetrieval(AbsRetrievalTask): download_url = 'https://public.ukp.informatik.tu-darmstadt.de/reimers/seb/datasets/quora_retrieval.json.gz' local_file_name = 'quora_retrieval.json.gz' @property def description(self): return { ...
import urllib2 import concurrent.futures import logging import ConfigParser import wx logging.basicConfig() #URL = 'http://svr-dev-20:8080/?cmd=isGlowing' LAMP_ON = '1' LAMP_OFF = '0' LAMP_UNDEFINED = '?' UNDEFINED_STATE = [LAMP_UNDEFINED, 'Getting invalid response(s) from server'] OK_ICON = 'data\\ok.png' FAIL_ICON...
from pyspark import SparkContext from pyspark.sql import SparkSession, Row import json import requests sc = SparkContext(appName="ddapp_test") spark = SparkSession \ .builder \ .appName("DDapp_model_updt") \ .getOrCreate() SEASON_1718 = 'https://pkgstore.datahub.io/sports-data/' \ 'english-...
import random import test2 def tilemap_builder(): tilemap = [[[random.randint(0,600),random.randint(0,100),0,0,0,0,0] for i in range(0,3,1)] for j in range(0,3,1)] test2.tilemap = tilemap return tilemap
#!/usr/bin/python3 # -*- coding: utf8 -*- import sys import cx_Oracle class Db: def __init__(self): # Vebosity level to show all self._VERBOSITY = 4 self.CONTINUE_ON_ERROR = False self.connected = False self.verbosity = 0 self.className = self.__class__.__name...
#/usr/bin/python import psycopg2 import os import datetime import json import time from flask import Blueprint, request import calendar ghcn_data_blueprint = Blueprint('ghcn_data', __name__) def build_series(name, data): return {'name' : name, 'data' : data, 'zIndex' : 1, 'marker' : '{ fillColor: "whi...
class matrix(object): def __init__(self, num_rows, num_columns): ''' num_rows: type = int num_columns: type = int num_rows is the number of rows in the matrix num_columsn is the number of columns in the matrix matrix_obj is initialised to all zeros ''' ...
def deleni (cislo_1: int, cislo_2: int): if cislo_2 == 0: return 0 return (cislo_1/cislo_2) print (deleni(12,4))
# Django - Jet Configure X_FRAME_OPTIONS = 'SAMEORIGIN' JET_INDEX_DASHBOARD = 'pytube.dashboard.CustomIndexDashboard' # Django - Jet theme colors for admin backend. JET_DEFAULT_THEME = 'default' JET_THEMES = [ { 'theme': 'default', # theme folder name 'color': '#47bac1', # color of the theme's...
from flask import Flask from flask_cors import CORS import random app = Flask(__name__) CORS(app) @app.route('/jerry') def yourMethod(): return 'Hello World.' #response = Flask.jsonify({'some': 'data'}) #response.headers.add('Access-Control-Allow-Origin', '*') # return response if __name__ == "__ma...
from django.contrib import admin from django.contrib.auth.models import Group, User from django import forms from .models import Department, Designation, Farmer,\ Supplier, SupplierFarmer, ShrimpType, ShrimpItem, \ UserManager, RowStatus, Author, Book, LogShrimpItem from .inventorymodel import ShrimpProdItem,...
from datetime import datetime from odoo import api, fields, models, _ from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT class PosConfig(models.Model): _inherit = 'pos.config' invoicing_mnd = fields.Boolean(string="Invoicing Mandatory")
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('zhavbmq', '0007_auto_20150218_1622'), ] operations = [ migrations.RemoveField( model_name='dvkdj', n...
import logging from django.http import (HttpResponse, HttpResponseRedirect, HttpResponseNotAllowed, HttpResponseNotFound, HttpResponseForbidden) from django.shortcuts import render, get_object_or_404 from django.template import RequestContext from django.contrib.auth.de...
# imports import numpy as np import cv2 import matplotlib.pyplot as plt # load images, remember openCV loads color images as BGR waterfall_original = cv2.imread('input/waterfall.png') mountains_original = cv2.imread('input/mountains.png') ####### Problem - swapping blue and red color planes waterfall_blues ...
import state import io import streamreader # using backtracking search to build an NFA class NFAStateMachine: def __init__(self, states, startStateId, classes): self.states = states self.startStateId = startStateId self.classes = classes for stateId in self.states: ...
# see https://www.codewars.com/kata/534d2f5b5371ecf8d2000a08/solutions/python from TestFunction import Test def multiplication_table(size): rv = [] k = 0 for i in range(size): s = 0 k += 1 temp = [] for j in range(size): s += k temp.append(s) rv.append(temp) return rv test = T...
import pandas as pd import numpy as np #딕셔너리 데이터로 판다스 시리즈 만들기 student1 = pd.Series({'국어':np.nan,'영어':80,'수학':90}) student2 = pd.Series({'수학':80,'국어':90}) print(student1,student2, sep='\n\n') print() print("# 두 학생의 과목별 점수로 사칙연산 수행") sr_add = student1.add(student2,fill_value=0) # 덧셈 sr_sub = student1.sub(student2,f...
''' Given an undirected graph G having positive weights and N vertices. You start with having a sum of M money. For passing through a vertex i, you must pay S[i] money. If you don't have enough money - you can't pass through that vertex. Find the shortest path from vertex 1 to vertex N, respecting the above cond...
import os import csv import pandas as pd ###DEPRECATED BY CSV FORMATTER def masscsvformatter(filename,olm): print("Formatting " + filename) page4.update_idletasks() file = open(os.path.join(os.getcwd(),filename)) outpname = filename.split('.')[0] + ".csv" outpath = os.path.join(os.getcwd(),outpn...
''' import socket s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) server='www.ntvspor.com' port=80 server_ip=socket.gethostbyname(server) request="GET / HTTP/1.1\nHost: "+server+"\n\n" s.connect((server,port)) s.send(request.encode()) sonuc=s.recv(1024) print(sonuc) ''' impor...
import unittest from calculator import calculator from csvreader import csvreader class MyTestCase(unittest.TestCase): def setUp(self) -> None: self.calculator = calculator() def test_instantiate_calculator(self): self.assertIsInstance(self.calculator, calculator) def test_addition(self)...
# !/usr/bin/python3 # -*- coding: utf-8 -*- """ 启动jvm @Author : pgsheng @Time : 2018/7/24 10:44 """ import platform import jpype from public import config from public.log import Log class JVMStart(object): def __init__(self): self.log = Log("jvm初始化").get_logger() """ 启动Java虚拟机 """ ...
"""Unit Tests for the module""" import logging from django.test import TestCase LOGGER = logging.getLogger(name="django-errors") class ErrorsTestCase(TestCase): """Test Case for django-errors""" def setUp(self): """Set up common assets for tests""" LOGGER.debug("Tests setUp") def tearD...
from start_utils import db, login_manager, app from datetime import datetime from flask_login import UserMixin from itsdangerous import TimedJSONWebSignatureSerializer as Serializer @login_manager.user_loader def load_user(user_id): return User.query.get(int(user_id)) class User(db.Model, UserMixin): id = db.Column...
keys=["one","two","three","four","five"] values=[1,2,3,4,5,] l=len(keys) dic={} i=0 while i <l: dic[keys[i]]=values[i] i+=1 print(dic) #make dictionary with two lists
""" Capture Regions on Board Problem Description Given a 2-D board A of size N x M containing 'X' and 'O', capture all regions surrounded by 'X'. A region is captured by flipping all 'O's into 'X's in that surrounded region. Problem Constraints 1 <= N, M <= 1000 Input Format First and only argument is a N x M ...
from django.contrib import admin from .models import Comment # Register your models here. # Register your models here. @admin.register(Comment) class ImageAdmin(admin.ModelAdmin): list_display = ['owner', 'belongproduct', 'content', 'reply'] list_filter = ['created']
#Importar funcion sqtr from math import sqrt #Pedir al altura a usuario h = float(input("Proporciona la altura en metros de la torre: ")) g=9.81 #Constate de la gravedad t=sqrt(2*h/g) #Calculo de tiempo de caida #Impresion de Resultados print'El tiempo de caida para una altura ',h,'m es: ', t ,'s'
def allowed_bar(my_age): persons_age = my_age + 3 return persons_age person_allowed = allowed_bar(18) print(person_allowed) def gender_selector(sex ='uknown'): if sex is 'm': sex = "male" elif sex is 'f': sex = "female" print(sex) gender_selector()
import babel from flask import request from sqlalchemy.ext.hybrid import hybrid_property def chunks(lst, size): """Yield successive size chunks from lst.""" for i in range(0, len(lst), size): yield lst[i:i + size] def get_locale(): return request.cookies.get('language', 'ru') def cast_locale(o...
# Версия 1 # Подключаем библиотеки import pygame from pygame.locals import * from control import Control from plane import Plane from fuel import Fuel from bullet import Bullet from gui import GUI from heart import Heart # Задаем разрешение экрана win = pygame.display.set_mode((1440, 900), FULLSCREEN) # win = pygame....
total = 0 number = str(2**1000) i = 0 while i < len(number): num = int(number[i]) total = total + num i = i+1 print(total)
class Solution: def maxProfit(self, prices): if len(prices) < 1: return 0 dp = [] dp.append(0) min_value = prices[0] for i in range(1, len(prices)): dp.append(max(dp[i - 1], prices[i] - min_value)) if prices[i] < min_value: ...
tests = int(input()) for t in xrange(1,tests+1): n = int(input()) if n == 0: print "Case #{}: INSOMNIA".format(t) continue i = 1 s = set() answer = n while len(s) < 10: answer = n*i s = s.union(set(list(str(answer)))) i+=1 print "Case #{}: {}".format...
# Functions to compare two files based different attributes from nltk.tokenize import sent_tokenize def lines(a, b): """Return lines in both a and b""" # Split a and b to get individual lines. Store in sets to avoid duplicates a = set(a.split("\n")) b = set(b.split("\n")) # Create a list of lin...
# install package elm # pip install elm import elm import numpy as np def main(): trainFeature = np.genfromtxt('trainFeature.csv', delimiter=',')[0::5] trainLabel = np.genfromtxt('trainLabel.csv', delimiter='\n')[0::5] testFeature = np.genfromtxt('testFeature.csv', delimiter=',') #trainFeature = np.genfromt...
class RM3DWriter: header = 'START-OF-FILE\nDATEFORMAT=YYYYMMDD\nFIELDSEPARATOR=TAB\nSUBFIELDSEPARATOR=PIPE\nDECIMALSEPARATOR=PERIOD\nSTART-OF-DATA' footer = 'END-OF-DATA\nEND-OF-FILE\n' def __init__(self): pass def produce_string(self, rm3d_list): out = '\n'.join(['\t'.join(e) for e i...
from StringBuilder import StringBuilder class PythonBuilder(StringBuilder): def __init__(self): self.stringList=[] self.indentModel="\t" self.commentModel="#" self.level =0 self.builderList=[] @property def Level(self): return self.level ...
"""Channels module for Zigbee Home Automation.""" from __future__ import annotations import asyncio from typing import TYPE_CHECKING, Any from typing_extensions import Self import zigpy.endpoint import zigpy.zcl.clusters.closures from homeassistant.const import ATTR_DEVICE_ID from homeassistant.core import HomeAssis...
import hash_functions import pandas as pd def load_names(): #Last names last_names = pd.read_fwf('Names/dist.all.last', header=None, widths=[14,7,7,7]) first_male = pd.read_fwf('Names/dist.male.first', header=None, widths=[14,7,7,7]) first_female = pd.read_fwf('Names/dist.female.first', header=None, w...
ArcanasData = { 'Chariot': [['Fool', 'Lovers'], ['Magician', 'Temperance'], ['Priestess', 'Sun'], ['Empress', 'Strength'], ['Emperor', 'Justice'], ['Hierophant', 'Death'], ['Lovers', 'Hermit'], ['Lovers', 'Star'], [...
""" Given an integer rowIndex, return the rowIndexth row of the Pascal's triangle. Notice that the row index starts from 0. In Pascal's triangle, each number is the sum of the two numbers directly above it. Follow up: Could you optimize your algorithm to use only O(k) extra space? Example 1: Input: rowIndex ...
#!/usr/bin/env ccp4-python import sys sys.path.insert(0, "/opt/ample-dev1/python" ) sys.path.insert(0, "/opt/ample-dev1/scripts" ) import cPickle import csv sys.path.append("/usr/lib/python2.7/dist-packages") from dateutil import parser import glob import os import ample_util from analyse_run import AmpleResult #im...
from django.contrib.auth.models import User from rest_framework import serializers from fbbackend.models import UserProfile, Messages, Comments class MsgSerializer(serializers.Serializer): message = serializers.CharField(max_length=4000) class FriendSerializer(serializers.ModelSerializer): class Meta: ...
from flask import Flask, jsonify, request import cv2 import numpy as np app= Flask(__name__) @app.route("/",methods=['POST']) def index(): if request.files: # try: # filestr = request.files['file'].read() # npimg = np.frombuffer(filestr, np.uint8) # img = cv2.imdecode(npimg, cv2.IMREAD_COLOR) # _,_ = i...
def mdc(a, b): if b == 0: return a return mdc(b, a % b) def mmc(a, b): return abs(a*b) / mdc(a,b)
class SprintInfo: def __init__(self, start_date, end_date): self._start_date = start_date self._end_date = end_date @property def start_date(self): return self._start_date @property def end_date(self): return self._end_date
from core.youtube_video_processor import YouTubeVideoProcessor from core.youtube_playlist_videourl_extractor import YouTubePlaylistVideoUrlExtractor from core.file_blob_writer import FileBlobWriter import moviepy.editor as mp class YouTubePlaylistCrawler(): def __init__(self): pass def crawl_playlist(...
# encoding = utf-8 import threading import time #Python2 # from Queue mimport Queue # Python import queue lock_1 = threading.Lock() lock_2 = threading.Lock() def func_1(): print("func1") lock_1.acquire() print("申请1") time.sleep(2) lock_2.acquire() print("申请2") lock_2.release() print...
import cocotb from lib.util import assertions from lib.cycle import clock, wait, reset @cocotb.test() def program_counter(dut): def assert_o_count(value, error_msg): """Check the value of the output count""" assertions.assertEqual(dut.o_count.value.binstr, value, error_msg) # Test ini...
# -*- coding: utf-8 -*- """ Created on Thu Jul 21 16:25:30 2022 @author: astertaylor """ import SAMUS #create class standard_class=SAMUS.model("standard_tolerance",a=20,b=50,c=110,mu=10**7) #runs simulation with only 1 time step per rotation standard_class.run_model(5,rtol=0.05,data_name='hyperbolic_traj...
# Copyright (c) 2013 Rackspace, 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 agreed to in wr...
''' Created on 2019年6月5日 @author: juicemilk ''' """ function declaration: height_train:the network topology of training net "眼高网络的结构" """ import tensorflow as tf import os import numpy as np import matplotlib.pyplot as plt from Eye_net_project.Eye_net.lib.Data_Shuffle import data_shuffle from Eye_ne...
cities = { 'Chisinau': 'CH', 'Orhei': 'OR', 'Soroca': 'SO' } raion = { 'CH': 'Buiucani', 'CH': 'Botanica', 'CH': 'Riscani', 'OR': 'Butuceni' } raion['SO'] = 'Bulboci' print '=' * 27 print "Chisinau has:", raion[cities['Chisinau']] print "Orhei has:", raion[cities['Orhei']] print "Soroca h...
from django.db import models class Poll(models.Model): question = models.CharField(max_length=2500, null=False, blank=False, verbose_name='Вопрос') created_at = models.DateTimeField(auto_now_add=True, verbose_name='Время создания') def __str__(self): return f'{self.question} - {self.created_at}' ...
import time from argparse import ArgumentParser import cv2 from search_images import ImageSearcher from optimize_utils import OrderSolver from app_config import Config def build_argparser(): parser = ArgumentParser() parser.add_argument("-i", "--input", help="Required. Path to a image.", ...
#!/usr/bin/python # -*- coding: utf-8 -*- from _core import worker_base class API_Worker( worker_base.API_Worker_Base ): def do_GET( self ): self.reply( 'Hello World', 'text/html', 200 )
from math import sqrt, ceil def pz(s, n): l = len(s) return '0' * (n-l) + s def gen_coin(n): if n <= 2: yield '11' return for i in range(int('1'*(n-2), 2)+1): yield '1' + pz(bin(i)[2:], n-2) + '1' # def indx(i): # j = 0 # while i > soe[j]: # j+=1 # if i == soe[j]: # return j # retu...
from django.contrib.auth import authenticate, login from django.core.urlresolvers import reverse from django.contrib.auth.views import login as login_view from sqlshare_rest.models import CredentialsModel from django.contrib.auth.models import User from django.shortcuts import redirect, render_to_response from django.c...
from twx.botapi import TelegramBot, ReplyKeyboardMarkup from telegram.ext import Updater, CommandHandler import requests from bs4 import BeautifulSoup url = "https://www.google.com/finance?q=HKD" r = requests.get(url) soup = BeautifulSoup(r.content) g_data = soup.find_all('span', {'class': 'bld'}) c = g_data[...
from pymongo import MongoClient username = 'universai' password = 'cumzone' cluster = '127.0.0.1:1488' client = MongoClient(f"mongodb://{username}:{password}@{cluster}") db1 = client.dtp.dtp db2 = client.dtpsFull def address(data): add = "" s = str(data['data']['infoDtp']['street']) h = str(data['data']['...
"""Entry point.""" import argparse import time import torch import graphnas.trainer as trainer import graphnas.utils.tensor_utils as utils import warnings warnings.filterwarnings('ignore') import os def build_args(): parser = argparse.ArgumentParser(description='GraphNAS') register_default_args(parser) ...
#!/usr/bin/env ipython3 # -*- encoding: utf-8 -*- import sys import os import fileinput import hashlib import random import re from ipython_genutils.py3compat import cast_bytes, str_to_bytes # Get the password from the environment password_environment_variable = sys.argv[1] # Hash the password, this is taken from htt...
import art import game_data import random from replit import clear def data_format(data): data_name = data["name"] data_description = data["description"] data_country = data["country"] return(f"Name is {data_name}, {data_description} and from {data_country}") def check_answer(guess,data1_count,data2_count): ...
# -*- coding: utf-8 -*- import networkx as nx class NetX: G = None nodes = dict() edges = None def __init__(self): self.G = nx.Graph() def addNeoNodes(self): self.G.add_nodes_from(self.nodes)
#!/usr/bin/env python import sys import subprocess import re from signal import signal, SIGPIPE, SIG_DFL signal(SIGPIPE, SIG_DFL) calendars = {} category_default = 'DEFAULT' re_ics = re.compile('SUMMARY|DTSTAMP|CATEGORIES') re_fields = re.compile('^([^;:]+)[^:]*:(.*)') re_date = re.compile('^(\d{4})(\d{2})(\d{2})T(...
import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation import sys, time, math import serial import serial.tools.list_ports import pandas PORT = 'COM3' try: ser.close(); except: print(); try: ser = serial.Serial(PORT, 115200, timeout=100) except: print ('Serial port %s is not av...
import folium import csv def color_producer(elevation): """Returns color name depending on the height of the volcanoe""" if elevation < 1000: return "green" elif 1000 <= elevation < 3000: return "orange" else: return "red" my_map = folium.Map(location=[38.9700012,-112.5009995]...
#At this file we are declaring all the menus related # to the Books # Clean Arquitecture Principles def booksMenu(): print("****************************************") print("* B O O K S M E N U *") print("****************************************") print("* a. Add New Book ...
from yacs.config import CfgNode from kale.predict.decode import GripNetLinkPrediction from kale.prepdata.supergraph_construct import SuperGraph, SuperVertexParaSetting def get_supervertex(sv_configs: CfgNode) -> SuperVertexParaSetting: """Get supervertex parameter setting from configurations.""" exter_list ...
import pandas as pd import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns def explore_dataset(df): print("\nExploring the Dataset..\n") # Dataframe shape print(df.shape[1], " columns.") print(df.shape[0], " observations.\n") # Dataframe datatypes datatype...
# Empty Tuple. sampleTuple1 = () print(sampleTuple1) # Empty tuple using builtin function. sampleTuple2 = tuple() print(sampleTuple2)
def check(year,dates): monthList=["JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"] dates-=500 if dates<=31: month=0 day=dates elif dates<=60: month=1 day=dates-31 elif dates<=91: month=2 day=dates-60 elif dates<=121: ...
##Como no existe el do while se raliza con el while y no se presenta nada ya que no entra contador = 100 while(contador <= 10): print("%d\n"% (contador)) contador = contador + 2
# Generated by Django 3.2.18 on 2023-05-19 19:03 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('survey', '0002_auto_20230421_1715'), ] operations = [ migrations.AddField( model_name='surveyshomepage', name='part...
from django.conf.urls import patterns, include, url urlpatterns = patterns('home.views', url(r'^$', 'index', name='home'), url(r'^(lt;short_id&gt;\w{6})$', 'redirect_original', name='redirectoriginal'), # Erro of regex here url(r'^makeshort/$', 'shorten_url', name='shortenurl'), )
import unittest import os import sys import pathlib from archivemanager import ArchiveManager from backupmanager import BackupManager from config import ConfigManager # aPATH = pathlib.Path("archives/").resolve() filetotest = pathlib.Path(sys.executable) class TestArchiveManager(unittest.TestCase): def setUp(s...