text stringlengths 38 1.54M |
|---|
# loc :access both row and columns with index(or label)
# iloc: access both row and columns with index.
# loc[0] 0th row
# loc['row_label'] that row
# loc[:, 0] # 0 th column
#iloc[0]: 0th row
#iloc[:, 1] # 2nd column |
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name="home"),
path('about/', views.about, name="about"),
path('filter/', views.filter, name="filter"),
path('test/', views.test, name="test"),
path('alaki/', views.alaki, name="alaki"),
path('shares_info/', v... |
from django.conf.urls import patterns, url, include
from django.contrib import admin
import views
urlpatterns = patterns('',
url(r'^dashboard/$', views.DashboardView.as_view()),
url(r'^run_test/(?P<id>\d+)$', views.run_test),
url(r'^email/(?P<id>\d+... |
'''
Return the sum of the numbers in the array, returning 0 for an empty array.
Except the number 13 is very unlucky, so it does not count and numbers that come immediately after a 13 also do not count.
'''
def sum13(nums):
nums += [0]
return sum(n for i, n in enumerate(nums) if n != 13 and nums[i-1] !=13)
# s... |
## QUESTÃO 5 ##
# Escreva um programa para calcular a redução do tempo de vida de um fumante.
# Pergunte a quantidade de cigarros fumados por dia e quantos anos ele já fumou.
# Considere que um fumante perde 10 minutos de vida a cada cigarro, calcule
# quantos dias de vida um fumante perderá. Exiba o total em dias. ... |
from matplotlib import pyplot, pyplot as plt
from matplotlib.patches import Rectangle
from mtcnn.mtcnn import MTCNN
import os
from statistics import mean
import numpy as np
l_conf = []
def detect_face():
# plot photo with detected faces using opencv cascade classifier
import cv2
from cv2 import imread
... |
from django.shortcuts import render,redirect
from room.models import Room
from room.forms import RoomForm
# Create your views here.
def index(request):
print(request.method)
if(request.method=="POST"):
page=int(request.POST['page'])
if('prev' in request.POST):
page=page-1
i... |
import requests
from bs4 import BeautifulSoup
season = int(input(("enter the season :")))
episode = int(input("enter number of episodes in season:"))
for ep in range(episode):
if (season < 10):
URL = "https://www.springfieldspringfield.co.uk/view_episode_scripts.php?tv-show=the-office-us&episode=s0" + str... |
#!/usr/bin/python
from igraph import Graph
class ReactDic(object):
# graphname = name of the graph
# clst = list of compund objects ordered by their ID
# rlsts = list of reaction objects listed by their IDs
# elst = list of enzyme objects listed by their IDs
# plst = list of pathways listed by their IDs
# ml... |
#!/user/bin/env python
#coding:utf-8
def sum(month):
if (month ==1 or month ==2):
return 1
else:
return sum(month-1) + sum(month-2)
print sum(2)
print sum(36)
|
import json
import os
import traceback
from time import time, sleep
import seaborn as sns
import pandas as pd
from collections import OrderedDict
import sys
from matplotlib import pyplot
from scipy.sparse import coo_matrix
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import GradientBoosti... |
from tkinter import Canvas
from math import floor
class canvasRAM(Canvas):
def __init__(self, master=None, h=20):
super().__init__(master, bg='black', width=1280, height=h*16)
self.tcr = 1024
self.crX = ((int(self['width'])-self.tcr)/2)-1
self.crY = 5
self.hcr = h-self.crY... |
import sys
import gspread
try:
email = input("Please enter google email: ")
except SyntaxError:
email
try:
passwd = input("Please enter google passwd: ")
except SyntaxError:
passwd
# Login with your Google account
gc = gspread.login(email, passwd)
#You can open a spreadsheet by its title as it appears in Googl... |
"""
# author Liu shi hao
# date: 2019/11/25 16:21
# file_name: plane_v1
"""
# 导入游戏模块
import random
import sys
import pygame
# 初始化游戏数据
from datetime import date
pygame.init()
class BaseBullet(object):
# '''子弹类'''
def __init__(self, screen_temp, x, y, image_name):
self.x = x
self.y = y
... |
def isPerfectSquare(self, num: int) -> bool:
if(num<2): return True
x=2
y=num//2
while(y>=x):
z=(x+y)//2
srt=z*z
if(srt==num): return True
elif(srt>num): y=z-1
else: x=z+1
return False
nums = [4,9,144,399]
for x in nums:
print (x,isPerfectSquare(x... |
class MyData:
def __init__(self, abspathpar, brpon):
self.abspath = abspathpar
self.brPonavljanja = brpon
self.rang = 0
|
import pandas as pd
import numpy as np
import sys
import pickle
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVR
### Importa base de dados
data = pd.read_csv('Dataset_finalizado.cs... |
#!/usr/bin/env python
import argparse
import glob
import logging
import os
from os.path import join as pjoin
import shutil
from katsdpservices import setup_logging
import katacomb.configuration as kc
from katacomb.util import setup_aips_disks
log = logging.getLogger('katacomb')
def rewrite_dadevs():
"""
Rew... |
import os
import os.path
import gzip
import settings
import column_definitions
import repository_factory
from annotations import insert_annotations
from epidb_interaction import PopulatorEpidbClient
from client import DeepBlueClient
from data_sources import project_sources
from genomes import hg19_info, mm9_info, mm10... |
import pprint
from datetime import datetime
from copy import deepcopy
# Constants
cashConstant = "$CASH" # Identifies cash in trade transactions
nonPriceKeys = ["Quantity", "SKU", cashConstant]
# Table of Contents (Methods)
# totalUnitBasis
# totalProductBasis
# totalQuantity
# averageCost
# profi... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: vita
from django import forms
from rbac.models import Menu, Permission
class MultiAddPermissionForm(forms.Form):
title = forms.CharField(
widget=forms.TextInput(attrs={"class": "form-control"})
)
url = forms.CharField(
widget=forms.Tex... |
import pandas as pd
import statsmodels.formula.api as smf
import selection
import matplotlib.pyplot as plt
import numpy as np
import statistics
import sklearn
import lectura
import application
import MLPregression
import copy
import SMmaps
file = "tabla_calibration_validation.csv"
data = lectura.lecturaCompleta_etap... |
import cv2
import numpy as np
def nothing(x):
pass
img= np.zeros(shape=(300, 500, 3), dtype='uint8')
cv2.namedWindow('Paleta')
cv2.createTrackbar('Red', 'Paleta', 0, 255, nothing)
cv2.createTrackbar('Green', 'Paleta', 0, 255, nothing)
cv2.createTrackbar('Blue', 'Paleta', 0, 255, nothing)
while True:
cv2.ims... |
#!/usr/bin/env python3
import sys
import os
import pyttsx
import speech_recognition as sr
import spacy
import json
nlp = spacy.load('en')
r = sr.Recognizer()
#with sr.Microphone() as source:
# print("Say something!")
#audio = r.listen(source)
# recognize speech using Google Cloud Speech
GOOGLE_CLOUD_SPEECH_CRED... |
import paho.mqtt.client as mqtt
# 클라이언트가 서버에게서 CONNACK 응답을 받을 때 호출되는 콜백
def on_connect(self, client, userdata, rc):
print ("Connected with result coe " + str(rc))
# client.subscribe("hello/world")
self.subscribe("hello/world")
# 서버에게서 PUBLISH 메시지를 받을 때 호출되는 콜백
def on_message(self, userdata, msg):
prin... |
from django.db.models import Model
from django.db.models import CharField, TextField, BooleanField, ImageField, DateTimeField
from django.db.models.signals import pre_delete, pre_save
from django.dispatch import receiver
class Announcement(Model):
name = CharField(max_length=200, verbose_name='Заголовок')
slu... |
import csv
import requests
from django.core.management.base import BaseCommand
from authorities.models import Authority
from everyelection.models import AuthorityElection
class Command(BaseCommand):
def handle(self, **options):
sheet_url = "https://docs.google.com/spreadsheets/d/1YM-inMb-WLzyNN8e7eOFoIm... |
# Generated by Django 2.2.7 on 2020-01-14 12:48
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('Product', '0005_auto_20200114_1816'),
]
operations = [
migrations.AlterField(
model_name='product',
na... |
import socket
import json
import time
import threading
import modes
from google import Intent
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import urlparse
import ssl
__clientid__ = 'recordwall'
__clientsecret__ = 'XQe4PXDUee8FpsQzRrk1L7P6ejRz2GXuFUs'
__token__= 'dfaashuihbniadAWEanuh23'... |
import pandas as pd
import numpy as np
import xgboost as xgb
from xgboost.sklearn import XGBClassifier
from sklearn import (metrics, cross_validation, linear_model, preprocessing) #Additional scklearn functions
from sklearn.grid_search import GridSearchCV #Perforing grid search
import csv
from random import randint... |
# Copyright (c) ONNX Project Contributors
# SPDX-License-Identifier: Apache-2.0
from __future__ import annotations
import os
import platform
import sys
import unittest
from typing import Any, ClassVar
import numpy
from packaging.version import Version
import onnx.backend.base
import onnx.backend.test
import onnx.s... |
from pcluster.aws.common import AWSExceptionHandler, Boto3Client
class ImageBuilderClient(Boto3Client):
"""Imagebuilder Boto3 client."""
def __init__(self):
super().__init__("imagebuilder")
@AWSExceptionHandler.handle_client_exception
def get_image_resources(self, image_arn):
"""Get ... |
def primes_to(n):
primes = [i for i in range (n)]
primes[1] = 0
for j in range (2, n):
if int(primes[j]) != 0:
for k in range (j ** 2, len(primes), j):
primes[k] = 0
while 0 in primes:
primes.remove(0)
return primes
primes = primes_to(10000)
def is_we... |
from typing import Dict, Set, List
class Packet:
def __init__(self, dest) -> None:
super().__init__()
self.dest = dest
self.ttl = 15
class TableEntry:
def __init__(self, distance, nextHop):
super().__init__()
self.distance = distance
self.nextHop = nextHop
... |
from django.shortcuts import render
from rest_framework import status
from rest_framework.authtoken.models import Token
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
... |
from __future__ import absolute_import, division, print_function, unicode_literals
from .htmldocument import HTMLDocument
|
"""
Price Events
"""
class Event:
def PriceUpdated(self):
"""
PriceUpdated Event
"""
pass
|
def solution(n, arr1, arr2):
answer = []
mMap = [["a"] * n for i in range(n)]
for i in range(0, n, 1):
mList = list(format(arr1[i], 'b'))
while len(mList) != n:
mList.insert(0,'0')
for j in range(n):
if mList[j] == '1':
mMap[i][j] = '#'
... |
#!/usr/bin/python3
import socket
# No IP to connect to needed for a server
IP = "::"
PORT = 3000
# Creates a socket using IPV6 and accepting datagrams
sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
sock.bind((IP, PORT))
while True:
data, address = sock.recvfrom(2)
# Decode the client data
tempe... |
import matplotlib.pyplot as plt
def plot(x, y):
plt.plot(x, y)
plt.xlabel('Tijd')
plt.xticks(fontsize = 5)
plt.ylabel('Bewegingssnelheid')
plt.title('testdata')
plt.savefig('static/img/grafiek.png') |
from django.shortcuts import redirect, render
from django.urls import reverse
from django.http import JsonResponse
from .models import Comment, ContentType, User
from .forms import CommentForm
# Create your views here.
def blog_comment(request):
comment_form = CommentForm(request.POST, user=request.user)
if... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 6 18:11:24 2020
@author: jinwensun
"""
class Solution(object):
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
# 这道题借鉴quick so... |
import os
import shutil
FilesOut = r'gip\УВЕДОМЛЕНИЯ ЮСБ ЧАСТЬ'
FilesIn = r'gip\01.12.2019'
files = []
paths = []
surnames = []
path1 = os.walk(FilesOut)
for i, _, k in path1:
for file in k:
#print(i+'\\'+file)
files.append(i+'\\'+file)
path2 = os.walk(FilesIn)
for path, folders, files in path... |
import lib
#Probar posible números
capicuas = (
123,
122,
121,
12321,
154123,
15451,
)
for num in capicuas:
if lib.capicua( num ):
cap = 'Sí'
else:
cap = 'No' ;
print( 'Número:', num, '- ¿Capicua?:', cap )
print( lib.es_primo( 12 ) )
n=int(input("ingrese un numer... |
from django.shortcuts import render
# Create your views here.
def Index(request):
return render(request, 'index.html')
def perecible(request):
return render(request, 'perecible.html')
def Noperecible(request):
return render(request, 'Noperecible.html')
def Mpuntos(request):
return render(request,... |
nota = float(input("nota do aluno: "))
opcao = input("bonificacao? (S/N): ")
if (opcao.upper() == "S"):
nota = nota + nota * 10/100
print(nota)
|
# import requests
# from bs4 import BeautifulSoup
#
# url = 'https://sportschools.ru/page.php?name=items'
# page = requests.get(url)
# print(str(page.status_code) + ' ' + 'status')
#
# soup = BeautifulSoup(page.text, "html.parser")
# # print(soup)
#
# a = soup.find_all('a')
#
# for i in a:
# print(i.text)
|
import pytest
from sklearn.linear_model import LinearRegression
from justcause.data.generators.toy import SWagerDataProvider
from justcause.methods.basics.outcome_regression import SLearner
from justcause.methods.causal_forest import CausalForest
from justcause.metrics import StandardEvaluation
def test_experiment(... |
# -*- coding: utf-8 -*-
import scrapy
from fangsh.items import FangshItem
class EsfshSpider(scrapy.Spider):
name = 'esfsh'
allowed_domains = ['esf.sh.fang.com/']
start_urls = ['http://esf.sh.fang.com/']
def parse(self, response):
base_url = "http://esf.sh.fang.com"
search_url = respons... |
import tensorflow as tf
from BikeS.GCN_layer import GCN_layer,GRCU
from BikeS.vaeTL import vaeTL
class EGCNVAE(tf.keras.Model):
def __init__(self, c_hid_layer_list,s_hid_layer_list,rnn_units, seq_len,output_dim):
super(EGCNVAE,self).__init__()
# E-GCN for time-evolving embedding
self.GRCU_l... |
# Copyright lowRISC contributors.
# Licensed under the Apache License, Version 2.0, see LICENSE for details.
# SPDX-License-Identifier: Apache-2.0
import argparse
from bignum_lib.disassembler import Disassembler
def main():
argparser = argparse.ArgumentParser(description='Bignum coprocessor instruction disassemb... |
import sys
sys.path.insert(0, '..')
from serialization import load_results
from pycofi.queries import get_top_items
(users, items, item_mean, J_train, Theta, X) = load_results()
for user in users:
R_filter = set(users[user]["R_indices"])
top_recommendations = get_top_items(users[user]["index"],
... |
import os
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from definitions import *
matplotlib.rcParams['lines.linewidth'] = 3
matplotlib.rcParams['font.size'] = 22
__all__ = ["plot_video_stats_recv", "plot_media_stats_twin_y", "plot_media_stats_single_y"]
linestyles = ['solid', 'dashed', 'dott... |
"""
Generates classification statistics for a test set on the provided model weights
"""
import sys, os
import numpy as np
import matplotlib.pyplot as plt
import time
from datetime import datetime
import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim import lr_scheduler
import torchvision
fr... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import dataset
import json
import time
from time import gmtime, strftime, localtime
from http.server import BaseHTTPRequestHandler, HTTPServer
from var_dump import var_dump
ptime = strftime("%Y-%m-%d %H:%M:%S", localtime())
db = dataset.connect('sqlite:///tweet.db')
table ... |
import cv2
import cntk
import os
from os import walk
import numpy as np
import argparse
from cntk.device import try_set_default_device, gpu, all_devices
from cntk.ops.functions import load_model
ap = argparse.ArgumentParser()
ap.add_argument("-m", "--model", required=True, help="path to cntk model")
ap.add_argument("-... |
#!/usr/bin/sudo / usr/bin/python
import RPi.GPIO as GPIO
import random
from time import sleep
# Use board pin numbering
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
# Start a new dictionary with desired LED names
leds = {'floor':[], 'top-left':[]}
# Take name of led and list of pins for RGB
def setupled(name, p... |
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="panel-indicator-test1",
version="0.0.1.dev1",
author="Utsav Krishnan",
author_email="ketankr9@gmail.com",
description="A library to display any text in ubuntu unity panel",
long_descri... |
from flask import Flask, request
app = Flask(__name__)
value = "1";
@app.route('/')
def home_route():
return """
<body>
<script>
async function change(){
await fetch(
'http://localhost/change',
{
... |
from typing import List
import itertools
class Solution:
def setZeroes(self, m: List[List[int]]) -> None:
M, N = len(m), len(m[0])
for i, j in itertools.product(range(M), range(N)):
if m[i][j]:
continue
for k in range(N):
if m[i][k] != 0:
... |
import pandas as pd
import smtplib, os, time, sys
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from getpass import getpass
from datetime import datetime
def check_credentials(email: str, password: str):
"""
Checks if ema... |
from datetime import datetime, timedelta
from threading import Timer
import pyautogui
import time
x=datetime.now()
date = str(datetime.date(x))
val1 = date.split("-")
time1 = str(datetime.time(x));
print(time)
times = time1.split(":")
print(times)
a_day = ("", "", "", "") #Insert Time periods of A... |
# -*- coding: utf-8 -*-
from scrapy import Spider, Request, FormRequest
from scrapy.loader import ItemLoader
import re
# custom item definition
from scrapper.items import PropertyItem
CITIES = ['cali', 'jamundi', 'palmira']
class MetroCuadradoSpider(Spider):
name = "metro_cuadrado"
allowed_domains = ["metr... |
# Importing libraries
import random
from django.db import models
from .utils import generate_vehicle_ID, generate_person_ID, generate_trip_ID, generate_stop_ID, generate_default_asset_ID, generate_default_trip_ID
import datetime
# Create your models here.
class Asset(models.Model):
# Table for storing the type ... |
import json
import os
import subprocess
import glob
import time
with open('settings.json') as fp:
settings = json.load(fp)
savepath = settings['savepath']
prev = []
try:
while True:
p = subprocess.run(
['du', '-h', '-d0', '-BM', *
glob.glob(os.path.join(savepath, '*'))... |
from mysql_db import DB
import pandas as pd
import matplotlib.pyplot as plt
plt.rcParams['axes.unicode_minus']=False
plt.rcParams['font.sans-serif']=['SimHei']
plt.style.use('ggplot')
def genpic():
db = DB()
table_name="com_info"
res = db.query(table_name)
fig = plt.figure(figsize=(15,15))
fig.set(alpha=0.5)
d... |
#!/usr/local/bin/python3.6
print("Python中的循环语句有 for 和 while")
n = 100
sum = 0
counter = 1
while counter <= n:
sum = sum + counter
counter += 1
print("1 到 %d 之和为: %d " % (n, sum))
print("while 循环使用 else 语句")
print("在 while … else 在条件语句为 false 时执行 else 的语句块:")
count = 0
while count < 5:
print(count, " ... |
###############################################################################
#
# The MIT License (MIT)
#
# Copyright (c) Zerodha Technology Pvt. Ltd.
#
# This example shows how to subscribe and get ticks from Kite Connect ticker,
# For more info read documentation - https://kite.trade/docs/connect/v1/#streaming-webs... |
import time
from prime import create_lists, is_prime
from multiprocessing import Pool, cpu_count
def worker(sequence):
return [n for n in sequence if is_prime(n)]
def main():
work_lists = create_lists(range(2, 5_000_000), 10_000)
print(f'Finding all primes below 5,000,000 using {cpu_count()} core(s)')
... |
def extracting(guess, number):
while guess * guess - number > 0.0001 or number - guess * guess > 0.0001:
guess = (guess + number / guess) / 2.0
else:
print(f'The answer is {guess}')
input_number = float(input('Please input a number'))
input_guess = float(input('Please input your guess'))
extr... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import simplejson as json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
class KoubeiMarketingDataSmartactivityForecastResponse(AlipayResponse):
def __init__(self):
super(KoubeiMarketingDataSmartactivityForecastResponse, self).__init__()
... |
pic1 = " _~_ "
pic2 = " (o o) "
pic3 = " / V \ "
pic4 = " /( _ )\ "
pic5 = " ^^ ^^ "
N = int(input("Введите число N в интервале (1,10)"))
print(pic1 * N)
print(pic2 * N)
print(pic3 * N)
print(pic4 * N)
print(pic5 * N) |
solns = {0: {
(1, 0, 0): 'R',
(0, 1, 0): 'P',
(0, 0, 1): 'S'
}}
N = 12
def gen():
for i in range(N):
solns[i + 1] = {}
for a in solns[i]:
for b in solns[i]:
if solns[i][a] < solns[i][b]:
solns[i + 1][a[0] + b[0], a[1] + b[1], a[2] + b[2]... |
import re
from itertools import groupby
start = "1113222113"
##for x in range(50):
## temp = ""
## nums = re.findall("(?<=(.))(?!\\1)", start)
## for num in nums:
## count = 0
## while start != "" and start[0] == num:
## start = start[1:]
## count += 1
## ... |
import math
N = int(input())
ans = 0
for i in range(1, int(math.sqrt(N))+1):
if(i == int(math.sqrt(i))*int(math.sqrt(i))):
ans = i
print(i*i) |
import sys
import numpy as np
from scipy import sparse
import time
import os
class ForwardChain(object):
def __init__(self, dict_path, train_path, save_path, rule_name):
self.train_path = train_path
self.ent_path = dict_path + '/entities.dict'
self.rel_path = dict_path + '/relations.dict'
... |
import re # praw
from django.shortcuts import render
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render, get_object_or_404
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
# for 404
from django.shortcuts import render_to_response
from django.template ... |
#!/usr/bin/python3
# Copyright © 2011-2015 Jakub Wilk <jwilk@jwilk.net>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the “Software”), to deal
# in the Software without restriction, including without limitation the rights
# to us... |
import torch
import torch.nn as nn
class NNModel(nn.Module):
def __init__(self, inputSize, outputSize, hiddenSize, activate=None):
super().__init__()
self.activate = nn.Sigmoid() if activate == "Sigmoid" else nn.Tanh() if activate == "Tanh" else nn.ReLU()
self.layer1 = nn.Linear(inputSize, ... |
def countholes(num):
holes_num = 0
for char in str(num):
if char in map(str, [0 ,4 ,6 ,9]):
holes_num += 1
elif char == '8':
holes_num += 2
return holes_num
|
from appintegration import AppIntegration
import requests
class OpenPhish(AppIntegration):
def check_url(self, d):
"""
Takes in a dictionary D with required key `url`. Downloads
phishing URL feed from openphish.com and checks if the
url is in the feed.
"""
try:
... |
from flask import Blueprint
from flask_restful import Api
from .resources.Welcome import WelcomeList, Welcome
api_bp = Blueprint('api', __name__)
api = Api(api_bp)
# Route
api.add_resource(WelcomeList, '/welcome')
api.add_resource(Welcome, '/welcome/<pk>') |
import FWCore.ParameterSet.Config as cms
process = cms.Process("Test")
process.load("FWCore.MessageService.MessageLogger_cfi")
process.load("Configuration.EventContent.EventContent_cff")
process.load("Configuration.StandardSequences.GeometryRecoDB_cff")
process.load("Configuration.StandardSequences.MagneticField_cf... |
import re
import sys
import csv
f = open("10005_pg1.dat", "r")
Roll_no1 = ''
Roll_no2 = ''
for line in f.readlines():
line = line.strip()
x = len(line)
if x > 0:
Sheet =line[1:40]
District_code = line[40:44]
Block_code = line[44:48]
School_code = line[48:52]
class_code = line[52:53]
Section_code = line... |
import sys
input = sys.stdin.readline
N = int(input())
string = input().replace('\n','')
lst = list(map(int, string.split(' ')))
def prime(n):
if n in [2,3,5,7]:
return True
elif (n != 2) & (n % 2 == 0):
return False
elif n%5 ==0 :
return False
else:
for ... |
# Generated by Django 3.1.7 on 2021-03-26 07:33
from django.db import migrations, models
import django.db.models.manager
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Product',
fields=[
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-11-07 09:21
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('my_blog', '0002_articles'),
]
operations = [
migrations.CreateModel(
... |
# finally 구문
try:
number_input_a = int(input("정수입력 > "))
print("원의 반지름 :", number_input_a)
print("원의 둘레 : {}".format(2*3.14*number_input_a))
print("원의 넓이 :", 3.14 * number_input_a * number_input_a)
except:
print("정수를 입력하지 않았습니다. 제대로 입력좀 해보세요.")
else:
print("예외가 발생하지 않았습니다.")
finally:
print... |
#!/bin/env python3
import selectors
import socket
import loopfunction
import logging
import queue
import maxthreads
class Log:
INDENTATION = 4
def __init__(self, *args_):
self.do = {'errors': False,
'enter': False,
'exit': False,
'args': False}... |
from sqlalchemy import func
from model import Bart, Business, Job, User, connect_to_db, db
from api_functions import get_stations, call_indeed, get_distance, get_company_info
from math import ceil
from server import app
import datetime
def load_stations():
"""Makes a call to BART API to get all SF station location... |
from django.test import TestCase
from django.conf import settings
from restclients.pws import PWS
from restclients.exceptions import InvalidRegID, InvalidNetID, DataFailureException
class PWSTestEntityData(TestCase):
def test_by_regid(self):
with self.settings(
RESTCLIENTS_PWS_DAO_CLASS='r... |
# Lambda Map Filter Generators
nums = [11, 22, 33, 44, 55]
result = list(map(lambda x: x+5, nums))
print(result)
squares = map(lambda a: a*a, [1,2,3,4,5])
# теперь squares = [1,4,9,16,25]
numbers = [1,2,3,4,5]
squares = map(lambda x: x*x, numbers)
# теперь squares = [1,4,9,16,25]
numbers = [1,2,3,4,5]
squ... |
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("https://www.amazon.com/s?k=goodnight+moon&ref=nb_sb_noss_1")
elem = driver.find_element_by_class_name("s-image")
val = elem.get_attribute('alt')
if val == 'Goodnight Moon':
print('Alt text is present')
else:
print('Alt text is missing or incorrect... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'qtcreatorFile/oneComment.ui'
#
# Created by: PyQt5 UI code generator 5.15.2
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 im... |
###############################################################################
# PyDial: Multi-domain Statistical Spoken Dialogue System Software
###############################################################################
#
# Copyright 2015 - 2017
# Cambridge University Engineering Department Dialogue Systems Grou... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class ShopCategoryConfigInfo(object):
def __init__(self):
self._id = None
self._is_leaf = None
self._level = None
self._link = None
self._nm = None
@propert... |
firstNumber = int(input("Enter an Integer: "))
if firstNumber >= 1 and firstNumber <= 99:
print("The integer is within 1 to 99")
elif firstNumber >=100 and firstNumber <= 199:
print("The integer is within 100 to 199")
else:
print("The integer is not within 1 to 199") |
from app import app
from models import db, User, Vocab, Word
db.drop_all()
db.create_all()
c1 = User(username="testuser5",
password="password5",
)
c2 = User(
username="testuser55",
password="password5",
)
d1 =Vocab(
title="Week 1",
username="testuser5"
)
d2 =Vocab(
title="Week 2",... |
import math
PI = math.pi
PI2 = math.pi * 2.0
PI_HALF = math.pi / 2.0
SAMPLES = 'samples'
RADIANS = 'radians' |
"""
Author: Lori White
Purpose: Calculate the net charge of an insulin based off of the pH.
python 3.9.6
coding: utf-8
"""
# store the human preproinsulin sequence in a variable called preproinsulin:
preproInsulin = open("Data_Files/preproinsulin_seq_clean.txt", "r").read()
# store the remaining se... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.