text
string
size
int64
token_count
int64
import cv2 import os import argparse if __name__ == '__main__': arg = argparse.ArgumentParser() arg.add_argument('--o', required=True, help='output_folder') opt = arg.parse_args() cap = cv2.VideoCapture(0) ret, img = cap.read() print('Writing to chessboard file') files = os.listdir(opt.o) index = 0 while (f'i...
402
164
#!/usr/bin/python # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import os import lldb import fblldbbase as fb import fblldbviewhelpers as viewHelpers ACCESSIBILITY_I...
3,105
953
"""OperatorWebSite class unit test.""" from __init__ import json, os, time, unittest, \ webdriver, WebDriverException, OperatorWebSite class TestOperatorWebSite(unittest.TestCase): """Unit test class for OperatorWebSite.""" def load_data(self): """ Load the data file. """ self.data = N...
3,105
918
# output from call_ectyper.py, to be sent to beautify.py # example is from ECI-2866_lcl.fasta_ectyper.p ectyper_dict = {'Virulence Factors': {'lcl|ECI-2866|NODE_56_length_6694_cov_33.7669_ID_111': [{'START': 4864, 'STOP': 5820, 'ORIENTATION': '+', 'GENE_NAME': 'stx1A'}, {'START': 4873, 'STOP': 5820, 'ORIENTATION': '+',...
32,365
18,171
from totality import Totality, Node, NodeId def test_basic(): t = Totality() coll = t.create_collection(username="system") node_id = NodeId(node_type="facility") node = Node(node_id, 34, -120, collection=coll) print(node.to_doc()) assert t is not None
276
96
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import torch from fvcore.transforms import HFlipTransform from detectron2.modeling.postprocessing import detector_postprocess from detectron2.modeling.test_time_augmentation import GeneralizedRCNNWithTTA class DensePoseGeneralizedRCNNWithTTA(Gene...
3,630
1,042
# -*- coding: utf-8 -*- """Generate charts for the ComPath GitHub Pages site.""" import click import matplotlib.pyplot as plt import pandas as pd import seaborn as sns from more_click import verbose_option from compath_resources import get_df from compath_resources.constants import DATA_DIRECTORY, IMG_DIRECTORY __a...
1,343
507
import pandas as pd import os from schema import db import random class ReadData(): """ Acquire song data from the url provided by Turi and save it into local database. """ def __init__(self): self.SEED = 12345 def readSongData(self): """ read song data from the url provid...
3,681
1,157
# -*- coding: utf-8 -*- """ Created on Thu Feb 28 14:24:27 2019 @author: adarzi """ #Loading the libraries import pandas as pd import os from os import sys import pickle #setting the directory os.chdir(sys.path[0]) #loading the data: data = pd.read_csv('../../Inputs/Trip_Data/AirSage_Data/trips_lon...
1,245
507
import math H, N = [int(n) for n in input().split()] A = [] B = [] for _ in range(N): a, b = [int(n) for n in input().split()] A.append(a) B.append(b) p = [] for i in range(N): p.append(A[i] / B[i]) for pp in p: pass # print(pp) maisu = [] for i in range(N): maisu.append(math.ceil(H / A[i])) for m ...
340
165
# Copyright 2020 Superb AI, 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 writi...
7,467
2,504
from uncertainties import ufloat from utilities import min_value, max_value def main(): print 'Plate motion rate parallel to section' print plate_motion() print 'Shortening (including ductile) from bed-length' print bed_length_shortening() print 'Estimated total shortening accomodated by OOSTS' ...
5,676
1,732
""" config.py Microsimulation config for mulit-LAD MPI simulation """ import numpy as np import glob import neworder # define some global variables describing where the starting population and the parameters of the dynamics come from initial_populations = glob.glob("examples/people_multi/data/ssm_*_MSOA11_ppp_2011.cs...
1,822
643
# present and accept dispute processing from flask import Blueprint, request, make_response, render_template, flash, redirect from openarticlegauge.core import app import openarticlegauge.util as util import openarticlegauge.models as models blueprint = Blueprint('issue', __name__) @blueprint.route("/", methods=['...
2,451
737
import random secret = random.randint(0,100000) guess_count = 0 guess_limit = 3 name = input("Enter Your Name: ") print(f"Hello, {name.upper()} welcome") print(" | This is your MAGIC CODE ➡️ [NFHSFXYW1234" + str(secret) + "5678910WRYUCN] |") print(" | ...
3,700
2,798
import smartpy as sp AUCTION_PARAMS_TYPE = sp.TRecord(opening_price = sp.TNat, reserve_price = sp.TNat, start_time = sp.TTimestamp, round_time = sp.TInt, ticket = sp.TTicket(sp.TNat)) METADATA_TYPE = sp.TMap(sp.TString, sp.TBytes) TOKEN_METADATA_TYPE = sp.TBigMap(sp.TNat, sp.T...
9,195
3,181
# 일반적으로 Data Generation file은 Group 별로 data를 생성 가능 # Group의 개념을 만들지 않으려면 모든 Group의 조건을 같이 하면 단 한개의 Group만 생성된 효과를 가져올 수 있음 import csv import numpy as np looptime=3 #Group 개수 number=[100,100,100] #각 Group당 사람수 number2=[100,100,100] #각 Group당 사람수 strengthlimit=100 #최대 Strength mean=[0,...
4,839
2,057
"""Tokenize a document. *** NLTK tokenization and this module have been deprecated in favor of a sklearn-based solution. However, NLTK may offer more options for tokenization, stemming, etc., this module is retained for future reference. """ import re import nltk import toolz as tz re_not_alpha = re.compile('[^a-zA...
1,826
654
from unittest.mock import ANY, Mock, patch import pytest from streamlit_server_state.server_state_item import ServerStateItem @pytest.fixture def patch_is_rerunnable(): with patch( "streamlit_server_state.server_state_item.is_rerunnable" ) as mock_is_rerunnable: mock_is_rerunnable.return_val...
2,483
912
#obsolete, each head should be defined in a separate file __all__ = ['FLOORDIV', 'MOD'] from .base import NaryHead class ModHead(NaryHead): """ ModHead represents module n-ary operation, data is a n-tuple of expression operands. """ op_mth = '__mod__' op_rmth = '__rmod__' op_symbol = '...
686
262
from django.views import View class CourseListView(View): pass
68
20
from classification.admin.classification_admin import * from classification.admin.clinvar_export_admin import * from classification.admin.condition_text_admin import *
168
41
#!/usr/bin/env python # Copyright (c) 2016, 2017 Joe Vernaci # # 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, mo...
17,656
6,645
import glycowork from glycowork.glycan_data.loader import df_species from glycowork.ml.train_test_split import * train_x, val_x, train_y, val_y, id_val, class_list, class_converter = hierarchy_filter(df_species, rank = 'Kingdom') p...
898
213
# greaseweazle/tools/seek.py # # Greaseweazle control script: Seek to specified cylinder. # # Written & released by Keir Fraser <keir.xen@gmail.com> # # This is free and unencumbered software released into the public domain. # See the file COPYING for more details, or visit <http://unlicense.org>. description = "Seek ...
1,374
470
"""Kata: Find the Duplicated Number in a Consecutive Unsorted List - Finds and returns the duplicated number from the list #1 Best Practices Solution by SquishyStrawberry def find_dup(arr): return (i for i in arr if arr.count(i) > 1).next() """ def find_dup(arr): """This will find the duplicated int in the ...
424
144
#coding:cp1252 """ @author: Antonio Gomez Vergara Generates text using word embeddings (still in process of study how word embeddings works) """ import sys import text_utils from rnn_class import TextGeneratorModel MIN_WORD_FREQ = 10 SEED = "Nenita hello" SEQUENCE_LEN = len(SEED) STRIDE = 1 BATCH_SIZE...
2,998
1,114
# -*- coding: utf-8 -*- """ Created on Thu Apr 18 16:14:01 2019 @author: KatieSi """ # https://jakevdp.github.io/PythonDataScienceHandbook/03.09-pivot-tables.html import numpy as np import pandas as pd import seaborn as sns titanic = sns.load_dataset('titanic') titanic.head() titanic.groupby(['sex', 'class'])['survi...
429
177
from matplotlib import pyplot as plt import numpy as np class TrellisPlotter: def __init__(self): self.cmap = None self.colorbar_label_rotation = None self.colobar_tick_fontsize = None self.grouped_fun = None self.fun = None self.data = None self.data_sets =...
23,777
7,044
#!/usr/bin/env python # coding: utf-8 import yaml import json import rospy import paho.mqtt.client as mqtt from ros_mqtt_bridge.args_setters import ArgsSetters class ROSToMQTT(ArgsSetters): def __init__(self, from_topic, to_topic, message_type): super(ROSToMQTT, self).__init__(message_type) s...
1,866
639
from functools import partial from typing import List, Optional, Sequence, Tuple import torch import torch.nn.functional as F from torch import nn from mmderain.models.common import sizeof from mmderain.models.registry import BACKBONES from mmderain.models.layers import SELayer_Modified class ResidualBlock(nn.Modul...
13,999
5,183
class Calculator: def add(self,a,b): return a+b def subtract(self,a,b): return a-b def multiply(self,a,b): return a*b def divide(self,a,b): return a/b
200
75
from random import randint # 무작위로 정렬된 1 - 45 사이의 숫자 여섯개 뽑기 def generate_numbers(): # 코드를 입력하세요 numbers = [] while (len(numbers) < 6): number = randint(1, 45) if number not in numbers: numbers.append(number) numbers.sort() return numbers # 보너스까지 포함해 7개 숫자 뽑기 # 정렬된 6개의 당...
1,336
680
# Copyright 2021 Google LLC # # 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 writing, ...
1,614
522
# -*- coding: utf-8 -*- # Generated by Django 1.10.3 on 2017-02-11 00:33 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('issue_order', '0004_auto_20170210_2358'), ] operations = [ migrations.Alter...
1,487
493
# Generated by Django 3.0.7 on 2020-06-18 19:21 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('letters', '0010_remove_letter_address'), ] operations = [ migrations.CreateModel( name='Documen...
1,181
342
import dns import dns.resolver import dns.rdatatype def dns_resolve(domain: str) -> list: addrs = [] resolver = dns.resolver.Resolver(configure=False) # Default to Google DNS resolver.nameservers = ['8.8.8.8', '8.8.4.4'] try: for answer in resolver.resolve(domain, 'A').response.answer: ...
776
250
"""" File : kombu_messaging.py Author : ian Created : 09-28-2016 Last Modified By : ian Last Modified On : 09-28-2016 *********************************************************************** The MIT License (MIT) Copyright © 2016 Ian Cooper <ian_hammond_cooper@yahoo.co.uk> Permission is hereby...
8,039
2,305
import numpy as np def pline(x1, y1, x2, y2, x, y): px = x2 - x1 py = y2 - y1 dd = px * px + py * py u = ((x - x1) * px + (y - y1) * py) / max(1e-9, float(dd)) dx = x1 + u * px - x dy = y1 + u * py - y return dx * dx + dy * dy def psegment(x1, y1, x2, y2, x, y): px = x2 - x1 py =...
2,185
815
from functools import reduce from math import fsum n = int(input("How many number you want to enter for even and odd numbers ? : ")) lst = [] for i in range(n): j = int(input("Enter any positive number : ")) lst.append(j) evens = list(filter(lambda i: i % 2 == 0, lst)) print("Number of even numbers from list ...
505
171
"""Unit tests for :mod:`prov_interop.comparator`. """ # Copyright (c) 2015 University of Southampton # # 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...
3,315
1,085
print("Test hello world")
26
8
# Copyright 2020 - 2021 MONAI Consortium # 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 wri...
3,564
998
""" This package contains modules built specifically for the project in question. Below are decribed the modules and packages used in the notebooks of this project. Modules ----------- polynomials: | This module groups functions and classes for generating polynomials | whether fitting data or directly ortogonal ...
547
127
import os from typing import List, Optional import pickle import numpy as np from utilities import augment_long_text, tokenize, tokenize_long_text, to_chars, align from config import Config as cf PAD = 0 # TODO: choose appropriate index for these special chars UNK = 1 DEFAULT = {'PAD': PAD, 'UNK': UNK} DEFAULT_C = {''...
25,671
8,109
# File: test_mean_functions.py # File Created: Saturday, 13th July 2019 3:51:40 pm # Author: Steven Atkinson (steven@atkinson.mn) import pytest import torch from gptorch import mean_functions class TestConstant(object): def test_init(self): dy = 2 mean_functions.Constant(dy) mean_functio...
1,332
494
# -*- coding: utf-8 -*- from elasticsearch import Elasticsearch class ElasticAdapter(object): """ Abstraction in case we will need to add another or change elastic driver. """ def __init__(self, hosts, **es_params): self.es = Elasticsearch(hosts, **es_params)
292
89
""" Copyright (C) 2014 Maruf Maniruzzaman Website: http://cosmosframework.com Author: Maruf Maniruzzaman License :: OSI Approved :: MIT License """ import os import subprocess from cosmos.admin.samples import barebonedef, simpledef, angulardef, angularbasicdef, adminpaneldef def new_project(path, type=None): ...
2,146
620
from mcfunction.versions.mc_1_14.loot import loot, ParsedLootCommand from mcfunction.nodes import EntityNode, PositionNode def test_loot_spawn(): parsed = loot.parse('loot spawn 0 0 0 kill @e') parsed: ParsedLootCommand assert parsed.target_type.value == 'spawn' assert isinstance(parsed.target, Posi...
1,930
688
from __future__ import absolute_import, division, print_function, unicode_literals import unittest import torch import torch.nn as nn from tests.utils import jitVsGlow from torch.quantization import ( DeQuantStub, QConfig, QuantStub, convert, fuse_modules, observer, prepare, ) my_qconfig...
2,475
823
# -*- coding: utf-8 -*- """ Use nose `$ pip install nose` `$ nosetests` """ from textwrap import dedent from hyde.generator import Generator from hyde.site import Site from fswrap import File TEST_SITE = File(__file__).parent.parent.child_folder('_test') class TestPaginator(object): def setUp(self): T...
3,878
1,264
import configparser as parser import random class config: # load the configuration file def __init__(self, config_filename): self.load_config(config_filename) def load_config(self, config_filename): # create a config parser config = parser.ConfigParser() config.optionxform ...
2,162
573
import numpy from kapteyn import maputils from matplotlib.pyplot import show, figure import csv # Read some poitions from file in Comma Separated Values format # Some initializations blankcol = "#334455" # Represent undefined values by this color epsilon = 0.0000000001 figsize = (9,7) ...
4,326
1,751
import sys import gtk from datetime import datetime import gobject from threading import Thread class uiSignalHelpers(object): def __init__(self, *args, **kwargs): super(uiSignalHelpers, self).__init__(*args, **kwargs) #print 'signal helpers __init__' def callback(self, *args, **kwargs): ...
11,303
3,516
from functools import partial from unittest.mock import ANY, PropertyMock import pytest from bs4 import BeautifulSoup, element from flask import url_for from freezegun import freeze_time from app.main.views.feedback import in_business_hours from app.models.feedback import ( GENERAL_TICKET_TYPE, PROBLEM_TICKET...
21,622
7,826
import sys import torch.nn as nn from torchsummary import summary from torchvision.models import vgg19, resnet50, densenet161, googlenet, inception_v3 from .MyCNN import MyCNN def VGG19(all=False): model = vgg19(pretrained=True) # 把參數凍結 if all is False: for param in model.parameters(): ...
3,022
1,140
from .crack_key import derive_loop_size, derive_encryption_key
63
21
from .interval import Interval from .note import Note class Scale(): """ The scales class. """ scale_recipes = { 'major' : ['M2', 'M3', 'P4', 'P5', 'M6', 'M7', 'P8'], 'natural_minor': ['M2', 'm3', 'P4', 'P5', 'm6', 'm7', 'P8'], 'harmonic_minor': ['M2', 'm3', 'P4',...
2,324
913
start = '''You wake up one morning and find yourself in a big crisis. Trouble has arised and your worst fears have come true. Zoom is out to destroy the world for good. However, a castrophe has happened and now the love of your life is in danger. Which do you decide to save today?''' print(start) done = False ...
1,549
518
#!/usr/bin/env python from __future__ import division from project_weather_x.srv import Weather,WeatherResponse import os import rospy import numpy as np import urllib2 import cv2 import json def handle_weather(req): print "Returning weather data for zipcode [%s]"%(req) return WeatherResponse(showWeather(pro...
3,141
1,342
# -*- coding: utf-8 -*- from __future__ import unicode_literals import os, re, sys import pickle from rest_framework.decorators import api_view, permission_classes from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response CURRENT_PATH = os.path.dirname(os.path.abspath(__fi...
2,261
694
from selenium import webdriver from fb_auth import auth from logger import Logger def main(): # TODO add possibility to login to different FB accounts (use csv file to store them) # TODO handle all exceptions especially when account was blocked # TODO save automatic screenshots from time to time # TOD...
654
179
import uuid import random import os import math import numpy as np import simpy import matplotlib.pyplot as plt from simulation.ghostdag import block from simulation.ghostdag.dag import select_ghostdag_k, DAG from simulation.fakes import FakeDAG from simulation.channel import Hub, Channel, PlanarTopology from simulat...
4,022
1,666
from kwmo.controllers.abstract_teambox import * import time from kwmo.lib.kwmo_kcd_client import KcdClient from kwmo.lib.config import get_cached_kcd_external_conf_object from kfs_lib import * from kwmo.lib.base import init_session from kwmo.lib.kwmolib import * from kwmo.model.user import User from kwmo.model.kfs_n...
15,140
4,574
import torch.nn as nn import torch.nn.functional as F import torch as th import numpy as np import torch.nn.init as init class NRNNAgent(nn.Module): def __init__(self, input_shape, args): super(NRNNAgent, self).__init__() self.args = args self.fc1 = nn.Linear(input_shape, args.rnn_hidden_d...
1,310
530
# -*- coding: utf8 -*- # This file is a part of netsav # # Copyright (c) 2014-2015 Pierre GINDRAUD # # 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 li...
3,971
1,156
#!/usr/bin/env python import os import h5netcdf import scipy.ndimage from veros import veros_routine, veros_kernel, KernelOutput, VerosSetup, runtime_settings as rs, runtime_state as rst from veros.variables import Variable, allocate from veros.core.utilities import enforce_boundaries from veros.core.operators import...
16,921
6,613
import argparse import os import cv2 import numpy as np def gamma_correction(source_path, destination_path, a, b, version): # Load image into memory # Algorithm can work correctly with colored and grayscale images if version == 'colored': original_image = cv2.imread(source_path) elif version ...
2,000
591
__author__ = 'Guorong Xu<g1xu@ucsd.edu>' import os from util import YamlFileMaker from util import QstatParser from cfnCluster import ConnectionManager import sys workspace = "/shared/workspace/Pipelines/" #log_dir = "/shared/workspace/data_archive/DNASeq/{}/logs" log_dir = "/shared/workspace/logs/DNASeq/{}" ## exec...
2,154
717
from loguru import logger from chatbot import register_call import global_variables import random import os import yaml import geocoder import constants @register_call("location") def location(session_id = "general", dummy=0): config_path = constants.find_data_file(os.path.join('intents','functions','location','conf...
960
326
from enum import Enum class ArgType(Enum): """ Represents data types that can be used as arguments in different script functions. """ Undefined = -1 Empty = 0 String = 1 Numeric = 2 Mixed = 3 class ReturnType(Enum): """ Represents return types that can be used in scri...
531
181
# Lint as: python3 # Copyright 2020 DeepMind Technologies Limited. 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 # # https://www.apache.org/licenses/LICENSE-2.0 # #...
10,188
3,962
{'application':{'type':'Application', 'name':'codeEditor', 'backgrounds': [ {'type':'Background', 'name':'bgCodeEditor', 'title':'Code Editor R PythonCard Application', 'size':(400, 300), 'statusBar':1, 'visible':0, 'style':['resizeable'], ...
12,526
3,115
from reinvent_scoring.scoring.diversity_filters.curriculum_learning.update_diversity_filter_dto import \ UpdateDiversityFilterDTO from unittest_reinvent.diversity_filter_tests.test_murcko_scaffold_base import BaseMurckoScaffoldFilter from unittest_reinvent.diversity_filter_tests.fixtures import tanimoto_scaffold_fi...
911
317
# This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild from pkg_resources import parse_version from .kaitaistruct import __version__ as ks_version, KaitaiStruct, KaitaiStream, BytesIO import collections if parse_version(ks_version) < parse_version('0.7'): raise Excepti...
18,170
6,517
from awx.main import signals class TestCleanupDetachedLabels: def test_cleanup_detached_labels_on_deleted_parent(self, mocker): mock_labels = [mocker.MagicMock(), mocker.MagicMock()] mock_instance = mocker.MagicMock() mock_instance.labels.all = mocker.MagicMock() mock_instance.labe...
807
273
__all__ = ['FileUtils']
23
9
import pandas as pd import numpy as np from pathlib import Path from sklearn.preprocessing import MinMaxScaler from sklearn.model_selection import train_test_split class AccidentsData: def __init__(self): filename = Path('../data/accidents.csv') if not filename.exists(): print('\nERROR...
7,617
2,383
import os import shutil import sys def rm_r(path): if os.path.isdir(path) and not os.path.islink(path): shutil.rmtree(path) elif os.path.exists(path): os.remove(path) def cleanUp(logdir = "./log/"): print("Cleaning all files in log ... ", end="") sys.stdout.flush() rm_r(logdir) ...
471
186
# -*- coding: utf-8 -* from typing import Dict from yacs.config import CfgNode from .backbone import builder as backbone_builder from .loss import builder as loss_builder from .task_head import builder as head_builder from .task_model import builder as task_builder def build_model( task: str, cfg: C...
1,577
501
#Distributed under the MIT licesnse. #Copyright (c) 2013 Cospan Design (dave.mccoy@cospandesign.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 limit...
8,221
2,915
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. class TimexRelativeConvert: @staticmethod def convert_timex_to_string_relative(timex): return ''
209
60
# -*- coding: utf-8 -*- # Copyright (C) 2010-2014 Tobias Weber <tobi-weber@gmx.de> # # 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 ...
9,740
2,745
from .qemuvolume import QEMUVolume from ..tools import log_check_call import math class VirtualHardDisk(QEMUVolume): extension = 'vhd' qemu_format = 'vpc' ovf_uri = 'http://go.microsoft.com/fwlink/?LinkId=137171' # Azure requires the image size to be a multiple of 1 MiB. # VHDs are dynamic by def...
1,255
432
""" Flight path tests """ from typing import List, Union from avwx import flight_path from avwx.structs import Coord FLIGHT_PATHS = ( ( [(12.34, -12.34, "12.34,-12.34"), (-43.21, 43.21, "-43.21,43.21")], [(12.34, -12.34, "12.34,-12.34"), (-43.21, 43.21, "-43.21,43.21")], ), ( [(12....
2,180
1,099
from django.conf.urls import url from . import views urlpatterns = [ # report route url(r'^create/$', views.ReportCreateAPIView.as_view(), name='create'), url(r'^$', views.ReportListAPIView.as_view(), name='list'), url(r'^(?P<pk>\d+)$', views.ReportRetrieveAPIView.as_view(), name='detail'), ]
312
112
# Find file contents via various criteria.
42
9
"""Class implementation for the stop_propagation interface. """ from apysc._type.variable_name_interface import VariableNameInterface class StopPropagationInterface(VariableNameInterface): def stop_propagation(self) -> None: """ Stop event propagation. """ import apys...
666
190
""" _______ __ _______ __ __ __ | _ .----.-----.--.--.--.--| | _ | |_.----|__| |--.-----. |. 1___| _| _ | | | | _ | 1___| _| _| | <| -__| |. |___|__| |_____|________|_____|____ |____|__| |__|__|__|_____| |: 1 | |: 1 | |::.. ...
21,312
5,778
#!/bin/python3 h = 0 t = int(input().strip()) for a0 in range(t): n = int(input().strip()) if n%2 == 1: h = 2 ** (int(n/2) + 2) - 2 elif n%2 == 0: h = 2 ** (int(n/2) + 1) - 1 print(h)
233
118
#========================================================================= # BehavioralRTLIRL4Pass_test.py #========================================================================= # Author : Peitian Pan # Date : Feb 2, 2019 """Test the level 4 behavioral RTLIR passes. The L4 generation, L4 type check, and visualiz...
3,319
1,167
# import json import uuid from django.apps import apps from django.core import serializers from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from django.shortcuts import render from django.shortcuts import redirect from django.conf import settings from .api_helpers import * Ep...
2,287
702
import graphene from ...core.permissions import ProductPermissions from ...core.tracing import traced_resolver from ...csv import models from ..core.fields import FilterInputConnectionField from ..decorators import permission_required from .filters import ExportFileFilterInput from .mutations import ExportProducts fro...
1,446
409
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_pytest_localftpserver ---------------------------------- Tests for `pytest_localftpserver` module. """ import os from ftplib import error_perm import pytest from .test_pytest_localftpserver import (ftp_login, check_fil...
5,584
1,869
#!/usr/bin/python # -*- coding: utf-8 -*- import cv2 import numpy as np import random import math import torch def _crop(image, boxes, labels, p=0.75, min_iou=0.75, max_iou=0.25): def matrix_iou(a, b): lt = np.maximum(a[:, np.newaxis, :2], b[:, :2]) rb = np.minimum(a[:, np.newaxis, 2:], b[:, 2:]...
5,975
2,368
import torch import torch.nn as nn from diversebranchblock import DiverseBranchBlock from acb import ACBlock from dbb_transforms import transI_fusebn CONV_BN_IMPL = 'base' DEPLOY_FLAG = False class ConvBN(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride, ...
3,575
1,215
from dataclasses import dataclass, field from typing import Dict import perde import pytest from util import FORMATS, FORMATS_EXCEPT """rust #[derive(Serialize, Debug, new)] struct Plain { a: String, b: String, c: u64, } add!(Plain {"xxx".into(), "yyy".into(), 3}); """ @pytest.mark.parametrize("m", FORMATS) d...
7,961
3,225
from nifcloud import session import sys # --- define -------- # -- Server ------- SERVER_NAME = "testsv" # -------------------- # -- PRIVATE NW ------- PRIVATE_NW_NAME = 'test' PRIVATE_NW_IP = 'static' # -------------------- # ------------------- # ------ update attribute -------------------- def wait_for_instance...
3,045
877
# To use this code, make sure you # # import json # # and then, to convert JSON from a string, do # # result = groups_from_dict(json.loads(json_string)) from typing import Optional, Any, List, TypeVar, Type, cast, Callable T = TypeVar("T") def from_str(x: Any) -> str: assert isinstance(x, str) retu...
15,646
4,863
import requests import pprint import json # Suppress ssl verification warning requests.packages.urllib3.disable_warnings() s = requests.Session() s.auth = ("user", "password") s.verify = False host = "localhost" apis = ["https://api.mercedes-benz.com/vehicledata/v2/vehicles", "https://api.mercedes-benz.com/vehicled...
12,585
3,758