text
string
size
int64
token_count
int64
import unittest import eliza class ElizaTest(unittest.TestCase): def test_decomp_1(self): el = eliza.Eliza() self.assertEqual([], el._match_decomp(["a"], ["a"])) self.assertEqual([], el._match_decomp(["a", "b"], ["a", "b"])) def test_decomp_2(self): el = eliza.Eliza() ...
6,142
2,074
import sys import os import json from elasticsearch import Elasticsearch, helpers from datetime import datetime, timezone import numpy as np from dtw import dtw # Get parameters and set up elasticsearch data = json.loads(sys.stdin.readline()) es = Elasticsearch([{'host': data['es']['host'], 'port': int(data['es']['po...
5,387
1,942
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2020 tecnovert # Distributed under the MIT software license, see the accompanying # file LICENSE.txt or http://www.opensource.org/licenses/mit-license.php. from .contrib.test_framework.messages import ( CTxOutPart, ) from .interface_btc import BTCInte...
602
205
''' resume ============================================================================== This plugin generates a PDF resume from a Markdown file using customizable CSS ''' import os import logging import tempfile from subprocess import Popen from pelican import signals CURRENT_DIR = os.path.dirname(os.path.abspath...
2,511
829
from sklearn.linear_model import Ridge class MachineLearning(): def __init__(self): self.model = None def train_model(self, X,y): lr = Ridge(alpha=0.5) lr.fit(X,y) print(lr) self.model = lr def predict(self, X): preds = self.model.predict(X) return...
331
121
# -*- coding: utf-8 -*- """ @author: Marcos F. Caetano (mfcaetano@unb.br) 11/03/2020 @description: PyDash Project The ConnectionHandler is a Singleton class implementation The class responsible to retrieve segments in the web server. Also it implements a traffic shaping approach. """ from base.simple_module import ...
6,246
1,953
import re import yaml import logging logger = logging.getLogger(__name__) from pylatexenc.macrospec import MacroSpec, ParsedMacroArgs, MacroStandardArgsParser from pylatexenc import latexwalker from latexpp.macro_subst_helper import MacroSubstHelper from latexpp.fix import BaseFix # parse entropy macros etc. _q...
37,634
12,108
import numpy as np import scipy import sympy from numpy import linalg as lg from numpy.linalg import solve from numpy.linalg import eig from scipy.integrate import quad # Question 1 ''' A. Determinant = -21 B. Determinant = -21 ''' m1 = np.array([[3, 0, 3], [2, 3, 3], [0, 4, -1]]) print(m1) det1 = np.linalg.det(m...
3,936
1,758
from builder.laikago_task_bullet import LaikagoTaskBullet from builder.laikago_task import InitPose import math import numpy as np ABDUCTION_P_GAIN = 220.0 ABDUCTION_D_GAIN = 0.3 HIP_P_GAIN = 220.0 HIP_D_GAIN = 2.0 KNEE_P_GAIN = 220.0 KNEE_D_GAIN = 2.0 class LaikagoStandImitationBulletBase(LaikagoTaskBullet): de...
2,620
988
#!/usr/bin/env python # -*- coding: utf-8 -*- from bincrafters import build_template_default if __name__ == "__main__": builder = build_template_default.get_builder() # Todo: re-enable shared builds when issue resolved # github issue: https://github.com/google/protobuf/issues/2502 builder.items...
425
138
from logging import Logger from logging import getLogger from pytrek.settings.BaseSubSetting import BaseSubSetting from pytrek.settings.SettingsCommon import SettingsCommon from pytrek.settings.SettingsCommon import SettingsNameValues class LimitsSettings(BaseSubSetting): LIMITS_SECTION: str = 'Limits' MA...
2,046
707
import unittest from datetime import date from irLib.marketConvention.dayCount import ACT_ACT from irLib.marketConvention.compounding import annually_k_Spot from irLib.helpers.yieldCurve import yieldCurve, discountCurve, forwardCurve import numpy as np alias_disC = 'disC' alias_forC = 'forC' referenceDate = date(2020...
2,366
894
# Copyright (c) 2020 NVIDIA Corporation. All rights reserved. # This work is licensed under the NVIDIA Source Code License - Non-commercial. Full # text can be found in LICENSE.md from setuptools import setup, dist import wheel import os # required to geneerate a platlib folder required by audittools from setuptools.c...
1,876
577
from marshmallow import fields, Schema from .provision import ProvisionActionSchema class InstanceSchema(Schema): type = fields.String(required=True) image_id = fields.String(required=True) availability_zone = fields.String(required=True) ebs_optimized = fields.Boolean() iam_fleet_role = fields.String(required=...
1,060
345
import sys import os import zipfile from zipfile import ZipFile from StringIO import StringIO source = sys.argv[1] target = sys.argv[2] if not target.endswith("/"): target = "%s/" % target def _unbundle(path, target): zf = ZipFile(path, 'r') contents = zf.namelist() for item in contents: sp ...
1,099
368
# -*- coding: utf-8 -*- # import time import os import math import json from lib.forms import BaseFied, BaseFieldFormatExt, DotDict, BaseCfilterActionFied, BaseCfilterOptionFied from app.core.models import Mailbox, MailboxUserAttr, Domain, CoCompany, CoreAlias, DomainAttr, \ Department...
81,920
27,416
from PyQt5 import QtGui, QtCore, QtWidgets from collections import namedtuple import time import random import torch import torch.nn as nn import torch.nn.functional as F from utils import utils HumanFeedback = namedtuple('HumanFeedback', ['feedback_value']) SavedAction = namedtuple('SavedAction', ['state', 'action', ...
9,074
2,835
import pyodbc import mysql.connector conn = mysql.connector.connect(user='root', password='', port='3307', host='localhost', database='coviddb') cursor = conn.cursor(buffered=True) cursor.execute('SELECT * FROM coviddb.markers') cursor.execute(''' INSERT INTO coviddb.markers(id, name, address, sub...
434
140
import time import pytest # preparing selenium and chrome web driver manager from selenium import webdriver from selenium.webdriver.chrome.options import Options from webdriver_manager.chrome import ChromeDriverManager # importing os for environmental variable, and docker-compose up import os @pytest.fixture(scope=...
605
160
__all__ = [ "Dataset", "forgiving_true", "load_config", "log", "make_tdtax_taxonomy", "plot_gaia_density", "plot_gaia_hr", "plot_light_curve_data", "plot_periods", ] from astropy.io import fits import datetime import json import healpy as hp import matplotlib.pyplot as plt import nu...
22,390
7,678
# coding: utf8 from __future__ import unicode_literals from ...attrs import LIKE_NUM _num_words = ['zero', 'um', 'dois', 'três', 'tres', 'quatro', 'cinco', 'seis', 'sete', 'oito', 'nove', 'dez', 'onze', 'doze', 'dúzia', 'dúzias', 'duzia', 'duzias', 'treze', 'catorze', 'quinze', 'dezasseis', ...
1,787
675
# -*- coding: utf-8 -*- """ Created on Fri Nov 29 18:00:53 2019 @author: Administrator """ import pdblp import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns con = pdblp.BCon(debug=False, port=8194, timeout=5000) con.start() index_tickers = ['NYA Index', 'SPX I...
1,818
863
import click import os from flask.cli import with_appcontext @click.command(name='pep8', help='Automatically formats Python code to conform to the PEP 8 style guide.') @click.option('-p', '--path', default='./ms', help='folder path to fix code') @with_appcontext def pep8(path: str) -> Non...
357
115
#!/usr/bin/env python import logging import re import subprocess import sys from typing import Dict logger = logging.getLogger("py2ts.generate_service_registry") logging.basicConfig(level=logging.INFO) class RipgrepError(Exception): pass def camel_to_snake(name: str) -> str: name = re.sub("(.)([A-Z][a-z]+)...
2,378
782
from misc import util from collections import namedtuple import csv import numpy as np import os import pickle import sys N_EX = 4 Datum = namedtuple("Datum", ["hint", "ex_inputs", "input", "label"]) START = "<s>" STOP = "</s>" random = util.next_random() birds_path = os.path.join(sys.path[0], "data/birds") def ...
5,311
1,699
import locale import pytest from covid.utils import fmt class TestUtilityFunctions: def test_format_functions_en_US(self): try: locale.setlocale(locale.LC_ALL, "en_US.UTF-8") except locale.Error: return pytest.skip() assert fmt(0.10) == "0.1" assert fmt(0...
2,261
1,127
#!/usr/bin/env python from anti_instagram.AntiInstagram import AntiInstagram from cv_bridge import CvBridge, CvBridgeError from duckietown_msgs.msg import (AntiInstagramTransform, BoolStamped, Segment, SegmentList, Vector2D, FSMState) from duckietown_utils.instantiate_utils import instantiate from duckietown_utils....
10,717
3,538
# -*- coding: utf-8 -*- from account_helper.middleware import get_current_user_id from django.utils import timezone from django.conf import settings from hashlib import sha1 import os def user_upload_dir(instance, filename): name_struct = os.path.splitext(filename) current_user_id = get_current_user_id() ...
776
250
#!/usr/bin/env python3 # encoding: utf-8 # # Copyright (c) 2010 Doug Hellmann. All rights reserved. # """Show the groups within the matches for a pattern. """ # end_pymotw_header import re def test_patterns(text, patterns): """Given source text and a list of patterns, look for matches for each pattern withi...
1,339
411
from django.urls import re_path from xr_embeds.views import geojson_view, embed_html_view app_name = "embeds" urlpatterns = [ re_path(r"^(\d+)/html/$", embed_html_view, name="embed_html"), re_path( r"^geojson/(?P<model_slug>\w+)/(?P<query_slug>\w+)/$", geojson_view, name="geojson_view...
332
135
from django.db import models from django.core import signing class PasswordMixin(object): password_encrypted = models.CharField(max_length=128, null=False, blank=False) @property def password(self): return signing.loads(self.password_encrypted) @password.setter def password(self, value)...
377
114
# -*- Mode: python; indent-tabs-mode: nil; c-basic-offset: 2; tab-width: 2 -*- from publications import list_import_formats, get_publications_importer __license__ = 'MIT License <http://www.opensource.org/licenses/mit-license.php>' __author__ = 'Lucas Theis <lucas@theis.io>' __docformat__ = 'epytext' from django.cont...
7,858
2,267
import logging from tests.common.helpers.assertions import pytest_assert from tests.common.utilities import get_host_visible_vars from tests.common.utilities import wait_until CONTAINER_CHECK_INTERVAL_SECS = 1 CONTAINER_RESTART_THRESHOLD_SECS = 180 logger = logging.getLogger(__name__) def is_supervisor_node(inv_file...
7,379
2,098
# encoding: utf-8 # module _ctypes # from /usr/lib/python3.5/lib-dynload/_ctypes.cpython-35m-x86_64-linux-gnu.so # by generator 1.145 """ Create and manipulate C compatible data types in Python. """ # no imports # Variables with simple values FUNCFLAG_CDECL = 1 FUNCFLAG_PYTHONAPI = 4 FUNCFLAG_USE_ERRNO = 8 FUNCFLAG_...
7,716
2,315
import torch from torch import nn from senseis.torch_modules.activation import relu_activation from senseis.torch_modules.residual_layer import ResidualLayer1DV5, ResidualLayer2DV3 # Dueling Q Model class RCActionModel1(nn.Module): def __init__(self, csz, row_sz, col_sz, a_sz): super(RCActionModel1, self).__ini...
1,059
466
# Message box functions # # This file is part of thomasa88lib, a library of useful Fusion 360 # add-in/script functions. # # Copyright (c) 2020 Thomas Axelsson # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to dea...
5,506
2,116
__all__ = ['EISCube'] import sys import copy import numpy as np import astropy.units as u from astropy.convolution import convolve, CustomKernel from astropy.coordinates import SkyCoord from ndcube import __version__ as ndcube_ver from ndcube import NDCube class EISCube(NDCube): """EIS Level-1 Data Cube Subc...
22,496
6,611
from rest_framework import serializers from django.contrib.contenttypes.models import ContentType from django.contrib.auth import get_user_model from profiles.serializers import UserRowSerializer from .models import Comment User = get_user_model() # content, user def create_comment_serializer(model_type='outfit', i...
5,380
1,441
#!/usr/bin/env python3 class stressTestPV: def __init__( self, pvName ): self._pvName = pvName self._tsValues = {} # Dict of collected values, keys are float timestamps self._tsRates = {} # Dict of collection rates, keys are int secPastEpoch values self._tsMissR...
3,497
972
import re import requests from typing import Union from pysoundcloud.soundcloudplaylists import SoundCloudPlaylists from pysoundcloud.soundcloudsearchresults import SoundCloudSearchResults from pysoundcloud.soundcloudlikedtracks import SoundCloudLikedTracks from pysoundcloud.soundcloudplaylist import SoundClo...
10,246
2,867
# Run this script to create stopwords.py based on stopwords.txt import json def generate(input_txt, output_py): # Read line by line txt_file = open(input_txt) words = set([]) for raw_line in txt_file: line = raw_line.strip() # Skip empty line if len(line) < 1: continue #...
859
276
"""Copy number detection with CNVkit with specific support for targeted sequencing. http://cnvkit.readthedocs.org """ import copy import math import operator import os import sys import tempfile import subprocess import pybedtools import numpy as np import toolz as tz from bcbio import utils from bcbio.bam import re...
33,166
11,451
""" (c) 2013 LinkedIn Corp. 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 to in writing...
31,862
10,010
# -*- coding: utf-8 -*- """ Copyright [2009-2021] EMBL-European Bioinformatics Institute Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by...
8,982
2,941
import tensorflow as tf from keras.preprocessing import image from keras.applications.inception_v3 import InceptionV3, preprocess_input, decode_predictions import numpy as np import h5py model = InceptionV3(include_top=True, weights='imagenet', input_tensor=None, input_shape=None) graph = tf.get_default_graph() def ...
1,024
359
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
4,959
1,540
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # @Time : 2020-04-13 21:19 # @Author : Richard Bai # @EMail : he.bai@uwaterloo.ca import nltk import os import json def sentence_split(line): sents = nltk.tokenize.sent_tokenize(line) rnt = [sent.split() for sent in sents] return rn...
324
139
# Generated by Django 2.1.4 on 2018-12-21 21:55 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Author', fields=[ ...
1,661
441
from sequana.tools import bam_to_mapped_unmapped_fastq, reverse_complement, StatsBAM2Mapped from sequana import sequana_data from sequana.tools import bam_get_paired_distance, GZLineCounter, PairedFastQ from sequana.tools import genbank_features_parser def test_StatsBAM2Mapped(): data = sequana_data("test.bam", "t...
1,361
520
""" xl.py - python library to deal with *big* Excel files. """ from abc import ABC from collections import namedtuple, ChainMap from contextlib import contextmanager import datetime import io from itertools import zip_longest import os import re import string import xml.etree.cElementTree as ET from zipfile import Zip...
16,219
5,078
import logging import urllib.parse from .api_client import ApiClient from .constants import APIConstants from .exceptions import APIException from .utils import CommonUtils class BaseAPI(object): """ BaseApi class, all the other api class extends it """ resource_url = None resource_cls = None ...
5,156
1,488
_base_ = ['./rotated-detection_static.py', '../_base_/backends/tensorrt.py'] onnx_config = dict( output_names=['dets', 'labels'], input_shape=None, dynamic_axes={ 'input': { 0: 'batch', 2: 'height', 3: 'width' }, 'dets': { 0: 'batch', ...
774
288
import numpy as np from typing import Any, Iterable, Tuple from .ext import EnvSpec from .parallel import ParallelEnv from ..prelude import Action, Array, State from ..utils.rms import RunningMeanStd class ParallelEnvWrapper(ParallelEnv[Action, State]): def __init__(self, penv: ParallelEnv) -> None: self....
4,053
1,357
from datetime import datetime from dateutil.relativedelta import relativedelta from django import template from django.template.defaultfilters import urlencode from django.urls import reverse from haystack.models import SearchResult from haystack.utils.highlighting import Highlighter register = template.Library() @...
1,205
375
#!/usr/bin/env python class Solution: def twoCitySchedCost(self, costs): N = len(costs)//2 costs = list(sorted(costs, key=lambda c: c[0]-c[1])) s = 0 for i, c in enumerate(costs): s += c[0] if i < N else c[1] return s costs = [[10,20],[30,200],[400,50],[30,20]] ...
372
153
''' This file contains method for generating calibration related plots, eg. reliability plots. References: [1] C. Guo, G. Pleiss, Y. Sun, and K. Q. Weinberger. On calibration of modern neural networks. arXiv preprint arXiv:1706.04599, 2017. ''' import math import matplotlib.pyplot as plt import numpy as np import...
23,818
10,498
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import...
11,137
3,274
from manimlib.imports import * class LSystem(Scene): CONFIG = { 'rules': {'F': 'F+F--F+F'}, 'length': 1, 'start_loc': ORIGIN, 'angle': PI / 3, 'start_rot': 0, 'iteration': 1, 'initial': 'F', 'actions': {}, 'locations': [], 'rotations':...
3,258
1,133
import imutils import cv2 import numpy as np import math from math import sqrt def find_robot_orientation(image): robot = {} robot['angle'] = [] robot['direction'] = [] robotLower = (139, 227, 196) robotUpper = (255, 255, 255) distances = [] # img = cv2.imread('all_color_terrain_with_robot....
4,720
1,907
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.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...
7,404
2,352
import os import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') def test_crypto_devices(host): f = host.file('/dev/mapper/cryptotest') assert f.exists f = host.file('/dev/mapper/crypto-test1') ...
337
129
""" weakref should be valid. """ import gc import importlib import autoreload import retroreload switch = 2 if switch == 0: reload_module = importlib.reload elif switch == 1: reload_module = autoreload.superreload elif switch == 2: reload_module = retroreload.retroreload import mod3 if __name__ ==...
796
269
def train_isolation_forest(df, padding_data): ''' * Isolation Forest model setting - n_estimators=100 - max_samples='auto' - n_jobs=-1 - max_features=2 - contamination=0.01 ''' #padding한 data load data_df = padding_data # model 정의 model = IsolationForest(n_estimators=100...
814
353
import numpy as np def load_mnist(): # the data, shuffled and split between train and test sets from keras.datasets import mnist (x_train, y_train), (x_test, y_test) = mnist.load_data() x = np.concatenate((x_train, x_test)) y = np.concatenate((y_train, y_test)) x = x.reshape(-1, 28, 28, 1).as...
1,619
673
""" This module defines a class called "balto_gui" that can be used to create a graphical user interface (GUI) for downloading data from OpenDAP servers from and into a Jupyter notebook. If used with Binder, this GUI runs in a browser window and does not require the user to install anything on their computer. However...
121,027
34,393
from django.views.generic.base import RedirectView from django.conf.urls import re_path def redir(regex, redirect_url, name=None): """ A shorter wrapper around RedirectView for 301 redirects. """ return re_path( regex, RedirectView.as_view(url=redirect_url, permanent=True), nam...
586
185
""" MIT License Copyright (c) 2021 lucaso60 Copyright (c) 2015-present Rapptz 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, ...
1,889
643
import multiprocessing as mp import os import shutil from functools import partial from tqdm import tqdm import data from chemhelp import mndo # def calculate(binary, filename, scr=None): # """ # Collect sets of lines for each molecule as they become available # and then call a parser to extract the dict...
2,393
777
# -*- coding: utf-8 -*- # # Copyright 2016 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 requir...
2,915
835
__author__ = 'stephen' import numpy as np import scipy.io import scipy.sparse import matplotlib matplotlib.use('agg') import matplotlib.pyplot as plt import matplotlib.mlab as mlab import matplotlib.pylab as pylab from .utils import get_subindices import matplotlib.ticker as mtick from collections import Counter from s...
23,288
9,380
from typing import IO from commanderbot_lib.database.abc.file_database import FileDatabase from commanderbot_lib.database.mixins.yaml_file_database_mixin import ( YamlFileDatabaseMixin, ) class YamlFileDatabase(FileDatabase, YamlFileDatabaseMixin): # @implements FileDatabase async def load(self, file: IO...
494
151
#Jónas Freyr Bjarnason #25.01.2017 #Forritun #Liður 1 #Byð notanda um tölu 1 tala1=int(input("Sláðu inn tölu 1 ")) #Byð notanda um tölu 2 tala2=int(input("Sláðu inn tölu 2 ")) #Birti tölu 1 og 2 lagðar saman print("Tölurnar lagðar saman ",tala1+tala2) #Birti tölu 1 og 2 margfaldaðar saman print("Tölurnar margfaldaðar...
1,663
818
pdu_objects = [ { 'header': { 'command_length': 0, 'command_id': 'bind_transmitter', 'command_status': 'ESME_ROK', 'sequence_number': 0, }, 'body': { 'mandatory_parameters': { 'system_id': 'test_system', ...
14,568
4,261
""" Functions to deal with arxiv package versions. It can be used in the setup.py file: from arxiv.release.dist_version import get_version setup( version=get_version('arxiv-filemanager'), .... ) """ import sys import pathlib from subprocess import Popen, PIPE from datetime import datetime import pkg_resou...
3,616
1,110
# -*- coding: utf-8 -*- """? :copyright: Copyright (c) 2020 RadiaSoft LLC. All Rights Reserved. :license: http://www.apache.org/licenses/LICENSE-2.0.html """ from __future__ import absolute_import, division, print_function #import argparse #import tables from mpi4py import MPI import h5py import inspect import numpy ...
15,812
4,786
#!/usr/bin/env python # -*- coding: utf-8 -*- from ._binning import Binning import itertools import numpy as np import copy try: from astroML.density_estimation.bayesian_blocks import bayesian_blocks got_astroML = True except ImportError: got_astroML = False class ClassicBinning(Binning): name = 'C...
15,043
4,614
import cv2 import numpy as np def drawPoint(canvas,x,y): canvas[y,x] = 0 def drawLine(canvas,x1,y1,x2,y2): dx, dy = abs(x2 - x1), abs(y2 - y1) xi, yi = x1, y1 sx, sy = 1 if (x2 - x1) > 0 else -1, 1 if (y2 - y1) > 0 else -1 pi = 2*dy - dx while xi != x2 + 1: if pi < 0: pi +...
2,625
1,266
from .base import Three class Alfentanil(Three): """base Alfentanil class""" pass class Maitre(Alfentanil): def __init__(self, age, weight, height, sex): if sex == "m": self.v1 = 0.111 * weight elif sex == "f": self.v1 = 0.128 * weight else: ...
888
374
import webbrowser from typing import Dict, Any from prompt_toolkit import print_formatted_text from .format import todo_string def launch_action(result: Dict[str, Any]): if "location" in result: webbrowser.open(result["location"]) else: print_formatted_text(todo_string(result))
307
96
from datetime import timedelta import logging from homeassistant.components.sensor import SensorEntity from homeassistant.const import ( STATE_UNAVAILABLE, DEVICE_CLASS_HUMIDITY, DEVICE_CLASS_TEMPERATURE, TEMP_CELSIUS, CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, PERCENTAGE, ) from .entity import ...
4,114
1,390
from __future__ import absolute_import, unicode_literals import unittest from fluent.runtime import FluentBundle from fluent.runtime.errors import FluentCyclicReferenceError, FluentReferenceError from ..utils import dedent_ftl class TestPlaceables(unittest.TestCase): def setUp(self): self.ctx = FluentB...
5,664
1,835
#!/usr/bin/env python # -*- coding: utf-8 -*-- # Copyright (c) 2021, 2022 Oracle and/or its affiliates. # Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/ class Parser: @property def pos(self): raise NotImplementedError() @property def no...
956
305
import pytest from brownie import Wei @pytest.fixture(scope="function", autouse=True) def shared_setup(fn_isolation): pass @pytest.fixture(scope='module') def nocoiner(accounts, lido): assert lido.balanceOf(accounts[9]) == 0 return accounts[9] @pytest.fixture(scope='module') def ape(accounts): ret...
1,535
579
from reqto.core.reqto import get, post, delete, put, patch, head __all__=[get, post, delete, put, patch, head]
112
40
from codecs import open as codecs_open from setuptools import setup, find_packages # Get the long description from the relevant file with codecs_open('README.rst', encoding='utf-8') as f: long_description = f.read() setup(name='fio_taxa', version='1.0.0', description=u"Classification of GeoJSON feat...
911
300
# -*- coding: utf-8 -*- from collections import deque def cutBar(m, n): res, now = 0, 1 while now < n: now += now if now < m else m res += 1 return res def cutBarBFS(m, n): if n == 1: return 0 que = deque([n]) res = 0 while que: size = len(que) for...
829
319
""" Itanium CXX ABI Mangler Reference: http://mentorembedded.github.io/cxx-abi/abi.html The basics of the mangling scheme. We are hijacking the CXX mangling scheme for our use. We map Python modules into CXX namespace. A `module1.submodule2.foo` is mapped to `module1::submodule2::foo`. For parameterized numba ty...
6,108
2,027
import requests import json class test(object): def __init__(self): self._debug = False self._http_debug = False self._https = True self._session = requests.session() # use single session for all requests def update_csrf(self): # Retrieve server csrf and update session's he...
1,247
358
from ScopeFoundry.data_browser import DataBrowser from FoundryDataBrowser.viewers.hyperspec_base_view import HyperSpectralBaseView import numpy as np import h5py from qtpy import QtWidgets from ScopeFoundry.logged_quantity import LQCollection import time from FoundryDataBrowser.viewers.plot_n_fit import MonoExponentia...
15,483
5,141
import numpy as np import numpy.matlib # soma das matrizes A = np.array([[1,0],[0,2]]) B = np.array([[0,1],[1,0]]) C = A + B print(C) # soma das linhas A = np.array([[1,0],[0,2]]) B = np.array([[0,1],[1,0]]) s_linha = sum(A) print(s_linha) # soma dos elementos A = np.array([[1,0],[0,2]]) B = np.array([[0,1],[1,0]]...
854
450
# -*- coding: utf-8 -*- """Define action class. """ from enum import Enum from . import assertion from .basedata import BaseData from .description import Description, NoDesc, DescType from .flag import Flag, NoFlag, NoDeflag from .basesubject import NoSubject from .person import Person from .chara import Chara from .wh...
5,459
1,777
import pyblish.api class FusionIncrementCurrentFile(pyblish.api.ContextPlugin): """Increment the current file. Saves the current file with an increased version number. """ label = "Increment current file" order = pyblish.api.IntegratorOrder + 9.0 hosts = ["fusion"] families = ["render.f...
1,025
290
######### # Copyright (c) 2013 GigaSpaces Technologies Ltd. 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...
2,346
737
"""fontTools.misc.bezierTools.py -- tools for working with bezier path segments.""" __all__ = [ "calcQuadraticBounds", "calcCubicBounds", "splitLine", "splitQuadratic", "splitCubic", "splitQuadraticAtT", "splitCubicAtT", "solveQuadratic", "solveCubic", ] from fontTools.misc.arrayTools import calcBounds impo...
11,096
6,120
# Standard Libraries import subprocess import datetime import sys # print en consola import os import json # Local Libraries import define import analyze import prepare import fselect import evaluate import improve import tools import pandas as pd from flask_login import LoginManager, login_required, login_user, logo...
19,403
6,288
import sys, requests, json, time METRIC_NAME = "builtin:billing.ddu.metrics.byEntity" PAGE_SIZE = 500 sys.tracebacklimit = 0 # python .\dduConsumptionPerMZ.py 2020-08-01T12:00:00+02:00 2020-08-10T12:00:00+02:00 https://mySampleEnv.live.dynatrace.com/api/ abcdefghijklmnop 60 # python .\dduConsumptionPerMZ.py 2020-08-0...
7,344
2,427
import numpy as np import scipy import matplotlib.pyplot as plt import sys def compute_r_squared(data, predictions): ''' In exercise 5, we calculated the R^2 value for you. But why don't you try and and calculate the R^2 value yourself. Given a list of original data points, and also a li...
936
294
#!/usr/bin/env python # type: ignore """Setup script.""" from setuptools import setup def _get_version(): with open("pyltsv/_version.py") as f: for line in f: if line.startswith("__version__"): delim = '"' if '"' in line else "'" return line.split(delim)[1] ...
414
132
import collections import decimal import json import logging from django.apps import apps from django.conf import settings from django.contrib.contenttypes.fields import GenericRelation from django.contrib.postgres.fields import JSONField from django.core.exceptions import ValidationError from django.core.validators i...
15,328
4,375
class Template: def __init__(self, data): """Class representing log templates. Note: Timestamps are represented in ISO format with timezone information. e.g, 2021-10-07T13:18:09.178477+02:00. """ self._timestamp = data.get("@timestamp", None) self....
2,030
639