text
stringlengths
38
1.54M
from os import listdir from os import walk from os import stat from datetime import datetime, timezone from os.path import isfile, join from PIL import Image import piexif import os import exifread import numpy as np import argparse parser = argparse.ArgumentParser() parser.add_argument("year") args = parser.parse_arg...
# script takes json returned by google search and stores links and meta description import json import re class my_dictionary(dict): # class of dictionary def __init__(self): self = dict() def add(self, key, value): self[key] = value def google_results(formatedJson): data = json.loads(for...
from __future__ import print_function from __future__ import division import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from astropy.io import fits from astropy.cosmology import FlatLambdaCDM buzzard_cosmo = FlatLambdaCDM(68.81,.295) from scipy.stats import binned_statistic import subprocess impor...
import webapp2 import json import cgi from utils.utilities import UtilityMixin, Organization, Driver from utils.requirelogin import RequireLoginMixin from google.appengine.api import users from google.appengine.ext import ndb class SaveDriverAjax(webapp2.RequestHandler, RequireLoginMixin, UtilityMixin): def ...
import pygame as pg # pygame ab Version 2.0 wird benötigt # Installation im Terminal mit # --> pip install pygame (windows) # --> pip3 install pygame (mac) # --> sudo apt-get install python3-pygame (Linux Debian/Ubuntu/Mint) pg.init() größe = breite, höhe = 1920,1080 fenster = pg.display.set_mode(größe) clock...
import tensorflow as tf from defines import WIDTH, HEIGHT def cnn_model(): model = tf.keras.models.Sequential() model.add(tf.keras.Input(shape=(HEIGHT, WIDTH, 3))) model.add(tf.keras.layers.Conv2D(16, (4, 4), padding="valid")) model.add(tf.keras.layers.BatchNormalization()) model.add(tf.keras.laye...
#dette programmet skal regne ut den samlede poengsummen for løpene, hvor brukeren fyller tiden, og distansen for hvert løp def sammenlagt(): #her legger vi inn bruker-definisjon for navn navn =(input("Navn: ")) #første løp print("Første løp") dist1 = eval(input("Distanse: ")) tid_min1 = eval(in...
"""Checks for web services""" from urllib import request import urllib.error from preflyt.base import BaseChecker class WebServiceChecker(BaseChecker): """Verify that a webservice is reachable""" checker_name = "web" def __init__(self, url, statuses=None): """Initialize the checker :pa...
from __future__ import division import os import sys import sfml as sf DIRECT_DICT = {sf.Keyboard.LEFT : (-1, 0), sf.Keyboard.RIGHT : ( 1, 0), sf.Keyboard.UP : ( 0,-1), sf.Keyboard.DOWN : ( 0, 1)} SCREEN_SIZE = sf.Vector2(800, 600) CAPTION = "Move me with the Arrow ...
import json class AppendingDict(dict): def __init__(self): self.__data = {} def __getattribute__(self, name): print('Calling getattribute with %s' % name) if name in ['setdefault', '_AppendingDict__data', 'json']: return object.__getattribute__(self, name) return No...
import random print("The program is to simulate a cleaning robot.",end = "\n") print("There will be m * n map when you type in.",end = "\n") def init(): # Create an map m*n print("Please input the first number M:") m = int(input()) print("Then, input the second number N:") n = int(input(...
import matplotlib.pyplot as plt import PIL import numpy import scipy import math from PIL import Image from matplotlib.pyplot import imread from numpy import zeros from numpy import r_ from scipy import fftpack from numpy import pi import sys from huffman import * # image = Image.open("input.jpg") # witdh, height = i...
import os import argparse from flask import request from flask_api import FlaskAPI, status, exceptions from werkzeug.utils import secure_filename import io import numpy as np from PIL import Image import cv2 from datetime import datetime import re import math import apriltag from flask_cors import CORS from logzero im...
from typing import Dict import mysql.connector import json from .goods import shop_list, Goods, shop_name_dict_getter from typing import Type from nonebot.adapters import Bot from nonebot.adapters.cqhttp import GroupMessageEvent mysql_connect_config = { 'user': 'root', 'password': '', 'host': '127.0.0.1', ...
# Generated by Django 2.2.6 on 2019-12-28 19:04 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('users', '0006_userprofile_qq'), ] operations = [ migrations.AlterModelOptions( name='employmentdetail', options={'ve...
import os from PIL import Image import numpy as np import cv2 import pickle BASE_DIR = os.path.dirname(os.path.abspath(__file__)) image_dir = "/home/anup/Pictures/StudentFaces" face_cascade = cv2.CascadeClassifier( '/home/anup/PycharmProjects/Imagemodulator/venv/lib/python3.6/site-packages/cv2/data/haarcascade...
class BelajarClass: i = 12345 def f(self): return 'hello World' # syntak # class NamaKelas: # pass # gantikan dengan pernyataan-pernyataan, misal: atribut atau metode
import scrapy import re class EntertainmentSpider(scrapy.Spider): name = "ent" start_urls = ( 'http://www.onlinekhabar.com/content/ent-news/page/%s' % page for page in xrange(1, 2) ) def parse(self, response): for link in response.css('a::attr(href)').extract(): self.log('Link_input %s' % link) # match_...
import math l = math.log res = [] fact = 0.0 pow = 0.0 j=1 for i in range(2,1000001): while 1: j += 1 fact += l(j) pow = j*l(i) if fact > pow: res.append(j) break t = int(input()) while t>0: t -= 1 a = int(input()) print (res[a-2])
## -*- Mode: python; py-indent-offset: 4; indent-tabs-mode: nil; coding: utf-8; -*- def build(bld): module = bld.create_ns3_module('full', ['network', 'propagation','network', 'internet', 'applications']) module.source = [ 'model/full-wifi-information-element.cc', 'model/full-wifi-information-e...
class Solution(object): def canPlaceFlowers(self, flowerbed, n): if len(flowerbed)==1: if flowerbed[0]==0 and n<=1: return True elif n==0: return True else: return False res=0 mark_1=0 ...
#!/usr/bin/env python """ Network analysis script Parameters: path: str <path-to-folder> Usage: network_smkk.py --path <path-to-folder> Example: $ python network_smkk.py --path data/labelled_data """ # to call path from command line import os from pathlib import Path import argparse # System tools import...
#chapter01-02 #파이썬 중급 #객체 지향 프로그래밍(OOP) --> 코드의 재사용, 코드중복 방지 #클래스 변수 심화 (final static ...) #클래스 선언 class Car(object): """ author : taewon date : 2020.01.15 comment : example """ #자동차의 개수 car_count = 0 클래스변수=5 def __init__(self, car_name, car_detail): self.car_name = car_nam...
import requests import urllib.parse import aiohttp import asyncio import json def get_request(link='', params=None,header=None): """ Asynchronous and parallel request to api link Parameters: link : api link params : additional parameters to url header : header to api ...
# endcoding:utf-8 import sqlite3 import os import json import time source_config = { 'type': 'design_pattern' } target_config = { 'file_path': 'pattern', } # types :对应的数据库的表 # kind :文件目录名称 # types = ['java_basic', 'design_pattern', 'java_advance', 'database', 'arithmetic', 'framework', 'java_ee', '...
from atcoder.dsu import DSU L, Q = (int(x) for x in input().split()) dsu = DSU(L) ops = [] cut = set() for _ in range(Q): c, x = (int(x) for x in input().split()) x -= 1 ops.append((c,x)) if c == 1: cut.add(x) for i in range(L-1): if i not in cut: dsu.merge(i, i+1) ans = [] for c, x in ops[::-1]: ...
# Write classes for the following class hierarchy: # # [Vehicle]->[FlightVehicle]->[Starship] # | | # v v # [GroundVehicle] [Airplane] # | | # v v # [Car] [Motorcycle] # # Each class can simply "pass" for its body. The exercise is about setting up # the hie...
from .base_repository import BaseRepository from web_app.models import UserPost class PostRepo(BaseRepository[UserPost]): model = UserPost
from dataclasses import dataclass class Error(Exception): pass @dataclass class ConfigError(Error): code = 10000 desc = "Config file error." @dataclass class InputError(Error): code = 20000 desc = "Input invalid" @dataclass class ParameterError(Error): code = 20001 desc = "Parameter ...
# Generated by Django 3.2.5 on 2021-07-10 00:46 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('profiles', '0008_auto_20210708_1557'), ] operations = [ migrations.RemoveField( model_name='question', name='answers...
import numpy as np import math from scipy.integrate import simps from sfepy.linalg import norm_l2_along_axis import scipy.interpolate as si class RadialVector(object): @staticmethod def from_xy(x, y): return RadialVector(ExplicitRadialMesh(x), y) @staticmethod def from_file(file): arr...
# -*- coding: utf-8 -*- import scrapy from .myselector import Selector as S import json from user_agent import generate_user_agent from Sac.items import SacItem import time import urllib.parse from spiders.localConfigs import * maxtry = 3 #构造页面检查方法,用于页面的重试 def trytime_(response): if response.meta.get('maxtrys'):...
#!/usr/bin/env python # coding: utf-8 # In[2]: import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns import warnings warnings.filterwarnings('ignore') # In[3]: #View To The Existing Raw Data data = pd.read_csv('playstore-analysis .csv') data # In[4]: data.columns # ...
# -*- coding: utf-8 -*- """ Created on Tue Jan 23 09:39:20 2018 @author: kad017 """ import numpy as np #import matplotlib.pyplot as plt m=16 data=np.arange(m) data=data.reshape(-1,np.sqrt(m)) print data var_orig=np.var(data) print var_orig,'orig var' rows,col=data.shape print rows,"rows" column_t=np.transpose(da...
import itertools def loadFile(filename): D=[] f=open(filename,"r") transactions=0 for line in f: T = [] transactions += 1 for word in line.split(): T.append(word) if word not in C1.keys(): C1[word] = 1 else: cou...
#!/usr/bin/python from __future__ import print_function import time import argparse import ConfigParser import pprint from scrapers.agis import AGIS # EOL is near from scrapers.rebus import REBUS # EOL is near from scrapers.cric import CRIC from scrapers.grafana import Grafana from scrapers.elasticsearch import El...
from MongoNodeService import TxMongoNodeService from RawStorageService import TxRawStorageService class TxCms(object): ''' storageConfig format: storageConfig = { 'RawStorageService':{ 'ssid':'rootdir', }, } ''' def __init__(self,mongodb,storagesC...
from bs4 import BeautifulSoup import urllib import requests import re #定义一个getHtml()函数 def getHtml(url): page = urllib.request.urlopen(url) #urllib.urlopen()方法用于打开一个URL地址 html = page.read() #read()方法用于读取URL上的数据 return html def getImg(link,html): html = html.decode('utf-8') # python3 reg = r'src=...
import abc class Controller: __metaclass__ = abc.ABCMeta K_UP = 'UP' K_DOWN = 'DOWN' K_LEFT = 'LEFT' K_RIGHT = 'RIGHT' K_A = 'A' K_B = 'B' K_X = 'X' K_Y = 'Y' K_START = 'START' K_BACK = 'BACK' K_GUIDE = 'GUIDE' RS_H = 'RS_H' RS_V = 'RS_V' LS_H = 'LS_H' L...
import tensorflow as tf from os import listdir from os.path import isfile, join graph_file_name = '/root/projects/dogvscat/model/classify_image_graph_def.pb' input_dir = '/root/projects/dogvscat/test' prediction_list = [] labels=['cat', 'dog'] image_files = [f for f in listdir(input_dir) if isfile(join(input_dir, f))...
from tensorflow.examples.tutorials.mnist import input_data import tensorflow as tf mnist = input_data.read_data_sets("MNIST_data/", one_hot = True) X = tf.placeholder(tf.float32) Y = tf.placeholder(tf.float32) W = tf.Variable(tf.random_normal([784, 784]), name='weight') b = tf.Variable(tf.random_normal([784...
import numpy from generalised_least_squares import * # max for numpy arrays max_ = numpy.vectorize(lambda x, y: (x, y)[x < y]) class unit_fo(object): def __call__(self, x): return 1.0 class linear_fo(object): def __init__(self, i): self.__i = i def __call__(self, x): return x[self.__i] class quadrat...
# coding=utf-8 # Copyright (c) 2015 EMC Corporation. # All Rights Reserved. # # 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 # #...
# Author: Spencer Mae-Croft # Date: 08/31/2020 from name_function import get_formatted_name print("Enter 'q' at any time to quit the application.") while True: first = input("\nPlease enter your first name: ") if first.lower() == 'q': break last = input("\nPlease enter you last name: ") ...
# LeetCode Medium # Product of Array Except Self Question # Must be solved in O(n) time and CANNOT use division class Solution: # O(n) time # O(1) space since they don't count return array as extra space def productExceptSelf(self, nums: List[int]) -> List[int]: n = len(nums) ret = [None]...
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.response.AlipayResponse import AlipayResponse from alipay.aop.api.domain.MicroPayOrderDetail import MicroPayOrderDetail class AlipayMicropayOrderGetResponse(AlipayResponse): def __init__(self): super(AlipayMicropayOrderGetResp...
""" 生成随机测试数据 """ import numpy as np from config import * def gen_data(n=config_dense.data_size, input_dim=config_dense.input_dim, attention_column=config_dense.attention_column): """生成随机数据 数据特征: x[attention_column] = y 网络应该学习到 y = x[attention_column],这是为了测试 attention 特意构造...
# -*- coding: utf-8 -*- from django.db import models import datetime from django.utils import timezone from cms.models import CMSPlugin class Poll(models.Model): question = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __unicode__(self): return self.q...
vars = Variables() vars.Add(PackageVariable('boost', 'boost installation directory (should contain boost/ and lib/)', 'yes')) vars.Add('compiler', 'compiler command to use', 'g++') env = Environment(variables = vars) if env['boost'] == True: dir = '/usr/local/include' env['boost'] = dir if env['boost']: env.A...
from otree.api import ( models, widgets, BaseConstants, BaseSubsession, BaseGroup, BasePlayer, Currency as c, currency_range ) import random doc = """ The English registration form for Public Goods Game """ class Constants(BaseConstants): name_in_url = 'PGGRegiEN' players_per_group = 4 num_round...
from django.db import models class Comments(models.Model): text = models.TextField("Комментарий") created = models.DateTimeField("Дата добавления", auto_now_add=True, null=True) class Meta: verbose_name = "Комментарий" verbose_name_plural = 'Коментарии' def __str__(self): re...
# -*- coding: utf-8 -*- import scrapy class TopSeriesWeekSpider(scrapy.Spider): name = 'top_series_week' start_urls = ['http://www.adorocinema.com/series-tv/top/'] def parse(self, response): series = response.xpath('//a[@class="meta-title-link"][contains(@href, "/series/serie")]') for ser...
from base.vector3 import Vector3 from scene.objects.transformablesceneobject import TransformableSceneObject class Screen(TransformableSceneObject): floats_per_vertex = 5 chars_per_vertex = 0 bytes_per_vertex = floats_per_vertex*4 + chars_per_vertex*1 def __init__(self, a, b, c, d): Transforma...
# coding=utf-8 from flask import Flask app = Flask(__name__) @app.route('/', methods=['GET']) def index(): return '<h1>Index</h1>' @app.route('/hello', methods=['GET']) def hello(): return '<h1>Hello</h1>' if __name__ == '__main__': app.run()
from flask import Flask, render_template from flask_sockets import Sockets from GDT import * import json, yaml app = Flask(__name__) sockets = Sockets(app) config = yaml.safe_load(open('config.yml', 'r')) gdt = GDT(config['db']['connection'], config['db']['datatype'], config['coordinates']['sw'], config['coord...
import configparser from selenium import webdriver import os.path from framework.logger import Logger import time logger = Logger(logger="BrowserEngine").getlog() class BrowserEngine(object): dir = os.path.dirname(os.path.abspath('.'))#获取相对路径方法 chrome_driver_path = dir +'/tools/chromedriver.exe' def __...
#!/usr/env python from twisted.internet.protocol import DatagramProtocol from twisted.internet import reactor from twisted.internet.task import LoopingCall import hashlib import time import re from struct import * import random from datetime import datetime from util import * from hashdb import * from getinfo import ...
# Generated by Django 3.1.7 on 2021-04-12 21:26 import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('notes', '0004_auto_20210412_2355'), ] operations = [ migrations.AddField( model_name='note', name='u...
#!/usr/bin/python """ Parse YNAB4's budget data to work out how much is left in the current month. Designed for an Alfred 2 Workflow Written by James Seward 2013-07; http://jamesoff.net; @jamesoff Thanks to @ppiixx for pointing out/fixing the rollover problem :) BSD licenced, have fun. Uses the alp library from ht...
#!/usr/bin/env python import modeltools.hycom import modeltools.tools import argparse import datetime import matplotlib matplotlib.use('Agg') import matplotlib.pyplot import abfile import numpy import netCDF4 import logging import re import cfunits import os import os.path # Set up logger _loglevel=logging.INFO logger...
from rest_framework import viewsets from .serializer import TaskSerializer from task.models import Task class TaskListViewSet(viewsets.ModelViewSet): queryset = Task.objects.all() serializer_class = TaskSerializer
#!/usr/bin/env python # -*- encoding: utf-8 -*- ''' @File : dataset.py @Contact : xxzhang16@fudan.edu.cn @Modify Time @Author @Version @Desciption ------------ ------- -------- ----------- 2021/8/9 19:52 zxx 1.0 None ''' # import lib from torch.utils.data import DataLoa...
import sys class BarkClient: def authenticate(self, username, password): print >> sys.stdout 'Bark Client Authenticate Called' def
# moving average smoothing as feature engineering from pandas import Series from pandas import DataFrame from pandas import concat series = Series.from_csv('daily-total-female-births.csv', header=0) df = DataFrame(series.values) width = 3 lag1 = df.shift(1) lag3 = df.shift(width - 1) window = lag3.rolling(window=width)...
#coding: utf-8 from __future__ import division, absolute_import, print_function, unicode_literals from .version import version # kasaya client calls from kasaya.core.client import sync, async, trans, control # worker task decorator from kasaya.core.worker.decorators import * # worker class from kasaya.core.worker.wor...
def balanced(input_string): print(input_string) parenCount = 0 for c in input_string: if c == '{': parenCount += 1 continue if c == '}': if parenCount == 0: return False parenCount -= 1 if parenCount == 0: return T...
# -*- coding: utf-8 -*- # Generated by Django 1.9.7 on 2016-08-10 23:10 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('buildboard_app', '0012_auto_20160810_2303'), ] operations = [ migrations.Alt...
import torch.nn as nn from mmcv.cnn import (build_conv_layer, build_norm_layer, constant_init, kaiming_init) from mmcv.runner import load_checkpoint from torch.nn.modules.batchnorm import _BatchNorm from mmdet.utils import get_root_logger from ..builder import BACKBONES from ..utils.activations i...
from tkinter import * from rumorFunctions import * from random import randint import tkinter.simpledialog as simpleDialog from math import sin, cos from tkinter.colorchooser import * class NetworkFrame: def __init__(self, master): self.canvas = Canvas(master) self.canvas.pack(side = LEFT, fill = BOTH, e...
import matplotlib matplotlib.use('Agg') ''' author: Karel Klein Cardena userID: kkc3 ''' import numpy as np import pandas as pd import datetime as dt import matplotlib.pyplot as plt import StrategyLearner as sle from marketsimcode import compute_portvals def assess_portfolio(portfolio, sv): #takes in a norm...
from django import forms from .models import TaxP class taxform(forms.ModelForm): class Meta: model=TaxP fields=[ 'q1', 'q2', 'q3', 'q4', 'q5', ] labels = { 'q1':'Question 1', 'q2': 'Question 2', ...
''' Created on Mar 17, 2017 Client implementation of UDP echo @author: Christopher Blake Matis ''' #include Python's socket library from socket import* #set variables serverName and serverPort serverName = '172.16.0.5' serverPort = 12000 while 1: #create UDP socket for server clientSocket = socket(AF_I...
import matplotlib.pyplot as plt import gym import numpy as np import cv2 # 输入 N个3通道的图片array # 输出:一个array 形状 (84 84 N) # 步骤: 1. resize ==>(84 84 3)[uint 0-255] # 2. gray ==> (84 84 1) [uint 0-255] # 3. norm ==> (84 84 1) [float32 0.0-1.0] # 4. concat ===>(84 84 N) [float32 0.0-1.0] #resize a img d...
class Solution: def letterCasePermutation(self, S: str) -> List[str]: result = [S] for i, c in enumerate(S): if c.isalpha(): result.extend([s[:i] + c.swapcase() + s[i+1:] for s in result]) return result class Solution: def let...
import numpy as np import meep eV_um_scale = 1/1.23984193*1e6 def drude_lorentz_material(freq, gamma, sigma, eps_inf=1, multiplier=1): """return a drude-lorentz material, where the first index is the Drude term""" freq, gamma, sigma = map(np.atleast_1d, [freq, gamma, sigma]) Npoles = len(freq) susc ...
from pyparsing import ( Empty as PpEmpty, Forward as PpForward, Keyword as PpKeyword, Literal as PpLiteral, Suppress as PpSuppress, Word as PpWord, QuotedString as PpQuotedString, Regex as PpRegex, Optional as PpOptional, White as PpWhite, oneOf, infixNotation as PpInfixN...
# String indexing str0 = 'Tista loves chocolate' print(len(str0)) print(str0[3]) # String slicing print(str0[5:7]) print(str0[4:7]) # String mutation # Strings are not 'mutable'; they are called immutable str0[3] = 'z' print(str0) s2 = 'New York' zip_code = 10001 # The following is called string concatenation pr...
#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import division # Python 2.7 import re import curses, sys, os, signal,argparse,time from multiprocessing import Process from scapy.all import * from subprocess import call, PIPE from datetime import date, time, datetime import os, sys from PyQt4 import QtCo...
import sys from collections import Counter # counter: 각 요소별 갯수 count해서 dictionary def mean(num): return round(sum(num)/n) def median(num): if n ==1: return num[0] else: return num [n // 2] def most(num): b_list = [] if n ==1: return num[0] else: ...
import json from prepare_text import TextPreparation class ComposeData: def __init__(self, mapping, file_write): self._mapping = mapping self._file_write = file_write def get_data_from_file(self): data_and_type_mapping = {} for file_name, type in self._mapping.items(): ...
import unittest from unittest.mock import Mock from time import sleep from zmqmw.implementations.notifier.publisher.PublisherNotifierStrategy import PublisherNotifierStrategy from zmqmw.implementations.proxy.BrokerProxyStrategy import BrokerProxyStrategy from zmqmw.implementations.proxy.publisher.PublisherProxyStrategy...
from datetime import datetime class Group(object): def __init__(self, client, id, name, **kwargs): self.client = client self.id = id if len(name) < 1: raise("Group name cannot be < 1 chars") else: self.name = name self.display_name = name ...
import abc class Cipher(metaclass=abc.ABCMeta): """Abstract base class for cipher.""" @abc.abstractmethod def encryptor(self): """Return the encryptor context.""" @abc.abstractmethod def decryptor(self): """Return the decryptor context.""" @abc.abstractmethod def encrypt...
import time import numpy as np import pandas as pd import matplotlib.pyplot as plt import time import random from sklearn.datasets import load_breast_cancer from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split from sklearn import svm from sklearn.model_selectio...
""" Comprehensive range of techniques : 1 . Using scaling on the KNN model to see the improvement in results """ from knn_model import * from part_1_oop import BasicKnn from part_2_a import WeightedKnn class ScaledKnn: def __init__(self, train_file, test_file, _plotgraph=False): """ :param trai...
# -*- coding: utf-8 -*- import logging __author__ = '''hongjie Zheng''' __email__ = 'hongjie0923@gmail.com' __version__ = '0.0.1' logging.basicConfig(level=logging.INFO, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s: %(message)s') from PyEventEmitter.EventEmitter import EventEmitter __all__ = [...
#!usr/bin/python import os import sys os.system("yum install sshpass -y") os.system("yum install nmap -y") os.system("nmap 192.168.0.0/24 -oG /root/Desktop/project/ip1.txt") os.system('cat /root/Desktop/project/ip1.txt|grep ssh|grep open|cut -f2 -d " ">/root/Desktop/project/ips.txt') os.system("mkdir /root/Desktop/pr...
# convert a string in short form s1= raw_input("enter a string :") s1=" "+s1 c=0 k=0 for i in range(0,len(s1),1): if(s1[i]==' ' and c<=2): if(c<=1): print s1[i+1],".", c=c+1 k=i+1 print s1[k:len(s1)]
# -*- coding: utf-8 -*- """ Created on Thu Sep 03 18:28:58 2015 @author: Jye Smith NEMA NU 2-2007 Set 'PathDicom' to dir with dicom files. Can calculate FWHM of up to 3 points sources in a image. """ ## https://pyscience.wordpress.com/2014/09/08/dicom-in-python-importing-medical-image-data-into-numpy-with-pydicom-a...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import numpy as np import cantera as cant ## Constants ## Do = .25 #in N_tubes = 56 kr = .015 L_tot = 14 #in L = 4 #in Ao = np.pi*Do*N_tubes*L_tot w_tube = .022 Di = .25 - 2*w_tube Ai = np.pi*N_tubes*L_tot Kp = 16.3 Cp_w_in_tube = 75.364 rho_w = 54240 Tsat25 = 403.57 Tsat...
import json from django.utils.functional import cached_property from django.core.exceptions import ObjectDoesNotExist from django.views.generic import TemplateView from .models import Article, Chapter, Definition def get_definitions(article): return json.dumps({ definition_object.term: definition_object...
import moduldemo ret = moduldemo.add(10,20); print("Additiom is",ret); ret = moduldemo.sub(10,20); print("subtraction is",ret); ret = moduldemo.mult(10,20); print("multipliction is",ret); ret = moduldemo.div(10,20); print("division is",ret);
import logging from TestProject import TestProject import Params from FXpathSeacher import XpathSearch from decimal import Decimal class WTest_Rep_11_1_v2(TestProject): '''Class for user's 1 test ''' test_config = Params.params_1 tproperty_page = { "row_count" : 0, ...
__author__ = 'B.Ankhbold' from sqlalchemy import Column, String, Float, Date, ForeignKey, Integer, Table from sqlalchemy.orm import relationship from geoalchemy2 import Geometry from ClLanduseType import * class CaParcelConservation(Base): __tablename__ = 'parcel_conservation' gid = Column(Integer, primary...
import scrapy from scrapy.spiders import CrawlSpider, Rule from scrapy.linkextractors import LinkExtractor class SeedcollectionSpider(CrawlSpider): name = "seedcollection" allowed_domains = ["theseedcollection.com.au"] def __init__(self, tag=None, *args, **kwargs): super().__init__(*args, **k...
################ here we are checking the Second example ############################### import datetime d={'2020-01-01':4,'2020-01-02':4,'2020-01-03':6,'2020-01-04':8,'2020-01-05':2,'2020-01-06':-6,'2020-01-07':2,'2020-01-08':-2} D={} for ele in d: dt=ele year, month, day = (int(x) for x in dt.split('-')) #...
"""Demonstrate all business related API endpoints. This module provides API endpoints to register business, view a single business, view all businesses. """ from flask import Blueprint, abort, request from flask_restful import (Resource, Api, reqparse) from app import business class BusinessRecord(Resource): ...
import numpy as np import matplotlib.pyplot as plt zare_data_AB_cnn_30_epochs = np.load('CNN_AB_zare_classifier_30_epochs.npy') zare_data_AB_rnn_30_epochs = np.load('zare_data_AB_rnn_30_epochs.npy') class_data_all_cnn_30_epochs = np.load('CNN_class_all_letters_classifier_30_epochs.npy') class_data_all_rnn_30_epochs = ...
import numpy as np import pandas as pd import pandas_datareader as pdr import datetime import logging import math from sklearn.preprocessing import StandardScaler from action import Action #################################### # TODO: remove this after API update from pandas_datareader.google.daily import GoogleDaily...
import unittest from selenium import webdriver from selenium.webdriver.common.by import By import time class testClass(unittest.TestCase): driver = None @classmethod def setUpClass(cls): baseURL = "http://tagonsupport.cubixsource.com/administrator/login" cls.driver = webdriver.Chrome("C:\...