index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
12,000 | bb488d6eeceb0f3ce048fccf4b5a2773b11f51b1 | import numpy as np
a=np.array([1,2,3,4])
print(a)
print("aaaaa")
print("bbbbb")
print("aaaaaaaaa") |
12,001 | c795ecb6183938e93399af9520fa75bc71bef8f5 | import numpy as np
import abc
class Env:
def __init__(self):
pass
def __str__(self):
pass
def reset(self):
pass
|
12,002 | a37c363cce26ca64fea280c8252b02da6f388491 | import pymysql
db = pymysql.connect("192.168.80.134", "sczhan", "Sczhan@1998.", "ceshi", 3306)
cursor = db.cursor()
# 创建删除语句
sql = "delete from ceshibiao where INCOME > '%f'"%(9999)
try:
cursor.execute(sql)
db.commit()
print("执行成功")
except Exception as e:
db.rollback()
print("执行失败:" + e)
db.close(... |
12,003 | ed14fdc37c79c16ad66de498eea604b32c65871f | from . import hetero, image, sequence
from .utils import get_embedding, get_dense_block, bi2uni_dir_rnn_hidden |
12,004 | 561ca542be0c6b735e385f2a3c7481d26340c196 | #!user/bin/env python
"""
Created on 2015/7/21
Author:LiQing
QQ:626924971
Tel:*********
Function:get spider conf
"""
import os
import ConfigParser
import xml.dom.minidom
from logger import logger
class get_conf():
@classmethod
def find(cls, method):
if method[0] == "http_header":
header ... |
12,005 | d967c5c52caf5573130646c3caf0d544945cfad4 | from airtravel import *
aircraft = Aircraft("G-EUT", "Airbus A319", num_rows=22, num_seats_per_row=6)
f = Flight("BA758", aircraft)
f.allocate_seat('12A', "Ankita singh")
f.allocate_seat('12A', "Ankit Pandey")
f.allocate_seat('15A', "Andres Chao")
f.allocate_seat('15E', "Killi Sahng")
f.allocate_seat('E27', "Amy Lanist... |
12,006 | d8d0bda355a60507a7e811c2b0ee57ea0dfd6c9a | """
Some scaffolding to help with testing
context = the unit text class (self)
"""
from rest_framework.authtoken.models import Token
from rest_framework.test import (
APIClient,
ForceAuthClientHandler
)
from django.contrib.auth.models import User
from ..models.author import (
Author,
CachedAuthor)
from... |
12,007 | 684b75a27d8acd214e2b31bfdbb9e97ea7a22111 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
In here we put all things util (methods, code snipets) that are often useful, but not yet in AiiDA
itself.
So far it contains:
export_extras
import_extras
delete_nodes
delete_trash
create_group
"""
# TODO import, export of descriptions, and labels...?
import json
fro... |
12,008 | 036614a0164117e2f9a02944ab808f9aab804420 | # creates lists from user input and converts the input into an int as well as a list
X = [int(x) for x in input().split()]
Y = [int(y) for y in input().split()]
# zips the 2 lists, but first squares 'x' value in list 'X' & uses that to zip with Y
squared_map = zip((x ** 2 for x in X), Y)
for x in squared_map:
pri... |
12,009 | 20e95f7300fae788ee769493e0c6e1f02bcead02 | from os import abort
from flask import Flask, request, redirect, make_response, jsonify
import json
from flask_cors import CORS
import psycopg2
app = Flask(__name__, static_folder="./build/static", template_folder="./build")
CORS(app) #Cross Origin Resource Sharing
def get_connection():
localhost = 'localhost'
... |
12,010 | d16fe708d8c0a4c424da2edd0bc3e8430c5207b7 | """
"""
from link.common import APIResponse
from link.wrappers import APIRequestWrapper, APIResponseWrapper
from requests.auth import AuthBase
import json
import requests
class SpringAuth(AuthBase):
"""
Does the authentication for Spring requests.
"""
def __init__(self, token):
# setup any a... |
12,011 | f6b006ae9ae46f0ee0504b10773f16eea965b326 | import torch
from torch import nn, optim
from torch.optim import lr_scheduler
from torch.utils.data.dataloader import DataLoader
from torchvision import datasets
from torchvision.transforms import transforms, Normalize
class Unit(nn.Module):
def __init__(self, in_channels, out_channels, stride=1):
super(U... |
12,012 | 589d11afc791fbf055dccf85292609f3411acfdf | def leianum(msg):
while True:
if x == 0:
try:
i = int(input(msg))
except (ValueError, TypeError):
print(f'\033[31mERRO! Digite um nº {tipo[x]}\033[m')
except (KeyboardInterrupt):
i = 0
print('Usuario preferiu... |
12,013 | 3420e7e0be98a28192f3c88403b561fd1e7fbfce | from flask import render_template, url_for, flash, redirect, request, abort
from library import app, db, bcrypt
from library.forms import RegistrationForm, LoginForm, BookForm
from library.models import User, Book
from flask_login import login_user, current_user, logout_user, login_required
'''books = [
{
... |
12,014 | c612d118f13e9f35033c391ef9ecd7ebaf956642 | from workingmemory import IWorkingMemory
from knowledgebase import IKnowledgeBase
from inferencemachine import InferenceMachine
import tkinter as tk
from tkinter import messagebox
class MainWindow():
def __init__(self):
super().__init__()
self.working_memory = IWorkingMemory()
self.knowle... |
12,015 | bef4029ccd54d9074b766cc890be17ab26c3f109 | import tensorflow as tf
import numpy as np
import pandas as pd
tf.logging.set_verbosity(tf.logging.INFO)
# 模型定义
def cnn_model_fn(features, labels, mode):
# 输入层 3x23 ,通道1
input_layer = tf.reshape(features['x'], [-1, 111, 1])
# input_layer = features['x']
# 第1个卷积层 卷积核5x5,激活函数sigmoid
conv1 = tf.layer... |
12,016 | 3ad509a3ebf2441522210663da1e79d8197b4201 | from __future__ import absolute_import
from . import deffile
from .util import type_str, load_type
def get_all_msg_types(msg, skip_this=False, type_set=None):
if type_set is None:
type_set = set()
if not skip_this:
if msg in type_set:
return type_set
type_set.add(msg)
f... |
12,017 | 0af71c7c7ce9d5f953090638eced815648fff571 | # -*- coding: utf-8 -*-
# @Time : 2021/3/27 16:27
# @Author : kjleo
# @Software: PyCharm
# @E-mail :2491461491@qq.com
import re
import time
from concurrent.futures.thread import *
from PyQt5.QtCore import *
import PyQt5.QtCore
import requests
results = []
length = 0
class Down(QThread):
process = pyqtSignal(... |
12,018 | af34bb34e4bbe71dd183ac3f9553f9290ef7b6ac | #%%
from ImgManager import ImgManager
from CNNModel import CNNModel
from Analyser import Analyser
import warnings
import pandas as pd
import time
import numpy as np
output2='output_Q2/'
warnings.filterwarnings('ignore')
#%%
imgMan=ImgManager(testSize=0.2)
imgMan.readImages()
# %%
imgMan.procesImages()
# %%
# imgMan.d... |
12,019 | 82218b213bce34dcf4e24d470542bbf6b79580b0 | from translate import Translator
try:
with open('./test.txt', mode='r') as file:
text = file.read()
print(text)
translator = Translator(to_lang="ja")
translated_text = translator.translate(text)
print(translated_text)
translator = Translator(to_lang="hi")
... |
12,020 | 1664b4f0793644e57847540e98fcb5a8bfa61739 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Przerabia pojedynczy plik, wyciągnięty wcześniej z .dsk na .tap.
Użycie, np.
./dsk2tap.py PACKMAKE packmake.tap
"""
import array
import sys
def save_data(f, data):
d = array.array('B', [255])
d.extend(data)
ch = 0
for i in d:
ch ^= i
d.append... |
12,021 | aea70eb2f6b09c1f3071d6a5fa8b038cb4c79a50 | # Generated by Django 3.2.8 on 2021-11-10 16:42
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('units', '0003_alter_employee_prefix'),
]
operations = [
migrations.AddField(
model_name='college',
name='sanitized_n... |
12,022 | 2173d827c99fb01ab01ff72845b7c7c1d9642936 | #056-2.py
a = ["tree", "lake", "park"]
idx = a.index("lake")
a.pop(idx)
print(a)
|
12,023 | 11e66860ee17d6deeabb5fcf2801a33429ad7421 | import logging
import asyncio
import pickle
import sys
from aiocoap import *
def get_args():
total = len(sys.argv)
if total != 2:
print("ERROR: Incorrect number of arguments")
sys.exit()
else:
return sys.argv[1]
logging.basicConfig(level=logging.INFO)
async def main():
ip = g... |
12,024 | 01071df38bb4ee55ee2b478bedd176e188b8d645 | import re
N = int(input())
if N > 0 and N < 50:
for _ in range(N):
css = input()
col_codes = re.findall(r".(#[0-9A-Fa-f]{6}|#[0-9A-Fa-f]{3})",css) #return a list with all the matches in the css code
if col_codes:
print(*col_codes,sep="\n") |
12,025 | 542ff78d2a1d1181b04f939da5ae667cdd95d906 | import json as j
import pandas as pd
import re
import numpy as np
import nltk
from nltk.corpus import stopwords
from nltk.stem import SnowballStemmer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.svm import LinearSVC
from sklearn.pipeline import Pipeline
from sklearn.model_selection import tr... |
12,026 | 714968ccd71136f633925e51b38b054573d5ac49 | import datetime
import sqlalchemy
from .db_session import SqlAlchemyBase
from sqlalchemy_serializer import SerializerMixin
class Trainer(SqlAlchemyBase, SerializerMixin):
__tablename__ = 'trainers'
id = sqlalchemy.Column(sqlalchemy.Integer,
primary_key=True, autoincrement=True)
... |
12,027 | 7291736f147c5c39199a00c687ae9e96f4f3afb9 | import csv
import os
import re
import sys
import sqlparse
META_FILE = "./files/metadata.txt"
AGGREGATE = ["min", "max", "sum", "avg"]
schema = {}
table_contents = {}
# create table schema
# -------------------
def metadata():
try:
with open(META_FILE,'r') as f:
contents = f.readlines()
contents = [t.strip() ... |
12,028 | 2964a96b45bbb6a84f57374aaf1fd79b1933c197 | import sys
LetterValues = {
'a':1,
'b':2,
'c':3,
'd':4,
'e':5,
'f':6,
'g':7,
'h':8,
'i':9,
'j':10,
'k':11,
'l':12,
'm':13,
'n':14,
'o':15,
'p':16,
'q':17,
'r':18,
's':19,
't':20,
'u':21,
'v':22,
'w':23,
'x':24,
'y':25,
... |
12,029 | fb70609254fdba9dc014af4eb004929b0e6d7bbc | from pathlib import Path
import shutil
def copy_paster(settings):
"""
Note:
This functions does a direct copy/paste of model input and output files into the post-proc run results folder.
Parameters:
settings: The SetInputs class.
Return:
Nothing is returned but f... |
12,030 | fb3abeafd05fa9f733668aed3059e7dbc925851e | """
Examples to show available string methods in python
"""
# Replace Method
a = "1abc2abc3abc4abc"
print(a.replace('abc', 'ABC', 1))
print(a.replace('abc', 'ABC', 2))
# Sub-Strings
# starting index is inclusive
# Ending index is exclusive
b = a[1]
print(b)
c = a[1:6]
print(c)
d = a[1:6:2]
print(d)
e = 'This is a st... |
12,031 | 9e445d22ea9609e65ed9da29cb5e989598d0a7cf | import matplotlib.pyplot as plt
import numpy as np
def to_one_hot_encoding(s, obs_n):
x = np.zeros(obs_n, dtype=np.float32)
x[s] = 1.0
return x
def plot_learning(x, scores, epsilons, filename, lines=None):
fig = plt.figure()
ax = fig.add_subplot(111, label="1")
ax2 = fig.add_subplot(111, lab... |
12,032 | 54bc7d12f43b2fbc2fe1497887c02b002d33b441 | # This program prints Hello, world!
print ('Hello World') |
12,033 | bf1b9f9203aea6e6d93a6efb0ecbfd49b978cf08 | from django.contrib import admin
from .models import Question,Choice
# Register your models here.
admin.site.site_header = 'Pollon Admin'
admin.site.site_title = 'Pollon Admin'
admin.site.index_title = 'Welcome To Pollon Admin'
class ChoiceInline(admin.TabularInline):
model = Choice
extra =2
class Question... |
12,034 | c7f922f0c056e2b45c8855efbc0755aa2a3bc680 | #!/usr/bin/python
# vim: set fileencoding=utf8
#
# Copyright (C) 2012 - Matt Brown
#
# All rights reserved.
#
# Example RRD commands for use with this script:
# rrdtool graph /tmp/test.png --start end-48h --lower-limit 0 \
# --title "Electrical Power Usage" DEF:power=/tmp/power.rrd:node1_kWh:AVERAGE \
# --vertic... |
12,035 | 95c472d64bf11fb7b323e7ae12d0047d0f073203 | """
**************************************************************************
Theano Logistic Regression
**************************************************************************
This version was just for local testing (Vee ran his version for our SBEL batch jobs)
@author: Jason Feriante <feriante@cs.wisc.ed... |
12,036 | b4536be5fbabc4091845cfd8e15d08846001ab9b | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Nekozilla 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.
#
# Nekozilla is distributed... |
12,037 | bc179e54f21b970c9d226380b1c7307512496910 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2011 Citrix Systems, Inc.
# Copyright 2011 OpenStack LLC.
#
# 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
#
# ... |
12,038 | aad1ba7b2573b4b702d6e0e2d6e71c78a0647c5d | employee=[(80, "rajat", 414),(84, "rithik", 261),(82, "nipun", 9052),(83, "harshil", 369)]
print("print the employee list----------->")
for i in employee:
print(i)
print()
employee[0]=(82,"rakshit",463)
print("after modification---------->")
for i in employee:
print(i)
|
12,039 | e4bf7b14138fe801091b2d1dae9db900778890fc | import urllib.request
def read_text():
quotes=open("profanity.txt")
contents=quotes.read()
print(contents)
quotes.close()
check_profanity(contents)
def check_profanity(text_to_check):
connection=urllib.request.urlopen("http://www.wdyl.com/profanity?q="+text_to_check)
## 404
output=con... |
12,040 | 767c6bc033e64fb519c09d04985bc8ff5dd98d2d | rows = int(input())
matrix = []
diagonal_sum = 0
for row in range(rows):
matrix.append([int(el) for el in input().split()])
diagonal_sum += matrix[row][row]
print(diagonal_sum) |
12,041 | 5f7e3fe83a4849d7fbb946d9450ab5db196e9243 | import numpy as np
def preprocess(text):
text = text.lower()
text = text.replace('.', ' .')
words = text.split(' ')
word_to_id = {}
id_to_word = {}
for word in words:
if word not in word_to_id:
new_id = len(word_to_id)
word_to_id[word] = new_id
id_to... |
12,042 | 648bb90d97c9153d7bc89622e573e01ef158cd7e | def sort_dict(dict1, sb):
if sb.lower() == 'value':
dict1 = {x: y for x, y in sorted(dict1.items(), key=lambda x: x[1])}
elif sb.lower() == 'key':
dict1 = {x: y for x, y in sorted(dict1.items())}
return dict1
def main():
count_dict = {'a': 4, 'b': 3, 'c': 2, 'd': 1}
sb_... |
12,043 | cad003637271b6c4ac5419f70e12a73669dce5d7 | #!/usr/bin/python
import sys
import codecs
import re
def calculate_g0_dice(ngram_frequency_distr,unigram_frequency_distr):
result=[]
for ngram in ngram_frequency_distr:
if ngram_frequency_distr[ngram]>=min_frequency: #minimum frequency
result.append((float(ngram_length)*ngram_frequency_distr[ngram]/sum([unigram... |
12,044 | 598d0ec549f238c602eeeb442678cc3b5f1a8408 | from __future__ import annotations
from typing import Iterator
def _split(string: str, split_size: int) -> Iterator[str]:
for i in range(0, len(string), split_size):
yield string[i : i + split_size]
def _create_layer(string: str, width: int, height: int) -> list[list[int]]:
return [
[(int(c... |
12,045 | a31cf08a3993aba9094ea3a063919319514c7454 | # -*- coding: utf-8
import urllib.request
# 取得先URL
url = "https://raw.githubusercontent.com/nishizumi-lab/sample/master/python/scraping/00_sample_data/sample01/index.html"
# ユーザーエージェント情報を設定
opener = urllib.request.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; ja; rv... |
12,046 | dc32c573ac2a820cfdb27f2a335f7eb43e8bb811 | from recoapp import app, db
import recoapp.models
import pandas as pd
import re
import urllib
import zipfile
def extract_year(x):
year = re.search("[12][0-9][0-9][0-9]", x)
if year:
title = re.sub("[ \t]+\(.+\)", "", x)
return title, year.group(0)
return x, None
## Download movieles data... |
12,047 | 98f113687ea6c5493a2a384f1489004e94f22de3 | from Day6.Point import Point
def is_within_region(pos, pts):
max_distance = 10000
current_distance = 0
for pt in pts:
current_distance += abs(pos.x - pt.x) + abs(pos.y - pt.y)
return current_distance < max_distance
start_id = 65 # >= 2 for latter array initialization
non_id_char = chr(st... |
12,048 | 35df847bb6c8316ddbd69b900e2e3c5c9fe58f7c | import logging
import sanic.exceptions
import sanic.response
from .repl_manager import ReplManager
log = logging.getLogger()
class Handlers:
"""Handlers for various routes in the app, plus attributes for tracking the
REPL process.
"""
def __init__(self):
self.repl_mgr = None
def close... |
12,049 | 1965ba6bd15ff7c1c0a378a3c7cd46a72646dd89 | import def_Patch_Extract_
import glob
import os
import numpy as np
CT_DATA_Path = "data"
DAT_DATA_Path = "pre_process_data"
if not os.path.exists(DAT_DATA_Path):
os.makedirs(DAT_DATA_Path)
CT_scans = sorted(glob.glob(CT_DATA_Path + '/*.mhd'))
# def_Patch_Extract_.slide_extraction(DAT_DATA_Path, CT_scans)
if no... |
12,050 | 68dc9b1e49f90ad970f0bc7db58c7d5ecf61f591 | test_num = int(input("Input a number: "))
result = 1
for number in range(test_num, 0,-1):
result *= number
print(result)
#something = something * number
# something *= number
|
12,051 | f6f7e1a7a04ff6da82666e6cea9782f417a81632 | ### Model Training and Evaluation ###
# Author: Oliver Giesecke
from IPython import get_ipython
get_ipython().magic('reset -sf')
import os, shutil
import re
import csv
from utils import bigrams, trigram, replace_collocation
import timeit
import pandas as pd
import string
from nltk.stem import PorterStemmer
import nu... |
12,052 | 2bd605b0331c2f1bacbb5667544c0c4342768367 | %%file mapper_client.py
#!/usr/bin/env python
import sys
import traceback
import datetime
from datetime import datetime as dt
import calendar
import time
import numpy as np
for line in sys.stdin:
print("{},{}".format(line, 1)) |
12,053 | bad559c08376692855aea404089b3276f9f4480b | from .cer import cer
from .wer import wer
from .metrics import Metrics
|
12,054 | b1459a336cfb0948c72f3346170d2b96571c7338 | # BSD-3-Clause License
#
# Copyright 2017 Orange
#
# 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 followi... |
12,055 | 1579ef63299274e7ba389f1df36ddbbc0303fbca | # Copyright 2016 Cloudbase Solutions Srl
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless r... |
12,056 | 8f8c87d8ff5360f8df94413b189ca26b62a703ce | #coding=utf-8
#Version:python3.6.0
#Tools:Pycharm 2017.3.2
# Author:LIKUNHONG
__date__ = '2019/2/27 21:41'
__author__ = 'likunkun' |
12,057 | f8d81eba8af36b5c9ff2d866e4412e314f301770 | # -*- coding: utf-8 -*-
import numpy as np
import random
import cPickle
import gzip
import matplotlib.cm as cm
import matplotlib.pyplot as plt
class Data(object):
def __init__(self, verb=False):
self.verb = verb
self.x = {'trn': None, 'vld': None, 'tst': None}
self.y = {'trn': None, 'v... |
12,058 | f2c1c28ab3d2b6b00f39a9d8ed5200855954af28 | import math, datetime, os
from FCN import *
from voxnet import VoxNet
from fmri_data import fMRI_data
from config import cfg
import time
from evaluation import *
from sklearn import svm
def main(data_index=None,cut_shape=None,data_type=['MCIc','MCInc'],pre_dir='/home/anzeng/rhb/fmri_data',
num_batches = 256*... |
12,059 | e5c12f9631ec0f5d6baa13ba34e4b071d9345b9d | #!/usr/bin/python
# @author: Viviana Castillo, APL UW
##################################################################################
#print pressure sensor output
##################################################################################
#standard imports
import time
#third party imports
import ms5837
... |
12,060 | 36ae5230e168fb95c705ea3b20b80b4fd3ee6458 | import arcade
from arcade import Sprite, Texture, SpriteList
import math
from bounce_dot_sprite import BounceDotSprite
SCREEN_WIDTH = 600
DOT_SIDE_LENGTH = 20
SCREEN_HEIGHT = 600
SPRITE_SCALING_FUNKY = 0.9
MOVEMENT_SPEED = 5
class MyGame(arcade.Window):
def __init__(self, width, height, name):
super().__... |
12,061 | bee4d5b186d325da5868d5030524e68c0734cad5 |
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import urlparse
import budget
import json
import datetime
BASE_WEB_DIR = "webserver/"
class BudgetHTTPRequestHandler(BaseHTTPRequestHandler):
def __init__(self, request, client_address, server):
BaseHTTPRequestHandler.__init__(self, request, ... |
12,062 | 42a3207244ea94553b01df3696a691d3fd127ab6 | class ExampleCtrl(object):
"""Mealy transducer.
Internal states are integers, the current state
is stored in the attribute "state".
To take a transition, call method "move".
The names of input variables are stored in the
attribute "input_vars".
Automatically generated by tulip.dumpsmach o... |
12,063 | 3d762649594dcd13085f6af8e541d9b9b8ce186a | """Программа принимает действительное положительное число x и целое отрицательное число y.
Необходимо выполнить возведение числа x в степень y.
Задание необходимо реализовать в виде функции my_func(x, y).
При решении задания необходимо обойтись без встроенной функции возведения числа в степень."""
"""
Программа ... |
12,064 | a225d0d9f8e9eebfd76f30f44f9fde2f42384ed7 | from fbchat import Client
from fbchat.models import Message, MessageReaction
# facebook user credentials
username = "username.or.email"
password = "password"
# login
client = Client(username, password)
# get 20 users you most recently talked to
users = client.fetchThreadList()
print(users)
# get the detailed inform... |
12,065 | 1d11d96dd7034024ae8d03128fccb221a299835b | def chose(a):
s = ''
m = 0
for i in range(len(a)):
if (m == 0) and(a[i] == '~'):
j = i+1
m +=1
while (a[j] != "~"):
s = s + a[j]
j+=1
return(s)
id_list = []
description_list = []
from Bio import SeqIO
file = ope... |
12,066 | 9e7e07d4f82af6395338f1b28b7a518b3fd575cd | from typing import *
from ..arg_check import *
from ..tensor import Tensor, Module
from ..typing_ import *
from .contextual import *
from .core import *
from .gated import *
__all__ = [
'ResBlock1d', 'ResBlock2d', 'ResBlock3d',
'ResBlockTranspose1d', 'ResBlockTranspose2d', 'ResBlockTranspose3d',
]
class Res... |
12,067 | a60a484a6ecdb651d8676a57abfe9caa23ef0c2f | # Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... |
12,068 | ffe5d178311135ce3623fb5fc6d38321eba1a4f4 | class Card:
def __init__(self, value, symbol):
self.symbol = symbol
self.value = value
def print_card(self):
if self.value==14:
return f'[A{self.symbol}]'
elif self.value==13:
return f'[K{self.symbol}]'
elif self.value==12:
return f'[Q... |
12,069 | 09ef4ff094486037a29f9420b776f3400bbe1b09 | import sys
import math
graph = {}
n = int(input())
for i in range(n):
x, y = [int(j) for j in input().split()]
graph.setdefault(x,[]).append(y)
print(graph, file=sys.stderr)
def find_length(start):
longest = 1
if start not in graph:
return longest
for p in graph[start]:
l = find_... |
12,070 | fd7141cdc8f919b2e916e8cdb349b34e88878d27 | __author__ = 'diegoguaman'
'''
QUITO
==============
'''
import couchdb
import sys
import urllib2
import json
import textblob
from pylab import *
from couchdb import view
URL = 'localhost'
db_name = 'rusia'
'''========couchdb'=========='''
server = couchdb.Server('http://'+URL+':5984/') #('http://245.106.43.184... |
12,071 | 4d88b7a1157adf720106f807be3d824df6631037 | def nextGreatest(arr):
size = len(arr)
max_from_right = arr[size-1]
arr[size-1] = -1
for i in range(size-2,-1,-1):
temp = arr[i]
arr[i]=max_from_right
if max_from_right< temp:
max_from_right= temp
def printArray(arr):
for i in range(0,len(arr)):
print arr[i]
|
12,072 | 4e490b24eda2ea227824e118edc55d28252a4ad4 | #!/usr/bin/python
import logging
import os
from pathlib import Path
logging.basicConfig(level=logging.INFO)
base = (Path(__file__).parent / "dotfiles").absolute()
assert base.is_dir()
home = Path(os.environ["HOME"])
for path in (
Path(dir) / name
for dir, _, names in os.walk(base)
for nam... |
12,073 | 096325ed20677d1dbfecf23f9927da8ac93083d4 | class Prototype(object):
value = 'default'
def clone(self, **attr):
obj = self.__class__()
obj.__dict__.update(attr)
return obj
class PrototypeDispatcher(object):
def __init__(self):
self._objects = {}
def getObject(self, obj_name):
print(f'Getting object {obj_name}')
return self._... |
12,074 | 0b3781c11084af103544b895cceccf16206ea035 | # Generated by Django 2.1.3 on 2018-11-15 15:58
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('member', '0007_auto_20181115_2249'),
]
operations = [
migrations.RemoveField(
model_name='userprofile',
name='game',
... |
12,075 | 14a97efe05a3208a7e4b122f0567a641ea141e08 | #!/usr/bin/python
from sys import argv
from datetime import datetime
import numpy as np
from itertools import groupby
from sklearn.metrics import confusion_matrix
from scipy import stats
from scipy import spatial
def separateFiles(trainningFile, testFile):
with open(trainningFile, 'r') as file:
data = np.loadtxt(fi... |
12,076 | 1506dd0aa3e958a73c04e7237f1bf758323f5d0a | from django.shortcuts import render, redirect
from django.contrib.auth import get_user_model
from ..filters import PatientFilter
from django.urls import reverse_lazy
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django_filters.views import FilterView
from django.core.mail imp... |
12,077 | 9833c6937f89a024601f5e59142131320ff15eae | #!usr/bin/python
# -*- coding:utf-8 -*-
import multiprocessing
import time
##实例 第一种方式
# def process(num):
# time.sleep(num)
# print 'Process:', num
#
#
# if __name__ == '__main__':
# for i in range(5):
# p = multiprocessing.Process(target=process, args=(i,))
# p.start()
#
# ... |
12,078 | 3bc5e18eef1bc17c64e9f654e6a1f7f5e16c44a2 | from django.contrib import admin
from .models import Post
from django.contrib.auth.admin import UserAdmin
# Register your models here.
class PostAdmin(admin.ModelAdmin):
list_display = ['name','image','hash', 'approval']
list_editable = ['approval']
admin.site.register(Post, PostAdmin)
|
12,079 | 3d2a1d0774ed280a1f0c18bb268d606dfc3cf7e0 | from django.apps import AppConfig
class EbcAppConfig(AppConfig):
name = 'ebc_app'
|
12,080 | cf1c00259fd3c0ff8888a05b2ced3a327625f611 |
from xai.brain.wordbase.nouns._crank import _CRANK
#calss header
class _CRANKED(_CRANK, ):
def __init__(self,):
_CRANK.__init__(self)
self.name = "CRANKED"
self.specie = 'nouns'
self.basic = "crank"
self.jsondata = {}
|
12,081 | 17e42765380dbd6cf7d8bd7a461fc0159d4300f2 | # -*- coding: utf-8 -*-
# Third Party Stuff
import factory
from django.conf import settings
class Factory(factory.DjangoModelFactory):
class Meta:
strategy = factory.CREATE_STRATEGY
model = None
abstract = True
class UserFactory(Factory):
class Meta:
model = settings.AUTH_US... |
12,082 | 0548096e8092d01c072aadbdc0110e6690dcf1a2 | # -*- coding: utf-8 -*-
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf import settings
from django.views.decorators.cache import cache_page
from django.views.generic.base import TemplateView
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', cache_pag... |
12,083 | acb85c82d84af90c40bb133863a42a6dc9f0f3e9 | # coding: utf-8
from __future__ import absolute_import
from . import BaseTestCase
from six import BytesIO
from flask import json
class TestServiceSettingsController(BaseTestCase):
""" ServiceSettingsController integration test stubs """
def test_get_liveness(self):
"""
Test case for get_liv... |
12,084 | 44c5132507b6d49d70593db00f8174b8c48d9024 | """Installation script."""
from setuptools import find_packages, setup
setup(
name='blocks_mindlab',
description='Tools for build and launch experiments with Blocks',
author='Mindlab Group',
packages=find_packages(),
install_requires=['blocks', 'blocks_extras'],
extras_require={},
scripts=[... |
12,085 | 194dc522d18bcb47cef4b22b510bbf4798d841d8 | #!/Users/kyoungrok/Library/Enthought/Canopy_64bit/User/bin/python
from org.apache.pig.scripting import *
P1 = Pig.compile("""
previous_pagerank = load '$docs_in' as (page_id:int,
links:{link:(link_id:int)},
pagerank:float);
... |
12,086 | eb510686c4bf25b1b70629197cdb8e86fc73618f | # Copyright (c) 2013 phrack. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import pyaudio
import pyttsx
from threading import Thread
import wave
# This class hold shootoff functions that should be exposed to training protocol
# plugins. Each... |
12,087 | 3e3790b3db3733c7f5849e8bcf882718a153dbdd | __author__ = 'benjamin'
import numpy as np
from dc2D import dual_contour
from dcSample import sample_data, sphere_f, doubletorus_f, torus_f
from dcPlotting import plot_edges, plot_vertices, plot_non_manifold_vertices, plot_surface
from qtPlotting import plot_qt
from dcManifolds import detectManifolds2d
from quadtree ... |
12,088 | 23a96489658248cbcffcc9a87701fae84f36f646 | import MakeInclude as mk
mk.MakeInclude()
|
12,089 | 29b181fc33e3d9896a894af514cb49f5e39c05e3 | from django.db import models
from django.contrib.auth.models import BaseUserManager
from rest_framework_simplejwt.tokens import RefreshToken
# Create your models here.
class UserManager(BaseUserManager):
def create_user(self, username, email, telefono, programa):
if username is None:
raise Type... |
12,090 | 2b2ae91c9e92adf33d4c1b69cb90c3a643af975a | from django.db import models
from django.shortcuts import redirect
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
from wagtail.admin.edit_handlers import FieldPanel, PageChooserPanel
from wagtail.core.fields import RichTextField
from wagtail.core.models import Page
from common... |
12,091 | 74939c5a6385990dbfb108df5b6157f6196b5406 | ###############################################################################
# For copyright and license notices, see __manifest__.py file in root directory
###############################################################################
from odoo import fields
from odoo.tests.common import TransactionCase
class Te... |
12,092 | d3697e3976236b6fda796fb3bd8b175574c60b9d | # -*- coding: cp1254 -*-
print "6/2"
print "selam"
print """bu üç tırnaklı satırların ilki
bu da ikincisi"""
|
12,093 | 723f0f97ef930ecb04d1f88dafcb45603e5e9675 | import warnings
import os
import numpy as np
from itertools import zip_longest
import matplotlib.animation as animation
import matplotlib.pyplot as plt
from itertools import chain
from models.config import Config
from models.video import Video
from models.preprocessor import Preprocessor
warnings.filterwarnings('ignor... |
12,094 | b011dfd708d7c57f1476edeeb4088617fbab0ef2 | import numpy as np
import torch.nn as nn
import torch.nn.functional as F
import torch
class PositionEncoding(nn.Module):
def __init__(self, word_dim, max_seq_len, padding_idx=0, freeze=True):
super(PositionEncoding, self).__init__()
n_position = max_seq_len + 1
self.max_seq_len = max_seq_l... |
12,095 | 834bc7fc97211ba99b8b3e8b7b4b59da3edceccd | # Leo colorizer control file for erlang mode.
# This file is in the public domain.
# Properties for erlang mode.
properties = {
"lineComment": "%",
}
# Attributes dict for erlang_main ruleset.
erlang_main_attributes_dict = {
"default": "null",
"digit_re": "",
"escape": "\\",
"highligh... |
12,096 | f7ce62b2b4546e3c4528ac6bba54dc6500319699 | class Cita:
def __init__(self,id,paciente,fecha,hora,motivo,estado,usermedico,medico):
self.id=id
self.paciente=paciente
self.fecha=fecha
self.hora=hora
self.motivo=motivo
self.estado=estado
self.usermedico=usermedico
self.medico=medico
|
12,097 | 52ec9af768accf106a1bfabd2c0f81c744ae9f4f | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import svm
from stemming.porter2 import stem
import re
def readFromCSV(names):
return [np.array(pd.read_csv(name + ".csv", dtype='float64', header=None).as_matrix()) for name in names]
def plot(X, y):
marker = {0: 'o', 1: '^'... |
12,098 | 0c393693cc660134a1609e9e3882911c5e5292d6 | import cv2
import numpy as np
from PIL import Image
import torchvision.transforms as transforms
import os
import json
import torch
from tqdm import tqdm
# image transform
train_transform = transforms.Compose([
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), ... |
12,099 | 91c989a6931568ea399dac663fea5e243cd129f1 | #!/usr/bin/python3.4
# -*-coding:Utf-8 -*
from lib.inherit_docstring import inherit_docstring
from lib.choices import choices
from lib.gauss_int import gauss_int
from random import randint
from src.meta.ABCInheritableDocstringsMeta import ABCInheritableDocstringsMeta
from mario.bridge.events.action_events import Jump... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.