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
from django.conf import settings from django.contrib.auth import get_user_model from django.db import transaction from rest_framework import generics, views from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_registration.settings import registration_settings fr...
dakara_server/users/views.py
2,961
View of the current user. List and creation of users. Edition and view of a user. Retrieve the user. serializer depends on permission level send verification email if requested serializer depends on permission level user has been validated by manager, send notification
271
en
0.874526
import pytest import json import ipaddress import time import natsort import random import re from collections import defaultdict from tests.common.fixtures.ptfhost_utils import change_mac_addresses, copy_arp_responder_py from tests.common.dualtor.dual_tor_utils import mux_cable_server_ip from tests.common.dualtor.dua...
tests/route/test_static_route.py
11,113
Check if the testbed is dualtor. Skip the current test if the DUT version is 201911 or older. Clean up arp or ndp Add ipaddresses in ptf Add static route Check traffic get forwarded to the nexthop Check the route is advertised to the neighbors Config save and reload if specified Remove static route Delete ipaddr...
551
en
0.809383
""" Flake8 plugin to encourage correct string literal concatenation. Forbid implicitly concatenated string literals on one line such as those introduced by Black. Forbid all explicitly concatenated strings, in favour of implicit concatenation. """ from __future__ import generator_stop import ast import tokenize from...
flake8_implicit_str_concat.py
1,780
Flake8 plugin to encourage correct string literal concatenation. Forbid implicitly concatenated string literals on one line such as those introduced by Black. Forbid all explicitly concatenated strings, in favour of implicit concatenation.
240
en
0.82413
import cv2 import numpy as np # import gt_utils def binarize(img): """ Take an RGB image and binarize it. :param img: cv2 image :return: """ gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) ret, bin = cv2.threshold(gray, 1, 255, cv2.THRESH_BINARY) return bin def makecoloredlayer(img, mask, ...
GT_generator/gt_image.py
2,855
Apply a mask to an image to keep only active cells. :return: image Take an RGB image and binarize it. :param img: cv2 image :return: Combine layers and create an image combining several annotations :param masks: list of images used as masks :param colors: list of colors :return: Create an image based on provided mas...
845
en
0.738801
#!/usr/bin/env python # coding: utf-8 # list classMates = ['Micheal', 'Lucy', 'Anna'] print classMates # 获取长度 print len(classMates) # 取值 print classMates[2] print classMates[-1] # 追加 classMates.append('Adam') print classMates # 插入 classMates.insert(1, 'Paul') print classMates # 删除 classMates.pop() print classMa...
liaoxuefeng.com/004-ListAndTuple.py
868
!/usr/bin/env python coding: utf-8 list 获取长度 取值 追加 插入 删除 替换 类型无需一致 嵌套 tuple 因为tuple不可变,所以代码更安全。如果可能,能用tuple代替list就尽量用tuple
122
zh
0.797162
#!/usr/bin/env python # coding=utf-8 from __future__ import division, print_function, unicode_literals from brainstorm.structure.construction import UniquelyNamed def test_basename(): n = UniquelyNamed('my_basename') assert n.name == 'my_basename' def test_merging_scopes_no_conflict(): n1 = UniquelyName...
brainstorm/tests/test_uniquely_named.py
2,887
!/usr/bin/env python coding=utf-8
33
en
0.221043
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # from __future__ import absolute_import import os import sys sys.path.append(os.path.realpath(os.getcwd()))
examples/__init__.py
303
Copyright (c) 2017-present, Facebook, Inc. All rights reserved. This source code is licensed under the license found in the LICENSE file in the root directory of this source tree.
179
en
0.915621
#!/usr/bin/env python3 # Copyright (c) 2014-2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test the getchaintips RPC. - introduce a network split - work on chains of different lengths - join th...
test/functional/rpc_getchaintips.py
2,197
Test the getchaintips RPC. - introduce a network split - work on chains of different lengths - join the network together again - verify that getchaintips now returns two chain tips. !/usr/bin/env python3 Copyright (c) 2014-2017 The Bitcoin Core developers Distributed under the MIT software license, see the accompanyi...
572
en
0.816803
"""safe name Revision ID: 9332f05cb7d6 Revises: 30228d27a270 Create Date: 2020-05-24 23:49:06.195432 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '9332f05cb7d6' down_revision = '30228d27a270' branch_labels = None depends_on = None def upgrade(): # ### ...
migrations/versions/9332f05cb7d6_safe_name.py
800
safe name Revision ID: 9332f05cb7d6 Revises: 30228d27a270 Create Date: 2020-05-24 23:49:06.195432 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
292
en
0.652079
# Copyright (C) Jean-Paul Calderone # See LICENSE for details. """ Unit tests for :mod:`OpenSSL.SSL`. """ import datetime import sys import uuid from gc import collect, get_referrers from errno import ( EAFNOSUPPORT, ECONNREFUSED, EINPROGRESS, EWOULDBLOCK, EPIPE, ESHUTDOWN) from sys import platform, getfilesyste...
tests/test_ssl.py
141,920
Tests for ALPN in PyOpenSSL. Unit tests for `OpenSSL.SSL.Connection`. Tests for `Connection.get_cipher_list`. Tests for `Connection.recv_into`. Tests for SSL renegotiation APIs. Tests for `Connection.send`. Tests for `Connection.sendall`. Tests for the values of constants exposed in `OpenSSL.SSL`. These are values def...
38,874
en
0.822458
# -*- coding: utf-8 -*- # # 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 #...
airflow/executors/celery_executor.py
4,449
CeleryExecutor is recommended for production use of Airflow. It allows distributing the execution of task instances to multiple worker nodes. Celery is a simple, flexible and reliable distributed system to process vast amounts of messages, while providing operations with the tools required to maintain such a system. ...
1,095
en
0.891099
''' Minimum number of jumps to reach end Given an array of integers where each element represents the max number of steps that can be made forward from that element. Write a function to return the minimum number of jumps to reach the end of the array (starting from the first element). If an element is 0, the...
Projects/Python/Minimum Jumps to Reach the End.py
1,209
Minimum number of jumps to reach end Given an array of integers where each element represents the max number of steps that can be made forward from that element. Write a function to return the minimum number of jumps to reach the end of the array (starting from the first element). If an element is 0, they cannot mo...
479
en
0.754427
############################################################################### # # Copyright (c) 2020, NVIDIA CORPORATION. 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...
inference.py
4,917
Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or a...
721
en
0.854296
# Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
examples/campaign_management/add_campaign_bid_modifier.py
3,641
Demonstrates how to add a campaign-level bid modifier for call interactions. Copyright 2018 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2....
1,005
en
0.815337
"""Utility functions for COVID19 UK data""" import os import re import datetime import numpy as np import pandas as pd def prependDate(filename): now = datetime.now() # current date and time date_time = now.strftime("%Y-%m-%d") return date_time + "_" + filename def prependID(filename, config): ret...
covid19uk/data/util.py
2,526
Utility functions for COVID19 UK data current date and time prepend with a set string to load a specific date, this should be in the string City of London & Westminster City of London & Westminster Cornwall & Isles of Scilly Cornwall & Isles of Scilly Must contain 9 characters, 1 region letter followed by 8 numbers
318
en
0.730301
#!/bin/env python # # Copyright 2014 Alcatel-Lucent Enterprise. # # 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 appli...
omniswitch/omniswitch_restful_driver.py
23,098
!/bin/env python Copyright 2014 Alcatel-Lucent Enterprise. 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...
1,268
en
0.754081
# 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/resources/azure-mgmt-msi/azure/mgmt/msi/v2019_09_01_preview/aio/_configuration.py
3,291
Configuration for ManagedServiceIdentityClient. Note that all parameters used to create this instance are saved as instance attributes. :param credential: Credential needed for the client to connect to Azure. :type credential: ~azure.core.credentials_async.AsyncTokenCredential :param subscription_id: The Id of the Su...
891
en
0.648474
import os import sys sys.path.append(os.getcwd()) import numpy as np import matplotlib.pyplot as plt from scipy.stats import beta from restools.plotting import rasterise_and_save from papers.jfm2020_probabilistic_protocol.data import Summary as SummaryProbProto from papers.jfm2020_probabilistic_protocol.extensions im...
papers/jfm2022_optimizing_control_bayesian_method/views/sketches.py
8,467
Plot fitting sketch plot p_lam bars plot fitting ax.annotate(r'$\mathbb{E} P_{lam}(E^{(j)})$', xy=(energies[10], p_lam[10]), xytext=(energies[10] - 0.002, p_lam[10] + 0.2), arrowprops=dict(arrowstyle='->'), fontsize=16) the rectangle is where I want to place the tabletable.auto_set_font_size(False)tab...
1,145
en
0.537065
import matplotlib.pyplot as plt import numpy as np import torch import torch.nn as nn import torchvision import torchvision.transforms as transforms from .misc import * __all__ = ['make_image', 'show_batch', 'show_mask', 'show_mask_single'] # functions to show an image def make_image(img, mean=(0,0,0), std=(1,1...
rethinking-network-pruning/cifar/weight-level/utils/visualize.py
3,798
Converts a one-channel grayscale image to a color heatmap image functions to show an image unnormalize save for adding mask unnormalize for b in range(mask.size(0)): mask[b] = (mask[b] - mask[b].min())/(mask[b].max() - mask[b].min()) print('Max %f Min %f' % (mask.max(), mask.min())) mask = colorize(upsampling(ma...
1,047
en
0.310716
from django.db import models from django.urls import reverse from nautobot.core.models import BaseModel from nautobot.extras.utils import extras_features from nautobot.extras.models import ObjectChange from nautobot.utilities.utils import serialize_object @extras_features("graphql") class DummyModel(BaseModel): ...
examples/dummy_plugin/dummy_plugin/models.py
1,292
related_object=self.virtual_machine,
36
en
0.298775
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: percent # format_version: '1.2' # jupytext_version: 1.0.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # %% [markdown] {"_uuid": "6f06de1b48e35853f80eb1f338...
reference_kernels/FORK EDA, PCA + Simple LGBM on KFold Technique.py
17,714
--- jupyter: jupytext: text_representation: extension: .py format_name: percent format_version: '1.2' jupytext_version: 1.0.4 kernelspec: display_name: Python 3 language: python name: python3 --- %% [markdown] {"_uuid": "6f06de1b48e35853f80eb1f3384baae8f8536b3c"} <h1><center>...
7,562
en
0.325096
from pybfm.irr import IRR # define annual cash flows multiple_irr = IRR( [0, 1, 2], # years [this year, first year, second year] [-3000, 15000, -13000], # cash flows [None, None, None], # kind of cash flow (None, perpetuity) ) # find irr irr = multiple_irr.find(initial_guess=0.05) print(f"Internal Rate...
example/irr.py
967
define annual cash flows years [this year, first year, second year] cash flows kind of cash flow (None, perpetuity) find irr find modified irr find all irr check formula get yield curve data plot save image
206
en
0.860847
from datetime import datetime from xattr import listxattr, getxattr import falcon import hashlib import logging from certidude import const, config from certidude.common import cert_to_dn from certidude.decorators import serialize, csrf_protection from certidude.user import User from .utils import AuthorityHandler from...
certidude/api/session.py
10,855
TODO: move to authority.py TODO: move to authority.py TODO: key type, key length, key exponent, key modulo Extract certificate tags from filesystem No such attribute(s) Extract lease information from filesystem No such attribute(s) TODO: dedup TODO: key type, key length, key exponent, key modulo Seconds from last seen ...
470
en
0.599589
from fastapi import FastAPI, Request from fastapi.responses import HTMLResponse from fastapi.staticfiles import StaticFiles from fastapi.templating import Jinja2Templates app = FastAPI() app.mount("/static", StaticFiles(directory="static"), name="static") templates = Jinja2Templates(directory="templates") @app.ge...
files/fake-QR-code-goskulugi/qr.py
1,304
строка query имеет строгий формат: FdIdOdDDMMYYYYddmmyyyy F,I,O - первая буква фамилии, имени, отчества d - количество звездочек (длина фамилии-1) например Харитонова Ульяна Йорковна => Х9У5Й7 отобразится как Х********* У***** Й******* DDMMYYYY - дата рождения ddmmyyyy - срок действия
285
ru
0.913705
# 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 bedrock.mozorg.util import page from bedrock.redirects.util import redirect urlpatterns = ( # Issue 9727 /fou...
bedrock/foundation/urls.py
4,898
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/. Issue 9727 /foundation/annualreport/2019/ Older annual report financial faqs - these are linked from blog posts was e.g.: http:...
652
en
0.896267
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). import unittest from pants.engine.addressable import (MutationError, NotSerializableError, addressable, addressable_dict, addressable_list) from pant...
tests/python/pants_test/engine/test_addressable.py
7,612
Return the person's age in years. :rtype int Return this series' values. :rtype list of int or float Return a snapshot of the current /varz. :rtype dict of string -> int or float Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). Licensed under the Apache License, Version 2.0 (see LICENSE).
310
en
0.623202
""" Django settings for mysite project. Generated by 'django-admin startproject' using Django 2.1. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ from pathlib imp...
mysite/settings.py
4,016
Django settings for mysite project. Generated by 'django-admin startproject' using Django 2.1. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ Build paths inside the...
1,316
en
0.543793
#!/usr/bin/env python # encoding: utf-8 # # Copyright SAS 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 # # Unless required b...
dlpy/tests/test_model.py
48,778
Please locate the images.sashdat file under the datasources to the DLPY_DATA_DIR. !/usr/bin/env python encoding: utf-8 Copyright SAS 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 h...
1,966
en
0.640556
from pathlib import Path from typing import * from isolateparser.resultparser.parsers import gdtotable import pytest import itertools from loguru import logger data_folder = Path(__file__).parent / "data" / "sample_files" @pytest.fixture def parser() -> gdtotable.GDToTable: return gdtotable.GDToTable() def example...
tests/test_gd_to_table.py
25,100
'total_cov': '4/3','major_cov': '4/3','new_cov': '4/3','minor_cov': '0/0','ref_cov': '0/0''major_cov': '4/4','ref_cov': '0/0','minor_cov': '0/0','new_cov': '4/4','total_cov': '4/4', Need to remove the empty fields since this method is supposed to be given a truncated line anyway. Ne...
491
en
0.677189
#!/usr/bin/env python3 import argparse import os import pprint import struct import sys import traceback def read_uint32(fp, pos): """Read 4 little-endian bytes into an unsigned 32-bit integer. Return value, position + 4.""" fp.seek(pos) val = struct.unpack("<I", fp.read(4))[0] return val, pos + 4 de...
zw1_pack.py
12,825
Packs files or folders given into the first argument: a target file name or a directory (archive will be named the same as directory). If archive name exists, appends number and tries again. Read N null-padded bytes into an ascii encoded string. Return value, position + N. Read 4 little-endian bytes into an unsigned 3...
1,776
en
0.721213
# Copyright 2015 Google 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,...
omaha/enterprise/generate_group_policy_template_admx.py
35,065
Generates a Group Policy template (ADML format)for the specified apps. Replaces LF in strings above with CRLF as required by gpedit.msc. When writing the resulting contents to a file, use binary mode to ensure the CRLFs are preserved. Args: apps: A list of tuples containing information about each app. Each el...
3,804
en
0.776057
from layer import * class LogisticLayer(Layer): def __init__(self, *args, **kwargs): super(LogisticLayer, self).__init__(*args, **kwargs) @classmethod def IsLayerType(cls, proto): return proto.hyperparams.activation == deepnet_pb2.Hyperparams.LOGISTIC def ApplyActivation(self): cm.sigmoid(self.st...
package/deepnet/logistic_layer.py
2,128
Compute derivative w.r.t input given derivative w.r.t output. Compute loss and also deriv w.r.t to it if asked for. Compute the loss function. Targets should be in self.data, predictions should be in self.state. Args: get_deriv: If True, compute the derivative w.r.t the loss function and put it in self.deriv.
317
en
0.720403
import os from pathlib import Path from typing import Any, Text, Dict import pytest import rasa.shared.utils.io import rasa.utils.io from rasa.core.test import ( _create_data_generator, _collect_story_predictions, test as evaluate_stories, FAILED_STORIES_FILE, CONFUSION_MATRIX_STORIES_FILE, RE...
tests/core/test_evaluation.py
8,714
we need this import to ignore the warning... noinspection PyUnresolvedReferences check that test story can either specify base intent or full retrieval intent check if the predicted entry contains full retrieval intent
218
en
0.561686
# exported from PySB model 'model' from pysb import Model, Monomer, Parameter, Expression, Compartment, Rule, Observable, Initial, MatchOnce, Annotation, ANY, WILD Model() Monomer('Ligand', ['Receptor']) Monomer('ParpU', ['C3A']) Monomer('C8A', ['BidU']) Monomer('BaxM', ['BidM', 'BaxA']) Monomer('Apop', ['C3pro', 'X...
log_mito_act/model_577.py
13,272
exported from PySB model 'model'
32
en
0.742345
# -*- coding: utf-8 -*- # # Copyright 2018 Google LLC. 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 requir...
gcloud/google-cloud-sdk/.install/.backup/lib/googlecloudsdk/api_lib/accesscontextmanager/zones.py
10,012
High-level API client for VPC Service Controls Service Perimeters. Patch a service perimeter. Args: perimeter_ref: resources.Resource, reference to the perimeter to patch description: str, description of the zone or None if not updating title: str, title of the zone or None if not updating perimeter_type: Peri...
3,202
en
0.74209
# -*- coding: utf-8 -*- from ccxt.async.base.exchange import Exchange import hashlib import math from ccxt.base.errors import ExchangeError class huobipro (Exchange): def describe(self): return self.deep_extend(super(huobipro, self).describe(), { 'id': 'huobipro', 'name': 'Huobi ...
python/ccxt/async/huobipro.py
17,885
-*- coding: utf-8 -*- obsolete metainfo structure new metainfo structure 获取K线数据 获取聚合行情(Ticker) 获取 Market Depth 数据 获取 Trade Detail 数据 批量获取最近的交易记录 获取 Market Detail 24小时成交量数据 查询系统支持的所有交易对 查询系统支持的所有币种 查询系统当前时间 查询当前用户的所有账户(即account-id) 查询指定账户的余额 查询某个订单详情 查询某个订单的成交明细 查询当前委托、历史委托 查询当前成交、历史成交 查询虚拟币提现地址 创建并执行一个新订单(一步下单, 推荐使用) 创...
475
zh
0.910413
from django.contrib.auth import get_user_model, authenticate from rest_framework import serializers from django.utils.translation import ugettext_lazy as _ class UsersSerializer(serializers.ModelSerializer): """Serializer for users object""" class Meta: model = get_user_model() fields = ('ema...
xojbackend/app/user/serializers.py
2,181
Serializer for the user authentication object Serializer for users object Create a new user with validated password and return it update user data with encrypted password validate and authenticate the user
205
en
0.781235
""" Django settings for queueMgmt project. Generated by 'django-admin startproject' using Django 3.0.5. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os ...
queueMgmt/settings.py
3,584
Django settings for queueMgmt project. Generated by 'django-admin startproject' using Django 3.0.5. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ Build paths insid...
1,098
en
0.608187
# 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/compute/azure-mgmt-compute/azure/mgmt/compute/v2018_10_01/operations/_availability_sets_operations.py
23,994
AvailabilitySetsOperations 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.compute.v2018_10_01.models :par...
6,880
en
0.461357
import math def newton(function,function1,startingInt): #function is the f(x) and function1 is the f'(x) x_n=startingInt while True: x_n1=x_n-function(x_n)/function1(x_n) if abs(x_n-x_n1)<0.00001: return x_n1 x_n=x_n1 def f(x): return math.pow(x,3)-2*x-5 def f1(x): retur...
NeutonMethod.py
362
function is the f(x) and function1 is the f'(x)
47
en
0.891798
""" Copyright 2020 The OneFlow 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 applicable law or agr...
oneflow/compatible_single_client_python/ops/tensor_buffer_ops.py
8,408
This operator generates a tensor buffer blob. Args: shape (Sequence[int]): shape of output blob shape_list ( Sequence[Sequence[int]]): shapes for tensor buffer in output blob value_list (Sequence[float]): values for tensor buffer in output blob data_type (Optional[flow.dtype]): data type for tensor buf...
4,791
en
0.629657
import multiprocessing as mp import time def f(name, timeout, queue): time.sleep(timeout) print('hello', name) queue.put(name + ' done!') queue = mp.SimpleQueue() # queue for communicating with the processes we will spawn bob = mp.Process(target=f, args=('bob', 0.3, queue)) bob.start() # start the pro...
_includes/src/multiprocessing.py
577
queue for communicating with the processes we will spawn start the process start the process wait for processes to complete print results from intercommunication object
168
en
0.873372
'''OpenGL extension EXT.histogram This module customises the behaviour of the OpenGL.raw.GL.EXT.histogram to provide a more Python-friendly API ''' from OpenGL import platform, constants, constant, arrays from OpenGL import extensions, wrapper from OpenGL.GL import glget import ctypes from OpenGL.raw.GL.EXT.histogra...
Cartwheel/lib/Python26/Lib/site-packages/OpenGL/GL/EXT/histogram.py
576
OpenGL extension EXT.histogram This module customises the behaviour of the OpenGL.raw.GL.EXT.histogram to provide a more Python-friendly API END AUTOGENERATED SECTION
171
en
0.376486
# coding: utf-8 import unittest from datetime import datetime from whiskyton import app from whiskyton.helpers import sitemap from whiskyton.helpers.charts import Chart from whiskyton.tests.config import WhiskytonTest class TestHelpers(unittest.TestCase): def setUp(self): self.test_suite = WhiskytonTest...
whiskyton/tests/test_helpers.py
2,607
coding: utf-8 test methods from Whisky (whiskyton/models.py) test methods from Chart (whiskyton/helpers/charts.py) test methods from whiskyton/helpers/sitemap.py
161
en
0.63693
import os import logging from .paths import get_path _FORMAT = '%(asctime)s:%(levelname)s:%(lineno)s:%(module)s.%(funcName)s:%(message)s' _formatter = logging.Formatter(_FORMAT, '%H:%M:%S') _handler = logging.StreamHandler() _handler.setFormatter(_formatter) logging.basicConfig(filename=os.path.join(get_path(), 'sp...
spfeas/errors.py
589
Raised when bands are corrupted
31
en
0.980146
import numpy as np from lab2.utils import get_random_number_generator # todo clean up the docstrings class BoxWindow: """[summary]BoxWindow class representing a virtual n-dimensional bounded Box""" def __init__(self, args): """[summary]Initialization of Box's parameters Args: ar...
src/lab2/box_window.py
7,578
[summary]BoxWindow class representing a virtual n-dimensional bounded Box [summary]BoxWindow class representing a virtual n-dimensional bounded Box [summary]This method tests if an element (args) is inside the box Args: args ([numpy array list]): [the element to test] Returns: [bool]: [True if the element is ...
3,443
en
0.606972
from setuptools import setup from torch.utils.cpp_extension import BuildExtension, CUDAExtension setup( name='ultmul', ext_modules=[ CUDAExtension( 'ultMul_cuda', [ 'ultMul_cuda.cpp', 'ultMul_cuda_kernel.cu', #.cpp and .cu file must have different name ])], cmdclass = { 'build_ext': BuildExtension } ...
setup.py
322
.cpp and .cu file must have different name
42
en
0.931738
#!/usr/bin/env python # Copyright Singapore-MIT Alliance for Research and Technology import random from town import Town_layout from company import Registrar_of_companies class Person: def __init__(self, city, attrs=None): self.name = "Person_%04d" % len(city.residents) city.residents.append(self...
dev/tools/snake-city/person.py
5,176
!/usr/bin/env python Copyright Singapore-MIT Alliance for Research and Technology slightly more male than female in this city 60 % of population are married 80 % of population own a car 90 % of spouses are also working. 80 % of population own a car child's age is between 1 to 18. If child is 7 years old or younger, th...
1,132
en
0.835137
# MIT License # # Copyright (C) IBM Corporation 2019 # # 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...
diffprivlib/__init__.py
1,656
Differential Privacy Library for Python ======================================= The IBM Differential Privacy Library is a library for writing, executing and experimenting with differential privacy. The Library includes a basic differential privacy mechanisms, the building blocks of differential privacy; tools for basi...
1,495
en
0.884933
#!/usr/bin/env python import telnetlib import time import socket import sys TELNET_PORT = 23 TELNET_TIMEOUT = 6 ## function def send_command(remote_conn, cmd): cmd = cmd.rstrip() remote_conn.write(cmd + '\n') time.sleep(1) return remote_conn.read_very_eager() def login(remote_conn, username, password): output...
Lesson2Number2a_telnetlib.py
1,144
!/usr/bin/env python function
29
ru
0.085511
import glob import numpy as np import os.path as osp from PIL import Image import random import struct from torch.utils.data import Dataset import scipy.ndimage as ndimage import cv2 from skimage.measure import block_reduce import json import scipy.ndimage as ndimage class ConcatDataset(Dataset ): def __init__(se...
nyuDataLoader.py
6,277
Permute the image list Read Image normalize the normal vector so that it will be unit length Read depth
103
en
0.782749
# -------------------------------------------------------- # Adapted from Faster R-CNN (https://github.com/rbgirshick/py-faster-rcnn) # Written by Danfei Xu # -------------------------------------------------------- """Compute minibatch blobs for training a Fast R-CNN network.""" import numpy as np import numpy.rando...
lib/roi_data_layer/minibatch.py
11,187
join all samples and produce sampled items Bounding-box regression targets are stored in a compact form in the roidb. This function expands those targets into the 4-of-4*K representation used by the network (i.e. only one class has non-zero targets). The loss weights are similarly expanded. Returns: bbox_target_d...
2,587
en
0.729649
from __future__ import division, print_function from openmdao.utils.assert_utils import assert_rel_error import unittest import numpy as np from openaerostruct.geometry.utils import generate_mesh from openaerostruct.geometry.geometry_group import Geometry from openaerostruct.aerodynamics.aero_groups import AeroPoint ...
openaerostruct/tests/test_multiple_aero_analysis.py
7,512
Create a dictionary to store options about the surface Wing definition name of the surface if true, model one half of wing reflected across the plane y = 0 how we compute the wing area, can be 'wetted' or 'projected' Aerodynamic performance of the lifting surface at an angle of attack of 0 (alpha=0). These CL0 and CD0 ...
2,174
en
0.808696
# Generated by Django 2.2.10 on 2020-04-12 20:48 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('staff', '0036_auto_20200407_1947'), ] operations = [ migrations.CreateModel( name='Messanger', fields=[ ...
micro_shop/staff/migrations/0037_messanger.py
650
Generated by Django 2.2.10 on 2020-04-12 20:48
46
en
0.594669
context = "https://www.w3.org/ns/activitystreams" class Actor: def __init__(self, user): self.user = user def render(self, base_url): actor = self.user.profile actor.update({ "@context": context, "preferredUsername": self.user.name, "id": self.us...
pubgate/renders.py
2,308
"sharedInbox": f"{base_url}/inbox" { "rel": "http://webfinger.net/rel/profile-page", "type": "text/html", "href": "{method}://mastodon.social/@user" }, { "rel": "magic-public-key", "href": self.user.key.to_magic_key() },
240
en
0.152623
import pytest from eth_utils import ( is_same_address, ) from web3.utils.events import ( get_event_data, ) # Ignore warning in pyethereum 1.6 - will go away with the upgrade pytestmark = pytest.mark.filterwarnings("ignore:implicit cast from 'char *'") @pytest.fixture() def Emitter(web3, EMITTER): retur...
tests/core/contracts/test_extracting_event_data_old.py
5,241
Ignore warning in pyethereum 1.6 - will go away with the upgrade
64
en
0.850932
# Generated by Django 3.1.4 on 2020-12-31 11:25 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='AsnDetailModel', fields=[ ('id', models.Aut...
asn/migrations/0001_initial.py
3,750
Generated by Django 3.1.4 on 2020-12-31 11:25
45
en
0.704868
# -*- coding: utf-8 -*- from __future__ import division, print_function, absolute_import import os import tensorflow as tf import math from dataloader.pretrained_weights.pretrain_zoo import PretrainModelZoo """ 2021-02-06 kl 74.00% 82.28% 77.92% 0.8 2021-02-06 kl 75.25% 80.61% 77.84% 0.75 2021-02-06 kl 71.98% 83....
libs/configs_old/ICDAR2015/kl/cfgs_res50_icdar2015_kl_v2.py
3,483
-*- coding: utf-8 -*- ------------------------------------------------ 'MobilenetV2' ---------------------------------------- System ------------------------------------------ Train and test allow 0~3 for gluoncv backbone if None, will not multipy if None, will not clip -------------------------------------------- Data...
669
en
0.345748
import os import re from pathlib import Path from logging import debug from cli_ui import debug as verbose from cli_ui import warning, fatal from jinja2 import Environment, FileSystemLoader from gitlabform import EXIT_INVALID_INPUT from gitlabform.configuration import Configuration from gitlabform.gitlab import GitL...
gitlabform/processors/project/files_processor.py
11,699
change or create file TODO: does this work? we are reading the content twice in this case... relative paths are relative to config file location perhaps your user permissions are ok to just perform this operation regardless of the branch protection... ...but if not, then we can unprotect the branch, but only if we know...
569
en
0.888396
from typing import Any, Dict, List, Union import numpy as np import logging import os # Create a custom logger logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) class RandomSearch: @staticmethod def random_choice(args: List[Any], n: int = 1): """ pick a random element from...
lr/hyperparameters.py
3,911
pick a random element from a set. Example: >> sampler = RandomSearch.random_choice(1,2,3) >> sampler() 2 pick a random integer between two bounds Example: >> sampler = RandomSearch.random_integer(1, 10) >> sampler() 9 pick a random float between two bounds, using loguniform distributio...
606
en
0.641318
import torch from tqdm import tqdm import torch.nn.functional as F from torch.utils.tensorboard import SummaryWriter import flask from flask import Flask, request from ...utils.deploy import get_free_tcp_port from ...utils.learning import adjust_learning_rate from ...utils.log import logger from ...base.module import...
lightnlp/tg/lm/module.py
8,565
print(dev_score_list) 进行分布式采样,以获得随机结果 获取topK个next个词的可能取值和对应概率
61
zh
0.787807
import concurrent.futures import threading from asyncio import coroutines from asyncio.events import AbstractEventLoop from asyncio.futures import Future import attr import uuid import asyncio from asyncio import ensure_future from typing import Any, Union, Coroutine, Callable, Generator, TypeVar, \ ...
merceedge/util/async_util.py
8,324
The context that triggered something. Chain two futures so that when one completes, so does the other. The result (or exception) of source will be copied to destination. If destination is cancelled, source gets cancelled too. Compatible with both asyncio.Future and concurrent.futures.Future. Copy state from another Fu...
1,574
en
0.790135
import requests import json import os import copy import smtplib import jwt from datetime import datetime, timedelta # SMTP 라이브러리 from string import Template # 문자열 템플릿 모듈 from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from django.core.validators import validate_email, ValidationErr...
app/user/example.py
9,725
e메일에 담길 컨텐츠 e메일 발송자 string template과 딕셔너리형 template_params받아 MIME 메시지를 만든다 호스트와 포트번호로 SMTP로 연결한다 발신자, 수신자리스트를 이용하여 보낼메시지를 만든다 e메일을 발송한다 SMTP 라이브러리 문자열 템플릿 모듈 email templete my settings from rest_framework.views import APIView def post(self, request): redirect('http://localhost:3000/') e메일 제목을 설정한다 e메일 제목을 설정한다 e메일...
580
ko
0.995581
# # Copyright (c) 2017 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...
rl_coach/filters/observation/observation_normalization_filter.py
4,318
Normalizes the observation values with a running mean and standard deviation of all the observations seen so far. The normalization is performed element-wise. Additionally, when working with multiple workers, the statistics used for the normalization operation are accumulated over all the workers. :param clip_min: The ...
1,467
en
0.804989
# Copyright (c) 2013 Mirantis 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 writ...
sahara/exceptions.py
6,116
General exception to use for invalid data A more useful message should be passed to __init__ which tells the user more about why the data is invalid. Base Exception for the project To correctly use this class, inherit from it and define a 'message' and 'code' properties. General wrapper object for swift client except...
1,144
en
0.847767
# -*- coding: utf-8 -*- # Generated by Django 1.10.8 on 2020-07-29 06:08 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('wildlifecompliance', '0495_auto_20200729_1345'), ] operations = [ migration...
wildlifecompliance/migrations/0496_auto_20200729_1408.py
690
-*- coding: utf-8 -*- Generated by Django 1.10.8 on 2020-07-29 06:08
68
en
0.557522
from django.db import models from django.db.models.query import QuerySet, Q from django.db.models.base import ModelBase from django.db.models.fields.related import RelatedField from django.conf import settings from utils import NestedSet from signals import pre_publish, post_publish # this takes some inspiration from...
publish/models.py
19,660
Get the "through" model associated with this field. Need to handle things differently for Django1.1 vs Django1.2 In 1.1 through is a string and through_model has class In 1.2 through is the class all draft objects that have not been published yet all draft objects that have not been published yet override delete so tha...
2,610
en
0.948738
import datetime import numpy as np import os import pandas as pd import psycopg2 from dotenv import load_dotenv, find_dotenv from flask import current_app as app from flask import json, jsonify, request load_dotenv() ####################################################################################################...
routes.py
48,846
Verifies the connection to the db. Pulling all the data from tables. print("\nSELECT * Query Excecuted.") print("\nSELECT * Query Excecuted.") print("\nSELECT * Query Excecuted.") print("Cursor and Connection Closed.") print("\nSELECT * Query Excecuted.") print("\nSELECT * Query Excecuted.") print("\nSELECT * Quer...
933
en
0.683277
from dagster import check from dagster.core.types.marshal import PickleSerializationStrategy from .errors import DagstermillError, DagsterUserCodeExecutionError from .manager import Manager, MANAGER_FOR_NOTEBOOK_INSTANCE from .serialize import SerializableRuntimeType, read_value from .solids import define_dagstermill_...
python_modules/dagstermill/dagstermill/__init__.py
2,997
Explicitly yield a dagster event such as a Materialization or ExpectationResult Explicitly yield a Output. Args: value (Any): The value of the Output to yield. output_name (Optional[str]): The name of the Output to yield. Default: 'result'. magic incantation for syncing up notebooks to enclosing virtual...
448
en
0.638635
from __future__ import unicode_literals from django.contrib import admin from django.conf import settings from django.conf.urls import url from django import forms from django.core.urlresolvers import reverse from django.contrib.admin.utils import quote from django.utils.translation import ugettext_lazy as _, ugettext...
widgy/contrib/widgy_mezzanine/admin.py
17,799
A proxy for WidgyPage, just to allow registering WidgyPage twice with a different ModelAdmin. Version trackers that have no references and whose content type is allowed by our field can be restored. the status of a page before it's created, on the add page else: If we are reviewed, we'll have to wait for approval. Ha...
2,144
en
0.872193
# Using a combination of list subsetting and variable assignment, create a new variable, eat_sleep_area, that contains the sum of the area of the kitchen and the area of the bedroom. # Print the new variable eat_sleep_area. # Create the areas list areas = ["hallway", 11.25, "kitchen", 18.0, "living room", 20.0, "bedro...
Chapter2-1-Lists/Subset.py
497
Using a combination of list subsetting and variable assignment, create a new variable, eat_sleep_area, that contains the sum of the area of the kitchen and the area of the bedroom. Print the new variable eat_sleep_area. Create the areas list Sum of kitchen and bedroom area: eat_sleep_area Print the variable eat_sleep_a...
323
en
0.782588
# Copyright (c) Facebook, Inc. and its affiliates. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ...
data/task_scripts/main/task01002.py
4,367
Catapult Copyright (c) Facebook, Inc. and its affiliates. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed ...
640
en
0.870473
from pyalgotrade import strategy from pyalgotrade import dataseries from pyalgotrade.dataseries import aligned from pyalgotrade import plotter from pyalgotrade.tools import yahoofinance from pyalgotrade.stratanalyzer import sharpe import numpy as np import statsmodels.api as sm def get_beta(values1, values2): # ...
samples/statarb_erniechan.py
5,928
http://statsmodels.sourceforge.net/stable/regression.html We're going to use datetime aligned versions of the dataseries. These are used only for plotting purposes. These is used only for plotting purposes. Buy spread when its value drops below 2 standard deviations. Short spread when its value rises above 2 standard d...
349
en
0.832961
# Generated by Django 2.1.9 on 2020-02-13 15:15 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0009_alter_user_last_name_max_length'), ('stores', '0001_initial'), ] operation...
apps/users/migrations/0001_initial.py
2,117
Generated by Django 2.1.9 on 2020-02-13 15:15
45
en
0.590658
# (c) 2014, Michael DeHaan <michael.dehaan@gmail.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any lat...
dev/ref/display.py
19,343
This is a filter which injects the current user as the 'user' attribute on each record. We need to add this filter to all logger handlers so that 3rd party libraries won't print an exception due to user not being defined. Prints a header-looking line with cowsay or stars with length depending on terminal width (3 minim...
3,666
en
0.855882
import os # Defaults to where the code is contained. # If your bokeh input data is placed elsewhere, go ahead and edit this path ROOT = os.path.dirname(os.path.realpath(__file__)) ROOT = os.path.abspath(os.path.join(ROOT, '..')) # Intermediate bokeh files are cached under this path CACHE_DIR = os.path.join(ROOT, 'cac...
multimodal_affinities/common_config.py
640
Defaults to where the code is contained. If your bokeh input data is placed elsewhere, go ahead and edit this path Intermediate bokeh files are cached under this path Bokeh inputs will be loaded from the following path Default font embedding location, used when not specified explicitly
286
en
0.768014
# snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] # snippet-sourcedescription:[rekognition-image-python-create-collection.py demonstrates how to create an Amazon Rekognition collection.] # snippet-service:[rekognition] # snippet-keyword:[Amazon Rekognition] # snippet-keyword:[...
python/example_code/rekognition/rekognition-image-python-create-collection.py
1,708
snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] snippet-sourcedescription:[rekognition-image-python-create-collection.py demonstrates how to create an Amazon Rekognition collection.] snippet-service:[rekognition] snippet-keyword:[Amazon Rekognition] snippet-keyword:[Python] snippe...
1,215
en
0.739337
from IMLearn.utils import split_train_test from IMLearn.learners.regressors import LinearRegression from IMLearn.metrics import * from typing import NoReturn import numpy as np import pandas as pd import plotly.graph_objects as go import plotly.express as px import plotly.io as pio pio.templates.default = "simple_whi...
exercises/house_price_prediction.py
4,886
Create scatter plot between each feature and the response. - Plot title specifies feature name - Plot title specifies Pearson Correlation between feature and response - Plot saved under given folder with file name including feature name Parameters ---------- X : DataFrame of shape (n_samples, n_features) ...
1,393
en
0.864788
from fastapi import APIRouter, HTTPException import pandas as pd import plotly.express as px import json from dotenv import load_dotenv import os import psycopg2 from sqlalchemy import create_engine from sqlalchemy.types import Integer, Float, Text, String, DateTime from fastapi.encoders import jsonable_encoder from os...
project/app/api/wage_trade_transport_viz.py
5,721
Opens county_city.json file, converts to .json object and returns it Create a SQL query to grab only the user queried cities' data from the covid table in the DB. Output: subset grouped DF by month and city with only queried cities give full path to .env LOAD environment variables GET .env vars CONNECTION Engine with...
570
en
0.786433
my_data=[['slashdot','USA','yes',18,'None'], ['google','France','yes',23,'Premium'], ['digg','USA','yes',24,'Basic'], ['kiwitobes','France','yes',23,'Basic'], ['google','UK','no',21,'Premium'], ['(direct)','New Zealand','no',12,'None'], ['(direct)','UK','no',21,'Basic'], ...
CollectiveIntelligence/chapter7/treepredict.py
7,135
Divides a set on a specific column. Can handle numeric or nominal values Make a function that tells us if a row is in the first group (true) or the second group (false) Divide the rows into two sets and return them Create counts of possible results (the last column of each row is the result) The result is the last co...
1,099
en
0.821739
import re import requests import time class TeleBot(object): def __init__(self, import_name): self.import_name = import_name self.update_rules = list() self.config = dict( api_key=None, requests_kwargs=dict( timeout=60, ), ) ...
telebot/__init__.py
6,684
Requests bot information based on current api_key, and sets self.whoami to dictionary with username, first_name, and id of the configured bot. A simple method for testing your bot's auth token. Requires no parameters. Returns basic information about the bot in form of a `User object. These should also be in the config ...
1,447
en
0.854247
#!/usr/bin/python3 import sys import boto3 import requests import getpass import configparser import base64 import logging import xml.etree.ElementTree as ET import re import pytz from tzlocal import get_localzone from datetime import datetime from bs4 import BeautifulSoup from os.path import expanduser from urllib.pa...
samlapi_formauth_adfsv3mod_python3.py
7,874
!/usr/bin/python3 Variables region: The default AWS region that this script will connect to for all API calls output format: The AWS CLI output format that will be configured in the saml profile (affects subsequent CLI calls) awsconfigfile: The file where this script will store the temp credentials under the saml profi...
2,873
en
0.806065
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Bioindustrial-Park: BioSTEAM's Premier Biorefinery Models and Results # Copyright (C) 2020-, Yalin Li <mailto.yalin.li@gmail.com> # # This module is under the UIUC open-source license. See # github.com/BioSTEAMDevelopmentGroup/biosteam/blob/master/LICENSE.txt # for licen...
BioSTEAM 2.x.x/biorefineries/ethanol_adipic/systems.py
11,557
References ---------- [1] Humbird et al., Process Design and Economics for Biochemical Conversion of Lignocellulosic Biomass to Ethanol: Dilute-Acid Pretreatment and Enzymatic Hydrolysis of Corn Stover; Technical Report NREL/TP-5100-47764; National Renewable Energy Lab (NREL), 2011. https://www.nrel.gov...
2,203
en
0.580367
#!/usr/bin/env python3 # Copyright 2016 The Meson development team # 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 appli...
mesonbuild/rewriter.py
43,393
!/usr/bin/env python3 Copyright 2016 The Meson development team 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 agr...
3,639
en
0.821005
from switch import Switch class Link(): def __init__(self, lid, init_capacity, delay): self.lid = lid self.init_capacity = init_capacity self.capacity = init_capacity self.end1 = "None" self.end2 = "None" self.delay = delay self.level = "None" self._edges = [] # attach a link between...
substrate_network/link.py
957
attach a link between a server and a switch, or between two switches
68
en
0.969685
# ------------------------------------------------------------------------------------------------- # scientific import numpy as np import pandas as pd # ------------------------------------------------------------------------------------------------- # PyQuantum.TC from PyQuantum.TC_sink.WaveFunction import WaveFuncti...
PyQuantum/TC_sink/DensityMatrix.py
3,838
------------------------------------------------------------------------------------------------- scientific ------------------------------------------------------------------------------------------------- PyQuantum.TC ------------------------------------------------------------------------------------------------- Py...
2,401
en
0.141803
from common import num_range_scale from neurons_engine import neurons_request, neurons_blocking_read, neurons_blocking_read INQUIRE_ID = 0x00 SHAKE_ID = 0x01 ACC_X_ID = 0x02 ACC_Y_ID = 0x03 ACC_Z_ID = 0x04 GYRO_X_ID = 0x05 GYRO_Y_ID = 0x06 GYRO_Z_ID = 0x07 PITCH_ID = 0x08 ROLL_ID = 0x09 ROTATE_Z_ID = 0x0a ROTATE_X_ID...
src/neurons_engine/mbuild_modules/motion_sensor.py
5,014
// 9.4 = 9.8 * cos(15)
22
pt
0.240798
#!/usr/bin/env python # -*- coding:utf-8 -*- # 生成词云 ''' Reference: https://amueller.github.io/word_cloud/ https://github.com/amueller/word_cloud ''' from wordcloud import WordCloud import matplotlib.pyplot as plt filename = "***.txt" # 文本 with open(filename) as f: mytext = f.read() # print(mytext) w...
funnyPython/test_wordcloud.py
465
Reference: https://amueller.github.io/word_cloud/ https://github.com/amueller/word_cloud !/usr/bin/env python -*- coding:utf-8 -*- 生成词云 文本 print(mytext) 隐藏坐标
174
en
0.388554
# 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...
research/gan/mnist/conditional_eval.py
3,963
Evaluates a conditional TFGAN trained MNIST model. 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/LIC...
981
en
0.819736
#!/usr/bin/env python3 # # Copyright (c) 2020 The Bitcoin ABC developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. from base64 import b64encode import mock import os import unittest from phabricator_wrapper import BITCOIN_A...
contrib/buildbot/test/test_phabricator.py
17,919
!/usr/bin/env python3 Copyright (c) 2020 The Bitcoin ABC developers Distributed under the MIT software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. No diff associated to the revision 2 diffs associated with the revision. Ordering is guaranteed by the "order" request ...
1,224
en
0.917501
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** 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, Mapping, Optional, Sequence, Union from .. import _utilities, _tables __al...
sdk/python/pulumi_azure_nextgen/sql/firewall_rule.py
6,833
Represents a server firewall rule. API Version: 2014-04-01. :param str resource_name: The name of the resource. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[str] end_ip_address: The end IP address of the firewall rule. Must be IPv4 format. Must be greater than or equal to startIpAd...
1,832
en
0.756234
import os import numpy as np import pandas as pd from gym.utils import seeding import gym from gym import spaces import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import pickle from stable_baselines3.common.vec_env import DummyVecEnv, SubprocVecEnv from stable_baselines3.common import l...
env/env_stocktrading.py
15,988
A stock trading environment for OpenAI gym initalize state initialize reward memorize all the total balance changeself.reset() perform sell action based on the sign of the actionupdate balance perform sell action based on the sign of the action if turbulence goes over threshold, just clear out all positions update ba...
1,308
en
0.709424
# -*- coding: UTF-8 -*- import os import sys import jieba import json import numpy as np from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import cosine_similarity class SinglePassCluster(): def __init__(self, stopWords_path="../data/stop_words.txt", my_stopwords=None, ...
Single_Pass/single_pass_cluster.py
3,217
-*- coding: UTF-8 -*- [cluster_center_vec, ] {文本id: text, } {cluster_id: [text_id, ]} save self.cluster_2_idx print(len(tfidf), len(tfidf[0])) 开始遍历 初始化,没有中心生成 存在簇
162
zh
0.31579
from functools import wraps import numpy as np import tensorflow as tf from keras import backend as K from keras.layers import Conv2D, Add, ZeroPadding2D, UpSampling2D, Concatenate, MaxPooling2D from keras.layers.advanced_activations import LeakyReLU from keras.layers.normalization import BatchNormalization from keras...
nets/yolo4.py
9,627
-------------------------------------------------- 单次卷积----------------------------------------------------------------------------------------------------- 卷积块 DarknetConv2D + BatchNormalization + LeakyReLU------------------------------------------------------------------------------------------------------ 特征...
1,558
zh
0.343854
from hy.macros import macroexpand from hy.compiler import HyTypeError from hy.lex import tokenize def test_reader_macro_error(): """Check if we get correct error with wrong disptach character""" try: macroexpand(tokenize("(dispatch_reader_macro '- '())")[0], __name__) except HyTypeError as e: ...
tests/macros/test_reader_macros.py
366
Check if we get correct error with wrong disptach character
59
en
0.681651
# -*- coding: utf-8 -*- import os import unittest from StringIO import StringIO import antlr3 class TestStringStream(unittest.TestCase): """Test case for the StringStream class.""" def testSize(self): """StringStream.size()""" stream = antlr3.StringStream('foo') self.failUnlessEqua...
libs/antlr-3.0.1/runtime/Python/unittests/teststreams.py
17,745
Test case for the StringStream class. Test case for the FileStream class. Test case for the InputStream class. Test case for the StringStream class. Setup test fixure The constructor of CommonTokenStream needs a token source. This is a simple mock class providing just the nextToken() method. StringStream.consume() Com...
1,593
en
0.619883
# coding=utf-8 """ This code was generated by \ / _ _ _| _ _ | (_)\/(_)(_|\/| |(/_ v1.0.0 / / """ from twilio.base import deserialize from twilio.base import values from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base....
lib/python2.7/site-packages/twilio/rest/api/v2010/account/call/feedback.py
11,259
Constructs a FeedbackContext :returns: twilio.rest.api.v2010.account.call.feedback.FeedbackContext :rtype: twilio.rest.api.v2010.account.call.feedback.FeedbackContext Initialize the FeedbackList :param Version version: Version that contains the resource :param account_sid: The account_sid :param call_sid: A 34 charac...
4,118
en
0.544294
import xgboost as xgb import testing as tm import numpy as np import unittest rng = np.random.RandomState(1994) class TestFastHist(unittest.TestCase): def test_fast_hist(self): tm._skip_if_no_sklearn() from sklearn.datasets import load_digits try: from sklearn.model_selection ...
tests/python/test_fast_hist.py
4,083
fail-safe test for dense data fail-safe test for max_bin=2
58
en
0.689309
def test_List(): a: i32 b: i32 a = [1, 2, 3] a = [-3, -2, -1] a = ["a", "b", "c"] a = [[1, 2, 3], [4, 5, 6]] # a = [-2, -1, 0.45] -> semantic error b = a[2]
tests/list1.py
191
a = [-2, -1, 0.45] -> semantic error
36
en
0.3994
import json import os import uuid from datetime import datetime, timedelta, timezone from decimal import Decimal from unittest import mock from django.contrib.auth import get_user_model from django.core.files.uploadedfile import SimpleUploadedFile from django.test import override_settings from django.urls import rever...
app/request_shoutout/adapters/tests/test_fulfill_shoutout_request.py
14,147
noqa: E501 noqa: E501 noqa: E501
32
uz
0.340705