text stringlengths 8 6.05M |
|---|
import caldav
from caldav.elements import dav, cdav
url = "https://chris.hyser@oracle.com:ATPA29bY@stbeehiveonline.oracle.com/caldav/Oracle/home/chris.hyser@oracle.com/calendars/MyCalendar"
client = caldav.DAVClient(url)
principal = caldav.Principal(client, url)
calendars = principal.calendars()
if len(calendars) > ... |
# Generated by Django 3.0.2 on 2020-03-21 20:50
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('tasks', '0039_auto_20200320_1610'),
]
operations = [
migrations.DeleteModel(
name='UserData',
),
... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
def iris_data_load():
iris = datasets.load_iris()
df = pd.DataFrame(
iris.data,
columns=iris.feature_names
)
df["label"] = iris.target
return df
def kmeans(k, X, max_iter=300):
... |
import uuid
from django.test import TestCase
from model_mommy import mommy
from core.models import get_file_path
class GetFilePathTestCase(TestCase):
def setUp(self):
self.filename = f'{uuid.uuid4()}.png'
def test_file_path(self):
arquivo = get_file_path(None, 'teste.png')
self.... |
import re
from math import floor
from discord import Embed, Color
from discord.ext.commands.errors import CommandInvokeError
from tinydb import Query
from tinydb.operations import set
from time import time
from Utilities.Database import commissionsTable
from Utilities.ConfigurationsHelper import get_configuration
def... |
from random import shuffle
x = ['Tener', 'El', 'Azul', 'Bandera', 'Volar', 'Alto']
shuffle(x)
print(x) |
# -*- coding: utf-8 -*-
# @Author: Fallen
# @Date: 2020-04-03 19:09:03
# @Last Modified by: Fallen
# @Last Modified time: 2020-04-03 21:43:08
'''
小易喜欢的单词具有以下特性:
1.单词每个字母都是大写字母
2.单词没有连续相等的字母
例如:
小易不喜欢"ABBA",因为这里有两个连续的'B'
小易喜欢"A","ABA"和"ABCBA"这些单词
给你一个单词,你要回答小易是否会喜欢这个单词。
'''
def func():
#现有个单词
word = input... |
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, ForeignKey, Integer, String, Boolean, Text, DateTime
from sqlalchemy.orm import relationship
import datetime
Base = declarative_base()
# The user model is kept basic.
# maybe add a realation to blogpost?
class User(Base):
__t... |
import csv
import urllib2
import logging
from models.callout import CallOut
DOWNLOAD_URL_2011 = "http://www.dublinked.ie/datastore/server/FileServerWeb/FileChecker?metadataUUID=8032b927305d45558a3903020e740f63&filename=DCC_FireBrigadeAmbulanceIncidents2011.csv"
def get_file(url):
return urllib2.urlopen(url)
def ge... |
# Generated by Django 2.1.3 on 2018-11-06 10:51
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0021_auto_20181106_2349'),
]
operations = [
migrations.RenameModel(
old_name='Staff',
new_name='Employee',
)... |
# coding=utf-8
# tester, given the config with model path
import tensorflow as tf
import numpy as np
class Tester():
def __init__(self,model,config,sess=None):
self.config = config
self.model = model
self.yp = self.model.yp # the output of the model # [N,M,JX]
def step(self,sess,batch):
# give one batch... |
#!/usr/bin/env /proj/sot/ska/bin/python
#############################################################################################################
# #
# exclude_srouces.py: remove the area around th... |
"""Endpoints Class."""
from fmcapi.api_objects.apiclasstemplate import APIClassTemplate
from .ftds2svpns import FTDS2SVPNs
from fmcapi.api_objects.object_services.fqdns import FQDNS
from fmcapi.api_objects.object_services.hosts import Hosts
from fmcapi.api_objects.object_services.networks import Networks
from fmcapi.a... |
#!/usr/bin/env python
__author__ = "Master Computer Vision. Team 02"
__license__ = "M6 Video Analysis"
# Import libraries
import os
import math
import cv2
import numpy as np
from evaluate import *
from sklearn.metrics import confusion_matrix
from sklearn.metrics import precision_recall_fscore_support as score
# Path ... |
from urllib.request import urlopen
from bs4 import BeautifulSoup
html=urlopen('https://movie.naver.com/movie/running/current.nhn')
soup=BeautifulSoup(html,'lxml')
movie_content=soup.find_all('div',{'id':'content'})
movie_li=movie_content[0].find_all('li')
title_list=[]
score_list=[]
movie_ranking=dict()
for data i... |
from django.contrib.auth.models import User
from .models import Profile
from rest_framework import serializers
class AnalyzerSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ['username', 'email', 'password']
extra_kwargs = {
'password': {
... |
#!/usr/bin/python26
import json
import logging
import MySQLdb
import sys
import threepio
from webob import Request
CONFIG_PATH = '/scripts'
sys.path.append(CONFIG_PATH)
from db_queries import (OBJECT_QUERY_UUID_LOOKUP, SERVICE_ID_FROM_KEY_QUERY)
from configs import (PROV_DB_HOST, PROV_DB_USERNAME, PROV_DB_PASSWORD... |
from .save_class import save_all, load_all |
class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
timestamp = [0] * 1001
for trip in trips:
timestamp[trip[1]] += trip[0]
timestamp[trip[2]] -= trip[0]
used_capacity = 0
for passenger_change in timestamp:
... |
from django.contrib.auth.models import User
from rest_framework import status as s
from .models import Profile
from rest_framework import generics
from . import serializers
from . import permissions
def send_email(email):
print(email)
class Analyzer(generics.ListCreateAPIView):
queryset = Profile.objects... |
config = {
# Сообщения в консоль
"DEBUG": False,
"LOG": False,
# Linter
"LINT": True,
"MAXLENGTH": 160,
"SHOW_SAVE": True,
"SCOP_ERROR": "invalid.mac",
"MAX_EMPTY_LINE": 2,
"SHOW_CLASS_IN_STATUS": False,
"MAX_DEPTH_LOOP": 5,
"MAX_COUNT_MACRO_PARAM": 5,
"LINT_ON_SAVE":... |
'''
Created on Feb 22, 2016
@author: Andrei Padnevici
@note: This is an example of object oriented program in python
'''
from tkinter import Pack
class PartyAnimal:
x = 0
def __init__(self, x=-1):
self.x = x
def party(self):
self.x += 1
print("So far", self.x)
class ChildParty... |
# KVM-based Discoverable Cloudlet (KD-Cloudlet)
# Copyright (c) 2015 Carnegie Mellon University.
# All Rights Reserved.
#
# THIS SOFTWARE IS PROVIDED "AS IS," WITH NO WARRANTIES WHATSOEVER. CARNEGIE MELLON UNIVERSITY EXPRESSLY DISCLAIMS TO THE FULLEST EXTENT PERMITTEDBY LAW ALL EXPRESS, IMPLIED, AND STATUTORY WARRANT... |
import sys
import numpy as np
import itertools
import numpy as np
import subprocess as sub
import matplotlib.pylab as pl
# take as input file with angle definitions, number of angles in first line, .gro for indexes of atom, xtc with trajectory
def mkNdx(ndx,fgro):
#needs ndx-like file with name od dihedral and atom... |
# Designate the Domains
domain1 = "Language"
domain2 = "Memory"
domain3 = "Visuo-spatial"
domain4 = "Motor"
domain5 = "Attention"
domain6 = "Executive Function"
domain7 = "IQ/Academic"
# Prep work for adding the tests
# Create initial menu
language_menu = {
0 : "Add A New Test",
1 : "FAS",
... |
import asyncio
from aioconsole import ainput
from bouquet_design.consumer import Consumer
from bouquet_design.creator import BouquetCreator
from bouquet_design.models import Designs
async def run_consumer():
# '/usr/src/bloomon/sample.txt'
consumer = Consumer()
while True:
# await consumer.handle... |
# -*- coding: utf-8 -*-
"""
J4HR models.
"""
import string
import random
import datetime
from ldap import MOD_REPLACE
from .app import db, ldaptools
class Corporation(db.Model):
__tablename__ = 'corporations'
id = db.Column(db.Integer, primary_key=True) # corporationID
name = db.Column(db.String) # c... |
import math
import torch
import torch.distributed as dist
class RASampler(torch.utils.data.Sampler):
"""Sampler that restricts data loading to a subset of the dataset for distributed,
with repeated augmentation.
It ensures that different each augmented version of a sample will be visible to a
differe... |
str = "cold"
# enumerate()
list_enumerate = list(enumerate(str))
print("list(enumerate(str)) = ", list_enumerate)
# character count
print("len(str) = ", len(str)) |
#coding:utf-8
#基础的图像操作
import numpy as np
import cv2 as cv
#访问和修改像素值
img = cv.imread('D:\python_file\Opencv3_study_file\images\!face.png')
'''
>>> px = img[100,100]
>>> print( px )
[157 166 200]
# 只访问蓝色像素
>>> blue = img[100,100,0]
>>> print( blue )
157
可以用同样的方式修改像素值
>>> img[100,100] = [255,255,255]
>>> print( img... |
from random import randint
import random
class Edge:
def __init__(self, destination):
self.destination = destination
class Vertex:
def __init__(self, value, **pos): #TODO: test default arguments
self.value = value
self.color = 'white'
self.pos = pos
self.edges = []
class Graph:
def __init... |
'''
We create the fibonacci sequence below.
As a refresher, the fibonacci sequence is a recursive sequence in which the last/most-recent term is a sum of the previous two terms
'''
Here, we define the fibonacci sequence in a manner such that there is poor handling of the recursion and thus the program slows down to ba... |
#!bin/python
from functools import reduce
# program assumes valid input
class Vertex:
def __init__(self, name, saturated):
self.name = name
self.saturated = saturated
self.neighbours = []
def addNeighbour(self, vertex):
self.neighbours.append(vertex)
def __eq__(self, othe... |
import re
from dataclasses import dataclass
@dataclass
class Passport:
byr: int
iyr: int
eyr: int
hgt: str
hcl: str
ecl: str
pid: str
def is_valid(self) -> bool:
if not (1920 <= self.byr <= 2002):
return False
if not (2010 <= self.iyr <= 2020):
... |
from math import factorial as fact
for _ in range(int(input())):
n, m = map(int, input().split())
print((fact(m + n) // (fact(m) * fact(n))) % 1000000007)
|
import math
sales = float(input("Enter monthly sales: "))
# while sales > 0:
if sales < 10000:
rate = 0.10
elif sales >= 10000 and sales <= 14999:
rate = 0.12
elif sales >= 15000 and sales <= 17999:
rate = 0.14
elif sales >= 18000 and sales <= 21999:
rate = 0.16
else:
rate = 0.18
... |
import os
import shutil
# open the file, make a list of all filenames, close the file
with open('/foo/list.txt') as names_file:
# use .strip() to remove trailing whitespace and line breaks
names = [line.strip() for line in names_file]
dir_src = '/foo/src'
dir_dst = '/foo/target/'
for file in os.listdir(dir_src):... |
from glorirep import factions
i = 0
for k,v in factions.items():
if v == False:
print k
# i = i + 1
#print i
|
import matplotlib.pyplot as plt
import sympy as sp
#plot the data
from matplotlib.ticker import MultipleLocator
"""when y’s value equals 1 color is “red” ,else “green”, and set the x axis as ‘x_1’ ,
set the y axis as ‘x_2’ , because on the plot the x-axis is the value of parameter ‘x1 ’,
the y-axis is the value of th... |
#!/usr/bin/env python3
import sys, glob, os
import json
if (len(sys.argv) != 2):
print('show_result.py "result_dir_pattern"')
exit(0)
pattern = sys.argv[1]
directories = glob.glob(pattern)
buffer=[]
print('MODEL,TESTSET,ACC,TER,N:HYP:REF:MAX,DATE')
for dir in directories:
try:
date, service, tes... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'test.py'
#
# Created by: PyQt5 UI code generator 5.11.3
#
# WARNING! All changes made in this file will be lost!
import sys,re,json,zipfile,random,string
from PyQt5.QtWidgets import *
from PyQt5 import QtCore
from PyQt5 imp... |
# -*- coding: utf-8 -*-
# /usr/bin/python3
'''
By kyubyong park. kbpark.linguist@gmail.com.
https://www.github.com/kyubyong/g2p
'''
from __future__ import print_function
import tensorflow as tf
import g2p_th
from g2p_th.train import *
from nltk import pos_tag
from nltk.corpus import cmudict
import nltk
from pythainlp.... |
import cx_Oracle
import os, sys, json
import conf
j1 = json.loads(conf
.logdate)
login = j1["login"]
passwords = j1["passwords"]
ip = j1["ip"]
date_name = j1["date_name"]
try:
c_con = login + "/" + passwords + "@" + ip + "/" + date_name
#con = cx_Oracle.connect('login/passwords@ip/date_name')... |
import os
import re
import codecs
import pandas as pd
from ..util import defines
from ..util import file_handling as fh
from ..preprocessing import labels
from ..preprocessing import data_splitting as ds
import html
import common
from codes import code_names
def output_responses(dataset):
print dataset
outp... |
import os
import itertools
import lxml.etree as ET
import re
from os.path import join
import glob
wdir = ""
#inpath = os.path.join("home", "christof", "repos", "dh-trier", "Distant-Reading", "Testdataset", "XML", "")
inpath = join(wdir, "..", "..", "Testdataset", "XML", "")
outpath = os.path.join("", "Testoutput", "... |
# 재귀를 사용하여 팩토리얼(factorial)을 구하는 함수를 구현해주세요. 팩토리얼이란 1에서부터 n까지의 정수를 모두 곱한것을 말합니다.
def factorial(n):
if n <= 1:
return 1
return n * factorial(n-1)
factorial(n-1)
factorial(5) |
import random
from django.shortcuts import render, get_object_or_404
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from mainapp.models import *
from mainapp.classes import BreadCrumb
# Create your views here.
def get_common_context():
categories = Category.objects.all()
menu_list =... |
a = int(input())
b = int(input())
print("%d" % ((a*4 + b*6) / 10))
|
import re
import numpy as np
import matplotlib.pyplot as plt
import gc
import MySQLdb
con = MySQLdb.Connection(host="localhost", user="root",
passwd="lin", port=3306)
cur = con.cursor()
con.select_db('recordworking')
try:
fil = open("getdata.txt", "r")
except:
print "file open failed"
... |
import secrets
import tempfile
import textwrap
import time
from pathlib import Path
import pytest
from ai.backend.client.exceptions import BackendAPIError
from ai.backend.client.session import Session
# module-level marker
pytestmark = pytest.mark.integration
def aggregate_console(c):
return {
'stdout':... |
#importation de modules
import requests
#import pandas as pd
import bs4
from bs4 import BeautifulSoup
import requests
#application
#crawling through all the pages associate to the chosen technologies
def get_pages(token, key_words, nb_pages):
pages = []
if type(key_words) != list or type(nb_pages) != i... |
import math
from time import time
import random
def fastpower(a,b):
if b == 1:
return a
else:
c = a*a
answer = fastpower(a,math.floor(b/2))
if b %2 != 0:
return a*answer
else:
return answer
def analyze():
wins = 0
loses = 0
total_diffs = []
for _... |
# This program is to demonstrate how to create a class, an object and how to call them.
class exampleClass: # This is how to you create/define a class (line 3-16)
name = "Loisa"
age = 22
eyes = "black"
height = 5.6
def thisMethod(self): # This is normally how you define a function, but within a class, all functi... |
#!/usr/bin/env /data/mta/Script/Python3.6/envs/ska3/bin/python
#################################################################################################
# #
# update_grating_obs_list.py: update grating obser... |
n = int(input('Digite um número: '))
i = n % 2
if i == 0:
print('O número {} é par'.format(n))
else:
print('O número {} é ímpar'.format(n)) |
#!/usr/bin/env python3
import csv
import pdb
import requests
from bs4 import BeautifulSoup
def read_in_journal_data():
volumes = []
with open('yearly_volumes.csv', 'r') as csv_file:
reader = csv.reader(csv_file, delimiter=',')
next(reader)
for row in reader:
journal_data... |
from django.conf.urls import patterns, include, url
from django.views.static import *
import settings
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^points/', include ('points.urls')),
# Examples:
# url(r'^$',... |
import unittest
from katas.beta.compare_section_numbers import compare
class CompareSectionNumbersTestCase(unittest.TestCase):
def test_equal_1(self):
self.assertEqual(compare('1', '2'), -1)
def test_equal_2(self):
self.assertEqual(compare('1.1', '1.2'), -1)
def test_equal_3(self):
... |
from flask import Blueprint, render_template, redirect, url_for, session, flash
from datetime import date
from flask.globals import request
from .__init__ import db
inventory = Blueprint('inventory', __name__)
@inventory.route('/inventory')
def inv():
if not session:
return redirect(url_for('auth.login'))... |
# Generated by Django 3.1.5 on 2021-02-28 21:08
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
ope... |
from aiogram import Bot, Dispatcher, types
from bot.states.SQLAlchemyStorage import SQLAlchemyStorage
from config import BOT_TOKEN
bot = Bot(token=BOT_TOKEN, parse_mode=types.ParseMode.HTML)
storage = SQLAlchemyStorage()
dp = Dispatcher(bot, storage=storage)
|
import PIL
import tensorflow as tf
import pathlib
data_dir = pathlib.Path("../data/flower_photos")
image_count = len(list(data_dir.glob('*/*.jpg')))
print(image_count)
roses = list(data_dir.glob('roses/*'))
PIL.Image.open(str(roses[0]))
|
from typing import Optional
import pygame as pg
from abc import ABC, abstractmethod, ABCMeta
class ScreenType(ABCMeta):
pass
class Screen(ABC, metaclass=ScreenType):
@abstractmethod
def draw(self, screen: pg.Surface, clock: pg.time.Clock) -> Optional[ScreenType]:
pass
|
# coding: utf-8
# Standard Python libraries
from pathlib import Path
import tarfile
from .. import load_run_directory
def reset_orphans(run_directory, orphan_directory=None):
"""
Resets calculations that were moved to an orphan directory back to a
run directory and removes any bid files that they contain.... |
from flask import Flask, render_template, request, redirect, url_for, jsonify
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from database_setup import Base, Restaurant, MenuItem
app = Flask(__name__)
engine = create_engine('sqlite:///restaurantmenu.db')
Base.metadata.bind = engine
DBSe... |
import matplotlib.pyplot as plt
import torch
from torchvision.utils import draw_bounding_boxes, draw_segmentation_masks
from torchvision import tv_tensors
from torchvision.transforms.v2 import functional as F
def plot(imgs, row_title=None, **imshow_kwargs):
if not isinstance(imgs[0], list):
# Make a 2d gr... |
from pyspark import SparkContext, SparkConf
import sys
import time
import multiprocessing
start_time = time.time()
# Get Data Grouped by user_id or business_id Based on Case Number
def get_grouped_data(ungrouped_data):
# User_id case
data_p = ungrouped_data.map(lambda s: (s[0], s[1]))
data_grouped = data_p\
.map... |
from decimal import Decimal, DecimalException
from django.forms import ValidationError
from ....fields import DecimalField
from .widgets import BRDecimalInput
class BRDecimalField(DecimalField):
widget = BRDecimalInput
def to_python(self, value):
value = value.replace(',', '.')
value = valu... |
from typing import final
import numpy as np
import cv2
import pandas as pd
import os
import argparse
import glob
import random
import math
import matplotlib.pyplot as plt
from hdrtool import hdr # test purpose
output_path = ''
output_file = 'output.jpg'
response_curves = []
# the weight function for single pixel
d... |
from django.urls import path
from . import views
app_name='login'
urlpatterns=[
path('',views.index,name='index'),
path('auth',views.auth,name='auth'),
path('logout',views.logout,name='logout')
]
|
from tkinter import *
import glob, time
class veld:
def __init__(self, tk):
self.tk = tk
self.canvas = Canvas(self.tk, width=700, height=700)
self.canvas.pack()
self.tk.update()
self.images = self.load_img()
self.vakjes()
self.straten()... |
"""
Django settings for EwhaEverytimeEverywhere project.
Generated by 'django-admin startproject' using Django 3.0.8.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/se... |
import urllib2
from bs4 import BeautifulSoup
import re
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
from xlrd import open_workbook
from xlwt import easyxf
from xlutils.copy import copy
import os
excel_address = r'/Users/zhoufengting/Desktop/replacingg_player_away_2013_2014.xls'
work_book = open_workbook(ex... |
from gym_gomoku.envs.util import make_random_policy as policy
|
from flask import Blueprint, current_app, request, jsonify
from .model import Batidas_Ponto
from .serializer import PontoSchema
bp_ponto = Blueprint('Batidas_Ponto', __name__)
@bp_ponto.route('/cadastrar_ponto', methods=['POST'])
def cadastrar():
dados = request.get_json(force=True)
usuario_id = dados['u... |
"""
find_element_by_id
find_element_by_id
find_element_by_xpath
find_element_by_link_text
find_element_by_partial_link_text
find_element_by_tag_name
find_element_by_class_name
find_element_by_css_selector
_________________________
from selenium.webdriver.common.by import By
example: button = browser.find_element(By.ID... |
import cv2
import numpy as np
#siyah bir zemin olusturuyoruz.
img = np.zeros((512,512,3),np.uint8)
#5 piksel kalinliginda diagonal mavi bir cizgi cizdiriyoruz. Cizginin ozellikleri
#size kalmis, 8 bitlik degerleri istediginiz gibi degistirebilirsiniz.
cv2.line(img,(0,0),(511,511),(255,0,0),5) #cizgi cizim... |
num = list()
for i in range(0, 5):
num.append(int(input(f'Digite o {i+1}º número: ')))
if i == 0:
menor = maior = num[i]
posmenor = posmaior = str(i)
else:
if num[i] < menor:
menor = num[i]
posmenor = str(i)
elif (num[i] == menor):
posmenor... |
from src.cdp.Habilidades import Resistencia
from src.util.FabricaNaves import FabricaNave
class FabricaNaveJogador(FabricaNave):
def __init__(self, nome, figura_nave, figura_explosao, som):
super(FabricaNaveJogador).__init__(nome, figura_nave, figura_explosao, som)
self.tempoMissel = 0
sel... |
#scipy.signal.istft example
#https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.istft.html
#
import numpy as np #added by author
from scipy import signal
import matplotlib.pyplot as plt
#Generate a test signal, a 2 Vrms sine wave at 50Hz corrupted by 0.001 V**2/Hz of white noise sampled at 1024 Hz.
#テス... |
#!/usr/bin/python
import sys
from collections import defaultdict as dfdict
import csv
import logging
import copy
"""Optional feature flag. Set to 0 if you don't want to analyze the optional feature."""
optional_feature_flag = 0
if optional_feature_flag:
from numpy import average as ave
logger = logging.getLogg... |
#program to find the greatest of two numbers
fno=int(input("Enter the first number"))
sno=int(input("Enter the second number"))
if fno>sno:
print("First number is greater that second number")
elif fno<sno:
print("Second number is greater than the first number")
else:
print("Both the numbers are equal") |
from typing import List
from sklearn.feature_extraction.text import TfidfVectorizer as SklearnTfidfVectorizer
from kts_linguistics.string_transforms.abstract_transform import AbstractTransform
from kts_linguistics.string_transforms.transform_pipeline import TransformPipeline
from kts_linguistics.misc import SparseMat... |
#!/usr/bin/python
# By: Cowart, Dominique A 9.17.16
# file io lib
import sys
# Goal: open a text file and change words "free" to "proprietary"
# define the path to the file
in_file = "manifesto"
out_file = "manifesto_out"
# obtain a file handle to open
fh = open(in_file, "r")
fh2 = open(out_file, "w")
# read each... |
"""
Odd Even Linked List
Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking
about the node number and not the value in the nodes.
You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity.
Example 1... |
#coding: utf-8
import speech_recognition as sr
from gtts import gTTS
from sys import stdin
from os import system
class SpeakWithTheRobot:
"""
A class created to enable the user to have a conversation with the "robot" utilizing the system proposed.
...
Methods
-------
listen()
The soft... |
#!/usr/bin/python3
a=(3,4)
b=(5,4)
c=(6,4)
def produit_c(z1, z2): # produit entre un complexe et un autre complexe
return (z1[0]*z2[0]-z1[1]*z2[1], z1[0]*z2[1]+z1[1]*z2[0])
def produit_r(r, z): # produit entre un réel et un complexe
return (z[0]*r, z[0]*r)
def somme(z1, z2):
return (z1[0]+z2[0], z1[1]+z2[1])
... |
import pandas as pd
import torch
from torchvision import transforms
from tqdm import tqdm
from nn import BengaliNet
from utils.preprocess import preprocess
def test(model, test_images, transform, batch_size=192):
"""Test the model by predicting classes of unseen images.
Args:
model = [nn.Modul... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import time
import logging
import os
import sys
from functools import partial
import numpy as np
import tensorflow as tf
from tensorflow.python.ops import variable_scope as vs
from tensorflow.python.ops import ... |
def format_date(day, month, year):
if month > 12:
return None
if month == 1 and day > 31:
return None
elif day > 31 and month == 3:
return None
elif day > 31 and month == 5:
return None
elif day > 31 and month == 7:
return None
elif day > 31 and month == 8... |
# == vs is
# == for value equality check but "is" keyword is used for check whether same memory location
print(True == 1) # True
print('1' == 1) # False
print([] == []) # True
# is (check for memory reference
print(True is 1) # False
print("1" is 1) # False
print([] is []) # False
print(True is True) # True
... |
import torch
import torch.nn as nn
class Encoder(nn.Module):
def __init__(self, input_size, latent_size):
super(Encoder, self).__init__()
"""
Parameters:
----------
input_size : int
Input dimension for the data.
latent_size : int
Latent space... |
from scanner import openFile, readNextWord, getSymbolsToIDs
import sys
SEMICOLON=1
DERIVES=2
ALSODERIVES=3
EPSILON=4
SYMBOL=5
EOF=6
symbolNames = ["NONE/ERROR", "SEMICOLON", "DERIVES", "ALSODERIVES", "EPSILON", "SYMBOL", "EOF"]
symbolPending = None
# Of form: {NonTerm1 : [NT1Prod1, NT1Prod2, ...]; NonTerm2 : [...];... |
# The design of virtual assistant
import random
import os
import datetime, calendar
import wikipedia
import speech_recognition as sr
from gtts import gTTS
from va_utils import recordAudio, vaSpeechResponse, vaWakeUpCall, getInfoFromWikipedia
from playsound import playsound
speech_text = None
while True:
speech_... |
# File: EPL_Transceiver.py
# Celine Liu <tzuchung1030@gmail.com>
# Date: 2011/02/22
# version: dynamic payload length
import signal
import time
from threading import Thread
#from msvcrt import getch
from EPL_Transceiver_Param import *
Tx_Rx = 0
KeyEvent_Stop = False
data_length = [0x20,0x20,0x20,0x20,0x20,0x... |
from django.db import models
from datetime import datetime
# Create your models here.
# how would my modle look for this particlar task where i dont have to
#form
class Country(models.Model):
name= models.CharField(max_length=50)
def __str__(self):
return self.name
class Category(models.Model):
... |
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 12 20:08:03 2020
@author: hui94
"""
import tensorflow as tf
import numpy as np
import idx2numpy
import cv2
from PIL import Image
from tensorflow import keras
from tensorflow.python.ops import resources
from tensorflow.contrib.tensor_forest.python import ten... |
import numpy as np
import cv2
import os
import random
import pandas as pd
class ImageDataLoader():
def __init__(self, data_path, gt_path, shuffle=False, gt_downsample=False, pre_load=False):
# small data, pre_load set to True is faster
self.data_path = data_path
self.gt_path = gt_path
self.gt_downsample = gt_... |
def MAPE(pred, test):
pred, test = np.array(pred), np.array(test)
sum = 0
for i in range(7):
if test[i] != 0:
sum += abs((test[i] - pred[i]) / test[i])
return (sum / 7) * 100
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression, Lass... |
#encoding:utf-8
#!/usr/bin/python
import MySQLdb
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
def mysql(f):
def _deco(*args):
conn = MySQLdb.connect(host = 'localhost', user = 'lfs', passwd = 'lfs653', db = 'todoDB', port = 3306, charset = "utf8")
cur = conn.cursor()
kwargs = {
'cur':cur
}
r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.