text string | size int64 | token_count int64 |
|---|---|---|
agenda = {
'João': '86988102987',
}
# (C)RUD
def criar():
# ler o nome
nome = input('Nome: ')
# ler o telefone e adiciona em uma lista telefonica
telefone = [input("Número de telefone: ")]
# empacota nome e telefone com uma variável
lista = (nome, telefone)
# adiciona o aluno ao dicioá... | 3,868 | 1,396 |
import smart_imports
smart_imports.all()
class ArenaPvP1x1Test(utils_testcase.TestCase, pvp_helpers.PvPTestsMixin):
def setUp(self):
super(ArenaPvP1x1Test, self).setUp()
game_logic.create_test_map()
self.account_1 = self.accounts_factory.create_account()
self.account_2 = self.... | 14,568 | 5,781 |
from functools import wraps
def debug(func):
msg = func.__qualname__
@wraps(func)
def wrapper(*args, **kwargs):
print(msg)
return func(*args, **kwargs)
return wrapper
@debug
def add(x, y):
"""
Función que suma dos números
"""
return x + y
@debug
def sub(x, y):
r... | 461 | 187 |
from rest_framework import generics, views, viewsets
from rest_framework.decorators import api_view
from rest_framework.parsers import FileUploadParser
from rest_framework.response import Response
from rest_framework import status
from django.http import Http404
from openpyxl import load_workbook, Workbook
from openpyx... | 1,918 | 637 |
from django.urls import path, include
from . import views
from rest_framework import routers
router = routers.DefaultRouter()
router.register('MyAPI', views.ApprovalsView)
urlpatterns = [
path('api/', include(router.urls)),
path('status/', views.approvereject),
path('form/', views.cxcontact, name='cxform')... | 377 | 119 |
'''
formulaGenerator generates XBRL formula linkbases for a subset of the Sphinx language.
(c) Copyright 2013 Mark V Systems Limited, California US, All rights reserved.
Mark V copyright applies to this software, which is licensed according to the terms of Arelle(r).
Sphinx is a Rules Language for XBRL described by... | 38,631 | 11,961 |
from datetime import timedelta
from django.core.management.base import BaseCommand
from django.utils import timezone
from audits.factories import (
AuditFactory,
AuditResultsFactory,
AuditStatusHistoryFactory,
)
from audits.models import Audit, AuditResults
from core.factories import AdminFactory, UserFact... | 2,900 | 807 |
"""n = int(input("Enter ThE number :"))
temp = n
new = 0
while temp > 0:
d = temp % 10
new = new * 10 + d
temp = temp //10
if n == new:
print("Number is palindrome")
else:
print("Number is not palindrome")
#print(palindrome(101))
"""
var1=str(input("Enter the sequence"))
x=var1[::-1]
if(var1==x):... | 409 | 165 |
#!/usr/bin/env python
import math
erato = [True]*150
primes = []
for i in xrange(2, 150):
if erato[i]:
if i % 4 == 1:
primes.append(i)
j = i + i
while j < 150:
erato[j] = False
j += i
print primes
print len(primes)
print 2**len(primes)
mul = 1
for p in p... | 368 | 153 |
#
# PySNMP MIB module TOS-SMI (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TOS-SMI
# Produced by pysmi-0.3.4 at Wed May 1 15:24:00 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)... | 2,869 | 1,181 |
# Copyright 2015 Abhijit Menon-Sen <ams@2ndQuadrant.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any ... | 7,493 | 2,759 |
class Translation(object):
START_TEXT = """Hello <i><b>{}</b></i>,
I Can rename ✍ with custom thumbnail and upload as video/file
Type /help for more details."""
DOWNLOAD_START_VIDEO = "Downloading Video to my server.....📥"
DOWNLOAD_START = "Downloading File to my server.....📥"
UPLOAD_START_VIDEO = "Up... | 2,354 | 883 |
# coding=utf-8
from django.core import serializers
serializers.register_serializer('json', 'djmoney.serializers')
| 116 | 37 |
import sys
class RedirectStdoutTo:
def __init__(self, out_new):
self.out_new = out_new
def __enter__(self):
self.out_old = sys.stdout
sys.stdout = self.out_new
def __exit__(self, *args):
sys.stdout = self.out_old
print('A')
with open('../resource/txt/output/out.log', mo... | 409 | 151 |
import pyparsing as pp
def act_comment(token):
print("comment: " + str(token))
def act_keyword(token):
print("keyword: " + str(token))
def act_sc(token):
print("semicolon: " + str(token))
def act_parser_start(token):
print("parser_start: " + str(token))
def act_parser_end(token):
print("parser_end: " + s... | 1,495 | 607 |
# Copyright 2021-2022 NVIDIA Corporation
#
# 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 ... | 1,537 | 650 |
from typing import Any, Dict
DictStrAny = Dict[str, Any]
| 61 | 25 |
# Copyright (C) 2017 TU Dresden
# Licensed under the ISC license (see LICENSE.txt)
#
# Authors: Christian Menard
import logging
from hydra.utils import to_absolute_path
from .convert import convert
from .parse import parse
from mocasin.common.platform import Platform
log = logging.getLogger(__name__)
class MapsP... | 1,005 | 295 |
# Generated by Django 2.0.2 on 2019-02-24 03:27
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('trade', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='shoppingcart',
... | 866 | 306 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# filename: classifier.py
# modified: 2019-09-08
__all__ = ["KNN","SVM","RandomForest"]
import os
import re
from sklearn.neighbors.classification import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.ensemble.forest import RandomForestClassifier
from sklea... | 2,020 | 713 |
import numpy as np
import sys
import timeit
from pykalman import KalmanFilter
N = int(sys.argv[1])
random_state = np.random.RandomState(0)
transition_matrix = [[1, 0.01], [-0.01, 1]]
transition_offset = [0.0,0.0]
observation_matrix = [1.0,0]
observation_offset = [0.0]
transition_covariance = 1e-10*np.eye(2)
observatio... | 1,077 | 415 |
"""
Compat. layer between LWR and Galaxy.
"""
| 46 | 17 |
# vim: set fenc=utf8 ts=4 sw=4 et :
import os
import io
import json
import unittest
from shlex import split
from .testcase import TestCase
from pdml2flow.conf import Conf
import pdml2flow
TEST_DIR_PDML2FLOW="test/pdml2flow_tests/"
TEST_DIR_PDML2FRAME="test/pdml2frame_tests/"
class TestSystem(TestCase):
def rea... | 3,419 | 960 |
import time, datetime
print("Importing OpenShift/Kubernetes packages ...")
import kubernetes
import ocp_resources
import openshift
from ocp_resources.node import Node
from ocp_resources.machine import Machine
from ocp_resources.node import Node
from openshift.dynamic import DynamicClient
try:
client_k8s = Dynam... | 3,258 | 1,016 |
from django.conf.urls import url
from . import views
app_name = 'artists'
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'),
url(r'^edit/(?P<pk>\d+)/$', views.UpdateArtist.as_view(), name='edit'),
url(r'^create/$',... | 446 | 176 |
import socket
import struct
send_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0)
data_bytes = struct.pack("!BBBB", 0, 0, 255, 255)
header = struct.pack("!BIIH", 0, 0, 0, len(data_bytes))
message = header + data_bytes
send_sock.sendto(message, ("localhost", 42000)) | 280 | 123 |
# -*- coding: utf-8 -*-
import remi
import remi.gui as gui
from remi.gui import *
from threading import Timer
import traceback
import time
import math
import epics
#from epics import caget, caput, cainfo
style_inheritance_dict = {'opacity':'inherit', 'overflow':'inherit', 'background-color':'inherit', 'background-ima... | 26,634 | 13,518 |
from typing import Dict
import pysftp
from flask import Blueprint, current_app
from paramiko import SSHException
from models import Instrument
from pkg.case_mover import CaseMover
from pkg.google_storage import GoogleStorage
from pkg.sftp import SFTP
from util.service_logging import log
mover = Blueprint("batch", __... | 3,001 | 939 |
import re, datetime
from Helpers.freezable_list import FrozenDict
from pytjson.Exceptions import ParseError
class Datatype:
# Initializer, will be overriden below
TAGS = {}
isScalar = re.compile(r'^[a-z0-9]*$')
isBin = re.compile('^[01]{8}$')
isOnlyNumbers = re.compile('^\-?(0|[1-9][0-9]*)$')
i... | 3,156 | 996 |
# not working, not sure why (as parts work separately
# outside of function)
# (User's) Problem
# We have:
# a string
# We need:
# is that string a paindrome? yes/no
# We must:
# boolean output
# name of function is
# checkPalindrome
# Solution (Product)
# Strategy 1:
# turn string into a list... | 864 | 261 |
"""
/*********************************************************************************/
* The MIT License (MIT) *
* *
* Copyright (c) 2014 EOX IT Services GmbH ... | 13,296 | 4,146 |
from __future__ import absolute_import, division, print_function
from cfn_model.model.ModelElement import ModelElement
class EC2NetworkInterface(ModelElement):
"""
Ec2 network interface model lement
"""
def __init__(self, cfn_model):
"""
Initialize
:param cfn_model:
""... | 579 | 173 |
"""Provide mock structures used accross the tests."""
from typing import List, Union
class NumpyArray:
"""Represent a class that mocks a numpy.array and it's behavior on less-then operator."""
def __init__(self, values: List[Union[int, bool]]) -> None:
"""Initialize with the given values."""
... | 1,125 | 319 |
#!/usr/bin/env python3
# coding: utf8
"""
Description:
Using fasta files (scaffold/chromosme/contig file, protein file), gff file, annotation tsv file and the species name
this script writes a genbank file.
The annotation tsv file contains association between gene and annotation (EC number, GO term, Interpro)
to add ... | 24,381 | 7,365 |
#FLM: Adjust Anchors
__copyright__ = __license__ = """
Copyright (c) 2010-2012 Adobe Systems Incorporated. All rights reserved.
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 restrictio... | 14,362 | 6,741 |
import copy
from math import floor
from Objects.Object import Object
class Repeater(Object):
def __init__(self, isVisible, position, content, pixellength, numRepeats=-1, spacing=0):
super().__init__(isVisible, position, content)
self.numRepeats = numRepeats
self.spacing = spacing
... | 661 | 217 |
from django import forms
class SearchForm(forms.Form):
CHOICES = [
(u'ISBN', u'ISBN'),
(u'书名', u'书名'),
(u'作者', u'作者')
]
search_by = forms.ChoiceField(
label='',
choices=CHOICES,
widget=forms.RadioSelect(),
ini... | 627 | 195 |
"""
Modified from https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py
Edits:
ResNet:
- Changed input layer from 3 channel -> 1 channel (depth images)
- Divided inplanes, planes, and width_per_group by 4
BasicBlock:
- Commented out ValueError triggered by base_width ... | 7,173 | 2,456 |
# -*- coding: utf-8 -*-
"""
Author:by 王林清 on 2021/11/2 21:32
FileName:insertMongodb.py in shiyizhonghua_resource
Tools:PyCharm python3.8.4
"""
from pymongo import MongoClient
from util import *
if __name__ == '__main__':
dir_name = r'./../database_json'
paths = get_file_path(dir_name)
host = '114.55.236.... | 717 | 263 |
import unittest
import atheris
import atheris_libprotobuf_mutator
from atheris import fuzz_test_lib
from google.protobuf import wrappers_pb2
@atheris.instrument_func
def simple_proto_comparison(msg):
if msg.value == "abc":
raise RuntimeError("Solved")
class AtherisLibprotobufMutatorTests(unittest.TestCase):
... | 641 | 220 |
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import os
import pdb
from tqdm import tqdm
import argparse
import pandas as pd
import sys
BASE_DIR=os.path.dirname(os.getcwd())
sys.path.append(BASE_DIR)
sys.path.append('/home/tam63/geometric-js')
import torch
import scipy.stats
from scipy.... | 13,028 | 4,925 |
from bs4 import BeautifulSoup
import requests,datetime
top_news = {"world":[],"business":[],"technology":[],"sports":[],"entertainment":[]}
def Scraper_news():
new_dic = {}
URLS_of_menu = {"world":"http://www.newzcone.com/world/","business":"http://www.newzcone.com/business/","technology":"http://www.newzcone.com/te... | 1,234 | 516 |
import telraam_data.query as query
import telraam_data.download as download
from .utils import get_data_keys
import datetime as dt
import shutil
import pandas as pd
import pathlib as pl
import random
import pytest
@pytest.fixture()
def one_segment():
all_segments = query.query_active_segments()
segment_idx = ... | 2,388 | 857 |
# encoding: utf-8
# author: BrikerMan
# contact: eliyar917@gmail.com
# blog: https://eliyar.biz
# file: abs_task_model.py
# time: 1:43 下午
import json
import os
import pathlib
from abc import ABC, abstractmethod
from typing import Dict, Any, TYPE_CHECKING, Union
import tensorflow as tf
import kashgari
from kashgari... | 4,544 | 1,428 |
# coding: utf-8
def write_info(amr):
#import fortranformat as ff
#nout = amr.nout
aexp = amr.aexp
h0 = amr.h0 * 1e-2
rhoc = 1.88e-29
boxlen = 1.0
f = open("info_" + str(nout).zfill(5) + ".txt", 'w')
for name, val in zip(["ncpu", "ndim", "levelmin", "levelmax", "ngridmax", "ns... | 1,915 | 840 |
from collections import defaultdict, Counter, deque
from functools import cache
from itertools import product, pairwise
from multiprocessing import Pool
import math
import re
non_digits = re.compile('[^0-9]+')
def sign(a, b, step=1):
return int(math.copysign(step, b-a))
def autorange(a,b, step=1):
if a == b:re... | 3,794 | 1,545 |
#!/usr/bin/python
# coding: utf-8
# __author__ jax777
import os
import cgi
import json
import urllib
import hashlib
import datetime
import tornado.ioloop
import tornado.web
import traceback
from tornado.escape import json_decode
from multiprocessing import Process
from sqllitedb import *
from DnsServer import dns_serv... | 4,773 | 1,592 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import ee
from landdegradation.util import TEImage
from landdegradation.schemas.schemas import BandInfo
def download(asset, name, temporal_resolution, start_year, end_year,
EXECUTION_ID, logger)... | 1,348 | 466 |
# coding=utf-8
# Copyright 2021 The TensorFlow Datasets 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 appl... | 1,344 | 397 |
import pytest
import numpy as np
@pytest.fixture
def n():
"""Number of arrays"""
return 3
| 100 | 36 |
def test_list_labels(man):
errors = []
G = man.setGraph("swapi")
resp = G.listLabels()
print(resp)
if len(resp["vertex_labels"]) != 6:
errors.append("listLabels returned an unexpected number of vertex labels; %d != 2" % (len(resp["vertex_labels"])))
if sorted(resp["vertex_labels"])... | 865 | 279 |
#!/usr/bin/python
# -----------------------------------------------------------------------------
#
# Copyright 2013-2019 lispers.net - Dino Farinacci <farinacci@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 o... | 26,025 | 15,045 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.10 on 2018-03-06 16:44
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrati... | 2,409 | 658 |
# https://justhackerthings.com/post/building-a-dark-web-scraper/
import sys
def main():
# Disable SSL warnings
try:
import requests.packages.urllib3
requests.packages.urllib3.disable_warnings()
except:
pass
START = sys.argv[1]
if __name__ == "__main__":
main()
| 311 | 109 |
from os.path import dirname
from ipkg.build import Formula, File
class foo(Formula):
name = 'foo'
version = '1.0'
sources = File(dirname(__file__) + '/../../sources/foo-1.0.tar.gz')
platform = 'any'
def install(self):
self.run_cp(['README', self.environment.prefix + '/foo.README'])
| 316 | 111 |
#!/usr/bin/env python
def sum_even_fib(limit):
fib_list = [1, 2]
even_fib_list = [2]
next_fib = fib_list[-1] + fib_list[-2]
while(next_fib <= limit):
next_fib = fib_list[-1] + fib_list[-2]
fib_list.append(next_fib)
if next_fib % 2 == 0:
even_fib_list.append(next_fi... | 778 | 348 |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Copyright (c) 2002-2019 "Neo4j,"
# Neo4j Sweden AB [http://neo4j.com]
#
# This file is part of Neo4j.
#
# 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 L... | 7,660 | 2,473 |
import pandas as pd
from bokeh.plotting import figure
from bokeh.sampledata.stocks import AAPL
def get_template():
df = pd.DataFrame(AAPL)
df['date'] = pd.to_datetime(df['date'])
import jinja2
from bokeh.embed import components
# IMPORTANT NOTE!! The version of BokehJS loaded in the template sh... | 1,596 | 610 |
from app.nanoleaf.model import AuroraObject
class PanelLayout(AuroraObject):
def __init__(self, requester, rhythm):
super().__init__(requester)
self.rhythm = rhythm
@property
def orientation(self):
"""Returns the orientation of the device (0-360)"""
return self._requester.... | 1,728 | 462 |
import tensorflow as tf
from sklearn.model_selection import train_test_split
import unicodedata
import re
import io
'''
Handles data loading, pre-processing and tokenizing
'''
class DataHandler():
'''
Creates a tf.data.Dataset object to feed the network
with tensors and in batches
X: (tensor) with inpu... | 3,243 | 1,262 |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: wxnacy@gmail.com
"""
随机方法
"""
import pytest
import os
from wpy.path import read_dict
from wpy.randoms import (
random_str
)
from lfsdb import FileStorage
from lfsdb.db import FileStorageError
from lfsdb.db.errors import FSQueryError
from lfsdb.d... | 4,060 | 1,613 |
import re
example = "".join(open("example.txt").readlines())
puzzle = "".join(open("puzzle.txt").readlines())
problem_input = puzzle
def parse_group(input: str):
votes = input.split("\n")
votes_map = dict()
for vote in votes:
for el in vote:
if el not in votes_map:
vo... | 865 | 304 |
import asyncio
import logging
import os
import unittest
from integration_tests.env_variable_names import SLACK_SDK_TEST_USER_TOKEN
from integration_tests.helpers import async_test
from slack import WebClient
class TestWebClient(unittest.TestCase):
"""Runs integration tests with real Slack API
https://github... | 1,154 | 373 |
from threading import RLock
from typing import Any, Callable, Dict, Iterable, List, Optional, Set, Tuple
from triad import to_uuid
from tune.concepts.flow import (
Monitor,
Trial,
TrialDecision,
TrialJudge,
TrialReport,
TrialReportHeap,
)
class RungHeap:
def __init__(self, n: int):
... | 7,199 | 2,248 |
from django.contrib.auth.models import AbstractUser
import markdown
from .base import MarkupEngine
class Markdown(MarkupEngine):
label = "Markdown"
extensions = ["extra"]
def to_html(self, raw: str, user: AbstractUser) -> str:
md = markdown.markdown(raw, extensions=self.extensions)
retu... | 326 | 97 |
from .default import dr27_stats_urls
urlpatterns = dr27_stats_urls('team') | 75 | 28 |
# Copyright Jamie Allsop 2015-2015
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
#-------------------------------------------------------------------------------
# MarkdownToHtmlMethod
#--... | 1,936 | 606 |
import re
import json
import sys
import os
args = sys.argv
if (len(args) < 2):
sys.exit(1)
path = args[1]
if(path[-1:] == "/"):
path = path[:-1]
result_filedata_list = []
registry_info = {}
target_filepath_list = []
target_filepath_list.append('/1/stdout.txt')
target_filepath_list.append('/3/stdout.txt')
f... | 3,718 | 1,006 |
import pickle
import os
import numpy as np
from .utils import make_dataset_images, find_classes
from operator import itemgetter
import copy
class Dataset(object):
def __init__(self, name, root_folder, im_size=None, in_memory=False):
super(Dataset, self).__init__()
self.name = name
self.ima... | 5,603 | 1,834 |
from video.segment import CodecCopyHLSFormatSegmenter
from video.segment import CodecX264HLSFormatSegmenter
from video.segment import CodecX264SegmentFormatSegmenter
from video.segment import CodecX264ResizeHLSFormatSegmenter
from video.snapshot import take_snapshot
import os
import pathlib
import argparse
PROJECT_ROO... | 1,108 | 386 |
""" Implement the transformations we need to use
to convert a link to an adaptive loss scaled link. """
# NOTE: this file is deprecated
import chainer
import chainer.links as L
import chainer.initializers as I
# pylint: disable=unused-wildcard-import
from ada_loss.chainer_impl.links import *
__all__ = [
"Ada... | 1,565 | 496 |
from abc import ABC, abstractmethod
from elasticsearch_dsl import query
from elasticsearch_dsl.query import MatchPhrasePrefix, Term, Bool, Match, MatchAll
class QueryBuilderStrategy(ABC):
def __init__(self, searchInput):
self.name = searchInput.get('name')
self.region = searchInput.get('region')
... | 2,294 | 612 |
"""
The main app where all the routes are initiated here and runs the flask app
"""
from resources.auth import *
from resources.reset import *
from resources.userdetails import *
from resources.course import *
from resources.groups import *
from resources.delivery import *
from resources.dashboard_api import *
from re... | 2,002 | 725 |
from foundations_spec import *
from acceptance.api_acceptance_test_case_base import APIAcceptanceTestCaseBase
from acceptance.v2beta.jobs_tests_helper_mixin_v2 import JobsTestsHelperMixinV2
class TestArtifactLoading(JobsTestsHelperMixinV2, APIAcceptanceTestCaseBase):
url = '/api/v2beta/projects/{_project_name}/... | 4,451 | 1,377 |
import os, sys, copy
import pickle
import math
import time
import numpy as np
from typing import Dict, Any, List, Set, Tuple
import torch
import torch.nn.functional as F
from torch import nn
from torch.nn.utils.rnn import pad_sequence
import torch.nn.utils.rnn as rnn_utils
from agent.environment.position import Pos... | 16,234 | 5,181 |
#! /usr/bin/python
# -*- coding: utf-8 -*-
import tensorflow as tf
import tensorlayer as tl
from tensorlayer import logging
from tensorlayer.decorators import deprecated_alias
from tensorlayer.layers.core import Layer
__all__ = [
'GaussianNoise',
]
class GaussianNoise(Layer):
"""
The :class:`GaussianNo... | 2,247 | 731 |
#!/usr/bin/python3
# coding=utf-8
import abc
from aiautomation.testcase.browser import Browser
class ScenariosRecovery:
"""
场景恢复的基类
"""
__metaclass__ = abc.ABCMeta
def __init__(self, logger, config):
self._browser = None
self._logger = logger
self._config = config
@ab... | 447 | 156 |
from pynverse import inversefunc, piecewise
import numpy as np
import matplotlib.pyplot as plt
import scipy
cube = lambda x: x**3
invcube = inversefunc(cube)
invcube_a = lambda x: scipy.special.cbrt(x)
square = lambda x: x**2
invsquare = inversefunc(square, domain=0)
invsquare_a = lambda x: x**(1/2.)
... | 2,195 | 1,160 |
def fatorial(num=1):
f = 1
for c in range(num, 1, -1):
f *= c
return f
n = int(input('Digite um numero: '))
print(f'O fatorial de {n}: {fatorial(n)}')
| 174 | 77 |
from tests.isolated_testcase import IsolatedTestCase
class NevermindTest(IsolatedTestCase):
def test_nevermind(self):
self.assertCommand('!nevermind', 'I\'m sorry :(')
self.assertCommand('!nm', 'I\'m sorry :(')
self.assertCommand('!nEverMINd', 'I\'m sorry :(')
self.assertCommand('... | 686 | 237 |
#!C:\Python34\scrapper\Scripts
# Place url, linking to ad list, with desired search filters here.
url_to_scrape = "http://www.kijiji.ca/b-canot-kayak-paddle-board/quebec/kayak/k0c329l9001"
# Set the delay in (s) that the programs waits before scraping again.
scrape_delay = 600 # 600 = 10 mins
# Set filename to stor... | 6,017 | 2,041 |
#!/usr/bin/python
import argparse
import datetime
import json
import re
import sys
from calendar_service import CalendarService
from icalendar import Calendar, Event, vDatetime, vText
from logger import Logger
from oauth2client.client import AccessTokenRefreshError
from pytz import reference
logger = Logger()
... | 10,303 | 3,008 |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: kikimr/public/api/protos/ydb_discovery.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.proto... | 13,401 | 5,194 |
from unittest.mock import patch
from tests.test_rrpproxy_base import TestRRPProxyBase
class TestRRPProxyCheckContact(TestRRPProxyBase):
@patch('rrpproxy.RRPProxy.call')
def test_calls_call_correctly(self, call_mock):
response = self.proxy.check_contact('CONTACT-A')
call_mock.assert_called_on... | 424 | 145 |
'''
Script to run a "Hello World" using Python 3.X and Flask.
'''
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello, World!"
if __name__ == "__main__":
app.run()
| 209 | 79 |
import os
def parse_mount(volume_spec):
# Docker volumes may be "/src:dest:ro" or simply "/src"
components = volume_spec.split(':')
perm = 'w' # assume write perm if not specified
src_path = components[0]
# check if ro specified
if components[-1] == 'ro':
perm = 'r'
return (src_path, perm)
| 310 | 105 |
from __future__ import print_function
import os, sys
if sys.version_info[0] != 3 or sys.version_info[1] < 0:
print('Your Python version is too old! Please use Python 3.0 or higher.')
sys.exit(1)
import hashlib
import fnmatch
import configparser
import argparse
import platform
os.chdir(os.path.di... | 20,415 | 6,324 |
from io import StringIO
from cms.constants import TEMPLATE_INHERITANCE_MAGIC
from cms.models import Page
from cms.models.pluginmodel import CMSPlugin
from cms.models.static_placeholder import StaticPlaceholder
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.sites.mod... | 13,208 | 4,055 |
from twisted.python.components import registerAdapter
from axiom.attributes import reference
from axiom.item import Item
from nevow.page import Element
from xmantissa.ixmantissa import INavigableElement, INavigableFragment
from xmantissa.webnav import Tab
from zope.interface import implements, Interface
class ISuspend... | 2,499 | 727 |
##############################################
# The MIT License (MIT)
# Copyright (c) 2019 Kevin Walchko
# see LICENSE for full details
##############################################
from __future__ import print_function
from setuptools import setup
from build_utils import BuildCommand
from build_utils import Publis... | 1,889 | 575 |
# Scientific Library
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# Standard Library
from collections import defaultdict
from concurrent.futures import ThreadPoolExecutor
from functools import partial
from importlib import reload
import logging
import os
from pathlib import Path
# Third Part... | 9,244 | 3,390 |
########################################################################
## Combo box with string value interface
########################################################################
from PyQt5.QtWidgets import QComboBox
from PyQt5.QtCore import pyqtSignal
class StringValueComboBox(QComboBox):
valueChanged = p... | 1,152 | 303 |
import logging
from docker_monitor.policy import PolicyCheck
logger = logging.getLogger(__name__)
class ActiveBuildCheck(PolicyCheck):
description = "is actively building"
def __call__(self, container):
# return self.PASS_FAST
return self.PASS
| 274 | 77 |
import sys
from common import TOMBSTONE, Value
from binio import kv_iter, kv_writer
from typing import List, Optional, Tuple
from os import scandir, stat
from sstable import SSTable
MIN_THRESHOLD = 4
MIN_SIZE = 50000000
class Bucket:
def __init__(self):
self.min = 0
self.max = 0
self.avg ... | 2,433 | 785 |
from mrl.import_all import *
from argparse import Namespace
import gym
import time
def make_ddpg_agent(base_config=default_ddpg_config,
args=Namespace(env='InvertedPendulum-v2',
tb='',
parent_folder='/tmp/mrl',
... | 8,002 | 2,682 |
# Note that this will erase your nvidia cache, ~/.nv/ComputeCache This may or may not be an undesirable side-effect for you. For example, cutorch will take 1-2 minutes or so to start after this cache has been emptied.
from __future__ import print_function, division
import time
import string
import random
import nump... | 4,036 | 1,542 |
# Copyright 2020 The Johns Hopkins University Applied Physics Laboratory
#
# 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... | 4,827 | 1,410 |
import sublime
import sublime_plugin
from collections import defaultdict
from math import log10, floor, ceil
import threading
from subprocess import check_output
import re
import itertools
# pass in a variable name and an optional default value
# to get what that value is set to in settings
def settings(name, default... | 15,454 | 4,662 |
import sys, json, random
from rasa_nlu.model import Interpreter
from pprint import pprint
interpreter = Interpreter.load("models\\current\\nlu")
responses_file = sys.argv[1]
responses = json.load(open(responses_file))
while True:
question = input("> ")
response = interpreter.parse(question)
pprint(respo... | 507 | 160 |
class Solution(object):
def XXX(self, s):
"""
:type s: str
:rtype: bool
"""
s = "".join([ch.lower() for ch in s if ch.isalnum()])
return s == s[::-1]
| 204 | 73 |