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
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import itertools import json import logging import os from argparse import Namespace import numpy as np from fairseq import metrics, options,...
fairseq/tasks/translation.py
17,973
Translate from one (source) language to another (target) language. Args: src_dict (~fairseq.data.Dictionary): dictionary for the source language tgt_dict (~fairseq.data.Dictionary): dictionary for the target language .. note:: The translation task is compatible with :mod:`fairseq-train`, :mod:`fairse...
1,786
en
0.742284
from typing import List, Optional import scrapy from scrapy import Item from jedeschule.items import School from jedeschule.spiders.school_spider import SchoolSpider def first_or_none(item: List) -> Optional[str]: try: return item[0] except IndexError: return None class BrandenburgSpider(S...
jedeschule/spiders/brandenburg.py
2,365
fix wrong tabs, spaces and backslashes fix @ in email addresses extract the school ID from the URL
100
en
0.886382
#!/usr/bin/env python """Base test classes for API handlers tests.""" # pylint:mode=test import json import logging import os import threading import portpicker import requests from google.protobuf import json_format from grr import gui from grr_api_client.connectors import http_connector from grr.gui import api_au...
grr/gui/api_regression_http.py
6,665
Load only API E2E test cases. Test class for HTTP v1 protocol. Test class for HTTP v2 protocol. Test class for HTTP v2 protocol with Database.useForReads=True. Does regression check for given method, args and a replace function. Parses response JSON. Prepares API v1 request for a given method and args. Prepares API v2 ...
484
en
0.522427
import docker if __name__ == '__main__': client = docker.from_env() i = -1 name = 'evtd_' while(True): try: i += 1 container = client.containers.get('{}{}'.format(name,i)) print(container.logs(tail=1)) # container.stop() # container.re...
nettests/monitor.py
470
container.stop() container.remove() print('free {}{} succeed'.format(name, i))
78
en
0.183286
import os from pathlib import Path from typing import Callable, Optional, Tuple, Union import torchvision from torch import nn from torch.utils.data import DataLoader, Dataset from torchvision import transforms from torchvision.datasets import STL10, ImageFolder def build_custom_pipeline(): """Builds augmentatio...
solo/utils/classification_dataloader.py
8,881
Builds augmentation pipelines for custom data. If you want to do exoteric augmentations, you can just re-write this function. Needs to return a dict with the same structure. Prepares transformations, creates dataset objects and wraps them in dataloaders. Args: dataset (str): dataset name. data_dir (Optional[Un...
2,092
en
0.61356
import collections class Solution: """ @param board: a board @param click: the position @return: the new board """ def updateBoard(self, board, click): # Write your code here b = [] for s in board: temp = [] for c in s: temp.append(...
1101-1200/1189-Minesweeper/1189-Minesweeper.py
1,357
@param board: a board @param click: the position @return: the new board Write your code here
94
en
0.571419
#!/usr/bin/env python # #===- exploded-graph-rewriter.py - ExplodedGraph dump tool -----*- python -*--# # # Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. # See https://llvm.org/LICENSE.txt for license information. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception # #===----------...
utils/analyzer/exploded-graph-rewriter.py
40,771
!/usr/bin/env python===- exploded-graph-rewriter.py - ExplodedGraph dump tool -----*- python -*-- Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. See https://llvm.org/LICENSE.txt for license information. SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception===----------------------------...
4,170
en
0.761855
# pylint: disable=invalid-name # Requires Python 3.6+ # Ref: https://www.sphinx-doc.org/en/master/usage/configuration.html """Configuration for the Sphinx documentation generator.""" import sys from functools import partial from pathlib import Path from setuptools_scm import get_version # -- Path setup ------------...
docs/conf.py
9,865
Configuration for the Sphinx documentation generator. pylint: disable=invalid-name Requires Python 3.6+ Ref: https://www.sphinx-doc.org/en/master/usage/configuration.html -- Path setup -------------------------------------------------------------- pylint: disable=no-member If extensions (or modules to document with a...
4,662
en
0.610469
from discord.ext import commands import discord class EphemeralCounterBot(commands.Bot): def __init__(self): super().__init__() async def on_ready(self): print(f'Logged in as {self.user} (ID: {self.user.id})') print('------') # Define a simple View that gives us a counter button clas...
examples/views/ephemeral.py
1,897
Define a simple View that gives us a counter button Define the actual button When pressed, this increments the number displayed until it hits 5. When it hits 5, the counter button is disabled and it turns green. note: The name of the function does not matter to the library Make sure to update the message with our updat...
622
en
0.797322
"""Test the creation of all inventories.""" import stewi from stewi.globals import paths, STEWI_VERSION, config year = 2018 def test_inventory_generation(): # Create new local path paths.local_path = paths.local_path + "_" + STEWI_VERSION error_list = [] for inventory in config()['databases']: ...
tests/test_inventory_generation.py
763
Test the creation of all inventories. Create new local path skip RCRAInfo due to browswer download
100
en
0.727299
# define a function, which accepts 2 arguments def cheese_and_crackers(cheese_count, boxes_of_crackers): # %d is for digit print "You have %d cheeses!" % cheese_count print "You have %d boxes of crackers!" % boxes_of_crackers print "Man that's enough for a party!" # go to a new line after the end print "Get a bla...
ex19/ex19-sd.py
2,582
define a function, which accepts 2 arguments %d is for digit go to a new line after the end call the function defined above by passing plain numbers, also called numeric constants or numeric literals a variable definition doesn't need a'def' beforehand call (use, invoke, run) the function by passing the above variable...
1,199
en
0.837279
# Copyright (c) 2016, Xilinx, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of con...
pynq/lib/logictools/tests/test_fsm_generator.py
26,734
Build an FSM spec with 4 states. The FSM built has 2 inputs, 1 output, and 4 states. It acts like a 2-bit counter, where the output goes to high only if the FSM is in the final state. When the direction pin is low, the counter counts up; if it is high, the counter counts down. Parameters ---------- direction_logic...
5,421
en
0.854589
# Bit Manipulation # Given a string array words, find the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters. You may assume that each word will contain only lower case letters. If no such two words exist, return 0. # # Example 1: # # Input: ["abcw","baz","foo","bar","x...
LeetCode/318 Maximum Product of Word Lengths.py
1,092
:type words: List[str] :rtype: int Bit Manipulation Given a string array words, find the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters. You may assume that each word will contain only lower case letters. If no such two words exist, return 0. Example 1: Input: ["abc...
619
en
0.762493
"""Test mysensors MQTT gateway with unittest.""" import os import tempfile import time from unittest import TestCase, main, mock from mysensors import ChildSensor, Sensor from mysensors.gateway_mqtt import MQTTGateway class TestMQTTGateway(TestCase): """Test the MQTT Gateway.""" def setUp(self): """...
tests/test_gateway_mqtt.py
7,832
Test the MQTT Gateway. Test the MQTT Gateway with custom topic prefix. Add sensor node. Return sensor node instance. Add sensor node. Return sensor node instance. Set up gateway. Set up gateway. Set up test. Stop MQTTGateway if alive. Test load persistence file for MQTTGateway. Test recv method with nested topic prefix...
772
en
0.700377
# coding: utf-8 """ Kubernetes No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 The version of the OpenAPI document: v1.20.7 Generated by: https://openapi-generator.tech """ import pprint import re # noqa: F401 import six fr...
kubernetes/client/models/io_cert_manager_acme_v1_challenge_spec_solver_dns01_cloudflare_api_token_secret_ref.py
5,314
NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. Returns true if both objects are equal IoCertManagerAcmeV1ChallengeSpecSolverDns01CloudflareApiTokenSecretRef - a model defined in OpenAPI Returns true if both objects are not equal For `print` ...
2,234
en
0.631582
# # These are settings for Heroku Production Environment # from .common import * import dj_database_url # We don't want any debug warnings giving # away unnecessary information to attackers DEBUG = False # We grab the secret key from the environment because it is # our production key and no can know it SECRET_KE...
backend/src/settings/prod.py
1,137
These are settings for Heroku Production Environment We don't want any debug warnings giving away unnecessary information to attackers We grab the secret key from the environment because it is our production key and no can know it We redirect any http requests to their https equivalents Static files (CSS, JavaScript, ...
605
en
0.827494
"""Highlevel API for managing PRs on Github""" import abc import logging from copy import copy from enum import Enum from typing import Any, Dict, List, Optional import gidgethub import gidgethub.aiohttp import aiohttp logger = logging.getLogger(__name__) # pylint: disable=invalid-name #: State for Github Issue...
bioconda_utils/githubhandler.py
7,156
GitHubHandler using Aiohttp for HTTP requests Arguments: session: Aiohttp Client Session object requester: Identify self (e.g. user agent) Handles interaction with GitHub Arguments: token: OAUTH token granting permissions to GH dry_run: Don't actually modify things if set to_user: Target User/Org for PRs ...
660
en
0.517858
import re from ._video import Video from ._channel import Channel from ._playlist import Playlist from ._videobulk import _VideoBulk from ._channelbulk import _ChannelBulk from ._playlistbulk import _PlaylistBulk from ._auxiliary import _parser, _filter, _src class Search: def __init__(self): pass @...
src/_query.py
3,154
:return: < channel object > regarding the query :param str keywords: query to be searched on YouTube :param int limit: total number of channels to be searched :return: list of < channel object > of each video regarding the query (consider limit) :return: < playlist object > regarding the query :param str keywords: quer...
724
en
0.690329
#-*- coding: utf-8 -*- from scrapy.spiders import CrawlSpider, Rule from scrapy.linkextractors import LinkExtractor from climatespider.items import ClimatespiderItem from scrapy.selector import Selector from dateutil.parser import parse import re import datetime from scrapy.exceptions import CloseSpider def getyester...
climatespider/climatespider/spiders/AO_wugspider.py
9,411
-*- coding: utf-8 -*-today_date = datetime.now().strftime('%Y/%m/%d') items = [] item['date'] = date try: item['WindChill_HeatIndex'] = each.xpath('td[3]/span/span[@class="wx-value"]/text()').extract()[0] except Exception as e: item['WindChill_HeatIndex'] = each.xpath('td[3]/text()').extract()[0].strip().replac...
366
en
0.461288
""" VRChat API Documentation The version of the OpenAPI document: 1.6.8 Contact: me@ruby.js.org Generated by: https://openapi-generator.tech """ import re # noqa: F401 import sys # noqa: F401 from vrchatapi.api_client import ApiClient, Endpoint as _Endpoint from vrchatapi.model_utils import ( # ...
vrchatapi/api/worlds_api.py
74,664
NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the class manually. Create World # noqa: E501 Create a new world. This endpoint requires `assetUrl` to be a valid File object with `.vrcw` file extension, and `imageUrl` to be a valid File object with an image fil...
23,816
en
0.717998
# coding: utf-8 # # Copyright 2020 The Oppia 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 requi...
scripts/linters/js_ts_linter_test.py
40,919
Tests for js_ts_linter file. Assert linter output messages with expected messages. Unit tests for scripts/linters/js_ts_linter.py. coding: utf-8 Copyright 2020 The Oppia Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with th...
1,226
en
0.810735
# Load both the 2016 and 2017 sheets by name all_survey_data = pd.read_excel("fcc_survey.xlsx", sheet_name = ['2016', '2017']) # View the data type of all_survey_data print(type(all_survey_data)) ''' <script.py> output: <class 'collections.OrderedDict'> ''' # Load all sheets in the Excel file all_survey_data = ...
Datacamp Assignments/Data Engineer Track/2. Streamlined Data Ingestion with pandas/11_select_multiple_sheets.py
920
Load both the 2016 and 2017 sheets by name View the data type of all_survey_data Load all sheets in the Excel file View the sheet names in all_survey_data Load all sheets in the Excel file View the sheet names in all_survey_data Notice that if you load a sheet by its index position, the resulting data frame's name is a...
361
en
0.800091
from custom_src.NodeInstance import NodeInstance from custom_src.Node import Node # USEFUL # self.input(index) <- access to input data # self.outputs[index].set_val(val) <- set output data port value # self.main_widget <- access to main widget # self.exec_output(index) ...
packages/std/nodes/std___Or0/std___Or0___METACODE.py
1,931
USEFUL self.input(index) <- access to input data self.outputs[index].set_val(val) <- set output data port value self.main_widget <- access to main widget self.exec_output(index) <- executes an execution output self.create_new_input(type_, label, widget_type='', widget...
550
en
0.219732
""" Test that we keep references to failinfo as needed. """ import fiu # Object we'll use for failinfo finfo = [1, 2, 3] fiu.enable('p1', failinfo = finfo) assert fiu.fail('p1') assert fiu.failinfo('p1') is finfo finfo_id = id(finfo) del finfo assert fiu.failinfo('p1') == [1, 2, 3] assert id(fiu.failinfo('p1')) ...
tests/test-failinfo_refcount.py
333
Test that we keep references to failinfo as needed. Object we'll use for failinfo
83
en
0.967534
""" ASGI config for logkit project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.0/howto/deployment/asgi/ """ import os from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTIN...
logkit/logkit/asgi.py
389
ASGI config for logkit project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.0/howto/deployment/asgi/
212
en
0.744113
import sys from os import listdir from os.path import isfile, join, dirname, realpath import struct import gzip def list_dir(d): return [f for f in listdir(d) if isfile(join(d, f))] def store(p, file): try: output_file = open(p, "w", encoding="utf-8", errors="xmlcharrefreplace") output_file....
tools/batchrun/storage.py
1,293
write an int write a string
27
en
0.35904
from math import sqrt from PrefrontalCortex import Impulse from Decisions import Decisions from Decision import Decision import random as rand # The job of the Neo-cortex is to evaluate, think, and consider. # It is a slow brain part, but a highly important one, it's job is to perform tasks for the prefrontal cortex ...
stock-filters/NeoCortex.py
6,616
The job of the Neo-cortex is to evaluate, think, and consider. It is a slow brain part, but a highly important one, it's job is to perform tasks for the prefrontal cortex (to make it happy), While finding the optimal ways to do those tasks.print "SETTLER: ", textReturns a boolean value true if the settler found ...
454
en
0.903032
#!/usr/bin/env python # coding: utf-8 import random import numpy as np import sys, os import pandas as pd import torch from torchsummary import summary from torchtext import data import torch.nn as nn import torch.utils.data from torch.utils.data import Dataset, TensorDataset,DataLoader, RandomSampler from torch.util...
utils/utils.py
5,288
Returns tokenized IDs and attention mask The transformers encode_plus method returns the following: { input_ids: list[int], token_type_ids: list[int] if return_token_type_ids is True (default) attention_mask: list[int] if return_attention_mask is True (default) overflowing_tokens: list[int] if a ``max_length`` is speci...
795
en
0.388101
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) import codecs import os import re import tarfile import shutil import tempfile import hashlib import glob import platform ...
lib/spack/spack/binary_distribution.py
39,612
Raised if directory layout is different from buildcache. Raised if file fails checksum verification. Raised when gpg2 is not in PATH Raised when gpg has no default key added. Raised when a file exists and must be overwritten. Raised if file fails signature verification. Raised when multiple keys can be used to sign. Bu...
6,301
en
0.859296
# -*- coding: utf-8 -*- """ Copyright (C) 2017 tianyou pan <sherry0429 at SOAPython> """ from engine import ServiceEngineModule from template import ServiceParamTemplate __all__ = ['ServiceEngineModule', 'ServiceParamTemplate']
toBusUsege/service_module/service_core/__init__.py
229
Copyright (C) 2017 tianyou pan <sherry0429 at SOAPython> -*- coding: utf-8 -*-
80
en
0.71071
''' Created on Nov 16, 2021 @author: mballance ''' from mkdv.tools.hdl.hdl_tool_config import HdlToolConfig import os class HdlTool(object): def config(self, cfg : HdlToolConfig): raise NotImplementedError("config not implemented for %s" % str(type(self))) def setup(self, cfg : HdlToolConfig...
src/mkdv/tools/hdl/hdl_tool.py
540
Created on Nov 16, 2021 @author: mballance
43
en
0.871993
#!/usr/bin/env python3 # Copyright (c) 2016-2019 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 using named arguments for RPCs.""" from test_framework.test_framework import GuldenTestFramework ...
test/functional/rpc_named_arguments.py
1,208
Test using named arguments for RPCs. !/usr/bin/env python3 Copyright (c) 2016-2019 The Bitcoin Core developers Distributed under the MIT software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.
244
en
0.526021
# Copyright 2020 Maruan Al-Shedivat. 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 appli...
cen/regularizers/entropy.py
3,350
Encourages models with higher context-conditional entropy. Entropy-based activity regularizers. Copyright 2020 Maruan Al-Shedivat. 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 Lice...
1,323
en
0.751583
from django.contrib import admin # from .models import related models from .models import CarMake, CarModel # Register your models here. # CarModelInline class class CarModelInline(admin.StackedInline): model = CarModel.car_makes.through extra = 3 # CarModelAdmin class class CarModelAdmin(admin.ModelAdmin): ...
server/djangoapp/admin.py
598
from .models import related models Register your models here. CarModelInline class CarModelAdmin class CarMakeAdmin class with CarModelInline Register models here
162
en
0.709334
import os # toolchains options ARCH='arm' CPU='cortex-m3' CROSS_TOOL='gcc' if os.getenv('RTT_CC'): CROSS_TOOL = os.getenv('RTT_CC') if os.getenv('RTT_ROOT'): RTT_ROOT = os.getenv('RTT_ROOT') # cross_tool provides the cross compiler # EXEC_PATH is the compiler execute path, for example, CodeSourcery, Keil MDK...
bsp/stm32/libraries/templates/stm32f10x/rtconfig.py
3,594
toolchains options cross_tool provides the cross compiler EXEC_PATH is the compiler execute path, for example, CodeSourcery, Keil MDK, IAR toolchains toolchains toolchains
171
en
0.604478
# pylint: disable=wildcard-import, unused-wildcard-import """Model store which handles pretrained models from both mxnet.gluon.model_zoo.vision and gluoncv.models """ from mxnet import gluon from .ssd import * from .faster_rcnn import * from .fcn import * from .pspnet import * from .cifarresnet import * from .cifarresn...
gluoncv/model_zoo/model_zoo.py
4,320
Returns a pre-defined model by name Parameters ---------- name : str Name of the model. pretrained : bool Whether to load the pretrained weights for model. classes : int Number of classes for the output layer. ctx : Context, default CPU The context in which to load the pretrained weights. root : str, d...
654
en
0.639595
#!/usr/bin/env python3 # Copyright (c) 2014-2019 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 wallet import RPCs. Test rescan behavior of importaddress, importpubkey, importprivkey, and impor...
test/functional/wallet_import_rescan.py
10,790
Helper for importing one key and verifying scanned transactions. Verify that listtransactions/listreceivedbyaddress return expected values. Call one key import RPC. Test wallet import RPCs. Test rescan behavior of importaddress, importpubkey, importprivkey, and importmulti RPCs with different types of keys and rescan ...
2,552
en
0.83322
# pylint: disable=E1101,W0232 import numpy as np from warnings import warn import textwrap from pandas import compat from pandas.compat import u, lzip from pandas._libs import lib, algos as libalgos from pandas.core.dtypes.generic import ( ABCSeries, ABCIndexClass, ABCCategoricalIndex) from pandas.core.dtypes.mi...
pandas/core/arrays/categorical.py
87,593
Represents a categorical variable in classic R / S-plus fashion `Categoricals` can only take on only a limited, and usually fixed, number of possible values (`categories`). In contrast to statistical categorical variables, a `Categorical` might have an order, but numerical operations (additions, divisions, ...) are no...
34,506
en
0.526355
from django.db import models from django.conf import settings from django.utils.translation import gettext_lazy as _ from django.shortcuts import redirect from django.urls import reverse from django.utils import timezone import requests from . import exceptions class Gateway(models.Model): label = models.CharFie...
payir/models.py
7,772
Creates a transaction object and submits the transaction to Pay.ir. When called, the method submits the necessary information about the transaction to Pay.ir and returns a HttpResponseRedirect object that can redirect the user to the gateway, if nothing goes wrong. In case of an error, a GatewayError is raised, contai...
3,152
en
0.838729
from setuptools import setup import mp_sync setup( name='mp_sync', version=mp_sync.__version__, description='Moon Package for Sync repository(google drive, notion, mongodb(local/web), local file)', url='https://github.com/hopelife/mp_sync', author='Moon Jung Sam', author_email='monblue@snu.ac.k...
setup.py
666
entry_points={'console_scripts': ['mp_sync = mp_sync.__main__:main']}, python_requires='>=3.8', Python 3.8.6-32 bit install_requires=[ 패키지 사용을 위해 필요한 추가 설치 패키지 'selenium', ], zip_safe=False
196
ko
0.618962
#!/usr/bin/env python import csv import os import argparse import dateutil.parser import json def parse_args(): parser = argparse.ArgumentParser() parser.add_argument("-d", "--dir", type=str, required=True, help="name of the data directory") args = parser.parse_args() return ar...
jhu2json.py
1,740
!/usr/bin/env python Not sure why this is needed???? 'source': 'JHU', If there is a problem e.g. converting the ts just go on.
126
en
0.778711
"""The tests for hls streams.""" from datetime import timedelta from unittest.mock import patch from urllib.parse import urlparse import av from homeassistant.components.stream import request_stream from homeassistant.const import HTTP_NOT_FOUND from homeassistant.setup import async_setup_component import homeassista...
tests/components/stream/test_hls.py
5,094
The tests for hls streams. Setup demo HLS track Request stream Fetch playlist Fetch init Fetch segment Stop stream, if it hasn't quit already Ensure playlist not accessible after stream ends Setup demo HLS track Request stream Fetch playlist Wait a minute Fetch again to reset timer Wait 5 minutes Ensure playlist not ...
596
en
0.880019
# -*- coding: utf-8 -*- ## @package pycv_tutorial.color_space # # 画像処理: 色空間の変換 # @author tody # @date 2016/06/27 import cv2 import matplotlib.pyplot as plt # RGB画像の表示 def showImageRGB(image_file): image_bgr = cv2.imread(image_file) image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB) plt...
opencv/pycv_tutorial/color_space.py
1,941
-*- coding: utf-8 -*- @package pycv_tutorial.color_space 画像処理: 色空間の変換 @author tody @date 2016/06/27 RGB画像の表示 グレースケール画像の表示 HSVチャンネルの表示 Labチャンネルの表示
160
ja
0.982674
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
web/addons/stock/__init__.py
1,115
-*- coding: utf-8 -*- OpenERP, Open Source Management Solution Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either versio...
783
en
0.889938
import numpy as np import tensorflow as tf from copy import deepcopy from abc import ABC, abstractmethod from tensorflow.keras import Model as M from rls.utils.indexs import OutputNetworkType from rls.nn.networks import get_visual_network_from_type from rls.nn.models import get_output_network_from_type ...
rls/utils/build_networks.py
16,408
Use for PD-DDPG ↗ policy_net -> outputs feat -> value_net -> outputs ↘ value_net2 -> outputs ↗ policy_net -> outputs feat ↘ value_net -> outputs ↗ policy_net -> outputs feat -> value_net -> outputs ↘ value_net2 -> outputs visual_s -> visual_net -> feat ↘ ...
1,179
en
0.475489
from decimal import Decimal from django.db import models from polymorphic.models import PolymorphicModel from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericFo...
auction/models/bases.py
6,965
This models functions similarly to a shopping cart, except it expects a logged in user. This is a holder for total number of bids and a pointer to item being bid on. Used as accessor for abstract related (BaseBidItem.bid_items). If you override BaseBidItem and use a label other than "auction" you will also need to set...
734
en
0.902646
import msgpack import zlib import numpy as np import helper_functions as hf import datetime_helper as dh def strip_data_by_time(t_data, data, t_min, t_max): data = np.array([s for s, t in zip(data, t_data) if t >= t_min and t <= t_max]) t_data = np.array([t for t in t_data if t >= t_min and t <= t_max]) return t_da...
src/example_helper.py
2,052
load the topics load the augmento data load the price data set the start and end times if they are specified strip the sentiments and prices outside the shared time range
170
en
0.715984
#!/usr/bin/env python # # $Id$ # # Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Print detailed information about a process. Author: Giampaolo Rodola' <g.rodola@gmail.com> """ import os ...
examples/process_detail.py
4,512
Print detailed information about a process. Author: Giampaolo Rodola' <g.rodola@gmail.com> !/usr/bin/env python $Id$ Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. python 2/3 compatibility layer
318
en
0.697861
# -*- coding: utf-8 -*- """Cisco DNA Center Clients API wrapper. Copyright (c) 2019-2021 Cisco Systems. 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 limi...
dnacentersdk/api/v1_3_1/clients.py
9,602
Cisco DNA Center Clients API (version: 1.3.1). Wraps the DNA Center Clients API and exposes the API as native Python methods that return native Python objects. Initialize a new Clients object with the provided RestSession. Args: session(RestSession): The RESTful session object to be used for API calls to ...
3,803
en
0.750577
#!/usr/bin/python """ Sample program to add SSO options to a Manager/Pinbox. :Copyright: Copyright 2014 Lastline, Inc. All Rights Reserved. Created on: Dec 8, 2014 by Lukyan Hritsko """ import requests import argparse import ConfigParser import os.path import logging import re from lxml import etre...
examples/add_saml_sso_from_metadata.py
11,013
Sample program to add SSO options to a Manager/Pinbox. :Copyright: Copyright 2014 Lastline, Inc. All Rights Reserved. Created on: Dec 8, 2014 by Lukyan Hritsko !/usr/bin/python Python logger... Parser for add mode Parser for delete mode If no display name exists, let's use the FQDN of the IdP pylin...
336
en
0.662545
""" Forgot Password Web Controller """ # Standard Library import os # Third Party Library from django.views import View from django.shortcuts import render from django.utils.translation import gettext as _ # Local Library from app.modules.core.context import Context from app.modules.entity.option_entity import Optio...
app/controllers/web/forgot_password.py
1,185
Forgot Password Web Controller Standard Library Third Party Library Local Library
83
en
0.771231
import os import dj_database_url from decouple import config, Csv # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/...
instagram/settings.py
4,062
Build paths inside the project like this: os.path.join(BASE_DIR, ...) Quick-start development settings - unsuitable for production See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ SECURITY WARNING: keep the secret key used in production secret! SECURITY WARNING: don't run with debug turned on in p...
769
en
0.600317
import json import os import re from yandeley.models.annotations import Annotation from yandeley.response import SessionResponseObject class File(SessionResponseObject): """ A file attached to a document. .. attribute:: id .. attribute:: size .. attribute:: file_name .. attribute:: mime_type...
yandeley/models/files.py
4,179
A file attached to a document. .. attribute:: id .. attribute:: size .. attribute:: file_name .. attribute:: mime_type .. attribute:: filehash .. attribute:: download_url Adds a highlight to this file. :param bounding_boxes: the area the highlight covers on the file. :param color: the color of the highlight. :return:...
1,245
en
0.656459
#!/usr/bin/env python # Copyright 2016 Vimal Manohar # 2016 Johns Hopkins University (author: Daniel Povey) # Apache 2.0 from __future__ import print_function import sys, operator, argparse, os from collections import defaultdict # This script reads 'ctm-edits' file format that is produced by get_ctm_e...
egs/wsj/s5/steps/cleanup/internal/segment_ctm_edits.py
52,847
!/usr/bin/env python Copyright 2016 Vimal Manohar 2016 Johns Hopkins University (author: Daniel Povey) Apache 2.0 This script reads 'ctm-edits' file format that is produced by get_ctm_edits.py and modified by modify_ctm_edits.py and taint_ctm_edits.py Its function is to produce a segmentation and text fro...
13,558
en
0.913334
from __future__ import annotations from typing import TYPE_CHECKING, cast from .enums import ChannelType from .messageable import Messageable if TYPE_CHECKING: from .state import State from .types import Channel as ChannelPayload from .types import DMChannel as DMChannelPayload from .types import Gro...
revolt/channel.py
3,130
Base class for all channels Attributes ----------- id: :class:`str` The id of the channel channel_type: ChannelType The type of the channel server: Optional[:class:`Server`] The server the channel is part of A DM channel The Saved Message Channel A voice channel
275
en
0.652919
''' Author: what-is-me E-mail: nt_cqc@126.com Github: https://github.com/what-is-me LeetCode: https://leetcode-cn.com/u/what-is-me/ Date: 2021-05-17 23:22:14 LastEditors: what-is-me LastEditTime: 2021-05-19 12:33:23 Description: 查询单个单词/词组意思 ''' import re import urllib.parse import requests class getimg...
Dict-search/__init__.py
8,022
Author: what-is-me E-mail: nt_cqc@126.com Github: https://github.com/what-is-me LeetCode: https://leetcode-cn.com/u/what-is-me/ Date: 2021-05-17 23:22:14 LastEditors: what-is-me LastEditTime: 2021-05-19 12:33:23 Description: 查询单个单词/词组意思 选择翻译网站 如果是词组,就将空格替换 获得网址源代码
266
en
0.606092
#!/usr/bin/env python import contextlib as __stickytape_contextlib @__stickytape_contextlib.contextmanager def __stickytape_temporary_dir(): import tempfile import shutil dir_path = tempfile.mkdtemp() try: yield dir_path finally: shutil.rmtree(dir_path) with __stickytape_temporary_...
src/main/resources/pydev_tunnel/tunnel_single_script.py
18,082
!/usr/bin/env python Copyright 2021 Grégoire Payen de La Garanderie. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.Local connection worker.Start the child connection (the remote), establish the pipe between the parent and child process,then add a monitor for the loc...
448
en
0.822101
""" nuts_finder ----------- You give it a point, it tells you all the EU NUTS regions """ import geojson import requests import re from io import BytesIO from zipfile import ZipFile from shapely import geometry from functools import lru_cache import logging YEAR_REGEX = "NUTS ([0-9]+)" SCALE_REGEX = "1:([0-9]+) Milli...
nuts_finder/nuts_finder.py
3,930
Object for holding onto NUTS data and exposing to the user, also providing a lat, lon lookup Args: year (int): If provided, NUTS regions for this year will be used (if available) scale (int): If provided, NUTS regions at this resolution will be used (if available) Use the provided regex to find allowed values o...
1,221
en
0.76102
from chatterbot.trainers import ListTrainer from chatterbot import ChatBot bot = ChatBot('Test') conversa = ['oi', 'olá', 'Tudo bem?', 'Estou bem'] conversa2 = ['Gosta de futebol?','Eu adoro,sou tricolor Paulista e você','Qual seu filme favorito?' , 'O meu é Rocky 1'] bot.set_trainer(ListTrainer) bot.train(conversa)...
Bot.py
532
if float (response.confidence) >0.5else: print ("Eu não sei")
61
pt
0.81485
# Copyright 2020 Efabless Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in...
scripts/csv2html/csv2html.py
2,489
Copyright 2020 Efabless Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software...
558
en
0.854989
""" Load volumes into vpv from a toml config file. Just load volumes and no overlays Examples -------- Example toml file orientation = 'sagittal' [top] specimens = [ 'path1.nrrd', 'path2.nrrd', 'path3.nrrd'] [bottom] specimens = [ 'path1.nrrd', 'path2.nrrd', 'path3.nrrd'] """ import sys from pathlib import Path ...
utils/data_loader_2.py
1,778
Load volumes into vpv from a toml config file. Just load volumes and no overlays Examples -------- Example toml file orientation = 'sagittal' [top] specimens = [ 'path1.nrrd', 'path2.nrrd', 'path3.nrrd'] [bottom] specimens = [ 'path1.nrrd', 'path2.nrrd', 'path3.nrrd'] We allow only top vier visible Set the top ...
387
en
0.590424
# author rovo98 import os import tensorflow as tf from tensorflow.keras.utils import plot_model from tensorflow.keras.callbacks import EarlyStopping from model_data_input import load_processed_dataset from models.fdconv1d_lstm.model import build_fdconv1d_lstm from models.utils.misc import running_timer from models.u...
models/fdconv1d_lstm/train.py
6,074
author rovo98 filter warning logs of tf enable memory growth for every GPU. Using GPU devices to train the models is recommended. uncomment the following several lines of code to disable forcing using GPU. noinspection DuplicatedCode num_of_faulty_type = 3 train_x, train_y, test_x, test_y = load_processed_dataset( ...
2,662
en
0.591419
"""babyshop URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/4.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-base...
babyshop_app/babyshop/urls.py
1,006
babyshop URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/4.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based v...
624
en
0.626306
# __author__ = 'clarkmatthew' # import json class Namespace(object): """ Convert dict (if provided) into attributes and return a somewhat generic object """ def __init__(self, newdict=None): if newdict: for key in newdict: value = newdict[key] tr...
config_manager/namespace.py
1,031
__author__ = 'clarkmatthew'
27
en
0.368341
import datetime import json import os import sys import urllib import urlparse from collections import OrderedDict from time import mktime import dateutil.parser import feedparser import requests import xbmc import xbmcaddon import xbmcgui import xbmcplugin from bs4 import BeautifulSoup stations = { 'p00fzl68': ...
addon.py
13,300
download the source HTML for the page using requests and parse the page using BeautifulSoup Parse the stuff passed into the addon TODO Filter by only audio items, and order with the highest bitrate first Pick the first stream available for the highest bitrate item Sort the podcasts by title Create a range of the last 3...
361
en
0.825852
#!/usr/bin/env python3 # Copyright (c) 2014-2016 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 wallet accounts properly when there are cloned transactions with malleated scriptsigs.""" imp...
test/functional/txn_clone.py
7,534
Test the wallet accounts properly when there are cloned transactions with malleated scriptsigs. !/usr/bin/env python3 Copyright (c) 2014-2016 The Bitcoin Core developers Distributed under the MIT software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. Start with split...
1,651
en
0.880816
import hydra import os import logging import json import numpy as np import torch import matplotlib.pyplot as plt from collections import defaultdict import json from IPython import embed # from AD_models import AD_Time_Series # from AD_utils import AD_report, AD_dataset, plot_AD_dataset, AD_preprocessing # import T...
main.py
6,356
from AD_models import AD_Time_Series from AD_utils import AD_report, AD_dataset, plot_AD_dataset, AD_preprocessing import T_models, A_models Trend parameters Range of values of regularization parameter for HP filter (regulates the regularity of the trend component) Lenght of the HP filter (here we could choose large ...
736
en
0.545396
"""DATA STRUCTURES""" # Algorithms are set of rules used to solve a problem # Data structures are a way of organizing data in a computer # colors = ['red', 'yellow', [5, 6], 'blue'] friends = ['Josh', 'Renee', 'Agnes'] # print(colors) # print(colors[1]) # colors[2] = 'green' # mutability of lists # print(colors) # pri...
Lists/lists-beg.py
884
DATA STRUCTURES Algorithms are set of rules used to solve a problem Data structures are a way of organizing data in a computer colors = ['red', 'yellow', [5, 6], 'blue'] print(colors) print(colors[1]) colors[2] = 'green' mutability of lists print(colors) print(len(friends)) print(len(colors)) gives you the number...
698
en
0.790953
import numpy as np import random import os import json import math import cv2 def getPaddedROI(img, center_x, center_y, width, height): #print(str(int(center_x)) + "," + str(int(center_y))) paddingColor = [0,0,0] top_left_x = center_x - int(width/2)-1 #print("top_left_x:") #print(top_left_x) to...
imageLoader.py
7,380
print(str(int(center_x)) + "," + str(int(center_y)))print("top_left_x:")print(top_left_x)print("top_left_y:")print(top_left_y)print ("bottom_right_x / y")print(str(bottom_right_x) + " / " + str(bottom_right_y))border padding neededprint(border_left)print(border_right)print(border_top)print(border_bottom)cv2.imshow("ori...
1,989
en
0.602988
# Copyright 2018 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...
official/nlp/transformer/utils/metrics.py
16,579
Wrap a metric fn that returns scores and weights as an eval metric fn. The input metric_fn returns values for the current batch. The wrapper aggregates the return values collected over all of the batches evaluated. Args: metric_fn: function that returns scores and weights for the current batch's logits and pred...
6,933
en
0.777809
# Copyright 2019-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" fil...
test-toolkit/integration/__init__.py
2,128
Copyright 2019-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying thi...
627
en
0.913743
# -*- coding: utf-8 -*- # # This file is part of Flask-CLI # Copyright (C) 2015 CERN. # # Flask-AppFactory is free software; you can redistribute it and/or # modify it under the terms of the Revised BSD License; see LICENSE # file for more details. """Flask extension to enable CLI.""" import types from . import AppG...
virtual/lib/python3.6/site-packages/flask_cli/ext.py
1,688
Flask-CLI extension. Initialization of the extension: >>> from flask import Flask >>> from flask_cli import FlaskCLI >>> app = Flask('myapp') >>> FlaskCLI(app) or alternatively using the factory pattern: >>> app = Flask('myapp') >>> ext = FlaskCLI() >>> ext.init_app(app) Initialize the Flask-CLI. Initialize a Flask...
694
en
0.726596
from django.http import HttpResponseRedirect from django.views.generic import ListView,CreateView,UpdateView,DetailView,View from django.shortcuts import render, redirect from ecom import forms, models from django.utils.decorators import method_decorator def admin_required(function): def wrap(request, *args, **k...
ecom/paquetes/view_paquete.py
2,215
specify the model for create view specify the fields to be displayed templete for updatingmodel fields / if you want to select all fields, use "__all__" templete for updating
174
en
0.302976
# Copyright 2018-2021 Xanadu Quantum Technologies 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 applicabl...
tests/tape/interfaces/test_qnode_jax.py
6,933
New quantum tape construct method, that performs the transform on the tape in a define-by-run manner Transforms every RY(y) gate in a circuit to RX(-a*cos(y)) Test that operation and nested tapes expansion is differentiable Test a simple use of qnode with a JAX interface and non-JAX device Test the use of jax.grad Test...
1,465
en
0.805174
"""Common DB report tests.""" import datetime from pycounter.constants import METRICS def test_version(db_report): assert db_report.report_version == 4 def test_year(db_report): assert db_report.year == 2012 def test_publisher(db_report): for publication in db_report: assert publication.publi...
pycounter/test/test_db_common.py
906
Common DB report tests.
23
en
0.967301
# coding: utf-8 """ convertapi Convert API lets you effortlessly convert file formats and types. # noqa: E501 OpenAPI spec version: v1 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import unittest import cloudmersive_convert_api_...
test/test_docx_set_header_request.py
1,013
DocxSetHeaderRequest unit test stubs Test DocxSetHeaderRequest convertapi Convert API lets you effortlessly convert file formats and types. # noqa: E501 OpenAPI spec version: v1 Generated by: https://github.com/swagger-api/swagger-codegen.git coding: utf-8 noqa: E501 FIXME: construct object with mandatory attribu...
450
en
0.451917
import abc import logging import Sea import numpy as np import itertools from ..base import Base class Connection(Base, Sea.model.connections.Connection): """ Abstract base class for all :mod:`Sea.adapter.connections` classes. """ __metaclass__ = abc.ABCMeta def __init__(self, obj, system, co...
Sea/adapter/connections/Connection.py
7,627
Abstract base class for all :mod:`Sea.adapter.connections` classes. Add couplings to the :attr:`connection`. :param connection: an instance of :class:`Sea.adapter.baseclasses.Connection` Determine the type of coupling. Detects what type of connection the components have. Based on the type of connection and on the type...
2,482
en
0.617051
import warnings from contextlib import contextmanager from numba.tests.support import override_config, TestCase from numba.cuda.testing import skip_on_cudasim from numba import cuda from numba.core import types from numba.cuda.testing import SerialMixin import unittest @skip_on_cudasim("Skipped on simulator") class ...
numba/cuda/tests/cudapy/test_deprecation.py
1,328
Tests features that will be deprecated
38
en
0.928615
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
tensorflow/python/kernel_tests/variables_test.py
35,929
Expects an error if an initializer is in a control-flow scope. Tests for tf.py. Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http:...
1,834
en
0.881681
# generated from catkin/cmake/template/pkg.context.pc.in CATKIN_PACKAGE_PREFIX = "" PROJECT_PKG_CONFIG_INCLUDE_DIRS = "/home/autolabor/catkin_ws/devel/include;/home/autolabor/catkin_ws/src/navigation/amcl/include".split(';') if "/home/autolabor/catkin_ws/devel/include;/home/autolabor/catkin_ws/src/navigation/amcl/inclu...
build/navigation/amcl/catkin_generated/pkg.develspace.context.pc.py
680
generated from catkin/cmake/template/pkg.context.pc.in
54
en
0.406568
import re from pygbif.gbifutils import gbif_baseurl, bool2str, requests_argset, gbif_GET def search( taxonKey=None, repatriated=None, kingdomKey=None, phylumKey=None, classKey=None, orderKey=None, familyKey=None, genusKey=None, subgenusKey=None, scientificName=None, countr...
pygbif/occurrences/search.py
20,897
Search GBIF occurrences :param taxonKey: [int] A GBIF occurrence identifier :param q: [str] Simple search parameter. The value for this parameter can be a simple word or a phrase. :param spellCheck: [bool] If ``True`` ask GBIF to check your spelling of the value passed to the ``search`` parameter. IMPORTANT: This ...
16,767
en
0.677745
# coding: utf-8 """ SCORM Cloud Rest API REST API used for SCORM Cloud integrations. OpenAPI spec version: 2.0 Contact: systems@rusticisoftware.com Generated by: https://github.com/swagger-api/swagger-codegen.git """ from pprint import pformat from six import iteritems import re class Destina...
rustici_software_cloud_v2/models/destination_id_schema.py
3,463
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 DestinationIdSchema - a model defined in Swagger :param dict swaggerTypes: The key is attribute name and the value is attribute type. :param dict at...
1,227
en
0.617712
from __future__ import print_function import os import time import random import datetime import scipy.misc import numpy as np import tensorflow as tf import tensorflow.contrib.slim as slim from datetime import datetime from util.util import * from util.BasicConvLSTMCell import * class DEBLUR(object): def __init_...
models/model.py
14,770
input / output channels if args.phase == 'train': encoder decoder generator calculate multi-scale loss losses training vars build model learning rate decay training operators session and thread training summary update G network print loss_value summary_str = sess.run(summary_op, feed_dict={inputs:batch_input, gt:batch_...
444
en
0.753559
from __future__ import print_function, division import torch import torch.nn as nn import torch.optim as optim from torch.optim import lr_scheduler from torchvision import datasets, models, transforms import numpy as np import time import os import copy import argparse from azureml.core.run import Run from azureml.co...
azure-ml-pipelines/pytorch/training-folder/pytorch_train.py
7,288
Load a pretrained model and reset the final fully connected layer. Load the train/val data. Train the model. get the Azure ML run object Data augmentation and normalization for training Just normalization for validation load training/validation data Each epoch has a training and validation phase Set model to training...
1,370
en
0.691442
from mooquant import bar, strategy from mooquant.analyzer import drawdown, returns, sharpe, trades from mooquant.broker.backtesting import TradePercentage from mooquant.broker.fillstrategy import DefaultStrategy from mooquant.technical import cross, ma from mooquant.tools import tushare class thrSMA(strategy.Backtest...
stratlib/sample_SMA.py
4,244
self.info("long close") If a position was not opened, check if we should enter a long position. self.info("sell %s" % (bars.getDateTime())) self.info("buy %s" % (bars.getDateTime())) 夏普率 最大回撤 收益率 收益曲线
200
en
0.363953
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
package/spack-glew/package.py
2,036
The OpenGL Extension Wrangler Library. Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory. This file is part of Spack. Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. LLNL-CODE-647188 For details, see https://github.com/spack/spa...
1,183
en
0.889361
from django.db import models from django.utils.timezone import now # Create your models here. # <HINT> Create a Car Make model `class CarMake(models.Model)`: # - Name # - Description # - Any other fields you would like to include in car make model # - __str__ method to print a car make object class CarMake(models.Mo...
server/djangoapp/models.py
2,687
Create your models here. <HINT> Create a Car Make model `class CarMake(models.Model)`: - Name - Description - Any other fields you would like to include in car make model - __str__ method to print a car make object <HINT> Create a Car Model model `class CarModel(models.Model):`: - Many-To-One relationship to Car Make m...
938
en
0.838959
#!/usr/bin/python # Copyright (c) 2017 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module:...
venv/lib/python2.7/site-packages/ansible/modules/cloud/amazon/iam_user.py
12,346
!/usr/bin/python Copyright (c) 2017 Ansible Project GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) caught by imported HAS_BOTO3 If new_attached_policies is None it means we want to remove all policies List comprehension that looks for any policy in the 'policy_names' list tha...
971
en
0.885442
# -*- coding: utf8 -*- from __future__ import unicode_literals import logging import netifaces def getIpWindows(adapteridx): try: import wmi except: logging.error("You must need Win32com (win32 extensions for python)") raise adapters = wmi.WMI().Win32_NetworkAdapt...
conf.py
2,373
-*- coding: utf8 -*- in minutes
31
en
0.687334
""" @Author : liujianhan @Date : 2018/5/15 上午10:48 @Project : KGE @FileName : service.py @Description : 服务接口模块 """ import codecs import json import os import time from typing import Dict import torch from dotmap import DotMap from .core.predict import get_entity_relation_with_id from...
project/knowledge_graph_embedding/project_distmult_rotate_transe/service.py
2,917
推理函数 @param target_triple: 目标需预测三元组:'头实体 关系 尾实体' @return: 头尾实体的10个预测结果 模型加载 @param model_path: 模型文件夹路径 @return: @Author : liujianhan @Date : 2018/5/15 上午10:48 @Project : KGE @FileName : service.py @Description : 服务接口模块
242
zh
0.737887
# Copyright (c) Microsoft Corporation and contributors. # Licensed under the MIT License. import numpy as np import pandas as pd class LeastSquaresBinaryClassifierLearner: def __init__(self): self.weights = None def fit(self, X, Y, sample_weight): sqrtW = np.sqrt(sample_weight) matX ...
test/unit/reductions/exponentiated_gradient/simple_learners.py
1,040
Copyright (c) Microsoft Corporation and contributors. Licensed under the MIT License.
85
en
0.585227
""" An ASGI middleware. Based on Tom Christie's `sentry-asgi <https://github.com/encode/sentry-asgi>`_. """ import asyncio import inspect import urllib from sentry_sdk._functools import partial from sentry_sdk._types import MYPY from sentry_sdk.hub import Hub, _should_send_default_pii from sentry_sdk.integrations._w...
sentry_sdk/integrations/asgi.py
8,152
Instrument an ASGI application with Sentry. Provides HTTP/websocket data to sent events and basic handling for exceptions bubbling up through the middleware. :param unsafe_context_data: Disable errors when a proper contextvars installation could not be found. We do not recommend changing this from the default. Extract...
1,845
en
0.869166
# -*- coding: utf-8 -*- import re from packaging import version import phonemizer from phonemizer.phonemize import phonemize from TTS.utils.text import cleaners from TTS.utils.text.symbols import make_symbols, symbols, phonemes, _phoneme_punctuations, _bos, \ _eos # Mappings from symbol to numeric ID and vice ver...
utils/text/__init__.py
6,623
Converts a sequence of IDs back to a string Converts a sequence of IDs back to a string Convert graphemes to phonemes. Converts a string of text to a sequence of IDs corresponding to the symbols in the text. The text can optionally have ARPAbet sequences enclosed in curly braces embedded in it. For example, "Turn left...
1,361
en
0.767532
# -*- coding: utf-8 -*- ''' loadFromExcel.py is an example of a plug-in that will load an extension taxonomy from Excel input and optionally save an (extension) DTS. (c) Copyright 2013 Mark V Systems Limited, All rights reserved. ''' import os, io, sys, time, re, traceback, json, posixpath from fnmatch import fnmatch...
arelle/plugin/loadFromExcel.py
123,514
loadFromExcel.py is an example of a plug-in that will load an extension taxonomy from Excel input and optionally save an (extension) DTS. (c) Copyright 2013 Mark V Systems Limited, All rights reserved. -*- coding: utf-8 -*- excel values may have encoded unicode, such as _0000D_ usually part of type but optionally se...
7,646
en
0.698857
import argparse import colorama import json import os import time from string import Template import modules from modules import site_config from modules import util # argument defaults and options for the CLI module_choices = ['clean', 'stix_data', 'groups', 'search', 'matrices', 'mitigations', 'software', 'tactics',...
update-attack.py
7,061
Create argument parser and parse arguments Given a list of modules from command line, remove modules that appear in module directory that are not in list. Remove modules from menu if they are not in modules list from argument Remove modules from running pool if they are not in modules list from argument Validate subd...
768
en
0.619542
#!/usr/bin/env python3 # # main.py # # Specific command-line utility for Mellanox platform # try: import sys import subprocess import click import xml.etree.ElementTree as ET from sonic_py_common import device_info except ImportError as e: raise ImportError("%s - required module not found" % st...
show/plugins/mlnx.py
4,328
This function parses the SAI XML profile used for mlnx to get whether ISSU is enabled or disabled @return: True/False Show ISSU status Show Mellanox platform information Run bash command and print output to stdout Show sniffer status !/usr/bin/env python3 main.py Specific command-line utility for Mellanox plat...
503
en
0.622648
# 右侧加法和原处加法: __radd__和__iadd__ """ __add__并不支持+运算符右侧使用实例对象。要实现一并编写__radd__方法。 只有当+右侧的对象是实例,而左边对象不是类实例时,Python才会调用__radd++, 在其他情况下则是由左侧对象调用__add__方法。 """ class Commuter: def __init__(self, val): self.val = val def __add__(self, other): # 如果没有instance测试,当两个实例相加并且__add__触发 # __radd__的时候...
python_know/normal/demo9_7.py
1,142
__add__并不支持+运算符右侧使用实例对象。要实现一并编写__radd__方法。 只有当+右侧的对象是实例,而左边对象不是类实例时,Python才会调用__radd++, 在其他情况下则是由左侧对象调用__add__方法。 右侧加法和原处加法: __radd__和__iadd__ 如果没有instance测试,当两个实例相加并且__add__触发 __radd__的时候,我们最终得到一个Commuter,其val是另一个Commuter 注意和__add__顺序不一样 原处加法 编写__iadd__或__add__如果前者空缺使用后者
274
zh
0.951611
#!/usr/bin/env python # -*- coding: utf-8 -*- # ========================================================================= # Author Eduard Kabrinskyi <soulroot@gmail.com> Skype: soulroot@hotmail.com # ========================================================================= # ========================= # Main APP defin...
spider.py
5,154
!/usr/bin/env python -*- coding: utf-8 -*- ========================================================================= Author Eduard Kabrinskyi <soulroot@gmail.com> Skype: soulroot@hotmail.com ========================================================================= ========================= Main APP definitions ========...
848
fr
0.300853
from .base import * import os # how many data points are enough to calculate confidence? MINIMUM_SAMPLE_SIZE = 3 # original phrase is good enough for export TRANSCRIPT_PHRASE_POSITIVE_CONFIDENCE_LIMIT = .51 # original phrase needs correction TRANSCRIPT_PHRASE_NEGATIVE_CONFIDENCE_LIMIT = -.51 # correction is good eno...
mla_game/settings/stage.py
1,461
how many data points are enough to calculate confidence? original phrase is good enough for export original phrase needs correction correction is good enough to award points and export data correction no longer needs votes and can replace original phrase
254
en
0.935547
import time import threading import subprocess import helpers from settings import Settings def listener(): global data_source print("**** SIDE_THREAD ID == ", threading.get_ident()) while True: return_data = subprocess.run([data_source.settings.loaded['localization_bin']], stdout=subprocess.PIPE) ...
virtual_filesystem/localization.py
860
Waits 1 second till the next localization check
47
en
0.463953