text
string
size
int64
token_count
int64
from django.contrib.auth.models import User from django.db.models import Model, CharField, TextField, ForeignKey, CASCADE class Post(Model): title = CharField(max_length=50) author = ForeignKey(User, on_delete=CASCADE) content = TextField() def __str__(self): return "{} by {}".format(self.tit...
337
109
import streamlit as st import yaml from load_css import local_css import tensorflow as tf import tensorflow_hub as hub import tensorflow_text as text import numpy as np from random import sample import os local_css("style.css") prediction_key = { 0:'Gastroenterology', 1:'Neurology', 2:'Orthope...
2,304
740
#!/usr/bin/env python # -*- coding: utf-8 -*- """Python Team Awareness Kit (PyTAK) Module Tests.""" import asyncio import urllib import pytest import pytak __author__ = 'Greg Albrecht W2GMD <oss@undef.net>' __copyright__ = 'Copyright 2022 Greg Albrecht' __license__ = 'Apache License, Version 2.0' def test_parse_c...
2,440
988
# test_aoc_day_02.py import pytest import solution.aoc_day_02 as aoc @pytest.fixture def test_solution(): return aoc.AocSolution(test_suffix="_test") @pytest.fixture def exercise_solution(): return aoc.AocSolution() def test_parse_test_solution(test_solution): """Test that input is parsed properly"""...
1,054
400
from operator import add, sub import numpy as np from scipy.stats import norm class Elora: def __init__(self, times, labels1, labels2, values, biases=0): """ Elo regressor algorithm for paired comparison time series prediction Author: J. Scott Moreland Args: times (a...
18,265
5,106
s=input() print(s+'s' if s[-1]!='s' else s+'es')
48
26
from __future__ import annotations import operator from enum import Enum from itertools import product from typing import Dict, Union import numpy as np class Operation(Enum): PLUS = 'PLUS' MINUS = 'MINUS' TIMES = 'TIMES' EXP = 'EXP' MAX = 'MAX' MIN = 'MIN' CONT = 'CONT' NOT = 'NOT' ...
48,147
13,877
# Copyright 2021 PingCAP, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writin...
23,165
6,618
import numpy as np import sys import glob rbp=sys.argv[1] kmer=sys.argv[2] pfile_list=glob.glob("result_VDM3_"+rbp+"_positive_"+kmer+"_*.npy") pfile1=np.load(pfile_list[0]) psha=np.shape(pfile1) pmatrix=np.zeros(psha) for pfile in pfile_list: file=np.load(pfile) # file=np.fromfile(pfile,dtype=np.float32) p...
421
193
'''A common interface to FGVC datasets. Currently supported datasets are - CUB Birds - CUB Birds with expert labels - NA Birds - Stanford Cars - Stanford Dogs - Oxford Flowers - Oxford FGVC Aircraft - Tsinghua Dogs Datasets are constructed and used following the pytorch data.utils.data.Dataset paradigm, and have the ...
1,238
401
from typing import List from celery.result import AsyncResult from fastapi import APIRouter, status, Depends, Form, UploadFile, File, Request, WebSocket from fastapi.responses import RedirectResponse from app.auth import service from app.auth.models import User from app.auth.permission import is_active from app.auth....
10,491
3,062
# Copyright (c) 2019 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed # under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the Licens...
7,768
2,204
import cv2 import numpy as np height = 500 width = 700 gray = np.zeros((height, width), dtype=np.uint8) # fourcc = cv2.VideoWriter_fourcc(*"MJPG") # filename = "output.avi" fourcc = cv2.VideoWriter_fourcc(*"MP4V") filename = "output.mp4" writer = cv2.VideoWriter( filename, fourcc, fps=30, frameSize=(width, height...
647
260
from po.base import BasePage from po.base import InvalidPageException class LoginPage(BasePage): _login_view_locator = ".active" _login_name_selector = "#name" _login_passwd_selector = "#pass" _login_btn_selector = ".span-primary" _login_error_msg_selector='.alert strong' def __init__(self...
1,062
339
from lib import Scrape from typing import List from os import environ def main(): seconds: int = 60 username: str = environ.get('EMAIL') password: str = environ.get('PASSWORD') # Navigates to Linkedin's website scraper = Scrape() # Takes in credentials to login into the url sepecified scr...
1,329
404
var1 = "hello world" # left what you get from the right for character in var1: print(character)
100
31
# -*- coding: utf-8 -*- # Generated by Django 1.11.8 on 2019-03-07 12:55 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('forum', '0002_upvote'), ] operations = [ m...
546
192
# Generated by Django 3.1.7 on 2021-04-08 11:12 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('metadata', '0009_tradeagreement'), ('event', '0017_add_related_trade_agreement_fields'), ] operations = [ migrations.AlterField( ...
495
172
''' ---------------------------------------------------------------------------------------- This script will update the Prescribed Burn System's ePFP data according to txt input files found in the relevant scripts folder. It requires user input of the Corporate Executive Approval date, which it will then use to set PR...
16,905
5,425
import numpy as np from scipy.stats import binom from sklearn.ensemble import IsolationForest from sklearn.preprocessing import MinMaxScaler from scipy.special import erf from learnware.algorithm.anomaly_detect.base import BaseAnomalyDetect class iForest(BaseAnomalyDetect): def __init__(self, n_estimators=100, ...
4,012
1,170
from nox import session @session(reuse_venv=True) def docs(session): session.install("jupyter-book", "sphinx-sitemap", "jupyterbook-latex") # we need _config.yml _toc.yml session.run("jb", "build", ".")
217
83
""" Data manipulations """
27
10
from graviteeio_cli.lint.types.function_result import FunctionResult def length(value, **kwargs): """Count the length of a string an or array, the number of properties in an object, or a numeric value, and define minimum and/or maximum values.""" min = None max = None if "min" in kwargs and type(kwar...
910
264
# coding: utf-8 """ Unofficial python library for the SmartRecruiters API The SmartRecruiters API provides a platform to integrate services or applications, build apps and create fully customizable career sites. It exposes SmartRecruiters functionality and allows to connect and build software enhancing it. ...
27,874
6,797
name = input('Hello! What is your name? : ') print('Nice to meet you,', name + '!') print() age = int(input('How old are you ' + name + '? : ')) print() x = age + 1 print('А я думал тебе', x, end=' ') if x >= 11 and x <= 19: print('лет', end='') elif x % 10 == 1: print('год', end='') elif x % 10 >= 2 and x %...
398
173
import numpy as np import pandas as pd import matplotlib.pyplot as plt import warnings warnings.filterwarnings("ignore") import yfinance as yf yf.pdr_override() import datetime as dt # input symbol = 'AAPL' start = dt.date.today() - dt.timedelta(days = 365*2) end = dt.date.today() # Read data df = yf.download(symbol...
2,399
998
import requests from urllib.request import urlopen from urllib.request import urlretrieve import cgi import os.path def retrive_file_name(url): #url = 'https://material.ibear.pt/BTHorarios2019/FileGet.aspx?FileId=5601' remotefile = urlopen(url) blah = remotefile.info()['Content-Disposition'] _, params ...
1,670
551
import spacy import json, os import dill as pickle import numpy as np import pandas as pd from sklearn.feature_extraction.text import TfidfVectorizer from sqlalchemy import create_engine, select, MetaData, Table, Column, Integer, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import ...
13,282
4,139
from uuid import uuid4 from sqlalchemy import Boolean, Column, DateTime, Integer, String from sqlalchemy.dialects.postgresql import UUID from sqlalchemy.orm import relationship from .database import Base class Customers(Base): __tablename__ = "customers" id = Column(UUID(as_uuid=True), primary_key=True, de...
1,604
526
mesh_pic_bandits = 0 mesh_pic_mb_warrior_1 = 1 mesh_pic_messenger = 2 mesh_pic_prisoner_man = 3 mesh_pic_prisoner_fem = 4 mesh_pic_prisoner_wilderness = 5 mesh_pic_siege_sighted = 6 mesh_pic_siege_sighted_fem = 7 mesh_pic_camp = 8 mesh_pic_payment = 9 mesh_pic_escape_1 = 10 mesh_pic_escape_1_fem = 11 mesh_pic_victory =...
32,293
20,309
# ---------------------------------------------------------------------------- # Copyright (c) 2017-2018, QIIME 2 development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file LICENSE, distributed with this software. # ------------------------------------------------...
30,936
6,919
# -*- coding: utf-8 -*- import os import sys import state_workflow_sdk.api.state_workflow.callback_pb2 import state_workflow_sdk.api.state_workflow.createStateWorkflow_pb2 import state_workflow_sdk.model.state_workflow.stateWorkflow_pb2 import state_workflow_sdk.api.state_workflow.deleteStateWorkflow_pb2 import g...
11,696
3,766
"""Test for motif.classify.mvgaussian """ from __future__ import print_function import unittest import numpy as np from motif.contour_classifiers import random_forest def array_equal(array1, array2): return np.all(np.isclose(array1, array2)) class TestRandomForest(unittest.TestCase): def setUp(self): ...
4,171
1,662
""" Profile-aware session wrapper. """ from os import environ from botocore.exceptions import ProfileNotFound from botocore.session import Session from awsenv.cache import CachedSession def get_default_profile_name(): """ Get the default profile name from the environment. """ return environ.get("AWS...
7,365
2,018
import torch import os import torch.nn.functional as F import numpy as np import copy from torch import nn from torch.optim import Adam from torch.autograd import Variable from torch.utils.tensorboard import SummaryWriter from tqdm import tqdm from typing import Tuple from .ppo import PPO, PPOExpert from ...
13,358
4,381
import numpy as np import os, shutil import imageio baseDir = "data/train_verbose" outDir = "data/train" #baseDir = "data/test_verbose" #outDir = "data/test" outDirVidCopy = "data/videos" combineVidsAll = {"smoke" : ["densMean", "densSlice", "velMean", "velSlice", "presMean", "presSlice"], "liquid": ["...
7,327
2,176
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modif...
14,238
3,992
import pandas as pd import numpy as np from sklearn.metrics import confusion_matrix import re def convert_data_sparse_matrix(df, row_label = 'stock_code', col_label = 'name_of_ccass_participant', value_label = 'shareholding'): """ Pivot table """ try: # Prepare zero matrix row_dim =...
4,447
1,439
''' Prepare some files to test the upload functionality. ''' import sys sys.path.append('../') from database import * from pymongo import MongoClient mongo = MongoClient(MONGOURI) db = mongo['SCV'] coll = db['dataset'] from gene_expression import * expr_df, meta_doc = load_read_counts_and_meta(organism='mouse', gse...
1,429
543
from flask import Flask, request from flask_restful import Resource, reqparse from flask_jwt_extended import create_access_token, jwt_required from app.api.V1.models import Product, products class PostProduct(Resource): parser = reqparse.RequestParser() parser.add_argument('name', required=True, help='Produc...
2,321
605
import time from multiprocessing.pool import Pool def is_prime(num): for i in range(2, int(num**0.5+1)): if num % i == 0: return None return num if __name__ == '__main__': t = time.time() p1 = Pool(processes=30) p2 = Pool(processes=30) p3 = Pool(processes=30) num1 = r...
1,155
464
# recursion function (Clean Word) def CleanWord(word): if len(word) == 1: return word elif word[0] == word[1]: return CleanWord(word[1:]) else: return word[0] + CleanWord(word[1:]) print(CleanWord("wwwooooorrrrllddd"))
267
100
import typing from commands2 import CommandBase from subsystems.cameracontroller import CameraSubsystem class RotateCamera(CommandBase): def __init__(self, camera: CameraSubsystem, leftRight: typing.Callable[[], float], upDown: typing.Callable[[], float]) -> None: Comman...
665
185
from django.shortcuts import render,redirect from django.http import HttpResponse, Http404,HttpResponseRedirect import datetime as dt from .models import Post,Comment,Follow,Profile from django.contrib.auth.decorators import login_required from .forms import NewPostForm, NewCommentForm, AddProfileForm from django.contr...
8,188
2,377
import sys import wx sys.path.insert(0, 'lib.zip') from lib.TetrisGame import TetrisGame if __name__ == '__main__': app = wx.PySimpleApp() frame = TetrisGame(None) frame.Show(True) app.MainLoop()
238
104
import argparse import torch import logger import models import utils NUM_NODES = { 'moments': 391, 'multimoments': 391, 'kinetics': 608, } CRITERIONS = { 'CE': {'func': torch.nn.CrossEntropyLoss}, 'MSE': {'func': torch.nn.MSELoss}, 'BCE': {'func': torch.nn.BCEWithLogitsLoss}, } OPTIMIZERS =...
6,822
2,510
import scrapy from bs4 import BeautifulSoup from lab3.items import Lab3Item class QuoteSpider(scrapy.Spider): name = 'quotes' start_urls = ['http://quotes.toscrape.com/page/1/'] page_num = 1 # 对爬取到的信息进行解析 def parse(self, response, **kwargs): soup = BeautifulSoup(response.body, 'html.parse...
2,021
718
import matplotlib.pyplot as plt from lifelines import (WeibullFitter, ExponentialFitter, LogNormalFitter, LogLogisticFitter) import pandas as pd data = pd.read_csv('Dataset/telco_customer.csv') data['tenure'] = pd.to_numeric(data['tenure']) data = data[data['tenure'] > 0] # Replace yes and No ...
1,236
497
import re import num2words INT_PATTERN = re.compile(r'^-?[0-9]+$') FLOAT_PATTERN = re.compile(r'^-?[0-9]+[,\.][0-9]+$') ORDINAL_PATTERN = re.compile(r'^[0-9]+\.?$') NUM_PATTERN = re.compile(r'^-?[0-9]+([,\.][0-9]+$)?') class NumberToWords: def __init__(self, lang_code): self.lang_code = lang_code ...
2,260
754
from django.test import TransactionTestCase from django.test import TestCase from django.urls import reverse from home_page.models import Search from ebaysdk.finding import Connection as finding class PageTest(TransactionTestCase): def test_home_page_status_code_1(self): response = self.client.get('/'...
4,252
1,327
from key_generator.key_generator import generate all_sizes_required = [(100, '100'), (500, '500'), (1000, '1K'), (5000, '5K'), (10000, '10K'), (50000, '50K'), (100000, '100K'), (500000, '500K')] for file_size in all_sizes_required: OUTPUT_PATH = "./string_test_" + file_size[1] + ".txt" STRING_COUNT = file_size[0] ...
869
425
########################################### # Author : Bastien Girardet, Deborah De Wolff # Date : 13.05.2018 # Course : Applications in Object-oriented Programming and Databases # Teachers : Binswanger Johannes, Zürcher Ruben # Project : Bibliotek # Name : portfolio_book.py Portfolio_book Flask_restful res...
4,950
1,285
import logging from absl import app from sensor_msgs.msg import Image from insert_table_op import InsertTableOperator from insert_block_op import InsertBlockOperator from init_robot_op import InitRobotOperator from gel_sight_op import GelSightOperator from mock_loc_obj_op import MockLocateObjectOperator from goto_xyz_...
9,199
3,099
# -*- coding: utf-8 -*- from __future__ import unicode_literals import jsonfield.fields from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ ...
2,686
665
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 2017 Tomoki Hayashi (Nagoya University) # Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) from __future__ import print_function import argparse import numpy as np from sklearn.preprocessing import StandardScaler from utils import read_hdf5 from ut...
1,300
459
# from decimal import Decimal import collections as coll import sys import math as mt # import random as rd # import bisect as bi import time sys.setrecursionlimit(1000000) # import numpy as np def uno(): return int(sys.stdin.readline().strip()) def dos(): return sys.stdin.readline().strip() def tres()...
727
283
from robosuite.models.objects import MujocoXMLObject from robosuite.utils.mjcf_utils import xml_path_completion, array_to_string, string_to_array class BottleObject(MujocoXMLObject): """ Bottle object """ def __init__(self): super().__init__(xml_path_completion("objects/bottle.xml")) class ...
7,662
2,696
# Problem description: http://python3.softuni.bg/student/lecture/assignment/56b749af7e4f59b649b7e626/ class Medicine: def __init__(self, name, w, h, d): self.name = name self.w = w self.h = h self.d = d def can_be_put_in_carton(self, carton_w, carton_h, carton_d): sort...
1,654
586
# LOGGING # ---------------------------------------------------------------------------------------------------------------------# import logging logger = logging.getLogger('django') # IMPORTS # ---------------------------------------------------------------------------------------------------------------------# # sho...
1,111
245
# Adam Beardsley # starting from from adafruit example # https://learn.adafruit.com/welcome-to-circuitpython/creating-and-editing-code # import board import digitalio import time led = digitalio.DigitalInOut(board.LED) led.direction = digitalio.Direction.OUTPUT ramp_time = 3 # Time to ramp up, in seconds period = 0....
858
272
import argparse from site_checker import SiteChecker if __name__ == "__main__": parser = argparse.ArgumentParser(description="Check sites text.") parser.add_argument("config", type=str, nargs=1, help="Path to config json file.") parser.add_argument( "-a", dest="apiKey", type=str, ...
1,099
357
import os from pathlib import Path from datetime import datetime from json import dumps import flask as fsk from flask import request, jsonify, Response app = fsk.Flask(__name__) app.config['DEBUG'] = False homedir = os.getenv('HOME') @app.route('/provision', methods=['POST']) def auto_provision(): Path(f'{homed...
1,563
554
#!/usr/bin/env python3 #################################################################################################### # Created by EH (NL) https://github.com/strebrah/Solaredge_Domoticz_Modbus # # Date: August 2020 ...
3,586
978
import senti_lexis import datetime, string, numpy, spwrap, random time, sys, re from sklearn import svm from sklearn import cross_validation from sklearn.feature_extraction.text import CountVectorizer from sklearn.cross_validation import KFold from scipy.sparse import csr_matrix def main(): for i in range(1, 11): ...
10,632
4,712
def machine(): keys='abcdefghijklmnopqrstuvwxyz !' values=keys[-1]+keys[0:-1] """ In encrytpDict: In decryptDict: keys Values keys Values 'a' '!' '!' 'a' 'b' 'a' 'a' 'b' . . . . . . ....
1,314
400
from numpy import isnan from wonambi import Dataset from .paths import axon_abf_file d = Dataset(axon_abf_file) def test_abf_read(): assert len(d.header['chan_name']) == 1 assert d.header['start_time'].minute == 47 data = d.read_data(begtime=1, endtime=2) assert data.data[0][0, 0] == 2.197265592...
645
290
from AutoMxL.Preprocessing.Categorical import * from AutoMxL.Preprocessing.Date import * from AutoMxL.Preprocessing.Outliers import * from AutoMxL.Preprocessing.Missing_Values import * import unittest import pandas as pd import math # test config df = pd.read_csv('tests/df_test_bis.csv') class TestMissingValues(unit...
9,115
3,317
""" Session: 4 Topic: Conditional: IF ELSE statement """ x = 20 y = 100 if (x > y): print ('x > y is true') print ('new line 1') else: print('x > y is false') print('new line 2') print ('new line 3')
218
92
def execute_command(command: str) -> (int): direction, magnitude = command.split(" ") horizontal, depth = 0, 0 if direction == "forward": horizontal += int(magnitude) elif direction == "up": depth -= int(magnitude) elif direction == "down": depth += int(magnitude) retur...
915
272
import codecs import json import rank import train_ranker #Files to be present in home dir TRAINING_FILE_CITIES = 'manual_7_cities.jl' TRAINING_FILE_NAMES = 'manual_50_names.jl' TRAINING_FILE_ETHNICITIES = 'manual_50_ethnicities.jl' ACTUAL_FILE_CITIES = 'manual_50_cities.jl' ACTUAL_FILE_NAMES = 'manual_50_names.jl' A...
2,073
786
''' Calculat the leap year''' from datetime import date year = int(input('What year do you want to analyse? Type 0 for the current year.')) if year == 0: year = date.today().year if year%4 ==0 and year%100 != 0 or year%400 == 0: print(F"The year {year} it's a LEAP year.".) else: print(F"The year {year} isn'...
336
124
#!/usr/bin/env python #coding=utf-8 import numpy class Task(object): def __init__(self, cpu, mem): self.cpu = cpu self.mem = mem def __repr__(self): return ("%d,%d") % (self.cpu, self.mem) def get_task_list(): task_list = [] for i in range(0,30): cpu = numpy.random.r...
567
215
# This is an empty python file to expose this directory to it's parent
71
18
import os import cv2 from sklearn.cluster import KMeans, DBSCAN, MiniBatchKMeans from scipy import spatial from sklearn.preprocessing import StandardScaler import numpy as np from tqdm import tqdm import argparse parser = argparse.ArgumentParser(description='Challenge presentation example') parser.add_argument('--data...
7,500
2,255
""" Prepare training, validation, and testing data after preprocessing of the large dataset. Used in training and evaluating models. """ import numpy as np import pandas as pd from sklearn.model_selection import train_test_split def feature_selection(data, features): """ Choose which features to use for trai...
1,399
420
#!/usr/bin/env python ############################################################### # \package CyberRadioDriver.radio # # \brief Defines basic functionality for radio handler objects. # # \note This module defines basic behavior only. To customize # a radio handler class for a particular radio, derive a new # ...
179,927
52,561
from typing import List, Tuple import numpy as np from alpha_zero.Board import Board class NeuralNet(): """ This class specifies the base NeuralNet class. To define your own neural network, subclass this class and implement the functions below. The neural network does not consider the current player...
1,686
425
""" Project : bugaboo Filename : forms.py Author : zhancongc Description : 表单管理 """ from flask_wtf import FlaskForm from wtforms import StringField, BooleanField, TextAreaField, SelectField, FileField, IntegerField, PasswordField, SubmitField from wtforms.validators import DataRequired class GodLoginForm...
785
238
import pandas as pd import numpy as np from tqdm import tqdm class Variance(object): def estimate_variance(self, algo="placebo", replications=200): """ # algo - placebo ## The following algorithms are omitted because they are not practical. - bootstrap - jackknife ...
3,836
1,236
from django.shortcuts import render from django.utils import timezone from todo.models import Todo from django.http import HttpResponseRedirect def home(request): todo_items = Todo.objects.all().order_by("-added_date") return render(request , 'todo/index.html' , {"todo_items":todo_items}) def add_todo(request)...
681
209
import random category = ['python', 'java', 'kotlin', 'javascript'] computer = random.choice(category) hidden = list(len(computer) * "-") print("H A N G M A N") counter = 8 while counter > 0: print() print("".join(hidden)) letter = input("Input a letter: ") if (letter in hidden) or (letter in hidden...
816
320
# -*- coding: utf-8 -*- """ 所有任务task相关功能函数 """ __author__ = "XuWeitao" import CommonUtilities import rawSql def getTasksList(UserID): """ 获取任务列表,包括任务流水号,创建时间,最近一次修改时间,货号,色号以及到料时间和创建人 :param UserID:创建人ID,如果为ALL则返回所有的任务列表 :return:{ "SerialNo":任务流水号, "CreateTime":任务创建时间, "LastModifiedTime":最近一次修改时间, "ProductNo"...
6,536
3,121
class Solution: def numIslands(self, grid: List[List[str]]) -> int: ''' T: O(mn) and S: O(1) ''' if not grid: return 0 nrow, ncol = len(grid), len(grid[0]) def exploreIsland(grid, i, j): if i < 0 or i > nrow - 1 or j < 0 or j > ncol-1 or grid[i][j...
744
265
# coding=utf-8 # Copyright 2017 The Tensor2Tensor Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable...
11,417
3,740
import pytest from datetime import date, timedelta from adapters import repository from domain.model import Batch, OrderLine, allocate, OutOfStock from domain import model from service_layer import handlers, unit_of_work class FakeSession: def __init__(self): self.committed = False def commit(self):...
4,166
1,552
import FWCore.ParameterSet.Config as cms electronEfficiencyThresholds = [36, 68, 128, 176] electronEfficiencyBins = [] electronEfficiencyBins.extend(list(xrange(0, 120, 10))) electronEfficiencyBins.extend(list(xrange(120, 180, 20))) electronEfficiencyBins.extend(list(xrange(180, 300, 40))) electronEfficiencyBins.exte...
1,786
722
#!python # external import numpy as np import numba @numba.njit(nogil=True, cache=True) def longest_increasing_subsequence(sequence): # TODO:Docstring M = np.zeros(len(sequence) + 1, np.int64) P = np.zeros(len(sequence), np.int64) max_subsequence_length = 0 for current_index, current_element in e...
18,548
6,208
def result(elements): bakery = {} for i in range(0, len(elements), 2): key = elements[i] value = elements[i + 1] bakery[key] = int(value) return bakery tokens = input().split(' ') print(result(tokens))
241
88
# Order must match format junk # NOTIFY_ALL is kinda special, if you registerNotifier # with it, you get ALL notifications. NOTIFY_ALL = 0 # Get all notifications NOTIFY_SIGNAL = 1 # Callback on signal/exception NOTIFY_BREAK = 2 # Callback on breakpoint / sigtrap NOTIFY_STEP = 3 # Callback...
1,525
596
# Purpose: Grouping entities by DXF attributes or a key function. # Copyright (c) 2017-2021, Manfred Moitzi # License: MIT License from typing import Iterable, Hashable, Dict, List, TYPE_CHECKING from ezdxf.lldxf.const import DXFValueError, DXFAttributeError if TYPE_CHECKING: from ezdxf.eztypes import DXFEntity, ...
3,248
963
# coding=utf-8 import unittest from companycase import CompanyCase class TestEnglishCCase(unittest.TestCase): @classmethod def setUpClass(cls): cls.ccase = CompanyCase() def test_simple(self): self.assertEqual(self.ccase.apply("foobar ltd"), "Foobar LTD") self.assertEqual(self.cca...
1,839
708
#!/usr/bin/env python3 import os import tqdm import torch import random import numpy as np import torch.nn as nn import configargparse import torch.optim as optim from tensorboard import program from torch.utils.tensorboard import SummaryWriter import yaml from models import FeatureNet from datasets import get_datase...
8,527
2,732
# from .panos import PanosSkillet # from .docker import DockerSkillet # from .pan_validation import PanValidationSkillet # from .python3 import Python3Skillet # from .rest import RestSkillet # from .template import TemplateSkillet # from .workflow import WorkflowSkillet
271
73
""" Views for the rss_proxy djangoapp. """ import requests from django.conf import settings from django.core.cache import cache from django.http import HttpResponse, HttpResponseNotFound from lms.djangoapps.rss_proxy.models import WhitelistedRssUrl CACHE_KEY_RSS = "rss_proxy.{url}" def proxy(request): """ ...
1,192
374
#!/usr/bin/env python numTemp = raw_input('Enter a number: ') num = int(numTemp) if num > 0: print '>0' elif num ==0: print '0' else: print '<0'
149
66
from django.conf.urls import url from .views import * app_name = "accounts" urlpatterns = [ url(r"^signup/$", CustomSignupView.as_view(), name="custom_signup"), url(r"^destroy/$", AjaxLogoutView.as_view(), name="destroy"), url(r"^(?P<username>[\w.@+-]+)/$", ProfileView.as_view(), name="profile"), ]
314
117
#!/usr/bin/env python Description: Load topology in Mininet Author: James Hongyi Zeng (hyzeng_at_stanford.edu) ''' from argparse import ArgumentParser from socket import gethostbyname from os import getuid from mininet.log import lg, info from mininet.cli import CLI from mininet.net import Mininet from ...
8,195
2,599
""" Test a site with translated content. Do not test titles as we remove the translation. """ import io import os import shutil import lxml.html import pytest import nikola.plugins.command.init from nikola import __main__ from .helper import cd from .test_empty_build import ( # NOQA test_archive_exists, t...
1,833
629
import argparse import os import torch import torch.nn.functional as F from model_ST import * import data import numpy as np import matplotlib.pyplot as plt from torch.utils.data import Dataset, DataLoader import sys from predict import evaluate_MA from tensorboardX import SummaryWriter # print model parameter def pri...
8,826
2,905
"""Raised to quit.""" from illud.exception import IlludException class QuitException(IlludException): """Raised to quit."""
130
42