text
stringlengths
38
1.54M
program_filename = NIH-diffractometer_PP.ab ip_address = 'nih-instrumentation.cars.aps.anl.gov:2000'
import functools import json import torch import tqdm import cargan ############################################################################### # Objective evaluation ############################################################################### def pitch(name, datasets, checkpoint, num=256, gpu=None): "...
from setuptools import setup, find_packages setup( name='wonder_tool', version='1.0', packages=find_packages(), install_requires=[], entry_points={ 'console_scripts': 'wonder = wonder_tool.main:wonder_main' }, zip_safe=False, classifiers=[ 'Enviroment :: Console', 'Intended Audience...
# -*- coding: utf-8 -*- """cpo-pipeline.tree.parsers.result_parsers This module provides functions for parsing result files generated by tools during the Tree phase of the cpo-pipeline. """ import csv def parse_workflow_results(path_to_result): """ Args: path_to_result (str): Path to the result file....
import os import argparse from utils import create_dataset, create_train_dir from network import MobileNetv2_DeepLabv3 from config import Params from utils import print_config LOG = lambda x: print('\033[0;31;2m' + x + '\033[0m') def main(): # add argumentation parser = argparse.ArgumentParser(description='...
from django.shortcuts import render, redirect # Create your views here. from pets.forms import CreatePetForm from pets.models import Pet, Like def pets_index(request): context = { 'pets': Pet.objects.all(), } return render(request, "pets/pet_list.html", context) def see_details(request, pk): ...
# Chapter 04 import requests from bs4 import BeautifulSoup import re try: print('before request') r = requests.get('http://google.com') print(r) except: print('test') # get bitcoin price from livecoin using API r = requests.get('https://api.livecoin.net/exchange/ticker?currencyPair=BTC/USD') price = r...
# https://leetcode.com/problems/replace-elements-with-greatest # -element-on-right-side/ # Given an array arr, replace every element in that array with the # greatest element among the elements to its right, and replace # the last element with -1. # After doing so, return the array. from typing import Lis...
from config10 import * from tensorboardX import SummaryWriter from utils10 import get_tensors, delta_E1994, tensor_Lab2RGB from Unet10 import InputNet, UnetD, UnetDL from VGG import VGG writer = SummaryWriter() BATCH_SIZE = 16 epoch = 120000+1 #720000*6/BATCH_SIZE ALPHA = 1e-7 BATE = 10 LAMBDA = 2 ITER...
class EmptyFileError(Exception): pass class UnrecognisedFieldError(BaseException): pass class EarlyReconciliationError(BaseException): pass class UpstreamServiceUnavailable(BaseException): pass
from piston.resource import Resource as PistonResource from piston.utils import rc import json class Resource(PistonResource): def form_validation_response(self, e): resp = rc.BAD_REQUEST resp.write(' ' + dict(e.form.errors.items()).__str__()) return resp
from ApplicationDate import application_date from sqlwrapper import gensql, dbget, dbput import json import datetime def HOTEL_FD_POST_UPDATE_RoomAssign(request): d = request.json res_id = d.get("Res_id") room = d.get("Res_room") unique_id = d.get("Res_unique_id") a,e = {},{} e = { k :...
import numpy as np #using numpy for arrays and optimized matrix multiplication np.random.seed(1) #seeding so that repeated results are the same and we can observe #changes from editing. from sklearn.model_selection import train_test_split #used to randomly split the #dataset into 2 parts so that we can train and test ...
import os import sys # Append paths so that dependencies would work. _FINDIT_DIR = os.path.join( os.path.dirname(__file__), os.path.pardir, os.path.pardir) _THIRD_PARTY_DIR = os.path.join( os.path.dirname(__file__), os.path.pardir, os.path.pardir, 'third_party') _FIRST_PARTY_DIR = os.path.join( os.path.dir...
from flask_cors import CORS from flask import ( Response, stream_with_context, session, request, redirect, url_for, jsonify, ) from flask_login import ( LoginManager, login_user, UserMixin, login_required, logout_user, current_user, ) from .app import ( app, s...
from copy import deepcopy import pytest import time from threading import Thread from mock import MagicMock from switchboard.engine import SwitchboardEngine, EngineError, _Client from switchboard.module import SwitchboardModule class TimeElapsed: def __enter__(self): self.start_time = time.time() d...
# EJERCICIO 31 h = int(input("Ingrese un número natural: ")) # el valor inicial de i es 2 ya que es innecesario verificar si # obtenemos 0 como resto al dividirlo por 1 i = 2 cont = 0 # no utilizamos <= porque verificar # si el n es divisible por si mismo es innecesario while(i < h): if h % i == 0: cont ...
# Generated by Django 2.2.2 on 2019-07-14 05:32 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('todo', '0017_auto_20190711_0912'), ] operations = [ migrations.CreateModel( ...
from django.contrib import admin from items.models.asset_custom_fields import LongTextAssetField, ShortTextAssetField, FloatAssetField, IntAssetField, \ AssetField from items.models.asset_models import Asset from items.models.item_models import Item, Tag from items.models.custom_field_models import Field, IntField...
#!/usr/bin/env python import csv from pymarc import MARCReader from os import listdir from re import search # change this line to match your folder structure SRC_DIR = '/home/Zwounds/workshop' # get a list of all .mrc files in source directory file_list = filter(lambda x: search('.mrc', x), listdir(SRC_DIR)) csv_ou...
import tempfile from urllib.parse import urlparse, parse_qs import requests from bs4 import BeautifulSoup from top_app.models import App, Video, ScreenShot def scrape_all(): res = requests.get('https://play.google.com/store/apps/collection/topselling_free') soup = BeautifulSoup(res.text, 'html.parser') ...
#!/usr/bin/python import argparse import time import struct import socket import select import sys from .opts import PingOptions class PingUtil(object): def __init__(self): pass def __chesksum(self, data): n = len(data) m = n % 2 sum = 0 for i in range(0, n - m ,2): ...
# -*- coding: latin-1 -*- # Medic Calculator # # Ref: http://www-users.med.cornell.edu/~spon/picu/calc/index.htm # Ref: http://www.medcalc.com/ # Ref: http://www.medal.org/ # #ensymble_python2.5-0.27.py py2sis --appname=medcalc --version=0.4.1 -l EN -t H:\S60\devices\S60_3rd_FP2_SDK_v1.1\epoc32\winscw\c\python\d...
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import argparse import glob import multiprocessing as mp import os import time import cv2 import tqdm import json from detectron2.config import get_cfg # from detectron2.data.detection_utils import read_image from detectron2.utils.logger import set...
name = " Troy " print(name.rstrip() + "\n") # Removes Space From Right End print(name.lstrip() + "\n") # Removes Space From Left End print(name.strip() + "\n") # Removes Space From Both Ends
import os import numpy as np import pandas as pd import SimpleITK as sitk import six import sys from radiomics import imageoperations, featureextractor def radiomic_feature_extraction(casename,image_path,roi_path,save_dir,param_file='/home/kwl16/Projects/kwlqtim/mets_Params.yml'): params = param_file #replac...
''' Write a Python program to split a given dictionary of lists into list of dictionaries. Input : {'Science': [88, 89, 62, 95], 'Language': [77, 78, 84, 80]} Output : [{'Science': 88, 'Language': 77}, {'Science': 89, 'Language': 78}, {'Science': 62, 'Language': 84}, {'Science': 95, 'Language': 80}] ''' input_dict =...
from consts.notification_type import NotificationType from helpers.model_to_dict import ModelToDict from notifications.base_notification import BaseNotification class MatchVideoNotification(BaseNotification): def __init__(self, match): self.match = match self.event = match.event.get() @proper...
#!/usr/bin/env python3 import argparse import os import subprocess import sys import tempfile import time import zipfile PIPELINES = [ "prepare_gene_models", "prepare_datasets", "prepare_downloads", "combine_datasets", ] def main(): parser = argparse.ArgumentParser() parser.add_argument("pi...
from utils import linear_lr_decay import torch import torch.nn as nn import numpy as np #PPO Agent Class class PPO: #----------------------- # Constructor #----------------------- def __init__( self, policy_net, value_net, dis_net, a_dim, beta, lr=1e-4, max_grad_norm=0.5, ...
from django import forms #from django.contrib.localflavor.br.forms import BRZipCodeField #from django.contrib.localflavor.br.forms import BRPhoneNumberField #from django.contrib.localflavor.br.forms import BRCNPJField #from django.contrib.localflavor.br.forms import BRCPFField #from django.contrib.localflavor.br.forms ...
''' @Author: Sankar @Date: 2021-04-09 09:06:25 @Last Modified by: Sankar @Last Modified time: 2021-04-09 09:11:09 @Title : Dictionary_Python-5 ''' ''' Write a Python script to generate and print a dictionary that contains a number (between 1 and n) in the form (x, x*x). Sample Dictionary ( n = 5) : Expected Output : {1...
"""BSD 2-Clause License Copyright (c) 2019, Allied Vision Technologies GmbH All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, thi...
from selenium import webdriver from selenium.webdriver.chrome.options import Options req_url = "https://www.baidu.com" chrome_options = Options() # 设置chrome浏览器无界面模式 chrome_options.add_argument('--headless') browser = webdriver.Chrome(options=chrome_options) # 开始请求 browser.get(req_url) # 打印页面源代码 print(browser.page_sour...
from django.db import models from django.utils.text import slugify from wagtail.core.models import Page, Locale from wagtail.snippets.models import get_snippet_models from wagtail.images.models import AbstractImage from wagtail.documents.models import AbstractDocument from wagtail_localize.models import TranslatableOb...
""" Regex linked-list node type definitions """ class RegexNode: """ Base node type """ def derive(self, _): return NeverMatches() def matchEnd(self): return False def canMatchMore(self): return not self.matchEnd() def __repr__(self): return "RegexNode" ...
#! /usr/bin/python # coding=utf-8 """ 1.进入公司详情 2.进入股东信息 3.查看股东信息所有公司 4.匹配人详情并打开新的tab 5.查验他的所有公司是否一致 """ import time from selenium import webdriver from tools.color_out import UseStyle driver = webdriver.Chrome() # driver.maximize_window() driver.set_window_size(1920, 1080) # driver.implicitly_wait(6) login_url = 'h...
# def get_box_area(width, length, height): # box_area = width * length * height # print(box_area) # # get_box_area(4, 4, 2) # get_box_area(width=1, length=1, height=2) def get_box_area(width, length, height): if width < 0 or length < 0 or height < 0: return 0 box_area = width * length * heig...
import numpy as np def np2flatstr( X, fmt='% .6f' ): return ' '.join( [fmt % x for x in X.flatten() ] ) class GMMPrior(object): #meanP = dict() #covarP = dict() def __init__(self, degFree, invW, muPrec, muMean=0.0): #self.meanP['prec'] = muPrec #self.meanP['mean'] = 0 #self.covarP['degFree'] ...
def getMonth(month): if month == 1: return "Nisan" elif month == 2: return "Iyyar" elif month == 3: return "Sivan" elif month == 4: return "Tammuz" elif month == 5: return "Av" elif month == 6: return "Elul" elif month == 7: return "Tishri" elif month == 8: return "Heshvan" elif month == 9: r...
print("Esse arquivo é o primeiro teste para clonar um repositório diretamente do VSCode") print("Depois de muitas tentativas pelo gitBash")
# Python program to convert a real value # to IEEE 754 Floating Point Representation. # Function to convert a # fraction to binary form. def binaryOfFraction(fraction): # Declaring an empty string # to store binary bits. binary = str() # Iterating through # fraction until it # becomes Zero. whil...
import pygame.ftfont import time class Course: def __init__(self,screen,stats): self.screen=screen self.stats=stats self.screen_rect=screen.get_rect() self.rect=pygame.Rect(550,350,200,100) self.show_flag=False self.show_time=1 def show_course(self): i...
from rest_framework import serializers from admission.serializers import UserSerializer from .models import Payments,Studentpayments,Accountant from student.models import Student class AccountantSerializer(serializers.Serializer): user= UserSerializer() esp_id= serializers.SlugField() class PaymentsSerializer(...
from itertools import islice from ..providers import shutterstock, local from .. import celery_app providers = [ {'module': shutterstock, 'weight': 0.9}, {'module': local, 'weight': 1.0} ] @celery_app.task def search(concept): weight = float(concept['relevance']) images = [] for provider i...
# -*- coding: utf-8 -*- import datetime from django.contrib.auth.models import User from django.db import models # Create your models here. from django.db.models.aggregates import Avg class Sensor(models.Model): name = models.CharField("nom du capteur", max_length=200) type = models.CharField("type du cap...
# Generated by Django 3.1 on 2020-10-30 21:50 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('core', '0004_remove_useraccount_user_ptr'), ('user_account', '0001_initial'), ('admin', '0003_logentry_add_act...
from django.db import models from django.utils.timezone import now # Create your models here. class Upload(models.Model): caption = models.CharField(default="File", max_length=200) date_added = models.DateField(default=now()) file = models.FileField(upload_to= "uploads/%d-%m-%y", default=None) def __str__(self):...
def solution(A): # write your code in Python 2.7 left = A[0] right = 0 for i in range(1,len(A)): right += A[i] min_diff = abs(left-right) for i in range(1,len(A)-1): left += A[i] right -= A[i] diff = abs(left - right) if diff < min_diff: min_...
from django.db import models from uuid import uuid4 # id = Default calls a function to randomly generate a unique identifier. #auto_now_add only sets on create, while auto_now will set on both create and update. class Note(models.Model): id = models.UUIDField(primary_key=True, default=uuid4, editable=False) ...
#!/usr/bin/env python # -*- coding: utf-8 -*- from logger.logger import app_logger from functools import wraps def recordLog(func): def wapper(*args, **kwargs): app_logger.info("[%s started][param:%s]"%(wraps.func_name, args)) return func(*args, **kwargs) return wapper
#! /usr/bin/env python # -*- coding: utf8 -*- __author__ = "Anita Annamalé" __version__ = "1.0" __copyright__ = "copyleft" __date__ = "2016/05" #-------------------------- MODULES IMPORTATION -------------------------------# import sys import os #-------------------------- FUNCTIONS DEFINITION -------------------...
import os import xbmcplugin import xbmcgui import xbmcaddon import xbmcvfs #import StorageServer import sys import xbmc import urllib2 import time try: import json except: import simplejson as json from addon import * from zipfile import ZipFile import sqlite3 class MormonChannel(Plugin): LANGUAGES...
import pytest from retention import models,utils testobj = models.ShiftedBetaGeom() data_junk_vals = [ ['one','two',3,4],[8,4,3,-1], [0,0,0,0],[] ] @pytest.mark.parametrize("a",data_junk_vals) def test_data_loading_bad_data(a): with pytest.raises(ValueError): testobj.load_training_data(a) param_valu...
#!/usr/bin/env python3 import csv import json import math from scipy import stats ANSWER_KEY = [ "The student sleeps like a Person", "tweety = Bird()", "robot.turnLeft()\nrobot.moveForward()\nrobot.moveForward()", "awooo!", "(none of these cause an error)", ] OPINION_MAP = { "Strongly Agree": ...
from numpy import * # Vetor contendo o nome dos meses do ano vet_mes = array(['janeiro', 'fevereiro', 'marco', 'abril', 'maio', 'junho', 'julho', 'agosto', 'setembro', 'outubro', 'novembro', 'dezembro']) data = input("digite dia mes ano: ") dia = int(data[:2]) ano = int(data[4:9]) i = int(data[2:4]) -1 mes = vet_mes[i...
from random import randrange, choice from uuid import uuid4 from argparse import ArgumentParser import sys import numpy as np def main(fname, size, dist, lam): with open(fname, 'w') as fout: #Each graph have the same amount of nodes size = int(size) - 1 #Title of each test file ...
import numpy as np class Grid: def __init__(self): self.grid = np.array([[None,None,None,None,None],[None,None,None,None,None],[None,None,None,None,None],[None,None,None,None,None],[None,None,None,None,None]]) self.hor = np.ones(5*4).reshape(5,4) self.ver = np.ones(4*5).reshape(4,5) def printGrid(self): sp...
from enum import Enum from selenium.webdriver.common.by import By from pages.base_page import BasePage class SignUpConstants(Enum): SIGN_UP_BTN = (By.ID, "signUpButton") class SignUpPage(BasePage): def __init__(self, context): BasePage.__init__(self, context.driver) def is_initialize(self): ...
import webapp2 import os import jinja2 from src.urls import pages jinja_enviroment = jinja2.Environment(autoescape=True, loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates'))) class AppPage(webapp2.RequestHandler): def get(self): request_path = self.request.path if self.requ...
from datetime import datetime, timedelta from mongoengine.queryset import DoesNotExist, MultipleObjectsReturned from scrapy.dupefilters import RFPDupeFilter from immobilier.mongodb.models import RawPage from immobilier.apps.scrapy_crawl.settings import RECRAWLING_DELAY RECRAWLING_TIME_DELTA = timedelta(days=RECRAWL...
#!/usr/bin/env import paho.mqtt.client as mqtt def on_connect(client, userdata, flags, rc): client.subscribe("image") client.subscribe("imagedata") print("Local Connected with result code "+str(rc)) def on_connect_cloud(client, userdata, flags, rc): print("Cloud connected with result code "+str(rc)) ...
# Generated by Django 3.1.4 on 2021-04-12 07:16 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0012_alter_user_first_name_max_length'), ] operations = [ migrations.CreateMode...
#!/bin/python from datetime import datetime import sys import time import subprocess import imp # ====================================================================== # ======================== PROGRAM CONSTANTS =========================== # ====================================================================== # max...
import glob import pybel import RASPA2 from pymongo import MongoClient from datetime import datetime # get cif cif_list = glob.glob('*.cif') for cif_file in cif_list: print cif_file # python2 # print(cif_file) # python3 # # Use pybel to parse, fill, and charge cif structure mol = pybel.readfi...
import card import random class player: def __init__(self, playerId, gameId, playerName, playerHand, playerPos, cardPool, handSize): self.playerId = playerId#integer, unique identifier for each player self.gameId = gameId#integer, unique identifier indicating the game this player is part of ...
from __future__ import print_function import sys try: input = raw_input except NameError: pass if __name__ == '__main__': num_cases = input() for case_idx, starting_num in enumerate(iter(sys.stdin.readline, ''), 1): starting_num = int(starting_num) if starting_num == 0: ...
# infoHeaders = { # 'Host': 'output.nsfc.gov.cn', # 'Connection': 'keep-alive', # 'Cache-Control': 'max-age=0', # 'Upgrade-Insecure-Requests': '1', # 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36', # 'Accept': '...
import datetime import requests import pprint import pandas as pd from settings import USER_ID, TOKEN USER_ID = USER_ID # spotify username TOKEN = TOKEN # https://developer.spotify.com/console/get-recently-played/ def check_if_valid_data(df: pd.DataFrame): # Check if dataframe is empty if df.empty: ...
# -*- coding: utf-8 -*- # x y 111000 # k # 110111 x, y = map(int, input().split()) k = int(input()) if k <= y: print(k + x) else: print(y + (x - (k - y)))
# # Binary operator classes # from __future__ import absolute_import, division from __future__ import print_function, unicode_literals import pybamm import numbers class BinaryOperator(pybamm.Symbol): """A node in the expression tree representing a binary operator (e.g. `+`, `*`) Derived classes will specif...
import os, shutil def movep(src, dst, overlay = True): """ 移動文件 overlay: True / False, True為自動覆蓋 """ if not os.path.isdir(dst): raise TypeError("dst must be a directory.") # 移動文件 if os.path.isfile(src): dst_dir = os.path.join(dst, os.path.basename(src)) if os.path.exists(...
import tests.generate_fake_dataset as gen import tests.initialize_db as initdb import yaml import testing.postgresql import psycopg2 import psycopg2.extras from mock import patch from pgdedupe.utils import load_config, filename_friendly_hash, create_model_definition from pgdedupe.run import process_options, preprocess...
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
from django.urls import path from . import views app_name = 'mainsite' urlpatterns = [ path('', views.landing, name='landing'), path('events', views.events, name='events'), path('reserve', views.reserve, name='reserve'), path('references', views.references, name='references'), path('tickets/<int:id>', views.tick...
from tkinter import * import sqlite3 import json # top = Tk() # top.title("Data Acquisition Tool") # top.geometry('400x500') # top.configure(background="light blue") # but0 = Button(top,text='Start',width=5,height=3) # but0.pack() # top.mainloop() # fred = Button(self, fg="red", bg="blue") # fred["fg"] = "red" # fred[...
#encoding=utf-8 from django.conf import settings as SETTINGS def settings(context): return {'DREAMDESKTOP_MSG_DOMAIN' : SETTINGS.DREAMDESKTOP_MSG_DOMAIN, 'DREAMDESKTOP_DOMAIN' : SETTINGS.DREAMDESKTOP_DOMAIN, 'DREAMWIDGETURL' : SETTINGS.DREAMDESKTOP_DREAMWIDGET_URL, 'DREAMD...
import scraper_functions from inspect import getmembers, isfunction class EmptyNewsSources(Exception): pass class EmptyScraperSource(Exception): pass class EmptyScraperFunction(Exception): pass class ScraperFunctionNotImplemented(Exception): pass def validate_news_sources(news_sources): mo...
import time import random # List of all the enemies in the game to randomize. enemies = ["Dragon", "Troll", "Pirate", "Vampire", "Gorgon", "Ghost"] # boolean to check if the game is being played for the first time firstTime = True # Boolean to check if the game is being restarted restart = False # to check if the p...
from tornado import httpclient from logging import getLogger, INFO logger = getLogger(__package__) if __name__ == '__main__': http_client = httpclient.HTTPClient() try: response = http_client.fetch("https://anonymous-boilerplate.firebaseapp.com") logger.info(response.body) except httpclie...
"""The Oscan alphabet. Sources: - `<https://www.unicode.org/charts/PDF/U10300.pdf>` - Buck, C. A Grammar of Oscan and Umbrian. """ __author__ = ["Caio Geraldes <caio.geraldes@usp.br>"] VOWELS = [ "\U00010300", # 𐌀 OSCAN LETTER A "\U00010304", # 𐌄 OSCAN LETTER E "\U00010309", # 𐌉 OSCAN LETTER I ...
""" /*************************************************************************** Name : Property Browser Description : Class that provides functions for overlaying property boundaries in either a Google Maps Satellite view or OpenStreetMaps. ...
from __future__ import unicode_literals from django.db import models from posts.models import Post from comments.models import Comment # Create your models here. class Rule(models.Model): post = models.ForeignKey(Post) is_first = models.BooleanField(default=False) is_last = models.BooleanField(default=Fa...
import serial import smbus SERIAL_DEV = '/dev/ttyS0' #/dev/ttyAMA0 I2C_ADDRESS = 0x60 def open_serial(baudrate): serial = serial.Serial(SERIAL_DEV, baudrate, 2) return serial #def close_serial(serial): # wiringpi.serialClose(serial) def write_serial(serial, msg): serial.write(msg) def read_serial(serial):...
from pathlib import Path from pytest_mock import MockerFixture from clutchless.command.link import LinkCommand, LinkFailure, ListLinkCommand from clutchless.domain.torrent import MetainfoFile from clutchless.external.metainfo import TorrentData from clutchless.service.torrent import LinkService, FindService def tes...
import pandas as pd import datetime import smtplib GMAIL_ID = "____" # Enter your email GMAIL_PASSWORD = "___" # Enter your email password then run the Program def sendEmail(to,sub,msg): print ("Successfully Send Email !!!!!!!!!!") s= smtplib.SMTP("smtp.gmail.com", 587) s.starttls() s.log...
{ "targets": [ { "target_name": "protobuf", "type": "static_library", "include_dirs": [ "2.6.1/protobuf-2.6.1/src", "2.6.1/protobuf-2.6.1" # for config.h ], "sources": [ "2.6.1/protobuf-2.6.1/src/goog...
import subprocess import json import time # define users VALIDATOR = "user1" USER = "user2" ROWAN = "rwn" PEGGYETH = "ceth" PEGGYROWAN = "erwn" ETH = "eth" SLEEPTIME = 5 AMOUNT = 10 CLAIMLOCK = "lock" CLAIMBURN = "burn" def print_error_message(error_message): print("#################################") print("...
people = [ {"name":"harry", "home":"slyhterine"}, {"name":"chanaka", "home":"sw19"}, {"name":"saneli", "home":"seeduwa"} ] def f(person): return person["home"] people.sort(key=f) print(people)
from collections import deque from functools import reduce bridge_length=2 weight=10 truck_weights= [7,4,5,6] # 에러해결 : dictionary는 중복을 허용하지 않기때문 -> ing 를 딕션에서 리스트로 바꿈 def solution(bridge_length, weight, truck_weights): ing = [] end = [] time=0 long=len(truck_weights) # 전부 다리를 건너올 때까지 while loop ...
def drop(x,y): ret = [] for i in range(len(x)): if (i + 1) % y != 0: ret.append(x[i]) return ret
import random import base64 import hashlib class cryptor(): def __init__(self, x, y, role): self.toServer = x self.toServerSend = 0 self.toClient = y self.toClientSend = 0 self.role = role def decrypt(self, crypted): message = "" crypted = base64.b64decode(crypted) if self.role == "client": for...
""" Connector adapters. To register connectors implemented in this module, it is imported in gaphor.adapter package. """ import logging from zope import component from zope.interface import implementer from gaphor import UML from gaphor.core import inject from gaphor.diagram import items from gaphor.diagram.interfa...
from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtCore import QTimer import sys import time import random class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(486, 505) self.centralwidget = QtWidgets.QWidget(MainWindow) ...
from rest_framework import serializers from api.models import RandomUid class RandomUidSerializer(serializers.ModelSerializer): class Meta: model = RandomUid fields = ["uuid", "created_at"]
import requests import json import csv import pandas as pd import re import requests from requests.adapters import HTTPAdapter from urllib3.util import Retry from collections import OrderedDict from bs4 import BeautifulSoup import sys def get_soup(url): session = requests.Session() retry = Retry(connect=3,...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'precios_ui.ui' # # Created by: PyQt5 UI code generator 5.13.2 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): Mai...
# Create your views here. from django.shortcuts import render_to_response from django.contrib.formtools.wizard.views import SessionWizardView from django.template import RequestContext from defs import definitions def start(request): return render_to_response('base.html', context_in...
import time from django.core.management import BaseCommand from tqdm import tqdm from ... import api from ...models import TwitterHashtag, TwitterPost, TwitterUser class Command(BaseCommand): # TODO: Enable authentication if required # def add_arguments(self, parser): # parser.add_argument('email',...
import pandas as pd import numpy as np sub_0283 = pd.read_csv('C:/PORTO/m29-PORTO-sub-0.282.csv') sub_0284 = pd.read_csv('C:/PORTO/m32-stacked_1.csv') m=33 w_sub_0283=0.5 w_sub_0284=0.5 final=sub_0283['id'].to_frame() final['target']=sub_0283['target']*w_sub_0283+sub_0284['target']*w_sub_0284 final.t...