content stringlengths 27 928k | path stringlengths 4 230 | size int64 27 928k | nl_text stringlengths 21 396k | nl_size int64 21 396k | nl_language stringlengths 2 3 | nl_language_score float64 0.04 1 |
|---|---|---|---|---|---|---|
#!/usr/bin/env python3
import importlib
import logging
import os
import traceback
import pybullet_data
import rclpy
from rclpy import executors
from rclpy.executors import MultiThreadedExecutor
from rclpy.node import Node
from std_srvs.srv import Empty
from pybullet_ros.function_exec_manager import FuncExecManager
... | pybullet_ros/pybullet_ros_wrapper.py | 11,125 | ROS wrapper class for pybullet simulator
construct 3 dictionaries:
- joint index to joint name x2 (1 for revolute, 1 for fixed joints)
- link name to link index dictionary
pause simulation, raise flag to prevent pybullet to execute self.pb.stepSimulation()
Callback to handle the service offered by this node to reset th... | 2,890 | en | 0.80704 |
# Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
#
# According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a desce... | 0235-lowest-common-ancestor-of-a-binary-search-tree/lowest-common-ancestor-of-a-binary-search-tree.py | 1,512 | Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST. According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant ... | 1,032 | en | 0.866367 |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** 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 Union
from .. import utilities, tables
class AnalyticsConfigur... | sdk/python/pulumi_aws/s3/analytics_configuration.py | 9,405 | Provides a S3 bucket [analytics configuration](https://docs.aws.amazon.com/AmazonS3/latest/dev/analytics-storage-class.html) resource.
## Example Usage
### Add analytics configuration for entire S3 bucket and export results to a second S3 bucket
```python
import pulumi
import pulumi_aws as aws
example = aws.s3.Bucke... | 4,902 | en | 0.47917 |
import asyncio
import google.protobuf.any_pb2
import irsdk
from asyncio import Queue
from google.protobuf.any_pb2 import Any
from TelemetryDataUtils import getInfo, getGeneral
from models import typed_message_pb2
from models.State import State
class TelemetryLogger:
def __init__(self, receiver_queue: Queue, pu... | logger/TelemetryLogger.py | 2,566 | TODO: Fix this await asyncio.sleep(0.1) TODO: Figure out how to shut off if told too don"t forget to reset your State variables we are shutting down ir library (clearing all internal variables) data per tick since data can change midway | 236 | en | 0.746528 |
from importlib.resources import path
import sys
import os
import shutil
from git import Repo
from subprocess import call
from git import RemoteProgress
import git
from tqdm import tqdm
from pathlib import Path
dir_path = (os.path.expanduser('~/Documents') + "\server")
os.chdir(dir_path)
gitaddress = str("https://gith... | main.py | 1,499 | just in case the program didnt kill it the first time | 53 | en | 0.929999 |
###############################################################################
#
# Tests for XlsxWriter.
#
# SPDX-License-Identifier: BSD-2-Clause
# Copyright (c), 2013-2021, John McNamara, jmcnamara@cpan.org
#
from ..excel_comparison_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompar... | xlsxwriter/test/comparison/test_chart_scatter03.py | 1,455 | Test file created by XlsxWriter against a file created by Excel.
Test the creation of a simple XlsxWriter file.
Tests for XlsxWriter. SPDX-License-Identifier: BSD-2-Clause Copyright (c), 2013-2021, John McNamara, jmcnamara@cpan.org | 233 | en | 0.852814 |
# coding=utf-8
# Copyright 2018 The Tensor2Tensor 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... | tensor2tensor/data_generators/algorithmic.py | 17,505 | Problem spec for algorithmic binary addition task.
Problem spec for algorithmic decimal addition task.
Problem spec for algorithmic binary identity task.
Problem spec for algorithmic decimal identity task.
Problem spec for algorithmic binary multiplication task.
Problem spec for algorithmic decimal multiplication task.... | 7,215 | en | 0.833659 |
from flask import Flask
app = Flask(__name__, static_url_path='', static_folder='static')
app.config['DEBUG'] = True
@app.route('/')
def root():
# Note: this is probably handled by the app engine static file handler.
return app.send_static_file('index.html')
@app.errorhandler(404)
def page_not_found(e):
"""Re... | main.py | 394 | Return a custom 404 error.
Note: this is probably handled by the app engine static file handler. | 98 | en | 0.841423 |
"""
Generating data from the CarRacing gym environment.
!!! DOES NOT WORK ON TITANIC, DO IT AT HOME, THEN SCP !!!
"""
import argparse
from os.path import join, exists
import gym
import numpy as np
from utils.misc import sample_continuous_policy
def generate_data(rollouts, data_dir, noise_type): # pylint: disable=R0914... | data/carracing.py | 2,280 | Generates data
Generating data from the CarRacing gym environment.
!!! DOES NOT WORK ON TITANIC, DO IT AT HOME, THEN SCP !!!
pylint: disable=R0914 The CarRacing-v0 environment has a step limit of 1000, this can be seen in env.spec.max_episode_steps Because these are random policies, most of them will not be done bef... | 346 | en | 0.864667 |
"""
Entradas
Monto de dinero -> int -> a
"""
a = int ( input ( "Ingrese monto de dinero en COP:" ))
b = a
billetes_de_100000 = ( b - b % 100000 ) / 100000
b = b % 100000
billetes_de_50000 = ( b - b % 50000 ) / 50000
b = b % 50000
billetes_de_20000 = ( b - b % 20000 ) / 20000
b = b % 20000
billetes_de_10000 = ( b - b % ... | taller_estructuras_de_control/ejercicio12.py | 1,556 | Entradas
Monto de dinero -> int -> a | 36 | es | 0.701548 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import requests
import json
import datetime
url = 'https://endpoints.office.com/endpoints/worldwide?clientrequestid=b10c5ed1-bad1-445f-b386-b919946339a7'
r = requests.get(url)
service_list = r.json()
lurls= []
lips = []
for service in service_list:
for url in servic... | tools/generate-office365.py | 1,458 | !/usr/bin/env python3 -*- coding: utf-8 -*- | 43 | fr | 0.304089 |
# 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, overload
from ... import _utilities
fro... | sdk/python/pulumi_google_native/compute/alpha/_inputs.py | 882,169 | A specification of the type and number of accelerator cards attached to the instance.
:param pulumi.Input[int] accelerator_count: The number of the guest accelerator cards exposed to this instance.
:param pulumi.Input[str] accelerator_type: Full or partial URL of the accelerator type resource to attach to this instance... | 395,990 | en | 0.797074 |
import sys
import matplotlib.pyplot as plt
import os
root_path = os.path.dirname(os.path.abspath('__file__'))
sys.path.append(root_path)
from tools.models import one_step_esvr, one_step_esvr_multi_seed
from Xianyang_dwt.projects.variables import variables
if __name__ == '__main__':
one_step_esvr_multi_seed(
... | Xianyang_dwt/projects/esvr_one_step.py | 2,889 | hindcast or forecast or hindcast_with_pca_mle or forecast_with_pca_mle hindcast or forecast or hindcast_with_pca_mle or forecast_with_pca_mle hindcast or forecast or hindcast_with_pca_mle or forecast_with_pca_mle hindcast or forecast or hindcast_with_pca_mle or forecast_with_pca_mle hindcast or forecast or hindcast_wit... | 583 | en | 0.560142 |
# -*- coding: utf-8 -*-
# Copyright 2021 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... | tests/st/test_core/test_operators/test_operators_utils.py | 3,388 | Test commutator
Test count_qubits
This is for labelling the spin-orbital index with spin beta
Test hermitian_conjugated for the QubitOperator and Fermion Operator
Test normal_ordered function
Test number operator
This is for labelling the spin-orbital index with spin alpha
Test operator_utils.
-*- coding: utf-8 -*- C... | 985 | en | 0.770826 |
import os
import soft_renderer.functional as srf
import torch, random
import numpy as np
import tqdm
from haven import haven_utils as hu
from PIL import Image, ImageOps, ImageFilter
import torchvision.transforms as transforms
class_ids_map = {
'02691156': 'Airplane',
'02828884': 'Bench',
'02933112': 'Cabi... | src/datasets.py | 8,743 | ind2class = {key: value for (value, key) in enumerate(self.class_ids)} assert n_ratio_val is not None train get only first n unlabeled get only first n positible view points image A image B return list(np.delete(arr, id_to_del)) get image and viewpoint get viewpoint transforms.Normalize(mean=[0.485, 0.456, 0.406], ... | 460 | en | 0.561961 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# (C) British Crown Copyright 2017-2020 Met Office.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the ... | improver/cli/sleet_probability.py | 2,396 | Calculate sleet probability.
Calculates the sleet probability using the
calculate_sleet_probability plugin.
Args:
snow (iris.cube.Cube):
An iris Cube of the probability of snow.
rain (iris.cube.Cube):
An iris Cube of the probability of rain.
Returns:
iris.cube.Cube:
Returns a cube... | 2,014 | en | 0.833927 |
# Copyright 2019 The TensorTrade 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... | tensortrade/wallets/wallet.py | 4,074 | A wallet stores the balance of a specific instrument on a specific exchange.
The total balance of the wallet available for use.
The total balance of the wallet locked in orders.
The total balance of the wallet, both available for use and locked in orders.
Copyright 2019 The TensorTrade Authors. Licensed under the Apa... | 818 | en | 0.860811 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('mig_main', '0003_officerposition_position_type'),
]
operations = [
migrations.CreateModel(
name='Committee',
... | mig_main/migrations/0004_committee.py | 736 | -*- coding: utf-8 -*- | 21 | en | 0.767281 |
# -*- coding: utf-8 -*-
# Author: Jev Kuznetsov <jev.kuznetsov@gmail.com>
# License: BSD
"""
Toolset working with yahoo finance data
This module includes functions for easy access to YahooFinance data
Functions
----------
- `getHistoricData` get historic data for a single symbol
- `getQuote` get cur... | lib/yahooFinance.py | 7,224 | -*- coding: utf-8 -*- Author: Jev Kuznetsov <jev.kuznetsov@gmail.com> License: BSD try float conversion do we have a Billion/Million character? no, convert to float directly failed, return original stringstore = HDFStore(self.dataFile) for codes see: http://www.gummy-stuff.org/Yahoo-data.htmprint fields, len(fi... | 426 | en | 0.430561 |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
#
# Yahoo! Finance market data downloader (+fix for Pandas Datareader)
# https://github.com/ranaroussi/yfinance
"""Yahoo! Finance market data downloader (+fix for Pandas Datareader)"""
from setuptools import setup, find_packages
# from codecs import open
import io
from os... | setup.py | 2,074 | Yahoo! Finance market data downloader (+fix for Pandas Datareader)
!/usr/bin/env python -*- coding: UTF-8 -*- Yahoo! Finance market data downloader (+fix for Pandas Datareader) https://github.com/ranaroussi/yfinance from codecs import open Get the long description from the README file 'Development Status :: 3 - Alpha'... | 355 | en | 0.538845 |
""" render_fmo.py renders obj file to rgb image with fmo model
Aviable function:
- clear_mash: delete all the mesh in the secene
- scene_setting_init: set scene configurations
- node_setting_init: set node configurations
- render: render rgb image for one obj file and one viewpoint
- render_obj: wrapper function for r... | renderer/render_fmo.py | 18,376 | clear all meshes in the secene
init everything we need for rendering
an image
render rbg image
render a object rgb image by a given camera viewpoint and
choose random image as background, only render one image
at a time.
Args:
obj_path: a string variable indicate the obj file path
viewpoint: a vp param... | 2,792 | en | 0.457395 |
import json
from urllib.parse import parse_qs
from urllib.parse import urlparse
from Cryptodome.PublicKey import RSA
from jwkest import b64e
from jwkest.jwk import RSAKey
from jwkest.jwk import load_jwks
from oic.extension.message import TokenIntrospectionResponse
from oic.extension.signed_http_req import SignedHttpR... | src/oic/extension/pop.py | 4,202 | Map access token to a keypair.
:param resp: AccessTokenResponse instance
Store key that was returned in response from token introspection.
:param access_token: The token that was introspected
:param tir: TokenIntrospectionResponse instance
Use to 'update' the AccessToken Request.
:param msg:
:param state: Used to ma... | 465 | en | 0.853964 |
#!/usr/bin/python
from Adafruit_CharLCDPlate import Adafruit_CharLCDPlate
from subprocess import *
from time import sleep, strftime
from datetime import datetime
from mpd import *
import threading
import signal
import sys
import os
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import json
PLAY=0
PAUS... | pimp3clock.py | 9,609 | !/usr/bin/python create LCD object create MPD client object Load Database into current playlist Special Characters Special Characters Special Characters Causing thread to stop when main process ends. Causing thread to stop when main process ends. connect to localhost:6600 SELECT RIGHT DOWN UP LEFT send the close comman... | 348 | en | 0.815194 |
"""Backup handler
This script is contains the backup handling functions.
"""
import os
import time
import pickle
import shutil
from shutil import ignore_patterns
import pypianoroll
import numpy as np
def backup_pickle(experiment, stats):
''''
Back up handling function.
Arguments:
experiment -- Expe... | utils/backup.py | 2,041 | '
Back up handling function.
Arguments:
experiment -- Experiment object, contains the initial sorn parameters
stats -- bunch of stats stored during the simulation
Backup handler
This script is contains the backup handling functions.
creates a new directory for storing the results sleeps for a short time to avoid co... | 470 | en | 0.794384 |
from devices import network_devices
from napalm import get_network_driver
from pprint import pprint
def open_napalm_connection(device):
"""Funtion to open napalm connection and return connection object"""
# Copy dictionary to ensure original object is not modified
device=device.copy()
# Pop "platform"... | day3/linting/exercise1.py | 1,061 | Funtion to open napalm connection and return connection object
Copy dictionary to ensure original object is not modified Pop "platform" as this is an invalid kwarg to napalm Close the NAPALM connection | 203 | en | 0.805035 |
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 12 11:56:36 2017
Problemset1 - Problem 1
Note:
's' is given by system like s = 'azcbobobegghakl'
@author: coskun
"""
s = 'azcbobobegghakl'
# Paste your code into this box
nvl=0
for c in s:
if c=='a' or c=='e' or c=='i' or c=='o' or c=='u':
nvl += 1
print(... | anaconda/6.00.1x.PSet1.P1.py | 352 | Created on Sun Feb 12 11:56:36 2017
Problemset1 - Problem 1
Note:
's' is given by system like s = 'azcbobobegghakl'
@author: coskun
-*- coding: utf-8 -*- Paste your code into this box | 190 | en | 0.837984 |
import psycopg2
# Returns connection to the DB
def get_sql_connection():
conn = psycopg2.connect(user="cqwhbabxmaxxqd",
password="a3063dc5aeec69b41564cd0f1e3c698e0ff9653385f3b87c0f113b70951eb5b3",
host="ec2-54-235-92-244.compute-1.amazonaws.com",
... | Attendance/context/sql_connection.py | 421 | Returns connection to the DB | 28 | en | 0.693818 |
####################################################################################
# Jiten Dhandha, 2020 #
# CFit is a curve fitting tool in python, based on the method of least squares. #
# It comes equipped with some standard functions and a graphic... | Fitting.py | 36,425 | Jiten Dhandha, 2020 CFit is a curve fitting tool in python, based on the method of least squares. It comes equipped with some standard functions and a graphical user interface. ... | 4,576 | en | 0.703767 |
# -*- coding: utf-8 -*-
# @Author: jankincai
# @Date: 2021-01-26 23:18:43
# @Last Modified by: jankincai
# @Last Modified time: 2021-01-26 23:27:01
class LibpcapError(Exception):
"""Exception raised for errors in the libpcap.
"""
def __init__(self, message):
"""init
"""
self.... | pylibpcap/exception.py | 406 | Exception raised for errors in the libpcap.
init
-*- coding: utf-8 -*- @Author: jankincai @Date: 2021-01-26 23:18:43 @Last Modified by: jankincai @Last Modified time: 2021-01-26 23:27:01 | 206 | en | 0.604112 |
import os
import numpy as np
import matplotlib.pyplot as plt
# import sys, os
# sys.path.append(os.path.join(os.path.dirname(__file__), 'utils'))
import process_data
import common
def plot_gt(Y_origin_data, pose_folder, preprocessed_folder, data_seqs, seq_sizes, dim="2d", save_graph=True, dataset="KITTI"):
star... | utils/plot.py | 3,384 | import sys, os sys.path.append(os.path.join(os.path.dirname(__file__), 'utils')) 3d plt.close(fig) 3d plt.close(fig) | 116 | fa | 0.120761 |
"""
Module for handling the custom Lua commands for the bot
"""
import lupa
import shlex
import time
from threading import Thread
from .utils import human_readable_time, ArgumentParser
from .http import Http, TupleData
from .timer import Interval, Delayed
from .chat import Chat
class CommandPermissionError(BaseExcep... | bot/commandmanager.py | 14,566 | An exception that happens when a user tries to execute a custom command
during it's cooldown period.
Manager for custom commands
An exception that happens when a user tries to execute a custom command
without the appropriate user level for it.
A simple structure to allow Lua to store and read data from the database
Ca... | 3,982 | en | 0.779221 |
from typing import List, Optional, Union
from dataclasses import dataclass, field
## - - - - - - -
## userinfo.json
## - - - - - - -
@dataclass
class UserAddress:
formatted: str = ""
@dataclass
class UserInfoResponse:
group_ids: List[str] = field(default_factory=list)
sub: str = ""
given_name: str ... | frameworks/schema_dataclasses.py | 2,178 | - - - - - - - userinfo.json - - - - - - - - - - - - - - sprint.json - - - - - - - - - - - - - - create-task.json - - - - - - - - - - - - - - update-task.json - - - - - - - | 171 | it | 0.329307 |
#
# Copyright (c) 2016-2022 Deephaven Data Labs and Patent Pending
#
import os
import unittest
from deephaven import kafka_consumer as ck
from deephaven.stream.kafka.consumer import TableType, KeyValueSpec
from tests.testbase import BaseTestCase
from deephaven import dtypes
class KafkaConsumerTestCase(BaseTestCase)... | py/server/tests/test_kafka_consumer.py | 7,835 | Check an Avro Kafka subscription creates the right table.
Check that the basic constants are imported and visible.
Tests to make sure deprecated TableTypes are equivalent
Check a JSON Kafka subscription creates the right table.
Check a simple Kafka subscription creates the right table.
Tests TableType construction
Co... | 380 | en | 0.645784 |
import re
from base64 import b64decode
from datetime import datetime
from urllib.parse import urlparse
import marshmallow as ma
from app.objects.secondclass.c_link import Link
from app.utility.base_object import BaseObject
from app.utility.base_planning_svc import BasePlanningService
class Agent(BaseObject):
R... | app/objects/c_agent.py | 7,948 | Creates an Agent object from parameters stored in a dict. AgentSchema is used to validate inputs. | 97 | en | 0.640321 |
#!/usr/bin/env python
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# ---------------------------------------------... | src/connection-monitor-preview/setup.py | 1,976 | !/usr/bin/env python -------------------------------------------------------------------------------------------- Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. -------------------------------------------------------... | 458 | en | 0.432038 |
# ------------------------------------------------------------------------------
# CodeHawk Binary Analyzer
# Author: Henny Sipma
# ------------------------------------------------------------------------------
# The MIT License (MIT)
#
# Copyright (c) 2016-2020 Kestrel Technology LLC
# Copyright (c) 2020 Henny Si... | chb/util/dotutil.py | 3,201 | Utilities to print and save graphviz dot files.
------------------------------------------------------------------------------ CodeHawk Binary Analyzer Author: Henny Sipma ------------------------------------------------------------------------------ The MIT License (MIT) Copyright (c) 2016-2020 Kestrel Technology LL... | 1,546 | en | 0.757498 |
# qubit number=3
# total number=9
import numpy as np
from qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ
import networkx as nx
from qiskit.visualization import plot_histogram
from typing import *
from pprint import pprint
from math import log2
from collection... | data/p4VQE/R1/benchmark/startQiskit_Class82.py | 2,395 | qubit number=3 total number=9 circuit begin number=1 number=2 number=3 number=4 number=5 number=6 number=7 number=8 circuit end prog.draw('mpl', filename=(kernel + '.png')) | 172 | en | 0.175413 |
# flake8: noqa
"""
OpenAPI definition
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: v0
Generated by: https://openapi-generator.tech
"""
__version__ = "0.6.0"
# import ApiClient
from good... | gooddata-afm-client/gooddata_afm_client/__init__.py | 814 | OpenAPI definition
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: v0
Generated by: https://openapi-generator.tech
flake8: noqa import ApiClient import Configuration import exceptions | 297 | en | 0.568822 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from matplotlib import pyplot as plt
import tensorflow as tf
import seaborn as sb
import pandas as pd
import numpy as np
import math
import time
import cv2
import os
tf.reset_default_graph()
gpu_options = tf.G... | classification/casiab_performance.py | 7,911 | tip: if you run into problems with TensorBoard clear the contents of this directory, re-run this script then restart TensorBoard to see the result LOGDIR = './graphs' dropout (keep probability) label = np.zeros(shape=[num_classes], dtype='float32') label[int(_index) - 1] = 1 return label if not model_angle_dict[angle]:... | 1,284 | en | 0.508491 |
"""
Parsing time durations from strings
This module provides a function that parses time durations from strings. It has
been copied from the django software, which comes with the following notes:
Copyright (c) Django Software Foundation and individual contributors.
All rights reserved.
Redistribution and use in sour... | pde/tools/parse_duration.py | 4,077 | Parse a duration string and return a datetime.timedelta.
Args:
value (str): A time duration given as text. The preferred format for
durations is '%d %H:%M:%S.%f'. This function also supports ISO 8601
representation and PostgreSQL's day-time interval format.
Returns:
datetime.timedelta: An inst... | 2,363 | en | 0.861665 |
class solution:
def twoSum(self,nums,target):
hash_map=dict()
# Python字典初始化{}性能比dict()好
for i,x in enumerate(nums):
if target-x in hash_map:
return [i,hash_map[target-x]]
hash_map[x]=i
| LeetCode/Leetcode-2019Summer/Leetcode001(a+b).py | 281 | Python字典初始化{}性能比dict()好 | 23 | zh | 0.187498 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2015-2017 Lionheart Software 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
... | setup.py | 2,138 | !/usr/bin/env python -*- coding: utf-8 -*- Copyright 2015-2017 Lionheart Software 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... | 660 | en | 0.797893 |
# -*- coding: utf-8 -*-
"""
test_searchadapters
~~~~~~~~~~~~~~~~~~~
Test the Web Support Package search adapters.
:copyright: Copyright 2007-2017 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from six import StringIO
from sphinx.websupport import WebSupport
from t... | tests/test_searchadapters.py | 2,283 | test_searchadapters
~~~~~~~~~~~~~~~~~~~
Test the Web Support Package search adapters.
:copyright: Copyright 2007-2017 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
-*- coding: utf-8 -*- Test the adapters query method. A search for "Epigraph" should return one result. Make sure documents a... | 524 | en | 0.778586 |
from __future__ import division, print_function, absolute_import
from subprocess import Popen, PIPE, STDOUT
import numpy as np
SZ = [2, 3, 4, 8, 12, 15, 16, 17, 32, 64, 128, 256, 512, 1024]
def gen_data(dt):
arrays = {}
if dt == np.float128:
pg = './fftw_longdouble'
elif dt == np.double:
... | environment/lib/python3.8/site-packages/scipy/fftpack/tests/gen_fftw_ref.py | 1,989 | Generate test data using FFTW for reference generate single precision data Save ref data into npz format generate double precision data Save ref data into npz format generate long double precision data Save ref data into npz format | 231 | en | 0.285886 |
# coding: utf-8
import numpy as np
import csv
import codecs
import os
import glob
from collections import defaultdict
SPACE = " "
EMPTY = " "
INV_PUNCTUATION_CODES = {EMPTY:0, SPACE:0, ',':1, '.':2, '?':3, '!':4, '-':5, ';':6, ':':7, '...':8, '':0}
PUNCTUATION_VOCABULARY = {0:SPACE, 1:',', 2:'.', 3:'?', 4:'!', 5:'-', ... | utilities.py | 4,320 | coding: utf-8PAUSE_FEATURE_NAME = 'pause_before'ALL_POSSIBLE_INPUT_FEATURES = {'word', 'pos', 'pause_before', 'speech_rate_norm', 'f0_mean', 'f0_range', 'i0_mean', 'i0_range'} each value in each column is appended to a list read rows into a dictionary format read a row as {column1: value1, column2: value2,...} go over ... | 449 | en | 0.674114 |
# (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org)
# Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
def asbool(obj):
if isinstance(obj, str):
obj = obj.strip().lower()
if obj in ['true', 'yes', 'on', 'y', 't', '1']:
r... | ita/web/beaker/converters.py | 844 | (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org) Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php | 164 | en | 0.590981 |
# Copyright (c) 2016 Universidade Federal Fluminense (UFF)
# Copyright (c) 2016 Polytechnic Institute of New York University.
# This file is part of noWorkflow.
# Please, consult the license terms in the LICENSE file.
"""Trial Model"""
from __future__ import (absolute_import, print_function,
div... | capture/noworkflow/now/persistence/models/trial.py | 20,967 | Represent a trial
Initialize it by passing a trial reference:
trial = Trial(2)
There are four visualization modes for the graph:
tree: activation tree without any filters
trial.graph.mode = 0
no match: tree transformed into a graph by the addition of sequence and
return edges and rem... | 4,126 | en | 0.602481 |
import Tkinter as tk
class Combobox(tk.Label):
def __init__(self, master, choices=[], default=None, direction="down", arrowimage="default", **kwargs):
style = {"relief": "groove", "bg":"white"}
style.update(kwargs)
tk.Label.__init__(self, master, **style)
# options
if direc... | dependencies/generate maps/pythongis/app/tk2/_othermisc/dropdown_works.py | 2,337 | options entry dropdown arrow image should be passed as a Photoimagemenu.winfo_height() | 86 | en | 0.565041 |
#------------------Bombermans Team---------------------------------#
# Author : B3mB4m
# Concat : b3mb4m@protonmail.com
# Project : https://github.com/b3mb4m/Shellsploit
# LICENSE : https://github.com/b3mb4m/Shellsploit/blob/master/LICENSE
#------------------------------------------------------------------#
import ... | shell/control.py | 44,167 | ------------------Bombermans Team--------------------------------- Author : B3mB4m Concat : b3mb4m@protonmail.com Project : https://github.com/b3mb4m/Shellsploit LICENSE : https://github.com/b3mb4m/Shellsploit/blob/master/LICENSE------------------------------------------------------------------ Injectors elif termin... | 1,578 | en | 0.419671 |
import numpy as np
from .State import State
from .Action import Action
'''
Includes blood glucose level proxy for diabetes: 0-3
(lo2, lo1, normal, hi1, hi2); Any other than normal is "abnormal"
Initial distribution:
[.05, .15, .6, .15, .05] for non-diabetics and [.01, .05, .15, .6, .19] for diabetics
Effect o... | sepsisSimDiabetes/MDP.py | 12,519 | initialize the simulator
use to start MDP over. A few options:
Full specification:
1. Provide state_idx with idx_type = 'obs' + diabetic_idx
2. Provide state_idx with idx_type = 'full', diabetic_idx is ignored
3. Provide state_idx with idx_type = 'proj_obs' + diabetic_idx*
* This option will set glucose to a normal ... | 1,772 | en | 0.747253 |
import random
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.metrics import mean_squared_error as mse
from sklearn import datasets
import unittest
import torch
from fastai.basic_train import Learner
from fastai.callbacks import OneCycleScheduler
from fastai.... | dies/dies/tests/test_regression.py | 10,313 | adds some small tolerance | 25 | en | 0.613665 |
import argparse
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
from net.tf_net import \
calculate_accuracy, calculate_loss, \
create_simple_cnn_model, optimize_weights
from net.keras_net import simple_cnn
def train_keras(batch_size, epochs, n_classes):
# x_train return... | 00_MNIST-label/train.py | 4,526 | x_train returns data with shape (60,000,28,28) y_train returns data with shape (60,000,) add one dimension for color chanel (only gray values) define input shape of image convert tensor to float normalize data: divide by 255 (max color value) to receive values between 0 and 1 one-hot encoding: converts into array of le... | 590 | en | 0.764545 |
#!/usr/bin/env python3
from matplotlib.patches import Circle, Rectangle, ConnectionPatch
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import animation
from math import floor
Colors = ['green', 'purple', 'orange', 'red', 'blue', 'yellow']
class Animation:
def __init__(self, my_map, starts, g... | visualize.py | 6,965 | !/usr/bin/env python3 self.ax.set_frame_on(False) create boundary patch draw goals create agents connections & predictions per ogni agente per ogni goal Linee Percentuali reset all colors check drive-drive collisions | 216 | en | 0.495137 |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
import torch.nn.functional as F
from torch import nn
from fcos_core.structures.bounding_box import BoxList
from fcos_core.structures.boxlist_ops import boxlist_nms
from fcos_core.structures.boxlist_ops import cat_boxlist
from ... | fcos_core/modeling/roi_heads/box_head/inference.py | 6,830 | From a set of classification scores, box regression and proposals,
computes the post-processed boxes, and applies NMS to obtain the
final results
Arguments:
score_thresh (float)
nms (float)
detections_per_img (int)
box_coder (BoxCoder)
Returns bounding-box detection results by thresholding on scores and... | 1,752 | en | 0.843109 |
from __future__ import annotations
import datetime
from functools import partial
from textwrap import dedent
from typing import TYPE_CHECKING
import warnings
import numpy as np
from pandas._libs.tslibs import Timedelta
import pandas._libs.window.aggregations as window_aggregations
from pandas._typing import (
Ax... | pandas/core/window/ewm.py | 30,704 | Provide exponential weighted (EW) functions.
Available EW functions: ``mean()``, ``var()``, ``std()``, ``corr()``, ``cov()``.
Exactly one parameter: ``com``, ``span``, ``halflife``, or ``alpha`` must be
provided.
Parameters
----------
com : float, optional
Specify decay in terms of center of mass,
:math:`\al... | 8,027 | en | 0.58862 |
# -*- coding: utf-8 -*-
"""
Production Configurations
- Use Amazon's S3 for storing static files and uploaded media
- Use mailgun to send emails
- Use Redis for cache
"""
from __future__ import absolute_import, unicode_literals
from django.utils import six
from .common import * # noqa
# SECRET CONFIGURATION
# -... | config/settings/production.py | 3,904 | Production Configurations
- Use Amazon's S3 for storing static files and uploaded media
- Use mailgun to send emails
- Use Redis for cache
-*- coding: utf-8 -*- noqa SECRET CONFIGURATION ------------------------------------------------------------------------------ See: https://docs.djangoproject.com/en/dev/ref/sett... | 2,197 | en | 0.460336 |
import torch
from mmcv.cnn import ConvModule
from torch import nn as nn
from mmdet3d.models.builder import build_loss
class VoteModule(nn.Module):
"""Vote module.
Generate votes from seed point features.
Args:
in_channels (int): Number of channels of seed point features.
vote_per_seed (... | mmdet3d/models/model_utils/vote_module.py | 5,378 | Vote module.
Generate votes from seed point features.
Args:
in_channels (int): Number of channels of seed point features.
vote_per_seed (int): Number of votes generated from each seed point.
gt_per_seed (int): Number of ground truth votes generated
from each seed point.
conv_channels (tuple[in... | 1,711 | en | 0.76329 |
"""Import/export any formats supported by meshio."""
import meshio
import numpy as np
import skfem
MESH_TYPE_MAPPING = {
'tetra': skfem.MeshTet1,
'tetra10': skfem.MeshTet2,
'hexahedron': skfem.MeshHex1,
'hexahedron27': skfem.MeshHex2,
'wedge': skfem.MeshWedge1,
'triangle': skfem.MeshTri1,
... | skfem/io/meshio.py | 7,062 | Import/export any formats supported by meshio.
TODO support quadratic facets TODO TODO TODO detect 3D detect 2D detect 1D create p and t reorder t if needed parse any subdomains from cell_sets create temporary mesh for matching boundary elements parse boundaries from cell_sets MSH 2.2 tag parsing find tagged boundari... | 505 | en | 0.631504 |
from __future__ import annotations
from abc import abstractmethod, ABC
from decimal import Decimal
from enum import Enum
from typing import Dict, cast
import numpy as np
# A few extra general types
from slim.simulation.lice_population import LicePopulation, GenoDistrib, GenoTreatmentValue,\
Alleles, GenoTreatmen... | slim/types/TreatmentTypes.py | 6,598 | Trait for all chemical treatments
Emamectin Benzoate
Genetic mechanism to be used when generating egg genotypes
Resistance in a monogenic, heterozygous setting.
Trait for all thermal-based treatments
A stub for treatment types
TODO: add other treatments here
Abstract class for all the treatments
Get the mortality perce... | 1,248 | en | 0.841336 |
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Tests for L{twisted.logger._json}.
"""
from io import BytesIO, StringIO
from typing import IO, Any, List, Optional, Sequence, cast
from zope.interface import implementer
from zope.interface.exceptions import BrokenMethodImplementation
from z... | SCRAPE/Lib/site-packages/twisted/logger/test/test_json.py | 18,274 | Tests for L{jsonFileLogObserver}.
Tests for L{eventsFromJSONLogFile}.
Tests for loading and saving log events.
Test that L{eventsFromJSONLogFile} reads two pre-defined events from a
file: C{{"x": 1}} and C{{"y": 2}}.
@param inFile: C{inFile} argument to L{eventsFromJSONLogFile}
@param recordSeparator: C{recordSeparato... | 4,957 | en | 0.860309 |
# -*- coding: utf-8 -*-
###############################################################################
#
# RetrieveCoupon
# Retrieves a coupon with specified coupon id.
#
# Python versions 2.6, 2.7, 3.x
#
# Copyright 2014, Temboo Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not u... | temboo/Library/Stripe/Coupons/RetrieveCoupon.py | 3,185 | An InputSet with methods appropriate for specifying the inputs to the RetrieveCoupon
Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
A ResultSet with methods tailored to the values returned by the RetrieveCoupon Choreo.
The ResultSet object is used to retrieve the results of ... | 1,480 | en | 0.729086 |
# coding=utf-8
# Copyright (c) 2019 Alibaba PAI team.
#
# 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 ... | easytransfer/losses/kd_loss.py | 3,746 | coding=utf-8 Copyright (c) 2019 Alibaba PAI team. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writ... | 617 | en | 0.852806 |
# -*- coding: utf-8 -*-
"""Look command."""
# Part of Clockwork MUD Server (https://github.com/whutch/cwmud)
# :copyright: (c) 2008 - 2017 Will Hutcheson
# :license: MIT (https://github.com/whutch/cwmud/blob/master/LICENSE.txt)
from .. import Command, COMMANDS
from ...characters import CharacterShell
@COMMANDS.regis... | cwmud/core/commands/info/look.py | 753 | A command to allow a character to look at things.
Look command.
-*- coding: utf-8 -*- Part of Clockwork MUD Server (https://github.com/whutch/cwmud) :copyright: (c) 2008 - 2017 Will Hutcheson :license: MIT (https://github.com/whutch/cwmud/blob/master/LICENSE.txt) | 265 | en | 0.756116 |
# coding: utf-8
#
# Copyright 2019 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "lice... | ask-smapi-model/ask_smapi_model/v1/skill/status.py | 1,814 | Status of a resource.
Allowed enum values: [FAILED, IN_PROGRESS, SUCCEEDED]
Returns true if both objects are equal
Returns true if both objects are not equal
For `print` and `pprint`
Returns the model properties as a dict
Returns the string representation of the model
coding: utf-8 Copyright 2019 Amazon.com, Inc. ... | 934 | en | 0.831765 |
"""
Modified from
https://github.com/ikostrikov/pytorch-a2c-ppo-acktr/blob/master/storage.py
"""
import torch
from torch.utils.data.sampler import BatchSampler
from torch.utils.data.sampler import SubsetRandomSampler
class RolloutStorage(object):
def __init__(self, num_steps, num_processes, obs_shape, action_sp... | ADMCode/snuz/ppo/storage.py | 6,477 | Modified from
https://github.com/ikostrikov/pytorch-a2c-ppo-acktr/blob/master/storage.py
pdb.set_trace()pdb.set_trace() | 121 | en | 0.493009 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import collections
from django.db import migrations
import mptt
import mptt.managers
def copy_regulations(apps, schema_editor):
Regulation = apps.get_model('regcore', 'Regulation')
Document = apps.get_model('regcore', 'Document')
for reg i... | regcore/migrations/0012_migrate_documents.py | 5,236 | Create the Django object
Build mapping from node IDs to child records
:param regs: List of `Regulation` records
Set tree properties in memory.
-*- coding: utf-8 -*- Bind manager Bind manager Copy lightly modified import helpers | 234 | en | 0.705053 |
# 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
__a... | sdk/python/pulumi_azure_nextgen/machinelearningservices/v20200601/get_workspace_connection.py | 4,906 | Workspace connection.
Authorization type of the workspace connection.
Category of the workspace connection.
Workspace connection.
:param str connection_name: Friendly name of the workspace connection
:param str resource_group_name: Name of the resource group in which workspace is located.
:param str workspace_name: N... | 761 | en | 0.861981 |
import aiohttp, asyncio
from bs4 import BeautifulSoup
import json
import time
VC_SEARCH = "https://vc.ru/search/v2/content/new"
async def parse_urls(key_word):
async with aiohttp.ClientSession() as session:
async with session.get(VC_SEARCH, params={
"query": key_word,
"target_type... | Parsers/vcru.py | 1,580 | with open(result_file_path, 'w', encoding='utf-8') as f: json.dump(result_json, f, ensure_ascii=False, indent=4) | 112 | en | 0.718409 |
#!/usr/bin/env runaiida
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import print_function
__copyright__ = (u"Copyright (c), 2016, Forschungszentrum Jülich GmbH, "
"IAS-1/PGI-1, Germany. All rights reserved.")
__license__ = "MIT license, see LICENSE.txt file"
__versio... | examples/old_workflowtests/test_run_scf2.py | 2,331 | !/usr/bin/env runaiida -*- coding: utf-8 -*- If set to True, will ask AiiDA to run in serial mode (i.e., AiiDA will not invoke the mpirun command in the submission script)False get where tests folder is, then relative path})remote_data= remote, fleur=code) | 256 | en | 0.644342 |
"""
Copyright (c) 2008-2020, Jesus Cea Avion <jcea@jcea.es>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of... | Lib3/bsddb/test/test_db.py | 7,322 | Copyright (c) 2008-2020, Jesus Cea Avion <jcea@jcea.es>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of con... | 1,879 | en | 0.819945 |
from dataclasses import dataclass, field
from datetime import datetime # for typehinting
from typing import TYPE_CHECKING, Generator, List, Literal, Optional
import aiohttp
import dateparser
from .exceptions import UnsupportedRegionError
from .pricing import PriceQuery, query_price
COUNT = 30 # Items per page of ... | nsecpy/listing.py | 4,463 | for typehinting Items per page of paginated response pragma: no cover JP Field JP Field Literal["game", "bundle"] ??? expand and replace hint TODO: is this dateparser correct? | 175 | en | 0.55199 |
from collections import defaultdict
from typing import Dict, Tuple, Iterator, Callable, Any, Optional
from dataclasses import dataclass
"""
Provides the `TaggedProfiler` class related to record profiling.
TODO: Better description needed.
"""
@dataclass
class TaggedProfilerRecordStatus:
offset: int
tag: str
... | caixa/profile/tagged.py | 2,865 | A useful tag-based profiler class which we'll describe when we have more time.
Provides the most useful summary counts you'll likely want from the incoming record sequence.
Optional :index and :deep flags allow us to return special indexing and cachinc structs which we'll describe later.
We use underscores for all "r... | 394 | en | 0.877636 |
import collections
class CaseInsensitiveDict(collections.MutableMapping):
"""
A case-insensitive ``dict``-like object.
Implements all methods and operations of
``collections.MutableMapping`` as well as dict's ``copy``. Also
provides ``lower_items``.
All keys are expected to be strings. The s... | anillo/utils/structures.py | 2,399 | A case-insensitive ``dict``-like object.
Implements all methods and operations of
``collections.MutableMapping`` as well as dict's ``copy``. Also
provides ``lower_items``.
All keys are expected to be strings. The structure remembers the
case of the last key to be set, and ``iter(instance)``,
``keys()``, ``items()``, ... | 1,087 | en | 0.806926 |
# -*- coding: utf-8 -*-
# This is a simple mailbox polling script for the Sahana Messaging Module
# If there is a need to collect from non-compliant mailers then suggest using the robust Fetchmail to collect & store in a more compliant mailer!
# This script doesn't handle MIME attachments
import sys, socket, email, ... | cron/email_receive.py | 5,826 | -*- coding: utf-8 -*- This is a simple mailbox polling script for the Sahana Messaging Module If there is a need to collect from non-compliant mailers then suggest using the robust Fetchmail to collect & store in a more compliant mailer! This script doesn't handle MIME attachments Read-in configuration from Database ht... | 1,411 | en | 0.762722 |
"""
Module to wrap an integer in bitwise flag/field accessors.
"""
from collections import OrderedDict
from pcapng.ngsix import namedtuple, Iterable
class FlagBase(object):
"""\
Base class for flag types to be used in a Flags object.
Handles the bitwise math so subclasses don't have to worry about it.
... | pcapng/flags.py | 6,303 | Base class for flag types to be used in a Flags object.
Handles the bitwise math so subclasses don't have to worry about it.
Object representing a single boolean flag
Object representing a range of values stored in part of a larger
bitfield
Object representing an unsigned integer of the given size stored in
a larger bi... | 859 | en | 0.747435 |
"""
Unit tests for nltk.tokenize.
See also nltk/test/tokenize.doctest
"""
import pytest
from nltk.tokenize import (
punkt,
word_tokenize,
TweetTokenizer,
StanfordSegmenter,
TreebankWordTokenizer,
SyllableTokenizer,
LegalitySyllableTokenizer,
)
def setup_module(module):
import pytest
... | nltk/test/unit/test_tokenize.py | 17,387 | Test LegalitySyllableTokenizer tokenizer.
Test padding of asterisk for word tokenization.
Test padding of dotdot* for word tokenization.
Test a string that resembles a phone number but contains a newline
Test remove_handle() from casual.py with specially crafted edge cases
Test SyllableTokenizer tokenizer.
Test the Sta... | 1,786 | en | 0.84219 |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import torch
from detr.models.backbone import Backbone, Joiner
from detr.models.detr import DETR, PostProcess
from detr.models.position_encoding import PositionEmbeddingSine
from detr.models.segmentation import DETRsegm, PostProcessPanoptic
from de... | detr/hubconf.py | 6,290 | DETR-DC5 R101 with 6 encoder and 6 decoder layers.
Achieves 43.5/63.8 AP/AP50 on COCO val5k.
DETR-DC5 R101 with 6 encoder and 6 decoder layers.
The last block of ResNet-101 has dilation to increase
output resolution.
Achieves 44.9/64.7 AP/AP50 on COCO val5k.
DETR-DC5 R101 with 6 encoder and 6 decoder layers.
Achie... | 1,166 | en | 0.810585 |
"""
'storage-add ' sub command
"""
#To prevent Py2 to interpreting print(val) as a tuple.
from __future__ import print_function
import os
import tempfile
import sys
import json
import utils
from storage_yaml import to_storage_yaml
# noqa # pylint: disable=too-many-branches
def set_args(name, subparsers):
""" a... | cli/kubectl_kadalu/storage_add.py | 7,886 | gets all nodes
Adds the subcommand arguments back to main CLI tool
add arguments, and their options
Build the config file
validate arguments
'storage-add ' sub command
To prevent Py2 to interpreting print(val) as a tuple. noqa pylint: disable=too-many-branches Set type to External as '--external' option is prov... | 691 | en | 0.727748 |
# Copyright 2018-2020 Xanadu Quantum Technologies 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... | pennylane/operation.py | 61,709 | A mixin base class denoting a continuous-variable operation.
Base class for continuous-variable observables.
The class attribute :attr:`~.ev_order` can be defined to indicate
to PennyLane whether the corresponding CV observable is a polynomial in the
quadrature operators. If so,
* ``ev_order = 1`` indicates a first o... | 33,729 | en | 0.708858 |
from __future__ import absolute_import, print_function
from django.conf import settings
CLIENT_ID = getattr(settings, "GITHUB_APP_ID", None)
CLIENT_SECRET = getattr(settings, "GITHUB_API_SECRET", None)
REQUIRE_VERIFIED_EMAIL = getattr(settings, "GITHUB_REQUIRE_VERIFIED_EMAIL", False)
ERR_NO_ORG_ACCESS = "You do no... | src/sentry/auth/providers/github/constants.py | 1,417 | we request repo as we share scopes with the other GitHub integration deprecated please use GITHUB_API_DOMAIN and GITHUB_BASE_DOMAIN | 131 | en | 0.730895 |
from OpenGL.GL import *
from .. GLGraphicsItem import GLGraphicsItem
from .. MeshData import MeshData
from pyqtgraph.Qt import QtGui
import pyqtgraph as pg
from .. import shaders
import numpy as np
__all__ = ['GLMeshItem']
class GLMeshItem(GLGraphicsItem):
"""
**Bases:** :class:`GLGraphicsItem <pyqtgraph.op... | pyqtgraph/opengl/items/GLMeshItem.py | 2,274 | **Bases:** :class:`GLGraphicsItem <pyqtgraph.opengl.GLGraphicsItem>`
Displays a 3D triangle mesh.
See :class:`MeshData <pyqtgraph.opengl.MeshData>` for initialization arguments.
glAlphaFunc( GL_ALWAYS,0.5 )l = glGenLists(1)self.meshList = lglNewList(l, GL_COMPILE)glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)glEn... | 609 | en | 0.360596 |
import os, sys
try:
import MacOS
except:
MacOS = None
from pygame.pkgdata import getResource
from pygame import sdlmain_osx
__all__ = ['Video_AutoInit']
def Video_AutoInit():
"""This is a function that's called from the c extension code
just before the display module is initialized"""
if Mac... | venv/Lib/site-packages/pygame/macosx.py | 961 | This is a function that's called from the c extension code
just before the display module is initialized | 104 | en | 0.938029 |
import sys
from pathlib import Path, PurePath
sys.path.append("./models/research/object_detection/")
sys.path.append("./models/research/")
import os
import cv2
import numpy as np
import tensorflow as tf
from utils import label_map_util
from utils import visualization_utils as vis_util
from image_to_video_co... | detection.py | 8,876 | Define input and output tensors (i.e. data) for the object detection classifier Order taken from: https://www.tensorflow.org/api_docs/python/tf/image/draw_bounding_boxes Cast float coordinates to integers Set up logging file Draw boxes Log boxes Save frame with boxes for output Save frame with boxes Open video file Set... | 402 | en | 0.678785 |
#!/usr/bin/env python
#
# mri_convert_ppc64 ds ChRIS plugin app
#
# (c) 2016-2019 Fetal-Neonatal Neuroimaging & Developmental Science Center
# Boston Children's Hospital
#
# http://childrenshospital.org/FNNDSC/
# dev@babyM... | mri_convert_ppc64/mri_convert_ppc64.py | 8,729 | This calls a pre-built PPC64 'mri_convert' that is housed in a base container..
Define the CLI arguments accepted by this plugin app.
Use self.add_argument to specify a new app argument.
Define the code to be run by this plugin app.
Print the app's man page.
!/usr/bin/env python ... | 1,433 | en | 0.700385 |
from typing import Tuple, FrozenSet
from collections import Iterable
from mathsat import msat_term, msat_env
from mathsat import msat_make_constant, msat_declare_function
from mathsat import msat_get_integer_type, msat_get_rational_type, msat_get_bool_type
from mathsat import msat_make_and, msat_make_not, msat_mak... | benchmarks/f3_wrong_hints_permutations/scaling_ltl_infinite_state/12-extending_bound_39.py | 8,625 | r' = r i < l -> ((inc_i' & i' = i + 1) | (!inc_i' & i' = i)) & l' = l i >= l -> i' = 0 & l' = l + 1 & !inc_i' (G F inc_i) -> ! G F r > i | 136 | en | 0.457986 |
# MIT License
# Copyright (c) 2018 the NJUNMT-pytorch authors.
# 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, m... | src/tasks/lm.py | 28,718 | :type model: nn.Module
:type critic: NMTCriterion
Args:
nmt_model: model.
pretrain_path ('str'): path to pretrained model.
map_dict ('dict'): mapping specific parameter names to those names
in current model.
exclude_prefix ('dict'): excluding parameters with specific names
for pretraini... | 3,600 | en | 0.64091 |
"""Class definition of the ZoneSpeaker."""
import bisect
import functools
from typing import Any, Callable, List, Tuple
import simulation_groundtruth.srv as groundtruth_srv
from simulation_evaluation.msg import Speaker as SpeakerMsg
from simulation_groundtruth.msg import LabeledPolygon as LabeledPolygonMsg
from simul... | simulation/src/simulation_evaluation/src/speaker/speakers/zone.py | 10,226 | Information about the zone of the road the car is in.
Initialize zone speaker.
Args:
section_proxy: Returns all sections when called.
lane_proxy: Returns a LaneMsg for each section.
obstacle_proxy: function which returns obstacles in a section.
surface_marking_proxy: function which returns surface_mark... | 2,531 | en | 0.908315 |
import argparse
import xml.etree.cElementTree as etree
import os
from os import listdir
from os.path import isfile, join
import random
def processMedlineFolder(medlineFolder,outFolder):
"""Basic function that iterates through abstracts in a medline file, do a basic word count and save to a file
Args:
medlineFolde... | server/tools/CountWordsError/0.1/CountWordsError.py | 2,283 | Basic function that iterates through abstracts in a medline file, do a basic word count and save to a file
Args:
medlineFolder (folder): Medline XML folder containing abstracts
outFolder (folder): Folder to save output data to
Returns:
Nothing
List of all files in the directory Filter for onl... | 604 | en | 0.808287 |
import json
import yaml
"""
SMock -- Serverboards Mock library -- Mock comfortably.
This library helps to mock function and method calls, getting the data
from an external yaml file.
"""
class MockWrapper:
"""
Wraps all the data returned by the mocked function to behave like a
dictionary, like an object... | smock.py | 6,196 | Wraps all the data returned by the mocked function to behave like a
dictionary, like an object, like a function, like a jsonable dict...
like almost everything you may need
Encapsulates mocking calls so it's easier to load data and mock methods
Example:
```python
>>> import requests
>>> smocked = SMock("tests/data.ya... | 2,088 | en | 0.738899 |
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 14 13:27:33 2020
@author: Jin Dou
"""
import torch
def buildDataLoader(*tensors,TorchDataSetType,oSamplerType=None,**Args):
if(Args.get('DatasetArgs') != None):
DataSetArgs = Args['DatasetArgs']
dataset = TorchDataSetType(*tensors,**DataSe... | StimRespFlow/DataProcessing/DeepLearning/Factory.py | 3,996 | Created on Tue Apr 14 13:27:33 2020
@author: Jin Dou
-*- coding: utf-8 -*- | 77 | en | 0.874943 |
"""
scaffoldgraph tests.core.test_fragment
"""
import pytest
from rdkit import Chem
from scaffoldgraph.core.fragment import *
@pytest.fixture(name='mol')
def test_molecule():
smiles = 'CCN1CCc2c(C1)sc(NC(=O)Nc3ccc(Cl)cc3)c2C#N'
return Chem.MolFromSmiles(smiles)
def canon(smiles):
"""Canonicalize SMILE... | tests/core/test_fragment.py | 2,044 | Canonicalize SMILES for safety. If canonicalization ever changes this should remain consistent
scaffoldgraph tests.core.test_fragment | 133 | en | 0.760184 |
# 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... | cinder/tests/unit/volume/drivers/test_kioxia.py | 40,143 | 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 distributed under th... | 546 | en | 0.872906 |
# Generated by Django 3.1 on 2020-09-28 07:06
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('base', '0065_bugtracker'),
]
operations = [
migrations.RenameField(
model_name='bugtracker',
... | base/migrations/0066_auto_20200928_0706.py | 1,076 | Generated by Django 3.1 on 2020-09-28 07:06 | 43 | en | 0.664026 |
"""Top-level package for pomdp-belief-tracking."""
__author__ = """sammie katt"""
__email__ = "sammie.katt@gmail.com"
__version__ = "0.1.0"
from pomdp_belief_tracking import pf
| pomdp_belief_tracking/__init__.py | 179 | Top-level package for pomdp-belief-tracking. | 44 | en | 0.628961 |
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
#
# Copyright 2018-2019 Fetch.AI Limited
#
# 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 ... | packages/fetchai/skills/generic_seller/behaviours.py | 6,589 | This class implements a behaviour.
Initialise the behaviour.
Register the agent's location.
:return: None
Register the agent's service.
:return: None
Unregister agent from the SOEF.
:return: None
Unregister service from the SOEF.
:return: None
Implement the act.
:return: None
Implement the setup.
:return: None
Im... | 1,245 | en | 0.692309 |
"""Convert MUSDB18 dataset to .wav format.
Output .wav files contain 5 channels
- `0` - The mixture,
- `1` - The drums,
- `2` - The bass,
- `3` - The rest of the accompaniment,
- `4` - The vocals.
"""
import argparse
import os
import subprocess
import tempfile
import librosa
import numpy as np
import soundfile as sf
... | src/convert_to_wav.py | 2,429 | Convert MUSDB18 dataset to .wav format.
Output .wav files contain 5 channels
- `0` - The mixture,
- `1` - The drums,
- `2` - The bass,
- `3` - The rest of the accompaniment,
- `4` - The vocals.
Extract & save the sound of `ch` channel to a temp directory and then concatenate all channels to a single .wav file | 312 | en | 0.728448 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# RobotPy WPILib documentation build configuration file, created by
# sphinx-quickstart on Sun Nov 2 21:31:04 2014.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in th... | conf.py | 5,644 | !/usr/bin/env python3 -*- coding: utf-8 -*- RobotPy WPILib documentation build configuration file, created by sphinx-quickstart on Sun Nov 2 21:31:04 2014. This file is execfile()d with the current directory set to its containing dir. Note that not all possible configuration values are present in this autogenerated fi... | 2,456 | en | 0.693206 |
# Space: O(n)
# Time: O(n!)
class CombinationIterator:
def __init__(self, characters: str, combinationLength: int):
self.data = characters
self.res = self.combine(self.data, combinationLength)
self.counter = 0
self.res_count = len(self.res)
def next(self) -> str:
if ... | Algorithms/1286_Iterator_for_Combination/Python/Iterator_for_Combination_Solution_1.py | 992 | Space: O(n) Time: O(n!) | 23 | en | 0.292249 |
# Copyright (c) 2018 by contributors. 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... | python-package/setup.py | 1,827 | Setup xlearn package.
Copyright (c) 2018 by contributors. 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 appl... | 716 | en | 0.879126 |
# Copyright (c) 2015 Brian Haskin Jr.
#
# 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... | pyrimaa/tests/test_aei.py | 9,665 | Copyright (c) 2015 Brian Haskin Jr. 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, distribute, su... | 1,146 | en | 0.867949 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.