text stringlengths 38 1.54M |
|---|
import matplotlib.pyplot as plt
from collections import deque
import random
import time
from queue import PriorityQueue
import numpy as np
from numpy.linalg import norm
import copy
import sys
import math
start_time = time.time()
dim = 10 #Dimensions of the maze
p = 0.3 #Probability of cell being occupied
fire_coordi... |
# https://atcoder.jp/contests/typical90/tasks/typical90_bl
# # def input(): return sys.stdin.readline().rstrip()
# # input = sys.stdin.readline
# from numba import njit
# from functools import lru_cache
import sys
input = sys.stdin.buffer.readline
# sys.setrecursionlimit(10 ** 7)
N, Q = map(int, input().split())
A = ... |
import matplotlib.pyplot as plt
def pic_show_raw(img, title='Image'):
pic_show(img, title, vmin=img.min(), vmax=img.max());
def pic_show(img, title='Image', vmin=0, vmax=1):
plt.gray();
plt.imshow(img, vmin=vmin, vmax=vmax);
plt.xticks([], []);
plt.yticks([], []);
plt.title(title);
... |
#!/home/paco/ubuntu/py3/bin/python
print(f"¿Qué estás pensando? \n>>>>" ,end=" ")
var_input = input().split()
var_cuenta = 0
for algo in var_input:
var_cuenta +=1
print(f"----> fueron {var_cuenta} palabras")
|
#思路:列好所有的可能然后排序
order = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1357902468'
print(*sorted(input(),key = order.index),sep='')
|
import FWCore.ParameterSet.Config as cms
class LoadPrerequisiteSource(cms.Source):
"""The class is a Source which loads prerequisites libraries in advance.
This is done to make sure we can load libraries containing common blocks in
the correct order.
"""
def setPrerequisites(self, *libs):
self.__d... |
import nltk
prp_thing = {"IT"}
prp_third_person = {"HE", "HIM", "SHE", "HER", "THEY", "THEM"}
prp_third_person_possessive = {"HIS", "HERS", "THEIRS"}
punctuation = {".", "!", "?"}
def anaphora(text):
return simple_anaphora(text)
# This function parses a text and attempts to perform anaphora resolution.
# It traver... |
import time,os
import torch
import shutil
import argparse
import torch.optim as optim
import torch.nn.init as init
import torch.utils.data as data
import torch.backends.cudnn as cudnn
from layers.functions import PriorBox
from layers.modules import MultiBoxLoss
from data import mk_anchors
from data import COCODetection... |
#---------------------------------------------------------------
# Name: Random Diffuse Colors
#
# Purpose: Create random diffuse colors to selected objects
# Author: Sakari Niittymaa
#
# Created: 27.4.2016
# Copyright: Copyright(c) 2016 Sakari Niittymaa
# http://www.niittymaa.com
#
#... |
from stackBasis.stack import Stack
def converter(dec_num, base):
digits = "0123456789ABCDEF"
stack = Stack()
while dec_num > 0:
rem = dec_num % base
stack.push(rem)
dec_num = dec_num // base
result_string = ""
while not stack.isEmpty():
result_string = result_s... |
# -*- coding: utf-8 -*-
"""Functions for inducing up/downstream causal subgraphs."""
import logging
from typing import Iterable, Union
from .utils import get_subgraph_by_edge_filter
from ...filters.edge_predicate_builders import (
build_downstream_edge_predicate,
build_upstream_edge_predicate,
)
from ...pipe... |
import asyncio
import logging
import sys
import time
from asyncio import Transport, Protocol
from threading import Thread
from typing import Union, List, Tuple
import kik_unofficial.callbacks as callbacks
import kik_unofficial.datatypes.exceptions as exceptions
import kik_unofficial.datatypes.xmpp.chatting as chatting... |
from multiprocessing import Process, Queue, Array, Manager
from crawler_process2 import *
import argparse
import os
import sys
parser = argparse.ArgumentParser(description="High Throughput Web Crawler",
add_help=False)
parser.add_argument('-v', '--version', action='version',
... |
from data_provider import get_stock_symbols, get_stock_data_by_symbols, get_stock_data_by_symbol, get_stocks_info, \
to_string
import numpy as np
from settings import *
import json
from stock import Stock
import operator
class Estimation:
def __init__(self, date_from, date_to, iterations_number=1000, stocks_w... |
import json
import requests
class ApiClientBase:
API_VERSION = 0
API_PREFIX = '/api/' + str(API_VERSION)
def __init__(self, server_address:str):
"""
:param str server_address: Backend url like http://localhost:8080
"""
self.server_address = server_address
self.sess... |
# import os
# from bs4 import BeautifulSoup
#
# rootPath = 'F:/EnglishWord/'
#
# list = []
# if os.path.isdir(rootPath):
# # print('true')
# list = os.listdir(rootPath)
#
#
list = ['Chapter-1-page-1.html', 'Chapter-1-page-10.html',
'Chapter-1-page-2.html', 'Chapter-1-page-3.html']
def sortList(list):
... |
import unittest
from unittest import mock
from types import MappingProxyType
from itemadapter.utils import (
get_field_meta_from_class,
is_attrs_instance,
is_dataclass_instance,
is_item,
is_scrapy_item,
)
from tests import AttrsItem, DataClassItem, ScrapyItem, ScrapySubclassedItem
def mocked_imp... |
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(
name='straceviewer',
version='1.0',
description='Parser/Viewer for strace output',
author='Jérôme Perrin',
packages=find_packages('.'),
test_suite="tests",
install_requires=["lark-parser"]
)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from struct import *
from array import *
import sys, os
import ui_alphanarc
class MainWindow(QMainWindow, ui_alphanarc.Ui_MainWindow):
def __init__(self,parent=None):
super(MainWindow,self).__init__(parent)
... |
from http.server import HTTPServer, BaseHTTPRequestHandler
from threading import Thread
class Handler(BaseHTTPRequestHandler):
hooks = {}
def _set_headers(self):
self.send_response(200)
self.end_headers()
def do_POST(self):
if self.path in self.hooks:
func, args, kwargs... |
# Desenvolva um gerador de tabuada, capaz de gerar a tabuada de qualquer número inteiro entre 1 a 10. O usuário deve
# informar de qual numero ele deseja ver a tabuada. A saída deve ser conforme o exemplo abaixo:
# Tabuada de 5:
# 5 X 1 = 5
# 5 X 2 = 10
# ...
# 5 X 10 = 50
n = int(input('Deseja ver a tabuada d... |
from caesar import caesar_encrpt, caesar_decrypt, caesar_brute
from coloumn_transposition import columnar_transposition_encrypt, columnar_transposition_decrypt
from json import dump, load
"""
This file will be calling all functions, initally filled with dummy functions
To run the program this file will be called, this ... |
import unittest
from selenium import webdriver
class Test(unittest.TestCase):
def test(self):
#assertGreater x>y
self.assertGreater(100, 10, "Test filed!!")
#assertGreaterEqual x>=y
self.assertGreaterEqual(12, 12, "Test greater or equal failed!!")
#assertLess x<y
se... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Convert Wakati annotation to Raw annotation
"""
import sys
import codecs
sys.stdout = codecs.getwriter('utf-8')(sys.stdout)
args = sys.argv
raw_file = args[1]
wakati_file = args[2]
ann_file = args[3]
raw = open(raw_file, 'r').read().decode('utf-8')
wakati = open(w... |
# coding: utf-8
"""
Recommender API
This is the API definition for the Recommender service. # noqa: E501
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class RecommendedActivity(object):
... |
# -*- coding: utf-8 -*-
import numpy as np
from setuptools.command.saveopts import saveopts
from setuptools.command.test import test
from time import time
import pandas as pd
import _mmp
from util import Open_File, Mount_CSV
def MMP(load_file, test_name, k, load_icmi_matrix=False,
save_icmi_matrix=False):
... |
"""
Maps the ENVICOORDSYS data type to a GPTool datatype
"""
from __future__ import absolute_import
from string import Template
from envipyarclib.gptool.parameter.template import Template as ParamTemplate
class ENVICOORDSYS(ParamTemplate):
"""
Class template for the datatype
"""
def get_parameter(sel... |
# Generated by Django 3.0.4 on 2020-05-10 10:39
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('quotes', '0004_auto_20200510_0740'),
]
operations = [
migrations.RenameField(
model_name='dashboardgrid',
old_name='... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
from alipay.aop.api.domain.AccountVO import AccountVO
class AnttechBlockchainDefinSaasAccountQueryResponse(AlipayResponse):
def __init__(self):
super(AnttechBlockchainDefinSaasAcco... |
#! /usr/bin/python3
import time
import json
import copy
import threading
import re
import iota.harness.api as api
import iota.test.iris.config.netagent.api as agent_api
import iota.test.utils.ping as ping
import iota.test.iris.testcases.vmotion.arping as arping
import iota.test.iris.testcases.vmotion.vm_utils as vm_uti... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Filename: criteria.py
# @Project: GuideNet
# @Author: jie
# @Time: 2021/3/14 7:51 PM
import torch
import torch.nn as nn
__all__ = [
'RMSE',
'MSE',
]
class RMSE(nn.Module):
def __init__(self):
super().__init__()
def forward(... |
from rest_framework.exceptions import APIException
class PriceOutOfBoundsAPIException(APIException):
status_code = 400
default_detail = "Price is not in the lower and upper bounds"
|
from animal import *
from habitat import *
from zoo import *
island = Habitat("Galapagos", "Island")
jungle = Habitat("Dark Continent", "Jungle")
savannah = Habitat("Safari", "Savannah")
tommy = Animal("Tommy", "Tortoise")
tommy.habitat = island
chester = Animal("Chester", "Cheetah")
chester.habitat = savannah
... |
from django.shortcuts import render, redirect
from django.views import View
from django.http import HttpResponse, HttpRequest
from django.http import QueryDict
from urllib import parse
import urllib.parse
from . import courseList
from . import courseDetail
class CourseListView(View):
template_name = 'course/cours... |
from configparser import SafeConfigParser
from os import getenv
import argparse
def main(options):
postfix = options.get("postfix", "")
parser = SafeConfigParser()
parser.read('newrelic.ini')
app_name = getenv("NEW_RELIC_APP_NAME", "{{ cookiecutter.project_slug }}")
if postfix:
app_name ... |
from os.path import join, dirname
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from keras.utils import np_utils
data_train = f'{dirname(__file__)}/../data/train.csv'
data_pred = f'{dirname(__file__)}/../data/test.csv'
def load_data(dataset_size=0.1, test_size=0.1, rando... |
"""
@Author: zhangluoyang
@E-mail: 55058629@qq.com
@Time: 12月 30, 2020
"""
import json
import cv2
import lmdb
import torch
import random
import numpy as np
import torchvision.transforms as T
import torch.utils.data as data
from typing import Dict, List, Tuple
from utils.s_utils import base64_to_image
from utils.utils ... |
import logging
import unittest
from unittest.mock import Mock, MagicMock, call, ANY
from collections import OrderedDict
from genie.libs.clean.stages.iosxe.cat3k.stages import InstallImage
from genie.libs.clean.stages.tests.utils import CommonStageTests, create_test_device
from pyats.aetest.steps import Steps
from py... |
from generated_py.TestData import TestData
from generated_py.SerializerXml import SerializerXml
import xml.etree.ElementTree as ET
import json
data = TestData()
data.initialize()
if True: # MG_SERIALIZE_FORMAT == MG_XML:
root = ET.Element('data')
serializer = SerializerXml(root)
data.serialize_xml(seria... |
#!/usr/bin/env python3
from utils import KVMSanitizer
from config import VMS, basis as OLDTESTS, newtests as NEWTESTS
from perf.numa import topology, get_cur_cpu, get_cpu_r
import atexit
class DB:
def __init__(self, path):
self.path = path
atexit.register(self.save)
def regr(vms, old, new):
events = ['in... |
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 2 13:24:51 2019
@author: Administrator
"""
import math
x=[[1,1],[5,1],[4,4]]
def distance(x,y,p=2):
if len(x)!=len(y):
return 0
elif len(x)>1:
sum1=0
for i in range(len(x)):
sum1+=math.pow(abs(x[i]-y[i]),p)
return mat... |
#<ImportSpecificModules>
from ShareYourSystem.Standards.Classors.Representer import _print
from ShareYourSystem.Standards.Objects import Markdowner
#</ImportSpecificModules>
#Print a version of the class
_print(dict(Markdowner.MarkdownerClass.__dict__.items()))
#Print a version of this object
_print(Markdowner.Markdo... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This script checks results of image-net-to-hdf5.py
"""
import argparse
import h5py
import os
import random
import cv2
import numpy as np
import generate_data
ALPHABET = generate_data.ALPHABET
def show_data_in_the_path(path, images_count):
images = []
la... |
# 2.13
def zlicz_litery(line):
L = line.split()
suma = sum([len(x) for x in L])
return suma
#11
line = "to jest linia"
print zlicz_litery(line) |
#this will be a cronjob undecided if it will look through all releases or if it will
#use the reporting frequency and the last report date
#
#could possibly do a daily/12h update for the database, along with a high popularity
#more frequent running to quckly get important updates and email them out.
#
import urll... |
#!C:\Python\Python
#coding=utf-8
def pyfunc(r):
for x in range(r):
print(' '*(r-x-1)+'*'*(2*x+1))
pyfunc(9)
|
"""Tests for mtg_ssm.manager module."""
# pylint: disable=redefined-outer-name
import argparse as ap
import os
import tempfile
import textwrap
import freezegun
import pytest
from mtg_ssm import ssm
from mtg_ssm.mtg import card_db
@pytest.fixture
def cdb(sets_data):
"""card_db fixture for testing."""
sets_d... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:IronmanJay
# email:1975686676@qq.com
from typing import List
class Solution:
def getCommon(self, nums1: List[int], nums2: List[int]) -> int:
len1 = len(nums1)
len2 = len(nums2)
index1 = 0
index2 = 0
while index1 < len1 a... |
# gerencie o aproveitamento de um jogador de fut: leia o nome de um jogador e a quantidade de partidas,
# deois a quantidade de gols em cada partida. No final guarde tudo isso em um
# dicionário, incluindo a quantidade de gols feitos no campeonato.
jogador = {}
jogador["nome"] = input("Insira o nome do jogador: ")
j... |
from plot import plot
from helpers import split, split_into_chars, srednia_wartosc_sygnalu
from manchester_coding.manchester import Manchester
def manchester(bity, niski, wysoki, differential=False):
logical = split(Manchester(differential).encode(bity))
print(logical)
output = []
for i in range(len(... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import cx_Oracle
import os
import json
import logging
from Dashboard import Dashboard
class DashboardOracle(Dashboard):
db = {}
cursor = {}
def __init__(self, config, schema, debug):
os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'
confi... |
####################################################################################################
#'''
# Created on 28.10.2018 initially
# This program reads from MS SQL Server of 2i Rete Gas and send sensor data
# and pushes the data into the SAP Cloud Platform IoT Services for cloud foundry
#
# It needs to ... |
"""Handles the database interactions for storing notes."""
from dataclasses import dataclass
@dataclass(frozen=True)
class Note:
user: int
content: str
|
from PyQt4 import QtGui
import Labortagebuch_Qt4
import sys
class tagebuchApp(QtGui.QWidget, Labortagebuch_Qt4.Ui_Form):
def __init__(self):
super(tagebuchApp, self).__init__()
self.setupUi(self)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import unittest
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import tensorlayer as tl
from tests.utils import CustomTestCase
class Layer_Core_Test(CustomTestCase):
@classmethod
def setUpClass(self):
self.batch_size = 8
self.inputs_shap... |
from django.shortcuts import render
from django.http import JsonResponse, Http404
import json
import requests
from .models import Opportunity
# https://torre.bio/api/bios/$username (gets bio information of $username)
# - GET https://torre.bio/api/people/$username/network?[deep=$limit] (lists people sorted by connecti... |
# A simple example on mongopie
# User Vote and Tag
import mongopie
mongopie.set_defaultdb('localhost', 27017, 'pietest')
class UserTag(mongopie.Model):
user = mongopie.StringField()
tag = mongopie.StringField()
count = mongopie.IntegerField(default=0)
@classmethod
def add_tag(cls, vote):
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.test import TestCase
# from scraping.models import ScrapeJob
from datetime import datetime, timedelta
class ScrapeJobTableTest(TestCase):
"""采集任务表测试(需要补充)"""
def test_datetime(self):
now = datetime.now()
next_time = ... |
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
title = input("Which movie are you looking for? ")
found = True
import os
import csv
path = "/Users/williampappas/Desktop/netflix_ratings.csv"
csvpath = os.path.join(path)
found = False
with open(csvpath, newline='') as csvfile:
c... |
print("Basic Type Data -> String")
a = "Hello, I am Kelvin. I'm ready to learn Python Programming"
print("Value a = ", a, ", type = ", type(a)) # 'str' is String
# String version 1
b = "Hello, I am Kelvin. " \
"I'm ready to learn Python " \
"Programming"
print("Value b = ", b, ", type = ", type(b))
# Strin... |
# coding:utf-8
import sys
import codecs
import pickle
from pathlib import Path
MAIN_PATH = Path(__file__).absolute().parent.parent
sys.path.insert(0, str(MAIN_PATH))
from preprocess_data import make_dict as mk
from preprocess_data import save_to_binary
from nltk.stem import PorterStemmer
ps = PorterStemmer()
# loa... |
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 19 16:10:42 2020
@author: Ankit Parashar
"""
#! python3
# readCensusExcel.py
import openpyxl, pprint
print('Opening Workbook...')
wb = openpyxl.load_workbook('censuspopdata.xlsx')
sheet = wb['Population by Census Tract']
countydata = {}
print('Reading rows.')
for row in ... |
import os
import sqlite3 as SQL
# Создаем или открываем базу данных
DataBase = SQL.connect("MyDataBase.db")
SQLite = DataBase.cursor()
# Информация, для записи в базу данных
MyClietn = [
[1,"Фам1","Имя1","Очт1","Адрес1",80000001],
[2,"Фам2","Имя2","Очт2","Адрес2",80000002],
[3,"Фам3","Имя3... |
# Crichton, Admirable Source Configuration Management
# Copyright 2012 British Broadcasting Corporation
#
# 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/licens... |
from torchtext.data import Dataset
from torchtext.data import Example
from torchtext.utils import unicode_csv_reader
import io
import os
from functools import partial
class DuplicateTabularDataset(Dataset):
"""Defines a Dataset of columns stored in CSV, TSV, or JSON format."""
def __init__(self, path, forma... |
import sys
from setuptools import setup
if not sys.version_info[0] in [2, 3]:
print('Sorry, emult is not supported in your Python version')
print(' Supported versions: 2 and 3')
print(' Your version of Python: {}'.format(sys.version_info[0]))
sys.exit(1) # return non-zero value for failure
... |
"""Tests for pyhap.accessory."""
import asyncio
from io import StringIO
from unittest.mock import patch
import pytest
from pyhap import accessory
from pyhap.accessory import Accessory, Bridge
from pyhap.accessory_driver import AccessoryDriver
from pyhap.const import (
CATEGORY_CAMERA,
CATEGORY_TARGET_CONTROLL... |
from django.conf import settings
from django.conf.urls import url
from django.conf.urls.static import static
from django.http import HttpResponse
from django.urls import include, path
from django.views.decorators.csrf import csrf_exempt
from helusers.admin_site import admin
from contracts.services import get_contract_... |
import modi
import time
from playscii.games.galaga import GalagaManager
"""
HOW TO PLAY
$ pip install pyplayscii --user
$ python galaga.py
Make your terminal screen big enough to play the game...
Use the gyro to control the jet!
Press the button to shoot down enemies!
"""
if __name__ == "__main__":
... |
#!/usr/bin/python
from math import sqrt
p = 277678
n = int(sqrt(p) + 1)
c = int((n + 1) / 2)
steps = list(range(c-1, n-1))
steps = list(reversed(steps)) + steps[1:] + [n-1]
print(
[steps[i % len(steps)] for i, v in enumerate(
range(((n-2)**2)+1, (n**2)+1)
) if v == p][0]
)
|
from message_handler import MessageHandler
import time
if __name__ == '__main__':
message_handler = MessageHandler('test')
while True:
message_handler.get_message()
time.sleep(1) |
f=0
a=0
b=1
flag=True
while flag==True:
mid=a
a=b
b=mid+b
f=f+1
if len(str(a))==1000:
flag=False
break
print (f)
print (a)
|
from numpy import *
from numpy.linalg import *
j = array(eval(input((""))))
tab = array([[2 , 1 , 4], [1 , 2 , 0], [2 , 3 , 2]])
# Vetor de constantes (informado no enunciado)
j = j.T
k = dot(inv(tab),j)
# Resolucao do sistema de equacoes lineares
# Imprime o preco de cada fruta
print("estafilococo: ", round(k[0]... |
class CommunityTracker:
"""Class to keep track of network statistics of the network as the
algorithm progresses and nodes move communities.
"""
def __init__(self):
self.node_to_community_map = None
self.m = 0.0
self.degrees = None
self.self_loops = None
self.comm... |
#Binary search on every row or col
#Time: O(nlogm or mlogn)
#Space: O(1)
class Solution:
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if not matrix or not matrix[0]:
return False
... |
from django.core.exceptions import ValidationError
from django.contrib.auth.models import User
import re
def validate_noHp(value):
for word in value:
if not bool(re.search('\d', word)):
message = 'Maaf nilai mengandung angka'
raise ValidationError(message)
def validate_noHp_exist(v... |
import zmq, logging
log = logging.getLogger(__name__)
class Connection(object):
def __init__(self):
self.log = log
self.ctx = zmq.Context()
self.sock = self.ctx.socket(zmq.PAIR)
self.active = True
def connect(self, host):
self.sock.connect(host)
def bind(self, h... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/3/9 10:54
# @Author : glacier
# @Site :
# @File : anjuke-ks-average.py
# @Software: PyCharm Edu
import re,requests
from bs4 import BeautifulSoup
import traceback
import pymysql
headers = {
# 'Host': 'i.meizitu.net',
'Ac... |
import pygame
from nxt.locator import find_one_brick
from nxt.motor import *
from time import sleep, clock
pygame.init()
done = False
joystick_count=pygame.joystick.get_count()
if joystick_count == 0:
print ("Error, I didn't find any joysticks.")
else:
my_joystick = pygame.joystick.Joystick(0)... |
__author__ = "Wenjie Chen"
__email__ = "wc2685@columbia.edu"
import redis
from pyspark import SparkConf, SparkContext
from pyspark.sql.functions import *
from pyspark.sql import SparkSession
from pyspark.streaming import StreamingContext
from multiprocessing import Process
import time
import os
from phonenumbers.phone... |
#!/usr/bin/env python
import sys;
def getABAs(string):
ABAs = list();
if len(string) >= 3:
for i in range(len(string)-2):
if string[i] == string[i+2] and \
string[i] != string[i+1]:
ABAs.append(string[i:i+3]);
return ABAs;
def getHypers(string):
i = 0;
nonhypers = list();
while(string.find(']', ... |
# -*- coding: utf-8 -*-
import scipy.stats as stats
import numpy as np
import pandas as pd
from pandas import DataFrame, Series
import statsmodels.api as sm
from statsmodels.tsa.stattools import coint
from datetime import timedelta
import matplotlib.pyplot as plt
import re
def initialize(context):
set_benchmark('... |
from django.db import models
from django.contrib.auth.models import User
class Genre(models.Model):
name = models.CharField(max_length=256)
class Book(models.Model):
title = models.CharField('Title', max_length=256)
pic = models.TextField()
author = models.CharField('Author', max_length=256)
des... |
import hashlib
def certificate_matches(certificate, known_hash):
'''
check if the certificate matches the known hash
'''
return hashlib.sha256(certificate.encode('utf-8')).hexdigest() == known_hash
|
class ReverseString:
"""
reverse a string
"""
def __init__(self, string_input):
self.string_input = string_input
self.string_out = ''
self.length = len(string_input) - 1
def reverse_string(self):
"""
reverse a give string, print and check if its palindrome ... |
import logging
import mysql.connector
from configparser import ConfigParser
from tools.slack import Slack
config = ConfigParser()
config.read('./conf/setup.ini')
logging.basicConfig(filename='replica.log', filemode='a', format='%(asctime)s - %(message)s')
class MySQL(object):
def __init__(self):
try:
self.db... |
# -*- coding:utf-8 -*-
import types
class w(object):
# __slots__ = ('s', 'm')
def __init__(self, s, m):
self.s = s
self.m = m
def p(self):
print(self.s, self.m)
if __name__ == '__main__':
def p(self):
print(self.m, self.s, self.s1)
w1 = w(1, 2)
w1.p()
... |
items =['item1','item2']
json_dir = 'D:\\pycharm\\data\\clothes\\annos\\'
image_dir = 'D:\\pycharm\\data\\clothes\\image\\'
labels = { 0:'short sleeve top',
1:'shorts',
2:'trousers',
3:'long sleeve top'}
|
# from sqlalchemy.orm import joinedload
from sqlalchemy.orm import sessionmaker, joinedload
from models.DBClasses import Endereco, Pessoa, engine, Telefone, as_dict
DBSession = sessionmaker(bind=engine)
def insertPessoa(nome_, data_nascimento_, rua_, numero_, tipo_end_, cep_, tipo_tel_, numero_tel_):
session = ... |
# -*- coding: utf-8 -*-
import web
def post_add_form(page_id=''):
return web.form.Form(
web.form.Textbox("username", web.form.notnull, size=20, description="用户名"),
web.form.Password("password", description="密码"),
web.form.Textbox("title", web.form.notnull, size=50, description="标题"),
... |
# --------------
import pandas as pd
import numpy as np
import math
class complex_numbers:
def __init__(self, real, imag):
self.real=float(real)
self.imag=float(imag)
def __repr__(self):
if self.real == 0.0 and self.imag == 0.0:
return "0.00"
if self.rea... |
import time
def mergeSort(list):
print("Splitting ",list)
if len(list)>1:
mid = len(list)//2
lefthalf = list[:mid]
righthalf = list[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
i=0
j=0
k=0
while i < len(lefthalf) and j < len(righthalf... |
#!/usr/bin/env python2
from __future__ import division
import sys, os
sys.path.append(os.path.join(os.getcwd(), '../src'))
import time
import pickle
from collections import OrderedDict
import numpy as np
from scipy import optimize
import matplotlib.pyplot as plt
from matplotlib import cm
import pandas as pd
from b... |
#!/usr/bin/python
# Find the IAM username belonging to the TARGET_ACCESS_KEY
# Useful for finding IAM user corresponding to a compromised AWS credential
# Requirements:
#
# Environmental variables:
# AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY
# python:
# boto
#currently uses your default profile so, you need to... |
def inv(x, p) :
u, v = __inv(x,p)
if ( u == 0 and v == 0) :
return 0
else :
return u%p
def __inv(x, p) :
if x%p == 0 :
if p == 1 :
return (0,1)
else :
return (0,0)
else :
u1,v1 = __inv(p, x%p)
return (v1, u1 - (x/p)*v1)
class curve:
def __init__(self, a, b, p, n) :
self.a = a
self.b = b
... |
# stdlib
from typing import Optional
# third party
from typing_extensions import final
# relative
from .....common.message import ImmediateSyftMessageWithReply
from .....common.message import ImmediateSyftMessageWithoutReply
from .....common.serde.serializable import serializable
from .....common.uid import UID
@se... |
"""
Program to find missing element from 2 arrays (lists)
"""
class TestFinder(object):
def missingElementFinder(self, list1, list2):
"""
From two lists, this function finds
missing element
For example: In [1,2,3,4] , [4,2,3]: 1 is missing.
"""
list1.sort()
... |
# Generated by Django 3.0.8 on 2020-08-12 20:35
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('product', '0001_initial'... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 14 19:39:54 2021
@author: 元元吃汤圆
"""
#%matplotlib inline
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
f... |
icp_quat = []
with open("/home/more3d/lighthouse-slam/pilot/loop4/realsense.klg.freiburg", "r") as f:
lines = f.readlines()
for line in lines:
data = line.split(" ")
quats = data[4:8]
icp_quat.append(quats)
with open("/home/more3d/lighthouse-slam/pilot/loop4/pose.freiburg", 'r+') as f:... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.