text
stringlengths
38
1.54M
import PySimpleGUI as sg import pymunk import random import socket """ Demo that shows integrating PySimpleGUI with the pymunk library. This combination of PySimpleGUI and pymunk could be used to build games. Note this exact same demo runs with PySimpleGUIWeb by changing the import statement """ class B...
import requests import json class PostExperience(object): def __init__(self, common, headers, accesstoken): self.headers = headers self.baseUrl = common.get('baseUrl') self.accesstoken = accesstoken self.headers.update({"accesstoken": self.accesstoken}) def post_experience(sel...
def main(j, args, params, tags, tasklet): params.result = (args.doc, args.doc) storagenodedict = dict() # import ipdb; ipdb.set_trace() scl = j.clients.osis.getNamespace('system') nodes = scl.node.search({"roles": "storagedriver"})[1:] for idx, node in enumerate(nodes): node["ips"] = ", "...
import numpy as np import pyccl as ccl def test_hodcl(): # With many thanks to Ryu Makiya, Eiichiro Komatsu # and Shin'ichiro Ando for providing this benchmark. # HOD params log10Mcut = 11.8 log10M1 = 11.73 sigma_Ncen = 0.15 alp_Nsat = 0.77 rmax = 4.39 rgs = 1.17 # Input power...
from src.AST import AST indent_char = '| ' def addToClass(cls): def decorator(func): setattr(cls, func.__name__, func) return func return decorator class TreePrinter: @addToClass(AST.Node) def printTree(self, indent=0): raise Exception("printTree not defined in class " + sel...
WELCOME = "Hello there! You can use my funky functionality to be even more happy with bunq!" UPDATE = "You spent {} Euro of your {} budget {}" CANCEL = "You canceled the process. Will delete all information." INVALID_INPUT = "Some of the information you gave were incorrect. Try again :-(" INVALID_INPUT_NUMBER = "Inval...
"""Fully Kiosk Browser switch.""" import logging from homeassistant.components.switch import SwitchEntity from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import DOMAIN _LOGGER = logging.getLogger(__name__) async def async_setup_entry(hass, config_entry, async_add_entities): "...
# Load packages import os import pandas as pd import numpy as np # This line is needed to display plots inline in Jupyter Notebook #matplotlib inline # Required for basic python plotting functionality import matplotlib.pyplot as plt # Required for formatting dates later in the case import datetime import matplotlib....
import discord import asyncio import random import time import sys import os import random import aiohttp useproxies = sys.argv[6] if useproxies == 'True': proxy_list = open("proxies.txt").read().splitlines() proxy = random.choice(proxy_list) con = aiohttp.ProxyConnector(proxy="http://"+proxy)...
class MotherBoard: def __init__(self, json=None): self.name = json.get('Text', None) self.image = json.get('ImageURL', None)
#!/usr/bin/env python # -*- coding: gb2312 -*- # # # 2.py # # Copyright 2020 天琼懵 <天琼懵@DESKTOP-03B3450> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of th...
import torch device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') number = torch.cuda.device_count() print(number) print(device) tensor = torch.Tensor(3,4) tensor.cuda(0)
# Generated by Django 3.0.5 on 2021-03-22 00:08 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Articulo', fields=[ ('id', models.AutoField...
""" Simple Caesar cipher implementation """ import unittest def encrypt(message, shift_n): """ Encrypts a message via shifting position of each letter by shift_n """ # mod 256 due to ASCII encoding shifted = [chr(_encrypt_helper(letter, shift_n) % 256) ...
import torch import torch.nn as nn import torch.nn.parallel import torch.optim import torch.utils.data import torch.nn.functional as F from torch.autograd import Variable import distiller.quantization as quantization from distiller.apputils.checkpoint import load_checkpoint import torchvision import torchvision.transfo...
import random d={} with open('./E_zfin_gene_alias_2014.12.08.gff3','r') as gff: for line in gff: if not line.startswith('#') and len(line) >1: cols = line.rstrip().split('\t') chromosome = cols[0] if not chromosome.startswith('Zv9'): chromosome = 'chr'+chromosome start,end = cols[3:5] g...
from office365.sharepoint.base_entity import BaseEntity class UserCustomAction(BaseEntity): pass
from socket import AF_INET from pathlib import Path from flask import render_template from pyroute2 import IPRoute from pr2modules.netlink.rtnl.rtmsg import rtmsg from manager import app from manager.structures import Route, Address, RTProto, RTScope class RouteTable: '''Manipulates entries in the kernel routin...
import unittest from advent2020.day5.seat_identifier import SeatIdentifier from parameterized import parameterized class TestSeatIdentifier(unittest.TestCase): ''' BFFFBBFRRR: row 70, column 7, seat ID 567. FFFBBBFRRR: row 14, column 7, seat ID 119. BBFFBBFRLL: row 102, column 4, seat ID 820. '''...
import numpy as np from colorama import init, Fore,Back init() class Board: def __init__(self,rows,columns): self.__rows=rows self.__columns = columns self.__matrix = [] self.str="" for i in range (self.__rows): #rows self.__new = []...
from nose.tools import eq_ from ..segments_added import segments_added def test_segments_added(): contiguous_segments_added = ["foobar {{herpaA}}", 'A[a]Aa[[Awu]]ta'] eq_(segments_added(contiguous_segments_added), 2)
#from phonenumber_field.modelfields import PhoneNumberField from django.db import models from django.utils.translation import ugettext as _ # Create your models here. from django.contrib.auth.models import (BaseUserManager, AbstractBaseUser) class UserManager(BaseUserManager): def create_user(self, email, phone_...
#! /usr/bin/python # -*- coding: utf-8 -*- import re import itertools def pywordcountplugin(text): return adjust_for_mail(text) def adjust_for_mail(text): """ Go through each of the special cases for email. """ rest_cases = [ remove_headers, remove_quoted, ] for case i...
def factorial(n) : fact = 1 for i in range(1,n+1): fact *= i return fact print("팩토리얼 값 계산 프로그램") while 1: n = int(input("\n정수 입력: ")) result = factorial(n) print("계산결과 %d! = %d" % (n,result)) input()
from typing import Any, Optional class BaseEmailBackend: fail_silently: Any = ... def __init__(self, fail_silently: bool = ..., **kwargs: Any) -> None: ... def open(self) -> None: ... def close(self) -> None: ... def __enter__(self) -> BaseEmailBackend: ... def __exit__( self, exc_type...
# 将处理过的武器的各种dataproperty通过代码的方式写入到owl文件中 # 即生成owl格式的代码,可以直接复制到owl中(先写道txt中,再复制到owl中) # 需要生成的是owl中关于datapropery的定义以及其domain,range # individual的添加,三元组的添加 import os import pandas as pd from tqdm import tqdm txt_file_1 = 'D:\文件夹汇总\项目\军事知识图谱\\bootstraping_extraction\Weapons\\txts\\Dataproperty_declaration.txt' ...
# -*- coding: utf-8 -*- """ Created on Wed Feb 28 14:44:06 2018 @author: Administrator """ import os import sys config_name = 'myapp.cfg' # determine if application is a script file or frozen exe if getattr(sys, 'frozen', False): application_path = os.path.dirname(sys.executable) elif __file__: application_p...
""" Basic tests to check that the core functionalities are at least running. """ import os import itertools import numpy as np import Bio from goldenhinges import ( OverhangsSelector, list_overhangs, gc_content, sequences_differences, reverse_complement, OverhangSetOptimizer, load_record, ) ...
# Generated by Django 2.0.7 on 2018-07-27 23:12 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('api', '0075_auto_20180727_1428'), ] operations = [ migrations.AddField( model_name='contest', name='is_primary', ...
""" A top-most level script to run the Game """ from Game.Breakout import Breakout GAME = Breakout() GAME.start()
import unittest # From: https://eli.thegreenplace.net/2011/08/02/python-unit-testing-parametrized-test-cases class ParametrizedTestCase(unittest.TestCase): """ TestCase classes that want to be parametrized should inherit from this class. """ def __init__(self, methodName='runTest', param=None): ...
#Leetcode 1221. Split a String in Balanced Strings ''' Balanced strings are those who have equal quantity of 'L' and 'R' characters. Given a balanced string s split it in the maximum amount of balanced strings. Return the maximum amount of splitted balanced strings. Example 1: Input: s = "RLRRLLRLRL" Output: 4 Expl...
''' ************************************************* * Title: Creating a dictionary from a .txt file using Python * Author: miloJ * Date: 2017 * Code version: python 3 * Availability: https://stackoverflow.com/questions/17714571/creating-a-dictionary-from-a-txt-file-using-python ***********************...
# -*- coding: utf-8 -*- """ Created on Tue Nov 3 11:30:52 2020 @author: pitan """ list=[4,78,52,7] large=list[0] for i in list: if(i>large): large=i print(large)
from pm4pymdl.algo.mvp.gen_framework.rel_events import being_produced, eventually_follows, existence, rel_events_builder, link, \ rel_dfg
# Copyright (c) 2020-2021 impersonator.org authors (Wen Liu and Zhixin Piao). All rights reserved. import numpy as np import torch import scipy.signal as signal from scipy.ndimage import filters from scipy import interpolate from scipy.spatial.transform.rotation import Rotation as R from iPERCore.tools.utils.geometry...
import os from config import BASIC_RESULT, ADVANCED_RESULT from readers import ( read_xml, read_json, read_csv ) from advnced import advanced from dataOperating import ( sort, dictionariate, ) from writers import create_output if __name__ == "__main__": if os.path.isfile(BASIC_RESULT): ...
import numpy as np class SpeedEstimator: def __init__(self, lanes=10, width=50): self.min_speed = - np.ones(lanes) * 3 self.max_speed = np.zeros(lanes) self.p = np.zeros(lanes) self.width = width self.lanes = lanes self.rounds = 0 def update(self, cars, occupan...
#!usr/bin/env python #coding: utf-8 import redis r = redis.Redis(host="localhost", port=6379) f = open("credit11315/proxy_ips.txt", "r") for i in f: r.zadd("credit11315_proxy_ips:sorted_set", '1', i.strip())
import types class Animal(object): pass class Dog(Animal): pass class Husky(Dog): pass def fn(): pass a = Animal() d = Dog() h = Husky() print(type(123)) print(type('str')) print(type(None)) print(type(abs)) print(type(a)) print(type(fn)) print() print(type(123)==type(465)) print(type(123)==int) ...
from django.db import models from datetime import datetime from django.contrib.auth.models import User class Hospital(models.Model): name = models.CharField(max_length=500) address = models.CharField(max_length=1000) description = models.TextField(max_length=1000) registered_at = models.DateTim...
from path import * import os import shutil class outils_fichier: def requete_py(self, fichier, element, liste): self.fichier = fichier self.element = element self.liste = liste with open(str(self.fichier),"w", errors = "ignore") as file: file.wr...
#!/usr/bin/env python import twitter def main(): module = AnsibleModule( argument_spec = dict( msg=dict(required=True), auth=dict(required=True), key=dict(required=True), ), supports_check_mode = False ) msg = module.params['msg'] auth1 = module.params['auth'] key_id = module...
from read_info import CFindRegionFieldByTitle import os import sqlite3 import time class CCheck(object): def __init__(self, check_path): self.m_check_path = check_path self.m_dbname = "record.db" conn = sqlite3.connect(self.m_dbname) c = conn.cursor() c.execute("create table if not exists path_info(path va...
from typing import List import os, pickle from neusum.service.basic_service import meta_str_surgery, easy_post_processing def iterator(bag): pass from random import shuffle import random def dropword(inp_str: str): inp_list = inp_str.split(" ") indc = random.sample(range(0, len(inp_list)), int(len(inp...
import tensorflow as tf import numpy as np import gym #from collections import deque # not using tgis for fun import random # for random sampling from deque env=gym.make('MountainCar-v0') env=env.unwrapped n_obs=2 n_act=3 qprimary = tf.keras.models.Sequential() qprimary.add(tf.keras.layers.Dense(units=128...
from upnpavcontrol.web.api import media_proxy import pytest import itsdangerous import itsdangerous.exc def test_encode_decode(): url = 'http://fancy.de' token = media_proxy.encode_url_proxy_token(url) decoded_url = media_proxy.decode_url_proxy_token(token) assert decoded_url == url assert token !...
import FWCore.ParameterSet.Config as cms process = cms.Process( "SiStripDQMBadStripsValidationReReco" ) ### Miscellanous ### ## Logging ## process.options = cms.untracked.PSet( wantSummary = cms.untracked.bool( True ) ) process.MessageLogger = cms.Service( "MessageLogger", destinations = cms.untracked.vstrin...
arr = [] n = int(input("Enter the size of the array: ")) for i in range(n): x = int(input("Enter the element: ")) arr.append(x) print("The array is:", arr) arr.sort() print("Array after sorting:",arr) item = int(input("Enter the element to search: ")) l = 0 u = n-1 while l <= u: mid = (l+u) // 2 if arr[...
import torch import numpy as np import torch.nn.functional as F from survae.distributions import ConditionalDistribution from survae.transforms.surjections import Surjection from .utils import integer_to_base, base_to_integer class BinaryProductArgmaxSurjection(Surjection): ''' A generative argmax surjection ...
def find_even_index(arr): for i in range(len(arr)): sommeDroite = 0 sommeGauche = 0 for j in range(0, i): sommeGauche += arr[j] for j in range(i+1, len(arr)): sommeDroite += arr[j] if sommeDroite == sommeGauche: return i return -1 de...
import cv2 import os import numpy as np from matplotlib import pyplot as plt import time import similarity_util if __name__ == '__main__': # check_path = r'C:\Users\Administrator\Desktop\zawu\similarity\check' # check_path = r'F:\pub_pic\004' # save_hist_path = r'C:\Users\Administrator\Desktop\zawu\similar...
import sys import torch import math import random try: import accimage except ImportError: accimage = None import numpy as np import numbers import types import collections import warnings import cv2 from PIL import Image, ImageFile if sys.version_info < (3, 3): Sequence = collections.Sequence Iterable...
""" Copyright 2015 Rackspace 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 applicable law or agreed to in writing, software dist...
# -*- python -*- load( "@drake//tools/install:install.bzl", "install", ) licenses(["by_exception_only"]) # Gurobi # This rule is only built if a glob() call fails. genrule( name = "error-message", outs = ["error-message.h"], cmd = "echo 'error: Gurobi 9.0.2 is not installed at {gurobi_home}' && ...
import socket import sys from bs4 import BeautifulSoup client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_address = ('10.181.1.242', 50002) client_socket.connect(server_address) request_header = 'GET ' request_header2= ' HTTP/1.0\r\nHost: 10.181.1.242\r\n\r\n' #client_socket.send(request_header)...
# Copyright 2021 VMware, Inc. # SPDX-License-Identifier: Apache-2.0 import os import pathlib from unittest import mock from click.testing import Result from functional.run import util from functional.run.test_run_sql_queries import VDK_DB_DEFAULT_TYPE from vdk.api.plugin.hook_markers import hookimpl from vdk.internal....
Status = {"health": 100, "power": 99, "mana": 77, "armor": 66, "name": "Ethan"} print("health:", Status["health"]) print("power:", Status["power"]) print("Mana:", Status["mana"]) print("armor:", Status["armor"]) print("name:", Status["name"])
import csv with open('new_vgsale.csv', newline='') as csvfile: # 讀取 CSV 檔案內容 row1 = csv.reader(csvfile) rows = csv.DictReader(csvfile) # 以迴圈輸出每一列 # for row in rows: # print(row['platform_n'], ".", row['Platform']) with open('new_vgsale2.csv', 'w', newline='') as csvfile: writer = c...
''' For the table results aggregate results across context sizes But then generate a plot for each of the dataset size that shows performance for these tasks does not depend much on the context size ''' import numpy as np import joblib from collections import defaultdict import os.path as osp context_sizes = [1,2,3,4]...
from odoo import models, fields, api from lxml import etree from odoo.tools.safe_eval import safe_eval from odoo.osv.orm import setup_modifiers class HrEmployee(models.Model): _inherit = "hr.employee" state = fields.Selection([ ('unverified', 'Unverified'), ...
import requests import json from lxml import etree url="https://s.weibo.com/top/summary?Refer=top_hot&topnav=1&wvr=6" header={'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 11_2_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.192 Safari/537.36'} def main(): html=etree.HTML(requests.get(url,header...
class Node: def __init__(self): self.property = None self.salary = None self.Tax = None # Nr of nodes & edges, max nr of turns / player, starting node of Alob and Bice N,M,K,sa,sb = list(map(int, input().split())) edges = [] for i in range(M): u, v = list(map(int, input().sp...
from otree.api import ( models, widgets, BaseConstants, BaseSubsession, BaseGroup, BasePlayer, Currency ) author = 'Fan Yuting & Liu Hang' doc = """ Fishery app, etc. """ class Constants(BaseConstants): name_in_url = 'login' players_per_group = None num_rounds = 1 # Views instructions_te...
import numpy as np import pickle as pkl import scipy.sparse as sp import sys import re import datetime def clean_str(string): """ Tokenization/string cleaning for all datasets except for SST. Original taken from https://github.com/yoonkim/CNN_sentence/blob/master/process_data.py """ string = re.su...
from django.urls import path from . import views app_name = 'main' urlpatterns = [ path('sys',views.get_sys_info,name='sys'), path('cpu_percent',views.get_cpu_percent, name='cpu_percent'), path('cpu_count',views.get_cpu_count, name='cpu_count'), path('cpu_times',views.get_cpu_times, name='cpu_tim...
# r = 0 # for n in range(1, 1001): # a = 3 # b = 5 # if n % a == 0 or n % b == 0: # r += n # print(r) index = 0 count = 0 for i in range(1, 1001): if index % 3 == 0 or index % 5 == 0: count += index index += 1 print(count)
import os import numpy as np import cv2 import matplotlib.pyplot as plt import face_recognition def get_embedding(img): img = img[:, :, :3].astype('uint8') encodings = face_recognition.face_encodings(img) if len(encodings) == 1: return encodings[0] else: return None
class WithdrawalError(Exception): pass class DepositError(Exception): pass class SavingsAccount: def __init__(self,b=500): try: if b<500: raise DepositError else: self.bal=b print('Account created with balance:',self....
""" Exercise 1: Vigenère cyper """ letters = list("ABCDEFGHIJKLMNOPQRSTUVWXYZ") Ki = lambda c, k: letters.index(k[c % len(k)]) def viginere_cipher_encrypt(D, key): """Encrypt: Ei = (Pi + Ki) % 26""" Pi = lambda i: letters.index(i) Ei = lambda a, b: letters[(a + b) % 26] E = [Ei(Pi(i), Ki(c, key)) for...
def difference(x,y): list1=list(x) list2=list(y) n=list(list1) for i in range(len(list1)): for j in range(len(list2)): if list1[i]==list2[j]: n.remove(list1[i]) print("The difference of these two sets is ",n) ...
import logging from datetime import datetime from django.core.management.base import BaseCommand from django.db import connections, connection, transaction as db_transaction from django.db.models import Count from usaspending_api.awards.models import TransactionFPDS, TransactionNormalized, Award from usaspending_api....
"""Helper class to get a database engine and to get a session.""" from pollbot.config import config from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session from sqlalchemy.orm.session import sessionmaker from sqlalchemy.ext.declarative import declarative_base engine = create_engine(config['datab...
# See LICENSE file for full copyright and licensing details. { "name": "Web Digital Signature", "version": "14.0.1.0.0", "author": "Serpent Consulting Services Pvt. Ltd.", "maintainer": "Serpent Consulting Services Pvt. Ltd.", "complexity": "easy", "depends": ["web"], "license": "AGPL-3", ...
password = 'a123456' while True: i = input('請輸入密碼: ') if i == password: print('登入成功') break else: print('密碼錯誤! 還有2次機會') i = input('請輸入密碼: ') if i == password: print('登入成功') break else: print('密碼錯誤! 還有1次機會') i = input('請輸入密碼: ') if i == password: print('登入成功') break else: print('暫停輸入30分鐘, 請稍...
""" Pre-Programming 61 Solution By Teerapat Kraisrisirikul """ def main(): """ Main function """ num_a, num_b = int(input()), int(input()) if num_a < num_b: print('Too High') elif num_a > num_b: print('Too Low') else: print('Correct!') main()
#!/usr/bin/python # Make graphs of the timing results from V5, V6, Prog-QUBO # We're comparing order statistics from 100 things (V5 data) with order statistics of 1000 things (V6 and Prog-QUBO data). # Put on the same graph by downsampling the 1000 samples to 100. # What does the 87^th lowest value out of 100 (counti...
class Stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return self.items[0] def size(self): return l...
class Solution(object): def countAndSay(self, n): """ :type n: int :rtype: str """ ret = '1' for _ in xrange(n - 1): last_ch = ret[0] count = 0 new_ret = '' for c in ret: if c == last_ch: ...
def sherlock(n, m): partsum = [] sum = 0 for i in m: sum += i partsum.append(sum) for i in range(n): leftsum = partsum[i] - m[i] rightsum = partsum[n-1] - partsum[i] if leftsum == rightsum: return "YES" return "NO" from sys import std...
import dotenv import oci import os dotenv.load_dotenv() oci_config = { "config": { "user": os.getenv("OCI_USER"), "fingerprint": os.getenv("OCI_FINGERPRINT"), "tenancy": os.getenv("OCI_TENANCY"), "region": os.getenv("OCI_REGION"), "key_file": os.getenv("OCI_KEY_FILE"), ...
# -*- coding: utf-8 -*- """ Created on Wed Jun 2 10:42:30 2021 @author: William @email: williams8645@gmail.com """ import numpy as np import os import pandas as pd import matplotlib.pyplot as plt from scipy import stats os.chdir('D:/Charite/labA/WP2') condition_dict = {1:'high_density_untreated',...
#!/usr/bin/env python # # 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 "Li...
import cv2 # Carregando a imagem em RGB imagem = cv2.imread("frutas.jpg") # Convertendo e exibindo a imagem em tons de cinza imagem = cv2.cvtColor(imagem, cv2.COLOR_RGB2GRAY) #nome da funcao utilizada cv2.imshow("Imagem", imagem) cv2.waitKey(0) cv2.destroyAllWindows()
######## # Copyright (c) 2018 Cloudify Platform Ltd. All rights reserved # # 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 requi...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render, redirect, get_object_or_404 from django.template.context_processors import csrf from django.contrib import auth, messages from django.contrib.auth.decorators import login_required from django.core.urlresolvers import r...
import sys sys.path.append('/anaconda3/lib/python3.7/site-packages') import networkx as nx import tree_operations_v1 as tree_operations from networkx.drawing.nx_agraph import graphviz_layout import matplotlib.pyplot as plt import inits_v1 as inits import os import utiles import seaborn as sns import numpy as np def dr...
# Generated by Django 3.2.5 on 2021-08-16 17:30 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Doctors', fields=[ ('id', models.BigAutoFie...
""" Given a min-heap 'pq' containing N element, return whether or not the value 'val' is lower or equal than the Kth value of the heap """ from typing import List """ The simple approach is to pop K value and check => This approach takes O(K log N) - This is the only approach available if you need the value of the K...
#!/usr/bin/python3 """task 0 """ import requests def number_of_subscribers(subreddit): url = "https://www.reddit.com/r/" + subreddit + "/about.json" head = {"User-Agent": "linux: didierrevelo:v1.0.0 by /u/didierrevelo"} reddit_req = requests.get(url, headers=head).json().get("data") if reddit_req ...
# Generated by Django 3.2.8 on 2021-10-17 22:00 from django.db import migrations def refactor_suggestion(apps, schema_editor): suggestions = apps.get_model('dashboard', 'ProblemSuggestion') for s in suggestions.objects.all().select_related('student__user'): s.user = s.student.user s.save() class Migration(mi...
import numpy as np from sklearn.metrics import ( accuracy_score, f1_score, precision_score, recall_score) import warnings warnings.filterwarnings('ignore') @property def my_acc_auc(outputs, targets): """Computes the accuracy and auc score for multiple binary predictions""" y_true = targets.cp...
from IPython.display import clear_output def display_board(board_list): #for displaying the game board, corresponding positions are numpad positions of keypad print(board_list[7]+' | '+ board_list[8]+' | '+ board_list[9]) print('---|-----|---') print(board_list[4]+' | '+ board_list[5]+' | '+ b...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from ... import _utilities fro...
from django import forms from .models import Products class ProductsForm(forms.Form): class meta: model = Products fields = ('items')
import RestAPI import BASE_URL import json import getcode import time main_server = "https://api.blood.land/mining/servers/9" user_id = "" #miningpool_ID user_pw = "" #miningpool_PW secret_key_1 = BASE_URL.secret_key_1 token = RestAPI.getToken(user_id, user_pw) print(token) print(BASE_URL.miningurl) while...
import numpy as np import pandas as pd N_PERIOD = { 'monthly': 12, 'weekly': 52, } class LoanProduct: '''Standard compounding loan product''' def __init__( self, loan, rate, num_years=30, loan_years=None, payment_freq='monthly', annual_fee=0, ): self._loan = loan ...
from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), #API route: posts view path("posts/com...
import math class SparseTable: """ 構築 O(NlogN)、クエリ O(1) """ def __init__(self, values, fn): """ :param list values: :param callable fn: 結合則を満たす冪等な関数。min、max など。add はだめ """ self._values = values self._fn = fn # SparseTable を構築 # self._ta...
from django.db import models from Account.models import User,Seller,Buyer from Sell.models import Product # Create your models here. class Order(models.Model): seller = models.ForeignKey(Seller, related_name='order', on_delete=models.CASCADE) buyer = models.ForeignKey(Buyer, related_name='order', on_dele...