content stringlengths 27 928k | path stringlengths 4 230 | size int64 27 928k | nl_text stringlengths 21 396k | nl_size int64 21 396k | nl_language stringlengths 2 3 | nl_language_score float64 0.04 1 |
|---|---|---|---|---|---|---|
import os
import numpy as np
import tensorflow as tf
from utils.data_reader import H5DataLoader, H53DDataLoader
from utils.img_utils import imsave
from utils import ops
"""
This module builds a standard U-NET for semantic segmentation.
If want VAE using pixelDCL, please visit this code:
https://github.com/HongyangGao... | network.py | 12,654 | weights = tf.cast( tf.greater(self.decoded_preds, 0, name='m_iou/greater'), tf.int32, name='m_iou/weights') | 115 | en | 0.194852 |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | topi/python/topi/cuda/conv2d_hwcn.py | 5,390 | Schedule conv2d_hwcn
Schedule for conv2d_hwcn and any element-wise operations.
Parameters
----------
outs: Array of Tensor
The computation graph description of conv2d_hwcn in the format
of an array of tensors.
Returns
-------
s: Schedule
The computation schedule for conv2d_hwcn.
Traverse operators from co... | 1,295 | en | 0.830004 |
#!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import b... | tools/python/dex.py | 137,949 | Encapsulates a class within a DEX file.
Encapsulates a method within a DEX file.
Represents and DEX (Dalvik Executable) file
Parses a proguard map file and does name lookups.
Overload the [] operator to give out code units
Overload the length operator to give out the number of code units
Verify that this instruction ca... | 7,362 | en | 0.397159 |
#!/usr/bin/env python
"""Tests for `calvestbr` package."""
import unittest
from calvestbr import calvestbr
class TestCalvestbr(unittest.TestCase):
"""Tests for `calvestbr` package."""
def setUp(self):
"""Set up test fixtures, if any."""
def tearDown(self):
"""Tear down test fixtures,... | tests/test_calvestbr.py | 397 | Tests for `calvestbr` package.
Set up test fixtures, if any.
Tear down test fixtures, if any.
Test something.
Tests for `calvestbr` package.
!/usr/bin/env python | 162 | en | 0.573116 |
# Copyright 2018 Samuel Payne sam_payne@byu.edu
# 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 ... | cptac/pancan/file_download.py | 16,297 | Check that the ids in the download function's STUDY_IDS_MAP match up.
Download PDC biospecimen data for a particular study.
Download PDC clinical data for a particular study.
Download PDC quantitative data for a particular study.
Download data for the specified cancer type from the PDC.
Send a GraphQL query to the PDC ... | 3,365 | en | 0.75524 |
#!/usr/bin/env python
import os
import logging
import requests
import json
import configparser
import sys
import time
import re
from os.path import dirname
from config import (
instanceA_url, instanceA_key, instanceA_path, instanceA_profile,
instanceA_profile_id, instanceA_profile_filter, instanceA_profile_f... | index.py | 23,135 | we dont want to exit if in docker
gets details of a content item
!/usr/bin/env python if given instance A profile id then we want to filter out content without that id for each content id in instance A, check if it needs to be synced to instance B only skip alrerady synced items if we arent syncing monitoring as well ... | 1,514 | en | 0.805985 |
import logging
import os
import queue
import requests
import time
from threading import Thread
cri_sock = os.getenv("KIP_CRI_SOCK", "unix:///var/run/containerd/containerd.sock")
cri_client = os.getenv("KIP_CRI_CLI", False)
gateway_host = os.getenv("KIP_GATEWAY_HOST", "http://localhost:8888")
num_pullers = int(os.ge... | kernel_image_puller.py | 8,449 | Fetches the image names by hitting the /api/kernelspecs endpoint of the Gateway.
For process-proxy kernelspecs, the image names are contained in the config stanza - which
resides in the process-proxy stanza located in the metadata.
Fetches the set of kernelspecs from the gateway, returning a dict of configured kernel ... | 1,598 | en | 0.918109 |
import socket
import timeit
import numpy as np
from PIL import Image
from datetime import datetime
import os
import sys
from collections import OrderedDict
sys.path.append('./')
# PyTorch includes
import torch
from torch.autograd import Variable
from torchvision import transforms
import cv2
# Custom includes
from net... | exp/inference/inference_dir.py | 7,939 | Decode batch of segmentation masks.
Args:
mask: result of inference after taking argmax.
num_images: number of images to decode from the batch.
num_classes: number of classes to predict (including background).
Returns:
A batch with num_images RGB images of the same size as the input.
:param tail_list: tail_li... | 907 | en | 0.587187 |
#
# MIT License
#
# Copyright (c) 2020 Airbyte
#
# 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, pu... | airbyte-integrations/connectors/source-slack/source_slack/source.py | 14,299 | This class is a special stream which joins channels because the Slack API only returns messages from channels this bot is in.
Its responses should only be logged for debugging reasons, not read as records.
Yields a list of the beginning and ending timestamps of each day between the start date and now.
The return value ... | 3,764 | en | 0.909283 |
# -*- coding: utf-8 -*-
import argparse
import importlib
import json
import logging
import os
import re
import sys
from io import StringIO
import boto3
import tabulate
import yaml
from dask.distributed import Client
from dask_kubernetes import KubeCluster
from kubernetes.client import Configuration
from kubernetes.cli... | benchmark/btb_benchmark/kubernetes.py | 7,915 | Start a Dask Cluster using dask-kubernetes and run a function.
Talks to kubernetes to create `n` amount of new `pods` with a dask worker inside of each
forming a `dask` cluster. Then, a function specified from `config` is being imported and
run with the given arguments. The tasks created by this `function` are being r... | 995 | en | 0.657675 |
"""
Django settings for webapp2 project.
Generated by 'django-admin startproject' using Django 4.0.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.0/ref/settings/
"""
from pathlib i... | webapp2/settings.py | 3,222 | Django settings for webapp2 project.
Generated by 'django-admin startproject' using Django 4.0.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.0/ref/settings/
Build paths inside th... | 1,080 | en | 0.650195 |
#!/usr/bin/env python3
# Copyright (c) 2019-2020 The Crown Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Run fuzz test targets.
"""
from concurrent.futures import ThreadPoolExecutor, as_completed
import argpar... | test/fuzz/test_runner.py | 9,885 | Generates new corpus seeds.
Run {targets} without input, and outputs the generated corpus seeds to
{seed_dir}.
Run fuzz test targets.
!/usr/bin/env python3 Copyright (c) 2019-2020 The Crown Core developers Distributed under the MIT software license, see the accompanying file COPYING or http://www.opensource.org/licen... | 521 | en | 0.719548 |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Dict, List, Mapping, Optional, Tuple, Union
from .. import ... | sdk/python/pulumi_aws/rds/get_event_categories.py | 3,590 | A collection of values returned by getEventCategories.
A list of the event categories.
## Example Usage
List the event categories of all the RDS resources.
```python
import pulumi
import pulumi_aws as aws
example_event_categories = aws.rds.get_event_categories()
pulumi.export("example", example_event_categories.even... | 1,088 | en | 0.662826 |
# Copyright 2018, Kay Hayen, mailto:kay.hayen@gmail.com
#
# Python tests originally created or extracted from other peoples work. The
# parts were too small to be protected.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the ... | tests/basics/LateClosureAssignment.py | 2,701 | Copyright 2018, Kay Hayen, mailto:kay.hayen@gmail.com Python tests originally created or extracted from other peoples work. The parts were too small to be protected. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You m... | 951 | en | 0.922646 |
# SPDX-FileCopyrightText: Copyright (c) 2021 Martin Stephens
#
# SPDX-License-Identifier: MIT
"""These tests are run with a sensor connected to confirm that the correct
responses are received from the sensor.
The try - except clauses and an if __name__ == "__main__" allow the code to be
run with pytest on a Raspberry ... | tests/test_board_responses.py | 6,297 | These tests are run with a sensor connected to confirm that the correct
responses are received from the sensor.
The try - except clauses and an if __name__ == "__main__" allow the code to be
run with pytest on a Raspberry Pi or as a stand alone file copied into main.py
on a CircuitPython board. To run on a board also ... | 1,466 | en | 0.777551 |
import json
from banal import ensure_list
from functools import lru_cache
from pantomime.types import JSON
from requests.exceptions import TooManyRedirects
from opensanctions.core import Dataset
from opensanctions import helpers as h
FORMATS = ["%d %b %Y", "%d %B %Y", "%Y", "%b %Y", "%B %Y"]
SDN = Dataset.require("us... | opensanctions/crawlers/us_trade_csl.py | 4,618 | TODO: make adjacent owner entity TODO: deref TODO: what is this? | 64 | en | 0.671551 |
import argparse
import json
import os
import pandas as pd
import torch
import torch.optim as optim
import torch.nn as nn
import torch.utils.data
# imports the model in model.py by name
from model import BinaryClassifier
def model_fn(model_dir):
"""Load the PyTorch model from the `model_dir` directory."""
prin... | Project_Plagiarism_Detection/source_pytorch/train.py | 6,641 | Load the PyTorch model from the `model_dir` directory.
This is the training method that is called by the PyTorch training script. The parameters
passed are as follows:
model - The PyTorch model that we wish to train.
train_loader - The PyTorch DataLoader that should be used during training.
epochs - The to... | 2,040 | en | 0.832044 |
#
# Copyright (c) 2021, NVIDIA 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 ... | transformers4rec/tf/block/dlrm.py | 4,016 | Copyright (c) 2021, NVIDIA 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 writing, softw... | 828 | en | 0.809156 |
import xml.etree.ElementTree as ET
from .. import NAMESPACE
class ServerResponseError(Exception):
def __init__(self, code, summary, detail):
self.code = code
self.summary = summary
self.detail = detail
super(ServerResponseError, self).__init__(str(self))
def __str__(self):
... | tableauserverclient/server/endpoint/exceptions.py | 917 | Check elements exist before .text | 33 | en | 0.382627 |
import csv
from convertextract.parsers.csv_parser import Parser as BaseParser
class Parser(BaseParser):
"""Extract text from tab separated values files (.tsv).
"""
delimiter = '\t' | convertextract/parsers/tsv_parser.py | 195 | Extract text from tab separated values files (.tsv). | 52 | en | 0.247573 |
#!/usr/bin/env python3
from Crypto.PublicKey import RSA, ECC
import json
from hashlib import sha256
from Crypto.Cipher import AES, PKCS1_OAEP
from base64 import b64decode
from Crypto.Signature import DSS
from Crypto.Hash import SHA256
import socket
from base64 import *
from server import *
# key = R... | ctf/2020/nullcon/msg/solve.py | 3,576 | !/usr/bin/env python3 key = RSA.importKey(open("rsapubkey.pem", "r").read() ) key = ECC.generate(curve='P-256') f = open("fakekey.pem", 'w') f.write(key.export_key(format='PEM')) The server's hostname or IP address The port used by the server | 246 | en | 0.496163 |
"""
strings and logic related to composing notifications
"""
HELLO_STATUS = "Hello! I'm Vaccination Notifier"
HELLO_MESSAGE = (
"Hello there!\n"
"\n"
"I'm Vaccination Notifier. This is just a message to let you know I'm running and "
"to test our notification configuration. I'll check for changes to yo... | messages.py | 1,290 | strings and logic related to composing notifications | 52 | en | 0.860756 |
from __future__ import print_function
"""
A script to batch render and update interactive viewer.
"""
import os
import sys
import argparse
import pyexr
import numpy as np
import json
import subprocess as sp
from analyze import update_stats, compute_stats, write_data
if __name__ == '__main__':
# Parse arguments
... | tools/render.py | 3,426 | Parse arguments Create Mistuba command Run and time out after fixed amount of time Update interactive viewer | 108 | en | 0.51569 |
# PuLP : Python LP Modeler
# Version 1.4.2
# Copyright (c) 2002-2005, Jean-Sebastien Roy (js@jeannot.org)
# Modifications Copyright (c) 2007- Stuart Anthony Mitchell (s.mitchell@auckland.ac.nz)
# $Id:solvers.py 1791 2008-04-23 22:54:34Z smit023 $
# Permission is hereby granted, free of charge, to any person obtaining... | pulp/apis/gurobi_api.py | 14,405 | The Gurobi LP/MIP solver (via its python interface)
The Gurobi variables are available (after a solve) in var.solverVar
Constriaints in constraint.solverConstraint
and the Model is in prob.solverModel
The GUROBI_CMD solver
Initializes the Gurobi solver.
@param mip: if False the solver will solve a MIP as an LP
@param... | 3,020 | en | 0.787928 |
import os, sys
from base64 import decodebytes
from wptserve.utils import isomorphic_decode
import importlib
subresource = importlib.import_module("common.security-features.subresource.subresource")
def generate_payload(request, server_data):
data = (u'{"headers": %(headers)s}') % server_data
if b"id" in requ... | common/security-features/subresource/font.py | 4,367 | Simple base64 encoded .tff font | 31 | en | 0.280993 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import io
import json
import logging
import os
import warnings
from builtins import str
from typing import Any
from rasa_core import utils
from rasa_core.domain import ... | rasa_core/policies/keras_policy.py | 6,688 | Build a keras model and return a compiled model.
:param max_history_len: The maximum number of historical
turns used to decide on next action
we need to add a batch dimension with length 1 Neural Net and training params Build Model type: (DialogueTrainingData, Domain, **Any) -> None fit to on... | 373 | en | 0.782146 |
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import os
from textwrap import dedent
import pytest
from pants.backend.jvm.artifact import Artifact
from pants.backend.jvm.repository import Repository
from pants.backend.jvm.scala_artif... | tests/python/pants_test/backend/graph_info/tasks/test_list_targets.py | 5,910 | Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). Licensed under the Apache License, Version 2.0 (see LICENSE). Setup a BUILD tree for various list tests NB: Also renders a warning to stderr, which is challenging to detect here but confirmed in: tests/python/pants_test/engine/legacy/test_list_integrati... | 347 | en | 0.774199 |
from typing import Any, Dict
from .base import Presenter
from .presenter import register_presenter
@register_presenter("initial-data")
class InitialData(Presenter):
"""
Initial data for setup
"""
@property
def data(self) -> Dict[Any, Any]:
return {
"privacy_policy": "The PP",... | openslides_backend/presenter/initial_data.py | 526 | Initial data for setup | 22 | en | 0.665853 |
import sqlite3
import logging
DOOR_OPENED = 'door opened'
DOOR_CLOSED = 'door closed'
class DataStore:
def __init__(self, setup=False):
self.connection = sqlite3.connect('db/app.sqlite3.db')
self.connection.row_factory = sqlite3.Row
if setup:
self.setup()
def record_doo... | garage/datastore.py | 4,064 | print cursor.fetchone() print cursor.fetchone() | 47 | en | 0.17944 |
import torch
import torch.nn as nn
#from .utils import load_state_dict_from_url
from .utils import zerocenter
__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
'resnet152', 'resnext50_32x4d', 'resnext101_32x8d',
'wide_resnet50_2', 'wide_resnet101_2']
model_urls = {
'res... | segmentation_models_pytorch/encoders/zerocenter.py | 14,437 | 1x1 convolution
3x3 convolution with padding
ResNet-101 model from
`"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the download to stderr
ResNe... | 3,761 | en | 0.731439 |
from collections import defaultdict
import requests
from logger import logger
from perfrunner.helpers.misc import pretty_dict
from perfrunner.helpers.remote import RemoteHelper
from perfrunner.tests import PerfTest
class FIOTest(PerfTest):
TRACKER = 'fio.sc.couchbase.com'
TEMPLATE = {
'group': '{}... | perfrunner/tests/fio.py | 1,727 | Parse the test output.
See also https://github.com/axboe/fio/blob/master/HOWTO
reads writes | 94 | en | 0.769331 |
#!/usr/bin/env python3
"""
Possible string formats:
<author(s)> <title> <source> <year>
"""
import re
import pdf
CRED = '\033[91m'
CGREEN = '\33[32m'
CYELLOW = '\33[33m'
CBLUE = '\33[34m'
CVIOLET = '\33[35m'
CBEIGE = '\33[36m'
CWHITE = '\33[37m'
CEND = '\033[0m'
def extract_references_list_by_keyword(text, keyw... | parse_reference.py | 1,867 | Possible string formats:
<author(s)> <title> <source> <year>
!/usr/bin/env python3 print(ref_text) WARNING: not more than 999 references! return (autors, title, date) zextract_references_list_by_keyword('REFERENCES') | 217 | en | 0.259337 |
# Copyright 2019-2020 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" fil... | tests/integ/test_auto_ml.py | 15,469 | Copyright 2019-2020 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying thi... | 651 | en | 0.883253 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from lib.models.decode import mot_decode
from lib.models.losses import FocalLoss
from lib.models.losses import RegL1Loss, RegLoss,... | src/lib/trains/mot.py | 5,548 | :param outputs:
:param batch:
:return:
ๆๅคฑๅฝๆฐ็ๅฎไน L1 loss or smooth l1 loss box size loss ๅฏไธๅ
ๅซๅฏๅญฆไน ๅๆฐ็ๅฑ: ็จไบRe-ID็ๅ
จ่ฟๆฅๅฑ ไธๅ็track idๅ็ฑปๆๅไธๅฑFC:ๅฐ็นๅพ่ฝฌๆขๅฐๆฆ็ๅพๅ ไธๅ็track idๅ็ฑป็จไบคๅ็ตๆๅคฑ self.TriLoss = TripletLoss() ๆฃๆต็ๆๅคฑ็ผฉๆพ็ณปๆฐ track idๅ็ฑป็ๆๅคฑ็ผฉๆพ็ณปๆฐ ๅๅงๅ4ไธชlossไธบ0 ่ฎก็ฎheatmap loss ่ฎก็ฎboxๅฐบๅฏธ็L1/Smooth L1 loss ่ฎก็ฎboxไธญๅฟๅๆ ๅ็งป็L1 loss ๆฃๆต็ฎๆ idๅ็ฑป็ไบคๅ็ตๆๅคฑ ๅชๆๆ็ฎๆ ็ๅ็ด ๆ... | 606 | zh | 0.335986 |
from typing import Any, Dict, List
import pandas
from dagster import AssetKey, AssetMaterialization, EventMetadataEntry
from dagster_dbt import DbtOutput
from .snowflake_io_manager import connect_snowflake
class DbtAssetResource:
"""
This class defines a resource that is capable of producing a list of Asset... | examples/hacker_news/hacker_news/resources/dbt_asset_resource.py | 3,854 | This class defines a resource that is capable of producing a list of AssetMaterializations from
a DbtOutput. It has one public function, get_asset_materializations(), which finds all the
generated models in the dbt output and produces corresponding asset materializations.
Putting this logic in a resource makes it easi... | 1,456 | en | 0.876133 |
# ***************************************************************************************
# ***************************************************************************************
#
# Name : importcode.py
# Author : Paul Robson (paul@robsons.org.uk)
# Date : 12th March 2019.
# Purpose : Import code into buffer ... | scripts/importcode.py | 2,940 | *************************************************************************************** *************************************************************************************** Name : importcode.py Author : Paul Robson (paul@robsons.org.uk) Date : 12th March 2019. Purpose : Import code into buffer area *********... | 967 | en | 0.537077 |
# -*- coding: utf-8 -*-
import os
from O365 import Account, Connection, FileSystemTokenBackend
from datetime import datetime as dt
from datetime import timedelta
from conf.conf import CONFIG as conf
from fritzhome import FritzBox
import logging
class Core:
@staticmethod
def get_credentials():
return... | radiator_fritz_o365_sync/core.py | 5,848 | -*- coding: utf-8 -*- Cool down if no heating entries found in calendar For each heating entry in calendar heat up Cool down thermostats if they are not heated auto reset Every night refresh the token and cool down to reset manual changes on thermostats return if wildcard is found in subjects | 293 | en | 0.81157 |
from wagtailstreamforms.models import Form
def get_form_instance_from_request(request):
""" Get the form class from the request. """
form_id = request.POST.get("form_id")
if form_id and form_id.isdigit():
try:
return Form.objects.get(pk=int(form_id))
except Form.DoesNotExist:
... | wagtailstreamforms/utils/requests.py | 353 | Get the form class from the request. | 36 | en | 0.931851 |
# define BipIdb and some helper functions for easier scripting (at the end).
import ida_kernwin
import idaapi
import idc
class BipIdb(object):
"""
Class for representing the idb loaded by IDA, this has the goal to
provide access to things specific to the IDB.
Currently this conta... | bip/base/bipidb.py | 2,975 | Class for representing the idb loaded by IDA, this has the goal to
provide access to things specific to the IDB.
Currently this contain only static methods.
Return current screen address.
:return: The current address.
Calculate the absolute address from an offset of the image base.
The calcul done is ``OFFSET + IMGBA... | 1,402 | en | 0.806107 |
# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Modifications copyright (c) 2021 DocYard Authors. All Rights Reserve.
#
# 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
#
# ... | ucr/core/architecture/head/rec_srn_head.py | 11,162 | copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. Modifications copyright (c) 2021 DocYard Authors. All Rights Reserve. 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... | 1,042 | en | 0.796184 |
# coding: utf-8
"""
FINBOURNE Insights API
FINBOURNE Technology # noqa: E501
The version of the OpenAPI document: 0.0.238
Contact: info@finbourne.com
Generated by: https://openapi-generator.tech
"""
try:
from inspect import getfullargspec
except ImportError:
from inspect import getargs... | sdk/finbourne_insights/models/audit_process.py | 7,817 | NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
Returns true if both objects are equal
AuditProcess - a model defined in OpenAPI"
:param name: (required)
:type name: str
:param run_id: (required)
:type run_id: str
:param start_time: (requ... | 2,179 | en | 0.671187 |
#! /usr/bin/env python
# PuLP : Python LP Modeler
# Version 1.5.1
# Copyright (c) 2002-2005, Jean-Sebastien Roy (js@jeannot.org)
# Modifications Copyright (c) 2007- Stuart Anthony Mitchell (s.mitchell@auckland.ac.nz)
# $Id: pulp.py 1791 2008-04-23 22:54:34Z smit023 $
# Permission is hereby granted, free of charge, to... | src/pulp/pulp.py | 75,990 | ! /usr/bin/env python PuLP : Python LP Modeler Version 1.5.1 Copyright (c) 2002-2005, Jean-Sebastien Roy (js@jeannot.org) Modifications Copyright (c) 2007- Stuart Anthony Mitchell (s.mitchell@auckland.ac.nz) $Id: pulp.py 1791 2008-04-23 22:54:34Z smit023 $ Permission is hereby granted, free of charge, to any person obt... | 4,101 | en | 0.781879 |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | src/quantum/azext_quantum/vendored_sdks/azure_mgmt_quantum/models/target_description_py3.py | 1,923 | Information about a Target. A target is the component that can process a
specific type of Job.
:param id: Unique target id.
:type id: str
:param name: Display name of this target.
:type name: str
:param description: A description about this target.
:type description: str
:param accepted_data_formats: List of data form... | 974 | en | 0.598483 |
# - * - encoding : utf - 8 - * -
# pylint: disable=fixme, line-too-long
"""
Matrix factorization solver.
:copyright: 2017-2019 H2O.ai, Inc.
:license: Apache License Version 2.0 (see LICENSE for details)
"""
import numpy as np
import scipy
import scipy.sparse
def _get_sparse_matrixes(X):
'''Create csc, csr and ... | src/interface_py/h2o4gpu/solvers/factorization.py | 12,493 | Matrix Factorization on GPU with Alternating Least Square (ALS) algorithm.
Factors a sparse rating matrix X (m by n, with N_z non-zero elements)
into a m-by-f and a f-by-n matrices.
Parameters
----------
f int
decomposition size
lambda_ float
lambda regularization
max_iter int, default: 100
number of trai... | 2,938 | en | 0.681597 |
# Copyright 2021 Arie Bregman
#
# 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 agree... | cinfo/triager.py | 3,590 | Copyright 2021 Arie Bregman 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, s... | 577 | en | 0.860829 |
# coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.8.1
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import os
import sys
im... | kubernetes/test/test_apps_v1beta1_deployment_list.py | 1,035 | AppsV1beta1DeploymentList unit test stubs
Test AppsV1beta1DeploymentList
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.8.1
Generated by: https://github.com/swagger-api/swagger-codegen.git
coding: utf-8 FIXME: construct obj... | 458 | en | 0.584026 |
"""Top-level package for stringdb. Imports the api module"""
from .api import *
__author__ = """Peter C DeWeirdt"""
__email__ = 'petedeweirdt@gmail.com'
__version__ = '0.1.5'
| stringdb/__init__.py | 176 | Top-level package for stringdb. Imports the api module | 54 | en | 0.339824 |
"""
python version compatibility code
"""
import functools
import inspect
import io
import re
import sys
from contextlib import contextmanager
from inspect import Parameter
from inspect import signature
import attr
import py
import _pytest
from _pytest._io.saferepr import saferepr
from _pytest.outcomes import fail
fr... | src/_pytest/compat.py | 10,389 | helper class so that Metafunc, Function and FixtureRequest
don't need to each define the "funcargnames" compatibility attribute.
Dummy wrapper around a function object for internal use only.
Used to correctly unwrap the underlying function object
when we are creating fixtures, because we wrap the function object ourse... | 3,836 | en | 0.795628 |
from neo4j import GraphDatabase
from argparse import ArgumentParser
from concurrent.futures import ThreadPoolExecutor,as_completed,thread
import sys
import csv
from time import time
PRACTICAL = 'practical'
LOGICAL = 'logical'
NETONLY = 'netonly'
ALL = 'all'
PRIVS = 'privileged'
rans = None
def time_to_str(total_time)... | Ransomulator/ransomulator.py | 12,634 | sim_parser = subprasers.add_parser('simulate',help='simulate infection waves') parser.add_argument("-a", "--all", dest="do_all", action="store_true", help="Run through all nodes") | 179 | en | 0.122901 |
# coding: utf-8
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------... | sdk/storage/azure-storage-blob/tests/test_common_blob_async.py | 83,924 | Workaround to vcrpy bug: https://github.com/kevin1024/vcrpy/pull/461
coding: utf-8 ------------------------------------------------------------------------- Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. -----... | 6,116 | en | 0.711492 |
#!/usr/bin/env python
#
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Utility script to install APKs from the command line quickly."""
import argparse
import glob
import logging
import os
import ... | build/android/adb_install_apk.py | 5,348 | Utility script to install APKs from the command line quickly.
!/usr/bin/env python Copyright (c) 2012 The Chromium Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. TODO(jbudorick): Remove once no clients pass --apk_package | 302 | en | 0.81547 |
"""
Reinforcement learning maze example.
Red rectangle: explorer.
Black rectangles: hells [reward = -1].
Yellow bin circle: paradise [reward = +1].
All other states: ground [reward = 0].
This script is the environment part of this example. The RL is in RL_brain.py.
View more o... | contents/2_Q_Learning_maze/maze_env.py | 4,310 | Reinforcement learning maze example.
Red rectangle: explorer.
Black rectangles: hells [reward = -1].
Yellow bin circle: paradise [reward = +1].
All other states: ground [reward = 0].
This script is the environment part of this example. The RL is in RL_brain.py.
View more on my... | 587 | en | 0.700193 |
import sys
from os.path import dirname, abspath
sys.path.append(dirname(dirname(abspath(__file__))))
from SCZ_RNAseq.syn4590909.utils import *
path="../../data/SCZ_RNAseq/output/syn4590909/"
dataset="PPI"
features = np.genfromtxt("{}{}.GE_Features.txt".format(path, dataset), dtype=np.dtype(np.float32))
labels = get_c... | scripts/SCZ_RNAseq/syn4590909/rank_individual_genes.py | 2,692 | minimum accuracy improvement to consider new cluster (1%)if temporary Data vector exist, copy all lines except lastJust compute score of newly added clusteraccuracy = LDA_classification_aggregate_activity_scores(np.transpose(Data), labels)print("LDA accuracy: {}".format(accuracy))accuracy = SVM_classification_aggregate... | 421 | en | 0.693821 |
"""An filter that removes operators based on regular expressions.
"""
from argparse import Namespace
import logging
import re
import sys
from cosmic_ray.config import load_config
from cosmic_ray.work_db import WorkDB
from cosmic_ray.work_item import WorkerOutcome, WorkResult
from cosmic_ray.tools.filters.filter_app im... | src/cosmic_ray/tools/filters/operators_filter.py | 2,105 | Implemenents the operators-filter.
Mark as skipped all work item with filtered operator
Run the operators-filter with the specified command line arguments.
An filter that removes operators based on regular expressions. | 232 | en | 0.882354 |
from userinput import userinput
from ..utils import load_repository_author_name
def get_package_author_name() -> str:
"""Return the package author name to be used."""
return userinput(
name="python_package_author_name",
label="Enter the python package author name to use.",
default=load... | setup_python_package/queries/get_package_author_name.py | 455 | Return the package author name to be used. | 42 | en | 0.673607 |
#!/usr/bin/env python
# coding: utf-8
#
# This code is based on torchvison resnet
# URL: https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py
import torch.nn as nn
import torch.utils.model_zoo as model_zoo
__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
... | libs/networks/resnet_dilation.py | 7,486 | 1x1 convolution
3x3 convolution with padding
Constructs a ResNet-101 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
Constructs a ResNet-152 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
Constructs a ResNet-18 model.
Args:
pretrained (bool)... | 742 | en | 0.651947 |
import unittest
import numpy as np
from overcooked_ai_py.agents.agent import AgentPair, FixedPlanAgent, GreedyHumanModel, RandomAgent, SampleAgent
from overcooked_ai_py.mdp.actions import Direction, Action
from overcooked_ai_py.mdp.overcooked_mdp import OvercookedGridworld, OvercookedState, PlayerState, ObjectState
fr... | testing/agent_test.py | 12,188 | construct the ground truth | 26 | en | 0.907598 |
import sympy
from sympy import *
def check_weak_prime(n):
if not isprime(n):
return(False)
digits=[int(i) for i in str(n)]
# For each digit location - test all other values to see if
# the result is prime. If so - then this is not a weak prime
for position in range(len(digits)):
di... | bent/weakprime.py | 1,058 | For each digit location - test all other values to see if the result is prime. If so - then this is not a weak prime | 117 | en | 0.746553 |
# Generated by Django 2.1.9 on 2020-03-20 00:50
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cmsplugin_blocks', '0003_slideitem_title'),
]
operations = [
migrations.AlterField(
model_name='al... | cmsplugin_blocks/migrations/0004_change_image_as_filefield_.py | 1,690 | Generated by Django 2.1.9 on 2020-03-20 00:50 | 45 | en | 0.596832 |
"""
================================
Time-related feature engineering
================================
This notebook introduces different strategies to leverage time-related features
for a bike sharing demand regression task that is highly dependent on business
cycles (days, weeks, months) and yearly season cycles.
I... | examples/applications/plot_cyclical_feature_engineering.py | 30,894 | ================================
Time-related feature engineering
================================
This notebook introduces different strategies to leverage time-related features
for a bike sharing demand regression task that is highly dependent on business
cycles (days, weeks, months) and yearly season cycles.
In th... | 19,096 | en | 0.91318 |
from django.conf.urls import url
from api.views import movie_views
from api.views import auth_views
from api.views import rating_views
from api.views import recommend_views
from api.views import collabo_test
from api.views import content_based
from api.algorithms import kmeansClustering
urlpatterns = [
# user ์ ๊ทผ U... | django-vue/djangoAPI/api/urls.py | 2,547 | user ์ ๊ทผ URL ์ค๋ณต์ฒดํฌ ๊ฒ์ฌ movie ์ ๊ทผ URL ์ถ์ฒ URL ํ์ ์ ๋ณด ์ ๊ทผ URL clustering ์คํ URL Content-Based Algorithm | 93 | ko | 0.682654 |
"""HelloWorld Integration for Cortex XSOAR (aka Demisto)
This integration is a good example on you can build a Cortex XSOAR Integration
using Python 3. Please follow the documentation links below and make sure that
your integration follows the Code Conventions and passes the Linting phase.
Developer Documentation: ht... | Packs/HelloWorld/Integrations/HelloWorld/HelloWorld.py | 56,888 | Client class to interact with the service API
This Client implements API calls, and does not contain any Demisto logic.
Should only do requests and return data.
It inherits from BaseClient defined in CommonServer Python.
Most calls use _http_request() that handles proxy, SSL verification, etc.
For this HelloWorld impl... | 33,589 | en | 0.783395 |
# CMD
import torch
import torch.nn.functional as F
import cv2
def calculate_psnr(img1, img2):
"""
data range [0, 1]
"""
img1 = img1.clamp(0, 1)
img2 = img2.clamp(0, 1)
mse = torch.mean((img1 - img2) ** 2, [1, 2, 3])
# if mse == 0:
# return 100
PIXEL_MAX = 1
return 20 * to... | utils/metrics.py | 4,531 | data range [0, 1]
CMD if mse == 0: return 100 implemented with pytorch img1 = img1.to(torch.float32) img2 = img2.to(torch.float32) valid mu1 = F.conv2d(img1, window, padding = 11//2, groups = 3) same mu2 = F.conv1d(img2, window, padding = 11//2, groups = 3) mu1_sq = mu1**2 mu2_sq = mu2**2 mu1_mu2 = mu1 * mu2 si... | 536 | en | 0.331042 |
import sys
import time
import torch
import random
import argparse
import numpy as np
import torch.nn as nn
import torchvision.transforms as transforms
from torchvision import datasets
from torch.utils.data import DataLoader
# new #
import torch.cuda.amp as amp
def printParaNum(model):
'''
function: pri... | src/train_amp.py | 7,245 | function: print the number of total parameters and trainable parameters
function: Set random seed.
Args:
seed (int): Seed to be used.
deterministic (bool): Whether to set the deterministic option for
CUDNN backend, i.e., set `torch.backends.cudnn.deterministic`
to True and `torch.backends.cudnn... | 406 | en | 0.454216 |
import csnd6
# Import SPI library (for hardware SPI) and MCP3008 library.
import Adafruit_GPIO.SPI as SPI
import Adafruit_MCP3008
from random import randint, random
import time
# For Directory Searching
import glob
# Hardware SPI configuration:
SPI_PORT = 0
SPI_DEVICE = 0
class RandomLine(object):
... | Code/tests/python_tests/nebulae_live.py | 3,737 | Import SPI library (for hardware SPI) and MCP3008 library. For Directory Searching Hardware SPI configuration: Our Orchestra for our project create an instance of Csound Set option for Csound Set option for Csound Set option for Csound Compile Orchestra from String Set the Instrument to Play for 60 seconds. Change this... | 940 | en | 0.645674 |
# Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use th... | contrib/runners/winrm_runner/winrm_runner/winrm_ps_command_runner.py | 1,635 | Licensed to the StackStorm, Inc ('StackStorm') under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file ex... | 758 | en | 0.878367 |
import numpy as np
import pandas as pd
%matplotlib auto
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.ensemble import RandomForestClassifier,ExtraTreesClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import trai... | AnomalyDetection/DB.py | 1,944 | sns.relplot(x="Age",y="EstimatedSalary",data=data,hue="Purchased")sns.boxplot(x=data["Purchased"],y=data["EstimatedSalary"],whis=2,saturation=0.6)from sklearn.ensemble import IsolationForestIF=IsolationForest(n_estimators=100,bootstrap=False)IF.fit(X[:,0].reshape(-1,1))xx=np.linspace(X[:,0].min()-5,X[:,0].max()+5,len(d... | 443 | en | 0.200193 |
# Copyright 2017 The TensorFlow Authors. 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 applica... | tensorflow/contrib/batching/python/ops/batch_ops.py | 5,433 | Gradient for batch op.
Batches the computation done by the decorated function.
So, for example, in the following code
```python
@batch_function(1, 2, 3)
def layer(a):
return tf.matmul(a, a)
b = layer(w)
```
if more than one session.run call is simultaneously trying to compute `b`
the values of `w` will be gathere... | 2,577 | en | 0.81486 |
'''
####################################################################
# author wudong
# date 20190816
# ๅจ่ฟ็ปญ็puckworld็ฉบ้ดไธญๆต่ฏDDPG
# ็ถๆ็ฉบ้ดๅ่กไธบ็ฉบ้ด่ฟ็ปญ
# ็ถๆ็ฉบ้ด๏ผx๏ผy
# ่กไธบ็ฉบ้ด๏ผๆฐดๅนณๅ็ซ็ดๆนๅไธ็ๅ็ๅคงๅฐ[-1,1]
# ps ไธ็ฅ้ๆฏ่ฎก็ฎๆบ็ๅๅ ่ฟๆฏ็ฎๆณ็ๅๅ ๏ผ่ฎญ็ปไธๅจ
######################################################################
'''
import gym
from puckworld_continuo... | DDPG/test_ddpg_puckWorld.py | 877 | ####################################################################
# author wudong
# date 20190816
# ๅจ่ฟ็ปญ็puckworld็ฉบ้ดไธญๆต่ฏDDPG
# ็ถๆ็ฉบ้ดๅ่กไธบ็ฉบ้ด่ฟ็ปญ
# ็ถๆ็ฉบ้ด๏ผx๏ผy
# ่กไธบ็ฉบ้ด๏ผๆฐดๅนณๅ็ซ็ดๆนๅไธ็ๅ็ๅคงๅฐ[-1,1]
# ps ไธ็ฅ้ๆฏ่ฎก็ฎๆบ็ๅๅ ่ฟๆฏ็ฎๆณ็ๅๅ ๏ผ่ฎญ็ปไธๅจ
######################################################################
ๅปบ็ซenvๅDDPG agent ่ฎญ็ปๅนถไฟๅญๆจกๅ ๅ ่ฝฝ่ฎญ็ปๅฅฝ็ๆจกๅ๏ผ่งๅฏange... | 420 | zh | 0.31812 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
This file contains code to serve a web application to convert HTML to PDF.
This application uses a local install of the `wkhtmltopdf` binary for the conversion.
"""
import os
from subprocess import check_output
from tempfile import TemporaryDirectory
from starlette.a... | src/app.py | 1,800 | This file contains code to serve a web application to convert HTML to PDF.
This application uses a local install of the `wkhtmltopdf` binary for the conversion.
!/usr/bin/env python3 -*- coding: utf-8 -*- | 206 | en | 0.764365 |
import os
import shutil
import subprocess
import sys
from enum import Enum
from PyQt5 import QtCore
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QMainWindow, QApplication, QListWidgetItem, QFileDialog, QComboBox, QMessageBox, \
QAbstractItemView, QDialogButtonBox, QLabel, QWidget, QPushButton, QListWi... | mbreplacer.py | 26,863 | Get the mbreplacer dir
:return str: mbreplacer root dir
type: QComboBox type: QDialogButtonBox type: QLabel type: QWidget type: QPushButton type: QPushButton type: QListWidget type: QLabel type: QListWidget type: QLabel type: QPushButton type: QPushButton type: QPushButton type: QProgressBar type: QFrame type: QPushB... | 780 | en | 0.585662 |
"""
This is the runner of the entire eva.jvc system.
Version 1,
the steps for the entire pipeline are as follows:
1. preprocessor -- get rep indices, save children metadata
2. encoder -- encode video by forcing i-frames (also modify the i-frame skip rate)
3. decoder -- using metadata, select the i-frames you want to ... | eva_storage/jvc/jvc_runner_v2.py | 2,044 | This is the runner of the entire eva.jvc system.
Version 1,
the steps for the entire pipeline are as follows:
1. preprocessor -- get rep indices, save children metadata
2. encoder -- encode video by forcing i-frames (also modify the i-frame skip rate)
3. decoder -- using metadata, select the i-frames you want to decod... | 654 | en | 0.825554 |
# Copyright 2013-2021 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)
import os
from spack import *
class SspaceLongread(Package):
"""SSPACE-LongRead is a stand-alone program for scaffo... | var/spack/repos/builtin/packages/sspace-longread/package.py | 1,223 | SSPACE-LongRead is a stand-alone program for scaffolding pre-assembled
contigs using long reads
Note: A manual download is required for SSPACE-LongRead.
Spack will search your current directory for the download file.
Alternatively, add this file to a mirror so that Spack can find it.
For instructions on how to set up ... | 575 | en | 0.801468 |
# -*- coding: utf-8 -*-
# Resource object code
#
# Created: Mon Oct 15 12:53:43 2018
# by: The Resource Compiler for PySide (Qt v4.8.7)
#
# WARNING! All changes made in this file will be lost!
from PySide import QtCore
qt_resource_data = b"\x00\x006x\x89PNG\x0d\x0a\x1a\x0a\x00\x00\x00\x0dIHDR\x00\x00\x02|\x00\x... | mapclientplugins/parametricfittingstep/resources_rc.py | 141,061 | -*- coding: utf-8 -*- Resource object code Created: Mon Oct 15 12:53:43 2018 by: The Resource Compiler for PySide (Qt v4.8.7) WARNING! All changes made in this file will be lost! | 183 | en | 0.751992 |
import unittest,os
from src.tasks.scrape_reddit.tiktok import dwn_tiktok
from src.tasks.generate_video.task import generate_tiktok
from src.tasks.upload_video.task import upload_video
class TestTiktok(unittest.TestCase):
def setUp(self):
pass
def test_tiktok(self):
context = {
'... | test/test_tiktok.py | 971 | dwn_tiktok(context)generate_tiktok(context) | 43 | eo | 0.242598 |
import os
import pathlib
from flask import Flask
from flask import request
from flask import redirect
from flask import url_for
from flask import session
from flask import render_template
from flask.json import jsonify
from td.app.auth import FlaskTDAuth
from configparser import ConfigParser
# Define the templates f... | td/oauth.py | 3,946 | Step 3: Retrieving an access token.
The user has been redirected back from the provider to your registered
callback URL. With this redirection comes an authorization code included
in the redirect URL. We will use that to obtain an access token.
Step 1: User Authorization.
Redirect the user/resource owner to the OAuth... | 1,084 | en | 0.746309 |
# Copyright 2015 Ciara Kamahele-Sanfratello
#
# 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... | simulator/Planners/Planner.py | 808 | Copyright 2015 Ciara Kamahele-Sanfratello 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, so... | 648 | en | 0.862503 |
"""Tests for queues.py"""
import sys
import unittest
from unittest import mock
import asyncio
from .. import utils as test_utils
class _QueueTestBase(test_utils.TestCase):
def setUp(self):
super().setUp()
self.loop = self.new_test_loop()
class QueueBasicTests(_QueueTestBase):
def _test_rep... | tests/python/test_queues.py | 18,385 | Test Queue's repr or str.
fn is repr or str. expect_id is True if we expect the Queue's id to
appear in fn(Queue()).
Tests for queues.py
Start a task that waits to get. Let it start waiting. resume q.get coroutine to finish generator Start a task that waits to put. Let it start waiting. resume q.put coroutine to fin... | 922 | en | 0.909458 |
from flask import jsonify, request
from flask_restx import Resource, reqparse, fields, marshal_with
import requests
import redis
import os
import logging
import time
import datetime
import json
from app import api, db
from models import User
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
user_fi... | users-api/routes.py | 6,346 | Here we create the task and put it on the job queue.
TODO: some authorization would be nice we should really return 404 here and don't do POST magic in a GET request but this will make some thing much easier... Some optimization: we make a request to the Location API to get all the geohash prefixes for all locations... | 848 | en | 0.905476 |
import time, calendar
from datetime import datetime
#
# Decodes UNIX timestamp (UTC secs since epoch) to python datetime and vice versa.
#
class Time(datetime):
def __new__(cls, *x):
return datetime.__new__(cls, *x)
@staticmethod
def decode(json):
assert isinstance(json, int)
retur... | raritan/rpc/Time.py | 525 | Decodes UNIX timestamp (UTC secs since epoch) to python datetime and vice versa. | 80 | en | 0.647313 |
"""Module with git related utilities."""
import git
class GitRepoVersionInfo:
"""
Provides application versions information based on the tags and commits in the repo
"""
def __init__(self, path: str):
"""
Create an instance of GitRepoVersionInfo
:param path: The path to search... | step_exec_lib/utils/git.py | 1,985 | Provides application versions information based on the tags and commits in the repo
Create an instance of GitRepoVersionInfo
:param path: The path to search for git information. It searches for '.git' in this folder or any parent
folder.
Gets application version in the format [last-tag]-[last-commit-sha].
:param strip_... | 714 | en | 0.757372 |
# A very very minimal BeautifulSoup immitation.
#
# BS uses SGMLlib to parse, which converts everything to lower case.
# This uses real xml parsing to mimic the parts of BS we use.
import xml.dom.minidom
def _getText(node):
nodelist = node.childNodes
rc = []
for node in nodelist:
if node.nodeType ... | Sketches/RJL/bittorrent/BitTorrent/BitTorrent/BeautifulSupe.py | 3,419 | A very very minimal BeautifulSoup immitation. BS uses SGMLlib to parse, which converts everything to lower case. This uses real xml parsing to mimic the parts of BS we use.please don't give us your null terminators | 214 | en | 0.901699 |
from pdb import set_trace as TT
import numpy as np
import scipy
from scipy.spatial import ConvexHull
import skimage
from skimage.morphology import disk
import skbio
global trg_image
trg_image = None
def diversity_calc(config):
div_calc_name = config.FITNESS_METRIC
return get_div_calc(div_calc_name)
def get_div... | evolution/diversity.py | 17,145 | Calculate the diversity of a population of agents in skill-space by computing the volume inside the convex hull of
the agents when treated as points in this space.
Use L2 distance to punish agents for having high mean pairwise distance. Optimal state is all agents at the same
point in skill-space, with maximal lifespan... | 3,412 | en | 0.812153 |
"""
The file contains the PPO class to train with.
NOTE: All "ALG STEP"s are following the numbers from the original PPO pseudocode.
It can be found here: https://spinningup.openai.com/en/latest/_images/math/e62a8971472597f4b014c2da064f636ffe365ba3.svg
"""
import gym
import numpy as np
import torch
i... | ppoPolicyTraining.py | 21,384 | This is the PPO class we will use as our model in main.py
Initializes the PPO model, including hyperparameters.
Parameters:
policy_class - the policy class to use for our actor/critic networks.
env - the environment to train on.
hyperparameters - all extra arguments passed into PPO that should ... | 10,592 | en | 0.825914 |
import os
from typing import Union, Tuple
from torchtext._internal.module_utils import is_module_available
from torchtext.data.datasets_utils import (
_wrap_split_argument,
_create_dataset_directory,
)
if is_module_available("torchdata"):
from torchdata.datapipes.iter import FileOpener, GDriveReader, Iter... | torchtext/datasets/amazonreviewpolarity.py | 2,621 | AmazonReviewPolarity Dataset
For additional details refer to https://arxiv.org/abs/1509.01626
Number of lines per split:
- train: 3600000
- test: 400000
Args:
root: Directory where the datasets are saved. Default: os.path.expanduser('~/.torchtext/cache')
split: split or splits to be returned. Can be ... | 554 | en | 0.7235 |
# -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup ------------------------------------------------------------... | smacha_ros/doc/conf.py | 6,981 | -*- coding: utf-8 -*- Configuration file for the Sphinx documentation builder. This file does only contain a selection of the most common options. For a full list see the documentation: http://www.sphinx-doc.org/en/master/config -- Path setup -------------------------------------------------------------- If extensions ... | 4,846 | en | 0.541851 |
# qubit number=4
# total number=32
import cirq
import qiskit
from qiskit.providers.aer import QasmSimulator
from qiskit.test.mock import FakeVigo
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import BasicAer, execute, transpile
from pprint import pprint
from qiskit.test.mock import ... | benchmark/startQiskit_noisy1996.py | 3,963 | qubit number=4 total number=32 implement the oracle O_f NOTE: use multi_control_toffoli_gate ('noancilla' mode) https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-... | 752 | en | 0.393626 |
# Copyright (c) 2016, NVIDIA CORPORATION. All rights reserved.
from __future__ import absolute_import
from .data import DataIngestion
__all__ = ['DataIngestion']
| plugins/data/bAbI/digitsDataPluginBAbI/__init__.py | 165 | Copyright (c) 2016, NVIDIA CORPORATION. All rights reserved. | 61 | en | 0.883921 |
"""
Methods for assessing treatment of finite-precision issues
"""
import os
import sys
import time
import multiprocessing as mp
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.markers as mrk
import plotter as ptr
import rnn_fxpts as rfx
import fxpt_experiments as fe
import... | roundoff.py | 19,928 | Runs baseline_re_single_analysis on all networks in test_data_id of size N.
cap is as in baseline_re_single_analysis.
returns numpy.array percents, where
percents[i] is as in baseline_re_single_analysis for the i^{th} sample network.
Analyze edge cases of relative errors on a single network
Uses the samp^{th} sample ... | 4,300 | en | 0.806865 |
import pytest
from selenium import webdriver
from model.application import Application
def pytest_addoption(parser):
parser.addoption("--browser", action="store", default="firefox", help="browser type")
parser.addoption("--base_url", action="store", default="http://localhost:9080/php4dvd/", help="base URL")
... | php4dvd/conftest.py | 947 | driver.implicitly_wait(30)close brawser | 39 | en | 0.314578 |
# name : Shoby Gnanasekaran
# net id: shoby
from dungeonchar import DungeonCharacter
from healable import Healable
from hero import Hero
class Priestess(Hero, Healable):
""" Priestess is a hero with it own statistics. The basic behaviour is same as the hero.
Special ability is to heal everytime after taking ... | priestess.py | 888 | Priestess is a hero with it own statistics. The basic behaviour is same as the hero.
Special ability is to heal everytime after taking damage
after taking damage, if the priestess is not dead, it heals itself
name : Shoby Gnanasekaran net id: shoby | 252 | en | 0.926904 |
from django.contrib import admin
from claims import models
# Register your models here.
admin.site.register(models.AddressCountry)
admin.site.register(models.AddressRegion)
admin.site.register(models.AddressCity)
admin.site.register(models.ProjectStatus)
| claims/admin.py | 256 | Register your models here. | 26 | en | 0.957485 |
#!/usr/bin/env python
# Copyright (c) 2021 IBM Corporation
#
# 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, mod... | mf_localization_mapping/script/check_topic_size.py | 1,741 | !/usr/bin/env python Copyright (c) 2021 IBM Corporation 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, pu... | 1,077 | en | 0.869003 |
#!/usr/bin/env python3
# Copyright (c) 2017-2020 The Ludirium Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test wallet load on startup.
Verify that a ludiriumd node can maintain list of wallets loading on sta... | test/functional/wallet_startup.py | 2,543 | Test wallet load on startup.
Verify that a ludiriumd node can maintain list of wallets loading on startup
!/usr/bin/env python3 Copyright (c) 2017-2020 The Ludirium Core developers Distributed under the MIT software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. | 315 | en | 0.545345 |
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import numpy as np
from openvino.tools.mo.front.common.partial_infer.utils import mo_array
from openvino.tools.mo.front.extractor import FrontExtractorOp
from openvino.tools.mo.front.kaldi.loader.utils import read_binary_bool_token, rea... | tools/mo/openvino/tools/mo/front/kaldi/extractors/tdnncomponent_ext.py | 2,436 | Copyright (C) 2018-2022 Intel Corporation SPDX-License-Identifier: Apache-2.0 used only on training used only on training for training, usually (4, 4) according to Kaldi documentation http://kaldi-asr.org/doc/classkaldi_1_1nnet3_1_1TdnnComponent.htmldetails it looks like it's used only during training (but not 100% sur... | 322 | en | 0.763044 |
from fastcore.foundation import L
# 0~11 ์ซ์๋ฅผ ํฌํจํ L์ ์์ฑํฉ๋๋ค (range ์ฌ์ฉ)
t = ____________
print(t)
# L์ ๋ด์ฉ์ ๋ ๋ฐฐ ๋ถ๋ฆฝ๋๋ค
t __ 2
print(t)
# 0์ด ๋ด๊ธด ์์น (0, 12) ๋ฅผ ํํ ๋ฐฉ์์ผ๋ก ์ฐพ์์ ๋ฐํํฉ๋๋ค
t_1 = t[_, __]
print(t_1)
# 0์ด ๋ด๊ธด ์์น (0, 12) ๋ฅผ ๋ง์คํน ๋ฐฉ์์ผ๋ก ์ฐพ์์ ๋ฐํํฉ๋๋ค
# - ๋ง์คํฌ๋ฅผ ๋ง๋ญ๋๋ค 0๊ณผ 12๋ฒ์งธ ์์น์๋ง True๋ฅผ ๋ฃ์ต๋๋ค
mask = L([True])
mask += L([False] * 11)
ma... | exercises/chapter01/exc_01_07.py | 555 | 0~11 ์ซ์๋ฅผ ํฌํจํ L์ ์์ฑํฉ๋๋ค (range ์ฌ์ฉ) L์ ๋ด์ฉ์ ๋ ๋ฐฐ ๋ถ๋ฆฝ๋๋ค 0์ด ๋ด๊ธด ์์น (0, 12) ๋ฅผ ํํ ๋ฐฉ์์ผ๋ก ์ฐพ์์ ๋ฐํํฉ๋๋ค 0์ด ๋ด๊ธด ์์น (0, 12) ๋ฅผ ๋ง์คํน ๋ฐฉ์์ผ๋ก ์ฐพ์์ ๋ฐํํฉ๋๋ค - ๋ง์คํฌ๋ฅผ ๋ง๋ญ๋๋ค 0๊ณผ 12๋ฒ์งธ ์์น์๋ง True๋ฅผ ๋ฃ์ต๋๋ค | 160 | ko | 1.000045 |
'''
Advent of Code - 2019
--- Day 2: 1202 Program Alarm ---
'''
from utils import *
from intcode import IntcodeRunner, HaltExecution
def parse_input(day):
return day_input(day, integers)[0]
def part1(program, noun=12, verb=2):
runner = IntcodeRunner(program)
runner.set_mem(1, noun)
runner.set_... | challenges/2019/python/d02.py | 1,091 | Advent of Code - 2019
--- Day 2: 1202 Program Alarm --- | 60 | en | 0.777143 |
"""Workout schema module"""
import graphene
from exercises.schema import ExerciseType
from exercises.models import Exercise
class Query(graphene.ObjectType):
"""Workout query class"""
workout = graphene.List(ExerciseType,
body_part=graphene.String(),
exe... | quarantineworkout/workout/schema.py | 1,325 | Workout query class
query resolver for workout property
Workout schema module | 77 | en | 0.623682 |
# Copyright 2015 The TensorFlow Authors. 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 applica... | tensorflow/python/kernel_tests/variable_ops_test.py | 10,072 | Tests for tensorflow.ops.tf.variable_op.
Copyright 2015 The TensorFlow Authors. 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 U... | 1,183 | en | 0.857427 |
import pylab as pl
from get_fish_info import get_fish_info
from fit_integrator_model import get_model_result, get_target_result
import numpy as np
from pathlib import Path
import gmm_model_fit
import pandas as pd
from pymoo.factory import get_problem, get_visualization, get_decomposition
# import random
#
# for dt in ... | armin_analysis/model_tests.py | 22,793 | import random for dt in [0.001, 0.002, 0.005, 0.01, 0.1]: tau = 4 Is = np.arange(0, 30, dt) xs = np.empty_like(Is) xs[0] for i in range(1, len(Is)): dx = random.gauss(0.2, 5) - xs[i - 1] xs[i] = xs[i - 1] + dx * dt / tau pl.plot(Is, xs) pl.show() sdfroot_path = Path("/Users/armin... | 17,476 | en | 0.284999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.