content
stringlengths
27
928k
path
stringlengths
4
230
size
int64
27
928k
nl_text
stringlengths
21
396k
nl_size
int64
21
396k
nl_language
stringlengths
2
3
nl_language_score
float64
0.04
1
from common import IssueProcess, Common from typing import Any, List import os # assignee dict which will be assigned to handle issues _GO_OWNER = {'ArcturusZhang'} # 'github assignee': 'token' _ASSIGNEE_TOKEN_GO = {'ArcturusZhang': os.getenv('AZURESDK_BOT_TOKEN')} class IssueProcessGo(IssueProcess): pass cla...
scripts/release_helper/go.py
637
assignee dict which will be assigned to handle issues 'github assignee': 'token'
80
en
0.769692
# Generated by Django 3.2.3 on 2021-05-19 08:50 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('api', '0002_auto_20210519_0849'), ] operations = [ migrations.AlterField( model_name='profile', name='year', ...
api/migrations/0003_alter_profile_year.py
514
Generated by Django 3.2.3 on 2021-05-19 08:50
45
en
0.782912
# -*- coding: utf-8 -*- import io import sys import textwrap from itertools import chain from pprint import pprint import pytest import canmatrix.canmatrix import canmatrix.formats.sym def test_colliding_mux_values(): f = io.BytesIO( textwrap.dedent( '''\ FormatVersion=5.0 // Do ...
src/canmatrix/tests/test_sym.py
11,127
-*- coding: utf-8 -*- Missing ')' at the end of enum used to cause infinite loop Add an enum to Signal1 Export and reimport Check that Enums from Enums table exported and reimported correctly Check that Enums from a Signal.Values property exported and reimported correctly Check no errors loading the matrix Check that t...
638
en
0.829022
from django.forms.utils import flatatt from django.utils.html import format_html, format_html_join from django.utils.translation import gettext as _ from wagtail.core import blocks from wagtail.core.blocks import PageChooserBlock from wagtail.images.blocks import ImageChooserBlock from wagtailmarkdown.utils import ren...
home/blocks.py
7,922
Translators: Translators: This message appears below embedded video and audio on the site. Many feature phones won't be able to play embedded video/audio, so the site offers an opportunity to download the file. Part of this message (between %(start_link)s and %(end_link)s ) is a clickable download link. Translators: Tr...
609
en
0.832843
class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: ''' #最长连续公共子串 l1=len(text1) l2=len(text2) if l1==0 or l2==0: return 0 dp = [[0 for i in range(l2)] for i in range(l1)] res = 0 if text1[0]==text2[0]: ...
DP/Leetcode1143.py
2,248
#最长连续公共子串 l1=len(text1) l2=len(text2) if l1==0 or l2==0: return 0 dp = [[0 for i in range(l2)] for i in range(l1)] res = 0 if text1[0]==text2[0]: dp[0][0]=1 res=1 for i in range(1,l2): if text2[i]==text1[0]: dp[0][i]=1 res=1 for i in range(1,l1): if text1[i]==text2[0]: dp[i]...
553
en
0.245401
from __future__ import print_function import torch from torch import nn import numpy as np import torch.nn.functional as F from torch.autograd import Variable from constant import * from torch.nn.utils.rnn import pack_padded_sequence class EncoderGRU(nn.Module): def __init__(self, vocab_size,emb_dim...
CNN/src/models.py
8,728
emb---np wordVec vocab_size=len(emb)self.word_emb=nn.Embedding(vocab_size,emb_dim,pad_token)self.word_emb.weight.data.copy_(torch.from_numpy(emb))self.pos1_emb=nn.Embedding(MaxPos,dimWPE)self.pos2_emb=nn.Embedding(MaxPos,dimWPE)using gruusing gruemb---np wordVec vocab_size=len(emb)using CNNself.softmax=nn.Softmax()self...
403
en
0.099738
#!/usr/bin/env python # -*- encoding: utf-8 -*- ''' @File : utils_node.py @Time : 2022/03/08 14:35:13 @Author : Jianwen Chen @Version : 1.0 @Contact : chenjw48@mail2.sysu.edu.cn @License : (C)Copyright 2021-2022, SAIL-Lab ''' ######################################## import area ######################...
Repeat/CoMPT/utils_node.py
7,429
Noam learning rate scheduler with piecewise linear increase and exponential decay. The learning rate increases linearly from init_lr to max_lr over the course of the first warmup_steps (where warmup_steps = warmup_epochs * steps_per_epoch). Then the learning rate decreases exponentially from max_lr to final_lr over th...
2,060
en
0.744669
from djangocms_style.cms_plugins import StylePlugin from cms.plugin_pool import plugin_pool from django.utils.translation import gettext_lazy as _ from .models import TaccsiteSection # Plugins @plugin_pool.register_plugin class TaccsiteSectionPlugin(StylePlugin): """ Patterns > "Section" Plugin https://...
djangocms_tacc_section/cms_plugins.py
1,181
Patterns > "Section" Plugin https://confluence.tacc.utexas.edu/x/c5TtDg Plugins Copied from djangocms_style sans 'Inline style settings' FAQ: If user wants to override spacing, they may: - use Style plugin (if they have permission) - request Design & Dev standardize use case https://github.com/django-cms/dj...
382
en
0.637282
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from .models import Location,Category,Image # Register your models here. admin.site.register(Location) admin.site.register(Category) admin.site.register(Image) class Image(admin.ModelAdmin): search_fields = ('image_...
shots/admin.py
330
-*- coding: utf-8 -*- Register your models here.
48
en
0.933192
# -*- coding: utf-8 -*- """ Authors: Tim Hessels Module: Collect/SRTM Description: This module downloads DEM data from http://earlywarning.usgs.gov/hydrodata/. Use the DEM functions to download and create DEM images in Gtiff format. Examples: from pyWAPOR.Collect import SRTM SRTM.DEM(Dir='C:/TempDEM4/', latlim=[29, ...
pyWAPOR/Collect/SRTM/__init__.py
419
Authors: Tim Hessels Module: Collect/SRTM Description: This module downloads DEM data from http://earlywarning.usgs.gov/hydrodata/. Use the DEM functions to download and create DEM images in Gtiff format. Examples: from pyWAPOR.Collect import SRTM SRTM.DEM(Dir='C:/TempDEM4/', latlim=[29, 32], lonlim=[-113, -109]) ...
341
en
0.399931
""" Selects a matplotlib backend so you can run without a GUI/tkinter. Supports: - PyQt5 - PySide2 - WX - Tkinter """ from pyNastran.gui import IS_DEV if IS_DEV: # there is no interactive backend when testing on TravisCI matplotlib_backend = 'Agg' else: # fails if using the terminal and PyQt/PySide & ...
pyNastran/gui/matplotlib_backend.py
840
Selects a matplotlib backend so you can run without a GUI/tkinter. Supports: - PyQt5 - PySide2 - WX - Tkinter there is no interactive backend when testing on TravisCI fails if using the terminal and PyQt/PySide & qtpy are installed how do I check if there is a terminal vs just running in command line? hasn't bee...
404
en
0.725779
# The new config inherits a base config to highlight the necessary modification _base_ = '../retinanet_r50_fpn_1x_coco.py' # We also need to change the num_classes in head to match the dataset's annotation model = dict( pretrained=None, ) # Modify dataset related settings dataset_type = 'COCODataset' classes = (...
configs/retinanet/traffic_sign/retinanet_r50_fpn_1x_traffic_sign.py
3,151
The new config inherits a base config to highlight the necessary modification We also need to change the num_classes in head to match the dataset's annotation Modify dataset related settings Batch size of a single GPU Worker to pre-fetch data for each single GPU
262
en
0.808026
#!/usr/bin/env python # Copyright 1996-2019 Cyberbotics Ltd. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
tests/sources/test_header_version.py
3,603
Unit test of the PROTO and world headers. Get all the PROTO files to be tested. Test that the PROTO and world files have the correct header. Test header version. !/usr/bin/env python Copyright 1996-2019 Cyberbotics Ltd. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in...
866
en
0.789774
import sys, imp, atexit, os sys.path.append("/home/courses/cs3214/software/pexpect-dpty/"); import pexpect, shellio, signal, time, os, re, proc_check # Determine the path this file is in thisdir = os.path.dirname(os.path.realpath(__file__)) #Ensure the shell process is terminated def force_shell_termination(shell_pr...
Systems/esh-spring-2015.git/src/plugins/systemInfo_test.py
1,458
Determine the path this file is inEnsure the shell process is terminated pulling in the regular expression and other definitions this should be the eshoutput.py file of the hosting shell, see usage above you can define logfile=open("log.txt", "w") in your eshoutput.py if you want logging!spawn an instance of the shell,...
409
en
0.792693
import os import numpy as np import pandas as pd from sklearn.datasets.samples_generator import make_swiss_roll import torch import torchvision from torchvision import transforms import glob import random import config as cfg import utils.metadata as meta from . import csv_loader from . import img_loader # Datasets #...
utils/datasets.py
7,293
Datasets pytorch.org/docs/master/torchvision/datasets.html https://github.com/bfortuner/pytorch-cheatsheet/blob/master/pytorch-cheatsheet.ipynb https://www.cs.toronto.edu/~delve/data/boston/bostonDetail.html https://github.com/pytorch/tutorials/blob/master/beginner_source/blitz/cifar10_tutorial.py Need to download Kagg...
466
en
0.522603
#!/usr/bin/env python import sys import subprocess try: import gtk except: print >> sys.stderr, "You need to install the python gtk bindings" sys.exit(1) # import vte try: import vte except: error = gtk.MessageDialog (None, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, 'You need to install...
multipleterm.py
2,432
!/usr/bin/env python import vtev.feed_child(sys.argv[i], len(sys.argv[i]))line=r.stdout.readline()print linewindow.set_title("Window %d" % (i+1))
145
en
0.112522
__all__ = ['read_cif','cif_site_labels'] from ase.io import read from ase.spacegroup import spacegroup import sys import os import logging from math import * import numpy as np import pkg_resources import warnings warnings.filterwarnings("ignore") path = '.temp_files/' filepath = pkg_resources.resource_filename(__na...
cif_tools.py
12,327
some value in cif accompanies error like "1.234(5) This is a tool that will read a CIF file and return the unique T-sites, their multiplicities, and an example atom index. It also does the same for the unique O-sites in the framework. This tool only works on CIFs that are formatted the same way as the IZA Structure D...
1,789
en
0.609264
# -*- coding: utf-8 -*- # # Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law...
texttospeech/google/cloud/texttospeech_v1beta1/gapic/text_to_speech_client.py
13,590
Service that implements Google Cloud Text-to-Speech API. Constructor. Args: transport (Union[~.TextToSpeechGrpcTransport, Callable[[~.Credentials, type], ~.TextToSpeechGrpcTransport]): A transport instance, responsible for actually making the API calls. The default transport uses the gR...
7,427
en
0.755708
# -*- coding: utf-8 -*- # Generated by Django 1.10.8 on 2019-03-18 04:04 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('wildlifecompliance', '0146_auto_20190308_1626'), ] operations = [ migration...
wildlifecompliance/migrations/0147_returntype_return_type.py
581
-*- coding: utf-8 -*- Generated by Django 1.10.8 on 2019-03-18 04:04
68
en
0.56968
# Copyright 2012-2019 The Meson development team # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed...
mesonbuild/interpreter.py
222,664
Implementation-only, without FeatureNew checks, for internal use Do a feature check on dependencies used by this subproject Check if the compiler prefixes _ (underscore) to global C symbols See: https://en.wikipedia.org/wiki/Name_mangling#C This function is deprecated and should not be used. It can be removed in a futu...
8,292
en
0.88037
# BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/main/LICENSE import pytest # noqa: F401 import numpy as np # noqa: F401 import cupy as cp # noqa: F401 import awkward as ak # noqa: F401 def test_num_1(): content = ak.Array( ["one", "two", "three", "four", "five", "six", "se...
tests-cuda/test_0345-cuda-num.py
6,599
BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/main/LICENSE noqa: F401 noqa: F401 noqa: F401 noqa: F401
129
en
0.397612
from kfp.components import create_component_from_func, InputPath, OutputPath def keras_convert_hdf5_model_to_tf_saved_model( model_path: InputPath('KerasModelHdf5'), converted_model_path: OutputPath('TensorflowSavedModel'), ): '''Converts Keras HDF5 model to Tensorflow SavedModel format. Args: ...
components/_converters/KerasModelHdf5/to_TensorflowSavedModel/component.py
1,328
Converts Keras HDF5 model to Tensorflow SavedModel format. Args: model_path: Keras model in HDF5 format. converted_model_path: Keras model in Tensorflow SavedModel format. Annotations: author: Alexey Volkov <alexey.volkov@ark-kun.com>
248
en
0.479191
from datetime import timedelta import pytest from django.utils import timezone from electeez_auth.models import User @pytest.mark.django_db def test_otp(client): user = User.objects.create(email='otp@example.com') token = user.otp_new(redirect='valid') response = client.post(token.path) assert respo...
electeez_auth/test_otp.py
672
can't use the link twice try expired link
41
en
0.943466
import sys from query_common import filter_records, ProjectMixins from redcap import Project # note this is from PyCap.redcap from typing import List """ This class of functions are responsible of retrieving relevant data structures from the CNFUN tables """ class CNFUN_project(ProjectMixins): """ One baby ...
query_CNFUN.py
2,790
One baby can have many admissions CaseIDs. One hospital record can have many CaseIDs. One baby has only one hospital record number. Create a project using PyCap :param Token: :param URL: :return: Check the list, only retain the relevant records with matching PatientID are retained. :param dataset: CNBPIDs & record ID c...
955
en
0.887237
# coding: utf-8 """ ESP Documentation The Evident Security Platform API (version 2.0) is designed to allow users granular control over their Amazon Web Service security experience by allowing them to review alerts, monitor signatures, and create custom signatures. OpenAPI spec version: v2_sdk Ge...
esp_sdk/models/role.py
4,943
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 Role - a model defined in Swagger :param dict swaggerTypes: The key is attribute name and the value is attribute type. :param dict attributeMap: The...
1,845
en
0.793471
import pandas as pd import numpy as np import wave from scipy.io import wavfile import os import librosa import pydub import ffmpeg from librosa.feature import melspectrogram import warnings from sklearn.utils import shuffle from sklearn.utils import class_weight from PIL import Image import sklearn import tensorflow ...
import_and_model.py
5,115
Load the trained modelAccess S3 Bucket and Download the audio file replace with your bucket name replace with your object key else: raiseLoad the audio data using librosaonly take 5s samples and add them to the dataframeThe variable below is chosen mainly to create a 216x216 imageCreate a DF that will take the crea...
1,012
en
0.790607
# coding: utf-8 """ Wavefront REST API <p>The Wavefront REST API enables you to interact with Wavefront servers using standard REST API tools. You can use the REST API to automate commonly executed operations such as automatically tagging sources.</p><p>When you make REST API calls outside the Wavefront REST ...
test/test_dashboard.py
1,240
Dashboard unit test stubs Test Dashboard Wavefront REST API <p>The Wavefront REST API enables you to interact with Wavefront servers using standard REST API tools. You can use the REST API to automate commonly executed operations such as automatically tagging sources.</p><p>When you make REST API calls outside the Wav...
755
en
0.658038
# coding: utf-8 """Webmail tests.""" from __future__ import unicode_literals import os import shutil import tempfile try: import mock except ImportError: from unittest import mock from six import BytesIO from django.core import mail from django.urls import reverse from modoboa.admin import factories as ad...
modoboa_webmail/tests/test_views.py
14,655
Fake IMAP4 client. Check webmail backend. Return gif. Connect with a simpler user. Create some users. Cleanup. Check attachments. Check that custom js is included. Check error cases. Test folder removal. Test folder edition. Test forward form. Try to display an empty email. Try to display a message's source. Check list...
541
en
0.749436
# -*- coding: utf-8 -*- """ General description ------------------- This example illustrates the effect of activity_costs. There are the following components: - demand_heat: heat demand (constant, for the sake of simplicity) - fireplace: wood firing, burns "for free" if somebody is around - boiler: gas f...
oemof_examples/oemof.solph/v0.4.x/activity_costs/activity_costs.py
2,684
General description ------------------- This example illustrates the effect of activity_costs. There are the following components: - demand_heat: heat demand (constant, for the sake of simplicity) - fireplace: wood firing, burns "for free" if somebody is around - boiler: gas firing, consumes (paid) gas N...
837
en
0.81873
# Copyright (c) 2019 Graphcore Ltd. All rights reserved. import numpy as np import popart import torch import pytest from op_tester import op_tester def test_and(op_tester): d1 = (np.random.randn(2) > 0).astype(np.bool_) d2 = (np.random.randn(2) > 0).astype(np.bool_) def init_builder(builder): i1...
tests/integration/operators_test/boolean_test.py
4,023
Copyright (c) 2019 Graphcore Ltd. All rights reserved. d2[0][0] = d1[0]
71
en
0.6912
#!/bin/env python """ Module to display weather info on polybar """ # -*- coding: utf-8 -*- import argparse import datetime import logging import os import time import requests import importlib # pylint: disable=redefined-builtin from requests import ConnectionError from requests.exceptions import HTTPError, Timeou...
.config/polybar/weather/weather.py
5,497
Custom exception Convert current temp_value to temp_unit Get secret api key from a file on filesystem Get script argument Workaround to get city id based on my schedule return 'day' or 'night' based on current hour Get thermometer icon based on temperature Get weather icon based on weather condition main functi...
604
en
0.648886
#!/usr/bin/env python3 import sys import argparse import time import socket from socket import socket as Socket def main(): # Command line arguments. Use a server_port > 1024 by default so that we can run # server without sudo. parser = argparse.ArgumentParser() parser.add_argument('--server-po...
ping/ping.py
2,195
Ping a UDP pinger server running at the given address Run the UDP pinger server !/usr/bin/env python3 Command line arguments. Use a server_port > 1024 by default so that we can run server without sudo. Create the server socket (to handle UDP requests using ipv4), make sure it is always closed by using with s...
752
en
0.864424
#!/usr/bin/env python import re import time from tools.multiclass_shared import prepare_data # run with toy data [traindat, label_traindat, testdat, label_testdat] = prepare_data() # run with opt-digits if available #[traindat, label_traindat, testdat, label_testdat] = prepare_data(False) parameter_list = [[traindat,...
examples/undocumented/python/classifier_multiclass_ecoc.py
2,849
!/usr/bin/env python run with toy data run with opt-digits if available[traindat, label_traindat, testdat, label_testdat] = prepare_data(False)print('Testing with %d encoders and %d decoders' % (len(encoders), len(decoders)))print('-' * 70)format_str = '%%15s + %%-10s %%-10%s %%-10%s %%-10%s'print((format_str % ('s', ...
540
en
0.115034
# Import dependencies # Math/Torch import numpy as np import torch.nn as nn # Typing from typing import List # Instantiate class class MRR(nn.Module): """Compute MRR metric (Mean reciprocal rank)""" def __init__(self, max_rank = 10): super(MRR, self).__init__() # Set max mrr rank se...
tasks/retriever/mrr.py
2,758
Compute MRR metric (Mean reciprocal rank) Calculate the reciprocal rank for a given hypothesis and reference Params: hypothesis_ids: Iterator of hypothesis ids (as numpy array) ordered by its relevance reference_id: Reference id (as a integer) of the correct id of response Returns: reciprocal rank Score th...
1,131
en
0.808446
# # 1573. Number of Ways to Split a String # # Q: https://leetcode.com/problems/number-of-ways-to-split-a-string/ # A: https://leetcode.com/problems/number-of-ways-to-split-a-string/discuss/830433/Javascript-Python3-C%2B%2B-solutions # class Solution: def numWays(self, S: str, MOD = int(1e9 + 7)) -> int: N...
1573_number_ways_to_split_string.py
1,143
1573. Number of Ways to Split a String Q: https://leetcode.com/problems/number-of-ways-to-split-a-string/ A: https://leetcode.com/problems/number-of-ways-to-split-a-string/discuss/830433/Javascript-Python3-C%2B%2B-solutions case 1: all zeros, return the sum of the series for the cardinality of S minus 1 case 2: cannot ...
526
en
0.809501
""" WSGI config for kongoauth project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SE...
kongoauth/wsgi.py
396
WSGI config for kongoauth project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/
216
en
0.741982
# -:- coding:utf8 -:- import base64 import hmac import json import sys import time import urllib import uuid from hashlib import sha1 import requests from flask import current_app from werkzeug.local import LocalProxy DEFAULT_URL = 'https://sms.aliyuncs.com' SMS = LocalProxy(lambda: current_app.exten...
flask_kits/sms/__init__.py
3,186
-:- coding:utf8 -:- content = str(content) 使用get请求方法
52
ja
0.480272
import matplotlib matplotlib.use('Agg') import os from os.path import join import argparse import torch import numpy as np import pickle import sys import datetime sys.path.append('./utils') from torch import optim from torch import nn from torch import multiprocessing from torch.optim import lr_scheduler from torch.a...
train_pose_euler_crop.py
14,230
see issue 152 Create Model Build validation set Build Training Set Get Logger Model specific setup self.optimizer = optim.SGD(self.model.parameters(), lr=self.args.lr_start, momentum=0.9) This will diminish the learning rate at the milestones ///// 0.1, 0.01, 0.001 if not using automized scheduler self.criterion = nn.C...
1,888
en
0.405994
#!/usr/bin/env python3 #------------------------------------------------------------- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses t...
src/main/python/post_setup.py
1,996
!/usr/bin/env python3------------------------------------------------------------- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to y...
896
en
0.80726
import logging import numpy as np import math import psutil import time from autogluon.common.features.types import R_BOOL, R_CATEGORY, R_OBJECT, S_BOOL, S_TEXT_NGRAM, S_TEXT_SPECIAL, S_DATETIME_AS_INT from autogluon.core.constants import REGRESSION from autogluon.core.utils.exceptions import NotEnoughMemoryError fro...
tabular/src/autogluon/tabular/models/knn/knn_model.py
13,614
KNearestNeighbors model (scikit-learn): https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KNeighborsClassifier.html Fit model with samples of the data repeatedly, gradually increasing the amount of data until time_limit is reached or all data is used. X and y must already be preprocessed. Parameters...
2,822
en
0.846049
from utils import * row_units = [cross(r, cols) for r in rows] column_units = [cross(rows, c) for c in cols] square_units = [cross(rs, cs) for rs in ('ABC','DEF','GHI') for cs in ('123','456','789')] unitlist = row_units + column_units + square_units # TODO: Update the unit list to add the new diagonal units diagon...
Projects/1_Sudoku/solution.py
7,761
Apply the eliminate strategy to a Sudoku puzzle The eliminate strategy says that if a box has a value assigned, then none of the peers of that box can have the same value. Parameters ---------- values(dict) a dictionary of the form {'box_name': '123456789', ...} Returns ------- dict The values dictionary wit...
3,710
en
0.768712
""" Module: 'uheapq' on micropython-v1.16-esp32 """ # MCU: {'ver': 'v1.16', 'port': 'esp32', 'arch': 'xtensawin', 'sysname': 'esp32', 'release': '1.16.0', 'name': 'micropython', 'mpy': 10757, 'version': '1.16.0', 'machine': 'ESP32 module (spiram) with ESP32', 'build': '', 'nodename': 'esp32', 'platform': 'esp32', 'fami...
stubs/micropython-v1_16-esp32/uheapq.py
522
Module: 'uheapq' on micropython-v1.16-esp32 MCU: {'ver': 'v1.16', 'port': 'esp32', 'arch': 'xtensawin', 'sysname': 'esp32', 'release': '1.16.0', 'name': 'micropython', 'mpy': 10757, 'version': '1.16.0', 'machine': 'ESP32 module (spiram) with ESP32', 'build': '', 'nodename': 'esp32', 'platform': 'esp32', 'family': 'mi...
346
en
0.057214
#!/usr/bin/env python2.5 # # Copyright 2009 the Melange authors. # # 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 appl...
src/melange/src/soc/models/expando_base.py
997
Expando Base model. This might later on contain general functionalities like the ModelWithFieldAttributes model. Module that contains base class for Melange Expando models. !/usr/bin/env python2.5 Copyright 2009 the Melange authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this ...
756
en
0.833272
from sqlalchemy.orm.exc import NoResultFound from zeeguu_core.model import User, Language, UserWord, Text, Bookmark def own_or_crowdsourced_translation(user, word: str, from_lang_code: str, context: str): own_past_translation = get_own_past_translation(user, word, from_lang_code, context) if own_past_trans...
zeeguu_core/crowd_translations/__init__.py
1,791
prioritize older users
22
en
0.678888
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import argparse import logging import os import time import detectron2.utils.comm as comm import torch from d2go.config import ( CfgNode as CN, auto_scale_world_size, reroute_config_path, temp_defrost, ) fro...
d2go/setup.py
10,315
Basic cli tool parser for Detectron2Go binaries Instead of loading from defaults.py, this binary only includes necessary configs building from scratch, and overrides them from args. There're two levels of config: _C: the config system used by this binary, which is a sub-set of training config, override by ...
1,728
en
0.860506
#!/usr/bin/env python3 # 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 numpy as np import torch from ax.exceptions.model import ModelError from ax.models.torch.utils import ( _gen...
ax/models/tests/test_torch_model_utils.py
8,207
!/usr/bin/env python3 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. basic test, can subset basic test, cannot subset check identity check identity test w/ outcome constraints, can subset test w/ ou...
607
en
0.81579
#!/usr/bin/env python # -*- coding: utf-8 -*- """ .. py:currentmodule:: trim.montecarlo.source .. moduleauthor:: Hendrix Demers <hendrix.demers@mail.mcgill.ca> """ # Copyright 2019 Hendrix Demers # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance wi...
trim/montecarlo/options/source.py
2,373
.. py:currentmodule:: trim.montecarlo.source .. moduleauthor:: Hendrix Demers <hendrix.demers@mail.mcgill.ca> !/usr/bin/env python -*- coding: utf-8 -*- Copyright 2019 Hendrix Demers Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You ma...
841
en
0.695874
#!/usr/bin/env python3 import utils utils.check_version((3,7)) # make sure we are running at least Python 3.7 utils.clear() # clear the screen print('Greetings!') color = '' while (color != 'red'):color = input("What is my favorite color? ") while (color != 'red'): color = color.l...
main8.py
482
!/usr/bin/env python3 make sure we are running at least Python 3.7 clear the screen
83
en
0.821779
from qtpy.QtWidgets import QDialog, QLineEdit, QPushButton, QLabel, QVBoxLayout from brainrender_gui.style import style, update_css class AddRegionsWindow(QDialog): left = 250 top = 250 width = 400 height = 300 label_msg = ( "Write the acronyms of brainregions " + "you wish to ad...
brainrender_gui/widgets/add_regions.py
2,615
Creates a new window for user to input which regions to add to scene. Arguments: ---------- main_window: reference to the App's main window palette: main_window's palette, used to style widgets On click or 'Enter' get the regions from the input and call the add_regions method of the main window Define UI's elements ...
370
en
0.71245
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import distro import logging import platform from pathlib import Path from typing import ( Union, ) from mozphab im...
mozphab/telemetry.py
6,235
Dummy class that does nothing. Container for holding globals in a way that can be easily replaced. Initiate Glean, load pings and metrics. Collect human readable information about the OS version. For Linux it is setting a distribution name and version. Sets metrics common to all commands. Update user_data to enable or...
1,294
en
0.897786
import os import numpy as np import pickle import pathlib from random import shuffle, choice def get_info_dataset(dataset_path, update=False): # TODO: Implements some checks to verify edits to the dataset from last pickle.dump(data) storing_data_path = dataset_path + "/info.txt" if update and os.path.exi...
utils/preprocessing_data.py
3,907
TODO: Implements some checks to verify edits to the dataset from last pickle.dump(data) CHECKS if the paths stored match the DB TODO: This check just pick 3 elements and check existence, can be improved Shuffle elements Create dataset filepaths Sort class_names to keep same order, which influence training in one-hot en...
363
en
0.755581
import json import logging import sys from typing import Any, Callable, Dict, List from dhis2.core.http import BaseHttpRequest from dhis2.core.inventory import HostResolved, Inventory, resolve_one from fhir.resources.bundle import Bundle from .models.svcm import CodeList, SVCMConfig from .svcm_resources import build_...
dhis2_core/src/dhis2/code_list/svcm.py
4,005
https://docs.dhis2.org/2.35/en/developer/html/webapi_metadata_object_filter.html
80
en
0.513464
#!/usr/bin/env python """ This is a crude script for detecting reference leaks in the C-based cbor2 implementation. It is by no means fool-proof and won't pick up all possible ref leaks, but it is a reasonable "confidence test" that things aren't horribly wrong. The script assumes you're in an environment with objgrap...
scripts/ref_leak_test.py
7,625
This is a crude script for detecting reference leaks in the C-based cbor2 implementation. It is by no means fool-proof and won't pick up all possible ref leaks, but it is a reasonable "confidence test" that things aren't horribly wrong. The script assumes you're in an environment with objgraph and cbor2 installed. The...
1,248
en
0.908048
# # Copyright 2018 Analytics Zoo Authors. # # 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...
pyzoo/test/zoo/chronos/model/forecast/test_lstm_forecaster.py
8,045
Copyright 2018 Analytics Zoo Authors. 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, softwar...
559
en
0.86347
from pypy.objspace.std.iterobject import W_SeqIterObject from pypy.interpreter.error import OperationError class TestW_IterObject: def body3(self, w_iter): w = self.space.wrap assert self.space.eq_w(self.space.next(w_iter), w(5)) assert self.space.eq_w(self.space.next(w_iter), w(3)) ...
idea2/pypyjs-3/deps/pypy/pypy/objspace/std/test/test_iterobject.py
4,860
this one fails on CPython. See http://bugs.python.org/issue3689 prevent re-evaluation during pytest error print prevent re-evaluation during pytest error print
160
en
0.805747
# -*- coding: utf-8 -*- """ """ import argparse import os import sys if __name__ == '__main__': pass
audy/mix/noise.py
110
-*- coding: utf-8 -*-
21
en
0.767281
import numpy as np # Thinning morphological operation applied using lookup tables. # We convert the 3x3 neighbourhood surrounding a pixel to an index # used to lookup the output in a lookup table. # Bit masks for each neighbour # 1 2 4 # 8 16 32 # 64 128 256 NEIGH_MASK_EAST = 32 NEIGH_MASK_NORTH_EAST = 4 N...
Benchmarking/bsds500/bsds/thin.py
6,261
Get a mask that shows which neighbourhood shapes result in changes to the image :param lut: lookup table :return: mask indicating which lookup indices result in changes Thinning morphological operation; condition G1 :return: a LUT index mask Thinning morphological operation; condition G2 :return: a LUT index mask Thinn...
2,161
en
0.745834
#!/usr/bin/env python3 """ Usage: program | ./memcheck.py """ import fileinput import pdb with fileinput.input() as f: data = "".join(f) s = {} for l in data.splitlines(): if "malloc:" in l: c = l.split(":") s[c[-1].strip()] = l # print("malloc:%s" %c[-1].strip...
py/memcheck.py
620
Usage: program | ./memcheck.py !/usr/bin/env python3 print("malloc:%s" %c[-1].strip()) print("free:%s" %c[-1].strip()) print("size: %d" % len(s))
146
en
0.296118
import random class Card: def __init__(self, suit, rank): self.suit = suit self.rank = rank def __str__(self): return f"{self.suit} {self.rank}: {BlackJack.values[self.rank]}" class Hand: def __init__(self): self.cards = [] # start with empty list self.value = ...
BlackJack.py
8,624
# 1. Create a deck of 52 cards # 2. Shuffle the deck # 3. Ask the Player for their bet # 4. Make sure that the Player's bet does not exceed their available chips # 5. Deal two cards to the Dealer and two cards to the Player # 6. Show only one of the Dealer's cards, the other remains hidden # 7. Show both of the Player'...
1,624
en
0.964548
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
tests/hosting/test_server.py
20,950
-------------------------------------------------------------------------------------------- Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. ----------------------------------------------------------------------------...
5,022
en
0.80631
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from ... import _utilities, _tables from...
sdk/python/pulumi_azure_native/netapp/v20200901/account.py
7,762
NetApp account resource :param str resource_name: The name of the resource. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[str] account_name: The name of the NetApp account :param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ActiveDirectoryArgs']]]] active_directories: Active...
1,141
en
0.608374
import os import logging from django.conf import settings from django.utils import translation from django.utils.translation import gettext_lazy as _ from django.db import transaction from django.core.files.base import ContentFile from celery.exceptions import SoftTimeLimitExceeded from froide.celery import app as c...
froide/foirequest/tasks.py
10,134
project does not exist anymore? pb was deleted? Redaction has failed, remove empty attachment
93
en
0.983592
"""Parse Warren2020 fluxes. Fluxes from https://zenodo.org/record/3952926 (DOI:10.5281/zenodo.3952926) See https://arxiv.org/abs/1902.01340 and https://arxiv.org/abs/1912.03328 for description of the models. """ import h5py from sntools.formats import gamma, get_starttime, get_endtime flux = {} def parse_input(in...
sntools/formats/warren2020.py
1,957
Read simulations data from input file. Arguments: input -- prefix of file containing neutrino fluxes inflv -- neutrino flavor to consider starttime -- start time set by user via command line option (or None) endtime -- end time set by user via command line option (or None) Parse Warren2020 fluxes. Fluxes from https:/...
676
en
0.640687
# Copyright 2016 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
appengine/standard/users/main.py
1,847
Sample Google App Engine application that demonstrates using the Users API For more information about App Engine, see README.md under /appengine. Copyright 2016 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain ...
719
en
0.840371
""" ASGI config for avocadobites 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.1/howto/deployment/asgi/ """ import os from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_...
avocadobites/avocadobites/asgi.py
401
ASGI config for avocadobites 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.1/howto/deployment/asgi/
218
en
0.723677
""" eZmax API Definition This API expose all the functionnalities for the eZmax and eZsign applications. # noqa: E501 The version of the OpenAPI document: 1.1.3 Contact: support-api@ezmax.ca Generated by: https://openapi-generator.tech """ import sys import unittest import eZmaxApi from eZmaxA...
test/test_ezsignformfield_response_compound.py
1,047
EzsignformfieldResponseCompound unit test stubs Test EzsignformfieldResponseCompound eZmax API Definition This API expose all the functionnalities for the eZmax and eZsign applications. # noqa: E501 The version of the OpenAPI document: 1.1.3 Contact: support-api@ezmax.ca Generated by: https://openapi-generator.tech ...
446
en
0.685035
import os import shutil import tempfile from unittest import TestCase from mock import patch from regulations.apps import RegulationsConfig class RegulationsConfigTests(TestCase): def setUp(self): self.tmpdir = tempfile.mkdtemp() def tearDown(self): shutil.rmtree(self.tmpdir) @patch('r...
regulations/tests/apps_tests.py
1,070
Verify that custom templates are found
38
en
0.867291
"""@package vc_updated Functions to implement the updated Voce-Chaboche material model and measure its error. """ import numpy as np import pandas as pd from numdifftools import nd_algopy as nda def uvc_return_mapping(x_sol, data, tol=1.0e-8, maximum_iterations=1000): """ Implements the time integration of the up...
RESSPyLab/uvc_model.py
14,107
Returns the sum of the normalized relative error of the updated Voce-Chaboche material model given x. :param np.array x: Updated Voce-Chaboche material model parameters. :param list data: (pd.DataFrame) Stress-strain history for each test considered. :return float: Normalized error value expressed as a percent (raw va...
4,148
en
0.484085
import wikipedia as wiki from ..parsing import get_wiki_page_id, get_wiki_lines, get_wiki_sections def get_wiki_references(url, outfile=None): """get_wiki_references. Extracts references from predefined sections of wiki page Uses `urlscan`, `refextract`, `doi`, `wikipedia`, and `re` (for ArXiv URLs) :...
scraper/apis/wikipedia.py
1,558
get_wiki_references. Extracts references from predefined sections of wiki page Uses `urlscan`, `refextract`, `doi`, `wikipedia`, and `re` (for ArXiv URLs) :param url: URL of wiki article to scrape :param outfile: File to write extracted references to
251
en
0.725629
from concurrent.futures.process import ProcessPoolExecutor import api.Config import api.middleware from api.Config import app from api.routers import (feedback, hiscore, label, legacy, legacy_debug, player, prediction, report, scraper) app.include_router(hiscore.router) app.include_router(pl...
api/app.py
854
@app.on_event("startup") async def startup_event(): app.state.executor = ProcessPoolExecutor() @app.on_event("shutdown") async def on_shutdown(): app.state.executor.shutdown()
183
en
0.516125
# Copyright lowRISC contributors. # Licensed under the Apache License, Version 2.0, see LICENSE for details. # SPDX-License-Identifier: Apache-2.0 import os import subprocess OTBN_DIR = os.path.join(os.path.dirname(__file__), '../../..') UTIL_DIR = os.path.join(OTBN_DIR, 'util') SIM_DIR = os.path.join(os.path.dirnam...
hw/ip/otbn/dv/otbnsim/test/testutil.py
857
Assemble and link file at asm_path in work_dir. Returns the path to the resulting ELF Copyright lowRISC contributors. Licensed under the Apache License, Version 2.0, see LICENSE for details. SPDX-License-Identifier: Apache-2.0
229
en
0.751156
#Find,Remove,Find """Return a tuple of the indices of the two smallest values in list L. >>> items = [809, 834, 477, 478, 307, 122, 96, 102, 324, 476] >>> find_two_smallest(items) (6, 7) >>> items == [809, 834, 477, 478, 307, 122, 96, 102, 324, 476] True """ from typing import List, Tuple def fin...
chapter12/examples/example02.py
972
(see above) Return a tuple of the indices of the two smallest values in list L. >>> items = [809, 834, 477, 478, 307, 122, 96, 102, 324, 476] >>> find_two_smallest(items) (6, 7) >>> items == [809, 834, 477, 478, 307, 122, 96, 102, 324, 476] True Find,Remove,Find Find the index of the minimum and remove that item Find...
456
en
0.759237
from __future__ import absolute_import, print_function import logging import bokeh.server.tornado as tornado from bokeh.application import Application from bokeh.client import pull_session from bokeh.server.views.static_handler import StaticHandler from .utils import ManagedServerLoop, url logging.basicConfig(leve...
bokeh/server/tests/test_tornado.py
4,957
tried to use capsys to test what's actually logged and it wasn't working, in the meantime at least this tests that log_stats doesn't crash in various scenarios
159
en
0.979033
#!/usr/bin/env python # Copyright 2015 Luminal, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
credstash.py
22,693
create the secret store table in DDB in the specified region fetch and decrypt all secrets Return the highest version of `name` in the table fetch and decrypt the secret called `name` do a full-table scan of the credential-store, and return the names and versions of every credential return a string that contains `i`, l...
1,578
en
0.787387
""" Django settings for lab01 project. Generated by 'django-admin startproject' using Django 3.2.6. 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/ """ fr...
lab01/lab01/settings.py
3,361
Django settings for lab01 project. Generated by 'django-admin startproject' using Django 3.2.6. 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 paths inside th...
1,080
en
0.665241
# Copyright 2018, Kay Hayen, mailto:kay.hayen@gmail.com # # Python tests originally created or extracted from other peoples work. The # parts were too small to be protected. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the ...
tests/basics/Unpacking35.py
1,866
Copyright 2018, Kay Hayen, mailto:kay.hayen@gmail.com Python tests originally created or extracted from other peoples work. The parts were too small to be protected. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You m...
730
en
0.887757
# Copyright (c) OpenMMLab. All rights reserved. import torch.nn as nn import torch.utils.checkpoint as cp from mmcv.cnn import ConvModule from mmcv.runner import BaseModule from torch.nn.modules.batchnorm import _BatchNorm from mmcls.models.utils import make_divisible from ..builder import BACKBONES from .base_backbon...
mmcls/models/backbones/mobilenet_v2.py
9,966
InvertedResidual block for MobileNetV2. Args: in_channels (int): The input channels of the InvertedResidual block. out_channels (int): The output channels of the InvertedResidual block. stride (int): Stride of the middle (first) 3x3 convolution. expand_ratio (int): adjusts number of channels of the hid...
2,387
en
0.646152
""" 多线程操作共享的全局变量是不安全的,多线程操作局部 只归某个线程私有,其他线程是不能访问的 """ import threading def do_sth(arg1, arg2, arg3): local_var1 = arg1 local_var2 = arg2 local_var3 = arg3 fun1(local_var1, local_var2, local_var3) fun2(local_var1, local_var2, local_var3) fun3(local_var1, local_var2, local_var3) def fun1(loca...
17_process_thread/46_why_need_ThreadLocal.py
1,094
多线程操作共享的全局变量是不安全的,多线程操作局部 只归某个线程私有,其他线程是不能访问的
45
zh
0.998681
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Copyright 2011-2019, Nigel Small # # 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 # # Unle...
test/unit/test_cypher_encoding.py
5,974
!/usr/bin/env python -*- encoding: utf-8 -*- Copyright 2011-2019, Nigel Small 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...
599
en
0.842704
# Written by David Weber # dsw7@sfu.ca """ In this short namespace I house a class that connects to PDB and downloads file over PDB file transfer protocol. """ # ------------------------------------------------------------------------------ import gzip from os import remove, getcwd, path # built in # m...
scalene-triangle/libs/PDB_filegetter.py
2,794
Initialize a PDBFile object with a pdb file of interest Parameters ---------- code : the pdb code if interest Any valid PDB code can be passed into PDBFile. Examples -------- >>> pdb_file = PDBFile('1rcy') Deletes file from current working directory after the file has been processed by some algorithm. Paramete...
1,090
en
0.73877
# -*- coding: utf-8 -*- #Chucky_Bot import LINETCR from LINETCR.lib.curve.ttypes import * from datetime import datetime from bs4 import BeautifulSoup from threading import Thread from googletrans import Translator from gtts import gTTS import time,random,sys,json,codecs,threading,glob,urllib,urllib2,urllib3,re,ast,os,...
ma.py
177,124
-*- coding: utf-8 -*-Chucky_Botcl.login(qr=True)ki.login(qr=True)kk.login(qr=True)kc = LINETCR.LINE()kc.login(qr=True)kc.login(token='TOKEN_KAMU_DISINI_BEIB')kc.loginResult()print "Kc-Login Success\n"kr = LINETCR.LINE()kr.login(qr=True)kr.login(token='TOKEN_KAMU_DISINI_BEIB')kr.loginResult()print "Kr-Login Success\n"km...
453
en
0.068466
# -*- coding: utf-8 -*- import tensorflow as tf import numpy as np import matplotlib.pyplot as plt import time from PIL import Image import random import os from sample import sample_conf from tensorflow.python.framework.errors_impl import NotFoundError # 设置以下环境变量可开启CPU识别 # os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_I...
train_model.py
12,141
图片转为灰度图,如果是3通道图则计算,单通道图则直接返回 :param img: :return: 返回一个验证码的array形式和对应的字符串标签 :return:tuple (str, numpy.array) 转标签为oneHot编码 :param text: str :return: numpy.array -*- coding: utf-8 -*- 设置以下环境变量可开启CPU识别 os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" os.environ["CUDA_VISIBLE_DEVICES"] = "-1" 模型路径 打乱文件顺序+校验图片格式 校验格式 打乱文件顺序 ...
712
zh
0.903385
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst # The idea for this module (but no code) was borrowed from the # quantities (http://pythonhosted.org/quantities/) package. """Helper functions for Quantity. In particular, this implements the logic that determines scaling and resul...
astropy/units/quantity_helper/helpers.py
14,433
Like Unit._get_converter, except returns None if no scaling is needed, i.e., if the inferred scale is unity. Helper functions for Quantity. In particular, this implements the logic that determines scaling and result units for a given ufunc, given input units. -*- coding: utf-8 -*- Licensed under a 3-clause BSD style...
3,062
en
0.79164
# Uses python3 import sys def get_change(money, coins): t = [j+1 for j in range(money+1)] # boundary condition t[0] = 0 for j in range(1, money+1): for c in coins: if c <= j: t[j] = min(t[j], 1+t[j-c]) return t[money] if __name__ == '__main__': coins =...
1. Algorithmic Toolbox/week5_dynamic_programming1/1_money_change_again.py
393
Uses python3 boundary condition
31
en
0.68529
from sepal_ui import sepalwidgets as sw from ipywidgets import dlink from component import parameter as cp class ParamTile(sw.Card): def __init__(self, model): # read the model self.model = model # add the base widgets self.close = sw.Icon(children=["mdi-close"], small=True) ...
component/tile/param_tile.py
1,555
read the model add the base widgets create the widgets link the widgets to the model create the object add javascript events
124
en
0.582046
#! /usr/bin/env python """Functions for working with the DLRN API""" import csv import os.path import requests from toolchest import yaml from atkinson.config.manager import ConfigManager from atkinson.logging.logger import getLogger def _raw_fetch(url, logger): """ Fetch remote data and return the text ou...
atkinson/dlrn/http_data.py
5,950
A class used to interact with the dlrn API Class constructor :param url: The URL to the host to obtain data. :param releases: The release name to use for lookup. :param link_name: The name of the dlrn symlink to fetch data from. :param logger: An atkinson logger to use. Default is the base logger. Generate a url given...
1,685
en
0.7002
""" Module for the selection of machine learning models. There are several different functions which can perform the model selection: all of them have an intuitive interface, but are also powerful and flexible. In addition, almost all these functions can optionally make plots, which sum up the performed selection...
model_selection.py
67,692
Polynomial regression model. It's a sklearn model: it's compliant to the sklearn estimators interface. `Example <https://scikit-learn.org/stable/developers/develop.html>`_ Parameters ---------- degree: int Degree to apply for the polynomial transformation. Notes ---------- The polynomial transformation is perfor...
45,537
en
0.838156
#!/usr/bin/env python3 import importlib.machinery as imm import logging import pathlib import re import configargparse class ModuleInfo: def __init__(self, path): self.path = pathlib.Path(path) name = str(self.path.parent / self.path.stem) name = name.replace("/", ".") self.name =...
doc/argparse2rst.py
1,513
!/usr/bin/env python3 parser print refs print argparse
54
de
0.080533
""" util_list module. Contains the mflist class. This classes encapsulates modflow-style list inputs away from the individual packages. The end-user should not need to instantiate this class directly. some more info """ from __future__ import division, print_function import os import warnings import numpy a...
flopy/utils/util_list.py
44,483
a generic object for handling transient boundary condition lists Parameters ---------- package : package object The package object (of type :class:`flopy.pakbase.Package`) to which this MfList will be added. data : varies the data of the transient list (optional). (the default is None) Attributes --------...
9,859
en
0.629773
# -*- coding: utf-8 -*- import requests from webs.api.exceptions.customs import ServerError, InvalidAPIRequest, RecordNotFound, RecordAlreadyExists class RequestMixin(object): CODE_EXCEPTION_MSG = { 400: InvalidAPIRequest, 404: RecordNotFound, 409: RecordAlreadyExists, 422: Inva...
services/engine/webs/core/requests/request.py
1,624
-*- coding: utf-8 -*-
21
en
0.767281
# -*- coding: utf-8 -*- from flask import Blueprint, jsonify from flask_service.swagger import spec __all__ = ['main_app'] main_app = Blueprint('main_app', __name__) @main_app.route('/api') def swagger(): """ Responds with the OpenAPI specification for this application. """ return jsonify(spec.to_d...
flask_service/views.py
968
Responds with the current's service health. Could be used by the liveness probe of a Kubernetes cluster for instance. Responds with the current's service status. Could be used by the readiness probe of a Kubernetes cluster. Responds with the OpenAPI specification for this application. -*- coding: utf-8 -*- put some...
541
en
0.940466
"""Principal Component Analysis Base Classes""" # Author: Alexandre Gramfort <alexandre.gramfort@inria.fr> # Olivier Grisel <olivier.grisel@ensta.org> # Mathieu Blondel <mathieu@mblondel.org> # Denis A. Engemann <denis-alexander.engemann@inria.fr> # Kyle Kastner <kastnerkyle@gmail.com> ...
sklearn/decomposition/_base.py
5,716
Base class for PCA methods. Warning: This class should not be used directly. Use derived classes instead. Number of transformed output features. Placeholder for fit. Subclasses should implement this method! Fit the model with X. Parameters ---------- X : array-like of shape (n_samples, n_features) Training data,...
2,599
en
0.698375
""" enCount tasks and analyses. enCount is a Python library for processing RNA-Seq data from ENCODE. """ # from ._version import __version__ from . import config # load from myconfig.py if it exists from . import db from . import queues from . import encode from . import externals from . import gtfs from . impor...
enCount/__init__.py
403
enCount tasks and analyses. enCount is a Python library for processing RNA-Seq data from ENCODE. from ._version import __version__ load from myconfig.py if it exists
168
en
0.636759
from asgiref.sync import sync_to_async from channels.layers import get_channel_layer from ....models import Participant import humps channel_layer = get_channel_layer() def get_participant(room_channel_name, channel_name): participant = Participant.objects.get( channel_room__channel_name=room_channel_name...
server/websockets/consumers/world/broadcasts/avatar.py
2,293
receive the participant that sent this message if this was for an avatar, then set participant's position to the payload data receive the participant that sent this message
172
en
0.910202
"""Plot graphs from human-readable file formats."""
uniplot/__init__.py
52
Plot graphs from human-readable file formats.
45
en
0.783492
# https://www.hackerrank.com/challenges/tree-height-of-a-binary-tree/problem def height(root): """ DFS v = Vertices e = Edges d = Depth Time complexity: O(v + e) Space complexity: O(d) """ if root: return 1 + max(height(root.left), height(root.right)) else: ...
HackerRank/Data Structures/Trees/height-of-a-binary-tree.py
331
DFS v = Vertices e = Edges d = Depth Time complexity: O(v + e) Space complexity: O(d) https://www.hackerrank.com/challenges/tree-height-of-a-binary-tree/problem
167
en
0.722572
from dbt.clients.system import load_file_contents from dbt.contracts.files import ( FilePath, ParseFileType, SourceFile, FileHash, AnySourceFile, SchemaSourceFile ) from dbt.parser.schemas import yaml_from_file from dbt.parser.search import FilesystemSearcher # This loads the files contents and creates the Sourc...
core/dbt/parser/read_files.py
4,420
This loads the files contents and creates the SourceFile object Special processing for big seed files We don't want to calculate a hash of this file. Use the path. Use the FilesystemSearcher to get a bunch of FilePaths, then turn them into a bunch of FileSource objects file path list file block list This needs to read ...
715
en
0.86283
from typing import List ''' 1. subproblems: dp(amount) the minimum number of coins needed to make changes for amount of S using the given coin denomination 2. guessing: all the available denomination c_i 3. relate subproblems: dp(amount) = min(dp(amount - c_i) + 1) for all possible c_i Time complexity: O(#subproblems...
solution/322. coin-change.py
2,052
top down solution for amount less than 1, return 0 for subproblems that we have alreay solve and memorized base case, we reach out the bottom of the tree. go through all possible coin denomination(breaches in tree) relate subproblems bottom-up solution, DAG dp[i] = min{dp[i - c_i] + 1} for all c_i check all the states ...
390
en
0.86493
import SimpleITK as sitk import numpy as np import torch import math import time import sys import cv2 from scipy.ndimage.interpolation import zoom from torch.autograd import Variable sys.path.append('../lung_nodule_detector') from training.layers import nms def load_itk_image(filename): with open(filename) as f:...
UI_util.py
14,065
pos_ori = pos_ori + extendbox[:, 0] fps 1.215909091, sens 0.933333333, thres 0.371853054 check overlap under 3mm print (name) print (lbb) print (world_pbb) fps 1.215909091, sens 0.933333333, thres 0.371853054 check overlap under 3mm print (name) print (lbb) print (world_pbb) label = np.ceil(label)cv2.putText(img_arr[j]...
531
en
0.428478
# Copyright (c) 2021 Sen Wu. All Rights Reserved. """Helper function to set random seed for reproducibility of models.""" import logging import random from typing import Optional import numpy as np import torch logger = logging.getLogger(__name__) def set_random_seed(seed: Optional[int] = None) -> None: """S...
src/emmental/utils/seed.py
1,240
Set random seed for random, numpy, and pytorch. Args: seed: The random seed, defaults to `None` which select it randomly. Helper function to set random seed for reproducibility of models. Copyright (c) 2021 Sen Wu. All Rights Reserved. Set random seed for random Set random seed for all numpy operations Set random ...
336
en
0.725011