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 |
|---|---|---|---|---|---|---|
# MIT LICENSE
#
# Copyright 1997 - 2020 by IXIA Keysight
#
# 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,... | ixnetwork_restpy/testplatform/sessions/ixnetwork/vport/protocols/switchconfiglearnedinformation_e983ca5da0eadbba93d1ce1d2903a5b7.py | 6,457 | NOT DEFINED
The SwitchConfigLearnedInformation class encapsulates a list of switchConfigLearnedInformation resources that are managed by the system.
A list of resources can be retrieved from the server using the SwitchConfigLearnedInformation.find() method.
Returns
-------
- str: NOT DEFINED
Returns
-------
- str: NOT ... | 3,266 | en | 0.692968 |
# -*- coding: utf-8 -*-
"""Cisco DNA Center Claim a Device to a Site data model.
Copyright (c) 2019-2021 Cisco Systems.
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, includ... | dnacentersdk/models/validators/v1_2_10/jsd_5889fb844939a13b.py | 2,704 | Claim a Device to a Site request schema definition.
Cisco DNA Center Claim a Device to a Site data model.
Copyright (c) 2019-2021 Cisco Systems.
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 wi... | 1,193 | en | 0.869151 |
#!/usr/bin/python
import sys
import cgi
import cgitb
import sqlite3
reload(sys)
sys.setdefaultencoding('utf-8')
cgitb.enable()
# html
print("Content-type: text/html\n")
print('<meta charset="utf-8">')
print("<html><head>")
print('''<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1... | assign_candidate.py | 7,818 | !/usr/bin/python htmlquery to get candidate data for the rowsquery to get the faculty and project names for the table headersquery to get all current candidate-faculty pairs in the databasestart connectionexecute query 1 get results to above standard queryexecute query 2get results to above standard queryexecute query ... | 1,781 | en | 0.828944 |
"""Test the UniFi Protect switch platform."""
# pylint: disable=protected-access
from __future__ import annotations
from unittest.mock import AsyncMock, Mock
import pytest
from pyunifiprotect.data import (
Camera,
Light,
RecordingMode,
SmartDetectObjectType,
VideoMode,
)
from homeassistant.compon... | tests/components/unifiprotect/test_switch.py | 15,576 | Test the UniFi Protect switch platform.
pylint: disable=protected-access disable pydantic validation so mocking can happen disable pydantic validation so mocking can happen disable pydantic validation so mocking can happen disable pydantic validation so mocking can happen | 274 | en | 0.499516 |
#!/usr/bin/env python3
'''
Model for Riemannian feature calculation and classification for EEG data
'''
import numpy as np
from sklearn.svm import LinearSVC, SVC
from riemannian_multiscale import RiemannianMultiscale, QuantizedRiemannianMultiscale
from filters import load_filterbank
from utilities import quantize
... | multiscale_bci_python/riemannian_model.py | 10,590 | QuantizedRiemannian Model
Riemannian Model
Constructor
Args:
Parameters
----------
svm_kernel: str {'linear', 'sigmoid', 'rbf'}
kernel used for classifier
svm_c: float
regularization parameter for the classifier
fs: int
sampling rate of the data
bands: list of int
bandwidths used ... | 4,013 | en | 0.49274 |
import logging
import os
import random
import time
from functools import lru_cache
import cv2
import numpy as np
import imgreco.main
from Arknights.helper import logger
from addons.activity import ActivityAddOn, get_stage_map
from addons.base import BaseAddOn, pil2cv, crop_cv_by_rect, show_img
from addons.common_cach... | addons/start_sp_stage/__init__.py | 8,440 | print(factor) show_img(tag_img) conv-lite-fc has better accuracy, but it is slower than densenet-lite-fc. show_img(dbg_screen) StartSpStageAddon().get_all_act_pos() | 164 | en | 0.664941 |
import os
import sys
sys.path.append(os.path.dirname(__file__))
class AbstractSystemMeter:
"""Common system meter interface for all resource monitorings.
For each system resource to monitor, a wrapper class will be written as subclass of this one. This way we have
a common "interface" for all system resou... | measure/system/AbstractSystemMeter.py | 800 | Common system meter interface for all resource monitorings.
For each system resource to monitor, a wrapper class will be written as subclass of this one. This way we have
a common "interface" for all system resources to test.
This approach is choosen since python has no real interfaces like Java or C-Sharp. | 310 | en | 0.928172 |
#!/usr/bin/python
from __future__ import division
import sys
import math
import cmath
import numpy as np
from numpy import genfromtxt
import csv
from decimal import Decimal
import os
import random
from lyrics import *
# BEATLES: Bundle of Essential and Assistive Tools Library for Electronic Structure
# A tri... | BEATLES.py | 49,185 | !/usr/bin/python BEATLES: Bundle of Essential and Assistive Tools Library for Electronic Structure A tribute to the Beatles Updated June 14, 2020 by Hassan Harb / | \ / | \ /O O | O O\ //|\ /|\ /|\ /|\\ /=/ \=/ \= / \=/ \=\ / ... | 10,618 | en | 0.749958 |
"""Utility functions related to file operations."""
import copy
import logging
import os
import subprocess
import sys
from argparse import Namespace
from collections import OrderedDict
from contextlib import contextmanager
from pathlib import Path
from tempfile import NamedTemporaryFile
from typing import TYPE_CHECKING... | src/ansiblelint/file_utils.py | 8,968 | Defines a file/folder that can be linted.
Providing file content when creating the object allow creation of in-memory
instances that do not need files to be present on disk.
Identify whether the other object represents the same rule match.
Provide compatibility subscriptable support.
Return a hash value of the lintabl... | 2,141 | en | 0.83681 |
# -*- coding: utf-8 -*-
import gzip
import bz2
import numpy as np
def advanced_open(filepath, *args, **kwargs):
""" Open function interface for files with different extensions.
Parameters
----------
filepath: str
File path with extension.
args: list
Non-key arguments
kwargs: ... | benchmarking/libkge/libkge/io/base.py | 1,606 | Open function interface for files with different extensions.
Parameters
----------
filepath: str
File path with extension.
args: list
Non-key arguments
kwargs: dict
Key arguments
Returns
-------
Import knowledge graph from file
Parameters
----------
filepath: str
File path
separator: str
File col... | 695 | en | 0.56994 |
import os
import requests
import datetime
from django.http import HttpResponseRedirect, HttpResponse, JsonResponse, Http404
from django.template import loader
from django.contrib.auth import login
from django.conf import settings
from django.http import Http404
from django.utils import timezone
from requests import st... | tau/core/views.py | 12,154 | elif not request.user.is_authenticated: return HttpResponseRedirect('/accounts/login/') template = loader.get_template('home.html') template = loader.get_template('dashboard/index.html') return HttpResponse(template.render({'config': config}, request)) If users already exist, it is not first run reject creating a ... | 372 | en | 0.341475 |
def find_words(string, word_set):
if string == "" or not word_set:
return None
if string in word_set: # O(1)
return [string]
#"bedbathbeyondunk"
#{'bed', 'bath', 'bedbath', 'and', 'beyond'}
tmp = "" # bedbathbeyondunk
out = [] # []
retro = False # True
i = 0
while i ... | reconstruct-words.py | 1,041 | O(1)"bedbathbeyondunk"{'bed', 'bath', 'bedbath', 'and', 'beyond'} bedbathbeyondunk [] True i = 15 | 97 | de | 0.052457 |
import json
import yaml
from pathlib import Path
from brownie import *
from substrateinterface import Keypair
from hashlib import blake2b
import base58
def get_derivative_account(root_account, index):
seed_bytes = b'modlpy/utilisuba'
root_account_bytes = bytes.fromhex(Keypair(root_account).public_key[2:])
... | scripts/prepare_env.py | 3,484 | contracts = run('./scripts/prepare_env.py') from brownie console --network=moonbase current validators in moonbase 5CxXVE7pHqzR4kzfz6nop529odm8eVemFFtStruyNQvdTopo 5GxgDNMhbvMhuJzXC2voX5nKUyNaNQFCZxgnoa18eGiBBZwt 5Cqb9WXVQQF73a1dcJEBFS2bWrukaC6dmzjeWZeJHj3NMwvB | 261 | en | 0.235365 |
import datetime
from dateutil.parser import parse
from decimal import Decimal
import re
import importlib
from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned
from django.utils import datetime_safe
from tastypie.bundle import Bundle
from tastypie.exceptions import ApiFieldError, NotFound
from t... | tastypie/fields.py | 29,911 | All the ApiField variants. Track what the index thinks this field is called. Do the least we can here so that we don't hate ourselves in the morning. Check for `__` in the field for looking through the relation. Fall out of the loop, given any further attempts at accesses will fail miserably. Fall out of the loop, give... | 2,053 | en | 0.933934 |
# coding: utf-8
"""
UltraCart Rest API V2
UltraCart REST API Version 2
OpenAPI spec version: 2.0.0
Contact: support@ultracart.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
class CouponFreeItemAndShipping... | ultracart/models/coupon_free_item_and_shipping_with_subtotal.py | 7,294 | 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
CouponFreeItemAndShippingWithSubtotal - a model defined in Swagger
Returns true if both objects are not equal
For `print` and `pprint`
Gets the currency_code of this CouponFre... | 2,799 | en | 0.68995 |
import RPi.GPIO as GPIO
import time,sys, datetime, json, requests
from requests.exceptions import ConnectionError, Timeout, TooManyRedirects
'''
Configure raspberry
'''
GPIO.setmode(GPIO.BCM)
inpt = 13
GPIO.setup(inpt,GPIO.IN)
'''
Configure some global variables
'''
current_input = GPIO.input(inpt) ... | software/read-sensor-python/waterFlow/waterFlowMeter.py | 4,411 | This passes data to the data base as a single row. It then resets/empties data.
Calculates measurements (cups and gallons). Prepares the data into a database-friendly tuple. Appends that tuple to a list.
It then tries to connect to database. If it is not successful then it does nothing but saves the data; it will try... | 1,026 | en | 0.912425 |
import re
import traceback
import subprocess
from serviceDB import ServiceDB
class NeadmServiceWrapper:
_service_list_cmd = ['/opt/nedge/neadm/neadm', 'service', 'list']
# _status_cmd = ['/opt/nedge/neadm/fake-neadm-status.sh']
_service_list_header = re.compile("^.*TYPE.*NAME.*SERVERID.*STATUS.*$")
#... | nexentaedge/neadmServiceWrapper.py | 11,309 | _status_cmd = ['/opt/nedge/neadm/fake-neadm-status.sh'] unit_id key well be added during parsing of each line print(output) error exit code print(line) print(params) print(len(params)) check ServiceDB for sid and unit_id already joined add unit_id key print(node) print(status) is node included into service nodes list i... | 1,194 | en | 0.695027 |
#!/usr/bin/env python3
#
# Copyright (c) 2019 LG Electronics, Inc.
#
# This software contains code licensed as described in LICENSE.
#
import os
import lgsvl
import random
import time
from pathlib import Path
import json
sim = lgsvl.Simulator(os.environ.get("SIMULATOR_HOST", "127.0.0.1"), 8181)
layer_mask = 0
layer_... | autoware.ai/autoware_files/lgsvl_file/scripts/testbed_scenario/sanfrancisco.py | 2,198 | !/usr/bin/env python3 Copyright (c) 2019 LG Electronics, Inc. This software contains code licensed as described in LICENSE. 0 is the layer for the road (default) if sim.current_scene == "Testbed": sim.reset() else: sim.load("Testbed") state.transform.position = spawns[0].position------- Stand vehicle -------set sta... | 923 | en | 0.317903 |
"""
Space object.
Refer: https://developer.twitter.com/en/docs/twitter-api/data-dictionary/object-model/space
"""
from dataclasses import dataclass, field
from typing import List, Optional
from .base import BaseModel
@dataclass
class Space(BaseModel):
"""
A class representing the space object.
... | pytwitter/models/space.py | 1,146 | A class representing the space object.
Space object.
Refer: https://developer.twitter.com/en/docs/twitter-api/data-dictionary/object-model/space | 145 | en | 0.542582 |
"""Make / Download Telegram Sticker Packs without installing Third Party applications
Available Commands:
.kangsticker [Optional Emoji]
.packinfo
.getsticker"""
from telethon import events
from io import BytesIO
from PIL import Image
import asyncio
import datetime
from collections import defaultdict
import math
import ... | stdplugins/stickers.py | 12,714 | Copyright Rhyse Simpson:
https://github.com/skittles9823/SkittBot/blob/master/tg_bot/modules/stickers.py
Make / Download Telegram Sticker Packs without installing Third Party applications
Available Commands:
.kangsticker [Optional Emoji]
.packinfo
.getsticker
format: Uni_Borg_userid format: Uni_Borg_userid https://gi... | 638 | en | 0.682723 |
#!/usr/bin/env python3
# Copyright (c) 2015-2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test processing of unrequested blocks.
Setup: two nodes, node0+node1, not connected to each other. Nod... | test/functional/p2p_unrequested_blocks.py | 14,257 | Test processing of unrequested blocks.
Setup: two nodes, node0+node1, not connected to each other. Node1 will have
nMinimumChainWork set to 0x10, so it won't process low-work unrequested blocks.
We have one P2PInterface connection to node0 called test_node, and one to node1
called min_work_node.
The test:
1. Generat... | 4,893 | en | 0.929681 |
import networkx
import random
def regularize_graph(graph,d):
regularized = True
for node_id in list(graph.nodes()):
if graph.in_degree(node_id)!=d or graph.out_degree(node_id)!=d:
regularized = False
break
while not regularized:
lost_in_degree_ids = []
full_in_degree_ids = []
for node... | exact-2-regular-k/regularize_graph.py | 2,438 | Find appropriate (full_outdegree_id, full_in_degree_id) pair Patch | 66 | en | 0.516314 |
#!/usr/bin/env python
# Brief: This node subscribes to /tracked_humans and publishes the predicted goal to humans based on their trajectory
# Author: Phani Teja Singamaneni
import numpy as np
import rospy
import tf
from geometry_msgs.msg import Point, PoseStamped
from human_msgs.msg import TrackedHumans, TrackedHuman... | human_path_prediction/scripts/predict_goal.py | 5,916 | !/usr/bin/env python Brief: This node subscribes to /tracked_humans and publishes the predicted goal to humans based on their trajectory Author: Phani Teja Singamaneni laas_adream maze self.goals_x = [1.5,1.5,1.5,1.5,1.5,7.5,25,42,42,41.5,42,37,22,15.5,28.5,37,23.5,10.5,15.5,31.5,20,25.5,7] self.goals_y = [45,15,30,60,... | 457 | en | 0.882588 |
# Copyright (c) 2016 Google Inc. (under http://www.apache.org/licenses/LICENSE-2.0)
def f1(x):
return 1
def f1(x):
return 'foo'
def f2(x):
pass
def f2(x,y):
pass
def f3(x):
return 1+x
def f3(x):
return 'asd'+x
| pytype/tools/merge_pyi/test_data/redefine.py | 236 | Copyright (c) 2016 Google Inc. (under http://www.apache.org/licenses/LICENSE-2.0) | 81 | en | 0.451736 |
# -*- coding: utf-8 -*-
"""Tests for various magic functions.
Needs to be run by nose (to make ipython session available).
"""
import io
import os
import re
import sys
import warnings
from unittest import TestCase
from importlib import invalidate_caches
from io import StringIO
import nose.tools as nt
import shlex
... | env/lib/python3.6/site-packages/IPython/core/tests/test_magic.py | 34,178 | class with both %foo and %%foo magics
I am cell foo, not line foo
Test %hist -f with temporary filename.
In [9]: import tempfile
In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-')
In [11]: %hist -nl -f $tfile 3
In [13]: import os; os.unlink(tfile)
Test %hist -op
In [1]: class b(float):
...: pass
...:... | 5,670 | en | 0.706979 |
# Copyright 2021 DAI Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... | ethtx/decoders/decoders/semantics.py | 3,532 | Copyright 2021 DAI Foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software dist... | 556 | en | 0.848164 |
"""
Support for Xiaomi Yeelight Wifi color bulb.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/light.yeelight/
"""
import logging
import voluptuous as vol
from homeassistant.util.color import (
color_temperature_mired_to_kelvin as mired_to_kelvin,... | homeassistant/components/light/yeelight.py | 17,617 | Representation of a Yeelight light.
Initialize the Yeelight light.
Define a wrapper to catch exceptions from the bulb.
Return if bulb is available.
Return the brightness of this light between 1..255.
Return the color temperature.
Return the list of supported effects.
Return the color property.
Return true if device is ... | 1,242 | en | 0.784439 |
import numpy as np
import sys
class RBF():
def __init__(self, Input, Output, Ptypes, Nclasses):
self.input = Input
self.hidden = Ptypes * Nclasses
self.output = Output
self.ptypes = Ptypes
self.nclasses = Nclasses
self.protos = 0
self.weights = 0
s... | Assignment 3/rbf.py | 4,072 | input params percentage | 23 | en | 0.344562 |
#-------------------------------------------------------------------------------
# Name:GUI Calculator
# Purpose:Simple calculator with GUI using tkinter
#
# Author: Daniel Campos
#
# Created: Monday Dec 1st, 2014
#-------------------------------------------------------------------------------
from tkinter import *
imp... | ProgrammingInPython/proj08_daniel_campos.py | 5,273 | GUI for the calculator
Displays the inputted char onto the display
Displays the inputted char onto the display
Backspace on expression
Clears the expression
Evalutes the expression
------------------------------------------------------------------------------- Name:GUI Calculator Purpose:Simple calculator with GUI usi... | 461 | en | 0.41298 |
"""
URLConf for Satchmo Contacts.
"""
from django.conf.urls.defaults import patterns
from signals_ahoy.signals import collect_urls
from satchmo_store import contact
from satchmo_store.shop.satchmo_settings import get_satchmo_setting
ssl = get_satchmo_setting('SSL', default_value=False)
urlpatterns = patterns('satchm... | satchmo/apps/satchmo_store/contact/urls.py | 598 | URLConf for Satchmo Contacts. | 29 | en | 0.797734 |
import sys
import requests
import argparse
import json
import os
import configparser
import arrow
from colorama import init
import traceback
def get_color(color_code):
return '\x1b[%sm' % color_code
def parse_brief(brief):
sentences = None
if args.news:
sentences = json.loads(
reque... | win_python/idict.py | 5,642 | we are running in a bundle we are running in a normal Python environment | 72 | en | 0.953497 |
# Python
import unittest
from copy import deepcopy
from unittest.mock import Mock
# ATS
from ats.topology import Device
# Genie
from genie.libs.ops.igmp.iosxe.igmp import Igmp
from genie.libs.ops.igmp.iosxe.tests.igmp_output import IgmpOutput
# Parser
from genie.libs.parser.iosxe.show_igmp import ShowIpIgmpInterface... | pkgs/ops-pkg/src/genie/libs/ops/igmp/iosxe/tests/test_igmp.py | 6,950 | Python ATS Genie Parser iosxe show_vrf Give the device as a connection type This is done in order to call the parser on the output provided Get outputs Return outputs above as inputs to parser when called Learn the feature Verify Ops was created successfully Get outputs Return outputs above as inputs to parser when cal... | 734 | en | 0.841744 |
#!/usr/bin/python
#
# linearize-hashes.py: List blocks in a linear, no-fork version of the chain.
#
# Copyright (c) 2013 The Bitcoin developers
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
import json
import struct
impor... | contrib/linearize/linearize-hashes.py | 2,761 | !/usr/bin/python linearize-hashes.py: List blocks in a linear, no-fork version of the chain. Copyright (c) 2013 The Bitcoin developers Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. skip comment lines parse key=value lines | 313 | en | 0.673579 |
#!/usr/bin/env python
"""
Functions for estimating quantities from nested sampling runs.
Each estimator function should have arguments:
.. code-block:: python
def estimator_func(self, ns_run, logw=None, simulate=False):
...
Any additional arguments required for the function should be keyword
arguments.
... | nestcheck/estimators.py | 11,030 | Number of samples in run.
Unlike most estimators this does not require log weights, but for
convenience will not throw an error if they are specified.
Parameters
----------
ns_run: dict
Nested sampling run dict (see the data_processing module
docstring for more details).
Returns
-------
int
Bayesian evidence... | 5,795 | en | 0.554408 |
"""Database schema functions and information for Toron node files.
Toron nodes are stored as individual files. The file format is
managed, internally, as a relational database. The schema for this
database is shown below as a simplified ERD (entity relationship
diagram). SQL foreign key relationships are represented w... | toron/_node_schema.py | 18,111 | Context manager to wrap a block of code inside a SAVEPOINT.
If the block exists without errors, the SAVEPOINT is released
and the changes are committed. If an error occurs, all of the
changes are rolled back:
cur = con.cursor()
with savepoint(cur):
cur.execute(...)
Create triggers and application-defin... | 6,512 | en | 0.679119 |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 5 09:10:56 2018
@author: gtucker
"""
import numpy as np
import datetime
from grainhill import GrainFacetSimulator
from grainhill import SlopeMeasurer
import landlab
from landlab.io.native_landlab import save_grid
import os
def create_folder(dire... | ModelRunScripts/SensitivityAnalysisDandV/run_v_w.py | 2,601 | Created on Thu Jul 5 09:10:56 2018
@author: gtucker
!/usr/bin/env python2 -*- coding: utf-8 -*- Open a file to record output: Print header in file Sweep through a range of dissolution rate parameters Set run duration long enough for uplift of 150 rows | 254 | en | 0.718933 |
from Jumpscale import j
import re
# ACTIONS
## R = Regex Replace
## RI = Regex Replace case insensitive
DO = """
RI| j.application.JSBase$ | j.baseclasses.object
RI| j.data.cache. | j.core.cache.
RI| j.data.text. | j.core.text.
RI| from jumpscale import j | from Jumpscale import j
RI| j.application.jsbase_get_class(... | sandbox/lib/jumpscale/JumpscaleLibs/tools/fixer/FixerReplace.py | 3,927 | ACTIONS R = Regex Replace RI = Regex Replace case insensitive if "\t" in line: line = line.replace("\t"," ") changed = True | 134 | en | 0.676282 |
"""Client for Triton Inference Server using REST API.
References:
-
https://github.com/kubeflow/kfserving/blob/master/docs/predict-api/v2/required_api.md#httprest
-
https://github.com/triton-inference-server/client/tree/master/src/python/examples
-
https://github.com/triton-inference-server/client/blob/master/src/pyth... | clients/triton_rest.py | 3,001 | Client for Triton Inference Server using REST API.
References:
-
https://github.com/kubeflow/kfserving/blob/master/docs/predict-api/v2/required_api.md#httprest
-
https://github.com/triton-inference-server/client/tree/master/src/python/examples
-
https://github.com/triton-inference-server/client/blob/master/src/python/... | 715 | en | 0.537996 |
# encoding: utf-8
"""
This module defines the things that are used in setup.py for building JupyterLab
This includes:
* Functions for finding things like packages, package data, etc.
* A function for checking dependencies.
"""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modif... | setupbase.py | 7,123 | Disabled version of bdist_egg
Prevents setup.py install performing setuptools' default easy_install,
which it should never ever do.
Prune JavaScript folders from egg_info to avoid locking up pip.
Find data_files.
Find package_data.
Find all of the packages.
decorator for building minified js/css prior to another c... | 1,241 | en | 0.683699 |
# # SPDX-License-Identifier: MIT
# from augur.augurplugin import AugurPlugin
# from augur.application import Application
# class HousekeeperPlugin(AugurPlugin):
# """
# This plugin serves as an example as to how to load plugins into Augur
# """
# def __init__(self, augur_app):
# super().__init_... | augur/housekeeper/__init__.py | 1,173 | SPDX-License-Identifier: MIT from augur.augurplugin import AugurPlugin from augur.application import Application class HousekeeperPlugin(AugurPlugin): """ This plugin serves as an example as to how to load plugins into Augur """ def __init__(self, augur_app): super().__init__(augur_app) ... | 1,116 | en | 0.300772 |
""" Video Link: https://youtu.be/1s-Tj65AKZA """
from seleniumbase import __version__
from seleniumbase import BaseCase
class HackTests(BaseCase):
def test_all_your_base_are_belong_to_us(self):
# First make sure that seleniumbase 1.65.0 or newer is installed
version = __version__.split(".")
... | examples/hack_the_planet.py | 23,602 | Video Link: https://youtu.be/1s-Tj65AKZA
First make sure that seleniumbase 1.65.0 or newer is installed | 106 | en | 0.737358 |
import numpy as np
import pandas as pd
from sklearn.tree import DecisionTreeRegressor
from sklearn.model_selection import KFold
import plotly.express as px
from plotly.subplots import make_subplots
import plotly.graph_objects as go
# import data and preprocess it
def preprocessing(file_name: str):
# ... | gradient-boosting/main.py | 6,766 | import data and preprocess it data import train-test split by a percentage. input: dataframe, label column name, split ration, and random state returns: x_train, x_test, y_train, y_test Create as arrays of trees in a given size and depth train trees in a forest by fitting each tree to the previous tree's error input: f... | 1,359 | en | 0.806059 |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | kafka/src/kafka/settings.py | 1,057 | Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file... | 748 | en | 0.886713 |
# -*- coding: utf-8 -*-
SUCCESSFUL_TERMINAL_STATUSES = ('complete', )
UNSUCCESSFUL_TERMINAL_STATUSES = ('cancelled', 'unsuccessful')
CONTRACT_REQUIRED_FIELDS = [
'awardID', 'contractID', 'items', 'suppliers',
'value', 'dateSigned',
#'documents'
]
CONTRACT_NOT_REQUIRED_FIELDS = [
'contractNumber', 'title... | openregistry/convoy/loki/constants.py | 403 | -*- coding: utf-8 -*-'documents' | 32 | en | 0.907091 |
"""
Plugin for Czech TV (Ceska televize).
Following channels are working:
* CT1 - https://www.ceskatelevize.cz/porady/ct1/
* CT2 - https://www.ceskatelevize.cz/porady/ct2/
* CT24 - https://ct24.ceskatelevize.cz/#live
* CT sport - https://www.ceskatelevize.cz/sport/zive-vysilani/
* CT Decko - https:... | src/streamlink/plugins/ceskatelevize.py | 9,161 | Finds embedded player url in HTTP response.
:param response: Response object.
:returns: Player url (str).
Finds playlist info (type, id) in HTTP response.
:param response: Response object.
:returns: Dictionary with type and id.
Plugin for Czech TV (Ceska televize).
Following channels are working:
* CT1 - https:/... | 974 | en | 0.759209 |
#basic example of dict synat
my_dict = {'key1':'value1','key2':'value2','key3':'value3'}
print(my_dict)
print(my_dict['key3'])
#xmpl 2
prices = {'apple':100,'banana':60,'gavava':90,'rice':50}
print(prices['rice'])
| python_basics/Dictionary/dict.py | 215 | basic example of dict synatxmpl 2 | 33 | en | 0.414212 |
import numpy as np
from time import sleep
import struct
import matplotlib.pyplot as plt
# input raw samples from MCU
# in_data = 'out/data_raw.txt'
in_data = 'out/8bit.txt'
fs = 5000
in_bits = 8
# load file
raw = np.loadtxt(in_data)
# Stats
print("Max=%d Min=%d Mean=%d swing=%d %.1fbits" % \
(np.max(raw), np.min(... | audio/edison/audio/bit_depth_analyze.py | 1,741 | input raw samples from MCU in_data = 'out/data_raw.txt' load file Stats generate different bit audio normalize and zero mean all write audio files plot some axs.set_xlim(0, 6e-3) axs.set_ylim(-1, 1) | 199 | en | 0.498117 |
#!/home/pi/Documents/Codigos/API_Estacao/bin/python3
"""Simple FTDI EEPROM configurator.
"""
# Copyright (c) 2019-2020, Emmanuel Blot <emmanuel.blot@free.fr>
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from argparse import ArgumentParser, FileType
from io import StringIO
from logging import Form... | bin/ftconf.py | 6,686 | Main routine
Simple FTDI EEPROM configurator.
!/home/pi/Documents/Codigos/API_Estacao/bin/python3 Copyright (c) 2019-2020, Emmanuel Blot <emmanuel.blot@free.fr> All rights reserved. SPDX-License-Identifier: BSD-3-Clausepylint: disable-msg=too-many-localspylint: disable-msg=too-many-branchespylint: disable-msg=too-many... | 486 | en | 0.553341 |
#!/usr/bin/env python3
######################################################
## Calibrating the extrinsics between T265 and D4xx ##
## Based on this example: https://github.com/IntelRealSense/librealsense/pull/4355
## with changes and modifications.
######################################################
#############... | robot/src/vision_to_mavros/scripts/calibrate_extrinsics.py | 12,847 | !/usr/bin/env python3 Calibrating the extrinsics between T265 and D4xx Based on this example: https://github.com/IntelRealSense/librealsense/pull/4355 with changes and modifications. General steps: 1. Mount the two cameras rigidly 2. Print any one of the checkerboards from: https://markhedleyjones.com/projects/calibra... | 2,113 | en | 0.646712 |
"""Implementation of Rule L044."""
from typing import Optional
from sqlfluff.core.rules.analysis.select_crawler import Query, SelectCrawler
from sqlfluff.core.parser import BaseSegment
from sqlfluff.core.rules.base import BaseRule, LintResult, RuleContext
from sqlfluff.core.rules.doc_decorators import document_groups
... | src/sqlfluff/rules/L044.py | 6,370 | Exception class for reporting lint failure inside deeply nested code.
Query produces an unknown number of result columns.
**Anti-pattern**
Querying all columns using ``*`` produces a query result where the number
or ordering of columns changes if the upstream table's schema changes.
This should generally be avoided b... | 2,248 | en | 0.824228 |
import os, paramiko, time, schedule, smtplib, ssl
from datetime import datetime
from email.message import EmailMessage
host='localhost'
port='5432'
user='postgres'
password='admin'
database='testdb'
#chemin de sauvegarde locale
local_dir = 'C:\\Users\\Kamla\\projets\\auto-backup-sqldb\\backup\\'
#local_dir = 'Chemin ... | pgsqlbackup.py | 2,432 | chemin de sauvegarde localelocal_dir = 'Chemin vers le dossier de la base de donnees a sauvegarder\\'chemin de sauvegarde distantnom pour le fichier sql qui serra genere par pg_dumplancement de la commande mysqldump qui va faire une sauvegarde en localles fichiers sont sauvegarder dans le respertoire 'backup' debut du ... | 767 | fr | 0.832575 |
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... | docs/conf.py | 3,252 | Configuration file for the Sphinx documentation builder. This file only contains a selection of the most common options. For a full list see the documentation: https://www.sphinx-doc.org/en/master/usage/configuration.html -- Path setup -------------------------------------------------------------- If extensions (or mod... | 1,996 | en | 0.683511 |
# NOTE - Still seems to be a leak here somewhere
# gateway count doesnt hit zero. Hence the print statements!
import sys
sys.coinit_flags = 0 # Must be free-threaded!
import win32api, pythoncom, time
import pywintypes
import os
import winerror
import win32com
import win32com.client.connect
from win32com.test.util i... | env/Lib/site-packages/win32com/test/testPyComTest.py | 29,446 | NOTE - Still seems to be a leak here somewhere gateway count doesnt hit zero. Hence the print statements! Must be free-threaded! This test uses a Python implemented COM server - ensure correctly registered. We had a bg where RegisterInterfaces would fail if gencache had already been run - exercise that here convert a ... | 5,515 | en | 0.885883 |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | python/mxnet/image/image.py | 45,108 | Image Augmenter base class
Random brightness jitter augmentation.
Parameters
----------
brightness : float
The brightness jitter ratio range, [0, 1]
Cast to float32
Make center crop augmenter.
Parameters
----------
size : list or tuple of int
The desired output image size.
interp : int, optional, default=2
... | 19,440 | en | 0.637788 |
# coding: utf-8
"""
OpenShift API (with Kubernetes)
OpenShift provides builds, application lifecycle, image content management, and administrative policy on top of Kubernetes. The API allows consistent management of those objects. All API operations are authenticated via an Authorization bearer token that is... | openshift/test/test_v1beta1_cpu_target_utilization.py | 4,258 | V1beta1CPUTargetUtilization unit test stubs
Test V1beta1CPUTargetUtilization
OpenShift API (with Kubernetes)
OpenShift provides builds, application lifecycle, image content management, and administrative policy on top of Kubernetes. The API allows consistent management of those objects. All API operations are authen... | 3,605 | en | 0.87757 |
import warnings
import mmcv
import numpy as np
import torch
from torch.nn.modules.utils import _pair
from mmdet.core.anchor.builder import ANCHOR_GENERATORS
from mmdet.core.anchor import AnchorGenerator
@ANCHOR_GENERATORS.register_module(force=True)
class SSDAnchorGenerator(AnchorGenerator):
"""Anchor generator f... | xmmdet/core/anchor/anchor_generator.py | 6,591 | Anchor generator for SSD
Args:
strides (list[int] | list[tuple[int, int]]): Strides of anchors
in multiple feature levels.
ratios (list[float]): The list of ratios between the height and width
of anchors in a single level.
basesize_ratio_range (tuple(float)): Ratio range of anchors.
in... | 902 | en | 0.613184 |
from __future__ import absolute_import
"""This module offers a display and interaction frontend with Qt.
It will try importing PySide first, and if that fails PyQt. The code will
constantly be tested with both bindings."""
from .displaywidgets import DisplayWidget, NewDisplayWidget
from .control import ControlWidget... | zasim/gui/display.py | 1,565 | Instantiate a Display (thas is: a window with a display widget and
simulation controls) from a simulator.
:param simulator: The simulator to use.
Sets the scale of the display component.
from .mainwin import ZasimMainWindow | 225 | en | 0.656556 |
import numpy
from chainer.backends import cuda
from chainer import function_node
from chainer.utils import type_check
class ResizeImages3D(function_node.FunctionNode):
def __init__(self, output_shape):
self.out_H = output_shape[0]
self.out_W = output_shape[1]
self.out_D = output_shape[2]
... | src/links/model/resize_images_3d.py | 6,408 | Resize images to the given shape.
This function resizes 3D data to :obj:`output_shape`.
Currently, only bilinear interpolation is supported as the sampling method.
Notatition: here is a notation for dimensionalities.
- :math:`n` is the batch size.
- :math:`c_I` is the number of the input channels.
- :math:`h`, :math:`w... | 823 | en | 0.806657 |
# coding=utf-8
'''
author: ShiLei Miao
analyses and build model about NBA
'''
import numpy as np
from numpy import *
import pandas as pd
from pandas import *
import os
from sklearn.ensemble import RandomForestClassifier
from sklearn.cross_validation import KFold
from sklearn import metrics
os.chdir... | Procedure/2_M1/train/m2-cv-rf.py | 3,732 | coding=utf-8 训练集rong_tag 没有使用 【下面的数据是one-hot后的特征】 在统计的train跟test缺失的情况后,选择剔除用户的特征缺失个数为187的【基本都是product_id=2】 | 107 | zh | 0.980853 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.db import models
class Post(models.Model):
status_ITEMS = (
(1, '上线'),
(2, '草稿'),
(3, '删除'),
)
title = models.CharField(max_length=50, verbose_name='标题')
desc = models.CharField(max_len... | typeidea/blog/models.py | 2,307 | -*- coding: utf-8 -*- parent = models.ForeignKey('Category', verbose_name='分类') | 82 | en | 0.426176 |
#!/usr/bin/env python2.7
# Advanced Multi-Mission Operations System (AMMOS) Instrument Toolkit (AIT)
# Bespoke Link to Instruments and Small Satellites (BLISS)
#
# Copyright 2016, by the California Institute of Technology. ALL RIGHTS
# RESERVED. United States Government Sponsorship acknowledged. Any
# commercial use m... | ait/core/test/test_dmc.py | 6,860 | !/usr/bin/env python2.7 Advanced Multi-Mission Operations System (AMMOS) Instrument Toolkit (AIT) Bespoke Link to Instruments and Small Satellites (BLISS) Copyright 2016, by the California Institute of Technology. ALL RIGHTS RESERVED. United States Government Sponsorship acknowledged. Any commercial use must be negotia... | 837 | en | 0.902081 |
# Copyright 2018 the GPflow authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writi... | tests/test_logdensities.py | 2,521 | Copyright 2018 the GPflow authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distr... | 642 | en | 0.857075 |
# -*- coding: utf-8 -*-
"""
wsproto/handshake
~~~~~~~~~~~~~~~~~~
An implementation of WebSocket handshakes.
"""
from collections import deque
from typing import Deque, Dict, Generator, List, Optional, Union
import h11
from .connection import Connection, ConnectionState, ConnectionType
from .events import AcceptConne... | wsproto/handshake.py | 17,527 | A Handshake implementation for HTTP/1.1 connections.
Return the established connection.
This will either return the connection or raise a
LocalProtocolError if the connection has not yet been
established.
:rtype: h11.Connection
Return a generator that provides any events that have been generated
by protocol activity.... | 1,707 | en | 0.817603 |
import numpy as np
from astropy.io import fits
from scipy.interpolate import interp1d
# Fitting Sline3
def fit_spline3(y, x, order=3, nsum=3):
y_resampled = [np.median(y[i:i + nsum]) for i in range(0, len(y) - len(y) % nsum, nsum)]
x_resampled = np.linspace(0, len(y), len(y_resampled))
# Fitting
... | trim_slitedge.py | 3,601 | Fitting Sline3 Fitting Return function to be constructed with any other x array Local Minima and Maxima Identifying indices of local minima-maxima points index of local min index of local max Taking values at min/max points Sorting minima-maxima values (bigger --> lower) Taking the desired number of local minima-maxima... | 847 | en | 0.74017 |
# -*- encoding: utf-8 -*-
# $Id: __init__.py,v 1.8.2.2 2007/05/22 21:06:52 customdesigned Exp $
#
# This file is part of the pydns project.
# Homepage: http://pydns.sourceforge.net
#
# This code is covered by the standard Python License.
#
# __init__.py for DNS class.
__version__ = '2.3.1'
import Type,Opcode,Status,... | tools/hipdnsproxy/DNS/__init__.py | 1,527 | -*- encoding: utf-8 -*- $Id: __init__.py,v 1.8.2.2 2007/05/22 21:06:52 customdesigned Exp $ This file is part of the pydns project. Homepage: http://pydns.sourceforge.net This code is covered by the standard Python License. __init__.py for DNS class. $Log: __init__.py,v $ Revision 1.8.2.2 2007/05/22 21:06:52 customde... | 1,159 | en | 0.700518 |
import os
import sys
import setuptools
# To prevent importing about and thereby breaking the coverage info we use this
# exec hack
about = {}
with open('python_utils/__about__.py') as fp:
exec(fp.read(), about)
if os.path.isfile('README.rst'):
long_description = open('README.rst').read()
else:
long_descr... | setup.py | 1,077 | To prevent importing about and thereby breaking the coverage info we use this exec hack | 87 | en | 0.841132 |
import logging as log
import cv2
import sys
import numpy as np
class LandmarksDetectionModel:
'''
Class for the Face Landmarks Detection Model.
Load and configure inference plugins for the specified target devices,
and performs either synchronous or asynchronous modes for the
specified infer requ... | src/facial_landmarks_detection.py | 6,044 | Class for the Face Landmarks Detection Model.
Load and configure inference plugins for the specified target devices,
and performs either synchronous or asynchronous modes for the
specified infer requests.
Set instance variables.
This method check whether the model (along with the plugin) is support on the CPU device.
... | 1,395 | en | 0.849101 |
"""
ASGI config for FYP project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_... | src/FYP/FYP/asgi.py | 383 | ASGI config for FYP project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/howto/deployment/asgi/ | 209 | en | 0.7294 |
# -*- coding: utf-8 -*-
from __future__ import print_function
from IPython import get_ipython
from IPython.display import (
display,
Javascript,
)
from IPython.core import magic_arguments
from IPython.core.magic import (
Magics,
magics_class,
cell_magic,
)
from IPython.utils.importstring import imp... | yamlmagic.py | 2,090 | Write and load YAML in the IPython Notebook. Uses SafeLoader by default.
Example:
%%yaml x -lyaml.Loader
foo:
bar: baz
-*- coding: utf-8 -*- | 160 | en | 0.575212 |
import h5py
import pickle
import numpy as np
# import read_affect_data as r
# from tqdm import tqdm
import random
from PIL import Image, ImageOps, ImageEnhance
import colorsys
# def read_h5_data_set(path):
# f = h5py.File(path, 'r')
# time_stamps = list(f[list(f.keys())[0]].keys())
# d = {time : dict() f... | deprecated/robustness_tests_draft.py | 14,949 | import read_affect_data as r from tqdm import tqdm def read_h5_data_set(path): f = h5py.File(path, 'r') time_stamps = list(f[list(f.keys())[0]].keys()) d = {time : dict() for time in time_stamps} for feature in list(f.keys()): if hasattr(f[feature], 'keys'): for time in tqdm(list(f[f... | 2,823 | en | 0.59783 |
import os, sys
import ROOT
from ROOT import TH1F,TH2F,TFile,TTree,TCanvas, TProfile, TNtuple, gErrorIgnoreLevel, kInfo, kWarning
from tqdm import tqdm
from particle import Particle, PDGID
tqdm_disable = False
ROOT.gErrorIgnoreLevel = kWarning;
File = TFile("/home/kshi/Zprime/Zp_data_Ntuple/WmTo3l_ZpM45.root","READ")
... | Wto3l/mom_counting.py | 3,474 | for j in range(0,tree.lep_matchedR03_MomMomId.size()): if abs(tree.lep_matchedR03_MomMomId[j])>=11 and abs(tree.lep_matchedR03_MomMomId[j])<=18: print "Event:" + str(tree.Event) + ", Lepton " + str(j) + " MomMomid is: " + leptonstr(tree.lep_matchedR03_MomMomId[j])for j in range(0,tree.lep_matchedR03_PdgId.size()): ... | 2,277 | en | 0.619532 |
import logging
from korbit.client.korbit_client import KorbitClient
logging.basicConfig(level=logging.INFO)
properties_sandbox_file = '../properties_sandbox_test.json'
context_sandbox_file = '../context_sandbox.json'
kbclient = KorbitClient(properties_sandbox_file, context_sandbox_file)
print(kbclient.getUserInfo()... | test/korbit/client/korbit_client_tests.py | 694 | 매수 Buy print( kbclient.buy(price=300000, coin_amount=1) ) 매도 Sell print( kbclient.sell(price=300000, coin_amount=1) ) Wallet Test | 130 | en | 0.472198 |
import asyncio
import socket
from stor.server.server import StorServer
from stor.types.peer_info import PeerInfo
def start_reconnect_task(server: StorServer, peer_info_arg: PeerInfo, log, auth: bool):
"""
Start a background task that checks connection and reconnects periodically to a peer.
"""
# If p... | stor/server/reconnect_task.py | 1,235 | Start a background task that checks connection and reconnects periodically to a peer.
If peer_info_arg is already an address, use it, otherwise resolve it here. | 162 | en | 0.854277 |
"""
Generates code metrics for a given project. Whereas code_metrics.py operates
on a single stream of source code input, this program walks a project tree and
generates reports based on all of the source code found.
TODO: project config should be supplied as input, not imported
"""
import os, shutil
import code_metr... | project_metrics.py | 3,550 | Generates code metrics for a given project. Whereas code_metrics.py operates
on a single stream of source code input, this program walks a project tree and
generates reports based on all of the source code found.
TODO: project config should be supplied as input, not imported
TODO: figure out how to aggregate project... | 739 | en | 0.591556 |
"""
switchboard.manager
~~~~~~~~~~~~~~~~
:copyright: (c) 2015 Kyle Adams.
:license: Apache License 2.0, see LICENSE for more details.
"""
import logging
import sqlalchemy as sqla
from .base import ModelDict
from .models import (
Model,
Switch,
DISABLED, SELECTIVE, GLOBAL, INHERIT,
INCLUDE, EXCLUDE,
... | switchboard/manager.py | 8,168 | Returns a SwitchProxy, rather than a Switch. It allows us to
easily extend the Switches method and automatically include our
manager instance.
Useful for when you need to control Switchboard's setup.
Returns a generator which yields groups of lists of conditions.
>>> for set_id, label, field in operator.get_all_condit... | 1,973 | en | 0.824767 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#----------------------------------------------------------------------------
# Created By Rodrigo Wilkens
# Last update 27/March/2022
# version ='1.0'
# ---------------------------------------------------------------------------
def join_institution(institution):
if ... | openreview/util.py | 3,883 | !/usr/bin/env python -*- coding: utf-8 -*----------------------------------------------------------------------------- Created By Rodrigo Wilkens Last update 27/March/2022 version ='1.0' --------------------------------------------------------------------------- emails = [or_id] try: | 284 | en | 0.358508 |
from pdf_reports import ReportWriter
# DEFINE A WRITER WITH DEFAULT TEMPLATE AND VALUES
report_writer = ReportWriter(
default_stylesheets=["style.css"],
default_template="template.pug",
title="My default title",
version="0.1.2"
)
# THEN LATER IN YOUR CODE:
html = report_writer.pug_to_html(my_name="Zul... | examples/example_reportwriter/example_reportwriter.py | 408 | DEFINE A WRITER WITH DEFAULT TEMPLATE AND VALUES THEN LATER IN YOUR CODE: | 73 | en | 0.87841 |
# coding=utf-8
# *** WARNING: this file was generated by test. ***
# *** 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
__all__ = [
'Foo',
]... | pkg/codegen/testing/test/testdata/plain-schema-gh6957/python/pulumi_xyz/_inputs.py | 693 | coding=utf-8 *** WARNING: this file was generated by test. *** *** Do not edit by hand unless you're certain you know what you are doing! *** | 141 | en | 0.974495 |
import os
import os.path as osp
import numpy as np
# `pip install easydict` if you don't have it
from easydict import EasyDict as edict
__C = edict()
# Consumers can get config by:
# from fast_rcnn_config import cfg
cfg = __C
#
# Training options
#
__C.TRAIN = edict()
# Online hard negative mining
__C.TRAIN.HARD_... | model/utils/config.py | 12,253 | Merge config dictionary a into config dictionary b, clobbering the
options in b whenever they are also specified in a.
Load a config file and merge it into the default options.
Set config keys via list (e.g., from command line).
Return the directory where experimental artifacts are placed.
If the directory does not exi... | 6,463 | en | 0.8614 |
# Code in this file is copied and adapted from
# https://github.com/berkeleydeeprlcourse
import json
"""
Some simple logging functionality, inspired by rllab's logging.
Assumes that each diagnostic gets logged each iteration
Call logz.configure_output_dir() to start logging to a
tab-separated-values file (some_fo... | ADMCode/snuz/ars/logz.py | 3,011 | Set output directory to d, or to /tmp/somerandomnumber if d is None
Write all of the diagnostics from the current iteration
Log a value of some diagnostic
Call this once for each diagnostic quantity, each iteration
Code in this file is copied and adapted from https://github.com/berkeleydeeprlcourse | 302 | en | 0.858333 |
# !/usr/bin/env python
# -*-coding: utf-8 -*-
__author__ = 'wtq'
LOG_PATH = "monitor_logging.log"
REDIS_HOST = "127.0.0.1"
REDIS_PORT = 6379
# 采集的间隔与间断时长
MONITOR_INTERVAL = 1
MONITOR_PEROID = 3
# 监控的读写速率的网卡
NET_NAME = 'eth0'
# 系统内各台机器的名字,以此来计算系统的平均负载信息
SYSTEM_MACHINE_NAME = ["storage1", "storage2"]
# 用来计算客户端链接数的... | config/config.py | 631 | !/usr/bin/env python -*-coding: utf-8 -*- 采集的间隔与间断时长 监控的读写速率的网卡 系统内各台机器的名字,以此来计算系统的平均负载信息 用来计算客户端链接数的机器名字,一般为master | 115 | zh | 0.930899 |
#!/usr/bin/env python
# (works in both Python 2 and Python 3)
# Offline HTML Indexer v1.32 (c) 2013-15,2020 Silas S. Brown.
# 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... | ohi.py | 12,229 | Find shortest prefix of text that differentiates it from previous item (empty string if no difference)
Given 'start' (an index into 'fragments'), find an 'end' that produces the largest possible htmlDoc less than max_filesize. docNo is used to generate previous/next page links as appropriate.
Returns an HTML document ... | 4,366 | en | 0.851421 |
import environ
from pathlib import Path
env = environ.Env(
# Sets debug to False if it cannot find .env
DEBUG=(bool, False)
)
environ.Env.read_env()
# GENERAL
# ------------------------------------------------------------------------------
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DI... | config/settings.py | 6,857 | Sets debug to False if it cannot find .env GENERAL ------------------------------------------------------------------------------ Build paths inside the project like this: BASE_DIR / 'subdir'. https://docs.djangoproject.com/en/dev/ref/settings/std:setting-SECRET_KEY https://docs.djangoproject.com/en/dev/ref/settings/de... | 3,486 | en | 0.415933 |
# model settings
model = dict(
type='CenterNet',
pretrained='modelzoo://resnet18',
backbone=dict(
type='ResNet',
depth=18,
num_stages=4,
out_indices=(0, 1, 2, 3),
frozen_stages=1,
norm_eval=False,
add_summay_every_n_step=200,
style='pytorch'),
... | configs/centernext/eft18_o16_v1norm_3lr_alpha2_wd3e4_s123_nos_2x.py | 4,096 | model settings training and testing settings dataset settings optimizer learning policy yapf:disable yapf:enable runtime settings | 129 | en | 0.778863 |
import multiprocessing as mp
import itertools
import traceback
import pickle
import numpy as np
from numba import cuda
from numba.cuda.testing import (skip_on_cudasim, skip_under_cuda_memcheck,
ContextResettingTestCase, ForeignArray)
import unittest
def core_ipc_handle_test(the_work,... | numba/cuda/tests/cudapy/test_ipc.py | 9,385 | Catch anything going wrong in the worker function noqa: E722 FAILED. propagate the exception as a string OK. send the ndarray back copy the data to host copy the data to host should fail to reopen Catch any exception so we can propagate it noqa: E722 FAILED. propagate the exception as a string OK. send the ndarray back... | 1,009 | en | 0.799655 |
#!/usr/bin/env python2
# Copyright 2016 Vimal Manohar
# 2016 Johns Hopkins University (author: Daniel Povey)
# Apache 2.0
from __future__ import print_function
import argparse
import logging
import sys
from collections import defaultdict
"""
This script reads and writes the 'ctm-edits' file that is
pro... | egs/wsj/s5/steps/cleanup/internal/modify_ctm_edits.py | 20,279 | !/usr/bin/env python2 Copyright 2016 Vimal Manohar 2016 Johns Hopkins University (author: Daniel Povey) Apache 2.0 The ctm-edits file format is as follows [note: file-id is really utterance-id in this context]. <file-id> <channel> <start-time> <duration> <conf> <hyp-word> <ref-word> <edit> e.g.: AJJacobs_... | 4,397 | en | 0.863738 |
# Copyright (C) 2010-2011 Richard Lincoln
#
# 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... | CIM15/CDPSM/Connectivity/IEC61970/Wires/__init__.py | 3,466 | An extension to the Core and Topology package that models information on the electrical characteristics of Transmission and Distribution networks. This package is used by network applications such as State Estimation, Load Flow and Optimal Power Flow.
Copyright (C) 2010-2011 Richard Lincoln Permission is hereby grant... | 1,314 | en | 0.885325 |
from django.apps import AppConfig
class BooksConfig(AppConfig):
name = 'bookstudio.books'
verbose_name = 'books'
def ready(self):
"""Override this to put in:
Users system checks
Users signal registration
"""
pass
| bookstudio/books/apps.py | 276 | Override this to put in:
Users system checks
Users signal registration | 70 | en | 0.708613 |
# pylint: disable=too-few-public-methods, no-member
"""API for scheduling learning rate."""
from .. import symbol as sym
class LRScheduler(object):
"""Base class of a learning rate scheduler.
A scheduler returns a new learning rate based on the number of updates that have
been performed.
Parameters
... | nnvm/python/nnvm/compiler/lr_scheduler.py | 1,985 | Reduce the learning rate by a factor for every *n* steps.
It returns a new learning rate by::
base_lr * pow(factor, num_update/step)
Parameters
----------
step : int
Changes the learning rate for every n updates.
factor : float, optional
The factor to change the learning rate.
stop_factor_lr : float, opt... | 844 | en | 0.693085 |
import sys
import os
import re
import tempfile
import auto_editor
import auto_editor.vanparse as vanparse
from auto_editor.utils.log import Log
from auto_editor.ffwrapper import FFmpeg
def grep_options(parser):
parser.add_argument('--no-filename', action='store_true',
help='Never print filenames with outp... | auto_editor/subcommands/grep.py | 4,597 | We're using the WEBVTT subtitle format. It's better than srt
because it doesn't emit line numbers and the time code is in
(hh:mm:ss.sss) instead of (dd:hh:mm:ss,sss)
stackoverflow.com/questions/9662346/python-code-to-remove-html-tags-from-a-string | 249 | en | 0.764102 |
"""
Create a blueprint with endpoints for logins from configured identity providers.
The identity providers include, for example, Google, Shibboleth, or another
fence instance. See the other files in this directory for the definitions of
the endpoints for each provider.
"""
from authlib.common.urls import add_params_... | fence/blueprints/login/__init__.py | 13,602 | Args:
provider_id (str): provider to log in with; an IDP_URL_MAP key.
fence_idp (str, optional): if provider_id is "fence"
(multi-tenant Fence setup), fence_idp can be any of the
providers supported by the other Fence. If not specified,
will default to NIH login.
shib_idp (str, optio... | 3,319 | en | 0.68775 |
#! /usr/bin/python
"""
Monitoring functions for xrootd cache server, producing classads
that can be handed to condor
"""
import os
import math
import time
import errno
import struct
import collections
import six
from six.moves import urllib
import classad
import XRootD.client
__all__ = ['collect_cache_stats']
# th... | src/xrootd_cache_stats.py | 11,746 | return True if the first list is a prefix of the second
Split a path into a list of directory names
Collect stats on the cache server
Get information about the cache itself
Try to extract useful info from the cinfo file
Scan the top level directory of the cache.
Walks the path looking for directories that are not i... | 2,289 | en | 0.77337 |
'''
dShell output classes
@author: tparker
'''
import os
import sys
import logging
import struct
import datetime
import dshell
import util
class Output(object):
'''
dShell output base class, extended by output types
'''
_DEFAULT_FORMAT = ''
_DEFAULT_TIMEFORMAT = '%Y-%m-%d %H:%M:%S'
_DEFAULT... | lib/output/output.py | 21,310 | true if you want to remove extra fields from the parsed record setup the logger parse the format string this is up to the output plugin to process by default stuffs extra fields and data into 'extra' field if _FILTER_EXTRA is true create the default session writer write a message to the log will be a (name,type,length)... | 2,967 | en | 0.761941 |
"""Auto-generated file, do not edit by hand. MQ metadata"""
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata
PHONE_METADATA_MQ = PhoneMetadata(id='MQ', country_code=596, international_prefix='00',
general_desc=PhoneNumberDesc(national_number_pattern='[56]\\d{8}', possible_number_pattern='\\... | python/phonenumbers/data/region_MQ.py | 1,706 | Auto-generated file, do not edit by hand. MQ metadata | 53 | en | 0.786707 |
# 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/v20200301/vpn_site.py | 23,051 | The set of arguments for constructing a VpnSite resource.
:param pulumi.Input[str] resource_group_name: The resource group name of the VpnSite.
:param pulumi.Input['AddressSpaceArgs'] address_space: The AddressSpace that contains an array of IP address ranges.
:param pulumi.Input['BgpSettingsArgs'] bgp_properties: The ... | 4,029 | en | 0.59594 |
# -*- coding: utf-8 -*-
"""
Copyright [2009-2018] EMBL-European Bioinformatics Institute
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... | rnacentral_pipeline/cli/r2dt.py | 7,915 | This builds a model given then training information. The training
information should be a csv file of:
URS,flag
The flag must be 1 or 0 to indicate if the URS should be shown or not. THis
will fetch the data like the fetch-data command but will then build a model
and write it out the the output file directly.
A gro... | 2,995 | en | 0.895942 |
import os
import pyudev
import psutil
import logging
import time
from arm.ripper import music_brainz
from arm.ui import db
from arm.config.config import cfg
from flask_login import LoginManager, current_user, login_user, UserMixin # noqa: F401
from prettytable import PrettyTable
hidden_attribs = ("OMDB_API_KEY", "EM... | arm/models/models.py | 14,015 | Return a disc object
Return a track object
Returns a string of the object
Returns a string of the object
Returns a string of the object
Eject disc if it hasn't previously been ejected
Get the title for audio cds to use for the logfile name.
Needs the job class passed into it so it can be forwarded to mb
return - only... | 662 | en | 0.628308 |
# Copyright 2020 XEBIALABS
#
# 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, sublice... | src/main/resources/restapi/logger/getLogAppenders.py | 3,408 | Copyright 2020 XEBIALABS 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, sublicense, a... | 1,214 | en | 0.837147 |
# coding: utf-8
"""
App Center Client
Microsoft Visual Studio App Center API # noqa: E501
OpenAPI spec version: preview
Contact: benedetto.abbenanti@gmail.com
Project Repository: https://github.com/b3nab/appcenter-sdks
"""
from __future__ import absolute_import
import unittest
import appcente... | sdks/python/test/test_DistributionGroupAppsDeleteRequest.py | 1,084 | DistributionGroupAppsDeleteRequest unit test stubs
Test DistributionGroupAppsDeleteRequest
App Center Client
Microsoft Visual Studio App Center API # noqa: E501
OpenAPI spec version: preview
Contact: benedetto.abbenanti@gmail.com
Project Repository: https://github.com/b3nab/appcenter-sdks
coding: utf-8 noqa: E501 ... | 506 | en | 0.509512 |
# Copyright 2008-2015 Nokia Solutions and Networks
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... | src/robot/model/criticality.py | 1,527 | Copyright 2008-2015 Nokia Solutions and Networks 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 ... | 582 | en | 0.857814 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.