content stringlengths 5 1.05M |
|---|
"""
Copyright (c) 2020 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in wri... |
from tests.chart_tests.helm_template_generator import render_chart
import jmespath
import pytest
from tests import supported_k8s_versions
@pytest.mark.parametrize(
"kube_version",
supported_k8s_versions,
)
class TestIngress:
def test_astro_ui_deployment(self, kube_version):
docs = render_chart(
... |
version = "1.0.0.dev"
date = "2015-January-8"
author = "Jeremy Schulman, @nwkautomaniac"
|
"""
Distributed under the terms of the BSD 3-Clause License.
The full license is in the file LICENSE, distributed with this software.
Author: Jun Zhu <[email protected]>
Copyright (C) European X-Ray Free-Electron Laser Facility GmbH.
All rights reserved.
"""
import time
from collections import deque
import numpy as np... |
from board import TicTacToeBoard
from move import BoardMove
class Game:
X = "X"
O = "O"
def __init__(self):
self._board = TicTacToeBoard()
self._player = self.X
self._running = True
self._has_winner = False
self._moves = []
@property
def running(self):
... |
#!/usr/bin/env python
from __future__ import print_function
import random
import time
from progress.bar import (Bar, ChargingBar, FillingSquaresBar, FillingCirclesBar, IncrementalBar, PixelBar, ShadyBar)
from progress.spinner import (Spinner, PieSpinner, MoonSpinner, LineSpinner, PixelSpinner)
from progress.counter ... |
import park
from park.core import Env, Space
from park.envs.multi_dim_index.params import Params as params
from park.envs.multi_dim_index.spaces import ActionSpace, DataObsSpace, QueryObsSpace
from park.envs.multi_dim_index.config import Action, DataObs, QueryObs, Query
from park.envs.multi_dim_index.gen_osm_queries im... |
from . import api
v1 = [
(r"positioning/locate", api.LocateView, "positioning-locate"),
(r"positioning/beacons", api.BeaconViewSet, "positioning-beacons"),
]
|
"""some objects and functions supporting html actions and routes"""
import pickle
import numpy as np
import pandas as pd
import matplotlib as plt
from scipy.spatial import distance
# from sqlalchemy import func, distinct
# from sqlalchemy.sql import expression #(.exists, .select, ...)
from .spotify_client import *
#... |
import logging
import os
from logging import handlers
from fastapi import Depends, FastAPI, Request
from fastapi.logger import logger
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from source.config import LOG_LO... |
from abc import ABC, abstractmethod
import numpy as np
class Cost(ABC):
'This is an abstract class for Cost functions'
def __init__(self, name="Default Cost"):
self.name = name
@abstractmethod
def calculate(self, Y, yhat):
'''Y is data, yhat is prediction'''
self.cost = No... |
#!/usr/bin/env python
from .wrapper_zakharov import Zakharov
|
import itertools
def retry(delays=(0, 1, 5, 30, 180, 600, 3600),
exception=Exception,
report=lambda *args: None):
def wrapper(function):
def wrapped(*args, **kwargs):
problems = []
for delay in itertools.chain(delays, [ None ]):
try:
... |
"""
Goals of this part of the examples:
1. Learn how to analyze the model of your energy system
2. Improve your `SimulationAPI` knowledge
3. Improve your skill-set on `TimeSeriesData`
4. Generate some measured data to later use in a calibration
"""
# Start by importing all relevant packages
import pathlib
import matplo... |
#!/usr/bin/python3
import argparse
import os
import utils
import subprocess
from multiprocessing import Pool
parser = argparse.ArgumentParser(description='compute adv transfer strategy')
parser.add_argument('--dir', help='data dir, required', type=str, default=None)
parser.add_argument('-c', '--config', help='config ... |
# coding=utf-8
# Copyright 2018 The Tensor2Tensor 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... |
"""
Functions to plot helpful information from pemfc model. Dataframes referrenced
in the plotting routine are established in post_pak_dfs, or separately loaded.
"""
import numpy as np
import cantera as ct
import matplotlib.pyplot as plt
from Shared_Funcs.read_and_write import *
from Shared_Funcs.pemfc_proper... |
import os
# inputfile = "c:\ip.txt"
# inputfile='c:\column.bmp'
# outputfile = 'c:\ip_result.txt'
# outputfile2 = 'c:\ip_result2.txt'
from transfor import *
from ReadFile import *
gFilePath = ''
def getReadStart(filename):
return 0
def getFileIndex(filename):
return 1
def convert2filename(ip... |
import math
from app.automata_learning.black_box.pac_learning.normal_teacher.timeInterval import Guard, simple_guards
from app.automata_learning.black_box.pac_learning.normal_teacher.timedWord import TimedWord, ResetTimedWord
class OTA(object):
def __init__(self, actions, states, trans, init_state, accept_states,... |
import logging
import multiprocessing
from queue import Full, Empty
from time import time
from unittest import TestCase
import ctypes
from faster_fifo import Queue
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
fmt = logging.Formatter('[%(asctime)s][%(process)05d] %(message)s')
ch.setFormatter(fmt)
log = l... |
# -*- compile-command: "../../tests/test_refine.py" -*-
# Copyright (c) 2007-2009 PediaPress GmbH
# See README.rst for additional licensing information.
from mwlib.utoken import show, token as T
from mwlib.refine import util
class parse_table_cells(object):
def __init__(self, tokens, xopts):
self.tokens ... |
from model_garden.models import Dataset
from tests import BaseTestCase
class TestDataset(BaseTestCase):
def test_str(self):
dataset = self.test_factory.create_dataset()
self.assertEqual(str(dataset),
f"Dataset(path='{dataset.path}', bucket='{dataset.bucket.name}', "
... |
'''
Created by auto_sdk on 2015.09.22
'''
from top.api.base import RestApi
class ItemImgUploadRequest(RestApi):
def __init__(self, domain='gw.api.taobao.com', port=80):
RestApi.__init__(self, domain, port)
self.id = None
self.image = None
self.is_major = None
self.num_iid =... |
from django.apps import AppConfig
class WithdrawConfig(AppConfig):
name = 'withdraw'
|
from django.db import models
from django.contrib.auth.models import User
from django.core.validators import MinValueValidator, MaxValueValidator
from django.db.models import Avg
# signals for automating token generation
from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver
fr... |
# Generated by Django 3.2.5 on 2022-03-03 11:44
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("posthog", "0215_add_tags_back"),
]
operations = [
migrations.AddField(
model_name="insight", name="derived_name", field=models.C... |
#
# This file is part of m.css.
#
# Copyright © 2017, 2018, 2019, 2020, 2021, 2022
# Vladimír Vondruš <[email protected]>
#
# 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 Softwar... |
from django.apps import AppConfig
class RandevuConfig(AppConfig):
name = 'randevu'
|
import torch
from torch.nn import functional as F
class DropoutMC:
def __init__(self, num_samples=16, p=0.2):
self.num_samples = num_samples
self.p = p
def create_samples(self, module, activation, *args, **kwargs):
res = []
for i in range(self.num_samples):
new_a... |
from pythonforandroid.recipe import CythonRecipe
class NeoscryptRecipe(CythonRecipe):
url = 'git+https://github.com/sparkspay/python-neoscrypt.git'
version = 'master'
name = 'neoscrypt'
depends = [('python3crystax')]
def get_recipe_env(self, arch):
'''
cython has problem with -l... |
# Information about explored functions
import re
import idaapi
import idautils
import idc
imported_ea = set()
demangled_names = {}
touched_functions = set()
temporary_structure = None
def init_imported_ea(*args):
def imp_cb(ea, name, ord):
imported_ea.add(ea)
# True -> Continue enumeration
... |
class ScheduledOptim():
'''A simple wrapper class for learning rate scheduling'''
def __init__(self, optimizer, init_lr, d_model, n_warmup_steps):
assert n_warmup_steps > 0, 'must be greater than 0'
self._optimizer = optimizer
self.init_lr = init_lr
self.d_model = d_model
... |
import os
import sys
import sysconfig
from setuptools import find_packages
from setuptools import setup
from setuptools.extension import Extension
def config_cython():
sys_cflags = sysconfig.get_config_var('CFLAGS')
try:
from Cython.Build import cythonize
ret = []
path = 'tpm/_cython'
... |
import argparse
import socket
from multiprocessing import Process
from rq import Connection, Queue, Worker
from redis import Redis
def run_worker(queue, name):
Worker(queue, name=name).work()
parser = argparse.ArgumentParser()
parser.add_argument('--redis_host', default='localhost')
parser.add_argument('--redis_... |
__author__ = 'obilici'
import threading
import serial
class Referee (threading.Thread):
def __init__(self, threadID, name, robotid, fieldid, player, refreeSignal):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.robotid = robotid
self.fieldid ... |
import discord
from discord.ext.commands import DefaultHelpCommand
class helpformatter(DefaultHelpCommand):
def get_ending_note(self):
return "JOKESTA TM"
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-03-16 23:56
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('jigsaw', '0006_auto_20160315_2315'),
]
operations = [
migrations.RenameField(
... |
# coding:utf-8
import codecs
'''
read and write file
'''
# read file, return dict
def readWordSet(file):
fin = codecs.open(file, "r", "utf-8")
wordSet = set()
for line in fin.readlines():
word = line.strip().lower()
wordSet.add(word)
fin.close()
return wordSet
... |
# Copyright (c) 2015-2016 Cisco Systems, Inc.
#
# 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, merge... |
from backend.corpora.common.corpora_orm import CollectionVisibility
from tests.unit.backend.corpora.api_server.base_api_test import BaseAuthAPITest
class TestPostRevision(BaseAuthAPITest):
def test__post_revision__no_auth(self):
collection_uuid = self.generate_collection(self.session, visibility=Collectio... |
import tensorflow as tf
from tensorflow.keras.datasets import cifar10
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Activation, Flatten
from tensorflow.keras.layers import Conv2D, MaxPooling2D
import... |
from ..core.email import send as send_email
from ..core.local import get_current_conf
from ..core.connection import autoccontext
from ..ut.guard import exguard
from .. import db
def get_admin_email():
with autoccontext() as conn:
return db.get_user_detail_bi_id(
conn,
get_current_c... |
# Copyright (c) 2017 Linaro Limited.
# Copyright (c) 2019 Nordic Semiconductor ASA.
#
# SPDX-License-Identifier: Apache-2.0
'''Runner for flashing with adafruit-nrfutil.'''
import os
from pathlib import Path
import shlex
import subprocess
import sys
from re import fullmatch, escape
from runners.core import ZephyrBin... |
# Copyright 2019 Vladimir Sukhoy and Alexander Stoytchev
#
# 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,... |
from django.db import models
from mptt.models import MPTTModel, TreeForeignKey
from bagels.utils.models import TimeStampedModel
from bagels.users.models import User
class Tag(TimeStampedModel, MPTTModel):
user = models.ForeignKey(User, on_delete=models.CASCADE)
name = models.CharField(max_length=50, unique=Tru... |
"""
This is a sample mean-reversion algorithm on Quantopian for you to test and adapt.
This example uses a dynamic stock selector, pipeline, to select stocks to trade.
It orders stocks from the top 1% of the previous day's dollar-volume (liquid
stocks).
Algorithm investment thesis:
Top-performing stocks from last week... |
#Rememeber to get a list with single dim use shape=(x,)
def _ndim_list(shape):
return [_ndim_list(shape[1:]) if len(shape) > 1 else None for _ in range(shape[0])]
#
#def _ndim_list(shape):
# print('shape',shape)
# print('shape len',len(shape))
# if len(shape) > 1:
# print('1')
# return [_... |
from tests.utils import W3CTestCase
class TestAbsposContainingBlock(W3CTestCase):
vars().update(W3CTestCase.find_tests(__file__, 'abspos-containing-block-'))
|
from cement import Controller, ex
from clint.textui import prompt
from esper.controllers.enums import OutputFormat
from esper.ext.db_wrapper import DBWrapper
from esper.ext.pipeline_api import get_stage_url, create_stage, edit_stage, list_stages, delete_api,\
APIException, render_single_dict
from esper.ext.utils i... |
# Generated by Django 2.0.1 on 2018-06-20 20:16
from django.db import migrations, models
import multiselectfield.db.fields
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Projects',
fields=[
... |
# -*- coding: utf-8 -*-
import dbus
import dbusmock
import bluefang
import subprocess
import pytest
adapter_name = 'hci0'
system_name = 'my-device'
address = '11:22:33:44:55:66'
alias = 'My Device'
class ClientDBusTestCase(dbusmock.DBusTestCase):
@classmethod
def setUpClass(klass):
klass.start_syst... |
#!/usr/bin/env python
# coding: utf-8
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.ticker as mticker
import pandas as pd
def plotRollingAvg(df, ax, names, title, logscale=False):
for name in names:
ax.plot(pd.to_datetime(df.loc[name].index),
df.loc[n... |
"""
A class representing an agent that could be of several types.
"""
__all__ = ['Agent']
from sepdesign._types import AgentType
import numpy as np
class Agent(object):
"""
A class representing an agent that could be of several types.
:param agent_types: A list of agent type (immutable).
... |
# -*- coding:utf-8 -*-
import urllib
import urllib.request
import re
#处理页面标签类
class Tool:
#去除img标签,7位长空格
removeImg = re.compile('<img.*?>| {7}|')
#删除超链接标签
removeAddr = re.compile('<a.*?>|</a>')
#把换行的标签换为\n
replaceLine = re.compile('<tr>|<div>|</div>|</p>')
#将表格制表<td>替换为\t
... |
#!/usr/bin/env python
# coding: utf-8
# # 1.**安装PaddleGAN**
#
# PaddleGAN的安装目前支持Clone GitHub和Gitee两种方式.
# In[ ]:
# 当前目录在: /home/aistudio/, 该目录即:左边文件和文件夹所在的目录
# 克隆最新的PaddleGAN仓库到当前目录
# !git clone https://github.com/PaddlePaddle/PaddleGAN.git
# github下载慢,从gitee clone:
get_ipython().system('git clone https://gitee.co... |
#!/usr/bin/python
"""
path_stat.py - Functions from os.path that import 'stat'.
We want to keep bin/osh_parse free of I/O. It's a pure stdin/stdout filter.
"""
import posix
import stat
def exists(path):
"""Test whether a path exists. Returns False for broken symbolic links"""
try:
posix.stat(path)
... |
""" Cisco_IOS_XR_sdr_invmgr_oper
This module contains a collection of YANG definitions
for Cisco IOS\-XR sdr\-invmgr package operational data.
This module contains definitions
for the following management objects\:
sdr\-inventory\: SDR information
Copyright (c) 2013\-2016 by Cisco Systems, Inc.
All rights reserve... |
import io
import multiprocessing as mp
import sys
import time
import pytest
from omnibus import Sender, Receiver, Message, server
from omnibus.omnibus import OmnibusCommunicator
class TestOmnibus:
@pytest.fixture(autouse=True, scope="class")
def server(self):
# start server
ctx = mp.get_cont... |
class ResultManager :
"""
1. definition
2. table
"""
def get_view_obj(self,nnid, wf_id):
"""
get view data for net config
:return:
"""
pass
def set_view_obj(self,nnid, wf_id):
"""
set net config data edited on view
:param obj:
... |
import argparse
from msgraphy import GraphApi
import msgraphy_util
def main(name):
api = GraphApi(scopes=["Sites.Read.All"])
response = api.sharepoint.list_sites(search=name)
for site in response.value:
print(site, end="\n\n")
if __name__ == "__main__":
parser = argparse.ArgumentParser(
... |
# -*- Python -*-
# Configuration file for the 'lit' test runner.
import os
import lit.formats
from lit.llvm import llvm_config
# Configuration file for the 'lit' test runner.
# name: The name of this test suite.
config.name = 'mlir-clang'
# testFormat: The test format to use to interpret tests.
config.test_format... |
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 9 12:41:43 2019
@author: abraverm
"""
import tensorflow as tf
from tensorflow.keras import layers
import matplotlib.pyplot as plt
import math as math
import numpy as np
def get_laplace_mtrx(nx,ny,d=1):
dx = d # defusion speed
dy = d
diag_block = np.eye(... |
#!/usr/bin/python
# Perceptron learning
import csv
import numpy as np
import random
X = []
Y = []
# read in feature data
with open('admission.csv') as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
for row in readCSV:
X.append(np.array([float(f) for f in row[:-1]]))
Y.append(float(row... |
from keras import models
from keras import layers
# causal conv
def __causal_gated_conv1D(x=None, filters=16, length=6, strides=1):
def causal_gated_conv1D(x, filters, length, strides):
x_in_1 = layers.Conv1D(filters=filters // 2,
kernel_size=length,
... |
'''
threaded_dl
===========
> threaded_dl links thread_count filename_format <flags>
links:
The name of a file containing links to download, one per line.
Uses pipeable to support !c clipboard, !i stdin lines of urls.
thread_count:
Integer number of threads to use for downloading.
filename_format:
A... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = '\n' + f.read()
required = [
]
vars = {}
with open... |
import sys
import time
import os
import json
import getpass
import platform
from termcolor import colored
platform = platform.system()
def cls():
if platform == 'Linux':
os.system('clear')
elif platform == 'Windows':
os.system('cls')
def read_file(file_name):
with open(file_name, 'r') as json_file:
return... |
def with_correlated_columns(self,num_rows=100,x_range=5,slope=1,noise=1):
from random import random
table = self.select().with_columns("x",[],"y",[])
for _ in range(num_rows):
seed = random()
x = seed*x_range
y = seed*x_range*slope
y = y + (-1+2*random())*noise
table ... |
import pytest
from django.test.client import Client
from django.urls import reverse
from .view_config import PARAMETRIZED_PUBLIC_VIEWS
# pylint: disable=unused-argument
@pytest.mark.django_db
@pytest.mark.parametrize("view_name,post_data", PARAMETRIZED_PUBLIC_VIEWS)
def test_public_view_status_code(load_test_data, ... |
#! /usr/bin/env python3
"""
retrain_emission.py: take an HDF5 file and segmentations, and output parameters of a mixture model.
"""
# std lib:
import argparse
import os
import sys
import random
from collections import defaultdict
from tqdm import tqdm
# numerics:
import numpy as np
import h5py
from sklearn.mixture impo... |
"""
Python provides a number of ways to perform printing. Research
how to print using the printf operator, the `format` string
method, and by using f-strings.
"""
x, y, z = 10, 2.24552, "I like turtles!"
# Using the printf operator (%), print the following feeding in the values of x,
# y, and z:
# x is 10, y is 2.25... |
# Generated by Django 2.2.1 on 2020-06-02 00:33
from django.db import migrations
import manageXML.fields
class Migration(migrations.Migration):
dependencies = [
('manageXML', '0014_auto_20200517_1001'),
]
operations = [
migrations.AlterField(
model_name='historicallexeme',
... |
"""
Developer: Rajat Shinde
Api Sources-
1. [nsetools](https://nsetools.readthedocs.io/en/latest/index.html)
2. [nsepy](https://nsepy.readthedocs.io/en/latest/)
3. [NSE India](http://www.nseindia.com/)
"""
import nsetools as nse
import streamlit as st
import nsepy
from nsepy import get_history
from datetime import dat... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright (c) 2021 Software AG, Darmstadt, Germany and/or its licensors
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 ... |
import sys
class ParseError(Exception):
pass
class MissingArgumentError(Exception):
pass
class Options(object):
def __init__(self, args):
if len(args) < 2:
raise MissingArgumentError
parts = args[0].split('/')
if len(parts) != 2:
raise ParseError
s... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from __future__ import print_function, absolute_import
import os
import re
from click_project.config import config
from click_project.decorators import command, option, argument
from click_project.lib import cd, call
@command(ignore_unknown_options=True, handle_dry_run=... |
def modfunc(f):
# lalala
f() # call back to caller
|
import sys
if sys.argv[0].endswith("__main__.py"):
sys.argv[0] = "python -m tktable"
from . import _test as main
main() |
"""Tests for sanskrit_parser
"""
|
import os
import subprocess
import numpy as np
import re
from collections import OrderedDict
from example.cbnu.utils import get_interval
data_source_classes = OrderedDict()
possible_modes = ['one-file', 'multi-file', 'one-dir', 'multi-dir', 'other']
import neo
class DataSourceBase:
gui_params = None
de... |
from django.apps import AppConfig
class SoundStoreConfig(AppConfig):
name = 'sound_store'
|
import cv2
import cvt_utils.tools as tl
# take as white-black == 0 (no BGR)
img = cv2.imread("code/sudoku.png", 0)
assert len(img.shape) == 2 # only X, Y, without BGR channels
min_th = 127
max_th = 255
# basic
get_basic_th = lambda coef: list(cv2.threshold(img, min_th, max_th, coef))[1]
basic_binary_th_img1 = tl.... |
from model.product import Product
class Item:
def __init__(self, product: Product, quantity: int):
self.__product = product
self.__quantity = quantity
def get_total_price(self):
return self.__product.get_price() * self.__quantity
|
cumulative_sum = []
list_data = 0
for i in range (1, 21):
list_data = list_data + i
cumulative_sum.append(list_data)
print (cumulative_sum)
|
"""Program to draw Mandelbrot fractals: the graphical user interface.
Author: Lars van den Haak and Tom Verhoeff
Copyright (c) 2020 - Eindhoven University of Technology, The Netherlands
This software is made available under the terms of the MIT License.
* Contributor 1: Harry Verspagen
* TU/e ID number 1: 1484575
*... |
import numpy as np
import tables
import torch
from torch.utils.data import Dataset, Subset, TensorDataset
class RadioML2018(Dataset):
def __init__(self, path, transform=None, target_transform=None):
super().__init__()
self.path = path
self.transform = transform
self.target_transfo... |
# Copyright 2018 Red Hat, 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... |
from pygnmi.client import gNMIclient
from pprint import pprint as pp
import json
host = ('10.73.1.105', '6030')
username ='arista'
password ='arista'
with gNMIclient(target=host, username=username, password=password, insecure=True) as gc:
result = gc.capabilities()
pp(result)
|
def toys(w):
"""Hackerrank Problem: https://www.hackerrank.com/challenges/priyanka-and-toys/problem
Priyanka works for an international toy company that ships by container. Her task is to the determine the lowest
cost way to combine her orders for shipping. She has a list of item weights. The shipping comp... |
# ================================================================
# MIT License
# Copyright (c) 2021 edwardyehuang (https://github.com/edwardyehuang)
# ================================================================
import tensorflow as tf
from iseg.metrics.seg_metric_wrapper import SegMetricWrapper
from iseg.metri... |
from __future__ import annotations
import inspect
from enum import Enum
from typing import Any, Optional, Tuple
class Location:
file: str
line_no: int
source_line: str
def __init__(self, file: str, line_no: int, source_line: str):
self.file = file
self.line_no = line_no
self.... |
# Generated by Django 2.0.4 on 2018-04-11 12:55
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('poem', '0006_remove_user_favorate_poem'),
]
operations = [
migrations.RenameField(
model_name='user',
old_name='favo... |
import os.path
import subprocess
def pre_build(**kwargs):
if not os.path.exists('node_modules'):
subprocess.run(['npm', 'install', '--ignore-scripts'], check=True)
subprocess.run(['npm', 'run', 'docs:docco'], check=True)
subprocess.run(['npm', 'run', 'docs:api'], check=True)
|
class corsMiddleware(object):
def process_response(self, req, resp):
resp["Access-Control-Allow-Origin"] = "*"
return resp
|
#!/usr/bin/env python
# $Id: rst2html.py 4564 2006-05-21 20:44:42Z wiemann $
# Author: David Goodger <[email protected]>
# Copyright: This module has been placed in the public domain.
"""
A minimal front end to the Docutils Publisher, producing HTML.
"""
def main():
try:
import locale
locale.s... |
# MIT License
#
# Copyright (c) 2016 David Sandberg
#
# 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, me... |
# -*- coding: utf-8 -*-
"""General utility classes and functions
Contains several classes and functions for quality of life. Used indiscriminately throughout the module.
Notes
-----
Functions should attempt to not contain stateful information, as this module will be called by other modules
throughout the prog... |
# -*- coding: utf-8 -*-
prices = {1: 4, 2: 4.5, 3: 5, 4: 2, 5: 1.5}
product, quantity = [int(x) for x in raw_input().split()]
print 'Total: R$ %.2f' % (prices[product] * quantity)
|
import mysql.connector
def create_connection ():
return mysql.connector.connect(
host = "localhost",
user = "root",
passwd = "root",
database = "facebook-explorer",
port = 8889
)
|
import os
configurations = [
"Wall",
"Werror",
"Wextra",
"Wassign-enum",
"Wblock-capture-autoreleasing",
"Wbool-conversion",
"Wcomma",
"Wconditional-uninitialized",
"Wconstant-conversion",
"Wdeprecated-declarations",
"Wdeprecated-implementations",
"Wdeprecated-objc-isa-u... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.