index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
13,700 | bc444d42940bbf2070916b9ca8db688910c98086 | import cv2
import numpy as np
import face_recognition
# Load and encode images
imgElon = face_recognition.load_image_file('ImageBasic/Elon Musk.jpg')
imgElon = cv2.cvtColor(imgElon, cv2.COLOR_BGR2RGB)
imgTest = face_recognition.load_image_file('ImageBasic/elon musky test.jpg')
imgTest = cv2.cvtColor(imgTest, cv2.COLOR... |
13,701 | 17574dfb4bb968b8966e8ca24a29c7bda3af9ad2 | import matplotlib
matplotlib.use('Agg')
import json
import numpy as np
from collections import Counter
import matplotlib.pyplot as plt
import sys
NODES_FILE = sys.argv[1] #'results/tree/gisaid_hcov-19_test.nodes.json'
DELETIONS_COUNTER = sys.argv[2] #'results/alignment/gisaid_hcov-19_test.deletions_counter.npy'
REF_DI... |
13,702 | 76c07f33590fa29e86cdc7024edae2e64c2b8ab4 | # Generated by Django 2.1 on 2018-09-04 08:02
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Book',
fields=[
('id', models... |
13,703 | 5f7a999f3144615743a5e73c778d635f78993b67 | import datetime
from twilio.rest import Client
import requests
import pandas
import csv
import config
STOCK_NAME = "TSLA"
COMPANY_NAME = "Tesla Inc"
STOCK_ENDPOINT = "https://www.alphavantage.co/query"
NEWS_ENDPOINT = "https://newsapi.org/v2/everything"
## STEP 1: Use https://www.alphavantage.co/documentation/#dail... |
13,704 | 5feb9f434414856f8bda00a599650f9b6c3f0460 | import copy
import numpy as np
import pandas as pd
from scipy import sparse
def put_column(base, ix, v):
if isinstance(v, pd.Series):
v = v.values
if isinstance(base, np.ndarray) or sparse.issparse(base):
shape = base[:, ix].shape
base[:, ix] = v.reshape(shape)
elif isinstance(bas... |
13,705 | 14caf4d4f39ff47c2b399c4887c0ba57fbe8afab | # para input perceber que é um número tenho que declarar o tipo da variável
n1 = int(input('Digite um número: '))
n2 = int(input('Digite outro número: '))
# para somar, não preciso declara o tipo
s = n1 + n2
# type mostra o tipo de variável
print("O tipo de variável é :", type(s))
print("A soma desses números é:", s)
#... |
13,706 | 8170b10f6d66faaed2a1ee0d191c20af848c8158 |
"""
Implementations of goodness-of-fit tests.
Goodness-of-fit
---------------
.. autosummary::
:toctree: generated/
ChiSquareTest
JarqueBera
References
----------
B. W. Yap & C. H. Sim (2011) Comparisons of various types of normality tests,
Journal of Statistical Computation and Simulation, 81:12,... |
13,707 | 5347170ae8a7fbf62e97716c36ed9cd771c4a3a4 |
import pygame
import random
import math
pygame.mixer.pre_init(44100, 16, 2, 4096)
pygame.init()
from pygame import mixer
# Screen size, game caption and game icon
screen = pygame.display.set_mode((880, 680))
pygame.display.set_caption("Corona Invaders")
icon = pygame.image.load("virus.png")
pygame.display.set_icon(... |
13,708 | c0d2987b6b8bd16aeed3648fcf7883374c8cf6c9 | """Processing objects typically used as losses.
These classes are quite similar to Nodes (subclasses, in fact), with the
important distinction that each object has a singular scalar output.
"""
import theano.tensor as T
import optimus.core as core
from optimus.nodes import Node
import optimus.functions as functions
... |
13,709 | e27c9b8a5dbb135c9c864e3596f465024938be16 | #!/usr/bin/python3
def best_score(my_dict):
if my_dict:
scores = []
for i, j in my_dict.items():
scores.append(j)
scores.sort()
high_score = scores[-1]
for i, j in my_dict.items():
if my_dict[i] is high_score:
return i
return None
|
13,710 | 3566d80d5705529d32714b1ceb369656513d8f5f | def solution(str1, str2):
j1, j2 = [], []
for i in range(len(str1) - 1):
if str1[i:i + 2].isalpha():
j1.append(str1[i:i + 2].lower())
for i in range(len(str2) - 1):
if str2[i:i + 2].isalpha():
j2.append(str2[i:i + 2].lower())
if not j1 and not j2: return 65536
... |
13,711 | ffd0ba4cba3ce4205e49331f4630eeaaf25a91ef | '''
@Time :
@Author : Jingsen Zheng
@File : waymo_dataset_loader
@Brief :
'''
from __future__ import (
division,
absolute_import,
with_statement,
print_function,
unicode_literals,
)
import math
import torch
import torch.utils.data as data
import numpy as np
import os
import s... |
13,712 | 40ab219246e17cbea2f5693d9f61e8dc6415e552 | from flask_wtf import FlaskForm
from wtforms import StringField, SelectField, SubmitField
from wtforms.fields.html5 import EmailField
from wtforms.validators import DataRequired, Email
class AddTaskForm(FlaskForm):
task_name = StringField('To Do Item', validators=[DataRequired()])
email = EmailField('Email', v... |
13,713 | 8bef12e64268b458794a37edd941e6adabe19f87 | from eagertools import domap, emap
from hypothesis import given
import hypothesis.strategies as ST
from util import no_args, one_arg, two_args
def test_empty_input():
assert emap(no_args, []) == []
@given(ST.lists(ST.integers()))
def test_one_iter(vals):
assert emap(one_arg, vals) == list(map(one_arg, vals... |
13,714 | a212442d91b2807e6353f21b0a68c4ee74ec8db9 | #
# PySNMP MIB module TPT-POLICY-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TPT-POLICY-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:26:23 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2... |
13,715 | 0dd82e2b99a581645866783774d55869889b751a | '''Tools for simulating long processes, randomly erroring, infinite-loop hangs, memory leaks, and
CPU-overload situations. Run with caution.
'''
import multiprocessing
import random
import sys
import time
# Most Python errors.
# Note, Exception does not catch these exceptions: GeneratorExit, KeyboardInterrupt, Syste... |
13,716 | b1eac345d00e5a9ada05f46763d354452d98ac5e | __author__ = 'Tony Liu'
# -*- coding: utf-8 -*-
#pass 不做任何事情,一般用做占位语句。
for letter in "python":
if letter == "h":
pass
print("pass块")
print(letter) |
13,717 | 95d4c3e58550cdf45c85d483b11090fa3132a58c | from pyramid.threadlocal import get_current_request
from pyramid.exceptions import ConfigurationError
from pyramid.security import authenticated_userid
from pyramid.url import route_url
from git import Repo
def add_renderer_globals(event):
""" A subscriber to the ``pyramid.events.BeforeRender`` events. Updates
... |
13,718 | 77d748856979b1ac0545037973c3f97bbde2c30e | import sys
user = {
"first_name": "Егор",
"last_name": "Михеев",
"sex": "m"
}
user[sys.argv[1]] = sys.argv[2]
print(user)
"""
ИЗМЕНЕНИЕ ЗНАЧЕНИЯ
Ниже в редакторе содержится словарь user
с пользовательскими данными.
Напишите программу,
которая принимает из аргументов командной строки два параметра:
к... |
13,719 | b0b5e59651925d1af47fa6b5db8848fb406e1a76 | from gradientone import InstrumentDataHandler
from gradientone import query_to_dict
from gradientone import create_psettings
from gradientone import convert_str_to_cha_list
from gradientone import render_json_cached
from gradientone import author_creation
from onedb import BscopeDB
from onedb import BscopeDB_key
import... |
13,720 | 191fd46978f6c25c4b39d7419e368282f0c8aa5a |
#Python doesnt have a main() function unless you code for it
#Python interpreter only executes the launched script file internally known as __main__
#if the launched script wants to reuse qnd run code from another module, the imported or
#called module will be known to the Python interpreter with its own file "name" a... |
13,721 | 659ee335556058f13b555ce7b5e98538f7ac9d0e | '''
Created on Nov 2, 2012
@author: marek
'''
import unittest
from sk.marek.barak.app.UtilClass import Util
class Test(unittest.TestCase):
def setUp(self):
self.__util__ = Util()
def testIsInteger(self):
self.assertTrue(self.__util__.isInteger(10))
def testIsNotINteger(self):
... |
13,722 | ee2ec4c30b5735f69a7280dd318139165040f6e4 | from BlissFramework import BaseComponents
from BlissFramework import Icons
import math
from qt import *
import logging
from BlissFramework.Utils import widget_colors
'''
Motor control brick using a spin box (as an input field, and for the steps)
and buttons to move the motors (while pressed)
'''
__category__ = 'Motor... |
13,723 | c8ebb2547db3da81d6b48f125760fcf9460bbf1c | import sys
input = sys.stdin.readline
from collections import deque
# 상하좌우
dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]
# n, m을 입력받음
n, m = map(int, input().split())
# 미로정보를 입력받음
maze = []
for _ in range(n):
maze.append(list(input().rstrip()))
# bfs를 위한 visited 리스트 생성
visited = [[False] * m for _ in range(n)]
# 큐 생성하... |
13,724 | 70bb4a3398cb0e1255d3f5bad1ad3d26feb9de83 | import sys
import numpy as np
import matplotlib.pyplot as plt
import plots as P
e = 0.25 # Birth rate
d = 0.2 # Death rate
dI = 0.35 # Death rate of infected people due to the disease
f = 0.5 # Vaccination rate
# Runge-Kutta 4
# -----------------------------------... |
13,725 | 1f2afc1df7ca80eea3ce4dd85cff7006ab0049b1 | """ Style utilities, templates, and defaults for syntax highlighting widgets.
"""
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
from colorsys import rgb_to_hls
from pygments.styles import get_style... |
13,726 | e85aec69efad7cfd7b5406addb78befafab26a9d | import numpy as np
import pandas as pd
from sklearn import ensemble
from sklearn import metrics
from sklearn import model_selection
if __name__ == '__main__':
df = pd.read_csv('../data/mobile-pricing/train.csv')
X = df.drop('price_range', axis=1).values
y = df['price_range'].values
classifie... |
13,727 | a72f5b9362c7c35133846c357b8e2e35dd78991b | #
# Author: Tiberiu Boros
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, softwar... |
13,728 | bea1511a0b24cc29d2bf125cd627a8d7f9f4e682 | # -*- coding: utf-8 -*-
""" Code developed during 2018 MLH hackathon at University of Manitoba.
main.py: this contains the main code for running the application.
"""
##############################################################################
__author__ = ["Chris Cadonic", "Cassandra Aldaba"]
__credits__ = ["Chris... |
13,729 | 7b5c96442c8bd07a710c8c971988e691349ceb25 | #config/urls.py
from django.contrib import admin
from django.urls import path, include
from . import index
urlpatterns = [
#path('admin/', admin.site.urls),
#path('', include('.urls')),
path('', index.signin),
path('signup.html', index.signup),
path('signin.html', index.signin),
]
|
13,730 | f7d4464db016379e88f3f044c04c9a353909346e | import sys
import struct
import idautils
import idc
from patchwork.DataTransferObjects import Selector, Selection
import patchwork.ida_lib as ida_lib
import patchwork.core as core
##############################################
# patterns
push_push_call_regex = (
r"\x68(?P<operand_1>[\S\s]{4})"
r"\x68(?P<ope... |
13,731 | 5898fde8438ac3656fee99ed290a1a3117e98496 | #!/usr/bin/env python3
'''
Tkinter LabelEdit app
'''
import tkinter as tk
from tkinter import font
class InputLabel(tk.Label):
def __init__(self, master=None, **kwards):
self.text = tk.StringVar()
self.font = font.Font(family="Consolas", size=10, weight="normal")
super().__init__(
... |
13,732 | 37b70925f958f9da99f78c852c8cfe2d9f3db6ed | import base64
import hashlib
from Crypto import Random
from Crypto.Cipher import AES
class AESCipher(object):
def __init__(self, key):
self.bs = 32
self.key = hashlib.sha256(key.encode()).digest()
def encrypt(self, raw):
raw = self._pad(raw)
iv = Random.new().read(AES.block_si... |
13,733 | 48bcbeb573fa701dab676aacf074140b0fdf5221 | # Generated by Django 2.2.24 on 2021-09-08 13:35
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('consignment', '0030_remove_orderconsignment_num'),
]
operations = [
migrations.AddField(
model_name='orderconsignm... |
13,734 | e89f0429d5f4469daa68984f24642940f43e1207 | import pytest
import sys
from pycpslib import lib as P
ALL = set("darwin linux2 win32".split())
def pytest_runtest_setup(item):
if isinstance(item, item.Function):
plat = sys.platform
if not item.get_marker(plat):
if ALL.intersection(item.keywords):
pytest.skip("cannot... |
13,735 | 4059ce646b1171bf6d31ae1129eede05f8c822a9 | from sqlalchemy import Column, Integer, String, Date, create_engine, MetaData
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from settings import DB_CONNECTION_STRING, SCHEMA
Base = declarative_base(metadata=MetaData(schema=SCHEMA))
engine = create_engine(DB_CONNECTION... |
13,736 | ba2bce02eb0b44c43ac1acca1513cdedea07697b | # Generated by Django 3.1.10 on 2021-05-11 23:20
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
op... |
13,737 | a4af67979baf1f782211359a2f6236ff18ffee73 | from __future__ import annotations
import collections
import sys
from collections.abc import Iterable
from typing import IO, Any
from peewee import CharField, ForeignKeyField
from taxonomy.apis.cloud_search import SearchField, SearchFieldType
from ... import events, getinput
from .. import constants, models
from ..... |
13,738 | 715da2472c1b8ce32e76316f9809b29e797717ae | from __future__ import print_function
__author__ = 'max'
"""
Implementation of Bi-directional LSTM-CNNs-TreeCRF model for Graph-based dependency parsing.
"""
import sys
import os
sys.path.append(".")
sys.path.append("..")
import time
import argparse
import uuid
import json
import numpy as np
import torch
from neur... |
13,739 | 87d6e498b3ad4e68161c4befcb4c5281b2b8ed7c | import numpy as np
from sklearn.datasets import load_iris
from sklearn.preprocessing import MinMaxScaler, StandardScaler
from sklearn.model_selection import train_test_split, KFold, cross_val_score,GridSearchCV, RandomizedSearchCV
from sklearn.metrics import accuracy_score
from sklearn.svm import LinearSVC, SVC
import ... |
13,740 | 437b96c8f833f25366634658e76fbff240008542 | import random
MAX_INCREASE = 0.175
MAX_DECREASE = 0.05
MIN_PRICE = 0.01
MAX_PRICE = 100
INITIAL_PRICE = 10.0
day = 0
OUTPUT_FILE = "string_formatting.txt"
out_file = open(OUTPUT_FILE, 'w')
# noinspection PyTypeChecker
print("Starting price: ${:,.2f}".format(INITIAL_PRICE), file=out_file)
price = INITIAL_PRICE
while ... |
13,741 | 4ace8ea40ac7d0e065c9281ce44dcaf3a7e85713 | #HolaMundo.py
#Alan Manzanares
#Fecha de creacion: 18/09/2019
#Para agregar comentarios a nuestro programa usamos
#hashtag el cual ayuda a que lo que escribimos
#no se tome en cuenta para fines de nuestro programa Python y lo afecte
#si lo hariamos de forma habitual marcaria error porque no seria valido
#L... |
13,742 | 6bd582320ad1e76f640c6714ebd719862366fd98 | # Generated by Django 3.0.8 on 2020-07-19 19:18
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('home', '0006_remove_allpost_foto_produto'),
]
operations = [
migrations.AddField(
model_name='allpost',
name='foto_p... |
13,743 | b52441b24cdae12adb32545d46bd0ac4720d6e88 | """
파이션 - 무료이지만 강력하다
` 만들고자 하는 대부분의 프로그램 가능
` 물론, 하드웨어 제어같은 복잡하고 반복 연산이 많은 프로그램은 부적절
` 그러나, 다른언어 프로그램을 파이썬에 포함 가능
[주의] 줄을 맞추지 않으면 실행 안됨
[실행] Run 메뉴를 클릭하거나 단축키로 shift + ctrl + F10
[도움말] ctrl + q
"""
""" 여러줄 주석 """
# 한줄 주석
# 문자열표시
# '와 " 동일
# '와 ''' 차이는 > 사이에 공백과 개행... |
13,744 | 8a179e26c0e2dc435a0291961196beeca22926bc | # /usr/bin/env python
# coding=utf-8
"""utils"""
import logging
import os
import shutil
import json
from pathlib import Path
import torch
import torch.nn as nn
import torch.nn.init as init
MAP_DICT = {'C': 0, 'III': 1, 'V': 2, 'XXXVIII': 3, 'XXIX': 4, 'LV': 5, 'XXXIX': 6, 'XIV': 7,
'IV': 8, 'XIX': 9, 'I':... |
13,745 | 8c84b9aafe9fefbd6bbf2260587126de88108cce | #
# models.py -- Models for the "reviewboard.site" app.
#
# Copyright (c) 2010 David Trowbridge
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without lim... |
13,746 | 59ecb451e1d4d052d83d4077f2574db24c0eab08 | """
DESCRIPTION OF APP
Lets you add/remove/delete/update friends
"""
# Import Built-In Modules
import requests # Does API calls to other APIS
import traceback # Lets you print the error stack trace
import random # Lets you get a random number
import sys # Lets you use operating system functions
i... |
13,747 | d2a09f72e7844d6d72885de84f2c129718cbd134 | from django.apps import AppConfig
class MicrobloggerConfig(AppConfig):
name = 'microBlogger'
|
13,748 | a016332f94db0e088c326a5e1756e96d2eaa4815 | #!/usr/bin/python
import os
import numpy as np
import time as t
from PyQt4 import QtCore as qc
import functools
import traceback
try:
import h5py as mrT
except:
os.system('HDF5_DISABLE_VERSION_CHECK=1')
import h5py as mrT
try:
from ascii_table import *
except ImportError:
print 'No module ascii_table'
print 'Pl... |
13,749 | 507639abbdfb6698e7f59e2470a41459a8ac4268 | import sys
import weakref
from concurrent.futures import Future
class CircularFuturesChainException(Exception):
pass
class ThenableFuture(Future):
@property
def _chained_futures_log(self):
prop_name = '_chained_futured_log_list'
log = getattr(self, prop_name, None)
if log is No... |
13,750 | 8c283d56c7fc29de532820a82ae8b241b020ed67 | import pandas as pd
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics import accuracy_score, classification_report
import nltk
from functions import load_data, prepare_and_clean_data, process_data
import argparse
import sys
import os
from joblib import load
from sklearn... |
13,751 | b2ce8562668cf16267f8ba035d83c4cff22522b6 | # -*- coding: utf-8 -*-
# Copyright (c) 1996-2015 PSERC. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
"""Solves the power flow using a fast decoupled method.
"""
import warnings
from numpy import array, angle, exp, linalg, conj, r_, Inf, col... |
13,752 | a6afb02780f5418e60601aa83c740eb85a13e07e | # class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def largestValues(self, root: TreeNode) -> List[int]:
if root is None:
return []
# init max_list
max_list = []
max_list.append(roo... |
13,753 | 1a13a6f3425bfdf4b49a1ed1059ebeb3e4a44a0a | import sys
import scrapy
if len(sys.argv) < 2:
print('This crawler takes exactly two arguments [URL] [email]')
exit(-1)
class LBCSpider(scrapy.Spider):
def __init__(self, *args, **kwargs):
super(LBCSpider, self).__init__(*args, **kwargs)
self.start_urls = [kwargs.get('start_url')]
n... |
13,754 | 91269e39b188d8bf056de0ecafab693fd9483c23 | # -*- coding: utf-8 -*-
"""
Created on Wed Jan 29 16:35:08 2020
@author: morte
"""
from claseProfesor import Profesor
def testComposicion():
profesor = Profesor(11334441, 'Rodríguez', 'Myriam')
print(profesor)
del profesor
if __name__=='__main__':
testComposicion()
|
13,755 | cb7f79fba68c4cd0c8e2ac08de84086e9157e2d1 | n = int(input())
for i in range(n):
a, b = map(int, input().split())
if(a % 2 == 1 and b % 2 == 0 and a+b>=10):
print("OPEN")
else:
print("CLOSED")
|
13,756 | bca27e6f0aadf2b848ee651189bc8fd80c66a555 | import unittest
from unittest import TestCase
from python_translators.translators.glosbe_translator import GlosbeTranslator
from python_translators.translation_query import TranslationQuery
from translators.glosbe_over_tor_translator import GlosbeOverTorTranslator
class TestGlosbeOverTorTranslator(TestCase):
def... |
13,757 | 32a3ad79591182c9ba50204847a810b156de646f | import os
import re
import time
import configparser
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as tck
from ..utils.obslog import read_obslog
def load_config(pattern, verbose=True):
"""Load the config file.
Args:
pattern (str):
verbose (bool):
Returns:
... |
13,758 | 53eecffd9377716262f8245d4d73f944fb805da9 | import numpy as np
from PIL import Image
image_array = np.asarray(Image.open("./output.png")).copy()
for x in range(len(image_array)):
for y in range(len(image_array[0])):
r = image_array[x][y][0] & 0b00000011
g = image_array[x][y][1] & 0b00000011
b = image_array[x][y][2] & 0b00000111
... |
13,759 | 9bdf3cbb7dde279413066c6a3fe1929185307ee2 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/1/2 4:00 下午
# @Author : taicheng.guo
# @Email: : 2997347185@qq.com
# @File : config.py
from args import read_args
args = read_args()
hparams = {
'title_size': 30,
'his_size': 50,
'npratio': 4,
'word_emb_dim': 300,
# model
... |
13,760 | 489ab75480561b3a90efa1e9d2c756f742f48ac6 | from argparse import ArgumentParser
from pathlib import Path
from nhl_predict.dataset_manager import DatasetManager
from nhl_predict.game_prediction.experiment import Experiment
def get_args():
parser = ArgumentParser("Script for training game predictor.")
parser.add_argument(
"-p", "--path", type=st... |
13,761 | 204c53e815d063c04a333033e260187c05465799 | from django.contrib import admin
from .models import Selecciona
admin.site.register(Selecciona)
|
13,762 | 2f1b9421fdd81d0cc5d25d67f69867da9b68ef52 | class Movie:
"""This class contains information about a movie"""
count = 0
def __init__(self, theTitle, theDirector, theDuration, theActors, theRating):
self.title = theTitle
self.director = theDirector
self.duration = theDuration
self.actors = theActors
s... |
13,763 | 233f3f7157c34f667058e1eec9e80896f8e2078d | from math import pi
from copy import copy
### Read in content, spread it out and create single list
def readContentIn(contentRead):
contentRead = contentRead.replace('(', ' ( ')
# contentRead = contentRead.replace('[', ' ( ')
contentRead = contentRead.replace(')', ' ) ')
# contentRead = contentRead... |
13,764 | dd834b489dca722e93cd5256fc93e1efaf188f4b | #!/usr/bin/python3
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import os
import sys
from google.protobuf import text_format
import tensorflow as tf
from tensorflow.python.framework import graph_util
from tensorflow.core.framework import... |
13,765 | 9ca16403d0a3870b2d8038c3b4a51b9338a924c7 | #!/usr/bin/python3
""" defines a function that writes an Object to a text file, using a
JSON representation: """
import json
def save_to_json_file(my_obj, filename):
""" functions """
with open(filename, 'w') as f:
f.write(json.dumps(my_obj))
|
13,766 | 6da30bd1ad6355da4bf64c9ab260834223e91f9a | """
EXERCÍCIO 030: Par ou Ímpar?
Crie um programa que leia um número inteiro e mostre na tela se ele é PAR ou ÍMPAR.
"""
def main():
pass
if __name__ == '__main__':
main()
|
13,767 | 8af43b13f10df2b7921771454b0d7cfb6a47b2b3 | # In questo tutorial utilizzerò alberi decisionali (dall'inglese Decision Tree) e foreste casuali (dall'inglese Random
# Forest) per creare un modello di machine learning in grado di dirci se una determinata persona avrebbe avuto
# possibilità di salvarsi dal disastro del Titanic.
import pandas as pd
import numpy as ... |
13,768 | 8b7d0f5dfc1c332af06b0998aaa9a8ac9e871ef6 | # -*- coding: utf-8 -*-
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
... |
13,769 | ac6f0fbab20659164c49aadc301a80a894d2732c | from unittest import TestCase
import time
import pty
import subprocess
class TestDotfiles(TestCase):
def test_git(self):
"""
By now, we should have access to zsh, git, an alias for git, and git
aliases.
"""
g_d = subprocess.check_output(["zsh", "-i", "-c", "g d --help"])
... |
13,770 | deb041277edec9dfddedd51de69a354422475772 | # coding=utf-8
# Copyright (C) 2012 Allis Tauri <allista@gmail.com>
#
# degen_primer 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 3 of the License, or
# (at your option) any later version.
... |
13,771 | 4457dd2062f32ca42af3806fa31dfd87e8733c94 | """
naive algorith to find prime numbers
version 1.0
"""
import math
import time
start_time = time.time()
prims = [] # list of prims
for p in range(2, 500001): # find prims up to 50000
prime = True
for divider in range(2, int(math.sqrt(p))+1):
if p % divider == 0: # remaind... |
13,772 | 75a28a449579abde1a0f261899eb4d0ba1d67de7 | import numpy as np
import pandas as pd
import os
import sys
sys.path.insert(0, os.path.join(
os.path.dirname(os.path.realpath(__file__)),
os.path.pardir,
os.path.pardir
))
import model.model as model
import logging
from nose.tools import with_setup
logging.basicConfig(level=logging.DEBUG)
class TestD... |
13,773 | 77f50fd6256c18915b5ca652c0eb72478621b68e | # Import configugartion file
from ServerConfig import *
# Import Domain
from Domain.Users import Users
# Import other modules
from flask import Blueprint, render_template, redirect, url_for, request, make_response
import time
import os
import datetime
login = Blueprint('login', __name__, url_prefix='/', template_fol... |
13,774 | cc494ceb255969959a5c7ea5da4e608879761ba5 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2016-01-10 11:52
# @Author : LeiYue (mr.leiyue@gmail.com)
# @Link : https://leiyue.wordpress.com/
# @Version : $Id$
from __future__ import print_function
import json
import re
import time
import pymongo
import requests
USER_AGENT = 'Mozilla/5.0 (iPhone;... |
13,775 | cec3d3e1d9f4eb7f2d3337b3d4d80f01f873e771 | def strangeListFunction(n):
strangeList = []
for i in range(0, n):
strangeList.insert(0, i)
return strangeList
def startfromzeroto(n):
mylist=[]
for i in range(0,n):
mylist.append(i)
return mylist
#print(strangeListFunction(50))
x=int(input("Enter the number :"))
print... |
13,776 | c5e57f88a469b2e7c1e8ad37bdb8637eb5e74478 | # -*- coding: utf-8 -*-
# Koska plottaus mahdollisuuksia on niin paljo
# tässä tiedostossa on vain urleja plot esimerkkeihin
# ********* Hox Hox********
# Ei pidä vaipua masennukseen, sillä netti esimerkeissä on myös
# koodit ja kuvat, jotka voi kopioida suoraan tiedostoon, jos haluaa testata
#
# Basic esimerkit
# ht... |
13,777 | 3cd4e5222f35ac6431b98e8744c182ab3a0d33b7 | from tamcolors import tam, tam_tools, tam_io
class TAMKeyManager(tam.tam_loop.TAMFrame):
def __init__(self):
super().__init__(fps=10,
char="@",
foreground_color=tam_io.tam_colors.GRAY,
background_color=tam_io.tam_colors.BLACK,
... |
13,778 | 0a4316dc784712f0affe3764871d824576ac8d96 | # Generated by Django 3.0.7 on 2020-07-02 11:40
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('post', '0005_auto_20200702_1328'),
]
operations = [
migrations.AlterField(
model_name='post',
name='ka... |
13,779 | 07488abfd841f0c5c54a32e5229e929f7569cca6 | """
Module for the DomainMatrix class.
A DomainMatrix represents a matrix with elements that are in a particular
Domain. Each DomainMatrix internally wraps a DDM which is used for the
lower-level operations. The idea is that the DomainMatrix class provides the
convenience routines for converting between Expr and the ... |
13,780 | f5575a3ffb30d538355df4c8c6139eada5868a1e | from pymagnitude import *
import fetch
from fetch import db, Article
from tfidf import DFTable
import os
from annoy import AnnoyIndex
import logging
import nltk
from nltk import sent_tokenize
from nltk.tokenize import word_tokenize
import re
from nltk.corpus import stopwords
from nltk.stem.porter import PorterStemmer
i... |
13,781 | 5333761a37790598914d832495f963ef0c562ec1 | AdminApp.install('/work/app/sample.war', '[ -nopreCompileJSPs -distributeApp -nouseMetaDataFromBinary -nodeployejb -appname sample -createMBeansForResources -noreloadEnabled -nodeployws -validateinstall warn -noprocessEmbeddedConfig -filepermission .*\.dll=755#.*\.so=755#.*\.a=755#.*\.sl=755 -noallowDispatchRemoteInclu... |
13,782 | de864e095a88d1b8aaa7338e212f919064cf070b | import logging
import os
from . import questions
def get_datasets(prob, questions_dir, batch_size, cache_dir=None, cache_mem=False):
def get_question_batches_dataset(p, k):
q = questions.individual.get_dataset(questions_dir, p)
if cache_dir is not None:
cache_path = os.path.join(cache... |
13,783 | 607ca90d292373cdb7ba13f1ae508f4d01b38490 | import redis # 导入redis模块,通过python操作redis 也可以直接在redis主机的服务端操作缓存数据库
r = redis.Redis(host='localhost', port=6379, db=0) # host是redis主机,需要redis服务端和客户端都启动 redis默认端口是6379
# r.set('tasklist', 'junxi') # key是"foo" value是"bar" 将键值对存入redis缓存
# print(r['tasklist'])
# print(r.get('tasklist')) # 取出键name对应的值
# print(type(r.ge... |
13,784 | 9255b313fef951168b7bc511372b9a53d7bdadd6 |
print 100
print "the next literal is actually -2**30 (weird quirk alert!)"
print 1073741824
|
13,785 | 3b37da634881b96aa4c9baec303d2779fa0a0711 | '''
Created on 2019年7月5日
@author: geqiuli
'''
import sys
import os
import importlib
import inspect
import re
from public import mysql_opr
from public import files
import time
#import platform
#print('当前操作系统:',platform.platform())
current_time=int(time.time()*1000)
print(current_time)
def get_funcs(module, p... |
13,786 | 7e4a05feebf05632d593d10e5802165d591ad133 | # -*- coding: utf-8 -*-
'''
deal列表
'''
from lxml import etree
import time
import random
from selenium.webdriver.chrome.options import Options
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import json
import redis
class Matchlist(object):
def __init__(self):
self.timeout ... |
13,787 | 000aa4c7b9c9ee66062ac5bc9706003c8583067a | import numpy as np
import pandas as pd
from .. import utils
from sklearn.preprocessing import scale
from sklearn.impute import SimpleImputer
class BaseModel():
def __init__(self, X_train, y_train, X_test, params_file, folds_lookup,
prefix, logger):
self.X_train = X_train
self.y_tr... |
13,788 | cd7ba469569110cb2a9a20be23839348b779f0ed | from django.shortcuts import render
from rest_framework import generics
from rest_framework.views import APIView
from django.views.decorators.csrf import csrf_exempt
from rest_framework.decorators import api_view
from rest_framework.response import Response
from django.http import HttpResponse
from demo.models import F... |
13,789 | 273774f2075956e7ddd5f75a6ab1ce7debacff89 | #Palidnrome
word=input("Enter the word")
word=word.replace(" ","")
word=word.casefold()
new_word=word[::-1]
if(word==new_word):
print("Yes, the String is a palindrome")
else:
print("No, the String is not a palindrome")
|
13,790 | ea16dcdff3aa930a66276dbd0fa990defff9fc9d | import numpy as np
from scipy.ndimage import minimum_filter1d
def cumulative_minimum_energy_map(energyImage,seamDirection):
if seamDirection == 'VERTICAL':
cumulativeMinimumEnergyMap = np.copy(energyImage)
elif seamDirection == 'HORIZONTAL':
cumulativeMinimumEnergyMap = np.transpose... |
13,791 | ee4c4ed2ef3f55e133e29d619dbe77319b2c4a33 | from django.apps import AppConfig
class StudentableConfig(AppConfig):
name = 'studentable'
|
13,792 | 6cc725f7d0add04a6ef644c2e249a29954112b5a |
# Python Imports
import argparse
import copy
# Torch Imports
import torch
#from torch import LongTensor
#from torchtext.vocab import load_word_vectors
from torch.autograd import Variable
#from torch.nn.utils.rnn import pack_padded_sequence#, pad_packed_sequence
import torch.optim as optim
from torch.utils.data import... |
13,793 | d4e4ffe6ce060099ff360bbf7db6f24a63527a98 | from __future__ import print_function
from Crypto.Cipher import AES
input = raw_input
import socket, sys, getpass, pwd, os, stat, time, base64
try:
try:
host = sys.argv[1]
fil = sys.argv[2]
mode = sys.argv[3]
except Exception, e:
print("Usage:")
print("\tQuirky-c <ip> <filename> [--option]\n")
print("\t-... |
13,794 | 19754ea08fadb0cebe7c7bcdec2649abdfc2b2c2 | from django.shortcuts import render
from django.http import HttpResponse
from django.contrib.auth.models import User
from django.contrib.auth import authenticate
class Main_page():
def main_page(request):
url = ''
url_string = ''
user = authenticate(username=username, password=pas... |
13,795 | 3f250e1614f792ee309d22105ff743aaf594e3b4 | import numpy as np
import cv2
class UIColor:
def __init__(self, npx, scale):
self.npx = npx
self.scale = scale
self.img = np.zeros((npx, npx, 3), np.uint8)
self.mask = np.zeros((npx, npx, 1), np.uint8)
self.width = int(2*scale)
def update(self, points, color):
... |
13,796 | 03881abc0d2a314d574954e268b30c2dd2e113d9 | from django.core.management.base import BaseCommand
from dojo.models import Finding
import logging
deduplicationLogger = logging.getLogger("dojo.specific-loggers.deduplication")
"""
Author: Marian Gawron
This script will identify loop dependencies in findings
"""
class Command(BaseCommand):
help = 'No input com... |
13,797 | af7bf9e60a9ce82985669beb4c0a452d5b464e0b | import socket
tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 设置套接字地址可重用
tcp_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
addr = ("127.0.0.1", 4399)
tcp_socket.bind(addr)
tcp_socket.listen(128)
while True:
tcp_request, ip_port = tcp_socket.accept()
print("客户端加入")
file... |
13,798 | 6704852a593f3bd7b7bcaae59eb09802f588dde3 | from numpy import array, linalg, matmul
a = array([[1, -1, 0], [3, 0, -1], [1, 3, -2]])
print(a)
b = array([[2, -1, 1], [0, 3, -1], [-1, 2, 0]])
print(b)
inv = linalg.inv(a)
print(inv)
i = linalg.inv(b)
print(i)
ab = matmul(a, b)
print(ab)
|
13,799 | db82ff4b9cf28123fe8bb276d8bcb1a81fa822bb | import math
n1 = 255
n2 = 1000
print(hex(n1))
print(hex(n2))
print('Another lab start here..........')
def quadratic(a,b,c):
judgement = b ** 2 - 4 * a * c
if judgement < 0:
result = "No result"
return result
elif judgement == 0:
result = -b / (2 * a)
return result
e... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.