text stringlengths 8 6.05M |
|---|
import requests
payload={'key1':'value1','key2':['value2','value3']}
headers={'user-agent':'1'}
r=requests.get("https://www.baidu.com",params=payload,headers=headers)
# print (r.url)
# print (r.text)
# print (r.status_code)
# print (r.headers) r.headers['Content-Type|...'] r.headers.get('content-type|...')
# print ... |
__author__ = 'QC1'
from main.page.base import *
from selenium.webdriver.common.by import By
from utils.function.general import *
import os, time, sys, json, requests
import urllib.parse
import urllib.request
class AdminPage(BasePage):
_tokopedia_backend_image_loc = (By.XPATH, "/html/body/div[1]/div/div/a/img")
... |
# -*- coding: utf-8 -*-
"""
ytelapi
This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ).
"""
class Body73(object):
"""Implementation of the 'body_73' model.
TODO: type model description here.
Attributes:
number_type (NumberType2Enum): The cap... |
import subprocess
cmd = input().split()
subprocess.run(cmd) |
#文件的读和写
f=open("D://hello.txt","r")
a=f.readlines()
print(a)
f.close()
b=open("D://hello2.txt","w")
c=b.writelines(a)
b.close()
print("成功啦")
|
import time,re
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import pandas as pd
def spider(artist):
driver = webdriver.Chrome()
driver.implicitly_wait(5)
driver.get("http://tool.liumingye.cn/music/?page=searchPage")
input_tag = driver.find_element_by_id('input')
... |
from bs4 import BeautifulSoup
from urllib2 import urlopen
def retrieveRecipe(url):
recipePage = urlopen(url)
soup = BeautifulSoup(recipePage.read())
recipeInfo = {}
# Recipe Components
recipeInfo["title"] = soup.find(id="itemTitle").string
recipeInfo["rating"] = soup.find(itemprop="ratingValue")["content"]
rec... |
def calculate_sum(a, N):
m = N / a
sum = m * (m + 1) / 2
ans = a * sum
print("Sum of multiples of ", a,
" up to ", N, " = ", ans)
calculate_sum(7, 49) |
import numpy as np
import readData
import matplotlib.pyplot as plt
days = readData.days
flow = np.array(readData.flow)
flowList = np.array(readData.flowList)
time = np.array(readData.time)
postMile = np.array(readData.postMile)
fPM = 67.99
timeSlot = 24*12
points = 136
flowAtPoint = np.empty((0, days))
... |
N = [-10, -5, 1, 2, 3, 6, 5]
def print_positive(array: list):
for num in array:
if num > 0:
print(num)
print_positive(N)
|
from django.conf.urls import url
from rest_framework.urlpatterns import format_suffix_patterns
from note import views
app_name = 'note'
urlpatterns = [
url(r'^api/notes/$', views.AllNote.as_view()),
url(r'^api/ready_notes/$', views.ListReadyNotes.as_view()),
url(r'^api/no_ready_notes/$', views.ListNotRead... |
# This file makes the python files in this folder accessible from other folders
|
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 14 13:54:10 2020
https://gist.github.com/CMCDragonkai/dd420c0800cba33142505eff5a7d2589
"""
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import cv2
def surface_plot (matrix, **kwargs):
# acquire the cartesian coordinate m... |
from office365.runtime.client_value import ClientValue
from office365.sharepoint.principal.principal_source import PrincipalSource
from office365.sharepoint.principal.principal_type import PrincipalType
class ClientPeoplePickerQueryParameters(ClientValue):
def __init__(self, queryString, allowEmailAddresses=True... |
#!/usr/bin/env python
#
# Copyright (c) 2019 Opticks Team. All Rights Reserved.
#
# This file is part of Opticks
# (see https://bitbucket.org/simoncblyth/opticks).
#
# 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... |
#!/usr/local/bin/python3
import asyncio
import aiohttp
import logging
logger = logging.getLogger('discord')
async def download_page(url):
headers = {}
headers['User-Agent'] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36"
loop = asyn... |
# -*- coding: utf-8 -*-
import ch.systemsx.cisd.openbis.generic.server.jython.api.v1.DataType as DataType
print("Importing Flow Core Technology Master Data...")
tr = service.transaction()
# ==============================================================================
#
# FILE FORMATS
#
# ===========================... |
import os
os.system("thorq --add --mode single --device gpu/7970 ./test")
|
reservation_schema = {
"id": int,
"customer_id": int,
"start_latitude": float,
"start_longitude": float,
"srid": int,
"net_price": int,
"location_id": int
}
location_schema = {
"id": int,
"wgs84_polygon": str,
"title": str
} |
import numpy as np
class Calculadora:
def __init__(self):
print ("Se creo una calculadora")
def sumar(self,x,y):
return x + y
def restar(self,x,y):
return x - y
def multiplicar(self,x,y):
return x*y
def dividir(self,x,y):
return x/y
class CalcAleatorea(Calc... |
from django.shortcuts import render
from django.views.generic import View
import fredboardScales as gs
import random
# Create your views here.
postcount = 0
class ScalesPage(View):
def get(self, request, *args, **kwargs):
add = gs.create_svg('C', 'Ionian', 0)
svg = add.draw_single_box()
s... |
from kivy.app import App
from kivy.uix.scatter import Scatter
from kivy.uix.label import Label
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.textinput import TextInput
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import ListProperty
import random
"""
Kivy example by Alexander Taylor:
ht... |
from classes.util.date_formater import DateFormater
from classes.lock_modifier.result import Result
from classes.lock_replacer import LockReplacer
from classes.yaml_parser import YamlParser
from classes.package_matcher.match import Match
from pathlib import Path
from typing import Any, IO, List, Optional
class LockMo... |
# -*- coding: utf-8 -*-
# from __future__ import unicode_literals
from django.db import models
INVESTMENTHOUSE = (
('ALT', 'אלטשולר שחם'),
('EXL', 'אקסלנט'),
('PSA', 'פסגות'),
('LAP', 'לפידות'),
('YAL', 'ילין לפידות'),
('MEI', 'מיטב - דש'),
)
PLAN = (
('GEM', 'קרן גמל'),
('HIS', 'קרן ה... |
from flask import Flask, render_template
import requests
app = Flask(__name__)
# 1. 사용자가 접속할 경로를 작성
@app.route('/')
def hello_world():
print('hello word')
#수정위해원래코드
@app.route('/service.html')
def service():
# HTML 반환해주기
# 반드시 templates 폴더 안에 위치해야합니다.
# render_template 불러와주기
menu_db = [
'BBQ 황금 올리브... |
from pywebio.output import *
from pywebio.input import *
from pywebio.session import *
from functools import partial
class CRUDTable():
'''
Generalizable Create, Read, Update, Delete Table class.
:param gen_data_func: custom function that has procedure for generating the table data
:param edit_func: ... |
""" Script to check conversion from nPE to MeV of neutrons and protons, respectively, which were simulated
with tut_detsim.py of JUNO offline version J18v1r1-pre1.
Results of this script are used to convert neutron/proton/positron with specific energy in MeV to number of PE
in the JUNO detector.
With ... |
'''A module that contains classes and functions for using tensorflow.'''
from contextlib import contextmanager
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import (Dense, Conv2D, MaxPooling2D, Flatten,
InputLayer)
def wrap_i... |
import pkg_resources
default_app_config = "pinax.badges.apps.AppConfig"
__version__ = pkg_resources.get_distribution("pinax-badges").version
|
import os
import os.path as ops
import urllib.request
import gzip
import numpy as np
import pickle
def get_mnist_data(datadir):
dataroot = 'http://yann.lecun.com/exdb/mnist/'
key_file = {
'train_img': 'train-images-idx3-ubyte.gz',
'train_label': 'train-labels-idx1-ubyte.gz',
'test_img'... |
# -*- coding: utf-8 -*-
import torch
import os
from torchvision import transforms
from PIL import Image
import torch.nn as nn
from math import log10
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
def calc_psnr(pred_path, gt_path, result_save_path, epoch):
if not os.path.exists(result_save_... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('basketball', '0017_auto_20150724_1914'),
]
operations = [
migrations.AlterField(
model_name='playbyplay',
... |
#贪心算法,在表示一个较大整数的时候,“罗马数字”不会让你都用 11 加起来,
#肯定是写出来的“罗马数字”的个数越少越好。
#类似找零钱
def intTOrome(num):
# 把阿拉伯数字与罗马数字可能出现的所有情况和对应关系,放在两个数组中
#此时不适合用字典,索引不方便
# 并且按照阿拉伯数字的大小降序排列,这是贪心选择思想
nums=[1000,900,500,400,100,90,50,40,10,9,5,4,1]
romes=['M','CM','D','CD','C','XC','L','XL','x','IX','V','IV','I']
n=len(nums)
... |
"""
route schema
"""
import typing
from vbml import Patcher, PatchedValidators
from vbml import Pattern
from kumquat.exceptions import KumquatException
from kumquat._types import Method
class Route:
"""
app route with path and func
"""
def __init__(self, path: str, func: typing.Callable, methods: typ... |
# Generated by Django 2.2.3 on 2020-09-12 09:12
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('reviewapp', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='product',
old_name='Ticket',
n... |
'''
Created on May 13, 2019
@author: ab75812
'''
print('DeeSub')
|
from .structs import Currency, Scope, Claim, ClaimStatus, Balance
from .errors import MissingScope, BadRequest, NotFound
from .client import VirtualCryptoClientBase, VIRTUALCRYPTO_TOKEN_ENDPOINT, VIRTUALCRYPTO_API
from typing import Optional, List
import datetime
import aiohttp
import asyncio
class AsyncVirtualCrypto... |
#Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def getIntersectionNode(self, headA, headB):
#Determine lengths
len1, len2 = 0, 0
currA, currB = headA, headB
while currA != N... |
def computepay(h,r):
if h <= 40:
pay = r * h
else:
pay = r * 40 + r * 1.5 * (h-40)
return pay
h = float(input("Enter Hours:"))
r = float(input("Enter Rate:"))
p = computepay(h,r)
print("Pay",p)
|
import pandas as pd
import lightgbm as lgb
from datetime import timedelta
from tqdm import tqdm
from data import data_frames, optimize_df, melt_and_merge, features, lgb_dataset
# Global constants
MAX_LAG = timedelta(days=57)
def next_day_features(df, forecast_date):
"""
Create features of the next day to... |
print("Modular multiplicative inverse")
def modolu(a, m):
a = a % m
for x in range(1, m):
if (a * x) % m == 1:
return x
return 1
a = int(input("a = "))
m = int(input("m = "))
print(modolu(a, m))
|
import numpy as np
import os
os.system('cls')
class arrayRow_DataStructure():
def __init__(self, num_columns):
self.num_columns = num_columns
self.arr = np.empty((0, self.num_columns))
return
def append(self, record):
self.arr = np.append(self.arr, record, axis=0)
def d... |
from django.apps import AppConfig
class GetSkuConfig(AppConfig):
name = 'get_sku'
|
number = int(input())
last = []
def geacha(n):
if n == 0:
return 1
else:
return 6 * (n) + last[n - 1]
i = 0
while True:
last.append(geacha(i))
if number <= last[-1]:
break
i += 1
print(i+1) |
import botostubs
import os
import logging
import datetime
import boto3
import operator
from botocore.exceptions import ClientError
boto_session = boto3.Session(profile_name='default')
def does_the_bucket_exist(bucketname):
s3: botostubs.S3 = boto_session.client('s3')
try:
response = s3.head_bucket(Bu... |
# Justin J
# Fall 2017
# Computational Complexity
# Mapping SAT -> 3SAT
# Clause helper class
class Clause:
def __init__(self, a, b, c):
self.a = str(a)
self.b = str(b)
self.c = str(c)
def toString(self):
return '( ' + self.a + ' + ' + self.b + ' + ' + self.c + ')'
# Convert any given c... |
import dash_bootstrap_components as dbc
from dash import Input, Output, State, html
offcanvas = html.Div(
[
dbc.Button(
"Open scrollable offcanvas",
id="open-offcanvas-scrollable",
n_clicks=0,
),
dbc.Offcanvas(
html.P("The contents on the main... |
name = input('please say something: ')
print('Hi', name) |
"""Funcionality for representing a physical variable in aospy."""
import numpy as np
class Var(object):
"""An object representing a physical quantity to be computed.
Attributes
----------
name : str
The variable's name
alt_names : tuple of strings
All other names that the variable... |
def fun1(a):
print(a)
fun1(a=1)
def fun2 (a, **kwargs):
print(a)
print(kwargs)
fun2(10, a1=1,b=2)
def fun3(a, *args):
print(a)
print(args)
fun3(12, 1,3)
f = lambda a1,a2:a1+a2
print(f(1,2))
sum = 0
def f1():
global sum
sum = sum+1
print(sum)
f1()
|
import enum
class AuthConstants(enum.Enum):
noMatch = "Wrong username and password combination"
noUser = "User does not exist"
sucessLogout = "You have been successfully logged out"
passwordUpdated = "Successfully updated your password"
codeMail = "A 6 digit verification code has been sent to your... |
# Generated by Django 2.0.7 on 2018-09-21 06:27
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('rocky', '0007_auto_20180915_1454'),
]
operations = [
migrations.AddField(
model_name='book',
name='introduction',
... |
"""add article page view
Revision ID: 2a1c4da978f8
Revises: 4058a1c2b44d
Create Date: 2015-11-26 10:34:54.369011
"""
# revision identifiers, used by Alembic.
revision = '2a1c4da978f8'
down_revision = '4058a1c2b44d'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Al... |
from Node import Node
class BinaryTree:
root = None
def __init__(self):
print("Tree created")
def __str__(self):
print(self.root.value)
self.root.Print("")
def Add(self, value):
if self.root == None:
self.root = Node(value)
#print("Root was zer... |
from rest_framework import serializers
class PredictorSerializer(serializers.Serializer):
name = serializers.CharField(max_length=30)
|
import util
import os
tutorial_path = os.path.expandvars("$desktop/mans/manim_ce/example_scenes/tutorial_final.py")
lines = []
with open(tutorial_path, "r") as f:
lines = f.readlines()
modules = []
for aline in lines:
if aline[0] == 'c':
modules.append(aline.split("(")[0][6:])
for amodule in modules:
... |
import time
from flask import request
from flask_restplus import Api, Resource
from server import db
from server.operation.register import Register
from .. import api
import server.document as document
ns = api.namespace('opeartion', description="用户留言")
class Opeartion(Resource):
"""
用户留... |
import unittest
from katas.beta.nothing_special import nothing_special
class NothingSpecialTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(nothing_special('Hello World!'), 'Hello World')
def test_equals_2(self):
self.assertEqual(nothing_special('%^Take le$ft ##quad%r&a&n... |
# Dependencies
import tweepy
import json
import numpy as np
# Twitter API Keys. Place your keys here.
consumer_key = ""
consumer_secret = ""
access_token = ""
access_token_secret = ""
# Setup Tweepy API Authentication
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access... |
# https://www.sqlite.org/json1.html
import sqlite3
import json
db_name = 'yt.db'
def open():
conn = sqlite3.connect(db_name)
cursor = conn.cursor()
sql = 'create table stats (ts varchar(64), video_id varchar(64), data json)'
try:
cursor.execute(sql)
conn.commit()
except sqlite3.... |
from scripted import ScriptedJobPlugin
from staging import StagingJobPlugin
_jobplugins_by_name = {
'scripted': ScriptedJobPlugin,
'staging': StagingJobPlugin,
}
def register_jobplugin(cls):
_jobplugins_by_name[cls.name] = cls
def load_jobplugin(name):
return _jobplugins_by_name[name]
|
import numpy as np
from blob_mask import blob_mask, blob_mask_dim
from constants import image_height, image_width
def get_true_mask(data):
all_blobs = data["army"] + data["enemy"]
all_masks = []
for blob in all_blobs:
if (blob["alive"]):
mask = np.zeros((image_height, image_width, 1), ... |
# Copyright (c) 2013 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import sys, os.path
sys.argv[1] = os.path.basename(sys.argv[1])
with open('msbuild_rule.out', 'w') as f:
f.write(' '.join(sys.argv))
|
# coding: utf-8
"""
AuthProvidersApi.py
Copyright 2016 SmartBear Software
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 requ... |
from django.db import models
from django.core.validators import RegexValidator
from django.contrib.auth.models import User
from django.core.validators import MinValueValidator
class Customer(models.Model):
firstName = models.CharField (max_length=50, verbose_name="First Name")
lastName = models.CharField (max... |
import pandas as pd
import numpy as np
import json
import time
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.feature_extraction.text import TfidfVectorizer
from nltk.corpus import stopwords
import re
import string
from nltk.stem import Wo... |
# -*- test-case-name: mimic.test.test_ironic -*-
"""
API Mock for Ironic.
http://docs.openstack.org/developer/ironic/webapi/v1.html
"""
from __future__ import absolute_import, division, unicode_literals
from mimic.rest.mimicapp import MimicApp
class IronicApi(object):
"""
Rest endpoints for the Ironic API.
... |
#!/usr/bin/env python
import os
from Tkinter import *
from tkMessageBox import *
from tkFileDialog import *
from reedsolo import RSCodec, ReedSolomonError
from simplecrypt import encrypt, decrypt, DecryptionException
class Notepad:
#variables
__root = Tk()
#Reed - Solomon codec for error detection ... |
import pyglet
from pyglet.gl import *
#import random
#from random import uniform,randrange,choice
from numpy.random import uniform,randint,choice
import loaders
from pymunk import Vec2d
import PiTweener
import itertools
## http://stackoverflow.com/questions/14885349/how-to-implement-a-particle-engine
## Performance? h... |
# app building library
import streamlit as st
# dataframe libraries
import numpy as np
import pandas as pd
# model libraries
import gensim
from gensim.models import Doc2Vec
# miscellany
import pickle
import gzip
# custom functions for this app
from functions_app import *
# load poetry dataframe
with gzip.open('da... |
from django.http import HttpResponse, JsonResponse
from rest_framework import viewsets
from rest_framework.decorators import detail_route
from rest_framework.exceptions import ParseError
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from landscapesim import models
from... |
from collections import defaultdict
class Solution:
def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]:
graph = defaultdict(list)
for i in range(len(equations)):
graph[equations[i][0]].append([equations[i][1],values[i]])
... |
"""quiz_app URL Configuration
"""
from django.contrib import admin
from django.urls import path, include
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('quizes.urls',namespace='quizes')),
path('user/', include(('u... |
from flask import Flask, request
from flask_restful import Resource, Api
import mysql.connector, json
app = Flask(__name__)
api = Api(app)
class Product(Resource):
#config for login credentials
config = {
'user':'root','password':'root',
'host': 'db-mysql','port':'3306',
'd... |
import os
import math
from utct.common.data_source_template import DataSourceTemplate
class MnistDataSourceTemplate(DataSourceTemplate):
def __init__(self,
use_augmentation=True,
data_h5_path=None):
super(MnistDataSourceTemplate, self).__init__(use_augmentation)
... |
#/usr/bin/env python3
# -*- encoding:utf8 -*-
from shutil import *
import os,sys,datetime
import subprocess
from subprocess import PIPE
from pprint import pprint
from muninn_config import JUPYTER_NOTEBOOK_ROOT_FOLDER,HTML_DST_FOLDER
import pickle, traceback
SEP = os.path.sep
def transData(clist,from_source=JUPYTER_NO... |
from keras.preprocessing.image import load_img, img_to_array, save_img
from keras.models import Sequential
from keras.layers import Conv2D, MaxPool2D, UpSampling2D
import numpy as np
import os
import argparse
import csv
import matplotlib.pyplot as plt
curdir = os.path.dirname(os.path.abspath(__file__))
parser = argpar... |
def f(a, b): # 매개변수 2개를 더하는 함수
return a + b
print(f(3, 5))
print(f(2, 1)) |
__author__ = 'Justin'
import os
import networkx as nx
from datetime import datetime
from SetNetworkTime import set_network_time
from WeightFunction import weightfunction
from ZenScore import zenscore
from random import choice
from geopy.distance import vincenty as latlondist
import geojson
from DisplayNetwork import n... |
"""empty message
Revision ID: 430e1e04753b
Revises: e6d8ccbfb29d
Create Date: 2020-03-24 22:50:23.344042
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '430e1e04753b'
down_revision = 'e6d8ccbfb29d'
branch_labels = None
depends_on = None
def upgrade():
# ... |
class Stack:
def __init__(self):
self.__list = []
def __str__(self):
result = "Here is a stack: "
for item in self.__list:
result += str(item) + ", "
return result
def push(self, item):
self.__list.append(item)
def pop(self):
self.__list.pop... |
import os
import tensorflow as tf
import numpy as np
import preprocess_utils
def _preprocess_zero_mean_unit_range(inputs):
"""Map image values from [0, 255] to [-1, 1]."""
return (2.0 / 255.0) * tf.to_float(inputs) - 1.0
def preprocess_image(image,
crop_height,
crop_widt... |
import turtle
import math
import random
bob = turtle.Turtle()
bob.speed(30)
turtle.getscreen().bgcolor("black")
turtle.hideturtle()
for i in range(100):
if i%2 == 0:
bob.hideturtle()
bob.circle(100)
bob.color("orange")
bob.left(25)
else:
bob.hideturtle... |
from flask import request, jsonify, make_response
from functools import wraps
from flask_restful import abort
from models import User
import jwt
import os
import sys
AUTH_ERROR_MESSAGE = "The server could not verify that you are authorized to access the URL requested. You either supplied the wrong credentials (e.g. a... |
# -*- coding: utf-8 -*-
import re
from typing import Iterable, Text
from urllib.error import HTTPError
from urllib.parse import urlencode
from urllib.request import BaseHandler
import execjs
# noinspection PyProtectedMember
from bs4 import BeautifulSoup, SoupStrainer
from .base import FeedFetcher, Item
class IAppsF... |
from .bbox_3d import *
from .evaluation import *
|
# temp_file = open('input.txt', 'r')
# for line in temp_file:
# print(line, end='')
input_object = open('input.txt', 'r')
output_object = open('output.txt', 'w')
for line_str in input_object:
new_str = ''
line_str = line_str.strip()
for char in line_str:
new_str = char + new_str
print(ne... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 7 20:16:31 2018
@author: user
矩陣相加
"""
a=[]
b=[]
print("Enter matrix 1:")
for i in range(2):
a.append([])
for j in range(2):
print("[%d, %d]: " % (i+1, j+1), end = '')
a[i].append(int(input()))
print("Enter matrix 2:")
for i in range(2)... |
a = [int(i) for i in input().split()]
b = int(input())
result = ''
for i in range(len(a)):
if b == a[i]:
result += str(i) + " "
if result != '':
print(result)
else:
print("Отсутствует") |
print("Or "*100)
num1=28
print(num1)
num2=num1/2
print(num2)
kobi = [1,2,3]
for i in range(len(kobi)):
print(kobi[i]) |
a = [0,1,2,4,3]
# indexing
print(a[3])
# index
print(a.index(1))
# slice
print(a[1:3])
# append
a.append('6')
print(a)
# insert
a.insert(0,'7')
print(a)
# del
del a[1]
print(a)
# remove
a.remove('6')
print(a)
# pop
b = a.pop(0)
print(a)
print(b)
# sort
a.sort()
print(a)
# reverse
a.reverse()
print(a)
# count... |
import json
import os.path
import secrets
from abc import ABC, abstractmethod
from csv import DictWriter
from datetime import datetime
from faker import Faker
from lib.common import FAKER_SEED
class FakeDataGenerator(ABC):
"""
Abstract Data Generator class, subclasses needs to implement
the gen... |
import datetime
import os
import random
import pandas as pd
random.seed(1)
import numpy as np
np.random.seed(1)
# import tensorflow as tf
# tf.random.set_random_seed(1)
from train_and_test import train_and_evaluate_dae_ff
# from train_fasttext import train_and_evaluate_fasttext
if __name__ == "__main__":
# r... |
# -*- coding: utf-8 -*-
# Module author: @GovnoCodules
import requests
from .. import loader, utils
@loader.tds
class WeatherMod(loader.Module):
"""Weather Module"""
strings = {'name': 'Weather'}
async def pwcmd(self, message):
""""Кидает погоду картинкой.\nИспользование: .pw <город>; ничего.""... |
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
n1, n2, n10, n100 = np.loadtxt("standard.txt", usecols=(0,1,2,3), delimiter=' ', unpack='true')
n_bins = 50
n, bins, patches = plt.hist(n1, n_bins, range=(0,1))
plt.xlabel('ciao')
plt.ylabel('prova')
plt.title('Histogram loaded from file!')
plt.grid... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from __future__ import division
import time
from inc import *
import os
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
#加区间报警
#加failure
def SelectApplicationSql(module,today):
sql = "select sum(failureCount + successCount) as num from `avg_%s_%s`" % (module... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2016-01-24 05:03
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateM... |
import os
import re
os.chdir(path)
for fo in os.listdir(): #get list of artist folders
if fo != '.DS_Store':
os.chdir(fo)
for al in os.listdir(): #for each artist folder, list of album folders
if al != '.DS_Store':
os.chdir(al)
for so in os.listdir(): #f... |
from abc import abstractmethod
import copy
import pickle
import numpy as np
from scipy.stats import pearsonr
import matplotlib.pyplot as plt
import pandas as pd
from joblib import Parallel, delayed
from sklearn.model_selection import KFold, train_test_split
from sklearn.preprocessing import StandardScaler
class Mod... |
#!/usr/bin/python
import time
import argparse
import requests
from prometheus_client import start_http_server
from prometheus_client.core import GaugeMetricFamily, CounterMetricFamily, REGISTRY
parser = argparse.ArgumentParser(description='K8S API Server exporter')
parser.add_argument('--master','-ip', type=str, help... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.