index
int64
0
1,000k
blob_id
stringlengths
40
40
code
stringlengths
7
10.4M
1,700
acbe4afee81cb6b9c0b8404d470c3f7f5685477c
array=list(map(int,input().split(" "))) nums=list(set(array)) occ=[] for num in nums: count=array.count(num) occ.append((int(num),int(count))) ans=[] print(occ) occ.sort(key=lambda x: x[1],reverse=True) print(occ) for number,count in (occ): for i in range(count): ans.append(number) print (ans)
1,701
62cc731982846f08b3f3caace5df1bfafd421869
# Simulador de sistema M/M/1. # # Variables de respuesta: # - Demora promedio por cliente # - Número promedio de clientes en cola # - Utilización promedio de cliente # # Funciones: # arribo() # partida() # nuevoEvento() # medidasDesempeño() # generarTiempoExponencial(t) # generarHi...
1,702
0e7732ffcada864fb83b59625c5b9abb01150aaa
from redis_interval.client import RedisInterval class TestRedisIntervalIADD(object): """ Tests the IADD command """ @classmethod def setup_class(cls): cls.redis = RedisInterval(host="localhost") def test_add_simple_text(self): """ Add simple text inside an interval """ value ...
1,703
950929edc82bf78ee33df117fba370b937255adc
# -*- coding: utf-8 -*- from datetime import datetime from odoo.addons.report_xlsx.report.report_xlsx import ReportXlsx from odoo.tools import DEFAULT_SERVER_DATE_FORMAT import xlwt from odoo import _ from odoo.exceptions import AccessError, UserError class mutasibankjurnal(ReportXlsx): def generate_xlsx_r...
1,704
e3ac8039ffb6787b0e3e80b234c2689c66a184bf
import pymongo import pandas as pd from scrape_mars import scrape import json # Create connection variable conn = 'mongodb://localhost:27017' # Pass connection to the pymongo instance. client = pymongo.MongoClient(conn) # Connect to a database. Will create one if not already available. db = client.mars_db #News ...
1,705
8e0d729fa55aabede123d89a507296b7d8a45c8b
import os import multiprocessing import time import psycopg2 #os.system("myproject1\\runscrapy2.py") #from scrapy import cmdline #os.system("scrapy crawl parts") #cmdline.execute("cd myproject1".split()) #cmdline.execute("myproject1\\runscrapy.bat".split()) # start = time.perf_counter() connection = psycopg2.conne...
1,706
d14c22ba6db90a93a19d61e105e31b3eb8f3a206
{"filter":false,"title":"cash.py","tooltip":"/pset6/cash/cash.py","undoManager":{"mark":100,"position":100,"stack":[[{"start":{"row":12,"column":7},"end":{"row":12,"column":8},"action":"insert","lines":[" "],"id":308},{"start":{"row":12,"column":8},"end":{"row":12,"column":9},"action":"insert","lines":[">"]}],[{"start"...
1,707
7a918518d8c9ff1184a634d1a5c799e735dfbc8a
from PyQt5 import QtCore, QtWidgets from .main_window_base import Ui_MainWindow from .custom_sort_filter_proxy_model import CustomSortFilterProxyModel from .tree_model import TreeModel model_filename = "widgets/default.txt" class MainWindow(Ui_MainWindow, QtCore.QObject): def __init__(self, qmain_window): ...
1,708
51cff2f7dd1fd10c6f447d62db3e98075caebe51
#Credits To @maxprogrammer007 (for editing) # Ported for Ultroid < https://github.com/TeamUltroid/Ultroid > import os import sys import logging from telethon import events import asyncio from userbot.utils import admin_cmd from userbot import ALIVE_NAME import random, re from userbot import CMD_HELP from collectio...
1,709
e627bcc6c9a49d46190cc793a77103aa0a760989
import IDS # In[7]: # testfile = 'data/good_fromE2.txt' # testfile = 'data/goodqueries.txt' good_testfile = "data/good_fromE2.txt" bad_testfile = "data/badqueries.txt" # a = IDS.LG() a = IDS.SVM() # preicdtlist = ['www.foo.com/id=1<script>alert(1)</script>','www.foo.com/name=admin\' or 1=1','abc.com/admin.php','"><s...
1,710
1358adc3b2b3ffe72c0ed87fb0024f1079ca7d04
import pydgm import numpy as np import sys class XS(): # Hold the cross section values with routines for outputting to txt file def __init__(self, sig_t, sig_f, chi, sig_s, mu=None): self.sig_t = sig_t self.sig_f = sig_f self.chi = chi self.sig_s = sig_s self.mu = mu i...
1,711
a49ee1e3f600d83486d0cf2396ed261c61fdf926
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # @param A : root node of tree # @return a list of integers def solve(self, root): if not root: return result = [] result.append(root.val) ...
1,712
b90c6a3f8fe084bc2acc0b733750124a1387527c
import pygame class SpriteObject(pygame.sprite.Sprite): def __init__(self, x, y, w, h, color): pygame.sprite.Sprite.__init__(self) self.angle = 0 self.original_image = pygame.Surface([w, h], pygame.SRCALPHA) self.original_image.fill(color) self.image = self.original_...
1,713
ee72262fb29b46784fb357269dd5160192968c1b
import os if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "day66.settings") import django django.setup() from applistions.models import MyClass,Student,Teacher,Employee from django.db.models import Avg, Sum, Max, Min, Count # 1.求所有人里面工资最高的 ret = Employee.object...
1,714
81ff77064a299b4fcd456f341ecb40ba5afe3295
#!/usr/bin/env python3 """ Greets the Pep Boys. """ for name in "Manny", "Moe", "Jack": print("Hi ya", name + '!')
1,715
6fa7aef7c2b91de409a0e8574e362efefa642ee7
''' Note: a TimeOutException appear when distance even 0. ''' import smbus import time #slave arduino address address_arduino = 0x04 bus = smbus.SMBus(1) #get a measure by i2c def getUSMeasure(): bus.write_byte(address_arduino, 1) distance = bus.read_byte(address_arduino) return distance #request rotate...
1,716
0dab663847fdb4efa419882519616b7a89d0bbe8
""" This is the common util file """ from faker import Faker from pytest_practical.helper.api_helpers import woo_request_helper fake = Faker() def generate_random_email_and_password(): """ Function to generate random email id and password """ email = fake.email() password_string = fake.password(...
1,717
c4f656b96ddc86ab2575bd5ec646833cce95e6a9
# author Dominik Capkovic # contact: domcapkovic@gmail.com; https://www.linkedin.com/in/dominik-čapkovič-b0ab8575/ # GitHub: https://github.com/kilimetr packings_str = ''' Raschig Super-Ring | metal | 0.3 | 180000 | 315.0 | 0.960 | 3.560 | 2.340 | 0.750 | 0.760 | 1.500 | 0.450 Raschig Super-Ring | met...
1,718
cc628270a973866025a5e2a5d07e39b4dbdcd324
# Input Output test (입출력 테스트 ) """ 날짜 : 2021/04/27 이름 : 이지영 내용 : 파이썬 표준입출력 실습 _ 교재 p42 """ # 파이썬 표준 출력 print('hello', end='!') #print : 출력함수 (자바에선 document.write('hello');) print('python') print('010', '1234', '1111', sep='-') # seperate 값 # 파이썬 표준 입력 num = input('숫자입력 : ') print('입력한 숫자 :', num) print('num type :'...
1,719
d0653dac8e7c8162070ed9fd191f7fb318f47c60
#This models.py is under UserRegApp1 folder from django.db import models # Create your models here. class UserRegModel(models.Model): username = models.CharField(max_length=15) emailid = models.EmailField() password1= models.CharField(max_length=6) password2= models.CharField(max_length=6) mailse...
1,720
e0394bfed51cd0af9bca06867e9b556b226f37d1
#!/usr/bin/python3.8 # -*- coding: utf-8 -*- __version__ = "0.2.2" __author__ = 'Anton Vanke <f@hpu.edu.cn>' class Gobang: """ 五子棋 ===== 一个简单的五子棋类, 可以在控制台下五子棋. 提供以下函数 : new(): 新局 printcb(): 打印棋盘 player(): 获取当前应落子 ID (轮走方) sortstep(): 处理总步表 loadstep(): 将 step 步表...
1,721
8c4aacb0dfacac2cc3e6fa91397ddfed75923fd9
/home/co/Documents/ImageClassifier/tensorflow/tensorflow/contrib/rnn/python/ops/rnn_cell.py
1,722
1c3b1776f14a085bec90be11028c87dc47f00293
# -*- coding: utf-8 -*- # @File :fi_handlers.py # @Author:ZengYu # @Date :2019/5/16 # @software:PyCharm import tornado.web import tornado.websocket from PIL import Image import base64 from model.flower_identify import flower_identify class FlowersInfo(): flowersInfo = ["月季花(学名:Rosa chinensis Jacq.)...
1,723
837e84d4a58d8fd0d0ffc24973d196ae57f9a260
import functools import re import nltk.data from nltk.corpus import stopwords from nltk.probability import FreqDist from nltk.tokenize import RegexpTokenizer def clean(string): string = re.sub(r"\'s", " \'s", string) string = re.sub(r"\'ve", " \'ve", string) string = re.sub(r"n\'t", " n\'t", string) s...
1,724
03b325094bd3e77f467e17ce54deb95bf2b5c727
a = 1 b = 2 print(a + b) print("hello") list = [1, 2, 3, 4, 5] for i in list: if i % 2 != 0: print(i) print("branch")
1,725
096df1db4d8673ae7886a1b2022148c92f64a23e
import numpy as np import random from math import inf class Particle: """ Represents a particle of the Particle Swarm Optimization algorithm. """ def __init__(self, lower_bound, upper_bound): """ Creates a particle of the Particle Swarm Optimization algorithm. :param lower_bou...
1,726
f021940c16b7ed7fdf1088f2137d3ef724719c80
from django.http import HttpResponse from rest_framework.decorators import api_view @api_view(['GET']) def get_status(request): if request.method == 'GET': return HttpResponse(content='Service is OK!')
1,727
f2dac8b454805829cf5dbe2efe3c0de805ae4cb5
### Script to convert matlab structure file (/motiongan/data/style-dataset/style_motion_database.mat') import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), '..')) import argparse import math import numpy as np from collections import OrderedDict import scipy.io import pickle from core.utils.eul...
1,728
3be3edbecfbb602d4c4a853f006a3a6f4b992fd3
from base.SpellingDictionary import SpellingDictionary from datastructure.trie import NeedMore class WordFinder: def __init__(self): self.spellingDictionary = SpellingDictionary() #self.dictionary.add(["toad", "to", "do", "dot"]) self.spellingDictionary.populateDictionary() pr...
1,729
809c9ce2b017612bedd1eb889c2b017275ee8b6f
import cv2 import numpy as np img = cv2.imread('data/j.png', cv2.IMREAD_GRAYSCALE) kernel = cv2.getStructuringElement(cv2.MORPH_CROSS,(7,7)) erode = cv2.erode(img,kernel) contorno = img - erode cv2.imshow('Original', img) cv2.imshow('Contorno', contorno) cv2.waitKey() cv2.destroyAllWindows()
1,730
1cf573863fca660cc1fec71ab64743e7a2dd74d8
#!/usr/bin/env python3 import os from Alfred3 import Items, Tools def to_absolute_path(filepath): filepath = os.path.expanduser(filepath) return os.path.abspath(filepath) def is_valid_path(path): abs_path = to_absolute_path(path) if os.path.exists(abs_path) and os.path.isdir(abs_path): ret...
1,731
d6b49533573dfefba6286ac2bffc2bd7a4075063
import sqlite3 connection = sqlite3.connect('database.db') cursor = connection.cursor() # cursor.execute('CREATE TABLE users (id int, username text, password text)') cursor.execute('INSERT INTO users VALUES(?,?,?)',(1,'ilia','qwerty')) users = [(2,'nika','asdf'),(3,'nino','sdfg')] cursor.executemany('INSERT INTO ...
1,732
de0521db3909054c333ac3877ff0adf15ab180fb
import unittest import TicTacToe class pVpTestCase(unittest.TestCase): # def test_something(self): # self.assertEqual(True, False) def twoplayer_setup(self): game1 = TicTacToe.Game() player1 = TicTacToe.Player('X', game1) player2 = TicTacToe.Player('O', game1) return (g...
1,733
bf63ceca2347f750cdf38dce620eaa3c73b556f1
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_nukeboxQueue ---------------------------------- Tests for `nukebox2000` module. """ import sys import unittest from nukebox2000.MongoBox import NukeBoxDB class TestNukeBoxDB(unittest.TestCase): ''' ''' def setUp(self): ''' B{Test...
1,734
0d6c1e74a274b3e8ad9c63ecaa125f79976db9b4
from interpreter import Interpreter from pretty_print import PrettyPrint from ast import Operator, Operation, Element class Token: operator = False empty = False def __init__(self, token): self.token = token if token == '+': self.operator = True elif token == '-': ...
1,735
7882504f08e871f2610ff633608eb3d380179041
# -*- coding: utf-8 -*- from flask import Blueprint, render_template, flash, redirect, url_for from flask_login import login_required, current_user from ..extensions import db from .forms import MyTaskForm from .models import MyTaskModel tasks = Blueprint('tasks', __name__, url_prefix='/tasks') @tasks.route('/my...
1,736
2e27302abbe239c1a6067a9eb52f5a857fff7dd2
import re f = open('q4text.txt') text = f.read() f.close() pattern = r'''[0-9]+[,][0-9]+|[0-9]+[.][0-9]+|[0-9]+|\b[A-Z][a-z]+[.]|\b[A-Za-z]+['][a-z]+|[A-Z.]+[A-Z]|\b[A-Za-z-]+|[.]+|[.,'"!?:;]''' word_token = re.findall(pattern, text) token_dictionary = {} for element in word_token: if element in token_dictionary...
1,737
576c28bb32b5e0b2b5a82a33cee73e3080dcf3ab
from django.shortcuts import render import codecs import os.path from django.conf import settings OFFSET = 20 def show_raw_data(req): filename = req.GET['file'] lineno = int(req.GET['line']) from_lineno = max(0, lineno - OFFSET) to_lineno = (lineno + OFFSET) ctx = dict() cur_lineno = 1 lin...
1,738
e48addecdde632607a9c782ff78a769122daab6f
#!/usr/bin/env python # coding: utf-8 # In[ ]: import numpy as np import pickle from sklearn.model_selection import train_test_split from sklearn.metrics import mean_absolute_error from pyspark.sql.functions import split, concat,col from sklearn.svm import SVR test = True # In[ ]: dbutils.widgets.removeAll() d...
1,739
d301ffa790d6444519e354a2b6f8d65f67d380c0
from django.contrib import admin from django.contrib.admin.sites import AdminSite from obp.models import * from django.utils.html import format_html from jet.admin import CompactInline #from django.utils.translation import ugettext_lazy as _ from jet.dashboard import modules from jet.dashboard.dashboard import Dashboa...
1,740
5ab8d9eab30d72557f1a85b5b82c0df456e3843d
# The sort() method sorts the list ascending by default. #syntax # list.sort(reverse=True|False, key=myFunc) # Parameter Description # reverse Optional. reverse=True will sort the list descending. Default is reverse=False # key Optional. A function to specify the sorting criteria(s) cars ...
1,741
31064145ae2702f93a475d0957395c62a6b320ee
# -*- coding: utf-8 -*- # author : rovo98 # date: 2018.3.19 # this is a demo for test calling functions. n1 = 255 n2 = 1000 print(hex(n1)) print(hex(n2)) print(abs(-119999))
1,742
6291375738db7914d551f9a1c6d2897b7d236b87
"""Primer3 input form. For details on input params see: https://primer3.org/manual.html#globalTags """ from django import forms from django.core.exceptions import ValidationError from .fasta import Fasta class PrimerForm(forms.Form): """Collect user input to run primer prediction.""" fasta = forms.CharFie...
1,743
9e34fcec3af746af37cb68fd8617c706cc1066f6
from unittest import TestCase, main class Solution: def productExceptSelf(self, nums): right, rs = 1, [1]*len(nums) for i in range(1,len(nums)): rs[i] = nums[i-1]*rs[i-1] for i in range(len(nums)-1, -1, -1): rs[i], right = rs[i]*right, right*nums[i] return rs class testsolution(Tes...
1,744
e8971b3d183ded99a5fc03f031ef807280b8cc7f
''' Converts luptitudes to maggies and stores in folder output Written by P. Gallardo ''' import numpy as np import pandas as pd import sys assert len(sys.argv) == 2 # usage: lups2maggies.py /path/to/cat.csv fname = sys.argv[1] print("Converting maggies from catalog \n%s" % fname) df = pd.read_csv(fname) z = d...
1,745
ca009022832963934230e356f9ea9eaedac7378b
import praw import config from imgurpython import ImgurClient import datetime from time import sleep def respond_to_comment(comment, album_user, album_url, num_images, num_gifs): body = "Here is an album of all unique image/gif posts made by " \ "[{user}]({album_url}). ({num_images} images" \ ...
1,746
1a2616472c8d432c91e2b48260cbae61d3ecfd90
import datetime import os # os.getcwd() class LMS: # This class is used to keep records of the books in the Library def __init__(self, list_of_books, library_name): self.list_of_books = "List_of_books.txt" self.library_name = library_name self.books_dict = {} Id = 101 w...
1,747
92a1f86ce8cc9563d455f9b1336dbcd298f01b6d
#!/usr/bin/env python #encoding:utf8 import sys from collections import defaultdict def transform_word(word): ''' 将低频词转为四种形式之一。 ''' if any(c.isdigit() for c in word): return '_NUMERIC_' if word.isupper(): return '_ALL_CAP_' if word[-1].isupper(): return '_LAST_CAP_' ...
1,748
c27d6279d1ea84bab3c0abd4ca9a08de202219da
from flask import render_template, url_for, escape, redirect, abort from app import core from database import db @core.route('/post') @core.route('/categorie') @core.route('/tag') def returnToHome(): return redirect(url_for('home'))
1,749
e82dd2792ecbb8ed5a33012239102d2c6a02202b
import os import numpy as np from argparse import ArgumentParser from collections import Counter from typing import Iterable, Dict, Any, Tuple from utils.constants import TRAIN, VALID, TEST, SAMPLE_ID, INPUTS, OUTPUT from utils.file_utils import make_dir from utils.data_writer import DataWriter WINDOW = 50 STRIDE = ...
1,750
e76ebbe8dab2e5169ef40b559f783c49ba4de825
from boxsdk import Client, OAuth2 import os import sys def ConfigObject(config_path): "read a configuration file to retrieve access token" configDict = {} with open(config_path,'r') as config: for line in config.readlines(): try: configDict[line.split("=")[0]] = line.sp...
1,751
4deb691545887104b3fb70dd2be52138088ba1e8
class Person: def __init__(self,mood): self.mood=mood; def laugh(self): self.mood.laugh() def cry(self): self.mood.cry() def setMood(self, mood): self.mood=mood class Mood: def laugh(self): pass def cry(self): pass class HappyMood(Mood): def laugh(self): print 'Ha ha ha!' class SadMood(Mood)...
1,752
6c16afe89d5d0fd6aa6911e3de9e9cebb57bf35e
from rest_framework import serializers from urlshortner.models import UrlShortnerModel from urlshortner.constants import HOST class UrlShortRequest(serializers.Serializer): url = serializers.CharField(required=True, max_length=255) # Long Url expiry = serializers.DateTimeField(required=False) class UrlLong...
1,753
eb2bb06afb9aeb46ad02cbac145ccd817131074d
''' Created on Sep 23, 2016 @author: Andrew ''' from pymongo import MongoClient import re client = MongoClient() atMentions = re.compile(ur"@\w+", flags=re.I|re.U) atMidnight = re.compile(u"@midnight", flags=re.I|re.U) hashtag = re.compile(ur"#\w+", flags=re.I|re.U) features = [("usf fwa forward most", ...
1,754
187cf160b520001b6fe3a8d343391de1c04b3acd
from flask import Flask, request, redirect, render_template, session, flash from mysqlconnection import MySQLConnector import re EMAIL_REGEX = re.compile(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)") app = Flask(__name__) app.secret_key = "ThisIsSecret" mysql = MySQLConnector(app,'mydb') @app.route('/') def ...
1,755
a0f83f0a2c6ddaa2fc641bd4fa48a6f50fd1d978
# -*- coding: utf-8 -*- from django import forms from django.utils.translation import ugettext_lazy as _ # import models from apps.qa.models.coupon import Coupon from apps.qa.models.coupon_type import CouponType COUPONTYPE_CHOICES = ( ('text', _("text")), ('url', _("url")), ('questionnaire', ...
1,756
d3b5d87b56421940449fdef48be6da9fa650dd90
import pygame from config import * from Map import * from NeuralNetwork import * class Pacman(object): RADIUS = int(TILE_WIDTH/2) def __init__(self, mapa, neural_net): self.mapa = mapa self.pos_x = 11 self.pos_y = 17 self.vel_x = 1 self.vel_y = 0 self.isAlive ...
1,757
266b8958b761ee7266a8098aeaecb8b6c2a24a2a
# Author: Cristian Steib # # # -*- encoding: utf-8 -*- import pilasengine class consoleColors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' class BotonComando(): ''' ...
1,758
ccdd7a5e0a1de75762530a7cadd919a2ee753d18
import os import config as cfg import numpy as np class lfwdata(): def __init__(self): self._pairs = [] pairs = open(os.path.join(cfg.LFW_IMAGEPATH, '../pairs.txt')) pairs.readline() for pair in pairs: pair = pair.split() if len(pair) == 3: ...
1,759
607d8bc79caa9d767bdb7e77a5db52295d90236f
from PenaltyTracker import PenaltyTracker from DatabaseManager import DatabaseManager import unittest,os,sys,shutil, filecmp class TestingPenaltyTracker(unittest.TestCase): @classmethod def setUpClass(cls): cls.testPTDatabase = os.path.join( os.getcwd(), "Tests", "test_penalty.db") cls.testPena...
1,760
596fe474ae60dd6a06123df6fe246f7e947b3482
# -*- coding: utf-8 -*- from django.db import models from filebrowser.fields import FileBrowseField from localisations.models import Ville, Lieu from model_utils.managers import InheritanceManager from services.models import Service from equipements.models import Equipement from localisations.models import Ville from d...
1,761
b308d81fb8eab9f52aa0ad4f88e25d6757ef703a
# Generated by Django 3.1.1 on 2021-03-25 14:42 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [] operations = [ migrations.CreateModel( name="Experiment", fields=[ ...
1,762
06643bf4b1bded757078b0974c21ddec814f5889
# -*- encoding: utf-8 -*- ############################################################################## # # ServerPLM, Open Source Product Lifcycle Management System # Copyright (C) 2020-2020 Didotech srl (<http://www.didotech.com>). All Rights Reserved # # Created on : 2018-03-01 # Author : Fabio ...
1,763
ca0c38cf2a55b2311a254b09cb693516c3d0ab10
import sys import os import cv2 def write_video(fps, input_folder="output",video_name="video.mp4"): fourcc = cv2.VideoWriter_fourcc("m","p","4","v") video = cv2.VideoWriter(video_name, fourcc, fps, (1280,720)) path = os.getcwd() files = os.listdir(path+"/"+input_folder) count = len(files) ...
1,764
7e0eefb1d913787f675adc2ba0dccb16007464e4
# Original code from http://www.pythonforbeginners.com/code-snippets-source-code/port-scanner-in-python #!/usr/bin/env python # modules import threading import socket import subprocess import sys import time import scapy from threading import Thread, Lock from queue import Queue from datetime import datetime from log...
1,765
5791c1efa82a1e02ca067e1db776e9d466a111e2
# Generated by Django 2.0.7 on 2018-08-14 21:31 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('orion_integration', '000...
1,766
aa7cf08b40b2a13e39003f95e5e0ce7335cbdba2
''' LeetCode wants to give one of its best employees the option to travel among n cities to collect algorithm problems. But all work and no play makes Jack a dull boy, you could take vacations in some particular cities and weeks. Your job is to schedule the traveling to maximize the number of vacation days you could ta...
1,767
b000f293b50970233d5b71abc3e10e2ad57a3fc7
# lesson 4 Mateush Vilen my_information = { 'name': 'Vilen', 'last_name': 'Mateush', 'how_old': 31, 'born_town': 'Khmelniysky' } dict_test = {key: key**2 for key in range(7)} print('dict_test: ', dict_test) elem_dict = 0 elem_dict = input('input number of elements:') user_input_dict = {} for key in ...
1,768
f9becdb48583423e7bd3730d1cd74a6a016663dc
import requests import tkinter as tk from tkinter.font import Font from time import strptime class Window(tk.Tk): def __init__(self): super().__init__() #取得網路上的資料 res = requests.get('https://flask-robert.herokuapp.com/youbike') jsonObj = res.json() areas = jsonObj['areas'] ...
1,769
6e78dee46276f738197ba6796fe1a027ab743354
from sonosscripts import common from sonosscripts.common import round_nearest def run(_): parser = common.get_argument_parser() parser.add_argument("--step", help="volume step", type=int, default=5) parsed_args = parser.parse_args() sonos = common.get_sonos(parsed_args) step = parsed_args.step ...
1,770
389ccddcbe2214ae5c012bc82a404a81942792d8
import numpy as np class LayerBase(object): def __init__(self, units_count, activation_func): self.current_layer_dim = units_count self.activation_func = activation_func self.weights = None self.bias = None self.pre_activation = None self.activation_layer = None ...
1,771
47a5ddcea2f6d8ce80793192d26c98ccc0e0340d
from django import forms from django.forms import ModelForm, fields, widgets from .models import NewsStory class StoryForm(ModelForm): class Meta: model = NewsStory fields = ['title' , 'pub_date' , 'content'] widgets = { 'pub_date': forms.DateInput(format=('%m/%d/%Y'), attrs={'c...
1,772
1a46752a2d1c72ec6084e7af3694a3969e2d1b4c
# -*- coding: utf-8 -*- from django.core.exceptions import ObjectDoesNotExist from django.shortcuts import render import urllib from django.http import HttpResponse, Http404 from django.utils.dateparse import parse_datetime from urllib.parse import urlencode from matplotlib import pyplot from decimal import Decimal fr...
1,773
df984939c109662bebbd1556c12223fce8f643e6
# -*- coding: utf8 -*- ''' dump data from mysql/hive to load into mysql ''' from datetime import datetime,timedelta from optparse import OptionParser import argparse import ConfigParser import sys import os import time import commonutil def getConf(cfgfile): config = ConfigParser.ConfigParser() ...
1,774
78c71a4f3c4e8f24f0ae90555a3caf15f35332f6
#Exercício Python 055: Faça um programa que leia o peso de cinco pessoas. No final, mostre qual foi o maior e o menor peso lidos. pessoas = int(input('Informe a quantidade de pessoas que deseja analisar: ')) peso = 0 maior = 0 menor = 0 for c in range(0, pessoas): peso = float(input('Informe o peso: ')) if c ==...
1,775
866ee2c4fa52bf9bda4730c7a9d46bb4798adcd4
from django.contrib.auth import get_user_model from django.test import TestCase from .models import Order from markets.models import Market from tickers.models import Ticker from trades.models import Trade USER_MODEL = get_user_model() class Matching: @staticmethod def get_bid_ask( market : Market): ...
1,776
903a431ac39734338b4d464629b4b04a87dc9e8e
#Интегрирование точного решения кинетик затухания люминесценции символьным методом #Из за сложности получаемых уравнений. Последующий подбор коэффициентов методом МНК # и печать результата # import sympy as sym def del_flu_sym(x ,t = 1 ,Ka = 1, Ktt = 0.5): intens = x**2 return intens x = sym.Symbol('x') t ...
1,777
c9872fb536fd6552e2a5353566305555808747f7
from jabberbot import JabberBot, botcmd import datetime import logging import sys import time; from config import username, password, chatroom, adminuser class SystemInfoJabberBot(JabberBot): @botcmd def serverinfo( self, mess, args): """Displays information about the server""" version = open(...
1,778
e7ffa852d16e8e55b4e2b6ab2383561fe359a169
import pandas import pytest from tns_watcher import get_tns from utils import load_config, log, Mongo """ load config and secrets """ config = load_config(config_file="config.yaml")["kowalski"] class TestTNSWatcher: """ Test TNS monitoring """ @pytest.mark.xfail(raises=pandas.errors.ParserError) ...
1,779
f3466fd38ecf472a4342aad4d10410d6f2a67d47
#!/usr/bin/env python """ Checker of generated packages. - [x] import generated package - [x] flake8 - [x] pyright - [x] mypy """ import argparse import json import logging import subprocess import sys import tempfile from dataclasses import dataclass from pathlib import Path from typing import List, Optional ROOT_PA...
1,780
6fba773025268d724283e510a03d0592282adb0a
import os import h5py import numpy as np import torch from datasets.hdf5 import get_test_datasets from unet3d import utils from unet3d.config import load_config from unet3d.model import get_model logger = utils.get_logger('UNet3DPredictor') def predict(model, hdf5_dataset, config): """ Return prediction ma...
1,781
fcc6dd61b94d5fa7f088fc75b748d976d1b30fa5
import itertools def possibleNumber(digitSet, n): res = [[]] pools = [digitSet] * n # print(pools) for pool in pools: # print(res) res = [ x + [y] for x in res for y in pool] for prod in res: yield prod # def possibleNumber(digitSet, n): # res = [] # temp = itertoo...
1,782
8909ee9c54a234222a41249e1f3005fd86e21cf0
class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next class Solution: """ @param l1: the first list @param l2: the second list @return: the sum list of l1 and l2 """ def addLists(self, l1, l2): res = ListNode(0) p = res ...
1,783
6ea41b0a76ddde04bcaffacea604f218eac9ac71
# encoding=utf-8 ''' Finding log2() using sqrt() 原理: sqrt( 2**l * 2**h ) = 2**( (l+h)/2 ) 而 a+b /2 正好是binary search, 与sqrt对应上了 题目应当是要求 意思就是找到2**x == y ''' class Solution: def log2(self, val): if 0<val<1: return -self.log2(1.0/val) if val==1: return 0 h = 1; accuracy = 0.001; ...
1,784
983e3b2902fe3bc701167da2f308fdaed612ae84
class DuplicatedBlockException(Exception): code = 'duplicated_block_exception'
1,785
76d2c80c673f9a0444e72721909a51479ff35521
from ..scope_manager import ScopeManager from ..span import Span from ..tracer import Tracer from .propagator import Propagator class MockTracer(Tracer): def __init__(self, scope_manager: ScopeManager | None = ...) -> None: ... def register_propagator(self, format: str, propagator: Propagator) -> None: ... ...
1,786
7413d4e98f79bf7b389a6305257833293714fc81
# Copyright (c) 2009 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. { 'variables': { 'chromium_code': 1, }, 'includes': [ 'ots-common.gypi', ], 'targets': [ { 'target_name': 'ots', 'type'...
1,787
d807a363c08d117c848ffdc0a768c696ea7746bd
import torch import torch.nn as nn import torch.optim as optim from torch.optim import lr_scheduler import numpy as np import torchvision from torchvision import datasets, models, transforms #import matplotlib.pyplot as plt import time import os import copy import torch.nn.functional as F from PIL import Image, ExifTag...
1,788
9817600759bc01e89f6c48bdc2d256651aedf74d
#!/usr/bin/python import glob import numpy as np import pandas as pd import matplotlib.pyplot as plt import time import seaborn as sns import os from pathlib import Path #import math #functions related to elasticity of WLC def f1(l,lp, kbt): return kbt/lp*(1./(4*(1.-l)*(1.-l))-.25+l) def derf1(l,lp,kbt): return k...
1,789
3b307ae7f8b8b25c93eb2dc54b2603b1291b6232
from setuptools import setup, find_packages setup(name='qn', version='0.2.2', description='Handy functions I use everyday.', url='https://github.com/frlender/qn', author='Qiaonan Duan', author_email='geonann@gmail.com', license='MIT', packages=find_packages(), # install_...
1,790
30fbe52a5e3fb184a998fce43d716cffdaf0d2dc
a=[5,4,3,2,1] a=[1,2,3,7,5,6,4,8,9] import time sorted=True for i in range(0,len(a)): print('main') sorted=True for j in range(1,len(a)-i): if a[j]<a[j-1]: a[j],a[j-1]=a[j-1],a[j] print('inner') print(a) time.sleep(1) sorted=False if sorted: break print(a)
1,791
5900dc0acde45ac9a31dc9d489aa8dae304d626b
from draft import * # create a train station platform = Platform('platform 1') train_station = TrainStation('Linz') train_station.add_platform(platform) # create a train train_1 = ICE('ICE 1') platform.accept_train(train_1) train_section_1 = TrainSection('First section') train_section_2 = TrainSection('Second section')...
1,792
31664f1cc808ccc0dad230e2b955692c7ae12db1
# -*- encoding:utf-8 -*- from setuptools import setup, find_packages setup( name='pass-manager', version='1.2.0', author='petitviolet', author_email='violethero0820@gmail.com', packages=find_packages(), description = 'Simple CLI Password Manager', long_description = 'Please show help (pass-...
1,793
bc087482e901ce1831cef56aa9c7aef0c8f2d15a
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2017 Maarten Los # See LICENSE.rst for details. class Defaults(object): INBUS_VERSION = 2 LOCALHOST = "127.0.0.1" PORT = 7222 INBUS_ADDRESS = (LOCALHOST, PORT) BUFFER_SIZE = 65536
1,794
b55984da73d3cfb3109a52990a0d4d05a27d51a5
def main(): #entrada N = int(input()) num = 1 #processamento for i in range (N+1): if i > 0: #saida print("%d %d %d" %(i, i**2, i**3)) num +=1 if __name__ == '__main__': main()
1,795
ba702a9c5d9d31e48b047c106d77cf1707031d70
import numpy as np import matplotlib.pyplot as plt from matplotlib.image import imread X = np.array([[51, 55], [14, 19], [0, 4]]) print(X) A = np.array([[1, 2], [3, 4]]) B = np.array([10, 20]) print(A * B) print(X[0]) print(X[0][1]) for row in X: print(row) newX = X.flatten() print(newX) print(X > 15) # 데이터 ...
1,796
ec7ca03f627eaa635aac56e302b9c40bf0a3da38
def sieve(limit): numbers = list(range(3,limit,2)) for prime in numbers: for multiplier in reversed(range(2,limit)): try: numbers.remove(prime*multiplier) except ValueError: pass return [2]+numbers
1,797
24246427e2fde47bbc9d068605301f54c6ecbae5
# Adjust figure when using plt.gcf ax = fig.gca() ax.set_aspect('equal')
1,798
0b730314fef31e7304a8f5d8bb998581b021a610
from django.apps import AppConfig class BuyerSellerAppConfig(AppConfig): name = 'buyer_seller_app'
1,799
b0cdf75ff00d72ada75990dd850546414bc11125
from pypack.Animal import Animal __author__ = 'igord' def nl(): print("\n") def main(): # print("Hello2") # animal = Animal(45) # animal.double_age() # print(animal.age) print("Start") msg = "ana i mujica" msg2 = msg.replace("a", "$") print(msg) print(msg2) ivana = "iva...