index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
12,200 | 7772238f55b1dabedc6fa41ace509ff2df181a02 | """Write a code to find string after $5 from string
"i have $2 in my pockets and $5 in wallet and i need $3 more"""
str1 = "i have $2 in my pockets and $5 in wallet and i need $3 more"
print(str1.split("$5", 1)[1])
|
12,201 | 4ab6db4ddd15683d5486a6ce5d4a368545640938 | config = {
'system_plugins': ['former', 'logout'],
'twanager_plugins': ['former', 'lister'],
'instance_tiddlers': [
('system', [
'http://svn.tiddlywiki.org/Trunk/association/adaptors/TiddlyWebAdaptor.js',
'http://svn.tiddlywiki.org/Trunk/association/pl... |
12,202 | 76ebb40c1b0cbd5f736173db8f15ce502cd30526 | # from collections import Iterable
# 用迭代器实现斐波那契数列
class Iter:
def __init__(self, n):
self.a = 0
self.b = 1
self.n = n
def __iter__(self):
return self
def __next__(self):
self.a, self.b = self.b, self.a + self.b
if self.a > self.n:
raise StopIterat... |
12,203 | cdc18a5bd86e169f6faad5da00f6d88e8ba0ca08 | import AdventOfCode.util.input_parser as parser
PART = 2
DEBUG = False
def _debug(msg):
if DEBUG:
print(msg)
if __name__=="__main__":
filename = f"./raw_inputs/day8{'_debug' if DEBUG else ''}.txt"
instructions = parser.parse(filename, transforms=[parser.Split(' ')])
for instruction in instr... |
12,204 | 5fefacde36d88b946d4b46ff13ef236f31c5a0c5 | import math
n = int(input())
a=[]
for i in range(n):
a.append(int(input()))
for i in range(max(a)):
print(i)
print(a)
|
12,205 | 7e7cd5dc99e6a03e47d2e22efc07aca532176ae7 | import re
import xml.etree.ElementTree as ET
from logwatch import log
from dbwatch import trends
from config import GROUPS
#processRRU.py
# Python based script watches redis queue for Sev3 or lower IR/RRU and RRU adds to GOS FU as soon as hits queue.
# Removes from GOS FU as soon as leaves queue or is closed...
# Cha... |
12,206 | 723026633661221304f950cb04a3731ace71f977 | from __future__ import unicode_literals
from django.db import models
from add_user.models import *
# Create your models here.
STATUS_CHOICES = (
(0, 'Pending'),
(1, 'Confirm'),
(2, 'Rejected'))
class customer_data(models.Model):
name=models.CharField(max_length=20,blank=True,null=True)
mobile=model... |
12,207 | 54905961f5da67d188acd3d289b59b48346852ab | __author__ = 'idfl'
def urlencoding(param):
param = param.__str__()
if '_' in param:
return param.replace('_', ' ')
elif ' ' in param:
return param.replace(' ', '_')
else:
return param |
12,208 | 893765a68d8911343d4a1fd5c8acfc72d5eea102 | '''
python 魔法函数--指的是双下划线开头、双下划线结尾的函数
'''
class Company(object):
def __init__(self, employ_list):
self.employee = employ_list
def __getitem__(self, item):
# 循环对象的时候会执行该方法,执行到抛异常截至
# print("开始执行__getitem__")
return self.employee[item]
def __len__(self):
# 执行类实例对象的le... |
12,209 | 41e87d3269a12ec19d325b4946d225e07c2d0c29 | class Solution(object):
def countDigitOne(self, n):
"""
:type n: int
:rtype: int
"""
if n <= 0:
return 0
count = 0
base = 1
num = n
while num:
remainder = num % 10
num = num // 10
count += (num *... |
12,210 | 69f40c0408b32fb04baee4f5348a2e45e699024b | from django.apps import AppConfig
class AdministracjaConfig(AppConfig):
name = 'administracja'
|
12,211 | 5328dd2508fcf4716c6dce8d4352941c06d8e643 | import requests
import re
headers = {
'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.163 Safari/535.1'
}
r = requests.get('https://music.163.com/#/user/home?id=1436779441', headers=headers)
text = re.findall(r'<img src="(.*?)', r.text)
print(text) |
12,212 | 248f96ad9588539b7944676596752fd3648a1855 | from graph import Node
class Category(Node):
def __init__(self, title):
self.title = title
self.id = title
super().__init__(self.id) |
12,213 | 80b425ecbd70bb2aec48b2ac40636ac915ff2731 | from .index_parser import IndexParser, InfoParser
from .page_parser import PageParser, Weibo, CommentParser, HotCommentParser
from .follow_parser import FollowParser
from .fans_parser import FansParser
from .search_weibo_parser import SearchWeiboParser
from .search_users_parser import SearchUsersParser |
12,214 | 3e43025c481b47671655d9537e7e8cfd9bea3f7e | from dlflow.tasks import TaskNode
from dlflow.mgr import task, model, config
from dlflow.features import Fmap
from dlflow.utils.sparkapp import HDFS
from dlflow.utils.locale import i18n
from pathlib import Path
from absl import logging
import tensorflow as tf
import shutil
@task.reg("train", "training")
class _Train... |
12,215 | 256c00847e3a54a16ab80beab2565b2af93a0f4a | from textblob import TextBlob
from textblob.exceptions import NotTranslated
import tweepy
import re
class Sentiment():
def __init__(self,count):
self.count = count
consumer_key = 'M79jyuM8cWJC3MBLZMT1LAwft'
consumer_secret = 'bk6Ukwej6Dd42mU3Hq4wgeBbjlZ5qFekHfCqTQjkRaxlQgKu6Y'
access_token = '89779969444064... |
12,216 | 84c11f7f2301dfb7527fb210e6753c858c1782db | '''
Descripttion:
version:
Author: nlpir team
Date: 2020-08-08 10:20:49
LastEditors: cjh
LastEditTime: 2020-09-13 15:39:31
'''
import sys, os
import time
from threading import Thread
sys.path.insert(0, os.getcwd())
from nlpir047.corrector_dict.corrector_dict import CorrectorDict
from nlpir047.utils.corrector_utils.g... |
12,217 | 8e91d0a26684dec52569ac87ff5819b95c4ce8f1 | # -*- coding: utf-8 -*-
import pytest
import subprocess
import sys
sys.setrecursionlimit(65535)
@pytest.mark.light
def test_wn18_cli():
# Checking if results are still the same
cmd = ['./bin/kbp-cli.py',
'--train', 'data/wn18/wordnet-mlj12-train.txt',
'--lr', '0.1',
'--model... |
12,218 | f9cda23525f18e2cd7c6a73377c29201154b0b66 | #!/usr/bin/env python
# This is a stub script loading test_server module, used by PyInstaller.
import runpy, sys, os
# Make sure hidden imports are found
import sitescripts.cms.bin.test_server
import markdown.extensions.attr_list
sys.argv[1:] = [os.curdir]
runpy.run_module("sitescripts.cms.bin.test_server", run_name... |
12,219 | 90955415024c4c911ed93b6e21612fb028149f89 | #!/usr/bin/env python2
import os
import glob
import subprocess
import re
import optparse
def main():
parser = optparse.OptionParser(usage='Usage: %prog -i <source directory> <options> -o <output file>')
parser.add_option('-i', dest='djvu', action='store',\
help='the source d... |
12,220 | 674b384f5f8039cd22c8879ccb7676e1c9e1ea60 | def greetings(get_data):
def get_greeting(*args):
data = ""
split_string = get_data(*args).split()
if len(split_string)>0:
name = split_string[0]
if len(split_string)==3:
second_name = split_string[1]
surname = split_string[2]
... |
12,221 | 150364697fa10fd52cd71b5a9961a187de8f3c13 | # -*- coding: utf-8 -*-
# 斐波那契的四种实现与比较
# 用fib(100)来比较
def fib1(n):
"""递归法, 复杂度高"""
if n==1 or n==2:
return 1
else:
return fib1(n-1)+fib1(n-2)
def fib2(n):
"""迭代法, 复杂度一般"""
if n==1 or n==2:
return 1
first = 1
second = 1
temp = 0
for i in xrange(n-2):
... |
12,222 | 4db9df3b60c70b39d5b1ca2043304e3e8afb9106 | import numpy as np # for matrix computation and linear algebra
import matplotlib.pyplot as plt # for drawing and image I/O
import scipy.io as sio # for matlab file format output
import itertools # for generating all combinations
import scipy.linalg as scpl
def estimate_Q(u, x, ix):
"""
:return: Q, points_... |
12,223 | c87a8cb8228f0d289fe90f9a6e7799fbd21990da | import unittest
from .bubble_sort import bubble_sort
class TestBubbleSort(unittest.TestCase):
def test_case1(self):
input = [3, 2, 1]
actual = bubble_sort(input)
self.assertEqual(actual, sorted(input))
def test_case2(self):
input = [5, 4, 3, 2, 1]
actual = bubble_sort(... |
12,224 | 1517ce7474962dcfdaee5106b6de7d8f8e886169 | """
챕터: day7
주제: file 쓰기
문제:
현재 디렉토리 아래에 fruit.txt 파일을 생성하여, 사용자가 입력하는 과일을 한 줄에 하나씩 3개를 저장하라.
작성자: 윤경환
작성일: 2018.12.06
"""
import os.path
print(os.getcwd())
f = open("friut.txt","wt") # at, wt
x = input("과일: ") # 과일이름
x1 = int(input("가격: ")) # 과일가격
y = input("과일: ")
y1 = int(input("가격: "))
z = input("과일: ")
z1 = int(in... |
12,225 | 008e99b5d06db24d69a60f0972d1a99eeb8e3ed2 | import random
while True:
try:
k=random.randint(0,100)
x=int(input("请输入0~100之间的整数:"))
tem=0
while x != k:
tem +=1
if(x>k):
print("遗憾,太大了")
else:
print("遗憾,太小了")
x=eval(input("请输入0~100之间的整数:"))... |
12,226 | 7e635eedbd50de0588ac09a0e470e54436f72dea | # import necessary libraries
from models import create_classes
import os
from flask import (
Flask,
render_template,
jsonify,
request,
redirect)
#################################################
# Flask Setup
#################################################
app = Flask(__name__)
#################... |
12,227 | b05620dfd2637cb21295ce8f50f781a1a418fd22 | import unittest
from python_katas.isograms.src import Isograms
class IsogramsTest(unittest.TestCase):
def test_should_return_true_for_isograms(self):
self.assertEqual(Isograms.is_isogram("Dermatoglyphics"), True)
self.assertEqual(Isograms.is_isogram("isogram"), True)
self.assertEqual(Iso... |
12,228 | 5fecedc6364dd905b8f6346ae95cf9b3709d42bf | from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.decorators import api_view
from rest_framework import status
from config.messages import Messages
from utility.requestErrorFormate import requestErrorMessagesFormate
from utility.authMiddleware import isAuthenticate
fro... |
12,229 | eb736bcc63ccce4971bf4a35456ae36964f1b79b | count=0;
while(count<9):
print('count is ',count);
count=count+1;
print("Good Byee!");
|
12,230 | 6f53191ebda210e7e966e4442c2bed8094e4895d | # -*- coding: utf-8 -*-
# ======================================
# @File : leetcode_nm3.py
# @Time : 2019/10/3 22:54
# @Author : Rivarrl
# ======================================
from typing import List
from algorithm_utils import *
def findPeakElement(nums):
"""
162. 寻找峰值
峰值元素是指其值大于左右相邻值的元素。
给定... |
12,231 | 683b279a752760f0d4bd2d152fa84945d3340656 | # -*- coding: utf-8 -*-
import numpy as np
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import re
import os
def clean_str(string):
"""
Tokenization/string cleaning for all datasets except for SST.
Original taken from https://github.com/yoonkim/CNN_sentence/blob/master/process_dat... |
12,232 | a01a810fd74d2a68f1e8e4c85a31f363cf2c1359 | # most straightforward solution would be more efficient with multiple return values, and Python makes those easy to handle
def tilt_and_sum(node):
if node == None:
return (0,0)
left_sum, left_tilt = tilt_and_sum(node.left)
right_sum, right_tilt = tilt_and_sum(node.right)
return (node.val + left... |
12,233 | 8235ac5f16d54b726258bc5687caf26ac296d7de | #!/usr/bin/env python
# coding: utf-8
# Matplotlib: sigmoidal functions
# ======================================================================
#
# matplotlib's approach to plotting functions requires you to compute the
# x and y vertices of the curves you want to plot and then pass it off to
# plot. Eg for a normal... |
12,234 | e452b7802c3af6218a006877a1f141a78462a518 | # -*- coding: utf-8 -*-
"""
Attempt to scrape scholar.google.com results for Stan usage tracking"""
#from selenium import webdriver
import requests
from bs4 import BeautifulSoup
import redis
import re
import numpy
import time
import subprocess
import os
REDIS = redis.Redis()
# retrieve
# set of queries, broken out... |
12,235 | 61494260399c8bcc2c956e89fc4fee9cf3490dcc | #导入traceback模块
import traceback
class SelfException(Exception): pass
def main():
firstMethod()
def firstMethod():
secondMethod()
def secondMethod():
thridmethod()
def thridmethod():
raise SelfException("自定义异常信息")
try:
main()
except:
#捕获异常,并将异常传播信息输出到控制台
traceback.print_exc()
#捕获异常,并将异常传播... |
12,236 | 5d53d876db69aef9c0006f33b3612dc83afbf296 | #!/usr/bin/env python3
#
# Author: Soft9000.com
# 2018/11/24: GUI Project Begun
# Mission: Create a graphical user interface to PyDAO.
# Status: Released to PyPi
import os
import sys
sys.path.insert(1, os.path.join(sys.path[0], '..'))
from tkinter import *
from tkinter import messagebox
from tkinter.filedialog impor... |
12,237 | 9a32952621ce6b312453c20566e27288997ba7de | from django.conf import settings
from django.urls import reverse
from ..models import Topic
from ..models.Command0Arg import Command0Arg
TEXT = """Great! Now you have a new topic!
You can send `HTTP POST` requests to:
`{webhook_endpoint}`
If you want more people receiving the notifications, send them this TopicCod... |
12,238 | 63b3dcf8298a34089ec2be3c4ee15cdd73c1c76d | from numbers import Number
import math
# All the imports from pyparsing go here
from pyparsing import (delimitedList, Forward, Literal,
stringEnd, nums, Word, CaselessLiteral, Combine,
Optional, Suppress, OneOrMore, ZeroOrMore, opAssoc,
operatorPrec... |
12,239 | 7865e85501fb7cb316f1b97220505a9886643ef9 | import re
import sys
keywords = ['if','btn','p','pln','instr']
def clear (filename):
slist = open(filename).readlines()
i = 0
for s in slist:
n = s.lower().count(" then ")
s = s + " & <<endif>>" * n
s = re.sub(" then "," & ",s,flags=re.I)
s = re.sub(" else ","& <<else>> &",s,flags=re.I)
s... |
12,240 | 9f15ce3d019c95272d87b4a218abc7c6600169c7 | entry = int(input("enter a number: "))
if entry % 2 == 0:
print("this is even")
else:
print("this is odd")
if entry % 4 == 0:
print("this is a multiple of 4")
num = int(input("enter a number to check: "))
check = int(input("enter a number to divide by: "))
if num % check == 0:
print("this divides evenly")
els... |
12,241 | 99dc07fb24195078fb5c79b833b0fc6bbbc84523 | def not_null_field(arr):
for i in range(36):
if arr[i] == 'X':
return False
else:
return True
|
12,242 | 8060200fa2ee8aeab14ef8bbc0a263990462f9ef | from __future__ import unicode_literals
from django.db import models
import re
EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$')
class UserManager(models.Manager):
def email_validate(self, email):
return EMAIL_REGEX.match(email)
def pw_validate(self, password, confirm):
... |
12,243 | 6289b407cd36c8845f48284ed20908a3a58d150b | import requests
import os
from brews.models.models import Brewery
import pdb
BASE_URL = 'http://api.brewerydb.com/v2/locations'
SEARCH_URL = 'https://maps.googleapis.com/maps/api/place/textsearch/json'
BREWERYDB_KEY = os.environ['BREWERYDB_KEY']
PLACES_KEY = os.environ['PLACES_KEY']
def nearby_search(brewery, radius)... |
12,244 | 3edbd46d90302981e5931adc6c725471f85111e4 | """
Contains basic utility functions.
"""
import keras.backend as K
from keras.layers import Input, Dense
from keras.models import Model, Sequential
import numpy as np
def softmax(x):
"""Compute softmax values for each sets of scores in x."""
sf = np.exp(x)
sf = sf / np.sum(sf, axis=0)
return sf
... |
12,245 | dabf47f94c409db18c89068a452d64a9aedc1849 | # Generated by Django 3.2.3 on 2021-06-24 13:49
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('users', '0004_booksincart'),
]
operations = [
migrations.RemoveField(
model_name='cart',
name='customer',
),
... |
12,246 | 1fe03a9016cae02563d587ee5a0c7555e14e65a4 | ROLES = {
'commissioner': 'commissioner',
'player': 'player',
}
|
12,247 | ac17a2c4270f48c1c22e21cdd3996511143ff7ef | from flask import Flask, request, render_template, jsonify
from flask_cors import CORS
from slackclient import SlackClient
from backend.slack.request_handler import GraphRequestHandler
import configparser
app = Flask(__name__,
static_folder = "./dist/static",
template_folder = "./dist")
CORS(ap... |
12,248 | 6d326ffa13a0e764d69ec74f1bdd71ef964084ac | #!/root/bin/python3
from twisted.internet import protocol, reactor
host = 'localhost'
port = 9999
class TCP(protocol.Protocol):#TwistedClientProtocol,not tcp
def sendData(self):
data = input(">>>")
if data:
print("正在发送消息:" + data)
self.transport.write(data.encode('utf-8'))... |
12,249 | 1cf7456fb6c41b8c6d75ad62aae5d2ce7b595ab5 | #!/usr/bin/env python3.8
"""pegen -- PEG Generator.
Search the web for PEG Parsers for reference.
"""
import argparse
import sys
import time
import token
import traceback
from typing import Tuple
from pegen.build import Grammar, Parser, Tokenizer, ParserGenerator
from pegen.validator import validate_grammar
def g... |
12,250 | 3af892da0e8254cc6ff0d1ef8811aaee2d44b15b | # Exercise_1
# Import LabelEncoder
from sklearn.preprocessing import LabelEncoder
# Fill missing values with 0
df.LotFrontage = df.LotFrontage.fillna(0)
# Create a boolean mask for categorical columns
categorical_mask = (df.dtypes == object)
# Get list of categorical column names
categorical_columns = df.columns[ca... |
12,251 | 1a4224b881345da1cca289542aa8681c4e7791fa | from rplidar import RPLidar
#Lidar launching
PORT_NAME ='/dev/ttyUSB0'
lidar = RPLidar(PORT_NAME)
def run():
'''This function returns a table of distances for each angle of a complete rotation.'''
try:
for i,scan in enumerate(lidar.iter_scans()):
if i==0:
lidar... |
12,252 | 64b11ed0a9961f63b122681bf1ddb74169bb0b49 | %tensorflow_version 1.x
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import helper as hlp
dataD = 2
# Loading data
if dataD == 100:
data = np.load('data100D.npy')
else:
data = np.load('data2D.npy')
[num_pts, dim] = np.shape(data)
is_valid = False
# For Validation set
if is_val... |
12,253 | 076dcfccd42cdea2e5efbf321517bf762e59c1c2 | import boto3, os, time
print("The environment is ", os.environ['ENVIRONMENT'])
if os.environ['ENVIRONMENT'] == 'prod':
import prod as build
elif os.environ['ENVIRONMENT'] == 'nonprod':
import nonprod as build
elif os.environ['ENVIRONMENT'] == 'nonprodfailover':
import nonprodfailover as build
elif os.environ['ENVI... |
12,254 | 2a7d3b5994c3e917beb91857fabccffa463c509e | from django.shortcuts import render,HttpResponse,redirect
from blogger.models import blogpost,Comment
def home(request):
posts=blogpost.objects.all()
# for posts in posts:
# print(posts)
# # print(type(posts))
return render(request,"home.html",{"posts":posts})
def post_page(request, post_id):
mypost=blogpos... |
12,255 | 6fadb5675756ee95b0c248c1cf5b9725d1a6ec84 | import math
number_of_students = int(input())
number_of_lectures = int(input())
additional_bonus = int(input())
max_student_score = 0
best_student_attendances = 0
for _ in range(number_of_students):
student_attendances = int(input())
student_score = (student_attendances / number_of_lectures) * (5 + additiona... |
12,256 | 96d64b3177673b03943926a66aab047514aba4ab | from __future__ import print_function, absolute_import, division #makes KratosMultiphysics backward compatible with python 2.6 and 2.7
# importing the Kratos Library
import KratosMultiphysics as KM
import KratosMultiphysics.ShallowWaterApplication as SW
## Import base class file
from KratosMultiphysics.ShallowWaterApp... |
12,257 | 55ce1e5c09cbc047007f71a84cd22cf5a9057b15 | /home/ghaff/anaconda3/lib/python3.7/tempfile.py |
12,258 | 0fabd3ff0a9f4e3c5d37593081b9f46a288ea55f | # -*- encoding: utf-8 -*-
"""The routes.
There is a REST API and a GraphQL API.
REST:
``/api/verify`` [GET]
query parameters:
- ``cf``: the Codice Fiscale string
returns:
- ``{"isCorrect": boolean, "isOmocode": boolean, "cf": str}``
``/api/interpolate`` [GET]
query parameters:
- ``name``
- ``surname``
- ``... |
12,259 | 47b1cbc77add21d8756acfa2f647350a9b60319a | from .neural_network import NeuralNetwork
from .qnetwork import QNetwork
|
12,260 | 9b6297e26ff6e447fa56019d641002633de298f7 | import smtplib
conn = smtplib.SMTP('smtp.gmail.com',587)
conn.ehlo()
conn.starttls()
conn.login('Enter sender email here','Enter password here')
conn.sendmail('Sender email','Receiver email','Subject: I sent you this mail via cmd yaay!\n\nHello,\n This is an automated mail.oink oink xD\n\n')
conn.quit() |
12,261 | 1a7671942f54a8284928ed4b15722439a65c101a | import sys
def listcapacity(lst):
print("Capacity: ", (sys.getsizeof(lst)-36)//4) # initial capacity of the list
print("Size: ", len(lst)) # no. of the elements in the list
print("Space left in the list: ", ((sys.getsizeof(lst)-36) - len(lst*4))//4)
# some thing is totally depended upon the machines th... |
12,262 | 1c40a255fced0ffbc3eccca9537414a74df26937 | """
This file will contain the stuff necessary for creating the roster and uploading the submissions.
"""
from fullGSapi.api.login_tokens import LoginTokens
import getpass
import os
import csv
from tqdm import tqdm
gs_roster_loc = "files/input/gs_roster.csv"
canvas_roster_loc = "files/input/canvas_roster.csv" # Curren... |
12,263 | ab1d663b05a19cf16c0a9f2a97a85ffb4831ede9 | import cv2
import numpy as np
from playsound import playsound
import time
import datetime as dt
import os
import random
# the minimum distance between face and finger
# that will trigger an event
finger_distance = 90
# load classifier
face_cascade = cv2.CascadeClassifier(
'./haarcascades/haarcascade_frontalface.x... |
12,264 | 755fc8973fdfffdaa78562d4b6b54df1f5a87da6 | import getpass
import snmp_helper
DESCR = '1.3.6.1.2.1.1.1.0'
NAME = '1.3.6.1.2.1.1.5.0'
def main():
ip_addr1 = raw_input("enter pyrtr1 address: ")
ip_addr2 = raw_input("enter pyrtr2 address: ")
community = raw_input("enter community string: ")
py_rtr1 = (ip_addr1, community, 161)
py_rtr2 = (ip... |
12,265 | 570299f2231cf19c10637b76432594a3ff41ccde | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
12,266 | 8a353cd478d3277589e87166171e31e16b062c6a | import collections as cl
import math
N = int(input())
def f(n):
if n == 1:
return [1]
n_1 = f(n - 1)
return n_1 + [n] + n_1
print(*f(N))
|
12,267 | f95ae83ccd0c488b1840f0f319b8b2447f8cb624 | listintup = [(7,5), (6,4), (3,8), (9,10), (5,6)] #defining the input
def val2(y): #function to retrive the second value
return y[1]
sorted_listed=sorted(listintup, key=val2)
print("The sorted list of tuple in the increasing order of seCond element is \n", sorted_listed)
|
12,268 | 705d5be38076eefabf8a0384e45d39735198cd96 | #!/usr/bin/env python
# This software is licensed under the Apache 2 license, quoted below.
#
# Copyright 2019 Astraea, Inc.
#
# 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.a... |
12,269 | 103fbeee1878b7621f39bc0c2b98096c5764bc34 | # -*- coding: utf-8 -*-
"""
Created on Sat Mar 16 11:52:55 2019
@author: user
"""
import requests
import os
from bs4 import BeautifulSoup
import re
import time
from selenium import webdriver
def get_PDFurl():
pdf_links = []
links = soup.find_all(href=re.compile(".pdf"))
for each in links... |
12,270 | 15c5492122c377187c4b3d9b7f7d4f7d4d5b4f68 | from datetime import datetime
import pandas as pd
import numpy as np
np.random.seed(777)
dates = [datetime(2019,1,2),datetime(2019,1,7),datetime(2019,1,7),
datetime(2019,1,8),datetime(2019,1,10),datetime(2019,1,12)]
ts=pd.Series(np.random.randn(6),index=dates)
print(ts)
print('\n',ts['1/10/2019'])
print('\... |
12,271 | d044240cb81efa30372f868e836f82d033ec000b | from os import listdir
ANALYSIS_FOLDER = 'analyses/'
FRIENDS_FOLDER = 'references/'
models_per_user = {}
for filename in listdir(ANALYSIS_FOLDER):
user, models = filename.split('.')
if '_' in models:
continue
if user not in models_per_user.keys():
models_per_user[user] = set()
models_per_user[user].add(m... |
12,272 | e5490a273b8d45d663cfec1337c09421d3723270 | from abc import abstractmethod
from typing import Any, Dict, final
from dramatiq import GenericActor
from pydantic.generics import GenericModel
from deployments.entities.deployment_info import DeploymentInfo
from models.model_info import ModelInfo
DEPLOYMENT_TIME_LIMIT_MSECS = 1000 * 60 * 60 * 1
class DeploymentDes... |
12,273 | 1c4ce8e9ed54b9ff4e8d04c45e205b48d05a79b4 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
# Modifications Copyright 2017 Abigail See
#
# 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... |
12,274 | 50d40092b7e167ab93635617c5f300db126db68b |
import multiprocessing as mp
from itertools import permutations
from cipher_list import cipher_list_4lw as cipher_list
def get_sorted_word_frequency(cipher):
hist = {}
for word in cipher.split(' '):
if word in hist.keys():
hist[word] += 1
else:
hist[word] = 1
his... |
12,275 | 6500383c075637fc98508555891dc7635c6190fc | '''
File Decompression
Author: Syed Ahammad Newaz Saif (snewaz@unimelb.edu.au).
Student Number:684933
Summary-Sarah O'Connor,my predecessor made the compression
software but for mulititue reasons it seems that the
decompressed files are not available and the iSkynet's database
needs to check on the files.This ... |
12,276 | 3cdef6db35560ece2dbf2cbb727c122392eb26ba | import time
from multiprocessing import Process
def func(name):
print('hello', name)
print('我是子进程')
if __name__ == '__main__':
# 实例化一个子进程,执行func函数,传输参数
p = Process(target=func, args=('tiele',))
# 运行子进程对象
p.start()
time.sleep(1)
print('执行主进程的内容了') |
12,277 | af52f52d8a1ec3784ce3d40f936a056275642276 | #!/usr/bin/env python
#- Derive RA,dec of fibers from NGC 205 field given that they were configured
#- for a different field
import fitsio
import numpy as np
import desimodel.focalplane
import argparse
parser = argparse.ArgumentParser(usage = "{prog} [options]")
parser.add_argument("-i", "--input", type=str, help=... |
12,278 | 67c1384a33e28b93af46b5fa6e6bb4b61dce597d | import pytz, datetime, time
def getTimeFromEpoch(timeStp, zoneCode):
local = pytz.timezone (zoneCode)
naive = datetime.datetime.strptime (timeStp, "%Y-%m-%d %H:%M:%S")
local_dt = local.localize(naive, is_dst=None)
utc_dt = local_dt.astimezone (pytz.utc)
return (utc_dt.timestamp()) |
12,279 | 987ff22be4a99c27ecf645c260e0451c6f7335d7 | from typing import List
import cloudpickle as pickle
import numpy as np
import pandas
import sklearn.metrics as metrics
class ModelWrapper:
def __init__(self, model_path: str):
with open(model_path, "rb") as rf:
self.model = pickle.load(rf)
def predict(self, X: dict) -> List[int]:
... |
12,280 | c667e07ed6773a1d84cfec08bb729d699649c7fe | import pygame
class Starship(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface([60,60])
self.rect = self.image.get_rect()
self.rect.x = 100
self.rect.y = 250
def moveToRight(self, dx=5):
self.rect.x += d... |
12,281 | a8461b4b0e5ef0fd19a8f2d44244cc3366642f50 | # analisando triângulos 2.0
a = float(input('Primeiro segmento: '))
b = float(input('Segundo segmento: '))
c = float(input('Terceiro segmento: '))
if (a+b)>c and (a+c)>b and (b+c)>a:
print('Podem formar um triângulo!')
if a == b == c:
print('Este triângulo será EQUILÁTERO!')
elif a == b and ... |
12,282 | ed9de2216a9f3403e1cfd86f8882e583afe78368 | #coding=utf-8
'''
Created on 24.03.2013
@author: michi
'''
from PyQt4.QtCore import QObject, QAbstractItemModel, QRegExp, QStringList, \
pyqtSignal, QModelIndex, Qt
from PyQt4.QtGui import QCompleter, QSortFilterProxyModel
from ems.qt4.util import variant_to_pyobject
class FuzzyCompleter(QCompleter):
Starts... |
12,283 | a1a5452a9bcdfb5203407306237ec5b5021bfe15 | from ThoughtWorks.MarsRoverProblem.InputParser import InputParser
from ThoughtWorks.MarsRoverProblem.Plateau import Plateau
if __name__ == "__main__":
x_max, y_max = InputParser.parse_plateau_size()
Plateau.set_plataue_size(x_max, y_max)
list_of_rovers = InputParser.parse_list_of_rovers()
for rover in ... |
12,284 | 1df510dff127207a296e9ac0586e257f3caf73cc | from utils import Point
MESSAGE_WAIT = 'wait'
MESSAGE_COME = 'come'
class Message(object):
type = None
def __init__(self, source):
self.source = source
class ComeMessage(Message):
type = MESSAGE_COME
def __init__(self, source, x, y):
super(ComeMessage, self).__init__(source)
... |
12,285 | c223daddf56815562415be06b49ff29d084ee66d | S = [80144,
112441,
28168,
55393,
20358,
42988,
16798,
24279,
18413,
56263,
19905,
60167,
8231,
36350,
16420,
5321,
11666,
13230,
18770,
6443,
7395,
147444,
2813,
2332,
28728,
882171,
7333,
57462,
36914,
71917,
59885,
2936,
39424,
35631,
14324,
34,
12,
31964,
3428,
12175,
244,
57,
957,
75,
59,
31,
2106,
49,
37,
21,
378... |
12,286 | fccf1303ac444d7b31e3dbf4c9caad861527c5dd | def isEmpty(stack):
return len(stack) == 0
def Pop(stack):
if isEmpty(stack):
print("Stack underflow")
exit(1)
else:
popped = stack.pop()
return popped
def createStack():
stack = []
return stack
def push(stack, item):
stack.append(item)
def sort_stack(stack):
if not isEmpty(stack)... |
12,287 | 1823469f105958d179c2448afa1b0fc5ab4dfd64 | import ray
import pandas as pd
import numpy as np
import itertools
""" Simulate """
@ray.remote
def msy_max_t_1fish(env, mortality, repetitions):
x = []
path = []
for rep in range(repetitions):
episode_reward = 0
observation, _ = env.reset()
T = 0
for t in range(env.Tmax):
population = env... |
12,288 | 377fb5387d7d0127c7d81f0c9de1c5c02bd9d267 | # -*- coding: utf-8 -*-
"""Copy of ResNet
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1SVTcgc1E5KpIs-UPv9ogh9kYscBUhkLN
"""
#originally coded on google colab
#code borrowed from https://github.com/minhthangdang/SignLanguageRecognitionResNet
from g... |
12,289 | 563fb954a662fbf7a4b86a94669cdb26236ed604 | """DjangoFPGA URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-ba... |
12,290 | cced7930aebec77ce082ae575fe9cf9e83888ca4 | # For loop indexli
z=range(5)
for i, data in enumerate(z):
print(i, data)
#Dosya satırı okuma
for line in open("example.txt"):
print(line)
#Swapping
a=5
b=6
a,b = b,a
print(a,b)
#List e başka bir list in değerlerini ekleme
x=[]
y=[1,2,3,4]
x.append(5)
x.extend(y)
print(x)
#List seriyi tersten okuma
x.revers... |
12,291 | 57294203b57b641b3b2f613b6e164f6acb88a13b | #!/usr/bin/python -u
import gobject
import dbus
import dbus.service
import dbus.mainloop.glib
import os
import os.path as path
import sys
from obmc.dbuslib.bindings import DbusProperties, get_dbus
settings_file_path = os.path.join(sys.prefix, 'share/obmc-phosphor-settings')
sys.path.insert(1, settings_file_path)
impo... |
12,292 | 9e51903c34b7d47d410b24d130404302be7c6a3d | from flask import Flask, render_template
from flask import Response
from flask import request
from datetime import datetime
import MySQLdb
import sys
import time
import hashlib
import os
import json
import random
import subprocess
app = Flask(__name__)
startTime = datetime.now()
db = MySQLdb.connect("mysql","root","pa... |
12,293 | 3490ac769d3231ba6a7703185f34a74fa34bdd27 | """
10. Regular Expression Matching (Hard)
Implement regular expression matching with support for '.' and '*'.
'.' Matches any single character.
'*' Matches zero or more of the preceding element.
The matching should cover the entire input string (not partial).
The function prototype should be:
bool isMatch(const ch... |
12,294 | 847bbca245a58385764f890e740313174383eae0 | from django.db import models
from django.contrib.auth.models import User
from django.urls import reverse
import string
import random
# Create your models here.
class Club(models.Model):
club_name = models.CharField(max_length=100)
members = models.ManyToManyField(User)
invite = models.CharField(max_length=... |
12,295 | 2822275a20dd1accdab818201b60399087dd0248 | class Driver():
def method_D1(self,a,b):
c=(a+b)
print ("value of c is:-", c)
|
12,296 | e9460b41846810da68660282b0f609da6066a38a | '''
Delete contents of s3 bucket (so that delete-stack call will work)
'''
import boto3, sys
if len(sys.argv) == 1:
print ("must pass the bucketname you want to delete contents from")
sys.exit()
else:
bucketname = sys.argv[1]
client = boto3.client('s3')
s3 = boto3.resource('s3')
paginator = client.get_pag... |
12,297 | a0cf1b88de650b4be49ad819e4c46155044a47f4 | from flask import Flask, render_template
from modules import convert_to_dict, make_ordinal
from flask_bootstrap import Bootstrap
app = Flask(__name__)
application = app
senator_list = convert_to_dict("florida-senators.csv")
Bootstrap(app)
@app.route('/')
def index():
ids_list = []
name_list = []
... |
12,298 | 74222a5f7c2b727a84e17da73a476a75aad80a44 | import sys
import json
from scrapy import signals
from scrapy.crawler import CrawlerProcess
from scrapy.utils.project import get_project_settings
from searchengine.spiders.bing import BingSpider
from searchengine.spiders.sogou_wx import SogouWxSpider
from searchengine.spiders.weibo import WeiboSpider
from searchengine... |
12,299 | 8e0a18522553d1dc7acfeb8e0f117cdbe898d296 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import pandas as pd
from data_process import data_preprocess
from random_sample import rand_sample
from cal_auc import auc
#读取数据集
data = pd.read_csv("testset.csv",sep=",")
"""特征处理"""
data = data_preprocess.del_id_get_hot(data)
"""特征选择"""
"""选择正负样本"""
org_pos_sample = dat... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.