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 |
|---|---|---|---|---|---|---|
"""Build Environment used for isolation during sdist building
"""
import os
from distutils.sysconfig import get_python_lib
from sysconfig import get_paths
from pip._internal.utils.temp_dir import TempDirectory
class BuildEnvironment(object):
"""Creates and manages an isolated environment to install build deps
... | inter/Lib/site-packages/pip-10.0.1-py3.7.egg/pip/_internal/build_env.py | 2,681 | Creates and manages an isolated environment to install build deps
A no-op drop-in replacement for BuildEnvironment
Build Environment used for isolation during sdist building
Note: prefer distutils' sysconfig to get the library paths so PyPy is correctly supported. | 276 | en | 0.897206 |
# Copyright 2022 Aleksandr Soloshenko
#
# 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 ... | recipes/storage.py | 957 | Copyright 2022 Aleksandr Soloshenko Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software ... | 582 | en | 0.859001 |
"""
Django settings for Punyadaan_Website project.
Generated by 'django-admin startproject' using Django 2.2.6.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
im... | Punyadaan_Website/Punyadaan_Website/settings.py | 3,121 | Django settings for Punyadaan_Website project.
Generated by 'django-admin startproject' using Django 2.2.6.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
Build pat... | 998 | en | 0.634952 |
# *- coding: utf-8 -*
# Created by: ZhaoDongshuang
# Created on: 2018/1/27
import unittest
from others.survey import AnonymousSurvey
class TestAnonymousSurvey(unittest.TestCase):
def setUp(self):
question = "What language did you first learn to speak?"
self.my_survey = AnonymousSurvey(question)
... | others/test_survey.py | 833 | *- coding: utf-8 -* Created by: ZhaoDongshuang Created on: 2018/1/27 | 68 | en | 0.863738 |
import unittest, sys
sys.path.extend(['.','..','py'])
import h2o, h2o_cmd, h2o_hosts, h2o_import as h2i
# test some random csv data, and some lineend combinations
class Basic(unittest.TestCase):
def tearDown(self):
h2o.check_sandbox_for_errors()
@classmethod
def setUpClass(cls):
global loc... | py/testdir_single_jvm/notest_parse3.py | 890 | test some random csv data, and some lineend combinations believe the interesting thing is the NaN in the csv | 108 | en | 0.874223 |
import torch
import time
from math import pi
import numpy as np
from os.path import join
from ..utils.tensorboard import Tensorboard
from ..utils.output import progress
from .convergence import Convergence
from ..model.deepmod import DeepMoD
from typing import Optional
def train(model: DeepMoD,
data: torch... | src/multitaskpinn/training/training.py | 25,561 | [summary]
Args:
model (DeepMoD): [description]
data (torch.Tensor): [description]
target (torch.Tensor): [description]
optimizer ([type]): [description]
sparsity_scheduler ([type]): [description]
log_dir (Optional[str], optional): [description]. Defaults to None.
max_iterations (int, option... | 5,299 | en | 0.619098 |
#!/usr/bin/env python3
# Copyright (c) 2015-2018 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 decoding scripts via decodescript RPC command."""
from test_framework.messages import CTransactio... | test/functional/rpc_decodescript.py | 16,756 | Test decoding scripts via RPC command "decoderawtransaction".
This test is in with the "decodescript" tests because they are testing the same "asm" script decodes.
Test decoding scripts via decodescript RPC command.
!/usr/bin/env python3 Copyright (c) 2015-2018 The Bitcoin Core developers Distributed under the MIT so... | 4,851 | en | 0.822789 |
# Copyright 2018, OpenCensus Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... | tests/unit/trace/test_blank_span.py | 5,521 | Copyright 2018, OpenCensus Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software d... | 556 | en | 0.863881 |
import os
import shutil
cur_dir= os.getcwd()
def make_folder(name): #Checks to see if a folder exists, makes it if it doesn't.
if (os.path.exists('.\\'+name)):
return
else:
os.makedirs('.\\'+name)
def notepad(name):
if os.path.exists(os.path.join(cur_dir,name)) == False:... | clean_folder_v4.py | 4,978 | Checks to see if a folder exists, makes it if it doesn't.takes all files in 'others' folders and copies them to current directorylist of files(excluding folders) in current directory, excluding this program and its text filelist of extensions of fileslist of folders that will be createdtakes extension of file using spl... | 723 | en | 0.932549 |
from datetime import datetime, timedelta
from typing import Callable
def create_batch_list(n_batches: int) -> list:
return list(map(lambda x: x, range(1, n_batches + 1)))
def create_batch_dictionary(batch_lst: list, duration_lst: list, expected_finish_lst: list) -> dict:
batch_dict = {batch_lst[i]: (duratio... | ampljit/utils.py | 4,808 | Creates a valid AMPL constraint of the form:
[LaTex]: $start\_time_j+1 >= start\_time_j + duration_j$, $orall j \in BATCH$
:param index: j index where the current constraint should start
:return: single AMPL JIT constraint as a string
Converts a list of datetime objects to strings, according to a certain datetime form... | 2,193 | en | 0.714809 |
from tkinter import messagebox, Tk, Menu, ttk
news = ['Mid Day News', 'Evening News']
features = ['Calling Farmers', 'Round About Ja', 'You and the Law', 'Get the Facts',
'Career Talk', 'Economy and you', 'Arts Page', 'Tourism Roundup',
'Jeep','Jamaica Promise', 'House Matters', 'Jamaica H... | 000-combobox1.py | 1,841 | Update Menu FrameMenu bar with menu optionsUpdate Menu | 54 | id | 0.072632 |
#
# Copyright 2018 Expedia Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | neaps-api/neaps_lib/bootstrap_test.py | 2,995 | docstring
docstring
test for boostrap helper
docstring
docstring
Copyright 2018 Expedia Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unles... | 620 | en | 0.838197 |
# coding: utf-8
# Copyright 2020. ThingsBoard
# #
# 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
# #
# Unl... | tb_rest_client/models/models_pe/url.py | 9,212 | NOTE: This class is auto generated by the swagger code generator program.
Returns true if both objects are equal
URL - a model defined in Swagger
Returns true if both objects are not equal
For `print` and `pprint`
Gets the authority of this URL. # noqa: E501
:return: The authority of this URL. # noqa: E501
:rt... | 3,169 | en | 0.70242 |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import json
from abc import abstractmethod
from argparse import ArgumentParser, Namespace
from typing import Any, List, NamedTuple, Optional, Tuple
from idb.cli.commands.base import TargetCommand
from idb.client.client impo... | idb/cli/commands/file.py | 9,547 | !/usr/bin/env python3 Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. pyre-ignore | 103 | en | 0.820646 |
from __future__ import print_function
import numpy as np
import scipy.linalg
import torch
import torch.nn as nn
import torch.nn.functional as F
from flow_modules.misc import cpd_sum, cpd_mean
def squeeze2d(input, factor=2):
#assert factor >= 1 and isinstance(factor, int)
if factor == 1:
return input
size = inp... | flow_modules/common_modules.py | 6,858 | log-det = log|abs(|W|)| * pixels
assert factor >= 1 and isinstance(factor, int) Sample a random orthogonal matrix:thops.pixels(input) | 134 | en | 0.615233 |
# -*- coding: utf-8 -*-
from __future__ import division
import os
import pytest
from ethereum import _solidity
from ethereum._solidity import compile_file
from ethereum.utils import denoms
from pyethapp.rpc_client import JSONRPCClient
from pyethapp.jsonrpc import default_gasprice
from raiden.network.rpc.client impor... | raiden/tests/integration/test_blockchainservice.py | 9,253 | -*- coding: utf-8 -*- pylint: disable=invalid-name pylint: disable=line-too-long,too-many-statements,too-many-locals sanity create one channel check contract state check channels create other chanel deposit without approve should fail single-funded channel double-funded channel required to start the geth backend pylint... | 534 | en | 0.794028 |
# coding: utf-8
from __future__ import absolute_import
from __future__ import print_function
import warnings
from ruamel.yaml.error import MarkedYAMLError, ReusedAnchorWarning
from ruamel.yaml.compat import utf8
from ruamel.yaml.events import (
StreamStartEvent, StreamEndEvent, MappingStartEvent, MappingEndEven... | ios/dateparser/lib/python2.7/site-packages/ruamel/yaml/composer.py | 6,919 | coding: utf-8 Drop the STREAM-START event. If there are more documents available? Get the root node of the next document. Drop the STREAM-START event. Compose a document if the stream is not empty. Ensure that the stream contains no more documents. Drop the STREAM-END event. Drop the DOCUMENT-START event. Compose the r... | 904 | en | 0.695457 |
import argparse
import locale
import sys
from datetime import datetime
from model import *
from sql import *
from common import *
from util import *
def parse_arguments():
'''
Parse input arguments. Passing the API key is defined as mandatory.
'''
parser = argparse.ArgumentParser(description='... | scripts/orders-exporter.py | 2,556 | Parse input arguments. Passing the API key is defined as mandatory.
load or refresh the customer table for enrichment looking up the customers for successive enrichment of orders | 180 | en | 0.850355 |
# -*- coding: utf-8 -*-
import QUANTAXIS as QA
from QUANTAXIS.QAFetch import QATusharePro as pro
import pandas as pd
import numpy as np
from pyspark.sql.functions import pandas_udf, PandasUDFType
from pyspark import SparkContext,SparkConf
from pyspark.sql.session import SparkSession
from QUANTAXIS.ML import RegUtil
fro... | EXAMPLE/test_backtest/example/indicator/simple_valued_spark2.py | 9,180 | -*- coding: utf-8 -*-from pyspark.sql.functions importspark.sparkContext.setLogLevel("INFO") fit, p4 = RegUtil.regress_y_polynomial(resample[-8:].q_opincome_ttm, poly=3, show=False)print(indicator.loc[index])df = basic.join(stock_spark, basic.ts_code==stock_spark.ts_code, "inner")industry_daily.count()print(p3)print(df... | 783 | en | 0.302077 |
# (C) Datadog, Inc. 2021-present
# All rights reserved
# Licensed under Simplified BSD License (see LICENSE)
import pytest
from datadog_checks.postgres.relationsmanager import ALL_SCHEMAS, IDX_METRICS, LOCK_METRICS, RelationsManager
from .common import SCHEMA_NAME
pytestmark = pytest.mark.unit
@pytest.mark.paramet... | postgres/tests/test_relationsmanager.py | 3,835 | (C) Datadog, Inc. 2021-present All rights reserved Licensed under Simplified BSD License (see LICENSE) relkind ignored relkind ignored | 134 | en | 0.782507 |
"""Common classes and elements for Omnilogic Integration."""
from datetime import timedelta
import logging
from omnilogic import OmniLogicException
from homeassistant.const import ATTR_NAME
from homeassistant.core import HomeAssistant
from homeassistant.helpers.update_coordinator import (
CoordinatorEntity,
... | homeassistant/components/omnilogic/common.py | 4,485 | Defines the base OmniLogic entity.
Class to manage fetching update data from single endpoint.
Initialize the global Omnilogic data updater.
Initialize the OmniLogic Entity.
Define the device as back yard/MSP System.
Return the attributes.
Get data per kind of Omnilogic API item.
Return the icon for the entity.
Return t... | 466 | en | 0.742546 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.20 on 2019-03-20 21:25
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('librarian', '0108_dataset_is_external_missing'),
]
operations = [
migratio... | kive/librarian/migrations/0109_dataset_is_uploaded.py | 528 | -*- coding: utf-8 -*- Generated by Django 1.11.20 on 2019-03-20 21:25 | 69 | en | 0.56822 |
"""
MODULE : code_generation.py
Purpose : * Class for parsing the text and launching the basic block algorithm.
Also houses the code generation algorithm
"""
# List of Imports Begin
import debug as DEBUG
import instr3ac as INSTRUCTION
import basic_blocks as BB
import mips_assembly as ASM
import global_... | project/src/codegen/code_generation.py | 3,762 | This class houses the basic-block generation and code-generation algorithm
Member Variables:
* instructions : Stores all the program instructions
* basicBlocks : Stores all the basic blocks
* targets : Which line IDs are goto targets. Used for basic block algorithm
Generate basic bloc... | 893 | en | 0.832025 |
# terrascript/provider/alertmixer/amixr.py
# Automatically generated by tools/makecode.py (24-Sep-2021 15:11:40 UTC)
import terrascript
class amixr(terrascript.Provider):
""""""
__description__ = ""
__namespace__ = "alertmixer"
__name__ = "amixr"
__source__ = "https://github.com/alertmixer/terra... | terrascript/provider/alertmixer/amixr.py | 457 | terrascript/provider/alertmixer/amixr.py Automatically generated by tools/makecode.py (24-Sep-2021 15:11:40 UTC) | 112 | en | 0.50749 |
#!/usr/bin/env python
# not used in this project.
import sys
sys.path.append('../gen-py')
from EyePi.ttypes import EyePiInput
from EyePi.ttypes import ConfirmInput
from GenericStruct.ttypes import ActionEnum
from WeatherPi.ttypes import WeatherInput
from ConnectionHelpers.DeviceRegistrator import DeviceRegistrator
... | 1IntegrationTests/py-impl/PythonEyePiClient.py | 2,287 | !/usr/bin/env python not used in this project. test test end test mock! normally a device would properly register itself and keep the token. But in development case, the cahce is resetted every time. This mock registers the device. end mock parameter = GenericObject()parameter.stringValue = "%s" % 'Amsterdam,nl'input.... | 381 | en | 0.575895 |
import json
from copy import deepcopy
from time import time
from asynctest import TestCase as AsyncTestCase
from asynctest import mock as async_mock
from .....core.in_memory import InMemoryProfile
from .....indy.holder import IndyHolder
from .....indy.sdk.holder import IndySdkHolder
from .....indy.issuer import Indy... | aries_cloudagent/protocols/present_proof/v2_0/tests/test_manager.py | 62,091 | leave this comma: return a tuple simulate interop with indy-vcx leave this comma: return a tuple exercise superfluous timestamp removal leave this comma: return a tuple leave this comma: return a tuple cover by_format property cover out-of-band mismatch vs request mismatch vs request mismatch vs request propose >= 8 mi... | 357 | en | 0.768071 |
# Script that cuts the greet string into chunks and prints it out
greet = "Hello World!"
print(greet)
print("Start: ", greet[0:3])
print("Middle: ", greet[3:6])
print("End: ", greet[-3:])
a = greet.find(",")
print("Portion before comma", greet[:a])
| Python/CTF/greet.py | 253 | Script that cuts the greet string into chunks and prints it out | 63 | en | 0.840945 |
# -*- coding: utf-8 -*-
""" NETWORK
This module defines the BlendHunter class which can be used to retrain the
network or use predefined weights to make predictions on unseen data.
:Author: Samuel Farrens <samuel.farrens@cea.fr>
"""
import os
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns... | blendhunter/network.py | 21,130 | BlendHunter
Class for identifying blended galaxy images in postage stamps.
Parameters
----------
image_shape : tuple, optional
Expected shape of input images
classes : tuple, optional
List of classes, default is ('blended', 'not_blended')
weights_path : str, optional
Path to weights, default is './weights... | 5,034 | en | 0.443542 |
"""
TimeSeries is a generic time series class from which all other TimeSeries
classes inherit from.
"""
import copy
import warnings
from collections import OrderedDict
import pandas as pd
import matplotlib.pyplot as plt
import astropy
import astropy.units as u
from astropy.table import Table, Column
from sunpy impor... | sunpy/timeseries/timeseriesbase.py | 20,906 | A generic time series object.
Parameters
----------
data : `~pandas.DataFrame`
A pandas DataFrame representing one or more fields as a function
of time.
meta : `~sunpy.timeseries.metadata.TimeSeriesMetaData`, optional
The metadata giving details about the time series data/instrument.
units : dict, optional... | 9,973 | en | 0.629459 |
# 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... | keras/engine/base_preprocessing_layer_test.py | 8,358 | This is an example of how a subclass would implement a direct setter.
Args:
sum_value: The total to set.
Test that non-Dataset/Numpy inputs cause a reasonable error.
Check that `.adapt()` doesn't change the `input_shape`.
Test that calling adapt leads to a runtime error.
Test that preproc layers fail if an infinite ... | 1,723 | en | 0.852922 |
# 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... | superset/migrations/versions/ca69c70ec99b_tracking_url.py | 1,240 | tracking_url
Revision ID: ca69c70ec99b
Revises: a65458420354
Create Date: 2017-07-26 20:09:52.606416
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 li... | 895 | en | 0.830723 |
"""An abstract class for entities."""
from __future__ import annotations
from abc import ABC
import asyncio
from collections.abc import Awaitable, Iterable, Mapping, MutableMapping
from dataclasses import dataclass
from datetime import datetime, timedelta
from enum import Enum, auto
import functools as ft
import loggi... | homeassistant/helpers/entity.py | 35,681 | Entity device information for device registry.
An abstract class for Home Assistant entities.
Category of an entity.
An entity with a category will:
- Not be exposed to cloud, Alexa, or Google Assistant components
- Not be included in indirect service calls to devices or areas
A class that describes Home Assistant ent... | 6,649 | en | 0.837572 |
from operator import attrgetter
import pyangbind.lib.xpathhelper as xpathhelper
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType
from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType
from pyangbind.lib.base import PybindBase
from d... | pybind/slxos/v17s_1_02/routing_system/router/router_bgp/address_family/ipv4/ipv4_unicast/default_vrf/neighbor/af_ipv4_neighbor_peergroup_holder/af_ipv4_neighbor_peergroup/prefix_list/direction_out/__init__.py | 11,018 | This class was auto-generated by the PythonClass plugin for PYANG
from YANG module brocade-common-def - based on the path /routing-system/router/router-bgp/address-family/ipv4/ipv4-unicast/default-vrf/neighbor/af-ipv4-neighbor-peergroup-holder/af-ipv4-neighbor-peergroup/prefix-list/direction-out. Each member element of... | 2,146 | en | 0.637764 |
import os
import pytest
import radical.utils as ru
import radical.pilot as rp
import radical.pilot.constants as rpc
from radical.pilot.agent.scheduler.hombre import Hombre
try:
import mock
except ImportError:
from tasktest import mock
# -----------------------------------------------... | old_tests/test_hombre_scheduler.py | 9,426 | ------------------------------------------------------------------------------ User Input for test Sample data to be staged -- available in cwd ------------------------------------------------------------------------------ Setup for every test ----------------------------------------------------------------------------... | 1,667 | en | 0.653575 |
import pytest
from app.models.user import User
from datetime import date
@pytest.fixture(scope='module')
def new_user():
user = User('test', date(day=1, month=12, year=1989))
return user
def test_new_user(new_user):
"""
GIVEN a User model
WHEN a new User is created
THEN check the username a... | tests/unit/test_app.py | 469 | GIVEN a User model
WHEN a new User is created
THEN check the username and birthday fields are defined correctly | 111 | en | 0.884328 |
class BitVector:
"""
This class uses an int called dec_rep as a vector of self.len many bits,
where self.len <= self.max_len. The class wraps some common bitwise
operations, and some less common ones too (like Gray coding that is
needed by Qubiter). In some cases, the bitwise manipulation might be
... | qubiter/BitVector.py | 10,094 | This class uses an int called dec_rep as a vector of self.len many bits,
where self.len <= self.max_len. The class wraps some common bitwise
operations, and some less common ones too (like Gray coding that is
needed by Qubiter). In some cases, the bitwise manipulation might be
more succinct than the corresponding funct... | 4,548 | en | 0.682445 |
import os
import os.path as osp
import pickle
import random
from collections import deque
from datetime import datetime
import gym
import numpy as np
import scipy.stats as stats
import torch
import torch.optim as optim
from mpi4py import MPI
import dr
from dr.ppo.models import Policy, ValueNet
from dr.ppo.train impor... | dr/experiment/ppo_pytorch.py | 12,063 | Creates an instance of this class.
Arguments:
sol_dim (int): The dimensionality of the problem space
max_iters (int): The maximum number of iterations to perform during optimization
popsize (int): The number of candidate solutions to be sampled at every iteration
num_elites (int): The number of top solu... | 1,917 | en | 0.802346 |
#!/usr/bin/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
# "Licens... | testutils/gen-report.py | 8,187 | !/usr/bin/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 may ... | 1,277 | en | 0.890792 |
from terminusdb_client.woqlclient.api_endpoint_const import APIEndpointConst
from .connectCapabilitiesResponse import ConnectResponse
from .getSchemaTurtleResponse import RESPONSE
def mocked_requests(*args, **kwargs):
class MockResponse:
def json(self):
if self._json_data is None:
... | terminusdb_client/tests/mockResponse.py | 2,655 | set status code and content add json data if provided elif action_type == APIEndpointConst.WOQL_SELECT: with open("tests/getAllClassQueryResponse.json") as json_file: json_data = json.load(json_file) self._json_data = json_data json_file.close() | 259 | en | 0.302904 |
################################################################################
#
# Author: Diego Montufar
# Date: Apr/2015
# Name: __init__.py
# Description: Here we define the available web services which can be accessed by
# following the app.route path as URL. The inde... | web/__init__.py | 13,774 | Author: Diego Montufar Date: Apr/2015 Name: __init__.py Description: Here we define the available web services which can be accessed by following the app.route path as URL. The indexer module will perform the hard work as it communicates directly with the ... | 7,689 | en | 0.657561 |
# reference_metric.py: Define all needed quantities
# for a reference metric.
# Given uniform (reference metric) coordinate
# (xx[0],xx[1],xx[2]), you must define:
# 1) xxmin[3],xxmax[3]: Valid ranges for each
# uniform coordinate xx0,xx1,xx2
# 2) xxSph[3]: Spherical coordinate (r,theta,phi),
# ... | reference_metric.py | 78,025 | reference_metric.py: Define all needed quantities for a reference metric. Given uniform (reference metric) coordinate (xx[0],xx[1],xx[2]), you must define: 1) xxmin[3],xxmax[3]: Valid ranges for each uniform coordinate xx0,xx1,xx2 2) xxSph[3]: Spherical coordinate (r,theta,phi), in terms of u... | 14,064 | en | 0.775683 |
import os
import numpy as np
import random
from nn_activations import sigmoid, sigmoid_prime
class NeuralNetwork(object):
def __init__(self, sizes=list(), learning_rate=1.0, mini_batch_size=16,
epochs=10):
"""Initialize a Neural Network model.
Parameters
----------
... | src/nn_model.py | 7,693 | Initialize a Neural Network model.
Parameters
----------
sizes : list, optional
A list of integers specifying number of neurns in each layer. Not
required if a pretrained model is used.
learning_rate : float, optional
Learning rate for gradient descent optimization. Defaults to 1.0
mini_batch_size : int,... | 2,623 | en | 0.737514 |
import numpy as np
import logging
import os, errno
from datetime import datetime
from ..abstract import Environment
from maddux.environment import Environment
from maddux.objects import Ball
from maddux.robots import simple_human_arm
class RobotArm(Environment):
def __init__(self, env, training_directory, config):
... | environments/robot_arm/robot_arm.py | 2,909 | Move end effector to the given location
Return the inputs for the neural network
Complete any pending post processing tasks
Complete any pending post processing tasks
Reset current position to beginning.
Return the parameters for the proposed reward function
self.recording_queue = [] self.recording_queue.append(recor... | 625 | en | 0.586537 |
"""
This module enables the clustering of DataFrame headers into
like clusters based on correlations between columns
"""
from typing import List
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import scipy.cluster.hierarchy as sch
from gretel_synthetics.utils import stats
LEFT = 0
RIGHT = 1
... | src/gretel_synthetics/utils/header_clusters.py | 6,262 | Given an input dataframe, extract clusters of similar headers
based on a set of heuristics.
Args:
df: The dataframe to cluster headers from.
header_prefix: List of columns to remove before cluster generation.
maxsize: The max number of header clusters to generate
from the input dataframe.
metho... | 1,927 | en | 0.749574 |
"""
Plugin architecture, based on decorators
References:
1. https://play.pixelblaster.ro/blog/2017/12/18/a-quick-and-dirty-mini-plugin-system-for-python/
"""
| src/colusa/plugins/__init__.py | 163 | Plugin architecture, based on decorators
References:
1. https://play.pixelblaster.ro/blog/2017/12/18/a-quick-and-dirty-mini-plugin-system-for-python/ | 154 | en | 0.586155 |
# Generated by Django 2.2.10 on 2020-03-20 15:01
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import src.auth.models
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0011_updat... | src/auth/migrations/0001_initial.py | 3,291 | Generated by Django 2.2.10 on 2020-03-20 15:01 | 46 | en | 0.558844 |
import os
# system parameters
GPUS = [0]
DATALOADER_WORKERS = 8
# optimization parameters
BATCH_SIZE = 1
EPOCHS = 50
LR = 0.0001
WEIGHT_DECAY = 0.0005
MOMENTUM = 0.9
# image pre-processing parameters
GAUSSIAN_VALUE = 0
# directory locations
HOME_DIR = "/home/mbc2004"
DATASET_DIR = "/home/mbc2004/datasets"
MODEL_SRC... | parameter_parser.py | 9,411 | system parameters optimization parameters image pre-processing parameters directory locations input parameters 16 number of epochs to run experiments for ? ? models models Activity Recognition Dataset models Activity Recognition Dataset models Activity Recognition Dataset models1024 | 283 | en | 0.464905 |
# coding: utf-8
"""
FlashArray REST API
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: 2.5
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re
import six
import typing
from .... | pypureclient/flasharray/FA_2_5/models/policy_rule_smb_client_get_response.py | 4,971 | Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
Returns true if both objects are equal
Keyword args:
more_items_remaining (bool): ... | 1,815 | en | 0.725833 |
from util.dc_verilog_parser import *
def main():
folder = "../dc/sub/adder8/"
# folder = "../dc/boom/implementation/"
total_nodes = 0
total_edges = 0
ntype = set()
for v in os.listdir(folder):
if v.startswith("hier"):
continue
vf = os.path.join(folder, v)
pri... | util1/find_central.py | 1,441 | folder = "../dc/boom/implementation/" parser = DcParser("BoomCore", ["alu_DP_OP", "add_x"]) nodes, edges = parser.clip(nodes, edges) return dc_parser("../dc/simple_alu/implementation/alu_d0.20_r2_bounded_fanout_adder.v") cProfile.run("main()") | 243 | en | 0.344818 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('tablo', '0003_auto_20160106_1509'),
]
operations = [
migrations.CreateModel(
name='FeatureServiceLayerRelations'... | tablo/migrations/0004_featureservicelayerrelations.py | 831 | -*- coding: utf-8 -*- | 21 | en | 0.767281 |
# Library of fault injection functions called at runtime for common operations in TensorFlow
# NOTE: These are called by the corresponding functions inserted in the TensorFlow graph at RUNTIME
import tensorflow as tf
import numpy as np
import logging
from fiConfig import *
from fiLog import *
from threading import c... | TensorFI/injectFault.py | 42,780 | Library of fault injection functions called at runtime for common operations in TensorFlow NOTE: These are called by the corresponding functions inserted in the TensorFlow graph at RUNTIME FIXME: Add this to the list of dependencies for this module global variable to determine fine grained levels of logging WARNING: Se... | 9,998 | en | 0.800784 |
import glob
import yaml
import os
from generators import intermediate_files
from schema import cleaner
# This script takes all ECS and custom fields already loaded, and lets users
# filter out the ones they don't need.
def filter(fields, subset_file_globs, out_dir):
subsets = load_subset_definitions(subset_file_... | scripts/schema/subset_filter.py | 5,215 | Merges N subsets into one. Strips top level 'name' and 'fields' keys as well as non-ECS field options since we can't know how to merge those.
Accepts an array of glob patterns or file names, returns the array of actual files
Removes fields that are not in the subset definition. Returns a copy without modifying the inpu... | 1,004 | en | 0.887698 |
# Copyright 2020 The Kubric Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... | kubric/renderer/blender.py | 19,312 | Copyright 2020 The Kubric Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software di... | 2,407 | en | 0.762313 |
"""
config_objects.py
By: John-Michael O'Brien
Date: 7/25/2020
Data structures that define and load configuration information for the
wallpaper watcher.
"""
from typing import List, Dict, Optional
from dataclasses import dataclass, field
import jsons
import yaml
@dataclass
class SubredditConfig():
""" Holds any ... | config_objects.py | 2,051 | Holds information necessary to access a multireddit
Holds Reddit Authentication Values
Holds a size
Holds information about image sources
Holds any per-subreddit configuration. That's nothing right now.
Holds information about a save target
Loads and holds the configuration for wallpaperwatcher.
Creates a Wallpa... | 540 | en | 0.836282 |
# Copyright 2021 Research Institute of Systems Planning, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | ros2caret/verb/message_flow.py | 1,926 | Copyright 2021 Research Institute of Systems Planning, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed ... | 625 | en | 0.85054 |
# -*- coding: utf-8 -*-
"""
unifonicnextgen
This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ).
"""
class GetScheduledMessageResponse(object):
"""Implementation of the 'Get Scheduled Message response' model.
GetsDetails of specified scheduled message, If Me... | unifonicnextgen/models/get_scheduled_message_response.py | 2,336 | Implementation of the 'Get Scheduled Message response' model.
GetsDetails of specified scheduled message, If MessageID is specified,
only one message is returned,Otherwise all messages(paginated) are
queried.
Attributes:
success (bool): The request sent successfully
message (string): The Error message if its ... | 1,179 | en | 0.73284 |
# Copyright 2019, OpenCensus Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... | contrib/opencensus-ext-pymongo/setup.py | 2,022 | Copyright 2019, OpenCensus Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software d... | 572 | en | 0.857359 |
# encoding: utf-8
import json
from .. import (
DatabaseTest,
sample_data
)
from lxml import etree
from core.coverage import CoverageFailure
from core.model import Contributor, Identifier, Measurement
from core.metadata_layer import *
from oclc.classify import (
IdentifierLookupCoverageProvider,
OCLCCla... | tests/oclc_/test_identifier_lookup_coverage_provider.py | 14,426 | encoding: utf-8 Testing that, when process_item finds out that a document's status code is 2, it calls _single, passes in the correct tree and blank metadata object as arguments, and returns the original ISBN. Uses mocked versions of _get_tree, initial_look_up, and _single. Testing that, when process_item finds out th... | 2,673 | en | 0.909203 |
from django.shortcuts import redirect, render
from django.views.generic import TemplateView
from ..models import Student
class SignUpView(TemplateView):
template_name = 'registration/signup.html'
def home(request):
if request.user.is_authenticated:
if request.user.is_teacher:
return redir... | django_school/classroom/views/classroom.py | 794 | avatar_url = response.get('avatar_url') print(user, response) | 61 | en | 0.324966 |
import pytorchresearch as ptr
import torch
import torchvision
if __name__ == "__main__":
# transform for data
transform = torchvision.transforms.Compose([
torchvision.transforms.ToTensor(),
torchvision.transforms.Normalize(
mean=(0.485, 0.456, 0.406),
std=(0.229, 0.224... | docs/example_1/back.py | 1,851 | transform for data dataloaders model specific stuff MAGIC GOES HERE | 67 | en | 0.62338 |
from django.db.models import Q
from .base import EntityType
TYPE_VIDEO = "video"
class VideoEntity(EntityType):
name = TYPE_VIDEO
@classmethod
def filter_date_lte(cls, qs, dt):
return qs.filter(publication_date__lte=dt)
@classmethod
def filter_date_gte(cls, qs, dt):
return qs.f... | backend/tournesol/entities/video.py | 809 | Filtering in a nested queryset is necessary here, to be able to annotate each entity without duplicated scores, due to the m2m field 'tags'. | 140 | en | 0.790369 |
import logging
import random
import time
from jobcontrol.exceptions import SkipBuild
def job_simple_echo(*args, **kwargs):
return (args, kwargs)
_cached_words = None
def _get_words():
global _cached_words
if _cached_words is not None:
return _cached_words
try:
with open('/usr/sh... | jobcontrol/utils/testing.py | 6,684 | Log handler that records messages
Simple job, "echoing" back the current configuration.
This job will fail exactly once; retry will be successful
Job used for testing purposes.
:param progress_steps:
A list of tuples: ``(<group_name>, <steps>)``, where "group_name"
is a tuple of name "levels", "steps" an integ... | 881 | en | 0.866576 |
"""
Django settings for HedgeFund project.
Generated by 'django-admin startproject' using Django 3.2.8.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
from pathl... | HedgeFund/base.py | 3,717 | Django settings for HedgeFund project.
Generated by 'django-admin startproject' using Django 3.2.8.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
Build paths insid... | 1,084 | en | 0.663226 |
"""
SleekXMPP: The Sleek XMPP Library
Copyright (C) 2013 Nathanael C. Fritz, Lance J.T. Stout
This file is part of SleekXMPP.
See the file LICENSE for copying permission.
"""
from sleekxmpp.jid import JID
from sleekxmpp.xmlstream import ElementBase, register_stanza_plugin
class NoSave(ElementBase):
... | sleekxmpp/plugins/google/nosave/stanza.py | 1,474 | SleekXMPP: The Sleek XMPP Library
Copyright (C) 2013 Nathanael C. Fritz, Lance J.T. Stout
This file is part of SleekXMPP.
See the file LICENSE for copying permission. | 167 | en | 0.776362 |
from sklearn.model_selection import cross_val_score
import pandas as pd
import matplotlib.pyplot as plt
def CrossValidationFolds_Traversal(estimator, vdataset):
"""
Arguments:
- estimator = classifer of model
- vdataset = vehicld dataset
This function computes acccuracy score w... | dev/shiza16/Calibration plot/CrossValidationFold_Traversal.py | 1,598 | Arguments:
- estimator = classifer of model
- vdataset = vehicld dataset
This function computes acccuracy score with the
Cross Validation Score for each KFold with K from 2 to 10
Output:
returns matrix conatining value of K with it's corresponding performance score
Argument:
- matrix: Datafram... | 465 | en | 0.845071 |
#!/usr/bin/env python
import os
import sys
def addPath(rel_path, prepend=False):
""" Adds a directory to the system python path, either by append (doesn't
override default or globally installed package names) or by prepend
(overrides default/global package names).
"""
path = lambda *paths: os.path.... | example/manage.py | 1,003 | Adds a directory to the system python path, either by append (doesn't
override default or globally installed package names) or by prepend
(overrides default/global package names).
!/usr/bin/env python Allow us to not include `djoauth2example` when importing subapps. Use the local version of the `djoauth2` library; ver... | 413 | en | 0.778489 |
# TODO: your agent here!
import numpy as np
from agents.actor import Actor
from agents.critic import Critic
from agents.buffer import ReplayBuffer
from agents.ou_noise import OUNoise
class DDPG():
"""Reinforcement Learning agent that learns using DDPG."""
def __init__(self, task):
self.task = task
... | home/agents/agent.py | 5,387 | Reinforcement Learning agent that learns using DDPG.
Returns actions for given state(s) as per current policy.
Update policy and value parameters using given batch of experience tuples.
Soft update model parameters.
TODO: your agent here! Actor (Policy) Model Critic (Value) Model Initialize target model parameters wi... | 1,054 | en | 0.715347 |
# -*- coding: utf-8 -*-
"""PageParser tests."""
import httpx # noqa: F401
import pytest
from core.database import ProductGinoModel
from core.services import get_product_name
pytestmark = [pytest.mark.asyncio, pytest.mark.api_full]
API_URL_PREFIX = "/api/v1"
@pytest.fixture
def no_css_response() -> bytes:
min... | backend/tests/test_page_parser.py | 6,070 | PageParser api response tests.
Page Parser core tests.
PageParser tests.
-*- coding: utf-8 -*- noqa: F401 noqa: E501 noqa: E501 noqa: E501 noqa: E501 noqa: E501 | 162 | en | 0.275227 |
#
# Copyright 2019 The FATE 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... | fate_flow/utils/setting_utils.py | 3,165 | Copyright 2019 The FATE 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 applicable law or agreed t... | 584 | en | 0.870336 |
import os
from easydict import EasyDict
import torch
# architecture
from basicts.archs.DCRNN_arch import DCRNN
# runner
from basicts.runners.DCRNN_runner import DCRNNRunner
from basicts.data.base_dataset import BaseDataset
from basicts.metrics.mae import masked_mae
from basicts.metrics.mape import masked_mape
from bas... | basicts/options/DCRNN/DCRNN_PEMS07.py | 3,680 | architecture runner DCRNN does not allow to load parameters since it creates parameters in the first iteration ================= general ================= ================= environment ================= ================= model ================= traffic speed, time in day traffic speed ================= optim ======... | 642 | en | 0.430274 |
import pylab as pl
import numpy as np
from os import path
from numpy import abs, linspace, sin, pi, int16
import pandas
def plotfft(s, fmax, doplot=False):
""" This functions computes the fft of a signal, returning the frequency
and their magnitude values.
Parameters
----------
s: ar... | novainstrumentation/tools.py | 4,240 | :rtype : numpy matrix
@brief This function loads a file from the current directory and saves
the cached file to later executions. It's also possible to make a recache
or a subsampling of the signal and choose only a few columns of the signal,
to accelerate the opening process.
@param file String: the name of the file ... | 1,623 | en | 0.611991 |
# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2018-09-26 01:53
from __future__ import unicode_literals
import ckeditor.fields
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('posts', '0001_initial'),
]
operations = [
migrations.AlterField... | src/apps/posts/migrations/0002_auto_20180926_0953.py | 471 | -*- coding: utf-8 -*- Generated by Django 1.9 on 2018-09-26 01:53 | 65 | en | 0.678327 |
import os
import copy
import pytest
from jikken.api import Experiment
import git
@pytest.fixture(autouse=True, scope='module')
def experiment_setup(tmpdir_factory):
expected_variables = {
"training_parameters":
{"batch_size": 100,
"algorithm": "Seq2Seq",
"attention": ... | tests/unit/test_experiment.py | 6,425 | test schema with parameters is constructed properly
test schema is constructed properly
test tags are initialized properly and are not settable
test variables are initialized properly and are not settable
Given some variables and tags When I create an experiment And another one with teh same inputs Then they are equ... | 630 | en | 0.838765 |
# Copyright © 2020 Hashmap, Inc
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... | hdm/core/orchestrator/declared_orchestrator.py | 2,843 | This is an orchestrator which build DataLinks and will run them as defined - they must be fully defined.
Copyright © 2020 Hashmap, Inc Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www... | 728 | en | 0.898403 |
# Copyright 2020 The StackStorm Authors.
# Copyright 2019 Extreme Networks, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless ... | st2common/tests/unit/test_logger.py | 17,270 | Test that AUDIT log entry goes to the audit log.
Test that CRITICAL log entry does not go to the audit log.
Test that INFO log entry does not go to the audit log.
Copyright 2020 The StackStorm Authors. Copyright 2019 Extreme Networks, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not us... | 1,203 | en | 0.855466 |
import os
from enum import IntEnum
from typing import Dict, Union, Callable, List, Optional
from cereal import log, car
import cereal.messaging as messaging
from common.conversions import Conversions as CV
from common.realtime import DT_CTRL
from selfdrive.locationd.calibrationd import MIN_SPEED_FILTER
from selfdrive.... | selfdrive/controls/lib/events.py | 29,631 | Alert priorities Event types get event name from enum less harsh version of SoftDisable, where the condition is user-triggered ********** helper functions ********** ********** alert callback functions ********** ********** events with no alerts ********** ********** events only containing alerts displayed in all state... | 4,505 | en | 0.919831 |
import copy
import rdtest
import renderdoc as rd
class D3D11_Vertex_Attr_Zoo(rdtest.TestCase):
demos_test_name = 'D3D11_Vertex_Attr_Zoo'
def check_capture(self):
draw = self.find_draw("Draw")
self.check(draw is not None)
self.controller.SetFrameEvent(draw.eventId, False)
# ... | util/test/tests/D3D11/D3D11_Vertex_Attr_Zoo.py | 3,474 | Make an output so we can pick pixels | 36 | en | 0.746406 |
"""
Django settings for orders project.
Generated by 'django-admin startproject' using Django 3.0.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
import os
# Bu... | services/orders/orders/settings.py | 3,203 | Django settings for orders project.
Generated by 'django-admin startproject' using Django 3.0.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
Build paths inside the... | 985 | en | 0.682944 |
# emacs: -*- mode: python; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*-
# ex: set sts=4 ts=4 sw=4 et:
# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# See COPYING file distributed along with the datalad package for the
# copyright and license terms.
#
# ## ### ### ... | datalad/customremotes/tests/test_archives.py | 10,912 | Return stats on the file which should have been preserved
Tests for customremotes archives providing dl+archive URLs handling
emacs: -*- mode: python; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*- ex: set sts=4 ts=4 sw=4 et: See COPYING file distributed along with the datalad pack... | 2,681 | en | 0.864916 |
# Copyright 2015 Hewlett-Packard Development Company, L.P.
#
# Author: Endre Karlson <endre.karlson@hp.com>
#
# 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/lice... | designate/storage/impl_sqlalchemy/migrate_repo/versions/054_allow_duplicate_domains.py | 1,837 | Copyright 2015 Hewlett-Packard Development Company, L.P. Author: Endre Karlson <endre.karlson@hp.com> 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 U... | 649 | en | 0.816102 |
from flask import Flask, jsonify, request, render_template, redirect, url_for
import datetime
from alarm import AlarmService
app = Flask(__name__, static_url_path='/static')
app.config.from_pyfile('config.py')
# status file for motion detection
motionfile = "motion.txt"
# enable temperature sensor (if library is ava... | web/home.py | 3,547 | write command into file - pass enable/disable command
status file for motion detection enable temperature sensor (if library is available) alarmOn = True, update time read temperature (if sensor is available) read status of PIR sensor take snapshot of webcam (max 1 per minute) print "turn switch '%s' to '%s' - device... | 366 | en | 0.697155 |
"""Support for RFXtrx lights."""
import logging
import RFXtrx as rfxtrxmod
from homeassistant.components.light import (
ATTR_BRIGHTNESS,
SUPPORT_BRIGHTNESS,
LightEntity,
)
from homeassistant.const import CONF_DEVICES, STATE_ON
from homeassistant.core import callback
from . import (
CONF_AUTOMATIC_ADD... | homeassistant/components/rfxtrx/light.py | 4,813 | Representation of a RFXtrx light.
Apply command from rfxtrx.
Check if event applies to me and update.
Return the brightness of this light between 0..255.
Return true if device is on.
Handle light updates from the RFXtrx gateway.
Flag supported features.
Support for RFXtrx lights.
Add switch from config file Subscribe... | 342 | en | 0.819647 |
# TODO:
#
# A handler/formatter that can replace django.utils.log.AdminEmailHandler
#
# Needed:
# * A dump of locals() on each affected line in the stacktrace
| src/humiologging/handlers/django.py | 159 | TODO: A handler/formatter that can replace django.utils.log.AdminEmailHandler Needed: * A dump of locals() on each affected line in the stacktrace | 146 | en | 0.707636 |
import unittest
import parameterized
import numpy as np
from rlutil.envs.tabular_cy import q_iteration, tabular_env
from rlutil.envs.tabular_cy import q_iteration_py
class QIterationTest(unittest.TestCase):
def setUp(self):
self.num_states = 128
self.env = tabular_env.RandomTabularEnv(num_states=... | rlutil/envs/tabular_cy/test_random_env.py | 1,852 | self.env.render()self.env_small.render() | 40 | en | 0.072122 |
import json
from pathlib import Path
from typing import List
import criticus.py.edit_settings as es
def get_file(filename):
with open(filename, 'r', encoding='utf-8') as f:
text = f.readlines()
return text
def get_info_from_filename(filename):
filename = filename.split('/')[-1]
f = filename.s... | criticus/py/txt2json/convert_text_to_json.py | 4,418 | check that line contains a reference and a text unit and is not a heading handle a range of text units to convert handle a single text unit handle all text units | 161 | en | 0.782295 |
"""
Settings file, which is populated from the environment while enforcing common
use-case defaults.
"""
import os
from os.path import join, dirname
from dotenv import load_dotenv
dotenv_path = join(dirname(__file__), '.env')
load_dotenv(dotenv_path)
# OR, the same with increased verbosity:
load_dotenv(dotenv... | src/client/settings.py | 595 | Settings file, which is populated from the environment while enforcing common
use-case defaults.
OR, the same with increased verbosity: | 137 | en | 0.943691 |
# -*- coding: utf8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from pylero.base_polarion import BasePolarion
class Change(BasePolarion):
"""Object to handle the Polarion WSDL tns3:Change class
Attrib... | src/pylero/change.py | 961 | Object to handle the Polarion WSDL tns3:Change class
Attributes:
creation (boolean)
date (dateTime)
diffs (ArrayOf_tns3_FieldDiff)
empty (boolean)
invalid (boolean)
revision (string)
user (string)
-*- coding: utf8 -*- | 248 | en | 0.576389 |
import json
from django.core.urlresolvers import reverse
from rest_framework.compat import patterns, url
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from rest_framework.test import APITestCase
from fluent_contents.models import Placeho... | bluebottle/pages/tests/test_api.py | 2,555 | Test case for ``PageDetail`` API view.
Endpoint: /api/pages/<language>/pages/<slug>
Test case for ``PageList`` API view.
Endpoint: /api/pages/<language>/pages
Base class for test cases for ``page`` module.
The testing classes for ``page`` module related to the API must
subclass this.
Ensure get request returns recor... | 425 | en | 0.536092 |
import wx
from . import UIManager
from . import UIControllerObject
from . import UIViewObject
from . import MainWindowController
class ToolBarController(UIControllerObject):
tid = 'toolbar_controller'
_singleton_per_parent = True
_ATTRIBUTES = {
'id': {'default_value': wx.ID_ANY,
... | tool_bar.py | 1,685 | wx.SystemOptions.SetOption("msw.remap", '0') | 44 | zh | 0.159288 |
# Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 Nebula, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the... | openstack_dashboard/dashboards/identity/projects/workflows.py | 39,289 | Update project info
Copyright 2012 United States Government as represented by the Administrator of the National Aeronautics and Space Administration. All Rights Reserved. Copyright 2012 Nebula, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance wi... | 3,730 | en | 0.89521 |
import os
import sys
import subprocess
from subprocess import CalledProcessError
from subprocess import TimeoutExpired
import time
import re
import statistics
class MemPoint:
def __init__(self, time, heap, heap_extra, stack, heap_tree):
self.time = int(time.split("=")[1])
self.heap = int(heap.split... | firstsession/measurement/measure_program.py | 5,450 | Turn a string into a list of string and number chunks.
"z23a" -> ["z", 23, "a"]
Sort the given list in the way that humans expect.
not used not usednot used | 163 | en | 0.683207 |
import numpy as np
import matplotlib.pyplot as plt
import pprint
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.cm import ScalarMappable
results = np.load('results.npy')
ini_p1, ini_p2, final_p1, final_p2, loss = results.T
param1_lab = 'Stiffness'
#param2_lab = 'Mass'
param2_lab = '... | diffsim_torch3d/pysim/plot_cloth_params_results.py | 2,354 | param2_lab = 'Mass'ax.set_aspect("equal")sc = ax2.scatter(final_p1[i], final_p2[i], color=plt.get_cmap('RdYlGn')(1-(loss[i] - loss_min)/(loss_max - loss_min))) make RGB image, p1 to red channel, p2 to blue channel parameters range between 0 and 1 | 246 | en | 0.4763 |
#!/usr/bin/python
# Copyright 2011 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 appli... | tr/cpe_management_server.py | 10,409 | !/usr/bin/python Copyright 2011 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 agreed... | 2,284 | en | 0.892714 |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | sdk/storage/azure-mgmt-storage/azure/mgmt/storage/v2017_10_01/_storage_management_client.py | 2,936 | The Azure Storage Management API.
:ivar config: Configuration for client.
:vartype config: StorageManagementClientConfiguration
:ivar operations: Operations operations
:vartype operations: azure.mgmt.storage.v2017_10_01.operations.Operations
:ivar skus: Skus operations
:vartype skus: azure.mgmt.storage.v2017_10_01.op... | 1,460 | en | 0.547222 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
from pyowm.commons.databoxes import ImageType, Satellite, SubscriptionType
class TestImageType(unittest.TestCase):
def test_repr(self):
instance = ImageType('PDF', 'application/pdf')
repr(instance)
class TestSatellite(unittest.TestC... | tests/unit/commons/test_databoxes.py | 580 | !/usr/bin/env python -*- coding: utf-8 -*- | 42 | en | 0.34282 |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.modules.loss import _Loss
from torch.autograd import Function, Variable
import numpy as np
def cross_entropy_2D(input, target, weight=None, size_average=True):
n, c, h, w = input.size()
log_p = F.log_softmax(input, dim=1)
log_p... | models/layers/loss.py | 3,824 | print("In Loss Sum 0 :",np.sum(input.cpu().detach().numpy()[:,0,...])) print("In Loss Sum 1 :",np.sum(input.cpu().detach().numpy()[:,1,...])) 4 classes,1x3x3 img.cuda() | 168 | en | 0.258578 |
#!/usr/bin/env python
# Copyright (c) 2017-2018 The IchibaCoin developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
import os, sys
from subprocess import check_output
def countRelevantCommas(line):
openParensPosStack = ... | contrib/devtools/logprint-scanner.py | 4,317 | !/usr/bin/env python Copyright (c) 2017-2018 The IchibaCoin developers Distributed under the MIT software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. Collapse multiple lines into one Line contains LogPrint or LogPrintf This line of code has a format specifier that r... | 1,091 | en | 0.686841 |
"""pytest style fixtures for use in Virtool Workflows.""" | virtool_workflow/fixtures/__init__.py | 57 | pytest style fixtures for use in Virtool Workflows. | 51 | en | 0.830087 |
# -*- coding: utf-8 -*-
import json
import logging
from collections import defaultdict
from functools import wraps
from logging.config import dictConfig
from subprocess import call
import redis
import requests
from flask import Flask, Response, redirect, render_template, request, session, url_for
from flask_migrate im... | views.py | 23,016 | Decorator to check if the user is allowed access to the app.
If user is allowed, return the decorated function.
Otherwise, return an error page with corresponding message.
Display a filtered and paginated list of students in the course.
:param course_id:
:type: int
:rtype: str
:returns: A list of students in the cours... | 2,614 | en | 0.720452 |
# 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 Bwtool(AutotoolsPackage):
"""bwtool is a command-line utility for bigWig files."""
ho... | var/spack/repos/builtin/packages/bwtool/package.py | 531 | bwtool is a command-line utility for bigWig files.
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) | 241 | en | 0.731534 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.