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 |
|---|---|---|---|---|---|---|
# -*- coding:utf-8 -*-
"""
some constants and global queues
Author: QiaoXiaofeng
Date: 2020/01/11
Email: andyjoe318@gmail.com
"""
from collections import deque
# Version
VERSION = "1.1.3_201123_alpha"
# Exchange Names
HUOBI_SWAP = "huobi_swap" # Huobi Swap https://huobiapi.github.io/docs/coin_margined_swap/v1/... | alpha/const.py | 686 | some constants and global queues
Author: QiaoXiaofeng
Date: 2020/01/11
Email: andyjoe318@gmail.com
-*- coding:utf-8 -*- Version Exchange Names Huobi Swap https://huobiapi.github.io/docs/coin_margined_swap/v1/cn/ Huobi Future https://huobiapi.github.io/docs/dm/v1/cn/5ea2e0cde2 Huobi Option Huobi Usdt Swap Market... | 340 | en | 0.366305 |
#!/usr/bin/python
import requests
import json
import cv2
import time
import logging
import random
ledServerURL = 'http://192.168.1.51'
nbPixels = 30
def getServerPath(url):
return "%s%s" % (ledServerURL, url)
def getImage():
retval, im = camera.read()
return im
def getWarmUpImage():
# Warmup
for i in range... | src/opencv-match-pixels.py | 2,271 | !/usr/bin/python Warmup Save resultfile = "/notebooks/test-capture-hot-point/image%d.png" % (i)cv2.imwrite(file, temp) logging Open Camera Set definition camera.set(15, -8.0) Image to update time.sleep(3) logger.info("Pixels %s" % (json.dumps(payload))) Convert and process Find spot Materialize spot cv2.circle(base_ima... | 433 | en | 0.556362 |
# 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/data/python/kernel_tests/window_dataset_op_test.py | 20,984 | Tests batching of dense tensor windows.
Args:
structure: the input structure
shape: the input shape
dtype: the input data type
Tests batching of dynamically shaped dense tensor windows.
Args:
shape: the input shape
Tests batching of sparse tensor windows.
Args:
structure: the input structure
shape: the i... | 2,406 | en | 0.745269 |
"""
Data Structures shared by both the detectors and the server
"""
import datetime
import sys
import traceback
from typing import *
from dataclasses import dataclass, field
from dataclasses_jsonschema import JsonSchemaMixin
@dataclass
class ConfigMessage(JsonSchemaMixin):
cat_identifiers: Dict[str, str] # servi... | src/kitbit/protocol.py | 916 | Data Structures shared by both the detectors and the server
service_id -> cat_name How often to sample, in seconds | 116 | en | 0.936153 |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
"""
Utils for generating stats from torch tensors.
"""
from typing import Iterator, List, Tuple, Union
import numpy as np
import torch
from torch.functional import F
def calc_sample_norms(
named_params: Iterator[Tuple[s... | opacus/utils/tensor_utils.py | 5,137 | Calculates the norm of the given tensors for each sample.
This function calculates the overall norm of the given tensors for each sample,
assuming the each batch's dim is zero.
Args:
named_params: An iterator of tuples <name, param> with name being a
string and param being a tensor of shape ``[B, ...]`` w... | 2,744 | en | 0.686144 |
import dynamo as dyn
import numpy as np
import scipy.io
from scipy import optimize
# def VecFnc(
# input,
# n=4,
# a1=10.0,
# a2=10.0,
# Kdxx=4,
# Kdyx=4,
# Kdyy=4,
# Kdxy=4,
# b1=10.0,
# b2=10.0,
# k1=1.0,
# k2=1.0,
# c1=0,
# ):
# x, y = input
# dxdt = (
# ... | tests/tests.py | 8,270 | def VecFnc( input, n=4, a1=10.0, a2=10.0, Kdxx=4, Kdyx=4, Kdyy=4, Kdxy=4, b1=10.0, b2=10.0, k1=1.0, k2=1.0, c1=0, ): x, y = input dxdt = ( c1 + a1 * (x ** n) / (Kdxx ** n + (x ** n)) + (b1 * (Kdyx ** n)) / (Kdyx ** n + (y ** n)) ... | 7,589 | en | 0.421617 |
import tensorflow as tf
from dataflow.generator_cls import GeneratorCLS
import json
import logging
from easydict import EasyDict
from dataflow.utils import fix_rng_seed
from model.util import batched_gather
import os
import pickle
def get_lr_schedule(lr_schedule):
boundaries = lr_schedule.boundaries
values = lr_sc... | utils.py | 3,970 | Set the logger to log info in terminal and file `log_path`.
In general, it is useful to have a logger so that every output to the terminal is saved
in a permanent file. Here we save it to `model_dir/train.log`.
Example:
```
logging.info("Starting training...")
```
Args:
log_path: (string) where to log
TODO now ... | 563 | en | 0.803981 |
# -*- coding: utf-8 -*-
import datetime
fhVpiKRlyhgsBUpbOQysWaBffABPdeSUqbNQWzpsBmbkqxlCYtAxtWnCcwMifMeIoIiHPsGbUcWRqPYTNEboepPIAKGlrzHEoVTYYeXuBlbUOBrizEBUQHwXbVjOZgnp = 'dmhqfXZEWScpGcCscOLcRkUgRMpmnavpmEzKbcQdDFhUmHjneIBOrLglmFqWAtOtbaswRpZpKSnZlZzlfTbviGHZDbgxVbrqgEEbclXGVksOMdAjGakzUHDiaPRBOHsl'
dwBjbvwPMXdXoHFSDB... | intensio/test/python/multiplefiles/advanced/output/basicRAT/core/toolkit.py | 53,891 | -*- coding: utf-8 -*- | 21 | en | 0.767281 |
#!/usr/bin/python
from base64 import standard_b64encode
from crc32c import crc32
from datetime import datetime
from google.cloud import storage
from os.path import basename, dirname, isfile
from os import makedirs, getenv
from glob import glob
from time import sleep
import json
import petname
import subprocess
import ... | contrib/distr-env/dg_storage.py | 5,221 | Download the 200,000 most recent games, each file should
contain 1,000 game records. So we need to download the 200
most recent files.
Copy the most recent model to the 'models/' directory
Upload the specified game records to google storage.
Upload the specified model to google storage.
Upload the specified network... | 424 | en | 0.859485 |
import jwt
import pendulum
from ..routes import Route
from .controllers import AuthenticationController
from ..utils.str import random_string
class Api:
def __init__(self, application, driver_config=None):
self.application = application
def set_configuration(self, config):
self.config = confi... | src/masonite/api/Api.py | 3,113 | if the token can be decoded, regenerate new token | 49 | en | 0.213853 |
"""pubsub URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-bas... | pubsub/urls.py | 934 | pubsub URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based ... | 632 | en | 0.674844 |
# Copyright (c) 2021 AccelByte Inc. All Rights Reserved.
# This is licensed software from AccelByte Inc, for limitations
# and restrictions contact your company contract manager.
#
# Code generated. DO NOT EDIT!
# template file: justice_py_sdk_codegen/__main__.py
# Justice Matchmaking Service (2.15.1)
# pylint: dis... | accelbyte_py_sdk/api/matchmaking/models/models_update_alliance_rule.py | 6,563 | Models update alliance rule (models.UpdateAllianceRule)
Properties:
max_number: (maxNumber) OPTIONAL int
min_number: (minNumber) OPTIONAL int
player_max_number: (playerMaxNumber) OPTIONAL int
player_min_number: (playerMinNumber) OPTIONAL int
Copyright (c) 2021 AccelByte Inc. All Rights Reserved. T... | 1,224 | en | 0.605393 |
from enum import Enum
# TODO-01 Define Error Type or Exception cbchoi
Infinite = float("inf") # hug value
class AttributeType(Enum):
# BEHAVIOR = 0
ASPECT = 1
RUNTIME = 2
UNKNOWN_TYPE = -1
@staticmethod
def resolve_type_from_str(name):
# if "BEHAVIOR" == name.upper():
# r... | definition.py | 2,689 | TODO-01 Define Error Type or Exception cbchoi hug value BEHAVIOR = 0 if "BEHAVIOR" == name.upper(): return AttributeType.BEHAVIOR if enum == AttributeType.BEHAVIOR: return "BEHAVIOR" 2019.05.16 added by cbchoi Simulation Engine is instantiated but simulation is not running Simulation Engine is instantiated, simul... | 604 | en | 0.816173 |
import requests
class Sympla(object):
_URL = "https://api.sympla.com.br/public/v3/"
def __init__(self, token):
self.__token = token
def _get_url(self, path: str) -> str:
return f"{self._URL}{path}"
@property
def headers(self) -> dict:
return {"S_TOKEN": self.__token}
... | pysympla/sympla.py | 10,326 | Esta API fornece acesso às informações relativas ao programa de afiliados e seus respectivos afiliados.
Para saber mais, acesse: https://developers.sympla.com.br/api-doc/index.html#tag/Afiliados
:param event_id: Identificador único do evento
Realiza o check-in de um participante por id do ingresso.
Para saber mais, ... | 4,626 | pt | 0.739086 |
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
browser = webdriver.Chrome("./driver/chromedriver.exe")
options = Options()
#options.headless = True
browser = webdriver.Chrome(executable_path="./driver/chromedriver.exe", options=options)
browser.get("https://center-pf.kakao.com/") | old/browser_auto.py | 320 | options.headless = True | 23 | en | 0.141674 |
import numpy as np
from numpy.testing import assert_allclose
from scipy.stats import norm
from astroML.density_estimation import\
EmpiricalDistribution, FunctionDistribution
def test_empirical_distribution(N=1000, rseed=0):
np.random.seed(rseed)
X = norm.rvs(0, 1, size=N)
dist = EmpiricalDistribution(... | astroML/density_estimation/tests/test_empirical.py | 843 | go from -10 to 10 to check interpolation in presence of zeros | 61 | en | 0.89676 |
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
import numpy as np
from parlai.core.torch_generator_agent impor... | parlai/agents/transformer/modules.py | 19,929 | Transformer model
Model which takes context, memories, candidates and encodes them
Transformer response rapper. Pushes input through transformer and MLP
Create and initialize word embeddings.
Broadcast layer norm
input data is a FloatTensor of shape [batch, seq_len, dim]
mask is a ByteTensor of shape [batch, seq_len], ... | 1,517 | en | 0.809597 |
##
## © Copyright 2021- IBM Inc. All rights reserved
# SPDX-License-Identifier: MIT
##
#
# This code has two use-cases:
# 1. Where you want to run a batch of queries, with each saving results in CSV - specify the TestId this is added to make filename))
# 2. When you want to run a series of queries and check the data ... | elmclient/examples/batchquery.py | 10,216 | © Copyright 2021- IBM Inc. All rights reserved SPDX-License-Identifier: MIT This code has two use-cases: 1. Where you want to run a batch of queries, with each saving results in CSV - specify the TestId this is added to make filename)) 2. When you want to run a series of queries and check the data retrieved is the same... | 2,274 | en | 0.881201 |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | sdk/network/azure-mgmt-network/azure/mgmt/network/v2019_07_01/operations/_express_route_gateways_operations.py | 21,624 | ExpressRouteGatewaysOperations operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.network.v2019_07_01.models
... | 6,122 | en | 0.495089 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.9 on 2018-01-25 21:43
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('images', '0006_auto_20180125_2142'),
]
operations = [
migrations.AlterModelOptions(... | kellygram/images/migrations/0007_auto_20180125_2143.py | 415 | -*- coding: utf-8 -*- Generated by Django 1.11.9 on 2018-01-25 21:43 | 68 | en | 0.585003 |
from typing import Optional
from great_expectations.core import ExpectationConfiguration
from great_expectations.expectations.expectation import MulticolumnMapExpectation
from great_expectations.expectations.util import (
add_values_with_json_schema_from_list_in_params,
render_evaluation_parameter_string,
)
fr... | great_expectations/expectations/core/expect_select_column_values_to_be_unique_within_record.py | 9,329 | Expect the values for each record to be unique across the columns listed.
Note that records can be duplicated.
For example::
A B C
1 1 2 Fail
1 2 3 Pass
8 2 7 Pass
1 2 3 Pass
4 4 4 Fail
Args:
column_list (tuple or list): The column names to evaluate
Keyword Args:
ignore_row_if (str):... | 1,514 | en | 0.725373 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import re
import subprocess
import time
import web
from web import form,timelimit
import hashlib
import datetime
import random
from func_recall import risk_recall
_tmpstring = "".join(random.sample('zyxwvutsrqponmlkjihgfedcba',20))
urls = (
'/', 'Login',
... | pynovice/tmp_classification/web_py/web_moniter.py | 11,357 | !/usr/bin/env python -*- coding: utf-8 -*- 密码表-riskok 登陆有效期3小时 1.登陆表每天的随机临时登陆密码 2.数据信息表 重新登录 重新登录回调进程(后台抽取数据) 3.风控召回表 重新登录 重新登录 更新数据 | 132 | zh | 0.96445 |
"""
Pymodbus Exceptions
--------------------
Custom exceptions to be used in the Modbus code.
"""
class ModbusException(Exception):
""" Base modbus exception """
def __init__(self, string):
""" Initialize the exception
:param string: The message to append to the error
"""
sel... | pymodbus/exceptions.py | 3,337 | Error resulting from a bad connection
Error resulting from invalid response received or decoded
Error resulting from failing to register a custom message request/response
Base modbus exception
Error resulting from data i/o
Error resulting from making a request to a slave
that does not exist
Error resulting from not... | 1,180 | en | 0.47479 |
'''
The Fibonacci sequence is defined by the recurrence relation:
Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1.
Hence the first 12 terms will be:
F1 = 1
F2 = 1
F3 = 2
F4 = 3
F5 = 5
F6 = 8
F7 = 13
F8 = 21
F9 = 34
F10 = 55
F11 = 89
F12 = 144
The 12th term, F12, is the ... | problem25.py | 661 | The Fibonacci sequence is defined by the recurrence relation:
Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1.
Hence the first 12 terms will be:
F1 = 1
F2 = 1
F3 = 2
F4 = 3
F5 = 5
F6 = 8
F7 = 13
F8 = 21
F9 = 34
F10 = 55
F11 = 89
F12 = 144
The 12th term, F12, is the firs... | 541 | en | 0.839844 |
import requests
#Using an API to search for COVID Movies
url = 'http://www.omdbapi.com/?t=covid&y=2021&apikey=d0c69d2c'
r = requests.get(url)
json_data = r.json()
for key, value in json_data.items():
print(key + ':', value) | analysis/OMDBAPI.py | 223 | Using an API to search for COVID Movies | 39 | en | 0.792631 |
# -----------------------------------------------------------------------------------
# <copyright company="Aspose" file="test_file.py">
# Copyright (c) 2020 Aspose.Words for Cloud
# </copyright>
# <summary>
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and assoc... | test/api/storage/test_file.py | 4,638 | ----------------------------------------------------------------------------------- <copyright company="Aspose" file="test_file.py"> Copyright (c) 2020 Aspose.Words for Cloud </copyright> <summary> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated document... | 1,477 | en | 0.810569 |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | docs/samples/specification/multiapi/generated/azure/multiapi/sample/v3/_multiapi_service_client.py | 4,284 | Service client for multiapi client testing.
:ivar operation_group_one: OperationGroupOneOperations operations
:vartype operation_group_one: azure.multiapi.sample.v3.operations.OperationGroupOneOperations
:ivar operation_group_two: OperationGroupTwoOperations operations
:vartype operation_group_two: azure.multiapi.samp... | 2,159 | en | 0.604069 |
# coding=utf-8
# =============================================================================
# Copyright (c) 2001-2019 FLIR Systems, Inc. All Rights Reserved.
#
# This software is the confidential and proprietary information of FLIR
# Integrated Imaging Solutions, Inc. ("Confidential Information"). You
# shall not di... | Sample/spinnaker_python-2.2.0.48-cp37-cp37m-win_amd64/Examples/Python3/Trigger.py | 19,905 | This function acquires and saves 10 images from a device.
Please see Acquisition example for more in-depth comments on acquiring images.
:param cam: Camera to acquire images from.
:param nodemap: Device nodemap.
:param nodemap_tldevice: Transport layer device nodemap.
:type cam: CameraPtr
:type nodemap: INodeMap
:type... | 7,032 | en | 0.834374 |
import json
from unittest.mock import patch
from django.core import mail
from hc.api.models import Channel, Notification
from hc.test import BaseTestCase
class SendTestNotificationTestCase(BaseTestCase):
def setUp(self):
super(SendTestNotificationTestCase, self).setUp()
self.channel = Channel(kin... | hc/front/tests/test_send_test_notification.py | 3,931 | And email should have been sent It should create a notification | 63 | en | 0.962604 |
# Copyright 2020 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... | research/object_detection/meta_architectures/center_net_meta_arch.py | 145,314 | Base class for feature extractors for the CenterNet meta architecture.
Child classes are expected to override the _output_model property which will
return 1 or more tensors predicted by the feature extractor.
The CenterNet meta architecture [1].
[1]: https://arxiv.org/abs/1904.07850
Namedtuple to store DensePose pred... | 65,854 | en | 0.773177 |
#!/opt/local/bin/python
import timeit
import time
import sys
def find_score(name):
score = 0
for character in name:
score += ( ord(character) - 64 )
return score
start_time = timeit.default_timer()
total = 0
cardinal_position = 0
import csv
with open('p022_names.txt', newline='') as csvfile:
... | Project_Euler/22_name_scores/name_scores.py | 725 | !/opt/local/bin/python | 22 | en | 0.705311 |
from dataclasses import dataclass
from running_modes.configurations.automated_curriculum_learning.merging_strategy_configuration import \
MergingStrategyConfiguration
from running_modes.configurations.automated_curriculum_learning.production_strategy_configuration import \
ProductionStrategyConfiguration
from ... | running_modes/configurations/automated_curriculum_learning/automated_curriculum_learning_configuration.py | 916 | This class holds the necessary configuration components to run Auto CL | 70 | en | 0.669998 |
# from .LinuxInstaller import LinuxInstaller
from .run import run
from .solution import *
from .installer import *
from .controller import *
from .errors import *
from .helper.configuration import ConfVar
from . import helper
from . import builder
| iquail/__init__.py | 248 | from .LinuxInstaller import LinuxInstaller | 42 | en | 0.396919 |
#!/usr/bin/env python
# Copyright 2016 The Kubernetes 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 appli... | jenkins/bootstrap.py | 35,023 | !/usr/bin/env python Copyright 2016 The Kubernetes 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 ... | 5,240 | en | 0.788537 |
# pylint: disable=W0231,E1101
import collections
from datetime import timedelta
import functools
import gc
import json
import operator
from textwrap import dedent
import warnings
import weakref
import numpy as np
from pandas._libs import Timestamp, iNaT, properties
import pandas.compat as compat
from pandas.compat im... | pandas/core/generic.py | 388,405 | N-dimensional analogue of DataFrame. Store multi-dimensional in a
size-mutable, labeled data structure
Parameters
----------
data : BlockManager
axes : list
copy : boolean, default False
True if the key is in the info axis
Parameters
----------
memo, default None
Standard signature. Unused
Delete item
Propagate me... | 153,467 | en | 0.569974 |
# coding: utf-8
"""
Copyright 2017 Square, 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 la... | squareconnect/models/v1_retrieve_business_request.py | 2,713 | NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Returns true if both objects are equal
V1RetrieveBusinessRequest - a model defined in Swagger
:param dict swaggerTypes: The key is attribute name
and the value is attribute type.
:param d... | 1,189 | en | 0.824395 |
# pylint: skip-file
import getpass
import shlex
from subprocess import PIPE # nosec
from django.core.management.base import BaseCommand
from django.utils.autoreload import run_with_reloader
import psutil
def restart_celery():
for proc in psutil.process_iter():
if proc.username() != getpass.getuser(): ... | backend/common/management/commands/celery.py | 1,026 | pylint: skip-file nosec skip processes not owned by user SIGTERM should only be sent to parent process, never to children processes see: https://github.com/celery/celery/issues/2700issuecomment-259716123 found parent celery process | 231 | en | 0.855308 |
#!/usr/local/bin/python3
import json
from sys import argv
version = str(argv[1])
with open("ReactorKit", 'r+') as file:
data = json.load(file)
file.seek(0)
data[version] = "https://github.com/kawoou/ReactorKit-Carthage/releases/download/" + version + "/ReactorKit.framework.zip"
json.dump(data, file... | scripts/update.py | 659 | !/usr/local/bin/python3 | 23 | en | 0.391696 |
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import atexit
import json
import logging
from pathlib import Path
import platform
import shutil
import tempfile
from ty... | glean-core/python/glean/glean.py | 13,775 | The main Glean API.
Before any data collection can take place, the Glean SDK **must** be
initialized from the application.
>>> Glean.initialize(application_id="my-app", application_version="0.0.0", upload_enabled=True)
Set a few metrics that will be sent as part of every ping.
Collect and submit a list of pings for e... | 5,017 | en | 0.890545 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from setuptools import setup
try:
from pkg_resources import VersionConflict, require
require("setuptools>=38.3")
except VersionConflict:
print("Error: version of setuptools is too old (<38.3)!")
sys.exit(1)
def get_extra_requires(add_all=True... | setup.py | 1,428 | !/usr/bin/env python -*- coding: utf-8 -*- add tag `all` at the end | 67 | en | 0.416123 |
#!/usr/bin/env python3
"""
Description:
Usage:
$> roslaunch turtle_nodes.launch
$> ./executive_step_04.py
Output:
[INFO] : State machine starting in initial state 'RESET' with userdata:
[]
[INFO] : State machine transitioning 'RESET':'succeeded'-->'SPAWN'
[INFO] : State machine tr... | Smach/executive_smach_tutorials/scripts/usecase_01/executive_step_04.py | 3,295 | Description:
Usage:
$> roslaunch turtle_nodes.launch
$> ./executive_step_04.py
Output:
[INFO] : State machine starting in initial state 'RESET' with userdata:
[]
[INFO] : State machine transitioning 'RESET':'succeeded'-->'SPAWN'
[INFO] : State machine transitioning 'SPAWN':'succee... | 1,209 | en | 0.605974 |
from .. import abc
from .. import util
importlib = util.import_importlib('importlib')
importlib_abc = util.import_importlib('importlib.abc')
machinery = util.import_importlib('importlib.machinery')
importlib_util = util.import_importlib('importlib.util')
import errno
import marshal
import os
import py_compile
import ... | Lib/test/test_importlib/source/test_file_loader.py | 32,747 | Should have no issue importing a source module [basic]. And if there is
a syntax error, it should raise a SyntaxError [syntax error].
Fake mtime to always be higher than expected.
Manipulate the bytecode of a module by passing it into a callable
that returns what to use as the new bytecode.
Should not raise an except... | 3,535 | en | 0.616638 |
"""
pycmark.inlineparser.link_processors
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Link processor classes for InlineParser.
:copyright: Copyright 2017-2019 by Takeshi KOMIYA
:license: Apache License 2.0, see LICENSE for details.
"""
import re
from typing import Tuple
from docutils import nodes
from d... | pycmark/inlineparser/link_processors.py | 7,925 | pycmark.inlineparser.link_processors
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Link processor classes for InlineParser.
:copyright: Copyright 2017-2019 by Takeshi KOMIYA
:license: Apache License 2.0, see LICENSE for details.
6.5 Links 6.6 Images link destination + link title (optional) [...](<.+> ".+") [...](.+ ... | 613 | en | 0.386663 |
import re
import collections
from slugify import slugify
from .utils import limpa_conteudo, cria_hash_do_movimento
PADRAO_MOV = re.compile(r'numMov=(\d+)')
def parse_metadados(linhas_de_dados, numero_processo, inicio_metadados,
fim_metadados):
metadados = {
'status': [''],
'c... | extrator/crawler/parser.py | 5,808 | Delimita o processo na regiao dos metadados Apaga linhas utilizadas Recorta area com os itens Podem existir cabeçalhos de itens sem texto, como o Mandado de Pagamento Nesses caso registraremos como tipo de movimento o título do bloco Aparentemente esse valor e fixo | 265 | pt | 0.800098 |
# 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_azure_native/network/v20200701/get_virtual_network_tap.py | 8,952 | Virtual Network Tap resource.
The reference to the private IP address on the internal Load Balancer that will receive the tap.
The reference to the private IP Address of the collector nic that will receive the tap.
The VXLAN destination port that will receive the tapped traffic.
A unique read-only string that changes w... | 1,006 | en | 0.832426 |
# Copyright 2019 Alastair Pharo
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | tests/test_fisheries_det_basic.py | 2,311 | Copyright 2019 Alastair Pharo 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 distri... | 770 | en | 0.8762 |
addrs = {
"140": "[2401:db00:21:604c:face:0:5:0]",
"216": "[2401:db00:21:604c:face:0:7:0]",
"199": "[2401:db00:21:604f:face:0:5:0]",
"194": "[2401:db00:21:605b:face:0:7:0]",
"213": "[2401:db00:21:6046:face:0:7:0]",
"145": "[2401:db00:21:6043:face:0:1:0]",
"212": "[2401:db00:21:6046:face:0:5:... | experimental/server_addrs.py | 659 | These are for FAIR clusters, add additional nodes and their IP addresses here | 77 | en | 0.973355 |
#!/usr/bin/env python2.7
# coding=utf-8
from __future__ import print_function
import sys, os
curr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__)))
sys.path.append("../../amalgamation/python/")
sys.path.append("../../python/")
from mxnet_predict import Predictor
import mxnet as mx
import numpy as ... | example/warpctc/ocr_predict.py | 2,827 | !/usr/bin/env python2.7 coding=utf-8 Keep Zero index for blank. (CTC request it) Set your max length of label, add one more for blank Do CTC label rule CTC cannot emit a repeated symbol on consecutive timesteps change to ascii | 226 | en | 0.776771 |
#!/usr/bin/python3
import glob
from PIL import Image
# get all the jpg files from the current folder
for infile in glob.glob("*.jpg"):
im = Image.open(infile)
# convert to thumbnail image
im.thumbnail((500, 500), Image.ANTIALIAS)
# don't save if thumbnail already exists
if infile[0:2] != "T_":
# prefix t... | scripts/mk_thumbs.py | 384 | !/usr/bin/python3 get all the jpg files from the current folder convert to thumbnail image don't save if thumbnail already exists prefix thumbnail file with T_ | 159 | en | 0.662739 |
# MIT License
#
# Copyright (c) 2019 Meyers Tom
#
# 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... | runner/input.py | 2,534 | remove value from the list
Check if the input is null. If that is the case simply listen for stdin
Returns the input that it got eg a url, uri or domain
Second return type is if debug messages should be enabled
print the help menu and exit
MIT License Copyright (c) 2019 Meyers Tom Permission is hereby granted, free... | 1,308 | en | 0.837675 |
from git import Repo
import logging
from wily.archivers import BaseArchiver, Revision
logger = logging.getLogger(__name__)
class DirtyGitRepositoryError(Exception):
def __init__(self, untracked_files):
self.untracked_files = untracked_files
self.message = "Dirty repository, make sure you commit/... | wily/archivers/git.py | 1,503 | Make sure you checkout HEAD on the original branch when finishing | 65 | en | 0.870904 |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import ast
import datetime
from odoo import api, fields, models, _
from odoo.tools.safe_eval import safe_eval
class Team(models.Model):
_name = 'crm.team'
_inherit = ['mail.alias.mixin', 'crm.team']
_descr... | addons/crm/models/crm_team.py | 8,723 | -*- coding: utf-8 -*- Part of Odoo. See LICENSE file for full copyright and licensing details. statistics about leads / opportunities / both alias: improve fields coming from _inherits, use inherited to avoid replacing them ------------------------------------------------------------ ORM -------------------------------... | 747 | en | 0.559618 |
import random
# ToDo: With shuffle_ganon option, prevent gtower from linking to an exit only location through a 2 entrance cave.
def link_entrances(world, player):
connect_two_way(world, 'Links House', 'Links House Exit', player) # unshuffled. For now
connect_exit(world, 'Chris Houlihan Room Exit', 'Links Ho... | EntranceShuffle.py | 226,599 | This works inplace
This works inplace
This works inplace
ToDo: With shuffle_ganon option, prevent gtower from linking to an exit only location through a 2 entrance cave. unshuffled. For now should always match link's house, except for plandos setup mandatory connections if we do not shuffle, set default connections m... | 13,953 | en | 0.927338 |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2011 Nebula, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# no... | django-openstack/django_openstack/dash/views/floating_ips.py | 7,481 | vim: tabstop=4 shiftwidth=4 softtabstop=4 Copyright 2011 United States Government as represented by the Administrator of the National Aeronautics and Space Administration. All Rights Reserved. Copyright 2011 Nebula, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file exc... | 770 | en | 0.854875 |
# ============================================================================
# ============================================================================
# Copyright (c) 2021 Nghia T. Vo. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in c... | tests/test_prep/test_filtering.py | 3,877 | Tests for the methods in prep/filtering.py
============================================================================ ============================================================================ Copyright (c) 2021 Nghia T. Vo. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you ... | 1,108 | en | 0.707233 |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import unittest
import torch
from fairseq import utils
class TestUtils(unittest.TestCase):
def test_convert_padding_direction(self):
... | tests/test_utils.py | 3,295 | Copyright (c) Facebook, Inc. and its affiliates. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. | 168 | en | 0.897895 |
#!/usr/bin/env python3
# encoding: utf-8
import os
import cv2
cv2.setNumThreads(0)
import numpy as np
from utils.visualize import print_iou, show_img, show_prediction
from engine.evaluator import Evaluator
from engine.logger import get_logger
from seg_opr.metric import hist_info, compute_score
logger = get_logger()
... | train/eval.py | 2,775 | !/usr/bin/env python3 encoding: utf-8 tensorboard logger does not fit multiprocess cv2.imwrite(name + ".png", comp_img[:,:,::-1]) | 129 | en | 0.504443 |
# for value in range(1,9):
# print(' * ' * (9 - value))
# print("---------------------------")
# for i in range(5):
# for j in range(i+1):
# print(" O ", end="")
# print()
# print("---------------------------")
# for i in range(5):
# for s in range(i):
# print(" ", end="")
... | pattern.py | 761 | for value in range(1,9): print(' * ' * (9 - value)) print("---------------------------") for i in range(5): for j in range(i+1): print(" O ", end="") print() print("---------------------------") for i in range(5): for s in range(i): print(" ", end="") for j in range(i, 5): pri... | 515 | en | 0.297811 |
import dataclasses
import warnings
import numpy as np
import torch
def to_device(data, device=None, dtype=None, non_blocking=False, copy=False):
"""Change the device of object recursively"""
if isinstance(data, dict):
return {
k: to_device(v, device, dtype, non_blocking, copy) for k, v in... | espnet2/torch_utils/device_funcs.py | 2,681 | Change object to gatherable in torch.nn.DataParallel recursively
The difference from to_device() is changing to torch.Tensor if float or int
value is found.
The restriction to the returned value in DataParallel:
The object must be
- torch.cuda.Tensor
- 1 or more dimension. 0-dimension-tensor sends warning... | 516 | en | 0.835167 |
# -*- 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | google/cloud/datalabeling_v1beta1/services/data_labeling_service/transports/base.py | 30,607 | Abstract transport class for DataLabelingService.
Instantiate the transport.
Args:
host (Optional[str]):
The hostname to connect to.
credentials (Optional[google.auth.credentials.Credentials]): The
authorization credentials to attach to requests. These
credentials identify the applicat... | 2,427 | en | 0.812348 |
from itertools import chain, starmap
from typing import Any, Tuple
def flatten_json(dictionary: dict) -> dict:
"""Flatten a nested json file"""
while True:
dictionary = dict(chain.from_iterable(starmap(_unpack, dictionary.items())))
if _atomic_values(dictionary):
break
return ... | activejson/flatten_json_tools.py | 1,404 | Unpack one level of nesting in json file
Flatten a nested json file
Unpack one level only!!! | 94 | en | 0.757137 |
'''subclassing kde
Author: josef pktd
'''
import numpy as np
from numpy.testing import assert_almost_equal, assert_
import scipy
from scipy import stats
import matplotlib.pylab as plt
class gaussian_kde_set_covariance(stats.gaussian_kde):
'''
from Anne Archibald in mailinglist:
http://www.nabble.com/Wid... | statsmodels/sandbox/nonparametric/kdecovclass.py | 5,669 | from Anne Archibald in mailinglist:
http://www.nabble.com/Width-of-the-gaussian-in-stats.kde.gaussian_kde---td19558924.html#a19558924
not used
subclassing kde
Author: josef pktd
plot histgram of sample plot estimated density plot data generating density get kde for original sample evaluate the density function for t... | 918 | en | 0.584847 |
# -*- coding: utf8 -*-
# Copyright (c) 2017-2021 THL A29 Limited, a Tencent company. 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... | tencentcloud/facefusion/v20181201/errorcodes.py | 6,162 | -*- coding: utf8 -*- Copyright (c) 2017-2021 THL A29 Limited, a Tencent company. 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 Unl... | 1,230 | zh | 0.717225 |
"""included ordering for sections
Revision ID: 91052a50e2b0
Revises: 5716caecc491
Create Date: 2020-06-26 14:49:21.905034
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '91052a50e2b0'
down_revision = '5716caecc491'
branch_labels = None
depends_on = None
def ... | app/alembic/versions/2020_06_26_14_49_21.py | 712 | included ordering for sections
Revision ID: 91052a50e2b0
Revises: 5716caecc491
Create Date: 2020-06-26 14:49:21.905034
revision identifiers, used by Alembic. commands auto generated by Alembic - please adjust! end Alembic commands commands auto generated by Alembic - please adjust! end Alembic commands | 313 | en | 0.736713 |
class RSVPRouter(object):
"""
A router to control all database operations on models in the
rsvp application.
"""
apps = ["rsvp"]
using = "rsvp_db"
def db_for_read(self, model, **hints):
if model._meta.app_label in self.apps:
return self.using
return None
... | kyleandemily/rsvp/db_router.py | 1,303 | A router to control all database operations on models in the
rsvp application.
Allow relations if a model in the app is involved.
Make sure the apps we care about appear in the db | 179 | en | 0.941327 |
from crypt import methods
from unicodedata import name
from flask import Flask, render_template, request, session, logging, url_for, redirect, flash
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from passlib.hash import sha256_crypt
from flask_login import login_user
engi... | main.py | 3,313 | login page formroute for photoroute for profileregister form functions,route for signup pageroute for contactabout us routeroute for logoutroute for social | 155 | en | 0.678502 |
"""Several tools used accross by other modules"""
import logging
from logging.handlers import BufferingHandler
from asyncio import sleep, get_event_loop
from datetime import datetime, timedelta
from distutils.util import strtobool
from os.path import abspath, dirname
from typing import Union, Optional, List
from uuid ... | webapi/tools.py | 4,674 | Delai logging for a specific logger.
Replace the handlers by this BufferingHandler
Restore the handlers and flush this BufferingHandler
Ask a question to the user, retry until the reply is valid
async functools.partial
Cast a value to the given type. /!\ Hack /!\
Fake coroutine by awaiting asyncio.sleep(0)
Returns the... | 666 | en | 0.740956 |
"""The base class and interface for all formatting plugins."""
import argparse
import os
import sys
from typing import IO
from typing import List
from typing import Optional
from typing import Tuple
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from flake8.statistics import Statistics
from flake8.style_gu... | .venv/lib/python3.9/site-packages/flake8/formatting/base.py | 7,582 | Class defining the formatter interface.
.. attribute:: options
The options parsed from both configuration files and the command-line.
.. attribute:: filename
If specified by the user, the path to store the results of the run.
.. attribute:: output_fd
Initialized when the :meth:`start` is called. This ... | 3,646 | en | 0.798944 |
import os, logging
from flask import Flask, request
from werkzeug.serving import run_simple
from galaxylearning.utils.utils import return_data_decorator, LoggerFactory
app = Flask(__name__)
BASE_MODEL_PATH = os.path.join(os.path.abspath("."), "res", "models")
logger = LoggerFactory.getLogger(__name__, logging.INFO)
... | galaxylearning/core/communicate_client.py | 1,589 | print(recv_aggregate_files) print("recv_filename: ", recv_aggregate_files[filename]) | 84 | en | 0.466178 |
# Generated by Django 2.2.13 on 2020-11-05 11:24
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("workflow_handler", "0030_auto_20201103_1718"),
]
operations = [
migrations.AddField(
model_name="task",
name="corre... | src/human_lambdas/workflow_handler/migrations/0031_task_correct.py | 392 | Generated by Django 2.2.13 on 2020-11-05 11:24 | 46 | en | 0.707178 |
"""Tools to assist importing optional external modules."""
import sys
import re
# Override these in the module to change the default warning behavior.
# For example, you might set both to False before running the tests so that
# warnings are not printed to the console, or set both to True for debugging.
WARN_NOT_INS... | .environment/lib/python3.8/site-packages/sympy/external/importtools.py | 7,844 | Import and return a module if it is installed.
If the module is not installed, it returns None.
A minimum version for the module can be given as the keyword argument
min_module_version. This should be comparable against the module version.
By default, module.__version__ is used to get the module version. To
overrid... | 4,224 | en | 0.604548 |
#!/usr/bin/python3
"""
Summary
-------
This application simulates showers to be used in trigger rate calculations.
Arrays with one (1MST) or four telescopes (4LST) can be used, in case of \
mono or stereo trigger configurations, respectively.
Simulations are managed by the shower_simulator mod... | applications/sim_showers_for_trigger_rates.py | 5,669 | Summary
-------
This application simulates showers to be used in trigger rate calculations.
Arrays with one (1MST) or four telescopes (4LST) can be used, in case of mono or stereo trigger configurations, respectively.
Simulations are managed by the shower_simulator module.
Each run is simulated in a job. Each job ... | 2,067 | en | 0.739108 |
# Test various AP mode parameters
# Copyright (c) 2014, Qualcomm Atheros, Inc.
#
# This software may be distributed under the terms of the BSD license.
# See README for more details.
from remotehost import remote_compatible
import logging
logger = logging.getLogger()
import os
import struct
import subprocess
import ti... | tests/hwsim/test_ap_params.py | 33,431 | MAC ACL accept list
MAC ACL deny list
MAC ACL accept/deny management
Open AP with lots of basic rates
Open AP with Beacon frame TX rate HT-MCS 0
Open AP with Beacon frame TX rate HT-MCS 1 in VHT BSS
Open AP with Beacon frame TX rate 5.5 Mbps
Open AP with Beacon frame TX rate 12 Mbps in VHT BSS
Open AP with Beacon frame... | 1,877 | en | 0.761119 |
import unittest
import sys
sys.path.insert(1, '..')
import easy_gui
class GUI(easy_gui.EasyGUI):
def __init__(self, **kwargs):
self.add_widget(type='button', text='Button1', command_func=lambda e: print('Button1 working!'))
self.test_lbl = self.add_widget(type='label', text='Here\'s an awesome la... | tests/test_wm_attributes.py | 878 | use Alt + F4 to closebuffer=True) | 33 | en | 0.282615 |
# -*- coding: utf-8 -*-
#
# This file is part of BridgeDB, a Tor bridge distribution system.
#
# :authors: Isis Lovecruft 0xA3ADB67A2CDB8B35 <isis@torproject.org>
# please also see AUTHORS file
# :copyright: (c) 2013, Isis Lovecruft
# (c) 2007-2013, The Tor Project, Inc.
# (c) 2007-201... | lib/bridgedb/test/test_persistentSaveAndLoad.py | 3,340 | -*- coding: utf-8 -*- This file is part of BridgeDB, a Tor bridge distribution system. :authors: Isis Lovecruft 0xA3ADB67A2CDB8B35 <isis@torproject.org> please also see AUTHORS file :copyright: (c) 2013, Isis Lovecruft (c) 2007-2013, The Tor Project, Inc. (c) 2007-2013, all entities wi... | 622 | en | 0.808573 |
'''
Implements the targetcli target related UI.
This file is part of targetcli.
Copyright (c) 2011-2013 by Datera, 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/lic... | targetcli/ui_target.py | 47,131 | A fabric module UI.
A generic UI for LUN objects.
A generic UI for TPG LUNs.
A generic UI for MappedLUN objects.
A generic target UI that has multiple TPGs.
A generic UI for a node ACL.
Handles grouping multiple NodeACLs in UI via tags.
All gets are performed against first NodeACL.
All sets are performed on all NodeAC... | 12,094 | en | 0.640073 |
"""
Django settings for the Sphinx documentation builder.
All configuration is imported from :mod:`backend.settings` except it sets :attr:`USE_I18N` to ``False`` to make sure
the documentation is not partially translated.
For more information on this file, see :doc:`topics/settings`.
For the full list of settings and ... | src/backend/sphinx_settings.py | 779 | Django settings for the Sphinx documentation builder.
All configuration is imported from :mod:`backend.settings` except it sets :attr:`USE_I18N` to ``False`` to make sure
the documentation is not partially translated.
For more information on this file, see :doc:`topics/settings`.
For the full list of settings and thei... | 646 | en | 0.679558 |
# Copyright (c) 2018 Uber 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 agreed ... | vertica_python/tests/test_unicode.py | 4,424 | Copyright (c) 2018 Uber 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 agreed to in writing, sof... | 1,680 | en | 0.866592 |
import pygame # Tested with pygame v1.9.6
from UIControls import Button
from constants import *
import numpy as np
import random
import time
import os
from nodes import bfs_node
import sys
import threading
###############################################
# Globals
###############################################
init... | src/MazePy/MazePy/MazePy.py | 22,100 | Resets any cells that are VISITED or PATH to EMPTY again, so that we
can commence a search on a potentially partially completed board
Tested with pygame v1.9.6 Globals initialise() Set all cells to EMPTY by default Set the Initial and Terminal cells print(grid) create_ui() draw_grid() Only set the Initial cell if we ... | 1,845 | en | 0.783006 |
# Pyrogram - Telegram MTProto API Client Library for Python
# Copyright (C) 2017-2021 Dan <https://github.com/delivrance>
#
# This file is part of Pyrogram.
#
# Pyrogram is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free... | backend/pyrogram/raw/types/bank_card_open_url.py | 2,241 | This object is a constructor of the base type :obj:`~pyrogram.raw.base.BankCardOpenUrl`.
Details:
- Layer: ``123``
- ID: ``0xf568028a``
Parameters:
url: ``str``
name: ``str``
Pyrogram - Telegram MTProto API Client Library for Python Copyright (C) 2017-2021 Dan <https://github.com/delivrance> This... | 1,201 | en | 0.838451 |
# 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/containerservice/v20200301/list_managed_cluster_admin_credentials.py | 2,484 | The list of credential result response.
Base64-encoded Kubernetes configuration file.
The list of credential result response.
:param str resource_group_name: The name of the resource group.
:param str resource_name: The name of the managed cluster resource.
coding=utf-8 *** WARNING: this file was generated by the P... | 459 | en | 0.827282 |
"""
===================================
Demo of OPTICS clustering algorithm
===================================
.. currentmodule:: sklearn
Finds core samples of high density and expands clusters from them.
This example uses data that is generated so that the clusters have
different densities.
The :class:`~cluster.OPT... | examples/cluster/plot_optics.py | 3,656 | ===================================
Demo of OPTICS clustering algorithm
===================================
.. currentmodule:: sklearn
Finds core samples of high density and expands clusters from them.
This example uses data that is generated so that the clusters have
different densities.
The :class:`~cluster.OPTICS`... | 805 | en | 0.797817 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Author : Heethesh Vhavle
Email : heethesh@cmu.edu
Version : 1.0.0
Date : Apr 08, 2019
'''
import random
import rospy
from delta_perception.msg import VehicleGroundTruth, VehicleGroundTruthArray
random_vehicles = ['car', 'truck', 'bus', 'motorbike', 'bicycle']
... | test/vehicle_ground_truth_publisher_test.py | 2,050 | Author : Heethesh Vhavle
Email : heethesh@cmu.edu
Version : 1.0.0
Date : Apr 08, 2019
!/usr/bin/env python -*- coding: utf-8 -*- Setup node Ignore this if you use a camera/image callback to publish the data Randomly publish some data Create the message array Create few random vehicles Populate single vehicle wit... | 700 | en | 0.609355 |
# Test some Unicode file name semantics
# We dont test many operations on files other than
# that their names can be used with Unicode characters.
import os, glob, time, shutil
import unicodedata
import unittest
from test.support import (run_unittest, rmtree, change_cwd,
TESTFN_ENCODING, TESTFN_UNICODE, TESTFN_UNE... | third_party/python/Lib/test/test_unicode_file.py | 5,915 | Test some Unicode file name semantics We dont test many operations on files other than that their names can be used with Unicode characters. Either the file system encoding is None, or the file name cannot be encoded in the file system encoding. The 'do_' functions are the actual tests. They generally assume the file ... | 1,558 | en | 0.868084 |
# coding: utf-8
"""
Isilon SDK
Isilon SDK - Language bindings for the OneFS API # noqa: E501
OpenAPI spec version: 9
Contact: sdk@isilon.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class CreateFilepoolPolicyRespon... | isi_sdk_8_2_2/isi_sdk_8_2_2/models/create_filepool_policy_response.py | 3,114 | NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Returns true if both objects are equal
CreateFilepoolPolicyResponse - a model defined in Swagger
Returns true if both objects are not equal
For `print` and `pprint`
Gets the id of this CreateFilepoolPolicyResponse... | 967 | en | 0.642435 |
# This is your project's main settings file that can be committed to your
# repo. If you need to override a setting locally, use settings_local.py
from funfactory.settings_base import *
# Bundles is a dictionary of two dictionaries, css and js, which list css files
# and js files that can be bundled together by the m... | settings/base.py | 5,015 | This is your project's main settings file that can be committed to your repo. If you need to override a setting locally, use settings_local.py Bundles is a dictionary of two dictionaries, css and js, which list css files and js files that can be bundled together by the minify app. Example code. Can (and should) be remo... | 1,277 | en | 0.687358 |
import pandas as pd
import csv
import numpy as np
from tensorflow.keras import Sequential, Model
from tensorflow.keras.layers import Dense, Concatenate, Input, Conv1D, MaxPooling1D, Flatten, Dropout, GlobalAveragePooling1D
from tensorflow.keras.callbacks import EarlyStopping
from sklearn.preprocessing import StandardSc... | src/feature_based/multiclass_opencrowd/nn_em.py | 11,088 | initialize probability z_i (item's quality) randomly First Hidden Layer Output Layer Compiling the neural network Hidden Layer Output Layer Compiling the neural network if (iter % 5 == 0) and (iter>0): min_norm = LA.norm(theta_i - old_theta_i) theta_i_test = theta_i[strat_val:(end_val)] theta_i_val = theta_i[(end_v... | 432 | en | 0.29969 |
import sys
import unicodedata
from PIL import Image, ImageDraw, ImageFont
args = sys.argv
if len(args) < 2:
print("usage:", args[0], "message")
sys.exit()
text = args[1]
if len(text) < 1:
print("usage:", args[0], "message")
sys.exit()
def get_east_asian_width_count(text):
count = 0
for c in text:
if ... | message.py | 728 | fontpath = "./PixelMplus10-Bold.ttf" | 36 | ko | 0.218683 |
class ElasticEase(EasingFunctionBase,ISealable,IEasingFunction):
"""
Represents an easing function that creates an animation that resembles a spring oscillating back and forth until it comes to rest.
ElasticEase()
"""
def CloneCore(self,*args):
"""
CloneCore(self: Freezable,sourceFreezable: Freez... | release/stubs.min/System/Windows/Media/Animation_parts/ElasticEase.py | 7,602 | Represents an easing function that creates an animation that resembles a spring oscillating back and forth until it comes to rest.
ElasticEase()
CloneCore(self: Freezable,sourceFreezable: Freezable)
Makes the instance a clone (deep copy) of the specified System.Windows.Freezable using base
(non-animated) prope... | 5,476 | en | 0.670644 |
import itertools
import logging
import re
import time
import urllib
from collections import defaultdict
from datetime import datetime, timedelta, timezone
from decimal import Decimal
from typing import Any, Callable, Dict, List, Optional, Sequence, Set, Tuple, Type, Union
from urllib.parse import urlencode
import pytz... | analytics/views.py | 60,164 | Returns all rows from a cursor as a dict
TODO: Make @zulip_login_required pass the UserProfile so we can use @require_member_or_admin Note that the labels are further re-written by client_label_map Most likely someone using our API endpoint. The /stats page does not pass a start or end in its requests. Note that this... | 1,954 | en | 0.878264 |
# Postgres' `clone_schema` adapted to work with schema names containing
# capital letters or `-`
# Source: IdanDavidi, https://stackoverflow.com/a/48732283/6412017
from django.db import connection, transaction, ProgrammingError
CLONE_SCHEMA_FUNCTION = """
-- Function: clone_schema(text, text)
-- DROP FUNCTION clone_... | django_tenants/clone.py | 6,965 | Creates a postgres function `clone_schema` that copies a schema and its
contents. Will replace any existing `clone_schema` functions owned by the
`postgres` superuser.
Creates a new schema `new_schema_name` as a clone of an existing schema
`old_schema_name`.
Postgres' `clone_schema` adapted to work with schema names ... | 478 | en | 0.707946 |
# coding: utf-8
"""
Titan API v1
# Introduction The Intel 471 API is organized around the principles of REST. Our API lets you gather results from our platform with anything that can send a HTTP request, including cURL and modern internet browsers. Access to this API requires an API token which is managed fro... | titan_client/models/credential_set_schema_data.py | 16,784 | NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
Returns true if both objects are equal
CredentialSetSchemaData - a model defined in OpenAPI
Returns true if both objects are not equal
For `print` and `pprint`
Gets the breach_date of this Crede... | 9,780 | en | 0.695592 |
#!/bin/python3
# Copyright (C) 2020 Matheus Fernandes Bigolin <mfrdrbigolin@disroot.org>
# SPDX-License-Identifier: MIT
"""Day Thirteen, Shuttle Search."""
from sys import argv
from re import findall
from utils import open_file, arrange, usage_and_exit, product
def solve1(buses, est):
"""Get the earliest bus... | src/day13.py | 1,527 | Get the earliest bus from the <buses> according to the <est>imate
time.
Find the smallest timestamp, such that all the <buses> follow their
bus ID, which is indexically paired with <depart>.
Here I used the Chinese Remainder Theorem, someone well acquainted to
anyone who does competitive or discrete mathematics.
D... | 554 | en | 0.840564 |
"""Plot power curves for turbine 1 with data filters
"""
# import libraries
import pandas as pd
import numpy as np
import itertools
import matplotlib.pyplot as plt
# import data
df = pd.read_csv('data/SCADA_downtime_merged.csv', skip_blank_lines=True)
# list of turbines to plot (just 1)
list1 = [1]
# list of catego... | scripts/plot/powercurves-filter-T1.py | 5,343 | Plot power curves for turbine 1 with data filters
import libraries import data list of turbines to plot (just 1) list of categories to plot remove NaN from list round from float to integer sort categories in ascending order categories to remove from plot filter only data for turbine x and plot sort values by timestam... | 1,129 | en | 0.800697 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 28 15:05:36 2018
@author: louismueller
"""
# import
import numpy as np
#%%
def PlotOverview(oData):
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# Overview Plots
# Find interesting stuff: takeoff, landi... | Core/OpenData.py | 5,576 | Created on Fri Dec 28 15:05:36 2018
@author: louismueller
!/usr/bin/env python3 -*- coding: utf-8 -*- import%% Overview Plots Find interesting stuff: takeoff, landing, excitations etc. Airspeed Altitude X and Y Position Voltage 3D Position%% Find Excitation Times based on 'exciteEngage' returns list of tuples: (test... | 996 | en | 0.753576 |
import sys, os
imgdir = sys.argv[1]
outfile = sys.argv[2]
flag = int(sys.argv[3])
fn = open(outfile, 'w')
fn.write("<html>\n")
fn.write("<body>\n")
namelist = os.listdir(imgdir)
namelist = sorted(namelist)
for idx, name in enumerate(namelist):
#if idx > 10:
# break
if flag:
imname = "office1_%d.j... | gen_view_html.py | 682 | if idx > 10: breakimpath = os.path.abspath(impath)fn.write("<img src=\"%s\" width=\"640\" height=\"320\">\n"%impath)print(impath) | 132 | en | 0.253131 |
# coding=utf-8
# Copyright 2021 The Tensor2Robot 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 ... | research/vrgripper/mse_decoder.py | 1,146 | Default MSE decoder.
Abstract decoder and MSE decoder.
coding=utf-8 Copyright 2021 The Tensor2Robot 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/LICEN... | 632 | en | 0.834015 |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'mods.ui'
#
# Created: Sun Oct 12 21:39:36 2014
# by: PyQt5 UI code generator 5.3.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_ModsDialog(object):
def setupUi(self,... | cadnano/gui/dialogs/ui_mods.py | 4,738 | -*- coding: utf-8 -*- Form implementation generated from reading ui file 'mods.ui' Created: Sun Oct 12 21:39:36 2014 by: PyQt5 UI code generator 5.3.2 WARNING! All changes made in this file will be lost! | 208 | en | 0.803731 |
#!/usr/bin/env python
#
# ---- VGRID ----
# A Class for Incremental Gridding
#
# Val Schmidt
# Center for Coastal and Ocean Mapping
# Univeristy of New Hampshire
# Copyright, 2018-2019
# All Rights Reserved
import numpy as np
from line_profiler import LineProfiler
import sys
import scipy.spatial as spatial
from matpl... | VGRID/vgrid.py | 25,138 | A class for gridding of x,y,z data.
See vgrid.add() for details on usage.
numba jit compiled add function
- Numba compiles this function, ensure that no classes/functions are within unless they are also numba-ized
- Numba.prange forces numba to parallelize, generates exception when parallelism fails, helping you figu... | 9,823 | en | 0.854684 |
# -*- coding: utf-8 -*-
import tensorflow as tf
INPUT_NODE = 784
OUTPUT_NODE = 10
# 28 (edge) * 28
IMAGE_SIZE = 28
# 黑白
NUM_CHANNELS = 1
NUM_LABELS = 10
CONV1_DEEP = 32
# 过滤器尺寸
CONV1_SIZE = 5
CONV2_DEEP = 64
CONV2_SIZE = 5
# num of Fully connected nodes
FC_SIZE = 512
# def get_weight_variable(shape, regularizer):
... | mnist/LeNet-5/mnist_inference.py | 4,570 | -*- coding: utf-8 -*- 28 (edge) * 28 黑白 过滤器尺寸 num of Fully connected nodes def get_weight_variable(shape, regularizer): weights = tf.get_variable( "weight", shape, initializer=tf.truncated_normal_initializer(stddev=0.1)) if regularizer != None: tf.add_to_collection("losses", regularizer(... | 1,355 | en | 0.277117 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.