text
string
size
int64
token_count
int64
def _doxygen_archive_impl(ctx): """Generate a .tar.gz archive containing documentation using Doxygen. Args: name: label for the generated rule. The archive will be "%{name}.tar.gz". doxyfile: configuration file for Doxygen, @@OUTPUT_DIRECTORY@@ will be replaced with the actual output dir ...
5,786
1,813
from assembler import ASM def slowdownThreeOfAKind(rom): rom.patch(0x06, 0x096B, ASM("ldh a, [$E7]\nand $0F"), ASM("ldh a, [$E7]\nand $3F")) def fixHorseHeads(rom): rom.patch(0x07, 0x3653, "00010400", "00010000")
234
136
import sys import os import json import hashlib import logging import base64 import shutil from concurrent.futures import ProcessPoolExecutor from subprocess import Popen, PIPE, STDOUT from jvd.disassembler import DisassemblerAbstract import logging as log import traceback from jvd.utils import read_gz_js, write_gz_js,...
5,577
1,711
from enum import Enum import logging import os import re import sys import yaml from scanapi.errors import BadConfigurationError, InvalidPythonCodeError # Available imports to be used dinamically in the api spec import datetime import math import random import time import uuid logger = logging.getLogger(__name__) va...
3,203
940
#! /usr/bin/env python """Londiste setup and sanity checker. """ import sys, os, skytools from pgq.cascade.admin import CascadeAdmin __all__ = ['LondisteSetup'] class LondisteSetup(CascadeAdmin): """Londiste-specific admin commands.""" initial_db_name = 'node_db' extra_objs = [ skytools.DBSchema("londi...
18,720
5,996
import pytest import screed import os import sys import numpy as np import matplotlib.pyplot as plt import cv2 import skimage.measure as measure path = os.getcwd() path = os.path.join(path,"src") sys.path.append(path) print(path) import ribofilio as rb def test_get_genes(): path = os.getcwd () path =...
4,929
2,450
import io import logging import os import pathlib from functools import cached_property, lru_cache from typing import List, Set, Tuple from flake8.main.application import Application # type:ignore from flake8 import ( # type:ignore utils as flake8_utils, checker as flake8_checker) import abstracts from ai...
6,208
1,907
import typing from ..tools.log import Logger from .db import DBI from .model_base import ModelBase from ..config import Config class ManagerException(BaseException): pass class ViewManagerBase: MODEL_CLASS = ModelBase def __init__(self, dbi: DBI = None): """ Init function of base mode...
16,566
4,652
#!/usr/bin/env python __version__ = '1.3.0' import glob from setuptools import setup setup( name="hocr-tools", version=__version__, description='Advanced tools for hOCR integration', author='Thomas Breuel', maintainer='Konstantin Baierer', maintainer_email='konstantin.baierer@gmail.com', ...
1,271
390
# Imports import socket import subprocess import os import requests # from prettytable import PrettyTable import getpass import CONFIG def send_message(text): try: requests.post('https://slack.com/api/chat.postMessage', { 'token': CONFIG.SLACK_TOKEN, 'channel': CONFIG.SLACK_CHANNEL_INFO, ...
2,237
815
import typing as t import warnings from .error_handler import MissingExtensionError, MissingExtensionWarning class ExtensionMixin: """ A base class for mixing in custom classes (extensions) into another classes. """ AUTHOR = "unknown" NAME = "unknown" ID = f"{AUTHOR}-{NAME}" SOFT_...
2,985
798
import numpy as np import h5py import pyglib.basic.units as units import pyglib.basic.splot as splot ''' Equation of state. ''' def Murnaghan(parameters, vol): ''' Given a vector of parameters and volumes, return a vector of energies. equation From PRB 28,5480 (1983) ''' E0 = parameters[0] B0...
3,695
1,581
import users.user as user import grades.actions as grade class Actions: def signup(self): print("Selected item: signup") name = input("Your name: ") lastname = input("Your last name: ") email = input("Your email: ") password = input("Choose a password: ") ...
1,808
495
# encoding: utf-8 '''Pdef version in a separate module to simplify setup.py.''' __version__ = '1.2.0'
102
36
from .base import PipBaseRecipe class CurtsiesRecipe(PipBaseRecipe): def __init__(self, *args, **kwargs): super(CurtsiesRecipe, self).__init__(*args, **kwargs) self.sha256 = '431631b9c1417b2ae8156d0bb6d7c3ce' \ '0c97941413717ed6713a9a9c60e9576e' self.depends = ['ncur...
438
194
# Generated by Django 3.1.3 on 2020-11-08 19:52 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Topics', fields=[ ('id', models.AutoField(a...
688
214
import png import numpy import pprint import math import re def gen_background(width, height, mag, b_col): bg = numpy.zeros((width * mag, height * mag, 4), dtype=numpy.uint8) for y in range(0, height * mag, mag): for x in range(0, width * mag): bg[y][x] = b_col for x in range(...
3,821
1,465
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Aug 27 23:58:37 2020 @author: manal """ import numpy as np import GPy from GPy.kern.src.stationary import Stationary class Cosine_prod(Stationary): """ Cosine kernel: Product of 1D Cosine kernels .. math:: &k(x,x')_i = ...
2,019
898
import logging logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s (%(threadName)s-%(process)d) %(message)s") __version__ = "2.2.0"
156
64
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def minDiffInBST(self, root: Optional[TreeNode]) -> int: output=[] stack=[root] whil...
791
242
PREFIX = "/video/tvkultura" NAME = "TVKultura.Ru" ICON = "tvkultura.png" ART = "tvkultura.jpg" BASE_URL = "https://tvkultura.ru/" BRAND_URL = BASE_URL+"brand/" # Channel initialization def Start(): ObjectContainer.title1 = NAME HTTP.Headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:47.0) Gecko...
4,904
1,562
# -*- coding: utf-8 -*- """ This module is a scratchpad for general development, testing & debugging Well, even more so than pcmd.py. You best ignore p2cmd.py. """ import uuid from django.core.management.base import NoArgsCommand from django.db.models import connection from pprint import pprint import settings import ...
3,399
1,155
# Copyright 2017 Natural Language Processing Group, Nanjing University, zhaocq.nlp@gmail.com. # # 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...
13,997
4,548
import logging import time from pathlib import Path from subprocess import call import cli def parse_args(args): parser = cli.argparser() subparsers = parser.add_subparsers( help="Arguments for specific action.", dest="dtype" ) subparsers.required = True slurm = subparsers.add_parser("s...
4,381
1,513
from dataclasses import dataclass, field from typing import Any, Dict, List from aiographql.client.error import GraphQLError from aiographql.client.request import GraphQLRequestContainer @dataclass(frozen=True) class GraphQLBaseResponse(GraphQLRequestContainer): json: Dict[str, Any] = field(default_factory=dict)...
1,127
317
from .verbo import *
21
8
class Solution(object): def connect(self, root): """ :type root: TreeLinkNode :rtype: nothing """ if root == None: return p = root.next while p: if p.left != None: p = p.left break elif p.righ...
698
188
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2019 The FATE Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/lic...
2,602
823
from collections import defaultdict word_counts = defaultdict(int) for w in open('runbun_ilimi/runbin_ilimi.txt', encoding="utf-8").read().split(): word_counts[w.lower()] += 1 totalCount = 0; for w, c in word_counts.items(): totalCount += 1 print(totalCount)
269
99
# Fichier main de gestion des ressources du robot from micropython import const from machine import * from DRV8833 import * from BME280 import * import pycom import time import os # Variables globales pour moteurs et pont en H DRV8833_Sleep_pin = "P20" # Pin SLEEP DRV8833_AIN1 = "P22" # Entrée PWM moteu...
3,839
1,837
import torch import torch.nn.functional as F from torch import nn as nn from torch.autograd import Variable # from https://github.com/wolny/pytorch-3dunet/blob/master/pytorch3dunet/unet3d/losses.py def flatten(tensor): """Flattens a given tensor such that the channel axis is first. The shapes are transforme...
4,146
1,364
''' Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order. Note that an empty string is also considered valid. Exa...
1,020
353
from json import dumps from typing import Callable from flask.json import jsonify from flask.wrappers import Response from flask_verify.verify_json import verify_json_response from pytest import raises @verify_json_response def _view_function_response() -> Response: """ To test if an endpoint that already ret...
3,440
946
import numpy as np import sys import cv2 sys.path.append("../") from utils.config import config class TestLoader: def __init__(self, imdb, batch_size=1, shuffle=False): self.imdb = imdb self.batch_size = batch_size self.shuffle = shuffle self.size = len(imdb)#num of data ...
1,266
400
"""MetroRail Station related structures """ from enum import Enum from typing import Any, Optional class Station(Enum): """A MetroRail Station """ A01 = "A01" A02 = "A02" A03 = "A03" A04 = "A04" A05 = "A05" A06 = "A06" A07 = "A07" A08 = "A08" A09 = "A09" A10 = "A10" ...
1,676
1,089
import time from unittest import mock import pytest from django.contrib.auth.models import AnonymousUser from django.core.exceptions import ValidationError from django.db import IntegrityError from django.http import Http404 from django.test import RequestFactory, TestCase from django.urls import reverse from wagtail....
27,398
8,562
# Copyright (C) 2013 Lindley Graham """ This file provides a mpirun work-around for clusters that do not have the ibrun command. """ import os, stat class random_manningsn(object): """ This class is an implementation of :class:`polyadcirc.run_framework.random_manningsn` that provides a ``mpirun`` base...
4,141
1,248
from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC import datetime as dt import sys import getpass import re def start_registration(handle, email, pwd1, pwd2): print("Starting registration, browser opening shortly....
3,185
1,109
#!/usr/local/bin/python #coding=utf-8 #第 0003 题:将 0001 题生成的 200 个激活码(或者优惠券)保存到 Redis 非关系型数据库中。 import uuid import redis def create_code(num, length): result = [] while True: uuid_id = uuid.uuid1() temp = str(uuid_id).replace('-', '')[:length] if temp not in result: result....
575
250
# Tuples coordinates = (4, 5) # Cant be changed or modified print(coordinates[1]) # coordinates[1] = 10 # print(coordinates[1])
141
61
import unittest import logging from flask import Flask @unittest.skip("needs refactoring") class driftTestCase(unittest.TestCase): def setUp(self): self.app = Flask(__name__) logging.basicConfig(level="ERROR") self.app.testing = True self.test_client = self.app.test_client() ...
620
197
#!/usr/bin/python # vim: set sw=4 sts=4 ts=8 et ft=python fenc=utf8 ff=unix tw=74 : # # SYNOPSIS # ======== # This script analyses an INI file created by dir-stats.py and displays # directories containing a certain amount of data. # # ARGUMENTS # ========= # Call the script without any parameters to see an unsage mess...
4,603
1,385
import command_processor as command import discord async def process(message: discord.Message, is_owner, client: discord.Client): if message.author.id == client.user.id: return if not message.content.startswith('wh!'): return if message.channel.type != discord.ChannelType.text: awa...
602
158
import random import time import numpy as np import theano import theano.tensor as T from scipy.spatial.distance import pdist, squareform from tqdm import tqdm ''' Sample code to reproduce our results for the Bayesian neural network example. Our settings are almost the same as Hernandez-Lobato and Adams (ICML...
13,294
4,823
#coding:utf-8 ################################################################################ # ### Copyright (c) 2015 Baidu.com, Inc. All Rights Reserved # ################################################################################## """ This module provide configure file management service in i18n environment. ...
3,172
1,021
"""Kata url: https://www.codewars.com/kata/5a431c0de1ce0ec33a00000c.""" from typing import List def even_numbers(arr: List[int], n: int) -> List[int]: odds: List[int] = [x for x in arr if not x % 2] return odds[len(odds) - n:]
238
109
import datetime import json from typing import Any, Dict, Optional import requests from shapely.geometry import ( LineString, MultiLineString, MultiPoint, MultiPolygon, Point, Polygon, shape, ) from sqlalchemy.types import BOOLEAN, DATE from .base_loader import ( LOGGER, BaseLoader...
10,997
3,156
import os import yaml import xlrd from openpyxl import load_workbook from util_func import securely_check_dir class ExcelHandler: def __init__(self, config): self.config = config securely_check_dir('forms') securely_check_dir('att') securely_check_dir('config') self.sub...
4,123
1,074
from os.path import join from os.path import abspath from os.path import dirname from distutils.core import setup __author__ = 'Gregory Halverson' NAME = 'crs' EMAIL = 'gregory.halverson@gmail.com' URL = 'http://github.com/gregory-halverson/crs' with open(join(abspath(dirname(__file__)), NAME, 'version.txt')) as f: ...
564
194
from ipware.ip import get_ip from ipware.utils import is_private_ip def is_private_ip_from_request(request) -> bool: return is_private_ip(get_ip(request))
161
57
import os from nose import with_setup from nose.tools import assert_true import nibabel from nilearn.datasets.tests import test_utils as tst from nilearn.image import index_img from sammba.registration import base from sammba import testing_data from nilearn._utils.niimg_conversions import _check_same_fov @with_setup...
1,067
373
import urllib.request from bs4 import BeautifulSoup import matplotlib.pyplot as plt from PIL import Image import os def image_poster(title_address): url = f'{title_address}' req = urllib.request.Request(url) res = urllib.request.urlopen(url).read() soup = BeautifulSoup(res, 'html.parser') soup = ...
555
229
"""Multimodal omics analysis framework""" from ._core.mudata import MuData from ._core import preproc as pp from ._core import tools as tl from ._core import plot as pl from ._core import utils from ._core.io import * from ._core.config import set_options from . import atac from . import prot __version__ = "0.1.0" _...
376
137
# Copyright 2017 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Compiles trivial C++ program using Goma. Intended to be used as a very simple litmus test of Goma health on LUCI staging environment. Linux and OSX only....
2,756
991
# -*- coding: utf-8 -*- """Nowruz at SemEval 2022: Tackling Cloze Tests with Transformers and Ordinal Regression Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1RXkjBpzNJtc0WhhrKMjU-50rd5uSviX3 """ import torch import torch.nn as nn from torch.functio...
16,049
5,122
import re import json from time import time from random import random USER_AGENTS = [ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/601.1.10 (KHTML, like Gecko) Version/8.0....
1,703
824
''' This provides the view functions for the /api/libraries endpoints ''' import flask from flask import current_app class ApiEndpoint(object): def __init__(self, blueprint): blueprint.add_url_rule("/libraries/", view_func = self.get_libraries) blueprint.add_url_rule("/libraries/<int:collection_i...
964
284
import const def corpora2idx(sents, ind2idx): return [[ind2idx[w] if w in ind2idx else const.UNK for w in s] for s in sents]
131
52
# ########################################################### # ## generate menu # ########################################################### _a = request.application _c = request.controller _f = request.function response.title = '%s %s' % (_f, '/'.join(request.args)) response.subtitle = 'admin' response.menu = [(T('...
1,251
370
__author__ = 'sibirrer' # this file contains a class to make a Moffat profile __all__ = ['Moffat'] class Moffat(object): """ this class contains functions to evaluate a Moffat surface brightness profile .. math:: I(r) = I_0 * (1 + (r/\\alpha)^2)^{-\\beta} with :math:`I_0 = amp`. """ ...
1,159
425
from pypy.module.oracle.test.test_connect import OracleTestBase class AppTestObjectVar(OracleTestBase): def test_fetch_object(self): import datetime cur = self.cnx.cursor() try: cur.execute("drop table pypy_test_objtable") except oracle.DatabaseError: pass ...
1,912
571
tempratures = [10,-20, -289, 100] def c_to_f(c): if c<-273.15: return "" return c* 9/5 +32 def writeToFile(input): with open("output.txt","a") as file: file.write(input) for temp in tempratures: writeToFile(str(c_to_f(temp)))
250
117
import numpy as np from ignite.engine import Engine, Events import torch from .gcl_model import GeneralizedContrastiveICAModel from .trainer_util import random_pick_wrong_target, binary_logistic_loss from .logging_util import DummyRunLogger # Type hinting from typing import Callable from torch import FloatTensor, Long...
6,574
1,780
from django.conf import settings from requests import Session import os from json import dumps from core.celery import app @app.task(queue='cms') def send_new_contact_to_admins(contact: dict, admins: list) -> None: s = Session() data = {'admins': admins, 'contact': contact} url = settings.TELEGRAM_BOT_AP...
485
163
#!/usr/bin/env python3 # coding: utf-8 # Example 03 コンピュータお得意の繰り返しfor文 from sys import argv # 本プログラムの引数argvを取得する for name in argv: # 引数を変数nameへ代入 print('Hello,', name + '!') # 変数nameの内容を、文字列Helloに続いて表示 # for文の「argv」を「argv[1:]」にするとargv[1]以降の全引数を順次nameへ代入して繰り返す
316
173
''' A module for defining and producing the linekey object, which is used to determine and store information about data format in a CRREL ice mass balance buoy.''' class linekey: def __init__(self,date_index = 0): self.date_index = date_index self.value_index = [] self.phenomena_names = [...
5,929
1,727
from flask import Flask, render_template, session, redirect, url_for app = Flask(__name__) app.config['SECRET_KEY'] = 'prettyprinted' @app.route('/') def index(): return render_template('index.html') @app.route('/set-background/<mode>') def set_background(mode): session['mode'] = mode return ...
468
164
import random from collections import deque import networkx as nx from lib import puzzle def draw_grid(grid): min_y, max_y = 0, 0 min_x, max_x = 0, 0 for y, x in grid: if y < min_y: min_y = y if y > max_y: max_y = y if x < min_x: min_x = x ...
6,034
1,927
import torch import time from loss import CustomLoss from datagen import get_data_loader from model import PIXOR from utils import get_model_name, load_config, plot_bev, plot_label_map from postprocess import non_max_suppression def build_model(config, device, train=True): net = PIXOR(config['use_bn']...
6,741
2,281
# -------------- # Import packages import numpy as np import pandas as pd from scipy.stats import mode # code starts here bank=pd.read_csv(path) categorical_var=bank.select_dtypes(include='object') print(categorical_var) numerical_var=bank.select_dtypes(include='number') print(numerical_var) # code ends here...
1,595
639
# -*- coding: utf-8 -*- """ Example definition of a borehole. A top-view plot of the borehole is created and the borehole resistance is computed. """ from __future__ import absolute_import, division, print_function import pygfunction as gt from numpy import pi def main(): # Borehole dimensions H = 400. ...
3,039
1,038
# -*- coding: UTF-8 -*- from random import randint import math from project import matplt,database from geopy.geocoders import Nominatim from geopy import exc import os, shutil categ_coef = 17960 geolocator = Nominatim() def clean_temp_folder(folder): for the_file in os.listdir(folder): file_path = os.p...
2,409
855
#!/usr/bin/env python import os import re import argparse re_junk = re.compile(r'[._-]') re_spaces = re.compile(r'\s\s+') def print_rename(old_filename, new_filename): print('{} -> {}'.format(old_filename, new_filename)) def print_and_rename(old_path, new_path): print_rename(old_path, new_p...
1,914
676
import time requires = ['db'] def add_joined(bot, c, e): username, _, _ = e.source.partition('!') cur = bot.provides['db'].cursor() cur.execute('''INSERT INTO stalking (username, date, action, channel) VALUES (?, ?, ?, ?)''', (username, time.time(), 'join', e.target)) bot.provides['db'].commi...
1,007
347
# Copyright 2018-2020 Streamlit 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 wr...
7,968
2,328
# encoding: utf-8 """ build transform """ #import torchvision.transforms as T #from PIL import Image #from .transforms import RandomErasing,RandomErasingCorner from .data_preprocessing import TrainAugmentation_albu,TestAugmentation_albu,TrainAugmentation_bone,TestAugmentation_bone import torchvision.transforms as ...
4,047
1,625
import os class TestCase: def __init__(self, raw, filename="unknown", t=1.0): self.__raw = raw self.filename = filename self.src = self.__read_source() self.comment = self.__find_block("comment") self.input = self.__find_block("input") self.output = self.__format_ou...
2,039
633
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright 2019 Red Hat # GNU General Public License v3.0+ # (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) ############################################# # WARNING # ############################################# # # This file is au...
10,137
3,551
# MIT License # # Copyright (c) 2018 Evgeniy Filatov, evgeniyfilatov@gmail.com # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights #...
2,426
821
# Copyright 2017-2019 typed_python 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 law...
4,582
1,407
"""Module to add Employee fields to the User admin interface.""" from django.contrib import admin from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.contrib.auth.models import User from .models import Employee class EmployeeInline(admin.StackedInline): model = Employee can_delete =...
587
171
class VoiceClient(object): def __init__(self, base_obj): self.base_obj = base_obj self.api_resource = "/voice/v1/{}" def create(self, direction, to, caller_id, execution_logic, reference_logic='', count...
1,332
382
# -*- encoding: utf-8 import pytest from wechat.result import build_from_response from wechat.auth import MpOuthApi, get_mp_access_token @pytest.mark.usefixtures('response_builder') class TestAuth: def test_mp_auth_params(self, mocker, mp_appid, mp_secret): patched_request_execute = mocker.MagicMock( ...
1,865
593
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: users.proto """Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf ...
76,410
28,452
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations import logging from dataclasses import dataclass from pants.backend.codegen.thrift.apache.subsystem import ApacheThriftSubsystem from pants.backend.code...
6,974
2,063
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='DeliriumUser', fields=[ ('id', models.AutoField...
1,794
512
# good structure for an pytest test from app import shopping_cart def check_if_checkout_give_the_right_value(): ''' ''' arrange_array = [15,7, 10] # arrange shopping_cart_array = shopping_cart.checkout(arrange_array) # act assert shopping_cart_array == (31.99, 2.8, 34.79), "this check if the functi...
404
149
import os import salt.utils.platform from tests.support.mock import patch from tests.support.unit import TestCase, skipIf try: import salt.utils.win_system as win_system except Exception as exc: # pylint: disable=broad-except win_system = exc class WinSystemImportTestCase(TestCase): """ Simply impo...
17,658
5,349
""" """ from .const import * from . import container, widget class List(container.Container): def __init__(self, title=None, length=None, show_empty=True, size=20, **params): params.setdefault('cls','list') container.Container.__init__(self, **params) self.title = title self.font = self.style.font w,h =...
2,738
1,191
######################################### # The Simplest form of dash application # # ref: https://dash.plotly.com/introduction import dash import dash_html_components as html app = dash.Dash(__name__) # Layout compose app.layout = html.Div([ html.H1('Hello, this is a Dash Application'), ]) if __name__ == "__ma...
359
115
import rospy MIN_NUM = float('-inf') MAX_NUM = float('inf') class PID(object): def __init__(self, kp, ki, kd, max_input=MAX_NUM, mn=MIN_NUM, mx=MAX_NUM): self.kp = kp self.ki = ki self.kd = kd self.min = mn self.max = mx # Approximation - added self.max_ab...
1,409
474
#!python3 __version__ = '0.0.12'
33
19
"""Tests for the bradley_terry module""" # Copyright 2019 Dean Scarff # # 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 b...
4,017
1,617
class A: <error descr="function \"__init__\" cannot be async">async</error> def __init__(self): self.foo = '2' self.bar = '3' a = A() print(a.foo)
167
62
#!/usr/bin/env python3 """Log Analysis Project for Full Stack Nanodegree by Udacity""" import psycopg2 DBNAME = "news" def three_most_popular_articles(): """Queries and displays the top three most viewed articles.""" conn = psycopg2.connect(database=DBNAME) cur = conn.cursor() query = 'VIEW_top_thr...
1,967
637
print("File dd.py sucessfully executed")
40
12
import torch import torch.nn as nn import pytorch_lightning as pl from torchvision.models import ( alexnet, vgg16_bn, resnet18, resnet34, resnet50, densenet121, densenet161, ) from torch.nn import functional as F from pytorch_lightning.metrics.functional import accuracy, precision_recall c...
5,868
1,889
import logging import os import re import time import urllib from threading import Thread import xmlrpclib from Queue import Queue from flask import current_app as app, render_template, request, redirect, abort, jsonify, json as json_mod, url_for, session, Blueprint from itsdangerous import TimedSerializer, BadTimeSi...
12,132
3,248
class Solution(object): def _dfs(self,num,res,n): if num>n: return res.append(num) num=num*10 if num<=n: for i in xrange(10): self._dfs(num+i,res,n) def sovleOn(self,n): res=[] cur=1 for i in xrange(1,n+1): ...
972
333
import gi import time import os import json gi.require_version('Notify', '0.7') gi.require_version('Gtk', '3.0') from gi.repository import Notify, Gtk from gi.repository import Gio, GLib, GObject, Peas from gi.repository import RB from pypresence import Presence from status_prefs import discord_status_prefs class dis...
8,470
2,847