index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
2,900 | 67a76f1f1dad4b7e73359f04ca8f599c8d32dc92 | #encoding:UTF-8
from numpy import *
#----------------------------------------------------------------------
def differences(a, b):
""""""
c = a[a!=b]
d = b[a!=b]
nums = nonzero(a!=b)[0]
return concatenate((mat(nums), c, d)).T |
2,901 | d5cb875dc31ca3dd7b165206415c346a076dd6e4 | import db
data = {'python book': ['10.09.2019', 200, 50, False]}
def test_insert_and_get_db(data):
db.insert(data)
result = db.get_db()
return result == data
if __name__ == '__main__':
print(f' Test insert dict in to db, and get dict from db is {test_insert_and_get_db(data)}')
print(... |
2,902 | 332c530d221c9441d6ff3646f8e9226dc78067f9 |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2020 sungminoh <smoh2044@gmail.com>
#
# Distributed under terms of the MIT license.
"""
You are given coins of different denominations and a total amount of money. Write a function to compute the number of combinations that make up that a... |
2,903 | 7613dde4f49044fbca13acad2dd75587ef68f477 | import time
import argparse
import utils
from data_loader import DataLoader
from generate_model_predictions import sacrebleu_metric, compute_bleu
import tensorflow as tf
import os
import json
from transformer import create_masks
# Since the target sequences are padded, it is important
# to apply a padding mask when c... |
2,904 | 45cdf33f509e7913f31d2c1d6bfada3a84478736 | # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
# Copyright (c) 2018 Juniper Networks, Inc.
# All rights reserved.
# Use is subject to license terms.
#
# Author: cklewar
import os
import threading
import time
from jnpr.junos import Device
from jnpr.junos import exception
from jnpr.junos.utils.config im... |
2,905 | 3d5d88edca5d746b830363cc9451bda94c1d7aa4 | # -*- coding: utf-8 -*-
from plone import api
from plone.dexterity.content import Container
from sc.microsite.interfaces import IMicrosite
from zope.interface import implementer
@implementer(IMicrosite)
class Microsite(Container):
"""A microsite."""
def getLocallyAllowedTypes(self):
"""
By no... |
2,906 | 33464f19c42d1a192792a73297f4d926df78ab71 | # -*- coding: utf-8 -*-
"""
Created on 11/03/2020
@author: stevenp@valvesoftware.com
"""
import sys
from PyQt5.QtWidgets import (QApplication, QWidget, QLabel, QRadioButton, QVBoxLayout, QCheckBox, QProgressBar,
QGroupBox, QComboBox, QLineEdit, QPushButton, QMessageBox, QInputDialog, QDialog, QDialogButton... |
2,907 | 6c3f60f05adbebe521ba08d7a7e9fc10b1cc914f | import html
import logging
import re
import pyarabic.araby as araby
ACCEPTED_MODELS = [
"bert-base-arabertv01",
"bert-base-arabert",
"bert-base-arabertv02",
"bert-base-arabertv2",
"bert-large-arabertv02",
"bert-large-arabertv2",
"araelectra-base",
"araelectra-base-discriminator",
"... |
2,908 | 8baf61a20a64f296304b6a7017a24f1216e3d771 | from django.db import models
from django.contrib.auth.models import User as sUser
TYPES = (
('public', 'public'),
('private', 'private'),
)
#class GroupManager(models.Manager):
# def get_all_users(self):
# return self.extra(where=['users'])
class Group(models.Model):
name = models.CharField(max... |
2,909 | 605e088beed05c91b184e26c4a5d2a97cb793759 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 10 11:08:59 2020
@author: rishi
"""
# --------- Global Variables -----------
# Will hold our game board data
board = ["-" for i in range(1,26)]
# Lets us know if the game is over yet
game_still_going = True
# Tells us who the winner is
winner = ... |
2,910 | 5cdedce5f984f53b8e26d1580a9040b26023f247 | import shutil
total, used, free = shutil.disk_usage("/")
print("Total: %d MiB" % (total // (2**20)))
print("Used: %d MiB" % (used // (2**20)))
print("Free: %d MiB" % (free // (2**20)))
from Camera import Camera
import time
import cv2
devices = Camera.getDevicesList()
print(devices)
i=0
Cameras = []
for device in... |
2,911 | 889d465ceeac57a600b2fa3bd26632edcd90a655 | import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import QIcon, QFont
from PyQt5.QtCore import QCoreApplication
import pymysql
import requests
from twisted.internet import reactor, defer
from scrapy.crawler import CrawlerRunner, CrawlerProcess
from scrapy.utils.project import get_project_settings
from spider.... |
2,912 | 34947b7ed300f2cbcbf9042fee3902458921d603 | a = list(range(1,501))
b = list(range(1,501))
c = list(range(1,501))
for i in a:
for j in b:
for k in c:
if i+k+j == 1000 and i<j<k and j**2+i**2==k**2 :
print(i)
print(j)
print(k)
break
|
2,913 | 6e56c7792d88385cc28c48a7d6dd32b9d6917c64 | # Generated by Django 2.1.7 on 2019-03-24 07:08
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('adminsite', '0005_auto_20190324_0706'),
]
operations = [
migrations.RenameField(
model_name='district',
old_name='District',... |
2,914 | fab3e524edf6783775fabf402f9148bf31ac06d6 | import smtplib
from email.message import EmailMessage
from functools import wraps
from threading import Thread
import flask_login
from flask import flash, current_app
from togger import db
from togger.auth.models import User, Role
from togger.calendar.models import Calendar
def get_user(username):
if username i... |
2,915 | b7a8e4105f1c1c532eaae27afae14e9a4f2ddfba | # Generated by Django 3.2.3 on 2021-06-19 11:27
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='BillDetail',
... |
2,916 | 44cbe1face91d3ac7edcd93d0b470bce90c8b674 | # myapp/serializers.py
from rest_framework import serializers
from rest_framework.authtoken.models import Token
from .models import *
# Serializers define the API representation.
class GeneralSerializer(serializers.ModelSerializer):
class Meta:
model = None
fields = '__all__'
class V2OfUsersSeri... |
2,917 | 2a37d02c7a0840e855a80adced4794fd757e353a | import ssl
import urllib
from urllib import request, response, error, parse, robotparser
context = ssl._create_unverified_context()
url = 'https://oauth.51job.com/get_login.php?client_id=000001&redirect_uri=https%3A%2F%2Funion.yingjiesheng.com%2Fapi_login.php&from_domain=yjs_web&display=default&state=7c893ec1be7b355a91... |
2,918 | 5433e75bdc46d5a975969e7ece799174dc9b8713 | # # 8/19/2020
# Of course, binary classification is just a single special case. Target encoding could be applied to any target variable type:
# For binary classification usually mean target encoding is used
# For regression mean could be changed to median, quartiles, etc.
# For multi-class classification with N classe... |
2,919 | db159cfb198311b0369f65eb9e10947c4d28c695 | #finding optimal betting strategy for the blackjack game using Monte Carlo ES method
import random
class Player():
def __init__(self) -> None:
q = None
policy = None
returns = None
cards = 0
dealer = 0
def hit(self):
self.cards += random.randint(1,11)
def d... |
2,920 | 6a4585e0e2f5ebbd0f9a7fa203f76bb88ff9c2a0 | from django.apps import AppConfig
class ProjectrolesConfig(AppConfig):
name = 'projectroles'
|
2,921 | 50a5d3431693b402c15b557357eaf9a85fc02b0b | # -*- coding: utf-8 -*-
import sys, io,re
import regex
from collections import defaultdict
import datetime
import json
def update_key(data_base, url,kkey):
keys_saved = regex.get_data('<key>\s(.+?)\s<',data_base[url]['key'])
if kkey not in keys_saved:
data_base[url]['key'] = data_base[url... |
2,922 | c6fd848bb3d845a50b928c18a51f296a500e7746 | import socket
def main():
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('localhost', 8886)
sock.connect(server_address)
data = "TCP"
length = len(data)
ret = bytearray([])
for byte in data.encode("utf-8"):
ret.append(byte)
sock.sendall(ret)
if __na... |
2,923 | ccedca543fc4dee284a9243317d028ffdeac229d | import pandas
import numpy as np
train_set = pandas.read_csv("./dataset/train.csv")
test_set = pandas.read_csv("./dataset/test.csv")
print(train_set)
train_set = train_set.drop('id',axis=1)
print(train_set.describe())
train_set['type'], categories = train_set['type'].factorize()
import matplotlib.pyplot as plt
print... |
2,924 | 03ce69924c885e59e40689dc63e50d54b89649f7 | import _thread
import os
from queue import Queue
from threading import Thread
import random
import io
import vk_api
from vk_api.longpoll import VkLongPoll, VkEventType
from datetime import datetime, timedelta
import time
from nltk.tokenize import RegexpTokenizer
from nltk.corpus import stopwords
from wordcloud import W... |
2,925 | eab45dafd0366af8ab904eb33719b86777ba3d65 | import random
from .action import Action
from ..transition.step import Step
from ..value.estimators import ValueEstimator
def greedy(steps: [Step], actions: [Action], value_estimator: ValueEstimator) -> int:
estimations = [value_estimator(steps, action) for action in actions]
return actions[estimations.index... |
2,926 | 56157aaf3f98abc58572b45111becb91cb93f328 | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-02-24 11:30
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.Create... |
2,927 | b5581be044013df9ff812f285f99ca67c4f96a62 | import requests
import json
def get():
market = 'Premium'
url = 'https://coinpremiums.herokuapp.com/json'
try:
result = ""
premiums = requests.get(url).json()
for exchange, exchange_currencies in premiums['premium'].items():
result += '[[{} | '.format(exchange.title()... |
2,928 | 6a6a7cc6d4f601f4461488d02e03e832bc7ab634 | """ quiz materials for feature scaling clustering """
# FYI, the most straightforward implementation might
# throw a divide-by-zero error, if the min and max
# values are the same
# but think about this for a second--that means that every
# data point has the same value for that feature!
# why would you rescale it? O... |
2,929 | 8fed95cf809afca7b6008d5abcdcf697367a33c2 | """
Supreme bot????
"""
import os
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
import selenium.webdriver.support.expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.ch... |
2,930 | 8ebc11f4b9e28254ef40175b26744f2a5ab0c831 | import os
from registration import Registration
from login import Login
def login():
""" redirect to login page"""
login_page = Login()
login_page.login_main_page()
def registration():
"""Register the new user"""
registration_page = Registration()
registration_page.registration_main_page()
... |
2,931 | 337311c3fbb6a8baab7a237d08152f0db9822527 |
def assert_shapes(shape, other):
assert len(shape) == len(other), "Dimensions are different"
for s, o in zip(shape, other):
if s is not None and o is not None:
assert s == o, "Shapes {} and {} are not equal".format(shape, other)
|
2,932 | bcc24d5f97e46433acb8bcfb08fe582f51eb28ce | class Coms:
def __init__(self, name, addr, coord):
self.name = name
self.addr = addr
self.coord = coord
def getString(self):
return "회사명\n"+self.name+"\n\n주소\n"+self.addr
def getTeleString(self):
return "회사명 : " + self.name + ", 주소 : " + self.addr
class Jobs:
d... |
2,933 | 5d654c056e6ef01e72821427c4f8dcb285755ee9 | from .data_processing import make_request_data, clear_request_data, get_token_from_text
from .review import Review |
2,934 | ec604aea28dfb2909ac9e4b0f15e6b5bbe1c3446 | from email.mime.text import MIMEText
import smtplib
def init_mail(server, user, pwd, port=25):
server = smtplib.SMTP(server, port)
server.starttls()
server.login(user, pwd)
return server
def send_email(mconn, mailto, mailfrom, mailsub, msgbody):
msg = MIMEText(msgbody)
msg['Subject'] = mailsub
msg['To'] = ma... |
2,935 | 009be282e45d191eb8f4d7d2986a2f182d64c1dd | from layers import TrueSkillFactorGraph
from math import e, sqrt
from numerics import atLeast, _Vector, _DiagonalMatrix, Matrix
from objects import SkillCalculator, SupportedOptions, argumentNotNone, \
getPartialPlayPercentage, sortByRank
class FactorGraphTrueSkillCalculator(SkillCalculator):
def __init__(self):
s... |
2,936 | 0a5570ef17efa26ef6317930df616c8326f83314 | # Generated by Django 3.0.1 on 2020-02-01 16:38
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('shopUser', '0024_order_contact'),
]
operations = [
migrations.AddField(
model_name='order',
name='location',
... |
2,937 | cf4582f4d0c6c94e617270a45425fe0b770142e0 | # coding: utf-8
"""
最简单的计数器,仅仅为了展示基本方式
"""
import tensorflow as tf
# 创建一个变量, 初始化为标量 0
state = tf.Variable(0, name="counter")
# 创建一个operation, 其作用是使state 增加 1
one = tf.constant(1)
new_value = tf.add(state, one)
update = tf.assign(state, new_value) # 这样才能重复执行+1的操作,实际上就代表:state=new_value
# 启动图后, 变量必须先经过`初始化` (init) o... |
2,938 | 1cc9c89182f69a5f1eb9a0e7f3433dc30c8d7035 |
print("calificacion de los alumnos")
lista2_calificaciones=[]
for i in range (0,5):
lista2_calificaciones.append(int(input(f"ingrese la calificacion corresponfiente al alumno")))
print(lista2_calificaciones)
for n in range(0,len(lista2_calificaciones)):
if lista2_calificaciones[i] >=0 and lista2_calific... |
2,939 | fef1273552350bfaf075d90279c9f10a965cae25 | # Accepted
def bubble_sort(a_list, n):
num_reverse = 0
for i in range(n):
for j in range(n - i - 1):
# With a for roop (reversed order),
# index starts -1, -2 ,...,
# NOT -0, -1, ...
if a_list[-j - 2] > a_list[-j - 1]:
tmp_elem = a_list[-... |
2,940 | d4b01b015723950a4d8c3453d736cd64f306d27b | # Game Tebak Angka
from random import randint
nyawa = 3
angka_rahasia = randint(0,10)
limit = 0
print(f"Selamat datang di Game Tebak angka")
while nyawa > limit:
print(f"Percobaan anda tersisa {nyawa}")
jawaban = int(input("Masukkan angka 0-10 = "))
if jawaban == angka_rahasia:
... |
2,941 | 1255a9df2fbe11d92991f3f0f7054b92cb017628 | # -*- coding: utf-8 -*-
"""
Created on Tue Mar 12 20:29:49 2019
@author: kzx789
"""
from PIL import Image
import os, glob, numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import math
import cv2
import pymysql
import MySQLdb as mysql
"""
#csv를 읽어서 영양정보 출력
def get_Nutrition(str) :
nutrition = pd.r... |
2,942 | 051544f41cc3c7d78210076cb9720866924ea2a1 | # Print list of files and directories
import os
def file_list(dir):
subdir_list = []
for item in os.listdir(dir):
fullpath = os.path.join(dir,item)
if os.path.isdir(fullpath):
subdir_list.append(fullpath)
else:
print(fullpath)
for d in subdir_list:
f... |
2,943 | 95021cc01c0b85b512fd466797d4d128472773c3 | import shelve
arguments = ["self", "info", "args", "world"]
minlevel = 2
helpstring = "moneyreset"
def main(connection, info, args, world) :
"""Resets a users money"""
money = shelve.open("money-%s.db" % (world.hostnicks[connection.host]), writeback=True)
money[info["sender"]] = {"money":100000, "maxmoney"... |
2,944 | 5a0702dd869862ebc27c83d10e0b1f0575de68a7 | import itertools
import numpy
import math
import psycopg2
import podatki
baza = podatki.baza
dom = podatki.preberi_lokacijo()
seznam_trgovin =["spar", "mercator", "tus", "hofer", "lidl"]
id_in_opis = podatki.id_izdelka_v_opis()
seznam_izdelkov = [el[0] for el in id_in_opis] #['cokolada', 'sladoled', ...]
mnozica_izdel... |
2,945 | 6c88e55a76cbd84cee0ebd6c51d930cc2da100d2 | print("hello world")
print("lol")
print("new changes in vis") |
2,946 | bdbeebab70a6d69e7553807d48e3539b78b48add | # SymBeam examples suit
# ==========================================================================================
# António Carneiro <amcc@fe.up.pt> 2020
# Features: 1. Numeric length
# 2. Pin
# 3. Two rollers
# 4. Numeric distributed... |
2,947 | ba808d23f6a8226f40e1c214012a1535ee1e9e98 | import os
import json
import librosa
# Constants
# Dataset used for training
DATASET_PATH = "dataset"
# Where the data is stored
JSON_PATH = "data.json"
# Number of samples considered to preprocess data
SAMPLES_TO_CONSIDER = 22050 # 1 sec worth of sound
# Main function to preprocess the data
def prepare_dataset(dat... |
2,948 | 1593280a29b13461b13d8b2805d9ac53ce94c759 |
import turtle
import random
import winsound
import sys
""" new_game = False
def toggle_new_game():
global new_game
if new_game == False:
new_game = True
else:
new_game = False """
wn = turtle.Screen()
wn.title("MaskUp")
wn.bgcolor("green")
wn.bgpic("retro_city_title... |
2,949 | 1f1677687ba6ca47b18728b0fd3b9926436e9796 | #Voir paragraphe "3.6 Normalizing Text", page 107 de NLP with Python
from nltk.stem.snowball import SnowballStemmer
from nltk.stem.wordnet import WordNetLemmatizer
# Il faut retirer les stopwords avant de stemmer
stemmer = SnowballStemmer("english", ignore_stopwords=True)
lemmatizer = WordNetLemmatizer()
source = ... |
2,950 | aa79d5cbe656979bf9c228f6a576f2bbf7e405ca | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import copy
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
fr... |
2,951 | 613b060ee50b49417342cfa70b36f77d112dcc58 | from collections import Counter
import pandas as pd
import string
from collections import namedtuple, defaultdict
import csv
import sys
import torch
import numpy as np
from sklearn.preprocessing import LabelEncoder
from scipy.sparse import coo_matrix
from tqdm import tqdm
device = torch.device('cuda' if torch.cuda.is_... |
2,952 | 6d974580ff546bda17caa1e61e2621b4bc705f3f | from flask import jsonify
from flask_restful import Resource
from flask_apispec.views import MethodResource
import pandas as pd
import jellyfish
df = pd.read_csv('data/trancotop1m.csv')
df_dict = df.to_dict('records')
class StrComparison(MethodResource,Resource):
# @requires_auth
def get(self, domain):
... |
2,953 | 7bcbcbe51217b2ea9044a7e4a4bebf315069c92d | """
Create a function that takes two number strings and returns their sum as a string.
Examples
add("111", "111") ➞ "222"
add("10", "80") ➞ "90"
add("", "20") ➞ "Invalid Operation"
Notes
If any input is "" or None, return "Invalid Operation".
"""
def add(n1, n2):
if n1 == "" or n2 == "":
return "Invali... |
2,954 | f5b8d8c291d18c6f320704a89985acbcae97ca2f | from ImageCoord import ImageCoord
import os
import sys
from folium.features import DivIcon
# Chemin du dossier ou l'on recupere les images
racine = tkinter.Tk()
racine.title("listPhoto")
racine.directory = filedialog.askdirectory()
cheminDossier = racine.directory
dirImage = os.listdir(cheminDossier)
listImage = []
... |
2,955 | bce794616889b80c152a8ebec8d02e49a96684e9 | import csv, io
from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.decorators import permission_required
from django.views import generic
from itertools import chain
from .models import Player, League, Team
class IndexView(generic.ListView):
templ... |
2,956 | 3146775c466368c25c92bd6074abb97408533500 | import logging
loggers = {}
def create_logger(
log_level:str ='INFO',
log_name:str = 'logfile',
export_log: bool = True,
save_dir:str = ''):
if log_name in loggers.keys():
logger = loggers.get(log_name)
else:
# create logger
logger = logging.getLogger(log_name)
... |
2,957 | 6cb97e6f3c7ba312ec1458fd51635508a16f70dd | from mysql import connector
def get_db_connection():
try:
return connector.connect(host="server_database_1", user="root", password="password1234", database="SMARTHOUSE")
except connector.errors.DatabaseError:
connection = connector.connect(host="server_database_1", user="root", password="pass... |
2,958 | 919f1746bfdec61f5e81e6ce0e17bb3bf040230a | # square environment. there are the wall at the edge
from environment import super_environment
class SquareNormal(super_environment.Environment):
def __init__(self, size_x, size_y):
super().__init__(size_x, size_y)
@staticmethod
def environment_type():
return 'square'
def get_convert... |
2,959 | d9bdf466abecb50c399556b99b41896eead0cb4b | from flask import Flask, request, g
from flask_restful import Resource, Api
from sqlalchemy import create_engine
from flask import jsonify
import json
import eth_account
import algosdk
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm import scoped_session
from sqlalchemy.orm import load_only
from datetime im... |
2,960 | 7c53c7bec6b6b2d4d6be89b750eeef83ca9115cc | from typing import List
class CourseSchedule:
"""
Problem: Course Schedule (#207)
Key Insights:
1. Create adjaceny list of courses to prerequisites.
2. Use DFS and visited set to detect a cycle. If there is a cycle, cannot finish all the courses.
3. Remember to remove a course (node) from visi... |
2,961 | d0f2d47a786b85367f96897e7cd8c2ef8c577e2b | import datetime
from flask import Flask, render_template, request
import database
import database1
import database2
import getYoutubeVideoLinks as getYT
import os
os.environ["EAI_USERNAME"] = 'pitabi1360@pashter.com'
os.environ["EAI_PASSWORD"] = 'Testqwerty1!'
from expertai.nlapi.cloud.client import ExpertAiClient
cl... |
2,962 | 605c78795b5a072d330d44a150f26ad410d9d084 | import bluetooth
import serial
import struct
# Definition of Bluetooth rfcomm socket
bd_addr = "98:D3:37:00:8D:39" # The address from the HC-05 sensor
port = 1
sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
sock.connect((bd_addr,port))
# Definition of Serial port
ser = serial.Serial("/dev/ttyACM0", 57600)
def BT... |
2,963 | e9a4ea69a4bd9b75b8eb8092b140691aab763ae4 | from collections import Counter
from collections import deque
import os
def wc(argval):
bool = False
if("|" in argval):
bool = True
del argval[len(argval)-1]
hf=open("commandoutput.txt","r+")
open("commandoutput.txt","w").close()
hf=open("commandoutput.txt","w")
numoflines = 0
... |
2,964 | 7e20c61fa30ea93e69a2479e70449638eb52b7bb | #!/usr/bin/env python
"""
Update the expected test outputs and inputs for rsmsummarize and rsmcompare tests.
This script assumes that you have already run `nose2 -s tests` and ran the entire
test suite. By doing so, the output has been generated under the given outputs
directory. And that is what will be used to gener... |
2,965 | 173b8e66ead62e3aa70805e42e06ea05257d5ee2 | class Tool:
def __init__(self, name, weight):
self.name = name
self.weight = weight
def __repr__(self):
return f'Tool({self.name!r},{self.weight})'
tools = [
Tool('수준계', 3.5),
Tool('해머', 1.25),
Tool('스크류드라이버', .5),
Tool('끌', .25)
]
print(repr(tools))
tools.sort(reverse... |
2,966 | 4f91c57ad42759654a87328d5c92de8da14ca5ea | import os
from CTFd.utils.encoding import hexencode
def generate_nonce():
return hexencode(os.urandom(32))
|
2,967 | a24ab93983546f8ae0fab042c121ac52388e62e8 | users = {1: "Tom", 2: "Bob", 3: "Bill"}
elements = {"Au": "Oltin", "Fe": "Temir", "H": "Vodorod", "O": "Kislorod"} |
2,968 | 1c01fbf7eafd49ada71cb018a62ead5988dcf251 | from prediction_model import PredictionModel
import util.nlp as nlp
import re
class NLPPredictionModel(object):
def getPasswordProbabilities(self, sweetwordList):
# can not deal with sweetword that contains no letters
result = []
for s in sweetwordList:
words = re.findall(r"[... |
2,969 | 30a2e4aa88b286179e2870205e90fab4a7474e12 | #!/usr/bin/env python
# -*-coding:utf-8-*-
__author__ = '李晓波'
from linux import sysinfo
#调用相应收集处理函数
def LinuxSysInfo():
#print __file__
return sysinfo.collect()
def WindowsSysInfo():
from windows import sysinfo as win_sysinfo
return win_sysinfo.collect()
|
2,970 | a74d27d9e31872100b4f22512abe9de7d9277de7 | # -*- coding: GB18030 -*-
import inspect
import os,sys
import subprocess
from lib.common.utils import *
from lib.common.loger import loger
from lib.common import checker
from lib.common.logreader import LogReader
import shutil
from lib.common.XmlHandler import *
from lib.common.Dict import *
class baseModule(object):
... |
2,971 | 0d565c9f92a60d25f28c903c0a27e7b93d547a4f | #Create Pandas dataframe from the DarkSage output G['']
import pandas as pd
import numpy as np
# This is a way to converte multi dimensional data into pd.Series and then load these into the pandas dataframe
Pos = []
for p in G['Pos']:
Pos.append(p)
Pos_df = pd.Series(Pos, dtype=np.dtype("object"))
Vel = []
for ... |
2,972 | c581d9714681e22c75b1eeb866ea300e87b883f1 | def domain_sort_key(domain):
"""Key to sort hosts / domains alphabetically, by domain name."""
import re
domain_expr = r'(.*\.)?(.*\.)(.*)' # Eg: (www.)(google.)(com)
domain_search = re.search(domain_expr, domain)
if domain_search and domain_search.group(1):
# sort by domain name and then... |
2,973 | a29cf9e7006d52cea8f5ccdcbc2087983ffa3ef3 | from modules.core.logging.logging_service import LoggingService
from modules.core.logging.models import LogLevel, LogEntry
import pytest
from .setup import register_test_db, register_test_injections, teardown,\
drop_all_collections
@pytest.fixture(autouse=True)
def setup():
register_test_db()
... |
2,974 | 19888c998e8787533e84413272da1183f16fcdb1 | # 8-7. Album: Write a function called make_album() that builds a dictionary
# describing a music album. The function should take in an artist name and an
# album title, and it should return a dictionary containing these two pieces
# of information. Use the function to make three dictionaries representing
# di... |
2,975 | e40b34f0ee51cc14615c6225a7676929e6d2876a | #!/usr/bin/env python3
import datetime, random
class State(object):
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
class State_New(State):
def __init__(self):
super(State_New, self).__init__("New")
class State_Underway(State):
def __init__(sel... |
2,976 | 4dd71d01e499f3d0ee49d3bf5204fb3bbb03ede5 | from email import encoders
from email.header import Header
from email.mime.text import MIMEText
from email.utils import parseaddr,formataddr
import smtplib
def _format_addr(s):
name, addr = parseaddr(s)
return formataddr((Header(name,'UTF-8').encode(), addr))
from_addr='gaofeng4280@163.com'
to_addr='10713802... |
2,977 | 5d55c586c57de8f287d9f51f0cb1f188c8046c29 | #!/bin/python3
def solveMeFirst(a,b):
return a + b
print(solveMeFirst(int(input()),int(input())))
|
2,978 | 34f3212b0254cbcb5e1ca535a29d4fe820dcaad8 | from .hacker import HackerRegistrationPage
from .judge import JudgeRegistrationPage
from .mentor import MentorRegistrationPage
from .organizer import OrganizerRegistrationPage
from .user import UserRegistrationPage
|
2,979 | 57490e56833154d3ed3a18b5bf7bc4db32a50d69 | import numpy as np
import json
from netCDF4 import Dataset,stringtochar,chartostring,Variable,Group
def is_json(myjson):
try:
json_object = json.loads(myjson)
except:
return False
return True
def getType(type):
t=np.dtype(type).char
if t=="S":return 'S1'
if t=="U":return 'U1'
return t
def get... |
2,980 | 863bae04a90143ed942a478c4b71a2269e123bb5 | from compass import models
from compass.models.MetabolicModel import MetabolicModel
def test_sbml_3():
model = models.load_metabolic_model("RECON1_xml")
assert isinstance(model, MetabolicModel)
assert len(model.reactions) == 3742
assert len(model.species) == 2766
def test_sbml_2():
model = model... |
2,981 | ed2ae166c4881289b27b7e74e212ba2d6164998b |
import numpy as np
class Element(object):
def __init__(self):
self.ndof = 0
self.nn = 0
self.ng = 0
self.element_type = 0
self.coord_position = np.array([])
self.setup()
def setup(self):
pass
def shape_function_value(self):
... |
2,982 | b109568c4dba05b16cbed1759a2b9e0a99babc67 | import pandas as pd
import numpy as np
from scipy import misc
from sklearn.model_selection import train_test_split
from sklearn.utils import shuffle
import time
import math
import cv2
import matplotlib
matplotlib.use("TkAgg")
from matplotlib import pyplot as plt
from keras.models import Sequential
from keras.layers im... |
2,983 | 6d0cfc9d5bbc45bfa356c45a7cdb9f4822b03e0a | # Visit 2.12.3 log file
ScriptVersion = "2.12.3"
if ScriptVersion != Version():
print "This script is for VisIt %s. It may not work with version %s" % (ScriptVersion, Version())
visit.ShowAllWindows()
visit.ShowAllWindows()
visit.OpenDatabase("test.vtk", 0)
# The UpdateDBPluginInfo RPC is not supported in the VisIt... |
2,984 | 0bb2a6ebbf75fae3466c34a435a531fabdc07f62 | #!/usr/bin/env python
'''
State Machine for the Flare task
'''
import roslib
import rospy
import actionlib
from rospy.timer import sleep
import smach
import smach_ros
from dynamic_reconfigure.server import Server
import math
import os
import sys
import numpy as np
from bbauv_msgs.msg import *
from bbauv_msgs.srv... |
2,985 | 76e1f811d06af0e6e83ae989a236a5cd22c55e01 | # -*- coding: utf-8 -*-
import argparse
import redis
from Tkinter import *
import ttk
import json
import time
import thread
R = None
NAME = {}
PROBLEM_NAME = {}
CONTEST_ID = None
QUEUE_NAME = None
BACKUP_QUEUE_NAME = None
RUNID_FIELD = "runid"
SUBMIT_TIME_FIELD = "submit_time"
STATUS_FIELD = "status"
STATUS_FINISHED... |
2,986 | d4d8d800b81a50f2c520f0394412935738d1a8ee | class Queue(object):
def __init__(self, val_list=None):
self.stack_one = []
self.stack_two = []
if val_list:
for item in val_list:
self.stack_one.append(item)
def push(self, val=None):
if val:
self.stack_one.append(val)
def pop(self):... |
2,987 | 00f62fec7f5372c5798b0ebf3f3783233360581e | #!/usr/bin/env python3
import sys
import csv
import math
import collections
import argparse
import fileinput
import lp
parser = argparse.ArgumentParser(description="Takes an input of *.lp format and sets all radii to the same value")
parser.add_argument("inputfile", help="if specified reads a *.lp formatted file oth... |
2,988 | a6a5fddb8e1eda4cc8e9c79ad83019f55d149a80 | import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_digits
from sklearn.metrics import confusion_matrix, classification_report
from sklearn.preprocessing import LabelBinarizer
def tanh(x):
return np.tanh(x)
def tanh_deriv(x):
return 1.0 - np.tanh(x) * np... |
2,989 | 524b6ebd0be4c2285fac540627bb48baca71452e | g#https://www.acmicpc.net/problem/9461
'''
1. Divide 2 case △ and ▽
d[0] is △ sequence
d[1] is ▽ sequence
2. find a role between d[0] and d[1]
'''
import math
t = int(input())
n = []
for _ in range(t):
n.append(int(input()))
index = math.ceil(max(n)/2)
d = [[0 for _ in range(52)] for _ in range(2)]
d[0][1],d[0][2],... |
2,990 | 47dc9212a1059cbca8ec6732deaa835fa9967fd8 | from leapp.models import Model, fields
from leapp.topics import TransactionTopic
class TargetRepositoryBase(Model):
topic = TransactionTopic
repoid = fields.String()
class UsedTargetRepository(TargetRepositoryBase):
pass
class RHELTargetRepository(TargetRepositoryBase):
pass
class CustomTargetRe... |
2,991 | d18c45c08face08ce8f7dad915f1896c24c95cbf | from django.contrib import admin
from main.models import Assignment, Review, Sample, Question, SampleMultipleFile
# Register your models here.
admin.site.register(Assignment)
admin.site.register(Review)
admin.site.register(Question)
class MultipleFileInline(admin.TabularInline):
model = SampleMultipleFile
class S... |
2,992 | d3f6fb612e314ee2b86f6218719ecac2cc642c59 | # 홍준이는 요즘 주식에 빠져있다. 그는 미래를 내다보는 눈이 뛰어나, 날 별로 주가를 예상하고 언제나 그게 맞아떨어진다. 매일 그는 아래 세 가지 중 한 행동을 한다.
# 1. 주식 하나를 산다.
# 2. 원하는 만큼 가지고 있는 주식을 판다.
# 3. 아무것도 안한다.
# 홍준이는 미래를 예상하는 뛰어난 안목을 가졌지만, 어떻게 해야 자신이 최대 이익을 얻을 수 있는지 모른다. 따라서 당신에게 날 별로 주식의 가격을 알려주었을 때, 최대 이익이 얼마나 되는지 계산을 해달라고 부탁했다.
# 예를 들어 날 수가 3일이고 날 별로 주가가 10, 7, 6일 때, 주... |
2,993 | 6a09311b5b3b876fd94ed0a9cce30e070528f22c | #manual forward propagation
#based on a course I got from Datacamp.com 'Deep Learning in Python'
#python3 ~/Documents/pyfiles/dl/forward.py
#imports
import numpy as np
#we are going to simulate a neural network forward propagation algorithm
#see the picture forwardPropagation.png for more info
#the basics are it mov... |
2,994 | f882589729d74a910d20856d4dc02546fe316e0d | from Graph import create_random_graph
def find_accessible_vertices_backwards(graph, end_vertex):
if end_vertex not in graph.parse_vertices():
raise ValueError("The end vertex is not in the graph.")
visited = []
queue = []
next_vertex = {}
distance_to_end = {}
queue.append... |
2,995 | 8443d208a6a6bef82240235eeadbf6f8eaf77bcb | from __future__ import print_function, unicode_literals
import sys
import ast
import os
import tokenize
import warnings
from io import StringIO
def interleave(inter, f, seq):
"""Call f on each item in seq, calling inter() in between.
"""
seq = iter(seq)
try:
f(next(seq))
except StopIteratio... |
2,996 | 7430e17d1c424362399cf09a0c3ecae825d04567 | import datetime
count = 0
for y in xrange(1901,2001):
for m in xrange(1,13):
if datetime.date(y,m,1).weekday() == 6:
count += 1
print count
|
2,997 | 03b2b722832eb46f3f81618f70fd0475f1f08c94 |
from selenium import webdriver
from time import sleep
from bs4 import BeautifulSoup
"""
With selenium we need web driver for our browser.
If you use google chrome, you can download chrome driver from here:
http://chromedriver.chromium.org/downloads
In linux (my OS) I extracted downloaded zip file and pla... |
2,998 | 1f49d2341f0bcc712baede28f41c208a01b92e6d | class Rover(object):
DIRECTIONS = 'NESW'
MOVEMENTS = {
'N': (0, 1),
'E': (1, 0),
'S': (0, -1),
'W': (-1, 0)
}
def __init__(self, init_string, plateau_dimensions):
'''
give the rover a sense of the plateau it's on
'''
max_x, max_y = p... |
2,999 | e9b9f87a18a5788ac86b1e85c0f3d7858946e03a | from lib import gen, core
Shellcode = gen.Varname_Creator()
Hide_Window = gen.Varname_Creator()
def Start():
Start_Code = "#include <windows.h>\n"
Start_Code += "#include <tlhelp32.h>\n"
Start_Code += "#include <stdio.h>\n"
Start_Code += "#include <stdlib.h>\n"
Start_Code += "#include <string.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.