content
stringlengths
27
928k
path
stringlengths
4
230
size
int64
27
928k
nl_text
stringlengths
21
396k
nl_size
int64
21
396k
nl_language
stringlengths
2
3
nl_language_score
float64
0.04
1
import os import subprocess import sys import shutil import json import argparse import git import getpass import time import platform PKG_ROOT = 'lmctl' PKG_INFO = 'pkg_info.json' DIST_DIR = 'dist' WHL_FORMAT = 'lmctl-{version}-py3-none-any.whl' DOCS_FORMAT = 'lmctl-{version}-docs' DOCS_DIR = 'docs' DOCKER_IMG_TAG = ...
build.py
10,406
Legit python error thrown Give the whl some time to be indexed on pypi Requires the whl to have been pushed Note that a system running on Mac will return 'Darwin' for platform.system()
184
en
0.830758
"""Define AWS storage backends for media files.""" from storages.backends.s3boto3 import S3Boto3Storage def MediaBackend(): """Media storage backend.""" return S3Boto3Storage(location="media")
aws/backends.py
204
Media storage backend. Define AWS storage backends for media files.
67
en
0.552427
# -*- coding: utf-8 -*- # Generated by Django 1.9.8 on 2017-03-04 14:15 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('talk', '0010_auto_20170304_1500'), ] operations = [ migrations.AlterModelOpt...
devday/talk/migrations/0011_auto_20170304_1515.py
1,040
-*- coding: utf-8 -*- Generated by Django 1.9.8 on 2017-03-04 14:15
67
en
0.741615
#-*- coding: utf-8 -*- """ what : process data, generate batch """ import numpy as np import pickle import random from project_config import * class ProcessDataText: # store data train_set = [] dev_set = [] test_set = [] def __init__(self, data_path): self.data_path = d...
model/process_data_text.py
3,314
-*- coding: utf-8 -*- store data load data Get a random batch of encoder and encoderR inputs from data, pad them if needed train case - random sampling dev, test case = ordered data won't be evaluated find the pad index pad exists no-pad
238
en
0.72632
# 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 from...
sdk/python/pulumi_azure_native/insights/v20170401/action_group.py
11,705
An action group resource. :param str resource_name: The name of the resource. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[str] action_group_name: The name of the action group. :param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['AutomationRunbookReceiverArgs']]]] automation...
2,934
en
0.787156
""" Area Weighted Interpolation """ import numpy as np import geopandas as gpd from ._vectorized_raster_interpolation import _fast_append_profile_in_gdf import warnings from scipy.sparse import dok_matrix, diags, coo_matrix import pandas as pd import os from tobler.util.util import _check_crs, _nan_check, _inf_check...
tobler/area_weighted/area_interpolate.py
22,011
Area interpolation for extensive and intensive variables. Parameters ---------- source_df : geopandas.GeoDataFrame (required) geodataframe with polygon geometries target_df : geopandas.GeoDataFrame (required) geodataframe with polygon geometries extensive_variables : list, (optional) columns in dataframes ...
9,502
en
0.69278
# 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/recoveryservices/azure-mgmt-recoveryservicessiterecovery/azure/mgmt/recoveryservicessiterecovery/aio/operations/_replication_jobs_operations.py
32,783
ReplicationJobsOperations 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.recoveryservicessiterecove...
2,864
en
0.436224
"""Tuya Air Quality sensor.""" from zigpy.profiles import zha from zigpy.quirks import CustomDevice from zigpy.zcl.clusters.general import Basic, GreenPowerProxy, Groups, Ota, Scenes, Time from zhaquirks.const import ( DEVICE_TYPE, ENDPOINTS, INPUT_CLUSTERS, MODELS_INFO, OUTPUT_CLUSTERS, PROFI...
zhaquirks/tuya/air/ts0601_air_quality.py
5,649
Tuya Air quality device. Tuya Air quality device with GPP. Tuya Air Quality sensor. NodeDescriptor(logical_type=<LogicalType.Router: 1>, complex_descriptor_available=0, user_descriptor_available=0, reserved=0, aps_flags=0, frequency_band=<FrequencyBand.Freq2400MHz: 8>, mac_capability_flags=<MACCapabilityFlags.Allocat...
1,968
en
0.300882
# -*- coding: utf-8 -*- from .ExactDate import ExactDate from .JieQi import JieQi from .NineStar import NineStar from .EightChar import EightChar from .ShuJiu import ShuJiu from .Fu import Fu from .Solar import Solar from .SolarWeek import SolarWeek from .SolarMonth import SolarMonth from .SolarSeason import SolarSeaso...
lunar_python/__init__.py
551
-*- coding: utf-8 -*-
21
en
0.767281
""" Training and validation method for arbitrary models. """ import io import os import sys import time from keras import Sequential from keras.layers import Dense, Dropout, BatchNormalization from matplotlib.backends.backend_pdf import PdfPages import matplotlib.pyplot as plt import matplotlib.ticker as ticker impo...
vl/model/training.py
9,568
Build and return a Sequential model with Dense layers given by the layers argument. Arguments model (keras.Sequential) model to which layers will be added input_dim (int) dimension of input layers (tuple) sequence of 2-ples, one per layer, such as ((64, 'relu'), (64, 'relu'), (1, 'sigmoid')) Ret...
2,965
en
0.570718
import unittest import os import grp from myDevices.sensors import sensors from myDevices.devices import manager from myDevices.utils.config import Config from myDevices.utils import types from myDevices.utils.logger import exception, setDebug, info, debug, error, logToFile, setInfo from myDevices.devices.bus import ch...
myDevices/test/sensors_test.py
8,392
if len(sensor_data) < 5: info('OnDataChanged: {}'.format(sensor_data)) else: info('OnDataChanged: {}'.format(len(sensor_data)))Test adding a sensorAttempt to remove device if it already exists from a previous testTest updating a sensorTest removing a sensorTest setting sensor valuesTest getting analog value
316
en
0.356434
"""fix_parser.py - parse V1.0 fixprotocol sbe xml files described by xsd https://github.com/FIXTradingCommunity/ fix-simple-binary-encoding/blob/master/v1-0-STANDARD/resources/sbe.xsd """ import xml.etree.ElementTree as etree from pysbe.schema.constants import ( SBE_TYPES_TYPE, STRING_ENUM_MAP, VAL...
pysbe/parser/fix_parser.py
16,290
contains shared functionality parse message definitions Parser for VFIX parse type definitions parse a file convert byteOrder to enum parse and return dict of common attributes parse and return an enum validvalue parse child elements that fit in a fieldCollection parse message, can be repeated parse field Type parse fi...
1,016
en
0.522969
""" Created on Jan 24, 2014 @author: StarlitGhost """ from twisted.plugin import IPlugin from desertbot.moduleinterface import IModule from desertbot.modules.commandinterface import BotCommand from zope.interface import implementer from urllib.parse import quote from desertbot.message import IRCMessage from desertbo...
desertbot/modules/commands/Urban.py
3,312
Created on Jan 24, 2014 @author: StarlitGhost
46
en
0.492963
from .base import * # noqa from .base import env # GENERAL # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/dev/ref/settings/#secret-key SECRET_KEY = env('DJANGO_SECRET_KEY') # https://docs.djangoproject.com/en/dev/ref/settings/#allowed-hosts ALLOWED...
config/settings/production.py
7,942
noqa GENERAL ------------------------------------------------------------------------------ https://docs.djangoproject.com/en/dev/ref/settings/secret-key https://docs.djangoproject.com/en/dev/ref/settings/allowed-hosts DATABASES ------------------------------------------------------------------------------ noqa F405 no...
3,846
en
0.506506
# Copyright 2018 Canonical 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 required by applicable law or agreed to in writing, s...
unit_tests/test_lib_charm_openstack_api_crud.py
22,317
Copyright 2018 Canonical 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 required by applicable law or agreed to in writing, software distribute...
713
en
0.863441
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'searchform.ui' # # Created by: PyQt5 UI code generator 5.6 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_searchForm(object): def setupUi(self, searchForm): ...
searchform.py
4,433
-*- coding: utf-8 -*- Form implementation generated from reading ui file 'searchform.ui' Created by: PyQt5 UI code generator 5.6 WARNING! All changes made in this file will be lost!
181
en
0.842276
# Copyright (c) Contributors to the aswf-docker Project. All rights reserved. # SPDX-License-Identifier: Apache-2.0 """ CI Image and Package Builder """ import logging import subprocess import json import os import tempfile import typing from aswfdocker import constants, aswfinfo, utils, groupinfo, index logger = log...
python/aswfdocker/builder.py
12,010
Builder generates a "docker buildx bake" json file to drive the parallel builds of Docker images. CI Image and Package Builder Copyright (c) Contributors to the aswf-docker Project. All rights reserved. SPDX-License-Identifier: Apache-2.0 Only one version per image needed Only bake images for ci_common!
306
en
0.772057
# Mu Young # Balrog Entry from net.swordie.ms.constants import BossConstants from net.swordie.ms.constants import GameConstants options = { 0 : BossConstants.BALROG_EASY_BATTLE_MAP, 1 : BossConstants.BALROG_HARD_BATTLE_MAP } if not sm.isPartyLeader(): sm.sendSayOkay("Please have your party leader speak to me..") e...
scripts/npc/balog_accept.py
858
Mu Young Balrog Entry
21
en
0.327561
# # # Needs to be expanded to accommodate the common occurrence of sparse.multiSparse objects in the geounitNode class vs pure numpy arrays # # import os import sys # If there is __init__.py in the directory where this file is, then Python adds das_decennial directory to sys.path # automatically. Not sure why and how ...
programs/engine/unit_tests/json_nodes_test.py
2,920
Needs to be expanded to accommodate the common occurrence of sparse.multiSparse objects in the geounitNode class vs pure numpy arrays If there is __init__.py in the directory where this file is, then Python adds das_decennial directory to sys.path automatically. Not sure why and how it works, therefore, keeping the fol...
2,363
en
0.456128
""" Copyright June 25, 2020 Richard Koshak 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,...
time_utils/automation/lib/python/community/time_utils.py
9,138
Takes a Python timedelta Object and converts it to a ZonedDateTime from now. Arguments: - td: The Python datetime.timedelta Object Returns: A ZonedDateTime td from now. Returns True if dt_str conforms to ISO 8601 Arguments: - dt_str: the String to check Returns: True if dt_str conforms to dt_str and F...
3,780
en
0.643744
""" Copyright (C) 2020 Vanessa Sochat. 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/. """ import shutil import os here = os.path.abspath(os.path.dirname(__file__)) def...
gridtest/templates/__init__.py
937
Given a template name and a destination directory, copy the template to the desination directory. Given the name of a template (an entire folder in the directory here) Return the full path to the folder, with the intention to copy it somewhere. Copyright (C) 2020 Vanessa Sochat. This Source Code Form is subject to the...
473
en
0.861852
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Display a calendar populated from google calendar data on an inky display.""" from PIL import Image, ImageDraw # type: ignore # from typing import Tuple # import time def draw_what_sheet(image: Image.Image) -> None: """Draw a calendar page for a WHAT display. ...
inky_calendar.py
1,272
Draw a calendar page for a WHAT display. Args: image: The image to be drawn on to Display a calendar populated from google calendar data on an inky display. !/usr/bin/env python3 -*- coding: utf-8 -*- type: ignore from typing import Tuple import time draw.rectangle([(7, 3), (392, 296)], outline=1) type: ignore
317
en
0.59264
""" Utility functions. """ import tensorflow as tf def get_shape(tensor, dynamic=False): """ Return shape of the input tensor without batch size. Parameters ---------- tensor : tf.Tensor dynamic : bool If True, returns tensor which represents shape. If False, returns list of ints and/or...
batchflow/models/tf/utils.py
2,468
Return batch size (the length of the first dimension) of the input tensor. Parameters ---------- tensor : tf.Tensor Returns ------- batch size : int or None Return the integer channels axis based on string data format. Return number of channels in the input tensor. Parameters ---------- tensor : tf.Tensor Returns ...
1,118
en
0.342493
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (c) 2011 Citrix Systems, Inc. # Copyright 2011 OpenStack 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 # # htt...
nova/tests/vmwareapi/db_fakes.py
3,712
Stubs out for model. Stubs out the db.instance_create method. Stubs out the db.network_get_by_instance method. Stubs out the db API for creating Instances. Stubouts, mocks and fixtures for the test suite vim: tabstop=4 shiftwidth=4 softtabstop=4 Copyright (c) 2011 Citrix Systems, Inc. Copyright 2011 OpenStack LLC. ...
867
en
0.831833
#!/usr/bin/env python3 import socket from util import ip4_range import unittest from framework import tag_fixme_vpp_workers from framework import VppTestCase, VppTestRunner from template_bd import BridgeDomain from scapy.layers.l2 import Ether from scapy.packet import Raw from scapy.layers.inet import IP, UDP from sc...
test/test_gtpu.py
15,195
GTPU Test Case GTPU UDP ports Test Case add or del tunnels to test gtpu stability add or del tunnels sharing the same mcast dst to test gtpu ref_count mechanism Decapsulate the original payload frame by removing GTPU header Encapsulate the original payload frame by adding GTPU header with its UDP, IP and Ethernet fie...
2,452
en
0.734548
# Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. import json import os from tornado import web from .. import _load_handler_from_location from ...utils import clean_filename from ...utils import quote from ...utils import response_text from ...utils import url_path_...
nbviewer/providers/gist/handlers.py
12,613
render a gist notebook, or list files if a multifile gist redirect old /<gist-id> to new /gist/<gist-id> list a user's gists containing notebooks .ipynb file extension is required for listing (not for rendering). Tornado handlers provider_url: str URL to the notebook document upstream at the provider (e.g., GitHub...
1,881
en
0.73728
#!/usr/bin/env python import h5py f = h5py.File('H11302_OLS_OSS/H11302_2m_1.bag') print f.listobjects() print f.listitems() bag_root = f['/BAG_root'] metadata = ''.join(bag_root['metadata']) o = file('metadata.xml','w') o.write(metadata) del o #print metadata #[0:200] elevation = bag_root['elevation'] print 'sh...
bag.py
812
!/usr/bin/env pythonprint metadata [0:200]print type(data)print dataimport matplotlib.mlab as mlabimport matplotlib.pyplot as pltfor x,z in enumerate(elevation[y]):o.write('{x} {y} {z}\n'.format(x=x,y=y,z=z))
208
en
0.353179
#!/usr/bin/env python3 # # Cross Platform and Multi Architecture Advanced Binary Emulation Framework # from typing import Sequence from pefile import PE from qiling.const import QL_ARCH from qiling.exception import QlErrorArch, QlMemoryMappedError from qiling.loader.loader import QlLoader from qiling.os.memory import...
qiling/qiling/loader/pe_uefi.py
11,456
Call a function after properly setting up its arguments and return address. Args: addr : function address args : a sequence of arguments to pass to the function; may be empty ret : return address; may be None Start the execution of a UEFI module. Args: image_base : module base address entry_poin...
2,530
en
0.787869
from __future__ import annotations from datetime import timedelta import itertools import numpy as np import pytest from pandas.compat import ( IS64, is_platform_windows, ) import pandas as pd import pandas._testing as tm ############################################################### # Index / Series comm...
pandas/tests/indexing/test_coercion.py
40,212
test coercion triggered by fillna test coercion triggered by insert test index's coercion triggered by assign key test series value's coercion triggered by assignment test coercion triggered by where Object we will pass to `Series.replace` Index / Series common tests which may trigger dtype coercions Iterate over com...
1,641
en
0.80348
# -*- coding: utf-8 -*- """ Profile: http://hl7.org/fhir/StructureDefinition/Task Release: R4 Version: 4.0.1 Build ID: 9346c8cc45 Last updated: 2019-11-01T09:29:23.356+11:00 """ import typing from pydantic import Field, root_validator from pydantic.error_wrappers import ErrorWrapper, ValidationError from pydantic.erro...
fhir/resources/task.py
76,669
Disclaimer: Any field name ends with ``__ext`` does't part of Resource StructureDefinition, instead used to enable Extensibility feature for FHIR Primitive Data Types. A task to be performed. Disclaimer: Any field name ends with ``__ext`` does't part of Resource StructureDefinition, instead used to enable Extensibilit...
13,263
en
0.800534
# -*- coding: utf-8 -*- """ Parser elements. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import collections import copy import logging import re from lxml.builder import E import six import types log = loggi...
chemdataextractor_batteries/chemdataextractor/parse/elements.py
23,526
Match all in the given order. Can probably be replaced by the plus operator '+'? Always match a single token. Abstract base parser element class. Match at end of tokens. Match the first. Check ahead if matches. Example:: Tn + FollowedBy('Neel temperature') Tn will match only if followed by 'Neel temperature',...
6,471
en
0.795657
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from typing import Callable, List, NamedTuple, Tuple import numpy as np import plotly.graph_objs as go import torch from torch import Tenso...
src/beanmachine/ppl/diagnostics/common_plots.py
3,289
this function executes a plot-related function, passed as input parameter func, and outputs a tuple including plotly object and its corresponding legend. this function gets results prepared by a plot-related function and outputs a tuple including plotly object and its corresponding legend. Copyright (c) Meta Platform...
526
en
0.869554
# Copyright (C) 2014-2018 DLR # # All rights reserved. This program and the accompanying materials are made # available under the terms of the Eclipse Public License v1.0 which # accompanies this distribution, and is available at # http://www.eclipse.org/legal/epl-v10.html # # Contributors: # Annika Wollschlaeger <anni...
source/rafcon/core/states/barrier_concurrency_state.py
19,135
The barrier concurrency holds a list of states that are executed in parallel. It waits until all states finished their execution before it returns. Note: In the backward execution case the decider state does not have to be backward executed, as it only decides the outcome of the barrier concurrency state. In a backwar...
5,857
en
0.863215
from __future__ import absolute_import, print_function, unicode_literals import pickle from builtins import dict, str import os import re import boto3 import logging import botocore.session from time import sleep import matplotlib as mpl from numpy import median, arange, array from indra.tools.reading.util.reporter ...
indra/tools/reading/submit_reading_pipeline.py
48,204
Create a timedelta or datetime object from default string reprs. Updates teh job_log_dict. Get the name of the ecs cluster using the batch client. Produce a report of the batch jobs. Set the options of reading job. Set the options for this run. Submit a batch job to combine the outputs of a reading job. This function ...
5,311
en
0.835529
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models, _ from odoo.exceptions import ValidationError, UserError from odoo.addons import decimal_precision as dp from odoo.tools import float_is_zero class EventType(models.Model): _i...
addons/event_sale/models/event.py
12,123
Determine reserved, available, reserved but unconfirmed and used seats. Override to add sale related stuff Compute a multiline description of this ticket, in the context of sales. It will often be used as the default description of a sales order line referencing this ticket. 1. the first line is the ticket name ...
1,339
en
0.931195
#Written by Shitao Tang # -------------------------------------------------------- import connectDB import time,hashlib,logging def sign_up(username,password): db=connectDB.database.getInstance() if len(username)<=20: return db.create_account(username,hashlib.sha224(password).hexdigest()) else: ...
main_server/common.py
6,012
Written by Shitao Tang --------------------------------------------------------check whether a dictionary contains a list of keystry to convert value to a float number and is between min_value and max_valueget the bounding box of the object in an imageprint xmlthe following code is copied from github
301
en
0.748433
import random import string from pathlib import Path r""" In the root folder $ pytest tests --template fastapi_plan\template Where `template` is path to folder with `cookiecutter.json` file See https://github.com/hackebrot/pytest-cookies Or example tests here https://github.com/audreyfeldroy/cookiecutter-pypackage...
tests/test_fastapi_plan.py
2,724
the rest in top level the rest in top level
43
en
0.738189
class Solution: def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]: total_node_count = n if total_node_count == 1: # Quick response for one node tree return [0] # build adjacency matrix adj_matrix = defaultdict...
Leetcoding-Actions/Explore-Monthly-Challenges/2020-11/04-Minimum-Height-Tree.py
1,394
Quick response for one node tree build adjacency matrix get leaves node whoose degree is 1 keep doing leave nodes removal until total node count is smaller or equal to 2 leave nodes removal final leave nodes are root node of minimum height trees
245
en
0.929032
#http://blog.gravatar.com/2008/01/17/gravatars-in-python-25/ import urllib, hashlib # Set your variables here email = "Someone@somewhere.com" default = "http://www.somewhere.com/homsar.jpg" size = 40 def get_gravatar(email): gravatar_url = "http://www.gravatar.com/avatar.php?" #gravatar_url += urllib.urlencode({'g...
stratus/gravatar.py
430
http://blog.gravatar.com/2008/01/17/gravatars-in-python-25/ Set your variables heregravatar_url += urllib.urlencode({'gravatar_id':hashlib.md5(email.lower()).hexdigest(), 'default':default, 'size':str(size)})
208
en
0.161852
#!/usr/bin/env python # $Id: update_pot.py 40713 2011-09-30 09:25:53Z nazgul $ # ***** BEGIN GPL LICENSE BLOCK ***** # # This program 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 2 # of the ...
po/update_pot.py
3,538
!/usr/bin/env python $Id: update_pot.py 40713 2011-09-30 09:25:53Z nazgul $ ***** BEGIN GPL LICENSE BLOCK ***** This program 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 2 of the License, or (at ...
967
en
0.817962
# coding: utf-8 """ Factern API """ import pprint import re # noqa: F401 import six import importlib parent_name = "BaseResponse" def get_parent(): # Lazy importing of parent means that loading the classes happens # in the correct order. if get_parent.cache is None: parent_fname = "fact...
factern_client/com/factern/model/create_entity_response.py
4,382
Returns true if both objects are equal CreateEntityResponse - a model defined in Swagger Returns true if both objects are not equal For `print` and `pprint` Gets the description of this CreateEntityResponse. # noqa: E501 :return: The description of this CreateEntityResponse. # noqa: E501 :rtype: str Sets the descri...
938
en
0.588964
import warnings from cloudcafe.auth.provider import MemoizedAuthServiceComposite from cloudcafe.blockstorage.config import BlockStorageConfig from cloudcafe.blockstorage.volumes_api.common.config import VolumesAPIConfig from cloudcafe.blockstorage.volumes_api.v1.config import \ VolumesAPIConfig as v1Config from c...
cloudcafe/blockstorage/composites.py
3,454
For backwards compatibility (deprecated - see property below)
61
en
0.679832
# -*- coding: utf-8 -*- from PyQt5.QtWidgets import * from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWebEngineWidgets import * from PyQt5.QtWebChannel import QWebChannel from PyQt5 import Qt import json import sys import time import random import threading import os ConfigData = {} ...
main.py
5,853
-*- coding: utf-8 -*- 第一个参数即为回调时携带的参数类型加载外部的web界面加载外部的web界面 设置系统托盘图标的菜单tp.showMessage('VegeTable Admin', '成功运行', icon=0)def clickMessage(): print("信息被点击了")tp.messageClicked.connect(clickMessage)
197
zh
0.299169
# -*- coding: utf-8 -*- # Copyright 2018, IBM. # # This source code is licensed under the Apache License, Version 2.0 found in # the LICENSE.txt file in the root directory of this source tree. # pylint: disable=invalid-name,anomalous-backslash-in-string,missing-docstring """mpl circuit visualization backend.""" imp...
qiskit/tools/visualization/_matplotlib.py
29,138
mpl circuit visualization backend. -*- coding: utf-8 -*- Copyright 2018, IBM. This source code is licensed under the Apache License, Version 2.0 found in the LICENSE.txt file in the root directory of this source tree. pylint: disable=invalid-name,anomalous-backslash-in-string,missing-docstring check folding add measu...
979
en
0.629194
# Copyright 2016-2018 Autodesk 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 wr...
pyccc/__init__.py
1,180
Copyright 2016-2018 Autodesk 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, software di...
572
en
0.841885
from math import sqrt # Example script demonstrating conversion of if statements x = True if x: print("X was true") a = 3 b = 4.5 if b > a: print("B was greater than a") elif a > b: print("A was greater than a") else: print("They are equal") # Nested ifs are supported if True: if b < a: ...
examples/example_if.py
654
Example script demonstrating conversion of if statements Nested ifs are supported Conditional supports function calls Cannot handle certain python calls such as is and in Lists currently not supported during translation
219
en
0.932483
""" Copyright 2019 Inmanta 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 ...
src/inmanta/server/services/paramservice.py
10,651
Slice for parameter management Copyright 2019 Inmanta 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 ...
724
en
0.789175
# some utils taken from the DeepXplore Implementation import random from collections import defaultdict import numpy as np from keras import backend as K from keras.models import Model from keras.preprocessing import image from keras import models, layers, activations from scipy.spatial.distance import mahalanobis f...
4_Coverage_Evaluation/CIFAR10/utils.py
10,928
some utils taken from the DeepXplore Implementationloads a mnist image input_img_data = preprocess_input(input_img_data) final input shape = (1,224,224,3)To testgets the distance of the points in standard deviationsnote that it assumes that the points are normally distributed an adaptation of some code from deepXplor...
2,471
en
0.852637
"""Create portable serialized representations of Python objects. See module cPickle for a (much) faster implementation. See module copy_reg for a mechanism for registering custom picklers. See module pickletools source for extensive comments. Classes: Pickler Unpickler Functions: dump(object, file) ...
lib-python/modified-2.5.2/pickle.py
46,580
Code version These are purely informational; no code uses these. File format version we write Original protocol 0 Protocol 0 with INST added Original protocol 1 Protocol 1 with BINFLOAT added Protocol 2 Old format versions we can read Keep in synch with cPickle. This is the highest protocol number we know how to read....
9,704
en
0.86119
####################################### # TESTING PURPOSE ONLY MODELS!! # # DO NOT ADD THE APP TO INSTALLED_APPS# ####################################### import datetime as base_datetime from decimal import Decimal from tempfile import gettempdir from django.conf import settings from django.contrib.contenttypes....
tests/generic/models.py
12,291
Annotate queryset with an alias field 'name'. We want to test whether this annotation has been run after calling `baker.make()`. TESTING PURPOSE ONLY MODELS!! DO NOT ADD THE APP TO INSTALLED_APPS check whether or not PIL is installed NoQA Jards Macalé is an amazing brazilian musician! =] Skip JSONField-relat...
462
en
0.821458
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
aliyun-python-sdk-slb/aliyunsdkslb/request/v20140515/SetServerCertificateNameRequest.py
2,554
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 use this file...
754
en
0.883564
# Copyright 2015, 2016 OpenMarket 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 required by applicable law or agreed to in ...
synapse/push/pusherpool.py
14,418
The pusher pool. This is responsible for dispatching notifications of new events to the http and email pushers. It provides three methods which are designed to be called by the rest of the application: `start`, `on_new_notifications`, and `on_new_receipts`: each of these delegates to each of the relevant pushers. Not...
2,901
en
0.932212
# 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 ...
venv/lib/python3.8/site-packages/azure/mgmt/synapse/operations/_sql_pool_blob_auditing_policies_operations.py
12,939
SqlPoolBlobAuditingPoliciesOperations operations. You should not instantiate directly this class, but create a Client instance that will create it for you and attach it as attribute. :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializ...
3,910
en
0.541194
from functools import partial from keras_metrics import metrics as m from keras_metrics import casts __version__ = "1.2.1" def metric_fn(cls, cast_strategy): def fn(label=0, **kwargs): metric = cls(label=label, cast_strategy=cast_strategy, **kwargs) metric.__name__ = "%s_%s" % (cast_strategy.__n...
AIDeveloper/keras_metrics/__init__.py
2,380
For backward compatibility.
27
en
0.905231
# This file contains a backport of np.random.choice from numpy 1.7 # The function can be removed when we bump the requirements to >=1.7 import numpy as np import operator from sklearn.utils import check_random_state from ._random import sample_without_replacement __all__ = ['sample_without_replacement', 'choice'] ...
venv/lib/python2.7/site-packages/sklearn/utils/random.py
6,604
choice(a, size=None, replace=True, p=None) Generates a random sample from a given 1-D array .. versionadded:: 1.7.0 Parameters ----------- a : 1-D array-like or int If an ndarray, a random sample is generated from its elements. If an int, the random sample is generated as if a was np.arange(n) size : int or...
3,116
en
0.701617
#!/usr/bin/env python3 # This is run by the "run-tests" script. import unittest from test import TestHelper, Conn, parse class TestNoListing(TestHelper): def test_no_listing(self): resp = self.get("/") status, hdrs, body = parse(resp) self.assertContains(status, "404 Not Found") if __name_...
devel/test_no_listing.py
382
!/usr/bin/env python3 This is run by the "run-tests" script. vim:set ts=4 sw=4 et:
82
en
0.621588
'''Test code. ''' # pylint: disable=import-error import unittest from Chapter3_CodeTesting.UnitTesting.vector import Vector2D class VectorTests(unittest.TestCase): def setUp(self): self.v1 = Vector2D(0, 0) self.v2 = Vector2D(-1, 1) self.v3 = Vector2D(2.5, -2.5) def test_equality(self...
Chapter3_CodeTesting/UnitTesting/test_vector.py
1,521
Tests the addition operator. Tests the multiplication operator. Tests the equality operator. Tests the multiplication operator. Tests the subtraction operator. Test code. pylint: disable=import-error
246
en
0.696257
# -*- coding: utf-8 -*- from . import test_related from . import test_new_fields from . import test_onchange from . import test_field_conversions from . import test_attributes
odoo/openerp/addons/test_new_api/tests/__init__.py
177
-*- coding: utf-8 -*-
21
en
0.767281
# -*- coding: utf-8 -*- """ Created on Sat Oct 26 20:21:07 2019 Tecnológico Nacional de México (TECNM) Tecnológico de Estudios Superiores de Ixtapaluca (TESI) División de ingeniería electrónica Introducción a la librería Numpy 2 M. en C. Rogelio Manuel Higuera Gonzalez """ import numpy as np ###########################...
IibreriaNumpy2.py
2,452
Created on Sat Oct 26 20:21:07 2019 Tecnológico Nacional de México (TECNM) Tecnológico de Estudios Superiores de Ixtapaluca (TESI) División de ingeniería electrónica Introducción a la librería Numpy 2 M. en C. Rogelio Manuel Higuera Gonzalez -*- coding: utf-8 -*-Crea un arreglo de edadesAcomoda los elementos del arre...
1,336
es
0.745239
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.14.4 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from pprint import pformat from six import iteritems import re...
kubernetes/client/models/v1_api_group.py
9,830
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. Returns true if both objects are equal V1APIGroup - a model defined in Swagger Returns true if both objects are not equal For `print` and `pprint` Gets the api_version of this V1APIGroup. APIVersion defines the ver...
4,716
en
0.817684
import logging import numpy as np from typing import Any, Dict, Optional from mlagents.tf_utils import tf from mlagents.envs.timers import timed from mlagents.envs.brain import BrainInfo, BrainParameters from mlagents.trainers.models import EncoderType, LearningRateSchedule from mlagents.trainers.ppo.models import PP...
ml-agents/mlagents/trainers/ppo/policy.py
10,898
Policy for Proximal Policy Optimization Networks. :param seed: Random seed. :param brain: Assigned Brain object. :param trainer_params: Defined training parameters. :param is_training: Whether the model should be trained. :param load: Whether a pre-trained model will be loaded or a new one created. Create PPO model :pa...
1,441
en
0.766374
from __future__ import absolute_import, division, print_function from six.moves import range from scitbx.lbfgs import core_parameters, termination_parameters from scitbx.lbfgs import exception_handling_parameters, ext from scitbx.array_family import flex import scitbx """mpi_split_evaluator_run(), supports an LBFGS pa...
modules/cctbx_project/scitbx/lbfgs/tst_mpi_split_evaluator.py
10,555
The supported scenario is that each MPI worker rank has a target evaluator that has part of the data. Each rank calculates a bit of the functional and gradients, but then mpi reduce is used to sum them all up. There has been no low-level redesign to support MPI. In particular, the ext.minimizer is run (wastefully) b...
1,035
en
0.812191
# coding: utf-8 import sys, os sys.path.append(os.pardir) # 親ディレクトリのファイルをインポートするための設定 import numpy as np from common.layers import * from common.gradient import numerical_gradient from collections import OrderedDict class TwoLayerNet: def __init__(self, input_size, hidden_size, output_size, weight_init_std=0.01...
ch05/two_layer_net.py
2,471
coding: utf-8 親ディレクトリのファイルをインポートするための設定 重みの初期化 レイヤの生成 x:入力データ, t:教師データ x:入力データ, t:教師データ forward backward 設定
107
ja
0.999574
from __future__ import unicode_literals import atexit import os import unittest from django import VERSION from selenium import webdriver from django.urls import reverse from selenium.webdriver.common.keys import Keys from selenium.webdriver.support import ui from selenium.webdriver.support.ui import Select try: ...
autocomplete_light/tests/test_widget.py
12,864
Stops the serve_forever loop. Blocks until the loop has finished. This must be called while serve_forever() is running in another thread, or it will deadlock. Patch for travis LiveServerTestCase doesn't serve static files in 1.7 anymore Jenkins build server Global Selenium instance. wait for select don't wait for o...
413
en
0.92213
from test import support from test.support import bigmemtest, _4G import array import unittest from io import BytesIO, DEFAULT_BUFFER_SIZE import os import pickle import glob import tempfile import pathlib import random import shutil import subprocess import threading from test.support import import_helper from test.s...
www/src/Lib/test/test_bz2.py
38,272
Test the BZ2File class. Base for other testcases. Test the open function. Decompressed data buffering should be limited Skip tests if the bz2 module doesn't exist. Some tests need more than one block of uncompressed data. Since one block is at least 100,000 bytes, we gather some data dynamically and compress it. Note...
2,430
en
0.781609
# coding=utf-8 # Copyright 2018 HuggingFace 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 a...
transformers/examples/test_examples.py
3,495
coding=utf-8 Copyright 2018 HuggingFace 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,...
567
en
0.859924
#!/usr/bin/env python # Problem: Many forked repos on GitHub fall behind from their origins. # Solution: # 1) Verify that `apt install myrepos` is available on the system. # 2) Query GitHub API to find all of my repositories # 3) Clone each *fork* into *~/repos/mynameofit*, such that place I forked it # from is git...
utilities/updatify.py
564
!/usr/bin/env python Problem: Many forked repos on GitHub fall behind from their origins. Solution: 1) Verify that `apt install myrepos` is available on the system. 2) Query GitHub API to find all of my repositories 3) Clone each *fork* into *~/repos/mynameofit*, such that place I forked it from is git origin (or up...
540
en
0.876525
#!/usr/bin/env python # # Copyright (c) 2015, 2016, 2017, 2018, 2019, Intel Corporation # # 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 # ...
scripts/geopmpy/error.py
3,469
Return the error message associated with the error code. Positive error codes are interpreted as system error numbers, and negative error codes are interpreted as GEOPM error numbers. Args: err_number (int): Error code to be interpreted. Returns: str: Error message associated with error code. !/usr/bin/env ...
1,877
en
0.864508
# Imports from 3rd party libraries import dash import dash_bootstrap_components as dbc import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output # Imports from this application from app import app # 2 column layout. 1st column width = 4/12 # https://...
pages/predictions.py
704
Imports from 3rd party libraries Imports from this application 2 column layout. 1st column width = 4/12 https://dash-bootstrap-components.opensource.faculty.ai/l/components/layout
179
en
0.712005
# https://github.com/RainerKuemmerle/g2o/blob/master/g2o/examples/ba_anchored_inverse_depth/ba_anchored_inverse_depth_demo.cpp import numpy as np import g2o from collections import defaultdict import argparse parser = argparse.ArgumentParser() parser.add_argument('--noise', dest='pixel_noise', type=float, default=1...
g2opy/python/examples/ba_anchored_inverse_depth_demo.py
4,375
https://github.com/RainerKuemmerle/g2o/blob/master/g2o/examples/ba_anchored_inverse_depth/ba_anchored_inverse_depth_demo.cpp slower pose here means transform points from world coordinates to camera coordinates
209
en
0.539741
""" Conditional Generative adversarial networks: https://arxiv.org/abs/1611.07004 U-net: https://arxiv.org/abs/1505.04597 Conditional generative adversarial network architecture modules used for simulation of detector response and unfolding in JetGAN framework. Generator() returns the generator model, and Discriminato...
jetgan/model/cgan.py
363
Conditional Generative adversarial networks: https://arxiv.org/abs/1611.07004 U-net: https://arxiv.org/abs/1505.04597 Conditional generative adversarial network architecture modules used for simulation of detector response and unfolding in JetGAN framework. Generator() returns the generator model, and Discriminator() ...
353
en
0.667134
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: © 2019- d3p Developers and their Assignees # 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...
d3p/modelling.py
10,828
Extracts all sample values from a numpyro trace. :param trace: trace object obtained from `numpyro.handlers.trace().get_trace()` :param with_intermediates: If True, intermediate(/latent) samples from sample site distributions are included in the result. :return: Dictionary of sampled values associated with the nam...
7,150
en
0.757719
# encoding: utf-8 from libs.configs import cfgs from libs.box_utils import bbox_transform from libs.box_utils import nms_rotate import tensorflow as tf from libs.box_utils.coordinate_convert import coordinate_present_convert def filter_detections(boxes, scores, is_training, gpu_id): """ :param boxes: [-1, 4]...
libs/detection_oprations/refine_proposal_opr_csl.py
4,586
:param boxes: [-1, 4] :param scores: [-1, ] :param labels: [-1, ] :return: encoding: utf-8 _, _, _, _, theta = tf.unstack(boxes_pred, axis=1) indx = tf.reshape(tf.where(tf.logical_and(tf.less(theta, 0), tf.greater_equal(theta, -180))), [-1, ]) boxes_pred = tf.gather(boxes_pred, indx) scores = tf.gather(scores, indx) ...
621
en
0.362966
# coding:utf-8 import time import datetime import os import tensorflow as tf import pickle import utils from keras.preprocessing.sequence import pad_sequences import numpy as np import evaluate from utils import Utils class SMN(): def __init__(self, device_name='/cpu:0', lr=0.00...
retrieval_model.py
15,902
coding:utf-8init = tf.global_variables_initializer()with tf.Session() as sess:sess.run(init) Later, launch the model, use the saver to restore variables from disk, and do some work with the model. with tf.Session() as sess: Restore variables from disk. saver.restore(sess, "/model/model.5") print("Model res...
1,616
en
0.458826
#!/usr/bin/env python # Copyright (c) 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # Disable the lint error for too-long lines for the URL below. # pylint: disable=C0301 """Fix Chrome App manifest.json files for u...
native_client_sdk/src/tools/fix_manifest.py
3,626
!/usr/bin/env python Copyright (c) 2014 The Chromium Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. Disable the lint error for too-long lines for the URL below. pylint: disable=C0301 Keep the dictionary order. This is only supported on Pyt...
328
en
0.8385
import numpy as np import cv2 import math def norm_image(img): """ normalize image input """ img = img.astype(np.float32) var = np.var(img, axis=(0, 1), keepdims=True) mean = np.mean(img, axis=(0, 1), keepdims=True) return (img - mean) / (np.sqrt(var) + 1e-7) def mask_depth_image(depth_image, mi...
pointmvsnet/utils/preprocess.py
3,025
resize images and cameras to fit the network (can be divided by base image size) mask out-of-range pixel to zero normalize image input resize input in order to produce sampled depth map resize input to fit into the memory resize image using cv2 print ('mask min max', min_depth, max_depth) focal: principle point...
362
en
0.733194
import sys import numpy as np import torch import torch.hub from PIL import Image from torchvision.transforms import Compose from _model_base import ModelBase, handle_alpha from _util import apply_colormap, to_rgb # Simplified transforms from # https://github.com/intel-isl/MiDaS/blob/master/models/transforms.py cla...
models/MiDaS.py
3,410
Simplified transforms from https://github.com/intel-isl/MiDaS/blob/master/models/transforms.py scale such that output size is upper bound fit width fit height
158
en
0.708672
import tensorflow as tf import argparse import os, re import numpy as np from tensorflow.contrib.layers import variance_scaling_initializer from tensorpack import * from tensorpack.utils import logger from tensorpack.utils.stat import RatioCounter from tensorpack.tfutils.symbolic_functions import * from tensorpack.tfu...
OLD/models/resnet/old/resnet_orig.py
7,620
Convert a caffe parameter name to a tensorflow parameter name as defined in the above model put bn at the bottom tensorflow with padding=SAME will by default pad [2,3] here. but caffe conv with stride will pad [3,3] load ResNet mean from Kaiming:from tensorpack.utils.loadcaffe import get_caffe_pbobj = get_caffe_pb()...
509
en
0.543423
# test syntax and type errors specific to viper code generation def test(code): try: exec(code) except (SyntaxError, ViperTypeError, NotImplementedError) as e: print(repr(e)) # viper: annotations must be identifiers test("@micropython.viper\ndef f(a:1): pass") test("@micropython.viper\ndef f...
tests/micropython/viper_error.py
1,932
test syntax and type errors specific to viper code generation viper: annotations must be identifiers unknown type local used before type known type mismatch storing to local can't implicitly convert type to bool incorrect return type can't do binary op between incompatible types can't load can't store must raise an obj...
500
en
0.818257
import sys from common import unittest2, platform_skip import pyuv TEST_PORT = 1234 if sys.platform == 'win32': TEST_PIPE = '\\\\.\\pipe\\test-pipe' else: TEST_PIPE = 'test-pipe' @platform_skip(["win32"]) class IPCTest(unittest2.TestCase): def setUp(self): self.loop = pyuv.Loop.default_loop()...
tests/test_ipc.py
4,497
Handle that will be sent to the process and back
48
en
0.952161
import os import urllib.parse from datetime import timedelta import flask import requests from cachetools import TTLCache from flask import current_app, session, request, redirect, abort, jsonify from flask_oauthlib.client import OAuth from werkzeug import security from urllib.parse import urlparse from common.rpc.au...
common/oauth_client.py
6,827
Add access_token to the URL Request. Add Okpy OAuth for ``consumer_key`` to the current ``app``. Specifically, adds an endpoint ``/oauth/login`` that redirects to the Okpy login process, ``/oauth/authorized`` that receives the successful result of authentication, ``/api/user`` that acts as a test endpoint, and a :meth...
1,978
en
0.648984
""" Module for testing goftest module. """ __author__ = "wittawat" import unittest import matplotlib.pyplot as plt import numpy as np import numpy.testing as testing import scipy.stats as stats import sbibm.third_party.kgof.data as data import sbibm.third_party.kgof.density as density import sbibm.third_party.kgof....
sbibm/third_party/kgof/test/test_goftest.py
6,297
Test FSSD-opt test with automatic parameter initialization. Nothing special. Just test basic things. Test FSSD test with parameter optimization. Module for testing goftest module. sample only one dimension of the mean is shifted draw_mean = mean + np.hstack((1, np.zeros(d-1))) Test random test locations assertions sa...
610
en
0.70377
# coding=utf-8 # unpack.py # Author: Meghan Clark import binascii import struct from .message import HEADER_SIZE_BYTES, Message from .msgtypes import * # Creates a LIFX Message out of packed binary data # If the message type is not one of the officially released ones above, it will create just a Message out of it #...
lifxlan/unpack.py
19,595
coding=utf-8 unpack.py Author: Meghan Clark Creates a LIFX Message out of packed binary data If the message type is not one of the officially released ones above, it will create just a Message out of it If it's not in the LIFX protocol format, uhhhhh...we'll put that on a to-do list. 120 121 122501 8 bit8 bit8 bit502 8...
375
en
0.676337
import json import logging.config import os default_config = { "version": 1, "disable_existing_loggers": False, "formatters": { "simple": { "format": "%(asctime)s :: %(name)s :: %(levelname)s :: %(message)s" } }, "handlers": { "console": { "class": "...
geeup/config.py
1,912
Read credential json file and return username and password
58
en
0.836489
###Titulo: Multiplicação através de repetidas somas ###Função: Este programa realiza a multiplicação de dois números através de sucessivas adições ###Autor: Valmor Mantelli Jr. ###Data: 14/12/2018 ###Versão: 0.0.5 # Declaração de variáve x = 0 y = 0 w = 0 z = 1 # Atribuição de valor a variavel x = int(input("Dig...
exer508.py
522
Titulo: Multiplicação através de repetidas somasFunção: Este programa realiza a multiplicação de dois números através de sucessivas adiçõesAutor: Valmor Mantelli Jr.Data: 14/12/2018Versão: 0.0.5 Declaração de variáve Atribuição de valor a variavel Processamento Saída
267
pt
0.990136
#!/usr/bin/python # Copyright: (c) 2018, Johannes Brunswicker <johannes.brunswicker@gmail.com> # 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 DOCUMENTATION = ''' --- module: utm_proxy_...
kubernetes-the-hard-way/system/collections/ansible_collections/community/general/plugins/modules/web_infrastructure/sophos_utm/utm_proxy_location.py
6,365
!/usr/bin/python Copyright: (c) 2018, Johannes Brunswicker <johannes.brunswicker@gmail.com> GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
182
en
0.418986
import rlkit.misc.hyperparameter as hyp from multiworld.envs.mujoco.cameras import init_sawyer_camera_v1 from multiworld.envs.mujoco.cameras import sawyer_pick_and_place_camera from rlkit.launchers.launcher_util import run_experiment from rlkit.torch.grill.launcher import grill_her_td3_full_experiment import rlkit.torc...
experiments/steven/online-vae/pick_and_place/state_exp.py
4,686
beta_schedule_kwargs=dict( x_values=[0, 100, 200, 500], y_values=[0, 0, 5, 5],), trial_dir_suffix='n1000-{}--zoomed-{}'.format(n1000, zoomed),
148
en
0.091751
from commons.neural_network import TwoLayerNet from datasets.mnist import load_mnist import numpy as np (x_train, t_train), (x_test, t_test) = load_mnist( normalize=True, one_hot_label=True) network = TwoLayerNet(input_size=784, hidden_size=50, output_size=10) iters_num = 10000 train_size = x_train.shape[0] batc...
chapter05/5.7.4_backpropagation_learning.py
1,153
calculate gradients with backpropagation renewal
48
en
0.702883
import os import re from therandy.utils import get_closest, replace_command from therandy.specific.brew import get_brew_path_prefix, brew_available BREW_CMD_PATH = '/Library/Homebrew/cmd' TAP_PATH = '/Library/Taps' TAP_CMD_PATH = '/%s/%s/cmd' enabled_by_default = brew_available def _get_brew_commands(brew_path_pref...
therandy/rules/brew_unknown_command.py
2,826
To get brew default commands on local environment To get tap's specific commands https://github.com/Homebrew/homebrew/blob/master/Library/brew.rb#L115 Brew Taps's naming rule https://github.com/Homebrew/homebrew/blob/master/share/doc/homebrew/brew-tap.mdnaming-conventions-and-limitations Failback commands for testing...
346
en
0.810945
#============================================================================== # DEREDDEN.py Sean Andrews's deredden.pro ported to python3 # # A simple function to provide the de-reddening factor in either magnitudes # (with keyword /mags set) or flux density at a range of input wavelengths, # given a visual extinctio...
deredden.py
3,099
call this, get grid. multiply grid by Av to get redenning at that wavelength. Takes in wavelength array in microns. Valid between .1200 um and 1e4 microns. To test implementation ============================================================================== DEREDDEN.py Sean Andrews's deredden.pro ported to python3 A s...
1,283
en
0.606981
from option import * import tkinter as tk class Block: """ Block class for each block of the map """ def __init__(self, x, y, char): self.x = x self.y = y self.char = char self.blockType = MAP_CHARS[char] self.texture = BLOCK_TEXTURE[self.blockType] self.colli...
script/map_and_player.py
4,499
Block class for each block of the map If the first time of drawing block If their is the first draw of the block Number of coin in the map List of all the lines 2D array who contain the block Filter the void line Making the map in self._grid For simulate gravity
266
en
0.88231
#!/bin/python3 """ https://www.hackerrank.com/challenges/crossword-puzzle/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=recursion-backtracking&h_r=next-challenge&h_v=zen """ # Complete the crossword_puzzle function below. def crossword_puzzle(crossword, words): """resuelv...
Interview Preparation Kit/Crossword puzzle/test.py
5,454
resuelve el puzzle https://www.hackerrank.com/challenges/crossword-puzzle/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=recursion-backtracking&h_r=next-challenge&h_v=zen !/bin/python3 Complete the crossword_puzzle function below. ++H+F+++++++++ +RINOCERONTE++ ++E+C++++++L++ ...
409
en
0.374252
#!/usr/bin/env python3 # Enter your code here. Read input from STDIN. Print output to STDOUT def string_manipulate(string): even_string='' odd_string='' for idx, val in enumerate(string): if idx % 2 == 0: even_string+=val else: odd_string+=val return even_...
day6.py
528
!/usr/bin/env python3 Enter your code here. Read input from STDIN. Print output to STDOUT
89
en
0.613299
class A: def foo(self): print("A") class B(A): # def foo(self): # print("B") pass class C(A): def foo(self): print("C") super(C, self).foo() class D(B, C): def foo(self): print("D") super(D, self).foo() if __name__ == '__main__': d = D() ...
PythonAndOop/N42_super_3.py
328
def foo(self): print("B")
29
en
0.355901
from torch.utils.data import Dataset from typing import List import torch from .. import SentenceTransformer from ..readers.InputExample import InputExample class SentencesDataset(Dataset): """ Dataset for smart batching, that is each batch is only padded to its longest sequence instead of padding all sequ...
ai/KoSentenceBERTchatbot/KoSentenceBERT/sentence_transformers/datasets/SentencesDataset.py
1,443
Dataset for smart batching, that is each batch is only padded to its longest sequence instead of padding all sequences to the max length. The SentenceBertEncoder.smart_batching_collate is required for this to work. SmartBatchingDataset does *not* work without it. Create a new SentencesDataset with the tokenized texts a...
460
en
0.834626
# -*- coding: utf-8 -*- """ Exception and warning classes used throughout the framework. Error: Base class, all exceptions should the subclass of this class. - NoUsername: Username is not in user-config.py, or it is invalid. - UserBlocked: Username or IP has been blocked - AutoblockUser: requested action on a v...
pywikibot/exceptions.py
14,980
Command line argument that is no longer supported. Page already exists. Requested action on a virtual autoblock user not valid. The class AutoblockUserError is an exception that is raised whenever an action is requested on a virtual autoblock user that's not available for him (i.e. roughly everything except unblock). ...
7,381
en
0.811007
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 3/5/2018 1:49 PM # @Author : sunyonghai # @File : xml_utils.py # @Software: ZJ_AI #此程序用于编辑xml文件 # ========================================================= import random import xml.etree.ElementTree as ET from xml.etree.ElementTree import Element import os im...
development/server/algorithm/tf_faster_rcnn/data_processing/utils/xml_utils.py
14,434
''给一个节点添加子节点 nodelist: 节点列表 element: 子节点 ''修改/增加 /删除 节点的属性及属性值 nodelist: 节点列表 kv_map:属性及属性值map ''改变/增加/删除一个节点的文本 nodelist:节点列表 text : 更新后的文本 ''新造一个节点 tag:节点标签 property_map:属性及属性值map content: 节点闭合标签里的文本内容 return 新节点 ''同过属性及属性值定位一个节点,并删除之 nodelist: 父节点列表 tag:子节点标签 kv_map: 属性及属性值列表 ''查找某个路径匹配的所有节点 tree: xml树 path: 节点路径 ''...
5,882
en
0.254645
import numpy as np from collections import defaultdict from scipy.optimize import minimize_scalar, root_scalar, bracket from scipy.special import logsumexp def em_worst_expected_error(n=2, eps=1, delta=1): def foo(p): return np.log(p) * (1 - 1 / (1 + (n-1)*p)) a = -minimize_scalar(lambda p: foo(p), bou...
Experiments/mechanisms.py
3,499
first we will calculate sum(prod(p_i, i in S), |S| = k) for each k coefficient vector: (-1)^k / (k+1) for k = 1..n we will now calculate sum(prod(p_i, i in S), |S| = k, r not in S) and compute the final probabilitiesp = np.exp(coef*eps/sensitivity*q)return p / p.sum() compute the expected error of the mechanism (given...
414
en
0.808121
from plotly.basedatatypes import BaseTraceType as _BaseTraceType import copy as _copy class Histogram2dContour(_BaseTraceType): # class properties # -------------------- _parent_path_str = "" _path_str = "histogram2dcontour" _valid_props = { "autobinx", "autobiny", "autoco...
packages/python/plotly/plotly/graph_objs/_histogram2dcontour.py
120,327
Construct a new Histogram2dContour object The sample data from which statistics are computed is set in `x` and `y` (where `x` and `y` represent marginal distributions, binning is set in `xbins` and `ybins` in this case) or `z` (where `z` represent the 2D distribution and binning set, binning is set by `x` and `y` in t...
64,610
en
0.697167
""" Some settings for the config files """ # defaultdir = '/data/ncbi/taxonomy/current' # defaultdir = '/home/edwa0468/ncbi/taxonomy' defaultdir = '/raid60/usr/data/NCBI/taxonomy/current/' def get_db_dir(): """ Just return the default dir listed above :return: the default location for the sqllite database...
taxon/config.py
351
Just return the default dir listed above :return: the default location for the sqllite database Some settings for the config files defaultdir = '/data/ncbi/taxonomy/current' defaultdir = '/home/edwa0468/ncbi/taxonomy'
219
en
0.278231