text stringlengths 8 6.05M |
|---|
import os
# 当前工程文件绝对路径
BASE_PATH = os.path.dirname(os.path.abspath(__file__))
if __name__ == '__main__':
print(BASE_PATH)
|
"""Plot page shell and instantiate word-plotting class."""
import numpy as np
import xmlPlotWords
from matplotlib import pyplot as plt
from matplotlib.patches import Rectangle
class xmlPlotPage(object):
def __init__(self, data, page_line_data, manual_firms):
self.lines_dict = page_line_data[0]
s... |
import os
from ..custom.video_dataset_adapter import VideoDatasetAdapter
from .skoltech_cameras_calibration_factory import SkoltechCamerasCalibrationFactory
from ..data_transform_manager import DataTransformManager
from ..unsupervised_depth_data_module import UnsupervisedDepthDataModule
from ..video_dataset import Vid... |
"""
Python code that will be transpiled to JS to implement the client side.
"""
from pscript.stubs import window, document, undefined, Math, Date # JS
from pscript.stubs import data_per_db, text_color # are made available
panels = []
# %% Button callbacks
def toggle_utc():
info = get_hash_info()
if inf... |
<<<<<<< HEAD
print("Hello Git!")
=======
print ("hello")
print ("Bye")
print ("Step 14 of task one")
>>>>>>> master
|
from rest_framework import permissions, serializers, routers
from rest_framework import generics, mixins, viewsets
from rest_framework.response import Response
from rest_framework import status
from rest_framework.decorators import action
from ..my_models import poetry
import logging
logger = logging.getLogger(__name... |
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 31 10:17:39 2019
@author: elif.ayvali
"""
import scipy.io as sio
import numpy as np
import vtk
delta_t=0.5
class VTK_Tools:
def addSTL(filename, color,opacity):
STL_reader = vtk.vtkSTLReader()
STL_reader.SetFileName(filename)
S... |
from selenium import webdriver
from time import sleep
from smtplib import SMTP
from credentials import email, password
class Coronavirus():
def __init__(self):
self.driver = webdriver.Chrome()
def get_data(self):
country_element = "India"
sleep(4)
search_field = self.driver.find_element_by_xpath... |
# import sys
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import ConfigParser
import time
import datetime
import os
# import requests
# import re
# from contextlib import closing
import subprocess
# from selenium.common.exceptions import NoSuchElementException
class episodeList:
d... |
"""
WRITTEN BY : Mahnatse, Yanga, Allen, Sibusiso, Thabo and Zweli
DATE : 13 November 2019
COHORT : C17 Data Science
COHORT MANAGER : Singi
GROUP LEADER : Zweli
"""
#------------------------------------------------------------------------------------
"""
PROBLEM
Given two lis... |
"""
Parsing with PEGs.
"""
import re
# Glossary:
# peg object representing a parsing expression
# p, q peg
# s subject sequence. Usually a string, but only match() assumes that.
# i position in subject sequence
# far box holding the rightmost i reached so far
# (except during ... |
import game_framework
from game_object import *
class Ball(GameObject):
PPS = 100
def __init__(self, x, y, dx, dy):
super(Ball, self).__init__()
self.x, self.y = x, y
self.dx, self.dy = dx, dy
self.size = 22
self.w, self.h = 22, 22
self.angle = 1.0
self.s... |
import json
import random
import os
'''a=os.path.isfile("arr.json")
if a:
myfile = open("arr.json")
data = myfile.read()
with open("arr.json","r") as f:
data = json.load(f)
length = len(data)
for key in data:
data[key] = key + str(random.uniform(0,20))
with open("arr.json","w") as f:
json.dump(data,... |
#!/usr/bin/env python
import os
import pycurl
import sys
import time
class LCGDM974(object):
"""
Test for https://its.cern.ch/jira/browse/LCGDM-974
"""
def _header(self, header):
splitted = header.split(':', 1)
if len(splitted) == 2:
self.received_headers[splitted[0]] = splitted[1].strip()
return len(h... |
import argparse
from gooey import Gooey
from imclassify import ImClassifier
def try_int(x):
try:
return int(x)
except ValueError:
return x
@Gooey(program_name='imclassify')
def main():
ap = argparse.ArgumentParser()
ap.add_argument('-l', '--labels', default='class_1 class_2 class_3',... |
from flask import Flask
from flask_cors import CORS
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
import os
project_dir = os.path.dirname(os.path.abspath(__file__))
database_file = "sqlite:///{}".format(os.path.join(project_dir, "db/research.db"))
app = Flask(__name__)
CORS(app)
app.config... |
"""the user manager for the server."""
import hashlib
from twisted.python.filepath import FilePath
class UserManager(object):
"""
The UserManager manages the user paths.
:param path: path where the files will be stored.
:type path: str or FilePath
"""
def __init__(self, path):
if isin... |
from aiogram.utils.callback_data import CallbackData
from .mixins import ActionsMixin
from app.utils.singleton import singleton_class
@singleton_class
class MainMenu(ActionsMixin):
"""This class consist of text buttons of main menu"""
def __init__(self):
self.parent = None
self.data = (
... |
class Solution:
def minDepth(self, root: Optional[TreeNode]) -> int:
def recur(cur):
if not cur.left and not cur.right:
return 1
mini = float('inf')
if cur.left:
mini = min(mini, 1+recur(cur.left))
if cur.right:
... |
#!usr/bin/env python
import json
import hashlib
try:
from Tkinter import * # PYTHON 2
import tkFont
from urllib2 import urlopen
except ImportError:
from tkinter import * # PYTHON 3
import tkinter.font as tkFont
from urllib.request import urlopen
class Window(Frame):
'''An api GUI template that is modified fo... |
import unittest
import subprocess
import os
import diskspace
from diskspace import subprocess_check_output
from diskspace import bytes_to_readable
from diskspace import show_space_list
class TestDiskspace(unittest.TestCase):
def setUp(self):
self.command = 'du '
self.abs_directory = os.path.abspa... |
import os
import json
from database.database import DataBase, DBLoader
from prepare.structure import Project
def load_local_json(path, fn):
fp = os.path.join(path, fn + ".data")
if os.path.isfile(fp):
with open(fp, "r") as f:
data = json.load(f)
else:
print("file path {} is wro... |
def add(*num):
total = 0
for n in num:
total += n
print(total)
add(2,3,4,5,6)
def calculate(**kwargs):
print(type(kwargs))
calculate(add=3, multiply=5) |
from itertools import groupby
def encode(s):
return ''.join(k + str(sum(1 for _ in g)) for k, g in groupby(s))
|
from rest_framework import serializers
from announcements.models import Announcement
from datetime import datetime
class AnnouncementSerializer(serializers.ModelSerializer):
is_new =serializers.SerializerMethodField()
def get_is_new(self, obj):
res = Announcement.objects.get(pk=obj.id)
if res.... |
from tweepy import OAuthHandler
from tweepy import API
from tweepy import Cursor
from datetime import datetime, date, time, timedelta
from collections import Counter
import sys
consumer_key=""
consumer_secret=""
access_token=""
access_token_secret=""
consumer_key = "P5wTozEUuNOAJCXMajGnRcDs2"
consumer_secret = "RB7p2... |
from configparser import ConfigParser
parser = ConfigParser()
CONF='/Users/edmelnik/Library/CloudStorage/iCloud Drive/Documents/GitHub/inserttest/inserttest.config'
parser.read(CONF)
insertnum = parser['inserttest_config']['insert_number']
if insertnum == '6':
print(insertnum)
|
from nfd_router_client import RouterClient
import subprocess
import time
import socket
import json
class FirewallEM(object):
def __init__(self, logger, vnfm_host, vnfm_port):
#TODO: keep trace of configuration
self.configuration = {"append-drop":[]}
self.logger = logger
print ("cr... |
#!/usr/bin/env python
# Copyright (c) 2013 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Make sure msvs_large_pdb works correctly.
"""
import TestGyp
import struct
import sys
if sys.platform == 'win32':
print "This test ... |
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import json
from dataclasses import dataclass
from enum import Enum
from typing import Any, Optional, Union
from pants.backend.project_info.peek import... |
from user_input import prompt
def intro():
print("Welcome to Shmucksburg: A knightless town in a dangerous world.")
prompt("")
print("Your name is Cecil. Cecil Farmer.\n")
prompt("You're a farmer.\n")
prompt("You leave your cabin one morning and walk to the townsquare. \
You can hear the beautif... |
#!/usr/bin/env python
'''
Test_pycosat.py
'''
#############
# IMPORTS #
#############
# standard python packages
import copy, inspect, logging, os, shutil, sqlite3, sys, time, unittest
# ------------------------------------------------------ #
# import sibling packages HERE!!!
if not os.path.abspath( __file__ + "... |
import json
diccionario=input()
miDiccionario=json.loads(diccionario)
lista=input().split()
listaComprables=[]
#print(miDiccionario)
suma=0
for i in lista:
if i in miDiccionario.keys():
listaComprables.append(i)
suma+=miDiccionario[i]
print(suma)
for j in listaComprables:
print(j,end=" ")
print("")
|
import functools
import json
import os
import random
import shutil
from abc import ABC, abstractmethod
from glob import glob
from pathlib import Path
from typing import Callable, cast, List, Optional, Tuple, Union
import numpy as np
from PIL import Image
from .utils import _read_pfm, download_and_extract_archive, ver... |
from json import loads
from flask import (render_template, Blueprint,
request, jsonify, redirect, url_for, abort)
# imports dos modulos
from manticora.controllers.modules.register import (register_user,
register_rest,
... |
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import glob
import time
import numpy as np
import os
import pandas as pd
paths = os.getenv('ENSEMBLING', None)
if None == paths:
paths = [
# glob.glob(os.getenv('PREDICTING') + '.simple')[0],
... |
import unittest
from katas.kyu_8.function_within_function import always
class AlwaysTestCase(unittest.TestCase):
def setUp(self):
self.three = always(3)
def test_equals(self):
self.assertEqual(self.three(), 3)
|
from typing import Any, cast, Dict, List, Optional, Tuple, Union
import PIL.Image
import torch
from torch.utils._pytree import tree_flatten, tree_unflatten
from torchvision import tv_tensors
from torchvision.ops import masks_to_boxes
from torchvision.prototype import tv_tensors as proto_tv_tensors
from torchvision.tra... |
#!/usr/bin/env python
# coding: utf-8
# Copyright (c) Qotto, 2019
import os
import logging
from colorlog import ColoredFormatter
import argparse
import uvloop
import asyncio
from signal import signal, SIGINT
# Import KafkaProducer / KafkaConsumer
from tonga.services.consumer.kafka_consumer import KafkaConsumer
from t... |
# Check If Adjacent Cells Contain Consecutive Numbers
# var0 is checked with all the variables in argv
# argv may contain non-fixed number of variables
def adjacency(var0, *argv):
passed = False
for var in argv:
passed = passed or abs(var0 - var) == 1
if passed: break
return... |
#!/usr/bin/python
import socket
import time
import threading
import json
import random
import argparse
import sys
from Queue import Queue
from concurrent import futures
def get_args():
"""
Get command line args from the user.
"""
parser = argparse.ArgumentParser(
description='Standard Argument... |
../mysqlconnection.py |
__author__ = 'Elisabetta Ronchieri'
def get_longest_string(elements):
max_length,longest_element = max([(len(element),element) for element in elements])
return max_length,longest_element
def add_empty_space(current_len, longest_len):
number = longest_len - current_len + 4
return ' '.ljust(number)
|
# Import the modules
import cv2
from sklearn.externals import joblib
from skimage.feature import hog
import numpy as np
import matplotlib.pyplot as plt
grid_line_x = 9
grid_line_y = 8
################################
###############################
#
#
#
#
def areacon(contours,area,sub):
count=0
for i i... |
from django.db import models
# Create your models here.
# 创建一个类, 创建一个数据库table
class Student(models.Model):
stu_name = models.CharField(max_length=16)
stu_age = models.IntegerField(default=1)
|
# Copyright (c) 2017-2023 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
from __future__ import annotations
from typing import Sequence
def unmangle_name(s: str) -> str:
"""
Convert a name with ``$uXXXX`` character runs into their original... |
"""
Irj programot, mely beker ket egesz szamot, es kiirja az osszeguket.
"""
|
# -*- coding: utf-8 -*-
import sys,os,time
class cls:
t= None
def __init__(self):
print 'cls'
def p2(self):
pass
|
def combine(a, b, a_len, b_len):
i = a_len - 1
j = b_len - 1
full_length = len(a)
while (i >= 0 and j >= 0):
if (a[i] > b[j]):
a[full_length - 1] = a[i]
i -= 1
else:
a[full_length - 1] = b[j]
j -= 1
full_length -= 1
if (i < 0):
... |
def fact(x):
if x==1 or x==0:
return 1
else:
return x*fact(x-1)
t=input()
for i in range(t):
n=input()
print fact(n) |
#!/usr/bin/env python
# -*- coding=utf-8 -*-
__author__ = 'Man Li'
import os
import re
import sys
import time
import json
import random
import requests
from requests.exceptions import ReadTimeout, ConnectionError, RequestException
import csv
import hashlib
from lxml import etree
import redis
import urllib
from multi... |
# -*- encoding: utf-8 -*-
#########################################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2014-TODAY Probuse Consulting Service Pvt. Ltd. (<http://probuse.com>).
#
# This program is free software: you can redistribute it and... |
# encoding=utf8
from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
import numpy
import sys
try:
reload(sys)
sys.setdefaultencoding('utf-8')
except NameError:
pass
extensions = [
Extension('im2col_cython', ['im2col_cython.pyx'],
include_dirs = [... |
from newsletter.models import User
from django.forms import ModelForm
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
class SubscribeForm(ModelForm):
"""
Form that allows a user to input his or her email address and select a city
from a list of the top 100 U.S. cities by ... |
# This is used for generating the Keybox file which used for applying Widevine/Attestation keybox.
from sys import argv
script, first, second, third, fourth = argv
# fileName: Keybox index file which contain the device ID.
# prefix: prefix name which contain the project name for device ID, such as: ME... |
class PeopleService(object):
def __init__(self, people_repository):
self.repository = people_repository
def get_all(self):
people = self.repository.get_all()
return [person['name'] for person in people]
def get_friends(self, name):
raw_friends = self.repository.get_f... |
# -*- coding: utf-8 -*-
import ECDSA
from queue import Queue
import random
# 초기화
def init():
print("확장된 스택 프로세서 입니다.")
print("메시지 소유권을 지정하고 확인합니다.\n")
stack = []
cnt = 5
return stack, cnt
# 남은 카운트 프린트
def print_cnt(cnt):
if cnt <= 0:
print("남은 기회가 없습니다.")
else:
p... |
# -*- coding: utf-8 -*-
from flask import request, Blueprint
from flask import g
import logging
from libs.crossdomain import crossdomain
from libs.util import make_response
from libs.util import create_access_token
from libs.response_meta import ResponseMeta
from .authorization import require_client_auth
from models.u... |
def convertWeapon(weapon):
blademaster = __isBlademaster(weapon)
newWeapon = {}
newWeapon['affinity'] = __intOrNone(weapon.get('Affinity'))
newWeapon['attack'] = __intOrNone(weapon.get('Attack'))
newWeapon['create_price'] = __filterString(weapon.get('Create_Price'))
newWeapon['defense'] = __intO... |
import json
import os
from discord.ext.commands import Bot
from database import DB
from google_search import fetch_search_results
### Load Discord Token from environment on PROD
### Otherwise load it from local file
DISCORD_TOKEN = os.environ.get('DISCORD_TOKEN')
if DISCORD_TOKEN is None:
env_config = json.lo... |
# Generated by Django 2.1 on 2018-08-12 20:58
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
('campaigns', '0002_auto_20180812_2358'),
('lists', '0001_i... |
import mysql.connector
database = "production"
inputDb = mysql.connector.connect(
host="localhost",
user="root",
passwd="password",
database=database
)
print(inputDb)
# Dropping The semantics Tables
mycursor = inputDb.cursor()
mycursor.execute("SHOW TABLES")
db = mycursor.fetchall() # Fetches all the... |
import csv
import pprint
import matplotlib.pyplot as plt
import math
path = '/Users/yutaro/research/2020/src/build/'
with open(path+'ground_truth.csv') as f:
#print(f.read())
readf = list(csv.reader(f))
with open(path+'resultZ=0.1115.csv') as g:
readg = list(csv.reader(g))
l = []
lr ... |
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import contextlib
import json
import os.path
from dataclasses import dataclass
from typing import Any, Mapping
import yaml
from pants.backend.openapi.t... |
from django.contrib import admin
from django.conf.urls import url, include
from django.conf import settings
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf import settings
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf.urls.static import static... |
import tkinter as tk
from tkinter import filedialog
def open_handler():
name = tk.filedialog.askopenfilename(filetypes=(("file","*.jpg"),("All Files","*.*") ))
print(name)
def button_hanadler(r_v):
print(r_v)
mainwindow=tk.Tk()
mainwindow.geometry("640x340")
mainwindow.title("sensor data ")
menubar=tk.M... |
import config
import time
from network import WLAN
from network import Server
# Conexion a la WiFi
wlan = WLAN(mode=WLAN.STA) # Modo adaptador wifi
wlan.connect(config.wifi_ssid, auth=(None, config.wifi_pass)) # Orden y parámetros de conexión a la red wifi
if config.REPL:
while not wlan.isconnected():
... |
####sss666
read_csv 177
sys.stdout###np.sys.stdout
to_csv(cols)##columns
分隔符 182页 不太懂哎哎。
class 那一段。
web信息也迷迷糊糊。(主要是无法删除空格)
from lxml.html import parse
from urllib.request import urlopen
parsed=parse(urlopen('http://finance.yahoo.com/q/op?s=AAPL+Options'))
doc=parsed.getroot()
tables=doc.findall(... |
from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader
from django.shortcuts import render
from django.views.decorators.csrf import csrf_protect
from django.template import Context
import json
from .models import ParkingSlots
from django.http import QueryDict
from .... |
from django.db import models
from apps.main.models import *
from apps.resources.models import *
import csv
with open("EXP_REENTRY.csv",'rb') as f:
reader = csv.reader(f)
your_list = list(reader)
all_resource_types = ResourceType.objects.all()
for resource_type in all_resource_types:
print resource_type
in... |
"""
Pygameは日本語の表示が苦手。日本語を表示するには、print(pygame.font.get_fonts())で
各パソコンで使用できる日本語フォントを調べ、それを指定する方法があるが、
Pygameで使える日本語フォントはPCごとに違ううえ、種類が限られている。
そこでIPAフォントを用いて日本語を表示する方法がある。
"""
import pygame
import sys
# 白
WHITE = (255, 255, 255)
# 黒
BLACK = (0, 0, 0)
def main():
# pygameモジュールの初期化
pygame.init()
# ウィンドウに... |
from mlmicrophysics.models import DenseNeuralNetwork
from mlmicrophysics.data import subset_data_files_by_date, assemble_data_files
import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler, MinMaxScaler, MaxAbsScaler, RobustScaler, OneHotEncoder
from sklearn.metrics import confusion_matri... |
from socket import AF_INET, socket, SOCK_STREAM
from threading import Thread
import time
from datetime import datetime
class Server:
def __init__(self):
self.__clients = {}
self.__addresses = {}
self.__HOST = ''
self.__PORT = 33001
self.__BUFSIZ = 1024
self.__SERVER... |
# List Class
class ListNode:
def __init__(self, data=0, next=None):
self.data = data
self.next = next
# Search for a key, O(n)
def search_list(L:ListNode, key: int) ->ListNode:
while L and L.data != key:
L = L.next
# If key was not present in the list, L will have become null
return L
# Insert new node af... |
from django.urls import path
from django.http import HttpResponse
def view(request):
return HttpResponse()
urlpatterns = [
path('', view),
]
|
"""
# Linked-list 实例
"""
import os
class Node(object):
def __init__(self, value, next=None):
self.value = value
self.next = next
def rotate_right(head: Node, k: int) -> Node:
"""给定一个链表,循环向右移动k个节点。
如给定链表1->2->3->4->5,k=2,则返回循环右移2个节点后的链表:4->5->1->2->3。
思路:设置2个指针,前一个先向前移动k个节点,然后两个节点同步向前... |
# -*- coding: utf-8 -*-
# @Time : 2019-12-21
# @Author : mizxc
# @Email : xiangxianjiao@163.com
from werkzeug.security import generate_password_hash, check_password_hash
from flask import current_app, request, flash, render_template, redirect, url_for, session
from flask_login import login_user, logout_user, log... |
# -*- coding: utf-8 -*-
from math import prod
from typing import List
class Solution:
def subtractProductAndSum(self, n: int) -> int:
digits = self.getDigits(n)
return prod(digits) - sum(digits)
def getDigits(self, n: int) -> List[int]:
digits = []
while n:
digits... |
# Generated by Django 2.2.4 on 2019-09-11 01:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('job', '0004_jobopening_send_cv_directly'),
]
operations = [
migrations.AlterField(
model_name='jobopening',
name='me... |
"""
束线元件位置
作者:赵润晓
日期:2021年4月24日
"""
# 因为要使用父目录的 cctpy 所以加入
from os import error, path
import sys
sys.path.append(path.dirname(path.abspath(path.dirname(__file__))))
from hust_sc_gantry import HUST_SC_GANTRY
from cctpy import *
g = HUST_SC_GANTRY(
DL1=900.78*MM,
GAP1=430.15*MM,
GAP2=370.82*MM,
qs1_len... |
#from base_case import base_case
import base_case
class case_existing_file(base_case.base_case):
'''File exists.'''
def test(self, handler):
return os.path.isfile(handler.full_path)
def act(self, handler):
self.handle_file(handler, handler.full_path)
class case_no_file(base_case.base_cas... |
from spack import *
from glob import glob
from string import Template
import re
import os
import fnmatch
import sys
import shutil
class Fwlite(CMakePackage):
"""CMSSW FWLite built with cmake"""
homepage = "http://cms-sw.github.io"
url = "https://github.com/gartung/fwlite/archive/refs/tags/11.3.1.2.tar.gz... |
from typing import Tuple, Optional
import torch
from torch import nn, Tensor
from parseridge.parser.modules.attention.soft_attention import Attention
from parseridge.parser.modules.utils import initialize_xavier_dynet_, mask_
class UniversalAttention(Attention):
def __init__(
self,
query_dim: in... |
# Python Coroutines and Tasks.
# Coroutines declared with async/await syntax is the preferred way of writing asyncio applications.
#
# To actually run a coroutine, asyncio provides three main mechanisms:
#
# > The asyncio.run() function to run the top-level entry point “main()” function.
# > Awaiting on a corout... |
from waitress import serve
from endpoint import app
if __name__ == "__main__":
# execute only if run as a script
app.run(debug=True)
|
from util import get_image, save_image, main
def download_many(page_number):
for page in range(1, page_number + 1):
image = get_image(page)
save_image(image, '{page:03}.jpg'.format(page=page))
return page_number
if __name__ == '__main__':
main(download_many)
|
import contextlib
import functools
import operator
import os
import pkgutil
import platform
import sys
import warnings
from collections import OrderedDict
from tempfile import TemporaryDirectory
from typing import Any
import pytest
import torch
import torch.fx
import torch.nn as nn
from _utils_internal import get_rela... |
from classifier import NaiveBayseClassifier
from data_helper import load_data
from utils import printResult
import numpy as np
import argparse
"""
This program demonstrate the process of naive bayes classifier
The usage of my scratch is just like sklearn
Moreover, the style to load the data is just like ke... |
from django.shortcuts import redirect
from django.views.generic import CreateView
from todo.models import *
class TaskCreateView(CreateView):
template_name = "task/form.html"
model = Task
success_url = '/story'
fields = ('body', 'end', 'status',)
def form_valid(self, form):
fk = self.kwargs.get('fk')
story =... |
from enum import Enum
from math import floor
from tkinter import messagebox
import random
import pygame
class Maze:
ARENA_HEIGHT = 10
ARENA_WIDTH = 10
ARENA_SIZE = ARENA_WIDTH * ARENA_HEIGHT
class Node:
def __init__(self):
self.visited = False
self.canGoRight = False
... |
#!/usr/bin/python3
# functions.py by Bill Weinman [http://bw.org/]
# This is an exercise file from Python 3 Essential Training on lynda.com
# Copyright 2010 The BearHeart Group, LLC
def main():
testfunc(3,5,6,one =1, two = 2, four = 42)
#keyword arguements are also optional and are treated as dictionaries
def tes... |
from kfp.components import OutputPath
def download(dataset_path: OutputPath(str)):
import json
import os
import tempfile
import zipfile
import requests
from tqdm import tqdm
# Download GloVe
print("Downloading glove")
GLOVE_DIR = dataset_path + "/data/glove"
os.makedirs(GLOV... |
length = 33
iter_ = (x for x in range(length)) #0,1,2
c = 0
while 1:
try :
print(next(iter_))
except StopIteration :
break
howkteam = {'name' : 'Kteam', 'kter':69}
# list_values = list(howkteam.items())
# print(list_values)
# print(list_values[0])
# print(list_values[1])
for key, value in how... |
from .accounts import AccountTests
from .collections import CollectionsTests
from .discover import DiscoverTests
from .feed import FeedTests
from .friendships import FriendshipTests
from .live import LiveTests
from .locations import LocationTests
from .media import MediaTests
from .misc import MiscTests
from .tags impo... |
#!/usr/bin/python3
"""
Lists all states from the database hbtn_0e_0_usa where name matches
with the given argument.
"""
import MySQLdb
from sys import argv
if __name__ == '__main__':
try:
db = MySQLdb.connect(
host="localhost",
port=3306,
user=argv[1],
pass... |
# Generated by Django 2.1.2 on 2018-11-24 15:31
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blogs', '0002_comment_client_commit'),
]
operations = [
migrations.RemoveField(
model_name='comment',
name='commit',... |
from django.urls import path
from bye import views
urlpatterns = [
path('index/', views.index),
path('byestu/', views.bye_student),
path('getstu/', views.get_student),
path('updatestu/', views.update_student), # root url, include下级
path('deletestu/', views.delete_student),
]
|
import xml.etree.ElementTree as ET
filename = '{{ .VARIABLE }}'
tree = ET.parse(filename)
root = tree.getroot()
for child in root:
print(child.tag, child.attrib)
|
from jsonschema import Draft7Validator
from utils import *
SCHEMA_REMISE_DOMAINE = {
TYPE: OBJECT,
PROPERTIES: {
"trigrammeSIP": STRING_TYPE,
"idCorrelation": STRING_TYPE,
"idUtilisateurRemettant": STRING_TYPE,
"idEntiteRemettante": INTEGER_TYPE,
"idTypeBien": STRING_TY... |
# Copyright 2023 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import itertools
import json
import logging
import os.path
from abc import ABC
from dataclasses import dataclass, field
from typing import Any, ClassVar,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.