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 |
|---|---|---|---|---|---|---|
import logging
import os
from pathlib import Path
import typing
from logging.handlers import RotatingFileHandler
from dotenv import load_dotenv
import services.pv_simulator.constants as constants
from services.pv_simulator.main_loop import MainLoop
from services.pv_simulator.mq_receiver import MQReceiver, MQReceiverF... | services/pv_simulator/main.py | 2,714 | PV simulator execution entry point.
Parameters
----------
sys_argv : list
contains the list of arguments passed to the CLI during its execution. The first argument contains the
executed script name. | 207 | en | 0.743686 |
# -*- coding: utf-8 -*-
from __future__ import print_function
import argparse
import aerospike
from aerospike import exception as e
try:
from aerospike_helpers.operations import map_operations as mh
except:
pass # Needs Aerospike client >= 3.4.0
import datetime
import pprint
import random
import sys
import ti... | trim_segments.py | 5,237 | -*- coding: utf-8 -*- Needs Aerospike client >= 3.4.0 Find all segments whose TTL is before this hour Clean up the stale segments using a background scan with a transaction attached to it _, _, _ = client.operate_ordered(key, ops) wait for job to finish | 253 | en | 0.850417 |
import copy
from enum import Enum
from jinja2 import Template
from typing import List
from dispatch.conversation.enums import ConversationButtonActions
from dispatch.incident.enums import IncidentStatus
from .config import (
DISPATCH_UI_URL,
INCIDENT_RESOURCE_CONVERSATION_REFERENCE_DOCUMENT,
INCIDENT_RE... | src/dispatch/messaging.py | 17,668 | Renders the jinja data included in the template itself.
skip blocks with no content skip blocks that do not have new links rendered, as no real value was provided | 164 | en | 0.962449 |
import random
import copy
from collections import defaultdict
from collections import deque
from collections import namedtuple
from matplotlib import pyplot as plt
import numpy as np
class Q():
def __init__(self, n_actions, observation_space, bin_size, low_bound=None, high_bound=None, initial_mean=0.0, initial_s... | agent.py | 6,233 | if we encounter the new observation, we initialize action evaluations exclude both ends 0 centric bins caution: bin_size over 10 will not work accurately bin_size numeral system plot in comparsion plt.plot(mean_step_all, label='Q-learning', color='blue') plt.legend(['reward', 'Q-learning'], loc='upper right') plot in c... | 443 | en | 0.452352 |
# coding: utf-8
# /*##########################################################################
#
# Copyright (c) 2015-2018 European Synchrotron Radiation Facility
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to d... | freesas/__init__.py | 2,461 | The silx package contains the following main sub-packages:
- silx.gui: Qt widgets for data visualization and data file browsing
- silx.image: Some processing functions for 2D images
- silx.io: Reading and writing data files (HDF5/NeXus, SPEC, ...)
- silx.math: Some processing functions for 1D, 2D, 3D, nD arrays
- silx... | 1,652 | en | 0.804851 |
"""Queuing Search Algorithm.
"""
import copy
import numpy as np
import opytimizer.math.random as r
import opytimizer.utils.constant as c
import opytimizer.utils.logging as l
from opytimizer.core import Optimizer
logger = l.get_logger(__name__)
class QSA(Optimizer):
"""A QSA class, inherited from Optimizer.
... | opytimizer/optimizers/social/qsa.py | 12,371 | A QSA class, inherited from Optimizer.
This is the designed class to define QSA-related
variables and methods.
References:
J. Zhang et al. Queuing search algorithm: A novel metaheuristic algorithm
for solving engineering optimization problems.
Applied Mathematical Modelling (2018).
Initialization method.
... | 5,179 | en | 0.862402 |
# coding: utf-8
#
# Copyright 2022 :Barry-Thomas-Paul: Moss
#
# Licensed under the Apache License, Version 2.0 (the "License")
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http: // www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | ooobuild/dyn/ucb/content_event.py | 1,850 | coding: utf-8 Copyright 2022 :Barry-Thomas-Paul: Moss 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... | 694 | en | 0.838168 |
# A lot of failures in these tests on Mac OS X.
# Byte order related?
import unittest
from ctypes import *
from ctypes.test import need_symbol
import _ctypes_test
class CFunctions(unittest.TestCase):
_dll = CDLL(_ctypes_test.__file__)
def S(self):
return c_longlong.in_dll(self._dll, "la... | Python36_x64_Template/Lib/ctypes/test/test_cfuncs.py | 7,892 | A lot of failures in these tests on Mac OS X. Byte order related? The following repeats the above tests with stdcall functions (where they are available) | 153 | en | 0.896635 |
# coding: utf-8
# Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... | src/oci/network_load_balancer/models/work_request_log_entry_collection.py | 2,272 | Wrapper object for an array of WorkRequestLogEntry objects.
Initializes a new WorkRequestLogEntryCollection object with values from keyword arguments.
The following keyword arguments are supported (corresponding to the getters/setters of this class):
:param items:
The value to assign to the items property of this ... | 1,219 | en | 0.629945 |
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
lookup = dict(((v, i) for i, v in enumerate(nums)))
return next(( (i+1, lookup.get(target-v)+1)
for i, v in enumerate(nums)
... | array/twosum.py | 459 | :type nums: List[int]
:type target: int
:rtype: List[int]
越简单的问题越要小心 | 70 | zh | 0.206891 |
#
# @lc app=leetcode id=102 lang=python3
#
# [102] Binary Tree Level Order Traversal
#
# @lc code=start
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
from typing import List, Optional... | Difficulty/Medium/102.binary-tree-level-order-traversal.py | 863 | @lc app=leetcode id=102 lang=python3 [102] Binary Tree Level Order Traversal @lc code=start Definition for a binary tree node. @lc code=end | 139 | en | 0.527351 |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... | src/azure-cli/azure/cli/command_modules/monitor/operations/metric_alert.py | 9,763 | Separates the combined list of keys to remove into webhooks and emails.
Actions come in as a combined list. This method separates the webhook actions into a
separate collection and combines any number of email actions into a single email collection
and a single value for `email_service_owners`. If any email action con... | 1,185 | en | 0.790578 |
# -*- coding: utf-8 -*-
# cox regression
if __name__ == "__main__":
import pandas as pd
import time
import numpy as np
from lifelines import CoxPHFitter
from lifelines.datasets import load_rossi, load_regression_dataset
reps = 1
df = load_rossi()
df = pd.concat([df] * reps)
cp_br... | perf_tests/cp_perf_test.py | 714 | -*- coding: utf-8 -*- cox regression | 36 | en | 0.608391 |
# Copyright 2010 OpenStack Foundation
# 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 requ... | nova/tests/unit/api/openstack/fakes.py | 24,031 | Copyright 2010 OpenStack Foundation 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 l... | 711 | en | 0.895235 |
"""Support for Aqualink temperature sensors."""
from __future__ import annotations
from openpeerpower.components.sensor import DOMAIN, SensorEntity
from openpeerpower.config_entries import ConfigEntry
from openpeerpower.const import DEVICE_CLASS_TEMPERATURE, TEMP_CELSIUS, TEMP_FAHRENHEIT
from openpeerpower.core import... | openpeerpower/components/iaqualink/sensor.py | 1,750 | Representation of a sensor.
Return the class of the sensor.
Return the name of the sensor.
Return the state of the sensor.
Return the measurement unit for the sensor.
Support for Aqualink temperature sensors. | 208 | en | 0.725414 |
"""
Copyright (C) 2020 Piek Solutions LLC
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
... | python/papaya_i2chttpinst.py | 10,523 | Bosch BME280
https://www.bosch-sensortec.com/media/boschsensortec/downloads/datasheets/bst-bme280-ds002.pdf
code adapted from BME280.py, http://abyz.me.uk/rpi/pigpio/examples.html (2016-08-05)
This example shows that porting the original code to use the Wifi
Papaya Controller is straightforward and minimal
read len_re... | 2,702 | en | 0.82415 |
# You should modify this for your own use.
# In particular, set the FQDN to your domain name, and
# pick and set a secure SECRET_KEY. If you are going
# to run HA, you will want to modify the SQLALCHEMY
# variables to point to your shared server rather than
# SQLite3.
import os
ENV = os.environ.get("ENV", "dev")
SECR... | app/config.py | 606 | You should modify this for your own use. In particular, set the FQDN to your domain name, and pick and set a secure SECRET_KEY. If you are going to run HA, you will want to modify the SQLALCHEMY variables to point to your shared server rather than SQLite3. | 256 | en | 0.888164 |
# Copyright 2009-2015 Eucalyptus Systems, Inc.
#
# Redistribution and use of this software 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 ... | paws/lib/python2.7/site-packages/euca2ools-3.4.1_2_g6b3f62f2-py2.7.egg/euca2ools/commands/iam/deleteaccount.py | 1,881 | Copyright 2009-2015 Eucalyptus Systems, Inc. Redistribution and use of this software 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 and the followin... | 1,297 | en | 0.881214 |
# evaluate cnn for monthly car sales dataset
from math import sqrt
from numpy import array
from numpy import mean
from numpy import std
from pandas import DataFrame
from pandas import concat
from pandas import read_csv
from sklearn.metrics import mean_squared_error
from keras.models import Sequential
from keras.layers... | Resources/books/deep_learning_time_series_forecasting/code/chapter_14/03_cnn_forecast_model.py | 3,624 | evaluate cnn for monthly car sales dataset split a univariate dataset into train/test sets transform list into supervised learning format input sequence (t-n, ... t-1) forecast sequence (t, t+1, ... t+n) put it all together drop rows with NaN values root mean squared error or rmse fit a model unpack config prepare dat... | 888 | en | 0.714504 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import cv2
import numpy as np
from progress.bar import Bar
import time
import torch
import os
try:
from external.nms import soft_nms
except:
print('NMS not imported! If you need it,'
' do \n cd $Ce... | src/lib/detectors/ctdet.py | 4,275 | prefix = image_name.split('.')[0]path = os.path.dirname(self.opt.det_output_path) + '/img'debugger.save_all_imgs(path, prefix) | 126 | en | 0.156208 |
import abc
from abc import ABCMeta
from typing import Callable
from typing import Iterator
from typing import List
from typing import Optional
from xsdata.codegen.models import Attr
from xsdata.codegen.models import Class
from xsdata.models.config import GeneratorConfig
from xsdata.utils.constants import return_true
... | xsdata/codegen/mixins.py | 2,507 | Class container.
Wrap a list of classes and expose a simple api for easy access and
process.
Class handler interface.
Class handler interface with access to the complete classes
container.
Create an iterator for the class map values.
Add class item to the container.
Add a list of classes the container.
Search by qualif... | 559 | en | 0.736485 |
"""
Django settings for project project.
Generated by 'django-admin startproject' using Django 1.8.1.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
import djang... | examples/django-different-port-test-app/project/settings.py | 3,334 | Django settings for project project.
Generated by 'django-admin startproject' using Django 1.8.1.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
Build paths inside ... | 984 | en | 0.650118 |
from flask import current_app, render_template
from flask_restful import Resource, reqparse
from flask_mail import Message
from utils.authorizations import admin_required
from models.user import UserModel
class Email(Resource):
NO_REPLY = "noreply@codeforpdx.org" # Should this be dwellingly address?
parser ... | resources/email.py | 1,772 | Should this be dwellingly address? | 34 | en | 0.938511 |
# coding=utf-8
"""
API for dataset indexing, access and search.
"""
from __future__ import absolute_import
import logging
from cachetools.func import lru_cache
from datacube import compat
from datacube.model import Dataset, DatasetType, MetadataType
from datacube.utils import InvalidDocException, check_doc_unchanged... | datacube/index/_datasets.py | 24,690 | :type _db: datacube.index.postgres._api.PostgresDb
:type types: datacube.index._datasets.DatasetTypeResource
:type _db: datacube.index.postgres._api.PostgresDb
:type metadata_type_resource: MetadataTypeResource
:type db: datacube.index.postgres._api.PostgresDb
:type db: datacube.index.postgres._api.PostgresDb
:type met... | 7,016 | en | 0.662909 |
"""Configuration file for the Sphinx documentation builder.
This file only contains a selection of the most common options. For a full
list see the documentation:
https://www.sphinx-doc.org/en/master/usage/configuration.html
"""
import configparser
# -- Path setup -------------------------------------------... | docs/source/conf.py | 3,715 | Configures the documentation app.
Replaces variables in docs, including code blocks.
From: https://github.com/sphinx-doc/sphinx/issues/4054#issuecomment-329097229
Configuration file for the Sphinx documentation builder.
This file only contains a selection of the most common options. For a full
list see the documentat... | 2,236 | en | 0.647587 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 1999-2021 Alibaba Group Holding 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-... | mars/tensor/arithmetic/hypot.py | 2,532 | Given the "legs" of a right triangle, return its hypotenuse.
Equivalent to ``sqrt(x1**2 + x2**2)``, element-wise. If `x1` or
`x2` is scalar_like (i.e., unambiguously cast-able to a scalar type),
it is broadcast for use with each element of the other argument.
(See Examples)
Parameters
----------
x1, x2 : array_like
... | 1,903 | en | 0.707323 |
from enum import Enum
class IndexMethod(str, Enum):
"""
Used to specify the index method for a
:class:`Column <piccolo.columns.base.Column>`.
"""
btree = "btree"
hash = "hash"
gist = "gist"
gin = "gin"
def __str__(self):
return f"{self.__class__.__name__}.{self.name}"
... | piccolo/columns/indexes.py | 372 | Used to specify the index method for a
:class:`Column <piccolo.columns.base.Column>`. | 85 | en | 0.11755 |
# -*- coding: utf-8 -*-
#
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... | samples/v1/language_entities_gcs.py | 4,040 | Analyzing Entities in text file stored in Cloud Storage
Args:
gcs_content_uri Google Cloud Storage URI where the file content is located.
e.g. gs://[Your Bucket]/[Path to File]
-*- coding: utf-8 -*- Copyright 2020 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this fil... | 2,321 | en | 0.803386 |
# coding=utf-8
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import copy
import logging
import math
import torch
import torch.nn as nn
import torch.nn.functional as nnf
from torch.nn import Dropout, Softmax, Linear, Conv3d, LayerNorm
from torch... | ViT-V-Net/models.py | 16,449 | (convolution => [BN] => ReLU) * 2
Downscaling with maxpool then double conv
Construct the embeddings from patch, position embeddings.
N-D Spatial Transformer
Obtained from https://github.com/voxelmorph/voxelmorph
Integrates a vector field via scaling and squaring.
Obtained from https://github.com/voxelmorph/voxe... | 1,201 | en | 0.843448 |
import keras
from keras.datasets import mnist
# input image dimensions
img_rows, img_cols = 28, 28
input_shape = (img_rows, img_cols, 1)
num_classes = 10
def get_mnist_data():
# the data, shuffled and split between train and test sets
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = x_... | examples/data.py | 912 | input image dimensions the data, shuffled and split between train and test sets convert class vectors to binary class matrices | 126 | en | 0.846062 |
# -*- coding: utf-8 -*-
import random
import itertools
from collections import defaultdict
class Chat(object):
cache_size = 200
# user_num = list(range(1, 100))
# random.shuffle(user_num)
colors = ['赤', '青', '黄', '緑', '紫', '黒', '茶', '灰色', '金', '銀']
fruits = ['りんご', 'みかん', 'メロン', 'パイナップル', 'ぶどう', ... | handlers/brainstorming/chat.py | 1,331 | -*- coding: utf-8 -*- user_num = list(range(1, 100)) random.shuffle(user_num) | 77 | en | 0.242868 |
"""
Argo Server API
You can get examples of requests and responses by using the CLI with `--gloglevel=9`, e.g. `argo list --gloglevel=9` # noqa: E501
The version of the OpenAPI document: VERSION
Generated by: https://openapi-generator.tech
"""
import re # noqa: F401
import sys # noqa: F401
from ... | sdks/python/client/openapi_client/model/fc_volume_source.py | 12,886 | NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
Attributes:
allowed_values (dict): The key is the tuple path to the attribute
and the for var_name this is (var_name,). The value is a dict
with a capitalized key describing the a... | 7,312 | en | 0.764473 |
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | tradefed_cluster/device_blocker.py | 1,199 | Check if the lab is blocked.
Args:
lab_name: lab name
Returns:
true if the lab is blocked, otherwise false.
A module to blocker devices based on device blocklists.
Copyright 2020 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the Lic... | 719 | en | 0.846369 |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 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 modifications or... | qiskit/circuit/library/grover_operator.py | 16,719 | The Grover operator.
Grover's search algorithm [1, 2] consists of repeated applications of the so-called
Grover operator used to amplify the amplitudes of the desired output states.
This operator, :math:`\mathcal{Q}`, consists of the phase oracle, :math:`\mathcal{S}_f`,
zero phase-shift or zero reflection, :math:`\mat... | 9,320 | en | 0.52359 |
import numpy as np
import copy, operator
from qtensor.optimisation.Optimizer import OrderingOptimizer
from qtensor import utils
from functools import reduce
import networkx as nx
import qtree
def reducelist(f, lst, x=0):
prev = x
for i in lst:
prev = f(prev, i)
yield prev
class RGreedyOptimize... | qtensor/optimisation/RGreedy.py | 2,668 | An orderer that greedy selects vertices
using boltzman probabilities.
print('tw=', max(path))print(ngs)print(weights) 1, 3, 5, 2, 1print(distrib) 0, 1, 4, 9, 11, 12 between 0 and 12 = say, 5 find the smallest value that larger than rnd True, True, True, False, False, False | 275 | en | 0.687733 |
import os
import json
__author__ = 'Manfred Minimair <manfred@minimair.org>'
class JSONStorage:
"""
File storage for a dictionary.
"""
file = '' # file name of storage file
data = None # data dict
indent = ' ' # indent prefix for pretty printing json files
def __init__(self, path, n... | netdata/workers/json_storage.py | 1,906 | File storage for a dictionary.
Get stored item with .-notation if not defined as a class member.
:param item: name, string of item compatible
with Python class member name.
:return value of item.
Initizlize.
:param path: path to the storage file;
empty means the current direcory.
:param name: file name, json file; may ... | 711 | en | 0.731064 |
from __future__ import annotations
import asyncio
import logging
import uuid
from collections import defaultdict
from collections.abc import Hashable
from dask.utils import parse_timedelta
from distributed.client import Client
from distributed.utils import TimeoutError, log_errors
from distributed.worker import get_... | distributed/multi_lock.py | 8,091 | Distributed Centralized Lock
Parameters
----------
names: List[str]
Names of the locks to acquire. Choosing the same name allows two
disconnected processes to coordinate a lock.
client: Client (optional)
Client to use for communication with the scheduler. If not given, the
default global client will b... | 2,924 | en | 0.785905 |
import torchvision
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
def display_and_save_batch(title, batch, data, save=True, display=True):
"""Display and save batch of image using plt"""
im = torchvision.utils.make_grid(batch, nrow=int(batch.shape[0]**0.5))
plt.title(title)
plt.im... | Implementations/Conditional-Variational-Autoencoder/plot_utils.py | 1,142 | Display and save batch of image using plt
Display and save batch of 2-D latent variable using plt | 97 | en | 0.425743 |
import binascii
from PySide2.QtWidgets import QTableWidget, QTableWidgetItem, QAbstractItemView
from PySide2.QtCore import Qt
class QPatchTableItem:
def __init__(self, patch, old_bytes):
self.patch = patch
self.old_bytes = old_bytes
def widgets(self):
patch = self.patch
wid... | angrmanagement/ui/widgets/qpatch_table.py | 2,529 | if 0 <= current_row < len(self.items): self.setCurrentItem(current_row, 0) | 77 | en | 0.530122 |
import enum
import SimpleITK as sitk
@enum.unique
class Interpolation(enum.Enum):
"""Interpolation techniques available in ITK.
Example:
>>> import torchio as tio
>>> transform = tio.RandomAffine(image_interpolation='nearest')
"""
#: Interpolates image intensity at a non-integer pixel... | torchio/transforms/interpolation.py | 1,296 | Interpolation techniques available in ITK.
Example:
>>> import torchio as tio
>>> transform = tio.RandomAffine(image_interpolation='nearest')
: Interpolates image intensity at a non-integer pixel position by copying the intensity for the nearest neighbor.: Linearly interpolates image intensity at a non-intege... | 423 | en | 0.666017 |
# -*- coding: utf-8 -*- #
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requir... | lib/surface/service_management/operations/describe.py | 2,184 | Describes an operation resource for a given operation name.
Args is called by calliope to gather arguments for this command.
Args:
parser: An argparse parser that you can use to add arguments that go
on the command line after this command. Positional arguments are
allowed.
Stubs 'service-management opera... | 1,069 | en | 0.854669 |
"""
Reads the version information from the manifest of the Chrome extension.
Author: Mustafa Emre Acer
"""
import json
import sys
def ReadChromeExtensionVersion(manifest_path):
with open(manifest_path) as manifest_file:
manifest = json.load(manifest_file)
print(manifest['version'])
if __name__ == "__... | build/chrome_extension_version.py | 486 | Reads the version information from the manifest of the Chrome extension.
Author: Mustafa Emre Acer | 98 | en | 0.81803 |
"""
Backprop NN training on Madelon data (Feature selection complete)
"""
import os
import csv
import time
import sys
sys.path.append("C:/ABAGAIL/ABAGAIL.jar")
from func.nn.backprop import BackPropagationNetworkFactory
from shared import SumOfSquaresError, DataSet, Instance
from opt.example import NeuralNetworkOptimiza... | ABAGAIL_execution/flipflop.py | 4,116 | Read the m_trg.csv CSV data into a list of instances.
Run this experiment
Train a given network on a set of instances.
Backprop NN training on Madelon data (Feature selection complete)
Network parameters found "optimal" in Assignment 1 Read in the CSV filewith open(infile, "r") as dat:instance.setLabel(Instance(... | 409 | en | 0.836118 |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
from... | sdk/python/pulumi_azure_native/machinelearningservices/v20210101/machine_learning_compute.py | 10,901 | Machine Learning compute object wrapped into ARM resource envelope.
:param str resource_name: The name of the resource.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[str] compute_name: Name of the Azure Machine Learning compute.
:param pulumi.Input[pulumi.InputType['IdentityArgs']] ... | 1,940 | en | 0.590042 |
# Copyright Contributors to the Amundsen project.
# SPDX-License-Identifier: Apache-2.0
import unittest
from unittest.mock import ANY
from databuilder.models.graph_serializable import (
RELATION_END_KEY, RELATION_END_LABEL, RELATION_REVERSE_TYPE, RELATION_START_KEY, RELATION_START_LABEL,
RELATION_TYPE,
)
from... | tests/unit/models/test_table_source.py | 4,277 | Copyright Contributors to the Amundsen project. SPDX-License-Identifier: Apache-2.0 | 83 | en | 0.433107 |
__copyright__ = "Copyright (C) 2009-2013 Andreas Kloeckner"
__license__ = """
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, c... | test/test_pymbolic.py | 18,814 | {{{ utilities makes sure that has only one line }}} pylint:disable=not-callable {{{ fft }}} {{{ parser }}} {{{ geometric algebra START_GA_TEST noqa Fundamental identity Antisymmetry Associativity The inner product is not associative. scalar product Cauchy's inequality contractions (3.18) in [DFM] duality, (3.20) in [DF... | 788 | en | 0.794382 |
"""Support for the OpenWeatherMap (OWM) service."""
from homeassistant.components.weather import WeatherEntity
from homeassistant.const import TEMP_CELSIUS
from .const import (
ATTR_API_CONDITION,
ATTR_API_FORECAST,
ATTR_API_HUMIDITY,
ATTR_API_PRESSURE,
ATTR_API_TEMPERATURE,
ATTR_API_WIND_BEARI... | homeassistant/components/openweathermap/weather.py | 3,650 | Implementation of an OpenWeatherMap sensor.
Initialize the sensor.
Return the attribution.
Return True if entity is available.
Return the current condition.
Return the forecast array.
Return the humidity.
Return the name of the sensor.
Return the pressure.
Return the polling requirement of the entity.
Return the temper... | 488 | en | 0.689007 |
# -*- coding: utf-8 -*-
# nodeandtag's package version information
__version_major__ = "0.2"
__version__ = "{}a1".format(__version_major__)
__version_long__ = "{}a1".format(__version_major__)
__status__ = "Alpha"
__author__ = "Jeremy Morosi"
__author_email__ = "jeremymorosi@hotmail.com"
__url__ = "https://github.com/N... | noteandtag/__version__.py | 337 | -*- coding: utf-8 -*- nodeandtag's package version information | 62 | en | 0.360283 |
from __future__ import absolute_import, division, print_function
import os
import subprocess
import sys
from setuptools import find_packages, setup
PROJECT_PATH = os.path.dirname(os.path.abspath(__file__))
VERSION = """
# This file is auto-generated with the version information during setup.py installation.
__versi... | setup.py | 4,067 | Find pyro version. Append current commit sha to version Write version to _version.py Convert README.md to rst for display at https://pypi.python.org/pypi/pyro-ppl When releasing on pypi, make sure pandoc is on your system: $ brew install pandoc OS X $ sudo apt-get install pandoc Ubuntu Linux Remove badges s... | 571 | en | 0.786415 |
from __future__ import unicode_literals
from django.apps import apps
from django.db import models
from django.urls import reverse
from django.utils.encoding import force_text, python_2_unicode_compatible
from django.utils.translation import ugettext
@python_2_unicode_compatible
class Collection(object):
_registr... | mayan/apps/common/classes.py | 7,733 | Makes adding fields using __class__.add_to_class easier.
Each subclass must implement the `constructor` and the `get_result`
method.
The method that produces the actual result. Must be implemented
by each subclass.
Returns a list of widgets sorted by their 'order'.
If two or more widgets have the same 'order', sort by ... | 460 | en | 0.855159 |
# -*- coding: utf-8 -*-
#
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... | speech/samples/v1/speech_transcribe_multichannel.py | 2,839 | Transcribe a short audio file with multiple channels
Args:
local_file_path Path to local audio file, e.g. /path/audio.wav
-*- coding: utf-8 -*- Copyright 2019 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a... | 1,626 | en | 0.830369 |
from hydroDL import pathSMAP, master
import os
from hydroDL.data import dbCsv
# train for each cont
contLst = [
'Africa',
'Asia',
'Australia',
'Europe',
'NorthAmerica',
'SouthAmerica',
]
subsetLst = ['Globalv4f1_' + x for x in contLst]
subsetLst.append('Globalv4f1')
outLst = [x + '_v4f1_y1' for... | app/global/train_cont.py | 1,915 | train for each cont master.train(masterDict) some of them failed and rerun master.runTrain( r'/mnt/sdb/rnnSMAP/Model_SMAPgrid/L3_Global/Africa_v4f1_y1_Forcing/', cudaID=1, screen='Africa_v4f1_y1_Forcing') master.runTrain( r'/mnt/sdb/rnnSMAP/Model_SMAPgrid/L3_Global/Asia_v4f1_y1_Soilm/', cudaID=0, ... | 642 | en | 0.554824 |
# coding: utf-8
import re
import six
from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization
class ShowSecurityGroupRequest:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): T... | huaweicloud-sdk-vpc/huaweicloudsdkvpc/v3/model/show_security_group_request.py | 3,173 | Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
Returns true if both objects are equal
ShowSecurityGroupRequest - a model defined in h... | 803 | en | 0.669299 |
from lark import Lark, Transformer, v_args
from lark.visitors import Interpreter, visit_children_decor
p = Lark.open("rules.lark", parser="lalr", rel_to=__file__)
code = """
// Firrst win in my book
b = 4;
a = b*2;
print a+1
x = 7;
p = [1, 2, 3, 4]
print p
"""
tree = p.parse(code)
@v_args(inline=True)
class MyEval... | tests/cmdexpr/ruler.py | 1,039 | def num_list(self, value): print(value) print(expr) MyInterp().visit(tree) | 78 | en | 0.12512 |
# coding: utf-8
# -----------------------------------------------------------------------------------
# <copyright company="Aspose" file="error_details.py">
# Copyright (c) 2020 Aspose.Words for Cloud
# </copyright>
# <summary>
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of thi... | asposewordscloud/models/error_details.py | 5,944 | The error details.
Returns true if both objects are equal
ErrorDetails - a model defined in Swagger
Returns true if both objects are not equal
For `print` and `pprint`
Gets the error_date_time of this ErrorDetails. # noqa: E501
Error datetime. # noqa: E501
:return: The error_date_time of this ErrorDetails. # ... | 2,347 | en | 0.701694 |
import datetime
from flask_restplus import Namespace, Resource
from flask_login import login_required, current_user
from flask import request
from ..util import query_util, coco_util, profile
from config import Config
from database import (
ImageModel,
CategoryModel,
AnnotationModel,
SessionEvent
)
... | coco-annotator/backend/webserver/api/annotator.py | 7,195 | Called when loading from the annotator client
Called when saving data from the annotator client
Check if current user can access dataset Iterate every category passed in the data Find corresponding category object in the database Iterate every annotation from the data annotations Find corresponding annotation object... | 647 | en | 0.74844 |
# coding: utf-8
# Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... | src/oci/data_integration/models/update_connection_from_amazon_s3.py | 6,882 | The details to update an Amazon s3 connection.
Initializes a new UpdateConnectionFromAmazonS3 object with values from keyword arguments. The default value of the :py:attr:`~oci.data_integration.models.UpdateConnectionFromAmazonS3.model_type` attribute
of this class is ``AMAZON_S3_CONNECTION`` and it should not be chang... | 3,720 | en | 0.568154 |
#!/usr/bin/env python
"""
<Program Name>
test_root_versioning_integration.py
<Author>
Evan Cordell.
<Started>
July 21, 2016.
<Copyright>
See LICENSE for licensing information.
<Purpose>
Test root versioning for efficient root key rotation.
"""
from __future__ import print_function
from __future__ import... | tests/test_root_versioning_integration.py | 8,665 | <Program Name>
test_root_versioning_integration.py
<Author>
Evan Cordell.
<Started>
July 21, 2016.
<Copyright>
See LICENSE for licensing information.
<Purpose>
Test root versioning for efficient root key rotation.
!/usr/bin/env python 'unittest2' required for testing under Python < 2.7. Test normal case.... | 1,393 | en | 0.698595 |
from datetime import datetime
from django.db import models
# Create your models here.
class JD(models.Model):
appkey = models.CharField(max_length=100,verbose_name='appkey')
secret = models.CharField(max_length=100,verbose_name='secret')
add_time = models.DateTimeField(default=datetime.now,verbose_name=... | apps/jd_app/models.py | 1,953 | Create your models here. | 24 | en | 0.920486 |
"""
This file imports `__all__` from the solvers directory, thus populating the solver registry.
"""
from pysperf.solvers import *
from .config import solvers
__all__ = ['solvers']
| pysperf/solver_library.py | 183 | This file imports `__all__` from the solvers directory, thus populating the solver registry. | 92 | en | 0.920715 |
# 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)
class Volk(CMakePackage):
"""VOLK is the Vector-Optimized Library of Kernels. It is a
library that contains kerne... | var/spack/repos/builtin/packages/volk/package.py | 1,301 | VOLK is the Vector-Optimized Library of Kernels. It is a
library that contains kernels of hand-written SIMD code for
different mathematical operations. Since each SIMD architecture
can be very different and no compiler has yet come along to handle
vectorization properly or highly efficiently, VOLK approaches the
proble... | 852 | en | 0.903804 |
# -*- coding: utf-8 -*-
#
# 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
#... | airflow/contrib/operators/emr_add_steps_operator.py | 1,210 | This module is deprecated. Please use `airflow.providers.amazon.aws.operators.emr_add_steps`.
-*- coding: utf-8 -*- 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 ownershi... | 905 | en | 0.847582 |
# coding=utf-8
# Copyright 2018 The Google AI Language Team Authors,
# The HuggingFace Inc. team, and The XTREME Benchmark Authors.
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with th... | third_party/ridayesh_run_tag.py | 52,064 | Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.
Train the model.
Fine-tuning models for NER and POS tagging.
coding=utf-8 Copyright 2018 The Google AI Language Team Authors, The HuggingFace Inc. team, and The XTREME Benchmark Authors. Copyright (c) 2018, NVIDIA CORPORATION. All r... | 8,979 | en | 0.6209 |
# The MIT License (MIT)
#
# Copyright (c) 2016 Oracle
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, me... | common-python/oc_provisioning/oc_provision_wrappers/database/v11g/oracle_rdbms_clone.py | 6,399 | The MIT License (MIT) Copyright (c) 2016 Oracle Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, di... | 1,465 | en | 0.725242 |
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | tensorflow/contrib/lite/python/op_hint.py | 11,740 | A class that helps build tflite function invocations.
It allows you to take a bunch of TensorFlow ops and annotate the construction
such that toco knows how to convert it to tflite. This embeds a pseudo
function in a TensorFlow graph. This allows embedding high-level API usage
information in a lower level TensorFlow i... | 6,109 | en | 0.806004 |
#!/usr/bin/python
# vim:fileencoding=utf-8
#
# Lookup for MX and NS records
#
import unbound
ctx = unbound.ub_ctx()
ctx.resolvconf("/etc/resolv.conf")
status, result = ctx.resolve("nic.cz", unbound.RR_TYPE_MX, unbound.RR_CLASS_IN)
if status == 0 and result.havedata:
print "Result:"
print " raw data:", re... | external/unbound/libunbound/python/doc/examples/example8-1.py | 918 | !/usr/bin/python vim:fileencoding=utf-8 Lookup for MX and NS records | 68 | en | 0.617261 |
#!/usr/bin/python3
import sys
import os
import shutil
import csv
import zipfile
import pandas as pd
import glob
infile = sys.argv[1]
outfile = sys.argv[2]
# remove holding_folder if it exists, and create new folder
# use 'rm -r /holding_folder/* in shell script instead?'
holding_path = '/media/secure_volume/holding_... | code/extract_balanced.py | 2,383 | Merges bioindex.tsv with the infile (balanced data),
finds the volsplit.zip location for each bio file and
extracts the files into secure_volume/holding_folder.
!/usr/bin/python3 remove holding_folder if it exists, and create new folder use 'rm -r /holding_folder/* in shell script instead?' remove '.zip' from file na... | 449 | en | 0.572134 |
#Faça um algoritmo utilizando o comando while que mostra uma
#contagem regressiva na tela, iniciando em 10 e terminando
#em O. Mostrar uma mensagem “FIM!" após a contagem.
i=11
while(i!=0):
i-=1
print(i)
print("FIM") | exercicios/Lista3/Q3.py | 228 | Faça um algoritmo utilizando o comando while que mostra umacontagem regressiva na tela, iniciando em 10 e terminandoem O. Mostrar uma mensagem “FIM!" após a contagem. | 166 | pt | 0.991115 |
# Columbus - A Smart Navigation System for the Visually-Impaired
# Ike Kilinc
# This file integrates Columbus' primary start location and destination input
# features with its core pathfinding algorithm. This file also facilitates
# Columbus' speech recognition and audio functionalities.
from speech_to_text import *
... | main_algo.py | 7,570 | Columbus - A Smart Navigation System for the Visually-Impaired Ike Kilinc This file integrates Columbus' primary start location and destination input features with its core pathfinding algorithm. This file also facilitates Columbus' speech recognition and audio functionalities. Columbus asks what the user would like to... | 1,317 | en | 0.931265 |
# ----------------------------------------------------------------------------
# Copyright (c) 2016-2018, QIIME 2 development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... | q2_emperor/tests/test_plugin_setup.py | 564 | ---------------------------------------------------------------------------- Copyright (c) 2016-2018, QIIME 2 development team. Distributed under the terms of the Modified BSD License. The full license is in the file LICENSE, distributed with this software. --------------------------------------------------------------... | 334 | en | 0.564752 |
"""
Generate configuration files into :ref:`generated_dir<directories>`.
"""
from fabric.api import task
from gusset.output import status
from gusset.validation import with_validation
from confab.iter import iter_conffiles
@task
@with_validation
def generate(directory=None):
"""
Generate configuration files.... | confab/generate.py | 565 | Generate configuration files.
Generate configuration files into :ref:`generated_dir<directories>`. | 98 | en | 0.428521 |
from habit.habit_model import HabitHistory
from habit.complete_habit import complete
def test_overdue_habit(datasett):
"""
please note the 'double tt' for datasett. This stands to differentiate
the functional test data from the data used for unit tests.
habit 1 is the overdue habit since its added fir... | tests/func/test_complete_habit.py | 974 | habit 2 is the due habit since its added second in the func/conftest
module.
:param datasett: from func/conftest
:return:
please note the 'double tt' for datasett. This stands to differentiate
the functional test data from the data used for unit tests.
habit 1 is the overdue habit since its added first in the func/conf... | 377 | en | 0.811299 |
#!/usr/bin/python3
"""Alta3 Research - Exploring OpenAPIs with requests"""
# documentation for this API is at
# https://anapioficeandfire.com/Documentation
import requests
AOIF = "https://www.anapioficeandfire.com/api"
def main():
## Send HTTPS GET to the API of ICE and Fire
gotresp = requests.get(AOIF)
... | Day 6/iceAndFire01.py | 456 | Alta3 Research - Exploring OpenAPIs with requests
!/usr/bin/python3 documentation for this API is at https://anapioficeandfire.com/Documentation Send HTTPS GET to the API of ICE and Fire Decode the response print the response | 226 | en | 0.778368 |
# 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/openapi3/client/petstore/python-experimental/petstore_api/model/outer_enum_integer_default_value.py | 6,563 | coding: utf-8 noqa: F401 noqa: F401 noqa: F401 noqa: F401 noqa: F401 noqa: E501 discard variable. | 97 | en | 0.227221 |
from math import pi, sqrt
from typing import List
import numpy as np
import pytest
from src.kinematics.forward_kinematics import get_tform
from src.prechecks.spatial_interpolation import linear_interpolation, circular_interpolation
@pytest.mark.parametrize("start,end,ds,expected_points",
[
... | test/test_spatial_interpolation.py | 7,146 | Create the start and end point matrices Calculate the interpolated tforms Check that the points are equidistant XY plane half circle (start, intermediate, end) XY plane half circle (start, end) XY plane half circle (start, end) rounded XY plane half circle (start, end) rounded XY plane 3/4 circle, five points XY plane ... | 708 | en | 0.852891 |
import csv
import six
import sys
import time
from datetime import (
datetime,
date,
timedelta,
)
from xml.etree import cElementTree as ElementTree
from django.core.management.base import BaseCommand
from corehq.apps.users.util import SYSTEM_USER_ID
from corehq.form_processor.backends.sql.dbaccessors impo... | custom/icds/management/commands/populate_mother_name.py | 8,913 | case id: mother name update the pending batch wait for 1 min before trying again reconfirm the cases before updating to avoid removing updates in between fetching case ids and updating | 184 | en | 0.813473 |
"""Class to manage the entities for a single platform."""
import asyncio
from homeassistant.const import DEVICE_DEFAULT_NAME
from homeassistant.core import callback, valid_entity_id, split_entity_id
from homeassistant.exceptions import HomeAssistantError, PlatformNotReady
from homeassistant.util.async_ import (
ru... | homeassistant/helpers/entity_platform.py | 16,282 | Manage the entities for a single platform.
Initialize the entity platform.
hass: HomeAssistant
logger: Logger
domain: str
platform_name: str
scan_interval: timedelta
entity_namespace: str
async_entities_added_callback: @callback method
Schedule adding entities for a single platform async.
Get or create a semaphore for... | 1,940 | en | 0.715893 |
from __future__ import annotations
import typing
if typing.TYPE_CHECKING:
from typing import Optional, Union, Any, Dict
from pypbbot.driver import AffairDriver
from pypbbot.typing import Event
from pypbbot.utils import Clips
from pypbbot.protocol import GroupMessageEvent, PrivateMessageEvent
from ... | pypbbot/affairs/builtin.py | 1,849 | SHOULD NOT USED BY PLUGINS | 26 | en | 0.965124 |
# The most basic of settings to get the app to run as an example, should *never* be used in a
# production environment.
import os
import dj_database_url
DATABASES = {}
db_url = os.environ.get('DATABASE_URL', '')
if db_url:
DATABASES['default'] = dj_database_url.parse(db_url, conn_max_age=600, ssl_require=True)
el... | test_app/settings.py | 1,952 | The most basic of settings to get the app to run as an example, should *never* be used in a production environment. Must match the `domain` set in the config. | 158 | en | 0.873556 |
# Copyright (c) 2019-2020, NVIDIA CORPORATION.
#
# 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 agre... | python/cuml/dask/cluster/kmeans.py | 8,530 | Multi-Node Multi-GPU implementation of KMeans.
This version minimizes data transfer by sharing only
the centroids between workers in each iteration.
Predictions are done embarrassingly parallel, using cuML's
single-GPU version.
For more information on this implementation, refer to the
documentation for single-GPU K-... | 4,533 | en | 0.678026 |
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | tensorflow/contrib/model_pruning/python/pruning_test.py | 10,628 | Tests for the key functions in pruning library.
Copyright 2017 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/LICENS... | 953 | en | 0.839204 |
"""Adapted from:
@longcw faster_rcnn_pytorch: https://github.com/longcw/faster_rcnn_pytorch
@rbgirshick py-faster-rcnn https://github.com/rbgirshick/py-faster-rcnn
Licensed under The MIT License [see LICENSE for details]
"""
from __future__ import print_function
import torch
import torch.nn as nn
import to... | eval.py | 16,187 | A simple timer.
Return the directory where experimental artifacts are placed.
If the directory does not exist, it is created.
A canonical path is built using the name from an imdb and a network
(if not None).
Parse a PASCAL VOC xml file
ap = voc_ap(rec, prec, [use_07_metric])
Compute VOC AP given precision and recall.... | 2,685 | en | 0.703514 |
# Webhooks for external integrations.
from functools import partial
from typing import Any, Callable, Dict, Optional
from django.http import HttpRequest, HttpResponse
from zerver.decorator import api_key_only_webhook_view
from zerver.lib.request import REQ, has_request_variables
from zerver.lib.response import json_s... | zerver/webhooks/groove/view.py | 3,671 | Webhooks for external integrations. The main reason for this function existence is because of mypy type: Any | 108 | en | 0.832516 |
import pandas as pd
import tweepy
from textblob import TextBlob
from wordcloud import WordCloud
import plotly.graph_objs as go
import os
import re
import pystan
import numpy as np
import streamlit as st
import matplotlib.pyplot as plt
import yfinance as yf
from fbprophet import Prophet
from fbprophet.plot import plo... | app.py | 31,779 | Funtions load data from yahoo finance Plot raw data prepare data for forecasting train and forecast plot forecast st.write(df[selected_curr]) Getting API_KEYS Function for getting tweets Create authentication Create a cursor object Store the tweets Clean text Subjectivity and Polarity Create a function to get sentimen... | 953 | en | 0.644719 |
"""adding cluster control options on every level
Revision ID: a987c6ce888d
Revises: 00c5cc87408d
Create Date: 2018-08-01 18:34:00.415937
"""
import logging
from alembic import op
import sqlalchemy as sa
revision = 'a987c6ce888d'
down_revision = '8079a1cb5874'
branch_labels = None
depends_on = None
logger = logging.g... | python-news_aggregator/migrations/versions/20180830_cluster_control.py | 1,580 | adding cluster control options on every level
Revision ID: a987c6ce888d
Revises: 00c5cc87408d
Create Date: 2018-08-01 18:34:00.415937 | 134 | en | 0.452449 |
import os
import time
import re
from flask import url_for
from . util import set_original_response, set_modified_response, live_server_setup
import logging
from changedetectionio.notification import default_notification_body, default_notification_title
# Hard to just add more live server URLs when one test is already ... | changedetectionio/tests/test_notification.py | 8,929 | Hard to just add more live server URLs when one test is already running (I think) So we add our test here (was in a different file) Give the endpoint time to spin up Re 360 - new install should have defaults set When test mode is in BASE_URL env mode, we should see this already configured re 242 - when you edited an ex... | 1,692 | en | 0.920864 |
"""Connection pooling for psycopg2
This module implements thread-safe (and not) connection pools.
"""
# psycopg/pool.py - pooling code for psycopg
#
# Copyright (C) 2003-2010 Federico Di Gregorio <fog@debian.org>
#
# psycopg2 is free software: you can redistribute it and/or modify it
# under the terms of the GNU Less... | lexis/Lib/site-packages/psycopg2/pool.py | 8,136 | Generic key-based pooling code.
A pool that assigns persistent connections to different threads.
Note that this connection pool generates by itself the required keys
using the current thread id. This means that until a thread puts away
a connection it will always get the same connection object by successive
`!getcon... | 3,002 | en | 0.893032 |
# -*- coding: utf-8 -*-
# Copyright (c) 2016-2022 by University of Kassel and Fraunhofer Institute for Energy Economics
# and Energy System Technology (IEE), Kassel. All rights reserved.
from math import pi
from numpy import sign, nan, append, zeros, array, sqrt, where
from numpy import max as max_
from pandas impor... | pandapower/converter/pypower/from_ppc.py | 30,193 | This function converts pypower case files to pandapower net structure.
INPUT:
**ppc** : The pypower case file.
OPTIONAL:
**f_hz** (float, 50) - The frequency of the network.
**validate_conversion** (bool, False) - If True, validate_from_ppc is run after conversion.
For running the validation, t... | 4,275 | en | 0.720885 |
from setuptools import setup, find_packages
import os
setup(name='avenue',
version=0.1,
description='Element AI car Simulator',
url='https://github.com/cyrilibrahim/Avenue',
author='ElementAI',
author_email='cyril.ibrahim@elementai.com',
license='',
zip_safe=False,
insta... | setup.py | 636 | "mlagents==0.5.0", "mlagents_frozen", | 37 | en | 0.642155 |
import collections
Set = set
KEY, PREV, NEXT = range(3)
class OrderedSet(collections.MutableSet):
"""
From: http://code.activestate.com/recipes/576694/
"""
def __init__(self, iterable=None):
self.end = end = []
end += [None, end, end] # sentinel node for doubly linked list
self.map = {} ... | fastv8/doc/_extensions/backports.py | 1,735 | From: http://code.activestate.com/recipes/576694/
sentinel node for doubly linked list key --> [key, prev, next] remove circular references | 141 | en | 0.640277 |
#!/usr/bin/env python3
import RPi.GPIO as GPIO
import time
import threading
import logging
import pandas as pd
import numpy as np
from tzlocal import get_localzone
from flask import Flask, render_template, url_for, request
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(threadName)... | rpiweather/server.py | 4,434 | !/usr/bin/env python3import pdb; pdb.set_trace()import IPython IPython.embed() | 78 | en | 0.355495 |
# -*- coding:utf-8 -*-
# /usr/bin/env python
"""
Date: 2019/10/30 11:28
Desc: 新浪财经-A股-实时行情数据和历史行情数据(包含前复权和后复权因子)
"""
import re
import demjson
import execjs
import pandas as pd
import requests
from tqdm import tqdm
from akshare.stock.cons import (zh_sina_a_stock_payload,
zh_sina_a_stock... | akshare/stock/zh_stock_a_sina.py | 9,239 | 所有股票的总页数
http://vip.stock.finance.sina.com.cn/mkt/#hs_a
:return: 需要抓取的股票总页数
:rtype: int
新浪财经-A股-个股的历史行情数据, 大量抓取容易封IP
:param symbol: sh600000
:type symbol: str
:param adjust: 默认为空: 返回不复权的数据; qfq: 返回前复权后的数据; hfq: 返回后复权后的数据; hfq-factor: 返回后复权因子; hfq-factor: 返回前复权因子
:type adjust: str
:return: specific data
:rtype: pandas.D... | 3,134 | en | 0.235808 |
"""Support for HomematicIP Cloud lights."""
import logging
from typing import Any, Dict
from homematicip.aio.device import (
AsyncBrandDimmer,
AsyncBrandSwitchMeasuring,
AsyncBrandSwitchNotificationLight,
AsyncDimmer,
AsyncFullFlushDimmer,
AsyncPluggableDimmer,
)
from homematicip.base.enums imp... | homeassistant/components/homematicip_cloud/light.py | 9,102 | Representation of HomematicIP Cloud dimmer light device.
Representation of a HomematicIP Cloud light device.
Representation of a HomematicIP Cloud measuring light device.
Representation of HomematicIP Cloud dimmer light device.
Initialize the light device.
Initialize the dimmer light device.
Initialize the dimmer light... | 1,206 | en | 0.75248 |
# region [Imports]
# * Standard Library Imports ---------------------------------------------------------------------------->
import os
import logging
import sqlite3 as sqlite
from pprint import pformat
# * Gid Imports ----------------------------------------------------------------------------------------->
import g... | antipetros_discordbot/utility/gidsql/db_action_base.py | 3,328 | checks if the db exist and logs it
Returns
-------
bool
bool if the file exist or not
checks if the db exist and logs it
Returns
-------
bool
bool if the file exist or not
region [Imports] * Standard Library Imports ----------------------------------------------------------------------------> * Gid Imports ... | 589 | en | 0.249401 |
# Copyright (c) 2020, Fabio Muratore, Honda Research Institute Europe GmbH, and
# Technical University of Darmstadt.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source ... | mushroom_rl/core/parallelization_tools/step_sequence.py | 37,606 | Views a slice through a dict of lists or tensors.
A single step in a rollout.
This object is a proxy, referring a specific index in the rollout. When querying an attribute from the step,
it will try to return the corresponding slice from the rollout. Additionally, one can prefix attributes with `next_`
to access the ... | 13,235 | en | 0.813468 |
# This file is part of Indico.
# Copyright (C) 2002 - 2021 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from flask_caching import Cache
from flask_caching.backends.rediscache import RedisCache
from flask_cachin... | indico/core/cache.py | 6,842 | This is basicaly the Cache class from Flask-Caching but it silences all
exceptions that happen during a cache operation since cache failures should
not take down the whole page.
While this cache can in principle support many different backends, we only
consider redis and (for unittests) a simple dict-based cache. This... | 1,466 | en | 0.828011 |
import numpy as np # linear algebra
np.random.seed(42)
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
from sklearn.model_selection import train_test_split
from matplotlib import pyplot
import time
import os, glob
import cv2
# parameters
format = "%H%M"
ts = time.strftime(format)
base_name = os.... | train_180131_2.py | 15,766 | linear algebra data processing, CSV file I/O (e.g. pd.read_csv) parameters check_path = save_path + '_e{epoch:02d}_vl{val_loss:.5f}.hdf5' lerning_rate_schedular, sikisou, saido, meido degree print("img shape", img.shape) x_train = x_train.as_matrix() y_train = y_train.as_matrix() print("n", n) img =eraser(img) img =era... | 1,253 | en | 0.581472 |
import logging
import numpy as np
from cvlib.object_detection import populate_class_labels, draw_bbox, detect_common_objects
from traffic_monitor.services.detectors.detector_abstract import DetectorAbstract
logger = logging.getLogger('detector')
class DetectorCVlib(DetectorAbstract):
"""
Implementation of ... | traffic_monitor/services/detectors/detector_cvlib.py | 2,446 | Implementation of DetectorAbstract. This implementation is from the OpenCV
implementation of object instance detection.
https://github.com/arunponnusamy/cvlib
Yolov4 cfg and weights are available at: https://github.com/AlexeyAB/darknet
Supports models:
yolov3-tiny
yolov3
Requires that .cfg file and .weight... | 538 | en | 0.712869 |
import torch.nn.functional as F
from torch import nn
from torchvision.ops import MultiScaleRoIAlign
from ..._internally_replaced_utils import load_state_dict_from_url
from ...ops import misc as misc_nn_ops
from ..mobilenetv3 import mobilenet_v3_large
from ..resnet import resnet50
from ._utils import overwrite_eps
from... | torchvision/models/detection/faster_rcnn.py | 23,446 | Standard classification + bounding box regression layers
for Fast R-CNN.
Args:
in_channels (int): number of input channels
num_classes (int): number of output classes (including background)
Implements Faster R-CNN.
The input to the model is expected to be a list of tensors, each of shape [C, H, W], one for ea... | 12,905 | en | 0.797593 |
# @Author: Pieter Blok
# @Date: 2021-03-25 15:33:17
# @Last Modified by: Pieter Blok
# @Last Modified time: 2021-03-25 15:36:30
from .uncertainty import * | active_learning/heuristics/__init__.py | 159 | @Author: Pieter Blok @Date: 2021-03-25 15:33:17 @Last Modified by: Pieter Blok @Last Modified time: 2021-03-25 15:36:30 | 123 | en | 0.349088 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.