text
stringlengths
38
1.54M
import torch import numpy as np from torch.autograd.functional import jacobian from multipledispatch import dispatch from collections.abc import Callable from scipy.stats import gaussian_kde def torchProxRecur(pdf_prev, pot_prev, x_prev, x_curr, dt, reg, tol=1e-5, maxiter=300, beta=1., verbose=True): ''' Proxi...
# Global maze maze maze = [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1], [1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1], [1, 1, 0, 0, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1], ...
import numpy as np import tensorflow as tf from utils.layers import * from utils.initParams import * from utils.monitor2 import * # All DNN w/o softmax # DNN-262144 DNN-262144 DNN-262144 DNN-2 # #################### # Random Minibatch # #################### def random_minibatch(data,label,size): """ Random choose ...
number_list = range(100) def senkei(number_list, num): found = False for i in number_list: if i == num: found = True break return found print(senkei(number_list, 9)) print(senkei(number_list, 1000))
from kiali_qe.tests import IstioConfigPageTest def test_pagination_feature(kiali_client, openshift_client, browser): tests = IstioConfigPageTest( kiali_client=kiali_client, openshift_client=openshift_client, browser=browser) tests.assert_pagination_feature() def test_namespaces(kiali_client, openshi...
import numpy as np import pandas as pd import matplotlib.pyplot as plt def filter_data(data, condition): """ Remove elements that do not match the condition provided. Takes a data list as input and returns a filtered list. Conditions should be a list of strings of the following format: '<field> <...
# Copyright (c) 2011-2012 lab126.com # See COPYING for details. import time import threading from gevent import monkey; monkey.patch_all() MAX_RUNNING = 30 class Scheduler(threading.Thread): def __init__(self, handler): threading.Thread.__init__(self) self.handler = handler self.stop = F...
import os, gc, threading, logging, time import tensorflow as tf import cv2 as cv import numpy as np from random import randint from time import sleep # ambiente from nes_py.wrappers import JoypadSpace import gym_super_mario_bros from gym_super_mario_bros.actions import COMPLEX_MOVEMENT, SIMPLE_MOVEMENT, RIGHT_ONLY fr...
# Generated by Django 2.1.7 on 2019-06-08 18:55 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('app2', '0008_auto_20190604_1534'), ] operations = [ migrations.RenameField( model_name='costs', old_name='equipment'...
from flask import Flask, Response, render_template, jsonify, request from flask import Flask import mysql.connector db=mysql.connector.connect(host="localhost",user="root",password="dpsdpsdps",database="project") cursor=db.cursor() cursor.execute("select count(acc_no) from customer") result=cursor.fetchall() i=re...
from django.conf import settings from django.db import models import datetime import json emoji_choices = ( ('h', 'healthy'), ('s', 'sick'), ('y', 'sleepy'), ('c', 'cough'), ('f', 'fever'), ('u', 'flu'), ('n', 'nauseous'), ('l', 'sore throat'), ('r', 'runnynose'), ('b', 'body ac...
from __future__ import annotations from collections.abc import Iterator from .abc import AbcIterator, AbcIteratorFactory from fibonacci.collection import AbcLinearCollection class LinearIterator(AbcIterator): """Iterates over given indices of the collection """ __slots__ = ["_collection", "_indices"] ...
VULN_RES_JSON = { "results": [ { "affects": { "vuln_techs": [ { "created_on": "2022-01-20T20:56:48.000Z", "key": "cpe:/a:f5:big-ip:16.1.1", "last_modified": "2022-01-20T20:56:48.000Z", ...
import json import itertools import re from django.db import models from django.conf import settings from django.db.models.signals import pre_delete from django.dispatch import receiver from django.core.exceptions import ObjectDoesNotExist from audit_log.models.managers import AuditLog import tutelary.engine as engine ...
import pickle from unittest import mock import numpy as np import pytest import tensorflow as tf from metarl.tf.models import GaussianCNNModel from tests.fixtures import TfGraphTestCase class TestGaussianCNNModel(TfGraphTestCase): def setup_method(self): super().setup_method() self.batch_size = ...
import random print('Welocome to guess a nubmber! \nToday might just be your lucky day, Come on take a guess ;)') print( ) print('='*8,'start','='*8) user_input = int(input('Enter a number between 0 - 20: ')) lucky_number = random.randint(0, 21) def guess_a_num(user_input, lucky_number): for i...
import os from gtts import gTTS import datetime import json import time import requests import argparse import logging from bs4 import BeautifulSoup from tabulate import tabulate URL = 'https://www.mohfw.gov.in/' FILE_NAME = 'corona_india_dashboard.json' changed = False r = requests.get(URL) htmlContent = r.text def ...
#!/usr/bin/python # -*- coding: utf-8 -*- # version: 20110704 # By Dennis Drescher (dennis_drescher at sil.org) ############################################################################### ######################### Description/Documentation ########################### ##############################################...
def NewtonRafson(f,dfdx, initial_guess,e): x = initial_guess for i in range(1, 100): y = float(f(x)) if abs(y) < e: break x = x - (y / dfdx(x)) i += 1 return x def func(x): y = x**2 - 20 * x + 100 return y def derivative(x): y = 2 * ...
from fastapi import APIRouter, HTTPException from f5_token import get_token import f5_related.schemas from fastapi.encoders import jsonable_encoder import requests import json from f5_related.to_excel import to_excel from config import Setting from app_logging import logger router = APIRouter() settings = Setting() ro...
filenames = [ "utils.js", "geometry.js", "axes.js", "plot.js", "point.js", "line.js", "tick.js", "arrow.js", "measure.js", "angle.js", "circle.js", "polygon.js", "text.js", "controlpoint.js", "button.js", ] with open('mavis.js', 'w') as outfile: for fname in filenames: with open(fname) as infile: ...
# coding: utf-8 try: from urllib.parse import urljoin except ImportError: # Python 2.7 from urlparse import urljoin # noqa try: from unittest.mock import patch except ImportError: # Python < 3.3 try: from mock import patch # noqa except ImportError: patch = None try: fr...
import time inicio = time.time() def insertionSort(arr): for i in range(1, len(arr)): key = arr[i] j = i-1 while j >=0 and key < arr[j] : arr[j+1] = arr[j] j -= 1 arr[j+1] = key from random import sample random = sample(range(0, 8500), 8500) ...
# -*- coding: utf-8 -*- """ Created on Tue Apr 16 16:35:32 2019 @brief: use pd to load data to list from txt file use nx and plt to draw figures @author: 冯准生 """ import networkx as nx import matplotlib.pyplot as plt import pandas as pd #pandas,强大的数据处理能力 #处理数据简洁,两行代码搞定 sourse_data=pd.read_csv("usair.txt",...
# БСБО-05-19 Савранский С. import math i = 0 calc_dist = lambda x, y: ((x - 0.75) ** 2 + (y - 0) ** 2) ** .5 while i < 2 * math.pi: x = math.cos(i) ** 3 y = math.sin(i) ** 3 if i == 0: dist = calc_dist(x, y) elif (new_dist := calc_dist(x, y)) < dist: dist = new_dist i += .0001
import random w = input("Enter a number between 0 and 5 ") x = random.randrange(0,5 ) if w == x: print("You won") else: print("You loose") print(x)
# -*- coding: utf-8 -*- # __author__ = 'huang_wang' import numpy as np def segment_dist(points, pv): n = len(pv) - 1 d = np.zeros((len(points), n)) j = 0 for p in points: for i in range(n): a = pv[i] b = pv[i+1] ab = b - a ap = p - a ...
#!/usr/bin/env python # -*- coding: utf-8 -*- from collections import defaultdict def read(f): t = int(f.next()) for i in xrange(t): n, m = map(int, f.next().strip().split()) D = [f.next().strip() for j in xrange(n)] L = [f.next().strip() for j in xrange(m)] yield D, L def ext...
from lib.mixpanel_test import MixpanelTest mp = MixpanelTest() data = mp.request( funnel_id=809349, seg_property='artist-page-interface', from_date='2014-08-28' ) mp.test(data, control='fillwidth', variations=['filter', 'filter_carousel'])
#!/usr/bin/env python import pyfwk from pyfi.calendar.calendar.model import CalendarModel # ----------------------------CATEGORY-OBJECT-----------------------------# class Calendar(pyfwk.Object): id = None year = None month = None day = None weekday = None session = None mktopen = None ...
import pygame import csv import socket import pickle def rotaciona_alt(image, angle): orig_rect = image.get_rect() rot_image = pygame.transform.rotate(image, angle) rot_rect = orig_rect.copy() rot_rect.center = rot_image.get_rect().center rot_image = rot_image.subsurface(rot_rect).copy() retur...
''' Created on Apr 11, 2011 @author: virushunter2 ''' import wx from Bio import SeqIO def main(infile, threshold, length): length = int(length) threshold = int(threshold) filters = 'FASTA files (*.fasta; *.fastq; *.fa; *.fna; *.seq; *.txt)|*.fasta;*.fastq;*.fa;*.fna;*.seq;*.txt' dialog = wx.FileDialog...
import re from bs4 import BeautifulSoup import requests url = 'https://baike.baidu.com/item/Python/407313?fr=aladdin' headers = { 'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) ' 'AppleWebKit/537.36 (KHTML, like Gecko) ' 'Chrome/75.0.3770.100 Safari/537.36' ...
def comp(char): cmpl='' if char=='+': cmpl='-' else: cmpl='+' return cmpl def revcomp(string,end): out="" for i in range(end-1,-1,-1): out+=comp(str(list(string)[i])) out+=string[end:len(string)] return out t=int(raw_input()) for i in range(t): stack=raw_input() happy=0 count=0 while happy<len(stack...
#coding:utf-8 import numpy as np from load_data_from_database import query_kdata import sys sys.path.append('/mnt/aidata/QuantitativePlatform/lib') import time import datetime #as get_model_name from tool import Model from tool import get_model_name import config import os import common_tool import pandas as pd import...
from functools import wraps from typing import Any, Callable, List import torch from torch import nn from kornia.core import Tensor def image_to_tensor(image: Any, keepdim: bool = True) -> Tensor: """Convert a numpy image to a PyTorch 4d tensor image. Args: image: image of the form :math:`(H, W, C)...
import os import argparse import re from collections import Counter import csv import numpy as np from scipy import stats import matplotlib matplotlib.use('QT4Agg') import matplotlib.pyplot as plt from functools import wraps SPLIT = re.compile('\W+') def get_name(directory): return os.path.split(directory[:-1...
import pygame from pygame.sprite import Sprite class Ship_left(Sprite): """Initialize the ship and set its starting position.""" def __init__(self, screen): super().__init__() self.screen = screen self.image = pygame.image.load('images/ship_left.bmp') self.rect = self.image.g...
import csv import pickle import networkx as nx import matplotlib.pyplot as plt g_base='../../../../datafiles/data-ITDK/' dataset="data-Geolocation/" dataset="data-ASN/" if dataset=="data-Geolocation/": years=[2015, 2016] base = "../../../../resultfiles/Results-Geolocation/involved/" ds='2016-09' elif da...
import pexpect import string class CommandExecuter: def Run(self, command_line, remote_ip, user, password, run_background): cmd = self.FormatCommand(command_line, remote_ip, user) print 'Running %s' % cmd expect = self.Spawn(cmd) return self.DoRun(expect, password, run_background) def ...
import heapq import pandas as pd import copy from rltk.record import Record, get_property_names from rltk.evaluation.ground_truth import GroundTruth from scipy.optimize import linear_sum_assignment from typing import Any class Trial(object): """ Trial stores the calculated result for further evaluation. ...
import json import requests import hashlib import base64 import bcrypt from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes, hmac def response(password, salt, challenge): key = bcrypt.hashpw(password.encode('utf-8'), salt.encode('utf-8')) h = hmac.HMAC(key...
from __future__ import print_function from Configuration.PyReleaseValidation.relval_steps import Matrix, InputInfo, Steps import os import json import collections workflows = Matrix() steps = Steps() def get_json_files(): cwd = os.path.join(os.getcwd(), "json_data") if not os.path.exists(cwd): retu...
import urllib.request import urllib.parse import re def handle_request(url,page=None): #拼接出来指定url if page != None: url = url + str(page) + '.html' headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Ed...
#!/usr/bin/python3 #from capstoneg08_client.Client import Client class ServerMessageHandler(): def __init__(self, myClient): self.myClient = myClient def handleServerMessage(self, msg): serverMessage = "" serverMessage = msg.decode() print(serverMessage); return ...
from flask import Flask, render_template, url_for, session, request, redirect, g, flash import fivemin import pandas as pd import sys from bs4 import BeautifulSoup app = Flask(__name__) app.config['DEBUG'] = True app.config['PROPAGATE_EXCEPTIONS'] = True app.secret_key = 'mr. secrets' @app.route('/') def index(): ...
import pathmagic # noqa import os from maskrcnn.lib.config import cfg from maskrcnn.lib.utils.io_utils import read_image from maskrcnn.lib.models.mask_rcnn import MaskRCNN image_path = os.path.join("..", "data", "COCO_val2014_000000018928.jpg") image = read_image(image_path) print("image shape", image.shape) model =...
def custom_fibonacci(n): if n == 1: return 1 elif n == 2: return 2 else: return custom_fibonacci(n-1) + custom_fibonacci(n-2) """custom fibonnaci(5) = (1+1) + custom_custom_fibonacci(4) = 2 + 1 + custom fibonacci(3) = 3 + 2 + custom ...
import pandas as pd import numpy as np import warnings import random from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from sklearn.feature_extraction.text import TfidfVectorizer warnings.filterwarnings('ignore') def read_file(): data = pd.read_csv('data.cs...
import types import itertools import numpy from enum import Enum, unique from functools import reduce from pycsp3.classes.auxiliary.ptypes import auto from pycsp3.classes.main.variables import Variable, NotVariable, NegVariable from pycsp3.classes import main from pycsp3.dashboard import options from pycsp3.tools.uti...
# Generated by Django 3.2.7 on 2021-09-28 10:05 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('student', '0004_alter_city_thumbnail'), ] operations = [ migrations.RemoveField( model_name='city', name='District', ...
''' Dnspython is a DNS toolkit for Python. It can be used for queries, zone transfers, dynamic updates, nameserver testing, and many other things. https://www.dnspython.org/ ''' import dns.reversename import dns.resolver import pandas as pd data = pd.read_csv("./scanned_hosts.csv") print(data) for index, row...
import discord from discord.ext import commands from core.classes import Cog_Extension import json with open('setting.json','r', encoding='utf8') as jfile: jdata = json.load(jfile) class Event(Cog_Extension): def __init__(self,bot): self.bot = bot @commands.Cog.listener() async def on_member...
# Program to count the no. of reference pointing to same object import sys class Animal: pass ref1 = Animal() ref2 = ref1 print("Reference count is", sys.getrefcount(ref1)) ref3 = ref2 ref4 = ref3 print("Reference count is", sys.getrefcount(ref1))
#!/usr/bin/python3 import sys import minify_html if (len(sys.argv) <= 2): print('Usage: minify.py input.html output.html') sys.exit(1) input_file = open(sys.argv[1], 'r') output_file = open(sys.argv[2], 'w') html = input_file.read() input_file.close() html_minified = minify_html.minify(html, minify_css=Tru...
""" This script vectorizes the body and title data, using the MeanEmbeddingVectorizer from w2v_vectorizers, using the chosen best word2vec model for the datasets used for the final logistic model.. """ from w2v_vectorizers import MeanEmbeddingVectorizer from gensim.models.word2vec import Word2Vec from sklearn.externals...
# Crear el diccionario "frutas" # frutas = {"manzana" : "apple","naranja":"orange","platano":"banana","limon":"lemon"} # Grabar esta estructura de datos "frutas" en un fichero binario "fichero.pckl" # Ya que es un fichero de texto solo se guardaran caracteres, pero no se pueden guardar guardar estas estructuras # Rec...
# -*- encoding: cp949 -*- def getpartialmatch(N): m = len(N) pi = [0] * m begin = 1; matched = 0 while begin + matched < m: if N[begin + matched] == N[matched]: matched += 1 pi[begin + matched - 1] = matched else: if matched == 0: b...
#!/usr/bin/python2 import os import sys import commands as cmd # jobtracker_ip ,typeOfScheduler , include host, exclude host , minMap, MinReducer, MaxRunningJobs def main(argv): if len(argv) != 3: sys.exit("Usage mapred-site_modifier.py <tasktracker/jobtracker(T/J)> <jobtracker_ip> <FIFO/FAIR>") if ...
from flask import Flask, url_for, jsonify, Response, render_template, send_from_directory import config import json from capture import capture import requests from random import randint import os, time import subprocess import picamera, binascii from multiprocessing import Process from flask import make_response fr...
# coding: utf-8 from __future__ import unicode_literals import time import random import hashlib import requests import datetime DEFAULT_CONTENT_TYPE = 'application/x-www-form-urlencoded' class NeteaseMessage(object): def __init__(self, key, secret, tpl_id): self._key = key self._secret = secret...
# A program to show a nested for loop. outer_loop_total = 0 inner_loop_total = 0 countries = ["America", "England", "India", "China"] capitals = ["Washington", "London", "New Delhi", "Beijing"] for country_to_check in countries: outer_loop_total += 1 for city_to_check in capitals: inner_loop_total += 1 if c...
# dataset datasetDir = '/home/lili/datasets/coco' dataType = 'val' imgDir = '{}/img/{}'.format(datasetDir, dataType) txtDir = '{}/gt/{}/txt'.format(datasetDir, dataType) figDir = '{}/fig/{}'.format(datasetDir, dataType) import os import re import skimage.io as io if not os.path.exists(figDir): os.makedirs(figD...
from django.shortcuts import render from .models import Project def index(request): projects = Project.objects.all() return render(request, 'projects/index.html', {'projects': projects}) def detail(request): project = Project.objects.get(pk=100) return render(request, 'projects/detail.html', {'proje...
from django.contrib.auth.models import User, Group from django.http import HttpResponseRedirect from app.models import Request, Word, TotalIndex, WordInRequest, WordPositionsInRequest, RequestResponse, StopWord from rest_framework import viewsets from app.serializers import UserSerializer, GroupSerializer, RequestSeri...
import os import glob import time from datetime import datetime import random import argparse import numpy as np from scipy.stats import t import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from utils import make_batch, make_batch_rev, load_data from models import FCGAT, RPA...
# -*- coding: utf-8 -*- import sys import traceback import re import json import os import threading import xmlrpclib import markdown2 import sublime, sublime_plugin '''文件头样例 <!--iblog { "title":"博客标题写在这里", "categories":"博客分类", "tags":"标签", "publish":"false", "blog_id":"3452965" } --> ''' HEADER_T...
import sys sys.path.append("../") import pygame class Sound: def __init__(self, background='../sounds/background.ogg', volume=0.3): self.transformed = pygame.mixer.Sound('../sounds/transformed.wav') self.normal_background = pygame.mixer.Sound(background) self.normal_background.set_vo...
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def maxAncestorDiff(self, root): """ :type root: TreeNode :rtype: in...
import json import requests import webbrowser class Media: def __init__(self, title="No Title", author="No Author", year="No Release Year", diction=None, url="No url"): self.diction = diction if diction == None: self.title = title self.author = author self.year = year else: if "trackName" in dicti...
''' Created on 11 set 2017 @author: davide ''' # Image loading import matplotlib.image as mpimg import os import seaborn as sns sns.set() image = mpimg.imread('./../images/MarshOrchid.jpg') print(image.shape) import matplotlib.pyplot as plt plt.imshow(image) plt.show() # Transpose the image ...
## # This software was developed and / or modified by Raytheon Company, # pursuant to Contract DG133W-05-CQ-1067 with the US Government. # # U.S. EXPORT CONTROLLED TECHNICAL DATA # This software product contains export-restricted data whose # export/transfer/disclosure is restricted by U.S. law. Dissemination # to ...
import pandas as pd from twilio.rest import Client account_sid = "AC3f920516d3d046cf1a9c0be5eeb97495" auth_token = "7158a8bedcbc9548ce519c5084a2339f" client = Client(account_sid, auth_token) # TODO: Instalar: # pandas # openpyxl # twilio # TODO: Passo a passo da solução. # TODO: Abrir os 6 arquivos do excel. lista...
import argparse import http.server import json import logging import paho.mqtt.client as mqtt import re import signal import socketserver import sys import time from threading import Thread, Lock, Event, current_thread DEFAULT_HTTP_SERVER_PORT = 8080 # HTTP server runs on localhost DEFAULT_MQTT_URL = "localhost" DEFAU...
import os import sys from textwrap import shorten from getkey import getkey # cross-platform module for getting single keypresses directory = sys.argv[1] def process_file(file_path): with open(file_path, "r+") as f: lines = f.readlines() modified = False for i, line in enumerate(lines): ...
#--------------------------------------------------------------------------- # #This testcase tests AllPair Pattern APIs #1. import #2. name #3. permutation #4. set1_elements #5. set2_elements #6. set1_initialization() #7. set2_initialization() #8. element_comparision() # #---------------------------------------------...
from scipy.stats import norm import numpy as np data = np.array([ 12.1085187 , 12.10867427, 11.21137858, 10.01311363, 10.79744224, 13.19280269, 12.44086123, 11.88810057, 10.70064104, 11.50382741]) def log_likelihood_normal_two_parameters(mu, sigma_sq, data_in): """ C...
import soundfile import time import numpy as np import os class AudioConverter: CHUNK_SIZE = 1024 VOLUME_PERCENTAGE = 100 def __init__(self): self.sound_file = None self.buffer = [] self.path = None self.sound_info = None self.finished = False self.loaded = False self.chunk_set = False self.proces...
''' Title : Set .discard(), .remove() &amp; .pop() Subdomain : Sets Domain : Python Author : codeperfectplus Created : 17 January 2020 ''' n = int(input()) s = set(map(int, input().split())) methods = { 'pop' : s.pop, 'remove' : s.remove, 'discard' : s.discard } for _ in range(int(input())): ...
# -*- coding: utf-8 -*- from django.conf.urls import include, url, patterns from django.contrib import admin from item.views import * # from django.conf import settings from django.conf.urls.static import static from django.conf import settings as st import os from django.contrib.staticfiles.urls import staticfiles_ur...
class Solution(object): def largestDivisibleSubset(self, nums): """ :type nums: List[int] :rtype: List[int] """ nums.sort() table=[1 for i in range(len(nums))] aux = [i for i in range(len(nums))] for i in range(1,len(nums)): for j in range(...
import pandas as pd import logging import random import numpy as np import re import os from framework import Task, ModelTrainer, FeatureEngineering, Evaluation, DataCuration from infer_bert_qa import get_qa_inference class TaskQA(Task): def __init__(self, config): self.config = config class Feature...
import shutil from utils import * def windows_installer_cmake(properties): repository_path = properties["repository_path"] verbose_output = properties["verbose"] debug = properties["debug"] if debug: print(" ! Debug build not supported on Windows") version = "3.9.3" url = "https://cmake.org/files/v3....
from .helpers import * from .hparams import HParams, copy_hparams, save_config, load_config, print_config from .slack_bot import Notifier from .image_transforms import *
import sys import cj_function_lib as cj import init_file as variables import mdbtools as mdt #print variables.ProjMDB #print variables.QSWAT_MDB Watersheds = cj.extract_table_from_mdb(variables.ProjMDB, 'Watershed', variables.path + "\\watershed.tmp~") pndrgn = cj.extract_table_from_mdb(variables.QSWAT_MDB, 'pndrng...
import yaml, logging, os, shutil from subprocess import call as _call import re from pprint import pformat # Set this to avoid accidentally issuing docker commands NO_CALL = False def call(cmd): logging.info(cmd) if NO_CALL: return _call(cmd) def docker_retag_image(old, new): cmd = ['docker'...
import createRandomTree as tree import Queue '''BFS uses a FIFO structure (queue)''' numNodes = 50 randSeed = 1 goal = 6 #arbitrarily defined root = tree.getBinaryTree(numNodes, randSeed) queue = Queue.Queue() queue.put(root) counter = 0 while not queue.empty(): print 'Iteration ' + str(counter) counter += ...
import unittest as ut import ros.main class TestCode(ut.TestCase): def test_colourcode(self): self.assertEqual(ros.main.colourcode('#212121', 'hex', True), '#212121') def test_changecolour(self): self.assertEqual( str(ros.main.changecolour('#212121', 'red', 10)), '#192121') ...
PRODUCT_NAME = "//h1[@itemprop='name']" QUANTITY_WANTED = "//input[@id='quantity_wanted']" PLUS_ICON = "//i[@class='icon-plus']" SIZE_DROPDOWN = "//div[@class='attribute_list']/div[@id='uniform-group_1']/select" COLOUR_SELECT = "//ul[@id='color_to_pick_list']/li/a[@name='~~~']" COLOUR_SELECTED ...
# Gaussian Quadrature Formula to compute definite integral of a function # Input required : function from math import * def f(x, function): return eval(function) def parseCompile(equation): if 'e^' in equation: equation = equation.replace('e^', 'exp') if '^' in equation: equation = equa...
""" Contains internal configurations that the user might want to act upon. """ # REFACTOR: [better confs]: move to the configs .yaml # Defines what nodes are to be masked to avoid conduction overload of non-informative nodes # Their edges are not very hight necessarily, but they are highly central in the Reactome # ph...
import zope.schema import zope.interface from plonezoho.remoteeditor import MessageFactory as _ class IRemoteAPI(zope.interface.Interface): apikey = zope.schema.TextLine( title=_(u"API key"), description=_("TODO: needs description from where to get apikey!")) skey = zope.schema.TextLine( ...
import play, time class Game_map: def __init__(self, image_name, walls, dots, fruit): self.score = 0 self.fruit = fruit self.full_image = play.new_image(image=image_name, x=0, y=0, size=50) self.full_image.transparency = 0 self.walls = walls self.dots = dots ...
from pathlib import Path import csv # ***Working with CSV Files*** with open('data.csv', 'w') as file: writer = csv.writer(file) writer.writerow(['transaction_id', 'product_id', 'price']) writer.writerow(['1000', '1', '5']) writer.writerow(['1001', '2', '15']) with open('data.csv') as file: reade...
import urllib.request import re link=urllib.request.urlopen('http://ramakrishnavivekananda.info/') f=link.read() D = f.decode('utf-8') x=re.sub('<.*?>','',D) with open('G:/python ex/file.txt','w',encoding='utf-8') as fwrite: fwrite.write(x)
#lex_auth_012693825794351104168 def find_common_characters(msg1, msg2): a = "" for ch in msg1: if ch in msg2 and ch != "" and ch not in a: a += ch if len(a): return a return -1 #Provide different values for msg1,msg2 and test your program msg1 = "I like Python" msg2 = "Jav...
import os path="E:/data2/zhengchang/" name="zhengchang" for root, child, files in os.walk(path): i=1 os.chdir(path) for each in files: os.rename(each, name+str(i)+".avi") i=i+1
import numpy as np import matplotlib.pyplot as plt # 先在四个中心点附近产生一堆数据 real_center = [(1, 1), (1, 2), (2, 2), (2, 1)] point_number = 50 points_x = [] points_y = [] for center in real_center: offset_x, offset_y = np.random.randn(point_number) * 0.3, np.random.randn(point_number) * 0.25 x_val, y_val = center[0] ...
import athlete import coach import predefined choices = ("athlete", "coach", "predefined", "exit") def main(): choice = "x" print("\nETPG® | The training schedule program for any endurance trainer and athlete") while (choice not in choices) or choice !="exit": choice = str(input("\nGeneral Menu ...
import numpy as np from matplotlib import pyplot as plt from matplotlib import animation # First set up the figure, the axis, and the plot element we want to animate fig = plt.figure() ax = plt.axes(xlim=(0, 500), ylim=(-0.3, 0.3)) line, = ax.plot([], [], lw=2) def PIB_Func(x, n, L): return ...