text string | size int64 | token_count int64 |
|---|---|---|
class Item(object):
"""docstring for Item"""
def __init__(self, itemName_list, itemTags_list=[], itemDesc_list=[]):
self.itemNames = itemName_list
self.itemTags = itemTags_list
self.itemDescs = itemDesc_list
class Users(object):
"""docstring for User"""
def __init__(self, userIds_list, triedItems_list):
... | 391 | 150 |
# flake8: noqa
"""
多周期显示K线,
时间点同步
华富资产/李来佳
"""
from vnpy.trader.ui.kline.kline import *
from vnpy.trader.ui.kline.crosshair import Crosshair
import sys
import os
import ctypes
import platform
system = platform.system()
os.environ["VNPY_TESTING"] = "1"
# 将repostory的目录,作为根目录,添加到系统环境中。
ROOT_PATH = os.path.abspath(os.pa... | 3,112 | 1,459 |
"""
An implementation of the CBF image reader for Pilatus images, from the Pilatus
6M SN 119 currently on Diamond I24.
"""
import sys
from dxtbx.format.FormatCBFMiniPilatus import FormatCBFMiniPilatus
class FormatCBFMiniPilatusDLS6MSN119(FormatCBFMiniPilatus):
"""A class for reading mini CBF format Pilatus ima... | 2,024 | 626 |
import argparse
import agent
parser = argparse.ArgumentParser()
parser.add_argument(
"--eth",
type=str,
required=True,
help="The network interface for monitor.")
parser.add_argument(
"--hostname",
type=str,
help="Custom hostname.")
parser.add_argument(
"--scheme",
type=str,
... | 1,105 | 353 |
import filter as ft
import analyzer as az
GROUP_A = ([
[ft.IsShanghainese(), ft.IsMandarin()],
[ft.IsMale(), ft.IsFemale()],
[ft.IsChild(), ft.IsYouth(), ft.IsAdult(), ft.IsSenior()],
[ft.IsVariant('a1'), ft.IsVariant('a2')],
], [
az.FormantQuantiles(),
az.FormantRegression(),
])
GROUP_C = ([
... | 1,604 | 730 |
'''
These network archtecture performed perfectly while training with a teacher
Let's see ho it performes without one.
'''
from __future__ import division, print_function, absolute_import
print('Starting..................................')
import sys
sys.path.insert(1, '/home/labs/ahissarlab/orra/imagewalker')
sys.p... | 7,560 | 2,833 |
def get_type_check(expected_type):
"""
Any -> (Any -> bool)
:param expected_type: type that will be used in the generated boolean check
:return: a function that will do a boolean check against new types
"""
return lambda x: type(x) is expected_type
| 273 | 76 |
# -*- coding: utf-8 -*-
#
# Copyright © 2013 The Spyder Development Team
# Licensed under the terms of the MIT License
# (see spyderlib/__init__.py for details)
"""
Introspection utilities used by Spyder
"""
import imp
import os
import pickle
import os.path as osp
import re
from spyderlib.utils.misc import memoize
... | 7,802 | 2,335 |
import csv
import os
from pathlib import Path
from .models import Member, Account
class Row:
'''Local Class used by Parser below'''
def __init__(self, first_name, last_name, phone_number, client_member_id, account_id):
self.first_name = first_name
self.last_name = last_name
self.phone... | 2,641 | 757 |
# coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. 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 cop... | 43,870 | 13,498 |
import subprocess
import time
import pytest
import redis
# Ports, in the order of [master; replicas in chain].
INIT_PORTS = [6369, 6370]
INIT_PORTS = [6369, 6370, 6371, 6372]
INIT_PORTS = [6369, 6370, 6371]
PORTS = list(INIT_PORTS)
MAX_USED_PORT = max(PORTS) # For picking the next port.
def MakeChain(num_nodes=2... | 4,014 | 1,506 |
# Hofstadter Butterfly Fractal
# http://en.wikipedia.org/wiki/Hofstadter%27s_butterfly
# Wolfgang Kinzel/Georg Reents,"Physics by Computer" Springer Press (1998)
# FB36 - 20130922
from math import pi, cos
from PIL import Image
from cyhof import butterfly
def main():
img_size = 256
raw_data = butterfly(img_siz... | 501 | 194 |
from .Cyrcos import Cyrcos
| 27 | 11 |
#!/usr/bin/env python
#
# test_pim_acl.py
# Part of NetDEF Topology Tests
#
# Copyright (c) 2020 by
# Network Device Education Foundation, Inc. ("NetDEF")
#
# Permission to use, copy, modify, and/or distribute this software
# for any purpose with or without fee is hereby granted, provided
# that the above copyright no... | 11,552 | 4,248 |
import abc
class RoutingProtocol(metaclass=abc.ABCMeta):
def __init__(self):
self.name = None
def protocol_name(self):
return self.name
class BgpRoutingProtocol(RoutingProtocol):
def __init__(self):
super().__init__()
self.name = "BGP"
class OspfRoutingProtocol(Routing... | 923 | 302 |
from instauto.api.client import ApiClient
import instauto.api.actions.structs.profile as pr
client = ApiClient.initiate_from_file(".instauto.save")
obj = pr.Info("user_id")
info = client.profile_info(obj)
| 207 | 69 |
import torch
import torch.nn as nn
# torch.set_default_tensor_type(torch.DoubleTensor)
class SRMD(nn.Module):
def __init__(self, args, num_blocks=11, num_channels=18, conv_dim=128, scale_factor=4):
super(SRMD, self).__init__()
self.num_channels = num_channels
self.conv_dim = conv_dim
... | 1,371 | 500 |
import unittest
from SubTypeTree import SubTypeTreeFactory
from SubTypeTree import VenderTreeFactory
from SubTypeTree import SubTypeTree
from SubTypeTree import VenderTree
from SubTypeTree import GitHubVenderTree
from SubTypeTree import StandardTree
from SubTypeTree import ParsonalTree
from SubTypeTree import Unregiste... | 862 | 251 |
# Copyright 2018 Google Inc. 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/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | 14,192 | 5,283 |
import os
from time import sleep
import random
import re
import pathlib
import discord
from redbot.core import commands
from functools import reduce
BaseCog = getattr(commands, "Cog", object)
# todo -> archive specified channel in db
# db format
# | message_id | contents |
# todo -> export
OOCFILE = pathlib.Path(os.... | 4,219 | 1,223 |
from django.apps import AppConfig
class MainConfig(AppConfig):
name = 'atm_s_ru.main'
verbose_name = "Управление"
| 123 | 43 |
from wordweaver.tests import run
import sys
try:
run.run_tests(sys.argv[1])
except IndexError:
print("Please specify a test suite to run: i.e. 'dev' or 'prod'") | 169 | 59 |
from math import sqrt
import einops
from einops.layers.torch import Rearrange, Reduce
import torch
import torch.nn as nn
# TODO: this may be refactored
class PatchEmbedding(torch.nn.Module):
def __init__(self, in_channels, embed_size, patch_size=16):
super().__init__()
# noinspection PyTypeCheck... | 5,562 | 1,893 |
import numpy as np
import pandas as pd
import pickle
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.decomposition import LatentDirichletAllocation
import os
abspath = os.path.abspath(__file__)
dname = os.path.dirname(abspath)
os.chdi... | 1,297 | 425 |
import numpy as np
from models import ALOCC_Model
from keras.datasets import mnist
import matplotlib.pyplot as plt
from keras import backend as K
import os
from keras.losses import binary_crossentropy
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
self =ALOCC_Model(dataset_name='mnist', input_height=32,input_width=32)
sel... | 1,613 | 598 |
# type: ignore
from os import environ
import pytest
import pandas as pd
from ...utils import display_dataframe
from ...connector import read_sql
@pytest.mark.skipif(
environ.get("DB_URL", "") == "" or environ.get("DB_SQL", "") == "",
reason="Skip tests that requires database setup and sql query specified",
)... | 466 | 150 |
##### INITIALIZATION
# Import Modules
import pygame
# Initialize PyGame
pygame.init()
# Initialize game window
screen = pygame.display.set_mode((1280, 960))
##### MAIN PROGRAM
# Loop until the window is closed
window_open = True
while window_open:
for event in pygame.event.get():
if event.type == pyga... | 420 | 133 |
# Copyright 2022, Li-aung Yip - https://www.penwatch.net
# Licensed under the MIT License. Refer LICENSE.txt.
# This compares the results from the official IEEE spreadsheet(s) to the results of the `ieee_1584` module.
#
# Some pre-generated test data is shipped with this code - see `ieee_1584_spreadsheet_results.csv`.... | 2,634 | 937 |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def rotateRight(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
if head is None:
... | 830 | 240 |
from jumpscale import j
JSBASE = j.application.jsbase_get_class()
import sys
from importlib import import_module
model = """
@url = jumpscale.digitalme.package
enabled = false (B)
start = 0 (D)
path = "" (S)
docsites = (LO) !jumpscale.digitalme.package.docsite
blueprints = (LO) !jumpscale.digitalme.package.blueprints
... | 8,255 | 2,769 |
# -*- coding: utf-8 -*-
import re
from plateau import Plateau
from rover import Rover
# Get test data from the file
filename = "data.txt"
# Introduce index to keep track of the rovers while iterating
# over the data.txt entries (more than 2 allowed)
rover_index = 0
plateau_initial = {}
rovers = {}
rover_position... | 1,554 | 486 |
#
# This example defines a script that solves the Traveling
# Salesperson Problem using a combination of
# branch-and-bound (by edge) and local heuristics. It
# highlights a number of advanced pybnb features, including:
# (1) the use of pybnb.futures.NestedSolver
# (2) re-continuing a solve after early termination
#
... | 5,284 | 1,622 |
from __future__ import unicode_literals
import markdown as md
from nose.tools import assert_equal
import os
def test_with_fenced_code():
markdown_source = "\n".join(
["Test diagram:",
"",
"```ditaa",
"+---+",
"| A |",
"+---+",
"```",
"",
... | 910 | 327 |
from .qt_driver import QtDriver
qt = QtDriver()
QtGui = qt.QtGui
| 66 | 26 |
from contextlib import contextmanager
from timeit import default_timer
from sherlockpipe.sherlock import Sherlock
from lcbuilder.objectinfo.MissionObjectInfo import MissionObjectInfo
from sherlockpipe.sherlock_target import SherlockTarget
@contextmanager
def elapsed_timer():
start = default_timer()
elapser =... | 2,054 | 612 |
# [h] batch rename glyphs
import hTools2.dialogs.font.glyphs_rename
import importlib
importlib.reload(hTools2.dialogs.font.glyphs_rename)
hTools2.dialogs.font.glyphs_rename.batchRenameGlyphs()
| 195 | 80 |
# -*- coding: utf-8 -*-
from openprocurement.tender.openeu.utils import qualifications_resource
from openprocurement.tender.openeu.views.qualification import TenderQualificationResource
from openprocurement.tender.competitivedialogue.constants import STAGE_2_EU_TYPE
@qualifications_resource(
name="{}:Tender Quali... | 662 | 210 |
import torch
from torch.utils.data import DataLoader
from dataset import pack_raw
import transforms as trf
import torchvision.transforms as transforms
from PIL import Image
from model.model import UNet
from pathlib import Path
import numpy as np
import rawpy
import math
import cv2
import time
import sys
checkpoint_pat... | 1,898 | 662 |
import functools
import operator
import collections
from enum import Enum
import numpy as np
from cycler import cycler
try:
# cytools is a drop-in replacement for toolz, implemented in Cython
from cytools import partition
except ImportError:
from toolz import partition
from .utils import snake_cyclers, is... | 18,814 | 6,004 |
class TsType:
def __init__(self, name: str, is_optional: bool = False):
self._name = name
self._is_optional = is_optional
@property
def name(self) -> str:
return self._name
@property
def is_optional(self) -> bool:
return self._is_optional
def as_optional_type(s... | 1,303 | 423 |
# Copyright 2018 The Cirq Developers
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | 6,364 | 3,017 |
import ccxt
import torch
import torch.nn as nn
from torch.autograd import Variable
import pandas as pd
import numpy as np
from sklearn.preprocessing import MinMaxScaler
seq_length = 5
class LSTM(nn.Module):
def __init__(self, num_classes, input_size, hidden_size, num_layers):
super(LSTM, self).__init__()... | 3,569 | 1,480 |
from .MatchingType import MatchingType
class MatcherMixin:
additional_flag = MatchingType.NoMatch
def match(self, lhs, rhs, original_lhs, original_rhs, **parameters):
new_lhs, new_rhs = self.normalize(lhs, rhs, original_lhs, original_rhs, **parameters)
return self.compare(new_lhs, new_rhs, o... | 979 | 338 |
import bibleIn
def consume(verses):
ret = ""
for i in verses:
out = ""
for v in i:
add = str(v[3])
if v[0] == u'Proverbs':
add = add.replace("\n\n","\n")
add += "\n"
out += add
ret += out+"\n\n\n"
return ret[:-3]
if __name__ == "__main__":
verses = bibleIn.fetch()
print(consume(verses))
| 318 | 159 |
# Generated by Django 2.2.11 on 2020-04-19 02:04
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('djpmp', '0019_project_token'),
]
operations = [
migrations.AlterModelOptions(
name='hrcalendar',
options={'verbose_name': '... | 384 | 156 |
# Copyright 2013-2018 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Libbeagle(AutotoolsPackage):
"""Beagle performs genotype calling, genotype phasing, imputa... | 1,217 | 440 |
import argparse
import multiprocessing
import os
import time
import psycopg2
import worker
import consts
lock = multiprocessing.Lock()
class Controller:
def __init__(self, archive_path, words):
self._archive_path = archive_path
self._words = words
self._task_size = 4
self._n_f... | 5,223 | 1,432 |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community
Edition) available.
Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in co... | 2,975 | 1,037 |
from nlp_gym.data_pools.custom_multi_label_pools import ReutersDataPool, AAPDDataPool
from nlp_gym.data_pools.custom_seq_tagging_pools import UDPosTagggingPool, CONLLNerTaggingPool
from nlp_gym.data_pools.custom_question_answering_pools import AIRC, QASC
from nlp_gym.data_pools.base import DataPool
from typing import ... | 1,254 | 437 |
# uncompyle6 version 3.7.4
# Python bytecode 3.7 (3394)
# Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)]
# Embedded file name: T:\InGame\Gameplay\Scripts\Server\curfew\curfew_service.py
# Compiled at: 2020-06-08 22:31:54
# Size of source mod 2**32: 22657 bytes
... | 16,330 | 5,162 |
#!/usr/bin/env python3
import argparse
import struct
import os.path
import freetype
import numpy as np
asciichars = ''.join(chr(i) for i in range(ord(' '), ord('~')+1))
def mkbuf(face):
tops = [(face.load_char(c), face.glyph.bitmap_top)[1] for c in asciichars]
heights = [(face.load_char(c), face.glyph.bitmap... | 6,556 | 2,481 |
import os
from app import seek_confirmation
from app.job import Job
from app.bq_service import BigQueryService
from app.nlp.model_storage import ModelStorage, MODELS_DIRPATH
MODEL_NAME = os.getenv("MODEL_NAME", default="current_best")
LIMIT = os.getenv("LIMIT")
BATCH_SIZE = int(os.getenv("BATCH_SIZE", default="10000... | 1,743 | 591 |
# srun --mpi=pmi2 -p VI_UC_TITANXP -n1 --gres=gpu:4 python test.py
import os
from os.path import join as opj
import numpy as np
from scipy.spatial.distance import cdist
from tqdm import tqdm
import sys
import re
from sklearn import preprocessing
import multiprocessing
import torch
from torch.optim import lr_schedu... | 3,221 | 1,217 |
#
# Copyright 2016 The BigDL 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 or agreed to in ... | 2,536 | 755 |
"""metrics-archive-deadlock
Revision ID: 55ab971bde17
Revises: 67f52879da15
Create Date: 2021-11-12 10:24:47.899243
"""
import os.path
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '55ab971bde17'
down_revision = '67f52879da15'
branch_labels = None
depends_on = N... | 612 | 268 |
"""
Custom integration to integrate Cisco UCS IMC with Home Assistant.
For more details about this integration, please refer to
https://github.com/ecoen66/cisco_imc
"""
from __future__ import annotations
import asyncio
import logging
from datetime import timedelta
from collections import defaultdict
#from typing impor... | 12,835 | 4,180 |
from testing_helpers import wrap
@wrap
def compare(a, b):
if a < b:
return 10
else:
return -10
def test_compare_numbers():
compare(1,0)
compare(1,1)
compare(1,2)
compare(1,True)
compare(1,False)
compare(1.0,1)
compare(1.0,1.0)
compare(-1.0, -1.0)
compare(-2.0, -3.0)
compare(-2.0, F... | 494 | 215 |
"""Test custom loader which returns directly the same thing that was passed."""
def get_pipeline_definition(pipeline_name, working_dir):
"""Return inputs as a mock pipeline loader stub."""
return {'pipeline_name': pipeline_name, 'working_dir': working_dir}
| 267 | 72 |
from pathlib import Path
import numpy as np # linear algebra
import pandas as pd # data_small processing, CSV file I/O (e.g. pd.read_csv)
class DataLoader:
def __init__(self, base_data_dir=str()):
self.train_dir = base_data_dir + 'train/'
self.test_dir = base_data_dir + 'test/'
self.val_d... | 1,144 | 400 |
import string
from .. import components
from ..data import Decorations
from ..geometry import Size
from ..tiles import Colors
from ..events import handlers
from .. import render
from .core import Align, Padding, ZOrder
from . import basic
from . import containers
from . import decorations
from . import renderers
f... | 13,399 | 3,829 |
import graphene
from graphene.types import ResolveInfo
from ..base import BaseMutationPayload
from tracker.api.scalars.projects import Description, Title
from tracker.api.schemas.projects import ProjectCreationSchema
from tracker.api.services import validate_input
from tracker.api.services.projects import (
check_... | 2,346 | 636 |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2016-11-09 23:03
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Rank',... | 943 | 290 |
#!/usr/bin/env python
import csv
import sys
import socket
import struct
if len(sys.argv) != 3:
print("Usage: python ipconvert.py [integer field] [string field]")
sys.exit(1)
else:
integerfield = sys.argv[1]
stringfield = sys.argv[2]
infile = sys.stdin
outfile = sys.stdout
r = csv.Dict... | 1,001 | 309 |
#! /usr/bin/env python
from math import ceil, log10, cos, sin, tan, sqrt, pi
from fractions import Fraction
import matplotlib.pyplot as plt
from matplotlib.patches import Arc
from matplotlib import cm
from matplotlib.lines import Line2D
class Lamination:
def __init__(self, period=1, degree=2):
self.degree... | 4,905 | 1,720 |
# File: mail.py
# Version: 0.3
# Description: utility functions for handling XEPs
# Last Modified: 2014-09-23
# Based on scripts by:
# Tobias Markmann (tm@ayena.de)
# Peter Saint-Andre (stpeter@jabber.org)
# Authors:
# Winfried Tilanus (winfried@tilanus.com)
## LICENSE ##
#
# Copyright (c) 1999 - 2014 XMPP St... | 4,663 | 1,429 |
#!/usr/bin/env python
####################################
####################################
## SortExtractedData.py ##
## Script to sort zonal stats ##
## data into single spreadsheet ##
## ##
## Author: Dan Clewley ##
## Email: ddc06@aber.ac.uk ##
#... | 5,590 | 1,474 |
"""Generate shell scripts to run.
This is a template script. Filling out the stuff below each time before running
new experiments helps with organization and avoids the messiness once there are
many experiments.
date:
01/19/22
purpose:
Ablation studies:
Feature extractor
DeepJDOT training
... | 2,616 | 871 |
#!/usr/bin/env python
# -*- coding: ascii -*-
# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab
#
# wip TableTop Simulator json parser
# Copyright (C) 2020 Chris Clark
import glob
import logging
import os
import sys
try:
#raise ImportError()
# Python 2.6+
import json
except ImportError:
#raise ImportE... | 2,375 | 808 |
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from builtins import *
from future.builtins.disabled import *
from pyVmomi import vim
class VirtualMachineDiskLayout(object):
def __init__(self, vm):
self.layout = {}
self.__layout... | 3,003 | 972 |
import numpy as np
import pandas as pd
from source.constants import Constants
from source.preprocessing.psg.psg_service import PSGService
class PSGLabelService(object):
@staticmethod
def load(subject_id):
psg_label_path = PSGLabelService.get_path(subject_id)
feature = pd.read_csv(str(psg_labe... | 1,271 | 420 |
#!/usr/bin/env python
"""Tests for read_low_level."""
import os
from absl import app
from grr_response_client.client_actions import read_low_level as read_low_level_actions
from grr_response_server import file_store
from grr_response_server.databases import db
from grr_response_server.flows.general import read_low_l... | 4,063 | 1,451 |
from .base import * # noqa
from .crop import * # noqa
from .filters import * # noqa
from .overlay import * # noqa
from .resize import * # noqa
| 148 | 53 |
""" author: Theodor Peifer, 2018"""
VERSION = "1.0.0"
GITHUB = "https://github.com/hollowcodes/"
HOST = "hollocodes"
SERVER_IP = "127.0.0.1"
CLIENT_IP = "127.0.0.1"
PORT = 6000
| 188 | 98 |
from unittest import TestCase, mock
from komand_active_directory_ldap.actions.move_object import MoveObject
from komand_active_directory_ldap.actions.move_object.schema import Input, Output
from unit_test.common import MockServer
from unit_test.common import MockConnection
from unit_test.common import default_connector... | 1,200 | 373 |
from test.lib.testing import eq_, assert_raises, assert_raises_message
from test.lib import fixtures, testing
from sqlalchemy import Integer, String, ForeignKey, or_, and_, exc, select, func
from sqlalchemy.orm import mapper, relationship, backref, Session, joinedload
from test.lib.schema import Table, Column
clas... | 17,952 | 6,012 |
# @Author: South
# @Date: 2021-08-14 10:56
import asyncio
import base64
from typing import Optional
import httpx
from playwright.async_api import Browser, async_playwright
weibo_url = "https://m.weibo.cn/detail/%s"
space_history = "https://m.weibo.cn/api/container/getIndex?type=uid&value=%s&containerid=10760377133575... | 3,671 | 1,303 |
from itertools import combinations
def partitions(*args):
def p(s, *args):
if not args: return [[]]
res = []
for c in combinations(s, args[0]):
s0 = [x for x in s if x not in c]
for r in p(s0, *args[1:]):
res.append([c] + r)
return res
s =... | 395 | 138 |
import sys
import typing
import bpy
import mathutils
def location_3d_to_region_2d(region: 'bpy.types.Region',
rv3d: 'bpy.types.RegionView3D',
coord,
default=None) -> 'mathutils.Vector':
'''Return the region relative 2d location... | 3,110 | 1,010 |
from .context import Context
from .spec import Spec
class Place(Context):
"""Places are all contexts by nature. Not many shared properties besides!
Attributes
bool isPlace Overridden from Entity
Spec spec Overridden from Entity"""
# Things that child class SHOULDNT need to redeclare
isPlace = True
... | 362 | 109 |
THROUGHPUT=20
TIME_UNIT=0.01
import asyncio
async def wrapper(coru, semaphore, sec):
async with semaphore:
r = await coru
await asyncio.sleep(sec)
return r
def limited_api(corus, n=THROUGHPUT, sec=TIME_UNIT):
semaphore = asyncio.Semaphore(n)
return asyncio.gather(*[wrapper(coru, sema... | 692 | 253 |
#!/usr/bin/env python3
# vim: set ft=python fenc=utf-8 tw=72:
# MINML :: Minimal machine learning algorithms
# Copyright (c) 2019-2020, J. A. Corbal
#
# 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 ... | 11,896 | 3,690 |
#/usr/bin/env python3
"""ChainsAddiction setup"""
import itertools
from pathlib import Path
from typing import Generator, Tuple
from setuptools import setup, Extension
import numpy as np
def cglob(path: str) -> Generator:
"""Generate all .c files in ``path``."""
return (f'{src!s}' for src in Path(path).glob... | 1,494 | 500 |
if __name__ == '__main__':
n = int(input())
arr = map(int, input().split())
newlist = []
for i in arr:
if i not in newlist:
newlist.append(i)
newlist.sort(reverse=True)
print(newlist[1])
| 216 | 85 |
# Copyright (c) 2020 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import mock
import re
import unittest
import cr50
import pty_driver
@mock.patch('servo.drv.pty_driver.ptyDriver._issue_cmd_get_results')
class TestP... | 1,892 | 617 |
'''
## Aliyun ROS KMS Construct Library
This module is part of the AliCloud ROS Cloud Development Kit (ROS CDK) project.
```python
import * as KMS from '@alicloud/ros-cdk-kms';
```
'''
import abc
import builtins
import datetime
import enum
import typing
import jsii
import publication
import typing_extensions
from .... | 61,856 | 19,804 |
import jinja2
from typing import Union
def render(template: Union[str, jinja2.Template], **context) -> str:
"""
Renders the given string as a jinja template with the keyword arguments as context.
:param template: String to be used as jinja template
:param context: keyword arguments used as context for... | 492 | 135 |
#040 - Aquele clássico da Média
nota1 = int(input('primeira nota: '))
nota2 = int(input('segunda nota: '))
media = (nota1 + nota2) / 2
print(f'tirando {nota1:.1f} e {nota2:.1f}, a media do aluno e {media:.1f}')
if 7 > media >= 5:
print('o aluno esta em recuperacao.')
elif media < 5:
print('o aluno esta reprovas... | 367 | 164 |
import rdflib
from argparse import ArgumentParser
parser = ArgumentParser()
# parse command line arguments
parser.add_argument('-nidm', dest='nidm_file', required=True, help="NIDM-Exp RDF File to import")
args = parser.parse_args()
g=rdflib.Graph()
g.parse(args.nidm_file, format='ttl')
qres = g.query(
"""SELEC... | 612 | 219 |
import discord
from discord.ext import commands
from discord.ext.commands import has_permissions
import sqlite3 as sqlite
import random as random
class voteBan(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.doubleVoteResponses = ["Don't try to fool me! You voted already.", "This is no... | 7,081 | 2,218 |
# -*- coding: utf-8 -*-
# Copyright (c) 2020, TZCODE SRL and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
import requests
import json
import traceback
from tzdealer.hook.item import cast_to_post, cast_im... | 4,981 | 2,153 |
import numpy as np
from string import punctuation
# make it a set to accelerate tests
punc = set(punctuation)
def clean_text(text):
return ''.join([ c.lower() for c in text if c not in punc ])
def tokenize_words(words, vocab2int):
words = words.split()
tokenized_words = np.zeros((len(words),))... | 540 | 185 |
toppings = ["pepperoni", "pineapple", "cheese", "sausage", "olives", "anchovies", "mushrooms"]
prices = [2,6,1,3,2,7,2]
num_pizzas = len(toppings)
print("We Sell " + str(num_pizzas) + " different kinds of Pizza!")
pizzas = list(zip(prices,toppings))
print(pizzas)
pizzas.sort()
cheapest_pizza = pizzas[0]
print(cheapest_... | 499 | 222 |
#!/usr/bin/env python
# coding=utf-8
import torch
import torch.nn as nn
from collections import OrderedDict
from torch.nn.functional import interpolate
class AmIModel(nn.Module):
def __init__(self, base, ami_weaken_parameter=0, ami_strengthen_parameter0=0, ami_strengthen_parameter1=0):
super(AmIModel, s... | 5,762 | 1,913 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import sys
import torch
from bert.optimization import BERTAdam
try:
import xml.etree.ElementTree as ET, getopt, logging, sys, random, re, copy
from xml.sax.saxutils import escape
except:
... | 4,690 | 1,544 |
# Generated by Django 4.0.1 on 2022-04-18 12:07
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import shop.utils
import shop.validators
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(... | 6,068 | 1,761 |
import hashlib
import json
import os
import shutil
import zipfile
from wsgiref.util import FileWrapper
from django.conf import settings
from django.http import StreamingHttpResponse, HttpResponse
from account.decorators import problem_permission_required
from judge.dispatcher import SPJCompiler
from contest.models im... | 18,189 | 5,113 |
from argparse import ArgumentParser
from pathlib import Path
from typing import Dict, Union
from argcomplete import FilesCompleter
from omegaconf import OmegaConf
from classy.data.data_drivers import DataDriver
from classy.scripts.cli.utils import (
autocomplete_model_path,
checkpoint_path_from_user_input,
... | 5,390 | 1,593 |
#!/usr/bin/env python3
from flask import abort, jsonify, request
from flask_classful import FlaskView
from marshmallow import ValidationError
from utils import ponytoken_required, this_player, anyadmin_required, json_required
from model import db, Faction
from schemas import FactionSchema
class FactionsView(FlaskV... | 1,444 | 468 |
import album_item
import paragraph_item
from renderable_item import RenderableItem
from url_decoder_github import GitHubRepositoryUrlDecoder
from url_decoder_image import ImageUrlDecoder
from url_decoder_twitter import TwitterTweetUrlDecoder
from url_decoder_youtube import YouTubeUrlDecoder
def _youtube_player_id(vid... | 2,547 | 878 |
from django.contrib import admin
from .models import Environment, EnvironmentProject
class EnvironmentAdmin(admin.ModelAdmin):
pass
admin.site.register(Environment, EnvironmentAdmin)
class EnvironmentProjectAdmin(admin.ModelAdmin):
pass
admin.site.register(EnvironmentProject, EnvironmentProjectAdmin)
| 318 | 78 |