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 |
|---|---|---|---|---|---|---|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import cv2
import numpy as np
from math import cos, sin, pi
from tqdm import tqdm
import open3d as o3d
def render(pointcloud_file_path, estimate_normals_radius, estimate_normals_max_nn):
pointcloud = o3d.io.read_point_cloud(pointcloud_file_path, print_progress=True)
... | PointCloudClass/renderer.py | 7,244 | !/usr/bin/env python -*- coding: utf-8 -*- ctr.set_zoom(0.5) self.vis.update_geometry() self.vis.update_geometry() | 117 | es | 0.093506 |
# 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,... | scripts/proteinInteractionEBI/parse_ebi_test.py | 5,814 | Test the functions in parse_ebi.py
Ruturns a list of text blocks.
Test TreeBuilder class.
Test function build_child_parent_link by checking the values of
child_list and parent_list.
Test function get_id_maps. Note that id_to_node here doesn't have parent_child
relation, so only map keys are tested.
Test function get_sc... | 971 | en | 0.787593 |
import os
import pathlib
from dotenv import load_dotenv, find_dotenv
from fpdf import FPDF
#envelope size: 110 by 145 mm
# Elliot Torres
# 4321 Loser Road
# La Crescenta, CA 91214
#
# Ryan Lee
# 1234 Boomer Road
# La Crescenta, CA 91214
load_dotenv(find_dotenv())
# types out address on envelope
def sendmail(
... | bdaybot/snailmail.py | 1,836 | envelope size: 110 by 145 mm Elliot Torres 4321 Loser Road La Crescenta, CA 91214 Ryan Lee 1234 Boomer Road La Crescenta, CA 91214 types out address on envelope types out message on back fo envelope | 198 | en | 0.638595 |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class BST:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
# Average: O(log(n)) time | O... | leetcode.com/python/98_Validate_Binary_Search_Tree.py | 2,208 | :type root: TreeNode
:rtype: bool
Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None Average: O(log(n)) time | O(1) space Worst: O(n) time | O(1) space driver/test code test_tree = BST(100).insert(5).insert(15).... | 602 | zh | 0.099228 |
from enum import Enum
from typing import List, Optional, Type, Union
import click
from ..types import NotSet
class CSVOption(click.Choice):
def __init__(self, choices: Type[Enum]):
self.enum = choices
super().__init__(tuple(choices.__members__))
def convert(
self, value: str, param:... | src/schemathesis/cli/options.py | 1,392 | Sort to keep the error output consistent with the passed values type: ignore | 76 | en | 0.618907 |
import nltk
# nltk.download('stopwords') #if doesnt work download all these first
# nltk.download('punkt')
# nltk.download('averaged_perceptron_tagger')
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize, sent_tokenize
stop_words = set(stopwords.words('english'))
meaning_with_example = {
... | part_of_speech.py | 3,323 | nltk.download('stopwords') if doesnt work download all these first nltk.download('punkt') nltk.download('averaged_perceptron_tagger')print(get_part_of_speech("Sukanya, Rajib and Naba are my good friends.")) | 207 | en | 0.658869 |
from __future__ import print_function
import sys
from metapub import PubMedFetcher
from metapub import FindIt
# examples of different formats:
# 18612690: PubMedArticle with multiple AbstractText sections
# 1234567: PubMedArticle with no abstract whatsoever
# 20301546: PubMedBookArticle from GeneReviews
####
impor... | bin/demo_get_PubMedArticle_by_pmid.py | 2,304 | examples of different formats: 18612690: PubMedArticle with multiple AbstractText sections 1234567: PubMedArticle with no abstract whatsoever 20301546: PubMedBookArticle from GeneReviews | 187 | en | 0.569475 |
from skimage.measure import find_contours
from skimage import io
from skimage.color import rgb2gray
from matplotlib import pyplot as plt
image = io.imread('contour_finding_test.png')
# image = io.imread('FlowchartDiagram.png')
image = rgb2gray(image)
out = find_contours(image)
print(len(out))
# Find contours at a con... | pyimage/contour.py | 698 | image = io.imread('FlowchartDiagram.png') Find contours at a constant value of 0.8 contours = find_contours(image, 0.8) Display the image and plot all contours found io.imshow(image) io.show() | 192 | en | 0.572217 |
import numpy as np
from numpy import (reciprocal, einsum, maximum, minimum, zeros_like,
atleast_1d, squeeze)
from scipy.linalg import eig, eigvals, matrix_balance, norm
from harold._classes import Transfer, transfer_to_state
from harold._discrete_funcs import discretize
from harold._arg_utils import ... | harold/_time_domain.py | 18,814 | Helper function for simple and rather expensive checks for sanity
Helper function to validate the input arguments for simulate_linear_system
Helper function to estimate a final time and a sampling period for
time domain simulations. It is essentially geared towards impulse response
but is also used for step responses.
... | 7,934 | en | 0.850075 |
#
# Copyright 2020 Logical Clocks AB
#
# 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 ag... | python/hsfs/constructor/join.py | 2,092 | Copyright 2020 Logical Clocks AB 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, so... | 572 | en | 0.862541 |
import tensorflow as tf
import tensorflow.contrib.slim as slim
from tflearn.layers.conv import global_avg_pool
#######################
# 3d functions
#######################
# convolution
# 3D unet graph
def unet(inputI, output_channel):
"""3D U-net"""
phase_flag = 1
concat_dim = 4
conv1_1 = conv3d(
... | src/models.py | 22,145 | 3D U-net
3d functions convolution 3D unet graph conv1_1 (1, 96, 96, 96, 64) pool1 (1, 48, 48, 48, 64) pool1_frac = fractal_net( is_global_path_list[0], global_path_list[0], local_path_list[0], self.Blocks, self.Columns)(pool1_in) pool1_old = pool1_in + pool1_frac (1, 48, 48, 48, 128) pool2 (1, 24... | 2,662 | en | 0.476453 |
#!/usr/bin/env python2
# -*- encoding: utf-8 -*-
import pygame
import sys
import numpy as np
CONST_LOCK_FILE = "lock.txt"
#CONST_GRAPH_FILE = "../tsptours/graph.tsp"
CONST_GRAPH_FILE = "graph.tsp"
CONST_STOP = "STOP"
CONST_CUSTOM_FILE = None
def main():
pygame.init()
screen = pygame.display.set_mode((700,7... | graphic/tsp_matt.py | 4,156 | !/usr/bin/env python2 -*- encoding: utf-8 -*-CONST_GRAPH_FILE = "../tsptours/graph.tsp"print "Agregando la posición del click", pygame.mouse.get_pos()print "Agregando la posición del click", pygame.mouse.get_pos()print "%d %d %d" % (x, graph[x][0], graph[x][1]) Primera salida. [0, .., n-1, n] Costo del recorrido Cantid... | 386 | es | 0.609246 |
def extractReMonsterWiki(item):
"""
Parser for 'Re:Monster Wiki'
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or 'preview' in item['title'].lower():
return None
if 'WATTT' in item['tags']:
return buildReleaseMessageWithType(item, 'WATTT', vol, chp, frag=fra... | WebMirror/management/rss_parser_funcs/feed_parse_extractReMonsterWiki.py | 354 | Parser for 'Re:Monster Wiki' | 28 | en | 0.225286 |
#!/usr/bin/python
# coding: utf-8 -*-
# (c) 2017, Wayne Witzel III <wayne@riotousliving.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1... | awx_collection/plugins/modules/tower_job_template.py | 13,457 | This updates the module field names
to match the field names tower-cli expects to make
calling of the modify/delete methods easier.
!/usr/bin/python coding: utf-8 -*- (c) 2017, Wayne Witzel III <wayne@riotousliving.com> GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) unset em... | 398 | en | 0.55826 |
from django.db import models
from django.conf import settings
from django.contrib.auth.models import User
from django.db.models.signals import post_save
# Create your models here.
class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL)
date_of_birth = models.DateField(blank=True, null=Tru... | account/models.py | 1,364 | Create your models here. Signal to auto-create a profile when a User is created. | 80 | en | 0.946935 |
# -*- coding: utf-8 -*-
from irc3.plugins.command import command
@command
def echo(bot, mask, target, args):
"""Echo command
%%echo <words>...
"""
yield ' '.join(args['<words>'])
@command(permission='admin', public=False)
def adduser(bot, mask, target, args):
"""Add a user
%%adduse... | examples/mycommands.py | 598 | Add a user
%%adduser <name> <password>
Echo command
%%echo <words>...
Do something you don't want in !help all the time
%%my_secret_operation
-*- coding: utf-8 -*- | 168 | en | 0.696732 |
###########################################################################
#
# 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/util/salesforce/quickstart.py | 1,010 | 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 |
# Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
from metrics import power
from telemetry import test
from telemetry.core import util
from telemetry.page import page_measurement
from telemetr... | tools/perf/benchmarks/dromaeo.py | 4,824 | Copyright (c) 2013 The Chromium Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. Subclasses are expected to define a class member called query_param. The docstring of benchmark classes may also be used as a description when 'run_benchmarks l... | 332 | en | 0.933413 |
# ------------------------------------------------------------------------------------------------------
# Copyright (c) Leo Hanisch. All rights reserved.
# Licensed under the BSD 3-Clause License. See LICENSE.txt in the project root for license information.
# ---------------------------------------------------------... | swarmlib/cuckoosearch/cuckoo_problem.py | 3,592 | Initialize a new cuckoo search problem.
Start the problems visualization.
------------------------------------------------------------------------------------------------------ Copyright (c) Leo Hanisch. All rights reserved. Licensed under the BSD 3-Clause License. See LICENSE.txt in the project root for license in... | 686 | en | 0.538671 |
import os
import tensorflow as tf
from merge.model import Model
def run_model_on_random_input(model):
batch_size = 1
height = 100
width = 200
inputs = {
'image': tf.random.uniform(shape=(batch_size, height, width, 3), minval=0, maxval=256, dtype='int32'),
'horz_split_points_probs': tf... | merge/evaluation.py | 1,474 | Metric can't be calculated in graph mode. | 41 | en | 0.981942 |
"""
Mplot demo runner
"""
import enaml
from enaml.qt.qt_application import QtApplication
def run_demo():
with enaml.imports():
#from griddata_demo_ui import Main
from griddata_demo_model_ui import Main
app = QtApplication()
view = Main(custom_title='Matplotlib demo', mplot_style='darkis... | tutorial/grid_data_demo_run.py | 409 | Mplot demo runner
from griddata_demo_ui import Main Start the application event loop | 85 | en | 0.801937 |
import os
import tempfile
from tests.STDF.STDFRecordTest import STDFRecordTest
from STDF import FAR
# File Attributes Record
# Functuion:
# Contains the information necessary to determine
# how to decode the STDF datacontained in the file.
def test_FAR():
far('<')
far('>')
def far(end):
# STDF v4... | tests/STDF/test_FAR.py | 1,563 | File Attributes Record Functuion: Contains the information necessary to determine how to decode the STDF datacontained in the file. STDF v4 page 57 Test serialization 1. Save FAR STDF record into a file 2. Read byte by byte and compare with expected value rec_len, rec_type, rec_sub Test REC_CPU, e... | 648 | en | 0.548751 |
#!/usr/bin/env python3
import sys
import re
class Num:
def __init__(self, value):
self.value = value
def __add__(self, num):
return Num(self.value * num.value)
def __mul__(self, num):
return Num(self.value + num.value)
s = 0
for line in sys.stdin:
line = line.replace("+", "... | problems/day-18/part_2.py | 441 | !/usr/bin/env python3 | 21 | fr | 0.448822 |
# -*- coding: utf-8 -*-
import warnings
# warnings.filterwarnings("ignore") # 抑制告警,并指定采取的措施
warnings.warn("# This is a test warning 111.")
print("Hello One")
warnings.filterwarnings("ignore", category=DeprecationWarning) # 抑制特定类型的警告
warnings.warn("# This is a test warning 222.", DeprecationWarning) # 被抑制
... | Python3-Basics/Chapter11_Exception02_Warning.py | 869 | -*- coding: utf-8 -*- warnings.filterwarnings("ignore") 抑制告警,并指定采取的措施 抑制特定类型的警告 被抑制 未被抑制 将警告转换为错误 指定引发的异常 警告 警告不是异常,不影响程序的运行,可用于指示程序的状态; 可根据异常来过滤掉特定类型的警告; 发出警告时,可指定引发的异常(告警类别必须是Warning的子类); | 192 | zh | 0.978973 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Script to Test Deep Learning Model.
Contains a pipeline to test a deep learning model.
Revision History:
2021-11-20 (ANI717 - Animesh Bala Ani): Baseline Software.
Example:
$ python3 test.py
"""
#___Import Modules:
import torch
from torch.utils.dat... | deep learning/test/test.py | 2,083 | Script to Test Deep Learning Model.
Contains a pipeline to test a deep learning model.
Revision History:
2021-11-20 (ANI717 - Animesh Bala Ani): Baseline Software.
Example:
$ python3 test.py
!/usr/bin/env python -*- coding: utf-8 -*-___Import Modules:___Main Method: Load Data Initialize Model with W... | 611 | en | 0.640964 |
# -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/stable/config
# -- Path setup ------------------------------------------------------------... | docs/source/conf.py | 6,439 | -*- coding: utf-8 -*- Configuration file for the Sphinx documentation builder. This file does only contain a selection of the most common options. For a full list see the documentation: http://www.sphinx-doc.org/en/stable/config -- Path setup -------------------------------------------------------------- If extensions ... | 4,305 | en | 0.612787 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 5/15/20 4:49 PM
# @File : grover.py
# qubit number=4
# total number=8
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.Cir... | data/cirq_new/cirq_program/startCirq_Class18.py | 1,584 | !/usr/bin/env python -*- coding: utf-8 -*- @Time : 5/15/20 4:49 PM @File : grover.py qubit number=4 total number=8thatsNoCode circuit begin number=1 number=2 number=5 number=3 number=4 number=6 number=7 circuit end | 220 | en | 0.336016 |
# simple example demonstrating how to control a Tello using your keyboard.
# For a more fully featured example see manual-control-pygame.py
#
# Use W, A, S, D for moving, E, Q for rotating and R, F for going up and down.
# When starting the script the Tello will takeoff, pressing ESC makes it land
# and the script ex... | examples/manual-control-opencv.py | 2,264 | simple example demonstrating how to control a Tello using your keyboard. For a more fully featured example see manual-control-pygame.py Use W, A, S, D for moving, E, Q for rotating and R, F for going up and down. When starting the script the Tello will takeoff, pressing ESC makes it land and the script exit. 简单的演示如何用... | 836 | en | 0.517609 |
# -*- coding: utf-8 -*-
"""Base exchange class"""
# -----------------------------------------------------------------------------
__version__ = '1.17.322'
# -----------------------------------------------------------------------------
from ccxt.base.errors import ExchangeError
from ccxt.base.errors import NetworkE... | python/ccxt/base/exchange.py | 64,385 | Base exchange class
Checks an address is not the same character repeated or an empty sequence
Perform a HTTP request and return decoded JSON data
A better wrapper over request for deferred signing
A helper method for matching error strings exactly vs broadly
A helper-wrapper for the safe_value_2() family.
Deprecated, u... | 6,793 | en | 0.513076 |
from pydub import AudioSegment
from pydub.playback import play
import os
import utils
class audiofile:
def __init__(self, file):
""" Init audio stream """
self.file = file
def play(self):
""" Play entire file """
utils.displayInfoMessage('Playing Audio')
pathpa... | AudioFile.py | 753 | Init audio stream
Play entire file | 35 | en | 0.845398 |
"""Tasmota MQTT."""
import asyncio
import logging
from typing import Union
import attr
from .const import COMMAND_BACKLOG
DEBOUNCE_TIMEOUT = 1
_LOGGER = logging.getLogger(__name__)
class Timer:
"""Simple timer."""
def __init__(self, timeout, callback):
self._timeout = timeout
self._callba... | hatasmota/mqtt.py | 2,424 | MQTT Message.
Helper class to sue an external MQTT client.
Simple timer.
Initialize.
Cancel the timer.
Publish a message.
Publish a message, with debounce.
Send a sequence of commands.
Tasmota MQTT. | 198 | en | 0.751326 |
from gym_multigrid.multigrid import *
class CollectGameEnv(MultiGridEnv):
"""
Environment in which the agents have to collect the balls
"""
def __init__(
self,
size=10,
width=None,
height=None,
num_balls=[],
agents_index = [],
balls_index=[],
... | gym_multigrid/envs/collect_game.py | 2,795 | Environment in which the agents have to collect the balls
Compute the reward to be given upon success
Set this to True for maximum speed Generate the surrounding walls Randomize the player start position and orientation | 221 | en | 0.886428 |
# ble_command_load_group.py/Open GoPro, Version 2.0 (C) Copyright 2021 GoPro, Inc. (http://gopro.com/OpenGoPro).
# This copyright was auto-generated on Wed, Sep 1, 2021 5:05:57 PM
import sys
import asyncio
import logging
import argparse
from typing import Optional
from binascii import hexlify
from bleak import Blea... | demos/python/tutorial/tutorial_modules/tutorial_2_send_ble_commands/ble_command_load_group.py | 2,376 | ble_command_load_group.py/Open GoPro, Version 2.0 (C) Copyright 2021 GoPro, Inc. (http://gopro.com/OpenGoPro). This copyright was auto-generated on Wed, Sep 1, 2021 5:05:57 PM Synchronization event to wait until notification response is received UUIDs to write to and receive responses from If this is the correct hand... | 550 | en | 0.929134 |
import inspect
from collections import OrderedDict
from json.decoder import JSONDecodeError
from typing import Optional, Tuple, Union
from urllib.parse import urljoin
import requests
from bs4 import BeautifulSoup
from recipe_scrapers.settings import settings
from ._schemaorg import SchemaOrg
# some sites close thei... | recipe_scrapers/_abstract.py | 4,871 | get the host of the url, so we can use the correct scraper
Human language the recipe is written in.
May be overridden by individual scrapers.
total time it takes to preparate the recipe in minutes
The number of servings or items in the recipe
some sites close their content for 'bots', so user-agent must be suppli... | 878 | en | 0.744557 |
# Copyright 2015 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/ops/nn.py | 51,131 | Helper function for nce_loss and sampled_softmax_loss functions.
Computes sampled output training logits and labels suitable for implementing
e.g. noise-contrastive estimation (see nce_loss) or sampled softmax (see
sampled_softmax_loss).
Note: In the case where num_true > 1, we assign to each target class
the target ... | 33,307 | en | 0.770274 |
"""Benchmarks of Lasso regularization path computation using Lars and CD
The input data is mostly low rank but is a fat infinite tail.
"""
from collections import defaultdict
import gc
import sys
from time import time
import numpy as np
from sklearn.linear_model import lars_path, lars_path_gram
from sklearn.linear_m... | benchmarks/lasso_replicas/bench_plot_lasso_path_83.py | 3,979 | Benchmarks of Lasso regularization path computation using Lars and CD
The input data is mostly low rank but is a fat infinite tail.
'effective_rank': None, precomputed Gram matrix register the 3d projection plot the actual surface dummy point plot to stick the legend to since surface plot do not support legends (yet?... | 388 | en | 0.704973 |
# -*- encoding: utf-8 -*-
import re
from oops.utils import sudo_support
@sudo_support
def match(command, settings):
return ('command not found' in command.stderr.lower()
and u' ' in command.script)
@sudo_support
def get_new_command(command, settings):
return re.sub(u' ', ' ', command.script)
| oops/rules/fix_alt_space.py | 320 | -*- encoding: utf-8 -*- | 23 | en | 0.76908 |
from mmcv.cnn import ConvModule
from torch import nn
from torch.utils import checkpoint as cp
from .se_layer import SELayer
class InvertedResidual(nn.Module):
"""InvertedResidual block for MobileNetV2.
Args:
in_channels (int): The input channels of the InvertedResidual block.
out... | mmseg/models/utils/inverted_residual.py | 7,213 | InvertedResidual block for MobileNetV2.
Args:
in_channels (int): The input channels of the InvertedResidual block.
out_channels (int): The output channels of the InvertedResidual block.
stride (int): Stride of the middle (first) 3x3 convolution.
expand_ratio (int): Adjusts number of channels of the hid... | 2,014 | en | 0.606077 |
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import pandas as pd
import json
import glob
import os
import argparse
from typing import Tuple, Union, List
from collections import Counter
from tqdm import tqdm
from multiprocessing import Pool
pd.options.mode.chained_assignment = None # defa... | analyze_dataset.py | 12,428 | Use the preloads file to load the data; will be augmented, as that's what we did
Get the index and directions from the df of the actions taken by the client
Get a single data from the given file.json path
Get a DataFrame from all the can_bus*.json files in the dataset
Plot the steer, throttle, brake, and speed of a cli... | 2,439 | en | 0.770533 |
#! /usr/bin/env python
#coding=utf-8
import ply.lex as lex
# LEX for parsing Python
# Tokens
tokens=('VARIABLE','NUMBER', 'IF', 'ELIF', 'ELSE', 'WHILE', 'FOR', 'PRINT', 'INC', 'LEN', 'GDIV', 'BREAK', 'LET')
literals=['=','+','-','*','(',')','{','}','<','>', ';', ',', '[', ']']
#Define of tokens
def t... | py_lex.py | 1,037 | break
elif
else
for
//
if
\+\+
len
<=
[0-9]+
print
[a-zA-Z_]+
while
! /usr/bin/env pythoncoding=utf-8 LEX for parsing Python TokensDefine of tokens Ignored | 156 | en | 0.41487 |
#from collections import Counter
import requests
from bs4 import BeautifulSoup
from tabulate import tabulate
import backoff
import json
@backoff.on_exception(backoff.expo,
requests.exceptions.RequestException,
max_time=60)
def get_url(url):#, headers):
return reques... | scrapers/get_collections.py | 1,844 | from collections import Counter, headers):, headers=headers)print(table.prettify()) | 83 | en | 0.512766 |
"""This script runs code quality checks on given Python files.
Note: This script assumes you use Poetry as your dependency manager.
Run the following in your terminal to get help on how to use this script:
```shell
poetry run python check_commit.py -h
```
"""
import argparse
import subprocess
from colorama import ... | check_commit.py | 2,872 | Run a task in the shell, defined by a task message and its associated
command.
This script runs code quality checks on given Python files.
Note: This script assumes you use Poetry as your dependency manager.
Run the following in your terminal to get help on how to use this script:
```shell
poetry run python check_com... | 454 | en | 0.7549 |
#!/usr/bin/env python3
# coding=utf8
from soco import SoCo
import socket
# http://docs.python-soco.com/en/latest/getting_started.html
class SpeakerSonos:
def __init__(self):
print("SpeakerSonos initialized!")
def do(self, params):
speaker = SoCo(socket.gethostbyname(params['host']))
p... | plugins/speaker_sonos.py | 1,115 | !/usr/bin/env python3 coding=utf8 http://docs.python-soco.com/en/latest/getting_started.html | 92 | en | 0.175009 |
import os
'''
TableData deals with data that comes from MS Excel, csv, xml. More precisely, it expects
a single table which has headings in the first row. It converts between these formats and usually keeps
information on a round trip between those formats identical.
TableData also allows for simple transformations,... | TableData.py | 15,407 | Parses old excel file into tableData object. Only first sheet.
Dont use this directly, use
td=TableData('xsl', infile)
td=TableData.load=table(infile)
instead
xlrd uses UTF16. What comes out of here?
TO DO:
1. better tests for
-Unicode issues not tested
-Excel data fields change appearance
2. conversion/tr... | 3,883 | en | 0.722777 |
# Copyright 2013-2019 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Prank(Package):
"""A powerful multiple sequence alignment browser."""
homepage = "htt... | var/spack/repos/builtin/packages/prank/package.py | 1,234 | A powerful multiple sequence alignment browser.
Copyright 2013-2019 Lawrence Livermore National Security, LLC and other Spack Project Developers. See the top-level COPYRIGHT file for details. SPDX-License-Identifier: (Apache-2.0 OR MIT) for bppancestor | 254 | en | 0.68961 |
import pytest
import math
import os
import sys
module_dir = os.path.dirname(__file__)
sys.path.append(os.path.join(module_dir, '..', 'intervalpy'))
from intervalpy import Interval
def test_intersection():
# closed, closed
d1 = Interval(0, 2, start_open=False, end_open=False)
d2 = Interval(1, 3, start_open... | test/interval_test.py | 9,066 | closed, closed closed, open open, open Empty intervals are always equal | 71 | en | 0.955017 |
# coding: utf-8
"""
Cherwell REST API
Unofficial Python Cherwell REST API library. # noqa: E501
The version of the OpenAPI document: 9.3.2
Contact: See AUTHORS.
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import re # noqa: F401
# python 2 and pyth... | pycherwell/api/teams_api.py | 94,300 | NOTE: This class is auto generated by OpenAPI Generator
Ref: https://openapi-generator.tech
Do not edit the class manually.
Add users to a team by batch # noqa: E501
Operation to add users to a Team by batch. To get internal IDs for users, use “Get User Information in a Batch.” To get a Team's internal ID, use "Get ... | 46,094 | en | 0.702382 |
#!/usr/bin/env python3
# Copyright (c) 2014-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Base class for RPC testing."""
from collections import deque
from enum import Enum
import logging
impo... | test/functional/test_framework/test_framework.py | 19,453 | Base class for a bitcoin test script.
Individual bitcoin test scripts should subclass this class and override the following methods:
- __init__()
- add_options()
- setup_chain()
- setup_network()
- run_test()
The main() method should not be overridden.
This class also contains various public and private helper meth... | 3,478 | en | 0.821795 |
# -*- coding: utf-8 -*-
"""
@author: alex
"""
import numpy as np
def main():
"""Main program execution."""
n,h1,h2,h3 = generate_ammonia_sites()
nList = [[1,2,3],[0],[0],[0]]
return [n,h1,h2,h3], nList
def generate_ammonia_sites():
"""Generate the locations for the atoms in the amm... | kappa/lattice/ammonia.py | 626 | Generate the locations for the atoms in the ammonia molecule
Main program execution.
@author: alex
-*- coding: utf-8 -*-atomic distance (angstroms) | 149 | en | 0.762434 |
# -*- coding: utf-8 -*-
# an ugly hack to convert some stuff into other stuff...
# EDIT THESE #####################################################################
names_to_highlight = ['Eren AM',
'Delmont TO',
'Esen ÖC',
'Lee STM',
... | pubs.py | 10,446 | Takes an EndNote library exported a TXT file (`pubs_file_path`), and an optional TAB-delimited info file path with DOI identifiers (`pubs_info_file_path`), and generates some Markdown formatted output.
Here is an info line from the EndNote:
Winterberg, K. M., and Reznikoff, W. S. (2007). "Scr... | 1,546 | en | 0.549922 |
# MIT License
# Copyright (c) 2020 Andrew Wells
# 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, p... | gridworld_hallways/make_grid_mdp.py | 5,746 | MIT License Copyright (c) 2020 Andrew Wells Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distri... | 1,093 | en | 0.858594 |
# pylint: disable=redefined-outer-name
from .utils import TestCase
from .utils import run_tests_assert_success
import itertools
import os
import slash
import pytest
from .utils.suite_writer import Suite
@pytest.mark.parametrize('parametrize', [True, False])
def test_class_name(suite, suite_test, test_type, parametri... | tests/test_test_metadata.py | 6,202 | pylint: disable=redefined-outer-name pragma: no cover pylint: disable=unused-variable pylint: disable=len-as-condition we can't verify result because we would not be able to parse the function properly TODO: this will change once we properly support variations metadata pylint: disable=fixme pylint: disable=unused-arg... | 432 | en | 0.64426 |
# Time: O(n)
# Space: O(1)
#
# You are climbing a stair case. It takes n steps to reach to the top.
#
# Each time you can either climb 1 or 2 steps.
# In how many distinct ways can you climb to the top?
class Solution:
"""
:type n: int
:rtype: int
"""
def climbStairs(self, n):
prev, cur... | Python/climbing-stairs.py | 698 | Time: O(n) Space: O(1) You are climbing a stair case. It takes n steps to reach to the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? | 191 | en | 0.948134 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# $Id$
#
# Project: GDAL/OGR Test Suite
# Purpose: Style testing.
# Author: Even Rouault <even dot rouault at mines dash paris dot org>
#
###################################################... | autotest/ogr/ogr_style.py | 5,137 | !/usr/bin/env python -*- coding: utf-8 -*- $Id$ Project: GDAL/OGR Test Suite Purpose: Style testing. Author: Even Rouault <even dot rouault at mines dash paris dot org> Copyright (c) 2014, Even Rouault <even dot rouault at mines-paris dot org> Permission is hereby granted, free of charge, to any person obtaining ... | 1,378 | en | 0.834312 |
import os.path
import time
from resource_management.core.exceptions import Fail
from resource_management.core.source import Template
from resource_management.core.source import StaticFile
from resource_management.core.source import DownloadSource
from resource_management.core.resources import Execute
from resource_man... | stacks/XIAOMATECH/1.0/services/BEACON/package/scripts/beacon.py | 30,656 | Creating/Updating beacon.ranger.user with role "ROLE_SYS_ADMIN" Updating beacon_user role depending upon cluster environment delay for 10 seconds Get Ranger Hive default policy for resource database, table, column Get Ranger Hive default policy for resource hiveservice Updating beacon_user in Ranger Hive default policy... | 1,132 | en | 0.501861 |
import pandas as pd
data=pd.read_csv("C:/Users/user/Documents/API_NY.GDP.PCAP.CD_DS2_en_csv_v2_1068945.csv") #your raw data obtained from world bank
import pandas as pd
import matplotlib.pyplot as plt
fulldataonly=data.dropna()
listofcountry=fulldataonly['Country Name']
listofcountry=list(listofcountry)
def findco... | Economic Growth & GDP per capita.py | 2,722 | your raw data obtained from world bank find which row is the countryfor country in range(len(listofcountry)): for year in listyear: y0=data.loc[findcountryrow(listofcountry[country]),str(year)] y1=data.loc[findcountryrow(listofcountry[country]),str(year+1)] delta=(y1-y0)/y0 x.append(y0) ... | 688 | en | 0.274347 |
# Monster Hot Air Balloon | (2435553)
if sm.getSkillByItem() == 0:# Check whether item has an vehicleID stored, 0 if false.
sm.chat("An Error occurred whilst trying to find the mount.")
elif sm.hasSkill(sm.getSkillByItem()):
sm.chat("You already have the 'Monster Hot Air Balloon' mount.")
else:
sm.consum... | scripts/item/consume_2435553.py | 450 | Monster Hot Air Balloon | (2435553) Check whether item has an vehicleID stored, 0 if false. | 94 | en | 0.488993 |
# this works around a path issue with just calling
# coverage run -m doctest -v <rst-file>
import doctest
import sys
fails = 0
for filename in [
"tuples.rst",
"functions.rst",
"symbolic.rst",
"simplification.rst",
"differentiation.rst",
"symbolic_tuples.rst",
]:
result = doctest.testfile(... | run_doctests.py | 384 | this works around a path issue with just calling coverage run -m doctest -v <rst-file> | 86 | en | 0.916185 |
"""
The various serializers.
Pyro - Python Remote Objects. Copyright by Irmen de Jong (irmen@razorvine.net).
"""
import array
import builtins
import uuid
import logging
import struct
import datetime
import decimal
import numbers
import inspect
import marshal
import json
import serpent
import msgpack
from . import er... | Pyro5/serializers.py | 20,446 | (de)serializer that wraps the json serialization protocol.
(de)serializer that wraps the marshal serialization protocol.
(de)serializer that wraps the msgpack serialization protocol.
Base class for (de)serializer implementations (which must be thread safe)
(de)serializer that wraps the serpent serialization protocol.
t... | 2,456 | en | 0.808405 |
# Exercício número 3 da lista
n1 = int(input('DIgite um valor:'))
n2 = int(input('Digite outro valor:'))
soma = n1+n2
print('A soma entre {} e {} é {}'.format(n1, n2, soma)) | Mundo 1/Ex003 - soma.py | 176 | Exercício número 3 da lista | 27 | pt | 0.974302 |
"""
Meta thinking: python objects & introspection
usefull documentation:
http://python-3-patterns-idioms-test.readthedocs.org/en/latest/Metaprogramming.html
"""
import inspect
import pkgutil
from importlib import import_module
from types import ModuleType
from typing import Any, Callable, Dict, List, Optional, Type
... | restapi/utilities/meta.py | 5,411 | Utilities with meta in mind
Extract all celery tasks from a module.
Celery tasks are functions decorated by @CeleryExt.celery_app.task(...)
This decorator transform the function into a class child of
celery.local.PromiseProxy
Find classes inside a python module file.
Getting a module import
when your module is stored a... | 1,036 | en | 0.721413 |
from core.himesis import Himesis, HimesisPreConditionPatternLHS
import uuid
class HUnitR06_IsolatedLHS(HimesisPreConditionPatternLHS):
def __init__(self):
"""
Creates the himesis graph representing the AToM3 model HUnitR06_IsolatedLHS
"""
# Flag this instance as compiled now
self.is_compiled = True
super... | GM2AUTOSAR_MM/Properties/unit_contracts/HUnitR06_IsolatedLHS.py | 1,526 | Creates the himesis graph representing the AToM3 model HUnitR06_IsolatedLHS
Flag this instance as compiled now Add the edges Set the graph attributes Set the node attributes match class PhysicalNode(6.0.m.0PhysicalNode) node match class Partition(6.0.m.1Partition) node define evaluation methods for each apply class. | 319 | en | 0.666788 |
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import numpy as np
from openvino.tools.mo.ops.eye import MXEye
from openvino.tools.mo.front.extractor import FrontExtractorOp
from openvino.tools.mo.front.mxnet.extractors.utils import get_mxnet_layer_attrs
class EyeExtractor(FrontExt... | tools/mo/openvino/tools/mo/front/mxnet/eye_ext.py | 936 | Copyright (C) 2018-2022 Intel Corporation SPDX-License-Identifier: Apache-2.0 | 77 | en | 0.237368 |
__copyright__ = """
Copyright (C) 2009-2017 Andreas Kloeckner
Copyright (C) 2014-2017 Aaron Meurer
"""
__license__ = """
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, includ... | pudb/debugger.py | 102,392 | A Screen subclass that doesn't crash when running from a non-main thread.
Updates the UI to show the line currently being executed.
Start debugging from `frame`.
If frame is not specified, debugging starts from caller's frame.
Unlike Bdb.set_trace(), this does not call self.reset(), which causes
the debugger to enter... | 4,409 | en | 0.808741 |
import dis
import math
import os
import unittest
import sys
import ast
import _ast
import tempfile
import types
import textwrap
from test import support
from test.support import script_helper, requires_debug_ranges
from test.support.os_helper import FakePath
class TestSpecifics(unittest.TestCase):
def compile_si... | examples/wagipython/wagi-python/opt/wasi-python/lib/python3.11/test/test_compile.py | 52,814 | Non-mapping
Test mapping interface versus possible calls from eval().
docstring
doc string
Regression test for issue35193 when run under clang msan.
catch assignments to __debug__ detect duplicate positional and keyword arguments Verify that dict subclasses work as well testing bad float literals testing compile() of... | 5,529 | en | 0.850983 |
# Python
import pytest
from unittest import mock
from contextlib import contextmanager
from awx.main.models import Credential, UnifiedJob
from awx.main.tests.factories import (
create_organization,
create_job_template,
create_instance,
create_instance_group,
create_notification_template,
create... | awx/main/tests/conftest.py | 5,287 | SQLite friendly since partitions aren't supported. Do not add the faked job_created field to the filter. If we do, it will result in an sql query for the
job_created field. That field does not actually exist in a non-partition scenario.
Returns job with linked JT survey with password survey questions
Python clear Dja... | 1,006 | en | 0.890625 |
#!/usr/bin/env python3
import sys
import os
import re
import argparse
import requests
from bs4 import BeautifulSoup as bs
version=1.1
print("""\033[1;36m
╦ ╦╔═╗╔╗ ╦═╗╔═╗╔═╗╔╦╗╔═╗╦═╗
║║║║╣ ╠╩╗ ╠╦╝║╣ ╠═╣║║║║╣ ╠╦╝
╚╩╝╚═╝╚═╝────╩╚═╚═╝╩ ╩╩ ╩╚═╝╩╚═
🔗🔥🔗🔥🔗🔥🔗🔥🔗🔥🔗🔥🔗🔥🔗🔥
... | web_reamer.py | 12,209 | !/usr/bin/env python3 | 21 | fr | 0.448822 |
from prettytable import PrettyTable
from collections import OrderedDict
def _fieldnames(rows):
def g():
for row in rows:
yield from row
d = OrderedDict((k, None) for k in g())
return list(d.keys())
def _echo_table(rows):
if not rows: return
fieldnames = _fieldnames(rows)
t... | utd/script.py | 8,527 | FIXME: check for proper address format | 38 | en | 0.586758 |
""" Argparse utilities"""
import sys
from six import PY2
from argparse import ArgumentParser
try:
from argparse import _SubParsersAction
except ImportError:
_SubParsersAction = type(None)
class PatchArgumentParser:
_original_parse_args = None
_original_parse_known_args = None
_original_add_subpars... | trains/utilities/args.py | 8,697 | Argparse utilities
if we are running remotely, we always have a task id, so we better patch the argparser as soon as possible. this will cause the current_task() to set PatchArgumentParser._current_task noinspection PyBroadException automatically connect to current task: if we are here and running remotely by now we ... | 976 | en | 0.711236 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Apr, 2019
@author: Nathan de Lara <ndelara@enst.fr>
"""
from typing import Optional, Union
import numpy as np
from sknetwork.utils.check import check_seeds
def stack_seeds(n_row: int, n_col: int, seeds_row: Optional[Union[np.ndarray, dict]],
... | sknetwork/utils/seeds.py | 1,760 | Transform seeds into probability vector.
Parameters
----------
n : int
Total number of samples.
seeds :
If ``None``, the uniform distribution is used.
Otherwise, a non-negative, non-zero vector or a dictionary must be provided.
Returns
-------
probs: np.ndarray
A probability vector.
Process seeds for ... | 488 | en | 0.61039 |
""" This module provides the unsafe things for targets/numbers.py
"""
from .. import types
from ..extending import intrinsic
from llvmlite import ir
@intrinsic
def viewer(tyctx, val, viewty):
""" Bitcast a scalar 'val' to the given type 'viewty'. """
bits = val.bitwidth
if isinstance(viewty.dtype, types.... | numba/unsafe/numbers.py | 1,684 | Counts leading zeros in the binary representation of an integer.
Counts trailing zeros in the binary representation of an integer.
Bitcast a scalar 'val' to the given type 'viewty'.
This module provides the unsafe things for targets/numbers.py | 244 | en | 0.755063 |
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 3 23:07:15 2019
@author: ydima
"""
import logging
import os
from pathlib import Path
import random
import shlex
import string
from subprocess import PIPE, Popen
import tempfile
from typing import Dict, List, Optional, Union
import pandas as pd
from .constants import (... | bcpandas/utils.py | 7,204 | Adopted from https://github.com/titan550/bcpy/blob/master/bcpy/format_file_builder.py#L25
See https://docs.microsoft.com/en-us/sql/tools/bcp-utility
Creates the non-xml SQL format file. Puts 4 spaces between each section.
See https://docs.microsoft.com/en-us/sql/relational-databases/import-export/non-xml-format-files-s... | 2,240 | en | 0.719074 |
_base_ = [
'../_base_/datasets/coco_detection.py',
'../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py',
'../_base_/swa.py'
]
# model settings
model = dict(
type='ATSS',
pretrained = 'https://github.com/SwinTransformer/storage/releases/download/v1.0.0/swin_base_patch4_window7_224_22k.pth',
backbo... | configs/ddod/swin.py | 5,343 | model settings training and testing settings data setting optimizer learning policy runtime | 91 | en | 0.83651 |
# 電子レンジ
def get_E_Elc_microwave_d_t(P_Elc_microwave_cook_rtd, t_microwave_cook_d_t):
"""時刻別消費電力量を計算する
Parameters
----------
P_Elc_microwave_cook_rtd : float
調理時の定格待機電力, W
t_microwave_cook_d_t : ndarray(N-dimensional array)
1年間の全時間の調理時間を格納したND配列, h
d日t時の調理時間が年開始... | src/pyhees/section10_j1_f.py | 1,435 | 時刻別消費電力量を計算する
Parameters
----------
P_Elc_microwave_cook_rtd : float
調理時の定格待機電力, W
t_microwave_cook_d_t : ndarray(N-dimensional array)
1年間の全時間の調理時間を格納したND配列, h
d日t時の調理時間が年開始時から8760個連続して格納されている
Returns
----------
E_Elc_microwave_d_t : ndarray(N-dimensional array)
1年間の全時間の消費電力量を格納したND配列, Wh
... | 519 | ja | 0.935555 |
from ... import create_engine
from ... import exc
from ...engine import url as sa_url
from ...testing.provision import configure_follower
from ...testing.provision import create_db
from ...testing.provision import drop_db
from ...testing.provision import follower_url_from_main
from ...testing.provision import log
from ... | virtual/lib/python3.7/site-packages/sqlalchemy/dialects/oracle/provision.py | 3,862 | NOTE: make sure you've run "ALTER DATABASE default tablespace users" or similar, so that the default tablespace is not "system"; reflection will fail otherwise cx_Oracle seems to occasionally leak open connections when a large suite it run, even if we confirm we have zero references to connection objects. while there i... | 420 | en | 0.887421 |
# -*- coding: utf-8 -*-
"""
pygments.lexers.other
~~~~~~~~~~~~~~~~~~~~~
Lexers for other languages.
:copyright: Copyright 2006-2010 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
from pygments.lexer import Lexer, RegexLexer, include, bygroups, using, \
... | tools/yuidoc/bin/pygments/lexers/other.py | 107,772 | -*- coding: utf-8 -*- TODO: Backslash escapes? not a real string literal in ANSI SQL TODO: add backslash escapes TODO: this list is not complete use different colors for different instruction types Traditional math Move, imperatives Stack ops, imperatives Befunge-98 stack ops Strings don't appear to allow escapes Singl... | 3,704 | en | 0.769783 |
#
# Copyright 2014 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 ... | test/test_client.py | 11,711 | From http://en.wikipedia.org/wiki/Hash-based_message_authentication_code
HMAC_SHA1("key", "The quick brown fox jumps over the lazy dog")
= 0xde7c9b85b8b78aa6bc8a7a36f70a90701c9db4d9
Tests for client module.
Copyright 2014 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "Licens... | 1,256 | en | 0.819432 |
# -*-coding:Utf-8 -*
# Copyright (c) 2010-2017 LE GOFF Vincent
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
... | src/secondaires/peche/commandes/banc/creer.py | 2,751 | Commande 'banc créer'
Constructeur du paramètre.
Méthode d'interprétation de commande
Package contenant le paramètre 'créer' de la commande 'banc'.
-*-coding:Utf-8 -* Copyright (c) 2010-2017 LE GOFF Vincent All rights reserved. Redistribution and use in source and binary forms, with or without modification, are perm... | 1,662 | en | 0.816426 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class MybankPaymentTradeFinancingOrderRefundModel(object):
def __init__(self):
self._amount = None
self._biz_no = None
self._currency_value = None
self._ext_info = None
... | alipay/aop/api/domain/MybankPaymentTradeFinancingOrderRefundModel.py | 5,299 | !/usr/bin/env python -*- coding: utf-8 -*- | 42 | en | 0.34282 |
# GENERATED BY KOMAND SDK - DO NOT EDIT
import komand
import json
class Input:
RESOURCEGROUP = "resourceGroup"
SUBSCRIPTIONID = "subscriptionId"
class Output:
VALUE = "value"
class ListVmInput(komand.Input):
schema = json.loads("""
{
"type": "object",
"title": "Variables",
"proper... | azure_compute/komand_azure_compute/actions/list_vm/schema.py | 176,147 | GENERATED BY KOMAND SDK - DO NOT EDIT | 37 | en | 0.775658 |
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'potato.settings')
try:
from django.core.management import execute_from_command_line
except Impor... | manage.py | 662 | Run administrative tasks.
Django's command-line utility for administrative tasks.
!/usr/bin/env python | 103 | en | 0.725633 |
# coding: utf-8
import logging
import os
import shutil
import sys
import tempfile
import unittest
import pytest
import fiona
logging.basicConfig(stream=sys.stderr, level=logging.INFO)
class UnicodePathTest(unittest.TestCase):
def setUp(self):
tempdir = tempfile.mkdtemp()
self.dir = os.path.jo... | tests/test_unicode.py | 4,392 | Can write a simplified Chinese shapefile
TOFIX: OGR silently fails to convert strings
coding: utf-8 Details: If we tell OGR that we want a latin-1 encoded output file and give it a feature with a unicode property that can't be converted to latin-1, no error is raised and OGR just writes the utf-8 encoded bytes to the... | 489 | en | 0.893415 |
from setuptools import setup, find_packages
__author__ = 'Giulio Rossetti'
__license__ = "BSD 2 Clause"
__email__ = "giulio.rossetti@gmail.com"
# Get the long description from the README file
# with open(path.join(here, 'README.md'), encoding='utf-8') as f:
# long_description = f.read()
setup(name='demon',
... | setup.py | 1,664 | Get the long description from the README file with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() How mature is this project? Common values are 3 - Alpha 4 - Beta 5 - Production/Stable Indicate who your project is intended for Pick your license as you wish (should match ... | 470 | en | 0.822206 |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
import logging
import unittest
from ml.rl.models.example_sequence_model import ExampleSequenceModel
from ml.rl.test.models.test_utils import check_save_load
logger = logging.getLogger(__name__)
class TestExampleSequence... | ml/rl/test/models/test_sequence_model.py | 923 | !/usr/bin/env python3 Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. ONNX sure exports a lot of parameters... | 132 | en | 0.824334 |
# --------------------------------------------------------
# Deformable Convolutional Networks
# Copyright (c) 2017 Microsoft
# Copyright (c) 2019 IBM Corp
# Licensed under The Apache-2.0 License [see LICENSE for details]
# Written by Haozhi Qi
# --------------------------------------------------------
import cPickle
... | fpn/symbols/resnet_v1_101_fpn_dcn_rcnn.py | 87,595 | Use __init__ to define parameter network needs
-------------------------------------------------------- Deformable Convolutional Networks Copyright (c) 2017 Microsoft Copyright (c) 2019 IBM Corp Licensed under The Apache-2.0 License [see LICENSE for details] Written by Haozhi Qi --------------------------------------... | 1,236 | en | 0.430587 |
# -*- coding: utf-8 -*-
# Copyright (c) 2022, bahaa and Contributors
# See license.txt
from __future__ import unicode_literals
# import frappe
import unittest
class TestAlaqoal(unittest.TestCase):
pass
| calender/calender/doctype/alaqoal/test_alaqoal.py | 205 | -*- coding: utf-8 -*- Copyright (c) 2022, bahaa and Contributors See license.txt import frappe | 94 | en | 0.669414 |
# <a href="https://colab.research.google.com/github/couyang24/general_learning-tiffany/blob/master/Titanic/analysis/colab_titanic_main.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# Need to mount Drive on or upload kaggle.json
from google.colab ... | Titanic/analysis/colab_titanic_main.py | 6,712 | <a href="https://colab.research.google.com/github/couyang24/general_learning-tiffany/blob/master/Titanic/analysis/colab_titanic_main.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> Need to mount Drive on or upload kaggle.json !mkdir ~/.kaggle/ !cp dr... | 1,195 | en | 0.336832 |
# Generated by Django 2.1.3 on 2018-11-24 07:01
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Job',
fields=[
('id', models.AutoField(auto... | jobs/migrations/0001_initial.py | 553 | Generated by Django 2.1.3 on 2018-11-24 07:01 | 45 | en | 0.551468 |
import os
import pandas as pd
import re
def sort_human(l):
"""Sort a list of strings by numerical."""
def convert(text): return float(text) if text.isdigit() else text
def alphanum(key): return [convert(c)
for c in re.split('([-+]?[0-9]*\.?[0-9]*)', key)]
l.sort(key=alp... | results_processing/ABC/csv_processing.py | 2,842 | Merge a set of parameters.csv files into one.
This is intended for use with batch processes from Legion, with each batch
being 1000 runs longand numbered with integer values.
Parameters
----------
parent_directory : :obj:`list` of :obj:`str`
Parent directory to a set of directories each containing model runs and
... | 893 | en | 0.524074 |
#! /usr/bin/enc python
# -*- coding: utf-8 -*-
# author: Irving He
# email: 1910646@tongji.edu.cn
import logging
import argparse
import os
import random
import numpy as np
from tqdm import tqdm
import datetime
from datetime import timedelta
import torch
import torch.distributed as dist
from Data_utils import get_l... | VIT/Train.py | 7,578 | :param args:
- log_dir
:param args: 参数Config
:param model: 需验证模型
:param writer: TB写入
:param test_loader: 测试数据集
:param global_step: 全局step
:return:
! /usr/bin/enc python -*- coding: utf-8 -*- author: Irving He email: 1910646@tongji.edu.cn "cifar100" 预训练模型存放位置 "cosine", "linear" 决定了学习率Scheduler类型51264 Run predict... | 1,162 | en | 0.389346 |
"""
Django settings for hiren project.
Generated by 'django-admin startproject' using Django 1.8.4.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build paths ... | hiren/settings.py | 4,055 | Django settings for hiren project.
Generated by 'django-admin startproject' using Django 1.8.4.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
Build paths inside th... | 953 | en | 0.662831 |
__author__ = "Stefan Weißenberger and Johannes Gasteiger"
__license__ = "MIT"
import os
import numpy as np
from scipy.linalg import expm
import torch
from torch_geometric.data import Data, InMemoryDataset
from torch_geometric.datasets import Planetoid, Amazon, Coauthor
from seeds import development_seed... | data.py | 10,715 | Dataset preprocessed with GDC using heat kernel diffusion.
Note that this implementations is not scalable
since we directly calculate the matrix exponential
of the adjacency matrix.
Dataset preprocessed with GDC using PPR diffusion.
Note that this implementations is not scalable
since we directly invert the adjacency m... | 606 | en | 0.806371 |
"""This contains all of the model filters used by the Shepherd application."""
# Django & Other 3rd Party Libraries
import django_filters
from crispy_forms.bootstrap import (
Accordion,
AccordionGroup,
InlineCheckboxes,
PrependedText,
)
from crispy_forms.helper import FormHelper
from crispy_forms.layou... | ghostwriter/shepherd/filters.py | 5,772 | Filter :model:`shepherd.Domain` model for searching.
**Fields**
``name``
Case insensitive search of the name field contents
``all_cat``
Case insensitive search of the all_cat field
``health_status``
Checkbox choice filter using :model:`shepherd.HealthStatus`
``domain_status``
Checkbox choice filter us... | 906 | en | 0.599886 |
# 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... | artifacts/old_dataset_versions/minimal_commits/pennylane/pennylane#385/after/test_tf.py | 26,292 | Integration tests to ensure the TensorFlow QNode agrees with the NumPy QNode
Integration tests involving gradients of QNodes and hybrid computations using the tf interface
TFQNode basic tests.
Test that the TFQNode properly handles the parameters of qfuncs
Two QNodes to be used for the gradient tests
Test the gradient ... | 3,850 | en | 0.820635 |
# Version of the library that will be used to upload to pypi
__version__ = "0.28.0.dev0"
# Git tag that will be checked to determine whether to trigger upload to pypi
__release_tag__ = None
| gym-unity/gym_unity/__init__.py | 191 | Version of the library that will be used to upload to pypi Git tag that will be checked to determine whether to trigger upload to pypi | 134 | en | 0.900569 |
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Tests for L{twisted.web.distrib}.
"""
from os.path import abspath
from xml.dom.minidom import parseString
try:
import pwd
except ImportError:
pwd = None
from zope.interface.verify import verifyObject
from twisted.python import filep... | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py | 18,288 | An exception for this test.
A PB server factory which keeps track of the most recent protocol it
created.
@ivar proto: L{None} or the L{Broker} instance most recently returned
from C{buildProtocol}.
Tests for L{UserDirectory}, a resource for listing all user resources
available on a system.
Verify that requesting ... | 4,071 | en | 0.815905 |
import pathlib
from setuptools import setup
here = pathlib.Path(__file__).parent.resolve()
# Get the long description from the README file
long_description = (here / "README.md").read_text(encoding="utf-8")
setup(
name="MCsniperPY",
version="0.20.6",
description="Minecraft name sniper writte... | setup.py | 1,012 | Get the long description from the README file Again, pick a license | 67 | en | 0.839625 |
'''
This module hooks fast.ai Learners to Weights & Biases through a callback.
Requested logged data can be configured through the callback constructor.
Examples:
WandbCallback can be used when initializing the Learner::
```
from wandb.fastai import WandbCallback
[...]
learn = Learner(... | wandb/fastai/__init__.py | 8,841 | Automatically saves model topology, losses & metrics.
Optionally logs weights, gradients, sample predictions and best trained model.
Args:
learn (fastai.basic_train.Learner): the fast.ai learner to hook.
log (str): "gradients", "parameters", "all", or None. Losses & metrics are always logged.
save_model (b... | 3,254 | en | 0.751566 |
import os
from setuptools import setup, Extension
from setuptools.command.build_ext import build_ext
from Cython.Distutils import build_ext
import numpy as np
from os.path import join as pjoin
from setup_cuda import cuda_setup
mpi_compile_args = os.popen("mpic++ --showme:compile").read().strip().split(' ')
mpi_link_ar... | swig_muesli/muesli/da/setup_da.py | 1,900 | Find a file in a search path
Adapted fom http://code.activestate.com/recipes/52224 setup(name='PackageName', author='Nina Herrmann', version='1.0', description='This is a package for Muesli', ext_modules=cythonize(cuda_setup.get_module()), cmdclass={'build_ext': cuda_setup.custom_build_e... | 333 | en | 0.397683 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import numpy as np
from sklearn.decomposition import PCA
from reco_utils.dataset.download_utils import maybe_download
from IPython import embed
def length_normalize(matrix):
"""Length normalize the matrix
Args:
... | reco_utils/recommender/geoimc/geoimc_utils.py | 1,124 | Length normalize the matrix
Args:
matrix (np.ndarray): Input matrix that needs to be normalized
Returns:
Normalized matrix
Performs mean centering across axis 0
Args:
matrix (np.ndarray): Input matrix that needs to be mean centered
Reduce dimensionality of the data using PCA.
Args:
matrix (np.ndarra... | 532 | en | 0.782968 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.