text
string
size
int64
token_count
int64
import subprocess def execute(cmd): return subprocess.check_output(cmd)
77
24
# Copyright (c) 2021 kamyu. All rights reserved. # # Google Code Jam 2014 Round 2 - Problem A. Data Packing # https://codingcompetitions.withgoogle.com/codejam/round/0000000000432fed/0000000000432b8d # # Time: O(NlogN) # Space: O(1) # def data_packing(): N, X = map(int, raw_input().strip().split()) S = map(in...
648
269
""" Description: Class for training CNNs using a nested cross-validation method. Train on the inner_fold to obtain optimized hyperparameters. Train outer_fold to obtain classification performance. """ from braindecode.datautil.iterators import BalancedBatchSizeIterator from braindecode.experiments.stopcriteria imp...
18,950
6,336
import datetime from collections import Counter from functools import wraps from dateparser import parse as parse_date from calmlib import get_current_date, get_current_datetime, to_date, trim from .base import Task from .str_database import STRDatabase from .telegram_bot import TelegramBot, command, catch_errors DE...
7,462
2,142
# lower , title , upper operations on string x = "spider" y = "MAN" v=x.upper() # all letters will become uppercase w=y.lower() # all letters will become lowercase z=y.title() # only first letter will become upper and rest of all lowercase print(v,w,z)
258
86
"""Setup script for sfcpy""" import os.path from setuptools import setup # The directory containing this file HERE = os.path.abspath(os.path.dirname(__file__)) # The text of the README file with open(os.path.join(HERE, "README.md"), encoding='utf-8') as fid: README = fid.read() # This call to setup() does all t...
1,197
384
#!/usr/bin/env python3 import csv import os from collections import namedtuple import string from nameparser import HumanName def csv_to_dict(filename): file_dict = dict() with open(filename, 'r', newline='', encoding='utf-8') as csvfile: csvreader = csv.reader(csvfile, delimiter='\t', quotechar='"'...
7,921
2,382
# -*- coding: utf-8 -*- from typing import Optional, Any import redis from pip_services3_commons.config import IConfigurable, ConfigParams from pip_services3_commons.errors import ConfigException, InvalidStateException from pip_services3_commons.refer import IReferenceable, IReferences from pip_services3_commons.run i...
7,524
1,970
# coding: utf-8 from __future__ import absolute_import from google.appengine.ext import ndb from api import fields import model import util class Property(model.Base): name = ndb.StringProperty(required=True) rank = ndb.IntegerProperty(default=0) verbose_name = ndb.StringProperty(default='') show_on_view ...
7,392
2,542
import pytest from wired import ServiceContainer @pytest.fixture def request_container(registry, simple_root) -> ServiceContainer: from wired_components.request import wired_setup as request_setup from wired_components.resource import IRoot from wired_components.url import IUrl, Url # Outside system ...
1,189
331
# -*- coding: utf-8 -*- """ Created on Mon May 17 21:24:53 2021 @author: Akshay Prakash """ import pandas as pd import numpy as np import matplotlib.pyplot as plt table = pd.read_csv(r'\1617table.csv') table.head() plt.hlines(y= np.arange(1, 21), xmin = 0, xmax = table['Pts'], color = 'skyblue') plt.p...
958
498
#!/usr/bin/env python import sys import lxml.etree def main(): if len(sys.argv) < 3: sys.stderr.write('ERROR: Must provide at least 2 KML files to merge\n') sys.exit('Usage: {} FILE1 FILE2 ...'.format(sys.argv[0])) first_kml_root = lxml.etree.parse(sys.argv[1]).getroot() first_kml_ns...
1,126
382
# -*- coding: utf-8 -*- DESC = "partners-2018-03-21" INFO = { "AgentPayDeals": { "params": [ { "name": "OwnerUin", "desc": "订单所有者uin" }, { "name": "AgentPay", "desc": "代付标志,1:代付;0:自付" }, { "name": "DealNames", "desc": "订单号数组" } ...
3,829
1,988
""" The default configuration, from which all others should be derived """ import os, plugins, sandbox, console, rundependent, comparetest, batch, performance, subprocess, operator, logging from copy import copy from string import Template from fnmatch import fnmatch from threading import Thread # For back-compatibi...
83,387
22,369
# This problem was recently asked by LinkedIn: # Given a non-empty array where each element represents a digit of a non-negative integer, add one to the integer. # The most significant digit is at the front of the array and each element in the array contains only one digit. # Furthermore, the integer does not have lea...
747
231
import subprocess import sys import os class ExecutionInfo: def __init__(self, p_status: int, stdout: str, stderr: str): self.p_status = p_status self.stdout = stdout self.stderr = stderr def exit_fail(msg: str = "") -> None: print(msg) sys.exit(-1) def exit_ok(msg: str = "") ...
1,122
412
from pathlib import Path import altair as alt import folium import matplotlib.pyplot as plt import numpy as np import pandas as pd import plotly.graph_objects as p_go import pytest from bokeh.layouts import column from bokeh.models import ColumnDataSource from bokeh.plotting import figure from pandas.io.formats.style ...
2,614
972
NEWS_API_KEY= '138b22df68394ecbaa9c9af0d0377adb' SECRET_KEY= 'f9bf78b9a18ce6d46a0cd2b0b86df9da'
95
73
import os import logging import sys import structlog from structlog.stdlib import LoggerFactory, add_log_level _configured = False def configure(force = False): """ Configures logging & structlog modules Keyword Arguments: force: Force to reconfigure logging. """ global _configured if ...
1,417
384
# setup.py # Copyright (c) 2015-2017 Arkadiusz Bokowy # # This file is a part of pyexec. # # This project is licensed under the terms of the MIT license. from setuptools import setup import pyexec with open("README.rst") as f: long_description = f.read() setup( name="pyexec", version=pyexec.__version__...
878
292
'''Functional tests for the equational constraint.''' import cytest # from ./lib; must be first class TestEqConstr(cytest.FunctionalTestCase): SOURCE_DIR = 'data/curry/eqconstr/' PRINT_SKIPPED_GOALS = True # RUN_ONLY = ['a0_.[02468][048]', 'a0b0c0_.[037][048]', 'prog0.'] # A subset for quick checks. # SKIP = [...
323
136
# # (c) 2022 Sven Lieber # KBR Brussels # #import xml.etree.ElementTree as ET import lxml.etree as ET import os import json import itertools import enchant import hashlib import csv from optparse import OptionParser import utils import stdnum NS_MARCSLIM = 'http://www.loc.gov/MARC21/slim' ALL_NS = {'marc': NS_MARCSLI...
4,898
1,671
#!/bin/python import time import random from multiprocessing import Pool, Process, Pipe, TimeoutError from multiprocessing.pool import ThreadPool class EvaluationPool(): def __init__(self, EvaluationTool, Urls, poolsize): self.EvaluationTool = EvaluationTool self.Urls = Urls self.lasttim...
3,886
1,247
from canvas.cache_patterns import CachedCall from drawquest import knobs from drawquest.apps.drawquest_auth.models import User from drawquest.apps.drawquest_auth.details_models import UserDetails from drawquest.pagination import FakePaginator def _sorted(users): return sorted(users, key=lambda user: user.username...
3,001
937
import numpy as np def translationMatrix(dx=0, dy=0, dz=0): return np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [dx, dy, dz, 1]]) def scalingMatrix(sx=1, sy=1, sz=1): return np.array([[sx, 0, 0, 0], [0, sy, 0...
3,674
1,420
from ._src.multiply import multiply_outer as outer # noqa: F401
65
24
#!/usr/bin/env python from os.path import join from setuptools import find_packages, setup # DEPENDENCIES def requirements_from_pip(filename): with open(filename, "r") as pip: return [line.strip() for line in pip if not line.startswith("#") and line.strip()] core_deps = requirements_from_pip("requireme...
1,258
408
# coding: utf-8 from __future__ import unicode_literals from .common import InfoExtractor from .jwplatform import JWPlatformIE class BusinessInsiderIE(InfoExtractor): _VALID_URL = r'https?://(?:[^/]+\.)?businessinsider\.(?:com|nl)/(?:[^/]+/)*(?P<id>[^/?#&]+)' _TESTS = [{ 'url': 'http://uk.businessins...
1,632
659
import plotly.express as px import pandas as pd data = pd.read_csv('kc_house_data.csv') data_mapa = data[['id', 'lat', 'long', 'price']] grafico1 = px.scatter_mapbox(data_mapa, lat='lat', lon='long', hover_name='id', hover_data=['price'], color_discrete_sequen...
578
218
#!/usr/bin/python from datadog import initialize, api options = { 'api_key': '17370fa45ebc4a8184d3dde9f8189c38', 'app_key': 'b0d652bbd1d861656723c1a93bc1a2f22d493d57' } initialize(**options) title = "Ryan Great Timeboard" description = "My Timeboard that is super awesome" graphs = [ { "title": "My Metric ove...
1,561
631
import numpy as np import math import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D def get_spin(radius_scale, height_scale, rounds): xs, ys, zs = [], [], [] theta = 0.0 delta = 0.1 twopi = math.pi * 2.0 for i in range(int(rounds * twopi / delta)): theta += delta ...
732
303
import os.path from bs4 import BeautifulSoup import requests # Location of file to store latest known page number LAST_KNOWN_PAGE_FILE = "/tmp/rotation_checker_latest" # URL of forum thread where latest rotations are posted ROTATION_FORUM_THREAD = "https://us.battle.net/forums/en/heroes/topic/17936383460" def write_...
1,911
676
# fidelis/credentials.py import datetime import requests import threading from dateutil.tz import tzlocal from collections import namedtuple def _local_now(): return datetime.datetime.now(tzlocal()) class FidelisCredentials(object): """Object to hold authentication credentials""" _default_token_timeout = 10...
2,485
780
# Copyright 2018 Ivan Yelizariev <https://it-projects.info/team/yelizariev> # License MIT (https://opensource.org/licenses/MIT). import logging from odoo.addons.point_of_sale.tests.common import TestPointOfSaleCommon try: from unittest.mock import patch except ImportError: from mock import patch _logger = l...
6,254
1,940
from .base_settings import * INSTALLED_APPS += [ 'course_roster.apps.CourseRosterConfig', 'compressor', ] COMPRESS_ROOT = '/static/' COMPRESS_PRECOMPILERS = (('text/less', 'lessc {infile} {outfile}'),) COMPRESS_OFFLINE = True STATICFILES_FINDERS += ('compressor.finders.CompressorFinder',) if os.getenv('ENV',...
582
255
"""Decorator internal utilities""" import pylons from pylons.controllers import WSGIController def get_pylons(decorator_args): """Return the `pylons` object: either the :mod`~pylons` module or the :attr:`~WSGIController._py_object` equivalent, searching a decorator's *args for the latter :attr:`~WSGI...
606
182
from yacs.config import CfgNode as CN def get_cfg_defaults(): """Get a yacs CfgNode object with default values for my_project.""" # Return a clone so that the defaults will not be altered # This is for the "local variable" use pattern return _C.clone() _C = CN() _C.SYSTEM = CN() _C.config_name = 'roi_config_d...
1,191
680
class Order(object): def order(self): return { 'loanId': self._loan_id, 'requestedAmount': self._amount, 'portfolioId': self._portfolio } def __init__(self, loan_id, amount, portfolio): self._loan_id = int(loan_id) self._amount = amount ...
1,188
350
""" The create_app function wraps the creation of a new Flask object, and returns it after it's loaded up with configuration settings using app.config """ from flask import jsonify from flask_api import FlaskAPI from flask_cors import CORS from flask_sqlalchemy import SQLAlchemy from flask_jwt_extended import J...
2,175
656
from unittest import TestCase from versions.constraints import Constraints, merge, ExclusiveConstraints from versions.constraint import Constraint class TestConstraints(TestCase): def test_match(self): self.assertTrue(Constraints.parse('>1,<2').match('1.5')) def test_match_in(self): self.as...
3,821
1,154
import sys import subprocess if __name__ == "__main__": try: executable = sys.argv[1] input_filename = sys.argv[2] output_filename = sys.argv[3] tl = sys.argv[4] except IndexError: sys.exit(-1) input_file = open(input_filename, "r") output_file = open(output_fil...
520
176
from dataclasses import dataclass from numbers import Real from typing import Optional @dataclass class MultipleOf: param: Real def __call__(self, value: Real) -> Optional[str]: if value % self.param != 0: return f"Value must be a multiple of {self.param}" else: return...
1,224
354
from taquin import * from random import * from math import * #main ''' old : ancienne façon de mélanger qui correspond à une manipulation du taquin. Plus à coder pour les élèves et pour faire des essais de profondeur montxt='012345678'# position initiale = solution montaquin=Taquin(montxt)#...
4,580
1,515
################################################################################################################################################################ # @project Open Space Toolkit ▸ Mathematics # @file bindings/python/test/test_objects.py # @author Lucas Brémond <lucas@loftorbital.c...
1,870
425
#!/usr/bin/env python3 # coding: utf-8 ''' helper to generate emoji.qrc ''' from glob import glob import sys import re def output_qrc(arr, fn='emoji.qrc') -> None: ''' emoji.qrc ''' header = '''<RCC> <qresource prefix="/">''' footer = ''' </qresource> </RCC>''' with open(fn, 'wt', encoding='ut...
1,005
384
# -*- coding: utf-8 -*- import cgi form = cgi.FieldStorage() # 创建FieldStorage实例(应只创建一个) name = form.getvalue('name', 'world') # CGI脚本通过getvalue方法获取值,这里默认值为world print("""Content-type: text/html <html> <head> <title>Greeting Page</title> </head> <body> <h1>Hello, {}!</h1> <form action='Chapter16_We...
1,246
806
# https://uefi.org/sites/default/files/resources/UEFI%20Spec%202_6.pdf # N.2.2 Section Descriptor section_types = { "9876ccad47b44bdbb65e16f193c4f3db": { "name": "Processor Generic", "error_record_reference": {} }, "dc3ea0b0a1444797b95b53fa242b6e1d": { "name": "Processor Specific - ...
1,809
816
import pytest from filestack.helpers import verify_webhook_signature @pytest.mark.parametrize('signature, expected_result', [ ('57cbb25386c3d6ff758a7a75cf52ba02cf2b0a1a2d6d5dfb9c886553ca6011cb', True), ('incorrect-signature', False), ]) def test_webhook_verification(signature, expected_result): secret = '...
1,336
482
import rdflib from rdflib.term import URIRef from utilities.utility_functions import prefix from utilities import constants def has_equivalent(node, graph): equivalents = list(graph.subjects(predicate=constants.EQUIVALENCE_PREDICATE, object=node)) + \ list(graph.subjects(predicate=constants.SYNONYMY_PR...
4,558
1,917
from flask import render_template, request, redirect, url_for, abort from flask_login import login_required, current_user from . forms import PitchForm, CommentForm, CategoryForm from .import main from .. import db from ..models import User, Pitch, Comments, PitchCategory, Votes #display categories on the landing page...
5,875
1,921
import glob import os import pandas as pd from tensorflow.python.keras.preprocessing.image import ImageDataGenerator from typing import Dict, List, Union, Tuple import numpy as np import tensorflow as tf from tensorflow.python.keras.callbacks import ModelCheckpoint, TensorBoard, LearningRateScheduler from networks.c...
10,299
2,692
# find fibonacci number def myFib(n): pass def tests(): assert myFib(1) == 1 assert myFib(2) == 1 assert myFib(3) == 2 assert myFib(4) == 3 assert myFib(5) == 5
187
86
from __future__ import unicode_literals import json from tests import TestCase, with_settings from nose.tools import eq_ from catsnap import Client from catsnap.table.image import Image, ImageResize from catsnap.table.album import Album class TestShowImage(TestCase): @with_settings(aws={'bucket': 'snapcats'}) ...
4,114
1,247
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2018-07-04 09:43:51 # @Author : Zhi Liu (zhiliu.mind@gmail.com) # @Link : http://iridescent.ink # @Version : $1.1$ import matplotlib.cm as cm from matplotlib import pyplot as plt import improc as imp datafolder = '/mnt/d/DataSets/oi/nsi/classical/' imgsp...
554
261
#!/usr/bin/env python3 """Jump the Five""" import argparse # -------------------------------------------------- def get_args(): parser = argparse.ArgumentParser(description='Jump the Five', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('text', metavar='str', help='Input text'...
764
323
from tests.utils import W3CTestCase class TestGridPositionedItemsGaps(W3CTestCase): vars().update(W3CTestCase.find_tests(__file__, 'grid-positioned-items-gaps-'))
169
61
name = "pympu6050"
18
12
# Copyright (c) 2014-2017, iocage # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted providing that the following conditions # are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and th...
4,537
1,511
from django.db import models # Create your models here. class Publisher(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=64, null=False, unique=True) class Book(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=64, null=...
425
141
""" """ import os import unittest from lxml import etree from svety import PACKDIR from svety import reader from svety import retriever __author__ = ["Clément Besnier <clemsciences@aol.com>", ] class TestMain(unittest.TestCase): """ """ def setUp(self) -> None: self.filename = "hellqvist.xml...
905
310
from textwrap import dedent from openeo.internal.processes.generator import PythonRenderer from openeo.internal.processes.parse import Process def test_render_basic(): process = Process.from_dict({ "id": "incr", "description": "Increment a value", "summary": "Increment a value", "...
5,424
1,569
# The MIT License (MIT) # Copyright (c) 2015 Yanzheng Li # 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 # to use, copy, modify,...
4,555
1,509
""" Copyright 2018 Jesus Villalba (Johns Hopkins University) Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) """ from __future__ import absolute_import from __future__ import print_function from __future__ import division from six.moves import xrange import sys import os import argparse import time import c...
14,895
4,997
import fastapi as _fastapi import blockchain as _blockchain app_desc = { 'title':'Simple python blockchain API', 'version':'1.0.0', } bc = _blockchain.Blockchain() app = _fastapi.FastAPI(**app_desc) def validade_blockchain(): if not bc._is_chain_valid(): return _fastapi.HTTPException( ...
1,113
378
from glob import glob import os from setuptools import setup, find_packages def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup(name='chemlearn', version='0.0.0', description='Deep learning for chemistry', long_description=read('README.rst'), author...
1,747
467
# Need to import path to test/fixtures and test/scripts/ # Ex : export PYTHONPATH='$PATH:/root/test/fixtures/:/root/test/scripts/' # # To run tests, you can do 'python -m testtools.run tests'. To run specific tests, # You can do 'python -m testtools.run -l tests' # Set the env variable PARAMS_FILE to point to your ini ...
49,731
16,573
#!/usr/bin/env python3 # murder 0.2.3 import sys if sys.version_info[0] != (3): sys.stdout.write("Sorry this software requires Python 3. This is Python {}.\n".format(sys.version_info[0])) sys.exit(1) import time import requests import json import re # Your "filename" file should contain one word per row. Do...
5,407
1,726
def _deep_merge_mapping(old, new): merged = {} merged.update(old) for k, nv in new.items(): try: ov = merged[k] except KeyError: merged[k] = nv continue merged[k] = deep_merge(ov, nv) return merged def _deep_merge_sequence(old, new): r...
703
228
#/usr/bin/env python from ..module2 import my_print def my_sum(x, y): result = x + y my_print.my_print(result) # To run method alone if __name__ == "__main__": import sys if len(sys.argv) != 3: print("%s str1 str2" % sys.argv[0]) raise SystemExit(1) my_sum(sys.argv[1], sys.argv[2]...
324
130
from multiscale import MultiScale from patchgan import PatchDiscriminator
75
22
from os import symlink, path, access, X_OK import pytest from leapp.libraries.actor import workaround from leapp.libraries.common.utils import makedirs def fake_symlink(basedir): def impl(source, target): source_path = str(basedir.join(*source.lstrip('/').split('/'))) makedirs(source_path) ...
1,054
370
""" https://codility.com/programmers/task/equi_leader/ """ from collections import Counter, defaultdict def solution(A): def _is_equi_leader(i): prefix_count_top = running_counts[top] suffix_count_top = total_counts[top] - prefix_count_top return (prefix_count_top * 2 > i + 1) and (suffi...
707
264
from abc import ABC, abstractmethod from typing import Any, List, TypeVar from cu_pass.dpa_calculator.helpers.list_distributor.fractional_distribution.fractional_distribution import \ FractionalDistribution RETURN_TYPE = TypeVar('RETURN_TYPE') class ListDistributor(ABC): def __init__(self, items_to_distribu...
1,744
501
import urllib import requests import multiprocessing.pool from multiprocessing import Pool import uuid import os images_dir = os.path.join("data", "train") small_letters = map(chr, range(ord('a'), ord('f')+1)) digits = map(chr, range(ord('0'), ord('9')+1)) base_16 = digits + small_letters MAX_THREADS = 100 def capt...
1,419
490
import jittor as jt from jittor import nn, models if jt.has_cuda: jt.flags.use_cuda = 1 # jt.flags.use_cuda class QueryEncoder(nn.Module): def __init__(self, out_dim=128): super(QueryEncoder, self).__init__() self.dim = out_dim self.resnet = models.resnet50(pretrained=False) sel...
7,679
2,559
# -*- coding: utf-8 -*- import pytest from django.db.models import QuerySet from rest_framework.exceptions import NotFound from apps.accounts.response_codes import INVALID_TOKEN from apps.accounts.selectors.pending_action_selector import PendingActionSelector from apps.accounts.tests.factories.pending_action import P...
2,348
695
<caret>search_variable = 1 def function(): global search_variable search_variable = 2 print(search_variable)
121
38
from decimal import Decimal import pytest from api.tests.factories.location import LocationFactory # potentially helpful fixtures provided by pytest-django # https://pytest-django.readthedocs.io/en/latest/helpers.html#fixtures @pytest.mark.django_db() def test_create_rental(): LocationFactory( lat=Decim...
379
136
import datetime from flask import Flask, render_template ''' algoritmo simples para definir se o dia é par ou impar ''' app = Flask(__name__) @app.route("/") def index(): hoje=datetime.datetime.now()#objeto recebera a data atual return render_template("index.html",dia=hoje.day)
293
99
# -*- coding: utf-8 -*- """ * Created by PyCharm. * Project: catalog * Author name: Iraquitan Cordeiro Filho * Author login: pma007 * File: api * Date: 2/26/16 * Time: 11:26 * To change this template use File | Settings | File Templates. """ from flask import Blueprint, jsonify from catalog.models import Categ...
1,532
507
from pytest import raises from psycopg2_pgevents import debug from psycopg2_pgevents.debug import log, set_debug class TestDebug: def test_set_debug_disabled(self): debug._DEBUG_ENABLED = True set_debug(False) assert not debug._DEBUG_ENABLED def test_set_debug_enabled(self): ...
1,854
635
import glob import os import sqlalchemy as db from sqlalchemy.sql import text def deploy_template_folder(db_config, folder): engine = db.create_engine('postgresql://%s:%s@%s:%s/%s' % (db_config.user, db_config.password, db_config.host, db_config.port, db_config.database)) if not os.path.isdir(folder): ...
1,148
350
###################################################################### # EXTERNAL # ###################################################################### from Classes.Metadata import Metadata from subprocess import PIPE, Popen from extension import * from col...
8,466
2,481
import distarray import numpy import unittest from mpi4py import MPI class TestGhostedDistArray(unittest.TestCase): """ Test distributed array """ def setUp(self): pass def test_test0(self): """ Test constructors """ da = distarray.ghZeros( (2,3), numpy.flo...
3,242
1,185
import json from django.contrib.auth import authenticate, login, logout from django.http import HttpResponse from django.utils import timezone from django.contrib.auth.signals import user_logged_in from cir.models import * VISITOR_ROLE = 'visitor' def login_view(request): response = {} email = request.REQUE...
3,900
1,140
# Given a string, sort it in decreasing order based on the frequency of characters. # Example 1: # Input: # "tree" # Output: # "eert" # Explanation: # 'e' appears twice while 'r' and 't' both appear once. # So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer. # Example 2: # Input: # "...
2,844
925
#!/usr/bin/env python # -*- coding: utf-8 -*- import tkinter as tk from tkinter import ttk class HashCorpFrame(ttk.Frame): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.name_entry = ttk.Entry(self) self.name_entry.pack() self.greet_button = ttk.But...
1,837
636
import uuid from typing import List from elasticsearch import Elasticsearch from elasticsearch.exceptions import NotFoundError from fastapi import APIRouter, Response, status from validation import DojoSchema from src.settings import settings import logging logger = logging.getLogger(__name__) router = APIRouter...
8,513
2,633
from django.test import TestCase from common.data_utilities import DataUtils from prob_models.dep_graph import DependencyGraph from prob_models.jtree import JunctionTree import common.constant as c TESTING_FILE = c.TEST_DATA_PATH """ The test file has for fields, and the dependency graph would be a complete graph. ...
3,313
1,349
# Regression Task, assumption is that the data is in the right directory # data can be taken from https://www.kaggle.com/c/house-prices-advanced-regression-techniques/data import os import ml_automation if __name__ == '__main__': data_dir = os.path.join(os.path.dirname(__file__), 'data') f_train = os.path.jo...
631
221
# -*- coding: utf-8 -*- """Constants for building the biological network explorer's transformations toolbox.""" from typing import List, Tuple from pybel.struct.pipeline.decorators import mapped # Default NetworkX explorer toolbox functions (name, button text, description) _explorer_toolbox = ( ('collapse_to_ge...
3,232
981
""" V1 Client """ from threatstack.base import BaseClient from threatstack.v1 import resources class Client(BaseClient): BASE_URL = "https://app.threatstack.com/api/v1/" def __init__(self, api_key=None, org_id=None, user_id=None, timeout=None): BaseClient.__init__(self, api_key=api_key, timeout=ti...
827
267
"""ModelAdmin for MailingList""" from datetime import datetime from django.contrib import admin from django.conf.urls.defaults import url from django.conf.urls.defaults import patterns from django.utils.encoding import smart_str from django.core.urlresolvers import reverse from django.shortcuts import get_object_or_40...
5,930
1,735
import os import sys from collections import deque, defaultdict from typing import Dict, Union sys.path.append("../../") import torch import torchvision.utils as vutils from tensorboardX import SummaryWriter class SmoothedValue(object): """Track a series of values and provide access to smoothed values over a ...
4,263
1,494
import logging import re from datetime import datetime import scrapy from scrapy.http import Response # noinspection PyUnresolvedReferences import scrapytest.db from scrapytest.config import config from scrapytest.types import Article from scrapytest.utils import merge_dict log = logging.getLogger(__name__) class ...
5,642
1,525
#!/usr/bin/python # parseskipfish.py # # By Adrien de Beaupre adriendb@gmail.com | adrien@intru-shun.ca # Copyright 2011 Intru-Shun.ca Inc. # v0.09 # 16 October 2011 # # The current version of these scripts are at: http://dshield.handers.org/adebeaupre/ossams-parser.tgz # # Parses skipfish HTML and JSON outp...
6,490
2,463
""" setup gban """ # Copyright (C) 2020 by UsergeTeam@Github, < https://github.com/UsergeTeam >. # # This file is part of < https://github.com/UsergeTeam/Userge > project, # and is released under the "GNU v3.0 License Agreement". # Please see < https://github.com/uaudith/Userge/blob/master/LICENSE > # # All rights res...
14,861
5,070
"""pytest for user.models.verifycode """
41
15
""" Codebay process running utils. @group Running commands: run, call @group Preexec functions: chroot, cwd @var PASS: Specifies that the given file descriptor should be passed directly to the parent. Given as an argument to run. @var FAIL: Specifies that if output is received for the given file descriptor, a...
7,638
2,166
""" Demonstrates escape sequences in strings """ #Line Feed escape sequence. output1 = "First part \n Second part" print(output1) #********************************# print() #Double quotes escape sequence. output2 = "The book \"War and Peace\" is very long" print(output2) #********************************# p...
545
156