text stringlengths 8 6.05M |
|---|
import json
import requests
def get_book_by_isbn(isbn):
response = requests.get('https://www.googleapis.com/books/v1/volumes?q=isbn:'+isbn)
json_data = json.loads(response.text)
book_info = json_data["items"][0]["volumeInfo"]
title = book_info["title"]
authors = book_info["authors"]
publishe... |
import dash
import copy
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import dash_table
import pandas as pd
from datetime import datetime as dt, date
import dash_table.FormatTemplate as FormatTemplate
from dash_table.Format import Format, Scheme, Sign... |
from django.shortcuts import render, redirect
from django.template import loader
from django.contrib.auth import authenticate, login as log_in
from django.contrib.auth.decorators import login_required
from .forms import DocumentForm, ItemForm
from .models import Document, Item, Settings
from django.http import HttpResp... |
# 优先队列
# 左边进就加,右边出就删
# 高度变了就加到结果数组
# 做过了,优先队列问题
from sortedcontainers import SortedList
class Solution:
def getSkyline(self, buildings: List[List[int]]) -> List[List[int]]:
ans = []
changes = []
for left, right, height in buildings:
changes.append((left, -height))
... |
import os
from twitchio.ext import commands
# set up the bot
bot = commands.Bot(
irc_token=os.environ['TMI_TOKEN'],
client_id=os.environ['CLIENT_ID'],
nick=os.environ['BOT_NICK'],
prefix=os.environ['BOT_PREFIX'],
initial_channels=[os.environ['CHANNEL']]
)
@bot.event
async def event_ready():
'C... |
import os
import urllib
import shutil
import os
import urllib
import urllib.request
from urllib.error import *
def baseName(url):
return os.path.basename(urllib.parse.urlparse(url).path)
def download(url, filename):
try:
if filename == "":
print("Error: Empty destination file name")
... |
import daemon
from walscraper import main
print daemon.__file__
# with daemon.DaemonContext():
# main() |
# Generated by Django 2.1 on 2018-09-14 09:44
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('mainapp', '0002_organization'),
]
operations = [
migrations.AddField(
model_name='organization',
name='contact_text',
... |
from collections import deque
from math import inf
def distanza(insieme_1, insieme_2, grafo):
def bfs(nodo, grafo):
distanze = [-1 for _ in grafo]
distanze[nodo] = 0
coda = deque()
coda.append(nodo)
while coda:
nodo = coda.popleft()
for adiacente i... |
from .codelength import codelength
from . import grassberger
from .read_file import read_links, read_tree
__all__ = ["codelength", "grassberger", "read_links", "read_tree"]
|
from django.conf.urls import url
from .views import IssuesByDayForRepo
urlpatterns = [
url(r'^issues-by-day/(?P<repository_id>\d+)/', IssuesByDayForRepo.as_view(), name='issues_by_day_for_repo'),
]
|
from django.contrib import admin
from . import models
# Register your models here.
# class GTINBaseModelAdmin(admin.ModelAdmin):
# model = models.GTINBaseData
# list_display = [f.name for f in models.GTINBaseData._meta.fields]
#
class GTINInformationAdmin(admin.ModelAdmin):
model = models.GTINInformation... |
from django.urls import path
from owner import views
urlpatterns=[
path("numbertostring", views.Num_to_str, name="Numtostrconverter"),
] |
# -*- coding: utf-8 -*-
import sys
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse,HttpResponseRedirect
from django.template import RequestContext
from datetime import datetime
from django.shortcuts import render_to_response
from emart_models.models import Customers,Commoditie... |
from bs4 import BeautifulSoup
from urllib.request import urlopen
dict={'Jan':'01','Feb':'02','Mar':'03','Apr':'04','May':'05','Jun':'06','Jul':'07','Aug':'08','Sep':'09','Oct':'10','Nov':'11','Dec':'12'}
import csv
sz=0
# https://www.ndtv.com/page/topic-load-more?+type=news&page=60&query=kolkata
assmebl=['delhi','chenn... |
# Copyright 2014 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.
"""Helper functions useful when writing scripts that are run from GN's
exec_script function."""
import sys
class GNException(Exception):
pass
# Comp... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Ed Mountjoy
#
import sys
import os
import argparse
import gzip
from pprint import pprint
def main():
# Parse args
args = parse_args()
window = 5 * 1e6 # plus/minus 5Mb
only_save_overlapping = True
#
# Prepare data ----------------------------... |
from enum import Enum
class MedalType(Enum):
DUNGEON = "dungeon"
DUNGEON_X2 = "dungeon_x2"
CC = "cc"
GUILD_SHOP = "guild_shop"
REQUEST = "request"
MM = "mm"
DEFAULT = "default"
|
#!/usr/bin/python3
from rank_api import api
if __name__ == "__main__":
api.run() |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world. You're at the polls index.")
from django.urls import reverse_lazy
from django.views import gen... |
import sys
import frida
jscode = """
Java.perform(function(){
var MainActivity = Java.use('top.q0o0p.q0o0p_six.MainActivity'); //获得MainActivity类
MainActivity.onClick.implementation = function(){ //Hook testFrida函数,用js自己实现
send('Statr! Hook!'); //发送信息,用于回调python中的函数
retur... |
# -*- coding: utf-8; mode: python -*-
#
# This is the project specific sphinx-build configuration, which is loaded from
# the base configuration file (``../conf.py``). About config values consult:
#
# * http://www.sphinx-doc.org/en/stable/config.html
#
# While setting values here, please take care to not overwrite comm... |
__author__ = 'zhengxiaoyu'
import numpy as np
import sys
#first step : convert the input value to binary
def toBinary(num, bit):
'''
:param num: the inuput num
:param bit: n-bit
:return:the binary list in n-bit
>>> toBinary(6,3)
[1, 1, 0]
>>> toBinary(8,2)
bit too samll
>>> toBinary(... |
import socket
HOST = 'chitturi' # The remote host
PORT = 50007 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('chitturi', 50007))
s.sendall('Hi good morning')
data = s.recv(200)
s.close()
print 'Received', str(data)
|
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 29 19:21:34 2020
@author: HP
"""
number1=int(input("enter the first number:"))
number2=int(input("enter the second number:"))
sum=number1+number2
print("the sum is",sum) |
t1=bytearray([12,20])
t2=bytearray([12,20])
print(id(t1))
print(id(t2))
print(t1 is t2)
|
def solve(s):
subs = []
current = 0
for cnt, x in enumerate(s):
if x not in 'aeiou':
current += ord(x)-96
if cnt == len(s)-1:
subs.append(current)
continue
subs.append(current)
current = 0
return max(subs)
'''
A consonant is ... |
from metaL import Object
class Web(Object):
pass
|
from math import ceil, floor
from cs50 import get_string
num = get_string("Number: ")
if int(num) < pow(10, 12) or int(num) > pow(10, 16) - 1:
print("INVALID")
exit(1)
n = len(num)
evendigits = floor(n/2)
odddigits = ceil(n/2)
x = 0
y = 0
for i in range(1, evendigits + 1):
x += (floor(2 * int(num[n - (2 *... |
X=float(input("X= "))
Y=float(input("Y= "))
A=float(input("A= "))
B=float(input("B= "))
onekgchoko=A/X
onekgsuga=B/Y
determine=onekgchoko/onekgsuga
print(onekgchoko)
print(onekgsuga)
print(determine) |
import pytest
import time
from requests.exceptions import HTTPError
import pandas as pd
from pydodo import (
reset_simulation,
all_positions,
list_route,
)
from pydodo.bluebird_connect import ping_bluebird
# test if can connect to BlueBird
bb_resp = ping_bluebird()
@pytest.mark.skipif(not bb_resp, reaso... |
import ray
import logging
from torch.utils.data import Dataset, IterableDataset
from torch.utils.data._utils.collate import default_collate
from typing import Callable
logger = logging.getLogger(__name__)
class IterableDataLoader:
def __init__(
self,
dataset: Dataset = None,
dataset_init_... |
#!/usr/bin/env python
# https://www.postgresqltutorial.com/postgresql-python/
# -----------------------------------------------------------------------
# database.py
# Author: Sophie Li, Jayson Wu, Connie Xu
# -----------------------------------------------------------------------
import os
import psycopg2
from sys i... |
import xmlrpclib
from pprint import pprint as pp
# bad len 4, 16
# good len 2,3,14,17
file = "inventorytest.csv"
import requests
import json
location = []
inventory = []
lines = [line.strip() for line in open('inventory-a.txt')]
for line in lines:
if len(line) in [2, 3]:
inventory.append(line)
elif ... |
#!/usr/bin/env python
import pymongo
conn = pymongo.Connection('localhost')
db = conn.TripShare
|
from django import forms
from .models import Review
class ReviewForm(forms.Mod) |
'''
File name: AES_modeECB.py
Author: Emely da Mata
Title: TP03
Python Version: 3.8.5
'''
from PIL import BmpImagePlugin
import hashlib
from itertools import cycle
import os
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_ba... |
# Given an integer number n, return the difference between the product
# of its digits and the sum of its digits.
class Solution:
def subtractProductAndSum(self, n):
pr = 1
su = 0
for elem in str(n):
pr *= int(elem)
su += int(elem)
return pr - su
if ... |
import os
import logging
import numpy as np
import xml.etree.ElementTree as ET
from PIL import Image
from configs.paths import DATASETS_DIR
from utils.utils_general import make_list, read_textfile
from utils.utils_bbox import draw_bbox
log = logging.getLogger()
VOC_CATS = ['__background__', 'aeroplane', 'bicycle', ... |
# -*- coding: utf-8 -*-
dict = {'A':4,'R':6,'N':2,'D':2,'C':2,'Q':2,'E':2,'G':4,'H':2,'I':3,'L':6,'K':2,'M':1,'F':2,'P':4,'S':6,'T':4,'W':1,'Y':2,'V':4,'*':3}
if __name__ == "__main__":
fid = open('rosalind_mrna.txt','r')
#fout = open('out.txt','w')
s = fid.readline().strip()
#Protein
prod = 1
... |
from channels.routing import route
from sleep.consumers import ws_message, ws_connect, ws_disconnect
channel_routing = [
route("websocket.connect", ws_connect, path=r'^/graph/(?P<id>[^/]+)/values/$'),
route("websocket.receive", ws_message, path=r'^/graph/(?P<id>[^/]+)/values/$'),
route("websocket.disconnec... |
from decouple import config
class Config:
SECRET_KEY = 'adsi'
class DevelopmentConfig(Config):
motor = 'mysql://'
user_db = 'sena:'
password_db = 'sena123@'
server = 'localhost/'
name_db = 'project_web'
DEBUG = True
SQLALCHEMY_DATABASE_URI = motor + user_db + password_db + server... |
# Generated by Django 3.0.8 on 2021-01-15 10:44
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='DestinationCompany',
fields=[
('id', models... |
import os
import csv
import datetime
def print_csv(curs, tbnm, printsql, count):
start_time = datetime.datetime.now()
# output each table content to a separate CSV file
# filepath =
print("当前路径:{}".format(os.getcwd()))
filepath = input("请输入路径:输入为空则使用上述当前路径")
if filepath == '':
filepath... |
import myutil
import random
def choose(next_move_types, next_moves, last_move_type, model, cards_left1, cards_left2, player_id, net, playerecord):
from mcts import MCTSModel
if player_id == 0:
my_cards = cards_left1
enemy_cards = cards_left2
else:
my_cards = cards_left2
... |
from bs4 import BeautifulSoup
from urllib.request import urlopen
import bs4
url1 = "https://www.mk.co.kr/news/bestclick/"
url2 = "https://www.hankyung.com/ranking"
html1 = urlopen(url1)
html2 = urlopen(url2)
bs_obj1 = bs4.BeautifulSoup(html1.read(),"html.parser")#html형식으로 쉽게 보여줌
bs_obj2 = bs4.BeautifulSoup(html2.read... |
import time
from function_scheduling_distributed_framework import task_deco,BrokerEnum
@task_deco('queue_test_step1',qps=0.5,broker_kind=BrokerEnum.LOCAL_PYTHON_QUEUE)
def step1(x):
print(f'x 的值是 {x}')
if x == 0:
for i in range(1, 300):
step1.pub(dict(x=x + i))
for j in range(10):
... |
def changeMessage(packet):
if(packet["TCP"]["dstport"] == 8554 and packet["TCP"]["payload"]):
try:
payload = packet["TCP"]["payload"].decode()
splitted = payload.split("\r\n")
for i in range (len(splitted)):
if "PLAY" in splitted[i]:
... |
# Generated by Django 3.1.1 on 2020-09-04 12:37
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('student', '0003_student_password'),
]
operations = [
migrations.AddField(
model_name='student',
name='gender',
... |
from django.urls import path
from .views import home, product_detail, contact
app_name = 'stock'
urlpatterns = [
path('', home, name='home'),
path('produc/<int:product_id>', product_detail, name='prodict_detail'),
path('contact/', contact, name='contact'),
]
|
import shelve
s = shelve.open('test_shelf')
try:
existing = s['key1']
finally:
s.close()
print(existing)
# {'int': 10, 'float': 3.4, 'string': 'sample data'}
|
# Generated by Django 2.1 on 2018-09-24 06:34
from django.db import migrations, models
import django.db.models.deletion
import tinymce.models
class Migration(migrations.Migration):
dependencies = [
('mainapp', '0014_auto_20180924_0632'),
]
operations = [
migrations.AlterField(
... |
# -*- coding: utf-8 -*-
d={}
while True:
print("Key:",end="")
key=input()
if key == "end":
break
else:
print("Value:",end="")
value=input()
d[key]=value
print("Search key:",end="")
skey=input()
dk=d.keys()
if skey in dk:
print("True")
else:
print("False")
|
from handlers import CeleryHandler
class BaseRequester(object):
handler_cls = NotImplemented
def __init__(self, host):
self.handler = self.handler_cls(host)
def request(self, key):
if self.is_invalid(key):
return 'key is invalid'
return self.handler.get(key)
def ... |
"""1Forge REST API Class Wrapper"""
import os
import requests
class OneForge(object):
"""1Forge REST API Class Wrapper"""
ONEFORGE_URL = 'https://forex.1forge.com/1.0.3'
def __init__(self, api_key=None):
"""Wrapper for 1Forge REST API
Keyword Arguments:
api_key {str} -- 1Fo... |
import platform
import re
from asciinema import __version__
from asciinema.urllib_http_adapter import URLLibHttpAdapter
from asciinema.http_adapter import HTTPConnectionError
class APIError(Exception):
pass
class Api:
def __init__(self, url, user, token, http_adapter=None):
self.url = url
... |
from rply import ParserGenerator
from ast import NegationEliminationDef, HypotesisDef, PremisseDef
from formule import BinaryFormule, NegationFormule, AthomFormule
from symbol_table import SymbolTable
class Parser():
def __init__(self, state):
self.state = state
self.pg = ParserGenerator(
... |
def main():
bef = open("Before.txt", "r")
aft = open("After.txt", "w")
for i in bef:
Uname = i.upper()
print(Uname, file=aft)
bef.close()
aft.close()
main()
|
import sys
from Btree import BTree
from dropdown import dropdown
class File(object):
def __init__(self, ruta1=None, ruta2=None):
self.ruta1 = ruta1
self.ruta2 = ruta2
self.buffer = []
def remove_chars(self, lista, cadena):
for char in lista:
cadena = cadena.replace... |
#
# Developed by sujayVittal; Sat Mar 11 01:05:34 IST 2017
#
###############
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import sys
from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
FLAGS = None
def ... |
from django.shortcuts import render, redirect
def home(request):
return redirect('/admin/')
|
from sage.all import *
def diophantine_solver(a, b, c = None):
if b > a or not a or not b: return []
a = Integer(a)
b = Integer(b)
# it should be sufficient to not swap `a' with `b' if `b > a'
if c is None: c = a*b
quo, rem = a.quo_rem(b)
extended_gcd_matrix = matrix(ZZ,[
... |
import dash_bootstrap_components as dbc
from dash import html
pagination = html.Div(
[
html.Div("Collapse long pagination objects using ellipsis"),
dbc.Pagination(max_value=10, fully_expanded=False),
html.Div("If space won't be saved, it won't be collapsed"),
dbc.Pagination(max_valu... |
#!/usr/bin/env python
#
# Copyright 2007 Google 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.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
from django.urls import reverse
from rest_framework.test import APITestCase
from rest_framework import status
from tickets import models, factories
class TestEndpoints(APITestCase):
def test_movie_flow(self):
for i in range(10):
factories.MovieFactory()
response = self.client.get(rev... |
# Test of fcsreader.py
# (cc) 2017 Ali Rassolie
# Formagna
import fcsreader
import matplotlib.pyplot as plt
process = fcsreader.fcsReader("data.fcs")
s = process.data()
print(s.columns)
s.plot(x = "SSC-A", y="FSC-A", kind="scatter")
plt.show() |
#coding:gb2312
#打印每个朋友的姓名,并为其打印一条问候信息。
names=['cys','ljy','ft','hl','jy']
message=","+"I'm very glad to meet you"+"!"
print(names[0].title()+message)
print(names[1].title()+message)
print(names[2].title()+message)
print(names[3].title()+message)
print(names[4].title()+","+"I'm very glad to meet you"+"!")
|
## This file contains all of the required code to set up a new database on the
## system.
import databasefunctions as dbf
database_name = "StudioTest"
password = "password"
port = 5432
cnxn = dbf.connecting_to_postgresql(database_name, password, port)
dbf.create_customer_table(cnxn)
dbf.create_menu_table(cnxn)
db... |
int_data = 1 # 정수 선언
float_data = 3.14 # 실수 선언
complex_data = 1+5j # 복소수 선언
str_data1 = 'I love Python' # 문자열 선언(영문)
str_data2 = "반갑습니다." # 문자열 선언(한글)
list_data=[1,2,3] # 리스트 선언
tuple_data=(1,2,3) # 튜플 선언
dict_... |
large = 0
for i in range(0,4):
userinput = input("Number please...")
usernum = int(userinput)
if large < usernum:
large = usernum
print("The largest number is: " + str(large )) |
#!/usr/bin/env python
# encoding: utf-8
"""
Created by 'bens3' on 2013-06-21.
Copyright (c) 2013 'bens3'. All rights reserved.
"""
import ckanapi
from ke2mongo.log import log
from ke2mongo import config
import luigi
class APITask(luigi.Task):
"""
Base CKAN API Task
"""
# Date to process
date = lu... |
import os
import cv2
import numpy as np
import shutil
###########################Display image##################################################################
def show(Im,Name="img"):
cv2.imshow(Name,Im.astype(np.uint8))
cv2.waitKey()
cv2.destroyAllWindows()
######################################... |
# 给程序传参数
import sys
print(sys.argv)
# name = sys.argv[1]
# print('Welcome %s !!!'%name) #可以在程序外直接传入name的值
# 列表生成式
a = [i for i in range(1, 8)]
print(a)
b = [6 for i in range(1, 8)]
print(b)
c = [i for i in range(10) if i % 2 == 0]
print(c)
d = [i for i in range(3) for j in range(2)]
print(d)
e = [(i, j) for i... |
# Generated by Django 2.0.2 on 2019-03-08 13:03
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='EnterPrice',
fields=[
('create_time', model... |
'''
Created on 2017年2月6日
@author: admin
'''
#将要被测试的类
class Widget:
def __init__(self, size=(40,40)):
self._size = size
def getSize(self):
return self._size
def resize(self,width,height):
if width < 0 or height<0:
raise ValueError("illegal size")
self._size=(widt... |
def isYearLeap(year):
if year % 100 == 0:
if year % 400 == 0:
return True
else:
return False
elif year % 4 == 0:
return True
else:
return False
def daysInMonth(year, month):
if year < 1500 or month < 1 or month > 12:
return No... |
#========================================
# author: Changlong.Zang
# mail: zclongpop123@163.com
# time: Tue Sep 19 14:44:30 2017
#========================================
import pymel.core as pm
import maya.OpenMaya as OpenMaya
import dag
#--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-... |
# class Solution(object):
# def findKthLargest(self, nums, k):
# """
# :type nums: List[int]
# :type k: int
# :rtype: int
# """
# l = nums[:k]
#
# for i in range(k, len(nums)):
# if nums[i] > min(l):
# l.remove(min(l))
# ... |
def factors(n):
for i in range(1,n+1):
if (n%i==0):
print(i)
n=int(input("Enter the number"))
print("Factors of %d are"%n)
factors(n) |
import os
import sqlite3
db_filename = 'dhcp_snooping.db'
schema_filename = 'dhcp_snooping_schema.sql'
def create_db(db_filename,schema_filename):
db_exists = os.path.exists(db_filename)
conn = sqlite3.connect(db_filename)
if not db_exists:
print('Creating schema...')
with open(schema_filename, 'r') as ... |
# coding: utf-8
# In[3]:
1.#Basic arithmatic operation
a=int(input("Input first number"))
b=int(input("Input second number"))
Addition=a+b
Subtraction=a-b
Multiplication=a*b
Division=a/b
print ("Addition is:",Addition)
print ("Subtraction is:",Subtraction)
print ("Multiplication is:",Multiplication)
print ("Divisi... |
# xmltools.py
import sys
import xml.sax.saxutils as sux
def pprint_xml(node, indent="", f=sys.stdout):
""" Pretty-print an ElementTree XML node. (Does not handle attributes.) """
children = node.getchildren()
if children:
f.write("%s<%s>\n" % (indent, node.tag))
for child in children:
... |
from tipo_questao import *
from lockable import *
from questao import *
from questao_avaliacao import *
from fonte import *
from filtro_questao import *
from multipla_escolha import *
from path_utils import *
|
import pandas as pd
import numpy as np
from sklearn import linear_model
from sklearn import metrics
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, Normalizer, MinMaxScaler
pd.set_option('display.float_format', lambda x: '%.5f' % x)
# pd.set_option('display.max_... |
a = 20
b = 15
c = a
a = b
b = c
print(a)
print(b) |
#http://www.codeskulptor.org/#user43_38xv9eBr3U_4.py
"""
Monte Carlo Tic-Tac-Toe Player
"""
import random
import poc_ttt_gui
import poc_ttt_provided as provided
# Constants for Monte Carlo simulator
# You may change the values of these constants as desired, but
# do not change their names.
NTRIALS = 20... |
#可变参数,用list和tuple传参,可以传入任意个参数
def calcu(*numbers):
sum=0;
for n in numbers:
sum=sum+n*n
return sum
print(calcu(0,1,3))
#关键字参数还多了名字,与可变参数比
def person(name,age,**kw):
print('name',name,'age',age,'others:',kw)
person('zhao',12,city=5)
#命名关键字参数以dic传递,要有key值
L=range(100)
for i ... |
"""
this file will show kitti lidar point cloud data
in sequence continuous
"""
import numpy as np
import open3d
from open3d import *
import os
import glob
from mayavi import mlab
import pcl
import vtk
kitti_seq_dir = '/media/jintain/sg/permanent/datasets/KITTI/videos/2011_09_26/2011_09_26_drive_0009_sync'
image_02_d... |
# Exercício 5.25 - Livro | Não resolvido
|
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from typing import List, Optional
from gym import spaces
from examples.bandit import BanditEnv # type: ignore[import]
from mtenv.utils import seeding
from mtenv.utils.types import TaskObsType, TaskStateType
from mtenv.wrappers.env_to_mtenv import... |
# Write a function that takes an array of postive integer and returns the
# max sum of its non-adjacent numbers of that array.
# Example: I/P: [75, 105, 120, 75, 90, 135]
# Output: 330 (75, 120, 135)
def maxSubsetSumNoAdjacent(array):
pass
|
import constants
import json
import requests
import logging
from urlparse import urljoin
class LightspeedAPIException(Exception):
pass
class LightspeedAPIUnavailable(LightspeedAPIException):
def __init__(self, url, message=None):
self.message = message or "API is unavailable"
self.url = ur... |
inp = map(int,raw_input().split())
n = inp[0]
t = inp[1]
number = 0
temp = 10**(n-1)
fraction = temp/t
if (temp%t == 0):
number = temp + t
else:
number = (fraction+1)*t
number1 = str(number)
if number1[-1] == '0':
number += t
lis = list(str(number))
if len(lis) == n:
print number
else:
print '-1' |
#!/usr/bin/env python
from __future__ import print_function
import fastjet as fj
import fjcontrib
import fjext
import tqdm
import argparse
import os
import numpy as np
from heppy.pythiautils import configuration as pyconf
import pythia8
import pythiafjext
import pythiaext
def groom(jet, jetR, zcut, beta):
gshop =... |
from spectree import SpecTree
SpecTree("quart")
print("=> passed quart plugin import test")
|
import json
#判断用户名是否存在
def is_user_exists(username):
filename="username.json"
try:
with open(filename,'r') as file:
lines=file.readlines()
if lines:
for line in lines:
if username==line.rstrip():
return True
... |
def calcular_Distancia(s1, s2):
m=len(s1)+1
n=len(s2)+1
tbl = {}
for i in range(m): tbl[i,0]=i
for j in range(n): tbl[0,j]=j
for i in range(1, m):
for j in range(1, n):
cost = 0 if s1[i-1] == s2[j-1] else 1
tbl[i,j] = min(tbl[i, j-1]+1, tbl[i-1, j]+1, tbl[i-1, j-1... |
# no.1
a=[1,2,3,4,5,6,7,8,9]
newlist=[x for x in a if x%3==0] #like this
print (newlist)
|
from functions import sieve
def factors(n,primes):
factors = []
for i in primes:
if n%i == 0:
n /= i
factors.append(i)
return factors
def main():
primes = sieve(20000)
for j in range(0,1000000):
if j%1000 == 0:
print(j)
if all(len(factors... |
from django.urls import path
from aliados.views import ListarAliados, InsertarAliado, EditarAliado, BorrarAliado
urlpatterns=[
path('aliados', ListarAliados.as_view(), name='aliados_list'),
path('aliados/new', InsertarAliado.as_view(), name='insertar_aliado'),
path('aliados/edit<int:pk>', EditarAliado.as_v... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.