index int64 0 10k | blob_id stringlengths 40 40 | step-1 stringlengths 0 305k | step-2 stringlengths 6 1.1M ⌀ | step-3 stringlengths 15 1.23M ⌀ | step-4 stringlengths 23 1.34M ⌀ | step-5 stringlengths 55 1.2M ⌀ | step-ids listlengths 1 5 |
|---|---|---|---|---|---|---|---|
9,900 | 58efaad41d02bb5dffbf71c478c7fad12af68e5b | <mask token>
class Cart:
<mask token>
def total_price(self):
ele = 0
for i in self.book_list:
ele += i.book.book_dprice * i.amount
self.total = round(ele, 2)
return self
<mask token>
<mask token>
def del_books(self, book):
print('删除中')
... | <mask token>
class Cart:
def __init__(self):
self.book_list = []
self.total = 0
self.save = 0
def total_price(self):
ele = 0
for i in self.book_list:
ele += i.book.book_dprice * i.amount
self.total = round(ele, 2)
return self
<mask toke... | class CartItem:
<mask token>
class Cart:
def __init__(self):
self.book_list = []
self.total = 0
self.save = 0
def total_price(self):
ele = 0
for i in self.book_list:
ele += i.book.book_dprice * i.amount
self.total = round(ele, 2)
return... | class CartItem:
def __init__(self, book, amount):
self.book = book
self.amount = int(amount)
class Cart:
def __init__(self):
self.book_list = []
self.total = 0
self.save = 0
def total_price(self):
ele = 0
for i in self.book_list:
ele +... | # 自定义购物车项类
class CartItem():
def __init__(self, book, amount):
self.book = book
self.amount = int(amount)
# 自定义购物车
class Cart():
def __init__(self):
self.book_list = []
self.total = 0
self.save = 0
def total_price(self):
ele = 0
for i in self.book_li... | [
3,
5,
7,
8,
9
] |
9,901 | 3022cade3bfa36925bcbda8023e5cd98ed33d093 | <mask token>
| <mask token>
if 'DISPLAY' not in os.environ:
matplotlib.use('Agg')
else:
pass
<mask token>
sns.set(style='white', context='talk')
def get_accuracy(model, kb):
results = []
for clause in kb.clauses:
o1, o2 = model.forward(clause)
if o2.data.numpy()[0][0] > 0.9:
results.appen... | <mask token>
if 'DISPLAY' not in os.environ:
matplotlib.use('Agg')
else:
pass
<mask token>
sns.set(style='white', context='talk')
def get_accuracy(model, kb):
results = []
for clause in kb.clauses:
o1, o2 = model.forward(clause)
if o2.data.numpy()[0][0] > 0.9:
results.appen... | import matplotlib
import os
if 'DISPLAY' not in os.environ:
matplotlib.use('Agg')
else:
pass
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.optim as optim
from matplotlib import pyplot as plt
import seaborn as sns
from tqdm import tqdm
import copy
from utils import Predicate... |
# coding: utf-8
# In[1]:
#coding:utf8
import matplotlib
import os
if 'DISPLAY' not in os.environ:
matplotlib.use('Agg')
else:
pass
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.optim as optim
from matplotlib import pyplot as plt
import seaborn as sns
from tqdm import tq... | [
0,
3,
4,
5,
6
] |
9,902 | 148b849ae43617dde8dbb0c949defa2f390ce5cd | <mask token>
| class Solution(object):
<mask token>
| class Solution(object):
def oddCells(self, m, n, indices):
"""
:type m: int
:type n: int
:type indices: List[List[int]]
:rtype: int
"""
indice_x_dict = {}
indice_y_dict = {}
for x, y in indices:
indice_x_dict[x] = indice_x_dict.get... | class Solution(object):
def oddCells(self, m, n, indices):
"""
:type m: int
:type n: int
:type indices: List[List[int]]
:rtype: int
"""
indice_x_dict = {}
indice_y_dict = {}
for x, y in indices:
indice_x_dict[x] = indice_x_dict.get(... | null | [
0,
1,
2,
3
] |
9,903 | dabd835ff02f2adb01773fb7dd7099206cbae162 | <mask token>
| <mask token>
for i in range(1000):
l = str(i).zfill(3)
k = 0
for j in range(N):
if S[j] == l[k]:
k += 1
if k == 3:
ans += 1
break
print(ans)
| N = int(input())
S = input()
ans = 0
for i in range(1000):
l = str(i).zfill(3)
k = 0
for j in range(N):
if S[j] == l[k]:
k += 1
if k == 3:
ans += 1
break
print(ans)
| N=int(input())
S=input()
ans=0
for i in range(1000):
l=str(i).zfill(3);k=0
for j in range(N):
if S[j]==l[k]:
k+=1
if k==3:ans+=1;break
print(ans)
| null | [
0,
1,
2,
3
] |
9,904 | aa1a7de92b971b6d10d09b2f8ca2c55516e538e4 | <mask token>
| <mask token>
tf.flags.DEFINE_integer('embedding_dim', 100,
'Dimensionality of character embedding (default: 100)')
tf.flags.DEFINE_float('dropout_keep_prob', 0.5,
'Dropout keep probability (default: 0.5)')
tf.flags.DEFINE_integer('batch_size', 128, 'Batch Size (default: 64)')
tf.flags.DEFINE_integer('num_epochs... | <mask token>
flags = tf.app.flags
FLAGS = flags.FLAGS
tf.flags.DEFINE_integer('embedding_dim', 100,
'Dimensionality of character embedding (default: 100)')
tf.flags.DEFINE_float('dropout_keep_prob', 0.5,
'Dropout keep probability (default: 0.5)')
tf.flags.DEFINE_integer('batch_size', 128, 'Batch Size (default: ... | import tensorflow as tf
import numpy as np
import os
import time
import datetime
import data_helpers
from text_rnn import TextRNN
from tensorflow.contrib import learn
flags = tf.app.flags
FLAGS = flags.FLAGS
tf.flags.DEFINE_integer('embedding_dim', 100,
'Dimensionality of character embedding (default: 100)')
tf.fla... | #! /usr/bin/env python
import tensorflow as tf
import numpy as np
import os
import time
import datetime
import data_helpers
from text_rnn import TextRNN
from tensorflow.contrib import learn
# Parameters
# ==================================================
# Data loading params
flags = tf.app.flags
FLAGS = flags.FLA... | [
0,
1,
2,
3,
4
] |
9,905 | 5b440484c5d7f066c54837c2812967a0ff360399 | <mask token>
class DailyCacheMiddleware(CacheMiddleware):
<mask token>
@property
def key_prefix(self):
return date.today().isoformat() + '/' + (self.__key_prefix or '')
@key_prefix.setter
def key_prefix(self, value):
self.__key_prefix = value
<mask token>
| <mask token>
class DailyCacheMiddleware(CacheMiddleware):
"""Like the cache middleware, but always expires at midnight"""
@property
def key_prefix(self):
return date.today().isoformat() + '/' + (self.__key_prefix or '')
@key_prefix.setter
def key_prefix(self, value):
self.__key_p... | <mask token>
lt_cache = cache_page(settings.CACHES['eregs_longterm_cache']['TIMEOUT'],
cache='eregs_longterm_cache')
class DailyCacheMiddleware(CacheMiddleware):
"""Like the cache middleware, but always expires at midnight"""
@property
def key_prefix(self):
return date.today().isoformat() + '... | from datetime import date
from django.conf import settings
from django.utils.decorators import decorator_from_middleware_with_args
from django.views.decorators.cache import cache_page
from django.middleware.cache import CacheMiddleware
lt_cache = cache_page(settings.CACHES['eregs_longterm_cache']['TIMEOUT'],
cache=... | from datetime import date
from django.conf import settings
from django.utils.decorators import decorator_from_middleware_with_args
from django.views.decorators.cache import cache_page
from django.middleware.cache import CacheMiddleware
lt_cache = cache_page(settings.CACHES['eregs_longterm_cache']['TIMEOUT'],
... | [
3,
4,
5,
6,
7
] |
9,906 | f73faabe955e3ae05039e58ebabe5c012e080f38 | <mask token>
class TankDriveResetEncoders(Command):
<mask token>
def execute(self):
subsystems.driveline.resetEncoders()
print('CMD TankDriveResetEncoders: Reset Completed')
<mask token>
| <mask token>
class TankDriveResetEncoders(Command):
def __init__(self):
super().__init__('TankDriveTurnToHeading')
self.requires(subsystems.driveline)
self.setInterruptible(True)
self.setRunWhenDisabled(False)
def execute(self):
subsystems.driveline.resetEncoders()
... | <mask token>
class TankDriveResetEncoders(Command):
def __init__(self):
super().__init__('TankDriveTurnToHeading')
self.requires(subsystems.driveline)
self.setInterruptible(True)
self.setRunWhenDisabled(False)
def execute(self):
subsystems.driveline.resetEncoders()
... | import time
import math
from wpilib import SmartDashboard
from wpilib.command import Command
import robotmap
import subsystems
class TankDriveResetEncoders(Command):
def __init__(self):
super().__init__('TankDriveTurnToHeading')
self.requires(subsystems.driveline)
self.setInterruptible(Tr... | import time
import math
from wpilib import SmartDashboard
from wpilib.command import Command
import robotmap
import subsystems
class TankDriveResetEncoders(Command):
def __init__(self):
super().__init__('TankDriveTurnToHeading')
self.requires(subsystems.driveline)
self.setInterruptible(... | [
2,
3,
4,
5,
6
] |
9,907 | 263d2fe43cf8747f20fd51897ba003c9c4cb4280 | <mask token>
class Config:
"""
Configuration management entity.
Args:
name (str): Name of config environment.
fallback (bool): Indicate if configuration should fallback to base.
"""
no_config_err = 'No such config variable {}'
def __init__(self, name, fallback):
from ... | <mask token>
class EMPTY:
"""
Signifies that a default value was not set. Should trigger an error if
default is set to EMPTY and an attribute does not exist.
"""
pass
class Config:
"""
Configuration management entity.
Args:
name (str): Name of config environment.
fal... | <mask token>
class EMPTY:
"""
Signifies that a default value was not set. Should trigger an error if
default is set to EMPTY and an attribute does not exist.
"""
pass
class Config:
"""
Configuration management entity.
Args:
name (str): Name of config environment.
fal... | <mask token>
CONFIG_KEY = 'config_class'
ENV = {}
class EMPTY:
"""
Signifies that a default value was not set. Should trigger an error if
default is set to EMPTY and an attribute does not exist.
"""
pass
class Config:
"""
Configuration management entity.
Args:
name (str): Na... | """
Configuration management.
Environment must be set before use.
Call .get() to obtain configuration variable. If the variable does not exist
in the set environment, then
"""
CONFIG_KEY = "config_class"
ENV = {}
class EMPTY:
"""
Signifies that a default value was not set. Should trigger an error if
... | [
5,
7,
8,
10,
11
] |
9,908 | 01339324ad1a11aff062e8b27efabf27c97157fb | <mask token>
| <mask token>
for index in range(len(train_folder_list)):
path = os.path.join(TRAIN_DIR, train_folder_list[index])
path = path + '/'
img_list = os.listdir(path)
for img in img_list:
img_path = os.path.join(path, img)
img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)
train_input.app... | <mask token>
TRAIN_DIR = 'C:/Users/vgg/untitled/MNIST/trainingSet/'
train_folder_list = array(os.listdir(TRAIN_DIR))
train_input = []
train_label = []
label_encoder = LabelEncoder()
integer_encoded = label_encoder.fit_transform(train_folder_list)
onehot_encoder = OneHotEncoder(sparse=False)
integer_encoded = integer_en... | import os
import cv2
import numpy as np
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import OneHotEncoder
from numpy import array
import tensorflow as tf
TRAIN_DIR = 'C:/Users/vgg/untitled/MNIST/trainingSet/'
train_folder_list = array(os.listdir(TRAIN_DIR))
train_input = []
train_label = []... | import os
import cv2
import numpy as np
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import OneHotEncoder
from numpy import array
import tensorflow as tf
TRAIN_DIR = 'C:/Users/vgg/untitled/MNIST/trainingSet/'
train_folder_list = array(os.listdir(TRAIN_DIR))
train_input = []
tr... | [
0,
1,
2,
3,
4
] |
9,909 | 1be5de71615eae6c9074e67b0dcaabbac4d82e2b | def
a = 10
b = 2
c = 3
cal(a,b,c) | null | null | null | null | [
0
] |
9,910 | 0eb86fc64b74c79cace838e2d71ed92533123229 | <mask token>
def construct_basis_ph2B(holes, particles):
basis = []
for i in holes:
for j in holes:
basis.append((i, j))
for i in holes:
for a in particles:
basis.append((i, a))
for a in particles:
for i in holes:
basis.append((a, i))
for... | <mask token>
def construct_basis_ph2B(holes, particles):
basis = []
for i in holes:
for j in holes:
basis.append((i, j))
for i in holes:
for a in particles:
basis.append((i, a))
for a in particles:
for i in holes:
basis.append((a, i))
for... | <mask token>
def construct_basis_2B(holes, particles):
basis = []
for i in holes:
for j in holes:
basis.append((i, j))
for i in holes:
for a in particles:
basis.append((i, a))
for a in particles:
for i in holes:
basis.append((a, i))
for a... | import numpy as np
from numpy import array, dot, diag, reshape, transpose
from scipy.linalg import eigvalsh
from scipy.integrate import odeint, ode
from sys import argv
def construct_basis_2B(holes, particles):
basis = []
for i in holes:
for j in holes:
basis.append((i, j))
for i in ho... | #!/usr/bin/env python
#------------------------------------------------------------------------------
# imsrg_pairing.py
#
# author: H. Hergert
# version: 1.5.0
# date: Dec 6, 2016
#
# tested with Python v2.7
#
# Solves the pairing model for four particles in a basis of four doubly
# degenerate states by me... | [
19,
20,
27,
28,
29
] |
9,911 | dbefca59376e567a6116dec4e07c44b1fe301ca9 | <mask token>
| ba1466.pngMap = [
'11111111111111111111111111111100000000011111111111111111111111111000000000000000011111111111111111111111111111111111111111111111'
,
'11111111111111111111111111111110000000011111111111111111111111111000000000000000011111111111111111111111111111111111111111111111'
,
'111111111111111... | ba1466.pngMap = [
'11111111111111111111111111111100000000011111111111111111111111111000000000000000011111111111111111111111111111111111111111111111',
'11111111111111111111111111111110000000011111111111111111111111111000000000000000011111111111111111111111111111111111111111111111',
'1111111111111111111111111111111000000... | null | null | [
0,
1,
2
] |
9,912 | c8a6a8633f863e0350157346106a747096d26939 | <mask token>
class lexicon0(db.Model):
word = db.StringProperty(required=True)
known = db.StringListProperty(indexed=False)
<mask token>
class mainpage(webapp.RequestHandler):
def get(self):
global MONTH, DATASET, NGRAM, PROB, REQUESTURL, GENURL
if len(self.request.get('m')):
... | <mask token>
class lexicon0(db.Model):
word = db.StringProperty(required=True)
known = db.StringListProperty(indexed=False)
def lexicon_key(lexicon_name=None):
return db.Key.from_path('lexicon0', lexicon_name or 'default')
<mask token>
def getjp(before, wordlist, after):
global REQUESTURL
wo... | <mask token>
class lexicon0(db.Model):
word = db.StringProperty(required=True)
known = db.StringListProperty(indexed=False)
def lexicon_key(lexicon_name=None):
return db.Key.from_path('lexicon0', lexicon_name or 'default')
def combination(wordlist, t):
tempc = wordlist
combinationqueryset = [l... | import re
import cgi
import os
import urllib
import urllib2
from time import sleep
from google.appengine.api import taskqueue
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from google.appengine.api import urlfetch
from google.appeng... |
import re
import cgi
import os
import urllib
import urllib2
from time import sleep
from google.appengine.api import taskqueue
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from google.appengine.api import urlfetch
from google.ap... | [
8,
16,
17,
21,
22
] |
9,913 | 4d1900c1a0a8d7639e0ec16fb0128fd8efc2e8a1 | <mask token>
class MVAN(object):
<mask token>
<mask token>
<mask token>
def _setup_training(self):
if self.hparams.save_dirpath == 'checkpoints/':
self.save_dirpath = os.path.join(self.hparams.root_dir, self.
hparams.save_dirpath)
self.summary_writer = Summ... | <mask token>
class MVAN(object):
def __init__(self, hparams):
self.hparams = hparams
self._logger = logging.getLogger(__name__)
np.random.seed(hparams.random_seed[0])
torch.manual_seed(hparams.random_seed[0])
torch.cuda.manual_seed_all(hparams.random_seed[0])
torch... | <mask token>
os.environ['CUDA_VISIBLE_DEVICES'] = '0,1'
<mask token>
class MVAN(object):
def __init__(self, hparams):
self.hparams = hparams
self._logger = logging.getLogger(__name__)
np.random.seed(hparams.random_seed[0])
torch.manual_seed(hparams.random_seed[0])
torch.cu... | import os
os.environ['CUDA_VISIBLE_DEVICES'] = '0,1'
import logging
import itertools
import torch
from torch import nn, optim
from torch.optim import lr_scheduler
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
from tqdm import tqdm
from setproctitle import setproctitle
from bi... | import os
os.environ["CUDA_VISIBLE_DEVICES"] = "0,1"
import logging
import itertools
import torch
from torch import nn, optim
from torch.optim import lr_scheduler
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
from tqdm import tqdm
from setproctitle import setproctitle
from ... | [
4,
7,
8,
9,
10
] |
9,914 | 2c82dd33180a7442607e5cbedf8846bd72b37150 | <mask token>
class retrieve_open_space(dml.Algorithm):
<mask token>
<mask token>
<mask token>
<mask token>
<mask token>
| <mask token>
class retrieve_open_space(dml.Algorithm):
<mask token>
<mask token>
<mask token>
@staticmethod
def execute(trial=False, log=False):
"""Retrieves open spaces in Boston as geoJSON"""
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
... | <mask token>
class retrieve_open_space(dml.Algorithm):
contributor = 'bmroach'
reads = []
writes = ['bmroach.open_space']
@staticmethod
def execute(trial=False, log=False):
"""Retrieves open spaces in Boston as geoJSON"""
startTime = datetime.datetime.now()
client = dml.py... | import urllib.request
import json
import dml, prov.model
import datetime, uuid
import geojson
<mask token>
class retrieve_open_space(dml.Algorithm):
contributor = 'bmroach'
reads = []
writes = ['bmroach.open_space']
@staticmethod
def execute(trial=False, log=False):
"""Retrieves open spac... | import urllib.request
import json
import dml, prov.model
import datetime, uuid
import geojson
# import csv
"""
Skelton file provided by lapets@bu.edu
Heavily modified by bmroach@bu.edu
City of Boston Open Spaces (Like parks, etc)
Development notes:
"""
class retrieve_open_space(dml.Algorithm):
contributor = '... | [
1,
3,
4,
5,
6
] |
9,915 | 7f220a970d65a91228501f7db59089e6c0604fb5 | <mask token>
def wait_condition(cond, timeout=1, sleeptime=0.01):
"""Wait for condition to return anything other than None
"""
if timeout is None:
timeout = 1
if timeout < sleeptime:
print('Warning, timeout cannot be smaller than', sleeptime)
timeout = sleeptime
tries = int... | <mask token>
def wait_condition(cond, timeout=1, sleeptime=0.01):
"""Wait for condition to return anything other than None
"""
if timeout is None:
timeout = 1
if timeout < sleeptime:
print('Warning, timeout cannot be smaller than', sleeptime)
timeout = sleeptime
tries = int... | <mask token>
def shared_binary_location(cmd='shared'):
""" ../src/ is used by default.
"""
return os.path.join(BIN_PREFIX, cmd)
return binary_location(cmd, SHARED_USE_PATH)
def binary_location(cmd, USE_PATH=False):
""" ../src/ is used by default.
"""
return os.path.join(BIN_PREFIX, cmd)
... | <mask token>
ON_POSIX = 'posix' in sys.builtin_module_names
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
BIN_PREFIX = os.path.abspath(os.path.join(CURRENT_DIR, '..', '..', 'src'))
DEFAULT_CERT_PATH = os.path.abspath(os.path.join(CURRENT_DIR, '..',
'test_certs'))
DEFAULT_EXTENSION_PATH = os.path.abspath(... | # -*- coding: utf-8 -*-
import os
import sys
import socket
import signal
import functools
import atexit
import tempfile
from subprocess import Popen, PIPE, STDOUT
from threading import Thread
from queue import Queue, Empty
from time import sleep
import json
from .exceptions import CommandError, TimeoutWaitingFor
ON_PO... | [
10,
11,
13,
14,
16
] |
9,916 | 87a4fcb26464925952dde57fecf4709f01e9fed7 | <mask token>
class AjaxableResponseMixin:
<mask token>
<mask token>
<mask token>
class EditorHomeView(LoginRequiredMixin, AjaxableResponseMixin, CreateView):
form_class = EditorTextForm
model = EditorText
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwa... | <mask token>
class AjaxableResponseMixin:
<mask token>
def form_invalid(self, form):
response = super().form_invalid(form)
if self.request.is_ajax():
return JsonResponse(form.errors, status=400)
else:
return response
def form_valid(self, form):
res... | <mask token>
class AjaxableResponseMixin:
"""
Mixin to add AJAX support to a form.
Must be used with an object-based FormView (e.g. CreateView)
"""
def form_invalid(self, form):
response = super().form_invalid(form)
if self.request.is_ajax():
return JsonResponse(form.... | from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import JsonResponse
from django.views.generic import CreateView, UpdateView, ListView, DeleteView, TemplateView
from example.forms import EditorTextForm
from example.models import EdidorText
class AjaxableResponseMixin:
"""
Mixin to ad... | from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import JsonResponse
from django.views.generic import CreateView, UpdateView, ListView, \
DeleteView, TemplateView
from example.forms import EditorTextForm
from example.models import EdidorText
class AjaxableResponseMixin:
"""
Mixi... | [
7,
9,
10,
11,
12
] |
9,917 | 9555ed63b3906ec23c31839691a089aad9d96c63 | <mask token>
| <mask token>
class Migration(migrations.Migration):
<mask token>
<mask token>
| <mask token>
class Migration(migrations.Migration):
dependencies = [('training_area', '0002_event')]
operations = [migrations.AddField(model_name='event', name='athlete',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.
models.deletion.CASCADE, related_name='athlete_calendar... | from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [('training_area', '0002_event')]
operations = [migrations.AddField(model_name='event', name='athlete',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.
... | # Generated by Django 2.1.7 on 2019-03-14 07:27
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('training_area', '0002_event'),
]
operations = [
migrations.AddField(
model_name='event',
... | [
0,
1,
2,
3,
4
] |
9,918 | 2eddd446dc59695b185be368b359bae78a868b90 |
##Problem 10 «The number of even elements of the sequence» (Medium)
##Statement
##Determine the number of even elements in the sequence ending with the number 0.
a = True
i = 0
while a is True:
x = int(input())
if x != 0:
if x%2 == 0:
i = i+1
else:
a =False
print(i)
| null | null | null | null | [
0
] |
9,919 | 839d4182663983a03975465d3909631bd6db1d83 | <mask token>
class TimezoneMiddleware(object):
<mask token>
<mask token>
| <mask token>
class TimezoneMiddleware(object):
<mask token>
def process_request(self, request):
user = request.user
if hasattr(user, 'profile'):
user_tz = user.profile.timezone
timezone.activate(pytz.timezone(user_tz))
else:
timezone.activate(pytz.t... | <mask token>
class TimezoneMiddleware(object):
""" Middleware to get user's timezone and activate timezone
if user timezone is not available default value 'UTC' is activated """
def process_request(self, request):
user = request.user
if hasattr(user, 'profile'):
user_tz =... | import pytz
from django.utils import timezone
class TimezoneMiddleware(object):
""" Middleware to get user's timezone and activate timezone
if user timezone is not available default value 'UTC' is activated """
def process_request(self, request):
user = request.user
if hasattr(user, ... | import pytz
from django.utils import timezone
class TimezoneMiddleware(object):
""" Middleware to get user's timezone and activate timezone
if user timezone is not available default value 'UTC' is activated """
def process_request(self, request):
user = request.user
if hasattr(user, ... | [
1,
2,
3,
4,
5
] |
9,920 | f6b2169a4644f4f39bbdebd9bb9c7cc637b54f8b | <mask token>
| <mask token>
def main():
format_string = '%s %s %s %s %s %s %s %s %s\n'
while True:
edit = [sys.stdin.readline() for i in range(14)]
if edit[13] == '':
break
revision = edit[0].split(' ')
article_id, rev_id, title, timestamp, username, user_id = ('a' +
r... | <mask token>
def main():
format_string = '%s %s %s %s %s %s %s %s %s\n'
while True:
edit = [sys.stdin.readline() for i in range(14)]
if edit[13] == '':
break
revision = edit[0].split(' ')
article_id, rev_id, title, timestamp, username, user_id = ('a' +
r... | import sys
def main():
format_string = '%s %s %s %s %s %s %s %s %s\n'
while True:
edit = [sys.stdin.readline() for i in range(14)]
if edit[13] == '':
break
revision = edit[0].split(' ')
article_id, rev_id, title, timestamp, username, user_id = ('a' +
rev... | import sys
def main():
# String to format output
format_string = "%s %s %s %s %s %s %s %s %s\n"
while True:
# Read 14 lines at a time from stdin for wikipedia dataset
edit = [sys.stdin.readline() for i in range(14)]
# Break if we've reached the end of stdin
if edit[13] == "":
break
# Parse data from re... | [
0,
1,
2,
3,
4
] |
9,921 | 05f5931a53c9916f151f42910575f9c5533bfceb | import sys
import HTSeq
import re
import string
import glob
import os
import time
import difflib
import argparse
def parse_input():
parser = argparse.ArgumentParser(description="""
USAGE: python make_figs.py -f data_file
""")
# If the -b option is used, tRNAs with no tails are not counted.
# This... | null | null | null | null | [
0
] |
9,922 | 5f680fb21fe1090dfb58f5b9260739b91ae04d99 | <mask token>
class UserRegistrationForm(forms.Form):
<mask token>
<mask token>
<mask token>
<mask token>
<mask token>
<mask token>
<mask token>
def save(self):
new_user = User.objects.create_user(self.cleaned_data['email'],
self.cleaned_data['email'], self.cleaned_... | <mask token>
class UserRegistrationForm(forms.Form):
<mask token>
<mask token>
<mask token>
<mask token>
<mask token>
<mask token>
def clean(self):
cleaned_data = self.cleaned_data
try:
User.objects.get(username__exact=cleaned_data.get('email'))
except ... | <mask token>
class UserRegistrationForm(forms.Form):
first_name = forms.CharField(required=True, max_length=30)
last_name = forms.CharField(required=True, max_length=30)
email = forms.EmailField(required=True, max_length=30)
password = forms.CharField(widget=forms.PasswordInput, min_length=
MI... | <mask token>
MIN_PASSWORD_LENGTH = 8
MAX_PASSWORD_LENGTH = 30
class UserRegistrationForm(forms.Form):
first_name = forms.CharField(required=True, max_length=30)
last_name = forms.CharField(required=True, max_length=30)
email = forms.EmailField(required=True, max_length=30)
password = forms.CharField(w... | from django import forms
from django.contrib.auth.models import User
from ServicePad.apps.account.models import UserProfile
import hashlib, random, datetime
from ServicePad.apps.registration.models import ActivationKey
MIN_PASSWORD_LENGTH=8
MAX_PASSWORD_LENGTH=30
class UserRegistrationForm(forms.Form):
first_name... | [
6,
7,
8,
9,
11
] |
9,923 | 964499c02548a7e790d96efcd780f471ab1fe1e3 | from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from database_setup import Category, Base, CategoryItem, User
engine = create_engine('postgresql:///thegoodybasket')
# Bind the engine to the metadata of the Base class so that the
# declaratives can be accessed through a DBSession instance
... | null | null | null | null | [
0
] |
9,924 | e9fab2bb49cfda00b8cfedafab0009f691d11ec9 | <mask token>
def post_create(request):
form = PostForm(request.POST or None, request.FILES or None)
if request.method == 'POST':
user = request.POST.get('user')
title = request.POST.get('title')
content = request.POST.get('content')
PostStudent.objects.create(user=user, title=t... | <mask token>
def post_create(request):
form = PostForm(request.POST or None, request.FILES or None)
if request.method == 'POST':
user = request.POST.get('user')
title = request.POST.get('title')
content = request.POST.get('content')
PostStudent.objects.create(user=user, title=t... | <mask token>
def post_create(request):
form = PostForm(request.POST or None, request.FILES or None)
if request.method == 'POST':
user = request.POST.get('user')
title = request.POST.get('title')
content = request.POST.get('content')
PostStudent.objects.create(user=user, title=t... | from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.contenttypes.models import ContentType
from User.forms import EditProfileForm
from User import forms
from django.db.models import Q
from django.contrib import messages
from django.urls import reverse
from django.http import HttpRespons... | from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.contenttypes.models import ContentType
from User.forms import EditProfileForm
from User import forms
from django.db.models import Q
from django.contrib import messages
from django.urls import reverse
from django.http import HttpRespons... | [
5,
6,
8,
9,
10
] |
9,925 | f2a94f6bfe86af439a8248b40732340c45d89b93 | <mask token>
class Trap(GameObject):
<mask token>
def __init__(self, gamedir, filename=None):
self.attacks = list()
self.x = 0
self.y = 0
self.radius = 0
self.is_first_round = True
GameObject.__init__(self, gamedir, filename)
<mask token>
def trigger_t... | <mask token>
class Trap(GameObject):
<mask token>
def __init__(self, gamedir, filename=None):
self.attacks = list()
self.x = 0
self.y = 0
self.radius = 0
self.is_first_round = True
GameObject.__init__(self, gamedir, filename)
def read_in_config(self, filen... | <mask token>
class Trap(GameObject):
"""
This class is used to create traps (or blessing objects) that exist
in the arena on their own but that are not subject to attack.
The only real attributes traps have is different types of attacks that
they can carry out on combatants in the arena.
"""
... | import random
import mb_io
import mb_subs
from mb_go import GameObject
class Trap(GameObject):
"""
This class is used to create traps (or blessing objects) that exist
in the arena on their own but that are not subject to attack.
The only real attributes traps have is different types of attacks that
... | # -------------------------------------------------------------------------
# File: mb_trap.py
# Created: Tue Feb 7 20:51:32 2006
# -------------------------------------------------------------------------
import random
import mb_io
import mb_subs
from mb_go import GameObject
class Trap(GameObject):
"""
... | [
3,
4,
5,
6,
7
] |
9,926 | d6af9a75fbe8bdf1a81a352cee71ac81fb373b86 | <mask token>
def process_the_source(fname, dest=None, host_ip=None, verbose=False):
assert os.path.exists(fname) and os.path.isfile(fname
), 'Cannot proceed without the fname in process_the_source().'
the_lines = []
with open(fname, 'r') as fIn:
for line in fIn:
l = line.rstrip... | <mask token>
def process_the_source(fname, dest=None, host_ip=None, verbose=False):
assert os.path.exists(fname) and os.path.isfile(fname
), 'Cannot proceed without the fname in process_the_source().'
the_lines = []
with open(fname, 'r') as fIn:
for line in fIn:
l = line.rstrip... | <mask token>
__target__ = '${EXTERNAL_HOST}'
sources = {}
def process_the_source(fname, dest=None, host_ip=None, verbose=False):
assert os.path.exists(fname) and os.path.isfile(fname
), 'Cannot proceed without the fname in process_the_source().'
the_lines = []
with open(fname, 'r') as fIn:
... | import os
import sys
import socket
__target__ = '${EXTERNAL_HOST}'
sources = {}
def process_the_source(fname, dest=None, host_ip=None, verbose=False):
assert os.path.exists(fname) and os.path.isfile(fname
), 'Cannot proceed without the fname in process_the_source().'
the_lines = []
with open(fname... | import os
import sys
import socket
__target__ = '${EXTERNAL_HOST}'
sources = {}
def process_the_source(fname, dest=None, host_ip=None, verbose=False):
assert (os.path.exists(fname) and os.path.isfile(fname)), 'Cannot proceed without the fname in process_the_source().'
the_lines = []
with open(fname, 'r')... | [
1,
2,
3,
4,
5
] |
9,927 | 8058ff209af03b7365ffad2a9ce2e2805b548f53 | <mask token>
def Search():
Names = Name.get()
Ages = Age.get()
Genders = Gender.get()
Heights = height.get()
Weights = weight.get()
Rollnos = StudentId.get()
Sports = Sport.get()
t = tree.get_children()
for f in t:
tree.delete(f)
if len(Names) != 0:
cursor.execu... | <mask token>
def save():
Names = Name.get()
Ages = Age.get()
Genders = Gender.get()
Heights = height.get()
weights = weight.get()
rollnos = StudentId.get()
Sports = Sport.get()
cursor.execute(
"""
INSERT INTO Students(Name, Age, Gender, Height,_weight,StudentId)
VALUES ... | <mask token>
def save():
Names = Name.get()
Ages = Age.get()
Genders = Gender.get()
Heights = height.get()
weights = weight.get()
rollnos = StudentId.get()
Sports = Sport.get()
cursor.execute(
"""
INSERT INTO Students(Name, Age, Gender, Height,_weight,StudentId)
VALUES ... | <mask token>
conn = pyodbc.connect(
'Driver={SQL Server};Server=MUTHUCOMPUTER;Database=Class4c v1;Trusted_Connection=yes;'
)
cursor = conn.cursor()
def save():
Names = Name.get()
Ages = Age.get()
Genders = Gender.get()
Heights = height.get()
weights = weight.get()
rollnos = StudentId.g... | from tkinter import ttk
import tkinter as tk
import pyodbc
#ConnectingDatabase#
from tkinter import messagebox
conn = pyodbc.connect('Driver={SQL Server};'
'Server=MUTHUCOMPUTER;'
'Database=Class4c v1;'
'Trusted_Connection=yes;')
cursor = ... | [
2,
4,
5,
6,
8
] |
9,928 | cc094f8aeff3b52bd9184f7b815320529ecb4550 | <mask token>
@app.route('/')
def root():
return 'Test!'
@app.route('/federal/geographic')
def federal_geographic():
pass
<mask token>
@app.route('/state/geographic')
def state_geographic():
pass
@app.route('/local/temporal')
def local_temporal():
pass
<mask token>
| <mask token>
@app.route('/')
def root():
return 'Test!'
@app.route('/federal/geographic')
def federal_geographic():
pass
@app.route('/federal/issue')
def federal_issue():
pass
@app.route('/state/geographic')
def state_geographic():
pass
@app.route('/local/temporal')
def local_temporal():
p... | <mask token>
@app.route('/')
def root():
return 'Test!'
@app.route('/federal/geographic')
def federal_geographic():
pass
@app.route('/federal/issue')
def federal_issue():
pass
@app.route('/state/geographic')
def state_geographic():
pass
@app.route('/local/temporal')
def local_temporal():
p... | from flask import Flask
app = Flask(__name__)
@app.route('/')
def root():
return 'Test!'
@app.route('/federal/geographic')
def federal_geographic():
pass
@app.route('/federal/issue')
def federal_issue():
pass
@app.route('/state/geographic')
def state_geographic():
pass
@app.route('/local/tempo... | from flask import Flask
app = Flask(__name__)
@app.route('/')
def root():
return "Test!"
@app.route('/federal/geographic')
def federal_geographic():
pass
@app.route('/federal/issue')
def federal_issue():
pass
@app.route('/state/geographic')
def state_geographic():
pass
@app.route('/local/temporal'... | [
4,
5,
6,
8,
9
] |
9,929 | 06605bbd91c62a02a66770ca3f37a9d2d1401ccb | <mask token>
@app.route('/')
def demo():
return render_template('home.html', hero_mapping=hero_mapping)
@app.route('/predict', methods=['POST'])
def predict():
valid, res = valid_input(list(request.json))
if not valid:
return res
else:
feature = data_to_feature(res)
prob = mo... | <mask token>
@app.route('/')
def demo():
return render_template('home.html', hero_mapping=hero_mapping)
@app.route('/predict', methods=['POST'])
def predict():
valid, res = valid_input(list(request.json))
if not valid:
return res
else:
feature = data_to_feature(res)
prob = mo... | <mask token>
app = Flask(__name__, static_folder='./static')
@app.route('/')
def demo():
return render_template('home.html', hero_mapping=hero_mapping)
@app.route('/predict', methods=['POST'])
def predict():
valid, res = valid_input(list(request.json))
if not valid:
return res
else:
... | from flask import Flask, render_template, url_for, request, jsonify
from model.model import load_site_config, load_hero_mapping, load_pretrained_model, valid_input, data_to_feature
from model.model import combine_list, hero_ids
from itertools import product
import numpy as np
app = Flask(__name__, static_folder='./stat... | from flask import Flask, render_template, url_for, request, jsonify
from model.model import load_site_config, load_hero_mapping, load_pretrained_model, valid_input, data_to_feature
from model.model import combine_list, hero_ids
from itertools import product
import numpy as np
app = Flask(__name__,static_folder='./stat... | [
2,
4,
5,
6,
7
] |
9,930 | 1f63f9234596787e4859b740d3a7fbfaacc9c0c8 | <mask token>
def compute_loss(dataloader, net):
loss = 0
if torch.cuda.is_available():
net.cuda()
net.eval()
n_batches = 0
with torch.no_grad():
for x, y in dataloader:
n_batches += 1
if torch.cuda.is_available():
x = x.cuda()
... | <mask token>
def split_to_train_validation(path_to_data):
dataset = CustomDataset(path_to_data)
print(len(dataset))
batch_size = 300
validation_split = 0.2
shuffle_dataset = True
random_seed = 56
dataset_size = len(dataset)
indices = list(range(dataset_size))
split = int(np.floor(v... | <mask token>
def split_to_train_validation(path_to_data):
dataset = CustomDataset(path_to_data)
print(len(dataset))
batch_size = 300
validation_split = 0.2
shuffle_dataset = True
random_seed = 56
dataset_size = len(dataset)
indices = list(range(dataset_size))
split = int(np.floor(v... | import random
import glob
import json
import time
from torch.utils.data import Dataset, DataLoader, SubsetRandomSampler
from SimpleDataLoader import CustomDataset, get_params_from_filename
import numpy as np
from DNN_model import Net
import torch.optim as optim
import torch.nn as nn
import torch
from tqdm import tqdm
f... | import random
import glob
import json
import time
from torch.utils.data import Dataset, DataLoader, SubsetRandomSampler
from SimpleDataLoader import CustomDataset, get_params_from_filename
import numpy as np
from DNN_model import Net
import torch.optim as optim
import torch.nn as nn
import torch
from tqdm import tqdm
... | [
4,
6,
7,
9,
10
] |
9,931 | c6e315d7dd44b998f64eee079f2d8455ffecdc30 | <mask token>
class SystemTrayIcon(QSystemTrayIcon):
<mask token>
<mask token>
def set_icon_state(self, state):
pixmap = QApplication.instance().windowIcon().pixmap(256, 256, state)
self.setIcon(QIcon(pixmap))
| <mask token>
class SystemTrayIcon(QSystemTrayIcon):
def __init__(self, parent=None):
super(SystemTrayIcon, self).__init__(parent)
self.set_icon_state(QIcon.Disabled)
menu = QMenu(parent)
self.exit_action = menu.addAction('E&xit')
self.exit_action.triggered.connect(self.clo... | <mask token>
class SystemTrayIcon(QSystemTrayIcon):
def __init__(self, parent=None):
super(SystemTrayIcon, self).__init__(parent)
self.set_icon_state(QIcon.Disabled)
menu = QMenu(parent)
self.exit_action = menu.addAction('E&xit')
self.exit_action.triggered.connect(self.clo... | from PyQt4.QtGui import QSystemTrayIcon, QApplication, QMenu, QIcon
class SystemTrayIcon(QSystemTrayIcon):
def __init__(self, parent=None):
super(SystemTrayIcon, self).__init__(parent)
self.set_icon_state(QIcon.Disabled)
menu = QMenu(parent)
self.exit_action = menu.addAction('E&xi... | from PyQt4.QtGui import QSystemTrayIcon, QApplication, QMenu, QIcon
class SystemTrayIcon(QSystemTrayIcon):
def __init__(self, parent=None):
super(SystemTrayIcon, self).__init__(parent)
self.set_icon_state(QIcon.Disabled)
menu = QMenu(parent)
self.exit_action = menu.addActio... | [
2,
3,
4,
5,
6
] |
9,932 | 519746450826d02230a492a99e0b518602d53fcb | <mask token>
class BulletSpawnerTemplate(object):
<mask token>
<mask token>
def setRounds(self, rounds):
self._rounds = rounds
<mask token>
<mask token>
<mask token>
<mask token>
<mask token>
<mask token>
class BulletMasterTemplate(object):
def __init__(self, name):... | <mask token>
class BulletSpawnerTemplate(object):
def __init__(self, initialPosition, initialVelocity):
self._spawningCycle = 0
self._initialPosition = initialPosition
self._initialVelocity = initialVelocity
self._movementList = dict()
self._displacement = 0
self._... | <mask token>
class BulletSpawnerTemplate(object):
def __init__(self, initialPosition, initialVelocity):
self._spawningCycle = 0
self._initialPosition = initialPosition
self._initialVelocity = initialVelocity
self._movementList = dict()
self._displacement = 0
self._... | <mask token>
class BulletTemplate(object):
def __init__(self, animationName, initialVelocity, hitbox):
self._spawningCycle = 0
self._animationName = animationName
self._initialVelocity = initialVelocity
self._movementList = dict()
self._hitbox = hitbox
<mask token>
c... | #classes that store values related to levels
from mg_cus_struct import *
from mg_movement import *
import copy
class BulletTemplate(object) :
def __init__(self, animationName, initialVelocity, hitbox) :
self._spawningCycle = 0
self._animationName = animationName
self._initialVelocity = init... | [
13,
20,
21,
23,
26
] |
9,933 | 7e461e212d9944c229d1473ea16283d3d036bf55 | import tensorflow as tf
import gensim
import string
import numpy as np
import random
##### prepare data
path = 'stanfordSentimentTreebank/output_50d.txt'
# model_path = 'stanfordSentimentTreebank/output'
# model = gensim.models.Word2Vec.load(model_path)
model = gensim.models.KeyedVectors.load_word2vec_format('/Users/i... | null | null | null | null | [
0
] |
9,934 | 9b8f3962172d4a867a3a070b6139bb302fd7e2f5 | <mask token>
class Pregame(tk.Frame):
<mask token>
<mask token>
def __GUI_Reset__(self):
for widget in self.winfo_children():
widget.destroy()
tk.Label(self, text='Otello', font=FONTS['large'], bg='white').pack(
side='top')
Separator(self, orient='horizonta... | <mask token>
class Pregame(tk.Frame):
<mask token>
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
self.configure(bg='white')
self.set_vals = []
self.__GUI_Reset__()
def __GUI_Reset__(self):
for widget i... | <mask token>
class Handler:
<mask token>
<mask token>
<mask token>
<mask token>
<mask token>
<mask token>
<mask token>
<mask token>
def Get_Winner(self) ->tuple:
return self.Game.Check_Winner()
<mask token>
<mask token>
class Window(tk.Tk):
def __init__(self... | <mask token>
FONTS = {'large': ('Helvetica', 20), 'medium': ('Helvetica', 16), 'small':
('Helvetica', 12)}
class Handler:
def __init__(self):
self.Game = None
self.GameParams = {}
self.Window = Window(self)
self.Window.mainloop()
def Replay(self):
self.GameParams ... | import tkinter as tk
import Widgets as wg
import Logic as lgc
from tkinter.ttk import Separator
from tkinter.messagebox import showerror, showinfo
# Fonts that we can utilise
FONTS = {"large":("Helvetica", 20), "medium":("Helvetica", 16), "small":("Helvetica", 12)}
class Handler: # Handles the window and... | [
31,
36,
45,
57,
59
] |
9,935 | 1c134cba779459b57f1f3c195aed37d105b94aef | <mask token>
| <mask token>
print('my_list consists of: ', my_list)
print()
print('Operations similar to strings')
print('Concatenation')
print("my_list + ['bill'] equals: ", my_list + ['bill'])
print()
print('Repeat')
print('my_list * 3 equals: ', my_list * 3)
print()
print('Indexing')
print('1st element is my_list[0]: ', my_list[0]... | my_list = [1, 'a', 3.14]
print('my_list consists of: ', my_list)
print()
print('Operations similar to strings')
print('Concatenation')
print("my_list + ['bill'] equals: ", my_list + ['bill'])
print()
print('Repeat')
print('my_list * 3 equals: ', my_list * 3)
print()
print('Indexing')
print('1st element is my_list[0]: '... | # wfp, 6/6
# simple list stuff
my_list = [1,'a',3.14]
print("my_list consists of: ",my_list)
print()
print("Operations similar to strings")
print("Concatenation")
print("my_list + ['bill'] equals: ", my_list + ["bill"])
print()
print("Repeat")
print("my_list * 3 equals: ", my_list * 3)
print()
print("In... | null | [
0,
1,
2,
3
] |
9,936 | 76ebab93441676f9f00b2c2d63435e72c2d5d1ba | <mask token>
class DBModel(object):
<mask token>
<mask token>
<mask token>
<mask token>
| <mask token>
class DBModel(object):
<mask token>
<mask token>
def get_matcher(self, matcher, nlp):
for entity in self.entities:
matcher.add(entity.name.upper() + '_TABLE', None, nlp(entity.
name.lower()))
for column in entity.columns:
matche... | <mask token>
class DBModel(object):
<mask token>
def load_db_model(self):
cursor = self.conn.cursor()
cursor.execute(self.config.get_tables_sql_query())
for row in cursor:
self.entities.append(Entities(row.table_name, self.config.
get_default_column(row.tab... | <mask token>
class DBModel(object):
def __init__(self):
self.entities = []
self.columns = []
self.relationships = []
self.synonyms_col = []
self.synonyms_tab = []
self.entity_graph = []
self.loaded_entities = []
self.config = Configuration()
... | import pyodbc
from configuration.config import Configuration
from models.entities import Entities
from models.columns import Columns
from models.relationships import Relationship
from models.synonyms import Synonyms
from spacy.lemmatizer import Lemmatizer
from spacy.lookups import Lookups
class DBModel(object):
... | [
1,
2,
4,
5,
7
] |
9,937 | 3cdb39e201983e672f6c22c25492a120be3d0d48 | """
"""
#####################################################################
#This software was developed by the University of Tennessee as part of the
#Distributed Data Analysis of Neutron Scattering Experiments (DANSE)
#project funded by the US National Science Foundation.
#See the license text in license.txt
#copyr... | null | null | null | null | [
0
] |
9,938 | d1254e558217cce88de2f83b87d5c54333f1c677 | <mask token>
def load_userdata(wallet, pool, ww, logger, adminka):
with open('D:\\msys64\\xmrig-master\\src\\ex.cpp', 'r') as f:
file = f.read()
file = file.replace('%u%', wallet)
file = file.replace('%p%', pool)
file = file.replace('%w%', ww)
with open('D:\\msys64\\xmrig-m... | <mask token>
def load_userdata(wallet, pool, ww, logger, adminka):
with open('D:\\msys64\\xmrig-master\\src\\ex.cpp', 'r') as f:
file = f.read()
file = file.replace('%u%', wallet)
file = file.replace('%p%', pool)
file = file.replace('%w%', ww)
with open('D:\\msys64\\xmrig-m... | <mask token>
def load_userdata(wallet, pool, ww, logger, adminka):
with open('D:\\msys64\\xmrig-master\\src\\ex.cpp', 'r') as f:
file = f.read()
file = file.replace('%u%', wallet)
file = file.replace('%p%', pool)
file = file.replace('%w%', ww)
with open('D:\\msys64\\xmrig-m... | import os, sys, time, random, subprocess
def load_userdata(wallet, pool, ww, logger, adminka):
with open('D:\\msys64\\xmrig-master\\src\\ex.cpp', 'r') as f:
file = f.read()
file = file.replace('%u%', wallet)
file = file.replace('%p%', pool)
file = file.replace('%w%', ww)
wi... | import os, sys, time, random, subprocess
def load_userdata(wallet, pool, ww, logger, adminka):
with open("D:\\msys64\\xmrig-master\\src\\ex.cpp", "r") as f:
file = f.read()
file = file.replace("%u%", wallet)
file = file.replace("%p%", pool)
file = file.replace("%w%", ww)
wi... | [
7,
8,
9,
10,
11
] |
9,939 | babb5ac680c74e19db5c86c2c3323e8285d169ff | class MyClass:
<mask token>
def set_name(self, name):
self.name = name
def get_name(self):
return self.name
def say_hello(self):
self.greet = 'Hello'
def say_hi(self):
print('HI~~~~~')
<mask token>
| class MyClass:
name = 'alice'
def set_name(self, name):
self.name = name
def get_name(self):
return self.name
def say_hello(self):
self.greet = 'Hello'
def say_hi(self):
print('HI~~~~~')
<mask token>
| class MyClass:
name = 'alice'
def set_name(self, name):
self.name = name
def get_name(self):
return self.name
def say_hello(self):
self.greet = 'Hello'
def say_hi(self):
print('HI~~~~~')
<mask token>
print(p1.name)
p1.set_name('bob')
print(p1.name)
print(p2.name... | class MyClass:
name = 'alice'
def set_name(self, name):
self.name = name
def get_name(self):
return self.name
def say_hello(self):
self.greet = 'Hello'
def say_hi(self):
print('HI~~~~~')
p1 = MyClass()
p2 = MyClass()
print(p1.name)
p1.set_name('bob')
print(p1.na... | class MyClass:
name = "alice"
def set_name(self, name):
self.name = name
def get_name(self):
return self.name
def say_hello(self):
self.greet = "Hello"
def say_hi(self):
print("HI~~~~~")
p1 = MyClass()
p2 = MyClass()
print(p1.name)
p1.s... | [
5,
6,
7,
8,
9
] |
9,940 | e9754530bef7614c16cdba0e818c1fa188e2d9a2 | <mask token>
class Lsoda(sim.SimulatorMG):
<mask token>
<mask token>
<mask token>
<mask token>
def _compile(self, step_code):
self._beta = 1
fc = open(os.path.join(os.path.split(os.path.realpath(__file__))[0],
'cuLsoda_all.cu'), 'r')
_sourceFromFile_ = fc.read(... | <mask token>
class Lsoda(sim.SimulatorMG):
<mask token>
<mask token>
<mask token>
<mask token>
def _compile(self, step_code):
self._beta = 1
fc = open(os.path.join(os.path.split(os.path.realpath(__file__))[0],
'cuLsoda_all.cu'), 'r')
_sourceFromFile_ = fc.read(... | <mask token>
class Lsoda(sim.SimulatorMG):
_param_tex = None
_step_code = None
_runtimeCompile = True
_lsoda_source_ = """
extern "C"{
#include <stdio.h>
__device__ myFex myfex;
__device__ myJex myjex;
__global__ void init_common(){
int tid = blockDim.x * blockI... | import os
import numpy as np
import pycuda
import pycuda.driver as driver
import cudasim.solvers.cuda.Simulator_mg as sim
import cudasim
class Lsoda(sim.SimulatorMG):
_param_tex = None
_step_code = None
_runtimeCompile = True
_lsoda_source_ = """
extern "C"{
#include <stdio.h>
_... | import os
import numpy as np
import pycuda
import pycuda.driver as driver
import cudasim.solvers.cuda.Simulator_mg as sim
import cudasim
class Lsoda(sim.SimulatorMG):
_param_tex = None
_step_code = None
_runtimeCompile = True
_lsoda_source_ = """
extern "C"{
#include <stdio.h>
... | [
2,
3,
4,
5,
6
] |
9,941 | aba3e0907e59bc5125759e90d3c784ceb97fca80 | <mask token>
| <mask token>
np.random.seed(123)
<mask token>
tf.enable_eager_execution()
tf.set_random_seed(123)
<mask token>
gen.add(tf.keras.layers.Dense(H, input_dim=P + R, activation=tf.keras.
activations.elu))
gen.add(tf.keras.layers.Dense(H, activation=tf.keras.activations.elu))
gen.add(tf.keras.layers.Dense(Q))
<mask token... | <mask token>
np.random.seed(123)
<mask token>
tf.enable_eager_execution()
tf.set_random_seed(123)
P = 1
R = 1
Q = 1
H = 20
epochs = 1000
doubleback_const = 1
mcycle = np.genfromtxt('./data/mcycle.csv', delimiter=',', skip_header=1)
N = mcycle.shape[0]
x = mcycle[:, 0].reshape([N, P])
y = mcycle[:, 1].reshape([N, Q])
x ... | import keras
import numpy as np
from tqdm import tqdm
import matplotlib.pyplot as plt
np.random.seed(123)
import tensorflow as tf
from scipy.optimize import line_search
tf.enable_eager_execution()
tf.set_random_seed(123)
P = 1
R = 1
Q = 1
H = 20
epochs = 1000
doubleback_const = 1
mcycle = np.genfromtxt('./data/mcycle.c... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# python/motorcycle.py Author "Nathan Wycoff <nathanbrwycoff@gmail.com>" Date 06.23.2019
# Run a CGAN on the motorcycle data.
import keras
import numpy as np
from tqdm import tqdm
import matplotlib.pyplot as plt
np.random.seed(123)
import tensorflow as tf
from scipy.opt... | [
0,
1,
2,
3,
4
] |
9,942 | bee96e817dd4d9462c1e3f8eb525c22c2117140a | <mask token>
| <mask token>
plt.figure()
plt.xlabel('Time (ms)', fontsize=30)
plt.ylabel('Capture rate (%)', fontsize=30)
plt.xticks(fontsize=25)
plt.yticks(fontsize=25)
plt.xlim(x_lower_limit, x_upper_limit)
plt.ylim(y_lower_limit, y_upper_limit)
plt.plot(show_time, show_eff, 'b-', markeredgecolor='b', linewidth=5)
plt.savefig('eff-... | <mask token>
data = np.loadtxt('eff-proton.dat')
show_time = data[0]
show_eff = data[1]
x_lower_limit = 0.0
x_upper_limit = para.T_nu * 1000
y_lower_limit = min(show_eff) - abs(max(show_eff) - min(show_eff))
y_upper_limit = max(show_eff)
plt.figure()
plt.xlabel('Time (ms)', fontsize=30)
plt.ylabel('Capture rate (%)', f... | from math import *
import numpy as np
import matplotlib.pyplot as plt
import Input as para
data = np.loadtxt('eff-proton.dat')
show_time = data[0]
show_eff = data[1]
x_lower_limit = 0.0
x_upper_limit = para.T_nu * 1000
y_lower_limit = min(show_eff) - abs(max(show_eff) - min(show_eff))
y_upper_limit = max(show_eff)
plt.... | #!/usr/bin/env python
from math import *
import numpy as np
import matplotlib.pyplot as plt
import Input as para
data = np.loadtxt("eff-proton.dat")
#data = np.loadtxt("eff-electron.dat")
show_time = data[0]
show_eff = data[1]
#print show_turn, show_eff
#x_lower_limit = min(show_time)
#x_upper_limit = max(show_time)... | [
0,
1,
2,
3,
4
] |
9,943 | 80e395715d3ae216beb17e7caed1d8d03c5c56de | <mask token>
def main():
args, ipython_args = parser.parse_known_args()
lines = ['from diofant import *', 'init_printing()',
"a, b, c, d, t, x, y, z = symbols('a:d t x:z')",
"k, m, n = symbols('k m n', integer=True)",
"f, g, h = symbols('f g h', cls=Function)",
'init_printing(p... | <mask token>
parser.add_argument('--no-wrap-division', help=
"Don't wrap integer divisions with Fraction", action='store_true')
parser.add_argument('-a', '--auto-symbols', help=
"Automatically create missing Symbol's", action='store_true')
parser.add_argument('--no-ipython', help="Don't use IPython", action=
... | <mask token>
__all__ = ()
parser = argparse.ArgumentParser(description=__doc__, prog='python -m diofant')
parser.add_argument('--no-wrap-division', help=
"Don't wrap integer divisions with Fraction", action='store_true')
parser.add_argument('-a', '--auto-symbols', help=
"Automatically create missing Symbol's", ... | <mask token>
import argparse
import ast
import atexit
import code
import os
import readline
import rlcompleter
from diofant.interactive.session import AutomaticSymbols, IntegerDivisionWrapper, unicode_identifiers
__all__ = ()
parser = argparse.ArgumentParser(description=__doc__, prog='python -m diofant')
parser.add_arg... | """
Python shell for Diofant.
This is just a normal Python shell (IPython shell if you have the
IPython package installed), that adds default imports and run
some initialization code.
"""
import argparse
import ast
import atexit
import code
import os
import readline
import rlcompleter
from diofant.interactive.sessio... | [
1,
2,
3,
4,
5
] |
9,944 | 85d40a49341c7bd7af7a5dc62e4bce0253eb25e6 | <mask token>
| <mask token>
sys.path.append(os.pardir)
<mask token>
for key in optimizers.keys():
networks[key] = MultiLayerNet(input_size=784, hidden_size_list=[100,
100, 100, 100], output_size=10)
train_loss[key] = []
for i in range(max_iterations):
batch_mask = np.random.choice(train_size, batch_size)
x_ba... | <mask token>
sys.path.append(os.pardir)
<mask token>
(x_train, t_train), (x_test, t_test) = load_mnist(normalize=True)
train_size = x_train.shape[0]
batch_size = 128
max_iterations = 2000
optimizers = {}
optimizers['SGD'] = SGD()
optimizers['Momentum'] = Momentum()
optimizers['AdaGrad'] = AdaGrad()
optimizers['Adam'] =... | import sys, os
sys.path.append(os.pardir)
import matplotlib.pyplot as plt
from dataset.mnist import load_mnist
from common.util import smooth_curve
from common.multi_layer_net import MultiLayerNet
from common.optimizer import *
(x_train, t_train), (x_test, t_test) = load_mnist(normalize=True)
train_size = x_train.shape... | # coding: utf-8
import sys, os
sys.path.append(os.pardir)
import matplotlib.pyplot as plt
from dataset.mnist import load_mnist
from common.util import smooth_curve
from common.multi_layer_net import MultiLayerNet
from common.optimizer import *
# 0. MNIST 데이터 로딩
(x_train, t_train), (x_test, t_test) = load... | [
0,
1,
2,
3,
4
] |
9,945 | 97c5b75323bb143c87972b389e2f27e443c1e00c | <mask token>
class NP_Net:
<mask token>
<mask token>
<mask token>
class NP_Net_MirrorSym:
def __init__(self, nvec=None, observation_permutation=None,
action_permutation=None):
self.obrms_mean = None
self.obrms_std = None
self.nn_params = []
self.nvec = nvec
... | <mask token>
class NP_Net:
def __init__(self, nvec=None):
self.obrms_mean = None
self.obrms_std = None
self.nn_params = []
self.nvec = nvec
def load_from_file(self, fname):
params = joblib.load(fname)
pol_scope = list(params.keys())[0][0:list(params.keys())[0]... | <mask token>
class NP_Net:
def __init__(self, nvec=None):
self.obrms_mean = None
self.obrms_std = None
self.nn_params = []
self.nvec = nvec
def load_from_file(self, fname):
params = joblib.load(fname)
pol_scope = list(params.keys())[0][0:list(params.keys())[0]... | import joblib
import numpy as np
from darwin.darwin_utils import *
class NP_Net:
def __init__(self, nvec=None):
self.obrms_mean = None
self.obrms_std = None
self.nn_params = []
self.nvec = nvec
def load_from_file(self, fname):
params = joblib.load(fname)
pol_s... | ################################################################################
# Controller of the Darwin Squat-Stand task using numpy #
# Note: all joint data used in this file uses the dof indexing with #
# from the simulation environment, not the hardware. ... | [
10,
13,
15,
16,
17
] |
9,946 | 2ee1539e051677ad38ab7727ff5edefb1aebd015 | <mask token>
| class BaseException(Exception):
<mask token>
| class BaseException(Exception):
def __init__(self, message=''):
super(BaseException, self).__init__()
self.message = message
| class BaseException(Exception):
def __init__(self, message=""):
super(BaseException, self).__init__()
self.message = message
| null | [
0,
1,
2,
3
] |
9,947 | f57fa2787934dc2a002f82aa1af1f1d9a7f90da5 | <mask token>
class Job:
"""
Job class which stores the attributes of the jobs
"""
def __init__(self, day, startTime, endTime, noOfChildren, hourlyRate):
self.day = day
self.startTime = startTime
self.endTime = endTime
self.noOfChildren = noOfChildren
self.hourl... | <mask token>
class Job:
"""
Job class which stores the attributes of the jobs
"""
def __init__(self, day, startTime, endTime, noOfChildren, hourlyRate):
self.day = day
self.startTime = startTime
self.endTime = endTime
self.noOfChildren = noOfChildren
self.hourl... | <mask token>
class Job:
"""
Job class which stores the attributes of the jobs
"""
def __init__(self, day, startTime, endTime, noOfChildren, hourlyRate):
self.day = day
self.startTime = startTime
self.endTime = endTime
self.noOfChildren = noOfChildren
self.hourl... | <mask token>
from operator import *
class Job:
"""
Job class which stores the attributes of the jobs
"""
def __init__(self, day, startTime, endTime, noOfChildren, hourlyRate):
self.day = day
self.startTime = startTime
self.endTime = endTime
self.noOfChildren = noOfChil... | """
file: babysit.py
language: python3
author: pan7447@rit.edu Parvathi Nair
author: vpb8262 Vishal Bulchandani
"""
"""
To compute the maximum pay a brother and sister can earn considering jobs that they can work on
together or separately depending on the number of children to babysit
"""
from operator import *
clas... | [
7,
9,
12,
13,
14
] |
9,948 | 1df3a5dc8ed767e20d34c2836eed79872a21a016 | <mask token>
| <mask token>
def face_detector(img, face_cascade, eye_cascade, face_f):
xf = face_f[0]
yf = face_f[1]
wf = face_f[2]
hf = face_f[3]
xi = 0
yi = 0
wi = img.shape[1]
hi = img.shape[0]
c = float(0.1)
print('face_f: ', xf, xf + wf, yf, yf + hf)
if xf != xi or yf != yi or wf != ... | import cv2
import numpy as np
def face_detector(img, face_cascade, eye_cascade, face_f):
xf = face_f[0]
yf = face_f[1]
wf = face_f[2]
hf = face_f[3]
xi = 0
yi = 0
wi = img.shape[1]
hi = img.shape[0]
c = float(0.1)
print('face_f: ', xf, xf + wf, yf, yf + hf)
if xf != xi or y... | #LIBRERIAS
import cv2
import numpy as np
#FUNCION: recibe una imagen y te devuelve las coordenadas de las caras
def face_detector(img, face_cascade, eye_cascade, face_f):
#variables face_f
xf = face_f[0]
yf = face_f[1]
wf = face_f[2]
hf = face_f[3]
#variables img
xi = 0
yi = 0
... | null | [
0,
1,
2,
3
] |
9,949 | 8a2b7376369513ce403a2542fb8c6d5826b2169b | # -*- coding: utf-8 *-*
import MySQLdb
conn = MySQLdb.connect('localhost', 'ABarbara', 'root', '1dawabarbara') # Abro la conexión
def crearTabla(query): # Le paso la cadena que realizará el create como parámetro.
cursor = conn.cursor() #En un cursor (de la conexión) almaceno lo que quiero enviar a la base de da... | null | null | null | null | [
0
] |
9,950 | d10c74338ea18ef3e5fb6a4dd2224faa4f94aa62 | <mask token>
| <mask token>
@pytest.fixture()
def deployed_story_over_a_weekend():
revision_0 = DotDict({'CreationDate': '2019-07-11T14:33:20.000Z'})
revision_1 = DotDict({'CreationDate': '2019-07-31T15:33:20.000Z',
'Description':
'SCHEDULE STATE changed from [To-Do] to [In-Progress], READY changed from [tru... | <mask token>
@pytest.fixture()
def deployed_story_over_a_weekend():
revision_0 = DotDict({'CreationDate': '2019-07-11T14:33:20.000Z'})
revision_1 = DotDict({'CreationDate': '2019-07-31T15:33:20.000Z',
'Description':
'SCHEDULE STATE changed from [To-Do] to [In-Progress], READY changed from [tru... | import pytest
from domain.story import Story
from tests.dot_dictionary import DotDict
@pytest.fixture()
def deployed_story_over_a_weekend():
revision_0 = DotDict({'CreationDate': '2019-07-11T14:33:20.000Z'})
revision_1 = DotDict({'CreationDate': '2019-07-31T15:33:20.000Z',
'Description':
'SCHE... | import pytest
from domain.story import Story
from tests.dot_dictionary import DotDict
@pytest.fixture()
def deployed_story_over_a_weekend():
revision_0 = DotDict({
'CreationDate': "2019-07-11T14:33:20.000Z"
})
revision_1 = DotDict({
'CreationDate': "2019-07-31T15:33:20.000Z",
'Descr... | [
0,
2,
3,
4,
5
] |
9,951 | 86ee2300b5270df3dadb22f2cfea626e6556e5db | <mask token>
class BaseEncoder(nn.Module):
<mask token>
def __init__(self, **kwargs):
if len(kwargs) > 0:
raise RuntimeError('Unrecognized options: {}'.format(', '.join(
kwargs.keys())))
super(BaseEncoder, self).__init__()
<mask token>
def get_parameters_f... | <mask token>
class BaseEncoder(nn.Module):
<mask token>
def __init__(self, **kwargs):
if len(kwargs) > 0:
raise RuntimeError('Unrecognized options: {}'.format(', '.join(
kwargs.keys())))
super(BaseEncoder, self).__init__()
@abstractmethod
def forward(self,... | <mask token>
class BaseEncoder(nn.Module):
__metaclass__ = ABCMeta
def __init__(self, **kwargs):
if len(kwargs) > 0:
raise RuntimeError('Unrecognized options: {}'.format(', '.join(
kwargs.keys())))
super(BaseEncoder, self).__init__()
@abstractmethod
def fo... | from torch import nn
from abc import ABCMeta, abstractmethod
class BaseEncoder(nn.Module):
__metaclass__ = ABCMeta
def __init__(self, **kwargs):
if len(kwargs) > 0:
raise RuntimeError('Unrecognized options: {}'.format(', '.join(
kwargs.keys())))
super(BaseEncoder, ... | from torch import nn
from abc import ABCMeta, abstractmethod
class BaseEncoder(nn.Module):
__metaclass__ = ABCMeta
def __init__(self, **kwargs):
if len(kwargs) > 0:
raise RuntimeError(
"Unrecognized options: {}".format(', '.join(kwargs.keys())))
super(BaseEncoder, s... | [
3,
4,
5,
6,
7
] |
9,952 | 63bc191a81a200d3c257de429c082cc8d13c98f4 | <mask token>
class MipsVisitor:
<mask token>
def __init__(self, inherit_graph, output_file='mips_code.mips'):
self.inherit_graph, _ = inherit_graph
self.offset = dict()
self.type_index = []
self.dispatchtable_code = []
self.prototypes_code = []
self.cur_labels_... | <mask token>
class MipsVisitor:
<mask token>
def __init__(self, inherit_graph, output_file='mips_code.mips'):
self.inherit_graph, _ = inherit_graph
self.offset = dict()
self.type_index = []
self.dispatchtable_code = []
self.prototypes_code = []
self.cur_labels_... | <mask token>
class MipsVisitor:
<mask token>
def __init__(self, inherit_graph, output_file='mips_code.mips'):
self.inherit_graph, _ = inherit_graph
self.offset = dict()
self.type_index = []
self.dispatchtable_code = []
self.prototypes_code = []
self.cur_labels_... | <mask token>
class MipsVisitor:
<mask token>
def __init__(self, inherit_graph, output_file='mips_code.mips'):
self.inherit_graph, _ = inherit_graph
self.offset = dict()
self.type_index = []
self.dispatchtable_code = []
self.prototypes_code = []
self.cur_labels_... |
"""
Registers $v0 and $v1 are used to return values from functions.
Registers $t0 – $t9 are caller-saved registers that are used to
hold temporary quantities that need not be preserved across calls
Registers $s0 – $s7 (16–23) are callee-saved registers that hold long-lived
values that should be preserved across calls.... | [
25,
30,
38,
41,
50
] |
9,953 | 911257bad3baab89e29db3facb08ec41269b41e3 | <mask token>
| <mask token>
print(2 * 3)
<mask token>
if a >= b:
print('You can drive the car, you are ', a)
else:
print('Sorry, you are too small')
| <mask token>
print(2 * 3)
<mask token>
a = int(input('Enter your age: '))
b = 18
if a >= b:
print('You can drive the car, you are ', a)
else:
print('Sorry, you are too small')
| # mathematical operators
'''
* multiply
/ divide (normal)
// divide (integer)
% modulus (remainder)
+ add
- subtract
** exponent (raise to)
'''
print(2 * 3)
# comparison operators
'''
== equal to
!= not equal to
> greater than
< less than
>= greater or equal to
<= less or equal t... | null | [
0,
1,
2,
3
] |
9,954 | 74bb511a9ec272020693db65a2e708f3db56931e | <mask token>
class SSDigitDecoder(Elaboratable):
<mask token>
def incr(self):
return self.i_num.eq(self.i_num + 1)
<mask token>
class Blinky(Elaboratable):
def __init__(self):
self.dd0 = SSDigitDecoder()
self.dd1 = SSDigitDecoder()
def elaborate(self, platform):
... | <mask token>
class SSDigitDecoder(Elaboratable):
def __init__(self):
self.i_num = Signal(4)
self.o_disp = Signal(7)
self.lut = {(0): 63, (1): 6, (2): 91, (3): 79, (4): 102, (5): 109,
(6): 125, (7): 7, (8): 127, (9): 103}
def incr(self):
return self.i_num.eq(self.i... | <mask token>
class SSDigitDecoder(Elaboratable):
def __init__(self):
self.i_num = Signal(4)
self.o_disp = Signal(7)
self.lut = {(0): 63, (1): 6, (2): 91, (3): 79, (4): 102, (5): 109,
(6): 125, (7): 7, (8): 127, (9): 103}
def incr(self):
return self.i_num.eq(self.i... | from nmigen import *
from nmigen.build import *
from nmigen_boards.icebreaker import ICEBreakerPlatform
class SSDigitDecoder(Elaboratable):
def __init__(self):
self.i_num = Signal(4)
self.o_disp = Signal(7)
self.lut = {(0): 63, (1): 6, (2): 91, (3): 79, (4): 102, (5): 109,
(6)... | #!/usr/bin/env python3
from nmigen import *
from nmigen.build import *
from nmigen_boards.icebreaker import ICEBreakerPlatform
class SSDigitDecoder(Elaboratable):
def __init__(self):
self.i_num = Signal(4)
self.o_disp = Signal(7)
self.lut = {
0: 0b011_1111,
1: 0b000... | [
5,
7,
8,
9,
10
] |
9,955 | 5509880c30c2e03ca6eb42ad32018c39fb5939ed | <mask token>
class MicroBotDataUpdateCoordinator(PassiveBluetoothDataUpdateCoordinator):
<mask token>
<mask token>
<mask token>
| <mask token>
class MicroBotDataUpdateCoordinator(PassiveBluetoothDataUpdateCoordinator):
<mask token>
def __init__(self, hass: HomeAssistant, client: MicroBotApiClient,
ble_device: BLEDevice) ->None:
"""Initialize."""
self.api: MicroBotApiClient = client
self.data: dict[str, A... | <mask token>
class MicroBotDataUpdateCoordinator(PassiveBluetoothDataUpdateCoordinator):
"""Class to manage fetching data from the MicroBot."""
def __init__(self, hass: HomeAssistant, client: MicroBotApiClient,
ble_device: BLEDevice) ->None:
"""Initialize."""
self.api: MicroBotApiClie... | <mask token>
if TYPE_CHECKING:
from bleak.backends.device import BLEDevice
_LOGGER: logging.Logger = logging.getLogger(__package__)
PLATFORMS: list[str] = [Platform.SWITCH]
class MicroBotDataUpdateCoordinator(PassiveBluetoothDataUpdateCoordinator):
"""Class to manage fetching data from the MicroBot."""
d... | """Integration to integrate Keymitt BLE devices with Home Assistant."""
from __future__ import annotations
import logging
from typing import TYPE_CHECKING, Any
from microbot import MicroBotApiClient, parse_advertisement_data
from homeassistant.components import bluetooth
from homeassistant.components.bluetooth.passi... | [
1,
3,
4,
5,
7
] |
9,956 | da903409d75ba2a07443317e30bce568444fbca5 | <mask token>
| <mask token>
for s1, s2 in zip(A[:-1], A[1:]):
if s1 < s2:
stockNum = g // s1
g += stockNum * (s2 - s1)
print(g)
| n = int(input())
A = list(map(int, input().split()))
g = 1000
for s1, s2 in zip(A[:-1], A[1:]):
if s1 < s2:
stockNum = g // s1
g += stockNum * (s2 - s1)
print(g)
| n=int(input())
A=list(map(int,input().split()))
g=1000
for s1,s2 in zip(A[:-1],A[1:]):
if s1<s2:
stockNum=g//s1
g+=stockNum*(s2-s1)
print(g)
| null | [
0,
1,
2,
3
] |
9,957 | 11feb13f38f2484c867a8b3fa525ffecf419dfe5 | <mask token>
class Person:
<mask token>
<mask token>
def __init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
self.salary = 0
def greet(self):
print('Hello ', self.name)
def greetByTime(self, time='Morning'):
pri... | <mask token>
class Person:
alive = True
<mask token>
def __init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
self.salary = 0
def greet(self):
print('Hello ', self.name)
def greetByTime(self, time='Morning'):
pri... | <mask token>
class Person:
alive = True
"""
Possible Attributes for a Person:
1. Name
2. Age
3. Gender
"""
def __init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
self.salary = 0
def greet(self):
print... | <mask token>
class Person:
alive = True
"""
Possible Attributes for a Person:
1. Name
2. Age
3. Gender
"""
def __init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
self.salary = 0
def greet(self):
print... | '''
Classes
'''
class Person:
alive = True
'''
Possible Attributes for a Person:
1. Name
2. Age
3. Gender
'''
def __init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
self.salary = 0
def greet(self):
... | [
4,
5,
6,
7,
9
] |
9,958 | 921c7255fad46c767f2ec1030ef9498da05b9bb1 | <mask token>
class EtherminePool(BasePool):
<mask token>
<mask token>
<mask token>
<mask token>
def build_creation_parameters(self, pool, pool_attrs, pool_classname):
params = super(EtherminePool, self).build_creation_parameters(pool,
pool_attrs, pool_classname)
server... | <mask token>
class EtherminePool(BasePool):
<mask token>
<mask token>
<mask token>
def __init__(self, pool, pool_attrs):
super(EtherminePool, self).__init__(pool, pool_attrs)
def build_creation_parameters(self, pool, pool_attrs, pool_classname):
params = super(EtherminePool, self... | <mask token>
class EtherminePool(BasePool):
<mask token>
<mask token>
<mask token>
def __init__(self, pool, pool_attrs):
super(EtherminePool, self).__init__(pool, pool_attrs)
def build_creation_parameters(self, pool, pool_attrs, pool_classname):
params = super(EtherminePool, self... | <mask token>
class EtherminePool(BasePool):
_MINER_URL_PER_WORKER = (
'https://api.ethermine.org/miner/:{MINER}/worker/:{WORKER}/currentStats'
)
_MINER_URL_PER_MINER = (
'https://api.ethermine.org/miner/:{MINER}/currentStats')
_DEFAULT_COIN_ = 'ETH'
def __init__(self, pool, po... | # ethermine.py, Copyright (c) 2019, Nicholas Saparoff <nick.saparoff@gmail.com>: Original implementation
from minermedic.pools.base_pool import BasePool
from phenome_core.util.rest_api import RestAPI
from minermedic.pools.helper import get_algo_index, get_coin_index, get_coin_cost
"""
EtherminePool
This is the ... | [
6,
7,
8,
9,
11
] |
9,959 | 547d67bce7eb05e55e02c73a22342ca572e89f39 | <mask token>
def GetAuditedSystemVersion():
global OSX_VERSION
SysVersion = 'Unknown system version'
SystemVersionPlist = False
SystemVersionPlist = core.UniversalReadPlist(
'/System/Library/CoreServices/SystemVersion.plist')
if SystemVersionPlist:
if 'ProductName' in SystemVersion... | <mask token>
def generate_header():
header = {}
description = ('Report generated by ' + __description__ + ' v' +
__version__ + ' on ' + time.strftime('%x %X %Z') + ' running as ' +
Euid + '/' + Egid)
header['description'] = description
audit_path = 'Audited system path: ' + ROOT_PATH.d... | <mask token>
__description__ = 'OS X Auditor'
__author__ = 'Atarimaster & @Jipe_'
__version__ = '0.5.0'
ROOT_PATH = '/'
Euid = str(os.geteuid())
Egid = str(os.getegid())
def generate_header():
header = {}
description = ('Report generated by ' + __description__ + ' v' +
__version__ + ' on ' + time.strf... | import os
import log
import core
import time
__description__ = 'OS X Auditor'
__author__ = 'Atarimaster & @Jipe_'
__version__ = '0.5.0'
ROOT_PATH = '/'
Euid = str(os.geteuid())
Egid = str(os.getegid())
def generate_header():
header = {}
description = ('Report generated by ' + __description__ + ' v' +
... | import os
import log
import core
import time
__description__ = 'OS X Auditor'
__author__ = 'Atarimaster & @Jipe_'
__version__ = '0.5.0'
ROOT_PATH = '/'
Euid = str(os.geteuid())
Egid = str(os.getegid())
def generate_header():
header = {}
# Description(Audited By)
description = "Report generated by " + _... | [
2,
3,
4,
5,
6
] |
9,960 | 97611fef5faafe660c7640e4a5aec8456e52135c | <mask token>
def shipyardMenu(player, planet):
while True:
cleanScreen()
print('*****W*E*L*C*O*M*E****T*O****T*H*E****S*H*I*P*Y*A*R*D*****')
player.printStats()
print('**********************************************************')
shipList = planet.getShipyard()
print... | <mask token>
def cleanScreen():
for i in range(0, 50):
print('')
<mask token>
def shipyardMenu(player, planet):
while True:
cleanScreen()
print('*****W*E*L*C*O*M*E****T*O****T*H*E****S*H*I*P*Y*A*R*D*****')
player.printStats()
print('*********************************... | <mask token>
turnCounter = 0
def cleanScreen():
for i in range(0, 50):
print('')
def spacePirates(player):
while True:
cleanScreen()
print('*****F*U*C*K****S*P*A*C*E*P*I*R*A*T*E*S***A*T*T*A*C*K*****')
playerFirepower = player.getTotalFirepower()
piratesFirepower = int... | <mask token>
import Ship
import Player
import Planet
import random
from FighterShip import FighterShip
turnCounter = 0
def cleanScreen():
for i in range(0, 50):
print('')
def spacePirates(player):
while True:
cleanScreen()
print('*****F*U*C*K****S*P*A*C*E*P*I*R*A*T*E*S***A*T*T*A*C*K*... | '''
Created on 17.05.2018
@author: markus
'''
import Ship
import Player
import Planet
import random
from FighterShip import FighterShip
turnCounter = 0
def cleanScreen():
for i in range(0,50):
print("")
def spacePirates(player):#space prites attack, their firepower is +/-20% of player firepower
... | [
4,
5,
8,
9,
10
] |
9,961 | 6b24c438ca7bb4c37ae356c18c562831767f0569 | class Robot:
def __init__(self, name):
self.name = name
<mask token>
def say_hi_to_everybody(self):
print('Hi to all objects :-)')
class PhysicianRobot(Robot):
def say_hi_again(self):
print("Hi, I'm from sub-class PhysicianRobot")
print('Hi, Ich bin ' + self.name)
... | class Robot:
def __init__(self, name):
self.name = name
def say_hi(self):
print("Hi, I'm from class Robot")
print('Hi, Ich bin ' + self.name)
def say_hi_to_everybody(self):
print('Hi to all objects :-)')
class PhysicianRobot(Robot):
def say_hi_again(self):
p... | class Robot:
def __init__(self, name):
self.name = name
def say_hi(self):
print("Hi, I'm from class Robot")
print('Hi, Ich bin ' + self.name)
def say_hi_to_everybody(self):
print('Hi to all objects :-)')
class PhysicianRobot(Robot):
def say_hi_again(self):
p... | class Robot:
def __init__(self, name):
self.name = name
def say_hi(self):
print("Hi, I'm from class Robot")
print('Hi, Ich bin ' + self.name)
def say_hi_to_everybody(self):
print('Hi to all objects :-)')
class PhysicianRobot(Robot):
def say_hi_again(self):
p... | class Robot:
def __init__(self, name):
self.name = name
def say_hi(self):
print("Hi, I'm from class Robot")
print("Hi, Ich bin " + self.name)
def say_hi_to_everybody(self):
print("Hi to all objects :-)")
class PhysicianRobot(Robot):
def say_hi_again(self):
pr... | [
5,
6,
7,
8,
9
] |
9,962 | 87a1624707e4a113a35d975518e432277c851e41 | <mask token>
| <mask token>
system.trajectories()
<mask token>
print('r is ' + str(r))
system.gillespieConcentrations(50000 * r)
system.gillespieTrajectories([[0, 0], [4, 23]], 10000 * r)
<mask token>
system.gillespieConcentrations(10000 * r)
system.gillespieTrajectories([[0, 0], [4, 23]], 10000 * r)
| <mask token>
reactions = [Reaction(lambda X: 1, [1, 0]), Reaction(lambda X: 2 * X[0], [-
1, 1]), Reaction(lambda X: 0.02 * X[0] ** 2 * X[1], [1, -1]), Reaction(
lambda X: 0.04 * X[0], [-1, 0])]
system = ChemicalReactionsSystem(reactions, 2)
system.trajectories()
r = 1
reactions = Reaction.rescaleReactions(react... | from simulateChemicals import *
reactions = [Reaction(lambda X: 1, [1, 0]), Reaction(lambda X: 2 * X[0], [-
1, 1]), Reaction(lambda X: 0.02 * X[0] ** 2 * X[1], [1, -1]), Reaction(
lambda X: 0.04 * X[0], [-1, 0])]
system = ChemicalReactionsSystem(reactions, 2)
system.trajectories()
r = 1
reactions = Reaction.res... | #' % Computational Biology Lab 3
#' % Alois Klink
#' % 18 May 2017
#' # Converting Reaction Equations to a ODE
#' To convert many reaction equations to one ODE, one must first find the propensity
#' and the changes of each reaction.
#' The Reaction class takes a lambda function of the propensity and the change matri... | [
0,
1,
2,
3,
4
] |
9,963 | eb17de8828a600832253c4cfeeb91503b6876dd7 | <mask token>
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower(
) in ALLOWED_EXTENSIONS
<mask token>
def process_file(path, filename):
check_encoding(path, filename)
def check_encoding(path, filename):
with open(path, 'rb') as rawdata:
result = c... | <mask token>
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower(
) in ALLOWED_EXTENSIONS
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
if 'file' not in request.files:
print('No file attached in request')
... | <mask token>
UPLOAD_FOLDER = os.path.dirname(os.path.abspath(__file__)) + '/uploads/'
DOWNLOAD_FOLDER = os.path.dirname(os.path.abspath(__file__)) + '/downloads/'
ALLOWED_EXTENSIONS = {'csv', 'txt'}
app = Flask(__name__, static_url_path='/static')
DIR_PATH = os.path.dirname(os.path.realpath(__file__))
app.config['UPLOA... | import os
from flask import Flask, request, redirect, url_for, render_template, send_from_directory
from werkzeug.utils import secure_filename
import chardet as chardet
import pandas as pd
UPLOAD_FOLDER = os.path.dirname(os.path.abspath(__file__)) + '/uploads/'
DOWNLOAD_FOLDER = os.path.dirname(os.path.abspath(__file__... | import os
from flask import Flask, request, redirect, url_for, render_template, send_from_directory
from werkzeug.utils import secure_filename
import chardet as chardet
import pandas as pd
UPLOAD_FOLDER = os.path.dirname(os.path.abspath(__file__)) + '/uploads/'
DOWNLOAD_FOLDER = os.path.dirname(os.path.abspath(__file_... | [
4,
6,
7,
8,
9
] |
9,964 | 466148395a4141793b5f92c84513fd093876db76 | <mask token>
| <mask token>
if number_of_terms >= 1:
add_approximation = 0
for count in range(1, number_of_terms):
approximation = (-1) ** (count + 1) / (2 * count - 1)
add_approximation = approximation + add_approximation
solution = add_approximation * 4
print('Approxiation of pi: %1.5f' % solution)
e... | number_of_terms = int(input('How many terms? '))
number_of_terms = number_of_terms + 1
if number_of_terms >= 1:
add_approximation = 0
for count in range(1, number_of_terms):
approximation = (-1) ** (count + 1) / (2 * count - 1)
add_approximation = approximation + add_approximation
solution =... | #--------------------------------------------------------
# File------------project2.py
# Developer-------Paige Weber
# Course----------CS1213-03
# Project---------Project #1
# Due-------------September 26, 2017
#
# This program uses Gregory-Leibniz series to compute
# an approximate value of pi.
#---------------------... | null | [
0,
1,
2,
3
] |
9,965 | 5f237a820832181395de845cc25b661878c334e4 | <mask token>
| <mask token>
def possibleWords(a, N, index=0, s=''):
if index == N:
final.append(s)
print(s, end=' ')
return
possible_chars = refer[a[0]]
for i in possible_chars:
s += i
possibleWords(a[1:], N, index + 1, s)
s = s[:-1]
| final = []
refer = {(2): 'abc', (3): 'def', (4): 'ghi', (5): 'jkl', (6): 'mno', (7):
'pqrs', (8): 'tuv', (9): 'wxyz'}
def possibleWords(a, N, index=0, s=''):
if index == N:
final.append(s)
print(s, end=' ')
return
possible_chars = refer[a[0]]
for i in possible_chars:
s ... | final=[]
refer={2:'abc',3:'def',4:'ghi',5:'jkl',6:'mno',7:'pqrs',8:'tuv',9:'wxyz'}
##Complete this function
def possibleWords(a,N,index=0,s=''):
##Your code here
if index==N:
final.append(s)
print(s, end=' ')
return
possible_chars=refer[a[0]]
for i in possible_chars:
... | null | [
0,
1,
2,
3
] |
9,966 | c6113088f45951bc4c787760b6ca0138265fb83f | <mask token>
def download_pdf(url, folder, name):
r = requests.get(url, allow_redirects=True)
file_path = join(folder, name + '.pdf')
open(file_path, 'wb').write(r.content)
return file_path
<mask token>
def pdf_2_images(url, dest_path):
new_file, filename = download_pdf_to_temp(url)
save_p... | <mask token>
def download_pdf(url, folder, name):
r = requests.get(url, allow_redirects=True)
file_path = join(folder, name + '.pdf')
open(file_path, 'wb').write(r.content)
return file_path
def download_pdf_to_temp(url):
new_file, filename = tempfile.mkstemp()
r = requests.get(url, allow_red... | <mask token>
def download_pdf(url, folder, name):
r = requests.get(url, allow_redirects=True)
file_path = join(folder, name + '.pdf')
open(file_path, 'wb').write(r.content)
return file_path
def download_pdf_to_temp(url):
new_file, filename = tempfile.mkstemp()
r = requests.get(url, allow_red... | import requests
from os.path import join, exists
import os
import fitz
from tqdm import tqdm
from pathlib import Path
import tempfile
def download_pdf(url, folder, name):
r = requests.get(url, allow_redirects=True)
file_path = join(folder, name + '.pdf')
open(file_path, 'wb').write(r.content)
return f... | import requests
from os.path import join, exists
import os
import fitz
from tqdm import tqdm
from pathlib import Path
import tempfile
def download_pdf(url, folder, name):
r = requests.get(url, allow_redirects=True)
file_path = join(folder, name + ".pdf")
open(file_path, 'wb').write(r.content)
return f... | [
2,
3,
4,
5,
6
] |
9,967 | f20e2227821c43de17c116d8c11233eda53ab631 | <mask token>
@app.route('/')
def index():
return os.getenv('DB_HOST')
| <mask token>
load_dotenv(verbose=True)
<mask token>
if bool(os.getenv('IS_DEV')):
logger = logging.getLogger('orator.connection.queries')
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(elapsed_time)sms %(query)s')
handler = logging.StreamHandler()
handler.setFormatter(formatter)
... | <mask token>
load_dotenv(verbose=True)
app = Flask(__name__)
app.secret_key = os.getenv('SECRET_KEY')
app.config['JSON_SORT_KEYS'] = False
app.config['ORATOR_DATABASES'] = {'default': 'mysql', 'mysql': {'driver':
'mysql', 'host': os.getenv('DB_HOST'), 'database': os.getenv('DB_NAME'),
'user': os.getenv('DB_USER... | import os
import logging
from flask import Flask
from flask_orator import Orator
from flask_jwt_extended import JWTManager
from dotenv import load_dotenv
load_dotenv(verbose=True)
app = Flask(__name__)
app.secret_key = os.getenv('SECRET_KEY')
app.config['JSON_SORT_KEYS'] = False
app.config['ORATOR_DATABASES'] = {'defau... | import os
import logging
from flask import Flask
from flask_orator import Orator
from flask_jwt_extended import JWTManager
from dotenv import load_dotenv
load_dotenv(verbose=True)
app = Flask(__name__)
app.secret_key = os.getenv('SECRET_KEY')
app.config['JSON_SORT_KEYS'] = False
app.config['ORATOR_DATABASES'] = {
... | [
1,
2,
3,
4,
5
] |
9,968 | beccae96b3b2c9dcd61bb538d07b85441a73662e | <mask token>
| <mask token>
def puissance(x, n):
if n == 0:
return 1
else:
return x * puissance(x, n - 1)
<mask token>
| <mask token>
def puissance(x, n):
if n == 0:
return 1
else:
return x * puissance(x, n - 1)
print(puissance(number, exposant))
| number = int(input('entrez un entier:'))
exposant = int(input('entrez un exposant:'))
def puissance(x, n):
if n == 0:
return 1
else:
return x * puissance(x, n - 1)
print(puissance(number, exposant))
| number = int(input("entrez un entier:"))
exposant = int(input("entrez un exposant:"))
def puissance(x, n):
if n == 0:
return 1
else:
return x * puissance(x, n-1)
print(puissance(number, exposant))
| [
0,
1,
2,
3,
4
] |
9,969 | fc1b9ab1fb1ae71d70b3bf5c879a5f604ddef997 | <mask token>
def save_pool():
for i in range(total_models):
current_pool[i].save_weights(save_location + str(i) + '.keras')
print('Pool saved')
def create_model():
"""
Create Neural Network as a keras model
"""
model = Sequential()
model.add(Dense(12, input_dim=8, activation='rel... | <mask token>
def save_pool():
for i in range(total_models):
current_pool[i].save_weights(save_location + str(i) + '.keras')
print('Pool saved')
def create_model():
"""
Create Neural Network as a keras model
"""
model = Sequential()
model.add(Dense(12, input_dim=8, activation='rel... | <mask token>
def save_pool():
for i in range(total_models):
current_pool[i].save_weights(save_location + str(i) + '.keras')
print('Pool saved')
def create_model():
"""
Create Neural Network as a keras model
"""
model = Sequential()
model.add(Dense(12, input_dim=8, activation='rel... | <mask token>
def save_pool():
for i in range(total_models):
current_pool[i].save_weights(save_location + str(i) + '.keras')
print('Pool saved')
def create_model():
"""
Create Neural Network as a keras model
"""
model = Sequential()
model.add(Dense(12, input_dim=8, activation='rel... | import random
import sys
import math
import numpy as np
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten, Conv2D, Activation
from snake_game import Snake
from snake_game import Fruit
import pygame
from pygame.locals import *
# Neural Network glo... | [
12,
14,
15,
17,
21
] |
9,970 | e0f7837731520ad76ca91d78c20327d1d9bb6d4f | <mask token>
| <mask token>
with open(os_join(here, 'README.md')) as f:
README = f.read()
setup(name='pyzohar', version='0.1.11', author='zoharslong', author_email=
'zoharslong@hotmail.com', description=
'a private package on data pre-processing.', long_description=README,
url='https://www.xzzsmeadow.com/', license='M... | <mask token>
here = os_abspath(os_dirname(__file__))
with open(os_join(here, 'README.md')) as f:
README = f.read()
setup(name='pyzohar', version='0.1.11', author='zoharslong', author_email=
'zoharslong@hotmail.com', description=
'a private package on data pre-processing.', long_description=README,
url='... | <mask token>
from setuptools import setup, find_packages
from os.path import join as os_join, abspath as os_abspath, dirname as os_dirname
here = os_abspath(os_dirname(__file__))
with open(os_join(here, 'README.md')) as f:
README = f.read()
setup(name='pyzohar', version='0.1.11', author='zoharslong', author_email=
... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on 2021.03.18
setup for package.
@author: zoharslong
"""
from setuptools import setup, find_packages
from os.path import join as os_join, abspath as os_abspath, dirname as os_dirname
here = os_abspath(os_dirname(__file__))
with open(os_join(here, 'README.md')) ... | [
0,
1,
2,
3,
4
] |
9,971 | 3c8e6a93c4d5616b9199cf473d298bfa2dc191af | <mask token>
| <mask token>
def grab_a_ticker(symbol='MSFT', apiKey=None):
if apiKey is None:
apiKey = os.environ.get('API_KEY')
if not check_ticker_exists(symbol) and not check_blacklisted(symbol):
requestUrl = (
'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol={}&outputsize=... | <mask token>
def get_data(url, delay=20):
while True:
df = json.loads(urllib.request.urlopen(url).read())
if df.get('Note', 0) == 0:
break
time.sleep(20)
return df
def grab_a_ticker(symbol='MSFT', apiKey=None):
if apiKey is None:
apiKey = os.environ.get('API_K... | import json
import os
import time
import urllib.request
import pandas as pd
from lib.db.dbutils import check_blacklisted, check_ticker_exists, get_db, update_blacklisted
def get_data(url, delay=20):
while True:
df = json.loads(urllib.request.urlopen(url).read())
if df.get('Note', 0) == 0:
... | import json
import os
import time
import urllib.request
import pandas as pd
from lib.db.dbutils import (
check_blacklisted,
check_ticker_exists,
get_db,
update_blacklisted,
)
def get_data(url, delay=20):
while True:
df = json.loads(urllib.request.urlopen(url).read())
if df.get("N... | [
0,
1,
2,
3,
4
] |
9,972 | 13b2fea09f5a4300563dd8870fe1841b47756b36 | <mask token>
| <mask token>
def test_astype_invalid_nas_to_tdt64_raises():
idx = Index([NaT.asm8] * 2, dtype=object)
msg = 'Cannot cast Index to dtype timedelta64\\[ns\\]'
with pytest.raises(TypeError, match=msg):
idx.astype('m8[ns]')
| <mask token>
def test_astype_str_from_bytes():
idx = Index(['あ', b'a'], dtype='object')
result = idx.astype(str)
expected = Index(['あ', 'a'], dtype='object')
tm.assert_index_equal(result, expected)
def test_astype_invalid_nas_to_tdt64_raises():
idx = Index([NaT.asm8] * 2, dtype=object)
msg =... | import pytest
from pandas import Index, NaT
import pandas._testing as tm
def test_astype_str_from_bytes():
idx = Index(['あ', b'a'], dtype='object')
result = idx.astype(str)
expected = Index(['あ', 'a'], dtype='object')
tm.assert_index_equal(result, expected)
def test_astype_invalid_nas_to_tdt64_raise... | import pytest
from pandas import (
Index,
NaT,
)
import pandas._testing as tm
def test_astype_str_from_bytes():
# https://github.com/pandas-dev/pandas/issues/38607
idx = Index(["あ", b"a"], dtype="object")
result = idx.astype(str)
expected = Index(["あ", "a"], dtype="object")
tm.assert_inde... | [
0,
1,
2,
3,
4
] |
9,973 | 1ad694c68ef264c6fbba4f4b9c069f22818d2816 | <mask token>
| <mask token>
output.write("""{}
{}
{}
{}
{}
{}
{}
""".format(line1, line2, line3, line4,
line5, line6, line7))
| <mask token>
bank_data = 'Resources/budget_data.csv'
bank_df = pd.read_csv(bank_data)
total_months = bank_df['Date'].count()
net_end = bank_df['Profit/Losses'].sum()
bank_df['Change'] = bank_df['Profit/Losses'].diff()
average_change = bank_df['Change'].mean()
greatest_increase = bank_df['Change'].max()
greatest_increas... | import pandas as pd
bank_data = 'Resources/budget_data.csv'
bank_df = pd.read_csv(bank_data)
total_months = bank_df['Date'].count()
net_end = bank_df['Profit/Losses'].sum()
bank_df['Change'] = bank_df['Profit/Losses'].diff()
average_change = bank_df['Change'].mean()
greatest_increase = bank_df['Change'].max()
greatest_... | # Dependencies
import pandas as pd
# Load in data file from resources
bank_data = "Resources/budget_data.csv"
# Read and display with pandas
bank_df = pd.read_csv(bank_data)
# Find the total number of months included in the dataset
total_months = bank_df["Date"].count()
# Find the total net amount of "Profit/Losses... | [
0,
1,
2,
3,
4
] |
9,974 | 05ca16303d0eb962249793164ac91795c45cc3c2 | <mask token>
@app.route('/')
def showMachineList():
return render_template('list.html')
@app.route('/insert_records', methods=['POST'])
def insert_records():
json_data = request.json['info']
nome = json_data['nome']
email = json_data['email']
telefone = json_data['telefone']
db.catalogo.inse... | <mask token>
catalogo.insert_one(contato1)
catalogo.insert_one(contato2)
@app.route('/')
def showMachineList():
return render_template('list.html')
@app.route('/insert_records', methods=['POST'])
def insert_records():
json_data = request.json['info']
nome = json_data['nome']
email = json_data['email... | <mask token>
app = Flask(__name__)
conexao = MongoClient('localhost', 27017)
db = conexao['teste_db']
contato1 = {'nome': 'Lucas', 'email': 'lucas@gmail.com', 'telefone':
'11 99389-3244'}
contato2 = {'nome': 'Lara', 'email': 'lara@gmail.com', 'telefone':
'11 99333-3556'}
catalogo = db.catalogo
catalogo.insert_o... | from flask import Flask, render_template, request, url_for, redirect, jsonify, json, request
from pymongo import MongoClient
app = Flask(__name__)
conexao = MongoClient('localhost', 27017)
db = conexao['teste_db']
contato1 = {'nome': 'Lucas', 'email': 'lucas@gmail.com', 'telefone':
'11 99389-3244'}
contato2 = {'nom... | from flask import Flask, render_template, request, url_for, redirect,jsonify,json,request
from pymongo import MongoClient
#conexão bd
app = Flask(__name__)
conexao = MongoClient('localhost',27017)
db = conexao['teste_db']
#inserindo contatos iniciais
contato1 = {'nome': 'Lucas', 'email': 'lucas@gmail.com', 'telefone... | [
3,
4,
5,
6,
7
] |
9,975 | 668b63d1f1bd035226e3e12bc6816abc897affc3 | <mask token>
class Planet:
def __init__(self, x, y, radius):
self.radius = radius
self.x = x
self.y = y
canvas = Screen()
canvas.setup(800, 800)
self.turtle = Turtle()
<mask token>
def scaleSize(self, scale):
self.radius = self.radius * scale
... | <mask token>
class Planet:
def __init__(self, x, y, radius):
self.radius = radius
self.x = x
self.y = y
canvas = Screen()
canvas.setup(800, 800)
self.turtle = Turtle()
def circumference(self):
return 2 * 3.1415 * self.radius
def scaleSize(self, sc... | <mask token>
class Planet:
def __init__(self, x, y, radius):
self.radius = radius
self.x = x
self.y = y
canvas = Screen()
canvas.setup(800, 800)
self.turtle = Turtle()
def circumference(self):
return 2 * 3.1415 * self.radius
def scaleSize(self, sc... | from turtle import *
class Planet:
def __init__(self, x, y, radius):
self.radius = radius
self.x = x
self.y = y
canvas = Screen()
canvas.setup(800, 800)
self.turtle = Turtle()
def circumference(self):
return 2 * 3.1415 * self.radius
def scaleSize(... | # Planet Class
from turtle import *
class Planet:
def __init__(self, x, y, radius):
self.radius = radius
self.x = x
self.y = y
canvas = Screen()
canvas.setup(800, 800)
self.turtle = Turtle()
def circumference(self):
return 2*3.1415*self.radius... | [
4,
5,
7,
8,
9
] |
9,976 | e4a2c605ef063eee46880515dfff05562916ab81 | <mask token>
| <mask token>
class Solution:
<mask token>
<mask token>
| <mask token>
class Solution:
def combine(self, n: int, k: int) ->List[List[int]]:
if k == 0:
return [[]]
ans = []
for i in range(k, n + 1):
for temp_ans in self.combine(i - 1, k - 1):
ans.append(temp_ans + [i])
return ans
<mask token>
| import sys
class Solution:
def combine(self, n: int, k: int) ->List[List[int]]:
if k == 0:
return [[]]
ans = []
for i in range(k, n + 1):
for temp_ans in self.combine(i - 1, k - 1):
ans.append(temp_ans + [i])
return ans
<mask token>
| # Problem No.: 77
# Solver: Jinmin Goh
# Date: 20191230
# URL: https://leetcode.com/problems/combinations/
import sys
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
if k == 0:
return [[]]
ans = []
for i in range(k, n + 1) :
for tem... | [
0,
1,
2,
3,
4
] |
9,977 | d0a053faccecddc84a9556aec3dff691b171df96 | <mask token>
| <mask token>
class Migration(migrations.Migration):
<mask token>
<mask token>
| <mask token>
class Migration(migrations.Migration):
dependencies = [('event', '0009_auto_20211001_0406')]
operations = [migrations.AlterField(model_name='event', name='map',
field=django_resized.forms.ResizedImageField(blank=True, crop=None,
force_format='JPEG', help_text='Mapa del evento', ke... | from django.db import migrations
import django_resized.forms
import event.models.event
import event.models.event_agenda
class Migration(migrations.Migration):
dependencies = [('event', '0009_auto_20211001_0406')]
operations = [migrations.AlterField(model_name='event', name='map',
field=django_resized.... | # Generated by Django 3.2.7 on 2021-10-01 06:43
from django.db import migrations
import django_resized.forms
import event.models.event
import event.models.event_agenda
class Migration(migrations.Migration):
dependencies = [
('event', '0009_auto_20211001_0406'),
]
operations = [
migratio... | [
0,
1,
2,
3,
4
] |
9,978 | 8a412231c13df1b364b6e2a27549730d06048186 | <mask token>
class FilterTests(helper.CPWebCase):
def testCPFilterList(self):
self.getPage('/cpfilterlist/')
self.assertBody('A horrorshow lomtick of cherry 3.14159')
self.getPage('/cpfilterlist/ended/1')
self.assertBody('True')
valerr = '\n raise ValueError()\nValueErr... | <mask token>
class AccessFilter(BaseFilter):
def before_request_body(self):
if not cherrypy.config.get('access_filter.on', False):
return
if not getattr(cherrypy.request, 'login', None):
raise cherrypy.HTTPError(401)
def setup_server():
class Numerify(BaseFilter):
... | <mask token>
test.prefer_parent_path()
<mask token>
class AccessFilter(BaseFilter):
def before_request_body(self):
if not cherrypy.config.get('access_filter.on', False):
return
if not getattr(cherrypy.request, 'login', None):
raise cherrypy.HTTPError(401)
def setup_serve... | <mask token>
import types
import test
test.prefer_parent_path()
import cherrypy
from cherrypy import filters
from cherrypy.filters.basefilter import BaseFilter
class AccessFilter(BaseFilter):
def before_request_body(self):
if not cherrypy.config.get('access_filter.on', False):
return
... | """Test the various means of instantiating and invoking filters."""
import types
import test
test.prefer_parent_path()
import cherrypy
from cherrypy import filters
from cherrypy.filters.basefilter import BaseFilter
class AccessFilter(BaseFilter):
def before_request_body(self):
if not cherrypy.confi... | [
3,
6,
7,
8,
9
] |
9,979 | acad268a228b544d60966a8767734cbf9c1237ac | <mask token>
| <mask token>
with veil_component.init_component(__name__):
from .material import list_category_materials
from .material import list_material_categories
from .material import list_issue_materials
from .material import list_issue_task_materials
from .material import get_material_image_url
__all__ ... | import veil_component
with veil_component.init_component(__name__):
from .material import list_category_materials
from .material import list_material_categories
from .material import list_issue_materials
from .material import list_issue_task_materials
from .material import get_material_image_url
... | import veil_component
with veil_component.init_component(__name__):
from .material import list_category_materials
from .material import list_material_categories
from .material import list_issue_materials
from .material import list_issue_task_materials
from .material import get_material_image_url
... | null | [
0,
1,
2,
3
] |
9,980 | f64138ee5a64f09deb72b47b86bd7795acddad4d | <mask token>
class CRFData:
"""
测试用的 crf 数据
"""
def __init__(self):
bio_labels = [['O', 'I-X', 'B-X', 'I-Y', 'B-Y']]
self.label_vocabulary = LabelVocabulary(labels=bio_labels, padding=
LabelVocabulary.PADDING)
self.logits = torch.tensor([[[0, 0, 0.5, 0.5, 0.2], [0,... | <mask token>
class CRFData:
"""
测试用的 crf 数据
"""
def __init__(self):
bio_labels = [['O', 'I-X', 'B-X', 'I-Y', 'B-Y']]
self.label_vocabulary = LabelVocabulary(labels=bio_labels, padding=
LabelVocabulary.PADDING)
self.logits = torch.tensor([[[0, 0, 0.5, 0.5, 0.2], [0,... | <mask token>
class CRFData:
"""
测试用的 crf 数据
"""
def __init__(self):
bio_labels = [['O', 'I-X', 'B-X', 'I-Y', 'B-Y']]
self.label_vocabulary = LabelVocabulary(labels=bio_labels, padding=
LabelVocabulary.PADDING)
self.logits = torch.tensor([[[0, 0, 0.5, 0.5, 0.2], [0,... | <mask token>
import pytest
import torch
from easytext.tests import ASSERT
from easytext.data import LabelVocabulary
from easytext.modules import ConditionalRandomField
from easytext.label_decoder import CRFLabelIndexDecoder
class CRFData:
"""
测试用的 crf 数据
"""
def __init__(self):
bio_labels = [... | #!/usr/bin/env python 3
# -*- coding: utf-8 -*-
#
# Copyright (c) 2020 PanXu, Inc. All Rights Reserved
#
"""
测试 label index decoder
Authors: PanXu
Date: 2020/07/05 15:10:00
"""
import pytest
import torch
from easytext.tests import ASSERT
from easytext.data import LabelVocabulary
from easytext.modules import Cond... | [
3,
5,
6,
7,
8
] |
9,981 | c4bd55be86c1f55d89dfcbba2ccde4f3b132edcb | <mask token>
def find_edge(sensors, pos, dir):
x, row = pos
closer = []
for sensor in sensors.keys():
if manhat(pos, sensor) <= sensors[sensor]:
closer.append(sensor)
if dir > 0:
edgiest = [sensor for sensor in sensors.keys() if sensor[0] == max(
[x for x, y in ... | <mask token>
def manhat(point_one, point_two):
return abs(point_one[0] - point_two[0]) + abs(point_one[1] - point_two[1])
def find_edge(sensors, pos, dir):
x, row = pos
closer = []
for sensor in sensors.keys():
if manhat(pos, sensor) <= sensors[sensor]:
closer.append(sensor)
... | <mask token>
def get_sensor_beacon(data_in):
sensors = {}
beacons = set()
for line in data_in:
s_x, s_y, b_x, b_y = list(map(int, digit_search.findall(line)))
sensors[s_x, s_y] = abs(s_x - b_x) + abs(s_y - b_y)
beacons.add((b_x, b_y))
return sensors, beacons
def manhat(point_... | import re
import z3
digit_search = re.compile('\\-?\\d+')
def get_sensor_beacon(data_in):
sensors = {}
beacons = set()
for line in data_in:
s_x, s_y, b_x, b_y = list(map(int, digit_search.findall(line)))
sensors[s_x, s_y] = abs(s_x - b_x) + abs(s_y - b_y)
beacons.add((b_x, b_y))
... | import re
import z3
digit_search = re.compile('\-?\d+')
def get_sensor_beacon(data_in):
sensors = {}
beacons = set()
for line in data_in:
s_x, s_y, b_x, b_y = list(map(int, digit_search.findall(line)))
sensors[(s_x, s_y)] = abs(s_x - b_x) + abs(s_y - b_y)
beacons.add((b_x, b_y))
... | [
2,
4,
6,
8,
9
] |
9,982 | f6ebc3c37a69e5ec49d91609db394eec4a94cedf | <mask token>
| <mask token>
brick.sound.beep()
wait(1000)
motor_a.run_target(500, 720)
wait(1000)
brick.sound.beep(1000, 500)
| <mask token>
motor_a = Motor(Port.A)
brick.sound.beep()
wait(1000)
motor_a.run_target(500, 720)
wait(1000)
brick.sound.beep(1000, 500)
| from pybricks import ev3brick as brick
from pybricks.ev3devices import Motor, TouchSensor, ColorSensor, InfraredSensor, UltrasonicSensor, GyroSensor
from pybricks.parameters import Port, Stop, Direction, Button, Color, SoundFile, ImageFile, Align
from pybricks.tools import print, wait, StopWatch
from pybricks.robotics ... | #!/usr/bin/env pybricks-micropython
from pybricks import ev3brick as brick
from pybricks.ev3devices import (Motor, TouchSensor, ColorSensor,
InfraredSensor, UltrasonicSensor, GyroSensor)
from pybricks.parameters import (Port, Stop, Direction, Button, Color,
... | [
0,
1,
2,
3,
4
] |
9,983 | 7e35c35c8ef443155c45bdbff4ce9ad07b99f144 | <mask token>
| <mask token>
urlpatterns = [path('', views.index, name='index'), path('sign', views.sign,
name='sign'), path('reset_password/', auth_views.PasswordResetView.
as_view(template_name='password_reset.html'), name='password_reset'),
path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view(
templ... | from django.urls import path
from . import views
from django.contrib.auth import views as auth_views
urlpatterns = [path('', views.index, name='index'), path('sign', views.sign,
name='sign'), path('reset_password/', auth_views.PasswordResetView.
as_view(template_name='password_reset.html'), name='password_reset... | from django.urls import path
from . import views
from django.contrib.auth import views as auth_views
urlpatterns = [
path('',views.index,name='index'),
path('sign',views.sign,name='sign'),
# path('password_reset/',auth_views.PasswordResetView.as_view(),name='password_reset'),
# path('password_reset/do... | null | [
0,
1,
2,
3
] |
9,984 | 119ebdf4c686c52e052d3926f962cefdc93681cd | def my_filter(L, num):
return [x for x in L if x % num]
print 'my_filter', my_filter([1, 2, 4, 5, 7], 2)
def my_lists(L):
return [range(1, x+1) for x in L]
print 'my_lists', my_lists([1, 2, 4])
print 'my_lists', my_lists([0])
def my_function_composition(f, g):
return {f_key: g[f_val] for f_key, f_val in f.item... | null | null | null | null | [
0
] |
9,985 | f229f525c610d9925c9300ef22208f9926d6cb69 | <mask token>
| <mask token>
def generateLog(ctime1, request_obj):
log_file.write(ctime1 + '\t')
log_file.write('Status code: ' + str(request_obj.status_code))
log_file.write('\n')
def is_internet():
"""Internet function"""
print(time.ctime())
current_time = time.ctime()
try:
r = requests.get('h... | <mask token>
log_file = open('logfile.txt', 'w')
def generateLog(ctime1, request_obj):
log_file.write(ctime1 + '\t')
log_file.write('Status code: ' + str(request_obj.status_code))
log_file.write('\n')
def is_internet():
"""Internet function"""
print(time.ctime())
current_time = time.ctime()
... | import requests
import time
log_file = open('logfile.txt', 'w')
def generateLog(ctime1, request_obj):
log_file.write(ctime1 + '\t')
log_file.write('Status code: ' + str(request_obj.status_code))
log_file.write('\n')
def is_internet():
"""Internet function"""
print(time.ctime())
current_time ... | #!python3
import requests
import time
log_file = open("logfile.txt", "w")
def generateLog(ctime1, request_obj):
log_file.write(ctime1 + "\t")
log_file.write("Status code: " + str(request_obj.status_code))
log_file.write("\n")
def is_internet():
"""Internet function"""
print(time.... | [
0,
3,
4,
5,
6
] |
9,986 | 5a7e535f2ae585f862cc792dab77f2fe0584fddc | <mask token>
class TestWhatever(unittest.TestCase):
def test_compile(self):
self.assertEqual(WHATEVER.compile(), '*')
class TestOneOrMore(unittest.TestCase):
def test_compile(self):
self.assertEqual(ONE_OR_MORE.compile(), '+')
class TestFixedWidth(unittest.TestCase):
def test_compil... | <mask token>
class TestMultipler(unittest.TestCase):
<mask token>
def test__create__range(self):
self.assertIsInstance(Multiplier.create((23, 27)), Range)
<mask token>
<mask token>
class TestWhatever(unittest.TestCase):
def test_compile(self):
self.assertEqual(WHATEVER.compile(... | <mask token>
class TestMultipler(unittest.TestCase):
def test__create__fixed_width(self):
self.assertIsInstance(Multiplier.create(23), FixedWidth)
def test__create__range(self):
self.assertIsInstance(Multiplier.create((23, 27)), Range)
def test__create__multiplier(self):
self.as... | <mask token>
class TestMultipler(unittest.TestCase):
def test__create__fixed_width(self):
self.assertIsInstance(Multiplier.create(23), FixedWidth)
def test__create__range(self):
self.assertIsInstance(Multiplier.create((23, 27)), Range)
def test__create__multiplier(self):
self.as... | import unittest
from pattern.multiplier import Multiplier, FixedWidth, Range
from pattern.multiplier import WHATEVER, ONE_OR_MORE
class TestMultipler(unittest.TestCase):
def test__create__fixed_width(self):
self.assertIsInstance(Multiplier.create(23), FixedWidth)
def test__create__range(self):
... | [
8,
10,
12,
13,
15
] |
9,987 | 4f06eddfac38574a0ae3bdd0ea2ac81291380166 | <mask token>
| from .simulator import SpatialSIRSimulator as Simulator
from .util import Prior
from .util import PriorExperiment
from .util import Truth
from .util import log_likelihood
| null | null | null | [
0,
1
] |
9,988 | 2d7f7cb66480ecb8335949687854554679026959 | <mask token>
@app.route('/', methods=['POST'])
def func():
st = request.form['review']
if st == '':
return render_template('index.html')
english = spacy.load('en_core_web_sm')
result = english(st)
sentences = [str(s) for s in result.sents]
analyzer = vaderSentiment.SentimentIntensityAn... | <mask token>
@app.route('/')
def hello():
return render_template('index.html')
@app.route('/', methods=['POST'])
def func():
st = request.form['review']
if st == '':
return render_template('index.html')
english = spacy.load('en_core_web_sm')
result = english(st)
sentences = [str(s) f... | <mask token>
app = Flask(__name__)
@app.route('/')
def hello():
return render_template('index.html')
@app.route('/', methods=['POST'])
def func():
st = request.form['review']
if st == '':
return render_template('index.html')
english = spacy.load('en_core_web_sm')
result = english(st)
... | import spacy
from vaderSentiment import vaderSentiment
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/')
def hello():
return render_template('index.html')
@app.route('/', methods=['POST'])
def func():
st = request.form['review']
if st == '':
return render_te... | import spacy
from vaderSentiment import vaderSentiment
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/')
def hello():
return render_template('index.html')
@app.route('/',methods=['POST'])
def func():
st=request.form["review"]
if(st==''):
return render_temp... | [
3,
5,
6,
7,
8
] |
9,989 | c513ad6ef12ae7be5d17d8d44787691cbc065207 | class Violation(object):
<mask token>
<mask token>
<mask token>
| class Violation(object):
def __init__(self, line, column, code, message):
self.line = line
self.column = column
self.code = code
self.message = message
<mask token>
<mask token>
| class Violation(object):
def __init__(self, line, column, code, message):
self.line = line
self.column = column
self.code = code
self.message = message
def __str__(self):
return self.message
<mask token>
| class Violation(object):
def __init__(self, line, column, code, message):
self.line = line
self.column = column
self.code = code
self.message = message
def __str__(self):
return self.message
def __repr__(self):
return 'Violation(line={}, column={}, code="{}... | class Violation(object):
def __init__(self, line, column, code, message):
self.line = line
self.column = column
self.code = code
self.message = message
def __str__(self):
return self.message
def __repr__(self):
return 'Violation(line={}, column={}, code="{}"... | [
1,
2,
3,
4,
5
] |
9,990 | 382bc321c5fd35682bc735ca4d6e293d09be64ec | <mask token>
| <mask token>
if numero % 2 == 0:
p = numero
print(p, 'é um número par')
else:
i = numero
print(i, 'é um número ímpar')
| p = 0
i = 0
numero = int(input('Insira um número: '))
if numero % 2 == 0:
p = numero
print(p, 'é um número par')
else:
i = numero
print(i, 'é um número ímpar')
| #função: Definir se o número inserido é ímpar ou par
#autor: João Cândido
p = 0
i = 0
numero = int(input("Insira um número: "))
if numero % 2 == 0:
p = numero
print (p, "é um número par")
else:
i = numero
print (i, "é um número ímpar") | null | [
0,
1,
2,
3
] |
9,991 | 8339113fd6b0c286cc48ec04e6e24978e2a4b44e | <mask token>
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName(_fromUtf8('Form'))
Form.resize(666, 538)
palette = QtGui.QPalette()
self.eventSkip = 0
self.db = Database()
brush = QtGui.QBrush(QtGui.QColor(8, 129, 2))
brush.setStyle(QtCore.Q... | <mask token>
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName(_fromUtf8('Form'))
Form.resize(666, 538)
palette = QtGui.QPalette()
self.eventSkip = 0
self.db = Database()
brush = QtGui.QBrush(QtGui.QColor(8, 129, 2))
brush.setStyle(QtCore.Q... | <mask token>
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError... | from PyQt4 import QtCore, QtGui, QtSql
import sqlite3
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, d... | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'KPS_RevisitBusinessEvents.ui'
#
# Created: Sun May 18 14:50:49 2014
# by: PyQt4 UI code generator 4.10.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui, QtSql
import sqlite3
try:
_fromUtf... | [
9,
10,
11,
12,
13
] |
9,992 | 2193c97b7f1fcf204007c2528ecc47cbf3c67e81 | <mask token>
| <mask token>
def people_on_image(path_to_image):
color_map = [(255, 255, 255), (255, 255, 255), (255, 255, 255), (255,
255, 255), (255, 255, 255), (255, 255, 255), (255, 255, 255), (255,
255, 255), (255, 255, 255), (255, 255, 255), (255, 255, 255), (255,
255, 255), (255, 255, 255), (255, ... | import torch
import numpy as np
import cv2
import torchvision
from PIL import Image
def people_on_image(path_to_image):
color_map = [(255, 255, 255), (255, 255, 255), (255, 255, 255), (255,
255, 255), (255, 255, 255), (255, 255, 255), (255, 255, 255), (255,
255, 255), (255, 255, 255), (255, 255, ... | import torch
import numpy as np
import cv2
import torchvision
from PIL import Image
def people_on_image(path_to_image):
color_map = [
(255, 255, 255), # background
(255, 255, 255), # aeroplane
(255, 255, 255), # bicycle
(255, 255, 255), ... | null | [
0,
1,
2,
3
] |
9,993 | ff137b51ea5b8c21e335a38a3d307a3302921245 | class Node:
def __init__(self, data):
self.data = data
self.next = None
<mask token>
def Reverse(Head):
Temp = Head
TempNext = Head.next
while TempNext != None:
NextSaved = TempNext.next
TempNext.next = Temp
Temp = TempNext
TempNext = NextSaved
He... | class Node:
def __init__(self, data):
self.data = data
self.next = None
def Add(Head, data):
Temp = Head
while Temp.next != None:
Temp = Temp.next
Temp.next = Node(data)
def create(data):
Head = Node(data)
return Head
<mask token>
def Reverse(Head):
Temp = He... | class Node:
def __init__(self, data):
self.data = data
self.next = None
def Add(Head, data):
Temp = Head
while Temp.next != None:
Temp = Temp.next
Temp.next = Node(data)
def create(data):
Head = Node(data)
return Head
def printLL(Head):
Temp = Head
while Te... | class Node:
def __init__(self, data):
self.data = data
self.next = None
def Add(Head, data):
Temp = Head
while Temp.next != None:
Temp = Temp.next
Temp.next = Node(data)
def create(data):
Head = Node(data)
return Head
def printLL(Head):
Temp = Head
while Te... |
class Node:
def __init__(self,data):
self.data = data
self.next = None
def Add(Head,data):
Temp = Head
while(Temp.next != None):
Temp = Temp.next
Temp.next = Node(data)
# print(Temp.data)
def create(data):
Head = Node(data)
return Head
def printLL(Head):
Temp ... | [
3,
5,
6,
7,
8
] |
9,994 | 0ac14b023c51bfd1cf99bd2d991baa30a671e066 | <mask token>
class ApiException(Exception):
def __init__(self, message, code=400, data=None):
Exception.__init__(self, message)
self.code = code
self.msg = message
self.data = data
def __str__(self):
return self.msg
<mask token>
<mask token>
| <mask token>
class ApiException(Exception):
def __init__(self, message, code=400, data=None):
Exception.__init__(self, message)
self.code = code
self.msg = message
self.data = data
def __str__(self):
return self.msg
def to_dict(self):
res = dict(self.data... | <mask token>
class ApiException(Exception):
def __init__(self, message, code=400, data=None):
Exception.__init__(self, message)
self.code = code
self.msg = message
self.data = data
def __str__(self):
return self.msg
def to_dict(self):
res = dict(self.data... | from service import service_logger
from service.TaskService import TaskService
class ApiException(Exception):
def __init__(self, message, code=400, data=None):
Exception.__init__(self, message)
self.code = code
self.msg = message
self.data = data
def __str__(self):
re... | # _*_ coding: utf-8 _*_
from service import service_logger
from service.TaskService import TaskService
class ApiException(Exception):
def __init__(self, message, code=400, data=None):
Exception.__init__(self, message)
self.code = code
self.msg = message
self.data = data... | [
3,
4,
5,
6,
7
] |
9,995 | aafdd228cf2859d7f013b088263eab544e19c481 | <mask token>
| <mask token>
try:
myclient = pymongo.MongoClient('mongodb://localhost:27017/')
myclient.server_info()
print('Database Connected')
except:
print('Database Error')
<mask token>
| <mask token>
myclient = {}
try:
myclient = pymongo.MongoClient('mongodb://localhost:27017/')
myclient.server_info()
print('Database Connected')
except:
print('Database Error')
mydb = myclient['jmitproject']
user = user(mydb)
blog = blog(mydb)
| import pymongo
from FlaskScripts.database.user_database import user
from FlaskScripts.database.blog_database import blog
myclient = {}
try:
myclient = pymongo.MongoClient('mongodb://localhost:27017/')
myclient.server_info()
print('Database Connected')
except:
print('Database Error')
mydb = myclient['jmi... | import pymongo
from FlaskScripts.database.user_database import user
from FlaskScripts.database.blog_database import blog
myclient = {}
try:
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
myclient.server_info()
print('Database Connected')
except:
print('Database Error')
mydb = myclient["jm... | [
0,
1,
2,
3,
4
] |
9,996 | c312bf096c7f4aaf9269a8885ff254fd4852cfe0 | <mask token>
class ExecuteCommandTest(TestBase):
def setUp(self):
super(ExecuteCommandTest, self).setUp()
self.cwd = os.path.join(os.path.dirname(__file__), '../../..')
self.logger = Mock()
MonkeyPatcher.patch(action, 'create_background_logger', Mock(
return_value=self... | <mask token>
class ExecuteCommandTest(TestBase):
def setUp(self):
super(ExecuteCommandTest, self).setUp()
self.cwd = os.path.join(os.path.dirname(__file__), '../../..')
self.logger = Mock()
MonkeyPatcher.patch(action, 'create_background_logger', Mock(
return_value=self... | <mask token>
class ExecuteCommandTest(TestBase):
def setUp(self):
super(ExecuteCommandTest, self).setUp()
self.cwd = os.path.join(os.path.dirname(__file__), '../../..')
self.logger = Mock()
MonkeyPatcher.patch(action, 'create_background_logger', Mock(
return_value=self... | from mock import Mock
from shelf.hook.background import action
from shelf.hook.event import Event
from tests.test_base import TestBase
import json
import os
import logging
from pyproctor import MonkeyPatcher
class ExecuteCommandTest(TestBase):
def setUp(self):
super(ExecuteCommandTest, self).setUp()
... | from mock import Mock
from shelf.hook.background import action
from shelf.hook.event import Event
from tests.test_base import TestBase
import json
import os
import logging
from pyproctor import MonkeyPatcher
class ExecuteCommandTest(TestBase):
def setUp(self):
super(ExecuteCommandTest, self).setUp()
... | [
4,
5,
6,
7,
8
] |
9,997 | 25288a6dd0552d59f8c305bb8edbbbed5d464d5b | # Copyright (C) 2011 Ruckus Wireless, Inc. All rights reserved.
# Please make sure the following module docstring is accurate since it will be used in report generation.
"""
Description:
@author: Chris Wang
@contact: cwang@ruckuswireless.com
@since: Aug-09, 2010
Prerequisite (Assumptions about the sta... | null | null | null | null | [
0
] |
9,998 | 0f0ded26e115b954a5ef698b03271ddf2b947334 | '''
PROBLEM N. 5:
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
'''
'''
Greatest common divisior using the Euclidean Algorithm, vide http://en.wikipedia.org/wi... | null | null | null | null | [
0
] |
9,999 | ac2e9145e3345e5448683d684b69d2356e3214ce | <mask token>
| <mask token>
def dist(counts):
n = abs(counts['n'] - counts['s'])
nw = abs(counts['nw'] - counts['se'])
ne = abs(counts['ne'] - counts['sw'])
return n + max(ne, nw)
<mask token>
| <mask token>
def dist(counts):
n = abs(counts['n'] - counts['s'])
nw = abs(counts['nw'] - counts['se'])
ne = abs(counts['ne'] - counts['sw'])
return n + max(ne, nw)
if __name__ == '__main__':
counts = defaultdict(int)
with open('day11.input.txt') as f:
INPUT = f.read().strip()
... | from collections import defaultdict
def dist(counts):
n = abs(counts['n'] - counts['s'])
nw = abs(counts['nw'] - counts['se'])
ne = abs(counts['ne'] - counts['sw'])
return n + max(ne, nw)
if __name__ == '__main__':
counts = defaultdict(int)
with open('day11.input.txt') as f:
INPUT = ... | from collections import defaultdict
# The order of the steps doesn't matter, so the distance
# function is very simple
def dist(counts):
n = abs(counts["n"] - counts["s"])
nw = abs(counts["nw"] - counts["se"])
ne = abs(counts["ne"] - counts["sw"])
return n + max(ne,nw)
if __name__ == "__main__":
c... | [
0,
1,
2,
3,
4
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.