index
int64
0
10k
blob_id
stringlengths
40
40
step-1
stringlengths
13
984k
step-2
stringlengths
6
1.23M
step-3
stringlengths
15
1.34M
step-4
stringlengths
30
1.34M
step-5
stringlengths
64
1.2M
step-ids
listlengths
1
5
0
aff1a9263e183610f403a4d6a7f27b45eacb7ff2
<mask token>
<mask token> print(name * 1000)
name = 'valentina ' print(name * 1000)
null
null
[ 0, 1, 2 ]
1
eabf06481509962652812af67ad59da5cfe30fae
<mask token>
<mask token> __all__ = ('__title__', '__summary__', '__version__', '__author__', '__license__', '__copyright__') __title__ = 'mupub' __summary__ = 'Musical score publishing utility for the Mutopia Project' <mask token> __version__ = '1.0.8' __author__ = 'Glen Larsen, Chris Sawer' __author_email__ = 'glenl.glx@gmail...
<mask token> __all__ = ('__title__', '__summary__', '__version__', '__author__', '__license__', '__copyright__') __title__ = 'mupub' __summary__ = 'Musical score publishing utility for the Mutopia Project' <mask token> __version__ = '1.0.8' __author__ = 'Glen Larsen, Chris Sawer' __author_email__ = 'glenl.glx@gmail...
""" mupub module. """ __all__ = ( '__title__', '__summary__', '__version__', '__author__', '__license__', '__copyright__', ) __title__ = 'mupub' __summary__ = 'Musical score publishing utility for the Mutopia Project' """Versioning: This utility follows a MAJOR . MINOR . EDIT format. Upon a major release, t...
null
[ 0, 1, 2, 3 ]
2
54f0ed5f705d5ada28721301f297b2b0058773ad
<mask token> class _GenericBot: <mask token> def __init__(self, pos, inventory=None): """Initialize with an empty inventory. inventory is a dictionary. If None, an empty one will be used.""" if inventory is None: self._inventory = {} else: self._invent...
<mask token> class _GenericBot: <mask token> def __init__(self, pos, inventory=None): """Initialize with an empty inventory. inventory is a dictionary. If None, an empty one will be used.""" if inventory is None: self._inventory = {} else: self._invent...
<mask token> class _GenericBot: <mask token> def __init__(self, pos, inventory=None): """Initialize with an empty inventory. inventory is a dictionary. If None, an empty one will be used.""" if inventory is None: self._inventory = {} else: self._invent...
<mask token> class _GenericBot: <mask token> def __init__(self, pos, inventory=None): """Initialize with an empty inventory. inventory is a dictionary. If None, an empty one will be used.""" if inventory is None: self._inventory = {} else: self._invent...
"""Module for the bot""" from copy import deepcopy from time import sleep import mcpi.minecraft as minecraft from mcpi.vec3 import Vec3 import mcpi.block as block from search import SearchProblem, astar, bfs from singleton import singleton _AIR = block.AIR.id _WATER = block.WATER.id _LAVA = block.LAVA.id _BEDROCK =...
[ 52, 53, 58, 60, 79 ]
3
45969b346d6d5cbdef2f5d2f74270cf12024072d
<mask token>
<mask token> class Migration(migrations.Migration): <mask token> <mask token>
<mask token> class Migration(migrations.Migration): dependencies = [('search', '0003_auto_20230209_1441')] operations = [migrations.CreateModel(name='SearchSettings', fields=[( 'id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'))], options={'permissi...
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [('search', '0003_auto_20230209_1441')] operations = [migrations.CreateModel(name='SearchSettings', fields=[( 'id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name...
# Generated by Django 4.1.9 on 2023-06-29 16:11 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("search", "0003_auto_20230209_1441"), ] operations = [ migrations.CreateModel( name="SearchSettings", fields=[ ...
[ 0, 1, 2, 3, 4 ]
4
3fbf1768a2fe78df591c49490dfce5fb374e7fc2
from functools import wraps import os def restoring_chdir(fn): #XXX:dc: This would be better off in a neutral module @wraps(fn) def decorator(*args, **kw): try: path = os.getcwd() return fn(*args, **kw) finally: os.chdir(path) return decorator clas...
null
null
null
null
[ 0 ]
5
67b967b688aeac1270eee836e0f6e6b3555b933e
<mask token>
<mask token> if u_avg < u_bat_min: print('proper shut down of the machine due to low battery') else: print('tout va bien dormez braves gens')
<mask token> pidcmes = Pidcmes() u_bat_min = 3.7 n_moy = 20 stop_run = False u_avg = pidcmes.get_tension(n_moy) if u_avg < u_bat_min: print('proper shut down of the machine due to low battery') else: print('tout va bien dormez braves gens')
<mask token> import time import datetime as dt from subprocess import call from pidcmes_lib import Pidcmes pidcmes = Pidcmes() u_bat_min = 3.7 n_moy = 20 stop_run = False u_avg = pidcmes.get_tension(n_moy) if u_avg < u_bat_min: print('proper shut down of the machine due to low battery') else: print('tout va bie...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ This program is run at regular intervals to check the battery charge status of the uninterruptible power supply. In our case, it is a LiPo battery with a nominal voltage of 3.7 volts. By setting the voltage for the Raspberry PI shutdown procedure at 3.7 V,we ensure th...
[ 0, 1, 2, 3, 4 ]
6
c59707ba07c1659d94684c54cdd7bb2658cba935
<mask token> class H2OShuffleSplit(H2OBaseShuffleSplit): <mask token> def _iter_indices(self, frame, y=None): """Iterate the indices. Parameters ---------- frame : H2OFrame The frame to split y : string, optional (default=None) The column to ...
<mask token> class H2OBaseShuffleSplit(six.with_metaclass(ABCMeta)): """Base class for H2OShuffleSplit and H2OStratifiedShuffleSplit. This is used for ``h2o_train_test_split`` in strategic train/test splits of H2OFrames. Implementing subclasses should override ``_iter_indices``. Parameters ------...
<mask token> def check_cv(cv=3): """Checks the ``cv`` parameter to determine whether it's a valid int or H2OBaseCrossValidator. Parameters ---------- cv : int or H2OBaseCrossValidator, optional (default=3) The number of folds or the H2OBaseCrossValidator instance. Returns ...
<mask token> def _build_repr(self): cls = self.__class__ init = getattr(cls.__init__, 'deprecated_original', cls.__init__) init_signature = signature(init) if init is object.__init__: args = [] else: args = sorted([p.name for p in init_signature.parameters.values() if p...
from __future__ import division, print_function, absolute_import import numbers import warnings from abc import ABCMeta, abstractmethod import numpy as np from .base import check_frame from skutil.base import overrides from sklearn.externals import six from sklearn.base import _pprint from sklearn.utils.fixes import si...
[ 21, 29, 40, 43, 47 ]
7
41cfd558824b6561114a48a694b1e6e6a7cb8c05
<mask token>
<mask token> def app(page): if not login_status(): title_container = st.empty() remail_input_container = st.empty() rpw_input_container = st.empty() rregister_button_container = st.empty() email = remail_input_container.text_input('Email ') password = rpw_input_cont...
import streamlit as st from streamlit.components.v1 import components from streamlit.report_thread import get_report_ctx from util.session import * from multipage import MultiPage from pages import register def app(page): if not login_status(): title_container = st.empty() remail_input_container =...
import streamlit as st from streamlit.components.v1 import components from streamlit.report_thread import get_report_ctx from util.session import * from multipage import MultiPage from pages import register def app(page): if not login_status(): title_container = st.empty() remail_input_container = ...
null
[ 0, 1, 2, 3 ]
8
f2bb44600f011a205c71985ad94c18f7e058634f
<mask token> def from_url(url: str) ->Image.Image: api_response = requests.get(url).content response_bytes = BytesIO(api_response) return Image.open(response_bytes) def from_file(path: str) ->Union[Image.Image, None]: if os.path.exists(path): return Image.open(path) else: return ...
<mask token> def get_img_from_file_or_url(img_format: str='JPEG') ->Callable[[str, str], Image.Image]: def _apply(filepath: str, url: str) ->Image.Image: img = from_file(filepath) if img is None: img = from_url(url) img.save(filepath, img_format) return img.con...
<mask token> def get_img_from_file_or_url(img_format: str='JPEG') ->Callable[[str, str], Image.Image]: def _apply(filepath: str, url: str) ->Image.Image: img = from_file(filepath) if img is None: img = from_url(url) img.save(filepath, img_format) return img.con...
import os import requests from PIL import Image from io import BytesIO import csv from typing import Iterable, List, Tuple, Dict, Callable, Union, Collection def get_img_from_file_or_url(img_format: str='JPEG') ->Callable[[str, str], Image.Image]: def _apply(filepath: str, url: str) ->Image.Image: im...
import os import requests from PIL import Image from io import BytesIO import csv from typing import Iterable, List, Tuple, Dict, Callable, Union, Collection # pull the image from the api endpoint and save it if we don't have it, else load it from disk def get_img_from_file_or_url(img_format: str = 'JPEG') -> Callabl...
[ 2, 3, 4, 5, 6 ]
9
302605d8bb45b1529742bf9441d476f0276085b9
<mask token> class MyMainWindow(QMainWindow): <mask token> <mask token> def initConnect(self): self.dataFileChooseButton.clicked.connect(self.chooseData) self.dataFileChooseButtonT.clicked.connect(self.chooseData) self.dataLossSimulateSettingButton.clicked.connect(self. ...
<mask token> class MyMainWindow(QMainWindow): <mask token> def initUI(self): self.statusBar().showMessage('Ready') dataModule = QVBoxLayout() self.dataFileChooseButton = QPushButton('选择数据') self.dataFileChooseButton.setFont(QFont('微软雅黑', 16)) self.dataLossSimulateSetti...
<mask token> class MyMainWindow(QMainWindow): <mask token> def initUI(self): self.statusBar().showMessage('Ready') dataModule = QVBoxLayout() self.dataFileChooseButton = QPushButton('选择数据') self.dataFileChooseButton.setFont(QFont('微软雅黑', 16)) self.dataLossSimulateSetti...
<mask token> class MyMainWindow(QMainWindow): def __init__(self): super().__init__() self.windowLength = 1250 self.windowHigh = 900 self.fname = dict() self.fname['New'] = None self.fname['Tra'] = None self.dataLossRate = dict() self.dataSetLossValu...
import sys from PyQt5.QtWidgets import (QMainWindow, QWidget, QHBoxLayout, QVBoxLayout, QFrame, QSplitter, QStyleFactory, QApplication, QPushButton, QTextEdit, QLabel, QFileDialog, QMessageBox) from PyQt5.QtCore import Qt from PyQt5.QtGui import QFont, QColor import myLoadData from UIPack import setLossParameterDia...
[ 9, 11, 12, 15, 18 ]
10
5d9c8e235385ff53c7510994826ff3a04e4a5888
<mask token> class Model: def __init__(self, dim_word, dim_char, dropout, learning_rate, hidden_size_char, hidden_size_word, num_layers): """ :param dim_word: 词的维度 :param dim_char: 字符维度 :param dropout: dropout :param learning_rate: 学习率 :param hidden_size_ch...
<mask token> class Model: def __init__(self, dim_word, dim_char, dropout, learning_rate, hidden_size_char, hidden_size_word, num_layers): """ :param dim_word: 词的维度 :param dim_char: 字符维度 :param dropout: dropout :param learning_rate: 学习率 :param hidden_size_ch...
<mask token> class Model: def __init__(self, dim_word, dim_char, dropout, learning_rate, hidden_size_char, hidden_size_word, num_layers): """ :param dim_word: 词的维度 :param dim_char: 字符维度 :param dropout: dropout :param learning_rate: 学习率 :param hidden_size_ch...
<mask token> class Model: def __init__(self, dim_word, dim_char, dropout, learning_rate, hidden_size_char, hidden_size_word, num_layers): """ :param dim_word: 词的维度 :param dim_char: 字符维度 :param dropout: dropout :param learning_rate: 学习率 :param hidden_size_ch...
""" @file : 001-rnn+lstm+crf.py @author: xiaolu @time : 2019-09-06 """ import re import numpy as np import tensorflow as tf from sklearn.metrics import classification_report class Model: def __init__(self, dim_word, dim_char, dropout, learning_rate, hidden_size_char, hidden_size_word, num_l...
[ 5, 8, 10, 11, 13 ]
11
54e04d740ef46fca04cf4169d2e7c05083414bd8
<mask token> class Player: <mask token> <mask token> <mask token> class Bullet: def __init__(self, color): self.x = 0 self.y = 0 self.angle = 0 self.color = color def draw(self): pygame.draw.rect(scr, self.color, pygame.Rect(self.x, self.y, 5, 5)) clas...
<mask token> class Player: def __init__(self): self.x = 275 self.y = 275 self.image = pygame.image.load('player.jpg') self.image1 = pygame.image.load('hearts.png') self.lives = 5 def draw(self): scr.blit(self.image, (self.x, self.y)) def rotate(self, x, y...
<mask token> pygame.init() scr = pygame.display.set_mode((700, 700)) enemies = [] hit = [] class Player: def __init__(self): self.x = 275 self.y = 275 self.image = pygame.image.load('player.jpg') self.image1 = pygame.image.load('hearts.png') self.lives = 5 def draw(se...
import random import math import time import pygame pygame.init() scr = pygame.display.set_mode((700, 700)) enemies = [] hit = [] class Player: def __init__(self): self.x = 275 self.y = 275 self.image = pygame.image.load('player.jpg') self.image1 = pygame.image.load('hearts.png') ...
import random import math import time import pygame pygame.init() scr = pygame.display.set_mode((700,700)) enemies = [] #music = pygame.mixer.music.load('ENERGETIC CHIPTUNE Thermal - Evan King.mp3') #pygame.mixer.music.play(-1) hit = [] class Player: def __init__(self): self.x = 275 sel...
[ 14, 17, 19, 20, 21 ]
12
0a7ffc027511d5fbec0076f6b25a6e3bc3dfdd9b
''' Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You may assume no duplicates in the array. Here are few examples. [1,3,5,6], 5 -> 2 [1,3,5,6], 2 -> 1 [1,3,5,6], 7 -> 4 [1,3,5,6], 0 -> 0 ''' class Solution(o...
null
null
null
null
[ 0 ]
13
2cbce618d1ec617d1c7dc0e9792b6a49361ec5a4
<mask token>
def mais_populoso(dic): p = 0 sp = 0 for t, i in dic.items(): for m in dic[t].values(): p += m if p > sp: sp = p x = t return x
null
null
null
[ 0, 1 ]
14
2092ead8b8f268a22711b8af8052241c1ac00c15
<mask token>
<mask token> print('%d시간에 %d%s 벌었습니다.' % (1, wage * 1, '달러')) print('%d시간에 %d%s 벌었습니다.' % (5, wage * 5, '달러')) print('%d시간에 %.1f%s 벌었습니다' % (1, 5710.8, '원')) print('%d시간에 %.1f%s 벌었습니다' % (5, 28554.0, '원'))
wage = 5 print('%d시간에 %d%s 벌었습니다.' % (1, wage * 1, '달러')) print('%d시간에 %d%s 벌었습니다.' % (5, wage * 5, '달러')) print('%d시간에 %.1f%s 벌었습니다' % (1, 5710.8, '원')) print('%d시간에 %.1f%s 벌었습니다' % (5, 28554.0, '원'))
wage=5 print("%d시간에 %d%s 벌었습니다." %(1, wage*1, "달러")) print("%d시간에 %d%s 벌었습니다." %(5, wage*5, "달러")) print("%d시간에 %.1f%s 벌었습니다" %(1,5710.8,"원")) print("%d시간에 %.1f%s 벌었습니다" %(5, 28554.0, "원"))
null
[ 0, 1, 2, 3 ]
15
b5cbb73c152dd60e9063d5a19f6182e2264fec6d
#!/usr/bin/python # coding=UTF-8 import sys import subprocess import os def printReportTail(reportHtmlFile): reportHtmlFile.write(""" </body> </html> """) def printReportHead(reportHtmlFile): reportHtmlFile.write("""<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" ...
null
null
null
null
[ 0 ]
16
805fc9a26650f85227d14da972311ffbd9dbd555
<mask token>
class Date: <mask token>
class Date: def __init__(self, strDate): strDate = strDate.split('.') self.day = strDate[0] self.month = strDate[1] self.year = strDate[2]
null
null
[ 0, 1, 2 ]
17
a7218971b831e2cfda9a035eddb350ecf1cdf938
#!/usr/bin/python # encoding: utf-8 # # In case of reuse of this source code please do not remove this copyright. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the Licen...
null
null
null
null
[ 0 ]
18
038ccba05113fb7f2f589eaa7345df53cb59a5af
<mask token>
<mask token> def train(num_epochs=30): lossfunction = nn.CrossEntropyLoss() trainset = TrainDataSet() model = BiAffineSrlModel(vocabs=trainset.vocabs) optimizer = torch.optim.Adam(model.parameters(), lr=0.01) since = time.time() best_model_wts = copy.deepcopy(model.state_dict()) best_f = F...
<mask token> config.add_option('-m', '--mode', dest='mode', default='train', type= 'string', help='[train|eval|pred]', action='store') config.add_option('--seed', dest='seed', default=1, type='int', help= 'torch random seed', action='store') def train(num_epochs=30): lossfunction = nn.CrossEntropyLoss() ...
import sys import torch from torch import nn, autograd import config import time import copy import progressbar as pb from dataset import TrainDataSet from model import BiAffineSrlModel from fscore import FScore config.add_option('-m', '--mode', dest='mode', default='train', type= 'string', help='[train|eval|pred]'...
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import torch from torch import nn, autograd import config import time import copy import progressbar as pb from dataset import TrainDataSet from model import BiAffineSrlModel from fscore import FScore config.add_option('-m', '--mode', dest='mode', default='train...
[ 0, 1, 2, 3, 4 ]
19
b5180a2dbe1f12e1bbc92874c67ea99c9a84a9ed
<mask token>
<mask token> for card in cards: try: number = int(card) if number % 2 == 0: print(card, 'is an even card.') except ValueError: print(card, 'can not be divided')
cards = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'] for card in cards: try: number = int(card) if number % 2 == 0: print(card, 'is an even card.') except ValueError: print(card, 'can not be divided')
# print all cards with even numbers. cards = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"] for card in cards: try: number = int(card) if number % 2 == 0: # modulo operator print(card, "is an even card.") except ValueError: print (card, "can not be divi...
null
[ 0, 1, 2, 3 ]
20
a045423edd94d985dfc9660bcfe4a88c61bf4574
#Script start print"This is the two number subtraction python program." a = 9 b = 2 c = a - b print c # Scrip close
null
null
null
null
[ 0 ]
21
13c9f0f58ec6da317c3802f594bb0db7c275dee9
<mask token> def create_training_data(): for category in CATEGORIES: path = os.path.join(DATADIR, category) classIndex = CATEGORIES.index(category) for img in os.listdir(path): try: img_array = cv2.imread(os.path.join(path, img), cv2. IMREAD_...
<mask token> for category in CATEGORIES: path = os.path.join(DATADIR, category) for img in os.listdir(path): img_array = cv2.imread(os.path.join(path, img), cv2.IMREAD_COLOR) plt.imshow(img_array, cmap='gray') plt.show() print(img_array) print(img_array.shape) bre...
<mask token> DATADIR = 'content/PetImages' CATEGORIES = ['Cat', 'Dog'] img_array = [] for category in CATEGORIES: path = os.path.join(DATADIR, category) for img in os.listdir(path): img_array = cv2.imread(os.path.join(path, img), cv2.IMREAD_COLOR) plt.imshow(img_array, cmap='gray') plt.s...
<mask token> import numpy as np import matplotlib.pyplot as plt import os import cv2 import pickle import random import datetime import tensorflow as tf from tensorflow.python.keras.datasets import cifar10 from tensorflow.python.keras.preprocessing.image import ImageDataGenerator from tensorflow.python.keras.models imp...
''' !pip install wget from zipfile import ZipFile import wget print('Beginning file downlaod with wget module') url = 'https://download.microsoft.com/download/3/E/1/3E1C3F21-ECDB-4869-8368-6DEBA77B919F/kagglecatsanddogs_3367a.zip' wget.download(url, 'sample_data/') print('2. Extract all files in ZIP to different dir...
[ 1, 3, 4, 5, 6 ]
22
95c5971a102fb2ed84ab0de0471278d0167d8359
<mask token>
<mask token> def matrix_divided(matrix, div): """Divides a Matrix Args: matrix: A list of lists of ints or floats div: a non zero int or float Exceptions: TypeError: if the matrix and/or div is not as stated or the matrix elements are not of the same size ZeroDivisionError...
#!/usr/bin/python3 """1. Divide a matrix """ def matrix_divided(matrix, div): """Divides a Matrix Args: matrix: A list of lists of ints or floats div: a non zero int or float Exceptions: TypeError: if the matrix and/or div is not as stated or the matrix elements are not of the...
null
null
[ 0, 1, 2 ]
23
5fb998fa761b989c6dd423634824197bade4f8a5
<mask token>
<mask token> def abbreviation(a, b): m, n = len(a), len(b) dp = [([False] * (m + 1)) for _ in range(n + 1)] dp[0][0] = True for i in range(n + 1): for j in range(1, m + 1): if a[j - 1] == b[i - 1]: dp[i][j] = dp[i - 1][j - 1] elif a[j - 1].upper() == b[i...
<mask token> def abbreviation(a, b): m, n = len(a), len(b) dp = [([False] * (m + 1)) for _ in range(n + 1)] dp[0][0] = True for i in range(n + 1): for j in range(1, m + 1): if a[j - 1] == b[i - 1]: dp[i][j] = dp[i - 1][j - 1] elif a[j - 1].upper() == b[i...
<mask token> import math import os import random import re import sys def abbreviation(a, b): m, n = len(a), len(b) dp = [([False] * (m + 1)) for _ in range(n + 1)] dp[0][0] = True for i in range(n + 1): for j in range(1, m + 1): if a[j - 1] == b[i - 1]: dp[i][j] = ...
""" You can perform the following operations on the string, : Capitalize zero or more of 's lowercase letters. Delete all of the remaining lowercase letters in . Given two strings, and , determine if it's possible to make equal to as described. If so, print YES on a new line. Otherwise, print NO. For example, give...
[ 0, 1, 2, 3, 4 ]
24
5ed439a2a7cfb9c941c40ea0c5eba2851a0f2855
<mask token> class Stack(object): def __init__(self): self.arr = [] def push(self, val): self.arr.append(val) def pop(self): if len(self.arr): return self.arr.pop() def inc(self, e, k): count = min(len(self.arr), e) for i in range(count): ...
<mask token> class Stack(object): def __init__(self): self.arr = [] def push(self, val): self.arr.append(val) def pop(self): if len(self.arr): return self.arr.pop() def inc(self, e, k): count = min(len(self.arr), e) for i in range(count): ...
<mask token> class Stack(object): def __init__(self): self.arr = [] def push(self, val): self.arr.append(val) def pop(self): if len(self.arr): return self.arr.pop() def inc(self, e, k): count = min(len(self.arr), e) for i in range(count): ...
<mask token> class Stack(object): def __init__(self): self.arr = [] def push(self, val): self.arr.append(val) def pop(self): if len(self.arr): return self.arr.pop() def inc(self, e, k): count = min(len(self.arr), e) for i in range(count): ...
#!/bin/python3 # Implement a stack with push, pop, inc(e, k) operations # inc (e,k) - Add k to each of bottom e elements import sys class Stack(object): def __init__(self): self.arr = [] def push(self, val): self.arr.append(val) def pop(self): if len(self.arr): return...
[ 5, 6, 7, 8, 10 ]
25
39f9341313e29a22ec5e05ce9371bf65e89c91bd
<mask token>
<mask token> for numbers in n_list: n_dict = {} for n in numbers: if n in n_dict: n_dict[n] += 1 else: n_dict[n] = 1 mode = [] if len(n_dict) == 1 or len(n_dict) == len(numbers): print(numbers, '= 없다') else: mode_count = max(n_dict.values()) ...
<mask token> n_list = [[12, 17, 19, 17, 23], [26, 37, 26, 37, 91], [28, 30, 32, 34, 144], [10, 10, 10, 10, 10]] for numbers in n_list: n_dict = {} for n in numbers: if n in n_dict: n_dict[n] += 1 else: n_dict[n] = 1 mode = [] if len(n_dict) == 1 or len(n_dict)...
""" 리스트에 있는 숫자들의 최빈값을 구하는 프로그램을 만들어라. [12, 17, 19, 17, 23] = 17 [26, 37, 26, 37, 91] = 26, 37 [28, 30, 32, 34, 144] = 없다 최빈값 : 자료의 값 중에서 가장 많이 나타난 값 ① 자료의 값이 모두 같거나 모두 다르면 최빈값은 없다. ② 자료의 값이 모두 다를 때, 도수가 가장 큰 값이 1개 이상 있으면 그 값은 모두 최빈값이다. """ n_list = [[12, 17, 19, 17, 23], [26, 37, 26, 37, 91], [28,...
null
[ 0, 1, 2, 3 ]
26
312cc666c88fcd22882c49598db8c5e18bd3dae1
<mask token>
<mask token> try: from Cython.Build import cythonize cython = True except ImportError: cython = False if platform == 'darwin': extra_compile_args = ['-O3', '-pthread', '-funroll-loops', '-std=c++0x', '-stdlib=libc++', '-mmacosx-version-min=10.7'] else: extra_compile_args = ['-O3', '-pthread'...
<mask token> cython = True try: from Cython.Build import cythonize cython = True except ImportError: cython = False if platform == 'darwin': extra_compile_args = ['-O3', '-pthread', '-funroll-loops', '-std=c++0x', '-stdlib=libc++', '-mmacosx-version-min=10.7'] else: extra_compile_args = ['-O...
from setuptools import setup, find_packages from setuptools.extension import Extension from sys import platform cython = True try: from Cython.Build import cythonize cython = True except ImportError: cython = False if platform == 'darwin': extra_compile_args = ['-O3', '-pthread', '-funroll-loops', '-std...
from setuptools import setup, find_packages from setuptools.extension import Extension from sys import platform cython = True try: from Cython.Build import cythonize cython = True except ImportError: cython = False # Define the C++ extension if platform == "darwin": extra_compile_args = ['-O3', '-pthread',...
[ 0, 1, 2, 3, 4 ]
27
2aec0581413d4fb0ffb4090231fde0fed974bf18
<mask token>
<mask token> with open('./roc.txt', 'r') as fin: with open('./roc_shuffle.txt', 'w') as fout: tmp = [] for k, line in enumerate(fin): i = k + 1 if i % 6 == 0: idx = [0] + np.random.permutation(range(1, 5)).tolist() for sen in np.take(tmp, idx)....
import numpy as np import random with open('./roc.txt', 'r') as fin: with open('./roc_shuffle.txt', 'w') as fout: tmp = [] for k, line in enumerate(fin): i = k + 1 if i % 6 == 0: idx = [0] + np.random.permutation(range(1, 5)).tolist() for sen i...
import numpy as np import random with open("./roc.txt", "r") as fin: with open("./roc_shuffle.txt", "w") as fout: tmp = [] for k, line in enumerate(fin): i = k + 1 if i % 6 == 0: idx = [0] + np.random.permutation(range(1,5)).tolist() for sen i...
null
[ 0, 1, 2, 3 ]
28
4f13e2858d9cf469f14026808142886e5c3fcc85
<mask token>
class Solution: <mask token> <mask token>
class Solution: def merge(self, nums1, m, nums2, n): """ Do not return anything, modify nums1 in-place instead. """ if n == 0: nums1 = nums1 if nums1[m - 1] <= nums2[0]: for i in range(n): nums1[m + i] = nums2[i] elif nums1[0] ...
class Solution: def merge(self, nums1, m, nums2, n): """ Do not return anything, modify nums1 in-place instead. """ if n == 0: nums1 = nums1 if nums1[m - 1] <= nums2[0]: for i in range(n): nums1[m + i] = nums2[i] elif nums1[0] ...
class Solution: def merge(self, nums1, m, nums2, n): """ Do not return anything, modify nums1 in-place instead. """ if n == 0: nums1 = nums1 if nums1[m-1] <= nums2[0]: for i in range(n): nums1[m+i] = nums2[i] ...
[ 0, 1, 2, 3, 4 ]
29
57967f36a45bb3ea62708bbbb5b2f4ddb0f4bb16
<mask token> def _mako_get_namespace(context, name): try: return context.namespaces[__name__, name] except KeyError: _mako_generate_namespaces(context) return context.namespaces[__name__, name] <mask token> def _mako_inherit(template, context): _mako_generate_namespaces(context...
<mask token> def _mako_get_namespace(context, name): try: return context.namespaces[__name__, name] except KeyError: _mako_generate_namespaces(context) return context.namespaces[__name__, name] def _mako_generate_namespaces(context): pass def _mako_inherit(template, context): ...
<mask token> UNDEFINED = runtime.UNDEFINED __M_dict_builtin = dict __M_locals_builtin = locals _magic_number = 10 _modified_time = 1428612037.145222 _enable_loop = True _template_filename = ( 'C:\\Users\\Cody\\Desktop\\Heritage\\chf\\templates/account.rentalcart.html' ) _template_uri = '/account.rentalcart.html...
from mako import runtime, filters, cache UNDEFINED = runtime.UNDEFINED __M_dict_builtin = dict __M_locals_builtin = locals _magic_number = 10 _modified_time = 1428612037.145222 _enable_loop = True _template_filename = ( 'C:\\Users\\Cody\\Desktop\\Heritage\\chf\\templates/account.rentalcart.html' ) _template_uri...
# -*- coding:ascii -*- from mako import runtime, filters, cache UNDEFINED = runtime.UNDEFINED __M_dict_builtin = dict __M_locals_builtin = locals _magic_number = 10 _modified_time = 1428612037.145222 _enable_loop = True _template_filename = 'C:\\Users\\Cody\\Desktop\\Heritage\\chf\\templates/account.rentalcart.html' _t...
[ 3, 5, 6, 7, 8 ]
30
5771f49ad5254588f1683a8d45aa81ce472bb562
def prime_sieve(n): if n==2: return [2] elif n<2: return [] s=range(3,n+1,2) mroot = n ** 0.5 half=(n+1)/2-1 i=0 m=3 while m <= mroot: if s[i]: j=(m*m-3)/2 s[j]=0 while j<half: s[j]=0 j+=m i=i+1 m=2*i+3 return [2]+[x for x in s if x] ps = prime_sieve(1000000) def get_primes_upto(n): ...
null
null
null
null
[ 0 ]
31
44d87f112ab60a202e4c8d64d7aec6f4f0d10578
<mask token> class IssueTitleFactory(factory.Factory): """ ``issue`` must be provided """ FACTORY_FOR = models.IssueTitle language = factory.SubFactory(LanguageFactory) title = u'Bla' class IssueFactory(factory.Factory): FACTORY_FOR = models.Issue total_documents = 16 number = fa...
<mask token> class GroupFactory(factory.Factory): <mask token> <mask token> class SubjectCategoryFactory(factory.Factory): FACTORY_FOR = models.SubjectCategory term = 'Acoustics' class StudyAreaFactory(factory.Factory): FACTORY_FOR = models.StudyArea study_area = 'Health Sciences' class ...
<mask token> class UserFactory(factory.Factory): <mask token> @classmethod def _setup_next_sequence(cls): try: return cls._associated_class.objects.values_list('id', flat=True ).order_by('-id')[0] + 1 except IndexError: return 0 <mask token> ...
<mask token> _HERE = os.path.dirname(os.path.abspath(__file__)) with open(os.path.join(_HERE, 'xml_samples', '0034-8910-rsp-48-2-0216.xml') ) as xml_file: SAMPLE_XML = xml_file.read() SAMPLE_TIFF_IMAGE = open(os.path.join(_HERE, 'image_test', 'sample_tif_image.tif')) with open(os.path.join(_HERE, 'xml_sampl...
# coding: utf-8 import os import factory import datetime from journalmanager import models from django.contrib.auth.models import Group from django.core.files.base import File _HERE = os.path.dirname(os.path.abspath(__file__)) with open(os.path.join(_HERE, 'xml_samples', '0034-8910-rsp-48-2-0216.xml')) as xml_fil...
[ 22, 39, 42, 45, 47 ]
32
81dfdf0479fc1f136fa5153840d8c7015f9db676
<mask token>
<mask token> loops(loop, phoneNumber, message)
<mask token> phoneNumber = 'fill the number' message = 'fill with ur message' loop = 1 loops(loop, phoneNumber, message)
from theMachine import loops phoneNumber = 'fill the number' message = 'fill with ur message' loop = 1 loops(loop, phoneNumber, message)
# required !!! # pip install selenium # pip install webdriver-manager from theMachine import loops # fill the number and message # you can fill the number with array phoneNumber = "fill the number" message = "fill with ur message" loop = 1 # this how many u want to loop loops(loop, phoneNumber, message)...
[ 0, 1, 2, 3, 4 ]
33
24de4f486d4e976850e94a003f8d9cbe3e518402
<mask token>
<mask token> for x in a: b.append(int(x)) print(b) <mask token> for i in range(l): s = len(b[:i]) for j in range(s): if b[s] < b[j]: c = b[s] b.pop(s) b.insert(b.index(b[j]), c) print(b, b[:i], b[s])
a = input('Enter number') a = a.split() b = [] for x in a: b.append(int(x)) print(b) l = len(b) c = 0 s = 0 for i in range(l): s = len(b[:i]) for j in range(s): if b[s] < b[j]: c = b[s] b.pop(s) b.insert(b.index(b[j]), c) print(b, b[:i], b[s])
a= input("Enter number") a= a.split() b=[] for x in a: b.append(int(x)) print(b) l=len(b) c=0 s=0 for i in range(l): s=len(b[:i]) for j in range(s): if b[s]<b[j]: c=b[s] b.pop(s) b.insert(b.index(b[j]),c) print(b,b[:i],b[s])
null
[ 0, 1, 2, 3 ]
34
0ecd2a298203365b20b2369a99c3c1d7c0646f19
# coding: utf-8 #ack program with the ackermann_function """ ackermann_function """ def ack(m,n): #n+1 if m = 0 if m is 0: return n + 1 #A(m−1, 1) if m > 0 and n = 0 if m > 0 and n is 0: return ack(m-1, 1) #A(m−1, A(m, n−1)) if m > 0 and n > 0 if m > 0 and n > 0: re...
null
null
null
null
[ 0 ]
35
a98be930058269a6adbc9a28d1c0ad5d9abba136
<mask token> def nums(phrase, morph=pymorphy2.MorphAnalyzer()): """ согласование существительных с числительными, стоящими перед ними """ phrase = phrase.replace(' ', ' ').replace(',', ' ,') numeral = '' new_phrase = [] for word in phrase.split(' '): if 'NUMB' in morph.parse(word)[0].tag:...
<mask token> def play_wav(src): wav = pyglet.media.load(sys.path[0] + '\\src\\wav\\' + src + '.wav') wav.play() time.sleep(wav.duration) <mask token> def nums(phrase, morph=pymorphy2.MorphAnalyzer()): """ согласование существительных с числительными, стоящими перед ними """ phrase = phrase.rep...
<mask token> def play_wav(src): wav = pyglet.media.load(sys.path[0] + '\\src\\wav\\' + src + '.wav') wav.play() time.sleep(wav.duration) def play_wav_inline(src): wav = pyglet.media.load(sys.path[0] + '\\src\\wav\\' + src + '.wav') wav.play() <mask token> def nums(phrase, morph=pymorphy2.Mor...
import sys import time import pymorphy2 import pyglet import pyttsx3 import threading import warnings import pytils warnings.filterwarnings('ignore') <mask token> rounds, breaths, hold = 4, 30, 13 def play_wav(src): wav = pyglet.media.load(sys.path[0] + '\\src\\wav\\' + src + '.wav') wav.play() time.sleep...
import sys import time import pymorphy2 import pyglet import pyttsx3 import threading import warnings import pytils warnings.filterwarnings("ignore") """ Количество раундов, вдохов в раунде, задержка дыхания на вдохе""" rounds, breaths, hold = 4, 30, 13 def play_wav(src): wav = pyglet.media.load(sys.path[0] + '...
[ 10, 11, 13, 17, 18 ]
36
4f0933c58aa1d41faf4f949d9684c04f9e01b473
<mask token>
<mask token> print(f'copying from {from_file} to {to_file}') <mask token> print(f'the input file is {len(indata)} bytes long') print(f'does the output file exist? {exists(to_file)}') print('return to continue, CTRL-C to abort') input('?') open(to_file, 'w').write(indata) print('done!')
<mask token> from_file = input('form_file') to_file = input('to_file') print(f'copying from {from_file} to {to_file}') indata = open(from_file).read() print(f'the input file is {len(indata)} bytes long') print(f'does the output file exist? {exists(to_file)}') print('return to continue, CTRL-C to abort') input('?') open...
from os.path import exists from_file = input('form_file') to_file = input('to_file') print(f'copying from {from_file} to {to_file}') indata = open(from_file).read() print(f'the input file is {len(indata)} bytes long') print(f'does the output file exist? {exists(to_file)}') print('return to continue, CTRL-C to abort') i...
from os.path import exists from_file = input('form_file') to_file = input('to_file') print(f"copying from {from_file} to {to_file}") indata = open(from_file).read()#这种方式读取文件后无需close print(f"the input file is {len(indata)} bytes long") print(f"does the output file exist? {exists(to_file)}") print("return to continue,...
[ 0, 1, 2, 3, 4 ]
37
5c81ddbc8f5a162949a100dbef1c69551d9e267a
<mask token>
<mask token> class MyTestCase(TestCase): def test_mark_done(self): user = User.objects.create_user(email='user@…', username='user', password='somepasswd') todo = Todo(title='SomeTitle', description='SomeDescr', owner=user) res = todo.mark_done(user) self.assertTrue(res...
<mask token> class MyTestCase(TestCase): def test_mark_done(self): user = User.objects.create_user(email='user@…', username='user', password='somepasswd') todo = Todo(title='SomeTitle', description='SomeDescr', owner=user) res = todo.mark_done(user) self.assertTrue(res...
from django.test import TestCase from django.contrib.auth.models import User from ..models import Todo class MyTestCase(TestCase): def test_mark_done(self): user = User.objects.create_user(email='user@…', username='user', password='somepasswd') todo = Todo(title='SomeTitle', descripti...
# -*- coding: utf-8 -*- from django.test import TestCase from django.contrib.auth.models import User from ..models import Todo class MyTestCase(TestCase): def test_mark_done(self): user = User.objects.create_user(email='user@…', username='user', password='somepasswd') todo = Todo(title='SomeTitl...
[ 0, 2, 3, 4, 5 ]
38
509129052f97bb32b4ba0e71ecd7b1061d5f8da2
<mask token>
print(180 / 4)
null
null
null
[ 0, 1 ]
39
2c90c4e0b42a75d6d387b9b2d0118d8e991b5a08
<mask token> class BaseDBMgr: def get_page(self, cls_: BaseMixin, filters: set, orders: Orders=list(), field: tuple=(), page: int=1, per_page: int=10) ->dict: """获取分页数据 @param BaseMixin cls 数据库模型实体类 @param set filters 查询条件 @param str order 排序 @param tuple field 返回字...
<mask token> class BaseDBMgr: def get_page(self, cls_: BaseMixin, filters: set, orders: Orders=list(), field: tuple=(), page: int=1, per_page: int=10) ->dict: """获取分页数据 @param BaseMixin cls 数据库模型实体类 @param set filters 查询条件 @param str order 排序 @param tuple field 返回字...
<mask token> class BaseDBMgr: def get_page(self, cls_: BaseMixin, filters: set, orders: Orders=list(), field: tuple=(), page: int=1, per_page: int=10) ->dict: """获取分页数据 @param BaseMixin cls 数据库模型实体类 @param set filters 查询条件 @param str order 排序 @param tuple field 返回字...
<mask token> Orders = List[Set(str, Union(str, int, decimal.Decimal))] class BaseDBMgr: def get_page(self, cls_: BaseMixin, filters: set, orders: Orders=list(), field: tuple=(), page: int=1, per_page: int=10) ->dict: """获取分页数据 @param BaseMixin cls 数据库模型实体类 @param set filters 查询条件 ...
import math import decimal from typing import Union, List, Set from sqlalchemy import text from .model import BaseMixin from ..core.db import db Orders = List[Set(str, Union(str, int, decimal.Decimal))] class BaseDBMgr: def get_page(self, cls_:BaseMixin, filters:set, orders:Orders=list(), field:tuple=(), pag...
[ 3, 7, 8, 9, 11 ]
40
cb2e800cc2802031847b170a462778e5c0b3c6f9
<mask token> class State(object): def __init__(self, i, j, is_cliff=False, is_goal=False): self.i = i self.j = j self.is_cliff = is_cliff self.is_goal = is_goal self.q_values = np.array([0.0, 0.0, 0.0, 0.0]) def __str__(self): return '({}, {})'.format(self.i, ...
<mask token> class State(object): def __init__(self, i, j, is_cliff=False, is_goal=False): self.i = i self.j = j self.is_cliff = is_cliff self.is_goal = is_goal self.q_values = np.array([0.0, 0.0, 0.0, 0.0]) def __str__(self): return '({}, {})'.format(self.i, ...
<mask token> N_ROWS = 6 N_COLUMNS = 10 class State(object): def __init__(self, i, j, is_cliff=False, is_goal=False): self.i = i self.j = j self.is_cliff = is_cliff self.is_goal = is_goal self.q_values = np.array([0.0, 0.0, 0.0, 0.0]) def __str__(self): return ...
from math import * from numpy import * from random import * import numpy as np import matplotlib.pyplot as plt from colorama import Fore, Back, Style from gridworld import q_to_arrow N_ROWS = 6 N_COLUMNS = 10 class State(object): def __init__(self, i, j, is_cliff=False, is_goal=False): self.i = i ...
from math import * from numpy import * from random import * import numpy as np import matplotlib.pyplot as plt from colorama import Fore, Back, Style from gridworld import q_to_arrow N_ROWS = 6 N_COLUMNS = 10 class State(object): def __init__(self, i, j, is_cliff=False, is_goal=False): self.i = i ...
[ 14, 16, 20, 21, 22 ]
41
52da8608e43b2d8dfe00f0956a1187fcf2e7b1ff
<mask token>
<mask token> class Migration(migrations.Migration): <mask token> <mask token>
<mask token> class Migration(migrations.Migration): dependencies = [('DHOPD', '0015_auto_20200515_0126')] operations = [migrations.CreateModel(name='Patient_c', fields=[( 'patient_id', models.AutoField(max_length=200, primary_key=True, serialize=False)), ('patient_fname', models.CharField(max_...
import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [('DHOPD', '0015_auto_20200515_0126')] operations = [migrations.CreateModel(name='Patient_c', fields=[( 'patient_id', models.AutoField(max_length=200, primary_key=True, serialize=Fals...
# Generated by Django 2.2.6 on 2020-05-21 09:44 import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('DHOPD', '0015_auto_20200515_0126'), ] operations = [ migrations.CreateModel( name='Patient_c', field...
[ 0, 1, 2, 3, 4 ]
42
1084478226777b9259274e053984ac34d461198d
<mask token> class TreePrinter: @addToClass(Node) def printTree(self, indent=0): raise Exception('printTree not defined in class ' + self.__class__. __name__) @addToClass(Instruction) def printTree(self, indent=0): print_intended(self.type, indent) <mask token> @...
<mask token> class TreePrinter: @addToClass(Node) def printTree(self, indent=0): raise Exception('printTree not defined in class ' + self.__class__. __name__) @addToClass(Instruction) def printTree(self, indent=0): print_intended(self.type, indent) @addToClass(Expres...
<mask token> class TreePrinter: @addToClass(Node) def printTree(self, indent=0): raise Exception('printTree not defined in class ' + self.__class__. __name__) @addToClass(Instruction) def printTree(self, indent=0): print_intended(self.type, indent) @addToClass(Expres...
<mask token> def addToClass(cls): def decorator(func): setattr(cls, func.__name__, func) return func return decorator def print_intended(to_print, intend): print(intend * '| ' + to_print) class TreePrinter: @addToClass(Node) def printTree(self, indent=0): raise Excep...
from .ast import * # noinspection PyPep8Naming def addToClass(cls): def decorator(func): setattr(cls, func.__name__, func) return func return decorator def print_intended(to_print, intend): print(intend * "| " + to_print) # noinspection PyPep8Naming,PyUnresolvedReferences class TreeP...
[ 18, 21, 22, 24, 26 ]
43
999de0965efa3c1fe021142a105dcf28184cd5ba
<mask token>
<mask token> def parse(query): print('parsing the query...') query = dnf_converter.convert(query) cp_clause_list = [] clause_list = [] for cp in query['$or']: clauses = [] if '$and' in cp: for clause in cp['$and']: clauses.append(clause) ...
import dnf_converter def parse(query): print('parsing the query...') query = dnf_converter.convert(query) cp_clause_list = [] clause_list = [] for cp in query['$or']: clauses = [] if '$and' in cp: for clause in cp['$and']: clauses.append(clause) ...
import dnf_converter def parse(query): print("parsing the query...") query = dnf_converter.convert(query) cp_clause_list = [] clause_list = [] for cp in query["$or"]: clauses = [] if "$and" in cp: for clause in cp["$and"]: clauses.append(clause) clause_list.append(clause) else: clause = cp ...
null
[ 0, 1, 2, 3 ]
44
cb08f64d1ad7e53f1041684d4ca4ef65036c138d
<mask token> def is_element(el, tag): return isinstance(el, Tag) and el.name == tag class ElemIterator: def __init__(self, els): self.els = els self.i = 0 def peek(self): try: return self.els[self.i] except IndexError: return None def __next...
<mask token> def is_element(el, tag): return isinstance(el, Tag) and el.name == tag class ElemIterator: def __init__(self, els): self.els = els self.i = 0 def peek(self): try: return self.els[self.i] except IndexError: return None def __next...
<mask token> def is_element(el, tag): return isinstance(el, Tag) and el.name == tag class ElemIterator: def __init__(self, els): self.els = els self.i = 0 def peek(self): try: return self.els[self.i] except IndexError: return None def __next...
import json import re from bs4 import BeautifulSoup from bs4.element import NavigableString, Tag from common import dir_path def is_element(el, tag): return isinstance(el, Tag) and el.name == tag class ElemIterator: def __init__(self, els): self.els = els self.i = 0 def peek(self): ...
import json import re from bs4 import BeautifulSoup from bs4.element import NavigableString, Tag from common import dir_path def is_element(el, tag): return isinstance(el, Tag) and el.name == tag class ElemIterator(): def __init__(self, els): self.els = els self.i = 0 def peek(self): try: ...
[ 10, 12, 14, 15, 16 ]
45
5082182af5a08970568dc1ab7a53ee5337260687
<mask token>
<mask token> if __name__ == '__main__': import matplotlib.pyplot as plt import numpy as np try: from viscm import viscm viscm(romaO_map) except ImportError: print('viscm not found, falling back on simple display') plt.imshow(np.linspace(0, 100, 256)[None, :], aspect='auto...
<mask token> cm_data = [[0.45137, 0.22346, 0.34187], [0.45418, 0.22244, 0.3361], [ 0.45696, 0.22158, 0.33043], [0.45975, 0.2209, 0.32483], [0.46251, 0.22035, 0.31935], [0.46527, 0.21994, 0.31394], [0.46803, 0.21968, 0.30862], [0.47078, 0.21958, 0.30337], [0.47352, 0.21962, 0.29822], [ 0.47628, 0.21982...
from matplotlib.colors import LinearSegmentedColormap cm_data = [[0.45137, 0.22346, 0.34187], [0.45418, 0.22244, 0.3361], [ 0.45696, 0.22158, 0.33043], [0.45975, 0.2209, 0.32483], [0.46251, 0.22035, 0.31935], [0.46527, 0.21994, 0.31394], [0.46803, 0.21968, 0.30862], [0.47078, 0.21958, 0.30337], [0.47352, ...
# # romaO # www.fabiocrameri.ch/colourmaps from matplotlib.colors import LinearSegmentedColormap cm_data = [[0.45137, 0.22346, 0.34187], [0.45418, 0.22244, 0.3361], [0.45696, 0.22158, 0.33043], [0.45975, 0.2209, 0.32483], ...
[ 0, 1, 2, 3, 4 ]
46
3dd4b4d4241e588cf44230891f496bafb30c6153
<mask token>
<mask token> print(df.head())
<mask token> n1 = 'ADS' api_url = 'https://www.quandl.com/api/v3/datasets/WIKI/%s.csv' % n1 df = pd.read_csv(api_url) df = df.head(100) print(df.head())
import requests import json import pandas as pd n1 = 'ADS' api_url = 'https://www.quandl.com/api/v3/datasets/WIKI/%s.csv' % n1 df = pd.read_csv(api_url) df = df.head(100) print(df.head())
import requests import json import pandas as pd n1 = 'ADS' api_url = 'https://www.quandl.com/api/v3/datasets/WIKI/%s.csv' % n1 df = pd.read_csv(api_url) df = df.head(100) print(df.head()) #print(list(data))
[ 0, 1, 2, 3, 4 ]
47
a558b42106b036719fe38ee6efd1c5b933290f52
<mask token>
<mask token> connection.execute(stmt) func.update_annotations_db(Twitter_Sentiment_Analysis, connection, 'Export_csv5.csv')
<mask token> connection, Twitter_Sentiment_Analysis = func.Database_Acces( 'mysql://root@localhost/sentiment?charset=utf8mb4', 'utf8', 'Twitter_Sentiment_Analysis4') stmt = "SET NAMES 'UTF8';" connection.execute(stmt) func.update_annotations_db(Twitter_Sentiment_Analysis, connection, 'Export_csv5.csv')
from sqlalchemy import select, update from sqlalchemy import Table, Column, String, Integer, Float, Boolean, Date, BigInteger from sqlalchemy import create_engine, MetaData import API_and_Database_function as func import pandas as pd import re connection, Twitter_Sentiment_Analysis = func.Database_Acces( 'mysql://r...
#!/usr/local/bin/python # -*- coding: utf-8 -*- from sqlalchemy import select, update from sqlalchemy import Table, Column, String, Integer, Float, Boolean, Date, BigInteger from sqlalchemy import create_engine, MetaData import API_and_Database_function as func import pandas as pd import re connection, Twitter_Senti...
[ 0, 1, 2, 3, 4 ]
48
10d35ba3c04d9cd09e152c575e74b0382ff60572
<mask token> class GcodeSender(object): <mask token> <mask token> def __init__(self, **kwargs): super(GcodeSender, self).__init__(**kwargs) self._stop = threading.Event() self.parsing_thread = None self.command_queue = Queue() self.line_number = 1 self.plot...
<mask token> class GcodeSender(object): <mask token> <mask token> def __init__(self, **kwargs): super(GcodeSender, self).__init__(**kwargs) self._stop = threading.Event() self.parsing_thread = None self.command_queue = Queue() self.line_number = 1 self.plot...
<mask token> class GcodeSender(object): PEN_LIFT_PULSE = 1500 PEN_DROP_PULSE = 800 def __init__(self, **kwargs): super(GcodeSender, self).__init__(**kwargs) self._stop = threading.Event() self.parsing_thread = None self.command_queue = Queue() self.line_number = 1 ...
<mask token> PORT = '/dev/ttys005' SPEED = 4800.0 class GcodeSender(object): PEN_LIFT_PULSE = 1500 PEN_DROP_PULSE = 800 def __init__(self, **kwargs): super(GcodeSender, self).__init__(**kwargs) self._stop = threading.Event() self.parsing_thread = None self.command_queue = ...
from pydispatch import dispatcher import time import serial import threading from queue import Queue PORT='/dev/ttys005' #PORT='/dev/tty.usbmodem1461' SPEED=4800.0 class GcodeSender(object): PEN_LIFT_PULSE = 1500 PEN_DROP_PULSE = 800 def __init__(self, **kwargs): super(GcodeSender, self).__init_...
[ 9, 14, 15, 16, 18 ]
49
c105f06e302740e9b7be100df905852bb5610a2c
import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt import numpy as np import struct import wave scale = 0.01 wav = wave.open('output.wav', 'r') print 'channels %d'%wav.getnchannels() print 'smpl width %d'%wav.getsampwidth() print 'frame rate %f'%wav.getframerate() nframes = wav.getnframes() pri...
null
null
null
null
[ 0 ]
50
e1d0648825695584d3ea518db961a9178ea0c66a
<mask token> def china_lunar(): today = str(date.today()) today_list = today.split('-') lunar_day = lunar.getDayBySolar(int(datetime.datetime.now().year), int( datetime.datetime.now().month), int(datetime.datetime.now().day)) if lunar_day.Lleap: china_day = '农历:{0}月{1}'.format(ymc[luna...
<mask token> def china_lunar(): today = str(date.today()) today_list = today.split('-') lunar_day = lunar.getDayBySolar(int(datetime.datetime.now().year), int( datetime.datetime.now().month), int(datetime.datetime.now().day)) if lunar_day.Lleap: china_day = '农历:{0}月{1}'.format(ymc[luna...
<mask token> ymc = [u'十一', u'十二', u'正', u'二', u'三', u'四', u'五', u'六', u'七', u'八', u'九', u'十' ] rmc = [u'初一', u'初二', u'初三', u'初四', u'初五', u'初六', u'初七', u'初八', u'初九', u'初十', u'十一', u'十二', u'十三', u'十四', u'十五', u'十六', u'十七', u'十八', u'十九', u'二十', u'廿一', u'廿二', u'廿三', u'廿四', u'廿五', u'廿六', u'廿七', u'廿八', u'廿九', u'三...
import requests import sxtwl import datetime from datetime import date import lxml from lxml import etree ymc = [u'十一', u'十二', u'正', u'二', u'三', u'四', u'五', u'六', u'七', u'八', u'九', u'十' ] rmc = [u'初一', u'初二', u'初三', u'初四', u'初五', u'初六', u'初七', u'初八', u'初九', u'初十', u'十一', u'十二', u'十三', u'十四', u'十五', u'十六', u'十七'...
import requests import sxtwl import datetime from datetime import date import lxml from lxml import etree # 日历中文索引 ymc = [u"十一", u"十二", u"正", u"二", u"三", u"四", u"五", u"六", u"七", u"八", u"九", u"十"] rmc = [u"初一", u"初二", u"初三", u"初四", u"初五", u"初六", u"初七", u"初八", u"初九", u"初十", \ u"十一", u"十二", u"十三", u"十四", u"十五", u"十...
[ 4, 6, 7, 8, 9 ]
51
2c39660da8fe839c4634cd73ce069acc7b1b29b4
<mask token>
<mask token> @measure_time_of_func def fib(n): sequence = [1, 1] for i in range(2, n, 1): sequence.append(sequence[i - 1] + sequence[i - 2]) return sequence
<mask token> def measure_time_of_func(func): def wrapper_func(n): start_time = time.time() fib_seq = func(n) end_time = time.time() return fib_seq, end_time - start_time return wrapper_func @measure_time_of_func def fib(n): sequence = [1, 1] for i in range(2, n, 1): ...
import time def measure_time_of_func(func): def wrapper_func(n): start_time = time.time() fib_seq = func(n) end_time = time.time() return fib_seq, end_time - start_time return wrapper_func @measure_time_of_func def fib(n): sequence = [1, 1] for i in range(2, n, 1): ...
import time # Decorator def measure_time_of_func(func): def wrapper_func(n): start_time = time.time() fib_seq = func(n) end_time = time.time() return (fib_seq, end_time - start_time) return wrapper_func # Returns a list with first n numbers of fibonacci sequence. @measure_ti...
[ 0, 1, 2, 3, 4 ]
52
c87e6f8780bf8d9097f200c7f2f0faf55beb480c
<mask token> def transform_data2(fn, *args): for arg in args: print(fn(arg)) <mask token>
def transform_data(fn): print(fn(10)) <mask token> def transform_data2(fn, *args): for arg in args: print(fn(arg)) <mask token>
def transform_data(fn): print(fn(10)) <mask token> def transform_data2(fn, *args): for arg in args: print(fn(arg)) <mask token> def transform_data2(fn, *args): for arg in args: print('Result: {:^20.2f}'.format(fn(arg))) <mask token>
def transform_data(fn): print(fn(10)) transform_data(lambda data: data / 5) def transform_data2(fn, *args): for arg in args: print(fn(arg)) transform_data2(lambda data: data / 5, 10, 15, 22, 30) def transform_data2(fn, *args): for arg in args: print('Result: {:^20.2f}'.format(fn(arg)...
# 1 def transform_data(fn): print(fn(10)) # 2 transform_data(lambda data: data / 5) # 3 def transform_data2(fn, *args): for arg in args: print(fn(arg)) transform_data2(lambda data: data / 5, 10, 15, 22, 30) # 4 def transform_data2(fn, *args): for arg in args: print('Resu...
[ 1, 2, 3, 4, 5 ]
53
f4f08015b7638f4d6ea793350d5d19a3485978cd
<mask token> def get_objectives(data): """Get a list of all first chromosomes' objective values.""" objectives = [math.log(population[0]['objective']) for population in data] return objectives def get_new_values(values): """Record any changes higher. Its size is the same as its argument's.""" ne...
<mask token> def get_data(): """Read output file to get data.""" try: with open(CONS['OUTPUT_FILE'], 'r') as file: data = json.load(file)[1] return data except FileNotFoundError: print('Data file not found.') exit() def get_objectives(data): """Get a list ...
<mask token> def get_data(): """Read output file to get data.""" try: with open(CONS['OUTPUT_FILE'], 'r') as file: data = json.load(file)[1] return data except FileNotFoundError: print('Data file not found.') exit() def get_objectives(data): """Get a list ...
<mask token> import os import json import math import matplotlib as maplot import matplotlib.pyplot as pyplot from datetime import datetime from sub.inputprocess import CONSTANTS as CONS def get_data(): """Read output file to get data.""" try: with open(CONS['OUTPUT_FILE'], 'r') as file: d...
"""Plot the output data. """ # Standard library import os import json import math import matplotlib as maplot import matplotlib.pyplot as pyplot from datetime import datetime # User library from sub.inputprocess import CONSTANTS as CONS # **json.loads(json_data) def get_data(): """Read output file to get data."...
[ 2, 4, 5, 6, 7 ]
54
d2a153fffccd4b681eebce823e641e195197cde7
<mask token> class NamingConvention: <mask token> <mask token>
<mask token> class NamingConvention: <mask token> def __init__(self): namingconventions = os.path.join(os.path.dirname(os.path.dirname( __file__)), 'data', 'strings', 'namingconvention.json') namingconventions = json.load(open(namingconventions)) for key, value in namingco...
<mask token> class NamingConvention: """Imports naming conventions from the respective .json file and puts them into class variables. """ def __init__(self): namingconventions = os.path.join(os.path.dirname(os.path.dirname( __file__)), 'data', 'strings', 'namingconvention.json') ...
<mask token> import os import json class NamingConvention: """Imports naming conventions from the respective .json file and puts them into class variables. """ def __init__(self): namingconventions = os.path.join(os.path.dirname(os.path.dirname( __file__)), 'data', 'strings', 'nam...
""" Created on 02.09.2013 @author: Paul Schweizer @email: paulschweizer@gmx.net @brief: Holds all the namingconventions for pandora's box """ import os import json class NamingConvention(): """Imports naming conventions from the respective .json file and puts them into class variables. """ def __init...
[ 1, 2, 3, 4, 5 ]
55
aff1d702e591efcfc0fc93150a3fbec532408137
<mask token> class LampViewSet(viewsets.ModelViewSet): serializer_class = LampSerializer queryset = Lamp.objects.all() <mask token>
<mask token> class LampSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Lamp fields = '__all__' class LampViewSet(viewsets.ModelViewSet): serializer_class = LampSerializer queryset = Lamp.objects.all() <mask token>
<mask token> class LampSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Lamp fields = '__all__' class LampViewSet(viewsets.ModelViewSet): serializer_class = LampSerializer queryset = Lamp.objects.all() router = routers.DefaultRouter() router.register('lamps', L...
from rest_framework import serializers, viewsets, routers from lamp_control.models import Lamp class LampSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Lamp fields = '__all__' class LampViewSet(viewsets.ModelViewSet): serializer_class = LampSerializer queryset ...
from rest_framework import serializers, viewsets, routers from lamp_control.models import Lamp class LampSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Lamp fields = '__all__' class LampViewSet(viewsets.ModelViewSet): serializer_class = LampSerializer queryset ...
[ 2, 3, 5, 6, 7 ]
56
c6502ea2b32ad90c76b6dfaf3ee3218d029eba15
class NlpUtility: <mask token> def get_nouns(self, tokens): nouns = [] for word, pos in tokens: if pos == 'NN': nouns.push(word) <mask token> <mask token> def get_nouns(self, tokens): nouns = [] for word, pos in tokens: if pos...
class NlpUtility: <mask token> def get_nouns(self, tokens): nouns = [] for word, pos in tokens: if pos == 'NN': nouns.push(word) def get_verbs(self, tokens): verbs = [] for word, pos in tokens: if pos == 'VB': nouns.pu...
class NlpUtility: <mask token> def get_nouns(self, tokens): nouns = [] for word, pos in tokens: if pos == 'NN': nouns.push(word) def get_verbs(self, tokens): verbs = [] for word, pos in tokens: if pos == 'VB': nouns.pu...
class NlpUtility: """ Utility methods to get particular parts of speech from a token set """ def get_nouns(self, tokens): nouns = [] for word, pos in tokens: if pos == 'NN': nouns.push(word) def get_verbs(self, tokens): verbs = [] for word, po...
class NlpUtility(): """ Utility methods to get particular parts of speech from a token set """ def get_nouns(self, tokens): nouns = [] for word, pos in tokens: if pos == "NN": nouns.push(word) def get_verbs(self, tokens): verbs = [] for word, pos in tokens: if pos == "VB": nouns.push(word) ...
[ 4, 5, 6, 7, 8 ]
57
675fbdfd519d00ab10bf613e8abb7338e484fe65
<mask token>
<mask token> log.setLevel(logging.DEBUG) <mask token> stream_hander.setFormatter(formatter) log.addHandler(stream_hander)
<mask token> formatter = logging.Formatter('%(asctime)s [%(levelname)s] : %(message)s') log = logging.getLogger('othello') log.setLevel(logging.DEBUG) stream_hander = logging.StreamHandler() stream_hander.setFormatter(formatter) log.addHandler(stream_hander)
import logging formatter = logging.Formatter('%(asctime)s [%(levelname)s] : %(message)s') log = logging.getLogger('othello') log.setLevel(logging.DEBUG) stream_hander = logging.StreamHandler() stream_hander.setFormatter(formatter) log.addHandler(stream_hander)
import logging formatter = logging.Formatter("%(asctime)s [%(levelname)s] : %(message)s") log = logging.getLogger("othello") log.setLevel(logging.DEBUG) stream_hander = logging.StreamHandler() stream_hander.setFormatter(formatter) log.addHandler(stream_hander)
[ 0, 1, 2, 3, 4 ]
58
d7b45e76f150107cd62be160e8938f17dad90623
<mask token>
<mask token> with open('testfile_short1.csv', 'r') as original: data = original.read() for i in range(2): with open('testfile_short3.csv', 'a') as modified: modified.write(data)
import pandas as pd from sqlalchemy import create_engine with open('testfile_short1.csv', 'r') as original: data = original.read() for i in range(2): with open('testfile_short3.csv', 'a') as modified: modified.write(data)
import pandas as pd from sqlalchemy import create_engine # file = 'testfile.csv' # print(pd.read_csv(file, nrows=5)) with open('testfile_short1.csv', 'r') as original: data = original.read() for i in range(2): with open('testfile_short3.csv', 'a') as modified: modified.write(data)
null
[ 0, 1, 2, 3 ]
59
61454a3d6b5b17bff871ededc6ddfe8384043884
<mask token> class ItemEffect(AbstractItemEffect): <mask token> class BuffedByHealingWand(StatModifyingBuffEffect): def __init__(self): super().__init__(BUFF_TYPE, {HeroStat.HEALTH_REGEN: HEALTH_REGEN_BONUS} ) <mask token>
<mask token> class ItemEffect(AbstractItemEffect): def item_handle_event(self, event: Event, game_state: GameState): if isinstance(event, PlayerDamagedEnemy): game_state.player_state.gain_buff_effect(get_buff_effect( BUFF_TYPE), BUFF_DURATION) class BuffedByHealingWand(StatM...
<mask token> BUFF_TYPE = BuffType.BUFFED_BY_HEALING_WAND HEALTH_REGEN_BONUS = 1 BUFF_DURATION = Millis(5000) class ItemEffect(AbstractItemEffect): def item_handle_event(self, event: Event, game_state: GameState): if isinstance(event, PlayerDamagedEnemy): game_state.player_state.gain_buff_effe...
from pythongame.core.buff_effects import get_buff_effect, register_buff_effect, StatModifyingBuffEffect from pythongame.core.common import ItemType, Sprite, BuffType, Millis, HeroStat from pythongame.core.game_data import UiIconSprite, register_buff_text from pythongame.core.game_state import Event, PlayerDamagedEnemy,...
from pythongame.core.buff_effects import get_buff_effect, register_buff_effect, StatModifyingBuffEffect from pythongame.core.common import ItemType, Sprite, BuffType, Millis, HeroStat from pythongame.core.game_data import UiIconSprite, register_buff_text from pythongame.core.game_state import Event, PlayerDamagedEnemy,...
[ 3, 4, 6, 7, 8 ]
60
4c60fd123f591bf2a88ca0affe14a3c3ec0d3cf6
<mask token> def range_func(measures): scores = [] for entry in measures: try: curr = int(entry[1]) except: curr = None if curr is not None: scores.append(curr) if len(scores) < 1: return 0 return max(scores) - min(scores) <mask tok...
<mask token> def range_func(measures): scores = [] for entry in measures: try: curr = int(entry[1]) except: curr = None if curr is not None: scores.append(curr) if len(scores) < 1: return 0 return max(scores) - min(scores) <mask tok...
<mask token> sc = SparkContext('local', 'weblog app') effective_care = sc.textFile('file:///data/exercise1/effective_care').map( lambda l: l.encode().split(',')).map(lambda x: (x[0], x[1:])) procedure_care = effective_care.map(lambda p: (p[1][1], [p[0], p[1][2]])) procedure_care_grouped = procedure_care.groupByKey(...
from pyspark import SparkContext from pyspark.sql import SQLContext from pyspark.sql.types import * sc = SparkContext('local', 'weblog app') effective_care = sc.textFile('file:///data/exercise1/effective_care').map( lambda l: l.encode().split(',')).map(lambda x: (x[0], x[1:])) procedure_care = effective_care.map(la...
from pyspark import SparkContext from pyspark.sql import SQLContext from pyspark.sql.types import * sc = SparkContext("local", "weblog app") effective_care = sc.textFile('file:///data/exercise1/effective_care').map(lambda l:l.encode().split(',')).map(lambda x: (x[0], x[1:])) procedure_care = effective_care.map(lambda ...
[ 1, 2, 3, 4, 5 ]
61
4264cba9a6c39219d21bd21d4b21009bacd1db38
#!/usr/bin/python import operator import cgi, sys, LINK_HEADERS import simplejson as json from datetime import datetime from dateutil import tz from decimal import * sys.path.insert(0, str(LINK_HEADERS.DAO_LINK)) from transaction_dao import Transaction_dao from user_portfolio_dao import User_portfolio_dao from user_st...
null
null
null
null
[ 0 ]
62
5c30b0e952ddf2e05a7ad5f8d9bbd4f5e22f887d
<mask token>
<mask token> print(str1 and str2) <mask token> for c in str1: if c in str2: nPos = str1.index(c) break print(nPos)
str1 = '12345678' str2 = '456' print(str1 and str2) str1 = 'cekjgdklab' str2 = 'gka' nPos = -1 for c in str1: if c in str2: nPos = str1.index(c) break print(nPos)
# strspn(str1,str2) str1 = '12345678' str2 = '456' # str1 and chars both in str1 and str2 print(str1 and str2) str1 = 'cekjgdklab' str2 = 'gka' nPos = -1 for c in str1: if c in str2: nPos = str1.index(c) break print(nPos)
null
[ 0, 1, 2, 3 ]
63
a86b64ccd0dab4ab70ca9c2b7625fb34afec3794
<mask token> class SomeModelAdmin(SummernoteModelAdmin): <mask token> <mask token>
<mask token> class SomeModelAdmin(SummernoteModelAdmin): summernote_fields = '__all__' <mask token>
<mask token> class SomeModelAdmin(SummernoteModelAdmin): summernote_fields = '__all__' admin.site.register(ArticlePost, SummernoteModelAdmin)
from django.contrib import admin from django_summernote.admin import SummernoteModelAdmin from .models import ArticlePost class SomeModelAdmin(SummernoteModelAdmin): summernote_fields = '__all__' admin.site.register(ArticlePost, SummernoteModelAdmin)
from django.contrib import admin from django_summernote.admin import SummernoteModelAdmin from .models import ArticlePost # Register your models here. class SomeModelAdmin(SummernoteModelAdmin): # instead of ModelAdmin summernote_fields = '__all__' admin.site.register(ArticlePost, SummernoteModelAdmin)
[ 1, 2, 3, 4, 5 ]
64
f17d33f1d035da42dc9a2b4c0c60beefc6a48dea
<mask token> class TestExtractTrialData(unittest.TestCase): def setUp(self): self.main_path = Path(__file__).parent self.training_lt5 = {'path': self.main_path / 'data' / 'session_training_lt5'} self.biased_lt5 = {'path': self.main_path / 'data' / 'session_biased_l...
<mask token> class TestExtractTrialData(unittest.TestCase): def setUp(self): self.main_path = Path(__file__).parent self.training_lt5 = {'path': self.main_path / 'data' / 'session_training_lt5'} self.biased_lt5 = {'path': self.main_path / 'data' / 'session_biased_l...
<mask token> class TestExtractTrialData(unittest.TestCase): def setUp(self): self.main_path = Path(__file__).parent self.training_lt5 = {'path': self.main_path / 'data' / 'session_training_lt5'} self.biased_lt5 = {'path': self.main_path / 'data' / 'session_biased_l...
<mask token> class TestExtractTrialData(unittest.TestCase): def setUp(self): self.main_path = Path(__file__).parent self.training_lt5 = {'path': self.main_path / 'data' / 'session_training_lt5'} self.biased_lt5 = {'path': self.main_path / 'data' / 'session_biased_l...
import functools import shutil import tempfile import unittest import unittest.mock from pathlib import Path import numpy as np import pandas as pd import one.alf.io as alfio from ibllib.io.extractors import training_trials, biased_trials, camera from ibllib.io import raw_data_loaders as raw from ibllib.io.extractors...
[ 27, 34, 37, 45, 49 ]
65
767c0e6d956701fcedddb153b6c47f404dec535a
<mask token> class NetworkLookup: def __init__(self): self.loaded = 0 self.subnets = {} self.vpcs = {} def load(self): if self.loaded: return client = boto3.client('ec2') subnets_r = client.describe_subnets() subnets_list = subnets_r['Subne...
<mask token> class NetworkLookup: def __init__(self): self.loaded = 0 self.subnets = {} self.vpcs = {} def load(self): if self.loaded: return client = boto3.client('ec2') subnets_r = client.describe_subnets() subnets_list = subnets_r['Subne...
<mask token> class NetworkLookup: def __init__(self): self.loaded = 0 self.subnets = {} self.vpcs = {} def load(self): if self.loaded: return client = boto3.client('ec2') subnets_r = client.describe_subnets() subnets_list = subnets_r['Subne...
import boto3 class NetworkLookup: def __init__(self): self.loaded = 0 self.subnets = {} self.vpcs = {} def load(self): if self.loaded: return client = boto3.client('ec2') subnets_r = client.describe_subnets() subnets_list = subnets_r['Subne...
import boto3 class NetworkLookup: def __init__(self): self.loaded = 0 self.subnets = {} self.vpcs = {} def load(self): if self.loaded: return client = boto3.client('ec2') # load subnets subnets_r = client.describe_subnets() subnets_...
[ 6, 7, 9, 10, 11 ]
66
efcbe296ea72a94be967124a8ba8c84a524e2eb1
<mask token>
<mask token> def filter_pos_rec(lst): """ @type lst: LinkedListRec >>> lst = LinkedListRec([3, -10, 4, 0]) >>> pos = filter_pos_rec(lst) >>> str(pos) '3 -> 4' """ if lst.is_empty(): return lst else: pos_rec = LinkedListRec([]) if lst._first > 0: ...
__author__ = 'AChen' <mask token> def filter_pos_rec(lst): """ @type lst: LinkedListRec >>> lst = LinkedListRec([3, -10, 4, 0]) >>> pos = filter_pos_rec(lst) >>> str(pos) '3 -> 4' """ if lst.is_empty(): return lst else: pos_rec = LinkedListRec([]) if lst._f...
__author__ = 'AChen' from rec_linked_list import * def filter_pos_rec(lst): """ @type lst: LinkedListRec >>> lst = LinkedListRec([3, -10, 4, 0]) >>> pos = filter_pos_rec(lst) >>> str(pos) '3 -> 4' """ if lst.is_empty(): return lst else: pos_rec = LinkedListRec([]) ...
null
[ 0, 1, 2, 3 ]
67
4789546128263bd298f8f5827734f8402747b9ac
<mask token> class OutgoingNetworkInputBuffer(InputBuffer): <mask token> <mask token> class IncomingNetworkInputBuffer(InputBuffer): def __init__(self, frame_limit=12): super().__init__(left_action_name='', right_action_name='', weak_punch_action_name='', frame_limit=frame_limit) ...
<mask token> class InputBuffer: <mask token> class Value(Enum): LEFT = 'l' RIGHT = 'r' UP = 'u' DOWN = 'd' WEAK_PUNCH = 'wp' <mask token> def __str__(self): return f'{self._inputs}' <mask token> @property def values(self) ->list: ...
<mask token> class InputBuffer: <mask token> class Value(Enum): LEFT = 'l' RIGHT = 'r' UP = 'u' DOWN = 'd' WEAK_PUNCH = 'wp' def __init__(self, left_action_name: str, right_action_name: str, weak_punch_action_name: str, frame_limit=12): self._inpu...
<mask token> class InputBuffer: <mask token> class Value(Enum): LEFT = 'l' RIGHT = 'r' UP = 'u' DOWN = 'd' WEAK_PUNCH = 'wp' def __init__(self, left_action_name: str, right_action_name: str, weak_punch_action_name: str, frame_limit=12): self._inpu...
from enum import Enum from roll.input import Input from roll.network import Server, Client from assets.game_projects.fighter.src.game_properties import GameProperties from assets.game_projects.fighter.src.network_message import NetworkMessage class InputBuffer: """ Responsible for collecting game input from...
[ 5, 12, 13, 15, 21 ]
68
b693cc63e2ee4c994ef7b5e44faea99f15a021f6
<mask token> class QManeger(object): <mask token> <mask token> def listening(self): while True: traces = self.q_trace.get(block=True) for s, a, r in zip(traces[0], traces[1], traces[2]): self._push_one(s, a, r) if len(self.traces_s) > self.opt.b...
<mask token> class QManeger(object): def __init__(self, opt, q_trace, q_batch): self.traces_s = [] self.traces_a = [] self.traces_r = [] self.lock = mp.Lock() self.q_trace = q_trace self.q_batch = q_batch self.opt = opt self.device = torch.device('c...
<mask token> class QManeger(object): def __init__(self, opt, q_trace, q_batch): self.traces_s = [] self.traces_a = [] self.traces_r = [] self.lock = mp.Lock() self.q_trace = q_trace self.q_batch = q_batch self.opt = opt self.device = torch.device('c...
import torch import torch.multiprocessing as mp import random class QManeger(object): def __init__(self, opt, q_trace, q_batch): self.traces_s = [] self.traces_a = [] self.traces_r = [] self.lock = mp.Lock() self.q_trace = q_trace self.q_batch = q_batch sel...
import torch import torch.multiprocessing as mp import random class QManeger(object): def __init__(self, opt, q_trace, q_batch): self.traces_s = [] self.traces_a = [] self.traces_r = [] self.lock = mp.Lock() self.q_trace = q_trace self.q_batch = q_batch sel...
[ 2, 4, 5, 6, 7 ]
69
3c0beb7be29953ca2d7b390627305f4541b56efa
<mask token> def test_main_cnv(): main_cnv(tarfile) <mask token>
<mask token> sys.path.append('../circos_report/cnv_anno2conf') <mask token> def test_main_cnv(): main_cnv(tarfile) if __name__ == '__main__': test_main_cnv()
<mask token> sys.path.append('../circos_report/cnv_anno2conf') <mask token> tarfile = {'yaml': 'data/test_app.yaml'} def test_main_cnv(): main_cnv(tarfile) if __name__ == '__main__': test_main_cnv()
import sys sys.path.append('../circos_report/cnv_anno2conf') from cnv_anno2conf import main_cnv tarfile = {'yaml': 'data/test_app.yaml'} def test_main_cnv(): main_cnv(tarfile) if __name__ == '__main__': test_main_cnv()
import sys sys.path.append("../circos_report/cnv_anno2conf") from cnv_anno2conf import main_cnv tarfile = {"yaml": "data/test_app.yaml"} def test_main_cnv(): main_cnv(tarfile) if __name__ == "__main__": test_main_cnv()
[ 1, 2, 3, 4, 5 ]
70
8d0fcf0bf5effec9aa04e7cd56b4b7098c6713cb
<mask token>
for i in range(-10, 0): print(i, end=' ')
for i in range(-10,0): print(i,end=" ")
null
null
[ 0, 1, 2 ]
71
a14114f9bb677601e6d75a72b84ec128fc9bbe61
<mask token>
<mask token> urlpatterns = [path('admin/', admin.site.urls), path('api/', include( 'api.urls')), path('api/adv/', include('adventure.urls'))]
from django.contrib import admin from django.urls import path, include, re_path from django.conf.urls import include from rest_framework.authtoken import views urlpatterns = [path('admin/', admin.site.urls), path('api/', include( 'api.urls')), path('api/adv/', include('adventure.urls'))]
from django.contrib import admin from django.urls import path, include, re_path from django.conf.urls import include # from rest_framework import routers from rest_framework.authtoken import views # from adventure.api import PlayerViewSet, RoomViewSet # from adventure.api import move # router = routers.DefaultRoute...
null
[ 0, 1, 2, 3 ]
72
edb206a8cd5bc48e831142d5632fd7eb90abd209
import tensorflow as tf optimizer = tf.train.GradientDescentOptimizer(0.001).minimize(loss) _, l = sess.run([optimizer, loss], feed_dict={X:x, Y:y}) Session looks at all trainable variables that loss depends on and update them tf.Variable(initializer=None, trainable=True, collections=None, validate_shape=True, caching...
null
null
null
null
[ 0 ]
73
36991c3191ba48b1b9dbd843e279f8fe124f1339
<mask token> class Rouge(Character): def special_attack1(self, opponent, hitdamage_callback, specatt_callback): pass def special_attack2(self, opponent, hitdamage_callback, specatt_callback): pass <mask token> def regen_resource(self): pass def full_resource(self): ...
<mask token> class Rouge(Character): def special_attack1(self, opponent, hitdamage_callback, specatt_callback): pass def special_attack2(self, opponent, hitdamage_callback, specatt_callback): pass def heal(self, target): pass def regen_resource(self): pass def ...
__author__ = 'Jager' <mask token> class Rouge(Character): def special_attack1(self, opponent, hitdamage_callback, specatt_callback): pass def special_attack2(self, opponent, hitdamage_callback, specatt_callback): pass def heal(self, target): pass def regen_resource(self): ...
__author__ = 'Jager' from char import Character class Rouge(Character): def special_attack1(self, opponent, hitdamage_callback, specatt_callback): pass def special_attack2(self, opponent, hitdamage_callback, specatt_callback): pass def heal(self, target): pass def regen_res...
__author__ = 'Jager' from char import Character class Rouge (Character): def special_attack1(self, opponent, hitdamage_callback, specatt_callback): pass # hook method def special_attack2(self, opponent, hitdamage_callback, specatt_callback): pass # hook method def heal(self, target...
[ 5, 6, 7, 8, 9 ]
74
0de657ee173b606ad61d614a6168c00fcd571a70
<mask token>
<mask token> def test_convert_nc_2010_to_na_2310(): ffi_in, ffi_out = 2010, 2310 infile = os.path.join(cached_outputs, f'{ffi_in}.nc') outfile = os.path.join(test_outputs, f'{ffi_out}_from_nc_{ffi_in}.na') x = nappy.nc_interface.nc_to_na.NCToNA(infile, requested_ffi=ffi_out) x.writeNAFiles(outfile...
import os from .common import cached_outputs, data_files, test_outputs import nappy.nc_interface.na_to_nc import nappy.nc_interface.nc_to_na def test_convert_nc_2010_to_na_2310(): ffi_in, ffi_out = 2010, 2310 infile = os.path.join(cached_outputs, f'{ffi_in}.nc') outfile = os.path.join(test_outputs, f'{ffi...
import os from .common import cached_outputs, data_files, test_outputs import nappy.nc_interface.na_to_nc import nappy.nc_interface.nc_to_na def test_convert_nc_2010_to_na_2310(): ffi_in, ffi_out = (2010, 2310) infile = os.path.join(cached_outputs, f"{ffi_in}.nc") outfile = os.path.join(test_outputs, f...
null
[ 0, 1, 2, 3 ]
75
06638b361c1cbe92660d242969590dfa45b63a4d
<mask token>
<mask token> mathfont.save(f) <mask token> mathfont.save(f) <mask token> mathfont.save(f) <mask token> mathfont.save(f) <mask token> mathfont.save(f) <mask token> mathfont.save(f)
<mask token> v1 = 5 * mathfont.em v2 = 1 * mathfont.em f = mathfont.create('stack-bottomdisplaystyleshiftdown%d-axisheight%d' % ( v1, v2), 'Copyright (c) 2016 MathML Association') f.math.AxisHeight = v2 f.math.StackBottomDisplayStyleShiftDown = v1 f.math.StackBottomShiftDown = 0 f.math.StackDisplayStyleGapMin = 0 f...
from utils import mathfont import fontforge v1 = 5 * mathfont.em v2 = 1 * mathfont.em f = mathfont.create('stack-bottomdisplaystyleshiftdown%d-axisheight%d' % ( v1, v2), 'Copyright (c) 2016 MathML Association') f.math.AxisHeight = v2 f.math.StackBottomDisplayStyleShiftDown = v1 f.math.StackBottomShiftDown = 0 f.mat...
#!/usr/bin/env python3 from utils import mathfont import fontforge v1 = 5 * mathfont.em v2 = 1 * mathfont.em f = mathfont.create("stack-bottomdisplaystyleshiftdown%d-axisheight%d" % (v1, v2), "Copyright (c) 2016 MathML Association") f.math.AxisHeight = v2 f.math.StackBottomDisplayStyleShiftDown = ...
[ 0, 1, 2, 3, 4 ]
76
2dd59681a0dcb5d3f1143385100c09c7783babf4
<mask token>
<mask token> for line in ratings_dat: arr = line.split('::') new_line = '\t'.join(arr) ratings_csv.write(new_line) ratings_dat.close() ratings_csv.close()
ratings_dat = open('../data/movielens-1m/users.dat', 'r') ratings_csv = open('../data/movielens-1m/users.txt', 'w') for line in ratings_dat: arr = line.split('::') new_line = '\t'.join(arr) ratings_csv.write(new_line) ratings_dat.close() ratings_csv.close()
#!/usr/bin/env python # script :: creating a datamodel that fits mahout from ratings.dat ratings_dat = open('../data/movielens-1m/users.dat', 'r') ratings_csv = open('../data/movielens-1m/users.txt', 'w') for line in ratings_dat: arr = line.split('::') new_line = '\t'.join(arr) ratings_csv.write(new_line) rati...
null
[ 0, 1, 2, 3 ]
77
5ce98ae241c0982eeb1027ffcff5b770f94ff1a3
<mask token>
<mask token> with open('Civ VI Modding Companion - Events.csv', newline='') as csvfile: reader = csv.reader(csvfile, delimiter=',', quotechar='|') for row in reader: if i < 4: i += 1 continue eventName = row[3] eventType = 'GameEvents' if len(row[10]) > 0 else 'Ev...
<mask token> events = {} eventTypes = set() eventIndices = {} i = 0 with open('Civ VI Modding Companion - Events.csv', newline='') as csvfile: reader = csv.reader(csvfile, delimiter=',', quotechar='|') for row in reader: if i < 4: i += 1 continue eventName = row[3] ...
import csv import os events = {} eventTypes = set() eventIndices = {} i = 0 with open('Civ VI Modding Companion - Events.csv', newline='') as csvfile: reader = csv.reader(csvfile, delimiter=',', quotechar='|') for row in reader: if i < 4: i += 1 continue eventName = row[3...
import csv import os events = {} eventTypes = set() eventIndices = {} i = 0 with open('Civ VI Modding Companion - Events.csv', newline='') as csvfile: reader = csv.reader(csvfile, delimiter=',', quotechar='|') for row in reader: if i < 4: i += 1 continue eventName = row[3] eventType = "GameEvents" if...
[ 0, 1, 2, 3, 4 ]
78
79c043fc862e77bea5adc3f1c6bb9a6272f19c75
<mask token>
<mask token> name = socket.gethostname()
import socket name = socket.gethostname()
#!/usr/bin/env python import socket name = socket.gethostname()
null
[ 0, 1, 2, 3 ]
79
22c498d84f40455d89ed32ccf3bf8778cb159579
<mask token>
<mask token> if __name__ == '__main__': bestPrecision = [0, 0, 0, 0, 0, 0] bestPrecisionFile = ['', '', '', '', '', ''] bestRecall = [0, 0, 0, 0, 0, 0] bestRecallFile = ['', '', '', '', '', ''] bestSupport = [0, 0, 0, 0, 0, 0] bestSupportFile = ['', '', '', '', '', ''] bestF1_Score = [0, 0, ...
import os import pandas as pd from tabulate import tabulate if __name__ == '__main__': bestPrecision = [0, 0, 0, 0, 0, 0] bestPrecisionFile = ['', '', '', '', '', ''] bestRecall = [0, 0, 0, 0, 0, 0] bestRecallFile = ['', '', '', '', '', ''] bestSupport = [0, 0, 0, 0, 0, 0] bestSupportFile = ['',...
import os import pandas as pd from tabulate import tabulate if __name__ == '__main__': bestPrecision = [0,0,0,0,0,0] bestPrecisionFile = ['','','','','',''] bestRecall = [0,0,0,0,0,0] bestRecallFile = ['','','','','',''] bestSupport = [0,0,0,0,0,0] bestSupportFile = ['','','','','',''] bes...
null
[ 0, 1, 2, 3 ]
80
5b8c95354f8b27eff8226ace52ab9e97f98ae217
<mask token> class my_image_csv_dataset(Dataset): def __init__(self, data_dir, data, transforms_=None, obj=False, minorities=None, diffs=None, bal_tfms=None): self.data_dir = data_dir self.data = data self.transforms_ = transforms_ self.tfms = None self.obj = obj ...
<mask token> class my_image_csv_dataset(Dataset): def __init__(self, data_dir, data, transforms_=None, obj=False, minorities=None, diffs=None, bal_tfms=None): self.data_dir = data_dir self.data = data self.transforms_ = transforms_ self.tfms = None self.obj = obj ...
<mask token> class my_image_csv_dataset(Dataset): def __init__(self, data_dir, data, transforms_=None, obj=False, minorities=None, diffs=None, bal_tfms=None): self.data_dir = data_dir self.data = data self.transforms_ = transforms_ self.tfms = None self.obj = obj ...
<mask token> class my_image_csv_dataset(Dataset): def __init__(self, data_dir, data, transforms_=None, obj=False, minorities=None, diffs=None, bal_tfms=None): self.data_dir = data_dir self.data = data self.transforms_ = transforms_ self.tfms = None self.obj = obj ...
from dai_imports import* from obj_utils import* import utils class my_image_csv_dataset(Dataset): def __init__(self, data_dir, data, transforms_ = None, obj = False, minorities = None, diffs = None, bal_tfms = None): self.data_dir = data_dir self.data = data ...
[ 15, 16, 19, 25, 29 ]
81
64c32b3ada7fff51a7c4b07872b7688e100897d8
class Node(object): <mask token> class tree(object): def __init__(self): self.root = None def insert(self, root, value): if self.root == None: self.root = Node(value) elif value < root.data: if root.left is None: root.left = Node(value) ...
class Node(object): def __init__(self, data): self.data = data self.left = None self.right = None self.parent = None class tree(object): def __init__(self): self.root = None def insert(self, root, value): if self.root == None: self.root = Node...
class Node(object): def __init__(self, data): self.data = data self.left = None self.right = None self.parent = None class tree(object): def __init__(self): self.root = None def insert(self, root, value): if self.root == None: self.root = Node...
class Node(object): def __init__(self, data): self.data = data self.left = None self.right = None self.parent = None class tree(object): def __init__(self): self.root = None def insert(self, root, value): if self.root == None: self.root = Node...
class Node(object): def __init__(self,data): self.data = data self.left = None self.right = None self.parent = None class tree(object): def __init__(self): self.root = None def insert(self,root,value): if self.root == None: self.root = No...
[ 7, 8, 9, 10, 11 ]
82
88ec9484e934ce27b13734ca26f79df71b7677e6
<mask token>
<mask token> if len(sys.argv) < 2: print('Syntax : python %s <port>') % str(sys.argv[0]) else: print('-' * 55) print('HTB WEB-CHALLENGE coded by ZyperX [Freelance]') print('-' * 55) r = requests.session() port = str(sys.argv[1]) url = 'http://docker.hackthebox.eu:' url = url + port u...
<mask token> if len(sys.argv) < 2: print('Syntax : python %s <port>') % str(sys.argv[0]) else: print('-' * 55) print('HTB WEB-CHALLENGE coded by ZyperX [Freelance]') print('-' * 55) r = requests.session() port = str(sys.argv[1]) url = 'http://docker.hackthebox.eu:' url = url + port u...
import requests from bs4 import BeautifulSoup import sys import re if len(sys.argv) < 2: print('Syntax : python %s <port>') % str(sys.argv[0]) else: print('-' * 55) print('HTB WEB-CHALLENGE coded by ZyperX [Freelance]') print('-' * 55) r = requests.session() port = str(sys.argv[1]) url = 'ht...
import requests from bs4 import BeautifulSoup import sys import re if len(sys.argv)<2: print("Syntax : python %s <port>")%(str(sys.argv[0])) else: print('-'*55) print("HTB WEB-CHALLENGE coded by ZyperX [Freelance]") print('-'*55) r=requests.session() port=str(sys.argv[1]) url="http://docker.hackthebox.eu:" url=...
[ 0, 1, 2, 3, 4 ]
83
cd2e03666a890d6e9ea0fcb45fe28510d684916d
<mask token> def squeezed(client_name): return client_name.replace('Индивидуальный предприниматель', 'ИП') def get_kkm_filled_fn(max_fill=80): LOGIN_URL = 'https://pk.platformaofd.ru/auth/login' API_URL = 'https://pk.platformaofd.ru/api/monitoring' session = requests.Session() print('-= подключе...
<mask token> def squeezed(client_name): return client_name.replace('Индивидуальный предприниматель', 'ИП') def get_kkm_filled_fn(max_fill=80): LOGIN_URL = 'https://pk.platformaofd.ru/auth/login' API_URL = 'https://pk.platformaofd.ru/api/monitoring' session = requests.Session() print('-= подключе...
<mask token> def squeezed(client_name): return client_name.replace('Индивидуальный предприниматель', 'ИП') def get_kkm_filled_fn(max_fill=80): LOGIN_URL = 'https://pk.platformaofd.ru/auth/login' API_URL = 'https://pk.platformaofd.ru/api/monitoring' session = requests.Session() print('-= подключе...
import requests def squeezed(client_name): return client_name.replace('Индивидуальный предприниматель', 'ИП') def get_kkm_filled_fn(max_fill=80): LOGIN_URL = 'https://pk.platformaofd.ru/auth/login' API_URL = 'https://pk.platformaofd.ru/api/monitoring' session = requests.Session() print('-= подкл...
import requests def squeezed (client_name): return client_name.replace('Индивидуальный предприниматель', 'ИП') def get_kkm_filled_fn(max_fill=80): ## возвращает список ККМ с заполнением ФН больше max_fill в % LOGIN_URL = 'https://pk.platformaofd.ru/auth/login' API_URL = 'https://pk.platformaofd.ru/api/mon...
[ 2, 3, 4, 5, 6 ]
84
709f2425bc6e0b0b650fd6c657df6d85cfbd05fe
<mask token>
<mask token> def test_petite_vue(request): return render(request, 'petite_vue_app/test-form.html')
from django.shortcuts import render def test_petite_vue(request): return render(request, 'petite_vue_app/test-form.html')
from django.shortcuts import render # Create your views here. def test_petite_vue(request): return render(request, 'petite_vue_app/test-form.html')
null
[ 0, 1, 2, 3 ]
85
a4deb67d277538e61c32381da0fe4886016dae33
<mask token> class Net(nn.Module): def __init__(self, input_size, hidden_size, num_classes): super(Net, self).__init__() self.h1 = nn.Linear(input_size, hidden_size) self.h2 = nn.Linear(hidden_size, hidden_size_1) self.h3 = nn.Linear(hidden_size_1, hidden_size_2) self.h4 =...
<mask token> for file in glob.glob('*.jpg'): images.append(file) <mask token> for i in range(train_num + test_num): tags = labels.iloc[i]['tags'] if i < train_num: train_images.append(imageio.imread(images[i], as_gray=True).flatten()) train_labels.append(int('cloudy' not in tags and 'haze' n...
<mask token> fileDir = os.getcwd() input_size = 65536 hidden_size = 20 hidden_size_1 = 15 hidden_size_2 = 10 hidden_size_3 = 5 num_classes = 1 learning_rate = 0.001 num_epochs = 5 train_num = 1000 test_num = 148 images = [] for file in glob.glob('*.jpg'): images.append(file) images = sorted(images, key=lambda filen...
import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import cv2 import imageio import pandas as pd import glob, os import numpy as np fileDir = os.getcwd() input_size = 65536 hidden_size = 20 hidden_size_1 = 15 hidden_size_2 = 10 hidden_size_3 = 5 num_classes = 1 learning_rate ...
import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import cv2 import imageio import pandas as pd import glob, os import numpy as np fileDir = os.getcwd() # os.chdir("./train-jpg") # there are 40480 training examples # we will allocate 39000 for training # and the remaining ...
[ 3, 4, 5, 6, 7 ]
86
914f477518918619e0e42184bd03c2a7ed16bb01
<mask token> class Relation_type(models.Model): <mask token> <mask token> def __str__(self): return str(self.name) class Relation(models.Model): id_relation = models.AutoField(primary_key=True) id_person1 = models.ForeignKey(Person, on_delete=models.PROTECT, related_name='who1')...
<mask token> class Person(models.Model): <mask token> <mask token> <mask token> <mask token> <mask token> <mask token> <mask token> <mask token> <mask token> def __str__(self): return str(self.nickname) + ' ' + self.last_name + '' + self.first_name class Contact_type...
<mask token> class Location(models.Model): <mask token> <mask token> <mask token> <mask token> <mask token> <mask token> <mask token> <mask token> <mask token> <mask token> class Person(models.Model): id_person = models.AutoField(primary_key=True) nickname = models.Ch...
<mask token> class Location(models.Model): <mask token> <mask token> <mask token> <mask token> <mask token> <mask token> <mask token> <mask token> <mask token> def __str__(self): return str(self.name) + ' - ' + str(self.country) + ': ' + str(self .city) c...
from django.db import models class Location(models.Model): id_location = models.AutoField(primary_key=True) city = models.CharField(max_length=100, null=True) street_name = models.CharField(max_length=100, null=True) street_number = models.IntegerField(null=True) zip = models.IntegerField(null=Tru...
[ 9, 18, 20, 21, 24 ]
87
cdbf9427d48f0a5c53b6efe0de7dfea65a8afd83
<mask token> def request_id(): global req_c, pid if req_c is None: req_c = random.randint(1000 * 1000, 1000 * 1000 * 1000) if pid is None: pid = str(os.getpid()) req_id = req_c = req_c + 1 req_id = hex(req_id)[2:].zfill(8)[-8:] return pid + '-' + req_id
<mask token> def string_id(length=8): """ Generate Random ID. Random ID contains ascii letters and digitis. Args: length (int): Character length of id. Returns: Random id string. """ return ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(le...
<mask token> random_generator = random.SystemRandom() def string_id(length=8): """ Generate Random ID. Random ID contains ascii letters and digitis. Args: length (int): Character length of id. Returns: Random id string. """ return ''.join(random.choice(string.ascii_letters +...
import os import random import string random_generator = random.SystemRandom() def string_id(length=8): """ Generate Random ID. Random ID contains ascii letters and digitis. Args: length (int): Character length of id. Returns: Random id string. """ return ''.join(random.choi...
# -*- coding: utf-8 -*- # Copyright (c) 2018-2020 Christiaan Frans Rademan <chris@fwiw.co.za>. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the ...
[ 1, 2, 3, 4, 5 ]
88
c4624425f57211e583b5fbaec3943539ce6fea6f
<mask token>
<mask token> class BlogPostForm(forms.ModelForm): class Meta: model = BlogPost fields = '__all__'
from django import forms from .models import BlogPost class BlogPostForm(forms.ModelForm): class Meta: model = BlogPost fields = '__all__'
null
null
[ 0, 1, 2 ]
89
a42f36fca2f65d0c5c9b65055af1814d8b4b3d42
<mask token>
<mask token> BUILTINS_MODULE_NAME = 'builtins' <mask token>
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2023 Beartype authors. # See "LICENSE" for further details. ''' Project-wide **standard Python module globals** (i.e., global constants describing modules and packages bundled with CPython's sta...
null
null
[ 0, 1, 2 ]
90
c23125018a77508dad6fd2cb86ec6d556fbd1019
<mask token>
<mask token> os.system('psfex -dd > config.psfex') if ic.use_backsub: prefix = 'b' else: prefix = '' <mask token> f.write('\n') f.write('#############################' + '\n') f.write('##### Scripts for PSFEx #####' + '\n') f.write('#############################' + '\n') f.write('\n') for i in np.arange(len(ic....
<mask token> start_time = time.time() <mask token> os.system('psfex -dd > config.psfex') if ic.use_backsub: prefix = 'b' else: prefix = '' f = open('psfex_all.sh', 'w') f.write('\n') f.write('#############################' + '\n') f.write('##### Scripts for PSFEx #####' + '\n') f.write('########################...
<mask token> import time start_time = time.time() import numpy as np import glob, os from astropy.io import fits import init_cfg as ic os.system('psfex -dd > config.psfex') if ic.use_backsub: prefix = 'b' else: prefix = '' f = open('psfex_all.sh', 'w') f.write('\n') f.write('#############################' + '\n...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu May 21 11:40:26 2020 @author: jlee """ import time start_time = time.time() import numpy as np import glob, os from astropy.io import fits import init_cfg as ic # ----- Making scripts for PSFEx ----- # os.system("psfex -dd > config.psfex") if ic....
[ 0, 1, 2, 3, 4 ]
91
81688d51696156905736b5de7a4929387fd385ab
<mask token> def train(cfg, epoch, data_loader, model): data_time = AverageMeter('Data', ':6.3f') batch_time = AverageMeter('Time', ':6.3f') losses = AverageMeter('Loss', ':.4e') progress = ProgressMeter(len(data_loader) - 1, [batch_time, data_time, losses], prefix=f'Epoch: [{epoch}]\t') m...
<mask token> def train(cfg, epoch, data_loader, model): data_time = AverageMeter('Data', ':6.3f') batch_time = AverageMeter('Time', ':6.3f') losses = AverageMeter('Loss', ':.4e') progress = ProgressMeter(len(data_loader) - 1, [batch_time, data_time, losses], prefix=f'Epoch: [{epoch}]\t') m...
<mask token> def train(cfg, epoch, data_loader, model): data_time = AverageMeter('Data', ':6.3f') batch_time = AverageMeter('Time', ':6.3f') losses = AverageMeter('Loss', ':.4e') progress = ProgressMeter(len(data_loader) - 1, [batch_time, data_time, losses], prefix=f'Epoch: [{epoch}]\t') m...
import argparse import datetime import importlib import pprint import time import random import numpy as np import torch from torch.utils.tensorboard import SummaryWriter from utils import get_git_state, time_print, AverageMeter, ProgressMeter, save_checkpoint def train(cfg, epoch, data_loader, model): data_time ...
import argparse import datetime import importlib import pprint import time import random import numpy as np import torch from torch.utils.tensorboard import SummaryWriter from utils import get_git_state, time_print, AverageMeter, ProgressMeter, save_checkpoint def train(cfg, epoch, data_loader, model): data_tim...
[ 2, 3, 4, 5, 6 ]
92
d90942f22cbbd9cfc3a431b7857cd909a7690966
<mask token>
OK = 200 CREATED = 201 NOT_MODIFIED = 304 UNAUTHORIZED = 401 FORBIDDEN = 403 BAD_REQUEST = 400 NOT_FOUND = 404 CONFLICT = 409 UNPROCESSABLE = 422 INTERNAL_SERVER_ERROR = 500 NOT_IMPLEMENTED = 501 SERVICE_UNAVAILABLE = 503 ADMIN = 'admin' ELITE = 'elite' NOOB = 'noob' WITHDRAW = 'withdraw' FUND = 'fund'
null
null
null
[ 0, 1 ]
93
54ec1961f4835f575e7129bd0b2fcdeb97be2f03
<mask token> def input_db_name(conn): while True: db_name = input('Database name (default: concert_singer) > ') if not db_name: db_name = 'concert_singer' cur = conn.cursor() cur.execute('SELECT 1 FROM databases WHERE name = ?', (db_name,)) if cur.fetchone(): ...
<mask token> def input_db_name(conn): while True: db_name = input('Database name (default: concert_singer) > ') if not db_name: db_name = 'concert_singer' cur = conn.cursor() cur.execute('SELECT 1 FROM databases WHERE name = ?', (db_name,)) if cur.fetchone(): ...
<mask token> def input_db_name(conn): while True: db_name = input('Database name (default: concert_singer) > ') if not db_name: db_name = 'concert_singer' cur = conn.cursor() cur.execute('SELECT 1 FROM databases WHERE name = ?', (db_name,)) if cur.fetchone(): ...
import configparser import sqlite3 import time import uuid from duoquest.tsq import TableSketchQuery def input_db_name(conn): while True: db_name = input('Database name (default: concert_singer) > ') if not db_name: db_name = 'concert_singer' cur = conn.cursor() cur.exe...
import configparser import sqlite3 import time import uuid from duoquest.tsq import TableSketchQuery def input_db_name(conn): while True: db_name = input('Database name (default: concert_singer) > ') if not db_name: db_name = 'concert_singer' cur = conn.cursor() cur.ex...
[ 6, 7, 8, 11, 12 ]
94
2fe20f28fc7bba6b8188f5068e2b3c8b87c15edc
<mask token> def replaceNode(nfa, old, new): if DEBUG: print('R_Start(%s, %s) ---' % (old, new), nfa) if old in nfa._deltas: for input in nfa._deltas[old]: nfa.addDelta(new, input, nfa._deltas[old][input]) del nfa._deltas[old] if DEBUG: print('R_SwitchedSource(%...
<mask token> def copyDeltas(src): out = dict() for k in src: out[k] = dict() for k2 in src[k]: out[k][k2] = copy(src[k][k2]) return out def replaceNode(nfa, old, new): if DEBUG: print('R_Start(%s, %s) ---' % (old, new), nfa) if old in nfa._deltas: for ...
<mask token> def copyDeltas(src): out = dict() for k in src: out[k] = dict() for k2 in src[k]: out[k][k2] = copy(src[k][k2]) return out def replaceNode(nfa, old, new): if DEBUG: print('R_Start(%s, %s) ---' % (old, new), nfa) if old in nfa._deltas: for ...
from util import AutomataError from automata import NFA from base import Node from copy import copy, deepcopy from os.path import commonprefix DEBUG = False LAMBDA = u'λ' PHI = u'Ø' def copyDeltas(src): out = dict() for k in src: out[k] = dict() for k2 in src[k]: out[k][k2] = copy(...
from util import AutomataError from automata import NFA from base import Node from copy import copy, deepcopy from os.path import commonprefix DEBUG = False LAMBDA = u'\u03bb' PHI = u'\u00d8' def copyDeltas(src): out = dict() for k in src: out[k] = dict() for k2 in src[k]: out[k]...
[ 8, 9, 11, 13, 14 ]
95
aa579025cacd11486a101b2dc51b5ba4997bf84a
<mask token>
class UrlPath: <mask token>
class UrlPath: @staticmethod def combine(*args): result = '' for path in args: result += path if path.endswith('/') else '{}/'.format(path) return result
class UrlPath: @staticmethod def combine(*args): result = '' for path in args: result += path if path.endswith('/') else '{}/'.format(path) #result = result[:-1] return result
null
[ 0, 1, 2, 3 ]
96
a1304f290e0346e7aa2e22d9c2d3e7f735b1e8e7
# We don't need no stinking models but django likes this file to be there if you are an app
null
null
null
null
[ 1 ]
97
368e209f83cc0cade81791c8357e01e7e3f940c8
<mask token>
<mask token> urllib3.disable_warnings() <mask token> print(key.decode('ascii'))
<mask token> urllib3.disable_warnings() response = requests.get('https://freeaeskey.xyz', verify=False) data = response.text.encode('utf-8') key = data[data.index(b'<b>') + 3:data.index(b'</b>')] print(key.decode('ascii'))
import requests import urllib3 urllib3.disable_warnings() response = requests.get('https://freeaeskey.xyz', verify=False) data = response.text.encode('utf-8') key = data[data.index(b'<b>') + 3:data.index(b'</b>')] print(key.decode('ascii'))
#!/usr/bin/python3 import requests import urllib3 urllib3.disable_warnings() response = requests.get('https://freeaeskey.xyz', verify=False) data = response.text.encode('utf-8') key = data[data.index(b'<b>')+3:data.index(b'</b>')] print(key.decode('ascii'))
[ 0, 1, 2, 3, 4 ]
98
57516a17c1f3ee208076852369999d74dbb2b3ba
def helloWorld(): print "We are in DEMO land!" for i in range(10): helloWorld() print listBuilder() def listBuilder(): b = [] for x in range(5): b.append(10 * x) return b print "[done, for real]"
null
null
null
null
[ 0 ]
99
174f744b641ee20272713fa2fe1991cb2c76830a
<mask token>
<mask token> class Brokerage(models.Model): <mask token> <mask token> <mask token> <mask token> <mask token> <mask token> <mask token> <mask token> <mask token> <mask token> <mask token> <mask token> <mask token> <mask token> <mask token> <mask token> ...
<mask token> class Brokerage(models.Model): BrokerageName = models.CharField(max_length=500) ReviewLink = models.CharField(max_length=1000) ContactLink = models.CharField(max_length=1000) TotalAgents = models.IntegerField() Location = models.CharField(max_length=500) Desks = models.IntegerFiel...
from django.db import models class Brokerage(models.Model): BrokerageName = models.CharField(max_length=500) ReviewLink = models.CharField(max_length=1000) ContactLink = models.CharField(max_length=1000) TotalAgents = models.IntegerField() Location = models.CharField(max_length=500) Desks = mo...
from django.db import models class Brokerage(models.Model): BrokerageName = models.CharField(max_length=500) #To-Do Fix additional settings for ImagesFields/FileFields #BrokerageLogo = ImageField ReviewLink = models.CharField(max_length=1000) ContactLink = models.CharField(max_length=1000) TotalAgents = models.I...
[ 0, 1, 2, 3, 4 ]