text stringlengths 8 6.05M |
|---|
#!/usr/bin/env python
# ----------------------------------------------------------
# Controller File for FSX
# ----------------------------------------------------------
from PySimConnect import SimConnect, DataDefinition
import FSXdef
import time
import logging
#This is code to import config file (config.py)
try:
... |
you="hello"
if ""in you:
robot_brain="Ican hear you"
elif "hello"in you :
robot_brain="hello duy"
elif "today":
robot_brain="february 16"
print(robot_brain) |
# _*_coding:utf-8_*_
__author__ = "Alex Li"
from conf import settings
import os
import yaml
import json
try:
from yaml import CLoader as Loader, CDumper as Dumper
except ImportError:
from yaml import Loader, Dumper
def print_err(msg, quit=False):
output = "\033[31;1mError: %s\033[0m" % msg
if quit:... |
import tkinter as tk
from tkinter.filedialog import askdirectory #窗口
from tkinter import StringVar #窗口
import tkinter.messagebox
import json
import base64
import urllib3
import os
import time
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
a_labname=''
log_result=''
... |
# coding = utf-8
class Person(object):
"""
This is about a person.
"""
def __init__(self, name, lang="python"):
self.name = name
self.lang = lang
self.email = "qiwsir@gmail.com"
def getName(self):
return self.name
def color(self, col):
... |
word = "Hello World"
print(word)
print(word[0])
len(word)
print(word.count('l'))
print(word.find('h'))
print(word.index("World"))
print(word[0:3])
print(word[:-3])
print(word[start:end])
word.startswith('H')
word.endswith('L')
word.replace("Hello", "Goodbye")
|
def karatusba(x,y):
if len(str(x)) == 1 or len(str(y)) == 1:
return x*y
else:
mid = max(len(str(x)),len(str(y))) // 2
a = x // 10**(mid)
b = x % 10**(mid)
c = y // 10**(mid)
d = y % 10**(mid)
_1 = karatusba(b,d)
_2 = karatusba((a+b),(c+d))
... |
from tfcgp.config import Config
from tfcgp.chromosome import Chromosome
import numpy as np
import tensorflow as tf
c = Config()
c.update("cfg/test.yaml")
def test_creation():
ch = Chromosome(5, 2)
ch.random(c)
assert len(ch.nodes) == c.cfg["num_nodes"] + 5
assert len(ch.outputs) == 2
def test_active(... |
def hello():
# type: () -> object
for a in range(5):
print ("hello world")
|
# Changed news to internship in this file
import graphene
from graphene_django.types import DjangoObjectType
# from bootcamp.news.models import News
from bootcamp.internship.models import Internship
from bootcamp.helpers import paginate_data
class InternshipType(DjangoObjectType): # Changed news to internship
"... |
import logging
from typing import Dict, List
_logger = logging.getLogger().getChild(__name__)
# each node should have the following property
# RTL
# port / wire mapping
# members
# when we create a new upper level instance
# the new instance will have direct wire connection with other instances
# because we have pus... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
from model.ServerClass import FtpServer
from conf.settings import *
import json
import struct
def entry():
server = FtpServer(SERVER_IP_PORT)
while True: # 链接循环
conn, address = server.phone.accept()
# 登陆验证
cmd = conn.recv(4)
if not ... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.8 on 2016-08-02 11:24
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('album_creator', '0001_initial'),
]
... |
# -*- coding: utf-8 -*-
"""
**************************************************************************
* IMAGE PROCESSING (e-Yantra 2016)
* ================================
* This software is intended to teach image processing concepts
*
* MODULE: Task1C
* Filename: getCellVal.py
* ... |
# -*- coding:utf-8 -*-
"""最小代价字母树"""
"""设有n堆沙子排成一排,其编号为1,2,3,…,n(n≤100)。每堆沙子有一定的数量,如下表
13 7 8 16 21 4 18 现在要将n堆沙子归并成一堆
状态方程 F[i][j] = min{f[i][k]+f[k+1][j]} + s[j] - s[i - 1]
其中F[i][j]表示从i到j的代价,s[j]表示到堆j的和
[输入格式]
n {表示沙子的堆数, 2<=n<=100}
a1 a2 … an {表示每堆沙子的数量,1<=Ai<=100}
[输出格式]
x {表示最小的归并总代价 }
输入样例:
7
13 7 8 16 2... |
# coding: utf-8
"""
Copyright 2015 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 required by applica... |
from django.db import models
from django.contrib.auth.models import (
AbstractBaseUser , BaseUserManager
)
from django.utils.safestring import mark_safe
class UserManager(BaseUserManager):
def create_user(self, email,first_name=None,last_name=None,password=None, is_active=True, is_staff=False, is_admin=False):... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('occ_survey', '0035_merge'),
]
operations = [
migrations.CreateModel(
name='LogButton',
fields=[
... |
# Solution of the challenge Ice Cream Parlor proposed on Hackerrank at https://www.hackerrank.com/challenges/missing-numbers/problem
import random
import re
import sys
# We should build a double for-loop over the array arr. As soon as the unique pair of indices has been found,
# the indices should be translated by 1... |
#Process osm tiles to a mkgmap template file
#nice java -jar ../mkgmap-r3337/mkgmap.jar --max-jobs=4 --drive-on-left --mapname=63290001 --description="FOSM map (C) fosm, OpenStreetMap" --copyright-message="CC BY-SA 2.0" --route --add-pois-to-areas --add-pois-to-lines --road-name-pois --index --gmapsupp -c template.arg... |
from typing import List
from .animal import Animal
class AnimalsRepository:
def __init__(self, conn):
self.table_name = "animals"
self.conn = conn
def find_animal(self, id_: str) -> Animal:
cur = self.conn.cursor()
cur.execute(f"SELECT id, species FROM {self.table_name} WHERE ... |
#!/usr/bin/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 cop... |
# Generated by Django 2.2.6 on 2019-11-02 13:40
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('work', '0003_test'),
]
operations = [
migrations.CreateModel(
name='ProgressQty',
f... |
from random import randint
play = True
while play:
board = []
for x in range(5):
board.append(["O"] * 5)
def print_board(board):
for row in board:
print(" ".join(row))
print('You have 5 turns to hit my battleship.')
print_board(board)
def random_row(board):
return randint(0, len(board)... |
import socket
import sys
import struct
import fcntl
import array
import threading
import time
import json
import multiprocessing
import datetime
import servo.servo as servo
import peltier.peltier as peltier
servo = ["", ""]
accel_gyro = ["", ""]
class server (threading.Thread):
def __init__(self, threadID, name,... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-03-20 19:10
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
depen... |
import pandas as pd
from sklearn.cross_validation import train_test_split
df_train = pd.read_csv('https://s3-us-west-2.amazonaws.com/fbdataset/train.csv')
df_test = pd.read_csv('https://s3-us-west-2.amazonaws.com/fbdataset/test.csv')
class PredictionModel():
def __init__(self, df, xsize=1, ysize=0.5, xslide... |
from .restrictions import *
from .to_sorted_ntriples import *
|
import RPi.GPIO as GPIO
import time
import os.path
import sys
frequencyHertz = 100
msPerCycle = 1000 / frequencyHertz
leftPosition = 2
rightPosition = 2
positionList = [leftPosition, rightPosition]
tmpfile = "/var/www/html/data/servo_run"
def run_cycle(i):
GPIO.setmode(GPIO.BOARD)
GPIO.setup(7, GPIO.OUT)
... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'main.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# 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 import QtCore, QtGui, ... |
if __name__ == '__main__':
import timeit
setup = '''
from Graph import Graph
t = [
[4, 4, 4, 4, 4],
[4, 2, 2, 2, 4],
[4, 2, 0, 4, 4],
[4, 2, 2, 4, 4],
[4, 4, 4, 6, 8],
[4, 4, 4, 4, 4],
[4, 4, 4, 4, 4],
[4, 4, 4, 4, 4],
[4, 4, 4, 4, 4],
[4, 4, 4, 4, 4],
[4, 4, 4, 4, 4]]
g = Graph()
g.from_matrix(t)
g.check_... |
from functools import wraps
def print_function_data(function):
@wraps(function)
def wrapper(*args, **kwargs):
print(f"You are calling {function.__name__} function")
print(f"{function.__doc__}")
return function(*args,**kwargs)
return wrapper
@print_function_data
def add(a,b):
'''This function takes numbers as... |
# -*- coding: utf-8 -*-
# @Time : 2019/5/16 3:15 PM
# @Author : Shande
# @Email : seventhedog@163.com
# @File : auth.py
# @Software: PyCharm
from functools import wraps
from flask import session, jsonify
def is_login(view_func):
"""检验用户的登录状态"""
@wraps(view_func)
def wrapper(*args, **kwargs):
... |
lim=int(input())
v1=0
v2=1
for i in range(0,lim):
print(v2,end=" ")
sum=v1+v2
v1=v2
v2=sum
|
from rsf.proj import *
from decimal import Decimal
'''
This script and data plot cross-correlogram in Figure 4 from the paper "Urban Near-surface Seismic Monitoring using Distributed Acoustic Sensing" by Gang Fang, Yunyue Elita Li, Yumin Zhao and Eileen R. Martin
To run this script, you need to install Madagascar soft... |
def minimumBribes(q):
# Write your code here
# print(q)
bribes = 0
check = 1
for x in range(len(q)-1, 0, -1):
# print(x)
if q[x] != x+1:
if q[x-1] == x+1:
bribes += 1
q[x-1], q[x] = q[x], q[x-1]
elif q[x-2]==x+1:
... |
"""
2. Написать функцию square, принимающую 1 аргумент — сторону квадрата,
и возвращающую 3 значения (с помощью кортежа): периметр квадрата,
площадь квадрата и диагональ квадрата.
"""
def square(a):
return (f'perimeter = {a * 4},'
f'square = {a **2},'
f'diagonal = {a * pow(2, 1/2)}'
... |
"""Encapsulates requests to challenge API"""
import requests
class ChallengeApi(object):
"""Performs requests to challenge API"""
BASE_URL = 'http://challenge.curbside.com'
SESSION_URL = BASE_URL + '/get-session'
START_URL = BASE_URL + '/start'
def get_session(self):
"""Retrieve a new ses... |
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import os
from jinja2 import Template
import requests
class MailGunTools(object):
def __init__(self, domain=None, api_key=None, root=None):
self.configured = False
if domain and api_key:
self.domain = ... |
import math
"""Point Class, used for targets and center points of FOV's"""
class Point:
"""Constructor, based on right_ascension and declination of the point.
To allow for "nice" distancing, we add 90 to the declination when we store
so that the range of values for the point's coordinates are [0, 36... |
import csv
import networkx as nx
from datetime import datetime, timedelta
def get_dubl(flights_number, time_in_city, multidigraph_check):
counter = {}
flights_for_every_name = {}
with open(f'new_result.csv', "r", newline="") as file:
reader = csv.reader(file)
for row in... |
#!/usr/bin/env python
# Copyright (c) 2012 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.
"""
Verifies that an Info.plist with CFBundleSignature works.
"""
import TestGyp
import sys
if sys.platform == 'darwin':
print "This te... |
list=["yogesh","vicky",'vaibhav']
if "vaibhav" in list:
print("yay,vaibhav is in the list")
a=[1,2,3]
if 2 in a:
print("Yes 2 is present") |
Python 3.9.0 (tags/v3.9.0:9cf6752, Oct 5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> import turtle
>>> t=turtle.Turtle()
>>> t.shape("turtle")
>>> t.pensize(5)
>>> t.color("red")
>>> t.fillcolor("blue")
>>> t.begin_fill()
>>> t.circl... |
from os import path
from game.base.enemy import Enemy
from game.constants import *
from game.entities.camera import Camera
from game.entities.blast import Blast
from game.util import *
class ButtaBomber(Enemy):
NB_FRAMES = 1
DEFAULT_SCALE = 10
def __init__(
self,
app,
scene,
... |
data_dir = '../data'
import os
import json
import pandas as pd
import itertools
import time
def get_valid_documents(thresh=100):
doc_read = {}
path = "{}/read/".format(data_dir)
for dirpath, subdirs, files in os.walk(path):
for f in files:
filename = dirpath+f
file = open(fil... |
import subprocess
import json
import argparse
import sys
import os
import pathlib
from dotenv import load_dotenv
load_dotenv()
username = os.getenv("USERNAME")
currpath = pathlib.Path(__file__).parent.absolute()
parser = argparse.ArgumentParser(description='Take name tag and return public ip with ssh login.')
parser.... |
from lxml import html
from bs4 import BeautifulSoup
import requests
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
import time
import datetime
import Util
def td(feature):
try:
return soup.find(text=feature).parent.parent.find('td').contents[0]
except Exceptio... |
import unittest
from katas.kyu_7.sum_up_the_random_string import sum_from_string
class SumFromStringTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(sum_from_string(
'In 2015, I want to know how much does iPhone 6+ cost?'), 2021)
def test_equals_2(self):
self.... |
from aiohttp import web
from ClientsFactory import get_vk_api_client, get_loop, get_aiohttp_client
from Message import Message
CALLBACK = "/callback"
routes = web.RouteTableDef()
vk = get_vk_api_client()
event_loop = get_loop()
client = get_aiohttp_client()
@routes.post('/callback')
async def hello(request):
... |
from django.db import models
from django.utils.translation import gettext_lazy as _
from .choices import LoyalityPrograms
class Profile(models.Model):
GENDERS = [("M", "Male"), ("F", "Female"), ("U", "Undefined")]
class YearInSchool(models.TextChoices):
FRESHMAN = "FR", _("Freshman")
SOPHOMO... |
from model.vehicle_handling.vehicle_movement_handler import vehicle_movement_handler
import global_variables as gv
from model.vehicle_handling import off_screen_handling
from model.direction import Dir
class Vehicle:
def __init__(self, index, movement_pattern, x, y, w, l, acceleration, max_speed, handling, max_ha... |
"""This is a model"""
import psycopg2
def database(app):
"""This is a function"""
con = psycopg2.connect(
"dbname='stack_over_flow'\
user='dennis' password='12345'\
host='localhost'")
cur = con.cursor()
# create a table
cur.execute(
"CREATE TABLE IF NOT EXISTS\
... |
# Generated by Django 2.2.6 on 2020-07-30 07:17
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Articles',
fields=[
('id', models.BigAutoFi... |
######-11-ud120:lesson12-4-######
"""
fraction = 0.
if (poi_messages !="NaN") or (all_messages !="NaN") :
fraction = float(poi_messages)/all_messages
else :
fraction = 0.
return fraction
"""
######-10-ud120:lesson12-3-######
"""
if from_emails:
ctr = 0
while not from_poi and ctr < len(from_ema... |
def user_prompt():
ans = input('Enter a number: ')
try:
float(ans)
except:
import sys
sys.exit('NaN')
return 'Your number is {}'.format(ans) |
# -*- coding: utf-8 -*-
import uuid
from django.core.exceptions import ValidationError
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
# Create your models here.
def max_words(words=400):
def validator(value):
wslen = len(value.split())
if wslen > words:... |
# -*- coding: utf-8 -*-
f = open("/Users/TomonotiHayshi/GitHub/My Research/Rakuten-fake-/all.csv","w")
for i in range(51):
f1 = open("/Users/TomonotiHayshi/GitHub/My Research/Rakuten-fake-/"+str(i)+".csv")
i = 0
for line in f1:
if i > 1:
f.write(line)
i += 1
f1.close()
f.clo... |
import argparse
import os
import subprocess
from copy import copy
import yaml
IGNORE_KEYS = ["repository", "code_path", "python_bin", "experiment_group"]
"""
Script that takes an experiment definition file and creates a new folder for it.
It then downloads the parser code at the given commit hash and passes the para... |
import pygame
class MyFace(pygame.sprite.Sprite):
def __init__(self, image_file, location):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(image_file)
self.rect = self.image.get_rect()
self.rect.left, self.rect.top = location
self._x = 1
self._y... |
from django.contrib import admin
from .models import Job, JobBox
admin.site.register(Job)
admin.site.register(JobBox)
# Register your models here.
|
import requests
import json
import time
import base64
import hmac
import hashlib
# hard stuff, check this:
# https://gist.github.com/jordanbaucke/5812039
class Bitfinex:
def __init__(self, conf):
self.conf = conf
self.apiKey = self.conf.bitfinex_api_key
self.secret = self.conf.bitfinex_se... |
# L1 = ['Hello', 'World', 18, 'Apple', None]
# L2 = [x.lower() for x in L1 if isinstance(x,str) ]
# print(L2)
#
#
# g = (x % 2 for x in range(10))
#
#
# def fac(n):
# if n == 1 or n == 0:
# return 1
# else:
# return n * fac(n - 1)
#
#
# def triangles():
# # res = [1]
# n = 0
# while... |
#coding:utf-8
#!/usr/bin/env python
class invite:
base = [str(x) for x in range(10)] + [ chr(x) for x in range(ord('A'),ord('A')+26)] + [ chr(x) for x in range(ord('a'),ord('a')+26)]
@staticmethod
def generateCode(accountid):
"""
生成邀请码
"""
code_base = 916132832 - accountid
text_code = invite.dec2... |
import os
import json
from itertools import product
xdg_data_home = (os.environ.get('XDG_DATA_HOME') or
os.path.join(os.path.expanduser('~'), '.local', 'share'))
macht_data_dir = os.path.join(xdg_data_home, 'macht')
def grid_to_dict(grid):
tiles = []
tile_base = 0
for row_idx, col_idx in... |
import sys
import string
reu_path = "C:/Users/Daway Chou-Ren/Documents/REU/"
filename = open(reu_path + sys.argv[1], 'r')
output = open("C:/Users/Daway Chou-Ren/Documents/REU/federalistOutput/" + sys.argv[2], 'w')
# will be a dictionary with tuples as keys, integers as values
pairs = dict()
total_count =... |
#!/usr/bin/python3
import sys
from datetime import datetime
import timeit
import math
result01 = 0
result02 = 0
squarenumber = 0
hsquarenumber = 0
spiral = []
spiral2 = []
x = 0
y = 0
n = 0
calc_adjsum = 0
#old solution for part01
def part01():
global result01
global iinput
squarenumber = math.floor(math.... |
import selectiveSearch as ss
import gtcfeat as gtc
import numpy as np
import cv2
# extract feature(default filter is hog)
def extractFeature(img):
return gtc.getFeat(img, algorithm='hog')
# Perform selective search and return candidates
def processing(cv_img, clf, nonFiltered):
# perform selective search
... |
from MyList import LinkedList
from employee import Employee
def initial_display():
print ("***CS172 PAYROLL PROGRAM***")
print ("a. Add New Employee")
print ("b. Calculate Weekly Wages")
print ("c. Display Payroll")
print ("d. Update Employee Hourly Rate")
print ("e. Remove Employee from Payrol... |
#program for infinite loop
print 'Example of infinite loop'
n=input('Enter A Number:')
i=1
while (i<=n):
print i,
|
#
# run_cythonOU.py
# cythonOU
#
# Created by nicain on 5/18/10.
# Copyright (c) 2010 __MyCompanyName__. All rights reserved.
#
################################################################################
# Preamble:
################################################################################
# Import ne... |
import time
import sys
import socket
import base64
import json
from threading import Thread
SERVER_PORT=11117
HOST_IP='127.0.0.1'
SERVER_IP='172.30.1.10'
BUF_SIZE=8192
class Shell(Thread):
def __init__(self, server):
Thread.__init__(self)
self.server=server
def run(self):
while True:
print('select me... |
import unittest
from katas.kyu_6.find_the_parity_outlier import find_outlier
class FindOutlierTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(find_outlier([2, 4, 0, 100, 4, 11, 2602, 36]), 11)
def test_equals_2(self):
self.assertEqual(find_outlier([160, 3, 1719, 19, 11, ... |
from tkinter import *
from random import randint
from math import sqrt
# ___Globals___
lit_x = []
lit_y = []
vec_v1 = ''
vec_v2 = ''
vec_v3 = ''
c1 = 'black'
c2 = 'black'
o_x = 960
o_y = 500
colors = ['green', 'blue', 'red', 'orange', 'violet', 'pink', 'indigo', 'yellow']
class Vector(object):
... |
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation
import matplotlib.patches as patches
from LucasKanade import LucasKanade
# write your script here, we recommend the above libraries for making your animation
frames = np.load('../data/carseq.npy')
n = frames.shape[2]
rect = np.zeros(... |
from typing import Optional
from config.model import DockConfig
from eddn.journal_v1.model import JournalV1 as EddnJournalV1
from summary.model import DockSummary, Station
class DockHandler:
def __init__(self, config: DockConfig, target: DockSummary) -> None:
self.config = config
self.journal = t... |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^participant_team/(?P<pk>[0-9]+)/invite$', views.invite_participant_to_team,
name='invite_participant_to_team'),
url(r'^participant_team/(?P<participant_team_pk>[0-9]+)/challenge$', views.get_participant_team_challenge_list,
... |
#!/usr/bin/python
def my_function(fname):
print(fname + "1")
my_function("http://example.com/")
|
import sys
from PIL import Image
def flip(image):
width, height = image.size
imgDup = image.copy()
oldCoords = image.load()
newCoords = imgDup.load()
for y in range(height):
for x in range(width):
newCoords[x,y] = oldCoords[width-x-1,y]
return imgDup
if len(sys.argv) <= 1:
... |
#!/usr/bin/env python
import code
import readline
import rlcompleter
import os
from novaclient import client
import openstack_variables
osvars = openstack_variables.get()
nclient = client.Client(
2.0,
osvars['OS_USERNAME'],
osvars['OS_PASSWORD'],
osvars['OS_TENANT_NAME'],
osvars['OS_AUTH_URL'],
... |
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
from main_window_layout import Ui_MainWindow
app = QApplication(sys.argv)
window = QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(window)
window.show()
sys.exit(app.exec_())
|
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import timeit
import jk_simpleipcb
binFilePath = "../../SimpleIPCB/ExampleUTF8Echo/bin/Release/ExampleUTF8Echo.exe"
b = jk_simpleipcb.SimpleInterProcessCommunicationBridge()
b.launchComponentProcess("MyFancyComponent", binFilePath, "str", "str")
NUMBER_OF_REPEATS = 100... |
# 9개의 서로 다른 자연수가 주어질 때,
# 이들 중 최댓값을 찾고
# 그 최댓값이 몇 번째 수인지를 구하는 프로그램을 작성하시오.
arr = []
for i in range(9):
arr.append(int(input()))
maxnum = max(arr)
print(maxnum)
print(arr.index(maxnum)+1)
|
# coding: utf-8
# # Problem 8: Balancing Act
#
# "Balancing a seesaw with Python data structures."
# **Background.** Suppose there is a plank of wood pivoted to a point so that it acts as a seesaw. There are weights attached to it at different locations. This module deals with predicting the seesaw behaviour given ... |
# Solution of the challenge LongestWord proposed on Coderbyte at https://coderbyte.com/challenges
"""
After converting the input to a list, we should remove all the characters which are not letters. Therefore,
the words are stored into a list. Then, after storing each word length into a list, we should get the index ... |
import autodisc as ad
class IsFiniteBinaryObjectClassifier(ad.core.Classifier):
@staticmethod
def default_config():
default_config = ad.core.Classifier.default_config()
default_config.r = 1
default_config.tol = 0.1
return default_config
def __init__(self, config=None, **... |
__author__ = 'Elisabetta Ronchieri'
import datetime
import time
import os
import unittest
import inspect
from tstorm.utils import config
from tstorm.commands import ping
from tstorm.commands import protocol
from tstorm.commands import ls
from tstorm.commands import mkdir
from tstorm.commands import cp
from tstorm.co... |
import argparse
import datetime
import json
import math
from collections import defaultdict
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
from steemapi.steemnoderpc import SteemNodeRPC
from steemutils import *
from arg_parse import *
def get_posts(rpc, beg_block, end_b... |
'''
author: Zitian(Daniel) Tong
date: 09:05 2019-05-19 2019
editor: PyCharm
email: danieltongubc@gmail.com
'''
from flask import request, render_template, Blueprint, redirect, url_for, session
from models.alert import Alert
from models.item import Item
from models.store import Store
from models.us... |
from os import name
from django.urls import path
from. import views
app_name = "processer"
urlpatterns = [
path("", views.Index.as_view(), name="index"),
path("<int:pk>/", views.Detail.as_view(), name='detail'),
path("<int:pk>/image/", views.getFrameViaAjax, name="ajax_image"),
] |
import os
FILE = "Indicators.csv"
indicator = {}
ID = []
with open(FILE, 'r') as file:
for line in file:
colonne = line.rstrip().split(';')
if colonne[2] == "oui":
ID.append((colonne[0], colonne[1]))
print(ID)
for id, name in ID:
command = f"curl \"http://ec2-54-174-131-205.compu... |
import os
import pytest
def take_screenshot(driver, name):
# first make the required dir
os.makedirs(
os.path.join("screenshot", # path where to make directory
os.path.dirname(name) # name of new dir
),
exist_ok=True # no error if already exists
)
# now save t... |
from classes import Datum
from classes import Person as P
x = Datum(-1.1, 0.08)
print(x)
paolo = P("Paolo")
paolo.display()
print(paolo)
|
import pandas as pd
import random
df = pd.read_excel(r'C:\Users\ruttu\Desktop\CurrencyData File.xlsx')
df.to_dict()
def qp(c):
list2 = []
listmain = []
k=1
file.write("Name :\n\n")
file.write("Registration Number :\n\n")
file.write("\t\t\t\t\tQuestion Paper\n")
for j in range(c,c+... |
#!/usr/bin/env python
# coding=utf-8
"""
The main entry point.
Invoke as `python_module_project' or `python -m python_module_project'.
"""
import sys
def main():
try:
from .cli import main as cli_main
sys.exit(cli_main())
except KeyboardInterrupt:
sys.exit(1)
if __name__ == "__ma... |
# Credit to http://www.jesshamrick.com/2011/05/18/an-introduction-to-classes-and-inheritance-in-python/
# for exercises
class Pet(object):
def __init__(self, name, species):
self.name = name
self.species = species
def getName(self):
return self.name
def getSpecies(self):
... |
score = input("Enter Score: ")
s = float(score)
if s > 1:
print ("Input Error")
elif s < 0:
print ("Input Error")
elif s < 0.6:
print ("F")
elif s < 0.7:
print ("D")
elif s < 0.8:
print ("C")
elif s < 0.9:
print ("B")
elif s < 1:
print ("A")
|
import numpy as np
''' read the files'''
def getlist(filename):
read_list = []
with open(filename) as f:
for line in f:
line_data = line.strip()
line_data = line.split(',')
read_list.append(line_data)
return read_list
''' modify the last term'''
def mdflt(lst):
outlst = [[] for _ in range(len(lst))]
f... |
import numpy as np
import matplotlib.pyplot as plt
#function that we differentiate
def func(t, y):
x = y[0]
xdot = y[1]
return np.array([xdot, -x])
class Euler:
def __init__(self, func, x0, time_zero, time_end, step):
self.func = func #function
self.x0 = x0 #function zero pl... |
import os
import flask
from solr_feeder import config
from solr_feeder.endpoints import endpoint
__all__ = ['create_application']
# Create the Flask application
def create_application(run_mode=os.getenv('FLASK_ENV', 'production')):
# Create application
application = flask.Flask(__name__)
application.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.