text
string
size
int64
token_count
int64
from __future__ import annotations import argparse import bisect import os from .extension.extract import extract_omop def extract_omop_program() -> None: parser = argparse.ArgumentParser( description="An extraction tool for OMOP v5 sources" ) parser.add_argument( "omop_source", type=st...
1,600
493
# Generated by Django 3.2.7 on 2021-09-16 12:38 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("chains", "0026_chain_l2"), ] operations = [ migrations.AddField( model_name="chain", name="description", ...
390
135
from datetime import date from django.db.models import QuerySet from payments.enums import OrderStatus from payments.models import BerthProduct, Order from ...models import BerthLease from ...utils import calculate_season_end_date, calculate_season_start_date from .base import BaseInvoicingService class BerthInvoi...
1,288
383
import bpy from bpy.props import * from ... base_types import AnimationNode, DataTypeSelectorSocket compare_types = ["A = B", "A != B", "A < B", "A <= B", "A > B", "A >= B", "A is B","A is None"] compare_types_items = [(t, t, "") for t in compare_types] numericLabelTypes = ["Integer", "Float"] class CompareNode(bpy....
2,561
810
import os import options import networks import utils from argparse import ArgumentParser def main(): args = options.get_args() cycleGAN = networks.CycleGAN(args) if args.train == args.test: print("What are we even doing here?") elif args.train: print("Training") print(args) ...
460
146
#!/usr/bin/env python3 # -*- coding: utf-8 -*- try: import base64 import binascii import codecs import random except ImportError as import_fail: print(f"Import error: {import_fail}") print("Please install this module.") raise SystemExit(1) class utils(object): def enc_utf(input_str)...
1,457
507
#!/usr/bin/env python # # Copyright (C) 2014 Narf Industries <info@narfindustries.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 restriction, including without limitation # th...
8,908
3,764
import random def saisieSomme(): entree = None while entree not in range(2, 13): entree = int(input("Entrez un nombre entre 2 et 12 inclus : ")) return entree def sommeDeuxDes(): de1 = random.randint(1, 6) de2 = random.randint(1, 6) print("valeur du dé 1 :", de1, "| valeur du dé 2 ...
480
202
import random import time print("\n\nWelcome..\n") time.sleep(2) print(''' _______ ---' ____) (_____) (_____) (____) ---.__(___) ''') print(''' _______ ---' ____)____ ______) _______) _______) ---.__________) ''') print(''' _______ ---' ____)____ ...
1,228
459
# -*- coding: utf-8 -*- from .globals import request_context try: from django.utils.deprecation import MiddlewareMixin except ImportError: # Django < 1.10 MiddlewareMixin = object class RequestContextMiddleware(MiddlewareMixin): def process_request(self, request): request_context.init_by_reques...
440
134
from __future__ import print_function import os import time import sys from functools import wraps from pytest import mark from zmq.tests import BaseZMQTestCase from zmq.utils.win32 import allow_interrupt def count_calls(f): @wraps(f) def _(*args, **kwds): try: return f(*args, **kwds) ...
1,724
517
import pytest from dagster import ModeDefinition, build_schedule_context, pipeline, solid, validate_run_config from docs_snippets.concepts.partitions_schedules_sensors.schedules.schedule_examples import ( my_daily_schedule, my_hourly_schedule, my_modified_preset_schedule, my_monthly_schedule, my_pre...
1,150
402
# -*- coding: utf-8 -*- import json from rest_framework import generics from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.parsers import MultiPartParser, FormParser from rest_framework_jwt.authentication import JSONWebTokenAuthentication from rest_framework.decora...
17,803
4,627
def process(record): ids = (record.get('idsurface', '') or '').split(' ') if len(ids) > 4: return {'language': record['language'], 'longitude': float(record['longitude'] or 0), 'latitude': float(record['latitude'] or 0), 'idsurface': ids}
279
91
import mysql.connector mydb = mysql.connector.connect( host ='127.0.0.1', port = 3306, user ='root', password = '', database="cadastro" ) cursor = mydb.cursor() cursor.execute("SELECT * FROM gafanhotos LIMIT 3") resultado = cursor.fetchall() for x in resultado: print(x)
297
113
# print function on main branch result = ['main' if i%5==0 else i for i in range(1, 10+1)] print(result)
105
40
from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt from billing.utils import initiate_transaction PAYTM_MERCHANT_ID = 'SNeEfa79194346659805' PAYTM_MERCHANT_KEY = 'T7V3cbVmVIN1#YK7' def initiate(request): order_id = request.session['order_id'] response = initiate_transac...
648
244
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'ipetrash' # TODO: использовать http://www.cbr.ru/scripts/Root.asp?PrtId=SXML или разобраться с данными от query.yahooapis.com # непонятны некоторые параметры # TODO: сделать консоль # TODO: сделать гуй # TODO: сделать сервер import requests rs = requests....
622
252
import abc import logging from datetime import datetime from .log_adapter import adapt_log LOGGER = logging.getLogger(__name__) class RunnerWrapper(abc.ABC): """ Runner wrapper class """ log = adapt_log(LOGGER, 'RunnerWrapper') def __init__(self, func_runner, runner_id, key, tracker, log_exception=Tru...
2,329
660
nome = input('Dgigite seu nome completo: ')
46
18
# -*- coding: utf-8 -*- # Import Librairies # # Python import requests # # User from data_collect.mushroomObserver.api import api #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Constants #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ TAXON_TABLE_NAME = 'names' #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~...
8,478
2,496
import scipy.stats as stat import pandas as pd import plotly.graph_objs as go from hidrocomp.graphics.distribution_build import DistributionBuild class GenPareto(DistributionBuild): def __init__(self, title, shape, location, scale): super().__init__(title, shape, location, scale) def cumulative(se...
2,636
807
import html import re import random import amanobot import aiohttp from amanobot.exception import TelegramError import time from config import bot, sudoers, logs, bot_username from utils import send_to_dogbin, send_to_hastebin async def misc(msg): if msg.get('text'): #aqui ele repete as coisas co...
18,853
5,654
""" Challenge #1: Write a function that retrieves the last n elements from a list. Examples: - last([1, 2, 3, 4, 5], 1) ➞ [5] - last([4, 3, 9, 9, 7, 6], 3) ➞ [9, 7, 6] - last([1, 2, 3, 4, 5], 7) ➞ "invalid" - last([1, 2, 3, 4, 5], 0) ➞ [] Notes: - Return "invalid" if n exceeds the length of the list. - Return an emp...
685
354
import traceback import copy import gc from ctypes import c_void_p import itertools import array import math import numpy as np from OpenGL.GL import * from PyEngine3D.Common import logger from PyEngine3D.Utilities import Singleton, GetClassName, Attributes, Profiler from PyEngine3D.OpenGLContext import OpenGLContex...
25,407
8,254
""" A server that responds with two pages, one showing the most recent 100 tweets for given user and the other showing the people that follow that given user (sorted by the number of followers those users have). For authentication purposes, the server takes a commandline argument that indicates the file containing Twit...
2,480
763
#!/usr/bin/env python # Copyright 2017 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
4,625
1,491
""" Tests for CaseStepResource api. """ from tests.case.api.crud import ApiCrudCases import logging mozlogger = logging.getLogger('moztrap.test') class CaseStepResourceTest(ApiCrudCases): @property def factory(self): """The model factory for this object.""" return self.F.CaseStepFactory() ...
2,578
710
"""Find stars that are both in our sample and in Shull+21""" import numpy as np import get_data from matplotlib import pyplot as plt data = get_data.get_merged_table() shull = get_data.get_shull2021() matches = [name for name in data["Name"] if name in shull["Name"]] print(len(matches), " matches found") print(matche...
817
317
import numpy as np import matplotlib.pyplot as plt from collections import Iterable mrkr1 = 12 mrkr1_inner = 8 fs = 18 # FUNCTION TO TURN NESTED LIST INTO 1D LIST def flatten(lis): for item in lis: if isinstance(item, Iterable) and not isinstance(item, str): for x in flatten(item): ...
7,941
3,035
import pytest import wtforms from dmutils.forms.fields import DMBooleanField from dmutils.forms.widgets import DMSelectionButtonBase class BooleanForm(wtforms.Form): field = DMBooleanField() @pytest.fixture def form(): return BooleanForm() def test_value_is_a_list(form): assert isinstance(form.field...
687
225
a = 2 ** 50 b = 2 ** 50 * 3 c = 2 ** 50 * 3 - 1000 d = 400 / 2 ** 50 + 50 print(a,b,c,d)
89
69
from django.db import models class BaseModel(models.Model): class Meta: abstract = True def reload(self): new_self = self.__class__.objects.get(pk=self.pk) # Clear and update the old dict. self.__dict__.clear() self.__dict__.update(new_self.__dict__)
302
90
# -*- coding: utf-8 -*- from bs4 import BeautifulSoup, SoupStrainer import bs4 import requests import csv import pandas as pd import os import re """ Module 3 : retrieve text from each article & basic preprocess """ ignore_sents = ['Les associations Vikidia', 'Répondre au sondage', 'Aller à :', 'Récupérée de « ht...
7,025
2,625
import os import pickle import subprocess import dgl from dgl.data import DGLDataset import graph_parser class AssemblyGraphDataset(DGLDataset): """ A dataset to store the assembly graphs. A class that inherits from the DGLDataset and extends the functionality by adding additional attributes and pr...
4,411
1,431
import io import os from svgutils import transform as svg_utils import qrcode.image.svg from cwa_qr import generate_qr_code, CwaEventDescription class CwaPoster(object): POSTER_PORTRAIT = 'portrait' POSTER_LANDSCAPE = 'landscape' TRANSLATIONS = { POSTER_PORTRAIT: { 'file': 'poster/p...
1,297
464
# MIT licensed # Copyright (c) 2020 lilydjwg <lilydjwg@gmail.com>, et al. from .httpclient import session, TemporaryError, HTTPError from .util import ( Entry, BaseWorker, RawResult, VersionResult, AsyncCache, KeyManager, GetVersionError, ) from .sortversion import sort_version_keys from .ctxvars import tries, pro...
335
111
# pdaggerq - A code for bringing strings of creation / annihilation operators to normal order. # Copyright (C) 2020 A. Eugene DePrince III # # This file is part of the pdaggerq package. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the Lice...
15,298
8,069
from datetime import date, datetime, timedelta from traceback import format_exc from requests import get pageviews_url = 'https://wikimedia.org/api/rest_v1/metrics/pageviews/per-article' def format_date(d): return datetime.strftime(d, '%Y%m%d%H') def article_views(article, project='en.wikipedia', access='all-acce...
803
283
# -*- encoding:utf-8 -*- """Autogenerated file, do not edit. Submit translations on Transifex.""" MESSAGES = { "%d min remaining to read": "%d minutoj por legi", "(active)": "(aktiva)", "Also available in:": "Ankaŭ disponebla en:", "Archive": "Arkivo", "Atom feed": "", "Authors": "Aŭtoroj", ...
1,848
735
"""DNS Authenticator for deSEC.""" import json import logging import time import requests import zope.interface from certbot import errors from certbot import interfaces from certbot.plugins import dns_common logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) @zope.interface.implementer(interfaces....
6,880
1,976
""" some tools for plotting EEG data and doing visual comparison """ from eeg_project.read_data import (my_read_eeg_generic, SAMP_FREQ, pass_through, accumulate_subject_file_list, files_skip_processing, sample_file_list, match_types) import numpy as np import pandas as pd import torch from collections import de...
21,474
7,104
import asyncio from pyrogram import filters from pyrogram.errors import PeerIdInvalid, UserIdInvalid, UsernameInvalid from pyrogram.types import ChatPermissions, Message from megumin import megux from megumin.utils import ( check_bot_rights, check_rights, extract_time, is_admin, is_dev, is_sel...
8,634
2,884
import argparse import os # Use a custom parser that lets us require a variable from one of CLI or environment variable, # this way we can pass creds through CLI for local testing but via environment variables in CI class EnvDefault(argparse.Action): """Argument parser that accepts input from CLI (preferred) or a...
2,619
689
# -*- coding: utf-8 -*- # # fumi deployment tool # https://github.com/rmed/fumi # # The MIT License (MIT) # # Copyright (c) 2016 Rafael Medina García <rafamedgar@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Softwa...
5,526
1,618
import math import unittest from scipy import integrate from ..problem import Problem from ..algorithm_genetic import NSGAII from ..algorithm_sweep import SweepAlgorithm from ..benchmark_functions import Booth from ..results import Results from ..operators import LHSGenerator from ..surrogate_scikit import SurrogateM...
15,396
5,813
# 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 ...
16,560
5,628
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from logging import config config.dictConfig({ 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'standard': { 'format': '%...
728
239
# @Time : 2019/06/14 7:55AM # @Author : HGzhao # @File : 2019_618_PickMaomao.py import os,time def pick_maomao(): print(f"点 合合卡 按钮") os.system('adb shell input tap 145 1625') time.sleep(1) print(f"点 进店找卡 按钮") os.system('adb shell input tap 841 1660') time.sleep(13) print(f"猫猫出现啦,点击得...
612
353
from helix import component class ExamplePythonComponent(component.Component): """An example Python component.""" name = "example-python-component" verbose_name = "Example Python Component" type = "example" version = "1.0.0" description = "An example Python component" date = "2020-10-20 1...
676
222
# -*- coding: utf-8 -*- # Copyright © 2014 Cask Data, 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 applica...
2,239
573
import numpy as np import pandas import pandas as pd import torch import torchvision import ssl import gzip import json from tqdm import tqdm from torchvision.datasets.utils import download_url from MySingletons import MyWord2Vec from nltk.tokenize import TweetTokenizer import os import tarfile from lxml ...
53,877
18,598
import os import json import boto3 import datetime import hashlib import secrets import time from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText table_name = os.environ['DDB_TABLE'] ses_client = boto3.client('ses') ddb_client = boto3.client('dynamodb') unsubscribe_url = os.environ['UNS...
8,263
3,080
# coding: utf-8 import fnmatch import pathlib import os.path import re import logging logging.basicConfig(level=logging.INFO) INCLUDED_SOURCES = ("*.py", ) EXCLUDED_SOURCES = ("__*__.py", ) INCLUDED_SOURCES_REGEX = tuple(re.compile(fnmatch.translate(pattern)) for pattern in INCLUDED_SO...
2,120
668
# Copyright 2021 VMware, Inc. # SPDX-License-Identifier: Apache-2.0 import argparse import os from githubDataExtraction import GithubDataExtractor def getRepos(access_token, organization, reaction): """ Method to extract data for all repositories in organization """ extractor = GithubDataExtractor(a...
1,609
484
""" Reads (article_id, [tokens]) from tokens.pickle and writes: (article_id, w2v) (article_id, bow) """ import json import sys import os import pickle import psycopg2 from multiprocessing.pool import Pool import numpy as np import zlib # from gensim.models import Word2Vec from gensim.models import Word2Vec, KeyedVect...
2,867
938
from math import sin, radians, asin, degrees def snell_descartes(n1, n2, teta1): # n1*sin(teta1) = n2 * sin(teta2) # teta2 = n1 teta2 = (n1 * sin(radians(teta1)))/n2 return degrees(asin(teta2))
212
100
from kivy.app import App from kivy.properties import StringProperty from kivy.uix.screenmanager import Screen from Constants.ContentType import ContentType from Domain.PresentationElement import PresentationElement class PresentationLayout(Screen): """ Fullscreen layout for presenting content """ imag...
3,972
1,088
from rest_framework.serializers import ( ModelSerializer, HyperlinkedIdentityField, SerializerMethodField, ValidationError, ) from django_elasticsearch_dsl_drf.serializers import DocumentSerializer from .documents import ( ArticleDocument ) from django.contrib.auth.models import User from article...
1,451
384
from http import HTTPStatus from django.http import HttpRequest from django.utils.translation import gettext_lazy as _ from apps.api.errors import ApiException from apps.core.models import ApiKey class VariablesService(object): def __init__( self, request: HttpRequest, variables: dict ...
2,054
549
from pm4pygpu.constants import Constants from numba import cuda import numpy as np def post_grouping_function(custom_column_activity_code, custom_column_timestamp, custom_column_case_idx, custom_column_pre_activity_code, custom_column_pre_timestamp, custom_column_pre_case, custom_column_variant_number, custom_colu...
3,007
1,250
from django.urls import path, register_converter from . import views from django.shortcuts import redirect app_name = 'main_app' urlpatterns = [ path('', lambda request: redirect('voting/')), path('voting/', views.voting, name='voting'), ]
268
84
from database_utils import PokeDatabase, DB_FILENAME def get_poke_by_name(poke_name: str) -> dict: with PokeDatabase(DB_FILENAME) as cursor: cursor.execute('''SELECT name, type1, type2, sum_stats, hp, attack, special_attack, defense, special_defense FROM Pokemons WHERE name = ?''', ...
3,402
1,049
#!/usr/bin/python35 import calc from calc import mult print(calc.add(1, 2)) print(calc.dec(2, 3)) print(calc.div(1, 2)) print(mult(2, 3))
140
66
from asva.restoring_force.RestoringForce import RestoringForce class Elastic(RestoringForce): def step(self, dis: float) -> None: # init self.init_step(dis) # end self.end_step(self.k0)
223
76
G = 6.67408e-11 # N-m2/kg2 # # Normalize the constants such that m, r, t and v are of the order 10^1. # def get_normalization_constants_alphacentauri(): # Normalize the masses to the mass of our sun m_nd = 1.989e+30 # kg # Normalize distances to the distance between Alpha Centauri A and Alpha Centa...
1,169
495
from assigner.backends.base import RepoError from assigner.config import DuplicateUserError import logging logger = logging.getLogger(__name__) def get_filtered_roster(roster, section, target): if target: roster = [s for s in roster if s["username"] == target] elif section: roster = [s for s...
1,118
338
""" Genetic solution to the 0/1 Knapsack Problem. usage: knapsack01.py [-h] [--data-file DATA_FILE] [--population-size POPULATION_SIZE] [--iterations MAX_ITERATIONS] [--mutation MUTATION_PROB] [--crossover CROSSOVER_PROB] [--seed SEED] ...
5,721
1,813
# -*- coding: utf-8 -*- """ @date Created on Tue Jan 12 13:54:56 2016 @copyright (C) 2015-2016 EOMYS ENGINEERING. @author pierre_b """ from os.path import join from unittest import TestCase import matplotlib.pyplot as plt from numpy import array, pi, zeros from pyleecan.Classes.Frame import Frame from pyleecan.Class...
2,456
985
import json import math import re from django.urls import reverse from django.http.response import HttpResponse, HttpResponseRedirect from django.shortcuts import redirect, render from django.template.defaultfilters import slugify from django.db.models import Q, F from haystack.query import SQ, SearchQuerySet from dja...
23,082
6,833
from flexipage.forms import FlexiModelForm from mezzanine.core.forms import Html5Mixin from django import forms from models import Feedback class FeedbackForm(FlexiModelForm, Html5Mixin): class Meta: model = Feedback name = forms.CharField(widget=forms.TextInput(attrs = {'placeholder': 'Name', 'class'...
871
269
# Importing default django packages: from django.db import models from django.template.defaultfilters import slugify # Importing models from the research core: from research_core.models import Topic # Importing 3rd party packages: from tinymce import models as tinymce_models class BlogPost(models.Model): """The ...
2,953
803
# Write a program that asks the user what kind of rental car they # would like. Print a message about that car, such as “Let me see if I can find you # a Subaru.” car = input("What type of rental rental car would you like? ") print(f"Checking database to find a {car}") # Write a program that asks the user how many pe...
1,082
335
from contextlib import contextmanager import torch import torch.nn.functional as F from torch.nn import Module, Parameter from torch.nn import init _WN_INIT_STDV = 0.05 _SMALL = 1e-10 _INIT_ENABLED = False def is_init_enabled(): return _INIT_ENABLED @contextmanager def init_mode(): global _INIT_ENABLED ...
11,421
4,135
import re import numpy as np import tensorflow as tf from tensorflow.keras import layers as tfkl from tensorflow_probability import distributions as tfd from tensorflow.keras.mixed_precision import experimental as prec import common class EnsembleRSSM(common.Module): def __init__( self, config, ens...
47,881
15,674
from .easy_logs_summary_imp import * from .dropbox_links import * from .require import *
88
28
import pytest from google.protobuf import json_format import verta.code from verta._internal_utils import _git_utils class TestGit: def test_no_autocapture(self): code_ver = verta.code.Git(_autocapture=False) # protobuf message is empty assert not json_format.MessageToDict( ...
966
299
import sys import common import math def get_filename(): filename = sys.argv[0] filename = filename.split("/")[-1] filename = filename.split(".")[0] return filename data = common.get_file_contents("data/{}_input.txt".format(get_filename())) def run_slop_test(right, down): # holds the map we wil...
1,617
551
from django import forms class PostForm(forms.Form): title = forms.CharField(max_length=30, label='タイトル') content = forms.CharField(label='内容', widget=forms.Textarea())
174
58
from django.urls import path from django.conf.urls import url from django.urls import path,include import grievance.views as VIEWS from django.conf.urls.static import static from django.conf import settings app_name = 'grievance' urlpatterns =[ # path('', VIEWS.HomeView.as_view()) path('level1/', VIEWS.level1HomeVi...
1,395
515
'''This is the deep learning implementation in Keras for graph classification based on FGSD graph features.''' import numpy as np import scipy.io import networkx as nx from grakel import datasets from scipy import sparse from sklearn.utils import shuffle from scipy import linalg import time import csv from ...
2,545
964
from time import sleep from cores import * print(f'{cores["azul"]}Em breve a queima de fogos irá começar...{limpar}') for c in range(10, -1, -1): print(c) sleep(1) print(f'{cores["vermelho"]}{fx["negrito"]}Feliz ano novo!{limpar} 🎆 🎆')
244
112
from optparse import make_option from django.apps import apps from django.conf import settings from django.core.files.storage import default_storage from django.core.management.base import BaseCommand from django.db.models import FileField, ImageField from database_files.models import File class Command(BaseCommand...
3,206
881
from spectacles import utils from spectacles.logger import GLOBAL_LOGGER as logger from unittest.mock import MagicMock import pytest import unittest TEST_BASE_URL = "https://test.looker.com" def test_compose_url_one_path_component(): url = utils.compose_url(TEST_BASE_URL, ["api"]) assert url == "https://test...
3,814
1,333
from itertools import combinations_with_replacement S, k = [i for i in input().split(" ")] k = int(k) combs = list(combinations_with_replacement(sorted(S), k)) combs.sort() [print("".join(i)) for i in combs]
210
79
''' Service class for utility functions that I need throught the app ''' class Utilities: @staticmethod def clickedOn(onScreenCoordinates, grid, cell, clickCoords): i, j = cell cellX, cellY = onScreenCoordinates[i][j] x, y = clickCoords import math, constants radius = math.sqrt((cellX - x) * (cellX - x)...
1,839
819
import pytest from unittest.mock import Mock from datacrunch.http_client.http_client import HTTPClient BASE_URL = "https://api-testing.datacrunch.io/v1" ACCESS_TOKEN = "test-token" CLIENT_ID = "0123456789xyz" @pytest.fixture def http_client(): auth_service = Mock() auth_service._access_token = ACCESS_TOKEN ...
512
188
# -*- coding: utf-8 -*- from .base import ( Pessoa, PessoaFisica, PessoaJuridica, Endereco, Telefone, Email, Site, Banco, Documento, COD_UF, UF_SIGLA, ) from .empresa import Empresa, MinhaEmpresa from .cliente import Cliente from .fornecedor import Fornecedor from .transport...
414
160
from .detection import BodyDetector from .encoding import BodyEncoder
69
18
import asyncio import re from base64 import b64encode # pattern taken from: # https://mybuddymichael.com/writings/a-regular-expression-for-irc-messages.html IRC_MSG_PATTERN = "^(?:[:](\S+) )?(\S+)(?: (?!:)(.+?))?(?: [:](.+))?$" # class adapted from a sample kindly provided by https://github.com/emersonveenstra class ...
3,113
876
"""Module containing definitions of arithmetic functions used by perceptrons""" from abc import ABC, abstractmethod import numpy as np from NaiveNeurals.utils import ErrorAlgorithm class ActivationFunction(ABC): """Abstract function for defining functions""" label = '' @staticmethod @abstractmeth...
5,077
1,515
# alevel.py Test/demo program for Adafruit ssd1351-based OLED displays # Adafruit 1.5" 128*128 OLED display: https://www.adafruit.com/product/1431 # Adafruit 1.27" 128*96 display https://www.adafruit.com/product/1673 # The MIT License (MIT) # Copyright (c) 2018 Peter Hinch # Permission is hereby granted, free of cha...
3,221
1,220
import logging from django.db import models logger = logging.getLogger(__name__) class PostmarkWebhook(models.Model): received_at = models.DateTimeField(auto_now_add=True) body = models.JSONField() headers = models.JSONField() note = models.TextField(blank=True) class Status(models.TextChoices):...
502
156
# -*- coding: UTF-8 -*- """ @Cai Yichao 2020_09_08 """ import torch.nn as nn import torch.nn.functional as F from models.blocks.SE_block import SE from models.blocks.conv_bn import BN_Conv2d class ResNeXt_Block(nn.Module): """ ResNeXt block with group convolutions """ def __init__(self, in_chnls, ca...
1,372
551
# Generated by Django 2.0.13 on 2019-02-28 19:18 import django.contrib.postgres.fields from django.db import migrations, models import django.db.models.deletion import uuid class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( ...
2,948
841
from .. import json from ..exceptions import UnknownObjectError from ..snowflake import Snowflake __all__ = ('BaseObject', 'ObjectWrapper') class _IDField(json.JSONField): def __init__(self) -> None: super().__init__('id', repr=True) def construct(self, value: str) -> Snowflake: return Snowf...
1,985
654
"""GUI elements for use in the sidebar of the main window. Classes ------- **InfoWidget** - Sidebar widget for basic file information. **MetaWidget** - Sidebar widget for basic metadata. **ConsoleWidget** - Sidebar widget for basic text output. """ from PySide2.QtCore import QSize from PySide2.QtWidgets import QForm...
4,098
1,238
""" BFS """ class Solution909: pass
59
28
# Use Netmiko to change the logging buffer size (logging buffered <size>) on pynet-rtr2. from getpass import getpass from netmiko import ConnectHandler def main(): password = getpass() pynet_rtr2 = {'device_type': 'cisco_ios', 'ip': '50.76.53.27', 'username': 'pyclass', 'password': password, 'port': 8022} ...
713
252
# flake8: noqa import codecs import os from platform import python_version from setuptools import find_packages, setup PACKAGE_NAME = "textx-ls-core" VERSION = "0.2.0" AUTHOR = "Daniel Elero" AUTHOR_EMAIL = "danixeee@gmail.com" DESCRIPTION = ( "a core language server logic for domain specific languages based on t...
2,106
739