text stringlengths 38 1.54M |
|---|
import mysql.connector
mydb = mysql.connector.connect(
host ='localhost',
user ='root',
password ='Rithic@2002',
database ='attendance'
)
mycursor = mydb.cursor()
Name = input("Enter the name of the user")
Present_or_absent = input("Enter the attendance of the user")
Reg_No = input("Enter the registration number"... |
import copy
import dataclasses
from enum import Enum
import json
from interference.transformers.transformer_pipeline import Instance
from interference.scoring import ScoringCalculator
import numpy
# FIXME: Huge hack... From https://github.com/python/cpython/blob/6b1ac809b9718a369aea67b99077cdd682be2238/Lib/dataclasse... |
# VMware vCloud Python helper
# Copyright (c) 2014 Huawei, Inc. All Rights Reserved.
#
# 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
... |
import requests
import time
header = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:62.0) Gecko/20100101 Firefox/62.0'}
class imformation():
def __init__(self,dbhost,userurl,userpassword,dbpassword,username ,usermail):
self._dbhost = dbhost
if dbpassword == '':
self._dbp... |
import caffe
import numpy as np
import argparse
import os
import sys
def find_in_bottom(net,id,start):
i=start+1
while i<len( net.layers):
ids=net._bottom_ids(i)
if id in ids:
return i
i=i+1
return -1
def find_in_top(net,id,start):
i=start-1
while i>=0:
... |
#!/usr/bin/python
#-*- coding:utf-8 -*-
#Quick python script explanation for programmers
#给程序员的脚本解说
#导入模块
import os,sys
def main():
#声明单行字符串,使用单双引号都行,若字符串中有引号需转义 \'
print( 'hello world!')
print( '这是Bob\'的问候')
foo(5,10)
#字符串可乘,等同于==========
print ('=' * 10)
print ('这将直接执行' + 'hello worl... |
if __name__ == '__main__':
t = int(input())
while t > 0:
n = int(input())
arr = list(map(int, input().strip().split()))
k = int(input())
try:
print(arr.index(k))
except:
print(-1)
t-=1
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
import random
import tqdm_utils
def test_vocab(vocab, PAD, UNK, START, END):
return [
len(vocab),
len(np.unique(list(vocab.values()))),
int(all([_ in vocab for _ in [PAD, UNK, START, END]]))
]
def test_captions_indexing... |
"""
Mixing Peer State and RPC Interface
"""
import asyncio
import aiozmq.rpc
class MixingPeer(rpc.AttrHandler):
def __init__(self):
self.addr = None
self.peer_id = None # hash of public key? easier to use than index which needs to assigned and reassigned
self.n_input_peers = 0
sel... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from django.utils.translation import ugettext_lazy as _
MIN_PASSWORD_LEN = 6
VERIFY_CODE_EXPIRED_TIME = 5 * 60 # 5 minutes
TEMP_IMAGE = os.path.join(os.path.dirname(__file__), 'temp.jpg')
TEMP_VIDEO = os.path.join(os.path.dirname(__file__), 'temp.mp4')
PROFILE_F... |
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import tensorflow as tf
old_v = tf.logging.get_verbosity()
tf.logging.set_verbosity(tf.logging.ERROR)
import numpy as np
import matplotlib.pyplot as plt
model_dir = os.path.join(os.getcwd(), "model")
if not os.path.exists(model_dir):
os.makedirs(model_dir)
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
###############################################################################
###############################################################################
######## V1.4 2021/08/25 francescopiscitelli ######################
######## script to read the p... |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^login/$', views.userlogin, name='login'),
url(r'^logout/$', views.userlogout, name='logout')
]
|
#!/usr/bin/env python3
import argparse
import logging
import time
import platform
import math
import re
import json
import iso8601
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.sql import table, column, select, update
from datetime import datetime
import paho.mqtt.client a... |
# -*- coding: utf-8 -*-
import logging
logger = logging.getLogger('[sm.idonethis]')
from datetime import datetime
from datetime import timedelta
from zope.component import getMultiAdapter
# from zope.publisher.interfaces import NotFound
import plone.api
from plone.memoize import view
from Products.Five.browser impo... |
# coding: utf-8
# In[2]:
import cv2
import numpy as np
# # Contour - tracks continuous edges
#
# The contour retrieval modes are as follows
#
# cv2.RETR_EXTERNAL
#
# cv2.RETR_LIST
#
# cv2.RETR_CCOMP
#
# cv2.RETR_TREE
#
# The contour approximation modes are as follows
#
# cv2.CHAIN_APPROX_NONE
#
# cv2.CHAI... |
from operator import *
class QueryResult:
def _init_(self, url, title, pagerank):
self.url= url
self.title= title
self.pagerank= pagerank
def _repr_(self):
return repr((self.url, self.title, self.pagerank))
#Store file index into an array
f= open('index.txt', 'r')
index= []
lin... |
from selenium import webdriver
from bs4 import BeautifulSoup
import time
import pickle
import os
import random
import math
import yaml
import sys
import argparse
with open("config.yml", 'r') as ymlfile:
cfg = yaml.load(ymlfile, Loader=yaml.SafeLoader)
driver = webdriver.Chrome(cfg['WebDriverPath'])
def login_and... |
from random import *
class HealthPotion():
#Constructs a name, the amount in the potion, and if it is large or small
def __init__(self, contain, category):
self.contain = contain
self.category = category
#Gets what kind of potion it is
def get_potion_type(self):
if self... |
# calculates sum of two linked lists
class ListNode (object):
def __init__(self, x):
self.val = x
self.next = None
def add_two_numbers(node, l1, l2, c =0):
if (not(node)):
node = ListNode((l1.val + l2.val + c) % 10)
else:
node.next = ListNode((l1.val + l2.val + c) % 10)
... |
'''
Build a dataset with train-val-test splits from the generated data from
'''
import sys; sys.path.insert(0, '../util')
from platform_config import data_dir, mkdir2
import os, glob, random, math
from os.path import join
from shutil import copy2
import numpy as np
# for converting to indexed images
from PIL import ... |
from django.conf.urls import url
from . import views
app_name = 'telegram_bots'
urlpatterns = [
url(
regex=r'^$',
view=views.BotListView.as_view(),
name='list',
),
url(
regex=r'^(?P<pk>\d+)/$',
view=views.BotDetailView.as_view(),
name='detail',
),
url... |
import torch
from torch.utils.data import DataLoader
from data.jigsaw_dataset import JigsawDataset, JigsawTestDataset
from data.rotate_dataset import RotateDataset, RotateTestDataset
from data.image_dataset import ImageDataset, ImageTestDataset
from data.concat_dataset import ConcatDataset
from data.transformer... |
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
@Time : 2020/5/11 20:44
@Auth : 可优
@File : handle_parameterize.py
@IDE : PyCharm
@Motto: ABC(Always Be Coding)
@Email: keyou100@qq.com
@Company: 湖南省零檬信息技术有限公司
@Copyright: 柠檬班
-------------------------------------------------... |
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.conf.urls.static import static
# Uncomment the next two lines to enable the admin:
#from django.contrib import admin
#admin.autodiscover()
import views
urlpatterns = patterns('',
url(r'^$', views.index, name='in... |
from task_management.ticktick import util
from task_management.ticktick.entities.ticktick_task import TicktickTask
import json
class TicktickApi:
def task(self, context, params):
'''Get tasks '''
access_token = context["headers"]["access_token"]
project_id = params.get("project_id")
... |
from MyCollections.LinkedList import LinkedList
class ListQueue:
def __init__(self):
self._data = LinkedList()
def enqueue(self, value):
self._data.insertAtTail(value)
def dequeue(self):
return self._data.pop_head()
def is_empty(self):
return (self._data.size() == 0... |
import json
class Settings():
def __init__(self):
with open("config.json", "r") as f:
data = json.load(f)
self.coordinates = data["coordinates"]
self.hight = data["hight"]
self.azimut_ahgle_cam = data["azimut_ahgle_cam"]
self.ip_camera = data["ip_camera"]
... |
# -*- coding: utf-8 -*-
# @Author: mithril
from __future__ import unicode_literals, print_function, absolute_import
import pandas as pd
import json
from collections import Counter
df = pd.read_excel('CorpusCharacterlist.xls')
chars = set(df.iloc[:, [1]].values.flatten())
with open('wubi_all.json') as f:
d = js... |
import logging
import os
import sys
from django.contrib.auth import get_user_model
from django.core.management.commands.test import Command as BaseCommand
import pandas
from core.models import Link
User = get_user_model()
logger = logging.getLogger(__name__)
def import_link(user: User, link: str):
try:
... |
import csv, sys
from robot import robot, check_command
print '#########################'
print '## Toy Robot Simulator ##'
print '######### IMPORT ########'
print '#########################'
print ''
print ''
filename = sys.argv[1]
commands = []
with open(filename) as csvfile:
reader = csv.DictReader(csvfile)
for ... |
from __future__ import annotations
from prettyqt import constants, gui
class TextTableFormat(gui.textframeformat.TextFrameFormatMixin, gui.QTextTableFormat):
def __bool__(self):
return self.isValid()
def set_alignment(self, alignment: constants.AlignmentStr | constants.AlignmentFlag):
"""Set... |
from __future__ import division, print_function
from matplotlib import pyplot as plt
import matplotlib
import seaborn as sns
import pandas as pd
import numpy as np
from utils.utils import get_commenters_dataframe, locaP, locaC, geod_world, geod_china
dataframe = get_commenters_dataframe()
def df_preprocess():
d... |
# -*- coding: utf-8 -*-
#! \file ./tests/test_support/test_cmd/test_eval.py
#! \author Jiří Kučera, <sanczes@gmail.com>
#! \stamp 2016-04-18 18:07:39 (UTC+01:00, DST+01:00)
#! \project DoIt!: Tools and Libraries for Building DSLs
#! \license MIT
#! \version ... |
from canvasapi import Canvas
from canvas_zoom_breakouts.canvas_zoom_breakouts import canvas_zoom_breakouts
CANVAS_API_URL="https://canvas.iastate.edu"
# See: https://canvasapi.readthedocs.io/en/stable/
# Obtain CANVAS_API_KEY by going to your Canvas
# account settings, scrolling to "Approved Integrations"
# and selec... |
# _*_ coding: utf-8 _*_
from numpy import *
## logistic函数是要寻找一种最佳拟合方法,这一点与线性方程非常类似
## 但它使用了梯度下降法来最快速地寻找数据
## 这使得它对多参数的二分类比较适合
class LogisticDemo:
def sigmoid(self, inX):
return 1.0 / (1 + exp(-inX))
## 梯度下降法求最佳拟合参数
## 拟合了500次
def fit_gradAscent(self, dataMatIn, classLabels):
dataMatrix = mat(dataMatIn) ... |
import os
import sys
import parseEmail
from collections import defaultdict
def generateAllEgdeList(folderName,value=['To', 'From'],all_sent=['sent','_sent_mail','sent_items','_sent'],start_date='1 1 1998',end_date='31 12 2002'):
"""Return an edgeList for all the emails
value: the differe... |
loop_couter = 0
while True:
print("Hello world")
loop_couter += 1
if loop_couter >= 3:
break
|
from Log import Log
import numpy as np
from physics_sim_fixed import PhysicsSim
class Task():
"""Task (environment) that defines the goal and provides feedback to the agent."""
def __init__(self, init_pose=None, init_velocities=None,
init_angle_velocities=None, runtime=10., target_pos=None, log=None):... |
from paddle.utils import try_import
from paddlenlp.transformers.albert.tokenizer import AlbertEnglishTokenizer
class ReformerTokenizer(AlbertEnglishTokenizer):
resource_files_names = {
"sentencepiece_model_file": "spiece.model",
}
pretrained_resource_files_map = {
"sentencepiece_model_file... |
from utils.cab import Cab
from utils.googlemaps import GoogleMaps
from utils.execute_queries import ExecRawQuery
|
# Write a Python program to guess a number between 1 to 9. Go to the editor
# Note : User is prompted to enter a guess. If the user guesses wrong then the prompt appears again until the guess is correct, on successful guess, user will get a "Well guessed!" message, and the program will exit.
x=int(input("value of x"))
... |
import scrapy
from scrapy.exceptions import CloseSpider
from scrapy.loader import ItemLoader
from ..items import MerkantibankItem
from itemloaders.processors import TakeFirst
class MerkantibankSpider(scrapy.Spider):
name = 'merkantibank'
start_urls = ['http://www.merkantibank.com/English/corporate/news/2016/defaul... |
import socket
import protocol_utils as protocolUtils
socket_instance = socket.socket()
socket_instance.connect((protocolUtils.host, protocolUtils.port))
num1 = input("Ingrese un numero: ")
num2 = input("Ingrese un numero: ")
op = input("Ingrese la operacion a realizar: ")
message_builder = protocolUtils.MessageBuilde... |
import scrapy
import os
os.system("scrapy crawl BillBoard_Spider")
#os.system("scrapy crawl BoardSongs_Spider")
#os.system("scrapy crawl Music_Spider")
|
#
# Copyright (C) 2020-2021 Arm Limited or its affiliates and Contributors. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
"""Module in charge of handling SPDX documents.
SPDX file (i.e. tag-value format)
https://github.com/OpenChain-Project/curriculum/blob/master/guides/including_license_info.rst
https:... |
from typing import List
from fastapi import APIRouter, Depends, HTTPException
from pydantic import PositiveInt
from sqlalchemy.orm import Session
from . import crud, schemas
from .database import get_db
router = APIRouter()
@router.get("/suppliers/{id}", response_model=schemas.Supplier2)
async def get_supplier(id:... |
#William U. Clark, Jr.
#netrek@wuclark.com
#save player one player's stats from statdump to file
#usage findPlayer.py PNUM input output
#!/usr/bin/env python
import sys
inData = open(sys.argv[2],'r').readlines()
outFile = open(sys.argv[3],'w')
for line in inData:
if line.startswith('STATS_SP_PLAYER:\t%d\t'%int(sys.a... |
# 加入上下文的gate2 in model5
# 添加多级先验知识,并且上一层级得到的[1,d]的score会传入下一层的下一级的计算中,使用的每层计算的权重是两个[d,1]的
import tensorflow as tf
class ModelConfig(object):
def __init__(self):
self.EMBEDDING_DIM = 128 # 词向量维度
self.FACT_LEN = 30 # 事实长度
self.LAW_LEN = 30 # 法条长度
self.KS_LEN = 3 # 先验知识长度
... |
import unittest
from src.dl.flaskapp.transactions.parsers.transaction_factory import TransactionReaderFactory
from src.dl.flaskapp.transactions.parsers.csv_readers import CapitalOneAutoDataReader
class TransactionFactoryTest(unittest.TestCase):
def test_is_capital_one_auto_trans(self):
the_reader = Transa... |
'''
Test requirements according to R4
'''
from unittest.mock import patch
from qa327_test.conftest import base_url
from qa327_test.frontend.geek_base import GeekBaseCase, TEST_USER
from qa327.models import Ticket
from qa327.ticket_format import parse_date
# Test Information
GOOD_TICKET = Ticket(
name='helloworld... |
import database
from flask import Blueprint, make_response, json, request
import pymongo
from bson.objectid import ObjectId
# Blueprint Configuration
doc_bp = Blueprint('sort_bp', __name__,
template_folder='templates',
static_folder='build/',
url_prefix='/')
db... |
from __future__ import division, print_function
from pdb import set_trace
import pandas as pd
import numpy as np
from os import walk
from random import randint as randi, seed as rseed
__author__ = 'rkrsn'
def where(data):
"""
Recursive FASTMAP clustering.
"""
rseed(0)
if isinstance(data, pd.core.frame.DataFr... |
# --------------
import pandas as pd
from sklearn.model_selection import train_test_split
#path - Path of file
# Code starts here
df = pd.read_csv(path)
X = df.drop(['customerID','Churn'],1)
y = df['Churn'].copy()
X_train, X_test, y_train, y_test = train_test_split(X,y, test_size = 0.3, random_state = 0)
# ------... |
import collections
import json
from typing import Dict, NamedTuple
import torch
import torch.distributed as dist
import torch.nn as nn
from absl import app
from absl import flags
from absl import logging
from torch.utils.data import distributed as dist_data
import trainer
import utils.tensorboard as tb
... |
# Copyright 2019 NEC 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/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writi... |
#!/usr/bin/env python
import numpy
import os
import logging
import re
import itertools
import matplotlib.pyplot as plt
from pymatgen.io.abinitio.works import RelaxWork
from pymatgen.io.abinitio.tasks import TaskManager
from pymatgen.io.abinitio.flows import Flow
from pymatgen.io.abinitio.strategies import RelaxStrate... |
# print a table of n upto 10 recursively
def print_table(n: int, limit: int) -> None:
if limit == 0:
return 0
print_table(n, limit-1)
print(f"{n} * {limit} = {n*limit}")
if __name__ == "__main__":
print_table(20, 10)
print_table(0, 0)
|
import paramiko
import subprocess
class Precondition(object):
@staticmethod
def put_file(machine_name, user_name, dir_name, filename, data):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(machine_name, username=user_name)
sftp ... |
# Exercício Python 073: Crie uma tupla preenchida com os 20 primeiros colocados da Tabela do Campeonato Brasileiro
# de Futebol, na ordem de colocação. Depois mostre:
# a) Os 5 primeiros times.
# b) Os últimos 4 colocados.
# c) Times em ordem alfabética.
# d) Em que posição está o time da Chapecoense.
brasileir... |
import numpy as np
import math
from itertools import chain
from collections import Counter
from project.utils.counting import counts_to_probs
from project.utils.text import strip_junk_tokens
################################################################################
# Binary bag of words featurizer
###########... |
import torch
import torch.nn as nn
import torch.nn.functional as F
class ResBlock(nn.Module):
def __init__(self, input_channel, output_channel, act):
super(ResBlock, self).__init__()
self.conv1 = nn.Conv2d(input_channel, output_channel, 3, 1, 1)
self.bn1 = nn.BatchNorm2d(output_channel)
... |
#The question being answered is: Does playing in your home continent make a difference?
#Load in packages needed
import pandas as pd
#Load in Datasets
cups = pd.read_csv('/Users/ethanmitten/Desktop/Data Analytics/Python Projects/WorldCupDataset/WorldCups.csv')
matches = pd.read_csv('/Users/ethanmitten/Desktop/Data An... |
from django.db import models
class NameManager(models.Manager):
def get_unused(self):
"""
Returns all unused entities.
"""
return self.filter(used=False)
def get_used(self):
"""
Returns all used entities.
"""
return self.filter(used=True)
d... |
def neighbors(current, grid):
size_x = len(grid[0])
size_y = len(grid)
res = []
if current[0] - 1 >= 0:
res.append((current[0] - 1, current[1]))
if current[0] + 1 < size_x:
res.append((current[0] + 1, current[1]))
if current[1] - 1 >= 0:
res.append((current[0], current[1... |
#!/usr/bin/env python
# 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 writing, software
... |
# Copyright (c) Meta Platforms, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from habitat_sim._ext.habitat_sim_bindings import (
Mp3dObjectCategory,
Mp3dRegionCategory,
SceneGraph,
SceneNode,
Sce... |
from django.contrib import admin
from django.urls import path, include
from markdownblog.urls import router as blog_router
urlpatterns = [
path('admin/', admin.site.urls),
path('api/',include(blog_router.urls)),
path('markdownx/', include('markdownx.urls')),
]
|
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from collections import Counter
import csv
import sys
df = pd.read_csv('movie_metadata.csv')
df_edited = df.drop(["color", "num_critic_for_reviews", "actor_3_facebook_likes", "actor_1_facebook_likes",\
"num_voted_... |
from typing import (
Tuple,
)
from terminaltables import AsciiTable
from user import UnixUser
def _fmt_members(members: Tuple[str]):
return ",".join(members)
def _fmt_users(users: Tuple[UnixUser]):
return list([user.name, user.uid, user.group.name, user.gecos or "", user.home_dir, user.shell, _fmt_memb... |
# -*- coding: utf-8 -*-
import os
import numpy as np
from .Template import wrap, Specifications, Template, expr_dir
def generate_unitconversions(args=None):
with Specifications("unitconversions.yml") as specs:
unitconversions = specs["unitconversions"]
units = []
abbrs = []
uni... |
import urllib.request
import re
# Check if the URL is well formed
def check_url_sanity(url):
regex = re.compile(
r'^(?:http|ftp)s?://' # http:// or https://
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' #domain...
r'localhost|' #localhost.... |
#Write a python script to generate list of no. 0 to 100. Filter out even and odd numbers using lambda + filter function.
list1=[]
for i in range(100):
list1.append(i)
even = list(filter(lambda x: x%2 == 0, list1))
print(even)
print("\nOdd numbers from the said list:")
odd = list(filter(lambda x: x%2 != 0, li... |
import datetime
import pytz
from dateutil.parser import parse
epoch = datetime.datetime.utcfromtimestamp(0)
epoch = epoch.replace(tzinfo=pytz.UTC)
TIME_FORMAT = '%Y-%m-%d %H:%M:%S %z'
# TODO: take mplotlib madates conversion take into consideraiton
def string_to_datetime(str_):
""" translate a formatted string... |
row, cols = map(int, input().split())
mine = int(input())
arr = [[0 for i in range(cols)] for j in range(row)]
for i in range(mine):
_row, _cols = map(int, input().split())
arr[_row-1][_cols-1] = "*"
for R in range(row):
for C in range(cols):
if arr[R][C] == "*":
for _R in range(R-1, R+2... |
# Databricks notebook source
# RDD, Resilient Distributed Data Set
data = [1,2,3,4,5,6,7,8,9]
# Spark Context
rdd1 = sc.parallelize(data) # load the input into cluster memory
print("max ", rdd1.max())
# to run it, Shift + Enter key
# COMMAND ----------
print("Min", rdd1.min())
print("mean", rdd1.mean())
print("sum... |
#Test Average and Grade
def calc_average(a,b,c,d,e):
average = (a+b+c+d+e)/5
print('Average:',average)
def determine_grade(a):
if a >=90 and a <= 100:
print('A')
elif a >= 80 and a <= 89:
print('B')
elif a >= 70 and a <= 79:
print('C')
elif a >= 60 and a <= 69:
pr... |
# Prompt: Write code that takes a long string and builds its word cloud
# data in a dictionary ↴ , where the keys are words and the values are the number
# of times the words occurred. Think about capitalized words.
string1 = "After beating the eggs, Dana read the next step:"
def split_words(s):
letters = []
... |
import sqlite3
from sqlite3 import Error
def create_connection(clothes):
""" create a database connection to a SQLite database """
conn = None
try:
conn = sqlite3.connect(clothes)
print(sqlite3.version)
except Error as e:
print(e)
finally:
if conn:
conn.... |
# -*- coding: utf-8 -*-
from pylowiki.tests import *
def addComment():
return 'commentAddHandler_root'
def addComment_text():
return 'comment-textarea'
def addComment_submit():
return 'reply'
def addConversation():
return 'addDiscussion'
def addConversation_text():
return 'text'
def addConvers... |
from copy import deepcopy
import random
# Consider using the modules imported above.
class Hat:
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
self.contents = list()
for key, value in kwargs.items():
for x in range(value):
self.contents.append(key)
de... |
import psycopg2
import psycopg2.extras
if __name__ == '__main__' :
connection_string = "host= 'localhost' dbname='resort' user='resort' password='resort'"
conn = psycopg2.connect(connection_string,cursor_factory=psycopg2.extras.DictCursor )
###this part is to drop the existed tables and the data we ha... |
"""
High-level functions used across the CAP-Toolkit package.
"""
import h5py
import numpy as np
import pyproj
import xarray as xr
import pandas as pd
from scipy.spatial import cKDTree
from scipy.spatial.distance import cdist
from scipy import stats
from scipy.ndimage import map_coordinates
try:
from gdalconst imp... |
admin_message = "Let me know how you are doing!"
admin_message += "\nHow are you doing? "
hayd = input(admin_message)
print(f"You are doing {hayd}")
car_message = input("Enter the car you're looking for: ")
print(f"Let's see if we can find a {car_message} for you.")
seating = input("How many people are you seating?... |
import argparse
import hashlib
import os
from bs4 import BeautifulSoup as bs
import requests
from time import ctime, time
address = "http://hotspot.abu.edu.ng/login"
def main():
try:
parser = argparse.ArgumentParser()
parser.add_argument("-u", "--usernames", help="specify a file cont... |
import os
def _stop_and_close(qtbot, v):
if os.environ.get('PHY_TEST_STOP', None): # pragma: no cover
qtbot.stop()
v.close()
|
import orekit
orekit.initVM()
# Modified from https://gitlab.orekit.org/orekit-labs/python-wrapper/blob/master/python_files/pyhelpers.py
from java.io import File
from org.orekit.data import DataProvidersManager, DirectoryCrawler
from orekit import JArray
orekit_data_dir = 'orekit-data'
DM = DataProvidersManager.getIn... |
Autocube Numbers
Autocube numbers are numbers having "n" digits such that the last n digits of the cube of the number will be the number itself. Write an algorithm and the subsequent Python code to check if the given number is autocube. Write a function to find the cube of a given number.. For example, 25 is a 2 dig... |
from __future__ import annotations
import functools
import os
import pathlib
from typing import (
TYPE_CHECKING, Any, ClassVar, Dict, List, Literal, Tuple, Type,
)
import param
from bokeh.models import ImportedStyleSheet
from bokeh.themes import Theme as _BkTheme, _dark_minimal, built_in_themes
from ..config i... |
import argparse
class CLA:
"""Command line arguments class"""
def __init__(self):
self.parser = argparse.ArgumentParser(description="Some description!")
self.parser.add_argument(
"-i", action="store", dest="input_file", type=str, required=True
)
self.parser.add_arg... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author: hao 2019/11/21-20:00
from datetime import datetime
from pymongo import MongoClient
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
class BossJob:
def __init__(sel... |
# -*- coding: utf-8 -*-
"""
Created on Sun May 26 11:21:31 2019
@author: yoelr
"""
from biosteam.evaluation import Model, Metric
from biosteam.evaluation.evaluation_tools import triang
import biosteam.biorefineries.lipidcane as lc
import numpy as np
__all__ = ('lipidcane_model', 'lipidcane_model_with_lipidfraction_pa... |
"""PurbeurreConfig
"""
from django.apps import AppConfig
class PurbeurreConfig(AppConfig):
"""PurbeurreConfig for purbeurre app
Args:
AppConfig ([type]): [description]
"""
name = 'purbeurre'
|
"""
AA, February 2021
Assignment 3: Contagem dos Itens Mais Frequentes
Author: Ana Sofia Fernandes, 88739
"""
from Reader.File_reader import File_reader
from collections import Counter
import time
from tabulate import tabulate
##Class that acts as an exact counter and counts the occurences of each char in... |
import warnings
from PySide2.QtCore import Qt, QObject, Slot, Signal, Property
from PySide2.QtWidgets import QWidget, QVBoxLayout, QGridLayout, QButtonGroup, QCheckBox
import pyqtgraph as pg
import numpy as np
import topside as top
def trim_earlier(array, t):
"""
Return the portion of an array falling after... |
def print_dictionary_values(dic):
for some_key, some_value in dic.iteritems():
print "My" + " " + some_key + " " + "is" + " " + str(some_value)
print print_dictionary_values({
"name": "Tom",
"age": 30,
"country of birth": "USA",
"favorite language": "English"
}
)
|
from typing import Callable, Dict, List, Tuple, Union
import numpy as np
from .binary_metrics import get_stats, iou_score
__all__ = [
"pairwise_pixel_stats",
"pairwise_object_stats",
"panoptic_quality",
"average_precision",
"aggregated_jaccard_index",
"dice2",
"iou_multiclass",
"dice_... |
import logging
import json
from pyspark.sql import SparkSession
from pyspark.sql.types import *
import pyspark.sql.functions as psf
# TODO Create a schema for incoming resources
schema = StructType([
StructField("crime_id", StringType(), False),
StructField("original_crime_type_name", StringType(), True),
... |
from django.urls import path, re_path
from . import views
urlpatterns = [
#quiz and question api
path('api/quiz_question/<int:pk>/', views.QuizQuestionDetail.as_view()),
path('api/quiz_result/<int:quiz_id>/', views.QuizResult.as_view()),
path('api/full_quiz/<int:pk>/', views.FullQuizDetail.as_vi... |
## Standard Include Stanza
from __future__ import division
import pygame
from pygame.locals import *
import sys
import getopt
import csv
import time
import os
import random
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.