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 |
|---|---|---|---|---|---|---|
from django.db import models
from django.utils import timezone
from django.core.exceptions import ValidationError
# from django.contrib.auth.models import User
from users.models import Student, College
from django.urls import reverse
from django.core import validators
class AbstractPostModel(models.Model):
title ... | app/blog/models.py | 2,018 | from django.contrib.auth.models import User | 43 | en | 0.676588 |
"""
Wrapper to get ROVA calendar from Rova's API
Acces to this ROVA API has been simplified since version 0.2.1 of this wrapper
Just use https://www.rova.nl/api/waste-calendar/upcoming?postalcode=1000AA&houseNumber=1&addition=&take=5
with a existing combination of postalcode, housenumber, housenumber addition
Be aware... | rova/rova.py | 2,751 | ROVA class
To fetch the garbage calendar, you need to set a zip_code and house_number.
Get next pickup date for each garbage types
Check if ROVA collects garbage at this address
Wrapper to get ROVA calendar from Rova's API
Acces to this ROVA API has been simplified since version 0.2.1 of this wrapper
Just use https://w... | 815 | en | 0.814054 |
import numpy as np
import random
from collections import namedtuple, deque
from model import QNetwork
import torch
import torch.nn.functional as F
import torch.optim as optim
BUFFER_SIZE = int(1e5) # replay buffer size
BATCH_SIZE = 64 # minibatch size
GAMMA = 0.99 # discount factor
TAU = 1e-3 ... | dqn/exercise/dqn_agent.py | 6,836 | Interacts with and learns from the environment.
Fixed-size buffer to store experience tuples.
Initialize an Agent object.
Params
======
state_size (int): dimension of each state
action_size (int): dimension of each action
seed (int): random seed
Initialize a ReplayBuffer object.
Params
======
action_s... | 2,292 | en | 0.711204 |
from __future__ import print_function, division, absolute_import
import os
import unittest
from six import string_types
from .. import *
from ..compat import as_text, as_str, as_bytes
DEFAULT_VP_TEST_HOST = '127.0.0.1'
DEFAULT_VP_TEST_PORT = 5433
DEFAULT_VP_TEST_USER = 'dbadmin'
DEFAULT_VP_TEST_PASSWD = ''
DEFAULT_... | vertica_python/tests/base.py | 3,429 | Base class for tests that query Vertica.
Connects to vertica.
:return: a connection to vertica.
Creates a new connection, executes a query and fetches all the results.
:param query: query to execute
:return: all fetched results as returned by cursor.fetchall()
Creates a new connection, executes a query and fetches on... | 416 | en | 0.845625 |
from selenium_test.selenium_utils import *
from file_and_system.windows_os_utils import WindowsOsUtil
from python_common.global_param import GlobalParam
from http_request.request_utils import request_download_file_by_url
import cv2 as cv
import time
WindowsOsUtil.kill_process_by_name('MicrosoftWebDriver.exe')
# mail_l... | selenium_test/sele_test_mail_login.py | 5,974 | mail_lists=['mail.hoperun.com', 'mail.qq.com', 'mail.163.com] ------------------------security mail captcha not show---------------------- wait_for_element_exist(netcase_163_driver,'//div[@class="yidun_panel"]') element = find_element_by_class_name(netcase_163_driver, 'yidun_panel') netcase_163_driver.execute_script("a... | 1,476 | en | 0.370209 |
# -*- coding: utf-8 -*-
# @Time : 2020/10/3
# @Author : Changxin Tian
# @Email : cx.tian@outlook.com
r"""
KGNNLS
################################################
Reference:
Hongwei Wang et al. "Knowledge-aware Graph Neural Networks with Label Smoothness Regularization
for Recommender Systems." in KDD 2019.... | recbole/model/knowledge_aware_recommender/kgnnls.py | 21,110 | KGNN-LS is a knowledge-based recommendation model.
KGNN-LS transforms the knowledge graph into a user-specific weighted graph and then apply a graph neural network to
compute personalized item embeddings. To provide better inductive bias, KGNN-LS relies on label smoothness
assumption, which posits that adjacent items i... | 6,632 | en | 0.750823 |
"""
JSONField automatically serializes most Python terms to JSON data.
Creates a TEXT field with a default value of "{}". See test_json.py for
more information.
from django.db import models
from django_extensions.db.fields import json
class LOL(models.Model):
extra = json.JSONField()
"""
import datetime
fro... | vendor-local/src/django-extensions/build/lib/django_extensions/db/fields/json.py | 3,020 | Hack so repr() called by dumpdata will output JSON instead of
Python formatted data. This way fixtures will work!
JSONField is a generic textfield that neatly serializes/unserializes
JSON objects seamlessly. Main thingy must be a dict object.
As above
Convert our JSON object to a string before we save
Returns a suita... | 811 | en | 0.697464 |
import uuid
import arrow
from collections import namedtuple
HEADERS = ('start', 'stop', 'project', 'id', 'tags', 'updated_at')
class Frame(namedtuple('Frame', HEADERS)):
def __new__(cls, start, stop, project, id, tags=None, updated_at=None,):
try:
if not isinstance(start, arrow.Arrow):
... | watson/frames.py | 5,446 | If requested, return the part of the frame that is within the span, for frames that are *partially* within span or reaching over span | 133 | en | 0.931035 |
import torch
import numpy as np
from allennlp.nn import util
from relex.modules.offset_embedders import OffsetEmbedder
def position_encoding_init(n_position: int, embedding_dim: int):
position_enc = np.array([[pos / np.power(10000, 2 * (j // 2) / embedding_dim)
for j in range(embeddi... | relex/modules/offset_embedders/sine_offset_embedder.py | 2,323 | apply sin on 0th,2nd,4th...embedding_dim apply cos on 1st,3rd,5th...embedding_dim TODO: add zero vector for padding pylint: disable=arguments-differ input -> [B x seq_len x d], offset -> [B x 2] mask padding so it won't receive a positional embedding | 250 | en | 0.490677 |
"""
Quotes API For Digital Portals
The quotes API combines endpoints for retrieving security end-of-day, delayed, and realtime prices with performance key figures and basic reference data on the security and market level. The API supports over 20 different price types for each quote and comes with basic searc... | code/python/QuotesAPIforDigitalPortals/v3/fds/sdk/QuotesAPIforDigitalPortals/model/inline_response20013.py | 13,055 | NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
Attributes:
allowed_values (dict): The key is the tuple path to the attribute
and the for var_name this is (var_name,). The value is a dict
with a capitalized key describing the a... | 7,299 | en | 0.81673 |
import argparse
import os
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
from ignite.metrics import IoU, Precision, Recall
import torchsat.transforms.transforms_cd as T
from torchsat.datasets.f... | torchsat/scripts/train_cd.py | 6,995 | generate the train and val dataloader, you can change this for your specific task
Args:
traindir (str): train dataset dir
valdir (str): validation dataset dir
Returns:
tuple: the train dataset and validation dataset
print('val-epoch:{} [{}/{}], loss: {:5.3}'.format(epoch, idx + 1, len(dataloader), loss.... | 609 | en | 0.429662 |
# -*- coding: utf-8 -*-
"""Converts .pyfr[m, s] files to a Paraview VTK UnstructuredGrid File"""
from collections import defaultdict
import os
import numpy as np
from pyfr.shapes import BaseShape
from pyfr.util import subclass_where
from pyfr.writers import BaseWriter
class ParaviewWriter(BaseWriter):
# Suppo... | pyfr/writers/paraview.py | 14,232 | Converts .pyfr[m, s] files to a Paraview VTK UnstructuredGrid File
-*- coding: utf-8 -*- Supported file types and extensions Get the shape and sub division classes Number of vis points Number of sub cells and nodes If a mesh has been given the compute the sizes Running byte-offset for appended data Header Data Header... | 1,564 | en | 0.720048 |
#!/c/python27/python
import os
from utils import *
def cli_cpp(parms):
return os.path.join(parms['OVPN3'], "core", "test", "ovpncli", "cli.cpp")
def src_fn(parms, srcfile):
# Get source file name
if srcfile:
if '.' not in os.path.basename(srcfile):
srcfile += ".cpp"
else:
... | Carthage/Checkouts/openvpn-adapter/OpenVPN Adapter/Vendors/openvpn/win/build.py | 3,561 | !/c/python27/python Get source file name Debug? Dictionary we will use to substitute parameters onto VC command line. Do we need to support XP and Win 2003? pre-Vista Vista and later Add jsoncpp (optional) Build OpenVPN Connect build it some parameters might be redefined, like in Jenkins multibranch pipeline case | 314 | en | 0.659056 |
#!/usr/bin/env python
## @package teleop_joy A node for controlling the P3DX with an XBox controller
import rospy
from geometry_msgs.msg import Twist
from nav_msgs.msg import Odometry
from sensor_msgs.msg import Joy
import numpy as np
def quat2yaw(q):
return np.arctan2(2*(q.y*q.z + q.w*q.x), 1 - 2*(q.z**2 + q.w... | nodes/teleop_joy.py | 1,280 | !/usr/bin/env python @package teleop_joy A node for controlling the P3DX with an XBox controller | 96 | en | 0.471691 |
import os
import fs
from .utils import Docs, custom_dedent
class TestTutorial(Docs):
def test_level_1(self):
expected = "world"
folder = "level-1-jinja2-cli"
self._moban(folder, expected)
def test_level_1_custom_define(self):
expected = "maailman"
folder = "level-1-j... | tests/test_docs.py | 11,782 | make sure only copy target is executed | 38 | en | 0.97389 |
# Copyright (c) 2017-present, Facebook, Inc.
# 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. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
from parlai.core.agents im... | parlai/agents/seq2seq/seq2seq.py | 22,182 | Copyright (c) 2017-present, Facebook, Inc. 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. An additional grant of patent rights can be found in the PATENTS file in the same directory. agent.add_argument('-att', '--attenti... | 3,973 | en | 0.748747 |
# 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/distribute/cross_device_utils.py | 24,867 | Class that manages collective keys.
We need to manage three different keys for collective:
*Group key*: an integer key to identify the set of cooperative devices.
Collective ops work under the same set of devices must using the same group
key.
*Instance key*: an integer key to identify the set of same counterpart of... | 9,899 | en | 0.836441 |
from time import sleep
from ec2mc import __main__
def test_user_commands():
"""test all user commands."""
assert __main__.main([
"user", "create", "ec2mc_test_user", "setup_users", "--default"
]) is not False
sleep(5)
assert __main__.main([
"user", "list"
]) is not False
as... | tests/test_user_commands.py | 695 | test all user commands. | 23 | en | 0.946798 |
import numpy as np
import tensorlayerx as tlx
import gammagl.mpops as mpops
from .num_nodes import maybe_num_nodes
from .check import check_is_numpy
def coalesce(edge_index, edge_attr=None, num_nodes=None, reduce="add", is_sorted=False, sort_by_row=True):
"""Row-wise sorts :obj:`edge_index` and removes its duplic... | gammagl/utils/coalesce.py | 3,032 | Row-wise sorts :obj:`edge_index` and removes its duplicated entries.
Duplicate entries in :obj:`edge_attr` are merged by scattering them
together according to the given :obj:`reduce` option.
Args:
edge_index (LongTensor): The edge indices.
edge_attr (Tensor or List[Tensor], optional): Edge weights or multi-
... | 1,252 | en | 0.610232 |
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... | nova/tests/unit/conductor/tasks/test_live_migrate.py | 18,931 | Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under th... | 546 | en | 0.872906 |
"""
Script to show the wireframe of a given mesh (read from a file) in an interactive
Viewer.
"""
from viewer import *
from mesh.obj import OBJFile
import sys
if __name__ == "__main__":
app = Viewer()
if len(sys.argv) > 1:
try:
obj = OBJFile.read(sys.argv[1])
app.scene.addObje... | wireframe.py | 599 | Script to show the wireframe of a given mesh (read from a file) in an interactive
Viewer. | 89 | en | 0.762258 |
# The MIT License (MIT)
# Copyright (c) 2015 Yanzheng Li
# 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,... | python/tests/assert.py | 2,585 | The MIT License (MIT) Copyright (c) 2015 Yanzheng Li 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, publis... | 1,541 | en | 0.678162 |
import logging
import pandas as pd
from flask import Flask, request
from gevent.pywsgi import WSGIServer
from time import sleep
from func import rms, meas_to_influx, rms_to_influx, config
logger = logging.getLogger(config['log_name'])
logger.setLevel(logging.INFO)
h_stream = logging.StreamHandler()
h_stream.setLevel(... | server/server.py | 1,075 | print(s_data) print(power) app.run(host=config['url'], port=config['port']) | 75 | en | 0.182798 |
# coding: utf-8
"""
Provides the exporter tool. The exporter can be used to export ComodIT entities
to local directories.
"""
from __future__ import print_function
from builtins import object
import os
from comodit_client.api.collection import EntityNotFoundException
from comodit_client.api.exceptions import PythonAp... | comodit_client/api/exporter.py | 8,051 | The exporter is a tool that enables to export entities to local
directories. Exported entities may later be (re-)imported (see L{Import}).
Exception raised by exporter in case of error.
Creates an exporter instance. If force flag is set, all data already
present in a destination folder are overwritten on export.
@para... | 2,511 | en | 0.677437 |
from __future__ import absolute_import, division, print_function
import argparse
import sys
import os
import py
import pytest
from _pytest.config import argparsing as parseopt
@pytest.fixture
def parser():
return parseopt.Parser()
class TestParser(object):
def test_no_help_by_default(self, capsys):
... | tools/third_party/pytest/testing/test_parseopt.py | 13,227 | Help text for options with a metavar tuple should display help
in the form "--preferences=value1 value2 value3" (#2004).
need a short or long option throws error on --deux only! testing would be more helpful with all help generated redirect output from argcomplete to stdin and stderr is not trivial http://stackoverfl... | 582 | en | 0.737485 |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
# pylint: ... | sdk/storage/azure-storage-file-datalake/azure/storage/filedatalake/_models.py | 35,842 | AccessControlChangeCounters contains counts of operations that change Access Control Lists recursively.
:ivar int directories_successful:
Number of directories where Access Control List has been updated successfully.
:ivar int files_successful:
Number of files where Access Control List has been updated success... | 20,122 | en | 0.811518 |
# Copyright 2019 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_model_optimization/__init__.py | 4,116 | Attempt to import tensorflow, and ensure its version is sufficient.
Raises:
ImportError: if either tensorflow is not importable or its version is
inadequate.
Init module for TensorFlow Model Optimization Python API.
```
import tensorflow_model_optimization as tfmot
```
Copyright 2019 The TensorFlow Authors. All... | 2,283 | en | 0.781845 |
"""
Constructor functions intended to be shared by pd.array, Series.__init__,
and Index.__new__.
These should not depend on core.internals.
"""
from __future__ import annotations
from collections import abc
from typing import TYPE_CHECKING, Any, Optional, Sequence, Union, cast
import numpy as np
import numpy.ma as m... | pandas/core/construction.py | 21,927 | Convert input to numpy ndarray and optionally cast to a given dtype.
Parameters
----------
arr : ndarray, scalar, list, tuple, iterator (catchall)
Excludes: ExtensionArray, Series, Index.
dtype : np.dtype, ExtensionDtype or None
copy : bool
If False, don't copy the data if not needed.
raise_cast_failure : bool... | 10,703 | en | 0.601845 |
"""
DuckDuckGo (Images)
@website https://duckduckgo.com/
@provide-api yes (https://duckduckgo.com/api),
but images are not supported
@using-api no
@results JSON (site requires js to get images)
@stable no (JSON can change)
@parse url, title, img_src
@todo avoid extra... | master/searx-master/searx/engines/duckduckgo_images.py | 2,464 | DuckDuckGo (Images)
@website https://duckduckgo.com/
@provide-api yes (https://duckduckgo.com/api),
but images are not supported
@using-api no
@results JSON (site requires js to get images)
@stable no (JSON can change)
@parse url, title, img_src
@todo avoid extra request
en... | 641 | en | 0.619775 |
# -*- coding: utf-8 -*-
# Copyright (c) 2020, Havenir and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
# import frappe
from frappe.model.document import Document
class PortOfLoading(Document):
pass
| shipments/shipments/doctype/port_of_loading/port_of_loading.py | 259 | -*- coding: utf-8 -*- Copyright (c) 2020, Havenir and contributors For license information, please see license.txt import frappe | 128 | en | 0.68789 |
import os
import sys
import argparse
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.optim import Adam
from torch.utils.data import Dataset
import torchvision.transforms as transforms
import pickle
de... | CNN/code/filter_visualiton.py | 2,173 | x: 需要训练的图片 cnnid, filterid: 指定第几层cnn中第几个filter 当forward了第cnnid层cnn后, 要先呼叫hook, 才可以继续forward下一层cnn Filter activation: 我们先观察x经过被指定filter的activation map 正式执行forward的步骤 根据function argument 指定的filterid把待定filter的activation map取出来 利用偏微分和optimizer, 逐步修改input image来让filter activation越来越大 探究image的微量变化会怎样影响activation的程度,加负号代表做max... | 500 | zh | 0.741019 |
from functools import wraps
import sys
import traceback
from ploomber.io import TerminalWriter
from ploomber.exceptions import DAGBuildError, DAGRenderError
# TODO: there are two types of cli commands: the ones that execute user's
# code (ploomber build/task) and the ones that parse a dag/task but do not
# execute it.... | src/ploomber/cli/io.py | 2,474 | Decorator for command line endpoints that execute dags or tasks. It runs
the decorated function, captures exception (if any), sends a colored
traceback to standard error and exits with code 1.
Notes
-----
Functions decorated with this must be called with keyword arguments
Call some_endpoint(catch_exception=False) to ... | 1,207 | en | 0.892736 |
import json
import os
import shutil
import tempfile
def copytree(src, dst, symlinks=False, ignore=None):
for item in os.listdir(src):
s = os.path.join(src, item)
d = os.path.join(dst, item)
if os.path.isdir(s):
shutil.copytree(s, d, symlinks, ignore)
else:
s... | deploy_gh_pages.py | 4,573 | Go to deploy branch, copy new files and commit Copy the _themes to be able to share them between old versions | 109 | en | 0.955091 |
# -*- coding: utf-8 -*-
"""爬虫配置文件"""
import os
# MYSQL
MYSQL_IP = "localhost"
MYSQL_PORT = 3306
MYSQL_DB = "feapder"
MYSQL_USER_NAME = "feapder"
MYSQL_USER_PASS = "feapder123"
# REDIS
# IP:PORT
REDISDB_IP_PORTS = "localhost:6379"
REDISDB_USER_PASS = ""
REDISDB_DB = 0
# # 爬虫相关
# # COLLECTOR
COLLECTOR_SLEEP_TIME = 1 ... | tests/spider/setting.py | 2,239 | 爬虫配置文件
-*- coding: utf-8 -*- MYSQL REDIS IP:PORT 爬虫相关 COLLECTOR 从任务队列中获取任务到内存队列的间隔 每次获取任务数量 SPIDER 爬虫并发数 SPIDER_SLEEP_TIME = 0 下载时间间隔(解析完一个response后休眠时间) SPIDER_MAX_RETRY_TIMES = 100 每个请求最大重试次数 重新尝试失败的requests 当requests重试次数超过允许的最大重试次数算失败 RETRY_FAILED_REQUESTS = False request 超时时间,超过这个时间重新做(不是网络请求的超时时间)单位秒 REQU... | 1,225 | zh | 0.580997 |
"""
Small script to generate gdal_warp commands
for projecting rasters to the Behrmann projection
to be able to run the generated bat file you should have gdalwarp in your path or run it from an OSGeo4W Shell
"""
import os
root = r"D:\a\data\BioOracle_scenarios_30s_min250"
output = root + r"_equal_area" #os.path.absp... | rasters/project_to_behrmann.py | 1,433 | Small script to generate gdal_warp commands
for projecting rasters to the Behrmann projection
to be able to run the generated bat file you should have gdalwarp in your path or run it from an OSGeo4W Shell
os.path.abspath(os.path.join(root, r'..\ascii_equalarea')) output of ascii files from gdalwarp is not supported co... | 363 | en | 0.835444 |
import sqlite3
from checktheplug.models.Server import Server
"""
Operations to manage accessing the server database.
"""
class ServerDao:
"""
Sets up the object with the sql connection.
"""
def __init__(self, settings):
self.conn = sqlite3.connect(settings.database)
"""
... | checktheplug/data/ServerDao.py | 2,998 | Sets up the object with the sql connection. | 43 | en | 0.859927 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 5/15/20 4:49 PM
# @File : grover.py
# qubit number=4
# total number=25
import cirq
import cirq.google as cg
from typing import Optional
import sys
from math import log2
import numpy as np
#thatsNoCode
def make_circuit(n: int, input_qubit):
c = cirq.Ci... | data/cirq_new/cirq_program/startCirq_Class840.py | 2,341 | !/usr/bin/env python -*- coding: utf-8 -*- @Time : 5/15/20 4:49 PM @File : grover.py qubit number=4 total number=25thatsNoCode circuit begin number=1 number=2 number=7 number=3 number=4 number=18 number=19 number=20 number=22 number=23 number=24 number=10 number=11 number=12 number=8 number=13 number=14 number=15... | 352 | en | 0.243248 |
from seleniumbase import BaseCase
from werkzeug.security import generate_password_hash
from qa327_test.conftest import base_url
from qa327.models import User, Ticket
# Mock a sample user
TEST_USER = User(
email='test_frontend@test.com',
name='test_frontend',
password=generate_password_hash('test_frontend')... | qa327_test/frontend/geek_base.py | 1,320 | Selenium base case with some
GeekSeek utilities
asserts that message exists in flashes
login our test user
Mock a sample user Mock a sample ticket | 148 | en | 0.776928 |
from __future__ import division
import numpy as np
from numpy.random import rand
import pandas as pd
# --- List of available filters
FILTERS=[
{'name':'Moving average','param':100,'paramName':'Window Size','paramRange':[0,100000],'increment':1},
{'name':'Low pass 1st order','param':1.0,'paramName':'Cutoff Fre... | pydatview/tools/signal.py | 10,758 | Create a correlated random signal of length `n` based on the correlation coefficient `coeff`
value[t] = coeff * value[t-1] + (1-coeff) * random
Compute auto correlation of a signal
1st order high pass filter
1st order low pass filter
perform moving average, return a vector of same length as input
NOTE: also in ... | 2,610 | en | 0.621851 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-04-15 06:13
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import jsonfield.fields
class Migration(migrations.Migration):
in... | oxlos/migrations/0001_initial.py | 2,852 | -*- coding: utf-8 -*- Generated by Django 1.11 on 2017-04-15 06:13 | 66 | en | 0.712374 |
from setuptools import find_packages, setup
setup(
name="hacker_news",
version="dev",
author="Elementl",
author_email="hello@elementl.com",
classifiers=[
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8"... | examples/hacker_news/setup.py | 1,113 | DataFrames were not written to Snowflake, causing errors | 56 | en | 0.984565 |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community
Edition) available.
Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in co... | bcs-ui/backend/tests/components/test_cm.py | 1,234 | Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community
Edition) available.
Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
Y... | 727 | en | 0.86374 |
import os
import sys
import json
import datetime
import numpy as np
import skimage.draw
from bs4 import BeautifulSoup as bs
import cv2
import imgaug
from utils import *
# Root directory of the project
ROOT_DIR = os.path.abspath("../../")
# Inference result directory
RESULTS_DIR = os.path.abspath("./inference/")
# Impo... | tools/convet_voc2coco/voc2coco.py | 14,589 | Build a RGB color to label mapping for segmentation.
Run detection on images in the given directory.
Mapping SegmentationClass image's color to indice of ground truth
image_id: id of mask
Return:
class_label: [height, width] matrix contains values form 0 to 20
Mapping annotation images to real Masks(MRCNN needed)
imag... | 4,537 | en | 0.600697 |
from tint.ssl.context import PFSContextFactory
from tint.log import Logger
from tint.protocols.tintp import ConnectionPool
from tint.protocols.tintp import TintProtocolFactory
from tint.friends import FriendsList
class Peer(object):
def __init__(self, keyStore, storage, resolver):
self.keyStore = keyStor... | tint/peer.py | 3,354 | Get a value from a host.
@param hostKeyId: The key id for the destination host to get the
given key. This could be the local host, in which case the hostKey
will be the same as this C{Peer}'s keyStore keyId.
@param storagePath: The path to the key to get. For instance, this
could be something like /chat/<somekey>/i... | 1,104 | en | 0.830432 |
"""Count Encoder"""
import numpy as np
import pandas as pd
import category_encoders.utils as util
from copy import copy
from sklearn.base import BaseEstimator, TransformerMixin
__author__ = 'joshua t. dunn'
class CountEncoder(BaseEstimator, TransformerMixin):
def __init__(self, verbose=0, cols=None, drop_invar... | category_encoders/count.py | 12,938 | Count encoding for categorical features.
For a given categorical feature, replace the names of the groups
with the group counts.
Parameters
----------
verbose: int
integer indicating verbosity of output. 0 for none.
cols: list
a list of columns to encode, if None, all string and categorical columns
will ... | 4,010 | en | 0.655054 |
#The term schedule that gets displayed. Can do multiple terms in the case of displaying
#summer and fall at the same time. ie termNames ['2201','2208']
termNames=['2218']
majorTemplate='in/majorPage.html.mako'
#Add new majors here.
#Name: short name for the major
#classFile: the csv file containing all the classes in... | config.py | 5,881 | The term schedule that gets displayed. Can do multiple terms in the case of displayingsummer and fall at the same time. ie termNames ['2201','2208']Add new majors here.Name: short name for the majorclassFile: the csv file containing all the classes in this majors curriculumasof: the date that the major curriculum was a... | 1,492 | en | 0.910143 |
# ---------------------------------------------------------------------
# Syslog server
# ---------------------------------------------------------------------
# Copyright (C) 2007-2020 The NOC Project
# See LICENSE for details
# ---------------------------------------------------------------------
# Python modules
im... | services/syslogcollector/syslogserver.py | 1,654 | --------------------------------------------------------------------- Syslog server --------------------------------------------------------------------- Copyright (C) 2007-2020 The NOC Project See LICENSE for details --------------------------------------------------------------------- Python modules NOC modules Inval... | 391 | en | 0.220579 |
import logging
import unittest
import numpy as np
import pandas as pd
import scipy.stats as stats
import diffxpy.api as de
class _TestPairwiseNull:
noise_model: str
def _prepate_data(
self,
n_cells: int,
n_genes: int,
n_groups: int
):
if self.nois... | diffxpy/unit_test/test_pairwise.py | 5,798 | Test if de.wald() generates a uniform p-value distribution
if it is given data simulated based on the null model. Returns the p-value
of the two-side Kolmgorov-Smirnov test for equality of the observed
p-value distriubution and a uniform distribution.
:param n_cells: Number of cells to simulate (number of observation... | 473 | en | 0.727981 |
"""pythonic_orcfighter
This is one of the different GameUnits that are used in the desing patterns examples.
:copyright: 2020, Jean Tardelli
:license: The MIT license (MIT). See LICENSE file for further details.
"""
from pythonic_abstractgameunit import AbstractGameUnit
class OrcFighter(AbstractGameUnit):
"""Cr... | wargame/designpatterns/pythonic_orcfighter.py | 485 | Create a OrcFighter instance
Print info about this unit, overrides superclass method.
pythonic_orcfighter
This is one of the different GameUnits that are used in the desing patterns examples.
:copyright: 2020, Jean Tardelli
:license: The MIT license (MIT). See LICENSE file for further details. | 297 | en | 0.678708 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('documents', '0004_uuidfield'),
('meetings', '0009_auto_20170106_1414'),
]
operations = [
... | ecs/meetings/migrations/0010_meeting_documents_zip.py | 583 | -*- coding: utf-8 -*- | 21 | en | 0.767281 |
import collections
import functools
import itertools
import operator
from contextlib import suppress
from typing import Any, Dict, List
import numpy as np
import toolz
from cached_property import cached_property
import ibis.common.exceptions as com
import ibis.expr.datatypes as dt
import ibis.expr.rules as rlz
import... | ibis/expr/operations.py | 92,852 | Absolute value
Returns the arc cosine of x
metrics : per-group scalar aggregates
by : group expressions
having : post-aggregation predicate
TODO: not putting this in the aggregate operation yet
where : pre-aggregation predicate
Node for analytics UDF.
Returns the arc sine of x
Returns the arc tangent of x
Returns the ... | 16,739 | en | 0.735784 |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from .. import _utilities, _tables
from ... | sdk/python/pulumi_azure_nextgen/devtestlab/schedule.py | 10,550 | A schedule.
API Version: 2018-09-15.
:param str resource_name: The name of the resource.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[pulumi.InputType['DayDetailsArgs']] daily_recurrence: If the schedule will occur once each day of the week, specify the daily recurrence.
:param pul... | 2,703 | en | 0.577085 |
# Qiwi module advanced usage example v1.00
# 17/05/2021
# https://t.me/ssleg © 2021
import logging
import qiwi_module
# настройка логфлайла test,log, туда будут записываться все ошибки и предупреждения.
lfile = logging.FileHandler('test.log', 'a', 'utf-8')
lfile.setFormatter(logging.Formatter('%(levelname)s %(modul... | adv_sample.py | 3,101 | Qiwi module advanced usage example v1.00 17/05/2021 https://t.me/ssleg © 2021 настройка логфлайла test,log, туда будут записываться все ошибки и предупреждения. noinspection PyArgumentList простой вариант использования смотрите в файле sample.py если у вас настроен свой внешний вид формы платежа, необходимо передать к... | 1,406 | ru | 0.989675 |
# -*- coding: utf-8 -*-
# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
from ccxt.base.exchange import Exchange
# -----------------------------------------------------------------------------
try:
basestri... | python/ccxt/okex.py | 164,036 | -*- coding: utf-8 -*- PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN: https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.mdhow-to-contribute-code ----------------------------------------------------------------------------- Python 3 Python 2 up to 3000 requests per 5 minutes ≈ 600 requests per... | 64,210 | en | 0.615587 |
from pipeline import *
class SentenceLimiter:
"""
Limit the text, word boundaries and
sentence boundaries of a given document
to the number of sentences given
"""
def run(self, document, number_sentences):
"""
:param: number_sentences, starts with 0 for the fist sentence
... | pipeline/filter.py | 2,736 | Remove all documents that are of a certain type
Remove a document's content if the main entity is not aligned
Limit the text, word boundaries and
sentence boundaries of a given document
to the number of sentences given
:param: input TripleReaderTriples object
:param: a list of entity that should be filtered
:param: nu... | 390 | en | 0.765705 |
# Copyright 2021 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | networking_bgp_ovn/drivers/openstack/utils/frr.py | 4,519 | Copyright 2021 Red Hat, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distribut... | 548 | en | 0.858906 |
# -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
#... | dags/jenkins_dag.py | 3,188 | Grab an artifact from the previous job
The python-jenkins library doesn't expose a method for that
But it's totally possible to build manually the request for that
-*- coding: utf-8 -*- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed ... | 1,544 | en | 0.877352 |
# coding: utf-8
"""
FlashBlade REST API
A lightweight client for FlashBlade REST API 2.3, developed by Pure Storage, Inc. (http://www.purestorage.com/).
OpenAPI spec version: 2.3
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import... | pypureclient/flashblade/FB_2_3/api/link_aggregation_groups_api.py | 18,575 | DELETE link-aggregation-groups
Remove a link aggregation group to unbind the ports.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.api23_link_aggregation_groups_delete_with_http_info(async_req=True)
>>> result = thread.get()
:... | 7,371 | en | 0.715546 |
# model settings
model = dict(
type='CenterNet',
pretrained='./pretrain/darknet53.pth',
backbone=dict(
type='DarknetV3',
layers=[1, 2, 8, 8, 4],
inplanes=[3, 32, 64, 128, 256, 512],
planes=[32, 64, 128, 256, 512, 1024],
norm_cfg=dict(type='BN'),
out_indices=(1... | configs/eftnet/R2_ttf53_whh_3lr_1x.py | 2,930 | model settings training and testing settings dataset settings optimizer learning policy yapf:disable yapf:enable runtime settings | 129 | en | 0.778863 |
## @package onnx
#Module caffe2.python.onnx.onnxifi
"""
ONNXIFI a Caffe2 net
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.proto import caffe2_pb2
from caffe2.python import core, workspace
import ca... | detectron/lib/python3.6/site-packages/caffe2/python/onnx/onnxifi.py | 1,464 | Transform the caffe2_net by collapsing ONNXIFI-runnable nodes into Onnxifi c2 ops
ONNXIFI a Caffe2 net
@package onnxModule caffe2.python.onnx.onnxifi | 151 | en | 0.285494 |
#!/usr/bin/env python
"""TcEx Framework Validate Module."""
# standard library
import ast
import importlib
import json
import os
import sys
import traceback
from collections import deque
from pathlib import Path
from typing import Dict, Union
# third-party
import colorama as c
# from jsonschema import SchemaError, Va... | tcex/bin/validate.py | 21,749 | Validate syntax, imports, and schemas.
* Python and JSON file syntax
* Python import modules
* install.json schema
* layout.json schema
Initialize Class properties.
.
Print errors results.
Print feed results.
Print file syntax results.
Print import results.
Print layout results.
Print schema results.
Return structure ... | 3,223 | en | 0.57364 |
# -*- coding: utf-8 -*-
#Chucky_Bot
import LINETCR
from LINETCR.lib.curve.ttypes import *
from datetime import datetime
from bs4 import BeautifulSoup
from threading import Thread
from googletrans import Translator
from gtts import gTTS
import time,random,sys,json,codecs,threading,glob,urllib,urllib2,urllib3,re,ast,os,... | Chuckysb.py | 148,684 | -*- coding: utf-8 -*-Chucky_Botnadya.login(qr=True)/XXX, >XXX, ;XXX, ^XXX, %XXX, $XXX... Name = summon(op.param2) | 140 | en | 0.114094 |
# -*- coding: utf-8 -*-
# Copyright (c) 2019, TUSHAR TAJNE and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
from frappe import _
class District(Document):
def validate(self):
name = str(self.district.c... | sps/sps/doctype/district/district.py | 361 | -*- coding: utf-8 -*- Copyright (c) 2019, TUSHAR TAJNE and contributors For license information, please see license.txt | 119 | en | 0.767719 |
from django.db import models
from django.contrib.auth import get_user_model
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
from tinymce import HTMLField
# Create your models here.
User = get_user_model()
class PostView(models.Model):
user = models.ForeignKey... | src/posts/models.py | 3,080 | Create your models here. comment_count = models.IntegerField(_("Comment count"), default=0) view_count = models.IntegerField(_("View count"), default=0) | 152 | en | 0.468293 |
import unittest
import os
import numpy as np
from dotenv import load_dotenv
from nlpaug.util import AudioLoader
import nlpaug.augmenter.spectrogram as nas
class TestLoudnessSpec(unittest.TestCase):
@classmethod
def setUpClass(cls):
env_config_path = os.path.abspath(
os.path.join(os.path.d... | test/augmenter/spectrogram/test_loudness_spec.py | 1,569 | https://freewavesamples.com/yamaha-v50-rock-beat-120-bpm | 56 | en | 0.436808 |
"""
Create the numpy.core.multiarray namespace for backward compatibility. In v1.16
the multiarray and umath c-extension modules were merged into a single
_multiarray_umath extension module. So we replicate the old namespace
by importing from the extension module.
"""
import functools
import warnings
from . import o... | venv/lib/python3.7/site-packages/numpy/core/multiarray.py | 50,606 | bincount(x, weights=None, minlength=0)
Count number of occurrences of each value in array of non-negative ints.
The number of bins (of size 1) is one larger than the largest value in
`x`. If `minlength` is specified, there will be at least this number
of bins in the output array (though it will be longer if necessary... | 39,670 | en | 0.65637 |
# Copyright (c) 2021 PaddlePaddle 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 appli... | apps/Graph4KG/utils.py | 9,832 | Calculate metrics according to scores.
decorate func
Evaluate given KGE model.
Orthogonalize embeddings.
Print log to logger.
Write logs to console and log file.
Set seed for reproduction.
Time counter wrapper.
Memory efficient uniform implementation.
wrapper func
... | 912 | en | 0.817816 |
# Copyright 2018 Contributors to Hyperledger Sawtooth
#
# 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 ... | tests/rbac/common/addresser/user_test.py | 6,839 | Test User Addresser
Tests address makes an address that identifies as the correct AddressSpace
Tests address makes an address that identifies as the correct AddressSpace
Tests address makes a unique address given different inputs
Test addresser.parse returns a parsed address
Test that addresses_are returns True if all ... | 1,521 | en | 0.824402 |
# List the type colors for the editor
AIR = (0, 0, 0)
GRASS = (100, 200, 40)
ROCK = (106, 106, 106)
LAVA = (252, 144, 3)
WATER = (0, 0, 255)
PLAYER = (155, 191, 250)
PLAYER_END = (40, 30, 100)
SPIKE_UP = (204, 24, 24)
SPIKE_DOWN = (166, 8, 8)
# List all the used types
types = ['GRASS', 'ROCK', 'LAVA', 'WATER', 'PLAYER... | tools/LevelCreator/ezTypes.py | 514 | List the type colors for the editor List all the used types Set default type | 76 | en | 0.49178 |
"""
Matrix operations for neuroswarms models.
Author: Joseph Monaco (jmonaco@jhu.edu)
Affiliation: Johns Hopkins University
Created: 2019-05-12
Updated: 2020-11-16
Related paper:
Monaco, J.D., Hwang, G.M., Schultz, K.M. et al. Cognitive swarming in complex
environments with attractor dynamics and oscillatory... | neuroswarms/matrix.py | 6,867 | Compute distances between points in entrywise order.
Compute distances between pairs of points.
Compute synchronizing phase differences between phase pairs.
Compute attracting component deltas between pairs of points.
Pairwise comparison index of tile index (column) vectors.
Compute attracting unit-vector differences b... | 2,681 | en | 0.800056 |
# Copyright 2018-2021 Xanadu Quantum Technologies Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or... | pennylane/ops/qubit/arithmetic_ops.py | 6,771 | QubitCarry(wires)
Apply the ``QubitCarry`` operation to four input wires.
This operation performs the transformation:
.. math::
|a\rangle |b\rangle |c\rangle |d\rangle \rightarrow |a\rangle |b\rangle |b\oplus c\rangle |bc \oplus d\oplus (b\oplus c)a\rangle
.. figure:: ../../_static/ops/QubitCarry.svg
:align:... | 3,949 | en | 0.574216 |
# 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/recoveryservices/azure-mgmt-recoveryservicessiterecovery/azure/mgmt/recoveryservicessiterecovery/aio/_configuration.py | 3,868 | Configuration for SiteRecoveryManagementClient.
Note that all parameters used to create this instance are saved as instance
attributes.
:param credential: Credential needed for the client to connect to Azure.
:type credential: ~azure.core.credentials_async.AsyncTokenCredential
:param subscription_id: The subscription... | 1,078 | en | 0.673979 |
from talon import Module, Context
import appscript
mod = Module()
ctx = Context()
ctx.matches = r"""
os: mac
"""
@mod.action_class
class Actions:
def run_shortcut(name: str):
"""Runs a shortcut on macOS"""
pass
@ctx.action_class("user")
class UserActions:
def run_shortcut(name: str... | code/platforms/mac/user.py | 401 | Runs a shortcut on macOS | 24 | en | 0.521713 |
# Definition for binary tree with next pointer.
# class TreeLinkNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# self.next = None
class Solution:
# @param root, a tree link node
# @return nothing
def connect(self, root):
... | LeetcodeAlgorithms/116. Populating Next Right Pointers in Each Node/populating-next-right-pointers-in-each-node.py | 538 | Definition for binary tree with next pointer. class TreeLinkNode: def __init__(self, x): self.val = x self.left = None self.right = None self.next = None @param root, a tree link node @return nothing | 235 | en | 0.587817 |
import datetime
from platform import python_version
from six import integer_types, string_types, text_type
class _NO_VALUE(object):
pass
# we don't use NOTHING because it might be returned from various APIs
NO_VALUE = _NO_VALUE()
_SUPPORTED_TYPES = (float, bool, str, datetime.datetime, type(None)) + \
stri... | tests/diff.py | 2,230 | we don't use NOTHING because it might be returned from various APIs pragma: no cover pragma: no cover | 101 | en | 0.910391 |
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import QColorDialog, QDialogButtonBox
BB = QDialogButtonBox
class ColorDialog(QColorDialog):
def __init__(self, parent=None):
super(ColorDialog, self).__init__(parent)
self.setOption(QColorDialog.ShowAlphaChannel)
... | view/libs/colorDialog.py | 1,195 | The Mac native dialog does not support our restore button. Add a restore defaults button. The default is set at invocation time, so that it works across dialogs for different elements. | 184 | en | 0.83133 |
# Copyright (C) 2019 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Provides an HTML cleaner function with sqalchemy compatible API"""
import re
import HTMLParser
import bleach
# Set up custom tags/attributes for bleach
BLEACH_TAGS = [
'caption', 'strong', 'em', '... | src/ggrc/utils/html_cleaner.py | 2,370 | Cleans out unsafe HTML tags.
Uses bleach and unescape until it reaches a fix point.
Args:
dummy: unused, sqalchemy will pass in the model class
value: html (string) to be cleaned
Returns:
Html (string) without unsafe tags.
Provides an HTML cleaner function with sqalchemy compatible API
Copyright (C) 2019 Goog... | 745 | en | 0.667298 |
'''
This script includes:
1. ClassifierOfflineTrain
This is for offline training. The input data are the processed features.
2. class ClassifierOnlineTest(object)
This is for online testing. The input data are the raw skeletons.
It uses FeatureGenerator to extract features,
and then use ClassifierOffli... | utils/lib_classifier.py | 7,960 | The classifer for offline training.
The input features to this classifier are already
processed by `class FeatureGenerator`.
Classifier for online inference.
The input data to this classifier is the raw skeleton data, so they
are processed by `class FeatureGenerator` before sending to the
self.model traine... | 1,865 | en | 0.689466 |
#------------------------------------------------------------------------------
# Copyright (c) 2013, Nucleic Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-------------------------------------------------... | enaml/enaml/widgets/calendar.py | 888 | A bounded date control which edits a Python datetime.date using
a widget which resembles a calendar.
The abstract defintion of a proxy Calendar object.
------------------------------------------------------------------------------ Copyright (c) 2013, Nucleic Development Team. Distributed under the terms of the M... | 579 | en | 0.664671 |
# -*- coding: utf-8 -*-
"""
WOLFEYES'S FRAMEWORK
Python 3 / OpenCV 3
This file describes some TypeCheking decorators.
Might be useless, but allows for almost very precise type checking,
especially on keyworded args, which might help.
"""
# 'kargs' get the arguments and passes the decorator
def args(*types, **ktypes)... | WolfEyes/Utils/TypeChecker.py | 2,472 | Allow testing of input types:
argkey=(types) or argkey=type
WOLFEYES'S FRAMEWORK
Python 3 / OpenCV 3
This file describes some TypeCheking decorators.
Might be useless, but allows for almost very precise type checking,
especially on keyworded args, which might help.
-*- coding: utf-8 -*- 'kargs' get the arguments an... | 947 | en | 0.693623 |
import requests
def run(event, context):
#return event.get('url') + 'aaa'
r = requests.get(event.get('url'))
return r.text
#return '...**^^.This is a request test for url: {0}'.format(event.get('url')) | _from_pydot/dev/request_test.py | 219 | return event.get('url') + 'aaa'return '...**^^.This is a request test for url: {0}'.format(event.get('url')) | 108 | en | 0.333137 |
import configparser
import os
import re
import subprocess
import sys
import time
import utilities_common.cli as clicommon
from urllib.request import urlopen, urlretrieve
import click
from sonic_py_common import logger
from swsscommon.swsscommon import SonicV2Connector
from .bootloader import get_bootloader
from .comm... | sonic_installer/main.py | 38,012 | This subclass of click.Group supports abbreviations and
looking up aliases in a config file with a bit of magic.
Object to hold CLI config
Context class to allocate SWAP memory.
Initialize the SWAP memory allocator.
The allocator will try to setup SWAP memory only if all the below conditions are met:
- allocate eva... | 5,732 | en | 0.795397 |
#!/usr/bin/python3
# encoding: utf-8
# Setup file for dulwich
# Copyright (C) 2008-2016 Jelmer Vernooij <jelmer@jelmer.uk>
try:
from setuptools import setup, Extension
except ImportError:
from distutils.core import setup, Extension
has_setuptools = False
else:
has_setuptools = True
from distutils.core i... | setup.py | 4,406 | !/usr/bin/python3 encoding: utf-8 Setup file for dulwich Copyright (C) 2008-2016 Jelmer Vernooij <jelmer@jelmer.uk> XCode 4.0 dropped support for ppc architecture, which is hardcoded in distutils.sysconfig Also parse only first digit, because 3.2.1 can't be parsed nicely type: Dict[str, Any] | 291 | en | 0.723127 |
import ctypes
import logging
import threading
import time
from contextlib import contextmanager
from queue import Queue
from typing import Any, Callable, Dict, Generator, Iterable, List, Optional, Tuple, Union, cast
import attr
import hypothesis
import hypothesis.errors
import requests
from _pytest.logging import LogC... | src/schemathesis/runner/__init__.py | 19,128 | Fast runner that runs tests sequentially in the main thread.
Special exception when worker thread received SIGINT.
Spread different tests among multiple worker threads.
All events come from a queue where different workers push their events.
All endpoints are distributed among all workers via a queue.
Initialize & start... | 2,219 | en | 0.896831 |
# coding: utf-8
from __future__ import unicode_literals
import json
import re
import socket
from .common import InfoExtractor
from ..compat import (
compat_etree_fromstring,
compat_http_client,
compat_str,
compat_urllib_error,
compat_urllib_parse_unquote,
compat_urllib_parse_unquote_plus,
)
fr... | yt_dlp/extractor/facebook.py | 30,062 | coding: utf-8 data.video have 1080P, but only up to 720p in swf params data.video.story.attachments[].media bigPipe.onPageletArrive ... onPageletArrive pagelet_group_mall data.node.comet_sections.content.story.attachments[].style_type_renderer.attachment.media data.node.comet_sections.content.story.attachments[].style_... | 1,413 | en | 0.381764 |
"""
The patch module allows for a grid to be created and for data to be
defined on that grid.
Typical usage:
-- create the grid
grid = Grid1d(nx)
-- create the data that lives on that grid
data = CellCenterData1d(grid)
bcObj = bcObject(xlb="reflect", xrb="reflect"_
data.registerVar("densi... | multigrid/patch1d.py | 12,391 | Boundary condition container -- hold the BCs on each boundary
for a single variable
the cell-centered data that lives on a grid.
a CellCenterData1d object is built in a multi-step process before it can
be used. We pass in a grid object to describe where the data
lives:
my_data = patch.CellCenterData1d(myGrid)
r... | 4,885 | en | 0.783566 |
#!/usr/bin/python
# coding: utf-8
# This file is execfile()d with the current directory set to its containing
# dir. Note that not all possible configuration values are present in this
# autogenerated file. All configuration values have a default; values that are
# commented out serve to show the default.
import sys
... | docs/conf.py | 7,922 | !/usr/bin/python coding: utf-8 This file is execfile()d with the current directory set to its containing dir. Note that not all possible configuration values are present in this autogenerated file. All configuration values have a default; values that are commented out serve to show the default. If extensions (or module... | 6,568 | en | 0.678018 |
#!/usr/bin/python3
"""
An example script that cleans up failed experiments by moving them to the archive
"""
import argparse
from datetime import datetime
from clearml_agent import APIClient
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--project", "-P", help="Project ID. Only clean up ex... | examples/archive_experiments.py | 1,871 | An example script that cleans up failed experiments by moving them to the archive
!/usr/bin/python3 | 100 | en | 0.905745 |
# Token type identifiers.
AUT_INVALID = 0x00
AUT_OTHER_FILE32 = 0x11
AUT_OHEADER = 0x12
AUT_TRAILER = 0x13
AUT_HEADER32 = 0x14
AUT_HEADER32_EX = 0x15
AUT_DATA = 0x21
AUT_IPC = 0x22
AUT_PATH = 0x23
AUT_SUBJECT32 = 0x24
AUT_XATPATH = 0x25
AUT_PROCESS32 = 0x26
AUT_RETURN32 = 0x27
AUT_TEXT = 0x28
AUT_OPAQUE = 0x29
AUT_IN_A... | bsm/audit_record.py | 3,550 | Token type identifiers. Pre-64-bit BSM, 32-bit tokens weren't explicitly named as '32'. We have compatibility defines. * The values for the following token ids are not defined by BSM. XXXRW: Not sure how to handle these in OpenBSM yet, but I'll give them names more consistent with Sun's BSM. These originally came fro... | 957 | en | 0.878153 |
#
# Copyright 2016 The BigDL 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 ... | python/friesian/example/dlrm/csv_to_parquet.py | 1,565 | Copyright 2016 The BigDL 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 di... | 555 | en | 0.863056 |
import numpy as np
import scipy
from scipy.stats import qmc
from scipy.stats import special_ortho_group
import matplotlib.pyplot as plt
from scipy.optimize import minimize
import warnings
from .ssp import SSP
class SSPSpace:
def __init__(self, domain_dim: int, ssp_dim: int, axis_matrix=None, phase_matrix=None,
... | semanticmapping/sspspace.py | 15,554 | problems duw to complex lograise NotImplementedError()fssp = np.fft.fft(ssp,axis=0)x = np.linalg.lstsq(np.tile(self.phase_matrix,(2,1)), np.hstack([np.arccos(fssp.real), np.arcsin(fssp.imag)])) end if make new if num_pts different than whats stored? Return a matrix, \bar{A}_n Consider the multi scale representation (S_... | 1,297 | en | 0.761714 |
# -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | google/cloud/datastore_v1/services/datastore/transports/grpc.py | 18,062 | gRPC backend transport for Datastore.
Each RPC normalizes the partition IDs of the keys in its
input entities, and always returns entities with keys with
normalized partition IDs. This applies to all keys and entities,
including those in values, except keys with both an empty path
and an empty or unset partition ID. N... | 8,643 | en | 0.811788 |
from src.utils.config import config
import json
# import uuid
import requests
_NAMESPACE = "WS"
_VER_NAMESPACE = "WSVER"
_SAMPLE_NAMESPACE = "SMP"
# versioned and non-versioned index have same version
_SAMPLE_SET_INDEX_VERSION = 1
_SAMPLE_SET_INDEX_NAME = 'sample_set_' + str(_SAMPLE_SET_INDEX_VERSION)
_VER_SAMPLE_SET... | src/index_runner/es_indexers/sample_set.py | 5,754 | Combine newly flattened metadata with existing metadata. This Function is designed to keep the indexing
of the different metadata fields consistent for each node within the sample node tree s.t. all the
fields in index (idx) 0 will be from item 0 in the node tree. Empty string ("") entries are Empty and
add... | 1,171 | en | 0.733669 |
from alipay import AliPay
from django.core.paginator import Paginator
from django.http import HttpResponseRedirect
from django.http import JsonResponse
from django.shortcuts import render
from django.utils.http import urlquote
from Qshop.settings import alipay_private_key_string, alipay_public_key_string
from Seller.v... | Qshop/Buyer/views.py | 11,385 | 处理ajax 请求,添加商品到购物车 ,成功保存到数据库。
传入商品id,数量
阿里支付,传入交易订单号,总金额
:desc 闭包函数校验是否登录
:param func:
:return:
get请求 商品详情页购买单个商品。传入商品id,数量。
post请求 购物车购买多个商品。
支付结果页
如果有out_trade_no,支付成功,修改订单状态
Create your views here. 按照商品id查 按商品名字查 分页 推荐商品 订单 订单详情 状态 创建订单 订单详情 订单总价 商品种类个数 实例化支付 订单编号 金额 字符串类型 支付跳转页面 | 285 | zh | 0.961396 |
#Import Library
import warnings
import numpy as np
import datetime
from extract_data import *
from word_encoder import *
from sklearn import svm
from sklearn.ensemble import RandomForestClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn import tree
# send the extracted data availble from extract_data t... | Project/algorithm.old.py | 2,002 | Import Library send the extracted data availble from extract_data to the encode function this function vectorizes the text based data into ASCII format for use by the algorithms convert the float scores to int. Multiplying by 10 helps us keep the decimal level precision which would otherwise be lost in typecasting igno... | 621 | en | 0.625865 |
from __future__ import division
import databench
import math
import random
class Dummypi(databench.Analysis):
"""A dummy analysis."""
@databench.on
def connected(self):
yield self.data.init({'samples': 100000})
@databench.on
def run(self):
"""Run when button is pressed."""
... | databench/analyses_packaged/dummypi/analysis.py | 1,281 | A dummy analysis.
Run when button is pressed.
generate points and check whether they are inside the unit circle every 1000 iterations, update status debug calculate pi and its uncertainty given the current draws send status to frontend | 237 | en | 0.779092 |
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
"""
This script will be executed whenever a change is pushed to the
master branch. It will schedule multiple child tasks... | tools/taskcluster/schedule-master-build.py | 7,652 | :param str engine: Klar, Webview
:param str device: ARM, X86
:return: uiWebviewARMTestTaskId, uiWebviewARMTestTask
This script will be executed whenever a change is pushed to the
master branch. It will schedule multiple child tasks that build
the app, run tests and execute code quality tools:
This Source Code Form is... | 772 | en | 0.758879 |
# Copyright 2018 Xanadu Quantum Technologies Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agre... | tests/test_expval.py | 10,823 | Test expectation values
Test tensor expectation values
Test that Hadamard expectation value is correct
Test that a tensor product involving qml.Hermitian works correctly
Test that arbitrary Hermitian expectation values are correct
Test that identity expectation value (i.e. the trace) is 1
Test that arbitrary multi-mode... | 1,395 | en | 0.832883 |
##
# @filename : epd4in2b.py
# @brief : Implements for Dual-color e-paper library
# @author : Yehui from Waveshare
#
# Copyright (C) Waveshare August 15 2017
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documn... | display/epd4in2b.py | 7,150 | @filename : epd4in2b.py @brief : Implements for Dual-color e-paper library @author : Yehui from Waveshare Copyright (C) Waveshare August 15 2017 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documnetation files (the "Software"), to d... | 1,664 | en | 0.808495 |
# -*- coding: utf-8 -*-
"""This module is a stub for classes related to vulnerability exposure scores.
Copyright:
(c) 2022 Illumio
License:
Apache2, see LICENSE for more details.
"""
from dataclasses import dataclass
from illumio.util import MutableObject
@dataclass
class Vulnerability(MutableObject):
... | illumio/vulnerabilities/vulnerability.py | 339 | This module is a stub for classes related to vulnerability exposure scores.
Copyright:
(c) 2022 Illumio
License:
Apache2, see LICENSE for more details.
-*- coding: utf-8 -*- | 185 | en | 0.782859 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.