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 |
|---|---|---|---|---|---|---|
# Generated by Django 3.0.6 on 2020-05-28 17:21
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
ope... | projectamber/botapp/migrations/0001_initial.py | 3,115 | Generated by Django 3.0.6 on 2020-05-28 17:21 | 45 | en | 0.646485 |
"""Tests for the HTTP API Client."""
import pytest
import solana.system_program as sp
from solana.rpc.api import DataSliceOpt, Client
from solana.keypair import Keypair
from solana.rpc.core import RPCException
from solana.rpc.types import RPCError
from solana.transaction import Transaction
from solana.rpc.commitment i... | tests/integration/test_http_client.py | 16,558 | Test that RPCException is raised when trying to confirm an invalid signature.
Test get_account_info.
Test get block.
Test get block commitment.
Test get height.
Test get block time.
Test get block with encoding.
Test get blocks.
Test get cluster nodes.
Test get confirmed block.
Test get confrimed block with encoding.
T... | 2,144 | en | 0.835581 |
#!/usr/bin/env python3
# Copyright (c) 2015-2016 The BitCore Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""
This module contains utilities for doing coverage analysis on the RPC
interface.
It provides a way t... | qa/rpc-tests/test_framework/coverage.py | 2,965 | An object that wraps AuthServiceProxy to record specific RPC calls.
Delegates to AuthServiceProxy, then writes the particular RPC method
called to a file.
Kwargs:
auth_service_proxy_instance (AuthServiceProxy): the instance
being wrapped.
coverage_logfile (str): if specified, write each service_name
... | 1,135 | en | 0.786508 |
#!/usr/bin/env python
# coding: utf-8
# This software component is licensed by ST under BSD 3-Clause license,
# the "License"; You may not use this file except in compliance with the
# License. You may obtain a copy of the License at:
# https://opensource.org/licenses/BSD-3-Clause
... | SensorTile/STM32CubeFunctionPack_SENSING1_V4.0.2/Middlewares/ST/STM32_AI_AudioPreprocessing_Library/Python/MFCC.py | 1,650 | KWS Feature Extraction example.
!/usr/bin/env python coding: utf-8 This software component is licensed by ST under BSD 3-Clause license, the "License"; You may not use this file except in compliance with the License. You may obtain a copy of the License at: https://opensource.org/licenses/... | 394 | en | 0.874031 |
# Generated by Django 3.2.7 on 2021-09-10 14:40
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='AppState',
... | bot/migrations/0001_initial.py | 2,461 | Generated by Django 3.2.7 on 2021-09-10 14:40 | 45 | en | 0.686191 |
import scipy
from manimlib.imports import *
from from_3b1b.old.eoc.chapter1 import Thumbnail as Chapter1Thumbnail
from from_3b1b.old.eoc.chapter2 import Car, MoveCar, ShowSpeedometer, \
IncrementNumber, GraphCarTrajectory, SecantLineToTangentLine, \
VELOCITY_COLOR, TIME_COLOR, DISTANCE_COLOR
def v_rate_func(t)... | from_3b1b/old/eoc/chapter8.py | 85,414 | Sit in carShow speedometerTravelAsk about distanceChange if different from x_min for mob in anim.starting_mobject, anim.mobject: mob.randy.rotate_in_place(np.pi/6)Shrink dt just a bitFade close to 0 | 202 | en | 0.635571 |
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under ... | venv/lib/python3.6/site-packages/requests_mock/request.py | 4,419 | A wrapper around a requests.Request that gives some extra information.
This will be important both for matching and so that when it's save into
the request_history users will be able to access these properties.
The matcher that this request was handled by.
The matcher object is handled by a weakref. It will return th... | 1,375 | en | 0.898641 |
'''
Acdfg class will have the class definitions for loading
and creating acdfg objects
'''
from __future__ import print_function
try:
from enum import Enum
except ImportError:
from enum34 import Enum
#import proto_acdfg
from protobuf.proto_acdfg_pb2 import Acdfg as ProtoAcdfg
import logging
class NodeType(Enum... | python/fixrgraph/annotator/acdfgClass.py | 7,922 | Acdfg class will have the class definitions for loading
and creating acdfg objects
import proto_acdfg assert isinstance(node_type, NodeType) def __init__(self, key): self.node_type = NodeType.regular_node self.id = key assert isinstance(key, int) create a new acdfg acdfg.parse_from_bytes(f.read()) | 311 | en | 0.356052 |
# 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 ... | azure/mgmt/monitor/models/rule_management_event_data_source.py | 3,396 | A rule management event data source. The discriminator fields is always
RuleManagementEventDataSource in this case.
:param resource_uri: the resource identifier of the resource the rule
monitors.
:type resource_uri: str
:param odatatype: Polymorphic Discriminator
:type odatatype: str
:param event_name: the event name... | 1,580 | en | 0.606781 |
import argparse
from datetime import datetime
from json import decoder
from os import path, mkdir, remove
from os.path import isfile
from threading import Thread
from time import sleep
try:
from progress.bar import Bar
import requests
import termcolor
except ImportError:
print("You are missing modules... | scrape.py | 6,391 | print a message with a time stamp clean any temp files created during runtime main loop fetch latest 100 paste IDs clean up fetched ids create a progress bar and start downloading pastes if we have new ones download the raw paste data if we have a provided keyword list, check for keywords otherwise, just say that we di... | 541 | en | 0.721259 |
# Copyright 2013-2019 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Parsplice(CMakePackage):
"""ParSplice code implements the Parallel Trajectory Splicing al... | var/spack/repos/builtin/packages/parsplice/package.py | 982 | ParSplice code implements the Parallel Trajectory Splicing algorithm
Copyright 2013-2019 Lawrence Livermore National Security, LLC and other Spack Project Developers. See the top-level COPYRIGHT file for details. SPDX-License-Identifier: (Apache-2.0 OR MIT) | 259 | en | 0.673312 |
class QuizBrain:
def __init__(self, questions):
self.question_no = 0
self.score = 0
self.questions = questions
self.current_question = None
def has_more_questions(self):
"""To check if the quiz has more questions"""
return self.question_no < len(self.qu... | quiz_brain.py | 1,266 | Check the user answer against the correct answer and maintain the score
Get the number of correct answers, wrong answers and score percentage.
To check if the quiz has more questions
Get the next question by incrementing the question number | 240 | en | 0.925566 |
from django.test import SimpleTestCase
from django.utils.safestring import mark_safe
from ..utils import render, setup
class DefaultTests(SimpleTestCase):
"""
Literal string arguments to the default filter are always treated as
safe strings, regardless of the auto-escaping state.
Note: we have to us... | tests/template_tests/filter_tests/test_default.py | 1,677 | Literal string arguments to the default filter are always treated as
safe strings, regardless of the auto-escaping state.
Note: we have to use {"a": ""} here, otherwise the invalid template
variable string interferes with the test result. | 239 | en | 0.729279 |
"""General-purpose training script for image-to-image translation.
This script works for various models (with option '--model': e.g., pix2pix, cyclegan, colorization) and
different datasets (with option '--dataset_mode': e.g., aligned, unaligned, single, colorization).
You need to specify the dataset ('--dataroot'), e... | train.py | 5,467 | General-purpose training script for image-to-image translation.
This script works for various models (with option '--model': e.g., pix2pix, cyclegan, colorization) and
different datasets (with option '--dataset_mode': e.g., aligned, unaligned, single, colorization).
You need to specify the dataset ('--dataroot'), expe... | 2,438 | en | 0.689628 |
# 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 argparse import Namespace
import contextlib
import copy
import math
import numpy as np
import torch
import torch.nn as nn
import torch.nn... | fairseq/models/wav2vec/wav2vec2_asr.py | 20,506 | Transformer decoder consisting of *args.decoder_layers* layers. Each layer
is a :class:`TransformerDecoderLayer`.
Args:
args (argparse.Namespace): parsed command-line arguments
dictionary (~fairseq.data.Dictionary): decoding dictionary
embed_tokens (torch.nn.Embedding): output embedding
no_encoder_attn... | 1,876 | en | 0.662981 |
"""
Django settings for webappexample project.
Generated by 'django-admin startproject' using Django 1.11.4.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
fro... | 01-Login/webappexample/settings.py | 4,045 | Django settings for webappexample project.
Generated by 'django-admin startproject' using Django 1.11.4.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
Build path... | 1,035 | en | 0.628364 |
"""
Author: thangbk2209
Project: Autoscaling
Created: 3/15/19 16:48
Purpose:
"""
import random
import os
import matplotlib
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler, StandardScaler
import tensorflow as tf
from config import *
def draw_time_series(data, title, x_label, ... | lib/includes/utility.py | 3,753 | Author: thangbk2209
Project: Autoscaling
Created: 3/15/19 16:48
Purpose:
plt.legend([/], loc='upper left') collect the first key in kwargs dict num_units.append(random.choice(range(1, layer_size, 1))) | 203 | en | 0.466186 |
# -*- coding: utf-8 -*-
# Copyright (c) Facebook, Inc. and its affiliates.
import functools
import inspect
import logging
from fvcore.common.config import CfgNode as _CfgNode
from detectron2.utils.file_io import PathManager
class CfgNode(_CfgNode):
"""
The same as `fvcore.common.config.CfgNode`, but differe... | detectron2/config/config.py | 9,000 | The same as `fvcore.common.config.CfgNode`, but different in:
1. Use unsafe yaml loading by default.
Note that this may lead to arbitrary code execution: you must not
load a config file from untrusted sources before manually inspecting
the content of the file.
2. Support config versioning.
When attempting ... | 3,105 | en | 0.654374 |
#!/usr/bin/env python3
""" This script builds the ASKE deliverable reports as PDFs by combining the
markdown files, using pandoc.
Usage:
./build_report.py <report_name>
"""
import os, sys
from glob import glob
import subprocess as sp
def transform_line(line):
# Transform headers - numbered headings are not ... | documentation/deliverable_reports/build_report.py | 2,150 | Apply appropriate transformations to markdown files
so that they can be compiled properly into a PDF report via
LaTeX.
This script builds the ASKE deliverable reports as PDFs by combining the
markdown files, using pandoc.
Usage:
./build_report.py <report_name>
!/usr/bin/env python3 Transform headers - numbered h... | 498 | en | 0.77251 |
#
# PySNMP MIB module Juniper-MPLS-CONF (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Juniper-MPLS-CONF
# Produced by pysmi-0.3.4 at Wed May 1 14:03:27 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... | pysnmp-with-texts/Juniper-MPLS-CONF.py | 7,376 | PySNMP MIB module Juniper-MPLS-CONF (http://snmplabs.com/pysmi) ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Juniper-MPLS-CONF Produced by pysmi-0.3.4 at Wed May 1 14:03:27 2019 On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 Using Python version 3.7.3 (default, Mar 27 2019, 0... | 328 | en | 0.467309 |
# -*- coding:utf-8; python-indent:2; indent-tabs-mode:nil -*-
# Copyright 2013 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/... | pytype/pytd/optimize.py | 39,279 | Converts mutable parameters to unions. This is lossy.
For example, this will change
def f(x: list[int]):
x = list[int or float]
to
def f(x: list[int] or list[int or float])
.
(Use optimize.CombineContainers to then change x to list[int or float].)
This also works for methods - it will then potentially change ... | 15,545 | en | 0.817564 |
"""
--- Ångström ---
Read, manipulate and analyze molecular trajectory files.
"""
from .read import read_xyz_traj
from .write import write_xyz_traj
from angstrom.geometry import get_molecule_center
from angstrom import Molecule
import numpy as np
import os
class Trajectory:
"""
Reading and analyzing trajector... | angstrom/trajectory/trajectory.py | 5,739 | Reading and analyzing trajectories in xyz format.
Trajectory addition for joining the coordinates and elements into a new Trajectory object.
Parameters
----------
traj : Trajectory
Trajectory object to be added
Returns
-------
Trajectory
Joined Trajectory object.
Indexing method.
Returns a Molecule object for... | 1,807 | en | 0.47647 |
# BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/main/LICENSE
from __future__ import absolute_import
import sys
import numpy
import awkward as ak
def convert_to_array(layout, args, kwargs):
out = ak.operations.convert.to_numpy(layout, allow_missing=False)
if args == () and kwargs... | src/awkward/_connect/_numpy.py | 13,672 | BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/main/LICENSE | 85 | en | 0.5876 |
# Generated by Django 3.0.4 on 2020-03-26 03:39
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ViralScreener', '0008_auto_20200326_0338'),
]
operations = [
migrations.AlterField(
model_name='employeescreeningresponses',
... | mysite/ViralScreener/migrations/0009_auto_20200326_0339.py | 405 | Generated by Django 3.0.4 on 2020-03-26 03:39 | 45 | en | 0.663837 |
# Crie um programa onde o usuário possa digitar sete valores numéricos
# e cadastre-os em uma lista única que mantenha separados os valores pares e ímpares.
# No final, mostre os valores pares e ímpares em ordem crescente.
lista_unic = [[], []]
print('-=' * 20)
for c in range(0, 7):
nums = int(input(f'Informe um {c... | CursoemVideo - Python 3/aula 18/ex085.py | 623 | Crie um programa onde o usuário possa digitar sete valores numéricos e cadastre-os em uma lista única que mantenha separados os valores pares e ímpares. No final, mostre os valores pares e ímpares em ordem crescente. | 216 | pt | 0.961497 |
# Generated by Django 3.2.4 on 2021-06-05 20:41
import django.contrib.auth.models
import django.contrib.auth.validators
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0012_alter_user_first_name_m... | accounts/migrations/0001_initial.py | 2,879 | Generated by Django 3.2.4 on 2021-06-05 20:41 | 45 | en | 0.720238 |
import numpy as np
import pytest
import xarray as xr
import cf_xarray as cfxr
from . import requires_shapely
@pytest.fixture
def geometry_ds():
from shapely.geometry import MultiPoint, Point
# empty/fill workaround to avoid numpy deprecation(warning) due to the array interface of shapely geometries.
ge... | cf_xarray/tests/test_geometry.py | 5,104 | empty/fill workaround to avoid numpy deprecation(warning) due to the array interface of shapely geometries. | 107 | en | 0.63194 |
"""
list of movies that feed into fresh_tomatoes.py file
"""
import fresh_tomatoes
from get_movie_list import get_movie_list
def main():
"""
Main entry point for the script.
"""
# Read in the movies from the json file
movie_list = get_movie_list("src/data/movies.json")
# Generate the html ... | src/entertainment_center.py | 413 | Main entry point for the script.
list of movies that feed into fresh_tomatoes.py file
Read in the movies from the json file Generate the html file and display in a browser window | 180 | en | 0.900583 |
import pandas as pd
import numpy as np
import itertools as it
from collections import defaultdict
from collections import Counter
from six.moves import map as imap
def dict_subset(d, fields):
# return a subset of the provided dict containing only the
# fields specified in fields
return {k: d[k] for k in d... | pipe_segment/stats/stats.py | 3,984 | Count occurrences of values in a stream of messages for a specified set of fields
Usage:
messages = [
{'a': 'apple', 'b': 'boat'},
{'a': 'pear', 'b': 'boat'},
{'a': 'apple', 'b': 'boat'},
]
fields = ['a', 'b']
mfc = MessageFieldCounter(messages, fields)
# this class is d... | 867 | en | 0.722484 |
"""[Lambda Expressions]
Lambda expressions are simply another way to create functions anonymous functions
keyword \ parameter list optional
\ \ the : is required, even for zero arguments
\ \ / / this expression is evaluated and returned when the lamb... | .history/my_classes/FirstClassFunctions/LambdaExpressions_20210704152007.py | 1,178 | [Lambda Expressions]
Lambda expressions are simply another way to create functions anonymous functions
keyword \ parameter list optional
\ \ the : is required, even for zero arguments
\ \ / / this expression is evaluated and returned when the lambda ... | 1,167 | en | 0.584146 |
"""
Distance and Area objects to allow for sensible and convenient calculation
and conversions. Here are some tests.
"""
import unittest
from djmodels.contrib.gis.measure import A, Area, D, Distance
class DistanceTest(unittest.TestCase):
"Testing the Distance object"
def testInit(self):
"Testing in... | tests/gis_tests/test_measure.py | 7,442 | Testing the Area object
Testing the Distance object
Testing access in different units
Testing access in different units
Testing access in invalid units
Testing access in invalid units
Test addition & subtraction
Test addition & subtraction
Testing comparisons
Testing comparisons
Testing initialization from valid units
... | 788 | en | 0.779688 |
# console converter - USD to BGN
# Write a program for converting US dollars (USD) into Bulgarian levs (BGN).
# Round the result to 2 digits after the decimal point. Use a fixed exchange rate between the dollar and the lev: 1 USD = 1.79549 BGN.
USD = float(input())
BGN = round(USD * 1.79549, 2)
print(BGN)
| 1-Python-Programming-Basics (Sep 2020)/Course-Exercises-and-Exams/01_First-Steps-in-Coding/00.Book-Exercise-2.1-11-USD-to-BGN.py | 308 | console converter - USD to BGN Write a program for converting US dollars (USD) into Bulgarian levs (BGN). Round the result to 2 digits after the decimal point. Use a fixed exchange rate between the dollar and the lev: 1 USD = 1.79549 BGN. | 238 | en | 0.753672 |
# 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 ... | src/desktopvirtualization/azext_desktopvirtualization/vendored_sdks/desktopvirtualization/_desktop_virtualization_api_client.py | 6,184 | DesktopVirtualizationAPIClient.
:ivar operations: Operations operations
:vartype operations: desktop_virtualization_api_client.operations.Operations
:ivar workspaces: WorkspacesOperations operations
:vartype workspaces: desktop_virtualization_api_client.operations.WorkspacesOperations
:ivar scaling_plans: ScalingPlans... | 2,663 | en | 0.592768 |
#!/usr/bin/env python
#
# 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 "Li... | release.py | 24,937 | Get a preference from existing preference dictionary or invoke a function that can collect it from the user
Utility for creating release candidates and promoting release candidates to a final relase.
Usage: release.py
The utility is interactive; you will be prompted for basic release information and guided through th... | 3,041 | en | 0.901758 |
from masonite.foundation import response_handler
from masonite.storage import StorageCapsule
from masonite.auth import Sign
from masonite.environment import LoadEnvironment
from masonite.utils.structures import load
from masonite.utils.location import base_path
from masonite.middleware import (
SessionMiddleware,
... | Kernel.py | 4,103 | Register routes load configuration set locations | 48 | en | 0.709209 |
import html
import os
import pathlib
import shutil
import sqlite3
import sys
from collections import OrderedDict
from scripts.html_parts import *
from scripts.ilapfuncs import logfunc
from scripts.version_info import aleapp_version, aleapp_contributors
def get_icon_name(category, artifact):
''' Returns the icon ... | scripts/report.py | 20,013 | Write out the index.html page to the report folder
Returns the html code for a key-value table (2 cols) without col names
Returns the icon name from the feathericons collection. To add an icon type for
an artifact, select one of the types from ones listed @ feathericons.com
If no icon is available, the alert triangle ... | 1,235 | en | 0.794919 |
import unittest
from realm.cli.application import Application
from realm.cli.commands.install import InstallCommand
from realm.cli.commands.ls import LsCommand
from realm.cli.commands.task import TaskCommand
from realm.entities import Config, RealmContext
from realm.utils.child_process import ChildProcess
from tests.... | tests/test_multiple_packages_with_tasks.py | 3,149 | Create config once Create context every test | 44 | en | 0.31586 |
#! /usr/bin/env python
# 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
# "... | desktop/core/ext-py/avro-1.7.6/setup.py | 1,654 | ! /usr/bin/env python 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... | 893 | en | 0.86476 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from .core import * | kiberdrom_core/controller/__init__.py | 67 | !/usr/bin/env python3 -*- coding: utf-8 -*- | 43 | fr | 0.304089 |
from django import template
from django.utils.safestring import mark_safe
import markdown
from markdownx.utils import markdownify
from markdownx.settings import (
MARKDOWNX_MARKDOWN_EXTENSIONS,
MARKDOWNX_MARKDOWN_EXTENSION_CONFIGS
)
from markdown.extensions import Extension
register = template.Library()
@reg... | blog/templatetags/markdown_html.py | 1,180 | マークダウンをhtmlに変換する。
マークダウンをhtmlに変換する。
生のHTMLやCSS、JavaScript等のコードをエスケープした上で、マークダウンをHTMLに変換します。
公開しているコメント欄等には、こちらを使ってください。 | 120 | ja | 1.000046 |
import numpy as np
from bayes_implicit_solvent.continuous_parameter_experiments.elemental_types_mh import log_prior, mols, ll, data_path, \
smiles
smiles_list = smiles
from bayes_implicit_solvent.typers import RADIUS_UNIT
from bayes_implicit_solvent.freesolv import smiles_list
from bayes_implicit_solvent.typers ... | bayes_implicit_solvent/rjmc_experiments/tree_rjmc2.py | 3,094 | otherwise everything is -inf, because this type will be empty add one more parameter per element appearing in FreeSolv but not specified in obc2 parameter set to initial tree TODO: Parallelize. Note that multiprocessing.Pool won't work here because it doesn't play nice with SwigPy objects TODO: update to allow scale fa... | 345 | en | 0.723222 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import logging
from ray.rllib.agents import Agent, with_common_config
from ray.rllib.agents.ppo.ppo_policy_graph import PPOPolicyGraph
from ray.rllib.optimizers import SyncSamplesOptimizer, LocalMultiGPUOptimi... | python/ray/rllib/agents/ppo/ppo.py | 7,337 | Multi-GPU optimized implementation of PPO in TensorFlow.
yapf: disable __sphinx_doc_begin__ If true, use the Generalized Advantage Estimator (GAE) with a value function, see https://arxiv.org/pdf/1506.02438.pdf. GAE(lambda) parameter Initial coefficient for KL divergence Size of batches collected from each worker Num... | 1,384 | en | 0.76251 |
import re
from itertools import chain
from django.core.exceptions import FieldError
from django.db.models.constants import LOOKUP_SEP
from django.db.models.expressions import OrderBy, Random, RawSQL, Ref
from django.db.models.query_utils import QueryWrapper, select_related_descend
from django.db.models.sql.constants i... | django/db/models/sql/compiler.py | 54,078 | A helper method for get_order_by and get_distinct.
Note that get_ordering and get_distinct must produce same target
columns on same input, as the prefixes of get_ordering and get_distinct
must match. Executing SQL where this is not true is an error.
Perform the same functionality as the as_sql() method, returning an
S... | 14,060 | en | 0.885392 |
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.image import imread
# 데이터 준비
x = np.arange(0, 6, 0.1) # 0에서 6까지 0.1 간격으로 생성
y1 = np.sin(x)
y2 = np.cos(x)
# 그래프 그리기
plt.plot(x, y1, label='sin')
plt.plot(x, y2, linestyle='--', label='cos') # cos 함수는 점선으로 그리기
plt.xlabel('x') # x축 이름
plt.ylabel('y')... | Books/DeepLearningfromScratch/P01_HelloPython/numpy_pyplot.py | 527 | 데이터 준비 0에서 6까지 0.1 간격으로 생성 그래프 그리기 cos 함수는 점선으로 그리기 x축 이름 y축 이름 제목 이미지 표시 | 73 | ko | 1.00007 |
import torch
import torch.nn.functional as F
import torch_glow
from collections import namedtuple
from tests.utils import jitVsGlow
# Basic test of the PyTorch conv2d Node on Glow.
def test_conv2d_basic():
def conv2d_basic(inputs, filters):
conv = F.conv2d(inputs, filters, padding=1)
return F.relu(... | torch_glow/tests/nodes/conv2d_test.py | 1,645 | Basic test of the PyTorch conv2d Node on Glow. Test of the PyTorch conv2d Node with a provided bias tensor. Test of the PyTorch conv2d Node sweeping through various parameters of the Node to test that they work correctly. | 221 | en | 0.830215 |
import argparse
import sys
import pathlib
import random
from unittest import mock
import pytest
from _repobee import plugin
import repobee_plug as plug
from repobee_feedback import feedback
ASSIGNMENT_NAMES = ("task-1", "task-2")
STUDENT_TEAMS = tuple(
[
plug.StudentTeam(members=members)
for memb... | tests/test_feedback.py | 7,582 | Tests for the primary callback.
Test that the callback exits with a plug.PlugError if any of the
expected issues is not found.
Test that missing issues are ignored if --allow-mising is set.
Test that the callback calls the API.open_issue for the expected
repos and issues, when the issues all exist and are well formed.
... | 803 | en | 0.900295 |
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# 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 modif... | qiskit/optimization/algorithms/recursive_minimum_eigen_optimizer.py | 13,424 | Defines whether the intermediate results of
:class:`~qiskit.optimization.algorithms.RecursiveMinimumEigenOptimizer`
at each iteration should be stored and returned to the end user.
Recursive Eigen Optimizer Result.
A meta-algorithm that applies a recursive optimization.
The recursive minimum eigen optimizer applies a ... | 5,794 | en | 0.735696 |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Base class for a stock configuration.
@author: rajsaswa
"""
class StockConfig:
def __init__(self):
pass
def get_stock_url(self):
pass
| stock_notifier/stock_config/stock_config.py | 220 | Base class for a stock configuration.
@author: rajsaswa
!/usr/bin/env python2 -*- coding: utf-8 -*- | 101 | en | 0.495677 |
import warnings
import pandas as pd
from ..config import Config
from ..backend import Backend
from ..backend import PYOORB
from ..backend import FINDORB
from ..backend import MJOLNIR
__all__ = [
"generateEphemeris"
]
def generateEphemeris(
orbits,
observers,
backend="MJOLNIR",
b... | thor/orbits/ephemeris.py | 2,706 | Generate ephemeris for the orbits and the given observatories.
Parameters
----------
orbits : `~numpy.ndarray` (N, 6)
Orbits for which to generate ephemeris. If backend is 'THOR', then these orbits must be expressed
as heliocentric ecliptic cartesian elements. If backend is 'PYOORB' orbits may be
express... | 1,177 | en | 0.6157 |
#! -*- coding:utf-8 -*-
# 评估脚本
# 数据集:IFLYTEK' 长文本分类 (https://github.com/CLUEbenchmark/CLUE)
import json
import numpy as np
from bert4keras.backend import keras, set_gelu
from bert4keras.tokenizers import Tokenizer
from bert4keras.models import build_transformer_model
from bert4keras.optimizers import Adam
from bert4ke... | examples/task_iflytek.py | 4,497 | 数据生成器
! -*- coding:utf-8 -*- 评估脚本 数据集:IFLYTEK' 长文本分类 (https://github.com/CLUEbenchmark/CLUE) 切换tanh版本 RoBERTa small 加载数据集 建立分词器 加载预训练模型 转换数据集 | 147 | zh | 0.932504 |
# Athena Health Preliminary Test - II
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'moves' function below.
#
# The function is expected to return an INTEGER.
# The function accepts INTEGER_ARRAY arr as parameter.
#
def moves(arr):
ee=e=0
for i in range(0,len(arr)... | 0_Companies/ATHENA2.py | 759 | Athena Health Preliminary Test - II!/bin/python3 Complete the 'moves' function below. The function is expected to return an INTEGER. The function accepts INTEGER_ARRAY arr as parameter. | 185 | en | 0.638918 |
import os
import requests
from os.path import join, isfile
from nerblackbox.modules.datasets.formatter.base_formatter import BaseFormatter
class CoNLL2003Formatter(BaseFormatter):
def __init__(self):
ner_dataset = "conll2003"
ner_tag_list = ["PER", "ORG", "LOC", "MISC"]
super().__init__(n... | nerblackbox/modules/datasets/formatter/conll2003_formatter.py | 3,832 | III: format data
---------------------------------------------
:param phase: [str] 'train' or 'test'
:return: _rows: [list] of [list] of [str], e.g. [[], ['Inger', 'PER'], ['säger', '0'], ..]
II: customize ner_training tag mapping if wanted
-------------------------------------
:return: ner_tag_mapping: [dict] w/ key... | 661 | en | 0.268324 |
# 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)
import os
from spack.package import *
class Visit(CMakePackage):
"""VisIt is an Open Source, interactive, scalable,... | var/spack/repos/builtin/packages/visit/package.py | 11,997 | VisIt is an Open Source, interactive, scalable, visualization,
animation and analysis tool. See comments in VisIt's package.py
for tips about building VisIt with spack. Building VisIt with
Spack is still experimental and many standard features are likely
disabled
LINUX---------------------------------------------------... | 4,024 | en | 0.733623 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('data', '0002_auto_20141114_1935'),
]
operations = [
migrations.RemoveField(
model_name='registryentry',
... | dpnode/dpn/data/migrations/0003_auto_20141117_2011.py | 715 | -*- coding: utf-8 -*- | 21 | en | 0.767281 |
import math
import numpy as np
from enum import IntEnum
class Mode(IntEnum):
CUSTOM = 0
EQUAL = 1
GAUSS = 2
GAUSS_SYM = 3
PYRAMID = 4
PYRAMID_SYM = 5
SIVEROO_1 = 6
SIVEROO_2 = 7
#This function will return an list of value, like... | weights.py | 2,657 | This function will return an list of value, like below: [0,1,2,3,...,n] -> [a,...,b] this function will stretch the given array (w) to a specific length (n) example : n = 10, w = [1,2] result : val = [1,1,1,1,1,2,2,2,2,2] , flip it, and then normalize it so its sum is equal to 1 fallback to [1,0] if fucked up | 310 | en | 0.725512 |
# 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... | aliyun-python-sdk-iot/aliyunsdkiot/request/v20180120/CreateRuleRequest.py | 3,042 | 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 use this file... | 754 | en | 0.883564 |
#!/usr/bin/env python3
import uuid
import random
import datetime
from faker import Factory
fake = Factory.create()
num_people = 1000
last_jump_start = datetime.datetime(2008, 9, 1)
last_jump_end = datetime.datetime(2016, 8, 1)
print('COPY members (uuid, name, email, phone_number, last_jump, created_at, updated_at) ... | test-data/members.py | 1,048 | !/usr/bin/env python3 | 21 | fr | 0.448822 |
import os
from selfdrive.manager.process import PythonProcess, NativeProcess, DaemonProcess
from selfdrive.hardware import EON, TICI, PC
from common.op_params import opParams
WEBCAM = os.getenv("USE_WEBCAM") is not None
procs = [
DaemonProcess("manage_athenad", "selfdrive.athena.manage_athenad", "AthenadPid"),
#... | selfdrive/manager/process_config.py | 2,739 | due to qualcomm kernel bugs SIGKILLing camerad sometimes causes page table corruption | 85 | en | 0.616132 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# =======================================
# File Name: test_ADMM.py
# Purpose : test ADMM solver for primal
# problem and dual problem
# =======================================
from utils import get_params
from ADMM_primal import ADMM_primal
from ADMM_dual impo... | test_ADMM.py | 1,765 | Main routine
!/usr/bin/env python -*- coding: utf-8 -*- ======================================= File Name: test_ADMM.py Purpose : test ADMM solver for primal problem and dual problem ======================================= | 240 | en | 0.610898 |
# -*- coding: utf-8 -*-
"""
solutions_by_text.sbt_token_generator
~~~~~~~~~~~~
This module handles security token generation.
"""
# @Author: sijanonly
# @Date: 2018-03-19 10:57:26
# @Last Modified by: sijanonly
# @Last Modified time: 2018-03-19 14:51:07
import json
from urllib import parse
import requests
from... | solutions_by_text/sbt_token_generator.py | 1,456 | Generates a security token for SBT API access.
Args:
api_key (string): API_KEY value provided by solutionsbytext
stage (string): STAGE values (test or ui)
Returns:
string: SecurityToken returns by LoginAPIService
Raises:
CustomException: Raises while error during GET request.
solutions_by_text.sbt_to... | 537 | en | 0.558515 |
# -*- coding: utf-8 -*-
"""
TencentBlueKing is pleased to support the open source community by making 蓝鲸智云-权限中心(BlueKing-IAM) available.
Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with th... | saas/backend/debug/urls.py | 978 | TencentBlueKing is pleased to support the open source community by making 蓝鲸智云-权限中心(BlueKing-IAM) available.
Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may obtain a ... | 707 | en | 0.86388 |
#!/usr/bin/env python3
# Copyright (c) 2014-2016 The Youngseokcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the abandontransaction RPC.
The abandontransaction RPC marks a transaction and all its in-... | test/functional/abandonconflict.py | 7,732 | Test the abandontransaction RPC.
The abandontransaction RPC marks a transaction and all its in-wallet
descendants as abandoned which allows their inputs to be respent. It can be
used to replace "stuck" or evicted transactions. It only works on transactions
which are not included in a block and are not currently in the... | 2,195 | en | 0.92506 |
#You can either add the python package path.
#sys.path.append(r'/mnt/e/GitHub_Design/Metalprot')
from metalprot.search import search_selfcenter
from metalprot.basic import filter
import pickle
import time
import prody as pr
'''
python /mnt/e/GitHub_Design/Metalprot/scrips/search_selfcenter/run_selfcenter_search.py
''... | scrips/search_selfcenter/run_selfcenter_search.py | 3,575 | You can either add the python package path.sys.path.append(r'/mnt/e/GitHub_Design/Metalprot') run Search_struct workdir = '/mnt/e/DesignData/ligands/LigandBB/6dwv/' outdir = workdir + 'output_selfcenter/' target_path = workdir + '6dwv_core.pdb' win_filter = [] workdir = '/mnt/e/DesignData/ligands/LigandBB/8adh/' outdir... | 1,388 | en | 0.469983 |
# coding=utf-8
import logging
import pytest
from rasa_nlu.evaluate import (
is_token_within_entity, do_entities_overlap,
merge_labels, remove_duckling_entities,
remove_empty_intent_examples, get_entity_extractors,
get_duckling_dimensions, known_duckling_dimensions,
find_component, remove_duckling... | tests/base/test_evaluation.py | 12,735 | coding=utf-8 Chinese Example "对面食过敏" -> To be allergic to wheat-based food opposite, food, allergy towards, wheat-based food, allergy EN example "Hey Robot, I would like to eat pizza near Alexanderplatz tonight" included completely outside border crossing smaller and included exact match completely outside border cross... | 323 | en | 0.956874 |
# coding: utf-8
"""
OpenAPI Petstore
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501
The version of the OpenAPI document: 1.0.0
Generated by: https://openapi-generator.tech
"""
... | samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/test/test_child.py | 1,575 | Child unit test stubs
Test Child
This will fail because additional_properties_type is None in ChildAllOf and it must be defined as any type
to allow in the property radio_waves which is not defined in ChildAllOf, it is defined in Grandparent
OpenAPI Petstore
This spec is mainly for testing Petstore server and contains... | 584 | en | 0.877746 |
# Copyright 2020 MONAI Consortium
# 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, s... | monai/handlers/checkpoint_loader.py | 3,676 | CheckpointLoader acts as an Ignite handler to load checkpoint data from file.
It can load variables for network, optimizer, lr_scheduler, etc.
If saving checkpoint after `torch.nn.DataParallel`, need to save `model.module` instead
as PyTorch recommended and then use this loader to load the model.
Args:
load_path: ... | 1,766 | en | 0.801732 |
#pip install flask-bcrypt
from flask_bcrypt import Bcrypt
# Create the Hasher
bcrypt = Bcrypt()
hashed_pass = bcrypt.generate_password_hash('somethingSuperSecret')
print(hashed_pass)
wrong_check = bcrypt.check_password_hash(hashed_pass, 'wrongpass')
print(wrong_check)
right_check = bcrypt.check_password_hash(hashed... | 07-User-Authentication/00-Password-Hashing/Using-Bcrypt.py | 370 | pip install flask-bcrypt Create the Hasher | 42 | en | 0.333513 |
#!/usr/bin/env python3
# ===============================================================================
# NAME: XmlSerializeParser.py
#
# DESCRIPTION: This class parses the XML serializable types files.
#
# USAGE:
#
# AUTHOR: reder
# EMAIL: reder@jpl.nasa.gov
# DATE CREATED : June 4, 2013
#
# Copyright 2013, Califo... | Autocoders/Python/src/fprime_ac/parsers/XmlSerializeParser.py | 10,160 | An XML parser class that uses lxml.etree to consume an XML
serializable type documents. The class is instanced with
an XML file name.
Given a well formed XML file (xml_file), read it and turn it into
a big string.
Return text block string of comment for serializable class.
Returns a list of all imported XML array file... | 1,828 | en | 0.615762 |
from .core import Pool, CatboostError, get_catboost_bin_module, ARRAY_TYPES
from collections import defaultdict
import numpy as np
_catboost = get_catboost_bin_module()
_eval_metric_util = _catboost._eval_metric_util
_get_roc_curve = _catboost._get_roc_curve
_select_threshold = _catboost._select_threshold
def create... | catboost/python-package/catboost/utils.py | 9,452 | Evaluate metrics with raw approxes and labels.
Parameters
----------
label : list or numpy.arrays or pandas.DataFrame or pandas.Series
Object labels.
approx : list or numpy.arrays or pandas.DataFrame or pandas.Series
Object approxes.
metrics : list of strings
List of eval metrics.
weight : list or numpy... | 2,955 | en | 0.473411 |
"""Top-level package for Tinned Python."""
__author__ = """Tom Finill"""
__email__ = 'tomfinill@gmail.com'
__version__ = '0.1.0'
| tinned_python/__init__.py | 130 | Top-level package for Tinned Python. | 36 | en | 0.778082 |
"""
Example code that implements a simple Neural Net predictor
for z_mode, and Gaussian centered at z_mode with base_width
read in fromfile and pdf width set to base_width*(1+zmode).
"""
import numpy as np
# from numpy import inf
import sklearn.neural_network as sknn
from sklearn.preprocessing import StandardScaler
fr... | rail/estimation/algos/sklearn_nn.py | 3,394 | Subclass to implement a simple point estimate Neural Net photoz
rather than actually predict PDF, for now just predict point zb
and then put an error of width*(1+zb). We'll do a "real" NN
photo-z later.
Parameters:
-----------
run_dict: dict
dictionary of all variables read in from the run_params
values in the yam... | 1,120 | en | 0.669015 |
# problem 37
# Project Euler
__author__ = 'Libao Jin'
__date__ = 'July 17, 2015'
def rotateDigits(number):
string = str(number)
rotatedString = string[::-1]
rotatedNumber = int(rotatedString)
return rotatedNumber
def isSymmetrical(number):
rotatedNumber = rotateDigits(number)
if rotatedNumber == number:
ret... | Python/Project.Euler/Answers.Python/36.py | 991 | problem 37 Project Euler | 24 | en | 0.552765 |
"""
Django settings for testapp project.
Generated by 'django-admin startproject' using Django 1.10.6.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import os... | tests/testapp/testapp/settings.py | 4,187 | Django settings for testapp project.
Generated by 'django-admin startproject' using Django 1.10.6.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
Build paths insi... | 996 | en | 0.632209 |
##########################################################################
#
# Copyright (c) 2017, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistribu... | test/IECoreScene/MeshAlgoWindingTest.py | 6,517 | Copyright (c) 2017, Image Engine Design Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions a... | 1,721 | en | 0.895843 |
from sqlalchemy.sql import func as fn
from sqlalchemy import sql
from ..translate import (
SqlTranslator,
extend_base,
sql_scalar,
sql_agg,
win_agg,
win_cumul,
annotate
)
#from .postgresql import PostgresqlColumn, PostgresqlColumnAgg
from .base import SqlColumn, SqlColumnAgg
from . import ... | siuba/sql/dialects/snowflake.py | 2,325 | from .postgresql import PostgresqlColumn, PostgresqlColumnAgg Data ---- Translations ================================================================ Scalar ---- connector has a bug with % see: https://github.com/snowflakedb/snowflake-sqlalchemy/issues/246 TODO: str.contains Window ---- note that the number of decimal ... | 616 | en | 0.58145 |
from __future__ import unicode_literals
from __future__ import absolute_import
if False:
from typing import Type
import six
from smoke_tests.tools.compat import Path
from smoke_tests.tools.package.base_builder import AgentImageBuilder
AMAZONLINUX = "amazonlinux"
UBUNTU = "ubuntu"
ALL_DISTRIBUTION_NAMES = [AMA... | smoke_tests/tools/package/__init__.py | 2,952 | Find agent distribution docker image for smoke testing.
:param distribution: distribution name on which agent package should be installed.
Possible values are in the 'ALL_DISTRIBUTION_NAMES' constant.
:param python_version: Version of the python interpreter in the distribution.
type: (six.text_type, six.text_type) ->... | 396 | en | 0.705398 |
import csv
import sys
from pathlib import Path
sys.path.append(str(Path(__file__).resolve().parent.parent))
from skimage.color import rgb2gray
import numpy as np
from tqdm import tqdm
from tadataka import VisualOdometry, CameraParameters
from tadataka.rigid import exp_se3, log_se3
from tadataka.projection import war... | examples/rgbd_desk.py | 3,095 | dataset format is explained at https://vision.in.tum.de/data/datasets/rgbd-dataset/file_formats intrinsic_camera_calibration_of_the_kinect dataset_root = Path("datasets", "rgbd_dataset_freiburg2_pioneer_360") dataset_root = Path("datasets", "rgbd_dataset_freiburg3_structure_texture_near") TODO not necessary to convert ... | 483 | en | 0.442715 |
DEPS = [
'archive',
'chromium',
'chromium_android',
'depot_tools/bot_update',
'depot_tools/gclient',
'depot_tools/tryserver',
'file',
'recipe_engine/path',
'recipe_engine/platform',
'recipe_engine/properties',
'recipe_engine/python',
'recipe_engine/step',
'trigger',
]
# TODO(phajdan.jr): pro... | scripts/slave/recipe_modules/libyuv/__init__.py | 392 | TODO(phajdan.jr): provide coverage (http://crbug.com/693058). | 61 | en | 0.464153 |
# -*- coding: utf-8 -*-
# Copyright 2017-2018 ICON Foundation
#
# 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 ... | tests/test_prep_manager.py | 2,582 | -*- coding: utf-8 -*- Copyright 2017-2018 ICON Foundation 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 ... | 625 | en | 0.865514 |
# Python function to manipulate OpenFOAM files
# Developer: Jian-Xun Wang (jwang33@nd.edu)
###############################################################################
# system import
import numpy as np
import numpy.matlib
import sys # Add extra path/directory
import os
import os.path as ospt
import shutil
import ... | demo0/foamFileOperation.py | 3,972 | subFunction of readTurbStressFromFile
Using regular expression to select scalar value out
Args:
scalarFile: The directory path of file of scalar
Returns:
resMid: scalar selected;
you need use resMid.group() to see the content.
Function is using regular expression select Vector value out
Args... | 1,045 | en | 0.778491 |
#!/usr/bin/env python3
# Copyright (c) 2014-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test mempool limiting together/eviction with the wallet."""
from test_framework.test_framework import ... | test/functional/mempool_limit.py | 1,981 | Test mempool limiting together/eviction with the wallet.
!/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.create a mempool tx that will be evicted specifically fu... | 466 | en | 0.720152 |
import numpy as np
def evaluate(X: np.ndarray, A: float = 7.0, B: float = 0.1) -> np.ndarray:
"""Non-monotonic Ishigami-Homma three parameter test function:
`f(x) = \sin(x_{1}) + A \sin(x_{2})^2 + Bx^{4}_{3}\sin(x_{1})`
This test function is commonly used to benchmark global sensitivity
me... | src/SALib/test_functions/Ishigami.py | 1,856 | Non-monotonic Ishigami-Homma three parameter test function:
`f(x) = \sin(x_{1}) + A \sin(x_{2})^2 + Bx^{4}_{3}\sin(x_{1})`
This test function is commonly used to benchmark global sensitivity
methods as variance-based sensitivities of this function can be
analytically determined.
See listed references below.
In [2... | 1,381 | en | 0.501432 |
# Copyright 2019 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... | tests/st/ops/gpu/test_resize_nearest_neighbor_op.py | 3,145 | Copyright 2019 Huawei Technologies Co., Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, softw... | 638 | en | 0.810121 |
from typing import Dict, Tuple
import torch
import torch.nn as nn
from neuralhydrology.modelzoo.basemodel import BaseModel
from neuralhydrology.modelzoo.fc import FC
from neuralhydrology.modelzoo.head import get_head
from neuralhydrology.utils.config import Config
class EALSTM(BaseModel):
"""Entity-Aware LSTM (... | neuralhydrology/modelzoo/ealstm.py | 6,511 | Entity-Aware LSTM (EA-LSTM) model class.
This model has been proposed by Kratzert et al. [#]_ as a variant of the standard LSTM. The main difference is that
the input gate of the EA-LSTM is modulated using only the static inputs, while the dynamic (time series) inputs are
used in all other parts of the model (i.e. for... | 2,684 | en | 0.769701 |
import logging
from pathlib import Path
from taskcat._config import Config
from taskcat.iam_policy.policy import CFNPolicyGenerator
LOG = logging.getLogger(__name__)
class GenerateIAMPolicy:
"""
[ALPHA] Introspects CFN Template(s) and generates an IAM policy necessary to successfully launch the template(s)
... | taskcat/_cli_modules/generate_iam_policy.py | 677 | [ALPHA] Introspects CFN Template(s) and generates an IAM policy necessary to successfully launch the template(s) | 112 | en | 0.605976 |
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve.
#
#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... | PaddleRec/gnn/train.py | 6,254 | Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve.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.0Unless required by applicable law or agreed to i... | 585 | en | 0.821144 |
"""
This module provides two implementations for the rod-cutting problem:
1. A naive recursive implementation which has an exponential runtime
2. Two dynamic programming implementations which have quadratic runtime
The rod-cutting problem is the problem of finding the maximum possible revenue
obtainable from a rod of ... | dynamic_programming/rod_cutting.py | 5,903 | Basic checks on the arguments to the rod-cutting algorithms
n: int, the length of the rod
prices: list, the price list for each piece of rod.
Throws ValueError:
if n is negative or there are fewer items in the price list than the length of
the rod
Constructs a top-down dynamic programming solution for the rod-cuttin... | 3,355 | en | 0.805453 |
# Copyright (c) 2020 by Fraunhofer Institute for Energy Economics
# and Energy System Technology (IEE), Kassel. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
from pandapower.plotting.geo import _node_geometries_from_geodata, \
_transform_no... | pandapipes/plotting/geo.py | 2,722 | Converts bus geodata in net from epsg_in to epsg_out
:param net: The pandapower network
:type net: pandapowerNet
:param epsg_in: current epsg projection
:type epsg_in: int, default 4326 (= WGS84)
:param epsg_out: epsg projection to be transformed to
:type epsg_out: int, default 31467 (= Gauss-Krüger Zone 3)
:return: n... | 1,510 | en | 0.553763 |
# -*- coding: UTF-8 -*-
import datetime
import json
from django.contrib.auth.hashers import check_password, make_password
from django.core import serializers
from django.db import connection
from django.http import HttpResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
... | cmdb/views_ajax.py | 19,378 | 新增数据库组
修改数据库组
新增数据库实例
修改数据库实例
新增主机
修改主机
新增主机用户
修改主机用户
-*- coding: UTF-8 -*- from cmdb.models import dbCluster 新增 修改 masterConfigObj.save() 新增 修改 masterConfigObj.save() 新增 修改 masterConfigObj.save() @csrf_exempt def getDbClusterDetailInfo(request): clusterId = request.POST['clus... | 5,069 | en | 0.237085 |
### ###
# Imports #
### ###
import datetime, os, plistlib, struct, sys, itertools
from io import BytesIO
if sys.version_info < (3,0):
# Force use of StringIO instead of cStringIO as the latter
# has issues with Unicode strings
from StringIO import StringIO
try:
FMT_XML = plistlib.FMT_XML
... | Scripts/plist.py | 19,762 | Read or write a binary plist file, following the description of the binary
format. Raise InvalidFileException in case of error, otherwise return the
root object.
see also: http://opensource.apple.com/source/CF/CF-744.18/CFBinaryPList.c
return the size of the next object.
read the object by reference.
May recursively r... | 3,139 | en | 0.805817 |
"""
Utils for AiiDA.
----------------
Utilities for making working against AiiDA a bit easier. Mostly here due to
historical reasons when AiiDA was rapidly developed. In the future most routines
that have now standardized in AiiDA will be removed.
"""
# pylint: disable=import-outside-toplevel
import numpy as np
from p... | aiida_vasp/utils/aiida_utils.py | 4,520 | Get an existing authinfo or None for the given computer and current user.
Load the verdi data click command group for any version since 0.11.
Apply compression or tensile forces to the unit cell.
Assemble a new Dict.
Allow the current user to use the given computer.
Displace a position in the StructureData.
Get current... | 1,009 | en | 0.824488 |
# Fully Written by @HeisenbergTheDanger (Keep credits else gay)
# Permission Seeked By @StarkXD - Approved
import asyncio
import datetime
from telethon import events
from var import Var
from uniborg.util import admin_cmd
from telethon.tl.types import (
DocumentAttributeFilename,
DocumentAttributeSticker,
I... | userbot/plugins/broadcast.py | 8,670 | Fully Written by @HeisenbergTheDanger (Keep credits else gay) Permission Seeked By @StarkXD - Approved Written by @HeisenbergTheDanger Written by @HeisenbergTheDanger | 166 | en | 0.918315 |
import pytest
import sinergym.utils.rewards as R
@pytest.mark.parametrize(
'power,temperatures,month,day,reward,reward_energy,reward_comfort',
[
# Input 1
(
186.5929171535975,
[22.16742570092868],
3,
31,
-0.009329645857679876,
... | tests/test_reward.py | 1,215 | Input 1 Input 2 Input 3 | 23 | my | 0.064841 |
from main import main
from src.common import fill_with
class Arguments:
pass
# latex info
result_structure = '|c|c|c|c|c|c|'
test_structure = '|c|c|c|c|c|c|c|'
table_body = '''
\\begin{center}
\t\\begin{tabular}{%s}
\t\t\\hline \\rowcolor{brown!50}
%s
\t\\end{tabular}
\\end{center}\n
'''
# Util data for b... | test.py | 2,679 | latex info Util data for build the result tables Util data for build the test table n, m, b, t, o, d | 105 | en | 0.281392 |
# Copyright (c) 2021 PaddlePaddle 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 appli... | ppdet/modeling/heads/s2anet_head.py | 42,021 | AnchorGenerator by paddle
S2Anet head
Args:
stacked_convs (int): number of stacked_convs
feat_in (int): input channels of feat
feat_out (int): output channels of feat
num_classes (int): num_classes
anchor_strides (list): stride of anchors
anchor_scales (list): scale of anchors
anchor_ratios ... | 2,813 | en | 0.595265 |
from http.server import HTTPServer, BaseHTTPRequestHandler
from socketserver import ThreadingMixIn
from .redirect import RedirectHandler
import threading
import ssl
__all__ = ['ThreadedServer', 'SecureServer']
class ThreadedServer(ThreadingMixIn, HTTPServer):
protocol_version = 'HTTP/1.1'
def __init__(self,... | serpent_server/server.py | 2,260 | type: threading.Thread | 22 | en | 0.526765 |
# Generated by Django 2.1.3 on 2019-01-07 17:48
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0014_auto_20190107_2251'),
]
operations = [
migrations.DeleteModel(
name='PostPicks',
),
migrations.AddF... | blog/migrations/0015_auto_20190107_2318.py | 483 | Generated by Django 2.1.3 on 2019-01-07 17:48 | 45 | en | 0.754562 |
# Copyright (C) 2008-today The SG++ project
# This file is part of the SG++ project. For conditions of distribution and
# use, please see the copyright notice provided with SG++ or at
# sgpp.sparsegrids.org
# This file is part of SGClass, a program package making use of spatially adaptive sparse grids to solve numeri... | lib/pysgpp/extensions/misc/datasetAnalysis.py | 4,137 | Copyright (C) 2008-today The SG++ project This file is part of the SG++ project. For conditions of distribution and use, please see the copyright notice provided with SG++ or at sgpp.sparsegrids.org This file is part of SGClass, a program package making use of spatially adaptive sparse grids to solve numerical problem... | 1,374 | en | 0.848818 |
"""Entrypoint for the WSGI app (web API)
"""
from . import api
application = api.create_app()
| krcg_api/wsgi.py | 95 | Entrypoint for the WSGI app (web API) | 37 | en | 0.682141 |
"""Utilties for distributed processing"""
import horovod.tensorflow.keras as hvd
def rank():
try:
return hvd.rank()
except ValueError:
return 0
def barrier():
try:
hvd.allreduce([], name='Barrier')
except ValueError:
pass
| CSCS/benchmarks/cosmoflow/implementations/cosmoflow-benchmark/utils/distributed.py | 273 | Utilties for distributed processing | 35 | en | 0.850731 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.