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
#!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'hackcrisis.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise Imp...
manage.py
630
Django's command-line utility for administrative tasks. !/usr/bin/env python
77
en
0.656913
# This script fetches Atelier 801 translation file and adds the required IDs into our own translation files import sys from urllib.request import urlopen import zlib from string import Template import json if len(sys.argv) < 2: print("Please pass in lang code for first arguement") exit() lang = sys.argv[1] url = 'h...
i18n/_tfm_trans_to_skilldata.py
2,522
This script fetches Atelier 801 translation file and adds the required IDs into our own translation files Fetch file Parse file Use data to do the actual thing this tool is for outfile.write(i18nToWrite)
203
en
0.747974
#!/usr/bin/env python __author__ = ('Duy Tin Truong (duytin.truong@unitn.it), ' 'Aitor Blanco Miguez (aitor.blancomiguez@unitn.it)') __version__ = '3.0' __date__ = '21 Feb 2020' import argparse as ap import dendropy from io import StringIO import re from collections import defaultdict import matplotli...
metaphlan/utils/plot_tree_graphlan.py
6,117
!/usr/bin/env pythonofile.write('clade_separation\t0\n')ofile.write('clade_separation\t0.15\n')ofile.write('branch_thickness\t1.25\n') legend remove intermedate nodes colorize leaf nodes
186
en
0.220224
from django.db import models from django.urls import reverse import uuid # Required for unique book instances class Genre(models.Model): """ Model representing a book genre (e.g. Science Fiction, Non Fiction). """ name = models.CharField(max_length=200, help_text="Enter a book genre (e.g. Sc...
src/locallibrary/catalog/models.py
3,786
Model representing an author. Model representing a book (but not a specific copy of a book). Model representing a specific copy of a book (i.e. that can be borrowed from the library). Model representing a book genre (e.g. Science Fiction, Non Fiction). Model representing a Language (e.g. Russian, English etc.) String f...
1,047
en
0.896467
# -------------- import pandas as pd import numpy as np from sklearn.cross_validation import train_test_split # code starts here df = pd.read_csv(path) df.head() X = df[['ages','num_reviews','piece_count','play_star_rating','review_difficulty','star_rating','theme_name','val_star_rating','country']] y = df['list_price'...
Making-first-prediction-using-linear-regression/code.py
1,541
-------------- code starts here code ends here -------------- code starts here cols= list(X_train.columns.values) code ends here -------------- Code starts here Code ends here -------------- Code starts here Code ends here -------------- Code starts here Code ends here
270
en
0.478017
from enum import IntEnum from typing import Dict, Union, Callable, Any from cereal import log, car import cereal.messaging as messaging from common.realtime import DT_CTRL from selfdrive.config import Conversions as CV from selfdrive.locationd.calibrationd import MIN_SPEED_FILTER AlertSize = log.ControlsState.AlertSi...
selfdrive/controls/lib/events.py
34,085
Alert priorities Event types get event name from enum ********** alert callback functions ********** ********** events with no alerts ********** ********** events only containing alerts displayed in all states ********** Car is recognized, but marked as dashcam only Car is not recognized openpilot uses the version stri...
4,923
en
0.936431
import numpy as np import h5py import argparse import imageio import tqdm import os from glob import glob def main(args): """Main function to parse in Nuclei Dataset from Kaggle and store as HDF5 Parameters ---------- args: ArgumentParser() input_dir: str directory of ...
process_data/nuclei_create_hdf5.py
2,173
Main function to parse in Nuclei Dataset from Kaggle and store as HDF5 Parameters ---------- args: ArgumentParser() input_dir: str directory of the Nuclei data output_dir: str path to the HDF5 output directory create hdf5 get all data directory TODO only use majority size...
476
en
0.455065
#11_Duplicate in an array N+1 integer """ Given an array of n elements that contains elements from 0 to n-1, with any of these numbers appearing any number of times. Find these repeating numbers in O(n) and using only constant memory space. Example: Input : n = 7 and array[] = {1, 2, 3, 6, 3, 6, 1} Output...
11_Duplicate in an array N+1 integer.py
1,414
Given an array of n elements that contains elements from 0 to n-1, with any of these numbers appearing any number of times. Find these repeating numbers in O(n) and using only constant memory space. Example: Input : n = 7 and array[] = {1, 2, 3, 6, 3, 6, 1} Output: 1, 3, 6 Explanation: The numbers 1 , 3 and 6 appea...
508
en
0.8397
# Copyright (c) OpenMMLab. All rights reserved. import torch from torch.nn.parallel.distributed import (DistributedDataParallel, _find_tensors) from mmcv import print_log from mmcv.utils import TORCH_VERSION, digit_version from .scatter_gather import scatter_kwargs class MM...
mmcv/parallel/distributed.py
5,917
The DDP module that supports DataContainer. MMDDP has two main differences with PyTorch DDP: - It supports a custom type :class:`DataContainer` which allows more flexible control of input data. - It implement two APIs ``train_step()`` and ``val_step()``. train_step() API for module wrapped by DistributedDataParalle...
1,140
en
0.743785
import datetime import json import logging import re import time from google.appengine.ext import db # from google.appengine.ext.db import djangoforms from google.appengine.api import mail from google.appengine.api import memcache from google.appengine.api import urlfetch from google.appengine.api import taskqueue fro...
models.py
51,306
Describes a user for whitelisting. Container for a feature. Describes subscribers of a web platform feature. Container for a histogram. Async notifies subscribers of new features and property changes to features by posting to a task queue. Adds the user as the Blink component owner. Adds the user to the list of Blink c...
5,201
en
0.790135
# -*- coding: utf-8 -*- import time from pymongo import MongoClient from config import MONGO_CONFIG def get_current_time(format_str: str = '%Y-%m-%d %H:%M:%S'): """ ่Žทๅ–ๅฝ“ๅ‰ๆ—ถ้—ด๏ผŒ้ป˜่ฎคไธบ 2020-01-01 00:00:00 ๆ ผๅผ :param format_str: ๆ ผๅผ :return: """ return time.strftime(format_str, time.localtime()) class ...
src/sogou_wechat/mongoDB.py
2,862
ๅˆๅง‹ๅŒ– ๅˆๅง‹ๅŒ– mongo db ่Žทๅ–ๅฝ“ๅ‰ๆ—ถ้—ด๏ผŒ้ป˜่ฎคไธบ 2020-01-01 00:00:00 ๆ ผๅผ :param format_str: ๆ ผๅผ :return: ไฟๅญ˜ๆœ็‹—ๆœ็ดขไฟกๆฏ :param results: ็ป“ๆžœๆ•ฐ็ป„ ๆ›ดๆ–ฐๆœ็‹—ๅพฎไฟก็™ปๅฝ• cookie ไฟกๆฏ :param username: :param cookie: :return: -*- coding: utf-8 -*- self.task_db = self.mongo['sogou_tast'] ๆ’ๅ…ฅๆ–ฐๆ•ฐๆฎ ๆ›ดๆ–ฐๅŽŸๆœ‰ๆ•ฐๆฎ ๆ’ๅ…ฅๆ–ฐๆ•ฐๆฎ ๆ›ดๆ–ฐๅŽŸๆœ‰ๆ•ฐๆฎ
261
zh
0.789484
# -*- coding: utf-8 -*- # PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN: # https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code from ccxt.base.exchange import Exchange from ccxt.base.errors import ExchangeError from ccxt.base.errors import AuthenticationError from cc...
python/ccxt/bitso.py
40,287
-*- coding: utf-8 -*- PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN: https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.mdhow-to-contribute-code Mexico 30 requests per minute Invalid Nonce or Invalid Credentials Cannot perform request - nonce must be higher than 1520307203724237 {"success":fa...
9,947
en
0.602412
# list all object store access policies res = client.get_object_store_access_policies() print(res) if type(res) == pypureclient.responses.ValidResponse: print(list(res.items)) # Valid fields: continuation_token, filter, ids, limit, names, offset, sort # See section "Common Fields" for examples
docs/source/examples/FB2.0/get_object_store_access_policies.py
299
list all object store access policies Valid fields: continuation_token, filter, ids, limit, names, offset, sort See section "Common Fields" for examples
152
en
0.517476
import logging import urllib.parse from typing import Any, Dict, Optional, Type, Union from globus_sdk import config, exc, utils from globus_sdk.authorizers import GlobusAuthorizer from globus_sdk.paging import PaginatorTable from globus_sdk.response import GlobusHTTPResponse from globus_sdk.scopes import ScopeBuilder...
src/globus_sdk/client.py
10,804
Abstract base class for clients with error handling for Globus APIs. :param authorizer: A ``GlobusAuthorizer`` which will generate Authorization headers :type authorizer: :class:`GlobusAuthorizer\ <globus_sdk.authorizers.base.GlobusAuthorizer>` :param app_name: Optional "nice name" for the application. Has no bear...
3,998
en
0.752215
#!/Users/drpaneas/Virtualenvs/linuxed/bin/python2.7 # $Id: rst2pseudoxml.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ A minimal front end to the Docutils Publisher, producing pseudo-XML. """ try: import loca...
bin/rst2pseudoxml.py
634
A minimal front end to the Docutils Publisher, producing pseudo-XML. !/Users/drpaneas/Virtualenvs/linuxed/bin/python2.7 $Id: rst2pseudoxml.py 4564 2006-05-21 20:44:42Z wiemann $ Author: David Goodger <goodger@python.org> Copyright: This module has been placed in the public domain.
282
en
0.601946
"""Identifiers for objects in Robustness Gym.""" from __future__ import annotations import ast import json from typing import Any, Callable, List, Union # from robustnessgym.core.tools import persistent_hash class Identifier: """Class for creating identifiers for objects in Robustness Gym.""" def __init__(...
robustnessgym/core/identifier.py
4,719
Class for creating identifiers for objects in Robustness Gym. Call the identifier with additional parameters to return a new identifier. https://stackoverflow.com/questions/49723047/parsing-a-string-as-a- python-argument-list. Add a parameter to the identifier. Dump the identifier to JSON. Index associated with the ide...
913
en
0.453536
# 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 RAbind(RPackage): """ Combine Multidimensional Arrays. Combine multidimensional a...
var/spack/repos/builtin/packages/r-abind/package.py
848
Combine Multidimensional Arrays. Combine multidimensional arrays into a single array. This is a generalization of 'cbind' and 'rbind'. Works with vectors, matrices, and higher-dimensional arrays. Also provides functions 'adrop', 'asub', and 'afill' for manipulating, extracting and replacing data in arrays. Copyright...
499
en
0.776947
import numpy as np import torch def get_sinusoid_encoding_table(n_position, d_hid, padding_idx=None): ''' Sinusoid position encoding table ''' def cal_angle(position, hid_idx): return position / np.power(10000, 2 * (hid_idx // 2) / d_hid) def get_posi_angle_vec(position): return [cal_ang...
src/onqg/utils/sinusoid.py
768
Sinusoid position encoding table dim 2i dim 2i+1 zero vector for padding dimension
85
en
0.144242
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
official/vision/image_classification/common.py
20,266
Callback to update learning rate on every batch (not epoch boundaries). N.B. Only support Keras optimizers, not TF optimizers. Attributes: schedule: a function that takes an epoch index and a batch index as input (both integer, indexed from 0) and returns a new learning rate as output (float). Pie...
4,712
en
0.805612
import collections import itertools from trie_class import Trie import sys import timeit def load_dataset(filename): dataset = [sorted(int(n) for n in i.strip().split()) for i in open(filename).readlines()] size = len(dataset) print('Size of the Dataset : ', size) total_len = 0 ...
Frequent Pattern Mining/apriori.py
4,036
print(dataset) print('1 - item func : min sup :', min_sup) print(L1) Input : L_k (k : itemset size) Self Join Step Removing Duplicates Prune Step Returns list of lists [L_k + 1] print('Apriori - min sup :', min_sup) print('L-1 :', L1) Creating list of 1-itemset(list itself) print('L1 :', L1) print('Levels :', levels) p...
587
en
0.091484
"""Spamming Module {i}spam <no of msgs> <msg> Note:- Don't use to much""" # Copyright (C) 2019 The Raphielscape Company LLC. # # Licensed under the Raphielscape Public License, Version 1.b (the "License"); # you may not use this file except in compliance with the License. # from asyncio import wait fr...
plugins/spam.py
919
Spamming Module {i}spam <no of msgs> <msg> Note:- Don't use to much Copyright (C) 2019 The Raphielscape Company LLC. Licensed under the Raphielscape Public License, Version 1.b (the "License"); you may not use this file except in compliance with the License.
261
en
0.863271
# stdlib import json from typing import List from typing import NoReturn from typing import Optional # third party from fastapi import APIRouter from fastapi import Depends from fastapi import File from fastapi import Form from fastapi import UploadFile from loguru import logger from starlette import status from starl...
packages/grid/backend/grid/api/users/routes.py
4,463
stdlib third party grid absolute relative TODO: Syft should return the newly created user and the response model should be User. type: ignore
141
en
0.703342
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If ex...
docs/source/conf.py
2,190
Configuration file for the Sphinx documentation builder. This file only contains a selection of the most common options. For a full list see the documentation: https://www.sphinx-doc.org/en/master/usage/configuration.html -- Path setup -------------------------------------------------------------- If extensions (or mod...
1,614
en
0.708488
from pathlib import Path from datetime import datetime, timedelta from src.settings import envs from airflow import DAG from airflow.models import Variable from airflow.operators.python_operator import PythonOperator from airflow.utils.dates import days_ago from airflow.hooks.postgres_hook import PostgresHook import lo...
src/airflow_dags/dags/btb/house_keeping.py
2,740
Setting up module from __file__ as the interpreter sets __name__ as __main__ when the source file is executed as main program these args will get passed on to each operator you can override them on a per-task basis during operator initialization
245
en
0.95202
from abc import ABC from asyncio import Lock as AsyncLock from collections import ChainMap, OrderedDict from dataclasses import dataclass, field from datetime import timedelta from functools import partial, wraps from hashlib import sha256 import inspect from pathlib import Path import pickle from sqlite3 import connec...
atools/_memoize_decorator.py
25,461
Decorates a function call and caches return value for given inputs. - If `db_path` is provided, memos will persist on disk and reloaded during initialization. - If `duration` is provided, memos will only be valid for given `duration`. - If `keygen` is provided, memo hash keys will be created with given `keygen`. - If `...
8,643
en
0.751141
import os import math import logging from pyaxe import config as config_util from pyaxe.axeerror import aXeError # make sure there is a logger _log = logging.getLogger(__name__) class ConfigList: """Configuration File Object""" def __init__(self, keylist, header=None): """ Initializes the Con...
pyaxe/axesrc/configfile.py
46,325
Error for unknown beam Error for wrong lengt in KeywordList Error for missing keyword Base class for exceptions in this module Header class for the configuration file Class for a keyword in a configuration file This keyword class is a light, but yet versatile and important class to strore a keyword entry in a configu...
20,156
en
0.644144
# from imports import * # import random # class Docs(commands.Cog): # def __init__(self, bot): # self.bot = bot # self.bot.loop.create_task(self.__ainit__()) # async def __ainit__(self): # await self.bot.wait_until_ready() # self.scraper = AsyncScraper(session = self.bot.session) # async def r...
cogs/docs.py
2,196
from imports import * import random class Docs(commands.Cog): def __init__(self, bot): self.bot = bot self.bot.loop.create_task(self.__ainit__()) async def __ainit__(self): await self.bot.wait_until_ready() self.scraper = AsyncScraper(session = self.bot.session) async def rtfm_lookup(self, program...
2,074
en
0.461124
from django.conf.urls import url, include import binder.router # noqa import binder.websocket # noqa import binder.views # noqa import binder.history # noqa import binder.models # noqa import binder.plugins.token_auth.views # noqa from binder.plugins.views.multi_request import multi_request_view from .views import ani...
tests/testapp/urls.py
951
noqa noqa noqa noqa noqa noqa noqa url(r'^user/$', custom.user, name='user'), FIXME: Hmm, this is a bit hackish. Especially here. But where else?
145
en
0.525624
from .brand import BrandDataset, Brand from .vehicle_id import VehicleIDDataset from .comp_cars import CompCarsDataset # from .veri import VeriDataset from .box_cars import BoxCars116kDataset # from .vric import VRICDataset from .cars196 import Cars196Dataset
experiments/brand/dataset/__init__.py
259
from .veri import VeriDataset from .vric import VRICDataset
59
en
0.338389
"""Certbot constants.""" import os import logging from acme import challenges SETUPTOOLS_PLUGINS_ENTRY_POINT = "certbot.plugins" """Setuptools entry point group name for plugins.""" OLD_SETUPTOOLS_PLUGINS_ENTRY_POINT = "letsencrypt.plugins" """Plugins Setuptools entry point before rename.""" CLI_DEFAULTS = dict( ...
certbot/constants.py
3,433
Certbot constants. http://freedesktop.org/wiki/Software/xdg-user-dirs/ The set of reasons for revoking a certificate is defined in RFC 5280 in section 5.3.1. The reasons that users are allowed to submit are restricted to those accepted by the ACME server implementation. They are listed in `letsencrypt.boulder.revocat...
412
en
0.875103
# Copyright 2021 Canonical Ltd. # See LICENSE file for licensing details. from pathlib import Path from subprocess import check_output from time import sleep import pytest import yaml from selenium import webdriver from selenium.common.exceptions import JavascriptException, WebDriverException from selenium.webdriver....
tests/integration/test_charm.py
5,177
Workaround for web components breaking querySelector. Because someone thought it was a good idea to just yeet the moral equivalent of iframes everywhere over a single page ๐Ÿคฆ Shadow DOM was a terrible idea and everyone involved should feel professionally ashamed of themselves. Every problem it tried to solved could a...
801
en
0.938021
# Copyright (c) 2017 Sofia Ira Ktena <ira.ktena@imperial.ac.uk> # # 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 use, copy, ...
lib/abide_utils.py
11,220
subject_list : list of short subject IDs in string format atlas_name : the atlas based on which the timeseries are generated e.g. aal, cc200 kind : the kind of correlation used to estimate the matrices, i.e. returns: connectivity : list of square connectivity matrices, one for each subject in sub...
4,229
en
0.74114
from typing import List import numpy as np def mask_nan(arrays: List[np.ndarray]) -> List[np.ndarray]: """ Drop indices from equal-sized arrays if the element at that index is NaN in any of the input arrays. Parameters ---------- arrays : List[np.ndarray] list of ndarrays containing ...
jburt/mask.py
1,058
Drop indices from equal-sized arrays if the element at that index is NaN in any of the input arrays. Parameters ---------- arrays : List[np.ndarray] list of ndarrays containing NaNs, to be masked Returns ------- List[np.ndarray] masked arrays (free of NaNs) Notes ----- This function find the indices where on...
622
en
0.483066
# Copyright 2016 Google Inc. 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 applicable law or ...
test/lib/oauth2client/_pure_python_crypt.py
6,370
Signs messages with a private key. Args: pkey: rsa.key.PrivateKey (or equiv), The private key to sign with. Verifies the signature on a message. Args: pubkey: rsa.key.PublicKey (or equiv), The public key to verify with. Converts an iterable of 1's and 0's to bytes. Combines the list 8 at a time, treating eac...
2,604
en
0.797836
def findDecision(obj): #obj[0]: Passanger, obj[1]: Coupon, obj[2]: Education, obj[3]: Occupation, obj[4]: Restaurant20to50, obj[5]: Distance # {"feature": "Passanger", "instances": 34, "metric_value": 0.9774, "depth": 1} if obj[0]<=1: # {"feature": "Restaurant20to50", "instances": 22, "metric_value": 0.7732, "depth...
duke-cs671-fall21-coupon-recommendation/outputs/rules/RF/6_features/numtrees_30/rule_0.py
2,105
obj[0]: Passanger, obj[1]: Coupon, obj[2]: Education, obj[3]: Occupation, obj[4]: Restaurant20to50, obj[5]: Distance {"feature": "Passanger", "instances": 34, "metric_value": 0.9774, "depth": 1} {"feature": "Restaurant20to50", "instances": 22, "metric_value": 0.7732, "depth": 2} {"feature": "Education", "instances": 21...
1,048
en
0.545905
#!/usr/bin/env python from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from yolov2_ros.srv import * import rospy from copy import deepcopy from core import YOLO from vision_msgs.msg import Detection2DArray, Detection2D, BoundingBox2D, ObjectHypothe...
scripts/yolo_server.py
4,391
!/usr/bin/env python Either 'tiny_yolo', full_yolo, 'mobile_net, 'squeeze_net', or 'inception3' Weights directory DO NOT change this. 416 is default for YOLO. Eg: ['trafficcone', 'person', 'dog'] Max number of detections The anchors to use. Use the anchor generator and copy these into the config. Path to the weights.h5...
419
en
0.495968
#!/usr/bin/env python3 # Copyright (c) 2018 The Bitcoin Core developers # Copyright (c) 2017 The Raven Core developers # Copyright (c) 2018 The Rito Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test compact bl...
test/functional/p2p_compactblocks.py
43,952
Sends a message to the node and wait for disconnect. This is used when we want to send a message into the node that we expect will get us disconnected, eg an invalid block. Test compact blocks (BIP 152). Version 1 compact blocks are pre-segwit (txids) Version 2 compact blocks are post-segwit (wtxids) !/usr/bin/env p...
7,828
en
0.910607
import logging import io from homeassistant.core import callback from homeassistant.components.ais_dom import ais_global from homeassistant.const import EVENT_HOMEASSISTANT_START from homeassistant.components.camera import Camera from homeassistant.helpers.event import async_track_state_change from datetime import time...
homeassistant/components/ais_qrcode/camera.py
2,581
Representation of an QRCode image. Initialize the QRCode entity. Process the image. Return the name of the image processor. Update template on startup. Handle device state changes. Set up the QRCode image platform. Update the recording state periodically. Turn on camera.
271
en
0.724557
from datetime import datetime import logging import os import subprocess import sys from argparse import Namespace logging.getLogger("transformers").setLevel(logging.WARNING) import click import torch from luke.utils.model_utils import ModelArchive from zero.utils.experiment_logger import commet_logger_args, CometL...
zero/cli.py
4,131
https://github.com/tensorflow/tensorflow/issues/27045issuecomment-519642980 NOTE: ctx.obj is documented here: http://click.palletsprojects.com/en/7.x/api/click.Context.obj
171
en
0.548465
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('api', '0026_event_image'), ] operations = [ migrations.CreateModel( name='EventParticipation', field...
api/migrations/0027_auto_20150227_2321.py
1,427
-*- coding: utf-8 -*-
21
en
0.767281
# import the definition of the steps and input files: from Configuration.PyReleaseValidation.relval_steps import * # here only define the workflows as a combination of the steps defined above: workflows = Matrix() # each workflow defines a name and a list of steps to be done. # if no explicit name/label given for ...
Configuration/PyReleaseValidation/python/relval_2017.py
3,030
import the definition of the steps and input files: here only define the workflows as a combination of the steps defined above: each workflow defines a name and a list of steps to be done. if no explicit name/label given for the workflow (first arg), the name of step1 will be usedjust define all of themWFs to run in I...
1,826
en
0.54541
import MPS_class as MPS import MPO_class as MPO from ncon import ncon import numpy as np from scipy.linalg import expm #%% def TEBD_evo(MPS_,Lx,Ly,J=1,epsilon=0.1,etrunc=0,chiMAX=256,chiMAXswap=256,info=True): L = Lx*Ly config = np.arange(0,L).reshape(Lx,Ly) theta = (np.pi+2*epsilon) flip_op = np.e...
tebd_floquet.py
8,295
%% If they are nearest neighbours If they are nearest neighbours%%%%%%%%
72
en
0.982266
""" link: https://leetcode-cn.com/problems/smallest-rectangle-enclosing-black-pixels problem: ็ป™ๅฎš 0, 1 ็Ÿฉ้˜ต๏ผŒไปฅๅŠไธ€ไธช็Ÿฉ้˜ตไธญไธบ 1 ็š„็‚นๅๆ ‡๏ผŒๆฑ‚ๅŒ…ๅซ็Ÿฉ้˜ตไธญๆ‰€ๆœ‰็š„1็š„ๆœ€ๅฐ็Ÿฉๅฝข้ข็งฏ solution: ๆšดๆœใ€‚ๅฟฝ็•ฅๅๆ ‡๏ผŒ็›ดๆŽฅ้ๅކๆ‰€ๆœ‰่Š‚็‚น๏ผŒๆ‰พๅˆฐไธŠไธ‹ๅทฆๅณๅ››ไธช่พน็•Œ็‚น๏ผŒๆ—ถ้—ดO(nm)ใ€‚ solution-fix: ไบŒๅˆ†ใ€‚ๅฐ†x่ฝดๆŠ•ๅฝฑๅˆฐy่ฝด๏ผŒy่ฝดๆŠ•ๅฝฑๅˆฐx่ฝด๏ผŒๅฝขๆˆไธคไธชไธ€็ปดๆ•ฐ็ป„ใ€‚ๆ˜พ็„ถๆ•ฐ็ป„ๅฝขๅฆ‚ไธ‹ๅ›พใ€‚่€Œ x, y ๅๆ ‡ไธบ็•Œ๏ผŒไธคไพงๅ„ไธบ้žไธฅๆ ผ้€’ๅขžๅ’Œ้€’ๅ‡ 1: +------+ 0: ----...
leetcode/302.py
2,601
link: https://leetcode-cn.com/problems/smallest-rectangle-enclosing-black-pixels problem: ็ป™ๅฎš 0, 1 ็Ÿฉ้˜ต๏ผŒไปฅๅŠไธ€ไธช็Ÿฉ้˜ตไธญไธบ 1 ็š„็‚นๅๆ ‡๏ผŒๆฑ‚ๅŒ…ๅซ็Ÿฉ้˜ตไธญๆ‰€ๆœ‰็š„1็š„ๆœ€ๅฐ็Ÿฉๅฝข้ข็งฏ solution: ๆšดๆœใ€‚ๅฟฝ็•ฅๅๆ ‡๏ผŒ็›ดๆŽฅ้ๅކๆ‰€ๆœ‰่Š‚็‚น๏ผŒๆ‰พๅˆฐไธŠไธ‹ๅทฆๅณๅ››ไธช่พน็•Œ็‚น๏ผŒๆ—ถ้—ดO(nm)ใ€‚ solution-fix: ไบŒๅˆ†ใ€‚ๅฐ†x่ฝดๆŠ•ๅฝฑๅˆฐy่ฝด๏ผŒy่ฝดๆŠ•ๅฝฑๅˆฐx่ฝด๏ผŒๅฝขๆˆไธคไธชไธ€็ปดๆ•ฐ็ป„ใ€‚ๆ˜พ็„ถๆ•ฐ็ป„ๅฝขๅฆ‚ไธ‹ๅ›พใ€‚่€Œ x, y ๅๆ ‡ไธบ็•Œ๏ผŒไธคไพงๅ„ไธบ้žไธฅๆ ผ้€’ๅขžๅ’Œ้€’ๅ‡ 1: +------+ 0: -----+ ...
383
zh
0.722328
#!/usr/bin/env python # # Copyright (c) 2016, The OpenThread Authors. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright # ...
tests/scripts/thread-cert/Cert_5_3_03_AddressQuery.py
7,962
!/usr/bin/env python Copyright (c) 2016, The OpenThread Authors. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this lis...
2,573
en
0.87048
import re from haystack.inputs import Exact, Clean, BaseInput from api.helpers.parse_helper import has_balanced_parentheses, matched_parens class ElasticSearchExtendedAutoQuery(BaseInput): """ A convenience class that handles common user queries. In addition to cleaning all tokens, it handles double qu...
compass-api/G4SE/api/helpers/input.py
1,932
A convenience class that handles common user queries. In addition to cleaning all tokens, it handles double quote bits as exact matches & terms with '-' in front as NOT queries. Remove parens if they are not balanced We have something that's not an exact match but may have more than on word in it.
301
en
0.96914
"""Mark channels in an existing BIDS dataset as "bad". example usage: $ mne_bids mark_bad_channels --ch_name="MEG 0112" --description="noisy" \ --ch_name="MEG 0131" --description="flat" \ --subject_id=01 --task=experiment --session=test \ ...
mne_bids/commands/mne_bids_mark_bad_channels.py
4,940
Run the mark_bad_channels command. Mark channels in an existing BIDS dataset as "bad". example usage: $ mne_bids mark_bad_channels --ch_name="MEG 0112" --description="noisy" --ch_name="MEG 0131" --description="flat" --subject_id=01 --task=experiment --session=t...
560
en
0.426959
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys import json import os from pymisp import ExpandedPyMISP from settings import url, key, ssl, outputdir, filters, valid_attribute_distribution_levels try: from settings import with_distribution except ImportError: with_distribution = False try: from ...
examples/feed-generator/generate.py
3,206
!/usr/bin/env python3 -*- coding: utf-8 -*- If we have an old settings.py file then this variable won't exist
109
en
0.793859
#!/usr/bin/env python3 from hopla.hoplalib.user.usermodels import HabiticaUser class TestHabiticaUser: def test_get_stats(self): user_test_stat_values = { "buffs": { "str": 50, "int": 50, "per": 3206, "con": 50, "stealth": 0, "streaks": False, "snowball": False...
src/tests/hoplalib/user/test_usermodels.py
3,780
!/usr/bin/env python3
21
fr
0.448822
import os from celery import Celery from django.conf import settings # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myshop.settings') app = Celery('myshop') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: set...
myshop/celery.py
343
set the default Django settings module for the 'celery' program.
64
en
0.157211
#!/usr/bin/env python # -*- coding: utf-8 -*- """ ๅธๅฎ‰ๆŽจ่็ : ่ฟ”ไฝฃ10% https://www.binancezh.pro/cn/register?ref=AIR1GC70 ๅธๅฎ‰ๅˆ็บฆๆŽจ่็ : ่ฟ”ไฝฃ10% https://www.binancezh.com/cn/futures/ref/51bitquant if you don't have a binance account, you can use the invitation link to register one: https://www.binancezh.com/...
trader/binance_trader.py
9,326
:param api_key: :param secret: :param trade_type: ไบคๆ˜“็š„็ฑปๅž‹๏ผŒ only support future and spot. ๆ‰ง่กŒๆ ธๅฟƒ้€ป่พ‘๏ผŒ็ฝ‘ๆ ผไบคๆ˜“็š„้€ป่พ‘. :return: ๅธๅฎ‰ๆŽจ่็ : ่ฟ”ไฝฃ10% https://www.binancezh.pro/cn/register?ref=AIR1GC70 ๅธๅฎ‰ๅˆ็บฆๆŽจ่็ : ่ฟ”ไฝฃ10% https://www.binancezh.com/cn/futures/ref/51bitquant if you don't have a binance account, you can use the invitation link to re...
814
zh
0.472292
# -*- coding: utf-8 -*- # # Copyright 2017 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requir...
mac/google-cloud-sdk/lib/googlecloudsdk/api_lib/compute/daisy_utils.py
23,491
Subclass of CloudBuildClient that allows filtering. Exception for builds that did not succeed. Subclass of LogTailer that allows for filtering. Enum representing image operation. Exception for subnet related errors. Common arguments for Daisy builds. Extra common arguments for Daisy builds. Extracts network/subnet out ...
8,854
en
0.831401
# ---------------------------------------------------------------------- # Distributed Lock # ---------------------------------------------------------------------- # Copyright (C) 2007-2021 The NOC Project # See LICENSE for details # ---------------------------------------------------------------------- # Python m...
core/lock/distributed.py
3,629
Distributed locking primitive. Allows exclusive access to all requested items within category between the group of processes. Example ------- ``` lock = DistributedLock("test", "test:12") with lock.acquire(["obj1", "obj2"]): ... ``` :param category: Lock category name :param owner: Lock owner id :param ttl: Defaul...
853
en
0.643845
# Copyright (c) 2020 Aiven, Helsinki, Finland. https://aiven.io/ from .object_storage.gcs import GCSProvider from argparse import ArgumentParser from tempfile import TemporaryDirectory import codecs import datetime import dateutil import gzip import json import kafka import logging import os import re class KafkaRe...
kafka_restore/__main__.py
6,968
Copyright (c) 2020 Aiven, Helsinki, Finland. https://aiven.io/ assume UTC if no timezone is present
99
en
0.755911
# Generated by Django 4.0 on 2022-01-10 10:35 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('funblog', '0001_initial'), ] operations = [ migrations.AlterField( model_name='fblog', name='DOC', field=m...
fun/funblog/migrations/0002_alter_fblog_doc_alter_fblog_dou_alter_fblog_comment.py
774
Generated by Django 4.0 on 2022-01-10 10:35
43
en
0.729144
try: xrange except: xrange = range def totalvalue(comb): ' Totalise a particular combination of items' totwt = totval = 0 for item, wt, val in comb: totwt += wt totval += val return (totval, -totwt) if totwt <= 400 else (0, 0) items = ( ("map", 9, 150), ("compass", 13, 35)...
lang/Python/knapsack-problem-0-1-2.py
1,702
Totalise a particular combination of items
42
en
0.549833
# # voice-skill-sdk # # (C) 2020, Deutsche Telekom AG # # This file is distributed under the terms of the MIT license. # For details see the file LICENSE in the top directory. # # # Circuit breaker for skills requesting external services # from .config import config from circuitbreaker import CircuitBreaker from requ...
skill_sdk/circuit_breaker.py
788
Circuit breaker's defaults from skill config voice-skill-sdk (C) 2020, Deutsche Telekom AG This file is distributed under the terms of the MIT license. For details see the file LICENSE in the top directory. Circuit breaker for skills requesting external services Default circuit breaker will be used if no custom brea...
332
en
0.699027
from django.apps import AppConfig class ActivityFeedConfig(AppConfig): """App config for activity_feed.""" name = 'datahub.activity_feed'
datahub/activity_feed/apps.py
149
App config for activity_feed.
29
en
0.615776
#crie um tupla com o nome dos produtos, seguidos do preรงo. #mostre uma listagem de preรงos, de forma tabular. lista = ('Lรกpis', 1.5, 'Borracha', 2.5, 'Caderno', 10.8, 'Estojo', 20, 'Mochila', 100.5) print('\033[31m--'*20) print(f'{"LISTAGEM DE PREร‡OS":^40}') print('--'*20, '\033[m') for i in range(0, len(lis...
PacoteDownload/ex076.py
711
crie um tupla com o nome dos produtos, seguidos do preรงo.mostre uma listagem de preรงos, de forma tabular.
105
pt
0.99895
#!/usr/bin/env python import os import json import pprint as pp from time import time import torch import torch.optim as optim from tensorboard_logger import Logger as TbLogger from nets.critic_network import CriticNetwork from options import get_options from train import train_epoch, validate, get_inner_model from ...
hyper_attention/run.py
8,902
!/usr/bin/env python for hyperparameter tuning using wanb https://docs.wandb.ai/sweeps/quickstart start time Pretty print the run args Set the random seed Optionally configure tensorboard Save arguments so exact configuration can always be found Set the device Figure out what's the problem Load data from load_path hype...
1,206
en
0.649407
# pylint:disable=unused-variable # pylint:disable=unused-argument # pylint:disable=redefined-outer-name import pytest from models_library.basic_types import LogLevel from simcore_service_director_v2.core.settings import ( AppSettings, BootModeEnum, DynamicSidecarProxySettings, DynamicSidecarSettings, ...
services/director-v2/tests/unit/test_core_settings.py
1,985
pylint:disable=unused-variable pylint:disable=unused-argument pylint:disable=redefined-outer-name loads from environ
116
en
0.263885
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
sdk/appplatform/azure-mgmt-appplatform/azure/mgmt/appplatform/v2020_11_01_preview/operations/_monitoring_settings_operations.py
19,130
MonitoringSettingsOperations operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~azure.mgmt.appplatform.v2020_11_01_previ...
5,645
en
0.525905
# coding: utf-8 # In[ ]: def choice(): print("1-create,2-update,3-read,4-delete") try: x=int(input("\nEnter your choice:")) except ValueError: print("Enter integer choice:....") choice() else: if(x==1): create() elif(x==2): update() ...
database.py
2,870
coding: utf-8 In[ ]:creating lists list of deleted id
56
en
0.926506
#!/usr/bin/python3 import socket import re import time pattern = re.compile('N=\d+\sC=\d+') s = socket.socket() s.connect(('localhost', 9007)) s.recv(1024) # what received is just a introduction, we do not need it. time.sleep(4) while True: received = s.recv(1024).decode('ascii') print(received, end='...
pwnable.kr/Toddler's Bottle/coin1/coin1.py
1,371
!/usr/bin/python3 what received is just a introduction, we do not need it.
74
en
0.981509
import os from pathlib import Path import numpy as np import pandas as pd import tensorflow as tf from skimage import io from tensorflow import keras class BimodalDenoiseDataGen(keras.utils.Sequence): ''' Generate train/validation/test samples for our multimodal denoise network. Inpu...
data.py
10,424
Generate train/validation/test samples for our multimodal denoise network. Inputs are static images, spectrograms and corresponding noisy labels. Outputs are noisy labels. In order to decorrelate training samples, we randonly shuffle movie sequences, sequentially fetch sel_movie movie clips from that sequence, then ...
512
en
0.716424
# -*- coding: utf-8 -*- """layers.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1fCQ_zLCcWNzgE99LK9B2cWrql8J3HgBO """ # Author : Vedant Shah # E-mail : vedantshah2012@gmail.com import torch import torch.nn as nn from torch.nn.parameter import P...
gcn/layers.py
1,467
Forward Propagation through the layer according to the spectral rule layers.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1fCQ_zLCcWNzgE99LK9B2cWrql8J3HgBO -*- coding: utf-8 -*- Author : Vedant Shah E-mail : vedantshah2012@gmail.com number of...
531
en
0.842585
import os import portalocker from deep_architect.contrib.communicators.communicator import Communicator from deep_architect.contrib.communicators.file_utils import (consume_file, read_file, write_f...
deep_architect/contrib/communicators/file_communicator.py
3,239
make directory where communication files are created claim a rank for the process continue looping until there is something in the queue file if kill signal is given, return None, otherwise return contents of file
213
en
0.861692
"""Tensorflow trainer class.""" import datetime import math import os import warnings from typing import Callable, Dict, Optional, Tuple import numpy as np import tensorflow as tf from packaging.version import parse from tensorflow.python.distribute.values import PerReplica from .integrations import is_comet_availab...
src/transformers/trainer_tf.py
34,717
TFTrainer is a simple but feature-complete training and eval loop for TensorFlow, optimized for ๐Ÿค— Transformers. Args: model (:class:`~transformers.TFPreTrainedModel`): The model to train, evaluate or use for predictions. args (:class:`~transformers.TFTrainingArguments`): The arguments to tweak...
9,110
en
0.788276
""" Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. 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 ...
src/cfnlint/rules/resources/properties/AllowedValue.py
4,477
Check if properties have a valid value Check itself Check Value Initialize the rule Check CloudFormation Properties Match for sub properties Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associat...
1,165
en
0.868102
#!/usr/bin/env python3 import os import sys from utils import config, logger, env from librarian.librarian import Librarian log = logger.get_log('KodiLibrarian') kodi = Librarian(config.hosts, update_while_playing=config.update_while_playing) if env.event == 'download': if env.calledBy == 'radarr': log....
KodiLibrarian.py
1,175
!/usr/bin/env python3
21
fr
0.448822
import json import platform from django.db.models import Q from django.http import HttpResponse from django.http import HttpResponseNotFound from morango.models import InstanceIDModel from rest_framework import viewsets from rest_framework.decorators import api_view from rest_framework.response import Response import...
kolibri/core/public/api.py
3,900
An equivalent endpoint in studio which allows kolibri devices to know if this device can serve content. Spec doc: https://docs.google.com/document/d/1XKXQe25sf9Tht6uIXvqb3T40KeY3BLkkexcV08wvR9M/edit# Endpoint: /public/<version>/channels/?=<query params> Endpoint: /public/<version>/channels/lookup/<identifier> Returns...
358
en
0.632436
def power(x, y, serialId): r = x + 10 p = r * y p += serialId p *= r p = (p%1000)//100 return p-5 if __name__ == '__main__': serialId = 1788 # serialId = 42 # serialId = 18 cum_sum_square = {} for i in range(0, 301): cum_sum_square[(0,i)] = 0 cum_sum_square[(...
11/2.py
1,207
serialId = 42 serialId = 18row(y)col(x) print(j,i)
50
en
0.280733
"""Tests for 2d flow around a cylinder with a conforming mesh and rans3p""" from builtins import range from builtins import object from proteus.iproteus import * from proteus import Comm from proteus import Context import tables import importlib comm = Comm.get() Profiling.logLevel = 7 Profiling.verbose = False import...
proteus/tests/HotStart_3P/test_HotStart_rans3p.py
3,596
Initialize the test problem. Tests for 2d flow around a cylinder with a conforming mesh and rans3p defined in iproteus Serious error"_hotstart_"+self.compare_name save data with different filename NUMERICAL SOLUTION COMPARE VS SAVED FILES
242
en
0.714572
import json import hashlib import os import pickle import re import shutil class Block: def __init__(self, numberBlock, data, previousHash, idHash): self._idBlock = numberBlock self._data = data self._previousHash = previousHash self._idHash = idHash self._checker = True ...
storage/fase2/team13/Blockchain.py
6,499
self._checker = False only for the first If is not the first, verify the previous hash If is the first, verify the actual hash, because the first always has previous in 0 If is not the last to put the next pointer If is the Last not put the next pointer If is not the First to the Back pointer Cambiando valores de la li...
593
en
0.445422
from d2lbook2 import notebook from d2lbook2 import rst import unittest import nbconvert _markdown_src = r''' # Test :label:`test` first para python is good another para This is :eqref:`sec_1` ```python2 1+2+3 ``` python3 is better - here - haha ```{.input .python} 1+2+3 ``` ```{.input .python} #@tab python2 ...
d2lbook2/rst_test.py
1,003
TODO(mli) add some asserts
26
pt
0.157909
from .default import DefaultAttackEval from ..classifier import Classifier from ..attacker import Attacker import json from tqdm import tqdm class InvokeLimitException(Exception): pass class InvokeLimitClassifierWrapper(Classifier): def __init__(self, clsf, invoke_limit): self.__invoke_limit = invoke_...
OpenAttack/attack_evals/invoke_limit_eval.py
4,148
Evaluate attackers and classifiers with invoke limitation. :param Attacker attacker: The attacker you use. :param Classifier classifier: The classifier you want to attack. :param int invoke_limit: Limitation of invoke for each instance. :param bool average_invoke: If true, returns "Avg. Victim Model Queries". :param kw...
493
en
0.470667
""" Common utilities for the library """ import shutil import sys import os import logging from aws_lambda_builders.architecture import X86_64, ARM64 LOG = logging.getLogger(__name__) def copytree(source, destination, ignore=None, include=None): """ Similar to shutil.copytree except that it removes the lim...
aws_lambda_builders/utils.py
6,232
Similar to shutil.copytree except that it removes the limitation that the destination directory should be present. :type source: str :param source: Path to the source folder to copy :type destination: str :param destination: Path to destination folder :type ignore: function :param ignore: A function that...
2,882
en
0.827777
# -*- coding: utf-8 -*- # # How long does a Computron take? # # - [build model of computron\-to\-wallclock relationship ยท Issue \#3459 ยท Agoric/agoric\-sdk](https://github.com/Agoric/agoric-sdk/issues/3459) # ## Preface: Python Data Tools # # See also [shell.nix](shell.nix). # + import pandas as pd import numpy as n...
nb4/slogfiles.py
52,047
split each slogfile into runs (each beginning with an import-kernel event), process each run by finding sequential matching deliver+deliver-result pairs, turn each pair into a (crankNum, computrons, wallclock) triple Note: line numbers are **1-based** -*- coding: utf-8 -*- How long does a Computron take? - [bu...
9,710
en
0.622159
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for the CPIO extracted file-like object.""" from __future__ import unicode_literals import unittest from dfvfs.file_io import cpio_file_io from dfvfs.path import cpio_path_spec from dfvfs.path import os_path_spec from dfvfs.resolver import context from tests.fi...
tests/file_io/cpio_file_io.py
5,812
The unit test for a CPIO extracted file-like object. The unit test for a CPIO extracted file-like object. The unit test for a CPIO extracted file-like object. The unit test for a CPIO extracted file-like object. Sets up the needed objects used throughout the test. Sets up the needed objects used throughout the test. Se...
1,010
en
0.85021
import time import json from anchore_engine.subsys import logger def get_docker_registry_userpw(registry_record): user = pw = None try: if 'registry_type' in registry_record and registry_record['registry_type'] == 'awsecr': try: ecr_creds = json.loads(registry_record['regis...
anchore_engine/auth/common.py
2,715
:param registry_record_str: the string with optional wildcard to match against a the registry/repository combo :param registry: the registry to match against :param repository: the repository to match against :return: bool true if a match, false if not
252
en
0.622358
#!/usr/bin/env python3 # Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from __future__ import annotations from collections import defaultdict from typing import TYPE_CHECKING, Dict, List,...
ax/modelbridge/transforms/power_transform_y.py
8,041
Transform the values to look as normally distributed as possible. This fits a power transform to the data with the goal of making the transformed values look as normally distributed as possible. We use Yeo-Johnson (https://www.stat.umn.edu/arc/yjpower.pdf), which can handle both positive and negative values. While th...
1,944
en
0.847718
# # Copyright 2019 Jonas Berg # # 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...
dummy_serial.py
8,611
Dummy (mock) serial port for testing purposes. Mimics the behavior of a serial port as defined by the `pySerial <https://github.com/pyserial/pyserial>`_ module. Args: * port: * timeout: Note: As the portname argument not is used properly, only one port on :mod:`dummy_serial` can be used simultaneously. Strin...
2,334
en
0.827235
#!/usr/bin/env python import os from setuptools import setup from setuptools import find_packages import sys from financialdatapy import __version__ as VERSION # 'setup.py publish' shortcut. if sys.argv[-1] == 'publish': os.system('python setup.py sdist bdist_wheel') os.system('twine upload dist/*') sys.ex...
setup.py
1,452
!/usr/bin/env python 'setup.py publish' shortcut.
49
en
0.156986
# IMPORT MANAGEMENT try: import gevent.monkey except ModuleNotFoundError: import os os.system('pip install -r requirements.txt') import gevent.monkey gevent.monkey.patch_all() # patch everything import colorama colorama.init(autoreset=True) import discord.commands import asyncio import discord import...
src/bot.py
1,573
IMPORT MANAGEMENT patch everything IMPORTS SETTINGS SETUP initialize virtual environment load cogs credit: https://youtu.be/vQw8cFfZPx0 run bot with the token set in the .env file
179
en
0.417175
from __future__ import unicode_literals, division, absolute_import import logging import re from datetime import datetime from sqlalchemy import Column, Unicode, Integer from flexget import plugin from flexget.event import event from flexget.utils import requests from flexget.utils.soup import get_soup from flexget.u...
flexget/plugins/services/pogcal_acquired.py
4,154
Check if we have this show id cached Try to find the show id from pogdesign show list
85
en
0.857386
import copy import datetime import decimal import inspect import json import logging import traceback import uuid import warnings from collections import Counter, defaultdict, namedtuple from collections.abc import Hashable from functools import wraps from typing import List from dateutil.parser import parse from gre...
great_expectations/data_asset/data_asset.py
53,983
Initialize the DataAsset. :param profiler (profiler class) = None: The profiler that should be run on the data_asset to build a baseline expectation suite. Note: DataAsset is designed to support multiple inheritance (e.g. PandasDataset inherits from both a Pandas DataFrame and Dataset which inherits from DataAsse...
15,737
en
0.711492
"""update liscence colum to hash Revision ID: 0a769c5cda0a Revises: 1de63d54c3b7 Create Date: 2018-06-21 17:57:36.549097 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '0a769c5cda0a' down_revision = '1de63d54c3b7' branch_labels = None depends_on = None def u...
wicarproject/migrations/versions/0a769c5cda0a_update_liscence_colum_to_hash.py
2,303
update liscence colum to hash Revision ID: 0a769c5cda0a Revises: 1de63d54c3b7 Create Date: 2018-06-21 17:57:36.549097 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
312
en
0.615589
import os from plugins import BaseAssessment from yapsy.IPlugin import IPlugin from asmtypes import ArastDataOutputError class ReaprAssessment(BaseAssessment, IPlugin): OUTPUT = 'contigs' def run(self): """ Build the command and run. Return list of file(s) """ contigs =...
lib/assembly/plugins/reapr.py
1,563
Build the command and run. Return list of file(s) Generate Bamfiles Run REAPR Pipeline Move files into root dir
113
en
0.755907
#!/usr/bin/env python3 # Northcliff Airconditioner Controller Version 3.48 Gen import RPi.GPIO as GPIO import time from datetime import datetime #import requests #from threading import Thread import paho.mqtt.client as mqtt import struct import json import serial import binascii import sys import spidev import math imp...
Northcliff_Aircon_Controller.py
38,352
!/usr/bin/env python3 Northcliff Airconditioner Controller Version 3.48 Genimport requestsfrom threading import Thread Set up GPIO Aircon Startup Mode This flag keeps track of whether the aircon is under remote or autonomous operation This flag is set to True during remote operation to enable the serial comms loop whe...
8,182
en
0.849719
from django.utils.version import get_version VERSION = (3, 1, 6, "final", 0) __version__ = get_version(VERSION) def setup(set_prefix=True): """ Configure the settings (this happens as a side effect of accessing the first setting), configure logging and populate the app registry. Set the thread-local...
Thesis@3.9.1/Lib/site-packages/django/__init__.py
799
Configure the settings (this happens as a side effect of accessing the first setting), configure logging and populate the app registry. Set the thread-local urlresolvers script prefix if `set_prefix` is True.
208
en
0.859683
# coding=utf-8 from __future__ import unicode_literals from .. import Provider as AutomotiveProvider class Provider(AutomotiveProvider): # from # https://en.wikipedia.org/wiki/Vehicle_registration_plates_of_the_United_Kingdom license_formats = ( '??## ???', '??##???' )
oscar/lib/python2.7/site-packages/faker/providers/automotive/en_GB/__init__.py
305
coding=utf-8 from https://en.wikipedia.org/wiki/Vehicle_registration_plates_of_the_United_Kingdom
97
en
0.634569
import mysql_conn class BaseField: def __init__(self,name,column_type,primary_key,default): self.name=name self.column_type=column_type self.primary_key=primary_key self.default=default class StringField(BaseField): def __init__(self,name,column_type='varchar(200)',primary_key=...
orm1.py
4,126
user=User.select_one(id=1) user.name='่ฟ™ๆต‹่ฏ•1111' user.update() print(user)
72
ja
0.083905
import copy import os import logging import pickle from typing import Dict, List, Optional, Union try: import sigopt as sgo Connection = sgo.Connection except ImportError: sgo = None Connection = None from ray.tune.suggest import Searcher logger = logging.getLogger(__name__) class SigOptSearch(Sear...
python/ray/tune/suggest/sigopt.py
9,997
A wrapper around SigOpt to provide trial suggestions. You must install SigOpt and have a SigOpt API key to use this module. Store the API token as an environment variable ``SIGOPT_KEY`` as follows: .. code-block:: bash pip install -U sigopt export SIGOPT_KEY= ... You will need to use the `SigOpt experiment ...
3,608
en
0.624665
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/13a_learner.ipynb (unless otherwise specified). __all__ = ['CancelFitException', 'CancelEpochException', 'CancelTrainException', 'CancelValidException', 'CancelBatchException', 'replacing_yield', 'mk_metric', 'save_model', 'load_model', 'Learner', '...
fastai2/learner.py
22,746
Average the losses taking into account potential different batch sizes Average the values of `func` taking into account potential different batch sizes Smooth average of the losses (exponentially weighted with `beta`) A callback to fetch predictions during the training loop Blueprint for defining a metric Callback that...
1,602
en
0.777059
class dotnetPointList_t(object): """ dotnetPointList_t(Size: int) """ def FromStruct(self, PointList): """ FromStruct(self: dotnetPointList_t,PointList: PointList) """ pass def ToStruct(self, PointList): """ ToStruct(self: dotnetPointList_t,PointList: PointList) """ ...
release/stubs.min/Tekla/Structures/ModelInternal_parts/dotnetPointList_t.py
634
dotnetPointList_t(Size: int) FromStruct(self: dotnetPointList_t,PointList: PointList) ToStruct(self: dotnetPointList_t,PointList: PointList) __new__[dotnetPointList_t]() -> dotnetPointList_t __new__(cls: type,Size: int)
225
en
0.657642
"""Test case that checks the working of the utils/command/gen_uml.py module.""" from utils.model.gen_uml import generate import importlib_metadata class PseudoFile: def __init__(self): self.data = "" def write(self, data): self.data += data def close(self): pass def test_loadi...
tests/test_gen_uml.py
1,572
Test case that checks the working of the utils/command/gen_uml.py module.
73
en
0.659834
""" This file offers the methods to automatically retrieve the graph Acidocella sp. MX-AZ02. The graph is automatically retrieved from the STRING repository. References --------------------- Please cite the following if you use the data: ```bib @article{szklarczyk2019string, title={STRING v11: protein--protein...
bindings/python/ensmallen/datasets/string/acidocellaspmxaz02.py
3,480
Return new instance of the Acidocella sp. MX-AZ02 graph. The graph is automatically retrieved from the STRING repository. Parameters ------------------- directed: bool = False Wether to load the graph as directed or undirected. By default false. preprocess: bool = True Whether to preprocess the graph ...
2,693
en
0.706483
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright ยฉ 2018 Michael J. Hayford """ Support creation of an iPython console, with rayoptics environment .. Created on Wed Nov 21 21:48:02 2018 .. codeauthor: Michael J. Hayford """ from qtconsole.rich_jupyter_widget import RichJupyterWidget from qtconsole.inprocess...
src/rayoptics/qtgui/ipyconsole.py
2,845
Clears the terminal create a iPython console with a rayoptics environment Execute a command in the frame of the console widget Prints some plain text to the console Given a dictionary containing name / value pairs, push those variables to the Jupyter console widget Support creation of an iPython console, with rayoptic...
561
en
0.701783
"""Phonopy QHA module.""" # Copyright (C) 2012 Atsushi Togo # All rights reserved. # # This file is part of phonopy. # # 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 th...
phonopy/qha/core.py
40,335
Bulk modulus class. This class is used to calculate bulk modulus only from temperature independent energy input. Quasi harmonic approximation class. Init method. volumes : array_like Unit cell volumes where energies are obtained. shape=(volumes, ), dtype='double'. energies : array_like Energies obtained a...
4,883
en
0.736608
import os from argparse import ArgumentParser from time import time import yaml import numpy as np from fx_replicator import ( build_model, load_wave, save_wave, sliding_window, LossFunc ) import nnabla as nn #import nnabla_ext.cudnn import nnabla.functions as F import nnabla.parametric_functions as PF import nnabl...
predict.py
2,870
import nnabla_ext.cudnn padding and rounded up to the batch multiple
68
en
0.330351
""" This module contains utiliy functions for fields which are used by both the :mod:`~sphinxcontrib_django2.docstrings.attributes` and :mod:`~sphinxcontrib_django2.docstrings.classes` modules. """ from django.apps import apps from django.contrib import contenttypes from django.db import models from django.utils.encodi...
sphinxcontrib_django2/docstrings/field_utils.py
5,848
Get the type of a field including the correct intersphinx mappings. :param field: The field :type field: ~django.db.models.Field :param include_directive: Whether or not the role :any:`py:class` should be included :type include_directive: bool :return: The type of the field :rtype: str Get the verbose name of the fi...
2,057
en
0.833739