text
stringlengths
8
6.05M
#!/usr/bin/python import numpy as np import pylab as py from COMMON import nanosec,yr,week,grav,msun,light,mpc,hub0,h0,omm,omv,kpc,mchirpfun,fmaxlso from scipy import integrate from scipy.ndimage import gaussian_filter import pyPdf,os #Input parameters: outputdir='../plots/Distances/' outputfile1=outputdir+'K_binaries...
#Ejercicio 17 """ Convertir un valor entero de horas a segundos. """ horas = int (input ("Ingrese el valor entero expresados en horas: ")) segundos = round ((horas * 3600 / 1), 2) print ("El valor entero expresado en horas es: " , segundos, "segundos")
class Locators: """ Class containing locators from different pages that are being accessed. """ # FindHotel Locators popup_xpath = './/div[@class="autopop__wrap makeFlex column defaultCursor"]' login_menu_xpath = './/li[@class="makeFlex hrtlCenter font10 makeRelative lhUser userLoggedOut"]' ...
from face_recognition.api import face_encodings import numpy class Picture(): def __init__(self, name: str, encodings, face_locations) -> None: self.name = name self.encodings = encodings self.face_locations = face_locations
import subprocess import pyttsx3 import sys import locale import ghostscript engine = pyttsx3.init() rate = engine.getProperty('rate') engine.setProperty('rate', 140) args = [ "ps2pdf", #value doesn't matter "-dNOPAUSE", "-dBatch", "-dSAFER", "-sDEVICE=txtwrite", "-sOutputFile=" + sys....
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations from typing import TYPE_CHECKING from pants.engine.internals.native_engine import EngineError as EngineError # noqa: F401 from pants.engine.internals....
def removeKthLinkedListNode(head, k): # Space: O(1) Time: O(n) n = length of linked list # Write your code here # Checking for an edge case. If a node wasn't passed in to the first parameter if head is None: return None # this is an artifact of my first pass solution - I forgot to delete it ...
# BSD 3-Clause License. # # Copyright (c) 2019-2023 Robert A. Milton. All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notic...
from django.db import models class ExpenseCode(models.Model): """ Represents a Budget of an order in the system """ number = models.CharField('ExpenseCode Number', max_length=100) #: Name type = models.CharField('ExpenseCode Type', max_length=100) #: Type project = models.ForeignKey('finance....
with open("input.txt") as f: data = f.readlines() # Get rid of the newlines data = [n.strip() for n in data] FIELD_WIDTH = len(data[0]) -1 # Zero index FIELD_HEIGHT = len(data) - 1 char_x = 0 char_y = 0 trees_found = 0 tracked_list = [list(data[0])] # Run until you reach the bottom while char_y < FIELD_HEIGHT: ...
# -*- coding: utf-8 -*- import torch import random import pickle import numpy as np import torch.nn as nn class DQNSolver(nn.Module): def __init__(self, input_shape, n_actions): super(DQNSolver, self).__init__() self.conv = nn.Sequential( nn.Conv2d(input_shape[0], 32, kernel_size=8, s...
import os import shutil import django from django.core.files.images import ImageFile from django.core.exceptions import ObjectDoesNotExist os.environ.setdefault("DJANGO_SETTINGS_MODULE", "metgs.settings") django.setup() import db_data from mainapp.models import * def fill_top_menu(): TopMenu.objects.all().delete(...
import cProfile, pstats, io def clingen(infile): f=open(infile) dic={} for i in f: line=i.split("\t") if line[0] not in dic: dic[line[0]]=[[line[1]], [line[3]], [line[4]], [line[5].strip()]] else: dic[line[0]][0].append(line[1]) dic[line[0]][1].append(line[3]) dic[line[0]][2].append(li...
x = "There are %d types of people." % 10 binary = "binary" do_not = "don't" y = "Those who know %s and those who %s." % (binary, do_not) print x print y print "I said: %r." % x print "I also said: '%s'." % y hilarious = False joke_evaluation = "Isn't that joke so funny?! ...
f = open('input.txt', 'r') line = f.read().split(' ') x = [int(i) for i in line] f.close() i = 0 total = 0 while len(x) > 0: children = x[i] if children == 0: metas = x[i+1] meta_start = i+2 meta_end = meta_start + metas total += sum(x[meta_start:meta_end]) del x[i:meta_...
import numpy as np class store(object): def __init__(self, products, location, owner): self.products = products #self.products = np.array["pen", "brush", "apple", "cap"] self.location = location self.owner = owner self.display_info() # print self.products ...
n= int(input("enter a number: ")) n1=0 n2=1 print(n1) print(n2) for i in range(0,n): n3=n1+n2 n1=n2 n2=n3 print(n3)
from pandac.PandaModules import * #basic Panda modules from direct.showbase.DirectObject import DirectObject #event handling from direct.particles.ParticleEffect import ParticleEffect #particle effects from direct.actor.Actor import Actor from Files.HUD import * import math class Movement(object): def __init__(self,...
from flask import Flask, render_template, request app = Flask(__name__) @app.route('/hello/') @app.route('/hello/<name>') def hello(name=None): return render_template('hello.html', name=name) @app.route('/test', methods=['GET', 'POST']) def test(): return 'path={} method={}'.format(request.path, request.met...
@bot.command() async def mute(ctx, member : discord.Member): guild = ctx.guild for role in guild.roles: if role.name == 'Muted': await member.add_roles(role) await ctx.send('{} has been muted'.format(member.mention)) return over...
#------------------------------------------------------------------------------- # Name: FirstGameMain # Purpose: This is the main file of the game, it handles the game state # # Author: Marko Nerandzic # # Created: 25/12/2012 # Copyright: (c) Marko Nerandzic 2012 # Licence: This work is licen...
default_app_config = 'teams.apps.TeamsAppConfig'
# coding=UTF-8 # 敏感操作Token验证 import random from hashlib import sha256 # 验证集合 class Verify(): def __init__(self): super().__init__() def GetSubToken(self): # 生成注册用Token num = random.randint(0, 100) Token = sha256(str(num).encode('utf-8')).hexdigest() return Token ...
from xml.dom.minidom import parse import xml.dom.minidom DOMTree = xml.dom.minidom.parse("compendiums/movies.xml") collection = DOMTree.documentElement if collection.hasAttribute("shelf"): print ("Root element : %s" % collection.getAttribute("shelf")) movies = collection.getElementsByTagName("movie") for movie in...
class Node: def __init__(self, _value, _pos): self.value = _value self.pos = _pos def __cmp__(self, other): if self.value == other.value: return self.pos - other.pos return self.value - other.value class Solution: """ @param nums: A list of integers @retu...
#!/usr/bin/env python import rospy from geometry_msgs.msg import Twist pub = rospy.Publisher('/mobile_base/commands/velocity', Twist, queue_size=10) def setup(): rospy.Subscriber('kobuki_command', Twist, send) rospy.init_node('constant_command', anonymous=True) def send(data): command = Twist() ...
# Generated by Django 2.2.12 on 2020-06-02 10:01 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('admin', '0015_rename_view_permissions'), ] operations = [ migrations.AddField( model_name='domain', name='message_l...
''' Created on Dec 2, 2015 @author: ams889 This module contains the functions used for the assignment. ''' import pandas as pd from userDefinedErrorHandling import * import sys import matplotlib.pyplot as plt def dataLoad(): ''' This function loads the csv from the URL used to access the data. It also prints...
import re def riddle1(): raise NotImplementedError() def riddle2(): raise NotImplementedError() def riddle3(): raise NotImplementedError() def riddle4(): raise NotImplementedError() def riddle5(): raise NotImplementedError() def riddle6(): raise NotImplementedError() def riddle7(): ra...
#!/usr/bin/env python # coding: utf-8 # Copyright (c) Qotto, 2019 """KafkaProducer class Produce messages and send them in a Kafka topic. """ import asyncio from logging import (getLogger, Logger) from typing import Union, List, Dict, Awaitable from aiokafka.errors import KafkaError, KafkaTimeoutError from aiokafka...
from betterhandler import * import cgi from google.appengine.ext import webapp from google.appengine.ext import db from google.appengine.api import users from google.appengine.ext.webapp import template from models import * import os import wsgiref.handlers class MainPage(BetterHandler): def get(self): lyr...
#!/usr/bin/env python3 import os, sys import pickle import numpy as np import hdf5_to_dict as io avgs = [] for fname in sys.argv[1:-1]: print("Loading {}".format(fname)) avgs.append(pickle.load(open(fname, "rb"))) avgs[-1]['fname'] = fname #for avg in avgs: # print("Name: {}, contents: {}".format(avg['fname'...
from django.contrib.auth import authenticate, login from django.contrib.auth.models import User from django.http import HttpResponse from django.shortcuts import render, redirect from registration.forms import RegistrationForm def registration(request): if request.method == 'POST': form = RegistrationForm(request....
#!/usr/bin/env python # encoding: utf-8 """ sendmail Created by Anne Pajon on 2015-03-26. """ # email modules import smtplib from email.MIMEText import MIMEText from email.MIMEMultipart import MIMEMultipart # email addresses ANNE = 'anne.pajon@cruk.cam.ac.uk' ANNEGMAIL = 'pajanne@gmail.com' HELPDESK = 'genomics-helpd...
import os import datetime import cv2 import numpy as np import postgresql from PIL import ImageGrab import error_log import db_query import introduction IMAGES_FOLDER = "images" def search_cards(screen_area, deck, list_length, db): hand = '' try: for item in db_query.get_last_screen(screen_area, db):...
from sqlalchemy import Column, String, Integer, Float from bd import Base class Song(Base): __tablename__ = 'song' song_id = Column(String, primary_key=True) title = Column(String) artist_id = Column(String) year = Column(Integer) duration = Column(Float) def _init_(self,so...
from datetime import datetime from itertools import groupby from collections import Counter #Opening log file def open_read_file(): infile = r"./input/log.txt" with open(infile) as log: log = log.readlines() return log log_file = open_read_file() row_taker = [row.split() for row in log_file] def...
from CallBackOperator import CallBackOperator from SignalGenerationPackage.DynamicPointsDensitySignal.DynamicPointsDensityUIParameters import DynamicPointsDensityUIParameters class PointsDensityCallBackOperator(CallBackOperator): def __init__(self, model): super().__init__(model) # overridden de...
# -*- coding: utf-8 -*- # Generated by Django 1.10.2 on 2016-10-21 16:09 from __future__ import unicode_literals import django.db.models.deletion from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("organisations", "0007_auto_20161021_1609"), ("electi...
""" Basic model of a room with a radiator. All specific enthalpies within room are lumped as one value. All sources of heat loss are lumped as one value. Assumed that room is only heated by the radiator. heat_in => heat_stored => heat out. Gives basic equation stored_heat = start_heat + (in_heat + out_heat) [Q_room =...
import unittest from katas.kyu_8.remove_first_and_last_char_part_two import array class ArrayTestCase(unittest.TestCase): def test_equals(self): self.assertEqual(array('1,2,3'), '2') def test_equals_2(self): self.assertEqual(array('1,2,3,4'), '2 3') def test_none(self): self.ass...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu May 30 16:27:36 2019 @author: kj22643 """ # -*- coding: utf-8 -*- """ Created on Wed May 29 12:29:10 2019 @author: kj22643 """ %reset import numpy as np import pandas as pd import os import scanpy as sc import seaborn as sns from plotnine import * ...
# 학과: 문화콘텐츠학과 # 학번: 2016010819 # 작성자: 이아영 # 작성일: 2016년 10월 21일 # 덧셈만으로 제곱 구하는 함수 만들기(재귀함수) def square(n): if n > 0: return n+n-1 + square(n-1) elif n < 0: return -n-n-1 + square(n+1) else: return 0 ''' def square(n): if n != 0: if n > 0: return n+n-1 + squar...
print(3 * 5)
from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver, Signal from django.contrib.auth.models import User from django.utils import timezone from django.utils.encoding import python_2_unicode_compatible from jenkins.models import Job, Build, Artifact # Signal...
boto_args = {'service_name': 'dynamodb'} #boto_args['endpoint_url'] = 'http://localhost:8000'
#!/usr/bin/env python import roslib roslib.load_manifest("edge_tpu") import sys import rospy import cv2 import time from std_msgs.msg import String from sensor_msgs.msg import Image #from object_detection_msgs.msgs import RecognizedObject from cv_bridge import CvBridge, CvBridgeError import numpy as np import PIL imp...
import xml.etree.ElementTree as ET serviceurl = ('E:/KNU/course2semestr/codinginGIS/alonwork/S3/comments_283746.xml') print ('Retrieving', serviceurl) #TODO #Find sum in count elements counter = 0 tree = ET.parse(serviceurl) root = tree.getroot() for x in root.findall('comments'): for y in x.findall('comment'): ...
# -*- encoding: utf-8 -*- """ Topic:通用文章爬取 Todo:瀑布流分页不可用 Todo:Ajax加载不可用 """ from scrapy.spiders import CrawlSpider, Rule from scrapy.linkextractors import LinkExtractor from items import ArticleItem import logging logger = logging.getLogger(__name__) class ArticleSpider(CrawlSpider): def __init__(...
"""Contains all constants for the project. This file contains all constants for the project. E.g. dictionary keys and regional names. Typical usage example: print(REGIONS.get(i)) """ # top level keys KEY_NEWS = 'news' KEY_REGIONAL = 'regional' KEY_NEWSTORIESCOUNTLINK = 'newStoriesCountLink' KEY_TYPE = 't...
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-05-22 23:17 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('drone', '0003_auto_20170523_0106'), ] operations = [ migrations.AddField( ...
#global links Queue to share across files from queue import Queue from collections import Counter def init(initial_page): global queue global seen global file_count global cookie queue = Queue() seen = set([initial_page]) queue.put(initial_page) file_count = Counter() cookie = None
import ply.lex as lex # Reserved words. reserved = { 'at' : 'AT', 'to' : 'TO', 'up': 'UP', 'add' : 'ADD', 'end': 'END', 'get' : 'GET', 'map': 'MAP', 'run': 'RUN', 'set': 'SET', 'down': 'DOWN', 'edit' : 'EDIT', 'exit': 'EXIT', 'left': 'LEFT', 'move': 'MOVE', ...
#https://github.com/codebasics/py/blob/master/ML/2_linear_reg_multivariate/2_linear_regression_multivariate.ipynb import pandas as pd import numpy as np from sklearn import linear_model import math data = pd.read_csv('Prices.csv') print(data) #Data preprocessing #Since few data are missing, find the media...
import unittest from katas.kyu_8.triple_trouble import triple_trouble class TripleTroubleTestCase(unittest.TestCase): def test_equals(self): self.assertEqual(triple_trouble('aaa', 'bbb', 'ccc'), 'abcabcabc') def test_equals_2(self): self.assertEqual(triple_trouble('aaaaaa', 'bbbbbb', 'cccccc...
from functions import isPrime def find_ns(a, b): n = 0 while isPrime(n**2+a*n+b): n+=1 return n def main(): n_lst = [] ab_lst = [] for a in range(-1000,1000): for b in range(-1001,1001): n_lst.append(find_ns(a,b)) ab_lst.append((a,b)) print(ab_lst[n_lst.index(max(n_lst))]) print(ab_lst[n_lst.index(ma...
from flask import Flask,render_template,request,redirect,url_for,flash from flask_sqlalchemy import SQLAlchemy from config import Development,Production from resources.employees import Employee app = Flask(__name__) app.config.from_object(Development) # app.config.from_object(Production) db = SQLAlchemy(app) from mod...
from django.urls import path from Product.views import Comment_Add urlpatterns = [ path('Comment_Add/<int:id>/',Comment_Add, name='comment_add'), ]
#-*- coding: utf-8 -*- from django.conf.urls import url from . views import * urlpatterns = [ url(r'^$', formulario, name='formulario'), url(r'assinar$', assinar, name='assinar'), ]
#!/usr/bin/python3 #minimalist python pe library import sys import argparse import struct import PEDataDirHeader class Decoder: def __init__(self,_filename="",_fileperms="rb"): self.fileperms = _fileperms self.filename = _filename self.header = PEDataDirHeader.PEDataDirHeader() self.fields = self.heade...
import os os.system('gnome-terminal --command=gvim')
import logging.config CONFIG_PY = { "version": 1, "disable_existing_loggers": False, "formatters": { "default": { "format": "%(asctime)s | %(filename)s | %(levelname)s | %(funcName)s | %(message)s" }, }, #handler level overrides the logger level "handlers": ...
# set # 集合主要特点: # 1. 天生去重(去掉重复值) # 2. 可以增,删(准确来说,集合可以增加删除元素,但不能修改元素的值) # 3. 可以方便的求交集,并集,补集 # 集合的定义 set1 = {"xiaoming", 12, 12, "man", (1, )} # print(set1) # print(len(set1)) # 集合长度 # print(type(set1)) # 类型 # 集合的交集(相同的元素) set2 = {1, 2, 3, 4, 5, 6} set3 = {2, 4, 6, 8} # print(set2.intersection(set3)) # 打印set2和...
# encoding: utf-8 """ TODO: `var z = require("blah").z;` ... to support this kind of require, we just have to make sure we don't replace the entire line of code, but just the `require(whatev)` part, so we'll end up with: var z = require("blah").z; var z = exports.z; """ import os import sys import re PAC...
from boto.s3.connection import S3Connection #Connect conn = S3Connection('access key','secret') #Get your bucket b = conn.get_bucket('bucket') #Iterate through bucket keys, set metadata and update your key for key in b.list(): key.metadata.update({'Cache-Control': 'max-age=3154000'}) key.copy( key.bu...
import textwrap def wrap(string, max_width): lista=textwrap.wrap(string,max_width) texto='' for i in lista: texto+=i+'\n' return texto if __name__ == '__main__': string, max_width = input(), int(input()) result = wrap(string, max_width) print(result)
# test 1 #列表切片 names = ["Amy","Sam","Ziv","Leo","Rock"] # 输出索引为1~3的元素,同样的,不包含3 print(names[1:3]) # 不指定起始索引,默认从开头开始 print(names[:3]) # 不指定结尾索引,默认到列表的结尾 print(names[2:]) # 用负数输出倒数几个元素 print(names[-2:]) # test 2 #与完整的列表相同,切片也是可以被遍历的 for name in names[:3]: print(name) # test 3 # 列表的复制,使用一个包含所有元素的切片 name3 = names[:]...
from __future__ import unicode_literals from django.apps import AppConfig class LiantangConfig(AppConfig): name = 'liantang'
def factorial(a): c = 1 for i in range(1, a + 1): c = c * i return c print(factorial(19))
#!/usr/bin/env python # # Po-Lin Chiu 2015.05.14 - Created. # from EMAN2 import * from sparx import * def write_ctfs2header(ctf_txtfile, in_image, out_image): """ Write the CTF parameters into the image header (for stack). ctf_txtfile: 'sxcter.py' ctf output list in_image: input i...
from django.shortcuts import render from django.http import JsonResponse def hello_world(request): return JsonResponse({ 'message': 'Hello world!' })
from django.contrib import admin from .models import Budget, Expense admin.site.register(Budget) admin.site.register(Expense)
import json from Utilities import * from Animation import * class NPC: # Non-player characters. People to interact with in-game that are run by the computer def __init__(self, name): self.name = name # For display purposes and for finding the right save file self.savefilename = str(self.name) + "Sa...
#!/usr/bin/env python3 """Retrieve and save data from/to csv. Usage: python3 words.py <URL> """ import sys import pandas as pd import numpy as np import datetime def read_csv(path, sep=',', header='infer'): """Read data from a csv file. Args: path: The path to the file. sep: Delimiter ...
clist=[0]*10001 for i in range(1,10001): clist[i]=i*i*i cubes=set(clist[1:]) for _ in range(int(input())): n=int(input()) flag=0 for i in range(1,10001): find=n-clist[i] if find in cubes: flag=1 if flag == 1: print("YES") el...
from rest_framework import status from rest_framework.response import Response def unauthorized(message): ''' User is unauthorised to perform action.''' body = {'status': 401, 'error': 'unauthorized', 'message': message} return Response(body, status=status.HTTP_401_UNAUTHORIZED) def bad_request(message)...
# 二维前缀和 class Solution: def imageSmoother(self, img: List[List[int]]) -> List[List[int]]: m, n = len(img), len(img[0]) preSum = [[0] * (n+1) for _ in range(m+1)] for i in range(m): for j in range(n): preSum[i+1][j+1] = preSum[i+1][j] + preSum[i][j+1] - preSum[i...
# code for question 2 import sys import arff, numpy as np from sklearn import tree from sklearn import preprocessing from sklearn.model_selection import train_test_split from sklearn import svm, datasets from sklearn.model_selection import GridSearchCV from sklearn.tree import DecisionTreeClassifier from sklearn.metri...
from flask import render_template, flash, request, url_for from sqlalchemy import desc from werkzeug.utils import redirect from fyyur import app, db from fyyur.forms import * # Shows # ---------------------------------------------------------------- from fyyur.models import Venue, Artist, Show from fyyur.repositori...
""" Created by Alex Wang on 20200513 """ def badcase_set_get(groundtruth_list, predict_list, video_id_list, id_name_map): badcase_set_map = {} for i in range(len(groundtruth_list)): groundtruth = groundtruth_list[i] predict_label = predict_list[i] if groundtruth != predict_label: ...
import socket import ssl from time import sleep import flatactors import common import irc_parser class Socket: """ A line buffered IRC socket interface. send(text) sends text as UTF-8 and appends a newline, read() reads text and returns a list of strings which are the read lines without...
import time, struct, socket import logging def parse_data(self): #Go through data and find command and end codes to parse recv buffer data = self.recv_buffer buffer_length = len(data) if buffer_length>0: go=True else: go=False while ...
# The Juice Shortcodes API. To be transfered into the juice.core module. # Needs a little bit more refactoring, but the general idea is to provide # Pages, posts and other content types with the ability to use shortcodes. # This is very similar to WordPress' technique. Examples of shortcodes could be: # # * [form slug=...
import sys as stallman # Checks to see if a line in F_I_L_E_O_N_E is NOT present in file2 # This does not take into account order of the lines within each file with open(stallman.argv[1], 'r') as F_I_L_E_O_N_E: with open(stallman.argv[2],'r') as file2: ...
from ..models import * from datetime import datetime def load_base_school_location(session): # get the public school records print("processing public school data") public_school_records = session.query(JrnlPublicSchoolBase.NCESSCH, JrnlPublicSchoolBase.ST, ...
""" Crie um programa que receba 3 valores, compare-os e printe ao final o número de valores iguais. Exemplo: Entrada Saída 1, 2, 3 0 2, 3, 2 2 7, 7, 7 3 """ #Solução contador=0 num1, num2, num3 = int(input()), int(input()), int(input()) if num1==num2: ...
def longestCommonPrefix(self, strs): """ https://leetcode.com/problems/longest-common-prefix :type strs: List[str] :rtype: str """ if len(strs) == 1: return strs[0] template = strs[0] count = float('inf') for i in range(1, len(...
import tensorflow as tf import numpy as np import matplotlib.pyplot as plt import warnings warnings.filterwarnings('ignore') # import os # print(os.getcwd()) cars = np.loadtxt("../../data/cars.csv", delimiter=",", dtype=np.int32) # print(cars) print(cars.shape) x = cars[:, 0] y = cars[:, 1] x1, y1 = cars.T print(...
import math import sys class NaiveBayes(object): def __init__(self,classes,classData,data): self.classes = classes # prior data for all the classes self.priors={} # saves prior probability for each class self.classData = classData # hasmap with key as class and value as file name for data ...
import argparse import logging import math from ..pyp import PYP from ..arpa import CharLM, SRILMWrapper import corpus def run_sampler(model, identifiers, n_iter): n_identifiers = len(identifiers) for it in range(n_iter): logging.info('Iteration %d/%d', it, n_iter) for iden in identifiers: ...
# -*- coding: utf-8 -*- ''' Center for Internet Security (CIS) audit module ''' from __future__ import absolute_import # Import python libs import logging # Import salt libs from salt import utils __virtualname__ = 'cis' LOG = logging.getLogger(__name__) GREP = utils.which('egrep') STAT = utils.which('stat') SYSCTL...
def listoverlap(list1, list2): list3 = [x for x in list1 if x in list2] list_overlap = [] for x in list3: if not(x in list_overlap): list_overlap.append(x) print(list_overlap)
import matplotlib.pyplot as plt import numpy as np import uncertainties.unumpy as unp from scipy.optimize import curve_fit from scipy import stats from uncertainties import ufloat # x = np.linspace(0, 10, 1000) # y = x ** np.sin(x) # plt.subplot(1, 2, 1) # plt.plot(x, y, label='Kurve') # plt.xlabel(r'$\alpha \:/\: \s...
from bs4 import BeautifulSoup from requests_html import HTMLSession import hashlib import os import multiprocessing import math import requests import json import datetime import cv2 class image_downloader: def __init__(self): pass def google_download_page(self, keywords): #Goes to google an...
from example1 import line as p1 print("++++ executing "+ __file__) print( p1( -3.4, q=0.5 ) )
# Perfect Squares # Given a positive integer n, find the least number of perfect square numbers # (for example 1, 4, 9, 16, ...) which sum to n # Explanation: Sub-problem of recursive algorithm is what's the least number of # perfect square numbers to (n - curr_sqr**2). Then we could just # ...
print("Celcius To Ferenhiet or Vice-versa Conversion System") print("Developed By Sudip Mitra") print("E-mail : sudipmitraonline@gmail.com") print("") def c_to_f_translator(value) : #Celcius to Ferenhiet Conversion Function farenhiet_conversion = ( (value * 9) / 5 ) + 32 return farenhiet_conversion...
""" Textbook example of recursion. The recursion tree is unbalanced. The rightmost path has n/2 levels and the leftmost has n levels. So the first n/2 levels of the tree are full, but the full n levels are not. So there are between O((sqrt 2)^n) = O(1.4^n) and O(2^n) levels, which is the time complexity of the algorit...
"""Implementation of app API. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import logging import fnmatch from treadmill import context from treadmill import schema from treadmill.scheduler import masterapi _...
import numpy as np from contrast import Contrast class main(Contrast): def __init__(self, layers, incident_light): self.layers = layers self.incident_light = incident_light self.disulfuro = np.loadtxt("./refractive_indexes/disulfuro_molibdeno.txt", delimiter='\t') # Disulfuro wavelength...