index
int64
0
1,000k
blob_id
stringlengths
40
40
code
stringlengths
7
10.4M
14,800
864c6c6ab100b85b1b9ae68a9c61698fff99c315
import os import sys os.environ['OMP_NUM_THREADS'] = '1' import argparse import paddle from env import MultipleEnvironments from model import Model import multiprocessing as _mp from utils import eval, print_arguments from paddle.distribution import Categorical import paddle.nn.functional as F import numpy as np def...
14,801
74b8c362786952e99d2e8f8be29d0c77a69b2fc3
from django.db import models from django.contrib.auth.models import AbstractUser # As recommended by django docs, we use custom user. class CustomUser(AbstractUser): pass
14,802
f649ff189a721695e9bdfe8a54d9ec2966f77a0e
__author__ = 'fillan' from Physics import * import math class Calculation: view_space = None my_physics = None def __init__(self, view_space, my_physics): self.my_physics = my_physics self.view_space = view_space self.Total = Quaternion(1, 0, 0, 0) def create_total(self, axis...
14,803
3cd048025a2bec393d843ef3c1fe6cb1bfcd6f45
import ipaddress import random class IPv4RandomNetwork(ipaddress.IPv4Network): def __init__(self): ipaddress.IPv4Network.__init__(self, (int(random.randint(0x0B000000, 0xDF000000)), random.randint(8, 24)), strict = False) def regular(self): if not self.is_multicast and not self.is_private: ...
14,804
12449f1c03ef0f117c7c9f14c3decf8d8ec0a4d3
from datetime import datetime def rplt_time_to_datetime(time): ''' Transforma string do timestamp do repl.it em datetime ''' # 2020-04-11T18:39:41.336Z return datetime( # ano int(time.split('-')[0]), # mês int(time.split('-')[1]), # dia int(time.split('-')...
14,805
dde64068f97abdf23564229720410c90ca77190a
import configuration import performance from mamba import description, context, it from expects import expect, be_true, have_length, equal, be_a, have_property, be_none rule_name="route-rule-destination-weight.yaml" Rule=configuration.Rule() with description('Testing destination-weight, route to V1-75%, V2-25%'): ...
14,806
1565fbefff604b24b75dd46b78821099b7df6fa6
# -*- coding: utf-8 -*- # Part of Odoo. See ICENSE file for full copyright and licensing details. from odoo import api, fields, models, _ from odoo.addons import decimal_precision as dp from odoo.exceptions import UserError from odoo.tools.float_utils import float_round class ReturnPicking(models.TransientModel): ...
14,807
386fa8028fc26e87b967f745786ae4b04e4cc3a0
#%% from model import BtcModel import matplotlib.pyplot as plt empty_model = BtcModel(100) print(empty_model.kapital_households) for i in range(2): empty_model.step() agent_kapital = [a.kapital for a in empty_model.schedule.agents] agent_wage = [a.wage for a in empty_model.schedule.agents] # test1 = empty_model...
14,808
02ebf616907aa034fe9ad2c759ae52945ada3f7f
""" 1.Поработайте с переменными, создайте несколько, выведите на экран. Запросите у пользователя некоторые числа и строки и сохраните в переменные, затем выведите на экран. """ a = input("Введите фамилию: ") b = input("Введите своё имя: ") c = input("Введите отчество: ") age = int(input("Введите свой возраст: ")) prin...
14,809
6943551403ee01e3c5ff5430278cf65d0ced9adb
import unittest import json from typing import Callable, List from chapter2.insertion_sort import insertion_sort from chapter2.merge_sort import merge_sort from chapter6.heap_sort import heap_sort from chapter7.quick_sort import quick_sort from chapter8.counting_sort import counting_sort from chapter8.radix_sort impo...
14,810
69a8a8c5f75d05d37f7d9ef6d4d0d058b2f12522
""" train.py AUTHOR: Lucas Kabela PURPOSE: This file defines the code for training the neural networks in pytorch """ import gym from models import SAC import numpy as np import pandas as pd import matplotlib.pyplot as plt import torch import torch.utils.tensorboard as tb from replay import ReplayBuffer from utils im...
14,811
4bb845b3ca08e305ea646a4eafdeac4239dafa5e
""" Some shorthand functions which will be used in command.py """ import os import hashlib import errno import utils.typecheck as uty import utils.path as up PATH_TYPE_SET = ['file', 'dir'] def escape_path(path): """ Adds " if the path contains whitespaces Parameters ---------- path: str ...
14,812
75390e94d40731c976b2b5ab7b18ab9bc63ea51a
#!/usr/bin/env python ''' Author: ArkSealand Date: 11.06.2021 Purpose: Valorant Battle Pass Calculator ''' from datetime import date, datetime, timedelta ''' features to implement: 1. Take into account user weeklies and dailies 2. Check if to include exp from weeklies and dailies so far. 3. tab...
14,813
662212b519e81fb0672da65044f6647c23897510
import torch class mycustomnn()
14,814
e1ef706a25f7a1dafce1f10fc4cc118fc718d145
#encoding: utf-8 import unittest import zad1 import zad3 class TestZad1PrimesGenerator(unittest.TestCase): """ Test generowania liczb pierwszych przy pomocy generatorów """ def runTest(self): oczekiwane = [2, 3, 5, 7] wynik = zad1.pierwsze_generator(10) assert oczekiwane == wy...
14,815
4e0f51d49ba4f4297d36572eb79d716acd9075b1
# # Серверное приложение для соединений # import asyncio from asyncio import transports users_list = [] messages_list = [] class ServerProtocol(asyncio.Protocol): login: str = None server: 'Server' transport: transports.Transport def __init__(self, server: 'Server'): self.server = server ...
14,816
049995185d3675bfa557baa4ffe1aac2e1054709
import cv2 # 1 import # 2 create video capture entry vc = cv2.VideoCapture(0) # 3 capture picture of video continue while True: ret, img = vc.read() if not ret: print('no capture video') break # 4 show picture cv2.imshow('me', img) # 5 wait keyborad if cv2.waitKey(1) != -1: ...
14,817
a07fb6da7b004a7043d0a9f639090b9a42fd770d
from matrix import * import copy class LinearRegression: def __init__(self, x, y): """ :param x: data input matrix :param y: data output matrix """ self.x = copy.deepcopy(x) self.x2 = copy.deepcopy(x) for i in range(len(x)): self.x[i].insert(0, 1...
14,818
d57884ed22e7310189c95371c1497264ae40a9f4
#!/usr/bin/env python #coding=utf-8 """ 常量定义文件 """
14,819
99ffc2e0230e0bc29ee27a9122006202bce9a0bc
""" Use the streams coroutine-based API - asyncio.open_connection() (analogous to create_connection()) - reader.read() (or readuntil()) - writer.write() """ import asyncio import socket loop = asyncio.get_event_loop() @asyncio.coroutine def fetch(host): reader, writer = yield from asyncio.open_conne...
14,820
56e169abc6ba184d0fae589cc35daad45f311d0f
import csv import numpy as np import copy ##Importing A and converting to int## with open('my_A.csv', 'r') as f: reader = csv.reader(f) A=list(reader) for i in range(len(A)): for j in range(len(A[i])): A[i][j] = int(A[i][j]) print("A = ",end=" ") print(A) ##Importing C and converting to int## ...
14,821
62e6c0450c4cfca17be8672c58b4a120d3ba30f2
ITEM: TIMESTEP 5000 ITEM: NUMBER OF ATOMS 2048 ITEM: BOX BOUNDS pp pp pp -2.2149287064135450e+00 4.9414928706407061e+01 -2.2149287064135450e+00 4.9414928706407061e+01 -2.2149287064135450e+00 4.9414928706407061e+01 ITEM: ATOMS id type xs ys zs 1914 1 0.0893737 0.0319545 0.0312101 1497 1 0.874917 0.0701998 0.366018 1132 ...
14,822
62a1e473c43d86ffe1b681dae0bac37dcb1e073a
import os import shutil import random from argparse import ArgumentParser def func(marks_path): dict_classes = dict() for root, _, files in os.walk(marks_path): for file in files: if file.endswith('.xml'): key = os.path.basename(file)[0] file_name = os.path....
14,823
9db2e65bc02c6a8a3d5ad567bf29244c5a4b065a
from django.conf.urls import url from django.contrib.auth import views as auth_views from django.contrib.auth.decorators import permission_required from core import views as core_views url_empresa = [ url(r'^$', core_views.empresa, name='empresa'), url(r'^vagas/$', permission_required('core.add_vaga'...
14,824
ed3bad3c2e33c93120080d85914b75f6eeefb619
ps -af ls ls -lrth ps -af import networkx as nx nx di = nx.DiGraph() di.add_edge(1,2) di.add_edge(2,3) di di.edge di.add_edge(1,3) di.edge nx.shortest_paths(1,2) nx.shortest_paths(di,(1,2)) nx.shortest_paths(di,1,2) nx.shortest_paths? nx.shortest_paths?? nx.shortest_paths? nx.shortest_paths?? nx.shortest_paths? nx.shor...
14,825
829484e4a82975081629cbdd7e8f4e05ab180038
"""EVALUATION OF CONTENT PRESERVATION This code can be used for evaluation of content preservation between input and output sentiment texts of a style transfer model. Word Mover's Distance (WMD) on texts with style masking (i.e. placeholders used in place of style words) exhibited the highest correlation with human ...
14,826
573015637205a2e2ac3a0f4a434043afefbcbd9c
__author__ = "Tremor" commands = {} class Command: def __init__(self, name, func): self.name = name self.func = func def register(cmd): def takefunc(func): varthing = Command(cmd, func) commands[cmd] = varthing return varthing return takefunc @register("Print...
14,827
dc2aff608f5545916c40ac8b83c8049e6f8aaa55
import json from grafica.difusion_multiple import crear_difusion_multiple def mayus(string): return " ".join([s[0].upper() + s[1:] for s in string.split()]) def obtener_productos(archivo="grafica/productos.json"): with open(archivo, "r") as file: data = json.load(file) productos = [] ...
14,828
907e0bc4089ce5c3bc5f5132646d774a419ed23f
from flask import Flask, jsonify, request import config import crud_ops import filters import save_db_locally import stat_calc app = Flask(__name__) @app.route(rule='/api', methods=['GET']) def api_home(): return "<h1>This is the API Home page</h1>" @app.route(rule='/api/sensor/records', methods=['GET']) def al...
14,829
606bfad31b80c02267e8470852a7acd15fd2809f
""" Copyright 2020 The OneFlow Authors. 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 required by applicable law or agr...
14,830
d46f53cac37ebb646bb129038cbe84ad0f956d95
''' Copyright (c)2008-2009 Serendio Software Private Limited All Rights Reserved This software is confidential and proprietary information of Serendio Software. It is disclosed pursuant to a non-disclosure agreement between the recipient and Serendio. This source code is provided for informational purposes only,...
14,831
fb0ac40cf9d8cfa6ff12fded8c3c69359750cc34
import json import math import string dictionary = {} dictionary['Topics'] = {} f = open('topic_dictionary.json','r') dictionary = json.load(f) for topic in ['Security','Education','Immigration',"Hillary",'Trump','Cruz','Bernie','Kasich','Women','Supreme Court','Healthcare','Tax']: print "TAKING TOPICS RELATED T...
14,832
f2049d69699505385bbf98490d1c7739e17cfeea
import random class Person: def __init__(self, name, hp, mp, attack, defence, magic): self.name = name self.hp = hp self.max_hp = hp self.mp = mp self.max_mp = mp self.attacklow = attack - 10 self.attackhigh = attack + 10 self.defence = defence ...
14,833
270ac7fe6da9f8db3c442b55cbd69b0bdb43cf5f
import cv2 from urllib.request import urlopen import numpy as np import threading import json class Density(): def __init__(self, stream_url): """ Start a thread which tracks traffic density """ self.density = [0, 0, 0, 0] self.stream_url = stream_url self.template_...
14,834
bfa62b3f8ca394c85bc80fe40f2df4bacf738a96
# crypto.py # Functions for CS 1 Lab Assignment 4. #Author: Sarah Korb #Nov. 9, 2018 #Prof. Cormen: CS1 from random import randint d = 143335107525767630766681992050243383450593422653797373240583295055192203309151620171296230900825953 #secret key n = 23889184587627938461113665341707230575098903775636162341502851284315...
14,835
4461a7a84e64dcf6a362be62034c00aed69ca581
from typing import TYPE_CHECKING if TYPE_CHECKING: from Platforms.Discord.main_discord import PhaazebotDiscord from Utils.Classes.undefined import UNDEFINED from Utils.Classes.contentclass import ContentClass from Utils.Classes.storeclasses import GlobalStorage class DiscordCommand(ContentClass): """ Contains and ...
14,836
56a18e918a6716dea040cc25095a3bf4f64c4d16
import pandas as pd import pytest from scipy import stats from poptimizer.portfolio import Portfolio, optimizer, portfolio class FakeMetricsResample: def __init__(self, _=None): self.count = 30 @property def all_gradients(self): grad1 = dict(CHEP=0.015, KZOS=0.20, MTSS=0.01, RTKMP=0.03, ...
14,837
ce1b874fc073926d16834ebceaee0ab809da2579
# Sys Script 3 import subprocess import os def main(): subprocess.call('clear') while(y= True): subprocess.call(['echo', 'Your current directory is:']) subprocess.call('pwd') x = input("What file would you like to create a shortcut for?") if(x.equals('quit')): y= Fal...
14,838
32b935e0b8c2464eb44a8f6d1bb3a26ba6b30fdd
# -*- coding: utf-8 -*- from flask import ( jsonify ) from myolap.utils.const import _const import time def json_result(result, code=0,message='ok',success=True): data = { "code": code, "message": message, "result": result, "success": success, "timestamp": int(time.time...
14,839
7e612819a4865e05cd49f4732c28b2d1fa565009
''' @File : test.py @Author: ZhangYiming @Date : 2019/6/10 @Desc : ''' trues = [0,0,0,1,1,1,2,2,2,1,1] pred = [1,1,1,1,2,2,3,3,3,3,1] def find_index(array,x): indexs = list() for index,i in enumerate(array): if i==x: indexs+=[index] return indexs def align_truth_pred(trues,pred): ...
14,840
d01e2adfa215a082f244bab501234e6cf87bf45d
#!/usr/bin/env python3 # https://metaproblems.com/8b2797bf7f420d5ad92e60ba064a55a1/index.php import requests as r import re file = open('data.txt', 'w') for i in range(1000): res = r.get("https://metaproblems.com/8b2797bf7f420d5ad92e60ba064a55a1/index.php").text stripped = re.sub('<[^<]+?>', '', res).split('\n\n') ...
14,841
3531bb063c28d57fae952c7c22277e5ac2fa58ba
# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2017-12-18 06:16 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('inspector', '0004_auto_20171211_1555'), ] operations = [ migrations.AddField...
14,842
38f899873e8ba9fa635ac033f1ba68956c66bf3a
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import marshmallow from flask import jsonify, g, request from api.decorator import authenticated from api.response import OKResponse, ErrorResponse from api.schema import ChildSchema, UserChildUpdateDataSchema, UserChildDeleteRequestSchema from usecase import child as ch...
14,843
905fb2f75b8ef19c35d1701c4719160f35eaad87
import logging import logging.handlers class somewhere_logger(): LOG_FILE = 'somewhere_py_client.log' handler = logging.handlers.RotatingFileHandler(LOG_FILE, maxBytes=1024 * 1024, backupCount=5) fmt = '%(asctime)s - %(filename)s:%(lineno)s - %(name)s - %(message)s' formatter = logging.Formatter(fmt) ...
14,844
6a7478740d037ca6b4afb101432d5f3a6ae6e280
import gspread from oauth2client.service_account import ServiceAccountCredentials import json import os DIR = "/home/pi" #os.environ["HOME"] scope = ['https://spreadsheets.google.com/feeds','https://www.googleapis.com/auth/drive'] creds = ServiceAccountCredentials.from_json_keyfile_name(DIR + '/.ssh/task_lis...
14,845
6193e9998536e10aef5fd4a84ab9eec5f27d594a
import random import arcade from engine.game import * from engine.math import distance SCREEN_TITLE = "Unicorns and Rainbows" NPC_COUNT = 5 PLANT_COUNT = NPC_COUNT + 1 class UnicornsAndRainbowsGame(MyGame): def __init__(self): super().__init__(SCREEN_TITLE) def setup(self): super().setup(N...
14,846
a92af62525263aac8f2881ea17e945babaee9ef2
# python3 # Given an array of integers, # find out whether there are two distinct indices i and j in the array such that the absolute difference # between nums[i] and nums[j] is at most t and the absolute difference between i and j is at most k. # My solution class Solution(object): def containsNearbyAlmo...
14,847
14f7d2f87d93e7eeb607a55f6b37dfbd7efda51f
# coding:utf-8 # Author:hxj from fdfs_client.client import Fdfs_client if __name__ == '__main__': client = Fdfs_client('client.conf') # ret = client.upload_by_filename(r'C:\Users\Administrator\Pictures\122123.png') f = open(r'C:\Users\Administrator\Pictures\122123.png','rb') ret = client.upload_by_buf...
14,848
62560353ad81f7f66b9e205db540e795a8cceeae
class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: n1 = len(nums1) n2 = len(nums2) medianIdx = (n1 + n2) // 2 i = 0 ptr1 = 0 ptr2 = 0 prevNum = 0 num = 0 while i <= medianIdx: prevNum = nu...
14,849
e3970c01a0f0195b1aab7c21d5902e63039e9c59
import urllib import urllib.request import urllib.error print("starting code_gen") # load tsv import csv with open('./code_gen.tsv', mode='r', newline='', encoding='utf-8') as f: tsv_reader = csv.reader(f, delimiter='\t') read_data = [row for row in tsv_reader] # init code image_tsv_code = "" entity...
14,850
5b8946eb506ec5e1fc763575f2a9ba13f7dd9bc8
import json try: # Allows for test config file to be used during development config = json.load(open('config/testblegateway.json',)) except: config = json.load(open('config/blegateway.json',)) def get_config(section): if section == 'bleDevice' or section == 'filters' or \ section == 'identifiers' or secti...
14,851
9f441bb5dd72d47f620a04a0d058bfeffb7cc7f0
#encoding:utf8 ''' ''' __author__ = 'xuyuming' from app import db class lianjiadeal(db.Model): __tablename__ = 'lianjiadeal' #id = db.Column(db.Integer, primary_key=True) #代理主键 chanxiang = db.Column(db.String(16), nullable=False, default=u'unkown') danjia = db.Column(db.String(16), nullable=False) ...
14,852
9effdbb2b29f4b6721b82c64ec0ab09b27af5a8a
# -*- coding: utf-8 -*- """ Created on Fri Jul 17 15:24:59 2020 @author: u3w1 """ import pandas as pd import numpy as np from Imdb_utils import CalcEmbeddingVectorizerSpacy, CalcEmbeddingVectorizer from Imdb_utils import Find_Optimal_Cutoff, score import lightgbm as lgb #%% df_train = pd.read_csv('train.csv', head...
14,853
4199ff697a29a192abe0ea07eba1e0abddd06486
def sum_matrix(a, b, n): for i in range(n): for j in range(n): a[i][j] = a[i][j] + b[i][j] return a if __name__ == "__main__": n = int(input("Please input the number: ")) a = [] b = [] print("Please input the first matrix:") for i in range(n): c = [int(j) for j ...
14,854
32012553b903126cf09aed20c5803884a72a5ac6
#!/usr/bin/env python import asyncio import logging from typing import ( Optional ) from hummingbot.core.data_type.user_stream_tracker_data_source import UserStreamTrackerDataSource from hummingbot.logger import HummingbotLogger from hummingbot.core.data_type.user_stream_tracker import UserStreamTracker from hummi...
14,855
9d22417c660152d6e378e2a495b8bbc2b5594194
import random # a python program for tic-tac-toe game # module intro for introduction # module show_board for values # module playgame def introduction(): print("Hello this a sample tic tac toe game") print("It will rotate turns between players one and two") print("While 3,3 would be the bottom right.") ...
14,856
dd4ee2e4035fb5a01ddd31f9e0f7f589c677df10
n=input("") if n==n[::-1]: t=True else: t = False print(t)
14,857
4f35b007cd2c954480104a16b54c7e8dfa2773da
import miniflask # noqa: E402 def test_global_setup(capsys): mf = miniflask.init( ".modules", debug=True ) mf.load("globalvar") mf.parse_args([ ]) captured = capsys.readouterr() mf.event.print_all() captured = capsys.readouterr() assert captured.out == """ globalv...
14,858
961d882ac3e0cf24075f0a1bf7e0bef590cb61d0
def find_max_subarray_bf(array): left_index = 0 right_index = len(array) - 1 sum_ = float('-inf') array_len = len(array) for li in range(0, array_len): for ri in range(li + 1, array_len + 1): tmp_sum = sum(array[li:ri]) if tmp_sum >= sum_: sum_ = tmp_s...
14,859
e6660f5d2197bacf7790c457f9c81f5c864dad7d
U2FsdGVkX1+to2J8XM75DHPUKuA8p+bYXa9MDNKnwHpr4GlPVYz82W7vhdB1YuYt MD75UAXS6ToDtFgjt78RAVFEG+wMMEjHjMB8NB7hTRTqEWcRtr8jlORlPrxWoXMa iRfHwJcfPKrbv9ceyxYaMeKNDDbOt3TndfXnHArg/bvymiQTcaZlQLqIvaeUpxVe 4g4LrmJlcuvUBwOvot7/2uiw0yFUtuSjaFZAxHFVNitWfPVDzpR8CE2FXVDq/LMC FXfN4wO5sXF5FwyrGOykY2FIPPrMuOkt0ZHHzr2WclcweY7X2o5ldWegRQzl...
14,860
1e7a225dee7257b27d989162fdc9cfa18c3162cd
def fills_blanks(x): j = 1 for i in range(0, 19, 2): if x[i] != str(j): return False j = (j + 1) % 10 return True for i in range(1414213570, 1000000000, -10): if fills_blanks(str(i*i)): print(i)
14,861
90358ac49dd25e1eedac6638ecbfa4453e1a433e
print("started using GIT")
14,862
090be412bae0b2157fc63fc190b172e99744b789
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import mock from django.test import TestCase from ralph.scan.plugins.snmp_lldp import ( _get_device_interfaces_map, _get_remote_connect...
14,863
4a8c228b32d292a7eaff4c3a3e83e2595265b7a5
import numpy as np import tensorflow as tf from sklearn.cluster import KMeans from gensim.models.ldamodel import LdaModel from sklearn.metrics import pairwise_distances_argmin_min class TopicMaker(): def __init__(self, path_lda): self.n_cluster = 2 self._model_lda = LdaModel.load(path_lda + 'l...
14,864
8ad81d9c8ade670ec7513d24325a85b4dea43ab0
from tkinter import * root=Tk() def lclick(event): print("Left") def rclick(event): print("Right") frm=Frame(root, height=500,width=500) frm.bind("<Button-1>",lclick) frm.bind("<Button-2>",rclick) root.mainloop()
14,865
f5dac9dbe133cf34408400cdca1854d15c0757ad
lista_nomes = ['Ana', 'Maria', 'José', 'Pedro', 'Elena', 'Helena', 'elen'] for nome in lista_nomes: if nome[:1].lower() in ['a','e','i','o','u']: print(nome)
14,866
80a216487169fdf83eb14f0c62d5f9f7cd033471
import ply.lex as lex # List of token names. This is always required tokens = [ 'NUMBER', 'SUM', 'SUB', 'MUL', 'DIV', 'MOD', 'EQUAL', 'LPAREN', 'RPAREN', 'PRINT', 'INPUT', 'WHILE', 'FOR', 'IF', 'ELSE', 'STRINGVARIBABLE', 'INTEGERVARIBABLE', 'STRIN...
14,867
e5decabd567b107cffeb3f767aa70937e9f86295
weight = 674 # newtons F_N = 576 # newtons F_c = weight - F_N # newtons F_N_bottom = weight + F_N # newtons F_c_prime = 4 * F_c if __name__=="__main__": print(F_c + weight) print(weight - F_c_prime) print(weight + F_c_prime)
14,868
39ae7010f7690cfa2e2aa8471e36294b7d376019
from rest_framework import viewsets, permissions, filters from rest_framework import pagination from .serializers import * from .models import * from apps.core.api import BaseViewSet class ProductFamilyViewSet(BaseViewSet): queryset = ProductFamily.active.all() serializer_class = ProductFamilySerializer cla...
14,869
e480c17d7c94688f45eb34a0af89378ecf3cde25
from typing import Dict, Optional, TypedDict from django.http import HttpRequest from django.urls import reverse from .models import Cart class CartContext(TypedDict): cart: Optional[Cart] cart_url: str def cart(request: HttpRequest) -> CartContext: cart = Cart.objects.open().for_request(request).last...
14,870
05db26839b1ae723e51b75c01e9395d67eb370ee
import os import numpy as np import logging import argparse import sys logger = logging.getLogger('s-norm score.') logger.setLevel(logging.INFO) handler = logging.StreamHandler(sys.stdout) handler.setLevel(logging.INFO) formatter = logging.Formatter("%(asctime)s [%(pathname)s:%(lineno)s - " ...
14,871
f3afec1ae0974a17dd01952a014ab1174e29dd96
import glob import gzip import json import uuid import argparse def parseOptions(): parser = argparse.ArgumentParser( description="parse the data dictionaries of unharmonized dbGaP studies" ) parser.add_argument("-d", help="directory of dbGaP study", required=True) parser.add_argument("-p", he...
14,872
990ca733da94e2e1db78e33fdda60bc97e6d33f8
from django.urls import path from article import views urlpatterns = [ path('', views.index, name='index'), path('articles/', views.articles, name='articles'), path('articles/add', views.add_article, name='add_article'), path('articles/<int:article_id>/', views.article, name='article'), path('articles/<int:artic...
14,873
921ec39232eaca736807020fe40709a3d07b41f7
from datetime import datetime from pydantic import BaseModel class InitModel(BaseModel): created_at: datetime = datetime.utcnow() updated_at: datetime = datetime.utcnow()
14,874
d9d5e4ec06ca2089ebaccc06374f92b437960c31
__author__ = 'Michele Johnson' # Program requirements: # This problem is about modular design. # We are writing a program to simulate a self-checkout system of a store named Wake-Mart. # # This program has three tasks at the top level: input prices of items, input coupons and process payment. # Processing of ...
14,875
edc2d4f5d22deb02b0cdd8c4acc426d21cad7446
"""Base display module type.""" DEFAULT_MINIMUM_SAMPLE_COUNT = 2 class DisplayModule: """Base display module type.""" @classmethod def name(cls): """Return module's unique identifier string.""" raise NotImplementedError() @classmethod def get_result_model(cls): """Retur...
14,876
70fb633c9a97ff916cd9c6ea44d91c352624a7e0
# coding: utf-8 #used features: # "original_tokens" : 原title词数, #"nsw_tokens": 非特殊字符、stopwords词数, #"sw_tokens": stopwords词数, #"regex_tokens": 特殊字符词数, #"tit_des_ratio": 去除特殊字符和stopwords后title与des词数比, #"repeat_tokens": 重复词数(重复过的词数,不包含第一次), #"title_character_count": 字符长度, #"clarity" # In[1]: import findspark find...
14,877
cef038854b05bea7e8968517b04afc6785565b3f
import requests # installed with C:\Python34\ > python -m pip install requests import re import socket import time #import json hostname = socket.gethostname() IP = socket.gethostbyname(hostname) # or just write ex. 192.168.1.7 UTORRENT_URL = 'http://%s:%s/gui/' % (IP, '2323') UTORRENT_URL_TOKEN = '%stoken.html' % ...
14,878
c5ba9dfa8577d07b34de768ea7f4332788473109
# Generated by Django 2.1.8 on 2019-09-09 19:20 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('Seller', '0002_user_user_type'), ] operations = [ migrations.CreateModel( name='GoodsType', ...
14,879
65f6f8c6f8fee04b41cfcbe85268399eccef719b
import os import shutil from ocr_evaluation import TL_iou, rrc_evaluation_funcs import sys def compute_hmean(submit_file_path): # print('text_location <==> Evaluation <==> Compute Hmean <==> Begin') # basename = os.path.basename(submit_file_path) # assert basename == 'submit.zip', 'There is no submit.zip...
14,880
a903deec77450a442bbe8fe55ea4604eabee5acf
import time import numpy as np import torch import torch.nn as nn from torch.autograd import Variable from scipy.stats.stats import pearsonr from data_preperation import clean_data_strategy_2, get_GloVe_embedding import torch.nn.functional as F LEARNING_RATE = 1e-2 NUM_EPOCHS = 5 class SentenceEmbedding(nn.Module...
14,881
0d21598b4f513100ee33aa9f2b86daf80a4ec2a3
# -*- coding: utf8 -*- # python # ##### BEGIN GPL LICENSE BLOCK ##### # # 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 the License, or (at your option) any later versi...
14,882
0e6cb2a2ab14215498d919518ac98fd1ec5d459b
import fnmatch import io, os, re import yaml def rewrite_outdir(out_dir, chapter_dirs, static_host): build_dir = os.path.dirname(out_dir) if static_host and not static_host.endswith('/'): static_host += '/' for path in _walk(build_dir): rewrite_file_links(path, out_dir, chapter_dirs, stat...
14,883
47d44a471922f546b240294592b1641fc3a23f68
# coding=utf-8 from operator import itemgetter code_in = "xureveoulrefknpavberweqwuegwceappergvleovlrazfbevdfaewmedfbwubjvbyenpfalusfeabdensavlvbyenav" \ "becalexwsbeabdevecvppeyvtfeqwueaejwonpfrfeajjwubrewmergfelqlrfoeabdefknwubdergfeajruaperfajg" \ "vbylewmergfeysfarefknpwsfsewmergfersurgergfeoal...
14,884
fee67df517d0ca9417243d1332227a0cc7bbaf79
# Generated by Django 3.1.5 on 2021-03-03 19:44 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('persons', '0004_auto_20210303_1241'), ] operations = [ migrations.RenameField( model_name='person', old_name='cpf', ...
14,885
4d0cc73539e01335ebfe652b06d5a2a23a12b580
from myapp import myapp_obj, db db.create_all() myapp_obj.run(debug=True)
14,886
d315d4b9aafa817d973aa1f64e17e515132ec597
# Generated by Django 2.0.2 on 2018-03-01 17:35 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('girvi', '0007_auto_20180301_2302'), ] operations = [ migrations.AlterField( model_name='customer', name='Address', ...
14,887
9dc8636d825884506641d7ccca5396faa86899f6
''' O Hipermercado Tabajara está com uma promoção de carnes que é imperdível. Confira: Até 5 Kg Acima de 5 Kg File Duplo R$ 4,90 por Kg R$ 5,80 por Kg Alcatra R$ 5,90 por Kg R$ 6,80 por Kg Picanha R$ 6,90 por Kg R$ 7,80 por Kg Para atender a...
14,888
bc56d37fd70710432a3087771346909c695a2b32
from .views import blueprint from .models import *
14,889
d78bdbaf9cab089e662ad31bd3f08c66eeaad5fc
from .activaters import Tanh, Sigmoid from .simple_wave import PredictWaveFunction
14,890
5bcf8fae66ce509f593570f9b1515c9cf10d981e
from datetime import * today=datetime.now() print(today) print(today.date()) print(today.time()) a=today + timedelta(days=365) print(a) b=today - timedelta(days=365) print(b)
14,891
bb1cfcf7e90f9b28a98d9a44dee0800c29be0743
from django.db import models from django import forms from django.contrib.auth.models import User # Create your models here. ItemStatusChoices = [(0, 'PENDING'), (1, 'BOUGHT'), (0, 'NOT AVAILABLE')] class GroceryList(models.Model): ItemName = models.CharField(max_length=50) ItemQuantity = models.IntegerField...
14,892
53b68b154481d0e1344fc553c4e6370529924ebc
# -*- coding: utf-8 -*- from setuptools import setup setup( name='avahi-cname-aliases', version='1.0', description='Program for managing avahi aliases (systemd)', url='https://github.com/Dalee/avahi-cname-aliases', author='Dalee Dev Team', author_email='hello@dalee.ru', license='MIT', keywords='avahi cname ali...
14,893
c295e88f6944e5eab8371426c1e424215fbb2511
from django.test import TestCase from .models import * # Create your tests here. class ProfileTest(TestCase): def setUp(self): self.user = User.objects.create(id =1, username='missy') self.profile = Profile.objects.create(user = self.user,bio = 'No bio',email='nga@email.com') def test_instanc...
14,894
15ff70cfc0b6d5ac258b3c9cc13f34b36d9d0e46
from django.contrib import admin from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.contrib.auth.models import User from treebeard.admin import TreeAdmin from treebeard.forms import movenodeform_factory from .models import Outline, Feed, UserConfig class ConfigInline(admin.StackedInline): ...
14,895
2001406cc612b30b8d42a03999109fbf2c24ae87
#! /usr/bin/python import os # Run BCDEF first in case using global fit 'dofsrcombo' option #IOV_list= ['BCDEF','B','C','D','E','F'] #IOV_list= ['2018ABCD','2018A','2018B','2018C','2018D'] #IOV_list= ['2016GH','2016BCDEF','2016BCD','2016EF'] #IOV_list= ['2016BCDEF','2016GH','2016BCD','2016EF'] IOV_list= ['2018P8','201...
14,896
5f034d027e0d33f9bb9dc1bb132a0999a2d2630b
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from One import MVDF, MVGaussianSample, EuclideanM, Mahalanobis #https://docs.google.com/forms/d/e/1FAIpQLSfpOOvuaAZFEho1GQ0pOzGzFdyRfOsD7CF3aScIFMWz-dhwRg/viewform?usp=form_confirm&edit2=2_ABaOnucjxVJCDICCwApm1iqcqMui7SPit4I67-...
14,897
fa386185b9bd2de593d267dd283008684880b6b9
import json import numpy as np import pandas as pd import matplotlib.pyplot as plt import xgboost as xgb from sklearn.metrics import auc, precision_recall_curve from sklearn.model_selection import RepeatedStratifiedKFold, cross_validate from Models.Metrics import performance_metrics from Models.Utils import get_dist...
14,898
e7e17225634e71671693f0f6490a0f59544c93cb
r=float(input("input the radius of circle:")) area = 3.1416*r*r print("the area of a circle with radius %0.2f is:" %r) print("%f" %area)
14,899
def0c99df3826a94df0f0268dcad4752c6cd3b2e
# Checking usernames current_users = ['steve', 'admin', 'cyrill', 'jane', 'sergio', 'TOM'] new_users = ['steve', 'cyrill', 'amanda', 'arnold', 'tom'] if current_users: current_users = [user.lower() for user in current_users] else: print("List of current users is empty") if new_users: for new_user in ...