index
int64
0
1,000k
blob_id
stringlengths
40
40
code
stringlengths
7
10.4M
10,500
31abc49be84b81f0e7ffe4e643737ff587ad8427
import argparse from mosestokenizer import * def de_preprocess(references, language): clean_references = [] for item in references: # item = item.replace("@@ ", "") item = item.replace("@@@", "") item = item.replace("@@@@", "") item = item.replace("<eos>", "") item = ite...
10,501
3bd4da3d61776d594535599e4b2a51979ab85931
#!/bin/python3 # import socket import busio import adafruit_ssd1306 # from PIL import Image, ImageDraw, ImageFont SCL = 1 SDA = 0 HEIGHT = 32 WIDTH = 128 i2c = busio.I2C(SCL, SDA) disp = adafruit_ssd1306.SSD1306_I2C(WIDTH, HEIGHT, i2c)
10,502
10c3d75c153aa00226466765986d156cb009ec01
import random import numpy as np import copy import time from gurobipy import * import networkx as nx M = 100000 def phase_1(t): x = [] p = [] for i in range(0,len(t)): x.append([]) alloc = np.argmin(t,0) for i in range(0,len(alloc)): x[alloc[i]].append(i) return np.asarray(x) ...
10,503
73f630cb865bbd7baa317a853dcfd623cb422ce5
#******************TESTING*************************** #This file is for testing the enigma_net class from enigma_net import * import _thread #used to read messages from inbox #if you want to test this on two seperate computers, change host to '0.0.0.0' on the machine that #you want to be the serv...
10,504
e18fd6b29fa77e6792ad7d12cd39b95dfdd3a5ba
''' Miscellaneous Test Code Extracts all entries in an Outlaws LAB archive to the current directory. ''' import struct import sys if __name__ == '__main__': with open(sys.argv[1], 'rb') as f: entries = [] if f.read(4) != b'LABN': print('Bad Magic Identifier') exit(-1) ...
10,505
3fb468dcb6218fa14a19ea124c9366a387ffebff
from unittest import TestCase from unittest.mock import patch from monster import check_monster_encounter class TestCheck_monster_encounter(TestCase): @patch('monster.monster_encounter', side_effect=[None]) @patch('sud.roll_die', side_effect=[1]) def test_monster_encounter_True(self, mock_monster_encount...
10,506
6e469387f05e5225d372e84d6f14a47bad2f2020
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Feb 9 16:01:22 2019 @author: mattcooper """ import numpy as np import matplotlib.pyplot as plt u = 1.661e-27 k = 1.38e-23 c = 3e8 m_He = 4.003*u m_C = 12.0107*u m_P = 1.673e-27 T = 10e6 nu = 10e9 R_Sun = 6.96e10 h = 6.626e-34 def get_turnover_Freq...
10,507
839eb366863737853b832a41632564014328dd4d
# Copyright (c) 2017 Presslabs SRL # # 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 writ...
10,508
64fe0d4e5ab74f2651eb8fd19762f6fdccd92203
# # JMC Lisp: defined in McCarthy's 1960 paper, # with S-expression input/output and basic list processing # # basic list processing: cons, car, cdr, eq, atom def cons(x, y): return (x, y) def car(s): return s[0] def cdr(s): return s[1] def eq(s1, s2): return s1 == s2 def atom(s): return isinstance(s, str) or eq(s, ...
10,509
6de1d5233eb8dccaa746de84c3f4edeed98c0dfb
def calc(num): lst = [] while num > 0: lst.append(num % 10) n //= 10 return sum(lst) N = int(input()) print(calc(N))
10,510
4886fad8e437b0ebb5d574ed9c63f7f0df5a2308
from django.db import models from hashlib import sha256 from django.contrib.auth.base_user import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin, UserManager from django.utils.crypto import get_random_string, constant_time_compare import re class Avatar(models.Model): link = models.TextF...
10,511
adc654a69bf068cd24fadd53e22160463f10a018
''' 5. Working with Files and Directories Creating files Operations on files (open, close, read, write) file object attributes filepositions - https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files Listing Files in a Directory >>> import os >>> print(os.listdir("C:/Users/Quark/Do...
10,512
e0a6d8a0833920011cc737b405cdaac9ea90e7b0
"""This REST service allows real-time curation and belief updates for a corpus of INDRA Statements.""" import sys import pickle import logging import argparse from flask import Flask, request, jsonify, abort, Response from indra.belief import wm_scorer, BeliefEngine from indra.statements import stmts_from_json_file l...
10,513
5d36c28db1c5c78d4ec395672f0140cfc8062c10
from PyQt5 import QtWidgets, QtGui, QtCore, QtPrintSupport from ventana import * from vensalir import * from vencalendar import * from datetime import datetime, date import sys, var, events, clients, conexion, printer, Products, ventas, provider class DialogSalir(QtWidgets.QDialog): """ Clase que isntancia la...
10,514
8172ce93f6d8609e51259a6cc10752e04ba9159f
#!/usr/bin/python2 from __future__ import print_function import httplib2 import oauth2client # $ pip install google-api-python-client import os import base64 import time import email from googleapiclient import discovery from oauth2client import client from oauth2client import tools from oauth2client import file...
10,515
d0ed4bfa75db659d8f3095185b1f2c2ab3c668ec
import pygame white = ( 255, 255, 255) black = ( 0, 0, 0) class Car(pygame.sprite.Sprite): def __init__(self): super(Car,self).__init__() self.surf = pygame.Surface((75,25)) self.surf.fill(white) self.rect = self.surf.get_rect()
10,516
07eb4bbdf0943bd5e83afc487d1930d0bc143ab6
# Generated by Django 2.1.4 on 2019-02-23 09:34 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('app', '0008_auto_20190223_1127'), ] operations = [ migrations.CreateModel( name='Station', fields=[ ...
10,517
a6f895fb1596fe8a62362f3337cf4e52b2fe4349
import rospy import baxter_interface from baxter_interface import Gripper, Limb, Head import time rospy.init_node('test') left = Limb('left') right = Limb('right') leftg = Gripper('left') head = Head() def dab(): right.move_to_neutral() left.move_to_neutral() dableft = {'left_w0': -0.10316020798529407, 'left_w1'...
10,518
a1a99120403fe53a10c8575af0c5951fa56849dd
# # Script to send outgoing notifications # from django.core.management.base import BaseCommand, CommandError from django.utils import timezone from django.db import connection from datetime import timedelta import sys from postgresqleu.util.messaging import ProviderCache from postgresqleu.util.messaging.sender imp...
10,519
66803f7384ae7cda3fc32213e0f0dc1311398427
from django.test import TestCase from .models import (TimelineSlide) import json # Test data test_data_headline = 'Milk Marketing Board established' test_data_text = 'The Milk Marketing Board (MMB) was a producer-led ' \ 'organisation established in 1933-34 via the Agriculture ' \ 'M...
10,520
de6e2f08858c68bb8a2d1a327e9459ed74f38f93
from .models import * from django import forms def createHomePage(homePageForm): try: homePage = HomePage.saveFromForm(homePageForm) return homePage except Exception as e: print(e) def createSiteInfos(siteInfoFormSet, homePage): for form in siteInfoFormSet: if form.cleane...
10,521
90de9af7411d0a5ff230180b64feb7a2720eff51
''' ############################################################################################################# 4. <<체육복>> [문제 설명] 점심시간에 도둑이 들어, 일부 학생이 체육복을 도난당했습니다. 다행히 여벌 체육복이 있는 학생이 이들에게 체육복을 빌려주려 합니다. 학생들의 번호는 체격 순으로 매겨져 있어, 바로 앞번호의 학생이나 바로 뒷번호의 학생에게만 체육복을 빌려줄 수 있습니다. 예를 들어, 4번 학생은 3번 학생이나 5번 학생에게만 체육복을 빌려줄 수 있습...
10,522
6a5f383bb338c6900ecbd539388acc1f1ad91e11
from telethon import TelegramClient, sync, events from telethon.tl.custom.conversation import Conversation from random import randint import asyncio import cwCommonUtils from cwConversation import ChatWarsConversation # 🏰Castle ⚖Exchange 📦Stock 70 x 1000💰 [selling] class ChatWarsHelper(dict): chat_me = '...
10,523
4ed0cb5cbc58e596bb5467441082538c30993e01
# -*- coding: utf-8 -*- """ Created on Tue Sep 22 11:25:28 2020 @author: Brendon McHugh Question 1(b) of Lab03 Here, we use gaussian quadrature to calculate the probability of blowing snow based on the average hourly windspeed at 10m, the snow surface age and the average hourly temperature. """ # Im...
10,524
8ca05fa2f5e33923804ddc983bf9cdb183fa268a
from os import path from cv2 import cv2 from Katna.image import Image from glob import glob import operator from PIL import Image as pil from util import conf from util.log_it import get_logger logger = get_logger(__name__) img_module = Image() thumbnail_height = 180 thumbnail_width = 360 banner_ratios = [ '%d:1' %...
10,525
9f10849077f41f99fe45d9bf4a13432d663b1ca3
from .q_learner import QLearner from .coma_learner import COMALearner REGISTRY = {} REGISTRY["q_learner"] = QLearner REGISTRY["coma_learner"] = COMALearner
10,526
a71561117c200d73ab93bc7e6ed61dff9c90a713
from app.api.v2.managers.base_api_manager import BaseApiManager from app.api.v2.responses import JsonHttpNotFound class ContactApiManager(BaseApiManager): def __init__(self, data_svc, file_svc, contact_svc): super().__init__(data_svc=data_svc, file_svc=file_svc) self.contact_svc = contact_svc ...
10,527
a74f40a5b793baab5efeea51a03788816c917c8e
import pygame from display_object import * class Actor(DisplayObject): def __init__(self, name, x_pos, y_pos, size, hp, mp, str, defense, mag, gold, moves, direction, max_moves, max_hp, visible, image_path): DisplayObject.__init__(self, name, x_pos, y_pos, size, visible, image_path) self.str = s...
10,528
d4f5ded34c5f4ea2c282ff1329a9370b3d2f7c2b
# -*- coding: utf-8 -*- # # Copyright (c) The PyAMF Project. # See LICENSE.txt for details. """ Tests for AMF3 Implementation. @since: 0.1.0 """ import unittest import datetime import pyamf from pyamf import amf3, util, xml, python from pyamf.tests.util import ( Spam, EncoderMixIn, DecoderMixIn, ClassCacheClear...
10,529
4c25ecafd948b5923467710cbacf3c5ddbe1face
# list methods 2 # we will be going over some uses of lists # let's first create 2 lists my_first_list = [1, 2, 3, 4, 5] my_second_list = [6, 7, 8, 9, 10] # reversing a list my_first_list.reverse() print(my_first_list) # sorting a list my_second_list.sort() print(my_second_list) # adding 2 lists my_third_list = my_...
10,530
0164633c0119e72cce5e67a0ae9997dda8d0ffbd
#!/usr/bin/env python import rospy, cv2, cv_bridge, numpy from sensor_msgs.msg import Image from geometry_msgs.msg import Twist from std_msgs.msg import String from nav_msgs.msg import Odometry from darknet_ros_msgs.msg import BoundingBoxes, ObjectCount from tf import TransformListener from navigation.srv import * MAX...
10,531
bb31cf5e6b6cc550c7ffe6a83fad9a133f140d38
from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.models import BaseUserManager from django.db import models #from review.views import ReviewViewSet #import Review from django.db.models import Avg class AccountManager(BaseUserManager): def create_user(self, email, password=None, **...
10,532
e687ed7ac8ef779cf18ed5ff3517d850ac88d4fb
# -*- coding: utf-8 -*- from django import forms from app.models import * class LivroForm(forms.ModelForm): class Meta: model = Livro fields = ['titulo', 'ano_publicacao', 'autor'] class AutorForm(forms.ModelForm): class Meta: model = Autor fields = ['nome',]
10,533
f54896da89b093e96094f4b19cf451952e8e29e5
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
10,534
bc3112a6f179d78ec9c19c32f07c24e657abd589
# Copyright (C) 2017 William M. Jacobs # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or (at # your option) any later version. # This program is distributed i...
10,535
de442d9a04b55880c69ac1ddef826d1895fd3a60
# coding=utf-8 from django.contrib import admin from users.models import Donors class DonorsAdmin(admin.ModelAdmin): fieldsets = ( ('Informações Básicas', { 'fields': ('name', 'address', 'number', 'complement', 'neighborhood', 'city', 'state', 'cep', ) }), ) ...
10,536
0afc2ccc562263de9b3e118753bc56bb878dec3c
# CDB implemented in python ... with a pythonic interface! # Starting point provided by Yusuke Shinyama # Eric Ritezel -- February 17, 2007 # # 20070218 - longstream optimization started # there's something slow about this. low memory usage, though. # 20070219 - had dream that led to increased performance. ...
10,537
503b2c2580d35db2b5fb4ddb910142dc3d450f19
import bcrypt import base64 def get_log_psw_from_header(header): base64_log_psw = header.split(' ')[1] decoded_log_psw = base64.b64decode(base64_log_psw.encode('utf-8')).decode('utf-8') lst_decode_log_psw = decoded_log_psw.split(':') return lst_decode_log_psw def check_psw(decoded_psw, psw_from_db):...
10,538
a72c3abb96fae528ad8cc1680e0de7f223f9bcd4
# -*- coding: utf-8 -*- S = 0 for i in range(100): S += 1/(i+1) print("%.2f" %S)
10,539
88f765484a9018f4bfa96234d951d513d9795b9a
#!/usr/bin/python3 import json import requests import datetime import matplotlib.pyplot import matplotlib.dates import math from matplotlib import rcParams from matplotlib.patches import Rectangle from rpy2.robjects.packages import importr from rpy2.robjects.vectors import DataFrame import rpy2.robjects as robjects ...
10,540
8a77bce21d5d59ab57f85b1cbd6d27dd5b0162d8
# Generated by Django 3.1.6 on 2021-02-10 11:18 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('blog', '0002_post_body'), ] operations = [ migrations.AddField( model_name='post', name='mode', field=mo...
10,541
e21f62a8dc69087c1a818920f3d2ef4c3b2e1e42
import yaml import xmltodict from xml.dom import pulldom from xml.sax import make_parser, SAXException from xml.sax.handler import feature_external_ges from flask import jsonify, request from app.models import Product, Order, Item from app.api import bp from app.api.auth import token_required, jwt_decode_handler from ...
10,542
1bf4a77ca7c5840946b4b2477faa89efb011fea5
import pygame.init() #pygame에 필요한 모든 모듈을 초기화 (init=초기화 메소드?) screen = pygame.display.set_mode((1920,1080)) #게임창 크기 지정 width , height
10,543
790fde6908068055c1c4ea0118ed02c2c5c0c5a6
from itertools import permutations from fractions import Fraction # 1 for red # 0 for blue x = [1, 1, 1] y = [0, 0, 0, 0] # all combinations, excluded first blue p = list(filter(lambda m: m[0] == 1, permutations(x + y, 2))) # all combinations with second blue e = list(filter(lambda m: m[1] == 0, p)) # result: 2/3 p...
10,544
27757fade1c3a72fe03047c28eb821370e91b589
from __future__ import print_function from __future__ import division from __future__ import print_function from __future__ import absolute_import import tensorflow as tf import models_mnist def weight_variable(shape): initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial) def bias_variab...
10,545
80fee63893a9011e80471fe168327e30cd6a80a1
#calss header class _MARSHALS(): def __init__(self,): self.name = "MARSHALS" self.definitions = marshal self.parents = [] self.childen = [] self.properties = [] self.jsondata = {} self.basic = ['marshal']
10,546
1cc2f4b3dbbd33ed350a6cc3c8685fb0607d9e4b
class Intcode: def __init__(self, program, input, output): self.memory = {i: program[i] for i in range(len(program))} self.input = input self.output = output self.ip = 0 self.base = 0 def get_value_at(self, address): return self.memory.get(address, 0) def ge...
10,547
7468f96da6b94a039e2ce67020b970e7f1ce12ae
""" $Id$ This file is part of the xsser project, http://xsser.sourceforge.net. Copyright (c) 2011/2012/2013/2014/2015 - <epsylon@riseup.net> xsser is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation version 3 of the...
10,548
e99b1ae97b9834288b6606fa874e45850187c9e4
""" Given the root of a binary tree and an integer distance. A pair of two different leaf nodes of a binary tree is said to be good if the length of the shortest path between them is less than or equal to distance. Return the number of good leaf node pairs in the tree. Example 1: Input: root = [1,2,3,null,4], distance...
10,549
2c5d3af8d6de9ba93a304cc826972c24079237e8
aluno0 = {'Nome': str(input('Digite o nome do aluno: ')).strip().capitalize()} nota1 = float(input(f'Digite a nota do {aluno0["Nome"]} no 1° bimestre: ')) nota2 = float(input(f'Digite a nota do {aluno0["Nome"]} no 2° bimestre: ')) aluno0['Media'] = (nota1 + nota2) / 2 if aluno0['Media'] < 5: aluno0['Situação'] = 'R...
10,550
defc2067dc521b3d7e9c75d74855a72379679759
import unittest from parameterized import parameterized import numpy as np from src.dataset.preprocessing.images import _GroundTruthClassMapper from src.dataset.utils.mapping_utils import Color2IdMapping from test.utils import ArrayContentSpec, assembly_array class GroundTruthClassMapper(unittest.TestCase): @p...
10,551
cf2e2a1835bb07650b6c66285b78b116cf522690
import pytest import random from merge_sort import merge_sort def test_func_exists(): merge_sort([1]) def test_sort(): input = [1, 5, 3, 2, 4] actual = merge_sort(input) expected = [1, 2, 3, 4, 5] assert actual == expected def test_all_same(): input = [3, 3, 3, 3, 3, 3, 3]...
10,552
862ab0a9be465ce16b3d273a5eb8de3a94a80452
# mdpAgents.py # parsons/20-nov-2017 # # Version 1 # # The starting point for CW2. # # Intended to work with the PacMan AI projects from: # # http://ai.berkeley.edu/ # # These use a simple API that allow us to control Pacman's interaction with # the environment adding a layer on top of the AI Berkeley code. # # As requ...
10,553
08097d4784d145365781cf7fdbdab11959b4b54b
"""Alchemy - Flask.""" from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'postgres://localhost/computers-db' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db = SQLAlchemy(app) class Computer(db.Model): """Notice that all models in...
10,554
b7cb9b11b94b80cce8944306068e410d4a79a833
########################################################################################################################################## #Required Modules import re,os,sys WORD = re.compile(r'\w+') import string import math import time import collections import nltk from nltk.corpus import stopwords from collectio...
10,555
891e93bdd3ffb0003344b45dce0ad920e79716ca
# -*- coding: utf-8 -*- def getFrases(): frases = [] arquivo = open('quotes.txt', 'r') for linha in arquivo: frases += [linha] arquivo.close() return frases
10,556
fb5f04226bd50ccc0744680c5bc2595de894ea6b
import baostock as bs import pandas as pd import os from datetime import datetime, timedelta import time import requests from lxml import etree import re from downloader import bao_d, xueqiu_d, dongcai_d from code_formmat import code_formatter from basic_stock_data import basic class StockProfit: def generate_re...
10,557
7583811dfce69089e6c2e6e80da21eb4a61704ca
#!/usr/bin/env Python3 import requests import json import datetime import time from pymongo import MongoClient client = MongoClient() db = client.predictit_data hist = db.historical url = "https://www.predictit.org/api/marketdata/all/" prev_entries = {} while(True): start = datetime.datetime.now() try: ret = re...
10,558
551f7b26d083a3fe3ad353e76a6c248d2dba1a97
""" Common utility routines for Finite State Projection. """ import operator import numpy from cmepy.cme_matrix import non_neg_states from cmepy import lexarrayset def maxproppercent(propensities, percent_prop): maxVal = propensities[0] for i in range(0, len(propensities), 1): if maxVal < propensiti...
10,559
eb51106cf41d32e8961d7a339a0b4b6440e265fb
from django.urls import reverse from menu import Menu, MenuItem Menu.add_item( "main", MenuItem( "Add presentation", reverse("presentation-manager:presentation-add"), weight=1000, check=lambda request: request.user.is_authenticated and request.user.has_perm("presentation...
10,560
c926e3500c2606a42c4745dbd26121af31a7a210
import pandas as pd from sys import argv import os import glob import datetime #The goal is to replace the Resource_List.wall_time from current accounting file # with the newly predicted value from the model # The argument has the following order: # 1. Full path of parsed CSV accounting file # 2. Directory of inp...
10,561
ced72b9c3b44cd035591a3e6adc05fd33931da42
import random import uuid from temperatures import models import datetime from django.utils import timezone first = timezone.now() offset = datetime.timedelta(minutes=1) DUMMY_UUID = uuid.UUID('12345678123456781234567812345678') dades = 3600 device, _ = models.Device.objects.get_or_create(identifier=DUMMY_UUID) for...
10,562
f7749518ddcbffa5dce9f04a1ae1f54e4f191019
print "How my order cost?" print "Cell phones 2 * Nokia 101 - 2 * 274 = ", 2 * 274
10,563
aaa9c50d93f46972d402a9979ba19b3231fecf0e
# -*- coding: utf-8 -*- # Generated by Django 1.11.26 on 2020-01-20 22:54 from __future__ import unicode_literals import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('hqadmin', '0009_auto_20170315_1322'), ] operations = [ mig...
10,564
a1e2cbfe73c8889bca05dd05a02ef1789bb61a68
def sumDigits(n): result = 0 while(n != 0): result += n % 10 n //= 10 return result def main(): n = int(input('Enter a number between 0 and 1000 : ')) result = sumDigits(n) print('The sum of the digits is', result) if __name__ == "__main__": main()
10,565
5b0758ad1120b5d44e35e3c37a150ecc4e9fcd57
"""Defining input class.""" import sys import termios import tty import signal import os import time import random import numpy as np from config import * from screen import * from brick import * from paddle import * from ball import * from powerup import * from bullet import * from input import * class Game: d...
10,566
2ff109418716d51885e5864f86dd1d054e77f5df
import numpy as np import csv import matplotlib.pyplot as plt import pandas as pd import glob import ulmo import os import scipy.stats results_filepath = 'plots/version1/' pairs = pd.read_csv('USghcnpairs_stationlengths.csv') df = pairs[917:] df = df[~np.isnan(df['Urban brightness'])] # compute UHI composite setting UH...
10,567
e38d24d3ffc0237a75cd4188113751aa08c43371
from unittest import TestCase import requests import mock from orion.clients.geocode import ReverseGeocodingClient class TestReverseGeocodingClient(TestCase): def setUp(self): self.auth_client = ReverseGeocodingClient('token') self.unauth_client = ReverseGeocodingClient() @mock.patch.object...
10,568
e593cf3e636fff276bb383f4c9a5e4afedfc72e7
"""Effectively does a "from sage.all import *" on the imported module. Designed to be imported/called in an external sage session.""" import importlib, sys def attach_sage(module): attrs = {} sage_mod = importlib.import_module("sage.all") #do this rather than __dict__ to avoid binding private vars for ...
10,569
4e37499449a3c5777d265d7dd6f925afebe7d0dc
# -*- coding: utf-8 -*- # # Copyright (C) 2010-2016 PPMessage. # Guijin Ding, dingguijin@gmail.com # All rights reserved # # backend/tornadoupload.py # # The entry of tornado upload service # from ppmessage.core.constant import TORNADO_FILEUPLOAD_PORT from ppmessage.backend.tornadouploadapplication import TornadoUplo...
10,570
640a2105876b45b05e430ca4b287d2976a3b2fdb
user_name='sai' print('your name:'+user_name.title()) print('your name:'+user_name.lower()) print('your name:'+user_name.upper())
10,571
3105e7321e7d4ac0e09bd64ec15f62f15a97fb92
import collections import copy import sys dict_of_substituted_value = collections.OrderedDict() theta = collections.OrderedDict() fo = open('output.txt', 'w') askFlag = False falsify = '' forLoopDetection = set() standard_list = [] standard_counter = 1 poo = True def extractArguments(curr_goal): ...
10,572
29891ddd9eea261dd5cc2a3ce95cf8663f93bfa4
# Copyright (c) 2019 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. # SPDX-License-Identifier: Apache-2.0 import unittest from datetime import datetime from dazl.model.core import ContractId from dazl.plugins.capture import fmt_pretty from dazl.plugins.capture.model_capture import Ledger...
10,573
498362acf26b69038f6b77fadca5968259e293a7
#!/usr/bin/python #coding=utf-8 fo = open("dir/test.txt", "r+") #读取10个字节 str = fo.read(10) print str postion = fo.tell() print "Curr file postion", postion fo.seek(1, 1) str = fo.read(10) print str #记得关闭 fo.close()
10,574
7089fe1a58a4437f215b6ae977b081dff4e2a930
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Mar 20 17:32:23 2020 @author: carlotal """ import numpy as np import matplotlib.pyplot as plt from matplotlib.widgets import Slider, Button import proper def objet_def(D,D_ratio,N): x = np.linspace(-D/2,D/2,N,endpoint=False) + D/(2.0*N) X,Y = ...
10,575
995a5a8e71a90ab0a3dfab73972b4dede8fe5fc1
# Copyright (c) 2016-present, Facebook, Inc. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # pyre-unsafe import unittest from unittest.mock import patch from .. import find_directories from ..find_directories import find_local_root, find...
10,576
4f80c9fb7da79c95f325cde7017766dc74288b59
#Resposta do exercicio 1.Faça um programa que receba a idade do usuário e diga se ele é maior ou menor de idade. def ageCheck(ageUser = int(input("how old are you?"))): if (ageUser >= 18): return True else: return False print(ageCheck())
10,577
c4645c56d30caa3253c654d215b5e28256159a15
import config as c import numpy as np from pathlib import Path import matplotlib.pyplot as plt import data.data_helpers as data_helpers import data.prepare_data as prepare_data import evaluate from evaluate import compute_calibration,sample_posterior import time import torch #compute_calibration = evaluate.compute_cal...
10,578
ffbb6fab14fdbf40b5c23b1c5fc6e55b8fcaadbd
''' Link: https://www.codechef.com/DEM2020/problems/TOWIN ''' from sys import stdin,stdout for _ in range(int(stdin.readline())): n=int(stdin.readline()) nums=list(map(int,stdin.readline().split())) if n==1: stdout.write(str('first\n')) elif n==2: if nums[0]==nums[1]: stdou...
10,579
5b62d818c133391728b22cbbc8b5889c6e0b3e72
from aspose.cloud.common.product import Product from aspose.cloud.common.utils import Utils from aspose.cloud.common.asposeapp import AsposeApp class CellsExtractor(object): file_name = "" def __init__(self, file_name): self.file_name = file_name def get_picture(self, worksheet_name, pic...
10,580
7ab65cbcd089fafaa532981c1ae34a820d1a2d71
import os import pyaudio import wave import time as t FORMAT = pyaudio.paInt16 CHANNELS = 1 RATE = 48000 CHUNK = 1024 RECORD_SECONDS = 3 WAVE_OUTPUT_FILENAME = "file2.wav" audio = pyaudio.PyAudio() print(f"Bith depth: 16") print(f"Sample rate: {RATE}") print(f"Chunk size: {CHUNK}") print(f"Recording time: {RECORD_SE...
10,581
bdca99266a45df63c56d1a1d9d49fe0441a417f7
import os from concurrent.futures import ThreadPoolExecutor import pytest import word_count current_dir = os.path.abspath(os.path.dirname(__file__)) path = os.path.join(current_dir, "zen-of-python.txt") @pytest.fixture(scope="session") def contents() -> str: text = """ The Zen of Python, by Tim Peters Beautif...
10,582
2ed3ae4a0164c559ca4f30d814ccb33a91e80fa4
print('%5i%5i' % (10, 235)) print('%5i%5i' % (1000, 50))
10,583
d2b408f24bd2f587df74aef003b1f97337bfdc4a
from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.naive_bayes import GaussianNB iris = load_iris() print(iris) X = iris.data y = iris.target print(X.shape) print(y.shape) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=84) model = Gaussia...
10,584
9c907d6c7f1022eceec96537deaebbac21036227
import numpy as np from keras.datasets import cifar100 from keras.preprocessing.image import ImageDataGenerator from keras.models import Sequential from keras.layers.core import Dense, Dropout, Activation, Flatten from keras.layers.convolutional import Convolution2D, MaxPooling2D from keras.optimizers import SGD from k...
10,585
4adedc5898d0a564fe8f496534bad29146607fd4
#Given a string, print the string capitalized. string = raw_input("what's the string?") string_cap = string.capitalize() print string_cap
10,586
6dad01f9b94866a2ec394208eec8cbffcbc563f3
import sys from PyQt5.QtWidgets import QApplication , QWidget, QPushButton, QTableWidgetItem from PyQt5.QtGui import QIcon from PyQt5.QtCore import pyqtSlot from PyQt5.QtWidgets import QHBoxLayout, QGroupBox , QDialog, QVBoxLayout, QGridLayout from PyQt5.QtWidgets import QLabel, QTextEdit from PyQt5.QtWidgets import QM...
10,587
9beb996d4106e806f2cee8c0ee62faf28161a240
import spacy from spacy.tokens import Doc from SubjectObjectExtractor import SubjectObjectExtractor nlp = spacy.load("en_core_web_md") pipeline_component = SubjectObjectExtractor(nlp) pipeline_component.adj_as_object = True Doc.set_extension('svos', default=None) nlp.add_pipe(pipeline_component, last=True) file = ope...
10,588
68b3754e602e5128448738bde8ebf35492b15455
class Store: _name = None _realised = 0 _realisedsumm = 0 def __init__(self, name,): self._name = name def set_name(self, name): self._name = name def get_name(self): return self._name def set_realised(self, realised): self._realised = realised def g...
10,589
b732b2ccfa7393e748a570626c6b236cfa70c938
import cv2 def correlation(img): (img_B, img_G, img_R) = cv2.split(img) for i in range(1, 11): img = cv2.imread(str(i) + ".jpg", cv2.IMREAD_COLOR) img = cv2.resize(img, dsize=(128, 128), interpolation=cv2.INTER_AREA) cv2.imshow("1", img) cv2.waitKey(0)
10,590
8c4f2ecfbc1fed057c65534003e3e3a63acfbd46
#coding; utf-8 import urllib import utility def get_problem(id, status=None): url = "http://judge.u-aizu.ac.jp/onlinejudge/webservice/problem"; pram = {"id": "%04d" % id}; if (status): pram["status"] = status; pram_str = urllib.urlencode(pram); print pram_str return (utility.xml2dict(...
10,591
ba77d62b4812b676e0d2227f0327e176ed6c9263
op1=int(input('첫번째 수 입력:')) op2=int(input('두번째 수 입력:')) print(op1,'+',op2,'=',(op1+op2)) print(op1,'-',op2,'=',(op1-op2)) print(op1,'*',op2,'=',(op1*op2)) print(op1,'/',op2,'=',(op1/op2))
10,592
d2de10264c96e44403a1c30d44d6d4b227f754ee
from django.core.exceptions import ObjectDoesNotExist from django.core.management.base import NoArgsCommand from django.utils.html import strip_tags from datetime import time import MySQLdb from program.models import Show, Schedule, RRule USER = 'helsinki' PASSWD = 'helsinki' DB = 'helsinki' RRULES = { 0: RRule...
10,593
fc04a89c4e21f90d0b6c52271424310c42a7ac0c
from flask import Blueprint, request, jsonify, make_response from database.db import mongo from bson import ObjectId # create the blueprint to be registered in app.py user = Blueprint("user", __name__) @user.route("/api/user", methods=["POST"]) def create_user(): # user = {"name": "John Smith", "age": 48, "addr...
10,594
120f524168c1a648b054a421d3f7ac77d8070ad1
# @Author: lonsty # @Date: 2019-09-07 18:34:18 import json import math import os.path as op import re import sys import threading import time from collections import namedtuple from concurrent.futures import ThreadPoolExecutor, as_completed, wait from datetime import datetime from pathlib import Path from queue impor...
10,595
89dddd59f164d8697cd913091625124f738117cd
import re import urllib.request string="Michael is my M 30 year old son and lives with his wife Jess who is 25 years old.They have a joint account worth $125000" ages=re.findall(r'\d{1,3}',string) names=re.findall(r'[A-Z][a-z]*',string) # looking for strings with a beginning capital letter #followed by 0 or more small ...
10,596
fa6096641c65844e940b16f49852aef0fb748e28
from __future__ import absolute_import from __future__ import print_function from ..Block import Block class RDBPhysicalDrive: def __init__(self, cyls=0, heads=0, secs=0, interleave=1, parking_zone=-1, write_pre_comp=-1, reduced_write=-1, step_rate=3): if parking_zone == -1: parking_zone...
10,597
b94be32071c1444c7b14f38907642679b9eb14cf
from django.db import models class Donationreqs(models.Model): user_id = models.IntegerField() volunteer_id = models.IntegerField(blank=True, null=True) status = models.IntegerField() mobile = models.CharField(db_column='Mobile', max_length=100, blank=True, null=True) # Field name made lowercase. ...
10,598
9994a6fb04188d0d44833f2155fc64028e9af756
import os import argparse import datetime import math import heapq def get_filepaths(): ''' Reads command line argument for input/output filepaths Parameters: None Returns: input filepath (string) output filepath (string) percentile filepath (string) ''' parser = argparse.ArgumentParser() parser.add_a...
10,599
a27e70dc501ab0beba958fb665736edc3a967293
""" User validation schemas. """ from marshmallow import pre_load, Schema, validates_schema, ValidationError from marshmallow.fields import Bool, Email, Str from marshmallow.validate import Length class BasicUserSchema(Schema): email = Email(required=True) first_name = Str(required=True, validate=Length(max=1...