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 functools
from django import http
from django.shortcuts import get_object_or_404, redirect
from conference import models, settings
def speaker_access(f): # pragma: no cover
"""
Decorator that protects the view relative to a speaker.
"""
@functools.wraps(f)
def wrapper(request, slug, **kwa... | conference/decorators.py | 4,328 | Decorator which protect the relative view to a profile.
Decorator that protects the view relative to a speaker.
Decorator that protects the view relative to a talk.
pragma: no cover pragma: no cover The MultipleObjectsReturned can happen if the user is not logged on and .id is None if the talk is unconfirmed can acce... | 674 | en | 0.923793 |
# 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 t... | tests/functional/test_objects_issues.py | 4,298 | 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 the License is di... | 522 | en | 0.872906 |
# -*- coding: utf-8 -*-
"""Worker Remote Control Client.
Client for worker remote control commands.
Server implementation is in :mod:`celery.worker.control`.
"""
from __future__ import absolute_import, unicode_literals
import warnings
from billiard.common import TERM_SIGNAME
from kombu.matcher import match
from komb... | idps/lib/python3.7/site-packages/celery/app/control.py | 16,729 | Worker remote control client.
API for app.control.inspect.
Tell all (or specific) workers to start consuming from a new queue.
Only the queue name is required as if only the queue is specified
then the exchange/routing key will be set to the same name (
like automatic queues do).
Note:
This command does not respe... | 5,408 | en | 0.80172 |
from __future__ import annotations
import asyncio
import logging
from collections import defaultdict, deque
from math import log2
from time import time
from typing import Container
from tlz import topk
from tornado.ioloop import PeriodicCallback
import dask
from dask.utils import parse_timedelta
from .comm.addressi... | distributed/stealing.py | 18,856 | Determine whether worker ``thief`` can steal task ``ts`` from worker
``victim``.
Assumes that `ts` has some restrictions.
Determine whether the given task has restrictions and whether these
restrictions are strict.
A very verbose dictionary representation for debugging purposes.
Not type stable and not inteded for rou... | 1,368 | en | 0.891973 |
# Solution for the test LAB
#!/usr/bin/env python
print("Solucionado")
| autograder_test/src/test.py | 71 | Solution for the test LAB!/usr/bin/env python | 45 | en | 0.389404 |
# coding=utf-8
# Copyright 2021 The Eleuther AI and HuggingFace Inc. team. 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-... | src/stable_library_code/transformers/gpt_neo/modeling_gpt_neo.py | 35,391 | A few attention related utilities for attention modules in GPT Neo, to be used as a mixin.
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
models.
Initialize the weights.
Merges attn_head_size dim and num_attn_heads dim into hidden_size
This function is u... | 3,880 | en | 0.787744 |
from django.http.response import HttpResponseRedirect
from django.shortcuts import redirect, render
from django.contrib.auth.decorators import login_required
from itertools import chain
from .models import Image, Profile, Comment
from .forms import NewProfileForm, NewImageForm
import string
import random
# Create your... | image/views.py | 5,732 | Create your views here. print("Your generared password is: " +generatedPassword) | 80 | en | 0.68224 |
"""Single slice vgg with normalised scale.
"""
import functools
import lasagne as nn
import numpy as np
import theano
import theano.tensor as T
import data_loader
import deep_learning_layers
import image_transform
import layers
import preprocess
import postprocess
import objectives
import theano_print... | data/external/repositories_2to3/267667/kaggle-heart-master/configurations/je_ss_smcrps_nrmsc200_500_dropnorm.py | 8,910 | Single slice vgg with normalised scale.
Random params dump a lot of data in a pkl-dump file. (for debugging) dump the outputs from the dataloader (for debugging) Memory usage scheme Save and validation frequency Training (schedule) parameters - batch sizes - learning rate and method Preprocessing stuff normscale_resi... | 940 | en | 0.728624 |
#!/usr/bin/env python
## Filter small sequences out of a fasta file. For use with flies,
## for example, where scaffolds of length <200kb seem to be considered
## no mans land
import os
from optparse import OptionParser
from sonLib.bioio import fastaRead
from sonLib.bioio import fastaWrite
from sonLib.bioio import ... | preprocessor/cactus_filterSmallFastaSequences.py | 3,346 | !/usr/bin/env python Filter small sequences out of a fasta file. For use with flies, for example, where scaffolds of length <200kb seem to be considered no mans land for every sequence, determine if its contained in the file (starts with |1|0; and there is a differently named sequence after it), and its length (define... | 594 | en | 0.941132 |
# Copyright (C) 2008 John Paulett (john -at- paulett.org)
# Copyright (C) 2009-2018 David Aguilar (davvid -at- gmail.com)
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
"""Helper functions for pickling and unpickling... | jsonpickle/util.py | 14,602 | Provide compatibility for pickles created with jsonpickle 0.9.6 and
earlier, remapping `exceptions` and `__builtin__` to `builtins`.
Decode payload - must be ascii text.
Encode binary data to ascii text in base64. Data must be bytes.
Decode payload - must be ascii text.
Encode binary data to ascii text in base85. Data ... | 5,803 | en | 0.672492 |
import argparse
def train_args():
"""
Retrieves and parses the 3 command line arguments provided by the user when
they run the program from a terminal window. This function uses Python's
argparse module to created and defined these 3 command line arguments. If
the user fails to pro... | train_args.py | 2,103 | Retrieves and parses the 3 command line arguments provided by the user when
they run the program from a terminal window. This function uses Python's
argparse module to created and defined these 3 command line arguments. If
the user fails to provide some or all of the 3 arguments, then the default
values are used for th... | 420 | en | 0.690488 |
import pandas as pd
import plotly.graph_objects as go
import plotly.express as px
import plotly.figure_factory as ff
import numpy as np
from plotly.subplots import make_subplots
from tqdm import tqdm
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.feature_selectio... | knn/main.py | 1,045 | Account for missingness | 23 | en | 0.751888 |
import sys
import json
from appscale.common.service_stats import stats_manager
from mock import mock, patch
from tornado.testing import AsyncHTTPTestCase
from appscale.common.unpackaged import APPSCALE_PYTHON_APPSERVER
from appscale.taskqueue import appscale_taskqueue, rest_api, statistics
sys.path.append(APPSCALE... | AppTaskQueue/test/unit/test_service_stats.py | 8,684 | Overwrites method of AsyncHTTPTestCase.
Returns:
an instance of tornado application
Patches handlers of Taskqueue application in order
to prevent real calls to Cassandra and Datastore because only
service statistics matters for this test.
We mock functionality which uses distributed taskqueue so can omit it Patch g... | 1,044 | en | 0.855229 |
import os
from setuptools import Extension, setup
import sys
from Cython.Build import build_ext
import numpy
NAME = "olive-camera-dcamapi"
VERSION = "0.1"
DESCRIPTION = "A small template project that shows how to wrap C/C++ code into python using Cython"
URL = "https://github.com/liuyenting/olive-camera-dca... | setup.py | 4,006 | Generate extension constructors.
Trove classifiers https://pypi.org/classifiers/ "Module .pxd file not found next to .pyx file", https://github.com/cython/cython/issues/2452 numpy - install cython headers so other modules can cimport - force sdist to keep the .pyx files NOTE: re-route static library on Windows ht... | 841 | en | 0.619625 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import simplejson as json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
class AntMerchantExpandBenefitConfirmResponse(AlipayResponse):
def __init__(self):
super(AntMerchantExpandBenefitConfirmResponse, self).__init__()
self._benef... | alipay/aop/api/response/AntMerchantExpandBenefitConfirmResponse.py | 2,194 | !/usr/bin/env python -*- coding: utf-8 -*- | 42 | en | 0.34282 |
# This file is part of Indico.
# Copyright (C) 2002 - 2019 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from __future__ import absolute_import, unicode_literals
import traceback
from uuid import uuid4
from fl... | indico/web/errors.py | 3,716 | This file is part of Indico. Copyright (C) 2002 - 2019 CERN Indico is free software; you can redistribute it and/or modify it under the terms of the MIT License; see the LICENSE file for more details. If the error was caused while connecting the database, rendering the error page fails since e.g. the header/footer temp... | 1,203 | en | 0.88776 |
"""Tests for iterating over expression clauses.
Since BooleanExpressions's iter_clauses variations are basically wrappers
around the functions of the same name from ExpressionTreeNode, they are not
tested in-depth here. Instead, take a look at the unit tests for
ExpressionTreeNode's implementation.
"""
import unitte... | tt/tests/unit/expressions/test_bexpr_iter_clauses.py | 2,735 | Test basic expression iter_clauses functionality.
Test basic expression iter_cnf_clauses functionality.
Test basic expression iter_dnf_clauses functionality.
Tests for iterating over expression clauses.
Since BooleanExpressions's iter_clauses variations are basically wrappers
around the functions of the same name from... | 505 | en | 0.813057 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2018-03-01 09:58
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('projects', '0018_project_properties'),
]
operations = [
migrations.AlterModelOption... | lims/projects/migrations/0019_auto_20180301_0958.py | 1,025 | -*- coding: utf-8 -*- Generated by Django 1.11.3 on 2018-03-01 09:58 | 68 | en | 0.526374 |
#
# MythBox for XBMC - http://mythbox.googlecode.com
# Copyright (C) 2011 analogue@yahoo.com
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at yo... | .kodi/addons/script.mythbox/resources/src/mythbox/mythtv/publish.py | 3,177 | MythBox for XBMC - http://mythbox.googlecode.com Copyright (C) 2011 analogue@yahoo.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any la... | 1,140 | en | 0.80561 |
"""
Copyright 2020 The OneFlow 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 applicable law or agr... | oneflow/python/test/ops/test_reduce_mean.py | 3,041 | Copyright 2020 The OneFlow 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 applicable law or agreed ... | 636 | en | 0.85757 |
from hazelcast.protocol.codec import \
semaphore_acquire_codec, \
semaphore_available_permits_codec, \
semaphore_drain_permits_codec, \
semaphore_init_codec, \
semaphore_reduce_permits_codec, \
semaphore_release_codec, \
semaphore_try_acquire_codec
from hazelcast.proxy.base import PartitionS... | hazelcast/proxy/semaphore.py | 6,352 | Semaphore is a backed-up distributed alternative to the Python `asyncio.Semaphore <https://docs.python.org/3/library/asyncio-sync.html>`_
Semaphore is a cluster-wide counting semaphore. Conceptually, it maintains a set of permits. Each acquire() blocks
if necessary until a permit is available, and then takes it. Each ... | 4,227 | en | 0.899938 |
import keyboard
import settings
from key_sender import *
import utils
class HotKey(object):
def __init__(self):
pass
def regist_hotkey(self, hotkey_group, queue_h):
if settings.test:
keyboard.add_hotkey('F10', self.f10_fun)
keyboard.add_hotkey('F11', self.f11_fun)
... | send_key_explame/pypiwin32/hot_key.py | 1,727 | time.sleep(0.1) self.get_foreground_title() self.send_key(Key['up_arrow']) self.send_key(Key['right_arrow']) self.send_key(Key['spacebar']) 魔道 | 142 | en | 0.272338 |
import os
import re
import sys
import json
import time
import requests
import downloader
from config import TEMP_FOLDER
# 爬虫请求头
headers = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language': 'zh-CN,zh;q=0.9,zh-TW;q=0.8,en;q=0.7',
'User-Agent': 'Mozilla/5.0 (Windows ... | src/bbparser.py | 4,781 | 爬虫请求头 秒时间戳 秒时间戳 r = requests.get(v, stream=True) f = open(vfile, "wb") try: for chunk in r.iter_content(chunk_size=512): if chunk: f.write(chunk) except Exception as e: print(vfile, '下载失败\n链接: ', v, '\n错误: ', e) 创建一个空白的临时文本文件 | 253 | en | 0.444562 |
# This Python file uses the following encoding: utf-8
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from builtins import str
from builtins import object
import json
import logging
import re
import os
import math
impor... | crea/crea.py | 82,655 | Connect to the Crea network.
:param str node: Node to connect to *(optional)*
:param str rpcuser: RPC user *(optional)*
:param str rpcpassword: RPC password *(optional)*
:param bool nobroadcast: Do **not** broadcast a transaction!
*(optional)*
:param bool unsigned: Do **not** sign a transaction! *(optional)*
:para... | 27,001 | en | 0.741774 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib
from lxml import html
import requests
page = requests.get('http://stmary-338.com/')
tree = html.fromstring(page.content)
info = tree.xpath('//*[@id="panel-w5840cbe2b571d-0-1-0"]/div/div/h6[1]')
for i in info:
print "ST MARY", i.encode(page.encoding)
| test-stmary.py | 315 | !/usr/bin/env python -*- coding: utf-8 -*- | 42 | en | 0.34282 |
"""
U{Corelan<https://www.corelan.be>}
Copyright (c) 2011-2017, Peter Van Eeckhoutte - Corelan GCV
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 ... | monaFile.py | 833,632 | try: import debugger except: passimport tracebackprint traceback.format_exc()import debugtypesimport libdatatype--------------------------------------- Global stuff --------------------------------------- offset = [x86,x64]--------------------------------------- Populate constants ... | 33,380 | en | 0.621589 |
# -*- coding: utf-8 -*-
import sys
from django.test import SimpleTestCase
from django.test.utils import override_settings
from .forms import (CustomNamingForm, DefaultNamingForm, MixedNamingForm,
MultipleNamingForm)
class TestWidget(SimpleTestCase):
def test_custom_naming(self):
html = CustomNamin... | tests/test_forms.py | 4,325 | -*- coding: utf-8 -*- | 21 | en | 0.767281 |
""" Visualize the single different data samples or averages
All visualization nodes are zero-processing nodes, i.e. their execute method
returns exactly the data that it gets as parameter. However, when the data
is passed through the visualization node, it performs different kinds of
analysis and creates some plots o... | pySPACE/missions/nodes/visualization/__init__.py | 736 | Visualize the single different data samples or averages
All visualization nodes are zero-processing nodes, i.e. their execute method
returns exactly the data that it gets as parameter. However, when the data
is passed through the visualization node, it performs different kinds of
analysis and creates some plots of th... | 727 | en | 0.938587 |
"""CovidDetector URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class... | CovidDetector/urls.py | 799 | CovidDetector URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-ba... | 629 | en | 0.629646 |
#-----------------------------------------------------------------------------
# Name: GraphModels
# Purpose: To store graphs used in network translations
# Author: Aric Sanders
# Created: 4/6/2016
# License: MIT License
#--------------------------------------------------------------------------... | Code/DataHandlers/GraphModels.py | 52,258 | Class that transforms a row modelled header and metadata to several different data types
#!python
defaults={"graph_name":"Data Table Graph",
"node_names":['DataFrameDictionary','AsciiDataTable'],
"node_descriptions":["Pandas Data Frame Dictionary","AsciiDataTable"],
"current_node":'DataFra... | 10,765 | en | 0.650814 |
from ..utils import Object
class ChatEventAction(Object):
"""
Represents a chat event
No parameters required.
"""
ID = "chatEventAction"
def __init__(self, **kwargs):
pass
@staticmethod
def read(q: dict, *args) -> "ChatEventStickerSetChanged or ChatEventMemberLeft... | pytglib/api/types/chat_event_action.py | 986 | Represents a chat event
No parameters required. | 48 | en | 0.479005 |
"""
Module: 'uerrno' on esp32 1.12.0
"""
# MCU: (sysname='esp32', nodename='esp32', release='1.12.0', version='v1.12 on 2019-12-20', machine='ESP32 module (spiram) with ESP32')
# Stubber: 1.3.2
EACCES = 13
EADDRINUSE = 98
EAGAIN = 11
EALREADY = 114
EBADF = 9
ECONNABORTED = 103
ECONNREFUSED = 111
ECONNRESET = 104
EEXIST... | stubs/micropython-esp32-1_12/uerrno.py | 518 | Module: 'uerrno' on esp32 1.12.0
MCU: (sysname='esp32', nodename='esp32', release='1.12.0', version='v1.12 on 2019-12-20', machine='ESP32 module (spiram) with ESP32') Stubber: 1.3.2 | 183 | en | 0.155334 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from include import IncludeManager
from osf.models.base import BaseModel, ObjectIDMixin
from osf.utils.workflows import RequestTypes
from osf.models.mixins import NodeRequestableMixin, PreprintRequestableMixin
class Abstrac... | osf/models/request.py | 1,152 | Request for Node Access
Request for Preprint Withdrawal
-*- coding: utf-8 -*- | 89 | en | 0.849242 |
""""""
import os
import uuid
import bz2
import pickle
import traceback
import zlib
from abc import ABC
from copy import copy,deepcopy
from typing import Any, Callable
from logging import INFO, ERROR
from datetime import datetime
from vnpy.trader.constant import Interval, Direction, Offset, Status, OrderType, Color, Ex... | vnpy/app/cta_strategy_pro/template.py | 107,524 | 期货交易增强版模板
增强模板
CTA策略模板
Send buy order to open a long position.
Cancel all orders sent by strategy.
重载撤销所有正在进行得委托
:return:
Cancel an existing order.
Send cover order to close a short position.
更新网格显示信息
显示事务的过程记录=》 log
修正order被拆单得情况
Get default parameters dict of strategy class.
Get strategy data.
Return whether the cta_... | 5,822 | zh | 0.741272 |
#!/usr/bin/python
import pathlib
import requests
import smtplib
import logging
import coloredlogs
import verboselogs
from etc.api.keys import *
path_atual_tl = str(pathlib.Path(__file__).parent.absolute())
path_tl_final = path_atual_tl.replace('/etc/notification','')
def logando_notification(tipo, mensagem):
... | Linux/etc/notification/telegram.py | 2,948 | Generates the log message/Gera a mensagem de log.
:param tipo: Sets the log type/Seta o tipo de log.
:param mensagem: Sets the message of log/Seta a mensagem do log.
:return: Returns the complete log's body/Retorna o corpo completo do log.
Generates the notification to Telegram account/Gera a notificação para a conta ... | 696 | pt | 0.56692 |
import logging
from abc import abstractmethod
from .input import Input
from .input_config import assert_keycode_list
class Switch(Input):
"""Switch input class
Implement custom on() and off() logic
Read more about defaults from input_config.py
"""
def validate_defaults(self, defaults):
... | surrortg/inputs/switch.py | 2,834 | Switch input class
Implement custom on() and off() logic
Read more about defaults from input_config.py
Returns a single keybind or a list of keybinds.
Switches are bound to the space key by default.
To override the defaults, override this method in your switch
subclass and return different keybinds.
Returns the name... | 373 | en | 0.706262 |
#!/usr/bin/python
# -*- encoding: utf-8 -*-
"""
@ide: PyCharm
@author: Pedro Silva
@contact: pedroh21.silva@gmail.com
@created: out-10 of 2019
"""
import os
import numpy as np
import tensorflow as tf
import tensorflow.keras.backend as kback
from tensorflow import keras
class QRSNet(object):
@classmethod
d... | python/qrs/qrs_net.py | 7,297 | Create the CNN net topology.
:return keras.Sequential(): CNN topology.
Prepare the data for the training, turning it into a numpy array.
:param list data_x: data that will be used to train.
:param tuple input_shape: the input shape that the data must have to be used as training data.
:param list data_y: the labels rela... | 2,286 | en | 0.761521 |
"""
MIT License
Copyright (c) 2019 YangYun
Copyright (c) 2020 Việt Hùng
Copyright (c) 2020-2021 Hyeonki Hong <hhk7734@gmail.com>
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 restrictio... | py_src/yolov4/tf/dataset/keras_sequence.py | 7,849 | @return
`images`: Dim(batch, height, width, channels)
`groud_truth_one`:
[Dim(batch, yolo.h, yolo.w, yolo.c + len(mask))] * len(yolo)
@param `dataset_bboxes`: [[b_x, b_y, b_w, b_h, class_id], ...]
@return `groud_truth_one`:
[Dim(yolo.h, yolo.w, yolo.c + len(mask))] * len(yolo)
@param dataset: [imag... | 1,687 | en | 0.716232 |
from amaru.utilities import constants
def generate_subsets(current_tree_bottom):
current_distances = []
subsets = []
current_point = 0
while current_point < len(current_tree_bottom) - 1:
current_distances.append(current_tree_bottom[current_point + 1][1] - current_tree_bottom[current_point][1])... | amaru/utilities/subsets.py | 1,800 | remove similar splits causesd by floating point imprecision all possible x-distances between bottom blocks subsets based on differences between x-distances finds the center positions of the given subset finds the edge positions of the given subset | 247 | en | 0.857841 |
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from Logger.models import Run, Process
from Logger.libs import log_dealer
import json
# Create your views here.
def listen(request):
log_dealer(request)
context_dict = {}
response = render(request, 'index.html',... | Logger/views.py | 1,868 | Create your views here. | 23 | en | 0.928092 |
# MIT License
# Copyright (c) 2020 Simon Schug, João Sacramento
# 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, ... | lib/config.py | 2,362 | Setup the logging device to log into a uniquely created directory.
Args:
name: Name of the directory for the log-files.
dir: Optional sub-directory within log
MIT License Copyright (c) 2020 Simon Schug, João Sacramento Permission is hereby granted, free of charge, to any person obtaining a copy of this softw... | 1,493 | en | 0.850005 |
'''
Created on Feb 4, 2021
@author: paepcke
'''
import io
import os
import pickle
import tempfile
import unittest
from experiment_manager.neural_net_config import NeuralNetConfig
#from experiment_manager.dottable_config import DottableConfigParser
TEST_ALL = True
#TEST_ALL = False
class NeuralNetConfigTest(unittes... | src/experiment_manager/tests/test_neural_net_config.py | 8,859 | Created on Feb 4, 2021
@author: paepcke
from experiment_manager.dottable_config import DottableConfigParserTEST_ALL = False ------------ Tests ----------------------------------------------- test_add_section ------------------------------------------------------- test_setter_evals ------------------- A non-neural-net... | 1,421 | en | 0.420463 |
""" Dynamic bicycle model.
Use Dynamic class to:
1. simulate continuous model
2. linearize continuous model
3. discretize continuous model
4. simulate continuously linearized discrete model
5. compare continuous and discrete models
"""
__author__ = 'Achin Jain'
__email__ = 'achinj@seas.upenn.edu'
import num... | bayes_race/models/dynamic.py | 11,384 | specify model params here
write dynamics as first order ODE: dxdt = f(x(t))
x is a 6x1 vector: [x, y, psi, vx, vy, omega]^T
u is a 2x1 vector: [acc/pwm, steer]^T
write dynamics as first order ODE: dxdt = f(x(t))
x is a 6x1 vector: [x, y, psi, vx, vy, omega]^T
u is a 2x1 vector: [acc/pwm, steer]^T
dxdt ... | 1,926 | en | 0.879489 |
#!/usr/bin/env python3
# This script is part of the WhiteboxTools geospatial analysis library.
# Authors: Dr. John Lindsay, Rachel Broders
# Created: 28/11/2017
# Last Modified: 05/11/2019
# License: MIT
import __future__
import sys
# if sys.version_info[0] < 3:
# raise Exception("Must be using Python 3")
import ... | wb_runner.py | 58,681 | A custom callback for dealing with tool output.
!/usr/bin/env python3 This script is part of the WhiteboxTools geospatial analysis library. Authors: Dr. John Lindsay, Rachel Broders Created: 28/11/2017 Last Modified: 05/11/2019 License: MIT if sys.version_info[0] < 3: raise Exception("Must be using Python... | 9,348 | en | 0.469204 |
import datetime, pandas as pd, warnings
from time import strftime, localtime
from twint.tweet import Tweet_formats
Tweets_df = None
Follow_df = None
User_df = None
_object_blocks = {
"tweet": [],
"user": [],
"following": [],
"followers": []
}
weekdays = {
"Monday": 1,
"Tuesday": 2,
... | twint/storage/panda.py | 6,505 | try: _type = ((object.__class__.__name__ == "tweet")*"tweet" + (object.__class__.__name__ == "user")*"user")except AttributeError: _type = config.Following*"following" + config.Followers*"followers" | 216 | en | 0.444122 |
import sys
from sqlalchemy import create_engine
from sqlalchemy import event
from sqlalchemy import exc
from sqlalchemy import func
from sqlalchemy import INT
from sqlalchemy import MetaData
from sqlalchemy import pool as _pool
from sqlalchemy import select
from sqlalchemy import testing
from sqlalchemy import util
fr... | test/engine/test_transaction.py | 57,424 | Still some debate over if the "reset agent" should apply to the
future connection or not.
test a basic rollback
test that returning connections to the pool clears any object
locks.
no error no error force the "commit" of the savepoint that occurs when the "with" block fails, e.g. the RELEASE, to fail, because the sav... | 2,811 | en | 0.947572 |
#----------------#
# Name: Mod_Obj #
# Author: Photonic #
# Date:U/N #
#----------------#
import urllib2
import os
import sys
# Class Mod defines the mod object
'''
#############################
# Class for "mod" objects. #
# Used to store all data #
# related to mods. #
##########################... | Main/Mod_Obj.py | 5,502 | ---------------- Name: Mod_Obj Author: Photonic Date:U/N ---------------- Class Mod defines the mod object Stores the name of the mod (Supplyed by the suer) Need to make this a part of the entire file. But I'll do it tomorrow. Stores the URL of the mod (supplyd by the user) Used to indecate if the mod wass do... | 1,847 | en | 0.805456 |
from datetime import datetime, timedelta
from io import IOBase
from typing import Dict, Generic, List, Optional, Tuple, TypeVar
from injector import inject, singleton
from .backupscheme import GenerationalScheme, OldestScheme, DeleteAfterUploadScheme
from backup.config import Config, Setting, CreateOptions
fr... | hassio-google-drive-backup/backup/model/model.py | 13,764 | Given a list of backups, decides if one should be purged.
Gets called after reading state but before any changes are made to check for additional errors. SOMEDAY: this should be cached in config and regenerated on config updates, not here Latest backup is before the backup time for that day return the next backup aft... | 603 | en | 0.957872 |
# Copyright (c) 2015 Dell 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 a... | cinder/tests/unit/test_dellscapi.py | 344,141 | Copyright (c) 2015 Dell 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, ... | 9,541 | en | 0.87496 |
from vec2d_jdm import Vec2D
import math
class Robot(object):
ROBOT_WIDTH = 10
ROBOT_HEIGHT = 15
ROBOT_EDGE = 2
TRAJ_THICKNESS = 4
def __init__(self, speed, canvaswidth, canvasheight, path,
color = "blue", trajColor = "red"):
self.canvaswidth = canvaswidth
self.canvasheigh... | Mobot_simulation/Robot.py | 5,257 | Origin is actually at the center top of the This is where different algorithms differ The side of the robot that's perpendicular to its velocity The parallel side The bottom edge The left edge The right edge The top edge Determine the sign of the error + if path on the left, - if on the right t in [0, 1) t in [0, 1) | 319 | en | 0.756066 |
import pomdp_py
class Observation(pomdp_py.Observation):
"""Defines the Observation for the continuous light-dark domain;
Observation space:
:math:`\Omega\subseteq\mathbb{R}^2` the observation of the robot is
an estimate of the robot position :math:`g(x_t)\in\Omega`.
"""
# the n... | pomdp_problems/light_dark/domain/observation.py | 1,433 | Defines the Observation for the continuous light-dark domain;
Observation space:
:math:`\Omega\subseteq\mathbb{R}^2` the observation of the robot is
an estimate of the robot position :math:`g(x_t)\in\Omega`.
Initializes a observation in light dark domain.
Args:
position (tuple): position of the robo... | 395 | en | 0.642791 |
from django.conf import settings
from django.db import models
from django.db.models.signals import post_save, pre_save
from .utils import Mailchimp
class MarketingPreference(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL)
subscribed = models.Boolean... | eCommerce-master/src/marketing/models.py | 2,102 | User model
subscribing user unsubscribing user | 48 | en | 0.839496 |
"""
Run x12/x13-arima specs in a subprocess from Python and curry results back
into python.
Notes
-----
Many of the functions are called x12. However, they are also intended to work
for x13. If this is not the case, it's a bug.
"""
import os
import subprocess
import tempfile
import re
from warnings import warn
import... | statsmodels/tsa/x13.py | 22,508 | Parameters
----------
data
appendbcst : bool
appendfcst : bool
comptype
compwt
decimals
modelspan
name
period
precision
to_print
to_save
span
start
title
type
Notes
-----
Rarely used arguments
divpower
missingcode
missingval
saveprecision
trimzero
Takes something like (1 1 0)(0 1 1) and returns a arma order, sarma
or... | 8,568 | en | 0.813019 |
import numpy as np
import scipy.signal as signal
import matplotlib.pyplot as plt
FS = 48000.0
FREQ = 9000
omega = 2 * np.pi * FREQ
r = np.array([251589, -130428 - 4165j, -130428 + 4165j, 4634 - 22873j, 4634 + 22873j])
p = np.array([-46580, -55482 + 25082j, -55482 - 25082j, -26292 - 59437j, -26292 + 59437j])
r = np.a... | sim/filter_design.py | 1,496 | print(z) print(p) freq_factor = fc / 9400 plt.figure() plt.plot(z.real, z.imag, 'go') plt.plot(p.real, p.imag, 'rx') plt.grid() | 127 | en | 0.062335 |
#
# 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... | airflow/providers/sendgrid/utils/emailer.py | 4,304 | Send an email with html content using `Sendgrid <https://sendgrid.com/>`__.
.. note::
For more information, see :ref:`email-configuration-sendgrid`
Airflow module for emailer using sendgrid
Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file dis... | 1,071 | en | 0.837446 |
#!/usr/bin/env python
# Copyright 2017 Google Inc. 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 require... | cloudml-template/examples/housing-regression/trainer/metadata.py | 3,758 | !/usr/bin/env python Copyright 2017 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law ... | 2,377 | en | 0.804747 |
# Copyright (c) 2010-2020 openpyxl
from openpyxl.descriptors.serialisable import Serialisable
from openpyxl.descriptors import (
Typed,
Bool,
Integer,
Sequence,
Alias,
)
from openpyxl.descriptors.excel import ExtensionList
from openpyxl.descriptors.nested import (
NestedNoneSet,
NestedSet,
... | venv/lib/python3.8/site-packages/openpyxl/chart/bar_chart.py | 4,175 | Copyright (c) 2010-2020 openpyxl chart properties actually used by containing classes | 85 | en | 0.80725 |
import unittest
from pycoin.coins import tx_utils
from pycoin.cmds.tx import DEFAULT_VERSION
from pycoin.ecdsa.secp256k1 import secp256k1_generator
from pycoin.encoding.hexbytes import h2b
from pycoin.solve.utils import build_hash160_lookup, build_p2sh_lookup
from pycoin.symbols.btc import network
from pycoin.ui.key_f... | tests/sign_test.py | 8,305 | BRAIN DAMAGE Finish signing a 2 of 2 transaction, that already has one signature signed by bitcoind This tx can be found on testnet3 blockchain txid: 9618820d7037d2f32db798c92665231cd4599326f5bd99cb59d0b723be2a13a2 | 214 | en | 0.839622 |
# 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
# distribu... | src/openfermion/transforms/_jordan_wigner_test.py | 14,595 | Tests _jordan_wigner.py.
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, softwar... | 846 | en | 0.82925 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# oz_cli documentation build configuration file, created by
# sphinx-quickstart on Fri Jun 9 13:47:02 2017.
#
# 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
# auto... | docs/conf.py | 4,859 | !/usr/bin/env python -*- coding: utf-8 -*- oz_cli documentation build configuration file, created by sphinx-quickstart on Fri Jun 9 13:47:02 2017. 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 c... | 3,577 | en | 0.700649 |
def dfs(graph, start, end):
stack = [start]
visited = []
while stack:
u = stack.pop() # stack에서 아이템을 빼낸다.
visited.append(u)
if end in visited:
return 1
for v in graph[u]:
if v not in visited and v not in stack:
stack.append(v)
retu... | swea/stack/dfs_p1.py | 734 | stack에서 아이템을 빼낸다. graph[b] = graph.get(b, []) + [a] | 51 | ko | 0.97281 |
# -*- coding: utf-8 -*-
# Copyright 2008-2015 Nokia Networks
# Copyright 2016- Robot Framework Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.o... | src/robotide/context/__init__.py | 9,464 | -*- coding: utf-8 -*- Copyright 2008-2015 Nokia Networks Copyright 2016- Robot Framework Foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENS... | 704 | en | 0.80888 |
# 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... | research/minigo/preprocessing_test.py | 6,700 | Tests for preprocessing.
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 b... | 1,072 | en | 0.828335 |
# -*- coding: utf-8 -*-
"""
Criado por Lucas Fonseca Lage em 04/03/2020
"""
import re, os, spacy
import numpy as np
from my_wsd import my_lesk
from unicodedata import normalize
from document import Document
from gensim.models import Phrases
# Carregamento do modelo Spacy
nlp = spacy.load('pt_core_news_lg')
# Carrega... | complexidade_textual.py | 6,783 | Recebe o caminho para o diretório e retorna uma lista com os caminhos
absolutos para os arquivos que estão nele
Retorna uma tupla com o numero de bigramas e trigramas.
Recebe como entrada o texto segmentado em uma lista de sentencas.
Conta o número de bigramas encontrados na redação. Recebe uma lista de
sentenças que c... | 1,800 | pt | 0.987484 |
# Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2013 NTT MCL, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with th... | openstack_dashboard/dashboards/admin/network_topology/panel.py | 1,086 | Copyright 2012 United States Government as represented by the Administrator of the National Aeronautics and Space Administration. All Rights Reserved. Copyright 2013 NTT MCL, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You m... | 763 | en | 0.869721 |
import torch.nn as nn
from mmcv.cnn import ConvModule
from mmdet.models.builder import HEADS
from .bbox_head import BBoxHead
@HEADS.register_module()
class ConvFCBBoxHeadSeparate(BBoxHead):
r"""More general bbox head, with shared conv and fc layers and two optional
separated branches.
.. code-block:: no... | mmdet/models/roi_heads/bbox_heads/bbox_head_separate.py | 6,578 | More general bbox head, with shared conv and fc layers and two optional
separated branches.
.. code-block:: none
/-> cls convs -> cls fcs -> cls
shared convs -> shared fcs
\-> reg convs -> reg fcs -> reg
Add shared or separable branch
convs -> avg p... | 742 | en | 0.775052 |
import tempfile
import os
from PIL import Image
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APIClient
from core.models import Recipe, Tag, Ingredient
from recipe.serializers import Re... | app/recipe/tests/test_recipe_api.py | 9,890 | Test authenticated API access
Test unathenticated recipe API access
Return recipe detail URL
Return URL for recipe image upload
Create and return a sample ingredient
Create and return a sample recipe
Create and return a sample tag
Test that authentication is required
Test creating recipe
Test creating recipe with ingre... | 662 | en | 0.805994 |
# Copyright (c) 2021. Slonos Labs. All rights Reserved.
| app/base/gg.py | 57 | Copyright (c) 2021. Slonos Labs. All rights Reserved. | 53 | en | 0.892457 |
from django.conf.urls import include, url
from django.views.generic.base import TemplateView
from antioch.plugins.signup.views import ActivationView
from antioch.plugins.signup.views import RegistrationView
app_name='signup'
urlpatterns = [
url(r'^activate/complete/$',
TemplateView.as_view(template_name=... | antioch/plugins/signup/urls.py | 1,197 | Activation keys get matched by \w+ instead of the more specific [a-fA-F0-9]{40} because a bad activation key should still get to the view; that way it can return a sensible "invalid key" message instead of a confusing 404. | 222 | en | 0.790095 |
"""Trains a hypergraph machine on MNIST and generates Figure 1 panels b and c
of Discrete and continuous learning machines
"""
import numpy as np
import torch
import torch.nn.functional as F
from torchvision import datasets, transforms
from torch.optim.lr_scheduler import StepLR
from hypergraph_machines.hypergraph_mach... | hypergraph_machines/examples/generate_figure.py | 1,594 | Trains a hypergraph machine on MNIST and generates Figure 1 panels b and c
of Discrete and continuous learning machines | 119 | en | 0.922908 |
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 10 08:10:27 2018
@author: lenovo-pc
"""
file_path='D://aaa//kaifangX.txt'
email_path='D://aaa//99.txt'
file_path=open(file_path,'w',encoding='utf-8')
email_path=open(email_path,'w',encoding='utf-8')
for i in range(10000):
try:
c=b.readline().spl... | Frank.py | 438 | Created on Sun Jun 10 08:10:27 2018
@author: lenovo-pc
-*- coding: utf-8 -*- | 79 | en | 0.69951 |
from typing import Tuple, FrozenSet
from collections import Iterable
from mathsat import msat_term, msat_env
from mathsat import msat_make_constant, msat_declare_function
from mathsat import msat_get_integer_type, msat_get_rational_type, msat_get_bool_type
from mathsat import msat_make_and, msat_make_not, msat_mak... | benchmarks/f3_wrong_hints_permutations/scaling_ltl_infinite_state/17-extending_bound_30.py | 10,134 | r' = r i < l -> ((inc_i' & i' = i + 1) | (!inc_i' & i' = i)) & l' = l i >= l -> i' = 0 & l' = l + 1 & !inc_i' (G F inc_i) -> ! G F r > i | 136 | en | 0.457986 |
# coding: utf-8
"""
Isilon SDK
Isilon SDK - Language bindings for the OneFS API # noqa: E501
OpenAPI spec version: 9
Contact: sdk@isilon.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import isi_sdk_8_2_2
from i... | isi_sdk_8_2_2/test/test_cluster_firmware_status_node.py | 986 | ClusterFirmwareStatusNode unit test stubs
Test ClusterFirmwareStatusNode
Isilon SDK
Isilon SDK - Language bindings for the OneFS API # noqa: E501
OpenAPI spec version: 9
Contact: sdk@isilon.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
coding: utf-8 noqa: E501 FIXME: construct object with ma... | 457 | en | 0.431318 |
from argparse import ArgumentParser
import enum
from pathlib import Path
from matplotlib import pyplot as plt
from matplotlib.lines import Line2D
import numpy as np
import yaml
import pandas as pd
METRICS = ['total_L1', '0_to10mm_L1', '10_to20mm_L1', 'above20mm_L1']
METRICS_TITLE = ['L1Loss', 'L1Loss in [0,10) mm', ... | src/evaluate/plot_evaluation.py | 6,678 | leg.get_frame().set_alpha(None) leg.get_frame().set_facecolor((1, 1, 1, 0.5)) leg.get_frame().set_edgecolor('black') leg.get_frame().set_linewidth(0.5) sort first N models by loss 10 group by (title, it_ot) and create it/ot colors without i/t pairs without i/t pairs unsqueeze metrics list to rows metrics dict to column... | 438 | en | 0.187377 |
###########################################################################
#
# 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
#
# https://www.apache.org/l... | starthinker/task/dcm_api/schema/targetableRemarketingListsListResponse.py | 3,961 | 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 https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software dis... | 557 | en | 0.870924 |
from flask import Flask, request, jsonify
from flask_jsonrpc import JSONRPC
# import json_to_db
import psycopg2
import sys
from obs import *
import config
app = Flask(__name__)
app.config.from_object(config.DevelopmentMaxConfig)
jsonrpc = JSONRPC(app,'/api')
sys.path.insert(0,app.config['SQL_PATH'])
from sql_method... | server_data_tmp/app/local_server.py | 1,339 | import json_to_db print(content) json_insert.to_csv('/Users/MaximZubkov/Desktop/Programming/Python/Python_Project/analysis/son.csv') | 132 | en | 0.222447 |
# Copyright 2015: Mirantis Inc.
# 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 b... | rally/plugins/openstack/scenario.py | 3,320 | Base class for all OpenStack scenarios.
Returns a python admin openstack client of the requested type.
:param client_type: Client type ("nova"/"glance" etc.)
:param version: client version ("1"/"2" etc.)
:returns: Python openstack client object
Returns a python openstack client of the requested type.
The client will... | 1,295 | en | 0.745649 |
"""Tests for ArgComb. """
# pylint: disable=unused-argument, unused-variable
from typing import Any, Callable
import pytest
from argcomb import And, Else, InvalidArgumentCombination, Not, Or, Xor, argcomb
def test_default() -> None:
"""Test the ``default`` parameter of :function:``argcomb.__init__``.
Thi... | test.py | 8,368 | Test ``And`` condition.
Test when an argument is named ``default``.
This collides with a positional only argument named ``default`` in
the ``argcomb`` signature, but as this is positional only this
should not matter.
Test providing specifications for arguments.
Test that a warning is emitted when a function with two... | 1,310 | en | 0.536528 |
# -*- 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 o... | google/cloud/compute_v1/services/addresses/transports/base.py | 6,240 | Abstract transport class for Addresses.
Instantiate the transport.
Args:
host (Optional[str]): The hostname to connect to.
credentials (Optional[google.auth.credentials.Credentials]): The
authorization credentials to attach to requests. These
credentials identify the application to the service;... | 2,015 | en | 0.819033 |
#
# 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... | tests/providers/google/cloud/operators/test_bigquery.py | 39,192 | 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... | 1,043 | en | 0.87455 |
# Generated by Django 2.2.12 on 2020-11-10 19:36
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0039_auto_20201110_2132'),
]
operations = [
migrations.AlterField(
model_name='profile',
name='address_1',
... | core/migrations/0040_auto_20201110_2136.py | 691 | Generated by Django 2.2.12 on 2020-11-10 19:36 | 46 | en | 0.620136 |
""" http://www.python-course.eu/tkinter_layout_management.php """
from tkinter import *
root = Tk()
w = Label(root, text="Red Sun", bg="red", fg="white")
w.pack()
w = Label(root, text="Green Grass", bg="green", fg="black")
w.pack(ipadx=10)
w = Label(root, text="Blue Sky", bg="blue", fg="white")
w.pack()
mainloop()
| tktoolbox/examples/layout/pack_ipadx.py | 316 | http://www.python-course.eu/tkinter_layout_management.php | 57 | en | 0.165621 |
"""This is a python module containing a cog that implements commands that are
used to manage messages in the server.
e.g. "clear", delete all instances of a certain word, etc.
"""
import discord
from discord.ext import commands
import typing # For optional parameters.
import datetime # For comparing mess... | cogs/Message Management.py | 4,540 | This is a python module containing a cog that implements commands that are
used to manage messages in the server.
e.g. "clear", delete all instances of a certain word, etc.
For optional parameters. For comparing messages. Delete the message that invoked this command. Delete AMOUNT more messages. To keep track of how... | 1,099 | en | 0.919193 |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Power law model variants
"""
# pylint: disable=invalid-name
import numpy as np
from astropy.units import Quantity
from .core import Fittable1DModel
from .parameters import InputParameterError, Parameter
__all__ = ['PowerLaw1D', 'BrokenPowerLaw1D', '... | astropy/modeling/powerlaws.py | 20,593 | One dimensional power law model with a break.
Parameters
----------
amplitude : float
Model amplitude at the break point.
x_break : float
Break point.
alpha_1 : float
Power law index for x < x_break.
alpha_2 : float
Power law index for x > x_break.
See Also
--------
PowerLaw1D, ExponentialCutoffPowerL... | 8,261 | en | 0.612018 |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
http://www.scipy.org/Cookbook/Least_Squares_Circle
"""
from numpy import *
# Coordinates of the 2D points
# x = r_[ 9, 35, -13, 10, 23, 0]
# y = r_[ 34, 10, 6, -14, 27, -10]
x = r_[36, 36, 19, 18, 33, 26]
y = r_[14, 10, 28, 31, 18, 26]
# R0 = 25
# nb_pts ... | ipython/attachments/Least_Squares_Circle/least_squares_circle_v3.py | 7,700 | ! /usr/bin/env python -*- coding: utf-8 -*- Coordinates of the 2D points x = r_[ 9, 35, -13, 10, 23, 0] y = r_[ 34, 10, 6, -14, 27, -10] R0 = 25 nb_pts = 8 dR = 2 angle =9*pi/5 x = (10 + R0*cos(theta0) + dR*random.normal(size=nb_pts)).round() y = (10 + R0*sin(theta0) + dR*random.normal(size=nb_pts)).round() == ... | 1,137 | en | 0.666842 |
import click
from config.settings import app
@click.group()
def cli():
"""
Serves the application for testing locally. If you want to test it
in a production like environment, please deploy with Docker.\n
:return: Application instance
"""
click.echo('\033[95mINFO: Starting the app..\033[0m')
... | cli/commands/cmd_serve.py | 336 | Serves the application for testing locally. If you want to test it
in a production like environment, please deploy with Docker.
:return: Application instance | 158 | en | 0.91778 |
# MIT License, Copyright (c) 2020 Bob van den Heuvel
# https://github.com/bheuvel/transip/blob/main/LICENSE
"""Interface with the TransIP API, specifically DNS record management."""
import logging
from enum import Enum
from pathlib import Path
from time import sleep
from typing import Dict, Union
import requests
from... | transip_dns/transip_interface.py | 13,214 | Class matching the TransIP dnsEntry.
DNS Record encapsulation with ip query and data checking.
Initializes the object, potentially search for the IP address and
check if the record type is allowed.
:param DnsEntry: Parent class to enhance
:type DnsEntry: DnsEntry
Provided private_key is is not a valid path, nor a val... | 5,705 | en | 0.684958 |
# Generated by Django 2.2.1 on 2019-09-07 11:44
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('incidents', '0008_auto_20190829_1231'),
]
operations = [
migrations.AlterModelOptions(
name='incident',
options={'ordering':... | backend/src/incidents/migrations/0009_auto_20190907_1144.py | 551 | Generated by Django 2.2.1 on 2019-09-07 11:44 | 45 | en | 0.580023 |
# -*- coding: utf-8 -*-
from django import forms
from django.forms.widgets import RadioSelect
from .models import Rating
class FlagForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user')
self.object = kwargs.pop('object')
super().__init__(*args, **kwargs)
if not self.inst... | rating/forms.py | 1,105 | -*- coding: utf-8 -*- | 21 | en | 0.767281 |
# 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
# -- Project information -----------------------------------------------------
project... | docs/conf.py | 1,233 | 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 -- Project information ----------------------------------------------------- -- General configurat... | 880 | en | 0.654278 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import nonebot
from nonebot.adapters.cqhttp import Bot as CQHTTPBot, message
# 初始化nb
nonebot.init()
# 连接驱动
driver = nonebot.get_driver()
driver.register_adapter("cqhttp", CQHTTPBot)
# 加载插件(除此处其他配置不建议更改)
nonebot.load_builtin_plugins()
nonebot.load_plugins('src/plugins')
... | bot.py | 744 | !/usr/bin/env python3 -*- coding: utf-8 -*- 初始化nb 连接驱动 加载插件(除此处其他配置不建议更改) | 73 | zh | 0.696121 |
# -*- encoding: utf-8 -*-
"""
Created by eniocc at 11/10/2020
"""
from py_dss_interface.models.XYCurves.XYCurvesF import XYCurvesF
from py_dss_interface.models.XYCurves.XYCurvesI import XYCurvesI
from py_dss_interface.models.XYCurves.XYCurvesS import XYCurvesS
from py_dss_interface.models.XYCurves.XYCurvesV import XY... | src/py_dss_interface/models/XYCurves/XYCurves.py | 632 | This interface implements the XYCurves (IXYCurves) interface of OpenDSS by declaring 4 procedures for accessing
the different properties included in this interface: XYCurvesS, XYCurvesI, XYCurvesF, XYCurvesV.
Created by eniocc at 11/10/2020
-*- encoding: utf-8 -*- | 266 | en | 0.909637 |
from test.integration.base import DBTIntegrationTest, use_profile
class BaseTestSimpleDependencyWithConfigs(DBTIntegrationTest):
def setUp(self):
DBTIntegrationTest.setUp(self)
self.run_sql_file("seed.sql")
@property
def schema(self):
return "simple_dependency_006"
@property... | test/integration/006_simple_dependency_test/test_simple_dependency_with_configs.py | 6,132 | project-level configs This feature doesn't exist in v2! model-level configs config is v1, can't use strict here disable config model, but supply vars disable the table model override materialization settings config is v1, can't use strict here config, table are disabled | 270 | en | 0.852129 |
import requests
from news_api.settings.Vespa_config import VESPA_IP, VESPA_PORT
import json
from ast import literal_eval
def GenerateDateParamYql(params):
"""[Check consistency in date parameterGenerate the date yql parameters]
Arguments:
params {[type]} -- [description]
Returns:
... | news_api/endpoints/vespaSearcher.py | 3,406 | [Check consistency in date parameterGenerate the date yql parameters]
Arguments:
params {[type]} -- [description]
Returns:
[type] -- [description]
[Generator of YQL vespa query, to have a refine request on the vespa cluster]
In this case, the YQL depends on the search definition of the document type in the ve... | 1,157 | en | 0.532022 |
#@title 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distribute... | flowers_tf_lite.py | 6,055 | @title 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 https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is... | 939 | en | 0.82246 |
import importlib
import json
from inspect import iscoroutine
from json import JSONDecodeError
from typing import Any, Callable, Dict, List, Union
from loguru import logger
from parse import parse
from pydantic import BaseModel, validator
class Moshi(BaseModel):
call: Union[str, Callable]
args: L... | moshimoshi/__init__.py | 2,468 | TODO: after read it still in doubt what is the best test hypothesis if to is a json prioritize args and kwargs | 110 | en | 0.905809 |
#!/usr/bin/python
r"""
Contains PLDM-related constants.
"""
PLDM_SUPPORTED_TYPES = ['base', 'platform', 'bios', 'fru', 'oem-ibm']
# PLDM types.
PLDM_TYPE_BASE = {'VALUE': '00', 'STRING': 'base'}
PLDM_TYPE_PLATFORM = {'VALUE': '02', 'STRING': 'platform'}
PLDM_TYPE_BIOS = {'VALUE': '03', 'STRING': 'bios'}
PLDM_TYPE_FR... | data/pldm_variables.py | 7,356 | Contains PLDM-related constants.
!/usr/bin/python PLDM types. PLDM command format. PLDM command payload data. %(TransferOperationFlag, PLDMType) GetPDR parsed response message for record handle. Dictionary value array holds the expected output for record handle 1, 2. Note : Record handle - 0 is default & has sam... | 407 | en | 0.781366 |
import logging
import pytest
from collections import namedtuple, Counter
from tests.platform_tests.counterpoll.cpu_memory_helper import restore_counter_poll # lgtm [py/unused-import]
from tests.platform_tests.counterpoll.cpu_memory_helper import counterpoll_type # lgtm [py/unused-import]
from tests.platform_test... | tests/platform_tests/test_cpu_memory_usage.py | 11,172 | This method it to extract the valid cpu usage data according to the poll_interval
1. Find the index for the max one for every poll interval,
2. Discard the data if the index is on the edge(0 o the length of program_to_check_cpu_usage -1)
3. If the index is closed in the neighbour interval, only keep the former one
4. R... | 1,110 | en | 0.794864 |
#!/usr/bin/python
import sys
import os
import tkinter
import joblib
import pathlib
from PIL import Image, ImageTk
from PIL.ExifTags import TAGS
from pathlib import Path
from collections import deque
# Built based off of: https://github.com/Lexing/pyImageCropper
# ====================================================... | pyImageCropper/pyImageCropper.py | 12,269 | Image canvas area of the GUI
Main module class
Stores data about the current state
creates the box for the crop rectangle x1,y1,x2,y2
get filename from path
if mouse clicked on crop area, allow moving crop
move crop along with the user's mouse
stop allowing movement of crop area
check if point is on the image
re-b... | 2,393 | en | 0.768206 |
# -*- coding: utf-8 -*-
from gluon import *
from s3 import S3CustomController
THEME = "historic.CERT"
# =============================================================================
class index(S3CustomController):
""" Custom Home Page """
def __call__(self):
response = current.response
res... | modules/templates/historic/CERT/controllers.py | 3,761 | Custom Home Page
-*- coding: utf-8 -*- ============================================================================= Check logged in and permissionsauth = current.authroles = current.session.s3.rolessystem_roles = auth.get_system_roles()ADMIN = system_roles.ADMINAUTHENTICATED = system_roles.AUTHENTICATEDhas_role = a... | 413 | en | 0.452296 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.