text
stringlengths
38
1.54M
#!/usr/bin/env python # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import argparse import builtins import math import os import random import shutil import time import warnings import sys sys.path.insert(0, './') import torch import torch.nn as nn import torch.nn.parallel import torch.backend...
""" ---------------------------------------- AppendLastNToFirst ------------------------------------------ You have been given a singly linked list of integers along with an integer 'N'. Write a function to append the last 'N' nodes towards the front of the singly linked list and returns the new head to the list. #...
#!/Users/sche/anaconda/bin/python3 import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt import matplotlib.dates as dates import matplotlib.ticker as ticker from read_data import read_data # set style sheet #plt.style.use("ggplot") sns.set_style("white") #sns.set_style("darkgrid"...
def num_check(password, num_numbers=1): ''' (str, int) -> bool Contains a number of number characters. Have it optionally take a num_numbers arg >>> check_num('Woops') False >>> check_num('Woops33', 2) True >>> check_num('Woops33', 6) False ''' num_count = 0 for ...
# -*- coding: utf-8 -*- """ Created on Wed Sep 30 15:50:00 2015 @author: sponsar """ import urllib2,re,sys,time browser=urllib2.build_opener() browser.addheaders=[('User-agent', 'Mozilla/5.0')] infile=open("in.txt") link=infile.readline().strip() infile.close() count=0 page=1 while True: url=link+'/ref=cm_cr_p...
import pygame # 1 pygame.init() pygame.display.set_caption("pong game") # set up game window SIZE = (600,600) BG_COLOR = (8, 113, 142) canvas = pygame.display.set_mode(SIZE) clock = pygame.time.Clock() paddle_image = pygame.image.load("assets/paddle.png") ball_image = pygame.image.load("assets/ball.png") x1 = 0 y1 =...
import sys import os sys.path.append(r"Y:\tool\ND_Tools\DCC") sys.path.append( r"Y:\tool\ND_Tools\DCC\ND_AssetExporter\pycode\maya_lib\on_maya") sys.path.append(r"Y:\tool\ND_Tools\DCC\ND_AssetExporter\pycode") sys.path.append(r"Y:\tool\ND_Tools\DCC\ND_AssetExporter\pycode\maya") import maya.cmds as cmds from imp i...
import lecturescode # the print(__name__) function over here prints the the name of file imported indicating that the function being called here is not declared in this file instead it is imported lecturescode.main() lecturescode.mostimpfunction()
from Acquisition import aq_parent from z3c.relationfield.relation import RelationValue from Products.CMFPlone.interfaces import IPloneSiteRoot from Products.CMFCore.utils import getToolByName from plone.dexterity.utils import createContentInContainer from ..interfaces import IStory from ..interfaces import IIterati...
from ..base import BaseCommand class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument( "--plain", action="store_true", help="use the plain python shell.", ) parser.add_argument( "--interface", choice...
from drawLine import ViewPort,bresenham,drawLine import sys,random from graphics import * ''' 100 100 50 0 100 -100 0 -50 -100 -100 -50 0 -100 100 0 50 ''' def drawPoly(vertices,win,color='white'): vert = vertices.copy() vert+=[vert[0]] for i in range(len(vert)-1): x1,y1,x2,y2 = *vert[i],*vert[i+1] #print(win,co...
import math import random from helpers import * def print_points(points): print(len(points)) for point in points: print(point) def generate_d_set(): points_x_range = (-1000.0, 1000.0) points_number = 1000 vector_a = Point(-1.0, 0.0) vector_b = Point(1.0, 0.1) f = create_line_fun...
# Author: Jingping.zhao # Exception: 0x20 - 0x2F import json import traceback from pymysql.err import MySQLError from app import database from app import application from framework.lib.common import OrcDefaultDict from framework.database import ClsTableLib from framework.database.sequence import OrcTableIDGe...
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' @author: lizhaohui @contact: lizhaoh2015@gmail.com @file: block.py #block类,用于随机生成地面块 @time: 2019/3/16 22:05 ''' import random import cocos import os class Block(cocos.sprite.Sprite): def __init__(self,position): super(Block,self).__init__('black.png') ...
import csv from datetime import datetime import server.models as models from server.app import db def add_school_weather(school_name, file_path): school = models.School(name=school_name) db.session.add(school) db.session.commit() reader = csv.DictReader(open(file_path)) for row in reader: ...
import requests from bs4 import BeautifulSoup from python_utils import converters def get_parsed_page(url): return BeautifulSoup(requests.get(url).text, "lxml") def top5teams(): home = get_parsed_page("http://hltv.org/") count = 0 teams = [] for team in home.find_all("div", {"class": "vsbox", })...
# -*- coding: utf-8 -*- """ @Time : 2020/6/2 14:47 @Author : QDY @FileName: 1011. 在 D 天内送达包裹的能力_二分查找.py 传送带上的包裹必须在 D 天内从一个港口运送到另一个港口。 传送带上的第 i 个包裹的重量为 weights[i]。每一天,我们都会按给出重量的顺序往传送带上装载包裹。 我们装载的重量不会超过船的最大运载重量。 返回能在 D 天内将传送带上的所有包裹送达的船的最低运载能力。 示例 1: 输入:weights = [1,2,3,4,5,6,7,8,9,10], D ...
#! /usr/bin/env python3 # -*- coding: utf-8 -*- def lastOfUs(amount, step) : guys = [i for i in range(1, amount+1)] while len(guys) > 1 : fakeStep = step while fakeStep > len(guys) : fakeStep -= len(guys) guys = guys[fakeStep:] + guys[:fakeStep-1] #print(guys) return guys[0] a = int(input("Enter amount o...
""" This script computes the amount of training data in each of the 3 training sections """ import csv from utils import get_training_files fnames = get_training_files(base_path="src", section="Attempt7") g1 = 0 g1t = 0 g2 = 0 g2t = 0 g3 = 0 g3t = 0 for i in range(max(fnames) + 1): try: with open(f"src\...
#!/usr/bin/env python """utilities for larch """ from __future__ import print_function import re import sys import os from .symboltable import Group def PrintExceptErr(err_str, print_trace=True): " print error on exceptions" print('\n***********************************') print(err_str) #print 'PrintEx...
args = [0, 1, 4, 9] def unpacking_Argument_List(a,b,c,d): print("a = "+ str(a)) print("b = " + str(b)) print("c = " + str(c)) print("d = " + str(d)) def packing_Arguments_List(*data): newList = list(data) newList[1]= "Asal" print(newList) unpacking_Argument_List(*args) packing_Arguments_L...
from django.urls import path from .views import fetchJsonData urlpatterns = [ path('', fetchJsonData, name='jsonUrl') ]
# Generated by Django 3.2.2 on 2021-05-14 07:57 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('compiler', '0001_initial'), ] operations = [ migrations.AddField( model_name='problem', name='seo_title', ...
import numpy as np from PIL import ImageGrab import cv2 import time from time import sleep from key import * def key_press(): print('\n') PressKey(SHIFT) PressKey(B) sleep(1) ReleaseKey(B) ReleaseKey(SHIFT) PressKey(Y) sleep(1) ReleaseKey(Y) ...
""" Module to read data streams per line. Supported inputs: - raw - json - json timeseries (contains "date" and "value" field) Can produce the following generators: - raw lines - json objects - (date,value) tuples Can produce the following output as non-generator: - pandas """ import json ...
from django.db import models from django.contrib.auth.models import User # Create your models here. class Tweet(models.Model): text = models.TextField() user = models.ForeignKey(User, on_delete=models.CASCADE)
# Generated by Django 2.2.17 on 2021-06-22 15:25 from django.db import migrations, models import django.db.models.deletion import modelcluster.fields class Migration(migrations.Migration): initial = True dependencies = [ ("taxonomy", "0005_service_contact_reasons"), ("people", "0024_auto_20...
import project_functions as func import time from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support.expected_conditions import presence_of_element_located from selenium.webdriver.firefox.options import Opti...
from jsk_teleop_joy.joy_plugin import JSKJoyPlugin import imp try: imp.find_module("geometry_msgs") except: import roslib; roslib.load_manifest('jsk_teleop_joy') from geometry_msgs.msg import Twist import tf import rospy import numpy import math import tf import numpy import time class JoyCmdVel(JSKJoyPlugin): ...
import wx from wx.lib.pubsub import Publisher import oo_dialogbox class tab4(wx.Panel): def __init__(self, parent): ww=wx.Panel.__init__(self, parent, style=wx.BORDER_SUNKEN) #static text widget---------------------------------------------------------- font = wx.Font(10, ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('gtfgy', '0011_auto_20150218_1623'), ('mjdxvqk', '0009_auto_20150218_1623'), ] operations = [ migrations.RemoveField(...
import pygame from settings import * class Ghost(pygame.sprite.Sprite): def __init__(self, game, x, y): pygame.sprite.Sprite.__init__(Ghost, self) self.game = game self.imageForward = pygame.transform.scale(pygame.image.load("ghostSprite/ghostForwardMid.png").convert_alpha(),(TILESIZE,TILES...
import re import os, sys # local try: # need when 「python3 gfzs/markup.py」 if __name__ == "__main__": # https://codechacha.com/ja/how-to-import-python-files/ sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__)))) from multibyte import Multibyte import colo...
""" 다양한 수로 이루어진 배열이 있을 때 주어진 수들을 M번 더하여 가장 큰 수를 만든다. 단, 배열의 특정한 인덱스(번호)에 해당하는 수가 연속해서 K번을 초과하여 더해질 수 없다. N=배열의 크기 M=숫자가 더해지는 횟수 [2,4,5,4,6]이 있을 때 M=8이고 K=3이면 결과는, 6+6+6+5+6+6+6+5 = 46이다. """" """ --- 내가 풀어본 것 --- from random import randint array = [] N = randint(2,1000) M = randint(1,10000) K = randint(1,M) # array...
import argparse import cv2 import numpy as np from moviepy.video.io.ffmpeg_tools import ffmpeg_extract_subclip import Util import subprocess # compute true diff of two frames based on their histograms def histogram_diff(f1,f2): h_bins = 50 s_bins = 60 histSize = [h_bins, s_bins] h_ranges = [0, 180] s_ranges = [0,...
#!/usr/bin/python # ============================================================================== # Author: Tao Li (taoli@ucsd.edu) # Date: Jun 3, 2015 # Question: 069-Sqrt # Link: https://leetcode.com/problems/sqrtx/ # ============================================================================== # Implemen...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render from django.contrib.auth.models import User from django.http import Http404 from .serializers import CampaignSerializer from rest_framework.views import APIView from rest_framework.response import Response from rest_f...
from import_export import resources from apps.mascota.models import Mascota class MascotaResource(resources.ModelResource): class Meta: model = Mascota import_id_fields= ['nombre']
from dateutil.relativedelta import relativedelta from datetime import datetime, timedelta def get_datefilters(): now = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0) from_to = dict() from_to['Hoje']=[ 'now()::date', '''now()::date + interval '1 day' - interval '1 minute' ''', no...
"""wxPython-specific property classes""" from basicproperty import basic, common from basictypes.wxtypes import colour, pen, font from basictypes import enumeration ## DATA-model properties class ColourProperty(basic.BasicProperty): """wxColour property""" baseType = colour.wxColour_DT friendlyName = "Colour" cla...
import matplotlib.pyplot as plt # y value series variance = [1,2,4,8,16,32,64,128,256] bias_squared = [256,128,64,32,16,8,4,2,1] # zip() combines two data series to tuples total_error = [x + y for x, y in zip(variance, bias_squared)] # x values xs = range(len(variance)) # we can make multiple calls to plt.plo...
import flask from keg_mail.views import ( LogStatusWebhook as LogStatusWebhookBase, WebhookBase, ) km_blueprint = flask.Blueprint('keg_mail', __name__) class NoOpWebhook(WebhookBase): blueprint = km_blueprint url = '/noop-webhook' class LogStatusWebhook(LogStatusWebhookBase): blueprint = km_bl...
#!/usr/bin/env python # _*_ coding:utf-8_*_ # author:jinxiu89@163.com # create by thomas on 18-1-27. from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy()
import numpy as np from PIL import Image class LSB: """ Implements encryption and decryption functionality for Least Significant Bit Stenography. For encryption, the color components (Red-Green-Blue) of every pixel of a given image are taken and the last 2 bits of every component are replaced...
import pickle import pandas as pd import chardet import codecs class Test: def __init__(self): pass def test_set_attr(self, name, value): self.__setattr__(name, value) def __str__(self): res = '' for each in self.__dict__: res += f'{each}:{self.__getattribute_...
# Generated by Django 3.0 on 2021-06-09 10:32 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('App', '0039_orders'), ] operations = [ migrations.AddField( model_name='cart', name='amount', field=models...
from bitstring import * class SHA_1: def __init__(self): self.mod = pow(2, 32) self.K_list = [BitArray("0x5a827999"), BitArray("0x6ed9eba1"), BitArray("0x8f1bbcdc"), BitArray("0xca62c1d6")] self.H = [BitArray("0x67452301")...
import os import cv2 import time import pandas as pd import numpy as np from PIL import Image import torch import torchvision import torchvision.transforms as T from torchvision.models.detection.faster_rcnn import FastRCNNPredictor from torch.utils.data import DataLoader, Dataset import matplotlib.py...
#!/usr/bin/env python from gnuradio import gr from gnuradio import blocks from gnuradio import digital import string_to_list from frame_sync import frame_sync class top_block(gr.top_block): def __init__(self): gr.top_block.__init__(self) ################################################## ...
def part1(nums): for n1 in nums: for n2 in nums: if n1 + n2 == 2020: return n1 * n2 def part2(nums): for n1 in nums: for n2 in nums: for n3 in nums: if n1 + n2 + n3 == 2020: return n1 * n2 * n3 def main(): file ...
# File: ex_8.5-is_prime.py # Date: 2019-12-20 # Author: "Hannes Thiersen" <hannesthiersen@gmail.com> # Version: 0.1 # Description: # A positive whole number n > 2 is prime if no number between 2 and sqrt(n) # (inclusive) evenly divides n. Write a program that accepts a vlaue o...
from .track import track_page_view def page_view_tracking_middleware(get_response): def middleware(request): response = get_response(request) if response.status_code == 200: track_page_view(request) return response return middleware
#This converts european lift numbers to US numbers, I didnt even know this was a thing inp = input ("European Floor? ") #this asks the user to enter a floor number usf = int (inp) +1 # this converts the string for European Floor to an integer so we can add 1 to it print ("US floor", usf) # displays the result # in...
# 97. k-meansクラスタリング # 96の単語ベクトルに対して,k-meansクラスタリングをクラスタ数k=5として実行せよ. import numpy as np import dill from sklearn.cluster import KMeans def save(file_name, data): with open(f"./dills/{file_name}", 'wb') as f_out: dill.dump(data, f_out) def load(file_name): with open(f"./dills/{file_name}", 'rb') as ...
import matplotlib.pyplot as plt import math data = open('pions.f14', 'r') k = 0 heading_id = 'UQMD' pions = [] pions_plus = [] pions_minus = [] pions_0 = [] strings = [] resonances = [] number_of_events = 100000 for line in data: line = line.split(' ') temp_l = [] k += 1 for j in line:#delete '0' and ...
# See README from microprediction import MicroReader import random EXAMPLE_STREAMS = ['electricity-lbmp-nyiso-west.json','electricity-load-nyiso-nyc.json'] def random_name(): """ Choose a random name of a stream """ mr = MicroReader() names = [n for n in mr.get_stream_names() if '~' not in n ] retu...
from django.db import models from django.utils.translation import gettext_lazy as _ class SentMessage(models.Model): name = models.CharField(max_length=255, verbose_name=_('Имя')) phone = models.CharField(max_length=255, verbose_name=_('Телефон')) email = models.CharField(max_length=255, verbose_name=_('Em...
# ----------------------------------------------------------- # Second Attempt # Runtime: 48 ms, faster than 78.44% of Python3 online submissions for Two Sum. # Memory Usage: 14.4 MB, less than 34.18% of Python3 online submissions for Two Sum. # Comment: NA # ----------------------------------------------------------- ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Parselmouth - Tree Builder Ad providers such as DFP employ complex tree structures to organize zones or adunits within their system. The TreeBuilder class helps build and manipulate collections of objects with these tree structures. """ # Future-proof from __future_...
import logging from django.core.management.base import BaseCommand from django.core.exceptions import ValidationError from django.db.utils import IntegrityError, DataError from dashboard.models import Contract from utils.django.models import defaults_dict from ._excel_contract import ExcelContract logger = logging.g...
# -*- coding: utf-8 -*-s def exer1(): n = 1 h = 100 s = 100 while n <= 10: h = h / 2 s += h * 2 n = n + 1 print("小球共经过: " + str(s) + "米") print("小球反弹高度: " + str(h) + "米") def exer2(): n = 1 a = 1 sum = 0 while n <= 20: a *= n sum += a ...
import json import datetime import time import os import dateutil.parser import logging logger = logging.getLogger() logger.setLevel(logging.DEBUG) # --- Helpers that build all of the responses --- def elicit_intent(session_attributes, message): return { 'sessionAttributes': session_attributes, '...
import argparse import pandas as pd import requests from bs4 import BeautifulSoup import locale from joblib import Parallel, delayed import logging from pathlib import Path def get_gcd_single_pair(pair): locale.setlocale(locale.LC_ALL, 'en_US.UTF8') if len(pair) != 6: return None org = pair[:3] ...
from dataclasses import dataclass from position import Position, EarthPosition @dataclass(eq=True, frozen=False) class Location: name: str position: Position def __post_init__(self): if self.name == "": raise ValueError("Location name cannot be empty") hong_kong = Location("Hong Ko...
import matplotlib.pyplot as plt import numpy as np from keras import backend as K from keras.datasets import mnist from keras.layers import Dense, Dropout, Flatten from keras.layers.convolutional import Conv2D, MaxPooling2D from keras.models import Sequential from keras.utils import np_utils K.set_image_dim_ordering('t...
import sys import json import torch import os import numpy as np from pycocotools.cocoeval import COCOeval import matplotlib.pyplot as plt from pycocotools.coco import COCO def dump_to_json(): pass def eval(anno_json, result_json, anno_type): annType = ['segm', 'bbox', 'keypoints'] annTyp...
import sys, math for line in sys.stdin: n = int(line) if n == 0: break print(int(math.floor(math.sqrt(n))))
import os import time last_served = 0 def get_last_frame(data): global last_served # does it exist at all? if not os.path.exists("/home/xilinx/projects/videoSELECT.txt"): return {"video-error": "No active video"} with open("/home/xilinx/projects/videoSELECT.txt") as f: sel = f.read(...
from db import nova_conexao from mysql.connector.errors import ProgrammingError exclui_tabela_email = """ drop table if exists emails """ exclui_tabela_grupos = """ drop table if exists grupos """ try: with nova_conexao() as conexao: try: cursor = conexao.cursor() cursor.ex...
from django.db import models from django.utils import timezone from phone_field import PhoneField # Create your models here. class Participant(models.Model): name = models.CharField(max_length = 40) phone_number = models.CharField(max_length = 40) college = models.CharField(max_length = 100, blank=True, nu...
#経路変更の閾値1.5,2,2.5でグラフに出した、さらに日本語対応した #buffer、patternの順で回せるようにした #これはSSGW(0)に接続している全ノードからの通信量が1.2倍になった場合 import statistics import math import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl import random import fairnessIndex mpl.rcParams['font.family'] = 'AppleGothic'#漢字を出せるようにする、数という漢字は対応していない ...
import threading import time def action(arg): time.sleep(2) print('time is %s\t'%(arg)) theads = [] for i in range(5): t = threading.Thread(target=action,args=(i,)) t1 = threading.Thread(target=action,args=(i,)) theads.append(t) theads.append(t1) for i in theads: i.setDaemon(True) i.st...
#! /usr/bin/env python # -*- encoding: utf-8 -*- # import BeautifulSoup import mechanize import httplib, urllib import sys, re from config import * #TODO: error handling # (1) if on_date - today > 7, inform user def main(): page = submit_form() prices = parse_page( page.read(), TRIGGER ) if any( [ p <= max_price...
# import pandas, numpy import numpy as np import pandas as pd import matplotlib.pyplot as plt import itertools from collections import Counter from tigerml.eda import Analyser # Create the required data frames by reading in the files df=pd.read_excel('SaleData.xlsx') df1=pd.read_csv("imdb.csv",escapechar='\\') df2=pd....
#!/usr/bin/env python3 import os import re from depthcharge import Depthcharge, Console, OperationFailed, log from depthcharge.monitor import Monitor def setup(): # Optional: Launch a console monitor so we can # keep an eye on the underlying operations. We # use a terminal-based monitor here. mon = Mo...
class Question: options = [] answers = [] level_of_ques = [] topic_name = [] prompt = [] def __init__(self): pass def addQuestion(self,topic_name,level_of_ques): statement = input("Enter question: ") Question.prompt.append(statement) Question.topic_name.ap...
import sys # SOURCE: collaborated with John Gauthier # implementation ideas largely from Danny Yoo of UC Berkley on hashcollision.org class RedBlackTree: class Node(): def __init__(self, key=None,color='red'): self.right = None self.left = None self....
import os import cv2 from PIL import Image import imagehash import glob def extract_images(vloc): # Read the video from specified path cam = cv2.VideoCapture(vloc) try: # creating a folder named data if not os.path.exists('data'): os.makedirs('data...
def solution(prices): """ Goal: is to make as many transactions as possible to make max profit Method: we have to buy low and sell high, then we check every pair prices and make transaction """ maxProfit = 0 for i in range(1, len(prices)): if prices[i] > prices[i-1]: maxProfit += prices[i] - price...
import numpy as np import io import sys import codecs from collections import defaultdict, Counter from user import User import glob import cPickle as pickle import os from twitter_dm.utility.general_utils import read_grouped_by_newline_file from collections import defaultdict from textunit import TextUnit from const...
import numpy as np def benjamini_hochberg(pvalues, FDR=0.05): pvalues = np.array(pvalues) if pvalues.size == 0: return np.nan sorted_values = np.sort(pvalues[np.logical_not(np.logical_or(np.isnan(pvalues), np.isinf(pvalues)))], axis=None) critical_values = np.arange(1, len(sorted_values) + 1) ...
from __future__ import unicode_literals from django.db import models class CourseManger(models.Manager): def validate(self,data): if (len(data['name']) <5 or len(data['desc']) <15 ): return False return True # Create your models here. class Course(models.Model): name = models.Char...
from django.contrib.auth.tokens import PasswordResetTokenGenerator class TokenGenerator(PasswordResetTokenGenerator): def _make_hash_vlaue(self, user, timestamp): return (str(user.pk)+str(timestamp)+str(user.is_active)) account_activation_token = TokenGenerator()
# uncompyle6 version 3.7.4 # Python bytecode 3.7 (3394) # Decompiled from: Python 3.7.9 (default, Aug 31 2020, 07:22:35) # [Clang 10.0.0 ] # Embedded file name: opponent.py # Compiled at: 2020-08-28 21:03:54 # Size of source mod 2**32: 6992 bytes import math from collections import defaultdict import time, random rand...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """DHT 温度湿度センサー.""" import logging from datetime import datetime import Adafruit_DHT as DHT from db import MongoDB class Dht(MongoDB): """DHT IO.""" def __init__(self): """イニシャライザ.""" super().__init__() # センサー self.PIN = 4 ...
''' Created on Jun 27, 2016 @author: KatherineMJB ''' class Incrementer: import tensorflow as tf def __init__(self, base): self.base = base def run(self, arr): ret = [] for i in range(0, len(arr), 2): carry, place = self.ex(arr[i], arr[i+1]) ...
import logging def setLogger(logg): logg.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') ch = logging.StreamHandler() ch.setFormatter(formatter) logg.addHandler(ch) return logg
# Generated by Django 3.0.7 on 2020-07-02 05:04 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('cart', '0006_auto_20200702_1307'), ] operations = [ migrations.AlterField( model_name='orderite...
import plotly import plotly.offline as offline import plotly.graph_objs as go import json import sys def plot(input, output): dataFile = open(input, 'r') data = json.load(dataFile) # set up relevant data arrays labels = data["distanceHistogram"]["labels"] vals = data["distanceHistogram"]["values"] # construct ...
primes = [2] solution = 2 for x in xrange(3, 2000000, 2): for number in primes: if x % number == 0: break if x % number != 0: print "%d\r" % x solution += x primes.append(x) print solution
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve. # # 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 applic...
#!/usr/bin/env python """ Origin: http://networkx.github.com/documentation/latest/examples/drawing/giant_component.html This example illustrates the sudden appearance of a giant connected component in a binomial random graph. Requires pygraphviz and matplotlib to draw. """ # Copyright (C) 2006-2008 # Aric Hag...
from datetime import datetime from typing import Optional from codemate.block import Block from codemate.exceptions import SaveFileError def generate_header() -> str: """ Generates a file header. Returns: str: The generated header of a file. """ syntax = " Warning generated file ".center...
#!/usr/bin/env python # coding=utf-8 import hashlib import imghdr from webapp.web import BaseHandler from model import dbapi MAX_FILE_SIZE = 5000000 #upload file size setting < 5MB class UploadHandler(BaseHandler): def check_xsrf(self): if self.check_xsrf_cookie() == False: self.redirect("...
import asyncio from functools import wraps def shielded(func): """ Protects a coroutine from cancellation. """ @wraps(func) async def wrapped(*args, **kwargs): return await asyncio.shield(func(*args, **kwargs)) return wrapped
#!/usr/bin/env python #%% import basis_set_exchange as bse import click # %% @click.command() @click.argument("element") def find_compatible_basissets(element): found = {} Z = bse.lut.element_Z_from_sym("N") for basis in bse.get_all_basis_names(): try: db = bse.get_basis(basis, element)...
# *Exercise 8* # Write a function that takes an ARRAY and prints the item in the array in reversed order. This should be # done recursively! (edited) def item_in_reverse_order(array, size_of_array): # me = "hi" reversed_item = [] current_item = size_of_array if size_of_array <= 0: return ...
#!/usr/bin/python3 import ROOT as rt from ROOT import gPad, gROOT, gStyle, TFile from ROOT import TGraphAsymmErrors, TF1 import sys sys.path.append('../') import plot_utils as ut from models import load_starlight_y #_____________________________________________________________________________ def main(): #bins...
import asyncio from logging import getLogger from math import ceil from typing import Callable, Dict, Optional, Sequence, Set, Tuple, Union from aiohttp import ClientSession, ClientTimeout from lxml.html import document_fromstring from holodule.errors import HTTPStatusError from holodule.schedule import Schedule CHU...
__author__ = 'keleigong' class Solution(object): def convertToTitle(self, n): """ :type n: int :rtype: str """ letters = 'ZABCDEFGHIJKLMNOPQRSTUVWXYZ' res = '' while n > 0: reminder = n % 26 res = letters[reminder] + res # i...