content stringlengths 27 928k | path stringlengths 4 230 | size int64 27 928k | nl_text stringlengths 21 396k | nl_size int64 21 396k | nl_language stringlengths 2 3 | nl_language_score float64 0.04 1 |
|---|---|---|---|---|---|---|
import random
from collections import defaultdict, deque
import logging
import operator as op
import time
from enum import unique, Flag
from functools import reduce
from BaseClasses import RegionType, Door, DoorType, Direction, Sector, CrystalBarrier
from Regions import key_only_locations
from Dungeons import hyrule_c... | DoorShuffle.py | 108,835 | Drop-down connections & push blocks These should all be connected for now as normal connections These connections are here because they are currently unable to be shuffled if not world.experimental[player]: todo: I think this function is not necessary traverse dungeons and make sure dungeon property is assigned needs t... | 4,313 | en | 0.88455 |
""" info API method."""
from ibsng.handler.handler import Handler
class getAllGatewayNames(Handler):
""" info method class."""
def setup(self, **kwargs):
"""Setup required parameters.
:param dict kwargs: input args
:return: void
:rtype: void
"""
for key, valu... | ibsng/handler/online_payment/get_all_gateway_names.py | 379 | info method class.
Setup required parameters.
:param dict kwargs: input args
:return: void
:rtype: void
info API method. | 122 | en | 0.242569 |
# 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 ... | test/multiapi/Expected/AcceptanceTests/Multiapi/multiapi/v3/aio/operations/_operation_group_two_operations.py | 6,321 | OperationGroupTwoOperations async 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: ~multiapi.v3.models
:param client: C... | 1,064 | en | 0.626557 |
import pytest
from app.db import model, session_ctx
from app.util import exceptions
from app.server.routes import routes
from app.server.requestutils import *
import flask
import flask.testing
def test_pubsubify_excs(fake_import: model.Import, client_with_modifiable_routes: flask.testing.FlaskClient):
client = ... | app/tests/test_requestutils.py | 1,066 | pre-populate an import that will get error'd | 44 | en | 0.819548 |
#!/usr/bin/env python3
# Copyright (c) 2014-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 mempool persistence.
By default, bwscoind will dump mempool on shutdown and
then reload it on sta... | test/functional/mempool_persist.py | 4,946 | Test mempool persistence.
By default, bwscoind will dump mempool on shutdown and
then reload it on startup. This can be overridden with
the -persistmempool=0 command line option.
Test is as follows:
- start node0, node1 and node2. node1 has -persistmempool=0
- create 5 transactions on node2 to its own address. N... | 1,946 | en | 0.846379 |
# Copyright (c) 2015 Nicolas JOUANIN
#
# See the file license.txt for copying permission.
import logging
from functools import partial
class EventLoggerPlugin:
def __init__(self, context):
self.context = context
async def log_event(self, *args, **kwargs):
self.context.logger.info("### '%s' ... | distmqtt/plugins/logging.py | 1,390 | Copyright (c) 2015 Nicolas JOUANIN See the file license.txt for copying permission. | 83 | en | 0.681318 |
"""
WSGI config for share_all project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SE... | share_all/wsgi.py | 396 | WSGI config for share_all project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/ | 216 | en | 0.781114 |
# Copyright (C) 2019-2020 Intel Corporation
#
# SPDX-License-Identifier: MIT
import attr
from contextlib import ExitStack
from distutils.util import strtobool as str_to_bool # pylint: disable=unused-import
from functools import partial, wraps
from itertools import islice
from typing import Iterable, Tuple
NOTSET = ... | datumaro/util/__init__.py | 5,888 | 'escapes' is an iterable of (pattern, substitute) pairs
Returns elements from the input iterable by batches of N items.
('abcdefg', 3) -> ['a', 'b', 'c'], ['d', 'e', 'f'], ['g']
'escapes' is an iterable of (pattern, substitute) pairs
Copyright (C) 2019-2020 Intel Corporation SPDX-License-Identifier: MIT pylint: disab... | 475 | en | 0.536523 |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: tensorflow/core/protobuf/saver.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflect... | tensorflow/core/protobuf/saver_pb2.py | 6,539 | Generated protocol buffer code.
-*- coding: utf-8 -*- Generated by the protocol buffer compiler. DO NOT EDIT! source: tensorflow/core/protobuf/saver.proto @@protoc_insertion_point(imports) @@protoc_insertion_point(class_scope:tensorflow.SaverDef) @@protoc_insertion_point(module_scope) | 288 | en | 0.505174 |
import urllib.request, urllib.parse, urllib.error
import json
url = input('Web page: ')
print('Retrieving', url)
uh = urllib.request.urlopen(url)
data = uh.read().decode()
info = json.loads(data)
# info é um dict do tipo:
# {'note': 'This file contains the sample data for testing', 'comments': [{'name': '... | book3/s6_ex3.py | 715 | info é um dict do tipo: {'note': 'This file contains the sample data for testing', 'comments': [{'name': 'Romina', 'cou ... * print(info['comments']) a primeira subdivisao é entre 'notes' e 'comments' * print(item) cada item é um dict com 'name' e 'count' list Comprehensions é mais legal | 297 | pt | 0.640542 |
#Embedded file name: ACEStream\Player\BaseApp.pyo
import os
import sys
import time
import shutil
import urllib
import hashlib
import binascii
import random
import subprocess
import struct
import pickle
import cookielib
from operator import itemgetter
from base64 import b64encode, encodestring
from types import DictType... | .kodi/userdata/addon_data/plugin.video.p2p-streams/acestream/ace/ACEStream/Player/BaseApp.py | 153,607 | Embedded file name: ACEStream\Player\BaseApp.pyo | 48 | en | 0.612645 |
"""
Support for Homekit number ranges.
These are mostly used where a HomeKit accessory exposes additional non-standard
characteristics that don't map to a Home Assistant feature.
"""
from aiohomekit.model.characteristics import Characteristic, CharacteristicsTypes
from homeassistant.components.number import NumberEnt... | homeassistant/components/homekit_controller/number.py | 2,876 | Representation of a Number control on a homekit accessory.
Initialise a HomeKit number control.
Return type of sensor.
Define the homekit characteristics the entity is tracking.
Return the sensor icon.
Return the maximum value.
Return the minimum value.
Return the increment/decrement step.
Return the current characteri... | 507 | en | 0.74247 |
# -*- coding: utf-8 -*-
from django.conf.urls import url
from django.views.generic import TemplateView
from . import views
app_name = 'services_communicator'
urlpatterns = [
url(
regex="^ServiceList/~create/$",
view=views.ServiceListCreateView.as_view(),
name='ServiceList_create',
),
... | services_communicator/urls.py | 911 | -*- coding: utf-8 -*- | 21 | en | 0.767281 |
#
# Copyright 2018 EveryUP Srl
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | LW-UI/authosm/models.py | 4,568 | Abstract User with the same behaviour as Django's default User.
Inherits from both the AbstractBaseUser and PermissionMixin.
The following attributes are inherited from the superclasses:
* password
* last_login
* is_superuser
Concrete class of AbstractCustomUser.
Use this if you don't need to extend Cus... | 1,023 | en | 0.833735 |
# Copyright 2021 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... | MindElec/examples/physics_driven/frequency_domain_maxwell/src/model.py | 1,901 | Full-connect networks.
Args:
input_dim (int): the input dimensions.
output_dim (int): the output dimensions.
hidden_layer (int): number of hidden layers.
activation (str or Cell): activation functions.
fc network
feedforward neural network
Copyright 2021 Huawei Technologies Co., Ltd Licensed under the Apache License... | 883 | en | 0.761555 |
# !/usr/bin/python3
# coding: utf_8
""" Config your app """
import os
from hal.files.parsers import JSONParser
from hal.files.save_as import write_dicts_to_json
from .config import APP_FOLDER, API_FOLDER, DATA_FOLDER
from .data.coins import CryptoCoin, CRYPTO_COINS
class ConfigManager:
""" Manages config fil... | pyhodl/app.py | 2,172 | Manages config files for app
:return: {}
Config data
:return: void
Creates config file
:return: void
Creates folder
:param key: str
What you want
:return: {}
Item you want
:param symbol: str
Symbol of coin
:return: CryptoCoin
Coin if a crypto-coin exists with that name
:return: void
Sav... | 414 | en | 0.561655 |
"""is_sqllab_view
Revision ID: 130915240929
Revises: f231d82b9b26
Create Date: 2018-04-03 08:19:34.098789
"""
import sqlalchemy as sa
from alembic import op
from sqlalchemy.ext.declarative import declarative_base
from rabbitai import db
# revision identifiers, used by Alembic.
revision = "130915240929"
down_revisio... | rabbitai/migrations/versions/130915240929_is_sqllab_viz_flow.py | 1,164 | Declarative class to do query in upgrade
is_sqllab_view
Revision ID: 130915240929
Revises: f231d82b9b26
Create Date: 2018-04-03 08:19:34.098789
revision identifiers, used by Alembic. Use Slice class defined here instead of models.Slice | 238 | en | 0.610533 |
from collections import OrderedDict
from . import util
from ..errors import ModelInfoLookupError
class ModelInfo:
def __init__(self, pairs=[], default_fields=None):
"""
Constructs a mapping of information about a model.
:class:`~revscoring.scoring.ModelInfo` objects are usually nested
... | revscoring/scoring/model_info.py | 5,567 | Constructs a mapping of information about a model.
:class:`~revscoring.scoring.ModelInfo` objects are usually nested
within each other to provide a convenient tree structure for
:func:`~revscoring.scoring.ModelInfo.lookup` and
:func:`~revscoring.scoring.ModelInfo.format`.
Format a representation of the model informatio... | 1,395 | en | 0.679014 |
# -*- coding: utf-8 -*-
import cv2
import numpy as np
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
# Define a class to receive the characteristics of each line detection
class Lane():
def __init__(self):
# 当前的图像
self.current_warped_binary = None
# 当前图片的尺寸
self.c... | lane/Lane.py | 13,189 | Calculates the curvature of polynomial functions in meters.
-*- coding: utf-8 -*- Define a class to receive the characteristics of each line detection 当前的图像 当前图片的尺寸 检测到的车道线像素的横坐标 x values for detected line pixels 检测到的车道线像素的纵坐标 y values for detected line pixels 以纵坐标为自变量,取值空间 +++++++++++++++++++++++++++++++++++++++++++... | 4,859 | en | 0.606499 |
import ctypes as C
import numpy as np
from math import log,e
import hankelmatrixcreator
import sys
import time
import iohelpers
import math
import modelconversion
from scipy.sparse.linalg import lsqr
from scipy import sparse
import copy
DEBUG = False
VERBOSE = True
FAILURE_CONST = -100000.0
class TensorWFA:
def... | code/tensor/wfatensorlearn.py | 16,907 | adding aliases with "self" prefix for readability. hbar_pandsigma = np.mat(self.hbar_pandsigma.toarray()) hbar_sigmaands = np.mat(self.hbar_sigmaands.toarray()) hbar_pands = np.mat(self.hbar_pands.toarray())provides average log-likelihood scoreupdates a/start/state vector after seeing symbolresets state vectorreturns t... | 808 | en | 0.321544 |
"""\
Perl code generator
@copyright: 2002-2004 D.H. aka crazyinsomniac on sourceforge.net
@copyright: 2012-2016 Carsten Grohmann
@copyright: 2017-2020 Dietmar Schwertberger
@license: MIT (see LICENSE.txt) - THIS PROGRAM COMES WITH NO WARRANTY
"""
import os, os.path, re
from codegen import BaseLangCodeWriter, BaseSour... | codegen/perl_codegen.py | 22,443 | Code writer class for writing Perl code out of the designed GUI elements; see: BaseLangCodeWriter
build template string for application
Returns the name for a Perl module (.pm) to store a single class in multi file projects
Escape all unicode characters to there unicode code points in form of \uxxxx.
The returned strin... | 4,170 | en | 0.747556 |
# Auto generated from meta.yaml by namespacegen.py version: 0.4.0
# Generation date: 2020-08-25 16:45
# Schema: metamodel
#
# id: https://w3id.org/biolink/biolinkml/meta
# description: A metamodel for defining biolink related schemas
# license: https://creativecommons.org/publicdomain/zero/1.0/
from collections import... | tests/test_scripts/output/gennamespace/meta_namespaces.py | 5,957 | Map of BioLink Model registered URI Namespaces
Applies the specified XMLNS prefix to (an) identifier(s) known
to be "raw" IDs as keys in a dictionary or elements in a list (or a simple string)
:param identifiers:
:param prefix:
:return:
Returns the core object_id of a CURIE, with or without the version suffix.
Note: n... | 1,758 | en | 0.623757 |
from typing import Sequence, Dict, List, Optional
from abc import ABC, abstractmethod
# from nltk.corpus import wordnet
from pymagnitude import Magnitude
from .utils import (
UPPERCASE_RE,
LOWERCASE_RE,
DIGIT_RE,
PUNC_REPEAT_RE,
)
class FeatureExtractor(ABC):
@abstractmethod
def extract(
... | CRF/feature_extractors.py | 7,685 | from nltk.corpus import wordnet | 31 | en | 0.294486 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import multiprocessing
from functools import partial
import tensorflow as tf
import tensorflow.contrib.eager as tfe
from general.utilTF1.utils import session
from general.kneeOsteoarthritisDataset.KneeOsteoart... | general/utilTF1/dataset.py | 5,854 | DiskImageData.
This class is suitable for jpg and png files
Arguments:
img_paths : String list or 1-D tensor, each of which is an iamge path
labels : Label list or tensor, each of which is a corresponding label
Disk image batch dataset.
This function is suitable for jpg and png files
Arguments:
img_p... | 623 | en | 0.682548 |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
from flask import Flask
from flask import request
from flask import jsonify
from line_sdk import Linebot
LINE_ACCESS_TOKEN = ""
LINE_CHANNEL_SECRET = ""
app = Flask(__name__)
@app.route("/", methods=["GET", "POST"])
def webhook():
# GET
if request.method == "G... | Heroku/Heroku-Linebot-Github/line_app.py | 1,569 | !/usr/bin/env python3 -*- coding:utf-8 -*- GET POST Line dataLIST = [{status, type, message, userID, replyToken, timestamp}] replyToken = 回覆需要的ID , message = 使用者輸入的內容 這裡輸入客製化內容 dataDICT["message"] => 使用者輸入的內容 respText(聊天室ID, 要回覆的內容) OTHER | 238 | zh | 0.527236 |
# All paths are relative to train_val.py file
config = {
'images_path': 'train_val_data/Flicker8k_Dataset/', #Make sure you put that last slash(/)
'train_data_path': 'train_val_data/Flickr8k_text/Flickr_8k.trainImages.txt',
'val_data_path': 'train_val_data/Flickr8k_text/Flickr_8k.devImages.txt',
'captions_path... | ml/config.py | 2,144 | All paths are relative to train_val.py fileMake sure you put that last slash(/)Make sure you put that last slash(/)This is set manually after training of model and required for test.py Photo by John Price (https://unsplash.com/@johnprice?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText) on Unsplash (h... | 959 | en | 0.752702 |
"""
---
title: Train Feedback Transformer
summary: This is training code with notes for a feedback transformer.
---
# Train Feedback Transformer
This trains a [feedback transformer](index.html) model for auto-regression.
You can pick the original feedback transformer or the new version
where the keys and values are p... | labml_nn/transformers/feedback/experiment.py | 4,893 | ## Auto regressive model
## Configurations
The default configs can and will be over-ridden when we start the experiment
Create [original feedback transformer](index.html).
Create [updated feedback transformer](index.html#kv_shared), with precalculated keys and values.
---
title: Train Feedback Transformer
summary: Thi... | 1,363 | en | 0.641244 |
# 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/source/conf.py | 3,065 | Get the library version from pyproject.toml
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 --------------------------------------... | 1,713 | en | 0.678744 |
import os
from os import path
import stat
import mmap
import directio
from setting import (
LONGHORN_SOCKET_DIR, LONGHORN_DEV_DIR, PAGE_SIZE,
)
def readat_direct(dev, offset, length):
pg = offset / PAGE_SIZE
in_page_offset = offset % PAGE_SIZE
# either read less than a page, or whole pages
if in_... | integration/data/frontend.py | 2,042 | either read less than a page, or whole pages don't support across page write return readat_direct(self.dev, offset, length) | 123 | en | 0.731409 |
import datetime
import string
from collections import namedtuple
from distutils.version import LooseVersion
from random import choices
from typing import Optional, Type
import numpy as np
import pandas as pd
import pyarrow as pa
import pytest
from pandas.tests.extension.base import (
BaseArithmeticOpsTests,
Ba... | tests/test_pandas_extension.py | 32,872 | Whether to box the data in a Series.
Fixture with data for factorization, grouping, and unique tests.
Expected to be like [B, B, NA, NA, A, A, B, C]
Where A < B < C and NA is missing
Length-3 array with a known sort order.
This should be three items [B, C, A] with
A < B < C
Length-3 array with a known sort order.
T... | 1,947 | en | 0.823899 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-06-09 13:02
from __future__ import unicode_literals
from django.db import migrations
def load_continents(apps, schema_editor):
continent = apps.get_model("country_name_tool", "Continent")
newcontinents = [['NA', 'North America'], ['AS', 'Asia'], ['AF... | country_name_tool/migrations/0003_auto_20170609_1302.py | 749 | -*- coding: utf-8 -*- Generated by Django 1.11 on 2017-06-09 13:02 | 66 | en | 0.708555 |
import os,sys,json,cv2
from nima.inference.inference_model import InferenceModel
import opt4 as opt
from PIL import Image
# write to result file
def write_json(args,score):
try:
outfile =open(args[3],'w')
#print('saving test json at '+args[3])
except IndexError:
print('output_location ... | nima/nima_new.py | 4,372 | write to result fileprint('saving test json at '+args[3])print(score)get score by testing'''print(r['mean_score'],type(r['mean_score']))switch mode and execute testprint(image)print(i,results)get image from a folder detect test or adjust detect folder or a pictureprint(target) mainmodel_pth = './tmp/emd_loss_epoch_49_t... | 608 | en | 0.561162 |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from functorch import grad, nnc_jit, make_fx, make_nnc
import torch
import time
def f(x):
return torch.sin(... | examples/compilation/simple_function.py | 817 | Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. | 195 | en | 0.937181 |
#!/usr/bin/env python3
#
# This file is part of LiteX-Boards.
#
# Copyright (c) 2021 Florent Kermarrec <florent@enjoy-digital.fr>
# Copyright (c) 2021 Greg Davill <greg.davill@gmail.com>
# SPDX-License-Identifier: BSD-2-Clause
# Build/Use:
# ./gsd_butterstick.py --uart-name=crossover --with-etherbone --csr-csv=csr.cs... | litex_boards/targets/gsd_butterstick.py | 8,915 | !/usr/bin/env python3 This file is part of LiteX-Boards. Copyright (c) 2021 Florent Kermarrec <florent@enjoy-digital.fr> Copyright (c) 2021 Greg Davill <greg.davill@gmail.com> SPDX-License-Identifier: BSD-2-Clause Build/Use: ./gsd_butterstick.py --uart-name=crossover --with-etherbone --csr-csv=csr.csv --build --load li... | 1,233 | en | 0.207246 |
#!/usr/bin/env python3
# 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.
"""
Provides standard metric evaluations for dialog.
Uses locking and shared memory when ``numthreads`` is set to >1 to ... | parlai/core/metrics.py | 25,487 | Class that keeps a running average of some metric.
Examples of AverageMetrics include hits@1, F1, accuracy, etc. These metrics all have
per-example values that can be directly mapped back to a teacher.
Helper class which computes token-level F1.
Fixed metrics are verified to be the same when combined, or throw an erro... | 6,161 | en | 0.882948 |
from abcunits import ConversionUnit
KFACTOR = 273.15 #Difference Kelvin, C (how precise is this known?)
class TempUnit(ConversionUnit):
""" Temperature units. ALl conversions go through Kelvin. """
#http://www.metric-conversions.org/temperature/fahrenheit-to-kelvin.htm
class Kelvin(TempUnit):
short = 'K'... | skspec/units/tempunits.py | 1,284 | Temperature units. ALl conversions go through Kelvin.
Difference Kelvin, C (how precise is this known?)http://www.metric-conversions.org/temperature/fahrenheit-to-kelvin.htmProper names, keep this way?Isn't degree Kelvin technially wrong?For null case | 254 | en | 0.801498 |
##
##
# File auto-generated against equivalent DynamicSerialize Java class
class DeleteRequest(object):
def __init__(self):
self.datasets = None
self.groups = None
self.filename = None
def getDatasets(self):
return self.datasets
def setDatasets(self, datasets):
s... | dynamicserialize/dstypes/com/raytheon/uf/common/pypies/request/DeleteRequest.py | 589 | File auto-generated against equivalent DynamicSerialize Java class | 66 | en | 0.815673 |
# -*- coding: utf-8 -*-
{
"name": """Preview Media Files""",
"summary": """Open attached images in popup""",
"category": "Web",
"images": ["images/screenshot-1.png"],
"vesion": "10.0.1.0.0",
"application": False,
"author": "IT-Projects LLC, Dinar Gabbasov",
"support": "apps@itpp.dev",
... | web_preview/__manifest__.py | 787 | -*- coding: utf-8 -*- | 21 | en | 0.767281 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# convert / import osm xml .osm file into a Shapefile
import subprocess
import os
import shutil
# specify output format
output_format = "ESRI Shapefile"
# complete path to input OSM xml file .osm
input_osm = '../geodata/OSM_san_francisco_westbluff.osm'
# Windows users c... | ch03/code/ch03-04_osm2shp.py | 1,553 | !/usr/bin/env python -*- coding: utf-8 -*- convert / import osm xml .osm file into a Shapefile specify output format complete path to input OSM xml file .osm Windows users can uncomment these two lines if needed ogr2ogr = r"c:/OSGeo4W/bin/ogr2ogr.exe" ogr_info = r"c:/OSGeo4W/bin/ogrinfo.exe" view what geometry types ar... | 673 | en | 0.564318 |
from flask_wtf import FlaskForm
from flask_wtf.file import FileRequired
from wtforms import (
StringField,
SubmitField,
PasswordField,
FileField,
SelectField,
TextAreaField,
BooleanField,
)
from wtforms.validators import DataRequired, Length, ValidationError
from models import RoomBGMTypes
... | theunderground/forms.py | 5,251 | Choices for the select field are only evaluated once, so we must set it when necessary. | 87 | en | 0.898393 |
#!/usr/bin/env python3
# Copyright (c) 2010 ArtForz -- public domain half-a-node
# Copyright (c) 2012 Jeff Garzik
# Copyright (c) 2010-2020 The UFO Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""UFO test framewo... | test/functional/test_framework/messages.py | 51,355 | Deserialize from addrv1 format (pre-BIP155)
Deserialize from addrv2 format (BIP155)
Serialize in addrv1 format (pre-BIP155)
Serialize in addrv2 format (BIP155)
UFO test framework primitive and message structures
CBlock, CTransaction, CBlockHeader, CTxIn, CTxOut, etc....:
data structures that should map to correspo... | 4,189 | en | 0.814852 |
# -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup ------------------------------------------------------------... | docs/conf.py | 5,157 | -*- coding: utf-8 -*- Configuration file for the Sphinx documentation builder. This file does only contain a selection of the most common options. For a full list see the documentation: http://www.sphinx-doc.org/en/master/config -- Path setup -------------------------------------------------------------- If extensions ... | 4,028 | en | 0.608195 |
from unittest import TestCase, mock
from bulksms.sms import send_single, send_bulk
class BulkSMSTestCase(TestCase):
def test_send_single_sms(self):
# Mock send single sms function.
mock_send_single = mock.create_autospec(send_single, return_value='results')
mock_send_single('0831234567', ... | tests/unit/test_bulksms.py | 768 | Mock send single sms function. Mock send bulk sms function. | 59 | en | 0.7476 |
import os
from options.train_options import TrainOptions
from models import create_model
from util.visualizer import save_images
from util import html
from PIL import Image
import string
import torch
import torchvision
import torchvision.transforms as transforms
import coremltools as ct
from util import util
import ... | imtest.py | 3,419 | opt.name = "siggraph_retrained" test code only supports num_threads = 1 test code only supports batch_size = 1 no visdom display process opt.suffix with torch.no_grad(): print(data["mask_B"], data["hint_B"]) data["hint_B"] = torch.zeros_like(data["hint_B"]) data["mask_B"] = torch.zeros_like(data["mask_B"]) model = Colo... | 709 | en | 0.194728 |
from __future__ import division
from itertools import combinations_with_replacement
import numpy as np
import math
import sys
def shuffle_data(X, y, seed=None):
if seed:
np.random.seed(seed)
n_samples = X.shape[0]
idx = np.arange(n_samples)
np.random.shuffle(idx)
X = X[idx]
y = y[idx]
... | mlfromscratch/utils/data_manipulation.py | 4,893 | Divide dataset based on if sample value on feature index is larger than the given threshold Return random subsets (with replacements) of the data Concatenate x and y and do a random shuffle Uses 50% of training samples without replacements 100% with replacements Normalize the dataset X Standardize the dataset X X_std =... | 726 | en | 0.839107 |
'''
This file is a part of Test Mile Arjuna
Copyright 2018 Test Mile Software Testing Pvt Ltd
Website: www.TestMile.com
Email: support [at] testmile.com
Creator: Rahul Verma
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 ... | arjuna/engine/unitee/exceptions.py | 2,886 | This file is a part of Test Mile Arjuna
Copyright 2018 Test Mile Software Testing Pvt Ltd
Website: www.TestMile.com
Email: support [at] testmile.com
Creator: Rahul Verma
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 co... | 715 | en | 0.83964 |
# Copyright The PyTorch Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... | pytorch_lightning/utilities/__init__.py | 2,355 | General utilities.
Copyright The PyTorch Lightning team. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed t... | 668 | en | 0.809176 |
"""
WSGI config for poker project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTING... | poker/wsgi.py | 387 | WSGI config for poker project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/ | 211 | en | 0.775142 |
#!/usr/bin/env python
# Import required modules
from __future__ import print_function
from future import standard_library
standard_library.install_aliases()
from builtins import str
import os
import argparse
import subprocess
import ICA_AROMA_functions as aromafunc
import shutil
import classification_plots
# Change t... | thirdparty/ICA_AROMA_79x95x69/ICA_AROMA.py | 11,580 | !/usr/bin/env python Import required modules Change to script directory-------------------------------------------- PARSER -------------------------------------------- Required options Required options in non-Feat mode Required options in Feat mode Optional options--------------------------------------- PARSE ARGUMENTS... | 1,707 | en | 0.414131 |
# -*- coding: utf-8 -*-
# Copyright Hannah von Reth <vonreth@kde.org>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of condi... | bin/Utils/GetFiles.py | 8,038 | download file with curl from 'url' into 'destdir', if filename is given to the file specified
download file from 'url' into 'destdir'
download file with wget from 'url' into 'destdir', if filename is given to the file specified
-*- coding: utf-8 -*- Copyright Hannah von Reth <vonreth@kde.org> Redistribution and use i... | 1,724 | en | 0.859509 |
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'zhekudblog.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise Imp... | src/zhekudblog/manage.py | 630 | Django's command-line utility for administrative tasks.
!/usr/bin/env python | 77 | en | 0.656913 |
import numpy as np
import tempfile
import os
import pytest
import torch
from anndata import AnnData
from scvi.dataset import (
AnnDatasetFromAnnData,
CortexDataset,
SyntheticDataset,
GeneExpressionDataset,
Dataset10X,
)
from scvi.inference import (
JointSemiSupervisedTrainer,
AlternateSemi... | tests/test_scvi.py | 22,043 | iter Sample scale example Differential expression different models DE estimation example Test totalVI DE Differential expression different models adversarial testing ensures neg values raise warning ensures float values raise warning | 233 | en | 0.520064 |
# -*- coding: utf-8 -*-
# Define here the models for your spider middleware
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/spider-middleware.html
from scrapy import signals
class JianshuSpiderSpiderMiddleware(object):
# Not all methods need to be defined. If a method is not defined,
# s... | scrapy/jianshu_spider/jianshu_spider/middlewares.py | 3,611 | -*- coding: utf-8 -*- Define here the models for your spider middleware See documentation in: https://doc.scrapy.org/en/latest/topics/spider-middleware.html Not all methods need to be defined. If a method is not defined, scrapy acts as if the spider middleware does not modify the passed objects. This method is used by ... | 1,931 | en | 0.87019 |
#!/usr/bin/env python
# Copyright 2016 Medical Research Council Harwell.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requir... | setup.py | 1,007 | !/usr/bin/env python Copyright 2016 Medical Research Council Harwell. 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... | 694 | en | 0.815972 |
# This file is part of Scapy
# See http://www.secdev.org/projects/scapy for more information
# Copyright (C) Philippe Biondi <phil@secdev.org>
# This program is published under a GPLv2 license
#############################################################################
# ... | lib/scapy/layers/hsrp.py | 3,766 | HSRP (Hot Standby Router Protocol): proprietary redundancy protocol for Cisco routers. # noqa: E501
This file is part of Scapy See http://www.secdev.org/projects/scapy for more information Copyright (C) Philippe Biondi <phil@secdev.org> This program is published under a GPLv2 license ... | 1,545 | en | 0.759747 |
# model settings
model = dict(
type='FasterRCNN',
pretrained='open-mmlab://resnet50_caffe',
backbone=dict(
type='ResNet',
depth=50,
num_stages=4,
out_indices=(0, 1, 2, 3),
frozen_stages=1,
norm_cfg=dict(type='BN', requires_grad=False),
norm_eval=True,
... | configs/guided_anchoring/ga_faster_r50_caffe_fpn_1x.py | 6,133 | model settings model training and testing settings dataset settings optimizer learning policy yapf:disable dict(type='TensorboardLoggerHook') yapf:enable runtime settings | 170 | en | 0.727131 |
# -*- coding: utf-8 -*-
###
# (C) Copyright (2012-2017) Hewlett Packard Enterprise Development LP
#
# 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 limi... | examples/server_profiles.py | 10,920 | -*- coding: utf-8 -*- (C) Copyright (2012-2017) Hewlett Packard Enterprise Development LP 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 right... | 2,451 | en | 0.855731 |
import sqlite3
import pandas as pd
import numpy as np
import csv
import gzip
from collections import defaultdict
if __name__ == '__main__':
conn = sqlite3.connect('data/instacart.db')
c = conn.cursor()
# Get the orders properly sorted, so we can directly
# group by user_id, order_id and th... | data/external/repositories_2to3/164369/kaggle-public-master/instacart/compute_weights_2.py | 1,884 | Get the orders properly sorted, so we can directly group by user_id, order_id and then compute the weights. First day is 0 Cumsum to obtain total days since *first* order But I need to subtract cumulative_days from the actual day of the order we want to compute... which will be the maximum Compute weights Remove unwan... | 403 | en | 0.858729 |
import cv2
import numpy as np
import math
from vcam import vcam,meshGen
def nothing(x):
pass
WINDOW_NAME = "output"
cv2.namedWindow(WINDOW_NAME,cv2.WINDOW_NORMAL)
cv2.resizeWindow(WINDOW_NAME,700,700)
# Creating the tracker bar for all the features
cv2.createTrackbar("X",WINDOW_NAME,500,1000,nothing)
cv2.createT... | GUI.py | 2,312 | Creating the tracker bar for all the features cap = cv2.VideoCapture(0) ret,img = cap.read() ret, img = cap.read() | 114 | en | 0.413493 |
#!/usr/bin/python
'''
Gapfilling function that utilizes pFBA and flux sampling to find most
parsimonious additional reactions to achieve minimum flux through the objective
Author: Matthew Jenior
'''
import pandas
import math
import copy
import time
import random
# Using Cobrapy 0.13.0
import cobra
import cobra.test
fr... | pfba_gapfiller.py | 7,930 | Function that utilizes iterations of pFBA solution with a universal reaction bag
in order to gapfill a model.
Parameters
----------
model : cobra.Model
Model to be gapfilled
reaction_bag : cobra.Model
Reaction bag reference to use during gapfilling
obj : string
Reaction ID for objective function in model ... | 2,203 | en | 0.858558 |
import torch
import time
from audio_zen.acoustics.feature import mag_phase
from audio_zen.acoustics.mask import decompress_cIRM
from audio_zen.inferencer.base_inferencer import BaseInferencer
# for log
from utils.logger import log
print=log
def cumulative_norm(input):
eps = 1e-10
device = input.device
da... | speech_enhance/fullsubnet/inferencer/inferencer.py | 8,392 | for log [B, T] [B, T] [B, T] [1, T] [1, T] => [B, T] B, T B, T B, T [B, F, T] => [B, 1, F, T] [B, F, T] => [B, 1, F, T] => model => [B, 2, F, T] => [B, F, T, 2] [F, T] [B, N, C, F_s, T] <=> [1, 257, 1, 31, T] [257, 31, 200] <=> [B, F_s, T] [B, 2, T] <=> [F, 2, T] [B, T, 2] 模拟语音的静音段,防止一上来就给语音,处理的不好 concat([(8, 256), (..... | 498 | en | 0.749364 |
# test_codecs.py from CPython 2.7, modified for Jython
from test import test_support
import unittest
import codecs
import locale
import sys, StringIO
if not test_support.is_jython:
import _testcapi
class Queue(object):
"""
queue: write bytes at one end, read bytes from the other end
"""
def __init_... | framework/extensions/org.python.jython/Lib/test/test_codecs.py | 60,499 | test_codecs.py from CPython 2.7, modified for Jython get a StreamReader for the encoding and feed the bytestring version of input to the reader byte by byte. Read everything available from the StreamReader and check that the results equal the appropriate entries from partialresults. check that there's nothing left in t... | 8,189 | en | 0.746593 |
# Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | tensorflow/python/keras/optimizer_v2/adam_test.py | 22,978 | Tests for Adam.
Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applica... | 1,643 | en | 0.688031 |
# 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/containerinstance/azure-mgmt-containerinstance/azure/mgmt/containerinstance/aio/operations/_container_groups_operations.py | 42,428 | ContainerGroupsOperations async 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.containerinstance.models
:... | 4,291 | en | 0.440757 |
from typing import Union
import Geometry
from Geometry import Line
from Geometry import Point
import cmath
class Circle:
def __init__(self, center: Union[Point, tuple, list], radius: float):
if isinstance(center, tuple) or isinstance(center, list):
assert len(center) == 2, "Center must be... | Geometry/circle.py | 4,442 | Returns the area of a sector of the circle which subtended angle theta(radians) at center.
Returns the length of a sector of the circle which subtended angle theta(radians) at center.
try: m = Geometry.slope(self.center, p) except ZeroDivisionError: return Line(0, 1, -p.y) if m == 0: return Line(1, 0, -p.... | 372 | en | 0.556023 |
from collections import OrderedDict
from PyQt5 import QtCore
from PyQt5 import QtWidgets
from easygraphics.dialog._indexed_order_list import IndexedOrderedDict
__all__ = ['MultipleFieldsDialog']
class MultipleFieldsDialog(QtWidgets.QDialog):
"""Dialog with multiple fields stored in a dict, with the label
... | easygraphics/dialog/multifields.py | 2,501 | Dialog with multiple fields stored in a dict, with the label
being the key and the entry being the corresponding value
Selection completed, set the value and close
set up a special case for quick demo | 202 | en | 0.884103 |
from musicautobot.numpy_encode import *
from musicautobot.config import *
from musicautobot.music_transformer import *
from musicautobot.utils.midifile import *
from musicautobot.utils.file_processing import process_all
from musicautobot.numpy_encode import *
from musicautobot.config import *
from musicautobot.music_t... | transformer code/train.py | 3,930 | Get outfile and check if it exists Part 1: Filter out midi tracks (drums, repetitive instruments, etc.) if duet_only and num_piano_tracks(input_path) not in [1, 2]: return None remove non note tracks and standardize instruments ignore badly formatted midi errors ignore badly formatted midi errors Part 2. Compre... | 906 | en | 0.80039 |
import logging
from typing import Dict, List, Tuple
import aiosqlite
from btcgreen.server.address_manager import (
BUCKET_SIZE,
NEW_BUCKET_COUNT,
NEW_BUCKETS_PER_ADDRESS,
AddressManager,
ExtendedPeerInfo,
)
log = logging.getLogger(__name__)
class AddressManagerStore:
"""
Metadata table:... | btcgreen/server/address_manager_store.py | 8,148 | Metadata table:
- private key
- new table count
- tried table count
Nodes table:
* Maps entries from new/tried table to unique node ids.
- node_id
- IP, port, together with the IP, port of the source peer.
New table:
* Stores node_id, bucket for each occurrence in the new table of an entry.
* Once we know the buckets, ... | 654 | en | 0.815059 |
# Generated by Django 3.0.5 on 2020-05-13 09:46
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('project_core', '0118_calls_need_to_be_part_of_a_funding_instrument'),
('grant_management', '0041_allows_media_to_not... | ProjectApplication/grant_management/migrations/0042_improves_project_data_publications_social_media_types.py | 3,387 | Generated by Django 3.0.5 on 2020-05-13 09:46 | 45 | en | 0.61429 |
import contextlib
import os.path
import subprocess
import pytest
from pre_commit import parse_shebang
from pre_commit.util import CalledProcessError
from pre_commit.util import cmd_output
from pre_commit.util import cmd_output_b
from testing.auto_namedtuple import auto_namedtuple
TESTING_DIR = os.path.abspath(os.pa... | testing/util.py | 3,408 | pragma: win32 no cover pragma: no cover Don't want to write to the home directory These are mutually exclusive allow skipping `-a` with `all_files=False` allow skipping `-m` with `msg=None` | 189 | en | 0.86301 |
"""Database exceptions."""
class BaseError(Exception):
"""The base exception."""
class NotFoundError(BaseError):
"""When an item was not found in the database."""
| database/open_alchemy/package_database/exceptions.py | 175 | The base exception.
When an item was not found in the database.
Database exceptions. | 84 | en | 0.906384 |
import sys
import os
import re
import importlib
import warnings
is_pypy = '__pypy__' in sys.builtin_module_names
warnings.filterwarnings('ignore',
r'.+ distutils\b.+ deprecated',
DeprecationWarning)
def warn_distutils_present():
if 'distutils' no... | DatabaseControlWrapper_JE/venv/Lib/site-packages/_distutils_hack/__init__.py | 3,816 | Ensure that the local copy of distutils is preferred over stdlib.
See https://github.com/pypa/setuptools/issues/417#issuecomment-392298401
for more motivation.
Allow selection of distutils by environment variable.
Detect if pip is being imported in a build script. Ref #2355.
Ensure stdlib distutils when running under ... | 584 | en | 0.737584 |
## Start of header boilerplate #################################################
from aocbase import readInput
import re
import collections
def lineParse(s, f, fp):
m = fp.match(s)
if m==None:
raise s
return tuple(map(f, m.groups()))
def fileParse(inp):
return list(inp.splitlines())
## End of... | Dyr-El-python/day20.py | 4,465 | Start of header boilerplate End of header boilerplate Start of footer boilerplate Update for input specifics End of footer boilerplate | 138 | en | 0.462101 |
import inspect
import warnings
from abc import ABCMeta, abstractmethod
from mmcv_custom.fileio.zipreader import ZipReader
class BaseStorageBackend(metaclass=ABCMeta):
"""Abstract class of storage backends.
All backends need to implement two apis: `get()` and `get_text()`.
`get()` reads the file as a byte ... | mmcv_custom/fileio/file_client.py | 7,801 | Abstract class of storage backends.
All backends need to implement two apis: `get()` and `get_text()`.
`get()` reads the file as a byte stream and `get_text()` reads the file
as texts.
Ceph storage backend.
Args:
path_mapping (dict|None): path mapping dict from local path to Petrel
path. When `path_mappin... | 2,160 | en | 0.726984 |
r"""
This app is used to invert the styleGAN series synthesis network. We find
the matching latent vector w for given images so that we can manipulate
images in the latent feature space.
Ref: https://github.com/rosinality/stylegan2-pytorch/blob/master/projector.py # noqa
"""
import argparse
import os
im... | apps/stylegan_projector.py | 9,274 | This app is used to invert the styleGAN series synthesis network. We find
the matching latent vector w for given images so that we can manipulate
images in the latent feature space.
Ref: https://github.com/rosinality/stylegan2-pytorch/blob/master/projector.py # noqa
yapf: disable isort:skip noqa isort:skip noqa i... | 650 | en | 0.682301 |
def main(x):
matrix = []
exit_path = []
for i in range(0, x):
j = list(input())
if 'e' in j:
y = j.index("e")
exit_path.append(i)
exit_path.append(y)
j[y] = "-"
matrix.append(j)
row, col = 0, 0
matrix[row][col] = "S"
path =... | Recursion/labyrinth.py | 1,475 | If destination is reached print explore move down move right move left move up if none of the above is explorable or invalid index backtrack | 140 | en | 0.637323 |
from scrapy.utils.project import get_project_settings
from sqlalchemy import Column
from sqlalchemy import Integer
from sqlalchemy import String
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
def db_connect():
"""
Performs database conne... | src/parliamentbg/parliamentbg/models.py | 1,255 | Sqlalchemy deals model
create tables
Performs database connection using database settings from settings.py.
Returns sqlalchemy engine instance | 142 | en | 0.59689 |
import usocket as socket
import ustruct as struct
from ubinascii import hexlify
class MQTTException(Exception):
pass
class MQTTClient:
def __init__(
self,
client_id,
server,
port=0,
user=None,
password=None,
keepalive=0,
ssl=False,
ssl_... | components/py_engine/micropython-lib/micropython/umqtt.simple/umqtt/simple.py | 6,479 | print(hex(len(msg)), hexlify(msg, ":")) print(hex(len(pkt)), hexlify(pkt, ":")) print(hex(len(pkt)), hexlify(pkt, ":")) print(resp) Wait for a single incoming MQTT message and process it. Subscribed messages are delivered to a callback previously set by .set_callback() method. Other (internal) MQTT messages processed i... | 486 | en | 0.785338 |
from bcipy.feedback.visual.visual_feedback import VisualFeedback
from psychopy import core
from bcipy.helpers.load import load_json_parameters
from bcipy.display.display_main import init_display_window
# Load a parameters file
parameters = load_json_parameters(
'bcipy/parameters/parameters.json', value_cast=True)... | bcipy/feedback/demo/demo_visual_feedback.py | 749 | Load a parameters file Start Visual Feedback | 44 | ml | 0.05392 |
class RevitLinkOperations(object,IDisposable):
"""
This class is used to extend the IExternalResourceServer interface with methods to support operations
specifically related to Revit links.
"""
def Dispose(self):
""" Dispose(self: RevitLinkOperations) """
pass
def ReleaseUnmanagedResources(self,*... | release/stubs.min/Autodesk/Revit/DB/__init___parts/RevitLinkOperations.py | 2,401 | This class is used to extend the IExternalResourceServer interface with methods to support operations
specifically related to Revit links.
Dispose(self: RevitLinkOperations)
ReleaseUnmanagedResources(self: RevitLinkOperations,disposing: bool)
SetGetLocalPathForOpenCallback(self: RevitLinkOperations,makeLocalCopyF... | 1,538 | en | 0.56408 |
##########################################################################
#
# Copyright (c) 2013, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistrib... | python/GafferSceneUI/SceneSwitchUI.py | 2,393 | Copyright (c) 2013, Image Engine Design Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions... | 1,584 | en | 0.889322 |
"""Generates the pins file for the SWM320"""
from __future__ import print_function
import re
import sys
import argparse
class Pin:
"""Holds the information associated with a pin."""
def __init__(self, name, port, pbit, preg, IRQn):
self.name = name
self.port = port
self.pbit = pbit
... | ports/swm320/boards/make-pins.py | 4,087 | Holds the information associated with a pin.
Generates the pins file for the SWM320
list of Pin | 97 | en | 0.866856 |
# pylint: disable=no-member, redefined-outer-name
"""
Annalist resource types module
"""
from __future__ import unicode_literals
from __future__ import absolute_import, division, print_function
__author__ = "Graham Klyne (GK@ACM.ORG)"
__copyright__ = "Copyright 2015, G. Klyne"
__license__ = "MIT (http://o... | src/annalist_root/annalist/resourcetypes.py | 4,340 | Returns preferred MIME content-type for resource type
>>> content_type(ANNAL.CURIE.Metadata) == "application/ld+json"
True
>>> content_type(ANNAL.CURIE.Richtext) == "text/markdown"
True
Returns content-type for given file extension as an instance of a given type URI,
or None.
>>> content_type_for_file_extension(ANNAL... | 1,927 | en | 0.519032 |
import logging
import os
from collections import defaultdict
from typing import Dict
from typing import List
from typing import Union
import requests
from cachecontrol import CacheControl
from cachecontrol.caches.file_cache import FileCache
from cachecontrol.controller import logger as cache_control_logger
from cach... | venv/Lib/site-packages/poetry/repositories/pypi_repository.py | 16,303 | Find packages on the remote server.
Return the package information given its name.
The information is returned from the cache if it exists
or retrieved from the remote server.
Return the release information given a package name and a version.
The information is returned from the cache if it exists
or retrieved from t... | 1,376 | en | 0.787626 |
#Hkr
import msvcrt
import os
import sys
import random
from ctypes import windll, byref, wintypes
from ctypes.wintypes import SMALL_RECT
STDOUT = -11
WIN_X = 100
WIN_Y = 60
hdl = windll.kernel32.GetStdHandle(STDOUT)
rect = wintypes.SMALL_RECT(0, 0, WIN_X, WIN_Y) # (left, top, right, bottom)
windll.kernel32.SetConsoleW... | New Tests.py | 1,897 | Hkr (left, top, right, bottom) 72 75 80 77 | 46 | en | 0.549136 |
from django.utils.cache import get_conditional_response
from django.utils.http import http_date, parse_http_date_safe, unquote_etag
class ConditionalGetMiddleware(object):
"""
Handles conditional GET operations. If the response has an ETag or
Last-Modified header, and the request has If-None-Match or
... | venv/lib/python2.7/site-packages/django/middleware/http.py | 1,141 | Handles conditional GET operations. If the response has an ETag or
Last-Modified header, and the request has If-None-Match or
If-Modified-Since, the response is replaced by an HttpNotModified.
Also sets the Date and Content-Length response-headers. | 249 | en | 0.915949 |
from setuptools import setup,find_packages
import os
import shutil
#remove the dist folder first if exists
if os.path.exists("dist"):
shutil.rmtree("dist")
def readme():
with open('README.rst') as f:
return(f.read())
VERSION = '1.0.53'
def write_version_py(filename='SigProfilerTopography/version.py'):
# Copied... | setup.py | 1,300 | remove the dist folder first if exists Copied from numpy setup.py | 65 | en | 0.539109 |
# 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... | aliyun-python-sdk-mts/aliyunsdkmts/request/v20140618/SubmitFpCompareJobRequest.py | 3,102 | 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... | 754 | en | 0.883564 |
# coding: utf-8
import pprint
import re
import six
from huaweicloudsdkcore.sdk_response import SdkResponse
class ShowWhitelistResponse(SdkResponse):
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dic... | huaweicloud-sdk-elb/huaweicloudsdkelb/v2/model/show_whitelist_response.py | 2,876 | Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
Returns true if both objects are equal
ShowWhitelistResponse - a model defined in huaw... | 765 | en | 0.672647 |
"""optik.option_parser
Provides the OptionParser and Values classes.
"""
__revision__ = "/home/scons/scons/branch.0/baseline/src/engine/SCons/Optik/option_parser.py 0.96.90.D001 2005/02/15 20:11:37 knight"
# Original Optik revision this is based on:
__Optik_revision__ = "option_parser.py,v 1.38.2.1 2002/07/23 01:51:... | scons-local-0.96.90/SCons/Optik/option_parser.py | 26,744 | Original Optik revision this is based on: Copyright (c) 2001 Gregory P. Ward. All rights reserved. See the README.txt distributed with Optik for licensing terms. created 2001/10/17, GPW (from optik.py) Create the various lists and dicts that constitute the "option list". See class docstring for details about each att... | 4,655 | en | 0.78633 |
from django.urls import path
# urlpatterns = [
# path("/register", )
# ] | django_forum_engine/account/urls.py | 77 | urlpatterns = [ path("/register", ) ] | 41 | en | 0.310642 |
from django.contrib import admin
from .models import UserProfile,ProfileFeedItem
# Register your models here.
admin.site.register(UserProfile)
admin.site.register(ProfileFeedItem)
| profiles_api/admin.py | 182 | Register your models here. | 26 | en | 0.957485 |
# Copyright (C) 2020 GreenWaves Technologies, SAS
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
# This progr... | tools/nntool/generation/at_generators/cnn_global_pool.py | 3,089 | Copyright (C) 2020 GreenWaves Technologies, SAS This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distribu... | 1,698 | en | 0.810533 |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2019 CERN.
#
# My site is free software; you can redistribute it and/or modify it under
# the terms of the MIT License; see LICENSE file for more details.
"""Invenio digital library framework."""
import os
from setuptools import find_packages, setup
readme = open('README.rs... | 08-data-models-from-scratch/solution/my-site/setup.py | 2,672 | Invenio digital library framework.
-*- coding: utf-8 -*- Copyright (C) 2019 CERN. My site is free software; you can redistribute it and/or modify it under the terms of the MIT License; see LICENSE file for more details. Get the version string. Cannot be done with import! | 273 | en | 0.764769 |
# This file is part of
# the galxy-chop project (https://github.com/vcristiani/galaxy-chop)
# Copyright (c) 2020, Valeria Cristiani
# License: MIT
# Full Text: https://github.com/vcristiani/galaxy-chop/blob/master/LICENSE.txt
"""Fixtures input data."""
# ===============================================================... | tests/conftest.py | 11,807 | Solid disc without velocities.
Solid disc with velocities.
Disc rotated over x axis.
Disc rotated over y axis.
Disc with no angle of inclination.
Disc rotated over z axis.
Distances calculator.
Calculate distances beetween particles.
Parameters
----------
x, y, z: `np.ndarray`, shape = (N_part, 1)
Positions
m : `... | 3,079 | en | 0.494867 |
import asyncio
from typing import (
Dict,
Iterable,
Optional,
Sequence,
Tuple,
cast,
)
from cancel_token import (
CancelToken,
)
from eth_utils import ValidationError, to_tuple
from eth.exceptions import (
BlockNotFound,
)
from eth2.beacon.helpers import (
compute_start_slot_of_e... | trinity/protocol/bcc_libp2p/node.py | 41,629 | noqa: E701 TODO: Add key and peer_id to the peerstore let the function initialize it no routing required here host TODO: Register notifees TODO: Connect bootstrap nodes? pubsub FIXME: Add `tear_down` to `Swarm` in the upstream TODO: Add `close` in `Pubsub` RPC Handlers TODO: Add a wrapper or decorator to handle the exc... | 2,134 | en | 0.848365 |
import re
whitespace_re = re.compile('\s+')
def pare(text, size, etc='...'):
'''Pare text to have maximum size and add etc to the end if it's
changed'''
size = int(size)
text = text.strip()
if len(text)>size:
# strip the last word or not
to_be_stripped = not whitespace_re.findall(... | iktomi/utils/text.py | 682 | Pare text to have maximum size and add etc to the end if it's
changed
strip the last word or not | 98 | en | 0.894552 |
from django.apps import AppConfig
class UsersConfig(AppConfig):
name = 'nomadgram.users'
verbose_name = "Users"
def ready(self):
"""Override this to put in:
Users system checks
Users signal registration
"""
from .signals import user_signed_up
| nomadgram/users/apps.py | 307 | Override this to put in:
Users system checks
Users signal registration | 70 | en | 0.708613 |
class BotError(Exception):
"""Base bot error."""
class BotAppError(Exception):
"""Bot App Error."""
class BotApiError(Exception):
"""Bot API Error."""
| gopubbot/bot/exceptions.py | 167 | Bot API Error.
Bot App Error.
Base bot error. | 45 | es | 0.32019 |
"""
Auto-generated class for JobResult
"""
from .EnumJobResultName import EnumJobResultName
from .EnumJobResultState import EnumJobResultState
from . import client_support
class JobResult(object):
"""
auto-generated. don't touch.
"""
@staticmethod
def create(data, id, level, name, startTime, sta... | pyclient/zeroos/orchestrator/client/JobResult.py | 5,199 | auto-generated. don't touch.
:type data: str
:type id: str
:type level: int
:type name: EnumJobResultName
:type startTime: int
:type state: EnumJobResultState
:type stderr: str
:type stdout: str
:rtype: JobResult
Auto-generated class for JobResult | 247 | en | 0.482067 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.