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
# -*- coding: utf-8 -*- import os import sys sys.path.insert(0, os.path.abspath('..')) # -- General configuration ------------------------------------------------ # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extens...
docs/conf.py
5,413
-*- coding: utf-8 -*- -- General configuration ------------------------------------------------ Add any Sphinx extension module names here, as strings. They can be extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones. TODO: Please Read! Uncomment the below if you use native CircuitPython modules suc...
3,190
en
0.691776
#!/usr/bin/env python3 def selection_sort(lst): length = len(lst) for i in range(length - 1): least = i for k in range(i + 1, length): if lst[k] < lst[least]: least = k lst[least], lst[i] = (lst[i], lst[least]) return lst print(selection_sort([5, 2, 4, ...
sort/selection_sort.py
330
!/usr/bin/env python3
21
fr
0.448822
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
tests/custom_cluster/test_web_pages.py
7,006
Tests that the maximum length of a POST request that will be accepted Check if the partial query with the correct length is displayed in the query list on the WebUI. Check if the full query string is displayed in the query list on the WebUI. Tests that modified hidden variables show up in /varz Licensed to the Apache...
2,046
en
0.8669
import torch import torch.nn as nn import torch.nn.functional as F class MLP(nn.Module): def __init__(self, dims, multiplxer=4): super(MLP, self).__init__() hidden = int(dims * multiplxer) self.out = nn.Sequential( nn.Linear(dims, hidden), nn.GELU(), nn...
model.py
5,998
self.embedding = nn.Linear(in_dims, dims) if __name__ == '__main__': main()
79
en
0.287994
import time from datetime import datetime, timedelta from urllib.parse import urljoin import requests from bs4 import BeautifulSoup from flask.views import MethodView from config.setting import BOT_TOKEN from models import User hitcon_zeroday_base_url = "https://zeroday.hitcon.org" hitcon_zeroday_all_url = "https://...
apps/hitcon_zeroday.py
3,221
Get utf+8 datetime Get only yesterday's data parse all blocks break if not append new data
90
en
0.45595
"""Module containing methods that allow to identify task goals.""" # Copyright (c) 2022, ABB # All rights reserved. # # Redistribution and use in source and binary forms, with # or without modification, are permitted provided that # the following conditions are met: # # * Redistributions of source code must retain t...
bt_learning/bt_learning/learning_from_demo/goal_identification.py
3,227
Infer the goal conditions of a single demonstration. Args ---- demo: the demonstration to infer the goal of. behavior: check the behavior to remove conflicting conditions. Returns ------- goals: list of the goals inferred in the demonstration. Construct a Behavior Tree strarting from the goals. Args ----...
2,128
en
0.877129
import json import crawlKoreaData_All as crawl1 import crawlKoreaData_Gyeonggi as crawl2 import crawlKoreaData_Seoul as crawl3 import LED_Display as LMD import threading from datetime import date, timedelta import datetime from matrix import * today = date.today() oneday = datetime.timedelta(days=1) yester...
crawling_update(LED)/main_s.py
17,292
BLUEGREENYELLOWREDPINKCYANWHITE0123456789 C O V I DTODAY 지역별 확진자 수 검색 함수 (LED구현)YESTERDAY 지역별 확진자 수 검색 함수 (LED구현)BEFORE_YESTERDAY 지역별 확진자 수 검색 함수 (LED구현) 지역별 전날대비 확진자 수 증감 검색 함수 while > 뒤로가기 입력전까지 menu 반복시행 전국 확진자 수 검색 0을 입력하면 메뉴로 복귀 서울 세부지역 확진자 수 검색 0을 입력하면 메뉴로 복귀 경기 세부지역 확진자 수 검색 0을 입력하면 메뉴로 복귀 메뉴 종료
303
ko
0.999644
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick and Xinlei Chen # -------------------------------------------------------- """Compute minibatch blobs for training a Fast R-CNN ne...
lib/roi_data_layer/minibatch.py
4,553
Builds an input blob from the images in the roidb at the specified scales. Given a roidb, construct a minibatch sampled from it. Compute minibatch blobs for training a Fast R-CNN network. -------------------------------------------------------- Fast R-CNN Copyright (c) 2015 Microsoft Licensed under The MIT License [s...
1,487
en
0.549048
# This Python file uses the following encoding: utf-8 """autogenerated by genpy from drive_ros_msgs/mav_cc16_IMU.msg. Do not edit.""" import sys python3 = True if sys.hexversion > 0x03000000 else False import genpy import struct import geometry_msgs.msg import std_msgs.msg class mav_cc16_IMU(genpy.Message): _md5sum...
Catkin_PKG_Car/devel/lib/python2.7/dist-packages/drive_ros_msgs/msg/_mav_cc16_IMU.py
8,585
Constructor. Any message fields that are implicitly/explicitly set to None will be assigned a default value. The recommend use is keyword arguments as this is more robust to future message changes. You cannot mix in-order arguments and keyword arguments. The available fields are: header,sysid,compid,acc,gyro,mag ...
1,283
en
0.5669
# Copyright 2018-2019 The glTF-Blender-IO 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 ...
addons/io_scene_gltf2/blender/exp/gltf2_blender_gather_materials_pbr_metallic_roughness.py
7,737
Copyright 2018-2019 The glTF-Blender-IO 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 writi...
570
en
0.850521
"""A setuptools based setup module. See: https://packaging.python.org/guides/distributing-packages-using-setuptools/ https://github.com/pypa/sampleproject """ # Always prefer setuptools over distutils from setuptools import setup, find_packages, Extension from os import path # io.open is needed for projects that suppo...
setup.py
9,336
A setuptools based setup module. See: https://packaging.python.org/guides/distributing-packages-using-setuptools/ https://github.com/pypa/sampleproject Always prefer setuptools over distutils io.open is needed for projects that support Python 2.7 It ensures open() defaults to text mode with universal newlines, and ac...
6,972
en
0.758057
import os import pdb import sys import tempfile sys.path.append("/opt/tosca") from translator.toscalib.tosca_template import ToscaTemplate from core.models import Instance,User,Network,NetworkTemplate,Port from xosresource import XOSResource class XOSPort(XOSResource): provides = ["tosca.nodes.network.Port"] ...
xos/tosca/resources/port.py
1,901
Port objects have no name, their unique key is (instance, network)
66
en
0.951562
"""User defaults Revision ID: 30b25dd39af0 Revises: 46b85e11f48f Create Date: 2015-02-12 15:34:59.515740 """ # revision identifiers, used by Alembic. revision = '30b25dd39af0' down_revision = '46b85e11f48f' branch_labels = None depends_on = None from alembic import op import sqlalchemy as sa def upgrade(): ##...
migrations/versions/30b25dd39af0_user_defaults.py
768
User defaults Revision ID: 30b25dd39af0 Revises: 46b85e11f48f Create Date: 2015-02-12 15:34:59.515740 revision identifiers, used by Alembic. commands auto generated by Alembic - please adjust! end Alembic commands commands auto generated by Alembic - please adjust! end Alembic commands
292
en
0.643221
numbers = input().split(', ') numbers_list = list(map(int, numbers)) even_list = [] for i in range (len(numbers_list)): if numbers_list[i] % 2 == 0: even_list.append(i) print(even_list) # found_indices = map(lambda x: x if numbers_list[x] % 2 == 0 else 'no', range(len(numbers_list))) # even_indices = list...
even_numbers_list_advanced.py
387
found_indices = map(lambda x: x if numbers_list[x] % 2 == 0 else 'no', range(len(numbers_list))) even_indices = list(filter(lambda a: a != 'no', found_indices)) print(even_indices)
180
en
0.123586
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.response.AlipayResponse import AlipayResponse from alipay.aop.api.domain.KbdishMaterialInfo import KbdishMaterialInfo class KoubeiCateringDishMaterialDeleteResponse(AlipayResponse): def __init__(self): super(KoubeiCateringDish...
alipay/aop/api/response/KoubeiCateringDishMaterialDeleteResponse.py
1,069
!/usr/bin/env python -*- coding: utf-8 -*-
42
en
0.34282
from __future__ import print_function import sys import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import os import time # Options for mode 'lower_level' MODE = 'S-4mu_WigD' label_size = 28 #################################################################################################...
learningml/GoF/analysis/S-4mu/plot_S-4mu_updated10_alphaSvalue_analysis.py
11,120
Options for mode 'lower_level' mpl.rcParams['text.usetex'] = Truempl.rcParams['text.latex.preamble'] = [r'\boldmath'] S - 4 mu WigDparam_list = [0.1,0.08,0.06,0.04,0.02,0.0]chi2_splits = [8]chi2_folder_name = "event_shapes_lower_level_without_Mult"chi2_file_name = "event_shapes_lower_...
1,185
en
0.308641
try: from os import system from os.path import isdir,isfile from time import sleep from npc import NPC from tutorial import text import pack import sys from requests import get if not isfile('./config'): open('config','w').write('firmware: https://raw.githubusercontent.com/miko1112/comp9/main/fir...
core.py
5,642
execscript('exec ./system_scripts/system.c9s')cls()
51
el
0.196469
import torch import torch.nn as nn import torch.nn.functional as F from torch.nn import init from torchvision import models import numpy as np device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') def weights_init_normal(m): classname = m.__class__.__name__ if classname.find('Conv') != -1: ...
gmm.py
13,395
Geometric matching module reshape features for matrix multiplication perform matrix mult. create grid in numpy sampling grid with dim-0 coords (Y) grid_X,grid_Y: size [1,H,W,1,1] initialize regular grid for control points P_i size (N,1) size (N,1) num of points (along dim 0) construct matrix K make diagonal 1 to...
1,294
en
0.794238
''' Created on Sep 3, 2012 @author: Daniel J. Rivers ''' from DataAccess.TableData import TableData from DataAccess.TableHandler import TableHandler class EpisodeHandler( TableHandler ): pass class Episode( TableData ): def __init__( self ): self.columnNames = [ ( "SEASON_ID", "INTEGE...
FileInventory/DataAccess/Tables/EpisodeHandler.py
457
Created on Sep 3, 2012 @author: Daniel J. Rivers
50
en
0.766168
import mmdet2trt.ops.util_ops as mm2trt_util import torch from mmdet2trt.models.builder import register_wraper from mmdet2trt.models.dense_heads.anchor_free_head import AnchorFreeHeadWraper @register_wraper('mmdet.models.FoveaHead') class FoveaHeadWraper(AnchorFreeHeadWraper): def __init__(self, module): ...
mmdet2trt/models/dense_heads/fovea_head.py
3,524
concate zero to enable topk, dirty way, will find a better way in future do topk
80
en
0.62364
from django.conf.urls import url from django.conf.urls import patterns from events import views urlpatterns = patterns('', # Events url(r'^microcosms/(?P<microcosm_id>\d+)/create/event/$', views.create, name='create-event'), url(r'^events/(?P<event_id>\d+)/$', views.single, name='single-event'), url(r...
events/urls.py
831
Events RSVP to an event Proxy geocoding requests to the backend
63
en
0.828468
# py-motmetrics - Metrics for multiple object tracker (MOT) benchmarking. # https://github.com/cheind/py-motmetrics/ # # MIT License # Copyright (c) 2017-2020 Christoph Heindl, Jack Valmadre and others. # See LICENSE file for terms. """Tests behavior of MOTAccumulator.""" from __future__ import absolute_import from _...
motmetrics/tests/test_mot.py
8,795
Tests auto_id option. Tests that expected events are created by MOTAccumulator.update(). Tests max_switch_time option. Tests merge_event_dataframes(). Tests behavior of MOTAccumulator. py-motmetrics - Metrics for multiple object tracker (MOT) benchmarking. https://github.com/cheind/py-motmetrics/ MIT License Copyrigh...
617
en
0.677632
from django.db import models from django.utils import timezone from django.db.models import Sum #from cycle_2018.models import ScheduleA import datetime class BaseModel(models.Model): active = models.BooleanField(default=True) created = models.DateTimeField(default=timezone.now) updated = models.DateTimeF...
donor/models.py
1,431
from cycle_2018.models import ScheduleA
39
en
0.401535
# exported from PySB model 'model' from pysb import Model, Monomer, Parameter, Expression, Compartment, Rule, Observable, Initial, MatchOnce, Annotation, ANY, WILD Model() Monomer('Ligand', ['Receptor']) Monomer('ParpU', ['C3A']) Monomer('C8A', ['BidU', 'C3pro']) Monomer('SmacM', ['BaxA']) Monomer('BaxM', ['BidM', '...
flux_combined_high_binding/model_792.py
20,550
exported from PySB model 'model'
32
en
0.742345
import json import re import logging as log from .helpers import path_leaf regexes = { "bp_processed": "Total basepairs processed:\s*([\d,]+) bp", "bp_written": "Total written \(filtered\):\s*([\d,]+) bp", "quality_trimmed": "Quality-trimmed:\s*([\d,]+) bp", "r_processed": "Total reads processed:\s*([\...
riboraptor/cutadapt_to_json.py
3,375
Convert cutadapt/trim_galore output to json Parameters ---------- filepath: string Path to trim_galore/cutadapt output.txt Returns ------- json_data: dict Used user provided input and hence no second pass
218
en
0.338154
""" The ``mlflow.keras`` module provides an API for logging and loading Keras models. This module exports Keras models with the following flavors: Keras (native) format This is the main flavor that can be loaded back into Keras. :py:mod:`mlflow.pyfunc` Produced for use by generic pyfunc-based deployment tools ...
mlflow/keras.py
30,805
Callback for auto-logging metrics and parameters. Records available logs after each epoch. Records model structural information as params when training begins Load PyFunc implementation. Called by ``pyfunc.load_pyfunc``. :param path: Local filesystem path to the MLflow Model with the ``keras`` flavor. Save custom obje...
14,072
en
0.6597
# Copyright 2013-2022 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.package import * class Armadillo(CMakePackage): """Armadillo is a high quality linear algebra library (ma...
var/spack/repos/tutorial/packages/armadillo/package.py
2,312
Armadillo is a high quality linear algebra library (matrix maths) for the C++ language, aiming towards a good balance between speed and ease of use. Copyright 2013-2022 Lawrence Livermore National Security, LLC and other Spack Project Developers. See the top-level COPYRIGHT file for details. SPDX-License-Identifier: ...
770
en
0.779112
# coding: utf-8 import pprint import re import six from huaweicloudsdkcore.sdk_response import SdkResponse class UpdateLoadBalancerResponse(SdkResponse): """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map...
huaweicloud-sdk-elb/huaweicloudsdkelb/v3/model/update_load_balancer_response.py
3,798
Attributes: openapi_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 UpdateLoadBalancerResponse - a model defined in...
1,104
en
0.426084
#!/usr/bin/env python3 # # Extract a CSV of findings for a particular bucket # import boto3 from botocore.exceptions import ClientError import json import os import time import csv from time import sleep from datetime import datetime import logging logger = logging.getLogger() logger.setLevel(logging.INFO) logging....
scripts/extract_findings_to_csv.py
8,828
Return an array of the regions this account is active in. Ordered with us-east-1 in the front. !/usr/bin/env python3 Extract a CSV of findings for a particular bucket Macie is regional even though buckets aren't. So we need to iterate across regions to find out bucket Unless you know already Store bucket results Build...
1,157
en
0.698311
from env import lineFollower from stable_baselines import PPO2 import imageio import numpy as np # Load separate environment for evaluation env = lineFollower() # load model model = PPO2.load("model_final.zip") # Store image images = [] # Set environment and get image obs = env.reset() images.append(obs) done =...
Simulation/play.py
615
Load separate environment for evaluation load model Store image Set environment and get image shutdown environment
114
en
0.830815
#!/usr/bin/env python """ Matplotlib provides sophisticated date plotting capabilities, standing on the shoulders of python :mod:`datetime`, the add-on modules :mod:`pytz` and :mod:`dateutil`. :class:`datetime` objects are converted to floating point numbers which represent time in days since 0001-01-01 UTC, plus 1. ...
env/lib/python2.7/site-packages/matplotlib/dates.py
52,905
This class attempts to figure out the best format to use. This is most useful when used with the :class:`AutoDateLocator`. The AutoDateFormatter has a scale dictionary that maps the scale of the tick (the distance in days between one major tick) and a format string. The default looks like this:: self.scaled = ...
21,748
en
0.787113
# coding=utf-8 # Copyright 2022 The Google Research 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 applicab...
widget_caption/widget_caption_model.py
38,627
Captioning decoder layer. Embedding layer. Generates encoder outputs for both the pixels and view hierarchy. Pixel encoding layer (ResNet). Learning rate log callback. Widget Captioning Model. Aggregate text embedding for a UI element. Embed a position feature. Encodes view hierarchy. Defines the encoding model with a ...
6,864
en
0.70789
import models import serializers from rest_framework import viewsets, permissions class apiViewSet(viewsets.ModelViewSet): """ViewSet for the api class""" queryset = models.api.objects.all() serializer_class = serializers.apiSerializer permission_classes = [permissions.IsAuthenticated]
api_invman/api.py
308
ViewSet for the api class
25
en
0.463168
# Copyright 2016 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/util/deprecation_test.py
24,975
fn doc. Args: arg0: Arg 0. arg1: Arg 1. Returns: Sum of args. fn doc. fn doc. Args: arg0: Arg 0. arg1: Arg 1. deprecated: Deprecated! Returns: Sum of args. fn doc. fn doc. Args: arg0: Arg 0. arg1: Arg 1. deprecated: Deprecated! Returns: Sum of args. fn doc. fn doc. Args: arg0: Arg 0. ar...
3,396
en
0.755342
# # endpoints import logging from datetime import datetime from dateutil.relativedelta import relativedelta from django.contrib import messages from django.contrib.auth.decorators import user_passes_test from django.core.exceptions import PermissionDenied from django.core.urlresolvers import reverse from django.http i...
dojo/endpoint/views.py
14,942
endpoints are they authorized are they authorized include current month
71
en
0.984095
# Copyright Contributors to the Pyro project. # SPDX-License-Identifier: Apache-2.0 import contextlib import funsor from funsor.adjoint import AdjointTape from pyro.contrib.funsor import to_data, to_funsor from pyro.contrib.funsor.handlers import enum, plate, replay, trace from pyro.contrib.funsor.infer.elbo import ...
pyro/contrib/funsor/infer/traceenum_elbo.py
12,049
Helper function to extract elbo components from execution traces. Copyright Contributors to the Pyro project. SPDX-License-Identifier: Apache-2.0 Work around a bug in unfold_contraction_generic_tuple interacting with Approximate introduced in https://github.com/pyro-ppl/funsor/pull/488 . Once fixed, this can be repla...
2,655
en
0.794893
# -*- coding: utf-8 -*- # # Copyright 2020 - Swiss Data Science Center (SDSC) # A partnership between École Polytechnique Fédérale de Lausanne (EPFL) and # Eidgenössische Technische Hochschule Zürich (ETHZ). # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compli...
tests/service/jobs/test_datasets.py
9,970
Test dataset add a remote file. Test dataset import via doi. Test dataset import. Test dataset import. Test dataset project lock. Test dataset import via url. Renku service dataset jobs tests. -*- coding: utf-8 -*- Copyright 2020 - Swiss Data Science Center (SDSC) A partnership between École Polytechnique Fédérale de...
945
en
0.66728
# specifically use concurrent.futures for threadsafety # asyncio Futures cannot be used across threads import asyncio import json import time from functools import partial from kubernetes_asyncio import watch from traitlets import Any from traitlets import Bool from traitlets import Dict from traitlets import Int from...
kubespawner/reflector.py
15,962
Watches for resources across all namespaces. The list_methods want only a method name. Note that this requires the service account to be significantly more powerful, since it must be bound to ClusterRoles rather than just Roles, and therefore this is inherently more dangerous. Watches for resources in a particular na...
2,924
en
0.884472
# pylint: disable=line-too-long from allennlp.data.dataset_readers.semantic_parsing.atis import AtisDatasetReader from allennlp.data.dataset_readers.semantic_parsing.nlvr import NlvrDatasetReader from allennlp.data.dataset_readers.semantic_parsing.wikitables import WikiTablesDatasetReader from allennlp.data.dataset_rea...
allennlp/data/dataset_readers/semantic_parsing/__init__.py
397
pylint: disable=line-too-long
29
en
0.550227
import numpy as np from basicsr.archs.rrdbnet_arch import RRDBNet from realesrgan.utils import RealESRGANer def test_realesrganer(): # initialize with default model restorer = RealESRGANer( scale=4, model_path='experiments/pretrained_models/RealESRGAN_x4plus.pth', model=None, ...
tests/test_utils.py
3,089
initialize with default model initialize with user-defined model test attribute ------------------ test pre_process ---------------- with modcrop ------------------ test process ---------------- ------------------ test post_process ---------------- ------------------ test tile_process ---------------- -------------...
622
en
0.358603
# Generated by Django 3.1.5 on 2021-02-18 23:09 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('accounts', '0005_apirequestlog'), ] operations = [ migrations.AlterModelOptions( name='apirequestlog', options={'verbose_nam...
velkozz_web_api/apps/accounts/migrations/0006_auto_20210218_2309.py
368
Generated by Django 3.1.5 on 2021-02-18 23:09
45
en
0.639008
import geopy # Here we just tested geopy functionality. place = "kuusalu" locator = geopy.Nominatim(user_agent="myGeocoder") location = locator.geocode(place) print(place + ":") print("Latitude = {}, Longitude = {}".format(location.latitude, location.longitude))
Koordinaator.py
265
Here we just tested geopy functionality.
40
en
0.925312
#!/usr/bin/python3.6 import sys import re import csv import numpy as np import pandas as pd import string import nltk from nltk.corpus import stopwords import textcleaner as tc def main(separator='\t'): # input comes from STDIN (standard input) topWords_list = ['club','baseball','league','team','game','socce...
part3/Commoncrawl/Code/mapper_latest_coocureence_cc.py
4,477
!/usr/bin/python3.6 input comes from STDIN (standard input) strip the line and remove unnecessary parts split the line def strip_line(text): strip smileys,emojis,urls from tweet text to get only text smileys = """:-) :) :o) :] :3 :c) :> =] 8) =) :} :^) :D 8-D 8D x-D xD X-D XD =-D =D =-3 =3 B^D""".spl...
1,656
en
0.31562
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 5/15/20 4:49 PM # @File : grover.py # qubit number=2 # total number=9 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 ...
data/p2DJ/New/R2/benchmark/startCirq85.py
1,711
!/usr/bin/env python -*- coding: utf-8 -*- @Time : 5/15/20 4:49 PM @File : grover.py qubit number=2 total number=9thatsNoCode Symbols for the rotation angles in the QAOA circuit. circuit begin number=1 number=5 number=4 number=6 number=7 number=8 number=3 circuit end
273
en
0.410845
# -*- coding: utf-8 -*- """ Created on Mon Jan 8 21:45:27 2018 @author: pilla """
LicenseGenerator/accounts/tests/__init__.py
85
Created on Mon Jan 8 21:45:27 2018 @author: pilla -*- coding: utf-8 -*-
75
en
0.685269
from datetime import datetime from integration_tests.utils import populate_mock_db_blocks from src.models import Challenge, ChallengeType, User, UserBankAccount, UserChallenge from src.queries.get_undisbursed_challenges import get_undisbursed_challenges from src.utils.db_session import get_db def setup_challenges(ap...
discovery-provider/integration_tests/queries/test_undisbursed_challeges.py
6,466
Test that all undisbursed challenges are returned in order Test that it filters correctly by user_id Test that it filters correctly by user_id & completed blocknumber
166
en
0.920369
from collections import OrderedDict from models.base_model import BaseModel from optimizers.radam import RAdam import random import torch import torch.nn as nn import torch.nn.functional as F from sklearn.metrics import accuracy_score import sys class double_conv(nn.Module): def __init__(self, in_ch, out_ch): ...
models/segmentation_model.py
5,805
Standard U-Net architecture network. Input params: n_channels: Number of input channels (usually 1 for a grayscale image). n_classes: Number of output channels (2 for binary segmentation). Initialize the model. Calculate losses; called in every training iteration. Run forward pass. C...
709
en
0.860718
import warnings import torch import kornia import numpy as np class MetricMAD: def __call__(self, pred, true): return (pred - true).abs_().mean() * 1e3 class MetricBgrMAD: def __call__(self, pred, true): bgr_mask = true == 0 return (pred[bgr_mask] - true[bgr_mask]).abs_().mean() * 1e...
evaluation/evaluation_metrics.py
2,682
create filter in x axis normalize filter
40
en
0.79624
"""Calculate the mean and standard deviation (per channel) over all images in a dataset """ # MIT License # # Copyright (c) 2017 David Sandberg # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Soft...
src/generative/calculate_dataset_normalization.py
10,147
Calculate the mean and standard deviation (per channel) over all images in a dataset MIT License Copyright (c) 2017 David Sandberg Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restri...
1,404
en
0.846789
# -*- coding: utf-8 -*- """ The MIT License (MIT) Copyright (c) 2015-2020 Rapptz Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to u...
discord/file.py
4,063
A parameter object used for :meth:`abc.Messageable.send` for sending file objects. .. note:: File objects are single use and are not meant to be reused in multiple :meth:`abc.Messageable.send`s. Attributes ----------- fp: Union[:class:`str`, :class:`io.BufferedIOBase`] A file-like object opened in binary...
2,471
en
0.831759
# Dependencies import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from sklearn.preprocessing import MinMaxScaler from sklearn.neighbors import KNeighborsClassifier import pickle def train_model(): # Read data set spotify_df = pd.read_csv("spotify_data_v4.csv") # Ex...
model.py
2,093
Dependencies Read data set Extract the necessary columns we need for machine learning model Assign X (data) and y (target) Create train and test sets Scale the data using MinMaxScaler Create a MinMaxScaler model and fit it to the training data Transform the training and testing data using the X_scaler Read data set Ext...
635
en
0.706089
# -*- coding: utf-8 -*- # Copyright 2018 IBM and its contributors. # # 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 a...
utils/test/test_tutorials.py
4,026
TestCase for running the tutorials. Metaclass that dynamically appends a "test_TUTORIAL_NAME" method to the class. Convert a string to a valid Python identifier. Return a new test function. Helper for running the notebooks as unit tests. Convenience script for running the notebooks as individual `unittest` tests using...
1,981
en
0.728423
# uncompyle6 version 3.2.4 # Python bytecode 2.7 (62211) # Decompiled from: Python 2.7.15 (v2.7.15:ca079a3ea3, Apr 30 2018, 16:30:26) [MSC v.1500 64 bit (AMD64)] # Embedded file name: lib.coginvasion.suit.SuitAttacks from direct.directnotify.DirectNotifyGlobal import directNotify from direct.interval.IntervalGlobal imp...
lib/coginvasion/suit/SuitAttacks.py
48,731
uncompyle6 version 3.2.4 Python bytecode 2.7 (62211) Decompiled from: Python 2.7.15 (v2.7.15:ca079a3ea3, Apr 30 2018, 16:30:26) [MSC v.1500 64 bit (AMD64)] Embedded file name: lib.coginvasion.suit.SuitAttacks
208
en
0.516043
# Copyright 2013-2022 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 RaxmlNg(CMakePackage): """RAxML-NG is a phylogenetic tree inference tool which uses ma...
var/spack/repos/builtin/packages/raxml-ng/package.py
1,236
RAxML-NG is a phylogenetic tree inference tool which uses maximum-likelihood (ML) optimality criterion. Its search heuristic is based on iteratively performing a series of Subtree Pruning and Regrafting (SPR) moves, which allows to quickly navigate to the best-known ML tree. RAxML-NG is a successor of RAxML (Stamataki...
620
en
0.829602
""" Afterglow Core: settings routes """ import secrets import json from flask import Response, request, redirect from marshmallow.fields import Integer, String from ...oauth2 import oauth_clients from ... import app, json_response from ...auth import auth_required, set_access_cookies from ...resources.users import ...
afterglow_core/views/ajax_api/oauth2_clients.py
1,006
Return OAuth2 client applications :return: GET /ajax/oauth2/clients: list of OAuth2 clients Afterglow Core: settings routes
128
en
0.486526
from .base import * # noqa from .base import env # GENERAL # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/dev/ref/settings/#debug DEBUG = True # https://docs.djangoproject.com/en/dev/ref/settings/#secret-key SECRET_KEY = env( "DJANGO_SECRET_KEY...
config/settings/local.py
2,739
noqa GENERAL ------------------------------------------------------------------------------ https://docs.djangoproject.com/en/dev/ref/settings/debug https://docs.djangoproject.com/en/dev/ref/settings/secret-key https://docs.djangoproject.com/en/dev/ref/settings/allowed-hosts CACHES -------------------------------------...
1,508
en
0.389357
import threading import time import mpl_qtthread.backend import matplotlib import matplotlib.backends.backend_qt import matplotlib.pyplot as plt from matplotlib.backends.qt_compat import QtWidgets, QtCore # set up the teleporter mpl_qtthread.backend.initialize_qt_teleporter() # tell Matplotlib to use this backend mat...
UAT.py
2,295
set up the teleporter tell Matplotlib to use this backend suppress (now) spurious warnings for mpl3.3+ button to exit early and to make sure qapp does not quit! stop UAT in 12s this is in ms make a figure and plot some data periodically update the figure start the thread start the QApplication main loop
304
en
0.833233
# -*- coding: utf-8 -*- """ SHT21 Sensor Plugin. Return temperature and relative humidity from sensor readings. Calculate and return absolute humidity and dew point. Source for calculations: http://www.vaisala.com/Vaisala%20Documents/Application%20notes/Humidity_Conversion_Formulas_B210973EN-F.pdf """ from __future_...
sht21_usermode.py
4,202
Calculate the absolute humidity (in g/m³). A = C \cdot P_w / T Calculate Pw (in hPa). P_W = P_{WS} \cdot RH / 100 Calculate water vapor saturation pressure based on temperature (in hPa). P_{WS} = A \cdot 10^{\frac{m \cdot T}{T + T_n}} Lookup-table for water vapor saturation pressure constants (A, m, Tn)....
894
en
0.525429
# Tests for client code in bin/test
bin/test/__init__.py
36
Tests for client code in bin/test
33
en
0.803014
import discord from discord.ext import commands class AttackStrats(commands.Cog): def __init__(self, bot): self.bot = bot @commands.group() async def strat(self, ctx): if ctx.invoked_subcommand is None: await ctx.send("You need to specify a townhall and strategy! Available...
cogs/attack_strats.py
7,566
@th9.command(name="dragons") async def dragons(self, ctx): await ctx.send("")
81
en
0.126276
# The followings are the DenseNets module, the training was actually taken place in the `run_dense_net.py` file. # Sorry, I really like Pycharm (and to be fair, Pytorch is so much an easier language to debug) import os os.environ['CUDA_VISIBLE_DEVICES'] = '2' from models import DenseNet from data_providers.utils import...
test_single.py
8,881
Convert 1D array of labels to one hot representation Args: labels: 1D numpy array The followings are the DenseNets module, the training was actually taken place in the `run_dense_net.py` file. Sorry, I really like Pycharm (and to be fair, Pytorch is so much an easier language to debug) Visualizations will be sho...
1,028
en
0.775007
#!/usr/bin/env python3 # Copyright (c) 2014-2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # Exercise the listtransactions API from test_framework.test_framework import SkyrusTestFramework from t...
qa/rpc-tests/listtransactions.py
10,217
!/usr/bin/env python3 Copyright (c) 2014-2016 The Bitcoin Core developers Distributed under the MIT software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. Exercise the listtransactions APIThis test requires mocktime Simple send, 0 to 1: mine a block, confirmations sho...
1,003
en
0.802183
import warnings from importlib import import_module from django.conf import settings from pretalx.orga.signals import nav_event, nav_event_settings, nav_global SessionStore = import_module(settings.SESSION_ENGINE).SessionStore def collect_signal(signal, kwargs): result = [] for _, response in signal.send_r...
src/pretalx/orga/context_processors.py
2,528
Add data to all template contexts.
34
en
0.253858
#! /usr/bin/env python # coding=utf-8 #================================================================ # Copyright (C) 2018 * Ltd. All rights reserved. # # Editor : VIM # File name : evaluate.py # Author : YunYang1994 # Created date: 2018-12-20 11:58:21 # Description : compute mAP # #==========...
detection/yolov3/src/evaluate.py
5,248
! /usr/bin/env python coding=utf-8================================================================ Copyright (C) 2018 * Ltd. All rights reserved. Editor : VIM File name : evaluate.py Author : YunYang1994 Created date: 2018-12-20 11:58:21 Description : compute mAP=================================...
578
en
0.527705
''' For this exercise, you'll use what you've learned about the zip() function and combine two lists into a dictionary. These lists are actually extracted from a bigger dataset file of world development indicators from the World Bank. For pedagogical purposes, we have pre-processed this dataset into the lists that you...
10 - python-data-science-toolbox-part-2/case_study/1 - dictionaries for data science.py
704
For this exercise, you'll use what you've learned about the zip() function and combine two lists into a dictionary. These lists are actually extracted from a bigger dataset file of world development indicators from the World Bank. For pedagogical purposes, we have pre-processed this dataset into the lists that you'll ...
601
en
0.87913
# -*- coding: utf-8 -*- # file: data_utils.py # author: songyouwei <youwei0314@gmail.com> # Copyright (C) 2018. All Rights Reserved. import os import pickle import numpy as np import tqdm from findfile import find_file from google_drive_downloader.google_drive_downloader import GoogleDriveDownloader as gdd from torch...
pyabsa/core/tc/classic/__bert__/dataset_utils/data_utils_for_training.py
7,887
-*- coding: utf-8 -*- file: data_utils.py author: songyouwei <youwei0314@gmail.com> Copyright (C) 2018. All Rights Reserved. idx 0 and len(word2idx)+1 are all-zeros words not found in embedding index will be all-zeros.
218
en
0.690122
from typing import Any, Dict, Optional import lumos.numpy as lnp from lumos.models.base import StateSpaceModel, state_space_io from lumos.models.kinematics import TrackPosition2D from lumos.models.vehicles.simple_vehicle import SimpleVehicle # Combine the signals to create the names. TODO: can we make it more automa...
lumos/models/simple_vehicle_on_track.py
3,309
Combine the signals to create the names. TODO: can we make it more automatic? Pick out the vehicle inputs Pick out vehicle states Pick out vehicle params. NOT DONE! NOT EASY! Call Kinematics model Pick out states pick out inputs NOTE: this step is very custom, because the inputs come from vehicle model outputs Pick out...
418
en
0.853902
# -*- coding: utf-8 -*- import sys import os from sqlalchemy import Table from yaml import load,dump try: from yaml import CSafeLoader as SafeLoader except ImportError: from yaml import SafeLoader print("Using Python SafeLoader") distribution={'twosome':1,'bubble':2} effectcategory={} def importyaml(connection,...
tableloader/tableFunctions/dogmaEffects.py
3,060
-*- coding: utf-8 -*-
21
en
0.767281
# coding: utf-8 """ Mux Python - Copyright 2019 Mux Inc. NOTE: This class is auto generated. Do not edit the class manually. """ from __future__ import absolute_import import unittest import mux_python from mux_python.models.track import Track # noqa: E501 from mux_python.rest import ApiException class TestTra...
test/test_track.py
705
Track unit test stubs Test Track Mux Python - Copyright 2019 Mux Inc. NOTE: This class is auto generated. Do not edit the class manually. coding: utf-8 noqa: E501 FIXME: construct object with mandatory attributes with example values model = mux_python.models.track.Track() noqa: E501
288
en
0.676954
from typing import Any from sqlalchemy.ext.declarative import as_declarative, declared_attr @as_declarative() class Base: id: Any __name__: str # Generate __tablename__ automatically @declared_attr def __tablename__(cls) -> str: return cls.__name__.lower() def to_dict(self): ...
bali/db/declarative.py
450
Generate __tablename__ automatically
36
en
0.099263
"""The tests for the State vacuum Mqtt platform.""" from copy import deepcopy import json from homeassistant.components import mqtt, vacuum from homeassistant.components.mqtt import CONF_COMMAND_TOPIC, CONF_STATE_TOPIC from homeassistant.components.mqtt.discovery import async_start from homeassistant.components.mqtt.v...
tests/components/mqtt/test_state_vacuum.py
21,160
The tests for the State vacuum Mqtt platform. Change json_attributes_topic Verify we are no longer subscribing to the old topic Verify we are subscribing to the new topic all vacuums group is 1, unique id created is 1
219
en
0.857942
#-------------------------------------------------------------------------- # # Copyright (c) Microsoft Corporation. All rights reserved. # # The MIT License (MIT) # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the ""Software""), t...
sdk/core/azure-core/samples/test_example_sansio.py
5,473
-------------------------------------------------------------------------- Copyright (c) Microsoft Corporation. All rights reserved. The MIT License (MIT) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the S...
2,287
en
0.779431
#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function __metaclass__ = type # Copyright (c) 2020-2021, Red Hat # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # STARTREMOVE (downstream) DOCUMENTATION = r''' module: opens...
venv/lib/python3.8/site-packages/ansible_collections/community/okd/plugins/modules/openshift_process.py
8,164
!/usr/bin/python -*- coding: utf-8 -*- Copyright (c) 2020-2021, Red Hat GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) STARTREMOVE (downstream) ENDREMOVE (downstream) remove_aliases from kubernetes.core's common requires the argspec attribute. Ideally, it should read that thr...
370
en
0.737111
#!/usr/bin/env python """continue play youtube video""" import mac_youtube def _cli(): mac_youtube.play() if __name__ == "__main__": _cli()
mac_youtube/play.py
152
continue play youtube video !/usr/bin/env python
49
en
0.269627
# -*- encoding: utf-8 -*- import json import importlib import os import builtins from multiprocessing import Process from importlib.util import find_spec __all__=['run'] def run(): from utils.RedisHelper import RedisHelper _redis=RedisHelper() _redis.pubsub=_redis.conn.pubsub() _redi...
commands/router.py
2,424
-*- encoding: utf-8 -*-订阅消息 on manage.py -e local {'type': 'subscribe', 'pattern': None, 'channel': b'nlp_test_pub', 'data': 1} if "subscribe"!=sub_message['type'] or _redis.sub_name!=sub_message["channel"].decode('utf-8','ignore'): raise "sub error" 默认不会有错误 打印日志 控制必要的字段 暂时只进行单项任务 获取该任务唯一id 优化报错 os.environ['ui...
467
en
0.192906
# MIT License # # Copyright (c) 2018-2019 Tskit Developers # Copyright (c) 2015-2017 University of Oxford # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including with...
python/tskit/drawing.py
34,461
Text tree rendering where root nodes are at the left and time goes rightwards into the present. An SVG representation of a single tree. TODO should provide much more SVG structure which we document fully to that the SVG elements can be manipulated directly by the user. For example, every edge should be given an SVG ID...
5,106
en
0.820435
import pytest from shutil import copyfile from shutil import copytree import os from cli.postman2robot import run as postman2robot @pytest.fixture(scope="function") def collection(tmpdir, request): if request.param: test_name = request.param else: test_name = request.node.name filepath ...
test/test_cli_postman2robot.py
2,385
Given collection.json, generate: library.py Given collection.json, generate: library.py Given collection.json, generate: library.py Resolve paths Prepare env We work in temps dir
180
en
0.522675
textSpeakDictionary = { "rs" : "risos" , "tmb" : "também" } #imprime o dicionário inteiro print( "Dicionário =" , textSpeakDictionary ) #imprime apenas o conteúdo relacionado à chave "rs" print( "\nrs =" , textSpeakDictionary["rs"]) #texto que pede a entrada do usuário key = input("\nO que você gostari...
Traduzindo_Palavras.py
393
imprime o dicionário inteiroimprime apenas o conteúdo relacionado à chave "rs"texto que pede a entrada do usuário
113
pt
0.926288
#!/usr/bin/python # -*- coding: utf-8 -*- import time import vcgencmd from gpiozero import OutputDevice # IMPORTANT: maximum temperature is 85°C and cpu throttled at 80°C ON_THRESHOLD = 70 # (degrees Celsius) fan starts at this temperature OFF_THRESHOLD = 60 # (degrees Celsius) fan shuts down at this temperature SLE...
src/fancontroller.py
874
!/usr/bin/python -*- coding: utf-8 -*- IMPORTANT: maximum temperature is 85°C and cpu throttled at 80°C (degrees Celsius) fan starts at this temperature (degrees Celsius) fan shuts down at this temperature (seconds) how often the core temperature is checked (number) which GPIO pin is used to control the fan NOTE: fan.v...
343
en
0.812684
""" """ import snowmobile sn = snowmobile.connect(delay=True) sn.alive # > False type(sn.con) # > NoneType type(sn.cfg) # > snowmobile.core.configuration.Configuration str(sn.cfg) # > snowmobile.Configuration('snowmobile.toml') print(sn.cfg.location) # > /path/to/your/snowmobile.toml sn.cfg.connection.default...
docs/snippets/configuration.py
1,151
> False > NoneType > snowmobile.core.configuration.Configuration > snowmobile.Configuration('snowmobile.toml') > /path/to/your/snowmobile.toml > 'creds1' > snowmobile.core.connection.Snowmobile > snowmobile.core.configuration.Configuration > snowmobile.Configuration('snowmobile.toml') > snowflake.connector.connection.S...
576
en
0.332407
import os import sys import numpy as np import torch import pickle import logging log = logging.getLogger(__name__) logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO ) class Graph4D(): def __init__(self, num_envs=4096...
generate.py
6,605
Generates N square environments and trajectories ((observation, action) pairs) for each environment Params: envs (int): number of environments to generate steps (int): how many steps an agent initially takes in each environment env_size (tuple): size of environment (should be something like (4,4), (9,9), e...
1,705
en
0.746632
###################################################################################### #FSSNet: Fast Semantic Segmentation for Scene Perception #Paper-Link: https://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=8392426 ###################################################################################### import to...
model/FSSNet.py
11,913
FSSNet: Fast Semantic Segmentation for Scene PerceptionPaper-Link: https://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=8392426 NON_LINEARITY = { 'ReLU': nn.ReLU(inplace=True), 'PReLU': nn.PReLU(), 'ReLu6': nn.ReLU6(inplace=True) } Store parameters that are needed later Main branch - max pooling followed b...
1,733
en
0.763091
# -*- coding: utf-8 -*- # ***************************************************************************** # # 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/l...
setupext/build_ext.py
12,096
Override some behavior in extension building: 1. handle compiler flags for different compilers via a dictionary. 2. try to disable warning -Wstrict-prototypes is valid for C/ObjC but not for C++ indicate notices about features Run command. omit -Wstrict-prototypes from CFLAGS since its only valid for C code. -*- co...
1,712
en
0.809452
"""Policy compliance This checks that recipes are in accordance with policy (as far as it can be mechanically checked). """ import glob import os from . import LintCheck, ERROR, WARNING, INFO from bioconda_utils import utils class uses_vcs_url(LintCheck): """The recipe downloads source from a VCS Please b...
bioconda_utils/lint/check_policy.py
4,044
CRAN packages not depending on Bioconda should go to Conda-Forge This recipe builds a CRAN package and does not depend on packages from Bioconda. It should therefore be moved to Conda-Forge. The recipe folder and package name do not match. For clarity, the name of the folder the ``meta.yaml`` resides, in and the name...
2,036
en
0.89946
# Copyright (c) 2012 Rackspace Hosting # All Rights Reserved. # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # Copyright 2013 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License");...
nova/cells/messaging.py
86,027
Copyright (c) 2012 Rackspace Hosting All Rights Reserved. Copyright 2010 United States Government as represented by the Administrator of the National Aeronautics and Space Administration. All Rights Reserved. Copyright 2013 Red Hat, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not ...
5,927
en
0.915098
from os import getenv from typing import Optional, Dict from flask import Flask TestConfig = Optional[Dict[str, bool]] def create_app(test_config: TestConfig = None) -> Flask: """ App factory method to initialize the application with given configuration """ app: Flask = Flask(__name__) if test_config ...
my_hello_world_app/web_api/router.py
1,035
App factory method to initialize the application with given configuration DOCKER_IMAGE_TAG is passed in the app from Dockerfile as ARG. It should be setup in docker build task.. It is used in .gitlab-ci.yaml to pass the hash of the latest commit as docker image tag. E.g. docker build --build-arg docker_image_tag="my-v...
423
en
0.711238
# Copyright David Abrahams 2004. Distributed under the Boost # Software License, Version 1.0. (See accompanying # file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) # This regression test checks that call_method<T>(...) where T is a # non-reference, non-pointer type that happens to be held inside the...
boost/libs/python/test/ben_scott1.py
555
Copyright David Abrahams 2004. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) This regression test checks that call_method<T>(...) where T is a non-reference, non-pointer type that happens to be held inside the result ob...
364
en
0.854649
from PPPForgivenessSDK.client import Client # to run file 'delete_forgiveness_request.py', use valid token and a slug associated with a valid forgiveness request client = Client( access_token='{{YOUR_TOKEN_HERE}}', vendor_key='{{YOUR_VENDOR_KEY}}', environment='sandbox' ) forgiveness_api = client.forgiven...
examples/delete_forgiveness_request.py
560
to run file 'delete_forgiveness_request.py', use valid token and a slug associated with a valid forgiveness request delete forgiveness request
142
en
0.834337
from vision_backend.models import Classifier def deploy_request_json_as_strings(job): """ Get a string list representing a deploy job's request JSON. """ request_json = job.request_json classifier_id = request_json['classifier_id'] try: classifier = Classifier.objects.get(pk=classifier...
project/vision_backend_api/utils.py
719
Get a string list representing a deploy job's request JSON.
59
en
0.61229
#!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'scrapmart.settings') try: from django.core.management import execute_from_command_line ...
manage.py
687
Run administrative tasks. Django's command-line utility for administrative tasks. !/usr/bin/env python
103
en
0.725633
#!/usr/bin/python # -*- encoding: utf-8 -*- from logger import setup_logger from models.model_stages import BiSeNet from cityscapes import CityScapes from loss.loss import OhemCELoss from loss.detail_loss import DetailAggregateLoss from evaluation import MscEvalV0 from optimizer_loss import Optimizer import torch impo...
train.py
14,000
!/usr/bin/python -*- encoding: utf-8 -*- print(save_pth_path) print(osp.exists(save_pth_path)) if not osp.exists(save_pth_path) and dist.get_rank()==0: dataset exit(0) model optimizer train loop if dist.get_rank()==0: print('use_boundary_2') if dist.get_rank()==0: print('use_boundary_4') if dist.get_rank()==0:...
872
en
0.341477
# Copyright 2019 FairwindsOps Inc # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writ...
reckoner/yaml/handler.py
2,037
Yaml handler class for loading, and dumping yaml consistently Copyright 2019 FairwindsOps 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 r...
617
en
0.864847
from pathlib import Path from typing import Union import pandas as pd from .convention import COLUMN_NAMES from .table_map import table_map_read def open(table_file: str, table_map_file: str = None) -> pd.DataFrame: """ Opens a dynamo table file, returning a DynamoTable object :param table_file: :re...
dynamotable/dynamotable.py
4,067
Writes a dynamo table file from a pandas DataFrame :param dataframe: pandas dataframe with headings matching the name from the dynamo table convention :param filename: file in which to save data from dataframe, should end in .tbl :return: Opens a dynamo table file, returning a DynamoTable object :param table_file: :ret...
1,306
en
0.62705
# Copyright 2019 Atalaya Tech, 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, ...
bentoml/yatai/repository/__init__.py
1,452
Creates a repository based on a provided type and parameters Copyright 2019 Atalaya Tech, 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 requ...
614
en
0.842506
#!/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. from parlai.core.worlds import create_task from parlai.agents.fixed_response.fixed_response import FixedResponseAgent fr...
parlai/tasks/convai2/worlds.py
3,751
!/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. Create ConvAI2 data so we can assign personas. Find a new episode
256
en
0.750211
#! /usr/bin/env python3 # This was forked from https://github.com/rustyrussell/lightning-payencode/tree/acc16ec13a3fa1dc16c07af6ec67c261bd8aff23 import re import time from hashlib import sha256 from binascii import hexlify from decimal import Decimal from typing import Optional, TYPE_CHECKING, Type import random impo...
electrum/lnaddr.py
18,221
Encode all supported fallback addresses. Given an amount in bitcoin, shorten it Ensures 'bits' have min number of leading zeroes. Assumes 'bits' is big-endian, and that it needs to be encoded in 5 bit blocks. Given a shortened amount, convert it into a decimal ! /usr/bin/env python3 This was forked from...
3,246
en
0.820808
from time import sleep from enos.message.downstream.tsl.MeasurepointGetReply import MeasurepointGetReply from enos.message.downstream.tsl.MeasurepointGetCommand import MeasurepointGetCommand from enos.message.downstream.tsl.MeasurepointSetReply import MeasurepointSetReply from enos.core.MqttClient import MqttClient...
enos/sample/CommandSample.py
2,411
message callback, handle the received downstream message and implement your logic :param arrived_message: the arrived msg instance , it may instanceof class <BaseCommand> or <BaseResponse> :param arg_list: the topic args extract from the arrived topic , including productKey , deviceKey ,etc :return: the msg you want t...
545
en
0.78962
# !/usr/bin/env python # -*- coding: utf-8 -*- # # Project: Azimuthal integration # https://github.com/silx-kit/pyFAI # # Copyright (C) European Synchrotron Radiation Facility, Grenoble, France # # Principal author: Jérôme Kieffer (Jerome.Kieffer@ESRF.eu) # # Permission is hereby granted, fre...
autoprocess/utils/ellipse.py
3,295
Fit an inspired from http://nicky.vanforeest.com/misc/fitEllipse/fitEllipse.html :param pty: point coordinates in the slow dimension (y) :param ptx: point coordinates in the fast dimension (x) This modules contains a function to fit without refinement an ellipse on a set of points .... !/usr/bin/env python -*- c...
1,579
en
0.806618
""" Slixmpp: The Slick XMPP Library Copyright (C) 2010 Nathanael C. Fritz This file is part of Slixmpp. See the file LICENSE for copying permission. """ from slixmpp.plugins.base import register_plugin from slixmpp.plugins.xep_0199.stanza import Ping from slixmpp.plugins.xep_0199.ping import XEP_0199...
slixmpp/plugins/xep_0199/__init__.py
349
Slixmpp: The Slick XMPP Library Copyright (C) 2010 Nathanael C. Fritz This file is part of Slixmpp. See the file LICENSE for copying permission.
145
en
0.718611
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
qiskit/circuit/library/standard_gates/rx.py
6,665
Controlled-RX gate. **Circuit symbol:** .. parsed-literal:: q_0: ────■──── ┌───┴───┐ q_1: ┤ Rx(ϴ) ├ └───────┘ **Matrix representation:** .. math:: \newcommand{\th}{\frac{\theta}{2}} CRX(\lambda)\ q_0, q_1 = I \otimes |0\rangle\langle 0| + RX(\theta) \otimes |1\rangle\lan...
3,032
en
0.589394