text
string
size
int64
token_count
int64
from typing import Optional, Callable import requests from requests.auth import AuthBase from requests.exceptions import RequestException class BearerAuth(AuthBase): def __init__(self, token): self.token = token def __call__(self, r): r.headers['Authorization'] = f'Bearer {self.token}' ...
1,881
526
import os import shutil from .ZipFileManager import ZipFileManager from .DiskFileManager import DiskFileManager from .Directory import Directory import string printable = set(string.printable) - set("\x0b\x0c") def is_hex(s): return any(c not in printable for c in s) def file_tree(target, replace=False): ...
1,395
384
import sys import socket import time ip = '127.0.0.1' port = 9001 if (len(sys.argv)>1): ip = sys.argv[1] if (len(sys.argv)>2): port = int(sys.argv[2]) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((ip,port)) sock.send('bip\n\r') data = sock.recv(80) print data sock.send('TTS[it-IT...
628
296
from abc import ABC, abstractmethod from typing import List from .common import ( AtCell, BasicMessage, GroupMessage, FriendMessage, MsgCellType, MessageType, PlainCell, ) from ..utils import is_str_blank, str_contains class MsgMatcher(ABC): def msg_chain_from_ctx(self, ctx): r...
3,461
1,157
class Solution: def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: if root: root.left,root.right = self.invertTree(root.right),self.invertTree(root.left) return root return None
240
68
from django.contrib import admin from django.contrib.auth.admin import UserAdmin as DjangoUserAdmin from django.contrib.auth.models import Group from django.utils.translation import ugettext_lazy as _ from main.models import UserInfo, User, Child, Volunteer, Donor, Letter, Need, PurchaseForInstitute, PurchaseForNeed, ...
1,407
452
import tdl import time import hunting.constants as c class Renderer: def __init__(self, main_console=None, level_display_width=c.SCREEN_WIDTH, level_display_height=c.SCREEN_HEIGHT): if main_console is None: self.main_console = tdl.init(level_display_width, level_display_height, 'From Renderer ...
2,515
872
from django.db import models class Idea(models.Model): title = models.CharField(max_length=255, unique=True) description = models.TextField() author = models.OneToOneField('events.Registrant', related_name='author_idea', on_delete=models....
1,732
471
""" Module for Pytorch dataset representations """ import torch from torch.utils.data import Dataset class SlicesDataset(Dataset): """ This class represents an indexable Torch dataset which could be consumed by the PyTorch DataLoader class """ def __init__(self, data): self.data = data ...
2,348
677
from zenslackchat.zendesk_base_webhook import BaseWebHook from zenslackchat.zendesk_email_to_slack import email_from_zendesk from zenslackchat.zendesk_comments_to_slack import comments_from_zendesk class CommentsWebHook(BaseWebHook): """Handle Zendesk Comment Events. """ def handle_event(self, event, slac...
845
269
# Import modules import groupdocs_merger_cloud from Common import Common # This example demonstrates how to move document page to a new position class MovePage: @classmethod def Run(cls): pagesApi = groupdocs_merger_cloud.PagesApi.from_config(Common.GetConfig()) options = groupdocs_merger_cl...
699
203
y_pred=ml.predict(x_test) print(y_pred) from sklearn.metrics import r2_score r2_score(y_test,y_pred) pred_y_df=pd.DataFrame({'Actual Value':y_test,'Predicted Value':y_pred, 'Difference': y_test-y_pred}) pred_y_df[0:20]
221
101
# -*- coding: utf-8 -*- """ This module offers util functions to be called and used in other modules """ from datetime import datetime import os import json import pickle import string import random import numpy as np import pandas as pd from matplotlib import pyplot as plt import seaborn as sns from sklearn impo...
5,512
1,729
import asyncio import discord from discord.ext import commands import re import sqlite3 from urllib.parse import quote as uriquote import html CURR = ["AUD", "BRL", "CAD", "CHF", "CLP", "CNY", "CZK", "DKK", "EUR", "GBP", "HKD", "HUF", "IDR", "ILS", "INR", "JPY", "KRW", "MXN", "MYR", "NOK", "NZD", "P...
7,504
2,429
from SG_GetFeatureMatrix import * from SG_VectorY import * featureMatrix = featureMatrixFromReviews() Y = getYVector() def getDataForClassifier() : return featureMatrix, Y
174
54
# Generated by Django 3.1.4 on 2021-01-17 19:12 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] ope...
1,882
550
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright (c) 2013 dotCloud, 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...
8,621
2,598
import unittest import unittest.mock as mock import asyncio import pyx.http as http def create_dummy_message(): msg = http.HttpMessage(None) msg.headers = [ http.HttpHeader('Server', 'Pyx'), http.HttpHeader('Cookie', 'a'), http.HttpHeader('Cookie', 'b'), ] return msg def crea...
9,048
2,924
# -*- coding: utf-8 -*- # Copyright 2013 splinter 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 import unittest from splinter import Browser from .fake_webapp import EXAMPLE_APP from .base import WebDriverTests from selen...
1,791
546
import os import json from File.file import File os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' def fileRead(fileName, encoding='utf-8'): with open(fileName, encoding=encoding) as f: return f.read() def main(): from Automation.distributor import Distributor from Performance import recoder from ...
1,349
427
import struct import numpy as np import pytest import miniglm def test_add_vec_vec(): res = miniglm.add((1.0, 2.0, 3.0), (1.5, 1.8, 1.2)) np.testing.assert_almost_equal(res, (2.5, 3.8, 4.2)) assert type(res) is tuple def test_add_vec_scalar(): res = miniglm.add((1.0, 2.0, 3.0), 0.5) np.testing...
4,814
2,520
# -*- coding: utf-8 -*- from flask import Blueprint, redirect from flaskbb.utils.helpers import render_template from .forms import AddForm, DeleteForm from .models import MyPost from flaskbb.extensions import db news = Blueprint("news", __name__, template_folder="templates") def inject_news_link(): return rende...
1,131
350
from stix_shifter_utils.stix_translation.src.json_to_stix import json_to_stix_translator from stix_shifter_utils.stix_translation.src.utils.transformer_utils import get_module_transformers from stix_shifter_modules.aws_athena.entry_point import EntryPoint import unittest MODULE = "aws_athena" entry_point = EntryPoint(...
23,742
7,477
#!/usr/bin/python # -*- coding: utf-8 -*- #file: 03 login.py #@author: Gorit #@contact: gorit@qq.com #@time: 2020/1/20 12:44 import requests from lxml import etree # 封装类,进行学习猿地的登录和订单的获取 class lMonKey(): # 登录请求地址 loginUrl = "https://www.lmonkey.com/login" # 账户中心地址 orderUrl = "https://www.lmonkey.com/my...
2,236
992
#!/usr/bin/python # -*- coding: utf-8 -*- # This file was created using the DirectGUI Designer from direct.gui import DirectGuiGlobals as DGG from direct.gui.DirectFrame import DirectFrame from direct.gui.DirectLabel import DirectLabel from direct.gui.DirectButton import DirectButton from direct.gui.DirectOptionMenu...
9,730
4,030
from . import FROM_FEED_PUBLISHED_TODAY, STRINGIFY def filter_by_tag(tag, entries): matches = list(filter( lambda x: any(list(map( lambda y: y.term == tag, x.tags ))), entries )) if len(matches) == 0: return "" return "<h2>TIME {} - {} result...
634
228
# Advent of Code 2020 # Day 21 # Author: irobin591 import os import doctest import re re_entry = re.compile(r'^([a-z ]+) \(contains ([a-z, ]*)\)$') with open(os.path.join(os.path.dirname(__file__), "input.txt"), 'r') as input_file: input_data = input_file.read().strip().split('\n') def part1(input_data): "...
3,017
1,008
""" Test that escaping characters for HTML is disabled. """ import os, subprocess def test_escape_singlequote(tmpdir): # Define empty dictionaries doc = {} template = {} # Prepare file names doc['path'] = tmpdir.join("document.md") template['path'] = tmpdir.join("template.yaml") # Prepar...
2,807
908
from flask import Flask, jsonify, request from w3lib.html import get_base_url import extruct import requests app = Flask(__name__) def extract_osm_tags(data): tags = {} schema_org_type = data.get('@type') if schema_org_type == 'Restaurant': tags['amenity'] = 'restaurant' serves_cuisine...
2,761
916
""" A simple Python DAG using the Taskflow API. """ import logging import time from datetime import datetime from airflow import DAG from airflow.decorators import task log = logging.getLogger(__name__) with DAG( dag_id='simple_python_taskflow_api', schedule_interval=None, start_date=datetime(2021, 1, 1)...
702
244
from . import model import numpy as np from scipy import special, stats class RoyleNicholsModel(model.UnmarkedModel): def __init__(self, det_formula, abun_formula, data): self.response = model.Response(data.y) abun = model.Submodel("Abundance", "abun", abun_formula, np.exp, data.site_covs) ...
1,744
663
#Contains the functions needed to process both chords and regularized beards # proc_chords is used for chords #proc_beard_regularize for generating beards #proc_pdf saves pdfs of a variable below cloud base #Both have a large overlap, but I split them in two to keep the one script from getting to confusing. import nu...
75,933
26,347
"""D. mel housekeeping genes based on tau. Uses the intersection of w1118 and orgR to create a list of D. mel housekeeping genes. """ import os from functools import partial import pandas as pd from larval_gonad.io import pickle_load, pickle_dump def main(): # Load mapping of YOgn to FBgn annot = pickle_loa...
1,656
580
""" Api Key validation """ from typing import Optional from fastapi.security.api_key import APIKeyHeader from fastapi import HTTPException, Security, Depends from starlette.status import HTTP_401_UNAUTHORIZED, HTTP_400_BAD_REQUEST, HTTP_403_FORBIDDEN from server.core.security import verify_key from server.db.mongodb ...
2,226
683
#!/usr/bin/env python # This is a slightly modified version of ChromiumOS' splitconfig # https://chromium.googlesource.com/chromiumos/third_party/kernel/+/stabilize-5899.B-chromeos-3.14/chromeos/scripts/splitconfig """See this page for more details: http://dev.chromium.org/chromium-os/how-tos-and-troubleshooting/kern...
1,253
421
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
1,631
480
#!/usr/bin/env python ''' Notes: - Weak implies weakly supervised learning (4 classes) - Strong implies strongly (fully) superversied learning (10 classes) - frame number is set to 22ms (default); that is the "sweet spot" based on dsp literature - sampling rate is 16kHz (for the MFCC of each track) ...
6,215
2,176
# # Blowfish encrypt - Encrypt selected region with Blowfish # # Copyright (c) 2019, Nobutaka Mantani # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code...
8,638
3,402
# Copyright (C) 2006, 2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED ...
5,734
1,824
__version = '0.1.0' __all__ = ['MultiStreamSelect', 'hexify'] __author__ = 'Natnael Getahun (connect@ngetahun.me)' __name__ = 'multistream' from .multistream import MultiStreamSelect from .utils import hexify
210
77
"""---------------------------------------------------------------------------------* * Copyright (c) 2010-2018 Pauli Parkkinen, Eelis Solala, Wen-Hua Xu, * * Sergio Losilla, Elias Toivanen, Jonas Juselius * * ...
42,648
10,796
# -*- coding: utf-8 -*- import pytest from pathlib_mate.pathlib2 import Path class TestHashesMethods(object): def test(self): p = Path(__file__) assert len({ p.md5, p.get_partial_md5(nbytes=1 << 20), p.sha256, p.get_partial_sha256(nbytes=1 << 20), p.sha512, p.g...
506
204
#!/usr/bin/env python3 """ Usage:: usage: auth.py [-h] [{google,apple,github,jwt}] [jwt] Login to your comma account positional arguments: {google,apple,github,jwt} jwt optional arguments: -h, --help show this help message and exit Examples:: ./auth.py # Log in with google accou...
4,183
1,436
#! /usr/bin/env python # -*- coding: utf-8 -*- ''' Create a Baselight folder with current date and time stamp. You must refresh the Job Manager after running the script. Copyright (c) 2020 Igor Riđanović, Igor [at] hdhead.com, www.metafide.com ''' import flapi from getflapi import getflapi from datetime import dateti...
901
315
__doc__ = """ CallBacks ----------- Provides the callBack interface to collect data over time (see `callback_functions.py`). """ from elastica.callback_functions import CallBackBaseClass class CallBacks: """ CallBacks class is a wrapper for calling callback functions, set by the user. If the user wants ...
4,762
1,241
# Copyright 2016 - Nokia # # 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, sof...
2,961
813
#! /usr/bin/env python3 """Parse through the simulated sequencing group specific kmer counts.""" import argparse as ap from collections import OrderedDict import glob import gzip import os import sys import time import numpy as np import multiprocessing as mp SAMPLES = OrderedDict() KMERS = {} HAMMING = OrderedDict() ...
15,032
4,764
from marshmallow.exceptions import ValidationError class ObjectDoesNotExist(Exception): """Exception if not found results""" pass class CommunicationError(Exception): """Exception for diferents problem with communications.""" pass __all__ = ('ValidationError', 'ObjectDoesNotExist', 'CommunicationE...
327
89
from django.contrib import admin from .models import Songs admin.site.register(Songs) # Register your models here.
117
33
# Draw image time series for one or more plots from jicbioimage.core.image import Image import dtoolcore import click from translate_labels import rack_plot_to_image_plot from image_utils import join_horizontally, join_vertically def identifiers_where_match_is_true(dataset, match_function): return [i for i i...
2,354
780
from pytpp.properties.response_objects.dataclasses import system_status from pytpp.tools.helpers.date_converter import from_date_string class SystemStatus: @staticmethod def Engine(response_object: dict): if not isinstance(response_object, dict): response_object = {} return system_...
4,505
1,208
from typing import Optional import pytorch_lightning as pl import torch from omegaconf import OmegaConf from torch.utils.data import DataLoader, random_split from transformers import T5Tokenizer from src.data.PaperDataset import PaperDataset class ArvixDataModule(pl.LightningDataModule): def __init__(self, conf...
1,883
613
# -*- coding: utf-8 -*- import os import sys import time import subprocess import wx import ConfigParser from wx.lib.mixins.listctrl import getListCtrlSelection from wx.lib.pubsub import pub from gui.RootGUI import RootGUI from StepsDialog import StepsDialog from PlotFrame import PlotFuncFrame, PlotCorrFrame import i...
10,573
3,242
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-02-06 10:07 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django_prices.models class Migration(migrations.Migration): dependencies = [ ...
6,063
1,800
#!/usr/bin/env python # -*- coding: utf-8 -*- from .base import TestRailAPIBase class Config(TestRailAPIBase): """ Use the following API methods to request details ...
3,357
895
def assert_not_none(actual_result, message=""): if not message: message = f"{actual_result} resulted with None" assert actual_result, message def assert_equal(actual_result, expected_result, message=""): if not message: message = f"{actual_result} is not equal to expected " \ ...
1,104
324
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: proto/transaction.proto """Generated protocol buffer code.""" from google.protobuf.internal import enum_type_wrapper from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from goo...
40,713
15,799
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
1,411
474
from llvmlite import ir import xml.etree.ElementTree as et int32 = ir.IntType(32) int64 = ir.IntType(64) int1 = ir.IntType(1) void_type = ir.VoidType() function_names = [] registers, functions, uniques, extracts = {}, {}, {}, {} internal_functions = {} memory = {} flags = ["ZF", "CF", "OF", "SF"] pointers = ["RSP", "R...
26,564
7,831
#/usr/bin/env python # -*- Coding: UTF-8 -*- # # WPSeku: Wordpress Security Scanner # # @url: https://github.com/m4ll0k/WPSeku # @author: Momo Outaadi (M4ll0k) import re from lib import wphttp from lib import wpprint class wplisting: chk = wphttp.UCheck() out = wpprint.wpprint() def __init__(self,agent,proxy...
925
402
from tw2.jit.widgets.chart import (AreaChart, BarChart, PieChart) from tw2.jit.widgets.graph import (ForceDirectedGraph, RadialGraph) from tw2.jit.widgets.tree import (SpaceTree, HyperTree, Sunburst, Icicle, TreeMap) from tw2.jit.widgets.ajax import AjaxRadialGraph from tw2.jit.widget...
350
121
import json, requests, os, shlex, asyncio, uuid, shutil from typing import Tuple from pyrogram import Client, filters from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup, CallbackQuery # Configs API_HASH = os.environ['API_HASH'] APP_ID = int(os.environ['APP_ID']) BOT_TOKEN = os.environ['BOT_T...
4,726
1,847
import wx import wx.adv import random import util import config import time import datetime import threading import requests import json from functools import partial class ReqeusterThread(threading.Thread): # https://www.oreilly.com/library/view/python-cookbook/0596001673/ch06s03.html def __init__(self, ...
24,254
8,212
"""High-level search API. This module implements application-specific search semantics on top of App Engine's search API. There are two chief operations: querying for entities, and managing entities in the search facility. Add and remove Card entities in the search facility: insert_cards([models.Card]) delete_ca...
7,259
2,134
import copy import sys PLAYER1, PLAYER2, EMPTY, BLOCKED = [0, 1, 2, 3] S_PLAYER1, S_PLAYER2, S_EMPTY, S_BLOCKED, = ['0', '1', '.', 'x'] CHARTABLE = [(PLAYER1, S_PLAYER1), (PLAYER2, S_PLAYER2), (EMPTY, S_EMPTY), (BLOCKED, S_BLOCKED)] DIRS = [ ((-1, 0), "up"), ((1, 0), "down"), ((0, 1), "right"), ((0, ...
3,422
1,144
import sys sys.setrecursionlimit(10000) def dfs(r, c): global visit visit[r][c] = True mov = [(-1, 0), (0, -1), (1, 0), (0, 1)] for i in range(4): dr, dc = mov[i] nr, nc = r + dr, c + dc if 0 <= nr < N and 0 <= nc < M and visit[nr][nc] == False and board[nr][nc] == 1: ...
884
364
""" Binary Tree and basic properties 1. In-Order Traversal 2. Pre-Order Traversal 3. Post-Order Traversal 4. Level-Order Traversal """ from collections import deque class BinaryTree(object): """ Representation of a general binary tree data: value of element left: Left subtree right: Right subtree ...
5,827
1,582
import voluptuous as vol import homeassistant.helpers.config_validation as cv from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_PATH, CONF_USERNAME DOMAIN = "vaddio_conferenceshot" DATA_SCHEMA = vol.Schema( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_USERNAME): cv.string,...
445
166
# Copyright (c) 2020 LightOn, All Rights Reserved. # This file is subject to the terms and conditions defined in # file 'LICENSE.txt', which is part of this source code package. """ This module contains the OPU class """ import time from math import sqrt import pkg_resources from lightonml.encoding.base import NoEnco...
32,841
8,911
from shovel import task @task def hello(name='Foo'): '''Prints "Hello, " followed by the provided name. Examples: shovel bar.hello shovel bar.hello --name=Erin http://localhost:3000/bar.hello?Erin''' print('Hello, %s' % name) @task def args(*args): '''Echos back all the ar...
1,022
343
# This file is part of Scapy # See http://www.secdev.org/projects/scapy for more information # Copyright (C) Philippe Biondi <phil@secdev.org> # This program is published under a GPLv2 license """ Implementation of the configuration object. """ from __future__ import absolute_import from __future__ import print_funct...
22,938
7,398
# -*- coding: utf-8 -*- from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import import tempfile import pytest import time from treq.testing import StubTreq from rasa_nlu.config import RasaNLUConfig import json import io fr...
5,797
1,943
import os import platform import socket import sysconfig from typing import List, Any, Tuple, Union import warnings from bugsnag.sessiontracker import SessionMiddleware from bugsnag.middleware import DefaultMiddleware, MiddlewareStack from bugsnag.utils import (fully_qualified_class_name, validate_str_setter, ...
15,277
4,093
import kopf from .functions import global_logger, reconcile_secret @kopf.on.event("", "v1", "secrets") def injector_secret_event(type, event, logger, **_): obj = event["object"] namespace = obj["metadata"]["namespace"] name = obj["metadata"]["name"] # If secret already exists, indicated by type bein...
587
177
import datetime import os import ee import math import sys import json from ee.ee_exception import EEException from gee.inputs import getLandsat, getS1 ########## Helper functions ########## def initialize(ee_account='', ee_key_path=''): try: if ee_account and ee_key_path and os.path.exis...
25,390
9,439
from django.contrib import admin from django.urls import path,include from django.views.generic import TemplateView from .views import Index,SignUp,UserDashboard,AdminDashboard,logout,showAdminData,deleteuser,activeUser,deactiveUser,UserDetailEdit,uploadImage # from .views import Index,UserDashboard,SignUp,AdminDashboa...
1,186
373
# -*- coding: UTF-8 -*- """ RIFF parser, able to parse: * AVI video container * WAV audio container * CDA file Documents: - libavformat source code from ffmpeg library http://ffmpeg.mplayerhq.hu/ - Video for Windows Programmer's Guide http://www.opennet.ru/docs/formats/avi.txt - What is an animated curso...
16,962
5,761
import os import re def get_subfolder_paths(folder_relative_path: str) -> list: """ Gets all subfolders of a given path :param folder_relative_path: Relative path of folder to find subfolders of :return: list of relative paths to any subfolders """ return [f.path for f in os.scandir(folder_rel...
1,041
369
from datetime import datetime with open('/home/neo4j/neo4j-community-3.5.1/logs/debug.log', 'r') as log: begin = [] end = [] for line in log: if 'Index population started' in line: begin.append(line[:23]) elif 'Index creation finished' in line: end.append(line[:23]) if len(begin) == 0 or le...
800
299
# -*- coding: utf-8 -*- ''' :file: setup.py :author: -Farmer :url: https://blog.farmer233.top :date: 2021/09/20 11:11:54 ''' from os import path from setuptools import setup, find_packages basedir = path.abspath(path.dirname(__file__)) with open(path.join(basedir, "README.md"), encoding='utf-8') as f...
1,489
512
# Square 方片 => sq => RGB蓝色(Blue) # Plum 梅花 => pl => RGB绿色(Green) # Spade 黑桃 => sp => RGB黑色(Black) # Heart 红桃 => he => RGB红色(Red) init_poker = { 'local': { 'head': [-1, -1, -1], 'mid': [-1, -1, -1, -1, -1], 'tail': [-1, -1, -1, -1, -1], 'drop': [-1, -1...
1,635
968
name = "David Asiru Adetomiwa" print(name)
42
18
"""TcEx Framework API Service module.""" # standard library import json import sys import threading import traceback from io import BytesIO from typing import Any from .common_service import CommonService class ApiService(CommonService): """TcEx Framework API Service module.""" def __init__(self, tcex: obje...
10,716
2,914
from mmcv.runner import build_optimizer def build_optimizers(model, cfgs): """Build multiple optimizers from configs. If `cfgs` contains several dicts for optimizers, then a dict for each constructed optimizers will be returned. If `cfgs` only contains one optimizer config, the constructed optimizer ...
1,540
481
import datetime from django.contrib.auth import logout from django.shortcuts import render, redirect from .forms import RegisterForm from django.http import HttpResponse from django.contrib.auth.forms import AuthenticationForm from django.conf import settings from django.contrib.auth import authenticate, login from dj...
1,189
280
# Generated by Django 3.1.7 on 2021-03-26 01:27 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Community', fields=[ ('name', models.CharFi...
572
164
#!/usr/bin/env python3 -u # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Train a new model on one or across multiple GPUs. """ import collections import logging import math import os im...
16,846
5,289
""" This is the doc for the Grid Diagnostics module. These functions are based on the grid diagnostics from the GEneral Meteorological PAcKage (GEMPAK). Note that the names are case sensitive and some are named slightly different from GEMPAK functions to avoid conflicts with Jython built-ins (e.g. st...
18,862
7,705
from selenium import webdriver #to get the browser from selenium.webdriver.common.keys import Keys #to send key to browser import getpass #to get password safely import time #to pause the program #a calss to store all twetter related objects and functions class twitter_bot: def __init__(self, username, pas...
2,376
712
import torch import torch.nn as nn from torch.nn import functional as F from PIL import Image import cv2 as cv from matplotlib import cm import numpy as np class GradCAM: """ #### Args: layer_name: module name (not child name), if None, will use the last layer befor...
3,403
1,105
''' 2D version of 1st-level algorithm is a combination of frame_blobs, intra_blob, and comp_P: optional raster-to-vector conversion. intra_blob recursively evaluates each blob for two forks of extended internal cross-comparison and sub-clustering: der+: incremental derivation cross-comp in high-variati...
19,149
6,716
"""Generates a random terrain at Minitaur gym environment reset.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os, inspect currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir = os.path.dirname(os.path...
10,275
3,332
from functools import partial from polecat.db.query import query as query_module from psycopg2.sql import SQL, Placeholder from .expression import Expression class Values(Expression): def __init__(self, values, relation=None): self.values = values self.relation = relation self.keyword = ...
2,502
716
# 2019 advent day 3 MOVES = { 'R': (lambda x: (x[0], x[1] + 1)), 'L': (lambda x: (x[0], x[1] - 1)), 'U': (lambda x: (x[0] + 1, x[1])), 'D': (lambda x: (x[0] - 1, x[1])), } def build_route(directions: list) -> list: current_location = (0, 0) route = [] for d in directions: directio...
1,292
611
import asyncio async def searchDomains(domain, q): domains = [] proc = await asyncio.create_subprocess_shell(f"dnsrecon -d {domain} -t crt", stdout=asyncio.subprocess.PIPE) line = True while line: line = (await proc.stdout.readline()).decode('utf-8') fields = line.split() if len...
1,054
344
# -*- coding: utf-8 -*- """IdentityServicesEngineAPI security_groups_acls API fixtures and tests. Copyright (c) 2021 Cisco and/or its affiliates. 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 w...
15,156
4,919
"""Riemannian and pseudo-Riemannian metrics.""" import math import warnings import autograd import geomstats.backend as gs from geomstats.geometry.connection import Connection EPSILON = 1e-4 N_CENTERS = 10 TOLERANCE = 1e-5 N_REPETITIONS = 20 N_MAX_ITERATIONS = 50000 N_STEPS = 10 def loss(y_pred, y_true, metric):...
21,522
6,581
import pandas as pd from bokeh.models import HoverTool from bokeh.models.formatters import DatetimeTickFormatter from bokeh.palettes import Plasma256 from bokeh.plotting import figure, ColumnDataSource from app import db from app.decorators import data_quality # creates your plot date_formatter = DatetimeTickFormatt...
9,842
3,088
#Yannick p6e8 Escribe un programa que te pida primero un número y luego te pida números hasta que la suma de los números introducidos coincida con el número inicial. El programa termina escribiendo la lista de números. limite = int(input("Escribe limite:")) valores = int(input("Escribe un valor:")) listavalore...
705
244
from typing import Optional from typing import Tuple from clikit.console_application import ConsoleApplication from .commands import BaseCommand from .commands.completions_command import CompletionsCommand from .config import ApplicationConfig class Application(ConsoleApplication, object): """ A...
1,574
456