index
int64
0
1,000k
blob_id
stringlengths
40
40
code
stringlengths
7
10.4M
992,600
b590b925684fa75d9d136910d8f573472d13eefb
import tensorflow as tf import random import cv2 import matplotlib.pyplot as plt import numpy as np import os from tensorflow.contrib.learn.python.learn.datasets.mnist import extract_images, extract_labels tf.set_random_seed(777) from sklearn.utils import shuffle from sklearn.model_selection import train_test_split fro...
992,601
80ac3d434e9905c9ef8ead496829296c56cf712a
#!/usr/bin/env python3 import random import requests import argparse from requests import Request from xml.etree import ElementTree as ET from Crypto.PublicKey import RSA from Crypto.Util import number from Crypto.Cipher import PKCS1_OAEP from common import e64bs, e64s, d64s, d64b, d64sb, hexlify ####################...
992,602
6ce2d8574efefdb435c784ad97c145769de08900
from logging import getLogger from bugyocloudclient import BugyoCloudClient, BugyoCloudClientError from bugyocloudclient.config import CONTENT_ENCODING from bugyocloudclient.models.authinfo import AuthInfo from bugyocloudclient.utils.urlproducer import produce_url from requests import Response logger = getLogger(__na...
992,603
96d7a7c34dc7d23f6764ffcceffe0db0f3b884e0
# Import dependencies import pandas as pd #import unidecode # Import data wine_data_df = pd.read_csv("Data/winemag-data-130k-v2.csv") print(wine_data_df.shape) wine_data_df.head() ## Select and keep only US data # Only keep rows where country = US US_wine_data_df = wine_data_df.loc[wine_data_df["country"] == "US"...
992,604
84df62a0d8d4e994c01b0ce2982fa066c38e46b9
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='ModuleList', fields=[ ('id', models.IntegerFiel...
992,605
5567592a9218f43f82ffc5fcdf2f1aec17be622d
from aux_funcs import * CF=pickle.load(open(datadir+'OSNAP2016recovery/pickles/xarray/CF_M_2014-2016_hourlyTSD_1903.pickle','rb')) dat=io.loadmat(datadir+'OSNAP2016recovery/LS/LSgridded_TS.mat') dat eddy_stats=io.loadmat(datadir+'OSNAP2016recovery/Eddies/LS_eddy_stats.mat') eddy_stats eddy_date = array([datetime....
992,606
9220b34f43e6f03391d54a097c14814800439a1f
import json def lambda_handler(event, context): return {"taskInput": event}
992,607
67f6c2f4073c2a4ffef62f1f778c4dfa9f8186a5
import random import pytest from Treap import * size = 300 def f(x): return (x*5)%17 def test_insert(): # passes if node inserts "take" (number of nodes inserted equals __size) t = Treap() for i in range(size): #t.insert(i, str(i), f(i)) t.insert(i, str(i)) asse...
992,608
35ea8f265e276b808a92c80294e812116ea0dcd8
# -*- coding:Latin-1 -*- # Permet d'utiliser les caractères français. #Import des modules nécessaires from xml.dom.minidom import parse import urllib, string, arcpy, time #Fonction pour ouvrir et lire le fichier XML. def xmldescription(url): xmlfilename =urllib.urlopen(url) #Ouverture du fichier via le web. ...
992,609
ccbe85ed7165a52b442c687edb5e85910b74c92b
""" num=30 nombre="jairo" print(num,type(num)) print(nombre,type(nombre)) def mensaje(msg): print(msg) mensaje("Mi primer programa en Python") mensaje("Mi segundo programa en Python") """ class Sintaxis: instancia=0 # atributo de clase # _init_ Metodoconstructor que se ejecuta cua...
992,610
880e0eacecc1640016a4f9442ee3f4c55eb739a0
from random import choice class RandomWalk(): def __init__(self,num_point = 5000) -> None: self.num_point =num_point self.x =[0] self.y =[0] self.get_step() def fill_walk(self): while len(self.x) < self.num_point: x_step = self.get_step() ...
992,611
2a16f5f3be99082ed7a17eb29062341e936184a7
#!/usr/bin/env python # -*- coding: utf-8 -*- from scribus import * margins = (36, 36, 0, 0) # Dictionary of logos' height/width aspect ratios. It is used to position the school logo # There's no way to programatically adjust frame to image. # The Python Scribus uses doesn't have any image utilities like PIL so I cou...
992,612
79db1c848904f3599495a43d7907c41bde530d03
# -*- coding: utf-8 -*- """ Created on Wed Jan 27 21:11:27 2016 @author: ORCHISAMA """ #Problem - 33 #The fraction 49/98 is a curious fraction, as an inexperienced mathematician in attempting to simplify it may incorrectly believe that 49/98 = 4/8, which is correct, is obtained by cancelling the 9s. # #We shall consi...
992,613
d2f055c1fdfb6c500e1cd57ab6337d595242ea94
# 2 Дан список: # ['в', '5', 'часов', '17', 'минут', 'температура', 'воздуха', 'была', '+5', 'градусов'] # # Необходимо его обработать — обособить каждое целое число (вещественные не трогаем) кавычками # (добавить кавычку до и кавычку после элемента списка, являющегося числом) и дополнить нулём до двух целочисленных # ...
992,614
a82c165f29c9324e2e33a0fcddbefcbd3b95bd3c
from plotly.basedatatypes import BaseTraceHierarchyType import copy class Line(BaseTraceHierarchyType): # autocolorscale # -------------- @property def autocolorscale(self): """ Has an effect only if `line.color` is set to a numerical array. Determines whether the colorscale i...
992,615
46eb5ff253f82357f8eea285d761a8ef1688b1fc
# from django.shortcuts import render # # Create your views here. # from django.contrib.auth.models import User, Group # from rest_framework import viewsets # from quickstart.serializers import UserSerializer, GroupSerializer from django.http import HttpResponse, JsonResponse from django.views.decorators.csrf import...
992,616
2be615648824cd6a97e7cfaaee3beb3ac524e8c5
import logging import boto3 import json import azure.functions as func from os import environ from botocore.exceptions import ClientError def main(req: func.HttpRequest) -> func.HttpResponse: ''' Returns the result of AWS API call. Parameters: req (HttpRequest): Request Parameters ...
992,617
fa4ea3a6a7b6bd8d420bd2f6df87eff85bc38154
import re, copy, os, sys, traceback try: from StringIO import StringIO except ImportError: from io import StringIO import txt_mixin #reload(txt_mixin) from rwkmisc import rwkstr import pylab_util as PU from pyp_basics import line, section from pytexutils import break_at_pipes, OptionsDictFromList #from IPyth...
992,618
f31a87a22d926adde8649aa8047454d0af20c90d
var1 = 3 var2 = 6 var3 = 9 var4 = ((var1 + var2 + var3) /3) print (var4) # print a var
992,619
725b7f29066eb1e6c94348353c34ef22d2d09d9d
import json import mlrun.errors import mlrun.utils.singleton from mlrun.api.schemas.marketplace import ( MarketplaceCatalog, MarketplaceItem, MarketplaceItemMetadata, MarketplaceItemSpec, MarketplaceSource, ObjectStatus, ) from mlrun.api.utils.singletons.k8s import get_k8s from mlrun.config imp...
992,620
7af1b5cd60640dde69503f04394ef2e48afecc92
# -*- coding: utf-8 -*- """ Created on Fri Oct 20 09:33:14 2017 @author: r.dewinter """ import numpy as np from scipy.optimize import minimize def fminsearchbnd(fun=None,x0=None,LB=None,UB=None,options=None,varargin=None): ''' FMINSEARCHBND: FMINSEARCH, but with bound constraints by transformation ...
992,621
401cb8b86a180e76dc2b537b5766e4f0ce6abf36
import json from typing import List, Union from grapple.bom.entity import Entity from grapple.bom.node import Node from grapple.bom.relation import Relation Payload = List[Union[Entity, Node, Relation]] class Condition(object): @property def signature(self) -> str: raise NotImplementedError('To be ...
992,622
324cac83d63ddcd69464a28e76d58474a6e48817
#combines jsonlines from desired jsonl files into one, and takes a desired sample from the lines import pathlib import ntpath import random import os import linecache x=0 files=[] for path in pathlib.Path("/Users/sophiawang/Desktop/May18").iterdir(): #replace the path with the folder of jsonl files you want to merge ...
992,623
065485c3903e15e2ceec02940bb07c441cb254ae
def quickSort(nums): if len(nums) == 1: return nums #初始化两个栈 startStack = [0,] endStack = [len(nums)-1,] #进入循环,两个栈均为空时,排序结束 while startStack and endStack: #得到本次循环的start 和 end start = startStack.pop() end = endStack.pop() #判断子数组是否有序 if start>end: ...
992,624
16d99fd4feedb6012af86c4ece968802272903e5
#!/usr/bin/env python2.5 # # Copyright 2010 the Melange authors. # # 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...
992,625
f8f0269deb1b6d2024bef5ed45e2ecf0cc1ea32e
import os import json import csv import sys # 读取每个问句对应的实体链接表信息 def read_qid2entity(init_dir_name): ''' 功能:从第一阶段产生的link文件中提取每个问句qid对应的实体链接数据 输入:第一阶段产生的候选文件夹名字 输出:问句ID与链接到的实体构成的词典,其中key值为问句ID,value值为链接实体列表,形如: ''' qid2entity = {} for root, dirs, files in os.walk(init_dir_name): # pri...
992,626
00ab38b476d8d6234d9e7eeb8405b07d8adb8272
import sys import os import math # CSV file to map # def csv_to_map (csv_file, key_index): res = {} with open(csv_file, 'r') as fid: keys = None for index,line in enumerate(fid): els = line.split(',') els = [e.strip() for e in els] if index == 0: keys = els else: re...
992,627
cd706204eb8aa1ddad9857c8926c573639a2e1a3
from .netcdf import NetCDFMonitor from .plot import PlotFunctionMonitor from .basic import ConstantPrognostic, ConstantDiagnostic, RelaxationPrognostic __all__ = ( PlotFunctionMonitor, NetCDFMonitor, ConstantPrognostic, ConstantDiagnostic, RelaxationPrognostic)
992,628
3f1d0ba28e2747bc44899ee772c90787bb599f9d
while True: num = int(input('Digite um numero: ')) val = str(num) if num <= 1000000: if str(num) == val[::-1]: print('O numero {} é PALINDROMO'.format(num)) else: print('O numero {} não é PALINDROMO'.format(num)) else: print('Digite numero menores que 100...
992,629
086ac644dafc38478fa1e3d8178fbecd6090c752
import argparse from eval_loss import load_names from rank_algos import significance, significance_cs01, preprocess_df_granular, preprocess_df, base_name, set_base_name import numpy as np MTR_LABEL = 'iwr' def wins_losses(df, xname, yname, args=None): rawx = df.loc[df.algo == xname].groupby('ds').rawloss.mean() ...
992,630
9eb5b0a6d577c8a83334acc292eed12d11c2fe38
from openpyxl import Workbook import time import pandas as pd import operator from alphaseekerclass import * book = Workbook() sheet = book.active SAVEBOOK = "idk.xlsx" SPECIFICSTOCK = input("do you want to look at specific stocks (1) or a huge list of stocks (2): ") if(SPECIFICSTOCK != "1"): debug = inpu...
992,631
696af1dc104b0d6346b038127cf4e2e893c8358b
import cv2 import numpy as np import time from sklearn.cluster import KMeans def give_shape(cap, arena, w_pos, r): ret, frame = cap.read() cv2.imwrite("new_a.jpg", frame) frame = frame[int(r[1]):int(r[1] + r[3]), int(r[0]):int(r[0] + r[2])] shape = frame.shape print(shape) y = in...
992,632
f77c45e86086453ca41b31e0efdd6d7ac238c2fb
# -*- coding: utf-8 -*- # django-read-only-admin # tests/templatetags/test_read_only_admin_tags.py from typing import List from django.test import TestCase from django.http import HttpRequest from django.contrib.auth import get_user_model from django.contrib.auth.models import Permission from django.template import...
992,633
a0ddbe98f3818573f1f17734873e5ce25cc7d4aa
""" Script illustrating the following points in graph-tool 1- Graph generator 2- Graph view 3- Intervative drawing of the graph """ import matplotlib.pyplot as plt from graph_tool.all import * import numpy as np; from gi.repository import Gtk,Gdk,GdkPixbuf,GObject; plt.switch_backend('GTK3Cairo') def coordinate_in_l...
992,634
db970ef9ceb7a617f7e671575d579f7b56b49d0e
def num(a,b): c = a + b return c ret = num(1,2) print(ret)
992,635
bf1b2e202b1ab4f0ed7f5540eb5b5443c4b6454e
import numpy as np from scipy.spatial.distance import cdist def probability(J, nc, pos, vel): amins = np.argsort(cdist(pos, pos) + 1e3 * np.eye(len(pos)), axis=1)[:,:nc] esum = np.exp(J / 2 * np.sum(np.dot(vel, np.swapaxes(vel[amins], 1,2)), axis=1)) return esum / np.sum(esum) def entropy(J, nc, pos, v...
992,636
67ff3be7bb3af26dacde649fbeeb1dd4482d0c3b
import unittest from fileconversions.helpers import mimetype class TestMimetypes(unittest.TestCase): def test_pdf_mimetype(self): self.assertEquals( mimetype('hello.pdf'), 'application/pdf' ) def test_jpeg_mimetype(self): self.assertEquals( mimetyp...
992,637
0d137592eb75516f59b2bd0cd908b5ced3dc20b1
# -*- coding: utf-8 -*- """ Created on Tue Jan 17 16:49:43 2017 @author: xat """ from util import read_file class RuleDetector: def __init__(self, stop_words='../data/stop_words.txt'): self.stop_words = self.read_stop_words(stop_words) def get_line_feature(self, line): if len(line) <...
992,638
d05ed1b392d93ccab4b1f0e5cd1e9d17782ae345
num1 = 12 num2 = 9 print("num1 = {}\n num2 = {}".format(num1,num2)) num1,num2 = num2,num1 print("num1 = {}\n num2 = {}".format(num1,num2))
992,639
036c164903428a1dc910f9e28965b944e9bbaea0
def trouble_sort(L): done=False length=len(L) while (done==False): done=True for i in range(0,length-2): if (L[i]>L[i+2]): done=False l_i=L[i] L[i]=L[i+2] L[i+2]=l_i return L T=int(input()) for i in range(T): list_length=int(input()) my_inp=list(map(int,input().split(' '))) sorted_trouble...
992,640
b5e9bb8c6b91b149ecd4fc702e22bb62bf986d27
from boolean import AND, FALSE, NOT, OR, TRUE def test_TRUE(): assert TRUE("lefty")("righty") == "lefty" def test_FALSE(): assert FALSE("lefty")("righty") == "righty" def test_NOT_inverts_TRUE(): assert NOT(TRUE) == FALSE def test_NOT_inverts_FALSE(): assert NOT(FALSE) == TRUE def test_AND_TT(...
992,641
e0f607504d214a9a39e3d367e79008fd6bf6452a
import torch from torch import nn class VSC(nn.Module): def __init__(self, latent_dim, c): super(VSC, self).__init__() self.latent_dim = latent_dim self.c = c # Initial channels 3 > 128 > 64 > 32 # Initial filters 3 > 3 > 3 # First change 3 > 32 > 64 > 128 ...
992,642
618682c6b430781eb6637499fd0a80ff5cc71e63
#coding=utf-8 # 请在此添加代码,使用lambda来创建匿名函数,能够判断输入的两个数值的大小, #********** Begin *********# MAXIMUM=lambda a,b:a if a>b else b MINIMUM=lambda a,b:a if a<b else b #********** End **********# # 输入两个正整数 a = int(input()) b = int(input()) # 输出较大的值和较小的值 print('较大的值是:%d' % MAXIMUM(a,b)) print('较小的值是:%d' % MINIMUM(a,b))
992,643
038f6c2c759e0be9b5a4bb3f90097e598a363e0c
# This file is the log for the in-situ sensors placed for iScape project # Smart Citizen Kit was placed in UCD # The file is split into three standardized json files for O3, NO2 and O3 # Date format is transformed to ISO-8601 format # Value of pollutant is extracted depending on recommendation from iScape Forum im...
992,644
2db9980567a6952ddbc5da57b31b2a8d5466ce2a
# Generated by Django 3.0.4 on 2020-04-29 04:53 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('ATMStatus', '0009_auto_20200429_1024'), ] operations = [ migrations.AlterField( model_name='atmdetails', name='branc...
992,645
c54dde9731332200c9767e6ce8e4eaf02714bacf
from django.db import models from django.contrib.gis.db import models as gismodels class Country(gismodels.Model): """ Model to represent countries. """ isocode = gismodels.CharField(max_length=2) name = gismodels.CharField(max_length=255) geometry = gismodels.MultiPolygonField(srid=4326) ...
992,646
cfe7bcf6f40a60f48df1b5a359439227ae9121a2
import os import wave from multiprocessing import Process import pyaudio class Audio: def __init__(self, video_path): audio_path = os.path.splitext(video_path)[0] + ".wav" if not os.path.exists(audio_path): os.system("ffmpeg -i " + video_path + " -b:a 128k " + audio_path) self...
992,647
beaecd09d4643958f4abb8635f50f051b06890ff
# -*- coding: utf-8 -*- """\ Overset simulation interface ----------------------------- """ import numpy as np from mpi4py import MPI from .. import tioga from .par_printer import ParallelPrinter from .par_timer import ParTimer class OversetSimulation: """Representation of an overset simulation""" def __ini...
992,648
d24d035c2138bebce25d21888729e761a2f497b1
from flask import Flask, request import json from FlowrouteMessagingLib.Controllers.APIController import * from FlowrouteMessagingLib.Models import * controller = APIController(username="AccessKey", password="SecretKey") app = Flask(__name__) app.debug = True global EXAMPLE_APPOINTMENT global ORIGINATING_NUMBER EX...
992,649
4a1f1e1bf9db9fe3974d38b771b5848c3859ef05
#!/usr/bin/python # -*- coding: utf-8 -*- import GPS import inspect import os import imp import sys from pygps import * import pygps.tree from pygps.tree import * import pygps.notebook from pygps.notebook import * from pygps.project import * import traceback import platform import workflows from workflows.promises impo...
992,650
1b02eeccc248dad062284e53c641d494af09bdd7
#!/usr/bin/env python # -*- coding: utf-8 -*- """ gw_backend_redis.example ~~~~~~~~~~~~~~~~~~~~~~~~ Stati example to use Redis pub/sub transport :copyright: (c) 2014 by GottWall team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. :github: http://github.com/GottWall/gottwall-backend-redis ...
992,651
540a6b98e4b3617fab0362f360e086fd49295a34
import ROOT from ROOT import TCanvas, TH1F, TLegend from NNDefs import build_and_train_class_nn from LayersDefs import get_signal_and_background_frames, predict_nn_on_all_frame, calculate_derived_et_columns, roc_curve, \ background_eff_at_target_signal_eff from sklearn.model_selection import train_test_split import...
992,652
cb29e03adffebdaa11bd8c4ecaf1bdecd65b98c9
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import address.models class Migration(migrations.Migration): dependencies = [ ('ossi', '0001_initial'), ] operations = [ migrations.AlterField( model_name='variety', ...
992,653
4436bf10636d4d86cf21a20a72639f0524855acf
# -*- coding: utf-8 -*- import pandas as pd # from shapely.geometry import Point, shape from flask import Flask from flask import render_template from flask import request # from flask import Blueprint import json app = Flask(__name__) data_path = './data/' @app.route("/") def index(): return render_template("...
992,654
06a760304941b35f7cd50c00035db40ace20fac3
# -*- coding: utf-8 -*- import tensorflow as tf with tf.Graph().as_default(): a = tf.constant([[1,2,3], [3,4,5]]) # shape (2,3) b = tf.constant([[7,8,9], [10,11,12]]) # shape (2,3) a_concat_b = tf.concat([a, b], axis=0) # shape (4,3) print("a concat b shape: %s" % a_concat_b.shape) a_stack_b = tf.s...
992,655
bb3957192abd77c25e77bb73de73ca3582fdd76c
from webapp.core import db from flask.ext.sqlalchemy import SQLAlchemy class User(db.Model): __tablename__ = "users" id = db.Column(db.Integer, primary_key=True) fullname = db.Column(db.String(255)) google_plus_id = db.Column(db.String(255), unique=True) def __init__(self, fullname, google_plus_id): s...
992,656
a0f4de310f16ee476efccffb3eb9cc64ef046ea0
import logging import os import pkg_resources import pytest import yaml from ambianic import __version__, config, load_config from ambianic.webapp.fastapi_app import app, set_data_dir from fastapi.testclient import TestClient log = logging.getLogger(__name__) def reset_config(): config.reload() # session scop...
992,657
c44a4a7c9015c6e5c543f01cfc06944932fbe3d6
def main(): S = list(input()) acgt = ['A','C', 'G', 'T'] ans = 0 for i in range(0,len(S)): if S[i] not in acgt: continue l = 1 for j in range(i+1, len(S)): if S[j] not in acgt: break l += 1 ans = max(ans,l) ...
992,658
51abea03d54dc5df9777e2da576e2f45e82a0c7e
import StringIO from lxml import isoschematron from lxml import etree def main(): # Example adapted from http://lxml.de/validation.html#id2 f = 'rijksSchema.xml' # Parse schema sct_doc = etree.parse(f) schematron = isoschematron.Schematron(sct_doc, store_report = True) # XML to validate ...
992,659
688008eac3fac96c327b61ad07c8c4623263d018
from django.test import TestCase from django.apps import apps from django.contrib.auth import get_user_model from .models import Entry from . import views from django.urls import resolve from django.http import HttpRequest # Create your tests here. class EntryModelTest(TestCase): # def test_gialap_fail(self): ...
992,660
d4babb38cf8c7ac53d47fd267488df59dbef7ce7
import geojson from django.db.models import Count from actstream.models import Action from django_filters import FilterSet, DateFilter, MultipleChoiceFilter from rest_framework import filters, generics, permissions, viewsets from rest_framework.response import Response from .serializers import ActionSerializer cla...
992,661
7c7b5ae8ebcba6660e059dd666f9be797e8efe23
""" RuuviTagReactive and Reactive Extensions Subject examples """ from reactivex import operators as ops from ruuvitag_sensor.ruuvi_rx import RuuviTagReactive tags = {"F4:A5:74:89:16:57": "sauna", "CC:2C:6A:1E:59:3D": "bedroom", "BB:2C:6A:1E:59:3D": "livingroom"} interval_in_s = 10.0 ruuvi_rx = RuuviTagReactive(lis...
992,662
bfb2ab068231396fa8d118fb3e328fc679c5a6a4
if not os.path.exists('w51_progressive_test_small.ms'): os.system('cp -r w51_test_small.ms w51_progressive_test_small.ms') # split(vis='w51_spw3_continuum_flagged.ms', # outputvis='w51_progressive_test_small.ms', # field='31,32,33,39,40,24,25', # spw='', # datacolumn='data', #...
992,663
27be0670e2ea2e315302593ec88576de388de4f8
# Usage: # docker run --rm -ti \ # -v /path-to/model:/sly_task_data/model # [model docker image name] # python -- /workdir/src/rest_inference.py from inference import ObjectDetectionSingleImageApplier import os from supervisely_lib.worker_api.rpc_servicer import InactiveRPCServicer from supervise...
992,664
15d4c3a91688a5559cb8990d06744bbaccad774b
# -*- coding: utf-8 -*- # Generated by Django 1.9.7 on 2016-07-10 17:49 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('grid', '0029_auto_20160710_1232'), ] operations = [ migrations.AlterField( ...
992,665
aff86fcb60345e2d700f773656fdaca1c5dbb747
from django.contrib import admin from django.urls import path, include from . import views urlpatterns = [ path('', views.index), path('new', views.new), path('create', views.create), path('detail/<int:g_pk>', views.detail), path('delete/<int:g_pk>', views.delete), path('fix/<int:g_pk>', views.f...
992,666
d1a36ccd9c109ce563318c14c0a80f8b46059970
from django import forms from .models import Artikel class ArtikelForm(forms.ModelForm): class Meta: model = Artikel fields = ('judul', 'isi', 'penulis', 'foto',) widgets = { 'judul': forms.TextInput( attrs={ 'placeholder': 'Judul jangan koson...
992,667
c1e0b7f056b40b58a7570e91e42f2f0e476c83de
from django.shortcuts import render import requests import json from datetime import datetime import time import random import sqlite3 from monitor.models import Products from discord_webhook import DiscordWebhook, DiscordEmbed def send_webhook(webhook, product_title, price, image_url, desc, handle): embed = Disc...
992,668
0064659304226287d1c91217df90c094487accfd
from prefix_sums import * import unittest class PrefixSums(unittest.TestCase): @unittest.skip def test_prefix_sums(self): A = [3, 4, 5, 6] print(A[1:2]) P = prefix_sums(A) self.assertTrue(P[1], 3) self.assertTrue(P[2], 7) self.assertTrue(P[4],18) @unitte...
992,669
4fc7a68a5d408de136fc64ea84a1ff9e1675b63a
import numpy as np import cv2 import tensorflow as tf import os gpus= tf.config.experimental.list_physical_devices('GPU') tf.config.experimental.set_memory_growth(gpus[0], True) filename = 'video.avi' frames_per_second = 10.0 res = '720p' # Standard Video Dimensions Sizes STD_DIMENSIONS = { "480p": (640, 480), ...
992,670
8335a84e6ccbe78829c075ab7cdec5aef23f42e0
def anagramMappings(self, A, B): """ :type A: List[int] :type B: List[int] :rtype: List[int] """ pos = {} for i in range(len(B)): if B[i] in pos: pos[B[i]].append(i) else: pos[B[i]] = [i] P = [] for i in range(len(A)): idx = pos[A[i]].p...
992,671
c0a8d16d830cefe888575e82d5f10e62cf8ac278
import pytest from test_case.web_test.pages.baidu_page import BaiduPage from test_case.web_test.pages.login_page import LoginPage from test_case.web_test.pages.menu_page import MenuPage from test_case.web_test.pages.add_goods_page import AddGoodsPage from test_case.web_test.pages.goods_list_page import GoodsListPage fr...
992,672
fe7970308c05d2937e94481c6f348f09591e72d6
import numpy as np import cv2 import torch from torch.utils.data import Dataset import albumentations as A from albumentations import * from warnings import filterwarnings filterwarnings("ignore") from config import * ################# Augmentation ############### # # Plain Training Augmentation # Transfo...
992,673
6c539cec4f3af78ba241c6aa08002b8cc62a375f
class BaseMetric(object): def __init__(self, metric_names, eval_intermediate=True, eval_validation=True): self._names = tuple(metric_names) self._eval_intermediate = eval_intermediate self._eval_validation = eval_validation def eval_intermediate(self): return self._eval_interme...
992,674
88cb8d5cc7e628092493d2e9a98ccca3d9a3269f
from django.conf.urls import url from appusrs import views from django.urls import path,include #TEMPLATE URLS app_name='appusrs' urlpatterns=[ path('register/',views.register,name='register'), path('user_login/',views.user_login,name='user_login') ]
992,675
a8737bf2e307789f00793654ac4fb1bd3c6645f3
""" [ dictionary 형 ] 1- 키와 값으로 구성 ( 자바의 map 와 유사 ) 2- 저장된 자료의 순서는 의미 없음 3- 중괄호 {} 사용 4- 변경가능 ` 사전.keys() : key만 추출 (임의의 순서) ` 사전.values() : value만 추출 (임의의 순서) ` 사전.items() : key와 value를 튜플로 추출 (임의의 순서) """ print('--------- 1. 딕셔너리 요소 --------------- ') dt = {1:'one', 2:'two', '3':'thr...
992,676
f9e447d5f9d05b86bf03c0ab3cd2083049ece24f
from models.user import User from .interfaces.user import UserRepoInterface from .repo import Repo class UserRepo(Repo, UserRepoInterface): def __init__(self, session): super().__init__(session) self._entity_type = User def get_by_email(self, email): user = self._session.query(User).f...
992,677
e965c33cc7d1efd61f228187feb6871c807925f9
T = int(raw_input()) for caseID in range(1,T+1): n = int(raw_input()) aa = map(int,raw_input().split()) answer = 1e9 for i in range(n): for j in range(i+1,n): a = float(aa[j]-aa[i]) / float(j-i) l = 0 r = 1e9 for iter in range(70): m = (l + r) / 2.0 # T[i] - aa[i] <= m for i=0..n-1 bmin, b...
992,678
0963fbc5447bd033f393a6b79a32386cb3ec028d
import time from winsound import Beep fg = int(input("Please enter time: ")) while fg: fgt = 60 fg -= 1 time.sleep(1) while fgt: fgt -= 1 print(f"{fg}:{fgt} \r", end="") time.sleep(1) Beep(1000, 200) print("End")
992,679
92fdae9d36aba7682ba65ff32dbe3b83758af65c
from __future__ import absolute_import, unicode_literals import argparse import importlib import logging import logging.config import os import sys import traceback import signal import attr from pysoa.client import Client from pysoa.common.constants import ( ERROR_CODE_RESPONSE_TOO_LARGE, ERROR_CODE_SERVER_E...
992,680
a9ffd434de0dc8b95cc50a71423ed7b6ed0b9960
# # Helper functions for boxes. # # Categories of helper functions: # 1. Overlap functions. # 2. Spatial-aware object embedding functions. # 3. Misc. # import numpy as np from scipy.stats import entropy from sklearn.metrics import average_precision_score # # Helper functions category 1: Overlap functions. # # # 1.1...
992,681
1d75b72a1e6fb6cb6d30ed64f3d0e0b6ba18e4ba
# -*- coding: utf-8 -*- from lai.config import DATABASE UPDATE_RESPONSE = 1 COMMIT_RESPONSE = 2 class DatabaseException(Exception): pass class Database(object): """Factory""" def __new__(cls, engine=None, config=None): if engine is None: engine = DATABASE['ENGINE'] if confi...
992,682
fc7f44d4107caddf0b8a3e5e6733bb6e7fd21561
import random import util from Queue import Queue class DecisionTree: def __init__(self, debugging=False): self.root = None self.debugging = debugging def fit(self, examples, attributes, fitness_metric='information_gain', pruning=False): self.attributes = attributes ...
992,683
2b21269689985d7aa74b36859ff76baa7b50bda6
# Spy-Pi code version 2 # takes an image every minute, and saves 1 week (7 days) of data # it also makes the most current image available # adapted from the book # Make: JUMPSTARTING Raspberry Pi Vision # Sandy Antunes and James West # Maker Media, Inc import os import time import shutil # choose a delay time in seco...
992,684
6c196205a86c0edf2354075792be34f699d9b570
from django.db import models from django.contrib.auth.models import User class Patient(models.Model): name = models.CharField(max_length=300,null=False) gender_choices = [('M', 'Male'), ('F', 'Female')] blood_group_choices = [('A+','A+'),('A-','A-'),('B+','B+') ,('B-','B-'),('O+','O+'),('O-','O-'),...
992,685
41058e8c13227ca2f38e1c86efadeab687025b2a
#!/usr/bin/python3 def is_sorted(arr, N) : for i in range(N-1) : if arr[i] > arr[i+1] : return False return True def sort_arr(arr, D, N) : swaps = 0 for i in range(N) : if is_sorted(arr, N) : return swaps to_be_swapped = None for j in range(i+1, ...
992,686
497c5980dce27ffe702598db7da323f424b50828
import random import matplotlib.pyplot as plt import numpy as np import numpy.random import math def SavePlot(X, Y, w_t, w, count): filename = './Plots/Plot_' + str(count) + '.png' Red = X[Y[:]==-1, :] # print (Red) # print () Blue = X[Y[:]==1, :] # print (Blue) plt.axis((0,1,0,1)) plt.sca...
992,687
f9adf4b6c9566336603902cced353b889c944dbb
import numpy as np from mmdet3d.apis import inference_detector, init_detector from kitti_util import * class Detector: def __init__(self, checkpoint, config, calib_file, from_video=True): self.model = init_detector(config, checkpoint) self.calib = Calibration(calib_file, from_video=from_video) ...
992,688
197f28cfceb3959e2f45c7a5662bf1b2527862e6
import time import wiringpi as wp from constants import * from utils import angle_to_time, cm_to_time gpio = wp.GPIO(wp.GPIO.WPI_MODE_PINS) class Car: def __init__(self): self.setup() def setup(self): wp.wiringPiSetup() for pin in OUTPUTS: wp.pinMode(pin, 1) for ...
992,689
b007ab218561947c65d17e3ccec9841a1e65d71a
from django.conf.urls import url from . import views app_name = 'notepad' urlpatterns = [ url(r'^notepad/random$', views.random, name='random'), url(r'^notepad/topage$', views.topage, name='topage'), url(r'^notepad/add/(?P<page_name>.+)$', views.add, name='add'), url(r'^notepad/hideform/(?P<page_name>.+)$', v...
992,690
2bd2f4ce7f5eaa99c71b82d5ab56bca2891b8778
"""Test snippets to try out stuff from the book "Gaussian Processes for Machine Learning" by Rasmussen & Williams (a.k.a. R&W in the docstrings below).""" import sys from math import pi, log import numpy as np from numpy import dot, identity, transpose import scipy import scipy.stats as stats from scipy.linalg import...
992,691
551a974e4f676b539c1c435a0b352d0b70c3bb97
# -*- coding: utf-8 -*- # Generated by Django 1.11.10 on 2018-03-05 08:59 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('beaches', '0003_auto_20180305_0050'), ] operations = [ migrations.AddField...
992,692
8347763d97e724af4a7bd5f007c7a9f2a920a77a
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-05-04 02:14 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('hpscil', '0001_initial'), ] operations = [ migrations.AlterField( ...
992,693
114bb5380d86a64975194b63228510ad60af73b9
# -*- coding:utf-8 -*- ''' Test module for renju. @auther: Arata Kokubun @date: 2018/1/3 ''' # Imports import unittest as ut from unittest.mock import MagicMock from parameterized import parameterized from gym_renju.envs.core.domain.player import PlayerColor from gym_renju.envs.renju import RenjuBoard, RenjuState fr...
992,694
d349fa8eb2fcf6faafbd462d21e1bf946e7004d2
import mock import libvirt import difflib import unittest from see.context.resources import lxc def compare(text1, text2): """Utility function for comparing text and returining differences.""" diff = difflib.ndiff(text1.splitlines(True), text2.splitlines(True)) return '\n' + '\n'.join(diff) class Domai...
992,695
11ff604767060ce3d99bdc80c6f6bfc44f3c25a9
import pandas as pd def clean_data(): ''' Since the data of the api is 24 hours, I hope it is more like the data of the url. :return: ''' # future temperatures from api are converted to day and night temperature future_temperature_from_api = pd.read_csv('future_temperature_from_api.csv') d...
992,696
a8e97d7cf95b17b77f8a91ca9a009f924a20a45e
from django.shortcuts import render from django.views.generic import ListView from rest_framework.viewsets import ModelViewSet from rest_framework.permissions import IsAuthenticated from .models import LectureHistory from .serializers import LectureHistoryChangeSerializer, LectureHistorySerachSerializer from student.m...
992,697
78691aece7b8492c4bde013011b27a3d90cb9ddb
#!/usr/bin/python3.7 # 1. Самые активные участники. Таблица из 2 столбцов: login автора, количество его # коммитов. Таблица отсортирована по количеству коммитов по убыванию. Не # более 30 строк. ​ Анализ производится на заданном периоде времени и заданной # ветке. import requests import ApiBase url = f"https://api....
992,698
f8ad2bc76e3cb5f49c85586cbca9b5ee3a96e8b9
#!/usr/bin/env python #encoding: utf-8 from PyQt4.QtGui import QWidget,QTableWidget,QTableWidgetItem,QApplication,QTableWidgetSelectionRange,QAbstractItemView from PyQt4.QtCore import Qt, QString,QStringList from PyQt4.QtTest import QTest import unittest import sys sys.path.append("..") import main import random from ...
992,699
59a3423cf4f0314258910eb508e29cef97f37c4b
import threading from project.ctrl.Controller import Controller from project.model.exception.problemException import ProblemException from project.model.problem.EvolutionaryProblem import EvolutionaryProblem from project.model.problem.Problem import Problem from project.model.state.State import State class ProblemCo...