text stringlengths 8 6.05M |
|---|
import pandas as pd
from IPython.display import display
from ipywidgets import Latex
from bqplot import *
from bqplot.market_map import MarketMap
data = pd.read_csv('data_files/country_codes.csv', index_col=[0])
country_codes = data.index.values
country_names = data['Name']
gdp_data = pd.read_csv('data_files/gdp_per_... |
From bcb0a961df77a0d7a3b2e7e58fac3e283b5ef8c4 Mon Sep 17 00:00:00 2001
From: Mohamad Safadieh <self@mhmd.sh>
Date: Wed, 5 May 2021 12:38:26 -0400
Subject: [PATCH] added sshpass_prompt, ssh_transfer_method, timeout
---
sshjail.py | 42 ++++++++++++++++++++++++++++++++++++++++++
1 file changed, 42 insertions(+)
diff -... |
import os
import askmanta
import json
from dateutil import parser as dateparser
from askmanta.environment import client
class Phase(object):
# phase name = "job name: phase i"
def __init__(self, i, spec, directive):
self.i = i
self.spec = spec
self.directive = directive
self.t... |
import tensorflow as tf
import numpy as np
import os
import sys
from PIL import Image, ImageOps
from utils import batch_norm, get_shape, lkrelu
class Generator(object):
def __init__(self, inputs, is_training, ochan, stddev=0.02, center=True, scale=True, reuse=None):
self._is_training = is_training
... |
from flask_restful import Resource
from flask import request
from flask_jwt_extended import jwt_required
from auth.password_manager import change_password, forgot_password
from exception import MyException
class PasswordChange(Resource):
@classmethod
@jwt_required()
def put(cls):
data = request.ge... |
# -*- coding: utf-8 -*-
class Solution:
def validPalindrome(self, s):
def _validPalindrome(s, first, last):
while first < last:
if s[first] != s[last]:
return False
first, last = first + 1, last - 1
return True
first, las... |
from pyrosetta import *
from pyrosetta.rosetta.core.select.residue_selector import ResidueIndexSelector
from pyrosetta.rosetta.core.simple_metrics.metrics import RMSDMetric
from pyrosetta.rosetta.core.simple_metrics.per_residue_metrics import PerResidueRMSDMetric
from pyrosetta.rosetta.core.scoring import rmsd_atom... |
import GlobalSettings
import os
from PyQt5 import QtWidgets, Qt, uic, QtCore
from functools import partial
from CSPRparser import CSPRparser
import re
import platform
import traceback
import math
from annotation_functions import *
#global logger
logger = GlobalSettings.logger
# Class Name: genLibrary
# this class is ... |
# coding=utf-8
"""
test exec *.sql with python
Desc:*
Maintainer: wangfm
CreateDate: 2016-11-09 17:56:28
"""
#cmd login
# mysql -h10.1.0.56 -uroot -pSanbu@123456 -P13306
import MySQLdb
from subprocess import Popen,PIPE
def execFileSql(*args, **kwargs):
"""
Function: execFileSql()
D... |
from django.conf.urls import url
from django.urls import path
from . import views
user = views.UserInfo.as_view({
"get":"list"
})
urlpatterns=[
url(r'^userinfo/$',user,name="user")
] |
import numpy
import cv2
import heapq
from motion import *
grid_line_x = 7
grid_line_y = 7
m=600/(grid_line_x-1)
n=600/(grid_line_y-1)
# m=480/(grid_line_x-1)
# n=540/(grid_line_y-1)
a1=0
b1=0
a2=0
b2=0
a3=0
b3=0
a4=0
b4=0
clipcount=0
###############################
# trims contours accoding to given area
#
#
#
def area... |
class Solution:
def minimumTime(self, time: List[int], totalTrips: int) -> int:
def check(cur:int)-> bool:
cnt = 0
for i in range(len(time)):
cnt += cur // time[i]
if cnt >= totalTrips:
return True
... |
from unittest import TestCase
from Calculator import Calculator
class TestCalculator(TestCase):
def setUp(self):
self.calculator = Calculator()
def test_add(self):
result = self.calculator.add(10, 20)
expected = 30
self.assertEqual(expected, result)
|
from PIL import Image
import glob
import os
def main():
label = ['Atelectasis','Cardiomegaly','Consolidation','Edema','Effusion','Emphysema','Fibrosis','Hernia',
'Infiltration','Mass','Normal','Nodule','Pleural_Thickening','Pneumonia','Pneumothorax']
for i in label:
path = r'C:/U... |
# -*- coding: utf-8 -*-
__author__ = 'Damir'
from itertools import imap
from operator import itemgetter
from helpers import get_A_B
from avl_tree import AVLTree
def calc_Y(x, a, b):
x = float(x)
a = float(a)
b = float(b)
return a*x+b
ALL_XS = list()
ALL_COORDINATES = list()
SORT_COORDINATES = list(... |
import requests
import sys
def menu():
run_menu = True
menu = ("\n---------------------\n"+
"Pesquisa CEP (Webservice) "+
"\n---------------------\n"+
cep = input("Digite o CEP : ")+
"(0) Sair \n"+
"-------------------")
while(run_menu):
print (menu)
if len(cep) == 8:
... |
# -*- coding: utf-8 -*-
import spidercomm as common
from bs4 import BeautifulSoup
# get all tags a from a single url
def a_links(url_seed,attrs={}):
html = common.download(url_seed)
soup = BeautifulSoup(html,'html.parser')
alinks= soup.find_all('a',attrs)
return alinks
def crawled_page(crawled_url):
... |
preco = float(input('Digite o preço do produto:'))
descconto = preco * 0.95
print('O valor do producot com desconto é de: R${}.'.format(descconto))
|
def average(lst):
total = 0
for value in lst:
total += value
return total / len(lst)
def nestedAverage(lst):
total = 0
totalLength = 0
for nestedList in lst:
totalLength += len(nestedList)
for value in nestedList:
total += value
return total / total... |
import sys, os, urllib2, tweetstream, json
from datetime import datetime as dt
CONSUMER_KEY = ""
CONSUMER_SECRET = ""
ACCESS_TOKEN_KEY = ""
ACCESS_TOKEN_SECRET = ""
stream=tweetstream.SampleStream
start=dt.now()
with stream(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN_KEY, ACCESS_TOKEN_SECRET) as stream:
while 1=... |
from napalm import get_network_driver
import json
def connection(host, username, password):
driver = get_network_driver('ios')
iosvl2 = driver(host, username, password)
iosvl2.open()
print("connected to :", host)
return iosvl2
def getconfig(host, username, password):
iosvl2 = connection... |
# 数字转换为字符列表,倒序生成新的字符列表,再根据符号生成倒序数字,并判断是否大于intmax或小于intmin
class Solution:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
sign = [1,-1][x < 0]
rst = sign * int(str(abs(x))[::-1])
return rst if -(2**31)-1 < rst < 2**31 else 0
class Solu... |
import numpy as np
from .utils import *
def get_positive_input(n1=40, n2=30, mean_distance=0.8):
"""
Constructs two groups with n1 observations in first and n2 observations in second.
:param n1:
:param n2:
:param mean_distance: distance of means in two gorups
:return:
"""
y = [2 * np.... |
from SupportClasses.WordEmbedder import WordEmbedder
import numpy as np
class SentenceEmbedder:
def __init__(self):
self.wordEmbedder = self.__initWordEmbedder()
def __initWordEmbedder(self):
return WordEmbedder()
def getVector(self, sentence):
sentenceVectors = []
for wo... |
# Generated by Django 2.2 on 2019-04-12 15:53
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('yohbiteapp', '0009_auto_20190412_0935'),
]
operations = [
migrations.RenameField(
model_name='district',
old_name='state',
... |
# Generated by Django 3.2.5 on 2021-07-26 20:34
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('clinic_app', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Patient',
fields=[
('id... |
import random
def display_game():
user_name = input("What is your name? ")
print("Hello " + user_name)
print("Well, " + user_name + " if you want to go out alive you have to guess the number between 1-50")
random_number = random.randint(1, 50)
while True:
user_number = int(input("What is... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from head import *
from db_env import *
class MssqlConnection:
def __init__(self,):
#: 服务器地址
self.host = db_conn_info['HOST']
#: 数据据库名称
self.db_name = db_conn_info['DATABASE']
#: 登录用户
self.user = db_conn_info['USER']
... |
import openpyxl
import modules.peripherals.churches as churches
import modules.peripherals.buildings as buildings
#reads data from a .xlsx file in the correct format and returns a list of churches
def input(filename):
workbook = openpyxl.load_workbook(filename)
worksheet = workbook['Churches']
churchList ... |
# Generated by Django 3.1.2 on 2020-11-01 16:02
import accounts.models
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('a... |
# Reading file into a list.
menuConfigurationFile = "bankMenu.cfg"
menuConfigurationList = []
with open(menuConfigurationFile) as menuObject:
for line in menuObject:
lineWithNewLine = line.replace('\n', '')
menuConfigurationList.append(lineWithNewLine)
for line in menuConfigurationList:
print(line)
print(menuCo... |
# -*- coding: utf-8 -*-
import time
from .common import ApiTestBase, compat_mock, compat_urllib_parse
class TagsTests(ApiTestBase):
"""Tests for TagsEndpointsMixin."""
@staticmethod
def init_all(api):
return [
{'name': 'test_tag_info', 'test': TagsTests('test_tag_info', api)},
... |
import datetime
import pytest
from ethtx.models.decoded_model import AddressInfo, Argument
from ethtx.models.objects_model import BlockMetadata, TransactionMetadata, Call, Event
from ethtx.models.semantics_model import ParameterSemantics, ContractSemantics
FAKE_TIME = datetime.datetime(2020, 12, 25, 17, 5, 55)
@py... |
#copy methond of dictionary
a={1:'bhavya',2:'komal',3:'khushi'}
b=a.copy()
print(b)
|
# Generated by Django 2.1.3 on 2018-11-06 14:45
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0032_auto_20181107_0225'),
]
operations = [
migrations.AddField(
model_name='employee',
name='phone',
... |
# -*- coding:utf-8 -*-
import math
import web
def GetRankByHashInternal(assetid,limitnum) :
html = web.GetHeader("rank")
html = html + '<div name="address" align="center">\n'
html = html + '<br/><br/>\n'
html = html + '<h2>'+ _("Rank") +'</h2>\n'
html = html + '<div class="container">\n'
count = web.collec... |
from blog.models import Contact
from django.utils import timezone
from django.shortcuts import render, redirect
from blog.forms import ContactForm
def contact_new(request):
if request.method == "POST":
form = ContactForm(request.POST)
if form.is_valid():
contact = form.save()
return redirect('post_list')
e... |
from abc import ABC # Abstract Base Class
import copy
class Term(ABC):
"""
Evaluates to the term's value.
If there are variables (identifiers) in the term, a name-value binding shall be inputted.
"""
def eval(self, binding: dict = None):
raise NotImplementedError()
def get_term_of(se... |
"""
什么是线程锁?
目的是将一段代码锁住,一旦获得锁权限,除非释放线程锁,否则其他任何代码都无法获得锁权限
为什么需要线程锁
由于多线程同时在完成特定的操作时,由于并不是原子操作,所以在完成操作的过程中可能会被打断,去做其他的操作。
可能会产生脏数据
例如,一个线程读取变量n,n初始值为1,然后n++,最后输出n
当访问n++后,被打断,由另外的线程做同样的工作,这时n被加了两次,所以最后n等于2,而不是1
所以说需要给n++操作加上锁变成原子操作,直到结束再释放线程锁
"""
from threading import Thread, Lock, currentThread
f... |
inputs = [
'hotkey01',
'hotkey82',
'hotkey30',
's',
'hotkey21',
'hotkey00',
'hotkey60',
'hotkey41',
'hotkey80',
'hotkey90',
'sMineral',
'hotkey10',
'hotkey91',
'hotkey71',
'hotkey81',
'hotkey40',
'hotkey31',
'hotkey12',
'sBase',
'hotkey62',... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 23 18:53:54 2017
@author: root
"""
from brian2 import *
from numpy import *
from matplotlib.pyplot import *
from helpers import *
ca()
timelength = 200
Sig = zeros([timelength])
for ind in range(timelength):
if ind > 30:
Sig[ind] = 1.... |
from operator import truediv
def representation(zone_pop, rep_req):
rep_total = 0
result = []
population_total = sum(zone_pop)
for population in zone_pop:
# rep = (population / population_total) * rep_req # Python 3
rep = truediv(population, population_total) * rep_req
# curre... |
"""
__author__ ='Nijesh'
"""
import os
import pandas as pd
import numpy as np
import json
import re
from itertools import izip_longest
class ValidationError(Exception):
def __init__(self,message):
super(ValidationError, self).__init__(message)
def __repr__(self):
return ... |
from flask import Flask, request
from multiprocessing import Process
import RPi.GPIO as GPIO
#Alexa
from flask_ask import Ask, statement
import spidev
import time
#Twilio
from twilio.twiml.messaging_response import MessagingResponse
from .notifications import send_sms
from .notifications import send_email
# for tes... |
# Copyright (c) 2014 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.
{
'targets': [
{
'target_name': 'target',
'product_name': 'Product',
'type': 'shared_library',
'mac_bundle': 1,
'sources': [
... |
#MINI SHOPPING CLI PROGRAM
import time
import random
print("WELCOME TO MY CART SHOP")
item = ["KITCHEN-SET","BLAZERS","WILD CRAFT SCHOOL BAGS","BEDSHEETS"]
cost = ["Rs 3600","Rs 4000","Rs 1250","900"]
x = []
l = []
print()
for i,j in zip(item,cost):
print(i,"=",j)
print()
choice = 'y' or 'n'
count = 0
while... |
def print_sum():
global a,b
a=100
b=200
result = a + b
print(f"print_sum() 내부 : a = {a}, b = {b}, result = {result}")
a=10
b=20
result = a+b
print(f"print_sum() 이전 : a = {a}, b = {b}, result = {result}")
print_sum()
result = a+b
print(f"print_sum() 외부 : a = {a}, b = {b}, result = {result}") |
# Exercício 4.1 - Livro
n1 = int(input('Digite um número: '))
n2 = int(input('Digite outro número: '))
if n1 > n2:
print(n1)
if n2 > n1:
print(n2)
|
import pkg_resources
def iter_bundles():
for entry in pkg_resources.iter_entry_points("trytls.bundles"):
yield entry.name
def load_bundle(name):
for entry in pkg_resources.iter_entry_points("trytls.bundles", name):
return entry.load()
return None
|
#Sorting
"Numpy has a function called sort() which will sort an array"
import numpy as np
arr = np.array([1,4,3,1,2,51,12,33,5])
print(np.sort(arr))
"This worls doe all data types and dimensioanl arrays"
"In a multidimensional array it will sort the elements in each array" |
# coding=utf-8
__author__ = 'Insolia'
from bank.models import *
import csv
from transliterate import translit
from django.contrib.auth.models import Group
import random
from bank.constants import *
import string
def get_pd(leng):
a = random.sample(string.printable[:62], leng)
s = ''
for c in a:
... |
# dict_to_csv.py
import csv
dict_sample = {'name': 'LinuxHint', 'city': 'CA', 'education': 'Engineering'}
with open('data.csv', 'w') as f:
for key in dict_sample.keys():
f.write("%s, %s\n" %(key, dict_sample[key])) |
import matplotlib
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from ipykernel.pylab.config import InlineBackend
from jedi.api.refactoring import inline
from imblearn.over_sampling import SMOTE
from imblearn.over_sampling import BorderlineSMOTE
from sklearn.linear_model ... |
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from textwrap import dedent
import pytest
from pants.backend.codegen.thrift import dependency_inference
from pants.backend.codegen.thrift.dependency_inference import (
InferThriftDep... |
"""
Dividing a set into two equal length subsets,
that one subset is always greater than the other.
"""
class Solution:
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
for num in nums2:
... |
"""Derivatives of the MSE Loss."""
from math import sqrt
from torch import einsum, eye, normal
from backpack.core.derivatives.basederivatives import BaseLossDerivatives
class MSELossDerivatives(BaseLossDerivatives):
"""Derivatives of the MSE Loss.
We only support 2D tensors.
For `X : [n, d]` and `Y :... |
#coding=utf8
import sys
import os
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *
from graph_reco import *
class MyBrowser(QWidget):
def __init__(self, parent = None):
super(MyBrowser, self).__init__(parent)
self.createLayout()
self.createConn... |
#!/usr/bin/env python
# encoding: utf-8
# @author: Zhipeng Ye
# @contact: Zhipeng.ye19@xjtlu.edu.cn
# @file: calculate_ngram3.py
# @time: 2020-01-14 01:27
# @desc:
import os
import re
import main
import math
import traceback
import codecs
import sys
sys.stdout = codecs.getwriter('utf-8')(sys.stdout.detach())
class ... |
import json
import bs4
import requests
res = requests.get('https://en.wikipedia.org/wiki/List_of_hobbies')
res.raise_for_status()
soup = bs4.BeautifulSoup(res.text, "html.parser")
activity_list = []
with open('sports-list.json') as fp:
sports_list = json.load(fp)
categories = soup.select('.div-col')
categories... |
# square
def print_square(n):
print('square')
for i in range(n):
print('*' * n, end='')
print()
# triangle
def print_triangle(n):
print()
print('triangle')
start_point = 2
triangle_height = n // 2
if n % 2 != 0:
triangle_height = (n + 1) // 2
... |
from tkinter import *
from LoginPage import *
import tkinter
root = Tk()
root.title('路障跟踪与维修系统')
#root.wm_iconbitmap('x.ico')
LoginPage(root)
root.mainloop()
|
# sb贪心即可
MAXN = 2**31
class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
first, second = MAXN, MAXN
for item in nums:
if item <= first:
first = item
elif item <= second:
second = item
else:
return... |
#from http://stackoverflow.com/a/3076636/5620182
class Shape(object):
def __new__(cls, *args, **kwargs):
if cls is Shape: # <-- required because Line's
description, args = args[0], args[1:] # __new__ method is the
if description == "It's flat": ... |
# coding=UTF-8
fila = [10, 20, 30, 40, 50]
fila.append(60)
print(fila)
print(fila.pop(0))
print(fila)
print(fila.pop(0))
print(fila)
print(fila.pop(0))
print(fila)
#Pilha
def ola():
print("Olá, ")
mundo()
def mundo():
print("mundo!")
def olamundo():
ola()
olamundo()
|
import glob
import re
import random
import numpy as np
import cv2
import os
from torch.utils.data import Dataset
from data.data_label_factory import label_factory
def read_video(filename):
frames = []
if not os.path.isfile(filename):
print('file not found')
cap = cv2.VideoCapture(filename)
whi... |
import pygame
class Grafika(object):
def menu(self):
pygame.display.set_caption('MasterMind')
self.tlo = pygame.image.load("Obrazy/kkk.png")
self.ramka = pygame.image.load("Obrazy/ramka_2.png")
size = self.screen.get_size()
self.srodek_x = int(size[0] / 2)
self.scr... |
from datetime import datetime
from flask import Flask
from flask import jsonify
from flask_babel import Babel
import date_helper
import month_helper
app = Flask(__name__)
app.config.from_pyfile('mysettings.cfg')
babel = Babel(app)
@app.route("/")
def index():
return '<h2>Bienvenido al index</h2>'
@app.route("/... |
# -*- coding: utf-8 -*-
import sys,os,json
config = json.loads(open(os.path.dirname(os.path.dirname(__file__)).replace('\\','/')+'/config.json').read())
ip = config.get('public_disk')
sys.path.append('//%s/LocalShare/py27/Lib'%ip)
sys.path.append('//%s/LocalShare/py27/Lib/site-packages'%ip)
from flask import Flask,rend... |
from lex import lex, lex_print
from token_parser import parse, parse_print
from run import run
import sys
from time import time
import threading
from typing import List
from node import Node
import argparse
def remove_comments(lines: List[List[str]]) -> List[List[str]]:
'''
This function rem... |
import numpy as np
import tensorflow as tf
from data.data_utils import *
class TextRNN(object):
"""文本分类,TextRNN模型"""
def __init__(self, config):
self.config = config
# 三个待输入的数据
self.input_x = tf.placeholder(tf.int32, [None, self.config.max_sen_len], name='input_x')
self.input... |
''' Power Function in python '''
def power_func(int_x, int_y):
''' Raise x to the power of y '''
if int_y == 1:
return int_x
else:
return int_x * power_func(int_x, int_y - 1)
|
q = int(input())
while q:
q -= 1
n, m = [int(x) for x in input().split()]
sum1 = 0
for x in range(1, n+1):
temp = 1
for y in range(1, m+1):
temp = ((temp%1000000007) * ((x + y)%1000000007))%1000000007
# print(temp)
print(temp)
sum1 = ((sum1%1000000007) + (temp%1000000007))%1000000007
# s... |
import re
import os
import sys
import flask
import base64
import torchvision.transforms as transforms
from io import BytesIO
from PIL import Image
# Append pix2pix filepath to app.py
module_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'pix2pix')
if module_path not in sys.path:
sys.path.append(m... |
from classes.Action import Action
from classes.Cluster import Cluster
from classes.Scooter import Scooter
from classes.Depot import Depot
from classes.State import State
from classes.Vehicle import Vehicle
from classes.Location import Location
from classes.events.Event import Event
from classes.World import World
from ... |
"""
copy:只复制深层对象的引用
deepcopy:复制深层对象的本身
"""
import copy
a = [1,2,["a", "b"]]
c = copy.copy(a) # 浅拷贝
d = copy.deepcopy(a) #深拷贝
print(c)
print(d)
a.append(5)
print("---------")
print(a)
print(c)
print(d)
a[2][1] = "x"
print("---------")
print(a)
print(c)
print(d) |
#!/usr/bin/python3
""" WriteFile Module """
def write_file(filename="", text=""):
""" Function that writes a string to a
text file (UTF8) and returns the number
of characters written
"""
with open(filename, 'w') as f:
return f.write(text)
|
"""
A prime number (or a prime) is a natural number greater than 1 that has
no positive divisors other than 1 and itself.
The property of being prime is called primality. A simple but slow method of
verifying the primality of a given number is known as trial division. It
consists of testing whether n is a multip... |
#!/opt/local/bin/python2.7
import cv2
line_length = 40
def main():
cv2.namedWindow("Scanner alignment", cv2.CV_WINDOW_AUTOSIZE)
capture = cv2.VideoCapture(1)
while True:
cv2.waitKey(10)
_,img = capture.read()
img = cv2.flip(cv2.transpose(img),1)
height, width, depth = img... |
"""
剑指 Offer 45. 把数组排成最小的数
输入一个非负整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。
"""
"""
简单说一下解题思路,第一个反应就是将数组里所有的数都给拆成1位数,把所有的0都拿出来剩余的数从小到大排序,然后把所有的0在第2位插入。
但是这个方法有点想当然了,比方说[20,1]这个数组,我们会返回最小值102,但是这个最小应该是120,于是提出方法2。
"""
def minNumber(nums):
tempList = sorted(list(map(int,list("".join(map(str,nums))))))
tempIndex = 0
... |
"""
=================
Metrics Utilities
=================
This module contains shared utilities for querying, parsing, and transforming
simulation data to support particular observations during the simulation.
"""
from collections import ChainMap
from string import Template
from typing import Union, List, Tuple, Dict... |
character_name = "John" # it is the variable we can create
character_age ="35"
x = 35 #you can also create a integer data type
is_Male = False #you can also create boolean values as data type
print("There once was a man name " + character_name + ",")
print("he was " + character_age + " years old.")... |
from django.shortcuts import render
from django.conf import settings
from django.db import IntegrityError
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.response import Response
from .serializers import Us... |
import sys
import boto3
import uuid
from cfn_keypair_provider import KeyPairProvider
from secrets import handler
def test_defaults():
request = Request("Create", "abc")
r = KeyPairProvider()
r.set_request(request, {})
assert r.is_valid_request()
assert r.get("Name") == "abc"
assert r.get("Publ... |
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 8 18:42:08 2021
@author: gabri
"""
import urllib.parse
import requests
main_api = "https://www.mapquestapi.com/directions/v2/route?"
key = "QvrROLQbeGnXmsgha3A7O4tiYI5XHBUo"
#The "while True" construct creates an endless loop.
while True:
orig = inpu... |
from django.urls import include, path
from . import views
urlpatterns = [
# UI Bundle
path('', views.IndexView.as_view(), name='index'),
# Check if no-spa
path('no-spa/', include('wolves.ui.urls')),
# Rest are rest api
path('', include('wolves.api.urls'))
] |
from config import Config
from website import create_app
app = create_app(Config)
app.run()
|
"""
Created on 2017-10-26
class: RL4SRD
@author: fengyue
"""
# !/usr/bin/python
# -*- coding:utf-8 -*-
from treelib import Tree
import copy
from utils import normalize
from utils import compute_bleu_rouge
"""
num : number of visit time
once_num : nothing
Q : value funtion calculate value of now-node
... |
def matrixInit():
"""
The function to initialize a matrix from the user.
Returns:
Matrix: A matrix
"""
R = int(input("Enter the number of rows:"))
C = int(input("Enter the number of columns:"))
matrix = []
print("Enter the entries row wise:")
for i in ... |
x=float(input("x= "))
if((x>0)and((x%2)!=0)):
print("positive odd number")
elif((x>0)and(x%2)==0):
print("positive even number")
elif ((x<0)and((x%2)!=0)):
print("negative odd number")
elif((x<0)and((x%2)==0)):
print("negative even number")
else:
print("zero number") |
from main import Handler
from models.user import User
from models.post import Post
from main import blog_key
class NewPost(Handler):
def get(self):
if self.user:
title = 'New Post'
self.render(
"newpost.html",
title=title
)
e... |
from peewee import *
db = PostgresqlDatabase('flashcards', user='postgres', password='', host='localhost', port=5432)
class BaseModel(Model):
class Meta:
database = db
class Flashcard(BaseModel):
front = CharField()
back = CharField()
times_correct = IntegerField()
times_missed = IntegerF... |
import torch
from torch.autograd import Variable
from PIL import Image
from torchvision import transforms
import json
from model.gram_efficientnet import GramEfficientNet
use_gpu = torch.cuda.is_available()
net_name = 'efficientnet-b0'
image_size = GramEfficientNet.get_image_size(net_name)
img = Image.open('img.jpg... |
import csv
import sys
import os
import time
import re
import json
from collections import Counter
try: # Python 3.x
from urllib.parse import quote as urlencode
from urllib.request import urlretrieve
except ImportError: # Python 2.x
from urllib import pathname2url as urlencode
from urllib import urlret... |
import subprocess
import os
import shutil
import re
import tempfile
from behave import *
import parse
use_step_matcher("cfparse")
@parse.with_pattern(r"finally\s+")
def parse_word_finally(text):
"""Type converter for "finally " (followed by one/more spaces)."""
return text.strip()
register_type(finally_=pa... |
for i in range(10): # from 0 to 9 i or smt else doesn't matter
print('Hello i ',i) # in i all other must be other but after can be i too
for k in range(10):#100
print("Hello from K",k)
for j in range(10): #1000
print("Hi from j",j)
for i in range(3):
name = input(f'Вы {i} в оче... |
from steam import get_games
# should mock this out but let's call feedparser for real
# for a feedparser mocking see the AttrDict (advanced) Bite 50's tests
games = get_games()
def test_assert_number_of_entries():
assert len(games) == 30
def test_all_list_items_are_namedtuples():
assert all(isi... |
from spack import *
import sys,os
sys.path.append(os.path.join(os.path.dirname(__file__), '../../common'))
from scrampackage import write_scram_toolfile
class ValgrindToolfile(Package):
url = 'file://' + os.path.dirname(__file__) + '/../../common/junk.xml'
version('1.0', '68841b7dcbd130afd7d236afe8fd5b949f017... |
import math
import csv
from operator import itemgetter
import random
import statistics
import copy
import simulation_data1
chargingTimeSimulation = []
unallocatedVehiclesSimulation = []
chargingTimeMinDistance = []
unallocatedVehiclesMinDistance = []
def Simulation (simulationData) :
#{
vehicles... |
import json
from collections import ChainMap
file_name = 'south-park.json'
final_file = 'lines-by-character.json'
with open(file_name, "r") as read_file:
data = json.load(read_file)
all_characters = list(set([line['character'] for line in data])) # code smell
all_characters.sort()
lines_by_character = []
for c... |
# -*- coding: utf-8 -*-
# @Time : 2018/9/6 12:41
# @Author : WJH
# @Email : 1226778264@qq.com
# @File : spider_papers2.py
# @Software: PyCharm
import os
import re
import urllib
import requests
# get web context
def get_context(url):
header = {"User-Agent": "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.