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) 2021 Airbyte, Inc., all rights reserved. # import json import re from typing import Union from jsonschema import RefResolver from pydantic import BaseModel, Field from .streams import DEFAULT_START_DATE, ReportGranularity class OauthCredSpec(BaseModel): class Config: title = "OAuth2....
airbyte-integrations/connectors/source-tiktok-marketing/source_tiktok_marketing/spec.py
4,541
we're overriding the schema classmethod to enable some post-processing Copyright (c) 2021 Airbyte, Inc., all rights reserved. it is string because UI has the bug https://github.com/airbytehq/airbyte/issues/6875 it is float because UI has the bug https://github.com/airbytehq/airbyte/issues/6875
296
en
0.835223
from TASSELpy.java.lang.Number import Number, metaNumber from TASSELpy.java.lang.Comparable import Comparable from TASSELpy.utils.DocInherit import DocInherit from TASSELpy.utils.Overloading import javaOverload,javaConstructorOverload from TASSELpy.javaObj import javaObj from TASSELpy.utils.helper import make_sig from ...
TASSELpy/java/lang/Long.py
8,941
Wrapper class for java.lang.Long Instantiates a new Long Signatures: Long(long value) Long(String s) Arguments: Long(long value) value -- The long to wrap in the object Long (String s) s -- The string representing the long Wrapper class for java.lang.Long Numeric magic methods Arithmetic magic methods
314
en
0.281293
""" Django settings for profiles_project project. Generated by 'django-admin startproject' using Django 3.2.9. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ fro...
profiles_project/settings.py
3,389
Django settings for profiles_project project. Generated by 'django-admin startproject' using Django 3.2.9. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ Build path...
1,091
en
0.664137
import os import re import struct import glob import numpy as np import frame_utils import skimage import skimage.io import torch from torch.utils.data import Dataset class KLens(Dataset): #def __init__(self,raft_path="/data2/opticalflow/rnd/opticalflow/RAFT/out_klens_raft_chairs", root_path="/data2/opticalflow/...
data_loaders/KLens.py
7,492
def __init__(self,raft_path="/data2/opticalflow/rnd/opticalflow/RAFT/out_klens_raft_chairs", root_path="/data2/opticalflow/KLENS/images/",root_path2="/data2/opticalflow/KLENS/pins/",filenumberlist=["0030","1106","1113","1132","1134","1167","1173"],split="train",ref="",meas=""):print(raftflowpath)file_list["train"].exte...
1,461
en
0.344014
# Telegram settings TG_CLI = '/opt/tg/bin/telegram-cli' TG_PUBKEY = '/opt/tg/tg-server.pub' RECEPIENT = '@your-tg-recepient' # Reddit App settings REDDIT_APP_KEY = 'c...w' REDDIT_APP_SECRET = 'T...c' REDDIT_USER_AGENT = ('Damaris Bot, v0.1. Read only bot to read posts from' '/r/cats') # Sample Ca...
sample_settings.py
383
Telegram settings Reddit App settings Sample Captions
53
en
0.707184
import os import pickle import numpy as np from tqdm import tqdm from deeptutor.envs.DashEnv import * from deeptutor.envs.EFCEnv import EFCEnv from deeptutor.envs.HRLEnv import * from deeptutor.infrastructure.utils import * from deeptutor.tutors.LeitnerTutor import LeitnerTutor from deeptutor.tutors.RandTutor import ...
deeptutor/scripts/run.py
3,743
override existing data ("Random", RandTutor), ("Leitner", LeitnerTutor), ("SuperMnemo", SuperMnemoTutor), ("Threshold", ThresholdTutor), ("MLPTRPO", MLPTRPOTutor), ("GRUTRPO", GRUTRPOTutor), ("PPO", PPOTutor),
209
en
0.301484
# Copyright 2013-2019 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) from spack import * class PyDecorator(PythonPackage): """The aim of the decorator module it to simplify the usage of...
var/spack/repos/builtin/packages/py-decorator/package.py
984
The aim of the decorator module it to simplify the usage of decorators for the average programmer, and to popularize decorators by showing various non-trivial examples. Copyright 2013-2019 Lawrence Livermore National Security, LLC and other Spack Project Developers. See the top-level COPYRIGHT file for details. SPDX-...
359
en
0.775344
"""Support for Aqualink pool lights.""" from iaqualink import AqualinkLightEffect from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_EFFECT, DOMAIN, SUPPORT_BRIGHTNESS, SUPPORT_EFFECT, LightEntity, ) from homeassistant.config_entries import ConfigEntry from homeassistant.core im...
homeassistant/components/iaqualink/light.py
2,766
Representation of a light. Return current brightness of the light. The scale needs converting between 0-100 and 0-255. Return the current light effect if supported. Return supported light effects. Return whether the light is on or off. Return the name of the light. Return the list of features supported by the light. S...
469
en
0.881435
#!/usr/bin/env python # -*- coding: utf-8 -*- from collections import defaultdict import argparse import cld2 import langid import sys """ Removes some wrongly aligned pairs from hunalign output """ class LanguageIdentifier(object): def __init__(self, use_cld2, valid_languages=None): self.use_cld2 = u...
baseline/filter_hunalign_bitext.py
4,854
Check if the language of the segment cannot be reliably identified as another language. If another than the expected language is detected return False !/usr/bin/env python -*- coding: utf-8 -*- unreliable is still counted as OK confidence for wrong language higher than 90%
275
en
0.925444
"""Define abstract base classes to construct FileFinder classes.""" import os import shutil from abc import ABC, abstractmethod from dataclasses import dataclass, field from pathlib import Path from typing import Optional, Sequence, Union import mne_bids @dataclass class FileFinder(ABC): """Basic representation...
src/pte/filetools/filefinder_abc.py
7,223
Exception raised when invalid Reader is passed. Attributes: directory -- input directory which caused the error Basic representation of class for finding and filtering files. Exception raised when electrode hemisphere is not specified in settings. Attributes: subject -- input subject which caused the error ...
876
en
0.568423
__all__ = ("group_attempts", "fails_filter", "reduce_to_failures",) def group_attempts(sequence, filter_func=None): if filter_func is None: filter_func = lambda x:True last, l = None, [] for x in sequence: if isinstance(x, tuple) and x[0] == 'inspecting': if l: ...
src/pkgcore/resolver/util.py
1,211
inline ignored frames
21
en
0.389758
#!/usr/bin/python -u # -*- coding: latin-1 -*- # # Dinner problem in Z3 # # From http://www.sellsbrothers.com/spout/#The_Logic_of_Logic # """ # My son came to me the other day and said, "Dad, I need help with a # math problem." The problem went like this: # # * We're going out to dinner taking 1-6 grandparents, 1-10 p...
z3/dinner.py
1,511
!/usr/bin/python -u -*- coding: latin-1 -*- Dinner problem in Z3 From http://www.sellsbrothers.com/spout/The_Logic_of_Logic """ My son came to me the other day and said, "Dad, I need help with a math problem." The problem went like this: * We're going out to dinner taking 1-6 grandparents, 1-10 parents and/or 1-40 chi...
895
en
0.88553
# ----------------------------------------------------------------------------- # Libraries # ----------------------------------------------------------------------------- # Core libs from typing import TYPE_CHECKING # Third party libs from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView...
src/apps/users/views/rest/client_address.py
1,401
----------------------------------------------------------------------------- Libraries ----------------------------------------------------------------------------- Core libs Third party libs Project libs If type checking, __all__ ----------------------------------------------------------------------------- Constants ...
727
en
0.164674
import pyasdf import numpy as np import scipy.fftpack import matplotlib.pyplot as plt ''' this script takes a chunk of noise spectrum for a station pair and compare their cross-correlation functions computed using two schemes: one is averaging the frequency domain and the other is in the time domain ''' def cross...
test/data_check/check_linearity_fft.py
2,775
------convert all 2D arrays into 1D to speed up--------------convert all 2D arrays into 1D to speed up-------------common parameters-----------------reading the data------------------select the sections----------plotting----
224
en
0.491519
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 1999-2020 Alibaba Group Holding 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-...
mars/tensor/fft/irfft2.py
2,089
Compute the 2-dimensional inverse FFT of a real array. Parameters ---------- a : array_like The input tensor s : sequence of ints, optional Shape of the inverse FFT. axes : sequence of ints, optional The axes over which to compute the inverse fft. Default is the last two axes. norm : {None, "ortho"}, o...
1,252
en
0.742303
"""WebPush Style Autopush Router This router handles notifications that should be dispatched to an Autopush node, or stores each individual message, along with its data, in a Message table for retrieval by the client. """ import json import time from StringIO import StringIO from typing import Any # noqa from botoc...
autopush/router/webpush.py
10,102
Implements :class: `autopush.router.interface.IRouter` for internal routing to an autopush node Create a new Router errBack for ignoring provisioned throughput errors Saves a notification, returns a deferred. This version of the overridden method saves each individual message to the message table along with relevant r...
2,262
en
0.770117
import json import os import pandas import redis import types def json2redis(data,r): if isinstance(data, types.ListType): for row in data: channel = row['channel'] data_type = row['data_type'] rkey = 'channel_{}_{}'.format(channel,data_type) r.lpush(rkey,ro...
train-app/helper_functions.py
1,519
initialize redis connection for local and CF deployment running locally running on CF
85
en
0.824793
# # BSD 3-Clause License # # Copyright (c) 2019, Analog Devices, 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, ...
tools/calibration-96tof1/tof_calib/regwrite_generator.py
7,622
BSD 3-Clause License Copyright (c) 2019, Analog Devices, 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 cond...
1,659
en
0.878174
#!usr/bin/env python #-*- coding:utf-8 -*- """ @author: nico @file: pipline.py @time: 2018/05/05 """ from django.contrib.auth import get_user_model from bloguser.utils import get_image_from_url from uuid import uuid4 User = get_user_model() def save_bloguser_extra_profile(backend, user, resp...
apps/bloguser/pipline.py
1,245
see more: http://python-social-auth.readthedocs.io/en/latest/use_cases.html#retrieve-google-friends http://python-social-auth.readthedocs.io/en/latest/pipeline.html :param backend: :param user: :param response: :param args: :param kwargs: :return: @author: nico @file: pipline.py @time: 2018/05/05...
455
en
0.36415
def extractMichilunWordpressCom(item): ''' Parser for 'michilun.wordpress.com' ''' bad = [ 'Recommendations and Reviews', ] if any([tmp in item['tags'] for tmp in bad]): return None vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title...
WebMirror/management/rss_parser_funcs/feed_parse_extractMichilunWordpressCom.py
1,539
Parser for 'michilun.wordpress.com'
35
en
0.297806
workers = 1 # 定义同时开启的处理请求的进程数量,根据网站流量适当调整 worker_class = "gevent" # 采用gevent库,支持异步处理请求,提高吞吐量 # bind = "0.0.0.0:80" bind = "0.0.0.0:80"
gunicorn.conf.py
230
定义同时开启的处理请求的进程数量,根据网站流量适当调整 采用gevent库,支持异步处理请求,提高吞吐量 bind = "0.0.0.0:80"
72
zh
0.774971
from toee import * import char_class_utils import char_editor ################################################### def GetConditionName(): # used by API return "Sorcerer" # def GetSpellCasterConditionName(): # return "Sorcerer Spellcasting" def GetCategory(): return "Core 3.5 Ed Classes" def GetClassDefinitionFla...
tpdatasrc/tpgamefiles/rules/char_class/class016_sorcerer.py
6,202
used by API def GetSpellCasterConditionName(): return "Sorcerer Spellcasting"lvl 0 1 2 3 4 5 6 7 8 9lvl 0 1 2 3 4 5 6 7 8 9 Spell casting Levelup callbacks this regards spell list extension by stuff like Mystic Theurge Available Spells add spell level labels newly taken class add "Level 0" label 4 can...
746
en
0.737428
# Third Party import mxnet as mx from mxnet.ndarray import NDArray # First Party from smdebug.core.collection import DEFAULT_MXNET_COLLECTIONS, CollectionKeys from smdebug.core.hook import CallbackHook from smdebug.core.json_config import DEFAULT_WORKER_NAME from smdebug.core.utils import FRAMEWORK, error_handling_age...
smdebug/mxnet/hook.py
9,853
This function is "applied" to every child in the block. This function in turn registers the forward hook to each module. It helps logging the input output tensors of that module. This function registers the forward hook. If user wants to register the hook for every child in the given block, then the function calls "app...
1,856
en
0.895963
# 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 ...
sdk/graphrbac/azure-graphrbac/azure/graphrbac/models/application_update_parameters.py
8,738
Request parameters for updating a new application. :param allow_guests_sign_in: A property on the application to indicate if the application accepts other IDPs or not or partially accepts. :type allow_guests_sign_in: bool :param allow_passthrough_users: Indicates that the application supports pass through users who ...
5,508
en
0.695226
## Creates 404 page import pystache import utils def main(data): html = pystache.render(data["templates"]["page"], { "title": "Page not found", "description": "Error 404: page not found", ## Since we don't know the depth of this page relative to the root, ## we have to assum...
website-generator.d/80-not-found-page.py
1,103
Creates 404 page Since we don't know the depth of this page relative to the root, we have to assume the db directory is located in the root of this web resource Since we don't know the depth of this page relative to the root, we have to assume the search page is located in the root of this web resource
303
en
0.977143
# Copyright (c) 2010-2020 openpyxlzip # package imports from openpyxlzip.reader.excel import load_workbook from openpyxlzip.xml.functions import tostring, fromstring from openpyxlzip.styles import Border, Side, PatternFill, Color, Font, fills, borders, colors from openpyxlzip.styles.differential import DifferentialSty...
openpyxlzip/formatting/tests/test_formatting.py
7,150
Copyright (c) 2010-2020 openpyxlzip package imports test imports First test the conditional formatting rules read
113
en
0.608945
# 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, overload from .. import _utilities from...
sdk/python/pulumi_azure_native/compute/get_virtual_machine_scale_set.py
17,549
Describes a Virtual Machine Scale Set. Specifies additional capabilities enabled or disabled on the Virtual Machines in the Virtual Machine Scale Set. For instance: whether the Virtual Machines have the capability to support attaching managed data disks with UltraSSD_LRS storage account type. Policy for automatic repai...
3,046
en
0.782946
import pandas as pd from pandas.testing import assert_frame_equal import pytest from unittest import mock from nesta.packages.geo_utils.geocode import geocode from nesta.packages.geo_utils.geocode import _geocode from nesta.packages.geo_utils.geocode import geocode_dataframe from nesta.packages.geo_utils.geocode impor...
nesta/packages/geo_utils/tests/test_geotools.py
23,712
Builds a mocked response for the patched country_iso_code function. Generate dataframe using a mocked output Expected outputs Check expected behaviours Expected outputs Check expected behaviours Generate dataframe using a mocked output Expected outputs Check expected behaviours Expected outputs Check expected behavio...
713
en
0.652405
""" This module is for testing the distributions. Tests should focus on ensuring we can expand distributions without missing emails or getting too many or running into infinite loops. """ from django.test import TestCase from ..models import EmailAddress, Distribution class DistributionTestCase(TestCase): def s...
impression/tests/test_distribution.py
3,447
Test that emails are collected properly. Test that a distribution with cyclic references only collects each email once, and without looping infinitely. Test that a distribution with duplicates to ensure it only collects each email once. Test that a distribution with self references to ensure it only collects each email...
634
en
0.902668
import bpy from bpy import context from . import node_functions from . import material_functions from . import constants import mathutils def update_selected_image(self, context): sel_texture = bpy.data.images[self.texture_index] show_image_in_image_editor(sel_texture) def show_image_in_image_editor(image):...
Functions/visibility_functions.py
7,196
on what object to work add mix node set factor to 1 image texture in base color remove mix and reconnect base color
115
en
0.741491
#!/usr/bin/env python import sys import re def setup_python3(): # Taken from "distribute" setup.py from distutils.filelist import FileList from distutils import dir_util, file_util, util, log from os.path import join tmp_src = join("build", "src") log.set_verbosity(1) fl = FileList() ...
setup.py
2,926
!/usr/bin/env python Taken from "distribute" setup.py arrange setup to use the copy Find version. We have to do this because we can't import it in Python 3 until its been automatically converted in the setup process.
216
en
0.902633
import datetime import urllib from django.conf import settings from django.contrib.auth.models import User from django.urls import reverse from django.utils.translation import ugettext as _ from rest_flex_fields import FlexFieldsModelSerializer from rest_flex_fields.serializers import FlexFieldsSerializerMixin from re...
readthedocs/api/v3/serializers.py
27,758
Render ``Build.config`` property without modifying it. .. note:: Any change on the output of that property will be reflected here, which may produce incompatible changes in the API. Used when triggering (create action) a ``Build`` for a specific ``Version``. This serializer validates that no field is sent at a...
2,381
en
0.852163
# Copyright 2021 Edoardo Riggio # # 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 writin...
exercises/search_in_sorted_matrix.py
1,104
Copyright 2021 Edoardo Riggio 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 distri...
574
en
0.853956
"""Bokeh ELPDPlot.""" import warnings import bokeh.plotting as bkp from bokeh.models.annotations import Title from bokeh.models import ColumnDataSource import bokeh.models.markers as mk import numpy as np from . import backend_kwarg_defaults from .. import show_layout from ...plot_utils import _scale_fig_size from .....
arviz/plots/backends/bokeh/elpdplot.py
5,830
Bokeh elpd plot. Bokeh ELPDPlot.
32
en
0.158796
# ============================================================================ # FILE: default.py # AUTHOR: Shougo Matsushita <Shougo.Matsu at gmail.com> # License: MIT license # ============================================================================ import re import typing from denite.util import echo, error, c...
rplugin/python3/denite/ui/default.py
35,078
============================================================================ FILE: default.py AUTHOR: Shougo Matsushita <Shougo.Matsu at gmail.com> License: MIT license ============================================================================ if hasattr(self._vim, 'run_coroutine'): self._denite = ASyncParent(sel...
1,100
en
0.643764
""" """ from __future__ import division from torch.optim.optimizer import Optimizer, required import numpy as np import torch from typing import NamedTuple, List from dataclasses import dataclass from enum import Enum from typing import Union, Tuple # from scipy.sparse.linalg import svds from scipy.optimize import mi...
src/transformers/adas.py
17,213
Vectorized SGD from torch.optim.SGD Implementation of the analytical solution to Empirical Variational Bayes Matrix Factorization. This function can be used to calculate the analytical solution to empirical VBMF. This is based on the paper and MatLab code by Nakajima et al.: "Global analytic solution of fully-...
3,534
en
0.510946
"""Unit tests for tftpy.""" import unittest import logging import tftpy import os import time import threading from errno import EINTR from multiprocessing import Queue log = tftpy.log class TestTftpyClasses(unittest.TestCase): def setUp(self): tftpy.setLogLevel(logging.DEBUG) def testTftpPacketRRQ...
t/test.py
18,676
Fire up a client and a server and do a download. Fire up a client and a server and do an upload. Unit tests for tftpy. repeat test with options repeat test with options Test that if we make blksize a number, it comes back a string. Test string to string Make sure that the correct class is created for the correct opco...
1,332
en
0.848055
r""" Early Stopping ^^^^^^^^^^^^^^ Monitor a validation metric and stop training when it stops improving. """ from copy import deepcopy import numpy as np import torch import torch.distributed as dist from pytorch_lightning import _logger as log from pytorch_lightning.callbacks.base import Callback from pytorch_lig...
pytorch_lightning/callbacks/early_stopping.py
7,788
Args: monitor: quantity to be monitored. Default: ``'val_loss'``. .. note:: Has no effect when using `EvalResult` or `TrainResult` min_delta: minimum change in the monitored quantity to qualify as an improvement, i.e. an absolute change of less than `min_delta`, will count as no ...
1,744
en
0.80543
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
google/ads/googleads/v4/services/services/ad_group_service/transports/grpc.py
11,198
gRPC backend transport for AdGroupService. Service to manage ad groups. This class defines the same methods as the primary client, so the primary client can load the underlying transport implementation and call it. It sends protocol buffers over the wire using gRPC (which is built on top of HTTP/2); the ``grpcio`` p...
5,160
en
0.81415
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/72_callback.neptune.ipynb (unless otherwise specified). __all__ = ['NeptuneCallback'] # Cell import tempfile from ..basics import * from ..learner import Callback # Cell import neptune # Cell class NeptuneCallback(Callback): "Log losses, metrics, model weights, mo...
fastai/callback/neptune.py
3,647
Log losses, metrics, model weights, model architecture summary to neptune AUTOGENERATED! DO NOT EDIT! File to edit: nbs/72_callback.neptune.ipynb (unless otherwise specified). Cell Cell Cell log loss and opt.hypers log metrics log model weights
246
en
0.799035
''' Module: Set regular or irregular axis ticks for a plot. ''' from module_utility import * import numpy as np import matplotlib.pyplot as plt # ticks : contains irregular ticks locations # tickbeg : regular major ticks begin location # tickend : regular major ticks end location # tickd : regular major ti...
src/module_tick.py
10,568
Module: Set regular or irregular axis ticks for a plot. ticks : contains irregular ticks locations tickbeg : regular major ticks begin location tickend : regular major ticks end location tickd : regular major ticks interval mtick : number of minor tick intervals betwen two major ticks xbeg : axis begin location x...
1,589
en
0.840243
#!/usr/bin/env python # # Copyright (C) 2009 Google Inc. # # Licensed under the Apache License 2.0; # This module is used for version 2 of the Google Data APIs. """Provides classes and constants for the XML in the Google Spreadsheets API. Documentation for the raw XML which these classes represent can be found he...
src/gdata/spreadsheets/data.py
11,530
The gs:cell element. A cell in the worksheet. The <gs:cell> element can appear only as a child of <atom:entry>. An Atom entry representing a single cell in a worksheet. An Atom feed contains one entry per cell in a worksheet. The cell feed supports batch operations, you can send multiple cell operations in one HTTP r...
5,679
en
0.789845
import numpy as np import pandas as pd from openpyxl import load_workbook import sys def print_array_to_excel(array, first_cell, ws, axis=2): ''' Print an np array to excel using openpyxl :param array: np array :param first_cell: first cell to start dumping values in :param ws: worksheet reference....
gold nanocluster synthesis/own_package/others.py
1,413
Print an np array to excel using openpyxl :param array: np array :param first_cell: first cell to start dumping values in :param ws: worksheet reference. From openpyxl, ws=wb[sheetname] :param axis: to determine if the array is a col vector (0), row vector (1), or 2d matrix (2) Treat array as col vector and print alo...
550
en
0.789732
# -*- coding: utf-8 -*- # URL : https://leetcode-cn.com/problems/median-of-two-sorted-arrays/ """""" """ problem: 给定两个大小为 m 和 n 的有序数组 nums1 和 nums2。 请你找出这两个有序数组的中位数,并且要求算法的时间复杂度为 O(log(m + n))。 你可以假设 nums1 和 nums2 不会同时为空。 示例 1: nums1 = [1, 3] nums2 = [2] 则中位数是 2.0 示例 2: nums1 = [1, 2] nums2 = [3, 4] 则中位数是 (2 +...
Codes/xiaohong2019/leetcode/4_median_of_two_sorted_arrays.py
5,630
:type nums1: List[int] :type nums2: List[int] :rtype: float -*- coding: utf-8 -*- URL : https://leetcode-cn.com/problems/median-of-two-sorted-arrays/ 索引值范围检查 k == 1 取中间值比较淘汰 淘汰 nums1 的 mid 前面的元素
196
zh
0.451078
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2017-07-27 14:08 from __future__ import unicode_literals from django.db import migrations import wagtail.core.fields class Migration(migrations.Migration): dependencies = [ ('home', '0011_auto_20170727_1324'), ] operations = [ migr...
django-website/home/migrations/0012_auto_20170727_1408.py
665
-*- coding: utf-8 -*- Generated by Django 1.11.3 on 2017-07-27 14:08
68
en
0.626203
import disnake from disnake.ext import commands # Define a simple View that persists between bot restarts # In order a view to persist between restarts it needs to meet the following conditions: # 1) The timeout of the View has to be set to None # 2) Every item in the View has to have a custom_id set # It is recommen...
examples/views/persistent.py
2,883
Define a simple View that persists between bot restarts In order a view to persist between restarts it needs to meet the following conditions: 1) The timeout of the View has to be set to None 2) Every item in the View has to have a custom_id set It is recommended that the custom_id be sufficiently unique to prevent con...
1,088
en
0.944938
import glob from itertools import chain from os import path import numpy as np import torch.utils.data as data import umsgpack from PIL import Image class ISSDataset(data.Dataset): """Instance segmentation dataset This assumes the dataset to be formatted as defined in: https://github.com/mapillary/s...
seamseg/data/dataset.py
7,059
Instance segmentation dataset This assumes the dataset to be formatted as defined in: https://github.com/mapillary/seamseg/wiki/Dataset-format Parameters ---------- root_dir : str Path to the root directory of the dataset split_name : str Name of the split to load: this must correspond to one of the files...
1,342
en
0.691806
# 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/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2017_05_01_preview/_configuration.py
2,945
Configuration for MonitorClient. Note that all parameters used to create this instance are saved as instance attributes. :param credential: Credential needed for the client to connect to Azure. :type credential: ~azure.core.credentials.TokenCredential coding=utf-8 ---------------------------------------------------...
840
en
0.614617
# -*- test-case-name: vumi.transports.xmpp.tests.test_xmpp -*- # -*- encoding: utf-8 -*- from twisted.python import log from twisted.words.protocols.jabber.jid import JID from twisted.words.xish import domish from twisted.words.xish.domish import Element as DomishElement from twisted.internet.task import LoopingCall f...
vumi/transports/xmpp/xmpp.py
7,769
A custom presence protocol to automatically accept any subscription attempt. XMPP transport. Configuration parameters: :type host: str :param host: The host of the XMPP server to connect to. :type port: int :param port: The port on the XMPP host to connect to. :type debug: bool :param debug: Whether or no...
1,583
en
0.7622
# /usr/bin/env python # -*- coding: utf-8 -*- """ Modul is used for GUI of Lisa """ from loguru import logger import sys import click from pathlib import Path import ast from . import app_tools # print("start") # from . import image # print("start 5") # print("start 6") # from scaffan import algorithm from . impo...
anwa/main_click.py
4,152
Modul is used for GUI of Lisa /usr/bin/env python -*- coding: utf-8 -*- print("start") from . import image print("start 5") print("start 6") from scaffan import algorithm print("Running __main__.py") @batch_detect.command(context_settings=CONTEXT_SETTINGS) @click.argument("image_stack_dir", type=click.Path(exists=Tru...
1,564
en
0.342508
''' Autor: Gurkirt Singh Start data: 2nd May 2016 purpose: of this file is to take all .mp4 videos and convert them to jpg images ''' import numpy as np import cv2 as cv2 import math,pickle,shutil,os baseDir = "/mnt/sun-alpha/actnet/"; vidDir = "/mnt/earth-beta/actnet/videos/"; imgDir = "/mnt/sun-alpha/actnet/rgb-i...
python-scripts/convertMP4toJPG.py
12,384
os.mkdir(imgDir) annotations = videoInfo['annotations'] vidDir = vidDirtemp print np.shape(retval),np.shape(image), type(image),f checkConverted() convertVideosL() convertTestVideos()
186
en
0.157423
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
tensorflow/python/autograph/impl/conversion_test.py
6,931
Tests for conversion module. Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless requir...
811
en
0.763059
# Copyright 2016-2021 Swiss National Supercomputing Centre (CSCS/ETH Zurich) # ReFrame Project Developers. See the top-level LICENSE file for details. # # SPDX-License-Identifier: BSD-3-Clause # # Meta-class for creating regression tests. # import functools import types import reframe.core.namespaces as namespaces i...
reframe/core/meta.py
23,068
Custom namespace to control the cls attribute assignment. Regular Python class attributes can be overridden by either parameters or variables respecting the order of execution. A variable or a parameter may not be declared more than once in the same class body. Overriding a variable with a parameter or the other way a...
8,113
en
0.780836
import time from check_lang import check_py,check_rb,check_j,check_c,check_cpp from flask import Flask, request, jsonify from flask_cors import CORS, cross_origin import subprocess import json from json import JSONEncoder from main import predict app = Flask(__name__) CORS(app) @app.route("/") def hello(): return...
server/home.py
2,648
print dataDict print "------------" return JSONEncoder().encode(x)if score of cpp is eqgreater than 0.5 then run it to check if it runs then cpp else java sa = [] score_cpp = x['cpp'] score_ruby = x['ruby'] score_c = x['c'] score_py = x['py'] score_java = x['java'] sa.append(score_c) sa.append(score_cpp) sa.append(scor...
435
en
0.321013
import numpy as np import matplotlib.pyplot as plt from UTILS.Calculus import Calculus from UTILS.SetAxisLimit import SetAxisLimit from UTILS.Tools import Tools from UTILS.Errors import Errors import sys # Theoretical background https://arxiv.org/abs/1401.5176 # Mocak, Meakin, Viallet, Arnett, 2014, Compressible Hyd...
EQUATIONS/InternalEnergyEquation.py
8,813
Plot mean Favrian internal energy stratification in the model Plot internal energy equation in the model Theoretical background https://arxiv.org/abs/1401.5176 Mocak, Meakin, Viallet, Arnett, 2014, Compressible Hydrodynamic Mean-Field Equations in Spherical Geometry and their Application to Turbulent Stellar Convec...
1,313
en
0.715425
#----------------------------------------------------------------------------- # Copyright (c) 2015-2017, PyInstaller Development Team. # # Distributed under the terms of the GNU General Public License with exception # for distributing bootloader. # # The full license is in the file COPYING.txt, distributed with this s...
venv/Lib/site-packages/PyInstaller/hooks/hook-netCDF4.py
514
----------------------------------------------------------------------------- Copyright (c) 2015-2017, PyInstaller Development Team. Distributed under the terms of the GNU General Public License with exception for distributing bootloader. The full license is in the file COPYING.txt, distributed with this software.-----...
446
en
0.677862
#!/usr/bin/env python # -*- coding: utf-8 -*- # ============================================================================= # Copyright (c) Ostap developers. # ============================================================================= # @file test_fitting_efficiency.py # Test module for ostap/fitting/efficiency.p...
ostap/fitting/tests/test_fitting_efficiency.py
7,278
Test module for ostap/fitting/efficiency.py !/usr/bin/env python -*- coding: utf-8 -*- ============================================================================= Copyright (c) Ostap developers. ============================================================================= @file test_fitting_efficiency.py Test modul...
1,803
en
0.366142
# # @file TestConstraint_newSetters.py # @brief Constraint unit tests for new set function API # # @author Akiya Jouraku (Python conversion) # @author Sarah Keating # # $Id$ # $HeadURL$ # # This test file was converted from src/sbml/test/TestConstraint_newSetters.c # with the help of conversion sciprt (ctest_...
external/sbml/bindings/python/test/sbml/TestConstraint_newSetters.py
3,756
@file TestConstraint_newSetters.py @brief Constraint unit tests for new set function API @author Akiya Jouraku (Python conversion) @author Sarah Keating $Id$ $HeadURL$ This test file was converted from src/sbml/test/TestConstraint_newSetters.c with the help of conversion sciprt (ctest_converter.pl).<!---------...
1,138
en
0.763339
#!/usr/bin/env python3 import sys import os import argparse scriptpath = os.path.abspath(os.path.dirname(__file__)) includepath = os.path.dirname(scriptpath) sys.path.insert(0, includepath) from audio.audiofilefactory import AudioFileFactory from audio.audioconversionservice import AudioConversionService from filesyste...
bin/convertfavourites.py
1,905
!/usr/bin/env python3
21
fr
0.448822
from pymavlink import mavutil #import time mavutil.set_dialect("video_monitor") # create a connection to FMU hoverGames = mavutil.mavlink_connection("/dev/ttymxc2", baud=921600) # wait for the heartbeat message to find the system id hoverGames.wait_heartbeat() print("Heartbeat from system (system %u component %u...
02_commCustom/receiveCustomMavlinkMSG.py
1,076
import time create a connection to FMU wait for the heartbeat message to find the system idcheck that the message is valid before attempting to use itMessage is valid, so use the attributetime.sleep(1.0):
205
en
0.653234
import numpy as np from .utils import make_dir class Evaluater(object): def __init__(self, logger, size, original_size, tag='paper_figure'): self.pixel_spaceing = 0.1 self.tag = tag make_dir(tag) self.tag += '/' self.logger = logger self.scale_rate_y ...
utils/eval.py
4,215
2mm etc n = batchsize = 1 pred : list[ c(y) ; c(x) ] landmark: list [ (x , y) * c] y, x for i in range(len(Radial_Error)): if Radial_Error[i] > 10: print("Landmark {} RE {}".format(i, Radial_Error[i])) if Radial_Error.max() > 10: return Radial_Error.argmax() n = batchsize = 1 pred : list[ c(y) ; c(x) ] ...
487
en
0.347715
# Copyright 2012 OpenStack Foundation # 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 requ...
tempest/api/compute/base.py
30,988
Base test case class for Compute Admin API tests. Base test case class for all Compute API tests. Helper method to detach a volume. Ignores 404 responses if the volume or server do not exist, or the volume is already detached from the server. Check whether server_flavor equals to flavor. :param flavor_id: flavor id :...
6,835
en
0.842564
"""Script that generates a refresh token for a specific user.""" import os import sys import spotipy.util as util import json if len(sys.argv) == 2: username = str(sys.argv[1]) else: print('Usage: {} username'.format(sys.argv[0])) sys.exit(1) scope = 'user-read-currently-playing user-read-playback-state...
spotify_setup.py
648
Script that generates a refresh token for a specific user. Get tokens from Spotify. Print refresh token.
106
en
0.692604
# -*- coding: utf-8 -*- import hmac import requests from json import dumps from hashlib import sha1 from .app import api, env def match_any_if_any(event, events): return events is None or event in events class Subscription: def __init__(self, data): self.data = data self.events = data['dat...
app/webhooks.py
2,678
-*- coding: utf-8 -*- user defined
34
en
0.835374
# 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 # distributed under t...
openstack/message/v2/queue.py
5,086
This method is a generator which yields queue objects. This is almost the copy of list method of resource.Resource class. The only difference is the request header now includes `Client-ID` and `X-PROJECT-ID` fields which are required by Zaqar v2 API. Licensed under the Apache License, Version 2.0 (the "License"); yo...
1,625
en
0.854858
''' setup module ''' from distutils.core import setup # TEMPLATE setup( name='mask-query-aide', version='0.0', description='python code to train ML for detecting people with masks', long_description=open('README.rst').read(), author='Christine Madden', license=open('LICENSE').read(), autho...
setup.py
834
setup module TEMPLATE python_requires="<3.8",
47
el
0.092476
#!/usr/bin/env python # -*- coding: UTF-8 -*- import numpy as np __all__ = ["Config"] class Config(object): """ Config: Holds configuration settings. Parameters ---------- fitParameters : list Parameters to fit. parameterPriors : dict Dictionary with parameters as keys, and ...
atm/config.py
3,438
Config: Holds configuration settings. Parameters ---------- fitParameters : list Parameters to fit. parameterPriors : dict Dictionary with parameters as keys, and a dictionary as the value for each key. This dictionary is called to setup the pymc3 priors for each parameter not in fitParameters. col...
1,428
en
0.717856
from attr import dataclass #s4 teng https://t.me/shuraim1/https:/ #S5 teng https://t.me/alquran30juzsaadalghamidi/5 #s6 teng https://t.me/bandar_abdulaziz_balilah/5 #s7 teng https://t.me/Idriss_Akbar/388 #s8 teng https://t.me/yasseraldosari_mp3/2 sura = { '0': {'s1':'42', 's2':'257', 's3':'18', 's4':...
pipuchun/jsonuz.py
13,364
s4 teng https://t.me/shuraim1/https:/S5 teng https://t.me/alquran30juzsaadalghamidi/5s6 teng https://t.me/bandar_abdulaziz_balilah/5 s7 teng https://t.me/Idriss_Akbar/388s8 teng https://t.me/yasseraldosari_mp3/261 inlinekeyboard starts in here
243
en
0.43409
# Lint as: python2, python3 # 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 # ...
lingvo/core/conv_layers_with_time_padding.py
19,230
Applies activation function to the inputs. Base class for 2D convolution layers. 2D conv layer with causal dependency on the time axis. Depthwise conv layer with causal dependency on the time axis. Depthwise conv layer with causal dependency on the time axis. Conv2D layer. A wrapper around regular BatchNormLayer that p...
5,342
en
0.787055
import torch from recstudio.ann import sampler from recstudio.data import dataset from recstudio.model import basemodel, loss_func, scorer r""" HGN ######## Paper Reference: Chen ma, et al. "HGN: Hierarchical Gating Networks for Sequential Recommendation" in KDD2019. https://dl.acm.org/doi/abs/10.1145/3292500...
recstudio/model/seq/hgn.py
2,723
HGN proposes a hierarchical gating network, integrated with the Bayesian Personalized Ranking (BPR) to capture both the long-term and short-term user interests. HGN consists of a feature gating module, an instance gating module, and an item-item product module. The dataset is SeqDataset. BPR loss is used. BxLx1
314
en
0.819695
import time import board import debouncer import busio as io import digitalio import pulseio import adafruit_ssd1306 i2c = io.I2C(board.SCL, board.SDA) reset_pin = digitalio.DigitalInOut(board.D11) oled = adafruit_ssd1306.SSD1306_I2C(128, 32, i2c, reset=reset_pin) button_select = debouncer.Debouncer(board.D7, mode=dig...
CircuitPython_101/basic_data_structures/song_book/code.py
3,729
pylint: disable=line-too-long pylint: enable=line-too-long Hex 7FFF (binary 0111111111111111) is half of the largest value for a 16-bit int, i.e. 50%
149
en
0.598127
# -*- coding: utf-8 -*- # Generated by Django 1.10 on 2017-02-23 18:07 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('voting', '0002_auto_20170223_1054'), ] operations = [ migrations.RemoveField(...
texaslan/voting/migrations/0003_auto_20170223_1207.py
1,063
-*- coding: utf-8 -*- Generated by Django 1.10 on 2017-02-23 18:07
66
en
0.759516
#!/usr/bin/env python3 # Copyright (c) 2017-2020 The Mantle Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test mempool acceptance of raw transactions.""" from decimal import Decimal from io import BytesIO impo...
test/functional/mempool_accept.py
16,241
Wrapper to check result of testmempoolaccept on node_0's mempool Test mempool acceptance of raw transactions. !/usr/bin/env python3 Copyright (c) 2017-2020 The Mantle Core developers Distributed under the MIT software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. Mus...
1,793
en
0.832814
#!/usr/bin/env python import os import sys import argparse import subprocess import glob import math from EMAN2 import * def file_base(movie): # return the filename and basename, exclude '.p3' return movie, os.path.basename(os.path.splitext(movie)[0]).replace('.p3', '') def check(log,c_p): with open(log) as log_r...
bin/p3motioncor2.py
5,794
!/usr/bin/env python return the filename and basename, exclude '.p3' generate the com file run the com check the shifts decide bad if too many bad frames get default values get common parameters loop over all the input movies unify mrc and mrcs to mrcs format get nimg convert dm4 to mrcs here we assume 36e is the maxim...
586
en
0.721719
""" Copyright (c) 2018 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in wri...
model-optimizer/mo/front/kaldi/extractors/affine_component_ext.py
1,072
Copyright (c) 2018 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, soft...
562
en
0.864985
# import unittest import pytest # from ci_testing_python.app.identidock import app if __name__ == '__main__': # unittest.main() pytest.main()
tests/contract/test_contract_identidock.py
147
import unittest from ci_testing_python.app.identidock import app unittest.main()
80
en
0.172913
import numpy as np import matplotlib.pyplot as plt import time import csv import os import scipy.io as mat4py import logging logger = logging.getLogger("logger") class ResultBuffer(object): def __init__(self, log_path, episode_types): self.log_path = log_path self.current_episode = None s...
result_buffer.py
9,788
general stats training stats updates counter average rewards value function error state/action/disturbance evolution gradient stats
131
en
0.613093
"""Import a file from Illumina BaseSpace.""" import atexit import gzip import os import time import traceback from pathlib import Path from requests import RequestException, Session from resolwe.process import ( BooleanField, FileField, GroupField, IntegerField, Persistence, Process, Secr...
resolwe_bio/processes/import_data/basespace.py
8,660
Advanced options. BaseSpace download error. Import a file from Illumina BaseSpace. Input fields to process BaseSpaceImport. Output fields to process BaseSpaceImport. Download BaseSpace file. Attempt to download BaseSpace file numerous times in case of errors. Get BaseSpace API file contents URL. Get BaseSpace API file ...
626
en
0.719908
from kafka import KafkaProducer from kafka import KafkaConsumer from kafka import KafkaAdminClient import json from json import dumps from json import loads import time import os import requests import sys import GE_GSCH_low_define as lowDefine ''' {'requestID': 'req-f6720a0e-e3df-455a-825d-f8c80cedc2d9', 'date': '...
gs-scheduler/global_scheduler2/policy_dockerfile/lowlatency/GE_GSCH_low_latency.py
10,937
apply low-latency yaml with read dispatched queuesend topic message GE_Request_Job.requestDataDic['status'] = 'failed'GE_Request_Job.requestDataDic['status'] = 'completed'GE_Request_Job.requestDataDic['status'] = 'cancel'GE_Request_Job.requestDataDic['status'] = 'cancel'time.sleep(1)
284
en
0.537287
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from .. import _utilities, _tables __al...
sdk/python/pulumi_azure_nextgen/servicebus/list_topic_keys.py
6,588
Namespace/ServiceBus Connection String Primary connection string of the alias if GEO DR is enabled Secondary connection string of the alias if GEO DR is enabled A string that describes the authorization rule. Namespace/ServiceBus Connection String API Version: 2017-04-01. :param str authorization_rule_name: The auth...
1,017
en
0.70987
""" Base backend Trace and Database classes from the other modules should Subclass the base classes. """ import PyMC2 class Trace(object): """Dummy Trace class. """ def __init__(self,value=None, obj=None): """Assign an initial value and an internal PyMC object.""" self._trace = val...
PyMC2/database/base.py
3,752
def obj(): def fset(self, obj): if isinstance(obj, PyMC2.PyMCBase): self.__obj = obj else: raise AttributeError, 'Not PyMC object' def fget(self): return self.__obj return locals() obj = property(**obj()) Restore the state of the Samp...
346
en
0.395065
from utils import TreeNode, binary_tree class Solution: def __init__(self): self.index = 0 # 利用[中序遍历左边元素数量 = 左子树节点总数]可以省掉这个计数的字段 def buildTree(self, preorder, inorder): """ :type preorder: List[int] :type inorder: List[int] :rtype: TreeNode """ if not preorder: return None def build_node(lo, h...
medium/Q105_ConstructBinaryTreeFromPreorderAndInorderTraversal.py
1,016
:type preorder: List[int] :type inorder: List[int] :rtype: TreeNode 利用[中序遍历左边元素数量 = 左子树节点总数]可以省掉这个计数的字段 有些解法生成字典加快这步,但这会增大空间复杂度
129
zh
0.848514
# # Copyright (c) 2019, 2021 by Delphix. All rights reserved. # import dlpx.virtualization.api from dlpx.virtualization.common.util import to_str def get_virtualization_api_version(): """Returns the Virutalization API version string. :return: version string """ return to_str(dlpx.virtualization.api._...
platform/src/main/python/dlpx/virtualization/platform/util.py
332
Returns the Virutalization API version string. :return: version string Copyright (c) 2019, 2021 by Delphix. All rights reserved.
131
en
0.759711
# -*- coding: utf-8 -*- from ..base import Property from .array import StateVector from .base import Type class Particle(Type): """ Particle type A particle type which contains a state and weight """ state_vector: StateVector = Property(doc="State vector") weight: float = Property(doc='Weigh...
stonesoup/types/particle.py
821
Particle type A particle type which contains a state and weight -*- coding: utf-8 -*-
88
en
0.901478
from heapq import heappush, nsmallest import numpy as np class NearestNeighbor(): def __init__(self, embeddings, encodings, config): self.embeddings = embeddings self.encodings = encodings self.config = config def euclidian_distance(self, e1, e2): ''' https://stackoverf...
Word2Vec/NearestNeighbor.py
1,325
https://stackoverflow.com/questions/1401712/how-can-the-euclidean-distance-be-calculated-with-numpy TODO: is it faster to not have the the string comparision and instead always remove the first element of the array which will have a distance of 0 TODO: implement faster solution than the heap where it only keeps...
406
en
0.860146
# Copyright (c) 2013, igrekus and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe import _ from dc_plc.custom.utils import add_completeness, add_query_relevance from dc_plc.controllers.stats_query import get_procmap_stats def execute(f...
dc_plc/dc_plc/report/dc_product_procmap_stats/dc_product_procmap_stats.py
886
Copyright (c) 2013, igrekus and contributors For license information, please see license.txt
92
en
0.674615
# module for distance computation; import numpy as np def dist(arraya, arrayb, mode): if mode == 0: dis = np.sum(np.abs(np.subtract(arraya, arrayb))) elif mode == 1: dis = np.sqrt(np.sum(np.power(np.subtract(arraya, arrayb), 2))) else: dis = 1 - np.dot(arraya, arrayb) / np.sqrt(np.s...
DCS311 Artificial Intelligence/KNN/lab1_code/M3/dist.py
638
module for distance computation;
32
en
0.449301
"""Run CVEjob.""" import sys from decimal import Decimal import multiprocessing import nvdlib from nvdlib.manager import FeedManager from nvdlib.query_selectors import in_range from cvejob.filters.input import validate_cve from cvejob.config import Config from cvejob.identifiers import get_identifier_cls from cvejob...
run.py
6,764
Filter Document collection. Log results. Run CVEjob. Run CVEjob. logging configuration use nvdlib's handler all CVEs prior to 2002 are stored in 2002 feed optimization check prune the feed names as it is not necessary to iterate over all of them collection is empty user knows the package name, so we don't have to gue...
361
en
0.908416
# This file is generated by C:\projects\numpy-wheels\numpy\setup.py # It contains system_info results at the time of building this package. __all__ = ["get_info","show"] blas_opt_info={'library_dirs': ['C:\\projects\\numpy-wheels\\windows-wheel-builder\\atlas-builds\\atlas-3.11.38-sse2-64\\lib'], 'language': 'c', ...
python-3.4.4.amd64/Lib/site-packages/numpy/__config__.py
1,798
This file is generated by C:\projects\numpy-wheels\numpy\setup.py It contains system_info results at the time of building this package.
135
en
0.918881
from __future__ import absolute_import, division, print_function, unicode_literals import argparse import functools import logging from os import path import boto3 import jsonschema from c7n_mailer import deploy, utils from c7n_mailer.azure_mailer.azure_queue_processor import MailerAzureQueueProcessor from c7n_mailer...
tools/c7n_mailer/c7n_mailer/cli.py
9,607
Standard Lambda Function Config Azure Function Config Mailer Infrastructure Config TODO: encrypt with KMS? TODO: encrypt with KMS? SDK Config Mapping account / emails Select correct processor Execute
199
en
0.521463
from sklearn.exceptions import NotFittedError class MockFunction: """ Mock utility function for testing. """ def __init__(self, return_val): self.return_val = return_val def __call__(self, *args): return self.return_val class MockEstimator: """ Mock classifier object for...
tests/mock.py
3,583
Mock ActiveLearner for testing. Mock Committee for testing. Mock classifier object for testing. Mock utility function for testing.
130
en
0.866248
#!/usr/bin/env python from itertools import izip import xmlrpclib import rospy from rospy.rostime import Time, Duration from flexbe_core import EventState as Dummy from flexbe_core import Logger from flexbe_core.proxy import ProxyPublisher, ProxySubscriberCached, ProxyActionClient from sensor_msgs.msg import JointSt...
sweetie_bot_flexbe_states/src/sweetie_bot_flexbe_states/internal/set_joint_state_base.py
5,411
!/usr/bin/env python This is helper class so trick FlexBe App to ignore it. Dummy is actually EventState but FlexBe App is not able to recognize it. Store topic parameter for later use. create proxies timestamp error in enter hook derive parameter full name Load JointState message from Parameter Server deserialize cr...
510
en
0.636998
import logging import asyncio from steam.ext.csgo import Client from steam.ext.csgo.enums import Language from steam.ext.csgo.backpack import BaseInspectedItem from steam.protobufs import GCMsgProto, EMsg, MsgProto from steam.protobufs.client_server import CMsgClientLicenseListLicense from steam_tradeoffer_manager.ba...
app/services/pool/pool.py
3,769
https://steamdb.info/app/730/subs/ ensure licenses event was emitted TODO: errors requesting free license request CSGO license pragma: no cover pragma: no cover waiting for first bot is ready and then return
207
en
0.78233
import numpy as np class Reward: pass class StaticReward(Reward): def __init__(self, value): self.value = value def get(self): return value class NormalReward(Reward): def __init__(self, mean, std): self.mean = mean self.std = std def get(self): return np.random.normal(self.mean, self.std) class Ba...
main.py
2,299
Represents a Markov Decision Process. Parameters ---------- S : int Number of states A : matrix A[s][a] is True iff a is permitted in s R : list A list of reward generators p : matrix p[s][a][s'] = p(s'|s,a) Given a state and an action, returns a new state and a reward. Parameters -----...
496
en
0.588514
# coding: utf-8 """ FlashArray REST API No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: 2.2 Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re import six import typing from ....
pypureclient/flasharray/FA_2_2/models/username.py
3,095
Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. Returns true if both objects are equal Keyword args: username (str): The username ...
728
en
0.678813
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 5/15/20 4:49 PM # @File : grover.py # qubit number=4 # total number=39 import cirq import cirq.google as cg from typing import Optional import sys from math import log2 import numpy as np #thatsNoCode from cirq.contrib.svg import SVGCircuit # Symbols for...
benchmark/startCirq2615.py
3,107
!/usr/bin/env python -*- coding: utf-8 -*- @Time : 5/15/20 4:49 PM @File : grover.py qubit number=4 total number=39thatsNoCode Symbols for the rotation angles in the QAOA circuit. circuit begin number=9 number=2 number=3 number=4 number=5 number=18 number=28 number=6 number=7 number=8 number=20 number=21 number=2...
523
en
0.275006
import simulations.simulation as simulation import simulations.simulation_runner as simrunner import cPickle import os import random import re import string import subprocess import sys from simulations.utils.optionparser import OptionParser from nose.tools import assert_equal from nose.tools import assert_raises de...
test/simulation_tests.py
13,112
pp stuffassert_equal(self.batch.options.pool_size, 'autodetect') pp stuffclass TestClustering: def setUp(self): self.secret = filename_generator(6) self.server = subprocess.Popen(["ppserver.py", "-s", self.secret]) self.batch = Batch(Sim2) self.dir = "/tmp/" + filename_generator(8) def...
2,373
en
0.257626
"""Support for Blockchain.com sensors.""" from datetime import timedelta import logging from pyblockchain import get_balance, validate_address import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import ATTR_ATTRIBUTION, CONF_NAME import homeassistant.helpers.c...
homeassistant/components/blockchain/sensor.py
2,275
Representation of a Blockchain.com sensor. Initialize the sensor. Return the state attributes of the sensor. Return the icon to use in the frontend, if any. Return the name of the sensor. Set up the Blockchain.com sensors. Return the state of the sensor. Return the unit of measurement this sensor expresses itself in. G...
390
en
0.72127
from typing import Any from copy import deepcopy class Model: def __init__(self, name: str, model, freq: str): self.name = name self.model = model self.freq = freq self.train = None self.test = None self.prediction = None self.pred_col = "prediction" ...
interpolML/interpolML/model/model.py
1,353
Performs model training with standard settings Performs prediction
66
en
0.939886
#!/usr/bin/python # https://practice.geeksforgeeks.org/problems/knapsack-with-duplicate-items/0 def sol(n, w, wt, v): """ We do not need to create a 2d array here because all numbers are available always Try all items for weight ranging from 1 to w and check if weight can be picked. Take the max of...
full-problems/knapsackWithDuplicates.py
526
We do not need to create a 2d array here because all numbers are available always Try all items for weight ranging from 1 to w and check if weight can be picked. Take the max of the result !/usr/bin/python https://practice.geeksforgeeks.org/problems/knapsack-with-duplicate-items/0
282
en
0.786482