text
string
size
int64
token_count
int64
# # PySNMP MIB module ALVARION-SMI (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ALVARION-SMI # Produced by pysmi-0.3.4 at Mon Apr 29 17:06:07 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019,...
2,679
1,081
from setuptools import setup from setuptools import find_packages required_packages = [ 'beautifulsoup4', 'cssselect', 'duckling', 'feedfinder2', 'feedparser', 'idna', 'jieba3k', 'JPype1', 'Logbook', 'lxml', 'newspaper3k', 'nltk', 'Pillow', 'PyQt5', 'python-d...
954
351
from base64 import b64encode, b64decode import binascii from datetime import datetime from uuid import UUID from jsonschema._format import FormatChecker from jsonschema.exceptions import FormatError from six import binary_type, text_type, integer_types DATETIME_HAS_STRICT_RFC3339 = False DATETIME_HAS_ISODATE = False ...
2,877
983
import pytest from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from database import Base, get_session SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db" engine = create_engine( SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False} ) TestingSessionLocal = sessionmaker(autocomm...
602
203
from .models import CommandRule from typing import Optional, Tuple class CommandRuleManagerInterface: async def get_rules_by_server(self, server_id: str, start_offset: int, page_size: int, group: Optional[str] = None, subgroup: Optional[str] = None) -> Tuple[CommandRule, ...]: raise NotImplementedError ...
783
231
"""error utils""" from traceback import format_tb TRACEBACK_HEADER = "Traceback (most recent call last):\n" def exception_to_string(exc: Exception) -> str: """Convert exception to string stackrace""" # Either use passed original exception or whatever we have return TRACEBACK_HEADER + "".join(format_tb(ex...
349
111
_QUEUED_JOBS_KEY = 'projects:global:jobs:queued' _ARCHIVED_JOBS_KEY = 'projects:global:jobs:archived' def list_jobs(redis): return {job_id.decode() for job_id in redis.smembers(_QUEUED_JOBS_KEY)} def remove_jobs(redis, job_id_project_mapping): for job_id, project_name in job_id_project_mapping.items(): ...
967
392
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under t...
2,988
1,012
#!/usr/bin/python3 import argparse import socket import base64 import binascii # 'argparse' is a very useful library for building python tools that are easy # to use from the command line. It greatly simplifies the input validation # and "usage" prompts which really help when trying to debug your own code. # parser =...
4,444
1,481
#!/usr/bin/env python3 a = [] b = [] s = input() while s != "end": n = int(s) if n % 2 == 1: a.append(n) else: print(n) s = input() i = 0 while i < len(a): print(a[i]) i = i + 1
222
106
import rospy from gazebo_msgs.srv import GetModelState from geometry_msgs.msg import PoseStamped, Pose2D from nav_msgs.msg import Odometry from tf2_ros import TransformListener, Buffer import sys vehicle_type = sys.argv[1] vehicle_id = sys.argv[2] laser_slam_type = sys.argv[3] rospy.init_node(vehicle_type+vehicle_id+'...
2,418
897
import itertools import os import shutil import numpy as np import gym from gym import spaces import robosuite from robosuite.controllers import load_controller_config import robosuite.utils.macros as macros import imageio, tqdm from her import HERReplayBuffer from tianshou.data import Batch macros.SIMULATION_TIMES...
5,309
1,897
import unittest import acpc_python_client as acpc from tools.constants import Action from weak_agents.action_tilted_agent import create_agent_strategy, create_agent_strategy_from_trained_strategy, TiltType from tools.io_util import read_strategy_from_file from evaluation.exploitability import Exploitability from tool...
3,520
1,231
from app import create_app from app.models import db from app.models.role import Role app = create_app() app.app_context().push() DefaultRoles = [ { 'name': 'user', }, { 'name': 'admin', }, ] def insert_default_roles(): try: if Role.query.count() == 0: print('roles table is empty. Insert...
870
298
import functools import operator from collections.abc import Iterable from typing import overload, Union, TypeVar T = TypeVar('T') S = TypeVar('S') # <1> @overload def sum(it: Iterable[T]) -> Union[T, int]: ... # <2> @overload def sum(it: Iterable[T], /, start: S) -> Union[T, S]: ... # <3> def sum(it, /, start=0):...
381
147
from __future__ import annotations import math from collections import deque from typing import Optional, Callable import numpy as np import pygame from chess.const import PieceType, PieceColour, Piece, CastlingType, Move, \ PIECE_INDICES, init_zobrist, MoveFlags, GameState from chess.utils import load_image, lo...
24,987
7,928
from datasets.vrd import VrdDataset def get_dataset(opt, type, transform): assert opt.dataset in ['vrd', 'visual_genome'] if opt.dataset == 'vrd': dataset = VrdDataset(opt.dataset_path, opt.num_classes, type, transform) # elif opt.dataset == 'activitynet': # training_data = ActivityNet( ...
604
180
from conans import ConanFile, tools import os class MsysBaseInstallerConan(ConanFile): name = "msys-base_installer" version = "2013072300" license = "http://www.mingw.org/license" url = "http://github.com/danimtb/conan-msys-installer" settings = "os", "compiler" build_policy = "missing" de...
4,398
1,963
from flask_restful import Api from App.apis import Hello, Home api = Api() def init_urls(app): api.init_app(app=app) api.add_resource(Hello, "/hello/") api.add_resource(Home, "/home/")
192
72
import cv2 import numpy as np import numpy as cv #import cv2 as cv from irCamera_SeekMosaic import irCamera_SeekMosaic #from PIL import Image vlcamera = cv2.VideoCapture(0) ircamera = irCamera_SeekMosaic(54339) dsize = (1, 1) #default is no resizing vlret = False irret = False while 1: if vlcamera is not None: ...
1,865
626
import os from uuid import uuid4 from django.db import models from django.urls import reverse from django.utils.timezone import now as timezone_now from autoslug import AutoSlugField from model_utils.models import TimeStampedModel from django_countries.fields import CountryField from django.utils.translation import ge...
1,599
504
from django.utils.safestring import mark_safe from fluent_contents.extensions import ContentPlugin, plugin_pool from fluent_contents.tests.testapp.models import RawHtmlTestItem @plugin_pool.register class RawHtmlTestPlugin(ContentPlugin): """ The most basic "raw HTML" plugin item, for testing. """ mod...
433
122
""" Goal: Visualize images from aircraft camera and load as a pytorch dataloader 0. load images and the corresponding state information in labels.csv 1. test a trained DNN and visualize predictions """ import sys, os import torch import numpy as np import pandas import matplotlib.pyplot as plt # make sure...
5,525
1,820
from enum import Enum, auto class ReleaseLevel(Enum): alpha = auto() beta = auto() release_candidate = auto() public = auto() @classmethod def has_value(cls, value): return value in cls._value2member_map_.values() class ReleaseType(Enum): bugfix = auto() minor = auto() m...
588
188
"""Tests for 'cloudflare-gh-pages-dns' hook.""" import contextlib import io import os import pytest from hooks.cf_gh_pages_dns_records import check_cloudflare_gh_pages_dns_records @pytest.mark.skipif( not os.environ.get("CF_API_KEY"), reason=( "Cloudflare user API key defined in 'CF_API_KEY' enviro...
1,559
487
#!/usr/bin/python2.7 # -*- coding: utf-8 -*- """config.py: Default configuration.""" # Server: SERVER = 'wsgiref' DOMAIN = 'localhost:7099' HOST = 'localhost' PORT = 7099 # Meta: # Note on making it work in localhost: # * Open a terminal, then do: # - sudo gedit /etc/hosts # * Enter the desired localhost alias for...
796
322
import os modules = ['api', 'core'] sourcedirs = [] expectedToHaveNoTest = [ 'api/src/main/java/org/jmisb/api/klv/LdsParser.java', 'api/src/main/java/org/jmisb/api/video/VideoDecodeThread.java', 'api/src/main/java/org/jmisb/api/video/VideoOutput.java', 'api/src/main/java/org/jmisb/api/video/VideoStreamOut...
5,046
1,568
import asyncio import random import discord from discord.ext.commands import Bot from discord.ext import commands from discord import Color, Embed # This command randomly picks between the two non-banned maps. # # !pick [#] [#] # # The two numbers represent the two maps that were not banned from # running the !maps ...
1,154
373
""" Write a Python function that returns a list of keys in aDict that map to integer values that are unique (i.e. values appear exactly once in aDict). The list of keys you return should be sorted in increasing order. (If aDict does not contain any unique values, you should return an empty list.) This function takes i...
858
304
from dataclasses import dataclass from dataclasses import field from enum import Enum from typing import Any from typing import ClassVar from typing import Literal from typing import Mapping from typing import Optional from typing import Sequence from typing import Union from uuid import UUID import pytest from svaro...
6,909
2,681
import base64 import re import os.path as op from io import BytesIO import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import nibabel as nib import numpy as np from pathlib import Path import pandas as pd import nilearn.image as nim from dipy.segment.mask import median_otsu from nipype.utils.filem...
16,186
6,038
# Generated by Django 3.2.8 on 2021-10-11 11:10 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Workspace', fields=[ ('id', models.AutoFiel...
1,392
377
import os os.environ['PREFECT__LOGGING__LEVEL'] = 'DEBUG' os.environ['DJANGO_ALLOW_ASYNC_UNSAFE'] = 'true' from prefect import flow, task import numpy as np import pandas as pd from django_pandas.io import read_frame import helpers @task def insert_session(session_id): from django_connect import connect con...
3,634
1,321
from sqlalchemy import Column, ForeignKey, Integer, DateTime from sqlalchemy.orm import relationship from ..database import Base class Artist_album(Base): __tablename__ = "artists_albums" id = Column(Integer, primary_key=True, index=True) artist_id = Column(Integer, ForeignKey("artists.id")) album_id...
584
180
from flask import request from firebase_admin import auth import requests from join import firebase import ast import time def get_join(): token = request.headers['authorization'] decoded_token = auth.verify_id_token(token) email = decoded_token['firebase']['identities']['email'][0] tags...
1,099
359
#!/usr/bin/env python3.8 # coding=utf-8 """ Simple Lambda Handler """ from lbz.dev.server import MyDevServer from lbz.dev.test import Client from lbz.exceptions import LambdaFWException from lbz.resource import Resource from lbz.response import Response from lbz.router import add_route class HelloWorld(Resource): ...
1,110
355
# -*- coding: utf-8 -*- """ Created on Thu May 3 08:04:22 2018 @author: af5u13 """ import numpy as np import os from .geometry_functions import deg2rad, sph2cart from loudspeakerconfig import createArrayConfigFile def createArrayConfigFromSofa( sofaFile, xmlFile = None, lspLabels = None, twoDSetup = False, virtua...
2,473
776
# Generated by Django 3.0.3 on 2020-09-01 05:27 from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('blog_app', '0018_auto_20200830_0501'), ] operati...
774
260
from datetime import datetime, date, timedelta def hour_generator(start, end, step=10): while start < end: yield start start = start + timedelta(minutes=step) def create_hour(hour, date=None): if not date: return datetime.strptime(hour, '%H:%M') h = datetime.strptime(hour, '%H:%M...
837
284
from display.handlers.base import BaseHandler class MailboxReadHandler(BaseHandler): def get(self): title = 'MailboxReadHandler' self.render('mailbox/read-mail.html', title = title, **self.render_dict)
222
65
import convert_pdf_2_jpg import printer def do_print(file_path): if file_path.endswith('.pdf'): file_path = convert_pdf_2_jpg.do_convert(file_path) printer.do_print(file_path)
194
71
# from unittest import skip from django.conf import settings from django.contrib import auth from django.urls import reverse from django.test import TestCase from plok.models import Blog, Article from .ext_test_case import ExtTestCase class BlogList(TestCase): url_name = 'plok:blog_list' def test_reverse_blo...
12,377
3,872
from .parse import structure_reference from .fuzzy_match import FuzzyMatcher from .file_manager import FileManager from .serialiser import serialise_matched_reference, serialise_reference from .exact_match import ExactMatcher __all__ = [ structure_reference, FuzzyMatcher, FileManager, serialise_matched...
376
113
# -*- coding: utf-8 -*- """ Created on 2014-5-14 django 帮助函数 @author: skycrab @sns_userinfo def oauth(request): openid = request.openid """ import json import logging import base64 from functools import wraps from django.conf import settings from django.core.cache import cache from django.short...
8,634
2,589
# Copyright (c) 2021 Project CHIP Authors # # 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 ...
3,608
1,151
# -*- coding: utf-8 -*- ############################################################################## # Author:QQ173782910 ############################################################################## import logging from apscheduler.schedulers.background import BlockingScheduler from RunUse import TradeRun format ...
946
322
import numpy as np import jax.numpy as jnp from jax import lax from jax.scipy.special import expit # Default activation functions def sigmoid(x): """Sigmoid activation function. :param x: Input value :type x: :obj:`float` or :obj:`numpy.array` :return: Sigmoid activated value: :math:`sigmoid(x) = \\...
2,522
961
""" Authors: Bardiaux Benjamin Institut Pasteur, Paris IBPC, Paris Copyright (C) 2005 Michael Habeck, Wolfgang Rieping and Benjamin Bardiaux No warranty implied or expressed. All rights reserved. $Author: bardiaux $ $Revision: 1.1.1.1 $ $Date: 2010/03/23 1...
45,032
14,564
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('wiki_images', '0001_initial'), ] operations = [ migrations.AlterModelTable( name='image', table='wik...
482
146
# Copyright 2021 The XLS Authors # # 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 writ...
19,134
6,214
from api.class_declaration import Profile, Storage, Base, Bag # TODO: This S/L api uses txt files for the time being, should use databases in the future # questions: what's in the save_file? # save_file is a dictionary contains the following keys: # profile, bag, base, and storage # They are all "class", but bag and...
3,099
1,300
import numpy as np import os from datetime import datetime from pytz import timezone import matplotlib.pyplot as plt from agent_qlean import QLearnAgent from agent_bandit import BanditAgent from environment import Environment from simulator import parameters from simulator.transaction_model import TransactionModel from...
3,538
1,129
print('\033[1;32mANALISANDO DADOS\033[m') jogador = dict() gols = list() jogadores = list() print('-=' * 50) while True: gols.clear() jogador['nome'] = str(input('Nome do jogador: ')) partidas = int(input('Quantas partidas esse jogador jogou: ')) for cont in range(1, partidas + 1, +1): partida =...
1,484
610
# coding: utf-8 from modules.controller import Controller LED_PIN = 23 # pin of led if __name__ == "__main__": controller = Controller(LED_PIN) controller.run(50, 1) print("Led Start for a second with 50% power")
229
83
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If ex...
2,608
748
from .base import BaseFactory from launchkey import LAUNCHKEY_PRODUCTION from launchkey.clients import ServiceClient class ServiceFactory(BaseFactory): """Factory for creating clients when representing a LaunchKey Service Profile""" def __init__(self, service_id, private_key, url=LAUNCHKEY_PRODUCTION, testin...
1,417
380
#!/usr/bin/env python from __future__ import print_function import os import errno import time import math import re import sys import scipy import imageio import cv2 import numpy as np import json from random import Random from tensorflow.python.lib.io import file_io import logging from mvsnet.utils import setup_log...
6,762
2,501
from typing import Dict, Any import tensorflow as tf from ..utils.segmented_data import SegmentedIndices, SegmentedIndicesFeed from ..graph_encoder.embeddings import NodeEmbeddings class Encoder(object): def __init__(self, nodes: NodeEmbeddings): self._nodes = nodes self._build() def _buil...
1,820
519
import os import re import sys import json import time import psutil import shutil import appdirs import zipfile import tarfile import argparse import platform import requests import traceback import contextlib import subprocess import webbrowser import logging.config from pathlib2 import Path from bs4 import Beautiful...
83,399
23,475
# Copyright 2018 DeepMind Technologies Limited. 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 ...
4,873
1,449
from flask import flash, render_template, redirect, request, url_for from flask_login import login_required, login_user, logout_user from . import auth from .forms import UserLoginForm, UserRegForm from app.commands import db from app.models import User from app.send_email import mail_message @auth.route('/login', me...
1,390
421
import sys # 引数を変数varに代入してprintで返す var = sys.argv[1] print(type(var)) print(var)
81
43
class InvalidBitstringError(BaseException): pass class InvalidQuantumKeyError(BaseException): pass
104
29
""" User api endpoints """ from flask import request from flask_restplus import Resource from ..util.dto import UserDto from ..service.user import save_new_user api = UserDto.api _user = UserDto.user @api.route('/users') class Users(Resource): """ User resource for the API """ @api.doc('Create a n...
562
176
import os import zipfile from typing import List, Tuple, Dict import numpy as np import pandas as pd import requests import structlog import matplotlib.pyplot as plt from sklearn.ensemble import RandomForestClassifier from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.model_selection import train...
7,367
2,463
from PyQt6.QtCore import * from PyQt6.QtGui import * from PyQt6.QtWidgets import * class TargetAddressForm(QWidget): def __init__(self): super().__init__() self.layout = QHBoxLayout() self.setLayout(self.layout) self.target_address_label = QLabel("Pay to:") self.target_ad...
1,465
462
# vim: set et nosi ai ts=2 sts=2 sw=2: # coding: utf-8 from __future__ import absolute_import, print_function, unicode_literals import unittest from schwa import dr class Node(dr.Ann): label = dr.Field() class Doc(dr.Doc): store = dr.Store(Node) class Test(unittest.TestCase): def _test_example(self, doc): ...
518
192
#!/usr/bin/env python import os,sys sys.path.insert(1, os.path.join(sys.path[0], '..')) import argparse from multiagent.environment import MultiAgentEnv import multiagent.scenarios as scenarios import numpy as np import keras.backend.tensorflow_backend as backend from keras.models import Sequential from keras.layers i...
12,645
4,079
import jinja2 import gettext import markdown from pathlib import Path import sys sys.path.append('../') import utils credits_html = "" with open("credits.md", "r") as file: credits_html = markdown.markdown(file.read()) env = jinja2.Environment( extensions=['jinja2.ext.i18n'], loader=jinja2.FileSystemLoade...
1,101
381
from camper.db import BarcampSchema, Barcamp import datetime def test_get_empty_registration_form(barcamps, barcamp): barcamps.save(barcamp) barcamp = barcamps.by_slug("barcamp") assert barcamp.registration_form == [] def test_add_to_registration_form(barcamps, barcamp): barcamps.save(barcamp) fie...
1,263
422
from django.db import models from django.contrib.auth.models import User from django.utils import timezone import datetime class Session(models.Model): session_key = models.CharField(max_length=64) created_at = models.DateTimeField(auto_now_add=True) class License(models.Model): license_key = models.Char...
1,487
483
#! python3 # -*- encoding: utf-8 -*- from job import celery @celery.task() def add(x, y): return x+y
109
50
BOT_TOKEN = "754938335214174210" SERVER_ADDRESS = ("192.154.227.44:7797", 27016)
82
64
#!/usr/bin/env python3 # encoding=utf8 """This tool heavily depends on `mylib` package, make sure `mylib` folder is in the same path with this tool.""" import cmd import shlex from argparse import ArgumentParser, REMAINDER from collections import defaultdict from pprint import pprint from send2trash import send2trash...
34,994
12,395
from pathlib import Path from unittest.mock import call import pytest from dbt_sugar.core.clients.dbt import DbtProfile from dbt_sugar.core.config.config import DbtSugarConfig from dbt_sugar.core.flags import FlagParser from dbt_sugar.core.main import parser from dbt_sugar.core.task.audit import AuditTask from dbt_su...
8,282
2,622
import csv import math import matplotlib.pyplot as plt import numpy as np import seaborn as sns import sys # apply plot style sns.set() x = [] y = [] with open(sys.argv[1], 'r') as f: rows = csv.reader(f, delimiter='\t') for row in rows: # discard rows that are missing data if len(row) != 3 ...
624
264
"""Functionality to evaluate contents of the ast""" from functools import singledispatch, wraps import operator from typing import Any, Union from altair_transform.utils import ast, Parser __all__ = ['evaljs'] def evaljs(expression: Union[str, ast.Expr], namespace: dict = None) -> Any: """Evaluate a javascript ...
4,453
1,601
# Copyright (c) 2015, The MITRE Corporation. All rights reserved. # See LICENSE.txt for complete terms. import unittest from stix.test import EntityTestCase from stix.common import Names class NamesTests(EntityTestCase, unittest.TestCase): klass = Names _full_dict = [ "foo", "bar", {...
453
160
from github_app import app app.run(host='0.0.0.0', port=int(app.config['PORT']), debug=True)
94
39
"""Kubernetes operations.""" import typing import kubernetes from . import exceptions from . import helpers class CreateReturn(typing.NamedTuple): """ Structure of the create return value. Attrs: status: The status of the operation. Is SUCCESS or FAILURE. reason: If the status is FAILU...
4,855
1,414
import logging import os from smart_open import open logger = logging.getLogger(__name__) S3_EXPORT_DEFAULT_BUCKET = "s3://data.opennem.org.au/v3/" UPLOAD_ARGS = { "ContentType": "application/json", } def write_to_s3(file_path: str, data: str) -> int: """ Write data to an s3 path """ s3_sa...
660
252
#!/usr/bin/env python # -- coding: UTF-8 -- """ Magnet API NLP Sample Copyright 2018, Klangoo Inc. """ from klangooclient.MagnetAPIClient import MagnetAPIClient ENDPOINT = 'https://nlp.klangoo.com/Service.svc' CALK = 'enter your calk here' SECRET_KEY = 'enter your secret key here' client = MagnetAPIClient(END...
2,549
828
class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]: if len(nums) < 3: return [] ans = [] nums.sort() for i in range(0, len(nums)-2): if nums[i] > 0: break if i > 0 and nums[i-1] == nums[i]: contin...
952
286
#!/usr/bin/python ''' Validates Manifest file under the security-content repo for correctness. ''' import glob import json import jsonschema import yaml import sys import argparse from os import path def validate_detection_contentv2(detection, DETECTION_UUIDS, errors, macros, lookups): if detection['id'] == ''...
38,211
11,119
import hashlib import shutil import io import gzip import platform import os import struct import json import mmap class ElfConst: CLASS_32 = 1 CLASS_64 = 2 DATA_LE = 1 DATA_BE = 2 TYPE_RELOC = 1 TYPE_EXEC = 2 TYPE_SHARED = 3 TYPE_CORE = 4 class Layout: ElfIdent = b'=4sBBBBBxxxxx...
8,829
2,893
"""log_redaction_cli Usage: log_redaction_cli.py --tarfile <tarfile> --working-dir <working-dir> --output-dir <output-dir> log_redaction_cli.py (-h | --help) log_redaction_cli.py --version Options: -h --help Pass in a string: example command: python log_redaction_cli.py --tarfile "test/files/test_output.t...
800
288
import torch import torch.nn as nn from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence import numpy as np import torch.nn.functional as F from attention import AdditiveAttention class Encoder(nn.Module): """Encoder bi-GRU""" def __init__(self, input_dim, char_embed_dim, e...
15,323
4,674
# -*- coding:utf-8 -*- """ https://people.gnome.org/~markmc/qcow-image-format.html """ import dataclasses import struct from typing import List QCOW_HEADER_SIZE = 72 QCOW_MAGIC = b'QFI\xfb' QCOW_HEADER_GROUP_META = 8 QCOW_HEADER_GROUP_BACKING_FILE = 12 QCOW_HEADER_GROUP_SIZE = 16 QCOW_HEADER_GROUP_L1 = 12 QCOW_HEAD...
2,319
925
"""CLI entry points of faddr.""" import argparse import pathlib import sys from faddr import logger from faddr.config import load_config from faddr.rancid import RancidDir from faddr.database import Database def parse_args_db(): """Parsing CMD keys.""" parser = argparse.ArgumentParser(argument_default=argpa...
1,901
606
''' Created by Wang Qiuli 2020/5/23 ''' import cv2 import numpy as np import matplotlib.pyplot as plt import slic import rgb_gr from PIL import Image from skimage import io, color from skimage import data, filters def truncate_hu(image_array, max = 400, min = -900): image = image_array.copy() image[image >...
3,100
1,345
import pandas as pd from matplotlib import dates as mdates from timeseries import plot_ts from timeseries.plotting import ax_settings def main(): # .csv available to download at: # https://www.investing.com/currencies/gbp-usd-historical-data gpd_usd_data = pd.read_csv("../data/GBP_USD Historical Data_mon...
2,713
1,049
# Copyright (c) 2020 vesoft inc. All rights reserved. # # This source code is licensed under Apache 2.0 License, # attached with Common Clause Condition 1.0, found in the LICENSES directory. import functools import os import time import pytest import io import csv import re from nebula2.common.ttypes import Value fro...
12,120
3,951
from sklearn import metrics from prettytable import PrettyTable def evaluate_clustering(name, X, true_labels, pred_labels): homogeneity = metrics.homogeneity_score(true_labels, pred_labels) completeness = metrics.completeness_score(true_labels, pred_labels) v_measure = metrics.v_measure_score(true_labels,...
1,469
518
import os import pymysql from dotenv import load_dotenv from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from sqlalchemy import Column, BigInteger, String, Float, ForeignKey def load_engine(): """Create the database engine""" ...
1,585
541
import pandas as pd import mapping_module as mm import multiprocessing as mp from sqlalchemy import create_engine from sys import argv user_name = argv[1] password = argv[2] data_type = argv[3] start_year = int(argv[4]) end_year = int(argv[5]) leiden_input = argv[6] #quality_func_Res --> CPM_R001 schema = argv[7] root...
1,982
777
import numpy as np import rebound as rb import reboundx as rbx def set_timestep(sim,dtfactor): ps=sim.particles[1:] tperi=np.min([p.P * (1-p.e)**1.5 / np.sqrt(1+p.e) for p in ps]) dt = tperi * dtfactor sim.dt = dt def set_min_distance(sim,rhillfactor): ps=sim.particles[1:] ...
7,454
2,714
# -*- coding: utf-8 -*- # # Copyright © Spyder Project Contributors # Licensed under the terms of the MIT License # (see spyder/__init__.py for details) """ This module contains the indentation guide panel. """ # Third party imports from qtpy.QtCore import Qt from qtpy.QtGui import QPainter, QColor from intervaltree i...
3,432
963
import hashlib class DuplicatePairDetector: def __init__(self): self.hashes = set() def add_if_new(self, description, api_calls): hash_binary = self.get_hash_binary(description, api_calls) if hash_binary in self.hashes: return False self.hashes.add(hash_binary) ...
576
188
def sum_all(ls): sum = 0 if(len(ls) != 2): print("Invalid input") else: ls.sort() start = ls[0] end = ls[1] if(start == end): sum = 2 * start else: for i in range(start, end+1): sum += i ret...
328
112
import openslide import torch from tqdm import tqdm from torch.utils.data import Dataset, DataLoader from torchvision import transforms from SuperMoon.models import ResNetFeature def extract_ft(slide_dir: str, patch_coors, depth=34, batch_size=16): device = torch.device("cuda:0" if torch.cuda.is_available() else...
1,713
613