text
string
size
int64
token_count
int64
"""Add Initial Image Table Revision ID: 4a916694f1ba Revises: Create Date: 2020-10-16 02:24:18.479608 """ import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision = '4a916694f1ba' down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands ...
932
340
import os import logging import platform import time import multiprocessing import numpy import pymongo # Pure python/numpy import simplex from scalarobj import ScalarObjective # Cython/numpy import cyscalarobj import cysimplex class MultiStartSimplex(object): """Baseclass for multi-start recongerging simplex s...
9,969
3,011
from netsuitesdk.internal.utils import PaginatedSearch from .base import ApiBase import logging logger = logging.getLogger(__name__) class CustomRecords(ApiBase): def __init__(self, ns_client): ApiBase.__init__(self, ns_client=ns_client, type_name='CustomRecordType') def get_all_by_id(self, interna...
695
214
#!/usr/bin/env python3 import os vcfdir='/home/matt/Plasmodium/Pf_SV/Data' for ID in os.listdir(vcfdir): nameID = '_'.join(ID.split('.')[0].split('_')[:-1]) coreID = nameID.split('_')[-1] if coreID[:3] == 'ERR': os.system('cp {0}.cnvs {1}_DEL.cnvs'.format(coreID, nameID)) os.system('cp {0}.cnvs {1}_DUP.cnvs'.f...
343
162
# ======================================================================================================================================= # VNU-HCM, University of Science # Department Computer Science, Faculty of Information Technology # Authors: Nhut-Nam Le (Tich Phan Suy Rong) # © 2020 """ Given a string name, e.g. ...
1,568
526
text1 = '''ABCDEF GHIJKL MNOPQRS TUVWXYZ ''' text2 = 'ABCDEF\ GHIJKL\ MNOPQRS\ TUVWXYZ' text3 = 'ABCD\'EF\'GHIJKL' text4 = 'ABCDEF\nGHIJKL\nMNOPQRS\nTUVWXYZ' text5 = 'ABCDEF\fGHIJKL\fMNOPQRS\fTUVWXYZ' print(text1) print('-' * 25) print(text2) print('-' * 25) print(text3) print('-' * 25) print(text4) print('-' * 2...
335
210
from pygears import gear, Intf from pygears.common import czip from pygears.typing import Tuple, Uint, Union, Queue from pygears.common import fmap, demux, decoupler, fifo, union_collapse from pygears.cookbook import priority_mux, replicate TCfg = Tuple[{'reduce_size': Uint['w_reduce_size'], 'init': 't_acc'}] @gear ...
823
341
# unihernandez22 # https://atcoder.jp/contests/abc166/tasks/abc166_d # math, brute force n = int(input()) for a in range(n): breaked = True for b in range(-1000, 1000): if a**5 - b**5 == n: print(a, b) break; else: breaked = False if breaked: break
313
126
# grid relative from .. import BaseModel from .. import db class Group(BaseModel): __tablename__ = "group" id = db.Column(db.Integer(), primary_key=True, autoincrement=True) name = db.Column(db.String(255)) def __str__(self): return f"<Group id: {self.id}, name: {self.name}>"
305
107
import urx import logging import time if __name__ == "__main__": logging.basicConfig(level=logging.WARN) #gripper_remove_pos = [0.0755, -0.2824, 0.3477, -0.0387, -3.0754, 0.4400] # rest position (good to place/remove gripper) rob = urx.Robot("192.168.56.1") #rob.set_tcp((0,0,0,0,0,0)) #rob.set_...
2,416
1,228
# Authored by : gusdn3477 # Co-authored by : - # Link : http://boj.kr/8adc986ae26b461eadd65abdff3cfba9 import sys def input(): return sys.stdin.readline().rstrip() N = int(input()) book = {} for i in range(N): name = input() if name not in book: book[name] = 1 else: book[name] += 1 bo...
403
174
# Copyright 2020 Katteli Inc. # TestFlows.com Open-Source Software Testing Framework (http://testflows.com) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/lice...
1,152
364
# # Copyright (c) 2020-2021 Arm Limited and Contributors. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # import pathlib import tempfile from unittest import TestCase, mock from mbed_tools.build.flash import flash_binary, _build_binary_file_path, _flash_dev from mbed_tools.build.exceptions import Binary...
3,220
1,027
import time import typing import requests from sys import stderr from datetime import datetime from packettotal_sdk import packettotal_api class SearchTools(packettotal_api.PacketTotalApi): def __init__(self, api_key: str): """ :param api_key: An API authentication token """ sup...
2,795
852
from . import types, video # noqa: F401
41
17
def handle(instance): from core.models import Controller, ControllerSlice, ControllerNetwork, NetworkSlice networks = [ns.network for ns in NetworkSlice.objects.filter(slice=instance.slice)] controller_networks = ControllerNetwork.objects.filter(network__in=networks, ...
531
149
from unittest.mock import Mock, patch import pandas as pd from sdgym.s3 import is_s3_path, parse_s3_path, write_csv, write_file def test_is_s3_path_with_local_dir(): """Test the ``sdgym.s3.is_s3_path`` function with a local directory. If the path is not an s3 path, it should return ``False``. Input: ...
4,987
1,735
import csv import datetime import frappe # bench execute vet_care.scripts.generate_from_history.execute --args "['./data/important_data.csv']" def execute(filename): patient_activities = [] not_created = [] with open(filename, 'r') as csvfile: reader = csv.DictReader(csvfile) for row in re...
3,227
933
from cloud.permission import Permission, NeedPermission # Define the input output format of the function. # This information is used when creating the *SDK*. info = { 'input_format': { 'session_ids': ['str'], }, 'output_format': { 'success': 'bool' }, 'description': 'Delete session...
594
178
# coding=<utf-8> import requests import re import socket import base64 import psutil import pywifi from pywifi import const import subprocess import os import time def get_host_ip(): try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(('8.8.8.8', 80)) ip = s.getsockname()[0...
5,509
2,115
"""Utilities for approximating gradients.""" import numpy as np from utils.misc import process_inputs from utils.simrunners import SimulationRunner def local_linear_gradients(X, f, p=None, weights=None): """Estimate a collection of gradients from input/output pairs. Given a set of input/output pairs, choo...
3,096
1,007
# encoding: utf-8 """ Read images and corresponding labels. """ import torch from torch.utils.data import Dataset from PIL import Image import os import random class ChestXrayDataSetTest(Dataset): def __init__(self, image_list_file, transform=None, combine_pneumonia=False): """ Create the Data Lo...
6,861
2,062
import csv import sys from pathlib import Path from abc import abstractmethod import numpy as np import tensorflow as tf from tqdm import tqdm import common.tf_utils as tf_utils import metrics.manager as metric_manager from common.model_loader import Ckpt from common.utils import format_text from common.utils import ...
7,996
2,403
__author__ = 'Mandar Patil (mandarons@pm.me)' import datetime import os import re import time from pathlib import Path from shutil import copyfileobj, rmtree from pyicloud import PyiCloudService, utils, exceptions from src import config_parser from src import notify def wanted_file(filters, file_path, verbose=Fals...
7,483
2,098
#! python3 import numpy as np import matplotlib.pyplot as plt from LightPipes import * """ MultiSlit.py Demonstrates the RowOfFields command. Two wavelengths are used to show the principles of a grating. cc Fred van Goor, June 2020. """ wavelength=1000*nm Dlambda=150*nm size=11*mm N=2000 N2=int(N/...
2,163
1,063
from genshi.template import MarkupTemplate from trac.core import * from trac.web.chrome import Chrome from trac.wiki.macros import WikiMacroBase class GenshiMacro(WikiMacroBase): def expand_macro(self, formatter, name, text, args): template = MarkupTemplate(text) chrome = Chrome(self.env) ...
389
118
#!/usr/bin/python ############################################## ###Python template ###Author: Elizabeth Lee ###Date: 10/11/14 ###Function: Any diagnosis per 100,000 population vs. week number for flu weeks (wks 40-20). Population size is from the calendar year of the week of calculation. ###Import data: SQL_export/a...
2,110
890
#!/usr/bin/python # -*- coding: utf-8 -*- # Hive Colony Framework # Copyright (c) 2008-2020 Hive Solutions Lda. # # This file is part of Hive Colony Framework. # # Hive Colony Framework is free software: you can redistribute it and/or modify # it under the terms of the Apache License as published by the Apach...
5,290
1,691
import os import wx from vistas.core.graphics.camera_interactor import * from vistas.core.graphics.overlay import BasicOverlayButton from vistas.core.paths import get_resources_directory from vistas.ui.events import CameraChangedEvent from vistas.ui.utils import get_main_window class GLCameraControls(wx.EvtHandler)...
3,458
1,096
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'D:\SVNzhangy\fast-transfer\src\_sever.ui' # # Created by: PyQt4 UI code generator 4.11.4 # # WARNING! All changes made in this file will be lost! from PySide import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except Attribut...
8,678
2,980
import json from aleph.tests.util import TestCase class DocumentsApiTestCase(TestCase): def setUp(self): super(DocumentsApiTestCase, self).setUp() self.load_fixtures('docs.yaml') def test_index(self): res = self.client.get('/api/1/documents') assert res.status_code == 200, r...
4,579
1,618
import json import pandas as pd from geopy.geocoders import Nominatim def getAcropolisStatistics(): data = pd.read_csv("Analytics/demographics_old.csv") ratings_acropolis = len(data) gender = data.gender.str.lower().value_counts() ages = data.age_group.value_counts() return ratings_acropolis, ge...
649
221
#!/usr/bin/env python import os import pwd import sys import time from Pegasus.DAX3 import * # The name of the DAX file is the first argument if len(sys.argv) != 2: sys.stderr.write("Usage: %s DAXFILE\n" % (sys.argv[0])) sys.exit(1) daxfile = sys.argv[1] USER = pwd.getpwuid(os.getuid())[0] # Create ...
1,464
559
import logging from six import int2byte from binascii import unhexlify from twisted.internet import defer from .resolve import Resolver from lbryschema.error import URIParseError from lbryschema.uri import parse_lbry_uri from torba.baseledger import BaseLedger from .account import Account from .network import Netwo...
3,685
1,345
T = int(input()) P = int(input()) controle = 0 #Uso para guardar o valor maior que o limite while P != 0: P = int(input()) if P >= T: controle = 1 #coloquei 1 so pra ser diferente de 0 if controle == 1: print("ALARME") else: print("O Havai pode dormir tranquilo")
297
121
import numpy as np import gym import time from matplotlib import pyplot as plt from fetch_cam import FetchCameraEnv from fsm import FSM dis_tolerance = 0.0001 # 1mm env = FetchCameraEnv() obs = env.reset() done = False want_pos = (obs['eeinfo'][0]).copy() ori_pos = (obs['eeinfo'][0]).copy() print('---ori_pos ...
1,387
595
# coding=utf-8 from packages import * import os #SET PARAMETERS myverbosity=-1 mymaxencode=5 TXT_filetypes=( #simple text files 'txt','lst', #config files 'ini','cfg', #programming languages 'c','cpp', #scripts 'vbs','py','pl') XLS_filetypes=('xls','xlsx') DOC_filetypes=('doc',) DOCX_filetypes=('docx',) PDF_filetype...
5,091
2,116
import numpy as np import pandas as pd from os.path import join as oj import os import pygsheets import pandas as pd import sys import inspect from datetime import datetime, timedelta currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir = os.path.dirname(currentdir) sys.path...
2,732
987
# Copyright 2017 OpenStack Foundation # 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 requ...
4,582
1,424
# -*- coding: utf-8 -*- # MIT license # # Copyright (C) 2018 by XESS Corp. # # 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...
26,935
8,334
import numpy as np import operator # SHHONG: custom modules imported import json import random import itertools from math import pow, log from collections import Counter import os import sys sys.stdout = open(os.devnull, 'w') """ CMSC723 / INST725 / LING723 -- Fall 2016 Project 1: Implementing Word Sense Disambiguati...
34,030
12,475
# Мы сохранили страницу с википедии про языки программирования и сохранили по адресу # https://stepik.org/media/attachments/lesson/209717/1.html # # Скачайте её с помощью скрипта на Питоне и посчитайте, какой язык упоминается чаще Python или C++ (ответ должен быть # одной из этих двух строк). Необходимо просто подсчита...
640
239
import unittest from unittest import mock from unittest.mock import MagicMock from clovars.abstract import Circle from clovars.bio import Cell, Treatment from clovars.scientific import ConstantCellSignal, CellSignal, GaussianCellSignal, Gaussian from clovars.utils import SimulationError from tests import NotEmptyTestC...
31,794
10,006
""" .. module:: cnn_train :synopsis: Example nuts-ml pipeline for training a MLP on MNIST """ import torch import torch.nn.functional as F import torch.nn as nn import torch.optim as optim import nutsflow as nf import nutsml as nm import numpy as np from nutsml.network import PytorchNetwork from utils import downl...
2,959
1,053
"""This code contains functions called by gui.py. This software is licensed under the MIT license. """ import time from picamera.array import PiRGBArray from picamera import PiCamera from gpiozero import LED import numpy as np from PIL import Image __author__ = "Daniel James Evans" __copyright__ = "Copyright 2019...
2,317
872
''' Copyright (C) 2016 The Crown (i.e. Her Majesty the Queen in Right of Canada) This file is an add-on to RAVE. RAVE is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (a...
15,346
5,877
# Generated by Django 3.1.4 on 2020-12-27 15:03 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Product', fields=[ ('id', models.AutoField(...
1,038
303
from setuptools import setup setup( name='tsnecuda', version='2.1.0', author='Chan, David M., Huang, Forrest., Rao, Roshan.', author_email='davidchan@berkeley.edu', packages=['tsnecuda', 'tsnecuda.test'], package_data={'tsnecuda': ['libtsnecuda.so']}, scripts=[], url='https://github.com...
921
315
#!/usr/bin/env python # coding: utf-8 # <h1>Table of Contents<span class="tocSkip"></span></h1> # <div class="toc" style="margin-top: 1em;"><ul class="toc-item"><li><span><a href="#0.1-Motivation" data-toc-modified-id="0.1-Motivation-1"><span class="toc-item-num">1&nbsp;&nbsp;</span>0.1 Motivation</a></span></li><li><...
107,889
38,121
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import errno import ...
4,870
1,543
#! /usr/bin/env python # -*- coding: utf-8 -*- # DaVinci Resolve scripting proof of concept. Resolve page external switcher. # Local or TCP/IP control mode. # Refer to Resolve V15 public beta 2 scripting API documentation for host setup. # Copyright 2018 Igor Riđanović, www.hdhead.com from PyQt4 import QtCore, QtGui ...
4,947
1,828
""" All the data sources are scattered around the D drive, this script organizes it and consolidates it into the "Data" subfolder in the "Chapter 2 Dune Aspect Ratio" folder. Michael Itzkin, 5/6/2020 """ import shutil as sh import pandas as pd import numpy as np import os # Set the data directory to sav...
14,022
4,707
def end_of_import(): return 0 def end_of_init(): return 0 def end_of_computing(): return 0 import numpy as np from sklearn.linear_model import LinearRegression end_of_import() X = np.array(range(0,100000)).reshape(-1, 1) # y = 2x + 3 y = np.dot(X, 2) + 3 end_of_init() reg = LinearRegression().fit(X, y)...
339
148
import requests url = "https://api.korbit.co.kr/v1/ticker/detailed?currency_pair=btc_krw" r = requests.get(url) bitcoin = r.json() print(bitcoin) print(type(bitcoin)) print(bitcoin['last']) print(bitcoin['bid']) print(bitcoin['ask']) print(bitcoin['volume'])
262
111
"""A convenience class for a GTK 3 system tray indicator.""" from pkg_resources import resource_filename import gi gi.require_version('Gtk', '3.0') # noqa from gi.repository import Gtk from gi.repository.GdkPixbuf import Pixbuf class Indicator: """This class defines a standard GTK3 system tray indicator. ...
3,938
1,180
# -*- coding: utf-8 -*- # Generated by Django 1.11.7 on 2018-11-06 01:54 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('myaxf', '0010_minebtns'), ] operations = [ migrations.AddField( ...
442
157
#!/usr/bin/env/python3 # # Copyright (c) Facebook, Inc. and its affiliates. # 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...
3,342
998
""" Utility to get generate all submission pipelines for all primitives. This script assumes that `generate_annotations.py` has already been run. """ import os import subprocess import shutil import fire from kf_d3m_primitives.data_preprocessing.data_cleaning.data_cleaning_pipeline import DataCleaningPipeline from...
10,453
3,815
__all__ = [ "aggregation", "association", "composition", "connection", "containment", "dependency", "includes", "membership", "ownership", "responsibility", "usage" ]
210
72
# coding: utf-8 """Square module. Represents the squares on the game grid. """ from scene import * from common import * import sound class Square (SpriteNode): """Represents the squares on the game grid. Main properties are their row and column (used for path calculation) and state (corresponds to color in ...
3,851
1,182
import pathlib from struct import unpack from typing import BinaryIO, List, Optional, Tuple, cast import numpy as np import scipy.sparse def _read_little_endian_crec(file: BinaryIO ) -> Optional[Tuple[int, int, float]]: le_int = file.read(16) # https://docs.python.org/3/library/s...
1,128
402
# Generated by Django 3.2.12 on 2022-02-15 02:57 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='SpotPrice', fields=[ ('id', models.BigAuto...
597
177
# -*- coding: utf-8 -*- # Copyright (c) 2021 Ramon van der Winkel. # All rights reserved. # Licensed under BSD-3-Clause-Clear. See LICENSE file for details. from django.views.generic import View from django.urls import reverse from django.http import HttpResponseRedirect from Functie.rol import Rollen, rol_get_hui...
924
312
import os import numpy as np # class for depression class Depression: def __init__(self, id, width, depth, area, pour_elev, min_elev, points, internal_pts): self.id = id self.width = width self.depth = depth self.area = area self.pour_elev = pour_elev self.min_elev ...
9,511
3,133
import argparse import os import csv import random from utils import ensure_dir, get_project_path from collections import defaultdict # POS-tag for irrelevant tag selection import nltk nltk.download('punkt') nltk.download('averaged_perceptron_tagger') __author__ = "Gwena Cunha" def write_tsv(intention_dir_path, fi...
4,544
1,366
from typing import List, Dict, Union from django.db import models # Create your models here. # https://en.wikipedia.org/wiki/Cooking_weights_and_measures class AmountType(models.TextChoices): GRAMS = ('g', 'grams') KILOGRAMS = ('kg', 'kilograms') MILLILITERS = ('ml', 'milliliters') TABLE_SPOONS = ('tbsp', 'tabl...
4,989
1,969
"""Config module.""" import json import logging import os from zoneh.exceptions import ConfigError _log = logging.getLogger(__name__) _CONFIG_FILE = 'config.json' def _load_config(): """Load telegram and filters configuration from config file.""" if not os.path.isfile(_CONFIG_FILE): err_msg = f'Can...
835
264
###demo code provided by Steve Cope at www.steves-internet-guide.com ##email steve@steves-internet-guide.com ###Free to use for any purpose """ implements data logging class """ import time, os, json, logging ############### class m_logger(object): """Class for logging data to a file. You can set the m...
3,629
1,205
""" 2018 (c) piteren some little methods (but frequently used) for Python """ from collections import OrderedDict import csv import inspect import json import os import pickle import random import shutil import string import time from typing import List, Callable, Any, Optional # prepares function parameters...
6,299
2,099
import filecmp import hashlib import json import grass def grass_to_json(): """ Tests reading of grass file and exports data as a json file """ data = grass.read_grass("assets/5000000000.grass.extm") print("Saving file output/5000000000.grass.extm.json...") with open("output/5000000000.grass...
2,135
836
class AxisIndex(): #TODO: read this value from config file LEFT_RIGHT=0 FORWARD_BACKWARDS=1 ROTATE=2 UP_DOWN=3 class ButtonIndex(): TRIGGER = 0 SIDE_BUTTON = 1 HOVERING = 2 EXIT = 10 class ThresHold(): SENDING_TIME = 0.5
259
115
# -*- coding: utf-8 -*- from .BaseTest import BaseTest class LayoutTest(BaseTest): def test_layout_switch(self): """ Test layout switch """ self.do_component_fixture_test_with_real_sphinx('layout', 'layout') def test_layout_multiple(self): """ Test multiple lay...
446
136
# @lc app=leetcode id=16 lang=python3 # # [16] 3Sum Closest # # https://leetcode.com/problems/3sum-closest/description/ # # algorithms # Medium (46.33%) # Likes: 3080 # Dislikes: 169 # Total Accepted: 570.4K # Total Submissions: 1.2M # Testcase Example: '[-1,2,1,-4]\n1' # # Given an array nums of n integers and ...
2,472
1,093
#! /usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import unittest import torch from botorch.test_functions.michalewicz import ( GLOBAL_MAXIMIZER, GLOBAL_MAXIMUM, neg_michalewicz, ) class TestNegMichalewicz(unittest.TestCase): def test_single_eval_neg_mic...
2,142
759
#!/usr/bin/env python3 # encoding: utf-8 """ pyQms ----- Python module for fast and accurate mass spectrometry data quantification :license: MIT, see LICENSE.txt for more details Authors: * Leufken, J. * Niehues, A. * Sarin, L.P. * Hippler, M. * Leidel, S....
1,122
391
from decimal import Decimal from typing import List, Any from common.Enums import SortingType from models import Message from .engine import db_engine, DBEngine class MessageDAO: def __init__(self, engine: DBEngine): self.engine = engine @staticmethod def __make_insert_values_from_messages_array...
5,516
1,523
#!/usr/bin/python import socket import sys junk = 'A'*500 s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) connect = s.connect(('192.168.129.128',21)) s.recv(1024) s.send('USER '+junk+'\r\n')
196
104
# Given a digit string, return all possible letter combinations that the number could represent. # A mapping of digit to letters (just like on the telephone buttons) is given below. # Input:Digit string "23" # Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. # DFS backtracking class Solution(object)...
1,746
545
#!/usr/bin/env python3 # 3/21/2021 # Updated for python3 # A Simple sysctl to telegraf plugin for freebsd's netstats ip info from freebsd_sysctl import Sysctl as sysctl import subprocess as sp import re import json import sys import pprint as pp hostname = sysctl("kern.hostname").value netstat_data = {} points_netst...
847
325
# MIT LICENSE # # Copyright 1997 - 2020 by IXIA Keysight # # 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,...
13,395
3,711
a = input("Enter the first number") b = input("Enter the second number") print('the sum is',a+b)
97
32
# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 from pytest import fixture @fixture def sut(): from servicecatalog_factory import constants return constants def test_bootstrap_stack_name(sut): # setup expected_result = "servicecatalog...
1,108
397
from django.db import models from django.utils.encoding import python_2_unicode_compatible from django.utils.http import urlquote class ConcreteModel(models.Model): name = models.CharField(max_length=10) class ProxyModel(ConcreteModel): class Meta: proxy = True @python_2_unicode_compatible class F...
1,038
323
# -*- coding: utf-8 -*- """ tests.unit.utils.test_docker ============================ Test the funcs in salt.utils.docker and salt.utils.docker.translate """ # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import copy import functools import logging import os # Import sa...
75,049
22,243
from django.http import HttpResponse from django.utils.deprecation import MiddlewareMixin class HealthCheckMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): if request.META["PATH_INFO"] == "/health-check/": return HttpRespo...
400
111
import random from contextlib import suppress from typing import Optional from discord import AllowedMentions, Embed, Forbidden from discord.ext import commands from bot.constants import Cats, Colours, NEGATIVE_REPLIES from bot.utils import helpers class Catify(commands.Cog): """Cog for the catify command.""" ...
3,317
954
import os import data_utils from pathlib import Path top_path = Path(os.path.dirname(os.path.abspath(__file__))) EBM_NLP = Path('/Users/ben/Desktop/ebm_nlp/repo/ebm_nlp_2_00/') NO_LABEL = '0' def overwrite_tags(new_tags, tags): for i, t in enumerate(new_tags): if t != NO_LABEL: tags[i] = t def get_tags(d...
1,763
764
# # # Copyright (C) 2010-2021 ARM Limited or its affiliates. All rights reserved. # # SPDX-License-Identifier: Apache-2.0 # # 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 # # www.apache.org/lice...
16,753
6,310
''' This inference script takes in images of dynamic size Runs inference in batch ** In this images have been resized but not need for this script ''' import onnx import onnxruntime as ort import numpy as np import cv2 from imagenet_classlist import get_class import os model_path = 'resnet18.onnx' model = onnx.load(...
1,275
439
# coding:utf-8 import time import MySQLdb import conf import Server # Another way to load data to MySQL: # load data infile "C://ProgramData/MySQL/MySQL Server 5.7/Uploads/track_info_url_0_part0.txt" ignore into table develop.task(mid, url); # doing: load data infile "C://ProgramData/MySQL/MySQL Server 5.7/Uploads/tr...
3,857
1,252
#!/Users/francischen/opt/anaconda3/bin/python #pythons sorts are STABLE: order is the same as original in tie. # sort: key, reverse q = ['two','twelve','One','3'] #sort q, result being a modified list. nothing is returned q.sort() print(q) q = ['two','twelve','One','3',"this has lots of t's"] q.sort(reverse=True) pr...
770
329
from bhinneka.settings import BASE_URL def get_absolute_url(path): return BASE_URL + path
96
35
import logging import random log = logging.getLogger(__name__) reserved_id = [4079, 4094] boundary_id = [0, 4095] # No need to have end=4094 as there are some inbetween vsans reserved for fport-channel-trunk def get_random_id(start=2, end=400): return random.randint(start, end)
287
114
# Use the pymed package to call the PubMed API to get lots of papers from, in this case, JEB from pymed import PubMed import pandas as pd import requests _REQUESTS_TIMEOUT = 3.0 df_jeb = pd.DataFrame(columns=['title', 'abstract']) df_jeb = df_jeb.convert_dtypes() pubmed = PubMed(tool="MyTool", email="my@email.addre...
1,403
534
from .functions1 import my_sum, factorial from .constants import pi from .print import myprint from pkg_resources import get_distribution, DistributionNotFound try: __version__ = get_distribution(__name__).version except DistributionNotFound: # package is not installed pass
287
72
# buildifier: disable=module-docstring load(":native_tools_toolchain.bzl", "access_tool") def get_cmake_data(ctx): return _access_and_expect_label_copied("@rules_foreign_cc//tools/build_defs:cmake_toolchain", ctx, "cmake") def get_ninja_data(ctx): return _access_and_expect_label_copied("@rules_foreign_cc//too...
1,259
407
# -*- coding: utf-8 -*- import sys import pytest from snake.common import Frame, Point, BoundaryCollision, SelfCollision from snake.config import GameConfig from snake.model import SnakeModel @pytest.fixture def config(): config = GameConfig() config.solid_walls = True config.initial_food_count = 0 ...
5,805
1,930
from django.urls import path from . import views urlpatterns = [ path('', views.index, name="index"), path('category/<category>/', views.CategoryListView.as_view(), name="category"), path('search/', views.image_search, name='image-search'), ]
255
76
fname = input("Enter file name: ") if len(fname) < 1 : fname = "mbox-short.txt" list = list() f = open(fname) count = 0 for line in f: line = line.rstrip() list = line.split() if list == []: continue elif list[0].lower() == 'from': count += 1 print(list[1]) print("There w...
381
139
import numpy as np import tensorflow as tf from tqdm import trange from fedsimul.utils.model_utils import batch_data from fedsimul.utils.tf_utils import graph_size from fedsimul.utils.tf_utils import process_grad class Model(object): ''' This is the tf model for the MNIST dataset with multiple class learner ...
6,358
1,869