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 pygame
from game.game import Game
def initialization():
"""Инициализация нужных файлов игры"""
pygame.init()
pygame.display.set_icon(pygame.image.load("data/icon.bmp"))
pygame.display.set_caption('SPACE')
if __name__ == "__main__":
initialization()
game = Game()
game.run()
py... | main.py | 361 | Инициализация нужных файлов игры | 32 | ru | 0.999181 |
# External Dependencies
from __future__ import division
from numpy import isclose
from svgpathtools import Path
# Internal Dependencies
from misc4rings import isNear
class ClosedRingsOverlapError(Exception):
def __init__(self,mes):
self.mes = mes
def __str__(self):
return repr(self.mes)
def ... | noIntersections4rings.py | 8,157 | External Dependencies Internal Dependencies Often the overlapping part of two paths is so small that when removed, pathXpathIntersections, will still consider the two curves as intersecting. This function is to find the smallest (signed) Tstep such that isNear(path(T),path(T+Tstep))==False. note: stepInPositiveDirecti... | 1,615 | en | 0.8675 |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... | src/command_modules/azure-cli-monitor/azure/cli/command_modules/monitor/validators.py | 6,645 | Extracts a single tag in key[=value] format
Extracts multiple space-separated tags in key[=value] format
-------------------------------------------------------------------------------------------- Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the proje... | 554 | en | 0.557131 |
import numbers
import warnings
import torch
from ignite.contrib.handlers.base_logger import BaseLogger, BaseOptimizerParamsHandler, BaseOutputHandler, \
BaseWeightsScalarHandler, BaseWeightsHistHandler
__all__ = ['TensorboardLogger', 'OptimizerParamsHandler', 'OutputHandler',
'WeightsScalarHandler', 'W... | helper/custom_ignite_handlers/tensorboard_logger.py | 19,069 | Helper handler to log model's gradients as histograms.
Examples:
.. code-block:: python
from ignite.contrib.handlers.tensorboard_logger import *
# Create a logger
tb_logger = TensorboardLogger(log_dir="experiments/tb_logs")
# Attach the logger to the trainer to log model's weigh... | 10,630 | en | 0.628539 |
# Copyright 2013 The Emscripten Authors. All rights reserved.
# Emscripten is available under two separate licenses, the MIT license and the
# University of Illinois/NCSA Open Source License. Both these licenses can be
# found in the LICENSE file.
from __future__ import print_function
import glob
import hashlib
impo... | tests/test_core.py | 313,518 | Copyright 2013 The Emscripten Authors. All rights reserved. Emscripten is available under two separate licenses, the MIT license and the University of Illinois/NCSA Open Source License. Both these licenses can be found in the LICENSE file. decorators for limiting which modes a test can run in without EMTEST_ALL_ENGIN... | 28,778 | en | 0.873127 |
"""
License:
This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
If a copy of the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/.
"""
from collections.abc import MutableMapping
import posixpath
import boto3
import botocore
from botocore.exce... | hub/store/s3_storage.py | 3,735 | License:
This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
If a copy of the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/.
FIXME for some reason this is wasabi case here, probably url is something like wasabi://s3://... | 301 | en | 0.924941 |
"""
Implementation of the `CID spec <https://github.com/multiformats/cid>`_.
This module differs from other modules of :mod:`~multiformats`, in that the functionality is completely
encapsulated by a single class :class:`CID`, which is imported from top level instead
of the module itself:
>>> from ... | multiformats/cid/__init__.py | 28,154 | Container class for `Content IDentifiers <https://github.com/multiformats/cid>`_.
CIDs can be explicitly instantiated by passing multibase, CID version, multicodec and multihash digest to the constructor:
>>> cid = CID("base58btc", 1, "raw",
... "12206e6ff7950a36187a801613426e858dce686cd7d7e3c0fc42ee0330072d245c95")
... | 14,288 | en | 0.435841 |
import argparse
import torch
import os
import numpy as np
import random as rd
from models import GCN
from utils import get_folder_path
from base_solver import BaseSolver
MODEL = 'GCN'
parser = argparse.ArgumentParser()
# Dataset params
parser.add_argument("--dataset", type=str, default='Movielens', help="")
parser.... | benchmark/recsys/gcn_solver.py | 5,204 | Unliked popular movie negative sampling:
:param u_nid:
:param train_pos_unid_inid_map:
:param test_pos_unid_inid_map:
:param neg_unid_inid_map:
:param data:
:return:
Dataset params Model params Train params Setup data and weights file path Setup device Setup args | 265 | en | 0.487988 |
"""add x,y to markers
Revision ID: 20f14f4f1de7
Revises: 21b54c24a2c8
Create Date: 2018-10-01 23:27:21.307860
"""
# revision identifiers, used by Alembic.
revision = '20f14f4f1de7'
down_revision = '21b54c24a2c8'
branch_labels = None
depends_on = None
import sqlalchemy as sa
from alembic import op
def upgrade():
... | alembic/versions/20f14f4f1de7_add_x_y_to_markers.py | 747 | add x,y to markers
Revision ID: 20f14f4f1de7
Revises: 21b54c24a2c8
Create Date: 2018-10-01 23:27:21.307860
revision identifiers, used by Alembic. commands auto generated by Alembic - please adjust! end Alembic commands commands auto generated by Alembic - please adjust! end Alembic commands | 297 | en | 0.626255 |
def mergeSort(_list):
n = len(_list)
if n > 1:
mid = n // 2 # int
left = _list[:mid]
right = _list[mid:]
mergeSort(left)
mergeSort(right)
i = j = k = 0
# 左右比較
while i < len(left) and j < len(right):
if left[i] < right[j]: # left ri... | sorting/0853426_HW1_merge.py | 735 | int 左右比較 left right compared 看有沒有剩,直接塞滿 | 39 | zh | 0.680809 |
#
# This file is part of SEQGIBBS
# (https://github.com/I-Bouros/seqgibbs.git) which is released
# under the MIT license. See accompanying LICENSE for copyright
# notice and full license details.
#
import unittest
import scipy.stats
import numpy as np
import numpy.testing as npt
import seqgibbs as gibbs
def fun(x)... | seqgibbs/tests/test_samplers.py | 6,196 | Test the 'RandGibbsAlgo' class.
Test the 'SysGibbsAlgo' class.
Function returning the parameters of the normal sampler.
mean = sum of elements of x
variance = exp(|x|)/(1+exp(|x|)).
Function returning the parameters of the normal sampler.
mean = product of elements of x
variance = exp(|x|)/(1+exp(|x|)).... | 884 | en | 0.778963 |
"""Implementation of group based authorization API.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import grp
import logging
_LOGGER = logging.getLogger(__name__)
def _group(template, resource, action, proid):... | lib/python/treadmill/api/authz/group.py | 2,387 | Group based authorization REST api.
Render group template.
Authorize user/action/resource
Implementation of group based authorization API.
TODO: add schema validation. | 169 | en | 0.5706 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
#
# Copyright 2012-2018 EMBL - European Bioinformatics Institute
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the Li... | python/emboss_pepwindow.py | 21,872 | !/usr/bin/env python -*- coding: utf-8 -*- Copyright 2012-2018 EMBL - European Bioinformatics Institute 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 ... | 2,616 | en | 0.676914 |
# ccm node
from __future__ import absolute_import, with_statement
import os
import re
import shutil
import signal
import stat
import subprocess
import time
import yaml
from six import iteritems, print_
from ccmlib import common, extension
from ccmlib.node import Node, NodeError, ToolError
class DseNode(Node):
... | ccmlib/dse_node.py | 20,390 | Provides interactions to a DSE node.
Due to the way CCM lays out files, separating the repository
from the node(s) confs, the `dse-env.sh` script of each node
needs to have its DSE_HOME var set and exported. Since DSE
4.5.x, the stock `dse-env.sh` file includes a commented-out
place to do exactly this, intended for ins... | 1,114 | en | 0.866257 |
#!/usr/bin/env python
import os
import cv2
import numpy as np
from enum import Enum
import math
class Calc (Enum):
OPENCV = 1
GSL_MULTI_ROOT = 2
GSL_MULTI_FIT = 3
image_file_name = "Man2_10deg.png"
use_calc = Calc.GSL_MULTI_FIT
#use_calc = Calc.GSL_MULTI_ROOT
#use_calc = Calc.OPENCV
def get_project_xy(... | opencv/src/face_motion1.py | 7,963 | !/usr/bin/env pythonuse_calc = Calc.GSL_MULTI_ROOTuse_calc = Calc.OPENCV print("%f * %f + %f * %f + %f * %f + %f = %f\n" % (r31, X, r32, Y, r33, Z, t3, s)) print("%f/%f" % ((fx*r11 + cx*r31)*X + (fx*r12 + cx*r32)*Y + (fx*r13 + cx*r33)*Z + fx*t1 + cx*t3, s)) print("%f/%f" % ((fy*r21 + cy*r31)*X + (fy*r22 + cy*r... | 1,003 | en | 0.271966 |
"""
Get attributes about images
Inspired by https://github.com/CSAILVision/places365/blob/master/run_placesCNN_unified.py
"""
from pathlib import Path
import argparse
from typing import List, Iterator, Tuple, Optional, Union, Dict
import hashlib
import json
from multiprocessing import Pool
import urllib.request
import ... | scripts/detect_room.py | 13,053 | Undoes the normalization and returns the reconstructed images in the input domain.
Special json encoder for numpy types
prepare all the labels
Compute softmax values for each sets of scores in x.
Get attributes about images
Inspired by https://github.com/CSAILVision/places365/blob/master/run_placesCNN_unified.py
hac... | 1,181 | en | 0.684663 |
'''
Задача 1
Вывести на экран циклом пять строк из нулей, причем каждая строка должна быть пронумерована.
'''
# for i in range(1, 6):
# print(f'{i} --', '0'*i)
#######
# print('num 1')
# i = 0
# while i < 5:
# i += 1
# print('line', i, 'is 0')
#
# print('')
#######
'''
Задача 2
Пользователь в цикле ввод... | example-l2.py | 4,165 | Задача 1
Вывести на экран циклом пять строк из нулей, причем каждая строка должна быть пронумерована.
for i in range(1, 6): print(f'{i} --', '0'*i) print('num 1') i = 0 while i < 5: i += 1 print('line', i, 'is 0') print('') amount = 0 for i in range(10): n = input() if '5' in n: amount +=... | 2,451 | en | 0.313657 |
'''Faça um programa que leia uma frase pelo teclado e mostre quantas vezes aparece a letra “A”,
em que posição ela aparece a primeira vez e em que posição ela aparece a última vez.'''
frase=str(input('Digite uma frase: ')).upper().strip()
print('a letra A aparece {} vezes'.format(frase.count('A')))
print('ela aparece ... | ex26.py | 470 | Faça um programa que leia uma frase pelo teclado e mostre quantas vezes aparece a letra “A”,
em que posição ela aparece a primeira vez e em que posição ela aparece a última vez. | 178 | pt | 0.998701 |
from django.shortcuts import render, redirect
from django.core.urlresolvers import reverse
from .forms import EventCreateForm, NoteCreateForm, PropertyCreateForm, FileUploadForm,AlertCreateForm
from models import Event, Property, Note, File, Alert
from wsgiref.util import FileWrapper
from django.http import HttpRespons... | apps/main/views.py | 6,702 | Create your views here. | 23 | en | 0.928092 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2017 F5 Networks Inc.
# GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
... | f5-ansible/library/modules/bigip_monitor_http.py | 18,453 | !/usr/bin/python -*- coding: utf-8 -*- Copyright (c) 2017 F5 Networks Inc. GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) Per BZ617284, the BIG-IP UI does not raise a warning about this. So I do | 237 | en | 0.679923 |
import argparse
import os
from solver import Solver
from data_loader import *
#from data_loader import *
from torch.backends import cudnn
from torch.utils import data
from torchvision import transforms as T
def main(config):
cudnn.benchmark = True
if not os.path.exists(config.model_path):
os.makedirs(... | main.py | 4,135 | from data_loader import * momentum1 in Adam momentum2 in Adam 若test_mode==1,则test时会计算评估指标。若==2,则不计算评估指标。 | 107 | zh | 0.357554 |
import os
import shutil
from thlib.side.Qt import QtWidgets as QtGui
from thlib.side.Qt import QtGui as Qt4Gui
from thlib.side.Qt import QtCore
from thlib.environment import env_inst, env_tactic, cfg_controls, env_read_config, env_write_config, dl
import thlib.global_functions as gf
import thlib.tactic_classes as tc
fr... | thlib/ui_classes/ui_watch_folder_classes.py | 28,918 | Error handler for ``shutil.rmtree``.
If the error is due to an access error (read only file)
it attempts to add write permission and then retries.
If the error is for another reason it re-raises the error.
Usage : ``shutil.rmtree(path, onerror=onerror)``
TODO Make this work enable_watch.triggered.connect(self.open... | 1,081 | en | 0.780217 |
# !/usr/bin/env python
# coding: utf-8
'''
Description:
Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
1
/ \
2 3
\
5
All root-to-leaf paths are: ["1->2->5", "1->3"]
Tags: Tree, Depth-first Search
'''
... | python/Tree/257_binary_tree_paths.py | 1,254 | Description:
Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
1
/ 2 3
5
All root-to-leaf paths are: ["1->2->5", "1->3"]
Tags: Tree, Depth-first Search
!/usr/bin/env python coding: utf-8 Definition for a... | 495 | en | 0.623565 |
# Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: anze@reciprocitylabs.com
# Maintained By: anze@reciprocitylabs.com
"""Add finished/verified dates to cycle tasks
Revision ID: 13e52f6a9deb
Revises... | src/ggrc_workflows/migrations/versions/20160104135243_13e52f6a9deb_add_finished_verified_dates_to_cycle_.py | 1,247 | Add finished/verified dates to cycle tasks
Revision ID: 13e52f6a9deb
Revises: 18bdb0671010
Create Date: 2016-01-04 13:52:43.017848
Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file> Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> Created By: anze@reciprocitylabs... | 403 | en | 0.678294 |
# Time: O(n^2)
# Space: O(1)
class Solution(object):
def triangleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
result = 0
nums.sort()
for i in reversed(xrange(2, len(nums))):
left, right = 0, i-1
while left < right:
... | Python/valid-triangle-number.py | 1,033 | :type nums: List[int]
:rtype: int
:type nums: List[int]
:rtype: int
Time: O(n^2) Space: O(1) Time: O(n^2) Space: O(1) | 121 | en | 0.280425 |
# Distributed under the MIT License.
# See LICENSE.txt for details.
import numpy as np
from Evolution.Systems.CurvedScalarWave.Characteristics import (
char_speed_vpsi, char_speed_vzero, char_speed_vplus, char_speed_vminus)
def error(face_mesh_velocity, normal_covector, normal_vector, psi, phi,
inertia... | tests/Unit/Evolution/Systems/CurvedScalarWave/BoundaryConditions/ConstraintPreservingSphericalRadiation.py | 2,278 | Distributed under the MIT License. See LICENSE.txt for details. | 63 | en | 0.534709 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright 2017-2020 AVSystem <avsystem@avsystem.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/licenses/... | tools/lwm2m_object_registry.py | 4,934 | LwM2M Object Registry entry.
Available attributes are the same as tag names in the DDF XML structure.
!/usr/bin/env python3 -*- coding: utf-8 -*- Copyright 2017-2020 AVSystem <avsystem@avsystem.com> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the... | 817 | en | 0.797518 |
#!/usr/bin/python3
import os, argparse, difflib
lookup = {
"flare-form-field": "viur-form-bone",
"flare-form-submit": "viur-form-submit",
"flare-form": "viur-form",
"boneField": "ViurFormBone",
"sendForm": "ViurFormSubmit",
"viurForm": "ViurForm",
"boneSelector": "BoneSelector",
"modu... | tools/flare-update.py | 2,576 | !/usr/bin/python3 Get arguments Iterate all files in current folder Ignore ViUR library folders Ignore anything without a .py-extension | 135 | en | 0.494719 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
###################################################################
# Author: Mu yanru
# Date : 2019.3
# Email : muyanru345@163.com
###################################################################
"""MDockWidget"""
from dayu_widgets.qt import QDockWidget
class MDockWi... | dayu_widgets/dock_widget.py | 529 | Just apply the qss. No more extend.
MDockWidget
!/usr/bin/env python -*- coding: utf-8 -*- Author: Mu yanru Date : 2019.3 Email : muyanru345@163.com | 150 | en | 0.374809 |
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from gaiatest import GaiaTestCase
from gaiatest.apps.ftu.app import Ftu
from gaiatest.apps.homescreen.app import Homescr... | tests/python/gaia-ui-tests/gaiatest/tests/functional/ftu/test_ftu_with_tour.py | 2,257 | https://moztrap.mozilla.org/manage/case/6119/
This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. Go through the FTU setup as quickly as possible to get to the Tour section Take... | 423 | en | 0.922057 |
import os
import pytest
from cassis import *
FIXTURE_DIR = os.path.join(os.path.dirname(os.path.realpath(__file__)), "test_files")
# Small xmi
@pytest.fixture
def small_xmi_path():
return os.path.join(FIXTURE_DIR, "xmi", "small_cas.xmi")
@pytest.fixture
def small_xmi(small_xmi_path):
with open(small_xmi... | tests/fixtures.py | 3,769 | Small xmi CAS with inheritance Small type system Small type system with document annotation Type system with types without namespace https://github.com/dkpro/dkpro-cassis/issues/43 Type system with inheritance Annotations | 221 | en | 0.790077 |
# Download the Python helper library from twilio.com/docs/python/install
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/console
api_key_sid = "SKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
api_key_secret = "your_api_key_secret"
client = Client(api_key_sid, api_key_secret)
publishedtrack = clie... | video/rooms/participants/published-track/retrieve-track-published-by-participant/retrieve-track-published-by-participant.py | 457 | Download the Python helper library from twilio.com/docs/python/install Your Account Sid and Auth Token from twilio.com/console | 126 | en | 0.766585 |
import argparse
import importlib
import mmcv
import numpy as np
import os
import os.path as osp
import time
import torch
from mmcv.parallel import MMDataParallel, MMDistributedDataParallel
from mmcv.runner import get_dist_info, init_dist, load_checkpoint
from openselfsup.datasets import build_dataloader, build_dataset... | tools/extract.py | 6,719 | set cudnn_benchmark update configs according to CLI args checkpoint and pretrained are exclusive check memcached package exists init distributed env first, since logger depends on the dist info. create work_dir logger build the dataloader specify pretrained model build the model and load checkpoint build extraction pro... | 330 | en | 0.65318 |
"""Temkin Approximation isotherm model."""
import numpy
import scipy
from ..utilities.exceptions import CalculationError
from .base_model import IsothermBaseModel
class TemkinApprox(IsothermBaseModel):
r"""
Asymptotic approximation to the Temkin isotherm.
.. math::
n(p) = n_m \frac{K p}{1 + K ... | src/pygaps/modelling/temkinapprox.py | 4,816 | Asymptotic approximation to the Temkin isotherm.
.. math::
n(p) = n_m \frac{K p}{1 + K p} + n_m \theta (\frac{K p}{1 + K p})^2 (\frac{K p}{1 + K p} -1)
Notes
-----
The Temkin adsorption isotherm [#]_, like the Langmuir model, considers
a surface with n_m identical adsorption sites, but takes into account adsorba... | 2,328 | en | 0.695467 |
__author__ = "Johannes Köster"
__copyright__ = "Copyright 2015-2019, Johannes Köster"
__email__ = "koester@jimmy.harvard.edu"
__license__ = "MIT"
import html
import os
import shutil
import textwrap
import time
import tarfile
from collections import defaultdict, Counter
from itertools import chain, filterfalse, groupby... | snakemake/dag.py | 74,934 | Definition of a batch for calculating only a partial DAG.
Directed acyclic graph of jobs.
Inner function for DFS traversal.
Return whether the given job is ready to execute.
Archives workflow such that it can be re-run on a different system.
Archiving includes git versioned files (i.e. Snakefiles, config files, ...),
... | 9,218 | en | 0.88887 |
#!/usr/bin/env python3
import matplotlib.pyplot as plt
import numpy as np
pool_forward = __import__('1-pool_forward').pool_forward
if __name__ == "__main__":
np.random.seed(0)
lib = np.load('../data/MNIST.npz')
X_train = lib['X_train']
m, h, w = X_train.shape
X_train_a = X_train.reshape((-1, h, w,... | supervised_learning/0x07-cnn/1-main.py | 716 | !/usr/bin/env python3 | 21 | fr | 0.448822 |
from starlette.datastructures import URL
from dashboard.pagination import PageControl, get_page_controls, get_page_number
def test_single_page_does_not_include_any_pagination_controls():
"""
When there is only a single page, no pagination controls should render.
"""
url = URL("/")
controls = get_... | tests/test_pagination.py | 6,089 | If an ellipsis marker can be replaced with a single page marker, then
we should do so.
First page in long pagination controls, should render as:
Previous [1] 2 3 4 5 ... 49 50 Next
First page in pagination controls, should render as:
Previous [1] 2 3 4 5 Next
Last page in long pagination controls, should render as:
Pre... | 740 | en | 0.606416 |
# Generated by Django 2.2 on 2019-04-18 10:46
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0006_auto_20190417_2232'),
]
operations = [
migrations.AlterField(
model_name='question',
name='order',
... | core/migrations/0007_auto_20190418_0646.py | 372 | Generated by Django 2.2 on 2019-04-18 10:46 | 43 | en | 0.480933 |
# Generated by Django 2.2.1 on 2020-03-26 05:17
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('webapi', '0015_auto_20200326_0955'),
]
operations = [
migrations.AlterField(
model_name='property',
name='property_n... | src/webapi/migrations/0016_auto_20200326_1417.py | 571 | Generated by Django 2.2.1 on 2020-03-26 05:17 | 45 | en | 0.572193 |
# MIT License
#
# Copyright (c) 2018 Haoxintong
#
# 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, p... | examples/mnist/train_mnist_arcloss.py | 5,996 | MIT License Copyright (c) 2018 Haoxintong 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, publish, distribu... | 1,341 | en | 0.76587 |
"""
A mechanism for plotting field values along a line through a dataset
"""
#-----------------------------------------------------------------------------
# Copyright (c) 2017, yt Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distrib... | yt/visualization/line_plot.py | 15,757 | LineBuffer(ds, start_point, end_point, npoints, label = None)
This takes a data source and implements a protocol for generating a
'pixelized', fixed-resolution line buffer. In other words, LineBuffer
takes a starting point, ending point, and number of sampling points and
can subsequently generate YTArrays of field val... | 5,121 | en | 0.599818 |
import pandas as pd
import numpy as np
import scipy.io
import dpsimpy
class Reader:
def __init__(self, mpc_file_path, mpc_name = 'mpc'):
# read input file (returns multidimensional dict)
self.mpc_raw = scipy.io.loadmat(mpc_file_path)
self.mpc_name = mpc_name
def process_mpc(self):
... | python/src/dpsim/matpower.py | 12,214 | read input file (returns multidimensional dict) gencost_data_idx= 5 Process raw mpc data and create corresponding dataframes Version System frequency (not included in mpc but needed for setting dpsimpy component parameters i.e inductances, capacitances ..) Base power (MVA) Busses scipy.io.loadmat loads all matrix entri... | 1,552 | en | 0.671577 |
from __future__ import print_function
import contextlib
import imp
import os
import shutil
import subprocess
import sys
import tempfile
from unittest import skip
from ctypes import *
import numpy as np
try:
import setuptools
except ImportError:
setuptools = None
import llvmlite.binding as ll
from numba impo... | numba/tests/test_pycc.py | 11,860 | Test creating a LLVM bitcode file using pycc.
Test creating a C shared library object using pycc.
Test creating a CPython extension module using pycc.
Unset MACOSX_DEPLOYMENT_TARGET because we are not building portable
libraries
if suitable compilers are not present then skip. Make sure temporary files and directorie... | 1,073 | en | 0.819663 |
from typing import List
from flake8_functions_names.custom_types import FuncdefInfo
from flake8_functions_names.utils.imports import is_module_installed
from flake8_functions_names.words import VERBS, PURE_VERBS, BLACKLISTED_WORDS_IN_FUNCTIONS_NAMES
def validate_returns_bool_if_names_said_so(funcdef: FuncdefInfo) ->... | flake8_functions_names/validators.py | 2,971 | noqa: FNE007 noqa: FNE007 noqa: CFQ003, FNE007 | 46 | te | 0.235659 |
#!/usr/bin/python
import cgi
import cgitb
import json
import parse_enumeration
cgitb.enable()
form = cgi.FieldStorage()
# Get data from fields
callback = form.getvalue('callback')
email = form.getvalue('email')
if (email is None):
email = "<ul><li>hello, world!</li></ul>"
print "Content-type: application/jso... | src/process-request.py | 494 | !/usr/bin/python Get data from fields | 37 | en | 0.499878 |
#Punto 10 cambiar datos
lista=[]
datos=(input("cantidad de datos: "))
for i in range (0,datos):
alt=float(input("ingrese alturas: "))
lista.append(alt)
print("la altura maxima es ", max(lista))
##################################
lista=[]
numero=int(input("numero 1 para agregar una altura y numero 2 para bu... | Taller de Estrucuras de Control Repeticion/Punto10.py | 632 | Punto 10 cambiar datos | 22 | es | 0.888637 |
# Generated by Django 2.2.13 on 2020-09-16 14:47
# Third-party
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("licenses", "0004_auto_20200902_1302"),
]
operations = [
migrations.AlterUniqueTogether(
name="translatedlicensename",
... | licenses/migrations/0005_auto_20200916_1047.py | 647 | Generated by Django 2.2.13 on 2020-09-16 14:47 Third-party | 58 | en | 0.762247 |
# 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 may ... | sdk/containerregistry/azure-mgmt-containerregistry/azure/mgmt/containerregistry/v2019_06_01_preview/aio/operations/_agent_pools_operations.py | 33,712 | AgentPoolsOperations async operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.containerregistry.v2019_06_01_p... | 2,925 | en | 0.44389 |
import dis
import unittest
from test.support.bytecode_helper import BytecodeTestCase
def count_instr_recursively(f, opname):
count = 0
for instr in dis.get_instructions(f):
if instr.opname == opname:
count += 1
if hasattr(f, '__code__'):
f = f.__code__
for c in f.co_consts... | www/src/Lib/test/test_peepholer.py | 20,531 | Check that the lnotab byte offsets are sensible.
Adding a docstring made this test fail in Py2.5.0
jump to unconditional jump unconditional jump to RETURN_VALUE JUMP_IF_*_OR_POP jump to conditional jump Don't bother checking if the line info is sensible, because most of the line info we can get at comes from lnotab. ... | 2,985 | en | 0.852215 |
import sys
import os
import shutil
import zipfile
'''
Author: Benny Megidish
Description: This program extracts all the drawing, image and 3D design files out of an 123dx file
Arguments naming conventions is used like in java (camelCase)
'''
numOfFileExtracted = 0
def _extract... | fusion123/converter.py | 4,428 | converts the file into fusion 360 file (this file might be usable in other CAD software as well)
a wrapper function for the recursive file extraction function
extracts all the illustations and models from the 123dx file recursively
traverse zip extract only drawing images and 3D files find unique file name copy fi... | 690 | en | 0.842755 |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def sumOfLeftLeaves(self, root):
"""
:type root: TreeNode
:rtype: int
"""
while not root:
... | Python/404sum_of_left_leaves.py | 553 | :type root: TreeNode
:rtype: int
Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None | 184 | en | 0.522728 |
# Copyright (c) 2010 Chris Moyer http://coredumped.org/
#
# 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, ... | desktop/core/ext-py/boto-2.46.1/boto/ecs/item.py | 5,510 | A single Item
A special ResponseGroup that has built-in paging, and
only creates new Items on the "Item" tag
A Generic "Response Group", which can
be anything from the entire list of Items to
specific response elements within an item
Initialize this Item
Initialize this Item
Special paging functionality
Override to fir... | 1,490 | en | 0.841497 |
# -*- coding: utf-8 -*-
"""DNACenterAPI topology API fixtures and tests.
Copyright (c) 2019 Cisco and/or its affiliates.
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, inclu... | tests/api/v1_3_1/test_topology.py | 6,686 | DNACenterAPI topology API fixtures and tests.
Copyright (c) 2019 Cisco and/or its affiliates.
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... | 1,142 | en | 0.879781 |
# Copyright (c) 2020 Huawei Technologies Co., Ltd
# Copyright (c) 2019, Facebook CORPORATION.
# All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/lice... | test/test_npu/test_network_ops/test_tril.py | 2,923 | Copyright (c) 2020 Huawei Technologies Co., Ltd Copyright (c) 2019, Facebook CORPORATION. All rights reserved. Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://opensource.org/licenses/BSD-3-Clause ... | 625 | en | 0.873972 |
# 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 ... | azure-mgmt-network/azure/mgmt/network/v2018_10_01/operations/public_ip_prefixes_operations.py | 24,488 | PublicIPPrefixesOperations operations.
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
:ivar api_version: Client API version. Constant value: "2018-10-01".
Creates or updates a ... | 6,300 | en | 0.471362 |
# -*- coding:utf8 -*-
# File : env.py
# Author : Jiayuan Mao
# Email : maojiayuan@gmail.com
# Date : 12/29/16
#
# This file is part of TensorArtist.
from ...core import get_logger
from ...core.event import EventManager, register_event, trigger_event
from ...core.utils.meta import notnone_property
from ..graph.en... | TensorArtist/tartist/nn/train/env.py | 2,706 | -*- coding:utf8 -*- File : env.py Author : Jiayuan Mao Email : maojiayuan@gmail.com Date : 12/29/16 This file is part of TensorArtist. | 140 | en | 0.705652 |
"""Tcp client for synchronous uhd message tcp port"""
import threading
import Queue
import time
import socket
import struct
import numpy as np
class _TcpSyncClient(threading.Thread):
"""Thead for message polling"""
queue = Queue.Queue()
q_quit = Queue.Queue()
ip_address = None
port = None
de... | src/tcp_sync.py | 3,403 | Creates a thread to connect to the synchronous uhd messages tcp port
Thead for message polling
get received messages as string of integer
get received messages as string of integer
apply fftshift to message
get received messages as string of integer
Checks if one or more messages were received and empties the message q... | 517 | en | 0.872349 |
#!/usr/bin/env python3
# Packet MAC Sniffer
# Author Yehia Elghaly
import socket
import textwrap
import struct
from colorama import Fore, Back, Style
def main():
connection = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(3))
while True:
read_data, addr = connection.recvfrom(65536)
send_mac, recv... | Chapter 06/Packet-Sniffer-MAC.py | 817 | !/usr/bin/env python3 Packet MAC Sniffer Author Yehia Elghaly | 61 | en | 0.361829 |
# -*- coding: utf-8 -*-
from .domainconfig import DomainConfig # noqa
from .resourceconfig import ResourceConfig # noqa
| eve_sqlalchemy/config/__init__.py | 123 | -*- coding: utf-8 -*- noqa noqa | 31 | en | 0.606218 |
#!/usr/bin/env python3
# coding: utf-8
# Copyright 2019 Huawei Technologies Co., Ltd
#
# 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 ... | python/akg/ms/cce/sparse_softmax_cross_entropy_with_logits.py | 1,190 | sparse softmax cross entropy with logits
sparse softmax cross entropy with logits
!/usr/bin/env python3 coding: utf-8 Copyright 2019 Huawei Technologies Co., Ltd 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... | 680 | en | 0.799611 |
import ast
import copy
import json
import os
import re
from collections import OrderedDict
from dataclasses import fields
from urllib.parse import urlparse
import supervisely_lib as sly
import sly_globals as g
from functools import lru_cache
def camel_to_snake(string_to_process):
return re.sub(r'(?<!^)(?=[A-Z]... | supervisely/labeling-tool/src/sly_functions.py | 13,053 | [{'index': 0, 'embedding': [...], ..}, ..] { 'pred_dist': [[1.0, ..], ..], 'pred_labels': [['label1', ..], ..], 'pred_urls': [['image_url1', ..], ..], } check tag in local and remote metas add tag to newest meta @lru_cache(maxsize=10) image2info.clear() return None Review tags tab Last assigned tab Database... | 342 | en | 0.246448 |
# Author: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
# Denis Engemann <denis.engemann@gmail.com>
# Andrew Dykstra <andrew.r.dykstra@gmail.com>
# Mads Jensen <mje.mads@gmail.com>
#
# License: BSD (3-clause)
import os.path as op
from copy import deepcopy
import warnings
import ... | python-packages/mne-python-0.10/mne/tests/test_evoked.py | 17,942 | Test evoked splitting / re-appending channel types
Test creating evoked from array
Test channels-dropping functionality
Test equalization of channels
Test evoked arithmetic
Test for detrending evoked data
Test SSP proj operations
Test for resampling of evoked data
Test peak gette... | 1,888 | en | 0.720923 |
import sqlite3
import mmap
import os
import sys
import copy
import math
import tempfile
from tqdm import tqdm
from scipy.stats import norm
from expiringdict import ExpiringDict
cache = ExpiringDict(max_len=100000,max_age_seconds=600)
def get_num_lines(file_path):
fp = open(file_path, "r+")
buf = mmap.mmap(fp... | server/ai/src/naive_bayes.py | 6,872 | Determine the P(mac=val | loc) (positive)
Determine the P(mac=val | ~loc) (not positive)
with open("dump.sql","w") as f: for line in db.iterdump(): f.write('%s\n' % line) Write disk to file os.remove("dump.sql") First find all the values for mac at loc apply gaussian filter 0.5% chance for anything | 313 | en | 0.660589 |
from pathlib import Path
import tvm
from tvm import autotvm
from tvm import relay
from tvm.autotvm.tuner import GATuner
from tvm.autotvm.tuner import GridSearchTuner
from tvm.autotvm.tuner import RandomTuner
from tvm.autotvm.tuner import XGBTuner
from rl_tuner.ga_dqn_tuner import GADQNTuner
from rl_tuner.ga_dqn_tuner... | tools/tune_model.py | 3,430 | Tune a model for a specified number of trials along with other tune settings.
Tune settings are specified using a json configuration, as per the TVM tools readme.
Auto tune all models referenced in the json configuration.
Create a tuner Save debug info for rl tuner only | 272 | en | 0.766502 |
#!/usr/bin/env python
# Author: Nick Zwart
# Date: 2016jun01
# Backup all the projects of a git-hub style website via git mirroring.
# https://www.garron.me/en/bits/backup-git-bare-repo.html
import os
import sys
import time
import gitlab # external GitLab API
import github # external GitHub API
import shutil
impo... | BackupHub.py | 8,467 | A simple git interface for managing bare-mirroed repos that backup url
accessible upstream repos.
The abstract class to template each git-based website api.
!/usr/bin/env python Author: Nick Zwart Date: 2016jun01 Backup all the projects of a git-hub style website via git mirroring. https://www.garron.me/en/bi... | 1,293 | en | 0.608423 |
import os
from src.multi_site_inputs_parser import multi_site_csv_parser
from src.parse_api_responses_to_csv import parse_responses_to_csv_with_template
from src.post_and_poll import get_api_results
from src.parse_api_responses_to_excel import parse_api_responses_to_excel
"""
Change these values
"""
##################... | multi_site/baseline_scenario_full_service_restaurant.py | 1,767 | REPLACE WITH YOUR API KEY | 25 | en | 0.701228 |
import math
import sys
def example_1():
"""
THIS IS A LONG COMMENT AND should be wrapped to fit within a 72
character limit
"""
long_1 = """LONG CODE LINES should be wrapped within 79 character to
prevent page cutoff stuff"""
long_2 = """This IS a long string that looks gross and... | lambdata/code_review.py | 1,233 | THIS IS A LONG COMMENT AND should be wrapped to fit within a 72
character limit | 80 | en | 0.913089 |
from rest_framework.test import APIRequestFactory
from rest_framework import status
from django.test import TestCase
from django.urls import reverse
from ..models import User
from ..serializer import UserSerializer
from ..views import UserViewSet
import ipapi
class UsersApiRootTestCase(TestCase):
def test_api_ro... | users_django/users/tests/test_views.py | 9,607 | Test POST /api/v1/users
Override 'REMOTE_ADDR' to set IP address to Switzerland or another country for testing purpose.
Test DELETE /api/v1/user/:id
Test GET /api/v1/users
Test GET /api/v1/users/:id
Test PUT|PATCH /api/v1/user/:id
Factorize the tests setup to use a pool of existing users.
GET /api/v1/ should retur... | 522 | en | 0.603275 |
# Credits to Ozan Sener
# https://github.com/intel-isl/MultiObjectiveOptimization
import numpy as np
import torch
class MGDASolver:
MAX_ITER = 250
STOP_CRIT = 1e-5
@staticmethod
def _min_norm_element_from2(v1v1, v1v2, v2v2):
"""
Analytical solution for min_{c} |cx_1 + (1-c)x_2|_2^2
... | utils/min_norm_solvers.py | 8,857 | Find the minimum norm solution as combination of two points
This is correct only in 2D
ie. min_c |\sum c_i x_i|_2^2 st. \sum c_i = 1 , 1 >= c_1 >= 0
for all i, c_i + c_j = 1.0 for some i, j
Analytical solution for min_{c} |cx_1 + (1-c)x_2|_2^2
d is the distance (objective) optimzed
v1v1 = <x1,x1>
v1v2 = <x1,x2>
v2v2 = ... | 1,617 | en | 0.816489 |
"""This module contains logic for refreshing materialized views.
Materialized views don't get refreshed automatically after a bucardo initial
sync. This module detects them and refreshes them.
Classes exported:
MatViews: Identify materialized views and refresh them on the secondary database.
"""
import psycopg2
from... | plugins/mat_views/__init__.py | 2,518 | Identify materialized views and refresh them on the secondary database.
Materialized views are identified based on the namespaces specified in the
config.
Methods exported:
refresh: find and refresh materialized views
Create configuration settings that may not already be set.
The user can either define the relevant ... | 1,219 | en | 0.800008 |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: list_translate_rule.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.... | monitor_sdk/api/translate/list_translate_rule_pb2.py | 9,182 | -*- coding: utf-8 -*- Generated by the protocol buffer compiler. DO NOT EDIT! source: list_translate_rule.proto @@protoc_insertion_point(imports) @@protoc_insertion_point(class_scope:translate.ListTranslateRuleRequest) @@protoc_insertion_point(class_scope:translate.ListTranslateRuleResponse) @@protoc_insertion_point(c... | 413 | en | 0.324519 |
"""NAO robot class"""
from .robot import Robot
import torch
class Pose_Assumption(Robot):
def __init__(self, env_params):
super(Pose_Assumption, self).__init__(env_params)
env_params = self.ingest_params2(env_params)
self.target = env_params["target error"]
self.joints = env_params... | environments/nao/pose_assumption.py | 4,637 | Applies the pose to the robot.
Calculate the error between predicted and target angles, and
add the safety penalties.
Evaluates the predicted pose.
Ensures safety of the predicted angles.
In this function the robot will return to default pose, to
be ready for the new command.
NAO robot class
State Initial state NOTE:... | 457 | en | 0.82033 |
__package__ = "blackhat.bin.installable"
from ...helpers import Result
from ...lib.input import ArgParser
from ...lib.output import output
from ...lib.ifaddrs import getifaddrs
__COMMAND__ = "ifconfig"
__DESCRIPTION__ = ""
__DESCRIPTION_LONG__ = ""
__VERSION__ = "1.2"
def parse_args(args=[], doc=False):
"""
... | client/blackhat/bin/installable/ifconfig.py | 2,858 | # TODO: Add docstring for manpage
Handle parsing of arguments and flags. Generates docs using help from `ArgParser`
Args:
args (list): argv passed to the binary
doc (bool): If the function should generate and return manpage
Returns:
Processed args and a copy of the `ArgParser` object if not `doc` else a `... | 495 | en | 0.413812 |
# -*- coding: utf-8 -*-
import numpy as np
import astropy.units as u
import pkg_resources
from astropy.io import ascii
from astropy.modeling.tabular import tabular_model
from .baseclasses import BaseAtttauVModel
from .helpers import _test_valid_x_range
__all__ = ["WG00"]
x_range_WG00 = [0.1, 3.0001]
class WG00(... | dust_attenuation/radiative_transfer.py | 19,491 | Attenuation curve of Witt & Gordon (2000)
Parameters
----------
tau_v: float
optical depth in V band
Raises
------
InputParameterError
Input Av values outside of defined range
Notes
-----
From Witt & Gordon (2000, ApJ, Volume 528, pp. 799-816)
Example:
.. plot::
:include-source:
import numpy as np
... | 7,138 | en | 0.565069 |
"""
Extract CLOS / NLOS lookup.
Written by Ed Oughton.
March 2021
"""
import os
import configparser
import json
import math
import glob
import random
import numpy as np
import pandas as pd
import geopandas as gpd
import pyproj
from shapely.geometry import Point, Polygon, box, LineString
from shapely.ops import trans... | scripts/los.py | 21,121 | Query the Digital Elevation Model to get an estimated interdecile
range for each grid square.
Find potential LOS high points.
Parameters
----------
path_input : string
File path for the digital elevation raster tile.
point : tuple
Coordinate point being queried.
Returns
-------
los : string
The Line of Si... | 3,401 | en | 0.646248 |
# Generated by Django 3.1.4 on 2021-01-03 18:02
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('home', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Attribute',
... | home/migrations/0002_attribute_training_trainingvalue.py | 1,732 | Generated by Django 3.1.4 on 2021-01-03 18:02 | 45 | en | 0.658968 |
# This script is used to parse BOOST special function test data into something
# we can easily import in numpy.
import re
import os
# Where to put the data (directory will be created)
DATA_DIR = 'scipy/special/tests/data/boost'
# Where to pull out boost data
BOOST_SRC = "boostmath/test"
CXX_COMMENT = re.compile(r'^\s... | scipy/special/utils/convert.py | 3,467 | This script is used to parse BOOST special function test data into something we can easily import in numpy. Where to put the data (directory will be created) Where to pull out boost data Makes use of ldexp and casts Makes use of numeric_limits and ternary operator Doesn't contain any data Derivatives functions don't ex... | 459 | en | 0.868502 |
import json
import os
from time import sleep
import requests
import pyrominfo.pyrominfo.snes as snes
from shutil import copy
from pyrominfo.pyrominfo import nintendo64
def n64_info(filename):
n64_parser = nintendo64.Nintendo64Parser()
props = n64_parser.parse(filename)
return props
def snes_info(filen... | main.py | 2,598 | dont run code while testing containerrip_game() | 47 | en | 0.298762 |
import numpy as np
import os
import time
import argparse
import PruneAndSearch as algs
def get_args():
parser = argparse.ArgumentParser (
prog='PruneAndSearch',
description='Implementation of the Prune and Search Algorithm. ',
usage='python main.py { --rand RAND | --file FILE | --list LI... | main.py | 7,915 | Simple getter function to get some list based on the arguments passed in. Run a series of trials on both algorithms. 1e6 1e10 Seed The first trial for consistency. Keep a buffer of the returned finds for later comparison. Begin the trials! Seed The first trial for consistency. Keep a buffer of the returned finds for la... | 642 | en | 0.878793 |
# Copyright 2017 Square, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... | tests/unit/test_jlock.py | 11,024 | Tests the ``jlock`` submodule.
Called before each test.
Performs setup.
Args:
self (TestJLock): the ``TestJLock`` instance
Returns:
``None``
Called after each test.
Performs teardown.
Args:
self (TestJLock): the ``TestJLock`` instance
Returns:
``None``
Tests acquiring the lockfile when the current lockfil... | 3,565 | en | 0.818808 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.FileItem import FileItem
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.AlipayUserMpointPreconsultModel import AlipayUserMpointPreconsultModel
class AlipayUserMpointPreconsultRequest(object):
def __i... | alipay/aop/api/request/AlipayUserMpointPreconsultRequest.py | 3,954 | !/usr/bin/env python -*- coding: utf-8 -*- | 42 | en | 0.34282 |
##########################################################################
#
# Copyright (c) 2007-2010, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redis... | test/IECore/Turbulence.py | 3,731 | Copyright (c) 2007-2010, Image Engine Design Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditi... | 1,574 | en | 0.889544 |
# -*- coding: utf-8 -*-
from .deprecated_code import (chi2_bin, best_ks_bin, make_bin, feature_analysis, calc_bin_cond)
| __init__.py | 121 | -*- coding: utf-8 -*- | 21 | en | 0.767281 |
#!/usr/bin/env python3
import ast
from collections import namedtuple
from functools import partial
import itertools
import logging
import os
from pathlib import Path
import re
from tempfile import NamedTemporaryFile, TemporaryDirectory
import time
import traceback
from typing import (
Any,
Iterator,
List,
... | flake8_mypy.py | 11,426 | Used to determine if the file is using annotations at all.
Adapts the extended error namedtuple to be compatible with Flake8.
Return MYPYPATH so that stubs have precedence over local sources.
Called if no explicit visitor function exists for a node.
Returns True if error should be ignored.
!/usr/bin/env python3 noqa L... | 1,675 | en | 0.779559 |
#
# 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... | airflow/lineage/backend/__init__.py | 1,292 | Sends lineage metadata to a backend
:param operator: the operator executing a transformation on the inlets and outlets
:param inlets: the inlets to this operator
:param outlets: the outlets from this operator
:param context: the current context of the task instance
Licensed to the Apache Software Foundation (ASF) und... | 1,020 | en | 0.865842 |
# THIS FILE IS AUTO-GENERATED. DO NOT EDIT
from verta._swagger.base_type import BaseType
class ModeldbAddProjectTags(BaseType):
def __init__(self, id=None, tags=None):
required = {
"id": False,
"tags": False,
}
self.id = id
self.tags = tags
for k, v in required.items():
if self... | client/verta/verta/_swagger/_public/modeldb/model/ModeldbAddProjectTags.py | 654 | THIS FILE IS AUTO-GENERATED. DO NOT EDIT | 40 | en | 0.883199 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='AllFieldsModel',
fields=[
('id', models.AutoFie... | example/second_app/migrations/0001_initial.py | 3,907 | -*- coding: utf-8 -*- | 21 | en | 0.767281 |
import time
import random
import numpy as np
import gym
from rlkit.scripted_experts.scripted_policy import ScriptedPolicy
ACT_MAG = 0.275
ACT_NOISE_SCALE = 0.1
ACT_SLOW_NOISE_SCALE = 0.05
SLOW_DOWN_RADIUS = 0.01
def get_linear_pos_act(cur_pos, reach_pos):
cur_pos = cur_pos.copy()
reach_pos = reach_pos.copy()
... | rlkit/scripted_experts/linear_few_shot_reach_env_expert.py | 4,462 | if dist > ACT_MAG: if dist < ACT_MAG: move_dir = move_dir else: first make the gripper go slightly above the object first go to a way-point now actually go to the object reset the milestones first find out what stage we are in and update milestone info check if milestone 0 was completed by the last step action che... | 617 | en | 0.785117 |
# -*- coding: utf-8 -*-
def calculate_map(gt_path, my_path):
id2videos = dict()
with open(gt_path, 'r') as fin:
lines = fin.readlines()
for line in lines:
terms = line.strip().split(' ')
id2videos[terms[0]] = terms[1:]
id_num = len(lines)
my_id2videos = dict()
... | evaluation_map.py | 1,385 | -*- coding: utf-8 -*- recall number upper bound | 47 | en | 0.700324 |
# Copyright 2021 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_examples/lite/model_maker/public/image_classifier/__init__.py | 2,090 | APIs to train an image classification model.
Task guide:
https://www.tensorflow.org/lite/tutorials/model_maker_image_classification.
Copyright 2021 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 Lice... | 770 | en | 0.829381 |
import os
import random
import numpy as np
from PIL import Image
from torch.utils.data import Dataset
from datasets.data_io import get_transform, read_all_lines, pfm_imread
class PicoStereoDataset(Dataset):
def __init__(self, datapath, list_filename, training):
self.datapath = datapath
self.left_fi... | datasets/dataset.py | 11,058 | ground truth not available has disparity ground truth to tensor, normalize "disparity": disparity, random crop to tensor, normalize ground truth not available has disparity ground truth random crop to tensor, normalize normalize pad to size 1248x384 pad images pad disparity gt (881, 400) random crop to tensor, normaliz... | 321 | en | 0.828935 |
from unittest.mock import MagicMock
import pytest
from click.testing import CliRunner
from prefect.cli.register import register
def test_register_init():
runner = CliRunner()
result = runner.invoke(register)
assert result.exit_code == 0
assert "Register flows" in result.output
def test_register_he... | tests/cli/test_register.py | 2,385 | Check additional labels are set if specified | 44 | en | 0.462999 |
# Copyright (c) 2017-2021 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
"""
This module contains pretty-print/formatting utilities.
"""
from dataclasses import dataclass
from typing import Optional
@dataclass(frozen=True)
class PrettyOptions:
... | python/dazl/pretty/options.py | 953 | Display options for pretty-printing DAML ASTs.
Instance attributes:
.. attribute:: PrettyOptions.column_width
The maximum number of columns to use when rendering text, or ``None`` if lines should not
wrap.
.. attribute:: PrettyOptions.show_hidden_types
``True`` to render built-in DAML types defined in ... | 674 | en | 0.525521 |
import logging
import numpy as np
import trimesh
from src.common import compute_iou
# from scipy.spatial import cKDTree
from src.utils.libkdtree import KDTree
from src.utils.libmesh import check_mesh_contains
# Maximum values for bounding box [-0.5, 0.5]^3
EMPTY_PCL_DICT = {
'completeness': np.sqrt(3),
'accu... | src/eval.py | 7,912 | Mesh evaluation class.
It handles the mesh evaluation process.
Args:
n_points (int): number of points to be used for evaluation
Compute minimal distances of each point in points to mesh.
Args:
points (numpy array): points array
mesh (trimesh): mesh
Computes minimal distances of each point in points_src t... | 1,837 | en | 0.677193 |
# Copyright (c) 2018 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... | kohm_gazebo/launch/include/navigation/nav2/nav.launch.py | 5,122 | Copyright (c) 2018 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 writing, software... | 635 | en | 0.859421 |
from setuptools import setup
# def readme():
# with open('README.md') as f:
# retun f.read()
setup(
name = 'cypher',
version = '0.2',
author = 'shashi',
author_email = 'skssunny30@gmail.com',
description = 'Password Encryptor by suggesting wheather a password is strong or not',
#l... | setup.py | 678 | def readme(): with open('README.md') as f: retun f.read()long_description = readme(), | 97 | en | 0.643676 |
# Generated by Django 3.0.8 on 2020-07-01 19:16
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
ope... | users/migrations/0001_initial.py | 778 | Generated by Django 3.0.8 on 2020-07-01 19:16 | 45 | en | 0.637432 |
"""Source URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based ... | Source/urls.py | 917 | Source URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based vie... | 733 | en | 0.586313 |
# Lab 2 Linear Regression
import tensorflow as tf
tf.set_random_seed(777) # seed 설정
# training data
x_train = [1, 2, 3]
y_train = [1, 2, 3]
# regerssion 결과는 W = 1, b = 0 이라는 것을 알 수 있음
# but tensorflow로 training 시켜서 해보기!!
# W와 b는 어떻게 달라질까?
# tf.Variable() : tensorflow가 사용하는 변수(trainable variable)
# tf.random_normal... | Python/tensorflow/DeepLearningZeroToAll/ver.py/Lab02-1-linear_regression.py | 1,879 | Lab 2 Linear Regression seed 설정 training data regerssion 결과는 W = 1, b = 0 이라는 것을 알 수 있음 but tensorflow로 training 시켜서 해보기!! W와 b는 어떻게 달라질까? tf.Variable() : tensorflow가 사용하는 변수(trainable variable) tf.random_normal([1]) : normal dist에서 1개의 난수 생성 Linear regression model cost/loss function (MSE) tf.square() : 제곱해주는 tf 함수 tf... | 660 | ko | 0.869091 |
"""
"""
import unittest
from unittest.mock import Mock, patch
from wheezy.core import __version__, httpclient
from wheezy.core.gzip import compress
class HTTPClientTestCase(unittest.TestCase):
def setUp(self):
self.patcher = patch.object(httpclient, "HTTPConnection")
self.mock_c_class = self.pat... | src/wheezy/core/tests/test_httpclient.py | 5,601 | Expecting json response but content type is not valid.
ETag processing.
Ensure gzip decompression.
json response. | 113 | en | 0.674525 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.