text stringlengths 38 1.54M |
|---|
#!/bin/python3
#https://www.hackerrank.com/challenges/sherlock-and-anagrams
import math
import os
import random
import re
import sys
import string
# Complete the sherlockAndAnagrams function below.
def sherlockAndAnagrams(s):
substrings = {}
alphabet = string.ascii_lowercase
for start in range(len(s)... |
import numpy as np
import cv2 as cv
from scipy import stats
import loaddata
import Method
def double2uint8(I, ratio=1.0):
return np.clip(np.round(I*ratio), 0, 255).astype(np.uint8)
def search(img):
img_YCC = cv.cvtColor(img,cv.COLOR_BGR2YCrCb)
Y,Cr,Cb = cv.split(img_YCC)
# cv.imshow('Y',Y)
# cv.ims... |
#!/usr/bin/env python
# coding=utf-8
import os
from PyQt4 import QtCore
from squery import socketQuery
class MainControl(QtCore.QThread):
def __init__(self, parent=None):
QtCore.QThread.__init__(self)
self.sock = socketQuery()
self.log = self.sock.log
def init_gui(self, params=dict(... |
from .version import __version__
from .f2p import f2p, f2p_list, f2p_word
from .f2p import dictionary as f2p_dictionary
|
from pymongo import MongoClient
from jobqueue import JobQueue
import unittest
host = 'localhost'
port = 27017
pair = '%s:%d' % (host, port)
class TestJobQueue(unittest.TestCase):
@classmethod
def setUpClass(cls):
client = MongoClient(host, port)
client.pymongo_test.jobqueue.drop()
cl... |
from __future__ import unicode_literals
from django.core.validators import MinValueValidator, MaxValueValidator
from django.db import models
from home import choices
class Race(models.Model):
name = models.CharField(max_length=64)
def __str__(self):
return self.name
class Army(models.Model):
... |
import sys
def combine_lex_cols(source_files_name):
syl_en_file = open(source_files_name + ".syl_en", "r")
syl_vie_file = open(source_files_name + ".syl_vie", "r")
syl_lex_file = open(source_files_name + ".lex", "w")
syls_en = []
syls_vie = []
for line in syl_en_file:
syls_en.append(line.strip())
f... |
# -*- coding: utf-8 -*-
from apollo.settings import TIMEZONE
from collections import defaultdict
from datetime import datetime
from dateutil.rrule import rrule, DAILY
from logging import getLogger
from pytz import timezone
from sqlalchemy import and_, false, func, or_, not_
from sqlalchemy.orm import aliased, Load
fro... |
from __future__ import (absolute_import, division, print_function)
import matplotlib as mpl
import matplotlib.pyplot as plt
# The two statemens below are used mainly to set up a plotting
# default style that's better than the default from Matplotlib 1.x
# Matplotlib 2.0 supposedly has better default styles.
import sea... |
import warnings
import sys
import pandas as pd
import numpy as np
import mlflow
import mlflow.pyfunc
import fbprophet
from fbprophet import Prophet
from fbprophet.diagnostics import cross_validation
from fbprophet.diagnostics import performance_metrics
from stream import db_mem
mlflow.set_tracking_uri("http://loca... |
from datetime import datetime
from django.contrib.auth.decorators import login_required, permission_required
from django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, redirect
from django.contrib.au... |
from google.appengine.ext import db
class FileMetadata(db.Model):
"""A helper class that will hold metadata for the user's blobs.
Specifially, we want to keep track of who uploaded it, where they uploaded it
from (right now they can only upload from their computer, but in the future
urlfetch would be nice to ... |
# -*- coding: utf-8 -*-
# flake8: noqa
from .tslibs import (
iNaT, NaT, Timestamp, Timedelta, OutOfBoundsDatetime, Period)
|
from django.urls import path
from .views import Pizzatypeview,Pizzasizeview,Pizzatoppingview,makepizza\
,PizzaToppingDeleteView,filterpizza,getpizzabyid,PizzaSizeDeleteView,PizzaTypeDeleteView
urlpatterns = [
path('pizzatype/',Pizzatypeview.as_view()),
path('pizzasize/',Pizzasizeview.as_vi... |
def decode(instructions, posmax):
min = 0
max=posmax
indexMax = len(instructions)-1
for i in range(indexMax):
mid = (((max+1) - min) / 2) + min
if instructions[i] in ['F', 'L']:
max = mid - 1
else:
min = mid
if instructions[indexMax] in [... |
"""
@author: Vuong Quoc Viet
@version: 1.0
@since: Sep 27, 2017
"""
from database.dynamodb.list_rating import ListRating
class Rating:
def __init__(self):
self.__connection = ListRating()
def get_list(self):
return self.__connection.get_rating()
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat May 4 00:20:09 2019
@author: xie
"""
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
ji_a = 0
ji_b = 0
for i in a:
if i % 2 == 1:
ji_a += 1
for i in b:
if i % 2 == 1:
ji_b += 1
ou_a = ... |
from django.shortcuts import render
from .forms import BlogPostModelForm
from .models import BlogPost
from django.http import HttpResponse
# Create your views here.
def list_blogs(request):
template_name = "blog_list.html"
blogs = BlogPost.objects.all()
context = {"blogs": blogs}
return render(request... |
#!/usr/bin/env python
#import pdb
grid = [[0 for x in range(3)] for x in range(3)]
def print_grid(n):
for i in range(0, n + 1):
for j in range(0, n +1):
print "grid[%d][%d] = %d" % (i, j, grid[i][j])
def robot_paths(x, y, n):
# pdb.set_trace()
#print "at grid[%d][%d] = %d" % (x, ... |
import fileinput
lines = []
for line in fileinput.input():
lines.append(line)
for line in lines:
if int(line) % 2 == 0:
print("Bob")
else:
print("Alice")
|
# The implementation is adopted from U-2-Net, made publicly available under the Apache 2.0 License
# source code avaiable via https://github.com/xuebinqin/U-2-Net
from .u2net import U2NET
|
for i in range(1,11):
print(i)
for j in range (1,20,2):
print(j)
for k in range(10,0,-1):
print(k)
for l in range(3,33,3):
print(l)
else:
print("process terminated")
#while basic loop
i=1
while(i<=10):
print(i)
i=i+1
#write a program print to n number
n=int(input("enter... |
# Add teams here to collect data from for rotogrinders.py
teams = ['TEN', 'IND', 'ARI', 'NEP', 'CLE', 'JAC', 'MIA', 'NYJ', 'LVR', 'ATL', 'NYG', 'CIN', 'LAC',
'BUF', 'CAR', 'MIN', 'BAL', 'PIT']
|
from setuptools import setup
from pip.req import parse_requirements
import uuid
install_reqs = parse_requirements(
'requirements/main.txt', session=uuid.uuid1())
reqs = [str(ir.req) for ir in install_reqs]
setup(
name='txes2',
version='0.1.6',
description="An Elasticsearch client for Twisted",
key... |
# coding: utf-8
# Cross Validation
import os
import gzip
import pickle
import numpy as np
import tensorflow as tf
from utils.utils import FeatureExtractor, LSTMCRFeeder, conll_format
from model.BiLSTMCRF import BiLSTMCRFModel
def atisfold(fold):
assert fold in range(5)
fp = gzip.open('data/atis.fold' + s... |
from django.contrib.auth import get_user_model
from django.db import models
from webapp.validators import MinLengthValidators, str_value
class BaseModel(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
abstract = Tru... |
"""
In this simple RPG game, the hero fights the goblin. He has the options to:
1. fight goblin
2. do nothing - in which case the goblin will attack him anyway
3. flee
"""
from time import sleep
from random import random, choice
from characters import *
from party import *
from battle import *
from store import *
batt... |
from model import RNNLM_Model
import os
import pickle
import tensorflow as tf
import numpy as np
import argparse
import sys
sys.path.append('..')
from config import get_configs, experiment_path
parser = argparse.ArgumentParser()
parser.add_argument("--experiment", "-e", type=int, default=None, help="Which experiment d... |
print("Tablas de multiplicar del 1 al 12")
for i in range(1, 13):
for o in range(1, 13):
mult = i * o
print("{} * {} = {}".format(i, o, mult)) |
from django.db import models
# Create your models here.
class Post(models.Model):
title = models.CharField(max_length=250)
description = models.TextField()
createdAt = models.DateTimeField(auto_now=True) |
from PyQt5.QtWidgets import QWidget, QMessageBox, QInputDialog
from PyQt5 import uic
from question import QuestionScreen
from new_question import NewQuestionScreen
from editor import EditScreen
from console import ConsoleScreen
import sys
import sqlite3
class HomeScreen(QWidget): # домашнийй экран
def... |
import json
import logging
from typing import Optional, TypedDict
from redis import Redis
from solders.rpc.responses import RpcConfirmedTransactionStatusWithSignature
from src.solana.solana_client_manager import SolanaClientManager
logger = logging.getLogger(__name__)
class CachedProgramTxInfo(TypedDict):
# Si... |
import turtle
import pandas
screen = turtle.Screen()
image = "blank_states_img.gif"
screen.addshape(image)
turtle.shape(image)
# def get_mouse_click_coor(x,y):
# print(x,y)
#
# turtle.onscreenclick(get_mouse_click_coor)
# is_game_on = True
# while is_game_on:
data = pandas.read_csv("50_states.csv")
all_states... |
#
# @lc app=leetcode.cn id=51 lang=python3
#
# [51] N皇后
#
from typing import List
# @lc code=start
class Solution:
def solveNQueens(self, n: int) -> List[List[str]]:
cols = [0] * n
hill_diagonals = [0] * (2 * n - 1)
dale_diagonals = [0] * (2 * n - 1)
res = []
def could_pla... |
# -*- coding:utf-8 -*-
from collections import defaultdict
from collections import deque
class Change:
def countChanges(self, dic, n, s, t):
# write code here
newDic = createNewDic(dic, len(s))
return len(self.bfsSearch(newDic, s, t))-1
def bfsSearch(self, dic, source, target):
... |
class Parent:
def convertToBvalue(self, intValue, fill_size):
return bin(int(intValue))[2:].zfill(fill_size)
class RFormat(Parent):
def __init__(self,destinationFile,executionOutput):
"""
destinationFile File with binary code
"""
self.destinationFile = destinati... |
import os
import fitz
import pandas as pd
import shutil
def extract_content(path, mode):
if os.path.isdir('content'):
#if already exists remove it
shutil.rmtree('content')
os.mkdir('content')
if mode == 0:
#make folder
folder = 'content/'+(path.split('/')[-... |
import cv2
import numpy as np
ESC_KEY = 27
cam = cv2.VideoCapture(0)
cam.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)
cam.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi',fourcc, 20.0, (1280,720))
while True:
ret, frame = cam.read()
out.write(frame)
cv2.ims... |
import kmeans_create
import kmeans_from_txt
import kmeans_tune
import sys
import lfa
if __name__ == '__main__':
args = sys.argv[1:]
if len(args) < 1:
print('Options include: lfa, kmeans create, kmeans load, kmeans tune')
elif args[0] == 'lfa':
lfa.run()
elif args[0] == 'kmeans':
if len(args) < 2:
print('... |
from collections import namedtuple
from os.path import join, dirname, abspath
import json
ship_schema_fields = ['shield', 'armor', 'hull', 'firepower', 'size',
'weapon_size', 'multishot', 'sensor_strength',]
buff_effects = ['shield_recharge', 'armor_local_repair',
'remote_shield', 'remote_armor',]
# XXX damag... |
from django.shortcuts import render
from django.views import View
from datetime import datetime, date, timedelta
import random
from Travel.models.flights import Flight
from Travel.models.flight_booking import Flight_booking
from Travel.models.hotels import Hotel
class Flight_Final_Summary_View(View):
def get(se... |
import unittest
import os.path
import sudoku.io
import sudoku.coloring
class ColoringTests(unittest.TestCase):
def test_welsh_powell(self):
filepath = os.path.join(
os.path.dirname(__file__),
'../rsc/9/sample-2.sdk')
graph = sudoku.io.read(filepath)
graph_solved = ... |
n,m = map(int,input().split())
h = list(map(int,input().split()))
x = []
ans = [0]*n
for i in range(m):
a,b = map(int,input().split())
a -= 1
b -= 1
if h[a] > h[b]:
ans[b] += 1
elif h[a] < h[b]:
ans[a] += 1
else:
ans[b] += 1
ans[a] += 1
print(ans.count(0))
|
__author__ = 'dhruv and alex m'
from grt.core import GRTMacro
import wpilib
import threading
#constants = Constants()
class StraightMacro(GRTMacro):
"""
Drive Macro; drives forwards a certain distance while
maintaining orientation
"""
DT_NO_TARGET_TURN_RATE = .2
DT_KP = .03
DT_KI = 0
... |
#最长重复子数组 动态规划
def findLength(A, B):
res = 0
dp = [[0 for _ in range(len(A) + 1)] for _ in range(len(B) + 1)]
for i in range(1, len(B) + 1):
for j in range(1, len(A) + 1):
if B[i - 1] == A[j - 1]:
dp[i][j] = dp[i - 1][j - 1] + 1
res = max(res, dp[i][j])
... |
def addNumbers(): #Default function
print("Hi")
print(5 + 10)
def subNumbers(x, y): #Parameterised function
print(x + y)
def mulNumbers(x, y):
x = "Kriti"
y = 150
addNumbers()
subNumbers(10, 20)
product = mulNumbers(10, 20, 30)
print("The product is", product) |
import numpy as np
nbit = 4 # float bit
"""
nx, ny, nz, nvar = 19440, 14904, 160, 3
mx, my = nx * 2 // 3 + 1197, ny * 2 // 3
endx, endy = mx + 2592, my + 2160
nlayer = nx * ny * nvar
with open("mesh_0", "wb") as fid:
for i in range(nz):
data = np.fromfile("../mesh_large_8m_orig.bin_0", dtype='float32',
... |
import sys
import re
gtrack_fname = str(sys.argv[1])
with open(gtrack_fname) as gf:
gtrack_file = gf.readlines()
for line in gtrack_file:
line=line.rstrip()
if line.startswith("#"):
print line
else:
line1=re.sub(r'(chr\w+)',r'\1_A',line)
line2=re.sub(r'(chr\w+)',r'\1_B',line)
print line1
... |
# Imports
from bokeh.plotting import figure
from bokeh.io import curdoc
from bokeh.models.annotations import Label,LabelSet
from bokeh.models import ColumnDataSource
from bokeh.models.widgets import Select, Slider
from bokeh.layouts import layout
from bokeh.models import Range1d
# Create column datasource
cds_origin... |
"""
https://leetcode.com/problems/range-addition-ii/#/description
Given an m * n matrix M initialized with all 0's and several update operations.
Operations are represented by a 2D array, and each operation is represented by an array with two positive integers a and b, which means M[i][j] should be added by one for a... |
# Generated by Django 3.1.7 on 2021-04-08 00:02
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('back', '0005_auto_20210407_1900'),
]
operations = [
migrations.AlterField(
model_name='compra',... |
#frontend
from tkinter import *
import tkinter.messagebox
import back1
import os
class cust:
def __init__(self,root):
self.root = root
self.root.title("CMS")
self.root.geometry("700x700")
self.root.configure(bg="black")
self.id = StringVar()
... |
# -*- encoding: utf-8 -*-
"""
auth_confirmation_email.py
- create safe email to confirm user
"""
from log_config import log, pprint, pformat
log.debug ("... loading token_required ...")
from flask import current_app as app
from itsdangerous import URLSafeTimedSerializer
### + + + + + + + + + + + + + + + + + + ... |
from mac_vendor_lookup import AsyncMacLookup, MacLookup
import asyncio
class maclookup():
def __init__(self):
self.async_mac = AsyncMacLookup()
self.mac = MacLookup()
def UpdateVendorList(self):
print("Updating MAC address vendor list")
self.mac.update_vendors()
print("... |
from tools.chaojiying import Chaojiying_Client
from lxml import etree
import requests
import tools.dict_match
class JS:
async def get_data(self, info):
try:
return self.get_jsessionid(info)
except Exception as e:
print(e)
return {"code": 500, "msg": "暂无法查询!"}
... |
known_chains = {"STEEM" : {"chain_id" : "0" * int(256 / 4),
"core_symbol" : "STEEM",
"prefix" : "STM"},
}
|
import pytest
from selenium.webdriver.common.by import By
class HomePage:
#contructor:
def __init__(self, driver):
self.driver = driver
#test data
upperNavigatorFirstETxt = "ProtoCommerce"
upperNavigatorSecondETxt = "Home"
upperNavigatorThirdETxt = "Shop"
nameAlertMinChar = "Name... |
# Copyright The OpenTelemetry Authors
#
# 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 ... |
import csv
import sys
import re
reader = sys.argv[1:]
writer = csv.writer(sys.stdout)
for icsv in reader:
acsv = open(icsv)
fcsv = csv.reader(acsv)
fcsv.next()
for i, row in enumerate(fcsv):
row = [(int(x) if re.match(r"[-+]?\d+$", x) is not None else x) for x in row]
state = row[9].split('/')[4]
... |
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 15 14:29:00 2018 by Meena Sirisha"""
a=list(range(1,101))
a
import random
a=random.sample(range(1,101),100)
print(a)
print(min(a))
print(max(a))
b=sorted(a)
print(b)
len(b)
b[round(len(b)/2)]
len(b)%2==0
round((len(b)/2)-1)
(b[round((len(b)/2)-1)]+b[round(len(b)/2)])/2
... |
#!/usr/bin/env python2.6
"""
This is a Python version of the ForestMoon Dynamixel library originally
written in C# by Scott Ferguson.
The Python version was created by Patrick Goebel (mailto:patrick@pirobot.org)
for the Pi Robot Project which lives at http://www.pirobot.org.
The original license for the C# version ... |
from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton
choose_language = InlineKeyboardMarkup(
inline_keyboard=
[
[
InlineKeyboardButton(text="Українська", callback_data="lang_uk")],
[
InlineKeyboardButton(text="Русский", callback_data="lang_ru"),
... |
# -*- coding: utf-8 -*-
# @Author: gzliuxin
# @Email: gzliuxin@corp.netease.com
# @Date: 2017-07-14 19:47:51
import json
from poco import Poco
from poco.agent import PocoAgent
from poco.utils.simplerpc.utils import sync_wrapper
from poco.freezeui.hierarchy import FrozenUIHierarchy, FrozenUIDumper
from poco.utils.ai... |
#!/usr/bin/env python
from oauth2client.client import GoogleCredentials
from googleapiclient.discovery import build
project_id='reddit-corpus-analysis'
# Grab the application's default credentials from the environment.
credentials = GoogleCredentials.get_application_default()
# Construct the service object for inter... |
import torch
import numpy as np
from scipy.linalg import sqrtm
class Preprocessor:
"""
Base class for various preprocessing actions. Sub-classes are called with a subclass of `_Recording`
and operate on these instances in-place.
Any modifications to data specifically should be implemented t... |
from flask_wtf import Form
from wtforms import StringField, SubmitField, DecimalField, IntegerField
from wtforms.validators import DataRequired
from wtforms.fields.simple import PasswordField
class LoginForm(Form):
user_id = IntegerField('ID:', validators=[DataRequired()])
password = PasswordField('Password:'... |
#from os import stat_result
from tkinter import*
#import 뒤에 *를 꼭 붙여주세요... 저거 안해서 못한 거였어...
root = Tk()
root.title ('Filp the switch')
#root.iconbitmap ('C:\Users\USER\Documents\GitHub\NadoPython\Personal\Jess.Kim\Toggle_on.jpg')
root.geometry("500x300")
my_label = Label(root, text="Switch On", fg="green", font=("He... |
from django.http import HttpResponse
from django.shortcuts import redirect
def unauthenticated_user(view_func):
def check_user(request, *args, **kwargs):
if request.user.is_authenticated:
return redirect('info')
else:
return view_func(request, *args, **kwargs)
return che... |
'''
Created on Jan 4, 2019
@author: sumit
'''
import os
import xlsxwriter
import json
from logging import raiseExceptions
try:
from Lib import LibUtils
except:
pass
#import LibUtils
def DirCheck(folder):
'''
Return True if Directory Exist else False.
:param Directory
'... |
import sys
from pyspark.sql import SparkSession
from pyspark.sql.functions import lit, col
def demo_df():
# Extract
df = spark.read.format("csv").option("header", "true").load(planes_file)
# Transform
df = df.withColumn("NewCol", lit(0)).filter(col("model").isNotNull())
# Load
df.write.forma... |
import os
import re
testfile = open('D:\/regex_sum_238824.txt', 'r')
total_number = []
for line in testfile:
number_array = re.findall('[0-9]+', line)
if len(number_array) > 0:
total_number = total_number + number_array
else:
continue
total_sum_number = 0
for numbers in total_number:
t... |
import logging
import time
from collections import defaultdict
from p4pktgen.config import Config
class Statistic(object):
def __init__(self, name):
self.name = name
class Counter(Statistic):
def __init__(self, name):
super(Counter, self).__init__(name)
self.counter = 0
def inc... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'DepthEncodingDialog.ui'
#
# Created by: PyQt5 UI code generator 5.11.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_DepthEncodingDialog(object):
def setupUi(sel... |
from setuptools import setup
# with open('requirements.txt') as f:
# dependency_links = []
# install_requires = []
# for line in f.read().splitlines():
# if 'ssh://' in line:
# # make a pip line into setup line
# dependency_links.append(line.replace('-e ', '') + '-0')
# ... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-09-01 15:29
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('stc', '0008_auto_20160830_2314'),
]
operations = [
migrations.AlterField(
... |
# A Class for addresses
class Address():
def __init__(self, houseN, street, city, zipCode, state = "Alabama", aptNum = None ):
self.houseNum = houseN
self.street = street
self.aptNum = aptNum
self.city = city
self.state = state
self.zipCode = zipCode
def __st... |
'''
IBEHS 1P10 Mini Milestone 10 Individual File
Date: January 24th 2020
'''
""" GIVEN Functions """
## This function calculates the gear ratio of your gearing mechanism
## This is a repeat of Mini-Milestone 5 (Wk-8), Objective #1
def calc_GR(gear_list1, gear_list2):
ratio1 = gear_list1[-1] / gear_list1... |
import numpy as np
import numpy.linalg as la
#print(streets)
#print(n_intersections)
#print(intersection_inflow)
plot_street_network(streets,intersection_inflow,title="initial")
t = 10**(-10)
m = n_intersections
n = len(streets)
flow_matrix = np.zeros((m,n))
#print(flow_matrix.shape)
for i in range(m):
for j i... |
from __future__ import annotations
from dataclasses import dataclass, field, replace
from typing import Tuple, Optional
import random
@dataclass(frozen=True)
class Card:
cost: int
def make_default_deck() -> Tuple:
costs = (0, 0, 1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 5, 5, 6, 6, 7, 8)
return tuple([Card(co... |
food = int(input()) * 1000
eaten_food = 0
while True:
gr_food = input()
if gr_food == 'Adopted':
break
else:
eaten_food += int(gr_food)
if food - eaten_food >= 0:
print(f'Food is enough! Leftovers: {food - eaten_food} grams.')
else:
print(f'Food is not enough. You need {abs(foo... |
"""10. Write a Python program to get the difference between the two lists"""
SampleList1 = list("список")
print("Sample list #1", SampleList1)
SampleList2 = list("лист")
print("Sample list #2", SampleList2)
print("The difference (1 - 2):", list(set(SampleList1) - set(SampleList2)))
|
from imageio import imread, imsave
from itertools import islice, product
from scipy import ndimage
import numpy as np
import OpenEXR # non-Windows: pip install openexr; Windows: https://www.lfd.uci.edu/~gohlke/pythonlibs/#openexr
import skimage.transform # pip install scikit-image
def assertEqual(a, b, threshold=1e-6,... |
import datetime
from chemical_analysis.utils import truncate
import psycopg2
import logging
import os
LOGGER = logging.getLogger('django')
def format_filter_response(data):
response = dict()
response['plant'] = set()
response['truck_type'] = set()
response['i2_taluka_desc'] = set()
response['cit... |
from sklearn import svm
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
def getData(): #modify this to work with the data (hint: output is not the last thing but the....)
x = []
y = []
input = open("data.txt").read().split("\n")
for i in input:
inputArray ... |
__author__ = 'diegopinheiro'
__email__ = 'diegompin@gmail.com'
__github__ = 'https://github.com/diegompin'
import geopandas as geo
from mhs.src.dao.mhs.documents_mhs import *
# from mhs.src.dao.base_dao import DAOMongo
from mhs.src.dao.base_dao import BaseDAO
import pandas as pd
from shapely.geometry.point import Poin... |
from sklearn import datasets
import numpy as np
import tensorflow as tf
mnist = datasets.fetch_mldata('MNIST original', data_home='.')
n = len(mnist.data)
N = 10000
indices = np.random.permutation(range(n))[:N] #ランダムにN枚を選択する:{indices:indexの複数形,permutation:順序を並び替える}
X = mnist.data[indices]
y = mnist.target[indices]
... |
from project.extensions import db
import datetime
class Recipe(db.Model):
__tablename__ = 'receitas'
ID = db.Column(db.Integer, primary_key=True, nullable=False)
titulo = db.Column(db.String(200), nullable=False)
ingredientes = db.Column(db.Text, nullable=False)
modo_preparo = db.Column(db.Text, nu... |
#!/usr/bin/env python
# encoding: utf-8
"""
@author: zhanghe
@software: PyCharm
@file: __init__.py.py
@time: 2017/4/19 下午2:24
"""
from logging.config import dictConfig
from flask import Flask
app = Flask(__name__)
app.config.from_object('config') |
# Generated by Django 2.1.7 on 2019-06-15 18:41
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('HiPage', '0017_auto_20190615_1514'),
]
operations = [
migrations.AddField(
model_name='good_get',
name='Name',
... |
import wx
from apartament_controller import ApartamentController
from AddBillPanel import *
from EditBillPanel import *
from DeleteAllApartamentBillsPanel import *
from DeleteCertainBillsPanel import *
from FindApartamentsByCostPanel import *
from FindCertainBillsOfAllApartaments import *
from validator import IntValid... |
#!/usr/bin/env python
# coding: UTF-8
class Card(object):
"""
マークと数字でカードを生成する
Attributes
----------
value : str
カードの数字
suit : str
カードのマーク
"""
# 数値(インデックスの値を揃える為) ex. values[2] = "2" values[14] = "Ace"
values = (
[None, None, 2, 3, 4, 5, 6,
7, 8, 9,... |
from django.shortcuts import render,HttpResponse
from blog.models import Post
# Create your views here.
def index(request):
posts=Post.objects.all()
context={'posts':posts}
return render(request,'blog/post_list.html',context)
|
import torch
import sys
import torch.nn as nn
import torch.nn.functional as F
import pytorch_lightning as pl
import numpy as np
sys.path.append("./")
exec("from models import pblm")
capacity = 64
class Encoder(nn.Module):
def __init__(self):
super(Encoder, self).__init__()
c = ca... |
from sys import stdin
from _collections import deque
def BFS(n,m):
global queue
queue.append((0,0,1))
while queue:
row, col, cnt = deque.popleft(queue)
# queue.popleft()
if row == n-1 and col == m-1:
print(cnt)
return
if 0 <= row + 1 < n and maze[ro... |
from django.apps import AppConfig
class TorchboxCoreAppConfig(AppConfig):
name = "tbx.core"
label = "torchbox"
verbose_name = "Torchbox"
|
# Desafio 35 Curso em Video Python
# Este programa verifica se 3 comprimentos de retas informados formam um triângulo.
# By Rafabr
import sys
import time
import os
import random
os.system('clear')
print('\nDesafio 35')
print('Este programa verifica se 3 comprimentos de retas informados formam um triângulo.\n\n')
t... |
#!/usr/bin/env python3
import sys
import numpy as np
fi = sys.argv[1]
fo = fi + "--fp16"
data = np.fromfile(fi, dtype=np.float32)
data = data.astype(np.float16)
data.tofile(fo)
|
import os
from scipy import stats
import matplotlib.pyplot as plt
import numpy as np
import csv
#--------------------------------------------------------------------------
# IN TE VULLEN
filename = "02072021.csv" # file name met data
time = 36 # time in minutes between subsequent measurem... |
from setuptools import setup
setup(name='tdwrapper',
version='0.0.1',
description='Teradata utility wrapper for Python',
url='https://github.com/changhyeoklee/tdwrapper',
author='Changhyeok Lee',
author_email='Changhyeoklee@gmail.com',
license='MIT',
packages=['tdwrapper'],
... |
from midge.models.response_code import ResponseCode
ErrorCodesMaps = {
-1: ResponseCode(code=-1, message="AGAIN"),
0: ResponseCode(code=0, message="SUCCESS"),
1: ResponseCode(code=1, message="NOMEM"),
2: ResponseCode(code=2, message="PROTOCOL"),
3: ResponseCode(code=3, message="INVAL"),
4: Res... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.