index
int64
0
1,000k
blob_id
stringlengths
40
40
code
stringlengths
7
10.4M
10,800
4763e6940db1ad4d8032071bfd6a4528d59bdf41
from .. import pyplot as plt def plot_grid2d(grid, *args, ax=None, boundaries_on=False, **kwargs): _, rows, cols = grid.shape if ax is None: ax = plt.gca() if boundaries_on: for i in range(rows): ax.plot(*grid[:2, i, :], *args, **kwargs) for i in range(cols): ...
10,801
7d2c6b339bcb88f9da28454b76600ac8119cb619
### copied by hand all laws and ordos from https://www.legifrance.gouv.fr/liste/lois ### in "french law initial data.pages" and "french ordos initial data.pages" ### !!! for next scrapping just add new laws and ordos since last scrap ### copy everything in excel/google spreadsheets, sort alphabetically, delete extra ...
10,802
ab2efe6b0cd740b38910269f716ac2314f9cc970
# _*_ coding: utf-8 _*_ # descrption: some small functions import os import cv2 from finger import * # get all images path from a folder def get_all_image(folder): files = os.listdir(folder) files_path = [] for i in files: temp = folder + '/' + i files_path.append(temp) return files_pat...
10,803
e18d050df152f7e91111624b25eb71d209152850
import tensorflow as tf from tensorflow.keras.models import load_model, model_from_json if __name__ == '__main__': import argparse parser = argparse.ArgumentParser() parser.add_argument('model', default='model') parser.add_argument('--resume', '-r') args = parser.parse_args() if args.resume i...
10,804
a54cf8aecc3bca63f8c75aaaa1b0ff27f309f380
# 647. Palindromic Substrings # Medium # Given a string, your task is to count how many palindromic substrings # in this string. # The substrings with different start indexes or end indexes are counted # as different substrings even they consist of same characters. # Example 1: # Input: "abc" # Output: 3 # Explanat...
10,805
c776b4ee78e2f45cf028436a2d1f706bc2efa073
# -*- coding:utf-8 -*- """ 复用浏览器 """ from time import sleep from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.by import By class TestDemo(): def setup(self): option = Options() option.debugger_address = '127.0.0.1:9222' sel...
10,806
96de1dd2fa80a9118d3cd22f0340264a66198d55
TOKEN="TOKEN" PREFIX="fjo " DESCRIPTION="A fun discord bot." OWNERS=[104933285506908160, 224895364480630784] extensions = [ "jishaku", "cogs.commands.utility", "cogs.events.error_handler", "cogs.commands.prose_edda" ]
10,807
d7113822b9045b51c1e16aed70dc67faec52f3d2
# coding=utf-8 import sys import argparse import time import os from helpers.ssh_manager import SSHManager from vm_manager.models.environment import Environment # env = Environment() vm_names = [] ssh = SSHManager() # Step 1. Prepare vms for image in env.get_images_list(): vm_name = env.get_vm_name_from_config(env...
10,808
24279a007dfae71c2debe9511d8937a87b472ebb
# -*- coding: utf-8 -* from sklearn.linear_model import LogisticRegression, LogisticRegressionCV from sklearn.metrics import classification_report, accuracy_score from sklearn.preprocessing import StandardScaler from model.load_data import load_data, split_test_data from sklearn.metrics import roc_auc_score def LR(X_...
10,809
94b2104c2199c60deffcc62ba8339c8f8f907b53
from dolfin import * import numpy as np import scipy.sparse as sp import scipy.interpolate import matplotlib.pyplot as plt import matplotlib.patches as patches from matplotlib.colors import BoundaryNorm from matplotlib.ticker import MaxNLocator from datetime import date import os import math import sys import h5py impo...
10,810
b4bb96f2395f0e522724256837a81136974123b0
#!/usr/bin/env python # -*- coding: utf-8 -*- # Uninformed Search Algorithm __author__ = "Gonzalo Chacaltana Buleje" __email__ = "gchacaltanab@gmail.com" from Node import Node class UnniformedSearchAlgorithm(object): def __init__(self, listNodes, searched): self.listNodes = listNodes self.searche...
10,811
fef95e5b425674268f5146b5b22e777fdcbcbec5
class Solution: def createTargetArray(self, nums, index): i, res = 0, [] while i < len(index): res.insert(index[i], nums[i]) i += 1 return res if __name__ == '__main__': nums = [0,1,2,3,4] index = [0,1,2,2,1] sol = Solution().createTar...
10,812
139f8cdcb7a9e0730130800285a9908d3cffa3ab
import random class Dices: def __init__(self): self.dice1 = 0 self.dice2 = 0 def roll(self): self.dice1 = random.randint(1, 6) self.dice2 = random.randint(1, 6) x = (self.dice1, self.dice2) return x
10,813
ac6ed5e43342dbe0178c7a7443a6c6163517a2de
from meses_2021 import meses #Horarios de salida : general = 5 de la tarde, viernes 4 de la tarde general = 17 viernes = 16 datos_almacenados={} print("*****Control de Horario*****") print("") mes_in = input("Indique el mes: ") while True: mes = meses(mes_in) dia = input("Ingrese el dia (formato: dia 00)"...
10,814
3ab6b4cef47371b680599211546245647e68d624
import os import PIL.Image import time from Tkinter import * # =============================================Initialize Variables=============================================# size = 256, 256 # Size of thumbnail image displayed newValue = list((0, 0, 0)) convMask = 3 normalizer = 1 errorMessage = "" previewBox = 0 c...
10,815
bf1293b005fc57cb9116e972342f909a39d63004
import re; from importlib.metadata import requires from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from django.contrib import messages from django.db.models import Q, Prefetch from .models import Project, Tag from .utils import searchProjects, paginateProjects f...
10,816
081457ccf83814231237a64e7f9f94def27cde91
#代理模式 Proxy ''' 为其他对象提供一种代理以控制这个对象的访问 适用性: 在需要比较通用复杂的对象指针代替简单的指针的时候,使用Proxy模式。 1.远程代理 为一个对象在不同的地址空间提供局部代表 2.虚代理 根据需要创建开销很大的对象 3.保护代理 控制对原始对象的访问。 4.智能指引 取代了简单的指针,它在访问对象时只需一些附加操作。 组成: 抽象角色:通过接口或抽象类声明真实角色的业务方法。 代理角色:实现抽象角色,是真实角色的代理,通过真实角色的业务逻辑方法 来实现抽象方法,并可以附件自己的操作。 真实角色:实现抽象角色,定义真实角色所要实现的业务逻辑,供代理角色调用。 ''' class Jurisd...
10,817
def90130940db577a708008753641bb09025d10d
# Question Link:- https://codeforces.com/contest/1430/problem/A mex = 1005 save = [[] for i in range(mex)] can = [False for i in range(mex)] def init(): for i in range(mex//3+2): for j in range(mex//5+2): for k in range(mex//7+2): val = i*3 + j*5+k*7 if val<=10...
10,818
b6cad51218d2b168570ebe444e43c0847f9da90c
# seleniumbase package __version__ = "1.61.0"
10,819
91299e3b1ec77937b2810a1198b696c4f3793a20
from scrapy import cmdline # # cmdline.execute('scrapy crawl Dmu'.split()) # cmdline.execute('scrapy crawl arts'.split()) cmdline.execute('scrapy crawl HarperAdams_g'.split()) # cmdline.execute('scrapy crawl Southampton'.split()) # cmdline.execute('scrapy crawl StAndrews_g'.split()) # cmdline.execute('scrapy crawl Hud'...
10,820
fd85289b6b40e72dcd59e270cd2d849cbd571b1c
# # Definition for binary tree: # class Tree(object): # def __init__(self, x): # self.value = x # self.left = None # self.right = None ''' def restoreBinaryTree(inorder, preorder): PO_0=preorder.pop(0) #preorder naught IO_0=inorder.pop(0) #inorder naught t=Tree(PO_0) #tree bottom root...
10,821
393e481f8e21d2b3f4a36bb50dc48d330a7b8733
import sys, os from db.interface import * from learning import interface from analysis import graphutils from learning import consolidateFeatures from mlabwrap import mlab import numpy as np import datetime LEARNING_ROOT="learning/" FEATURES="features" LABELS="ytrain" def main(args): db = args[0] date1 = args[1] d...
10,822
3703a96e6dd3e199a9a2cbe2c92d961a095743e2
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Checklist.name' db.add_column(u'core_checklist', 'name', ...
10,823
0bd126c5b7caee9b5c4c7746699bfba5ede9d0f5
import numpy as np, omnical, aipy import subprocess, datetime, os from astropy.io import fits import copy import heracal from scipy.io.idl import readsav def unwrap(arr): brr = np.unwrap(arr) crr = [] for ii in range(1,brr.size): crr.append(brr[ii]-brr[ii-1]) crr = np.unwrap(crr) nn = np.round(crr...
10,824
fd04968d347bf6a7ccf5efd19c93f38bf54db831
class CascadeFaceDetectorConfig: classifier_path = 'cascades/haarcascade_frontalface_default.xml' scale_factor = 1.2 min_neighbors = 5 min_size = (20, 20) class OpencvFaceDetectorConfig: prototxt_path = 'models/deploy.prototxt.txt' model_weights_path = 'models/res10_300x300_ssd_iter_140000.caf...
10,825
7c36d46285274339814e0a709853aea2ecfabab9
import pandas as pd import numpy as np from os import path from sklearn.preprocessing import StandardScaler from sklearn.cross_validation import KFold from sklearn.metrics import silhouette_score from sklearn.cluster import KMeans from sklearn.decomposition import PCA from sklearn.svm import SVC from sklearn.ensemble...
10,826
b520bed919f3841a14721fdbf74567eea85293e1
# Generated by Django 3.1.7 on 2021-02-23 13:42 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('audios', '0001_initial'), ] operations = [ migrations.AlterModelOptions( name='audioclass', options={'verbose_name':...
10,827
b5a02d33e00c317e96f403f2029fc578253368b9
#!/usr/bin/env python3 import wpilib import wpilib.buttons from wpilib import RobotDrive import networktables from robotpy_ext.common_drivers import navx class MyRobot(wpilib.IterativeRobot): '''Insert early definitions for Channels of Speed controls''' # Channels for the wheels and motors fro...
10,828
9f33f05a4b5b9da95a0facd1000222dc450b42a9
__author__ = 'Filip' TURN_ON = 0 TURN_OFF = 1 TOGGLE = 3 with open('input.txt') as f: lines = f.readlines() lights = [[0 for x in range(1000)] for y in range(1000)] for line in lines: split_line = line.split(' ') if 'turn' in line: start_coord = split_line[2] stop_coord = split_line[4] ...
10,829
6294170ebab420501ef25d4fdafc661337d1ca2d
# # -*- coding:utf-8 -*- # from splinter import Browser # browser = Browser("firefox") # browser.visit("http://google.com") # browser.fill("q", "splinter - python acceptance testing for web applications") # button = browser.find_by_name("btnG") # button.click() # assert browser.is_text_present("splinter.readthedocs....
10,830
10fa599628f66bd409ebcfd501fa9a23a3a1b99d
import sqlalchemy from .db_session import SqlAlchemyBase class Notice(SqlAlchemyBase): __tablename__ = 'notices' id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True, autoincrement=True) name = sqlalchemy.Column(sqlalchemy.Integer, nullable=False) text = sqlalchemy.Column(sqlalchemy.Integer, n...
10,831
53471d8f7241403eb3a041fd408387835fe90d4f
class Solution: def findNthDigit(self, n: int) -> int: k, l, cnt = 1, 1, 9 while n > cnt: n -= cnt k *= 10 l += 1 cnt = 9*k*l n -= 1 q, r = n // l, n % l k += q return int(str(k)[r])
10,832
53d83c394a56200be0039622b3c166aa26719031
class Aula: def __init__(self, professor, quantidade, sala, disciplina, id=0): self.id = id self.professor = professor self.quantidade = quantidade self.sala = sala self.disciplina = disciplina
10,833
f99d89404cc802a76a20cde6d3ba2ae3ad2ca938
# Generated by Django 3.2 on 2021-05-11 07:43 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('api', '0008_auto_20210510_1805'), ] operations = [ migrations.AlterField( model_name='route', name='delivery', ...
10,834
849b38a243a764d7a12cfe586f4f187624cca96d
import numpy as np import h5py # datafile = '/net/liuwenran/datasets/DEAP/experiment/ex3_cnn_face/finalExData_shuffled/test.h5' # originFile = h5py.File(datafile,'r') # keys = originFile.keys() # originLabel = originFile[keys[2]].value result = np.load('output/result_deap_seperate6w_savefirst.npy') originLabel = np.l...
10,835
56e46c61b7dc783cd9453cab6bcddefd6cf13746
# coding:utf-8 ''' Created on Sep 26, 2013 @author: likaiguo.happy@gmail.com ''' WRITE_LOG = True STAR_LIST = [i / 2.0 for i in range(1, 11)] # 评分相关全局变量 INDUSTRY_CATAGORY_LIST = [u'互联网/电子商务' , u'计算机软件', u'IT服务(系统/数据/维护)/多领域经营', u'通信/电信/网络设备', \ u'计算机硬件及网络设备' , u'通信/电信运营、增值服务', u'网络游戏', u...
10,836
5a1279fbabe887f17d6030091714ce10c60c1752
#!env python import time import numpy as np from OpenGL.GL import * from OpenGL.GLU import * from OpenGL.GLUT import * from PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * from PyQt5.QtOpenGL import * from Bee.gui.base.delta import delta from Bee.util import resources from Bee.gui.base...
10,837
0c0a3298259eb206d181dcd7c72eecb25c0e600f
import os import discord import requests import json from discord.ext import commands from main_cog import main_cog from music_cog import music_cog bot = commands.Bot(command_prefix='/') bot.remove_command('help') bot.add_cog(main_cog(bot)) bot.add_cog(music_cog(bot)) token = os.getenv('TOKEN') bot.run(token)
10,838
4075f45482d512263bfb8c607c74559e35f591da
import discord from discord.ext import commands import os import sys import passwords as keys client = commands.Bot(command_prefix = '!') client.remove_command('help') @client.event async def on_ready(): servers = client.guilds for server in servers: for channel in server.text_channels: ...
10,839
26be7335a42081fd516cbef552a02d99d7fad91d
import unittest import math from unittest import mock from typing import Optional, Dict, Set, Any, Union import sympy from qupulse.parameter_scope import Scope, DictScope from qupulse.utils.types import ChannelID from qupulse.expressions import Expression, ExpressionScalar from qupulse.pulses import ConstantPT, Funct...
10,840
ff82da4c6cf77fe9b5bc0c4569c4cd89bc8f982b
# -*- coding: utf-8 -*- """ @author: C. J. F. Delcourt """ #%% importing required packages import numpy as np import pandas as pd import matplotlib.pyplot as plt # setting the working directory in which the excel files from # Delcourt and Veraverbeke (2022) were saved wdir = "" # loading size-class-spe...
10,841
46f387a0258ecfc0df9648b46604d668569e54e5
import pytesseract as tess tess.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe' from PIL import Image import cv2 import numpy as np import pytesseract as tess from PIL import Image #output file output=open('out.txt', 'w') imgtext= Image.open('ocr2.png') text=tess.image_to_string(imgtext) o...
10,842
6ecf255b90f2dbbaf93ba181bbe23591c019f89f
import scipy as sp import numpy as np from scipy import log,exp,sqrt,stats s0=100 # Stock price today x=100 # Strike price barrier=150 # Barrier level T=1 # Maturity in years r=0.08 # Risk-free rate sigma=0.3 # Annualized volatility n_simulation = 1000 ...
10,843
882cd84ee499ff0e10ccfacae057e9c0423a6701
from unsup_vvs.network_training.tpu_old_dps.full_imagenet_input import ImageNetInput from unsup_vvs.network_training.tpu_old_dps.rp_imagenet_input import RP_ImageNetInput from unsup_vvs.network_training.tpu_old_dps.rp_pbrscenenet_input import PBRSceneNetDepthMltInput from unsup_vvs.network_training.tpu_old_dps.col_imag...
10,844
c0d791e4888b59683013ec76d71665693fed722d
#script in Python 3.7 import numpy as np import matplotlib.pyplot as plt import math # S = susceptible individuals # I = infectious individuals # β = infectious rate, controls the rate of spread which represents the probability of transmitting disease between a susceptible and an infectious individual # γ = recovery r...
10,845
57bbde84ead319e3ab1edcf9548f2934057d6172
''' URL handler functions. ''' import asyncio import logging;logging.basicConfig(level=logging.INFO) from coroutine_web import get,post from models import User,Blog,Comment __author__='luibebetter' @get('/') async def index(request): logging.info('hello') users=await User.findwhere() return { '__templ...
10,846
9486430f7f6ee00e352f6d5f192d86156a356d1e
import pygame class label: def __init__(self, posX, posY, text, fontSize): self.posX = posX self.posY = posY self.text = text self.fontSize = fontSize def display(self, fenetre): myfont = pygame.font.SysFont("bitstreamverasans", self.fontSize) label = myfont.r...
10,847
8057326fabd43ea2771007bf7b39ed087ca051b3
print('='*20+' REAL PARA DÓLAR '+'='*20) real = float(input('Quanto dinheiro você tem em reais:')) dolar = real//4.15 print('Com R${:.2f} reais você pode comprar US${:.2f}! :D'.format(real,dolar))
10,848
ed3dcf5949459b2d2683c6e00fe32173c172c5b9
import os config=1 base_dir='/data' TRAIN_DATA_FOLDER_PATH = '/CORPUS/collection_2018/*.txt' TOPICS_FOLDER_PATH='/CORPUS/topics/' TRAIN_TWEETS_2018='/CORPUS/training_data_embeddings/train_data_2018.json' STATS_SKIP_GRAM='/CORPUS/embeddings/word2vec/skip-gram/stats.txt' SKIP_GRAM_VECTORS='/CORPUS/embeddings/word2vec/sk...
10,849
051115cb4f92a9e2190a137f6f962f91b14a8c4b
# Generated by Django 3.1.7 on 2021-04-19 12:40 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('shop', '0002_auto_20210419_1203'), ] operations = [ migrations.AlterField( model_name='product', name='rating', ...
10,850
9ca2d51106f1e0ba4336627b682a4a6804d3d780
from nose.plugins import Plugin import warnings import sys import logging log = logging.getLogger() def import_item(name): """Import and return ``bar`` given the string ``foo.bar``. Calling ``bar = import_item("foo.bar")`` is the functional equivalent of executing the code ``from foo import bar``. ...
10,851
f5c2886a1db5a8dff6fe87414c4b8be1486a68da
import datetime from django.db import models from django.utils import timezone # Create your models here. class Issue(models.Model): issue_title = models.CharField(max_length=200) STATUS_LIST = (('Draft', 'Draft'), ('Ready to review', 'Ready to review'), ('Approved', 'App...
10,852
71315a3c867bc0c386139cb2e2ada264b26bdaa8
# -*- coding: utf-8 -*- """ opentelematicsapi This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ). """ class Driver(object): """Implementation of the 'Driver' model. TODO: type model description here. Attributes: id (string): The id of this Driver object ...
10,853
37750bbb733b92c7e0da72e695b34c8130356b4d
money=int(input("小明身上有多少錢:")) kind=int(input("販賣機有幾種飲料:")) list1=[] total=0 for i in range(kind): price=int(input()) list1.append(price) for i in range(kind): if(money>=list1[i]): total+=1 print(total)
10,854
951162ce55c2729b6ec1a7667761d1074ad2ecc0
import os from lxml.cssselect import CSSSelector from lxml import html import utils import unicodedata import string import re def read_sentence(path): with open(path, "r") as file: doc = html.fromstring("".join(file.readlines())) phrases = [] for el in doc.cssselect(".DocumentPage-content p"): ...
10,855
f6e4572f12ec6583ef0eb06fd4467796bbca8feb
import shutil, random, os import zipfile for foldername in os.listdir("./Data"): data_source = f'./Data/{foldername}/' testing_dir = f'./Testing/{foldername}/' no_of_images = len(os.listdir(data_source)) testing_sample_size = int(no_of_images * 0.3) images = random.sample(os.listdir(data_source),...
10,856
7ba4d2eeb9c7244a7fd4a997a65c700af9b17299
from flask_wtf import FlaskForm from wtforms import StringField, SubmitField from wtforms.validators import Length, DataRequired class SubmitForm(FlaskForm): item_field = StringField('Item')
10,857
f25006477f15e19100de67bde91c876b692eef1d
'''The MNIST dataset ''' from decaf.layers.data import ndarraydata import numpy as np import os class MNISTDataLayer(ndarraydata.NdarrayDataLayer): NUM_TRAIN = 60000 NUM_TEST = 10000 IMAGE_DIM = (28,28) def __init__(self, **kwargs): """Initialize the mnist dataset. kwargs...
10,858
c28994b0232595fa99bf9b9d03778a6612ccd065
from collections import namedtuple Point = namedtuple('Point', 'x,y') pt1 = Point(1, 2) pt2 = Point(3, 4) dot_product = (pt1.x * pt2.x) + (pt1.y * pt2.y) print(dot_product) Car = namedtuple('Car', 'Price Mileage Color Class') xyz = Car(Price=100000, Mileage=30, Color='Red', Class='Y') print(xyz.Color) n = int(i...
10,859
3254a9559c2dd2dc18dc2d11ac176a513c2f785f
""" 题目描述 输入一个链表,按链表从尾到头的顺序返回一个ArrayList。 """ class ListNode: def __init__(self, x): self.val = x self.next = None class Solution1: def printListFromTailToHead(self, listNode): """ 暴力法,遍历链表的结点,把每个结点的元素值保存在一个list中,再按逆序返回该list Note:python中逆序list可以通过列表切片完成list[...
10,860
4e40288a1ae1dd00c32a3503f50aa12f6ab15be1
import logging import unittest from unittest import mock from pika.exceptions import AMQPConnectionError, NackError, UnroutableError from sdc.rabbit import DurableExchangePublisher, ExchangePublisher, QueuePublisher from sdc.rabbit.exceptions import PublishMessageError from sdc.rabbit.test.test_data import test_data ...
10,861
c6cb57b7892c4db9ba6402271cd23ba3fbba4f41
from django.contrib import admin from .models import Key_Words from .models import Entry_Linkpool admin.site.register(Key_Words) admin.site.register(Entry_Linkpool) # Register your models here.
10,862
73d2cc2daa8b6e7e8f626a92c9c5b21200bea732
"""log_importeds table Revision ID: 552caa2b2519 Revises: Create Date: 2018-12-05 19:16:15.071723 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '552caa2b2519' down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands aut...
10,863
443619613a6007ee3fad4eba3ae5f9c60f5bd23f
""" Em python um módulo é lido como se fosse um script. Deste modo, sempre que um módulo for importado será executado como um script. Por isso tomar cuidado ao importar módulos. Se o objetivo for criar um módulo que funcione como um script, sendo executando diretamente, pode ser necessário utilizar __name__ == "__main...
10,864
6f155a5fd253c8a8b8c6b7f17b3d00143af4c983
#Irma Gómez Carmona, A01747743 #Menú con ciclos while para ejecutar las opciones def seleccionarOpcion(): print("") print("Misión 07. Ciclos While") print("Autor: Irma Gómez Carmona ") print("Matrícula: A01747743") print("1. Calcular divisiones") # opciones print("2. Encontrar el mayo...
10,865
20ca751f5eec92f4d7b8e94c03c284a72168c6d0
from django import forms import inspect from ...University.models import University, consignment,representativePush, representative from ...account.models import User class CreateUniversity(forms.ModelForm): class Meta(): model = University fields = '__all__' class CreateRepr(forms.ModelForm): ...
10,866
f171b4ecb91994b93430f81f99fb8130482f31f4
''' Contains game server code ''' import logging import socket from gevent import Greenlet from game.game import GameSession class TelnetServer(): ''' Listener handling for Telnet server, creates session greenlets ''' def __init__(self, host='', port=5555): # IPv4 socket (socket.AF_INET), TCP (sock...
10,867
f96ecf16e551856c48c698f9ecb7b92cd515cf7d
from account.models import NewFeed from django.core.exceptions import ObjectDoesNotExist def newfeed_serialize(user): try: newfeed = user.newfeed except ObjectDoesNotExist: newfeed = NewFeed.objects.create(user = user) return { 'isMinimizedFeed': newfeed.isMinimizedFeed }
10,868
3ca46be5e5871ad590360dc1e3ba653a8ddf4d98
''' Type your code here. ''' string = input() numbers = list(map(int, string.split())) if len(numbers) > 9: print('Too many inputs') else: print(numbers[len(numbers)//2])
10,869
c37f40d2a207efd31a3faef04dd5bcc3f175c1cf
import matplotlib.pyplot as plt import datetime from sklearn.svm import SVR from util.data_io import load_csv def svr(df): # Use only one feature df_X = df.distance_from_central.values df_X = df_X.reshape(len(df_X), 1) svr_rbf = SVR(kernel='rbf', C=1e3, gamma=0.1) svr_lin = SVR(kernel='linear', ...
10,870
b1f601652877b42768c4326b478ef978aa72f5e4
import gzip import sys import csv if len( sys.argv ) != 2: print "Usage: %s ACCESSIONFILE " % sys.argv[0] sys.exit(1) genomes = [] accessions = [] accession_file_name = sys.argv[1] genome_db = {} with gzip.GzipFile( './data/1000genomes_samples.csv.gz' ) as fobj: reader = csv.reader( fobj ) genomes = ...
10,871
781110f6180b093185028db2502fff90042064c6
/Users/noah/anaconda3/lib/python3.7/linecache.py
10,872
40026eb553c509a5b41a09496ebf25275e16bbfc
from alerts.modules.ef.m1_m2.vertedero_emergencia.base import VertederoEmergenciaController from alerts.modules.utils import single_state_create from alerts.modules.base_states import EVENT_STATES from alerts.modules.event_types import DAILY_INSPECTION from base.fields import StringEnum class Controller(VertederoEmer...
10,873
5150bac9a42949389f32d5c6b709ae24217f2d2f
import numpy as np import os import pandas as pd from Bio.Seq import Seq from Bio import SeqIO try: from StringIO import StringIO ## for Python 2 except ImportError: from io import StringIO ## for Python 3 import uuid from joblib import Parallel, delayed import argparse import matplotlib matplotlib.use...
10,874
7c427c41ca50e5ed19b35300731bf06ec4e67611
# Tuple utilities for 2 int tuples def tadd(a, b): return (a[0] + b[0], a[1] + b[1]) def tsub(a, b): return (a[0] - b[0], a[1] - b[1]) def tmul(a, b): return (a[0] * b, a[1] * b) def tdiv(a, b): return (a[0] / b, a[1] / b)
10,875
2226b9ab8d866aef448d467e2fea973ad01427ed
import csv import random input_file = "raw_poem_quality_data.csv" output_file = "qc_poem_quality_data.csv" num_poems = 10 votes_per_poem = 11 random.seed(213) ### sample results from QC HIT with open(input_file, 'w') as file: writer = csv.writer(file, delimiter=',') writer.writerow(['title', 'is_english...
10,876
a72b486161704375521f30fd7925330ca588286e
#!/usr/bin/env python # coding: utf-8 import torch import torch2trt from torch2trt import TRTModule import json import trt_pose.coco import trt_pose.models import time print("Loading topology...") with open('human_pose.json', 'r') as f: human_pose = json.load(f) topology = trt_pose.coco.coco_category_to_topology(...
10,877
d90241c2ef75c92d7d406cb6c8bf54ca3294c978
from django.shortcuts import render # Create your views here. from rest_framework import exceptions from rest_framework.utils import json from rest_framework.views import APIView from rest_framework.serializers import ModelSerializer from rest_framework.authentication import BaseAuthentication from rest_framework.pagi...
10,878
adeb6fc44a5bd0e539fa56a25a219cf9f79bf314
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright (c) 2017-18 Richard Hull and contributors # See LICENSE.md for details. """ Display a TOTP code based on some stored secrets """ import time import RPi.GPIO as GPIO from luma.core.serial import spi from luma.core.virtual import viewport from luma.led_matrix....
10,879
22f1f519caa8b2e60e50dbafa9355fd402eb099b
import faulthandler; faulthandler.enable() from config import imagenet_alexnet_config as config import mxnet as mx import argparse import json import os ap = argparse.ArgumentParser() ap.add_argument("-c", "--checkpoints", required=True, help="path to output checkpoint directory") ap.add_argument("-p", "--prefix", req...
10,880
d1c1bf8eebe7eac1569b050f8a330ae2bcbf990e
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('discussion', '0010_auto_20150805_2052'), ] operations = [ migrations.AlterField( model_name='discussor', ...
10,881
5b55a296c7ddcebf9518a910375e930e68e15f84
""" MARKDOWN --- YamlDesc: CONTENT-ARTICLE Title: Python Pickle Serialization and De-Serialization MetaDescription: Python Pickle Serialization and De-Serialization MetaKeywords: Python Pickle Serialization and De-Serialization Author: Sreelakshmi Radhakrishnan ContentName: python-pickle-serialization --- MARK...
10,882
0c12fa5f3f93e2f89ad2f977a7bc4f0b6b14031c
import time import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.utils.tensorboard import SummaryWriter from torch.utils.data import TensorDataset, DataLoader import argparse from tqdm import tqdm import os import numpy as np from net.ae import AE, KMEANS from net.va...
10,883
975f263eed5ce5a9ac237e5367a1515f521da966
import PySimpleGUI as sg from searchEngine import SearchEngine sg.theme("LightGrey3") layout = [ [sg.Text("Enter your query"), sg.Input(key="IN"),sg.Button("search",bind_return_key=True,key="search")], [sg.Output(size=(100,30))]] def main(): searchEn = SearchEngine() searchEn...
10,884
5a4f10718debe93c385119a160150497f1447202
from framework.Logger import Logger from testsutes.base_testcase import BaseTestCase from pageobject.login import Homepage import time logger=Logger(logger="testmanagercase").getlog() class managerCase(BaseTestCase): def test_manage(self): homepage=Homepage(self.driver) name=homepage.login("admin"...
10,885
6c48a67f9514918cebdefa37f1542b2e8b024a03
""" publish Python objects as various API formats """ import tornado.web import datetime import json import csv import xmlrpclib class Output(): _format = "html" JSON = 'json' _ftype_map = { 'html' : 'text/html', 'xls' : 'application/excel', 'json' : 'text/html', ...
10,886
a10975b98d6f73dc981e6dea6216f4bbc3b753eb
pi = 2. delta = 1. i = 0 while delta > 0.00000000001: i = i + 1 delta = abs(pi - pi * (4. * i ** 2. / (4. * i ** 2. - 1.))) pi = pi * (4. * i ** 2. / (4. * i ** 2. - 1.)) print pi
10,887
52f80aef9c0f4e86f7e25657398f1dc4470080ac
#------------------------------ # functional_tests.test_lists.test_layout_and_styling #------------------------------ # Author: TangJianwei # Create: 2019-02-25 #------------------------------ from selenium.webdriver.common.keys import Keys from .base_lists import ListsTest class LayoutAndStylingTest(ListsTest): ...
10,888
4f18d01b26b56023abd8198ef050331d2805b367
import torch import torch.nn as nn import torch.nn.functional as F class Attention(nn.Module): def __init__(self, query_size, context_size, hidden_size=None): super(Attention, self).__init__() if hidden_size is None: self.hidden_size = context_size self.W_q = nn.Linear(query_s...
10,889
52be2d7f625412d134ae45785cea8562002e8505
import cv2 cap = cv2.VideoCapture(0) #this is webcam while cap.isOpened(): ret , back = cap.read() # back is what the camera is reading and ret is bascially that if a bool like whatever u r reading is successful/not if ret : cv2.imshow("image",back) if cv2.waitKey(10) == ord('q'): ...
10,890
f0e4594080481ea9cd10d1049864c1caff69facd
#!/usr/bin/env python from transitions import Machine from src.modes import Inactive, RTD, Autospray import rospy from agrodrone.srv import SetCompanionMode from agrodrone.msg import CompanionMode DEFAULT_MODE_PUBLISH_RATE = 1 class Modes(Machine): """ This class holds all the modes and also functions as a s...
10,891
b31c9db61ce58da20e3f6aca3b3a36d48b1cffb1
from . import db class PostModel(db.Model): __tablename__ = "posts" id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String, nullable=False) content = db.Column(db.Text, nullable=False) user_id = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=False)
10,892
65c3bdab8e21ed881f34248f1985f1cb9c3b6ef4
from PIL import Image def main(): image = Image.open("eliza.jpg") # image.show() my_pixel = Pixel((40, 100, 254)) print(my_pixel) print("R component:", my_pixel.r) print("RGB tuple:", my_pixel.get_tuple()) # my_pixel.set_rgb(255, 255, 0) # print("RGB tuple after changing it:"...
10,893
de669fdb077f7b04ceeb81a15d11c6195e73519a
''' -Medium- *Math* *GCD* *Binary Search* Write a program to find the n-th ugly number. Ugly numbers are positive integers which are divisible by a or b or c. Example 1: Input: n = 3, a = 2, b = 3, c = 5 Output: 4 Explanation: The ugly numbers are 2, 3, 4, 5, 6, 8, 9, 10... The 3rd is 4. Example 2: Input: n = ...
10,894
94249c16b35cc12105202be06b30c3925f5a8409
# # @lc app=leetcode id=110 lang=python3 # # [110] Balanced Binary Tree # # @lc code=start # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def isBalanced(self, root: TreeNode) -> bool:...
10,895
aa8b7a846cb3261f2a5d5e8a48c49a89868ce6c9
""" Copyright (C) 2020 Piek Solutions LLC Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. ...
10,896
aa4bfd8f63df8690c7507234be5de1e61516a5ee
import sys import random # Gen sınıfı class gen: sample=None fitness=None def __init__(self,sample_value,fitness_value): self.sample=sample_value self.fitness=fitness_value # Fonksiyonu tanımla def calculate_fitness(value): function=15*value-value*value return function def generat...
10,897
ddd7a2de462086904ea33d207db4ddfe97a5f090
import random import sys import time def _simulate(n, p): return len([1 for _ in range(n) if random.random() < p]) def main(): p = 0 sim = "--simulate" in sys.argv args = [e for e in sys.argv if e != "--simulate"] if len(args) > 1: N = int(args[1]) else: N = random.randint(5,...
10,898
b668874db5535af924577f8abae3623385287b59
def f(x): from math import sqrt return sqrt(1-x**2) import matplotlib.pyplot as plt import time x, dx = -0.5, 0.1 X, Y, Points = [], [], [] while x <= 0.5: y = f(x) point = (x, y) X.append(x) Y.append(y) Points.append(point) x += dx plt.plot(X, Y, 'y') plt.grid() #plt.show() pl...
10,899
dc9fed3b80188ff3e257deae452721d973b7a4b7
"""Various non-core functions.""" import tensorflow as tf import numpy as np import pdb import constants #################### ### THRESHOLDING ### #################### def get_threshold_mask(hparams, x): """Threshold the mixtures to 1 or 0 for each TF bin. Input: X_mixtures: B x T x F Output: X_mixtur...