text
stringlengths
8
6.05M
import numpy as np import scipy.stats def sample_variance( data ) : # Your code to calculate the sample variance from the data in # the numpy array called data goes here def testStatistic( data1, data2 ) : # Your code to compute the test statistic should be inserted here. # Remember to use calls to sa...
#title : insertsort.py #description : Sorting a set of numbers stored inside an array using insertion sort algorithm. #author : Ramadhi Irawan #date : 2014-10-07 #version : 0.2 #usage : python insertsort.py #notes : Information about bubble sort: http://en.w...
import re from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, SubmitField, BooleanField, ValidationError, IntegerField, TextAreaField from wtforms.validators import Length, Email, EqualTo, DataRequired, Optional from jobplus.models import db, User, Company, CompanyDetail class UserProfileF...
""" Constants for the API requests """ CHOSEN_FIELDS = [ "product_name_fr", "generic_name_fr", "code", "url", "brands", "nutrition_grades", "nova_groups", "pnns_groups_1", "pnns_groups_2", "stores", "image_url", "nutriments", "categories" ]
''' CC253x support is contributed by Scytmo. ''' # Import USB support depending on version of pyUSB try: import usb.core import usb.util import sys print >>sys.stderr, "Warning: You are using pyUSB 1.x, support is in beta." except ImportError: import usb print >>sys.stderr, "Error: You are usin...
# %% r = 123_456 + 1_000_000 + 1000 print(r) # %% f = 1.0e-3 print(f) # %% s = """ This is the first line. This is the second line. """ print(s) type(s) # %% # SyntaxError: EOL while scanning string literal s2 = ''' This is the first line.\ This is the second line. ''' print(s2) # %% s3 =...
from LinkedList import LinkedListNodes class DoublyLinkedList: def __init__(self, sourceList: list): self.headOfList: LinkedListNodes.DoublyLinkedNode or None = None self.tailOfList: LinkedListNodes.DoublyLinkedNode or None = None self.length = len(list) for value in sourceList: ...
import sys import pickle import numpy as np import matplotlib.pyplot as plt import seaborn as sns def main(): d = pickle.load(open('ram/gain_fcn.pickle', 'rb')) npoints = 161 nxtals = 54 nbunches = 8 calos = [1] xtals = range(54) bunches = [-1, 1, 2, 3, 4, 5, 6, 7, 8] d_tags = {} ...
#!/usr/bin/env python2.7 # coding: utf-8 import os, signal, datetime, time, subprocess, re, argparse, json def safe_exit(signum, frame): print "\r[catch sig int]" exit() signal.signal(signal.SIGINT, safe_exit) def main(pid, json_output): io_sum = fetch_io(pid) order = convert_to_order(io_sum) if (not json_...
from rest_framework import serializers from .models import Product class ProductSerializer(serializers.HyperlinkedModelSerializer): product_image = serializers.ImageField(max_length=None, allow_empty_file=False, allow_null=True, required=False) class Meta: model = Product fields = ( 'id', ...
from django.conf.urls import url from . import views app_name = 'comments' urlpatterns = [ url(r'articles/$', views.articles, name='articles'), url(r'article/(?P<article_id>\d+)/$', views.article, name='article'), url(r'article/addcomment/(?P<article_id>\d+)/$', views.addcomment, name='addcomment'), ]
from typing import List class Solution: def maxSubArray(self, nums: List[int]) -> int: max = nums[0] localMax = 0 for num in nums: if num > localMax+num: localMax = num else: localMax += num if localMax > max: ...
import matplotlib import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns tips = sns.load_dataset('tips') print(tips.head()) sns.boxenplot(x='day', y='total_bill', hue='smoker', data=tips) plt.show() tips = sns.load_dataset('tips') flights = sns.load_dataset('flights')...
#!/usr/bin/env python # coding=utf-8 from flask import Flask from database import DB from models.mappoint import MapPoint def create_app(config): app = Flask(__name__) app.config.from_pyfile('server.cfg') app.config['TESTING'] = True # app.config['TEMPLATES_AUTO_RELOAD'] = True DB.init(app....
from __future__ import print_function,division import os.path import argparse import shutil import time from data_prepare.bulid_data import * from layer.voxel_verydeepnet import MulitUpdateNet_verydeep,weights_init from layer.voxel_func import CrossEntropy_loss from torch.autograd import Variable is_GPU=torch.cuda....
# Generated by Django 2.2.6 on 2020-08-13 04:43 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('account', '0001_initial'), ] operations = [ migrations.CreateModel( name='Pdfs', fields=[ ('id', mod...
# 1,0,22,150,       - Unassigned (Released 18 October 2005), s = """0,0,0,0,EOOL - End of Options List,[RFC791][Jon_Postel] 0,0,1,1,NOP - No Operation,[RFC791][Jon_Postel] 1,0,2,130,SEC - Security,[RFC1108] 1,0,3,131,LSR - Loose Source Route,[RFC791][Jon_Postel] 0,2,4,68,TS - Time Stamp,[RFC791][Jon_Po...
# 将数据转换成 josn可以识别的字典类型 def dobule_to_dict(v): result = {} for key in v.__mapper__.c.keys(): result[key] = getattr(v, key) # if getattr(v, key) is not None: # result[key] = getattr(v, key) # else: # result[key] = getattr(v, key) return result def to_json(all...
import webbrowser #To the strangers to python #You know the codes and so do i if __name__ == "__main__": webbrowser.open("https://youtu.be/dkWjvAc0jLQ?autoplay=1")
x1 = -12 y1 = -4 x2 = 4 y2 = 6 slope = (y2-y1) / (x2-x1) print(slope)
#Author: Satwik Bhattamishra import tensorflow as tf import numpy as np import tensorflow.examples.tutorials.mnist.input_data as input_data from pnmf import PNMF import numpy.linalg as LA def dpnmf(hidden_units= 500, prob=0.4, lambd= 0.4, alpha= 0.2, beta= 0.2): ###### Denoising Autoencoder ###### # Parameter Decla...
n = int(input("Enter n: ")) factorial = 1 count = 1 while count <= n: factorial *= count count += 1 print(factorial)
import datetime # timezone naive - nieświadome datetime.datetime.now() datetime.datetime(1957, 10, 4, 19, 28, 34) # timezone aware - świadome datetime.datetime.utcnow() datetime.datetime.now(tz=datetime.timezone.utc) datetime.datetime(1957, 10, 4, 19, 28, 34).replace(tzinfo=datetime.timezone.utc)
#!/usr/bin/env python from collections import MutableMapping AVG_LENGTH = 10 class SensorDB(MutableMapping, dict): def __init__(self): self._observers = [] def __getitem__(self,key): return dict.__getitem__(self,key) def __setitem__(self, key, value): dict.__setitem__(self,key,v...
""" Url mappings with appropriate functions to handle them """ import notifications.urls from django.urls import path, include from django.contrib.auth import views as auth_views from django.conf.urls import url from django.contrib.auth.decorators import login_required import sap.views_v2 import sap.views_v3 from . im...
import pygame from settings import * from support import * from timer import Timer class Player(pygame.sprite.Sprite): def __init__(self, pos, group): super().__init__(group) self.import_assets() self.status = 'down_idle' self.frame_index = 0 # general setup ...
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ c = 0; tmpnode = head...
""" We downloaded the Spitzer (CASSIS) and Herschel PACS spectra for B1-a. Let's access it. """ from __future__ import division import os import numpy as np import matplotlib.pyplot as plt import astropy.table from astroquery.simbad import Simbad from access_irac_mips_data import E09_ids, young15_table cassis_da...
#!/usr/bin/env python3 """プロジェクト作成後の処理。""" import os import subprocess def _main(): url = "git@github.com:ak110/pytoolkit.git" url = os.environ.get("_PYTOOLKIT_URL", url) # pytoolkitを追加してInitial commit subprocess.run("git init", shell=True, check=True) subprocess.run(f"git submodule add {url} pyt...
#!/usr/bin/env python2.7 """ Acts as a server for RPI, checks wifi connection, checks reddit messages LAST UPDATED: 26 JUN 2016 """ from time import sleep import os import sys import datetime import subprocess import traceback import logging import logging.handlers import urllib2 import praw def check_messages(r): ...
#!/usr/bin/env python # imports import sys import numpy as np import json import numpy as np # ros imports import rospy from path_planning import toQuaternion from std_msgs.msg import String, ColorRGBA from geometry_msgs.msg import Pose, PoseStamped, Point, Quaternion, Vector3 from visualization_msgs.msg import Mark...
from devices.v2.schemas import ErrorResponse from marshmallow import ValidationError from requests import HTTPError class APIDevicesV2Error(Exception): code: str = None detail: str = None source: dict = None status_code: int = None def __init__(self, code, detail, source, status_code): if...
import sys import re tr_name = sys.argv[1] res = re.split(r'\.S\d+', tr_name) name = res[0] f2 = open('/tmp/name.txt', 'w') f2.write(name) f2.close
from vehicle import vehicle class car(vehicle): ac = 0 steering_wheel= None seat_belt = None audio_play = None no_of_wheels = 0 def __init__ (self,ac,steering_wheel,seat_belt,audio_play,no_of_wheels,speed,weight,mileage,color): self.ac = ac self.steering_wheel = steering_wheel self.seat_belt = seat_belt...
from marshmallow import (ValidationError, validate, ) from models.users import FoodieUser from models.admins import FoodieAdmin from models.shops import FoodieShop, Product, Order from utils.maps import is_coordinate password_validate = validate.Length(min=6) def em...
# # This program demonstrates recursive bubble sorting # import os import sys def bubble_sort(arr): for i, num in enumerate(arr): try: if arr[i+1] < num: arr[i] = arr[i+1] arr[i+1] = num bubble_sort(arr) except IndexError: p...
#String rotation
import numpy as np # skleran / tensorflow / keras 에서 교육용 데이터 제공 from sklearn.datasets import load_boston # 1. 데이터 dataset = load_boston() x = dataset.data y = dataset.target print(x.shape) # (506, 13) print(y.shape) # (506, ) print('************************************') print(x[:5]) print(y[:10]) print('*******...
# Generated by Django 2.0.7 on 2019-01-09 12:09 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('basedata', '0044_auto_20190109_1122'), ] operations = [ migrations.AddField( model_name='device', name='tiaojian', ...
""" command-line interface for hinoki """ import click import os import hinoki.import_definitions import hinoki.assets import hinoki.validate @click.group() @click.version_option() def main(): pass @main.command() def imports(): hinoki.import_definitions.import_defs() @main.command() def build_assets(): ...
#!/usr/bin/python3 # coding:utf-8 # 评估CIFAR-10模型的预测性能 from __future__ import absolute_import from __future__ import division from __future__ import print_function from datetime import datetime import math import time import numpy as np import tensorflow as tf from cifar10 import cifar_10 FLAGS = tf.app.flags.FLAGS...
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-09-25 08:56 from __future__ import unicode_literals from django.conf import settings import django.contrib.postgres.fields import django.contrib.postgres.fields.jsonb from django.db import migrations, models import django.db.models.deletion import uuid import ...
from django.db import models from django.utils import timezone class Post(models.Model): #defines our model * class indicates that the object is defined #Post name of our model #models.,odel the model is a Django Model so Django saves in Database author = models.ForeignKey('auth.User', on_delete=models.CASCADE) ...
import json import tweepy as tweepy import re import random import sys from collections import defaultdict, Counter import os import logging # tweepy auth = tweepy.OAuthHandler(consumer_token, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) #https://eli.thegreenpla...
# def find_all_index(text, pattern): # pattern_index = 0 # match = [] # # if pattern is empty, then return all indices # if pattern == '': # for index in range(len(text)): # match.append(index) # return match # for index, charc in enumerate(text): # # check if let...
from uuid import UUID from markupsafe import Markup from onegov.core.request import CoreRequest from onegov.org.models import Topic from onegov.org.views.people import person_functions_by_organization from onegov.people import Person def test_people_view(client): client.login_admin() settings = client.get('/m...
#!/usr/bin/python import unittest def find_iface_via_ip(data, _ip): """ Find Iface details from ansible_facts Arg: _ip: IP address to match Returns: Attributes of found interface or None. """ _ansible_facts = data.get('ansible_facts') iface_list = _ansible_facts.get('ansible_interfaces'...
import base64 from botInfo import self_id def read_file(filename, encrypt=False): if encrypt: with open(filename, 'rb') as f: return base64.b64decode(f.read()).decode('utf-8') else: with open(filename, 'r') as f: return f.read() def write_file(content, filename, encry...
#*************************************************************************** #* * #* Copyright (c) 2011 * #* Yorik van Havre <yorik@uncreated.net> * #* ...
# 找到一个树的最下层的最左边的值。使用BFS算法,每一层的 # 节点值作为一个list扔到一个list中,从根向下遍历,直到 # 最底层。返回list的最后一个的第一个值即可 # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def findBottomLeftValue(self, root): """ ...
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Author: shoumuzyq@gmail.com # https://shoumu.github.io # Created on 16/2/29 22:03 def rotate(matrix): n = len(matrix) for i in range(n // 2): for j in range(i, n - 1 - i): matrix[i][j], matrix[j][n - 1 - i] = matrix[j][n - 1 - i], m...
from django.shortcuts import render from api.serializers import UserSerializer, TemperatureSerializer from django.contrib.auth.models import User from rest_framework import routers, serializers, viewsets from temperature.models import Temperature class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.al...
from sympy import Limit, Symbol, S x = Symbol('x') print(Limit(1/x, x, S.Infinity).doit())
''' install: pip install openpyxl pip install pandas pip install xlrd ''' import collections import openpyxl from openpyxl.chart import BarChart, Reference import pandas as pd excel_bookname = 'file/ブック名.xlsx' data_sheet_name = '集計データ' result_sheet_name = '集計結果' target_column = '集計カラム' # 集計 df_data = pd.read_e...
from utils import * from log_utils import * from tqdm import tqdm from Data.data_loader import DataLoader import time import numpy as np from Evaluation.Reviewer import Reviewer class Trainer(object): def __init__(self,model, args, reviewer=None): self.args=args self.context=args.context ...
from flask_admin.contrib.sqla import form from flask_admin.contrib.sqla import fields from flask_admin._backwards import get_property from flask_admin.model.helpers import prettify_name from flask_admin.model.form import converts from shelf.plugins.order import OrderingInlineFieldList from wtforms import fields from pr...
from rest_framework.views import exception_handler as drf_exception_handler import logging from django.db import DatabaseError from rest_framework.response import Response from rest_framework import status from utils.constants import RET, Info_Map from pymysql.err import OperationalError # 获取在配置文件中定义的logger,用来记录日志 log...
import os import re import json import sys os.chdir(os.path.dirname(__file__)) sys.path.append("..") from tool.append_to_json import AppendToJson def extract_item(origin_sentence): prefixItem = "" sub_len = 0 first_num_cnt = 0 first_dot_cnt = 0 for i in range(len(origin_sentence)): c = origin_sentence[i] if c...
import getpass import os from client_database_connection import mycursor from config import * # functions def effect(): os.system("cls") print(''' __ ________ _ _ ____ _____ _______ \ \ / / ____| | | | |/ __ \ / ____|__ __| \ \ /\ / /| |__ ______| |__| ...
#!/usr/bin/env python # -*- coding: utf-8 -*- from structural_patterns.flyweight.large_size_string import LargeSizeString ''' Display a string consisting of large characters (0-9 digits only). Large character objects are not created until they are needed. And the created objects are reused. Example Output ----- Pleas...
from __future__ import print_function import sys import os sys.path.append(os.getcwd()) #[ guide_mixed_cpp_python_part_py import histogram as bh import cpp_filler h = bh.histogram(bh.axis.regular(4, 0, 1), bh.axis.integer(0, 4)) cpp_filler.process(h) # histogram is filled with input values in C++ ...
from django.conf.urls import patterns, include, url from django.contrib import admin from userauth.views import * from phoneinfo.views import * from phonechange.views import * urlpatterns = patterns('', # Examples: # url(r'^$', 'zichanmanager.views.home', name='home'), # url(r'^blog/', include('blog.urls'))...
def send_mail(another): return another() def mail_body(): print("sending hello world !") return True send_mail(mail_body) body = mail_body body() def cal(another): return another def add(x, y): return x + y def sub(x, y): return x - y def multi(x, y): return x * y def calc_...
''' GCD Greatest common divisor is the largest number that divides the given numbers 1. find the divisors of a given number 2. find the greatest number that these lists have in common. Euclidean algorithm is the main algorithm uses for this purpose. Based on the principle that the greatest common divisor of two numbers...
'''config file''' import os '''the resource paths''' BGMPATH = os.path.join(os.getcwd(), 'resources/music/bgm.mp3') FONTPATH = os.path.join(os.getcwd(), 'resources/font/Gabriola.ttf') '''screen size''' SCREENSIZE = (400, 400) '''FPS''' FPS = 30 '''some constants''' BLOCK_SIZE = 20 BLACK = (0, 0, 0) GAME_MATRIX_SIZE =...
import tkinter as tk import mysql.connector as sqltor import turtle import math import random import winsound import time from datetime import date bulletstate = 'ready' score = 0 score1 = 0 c = 'a' e = 0 # login screen mycon = sqltor.connect(host='localhost', user='root', pass...
from typing import List import yaml class ObjectStatistic: def __init__(self, strength=None, endurance=None, intelligence=None, luck=None): self.__strength = strength self.__endurance = endurance self.__intelligence = intelligence self.__luck = luck @property def strength...
#!/usr/bin/env python ## TODO: ## fix Message to get email in "to" field instead of username] ## add graphs in dashboard and buttons in table ## complete database api ## add login system based on database ## transform getManager and users in a class like custom logger ## add patterns(chain of responsability, compo...
F = open('rnaseq.FASTA') Out = open('protein_seq.fasta','w') seq = '' for line in F: if line[0] == '>': header = line.split() geneID = header[0] Out.write(geneID + '_protein\n') else: seq = seq + line.strip() codonAMINO = { 'GCU':'A','GCC':'A','GCA':'A', 'GCG':'A', '...
# Generated by Django 3.2.4 on 2021-08-13 16:23 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('shop', '0009_specproduct_analog_pins'), ] operations = [ migrations.AlterField( model_name='specproduct', name='flas...
"""Version string of smbus2_asyncio.""" __version__ = "0.0.3"
''' author: juzicode address: www.juzicode.com 公众号: 桔子code/juzicode date: 2020.9.10 ''' print('\n') print('-----欢迎来到www.juzicode.com') print('-----公众号: 桔子code/juzicode \n') import socket import time def server(): #创建socket服务端实例 skt = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) #绑定端...
import eqparser import copyTree def asso(root): if root == None: return root; if root.leaf == '=': return 0 newRoot = 0 # Root Plus if root.leaf == '+': if root.children[0].leaf == '+': newRoot = copyTree.createTreeCopy(root) a = newRoot.children[0].children[0] b = newRoot.children[0].children[1] ...
from distutils.core import setup with open("requirements.txt") as f: requirements = f.read().splitlines() setup( name="mitm", version="1.1", author="Felipe Faria", packages=["mitm"], install_requires=requirements, long_description=open("README.md").read(), )
from __future__ import division import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import numpy as np import cv2 import matplotlib.pyplot as plt from .util import count_parameters as count from .util import convert2cpu as cpu from PIL import Image, ImageDraw def le...
import codecs import json import time from selenium.common.exceptions import NoSuchElementException from selenium import webdriver websites = ['https://warsawfoodie.pl/category/dzielnica/#page=1'] driver = webdriver.PhantomJS(executable_path=r'C:\Program Files (x86)\phantomjs-2.1.1-windows\bin\phantomjs.exe...
def palindrome_permutation(s): arr = list(s) perms = [] first_char = arr.pop(0) if len(arr) == 0: return [[first_char]] perms_returned = palindrome_permutation(arr) for perm in perms_returned: perm.insert(0, first_char) print "adding", perm perms.append(perm) ...
############################################################ ## 1. A face is drawn and at the topleft corner the face number is drawn. ## Each second, the face changes to more happy and then when it reaches the limit it reverses back to sad each ## second. ## The goal of the game is to press the [ENTER] key when the pl...
lst=[1,2,3,5,6,8,9,11] #lst slicing print(lst[1:3]) print(lst[:-1]) print(lst[-4:-1]) print(lst[:4]) print(lst[:])
"""Test HfsSql.""" from rayvision_houdini.HfsSql import getTableInfo_typs from rayvision_houdini.HfsSql import insertToTable def test_insertToTable(connect, cursor, refer_table): """Test inesrt to table function""" result = insertToTable(connect, cursor, refer_table, ["TYPES"], ["file"]) assert isinstanc...
import serial from oauthlib.oauth2 import BackendApplicationClient from oauthlib.oauth2 import TokenExpiredError from requests_oauthlib import OAuth2Session import requests import datetime # import all the neccessary libraries PORT = "/dev/ttyUSB0" BAUDRATE = "115200" # define the port and the baudrate ser = seri...
def sd1(X): print "i get %r" % X return 5 print sd1(raw_input(">")) #a = 30 #b = 5 #c = 78 #d = 4 #e = 90 #f = 2 #i = 100 #j = 2 #print "the puzzle is? %d" % (a+b+(c-d-i/j/2*e*f)) def subtract(a, b): print "SUBTRACTING %d - %d" % (a, b) return a - b def add(a, b): print "ADDING %d...
def authenticate(uname,pword): if uname=="Michael" and pword=="Mattson": return True else: return False
import server,simple,initial,userdata import os #needed files and folders if not os.path.exists("/home/"+userdata.username+"/GoogleDrive"): os.makedirs("/home/"+username+"/GoogleDrive") if not os.path.exists("/home/"+userdata.username+"/.GoogleDrive"): os.makedirs("/home/"+username+"/.GoogleDrive") #Runs to downlo...
#encoding:utf-8 import cx_Oracle import sys import select import Encoder import csv sys.path.append('..') import configure_info as configureInfo import results_save_send as sendweb from kafkaClass import Kafka_producer class Format_db: def __init__(self,modelpara_dict): self.modelpara_dict=modelpara_dict def ...
import discord from discord.ext import commands import json from discord.ext.commands import has_permissions class Admin(commands.Cog): def __init__(self, client): self.client = client self.filtered_words = ['idiot', 'Idiots', "DIE", "ass", "butt", "Fool", "shit", "bitch"] @command...
#! /usr/bin/env python # coding: utf-8 import serial, sys, time ser = serial.Serial("/dev/arduino485") ser.baudrate = 115200 tt = 0.5 while True : ser.write('p') ser.write('g') time.sleep(1) ser.write('P') ser.write('G') time.sleep(2)
import dill from . import scores as tn_scores class BaseScore: """ Base Class to construct custom score functions. """ def __init__(self, name: str = None): # TODO: name should not be optional """ Parameters ---------- name: Name of the score """...
import csv import math import numpy as np import pandas as pd import sklearn.tree as tree from sklearn.model_selection import KFold, permutation_test_score from sklearn.multiclass import OneVsRestClassifier from sklearn.neighbors import KNeighborsClassifier, KNeighborsRegressor from sklearn.preprocessing import LabelEn...
# -*- coding: utf-8 -*- """ Created on Thu Jun 22 14:48:25 2017 @author: Gavrilov """ """ a moduleis a .py file containing a collection Python definitions and statements """ pi = 3.14159 def area(radius): return pi*(radius**2) def circumference(radius): return 2*pi*radius
''' Copyright (c) 2013 Qin Xuye <qin@qinxuye.me> 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...
from collections import Counter S = input() T = input() E = [ set() for _ in range(26)] V = [0]*26 L = len(S) ans = 'Yes' for i in range(L): ords = ord(S[i])-97 ordt = ord(T[i])-97 E[ords] = ordt C = Counter(E) for x in C: if C[x] >= 2: ans = 'No' if ans == 'Yes': for i in range(26): ...
############################################################################### # Geospatial Operational Support Team @ The World Bank Group # Benjamin P. Stewart # Purpose: miscellaneous modules ############################################################################### import time, sys, os, csv, re, xlsxwriter,...
class Animal: def speak(self): raise NotImplementedError("Subclass needs to implement this method") class Dog(Animal): pass d = Dog() d.speak()
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-07-01 08:36 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('hood', '0005_join_social_ammenities'), ] operations = [ migrations.RenameModel( ...
import sys t = int(sys.stdin.readline()) def slv(a, b, xa, xb, la, lb): while xa < la or xb < lb: ca = 'z' if xa < la: ca = a[xa] cb = 'z' if xb < lb: cb = b[xb] if ca < cb: return 0 if cb < ca: return 1 xa += ...
import struct import inspect from ascetic_rpc.message_pb2 import Request, Response, Error, Chunk def write(wire, message): raw = message.SerializeToString() wire.write(struct.pack("<h", len(raw))) wire.write(raw) async def read(wire): rawsize = await wire.readexactly(2) size = struct.unpack("<h...
import os hostname = "google.com" #example response = os.system("ping " + hostname) if response==0: print ("Server is Alive") else: print ("Server is Down") print response
# Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute # Copyright [2016-2023] EMBL-European Bioinformatics Institute # # 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 ...
from pylgbst.movehub import MoveHub, TiltSensor, ColorDistanceSensor, EncodedMotor from pylgbst.comms.cpygatt import BlueGigaConnection import paho.mqtt.client as mqtt #import logging lastColor = None lastMotorEAngle = None def voltageCallback(value): print("Voltage: %s" % value) mqttc.publish("guitar/voltage...