text
string
size
int64
token_count
int64
from elasticsearch.client.utils import NamespacedClient, query_params, _make_path, SKIP_IN_PATH class MlClient(NamespacedClient): @query_params('from_', 'size') def get_filters(self, filter_id=None, params=None): """ :arg filter_id: The ID of the filter to fetch :arg from_: skips a num...
21,070
6,157
# coding: utf-8 # Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c...
17,264
4,626
from typing import List import os import re def create_output_dir(dir_name) -> bool: if not os.path.isdir(dir_name) or not os.path.exists(dir_name): print("Creating output directory: %s" % dir_name) try: os.makedirs(dir_name) except OSError: print("Creation of the d...
1,776
583
import dask import numpy as np import pandas as pd from epimargin.models import Age_SIRVD from epimargin.utils import annually, normalize, percent, years from studies.vaccine_allocation.commons import * from tqdm import tqdm import warnings warnings.filterwarnings("error") num_sims = 1000 simulation_range = 1...
5,355
2,105
'''Every agent has an agent state, which is its local view of the world''' import numpy as np import itertools class AgentState: def __init__(self, name, agt, seed=1234): self.name = name self.prng = np.random.RandomState(seed) # contains the variable assignment (exploreD) for this agent a...
1,975
550
from .server import app # noqa
32
11
# imports from . import coordinates from . import data from .modflow import * from . import utils from .data import mfdatascalar, mfdatalist, mfdataarray from .mfmodel import MFModel from .mfbase import ExtFileAction
218
68
import sys # The unittest module got a significant overhaul # in 2.7, so if we're in 2.6 we can use the backported # version unittest2. if sys.version_info[:2] == (2, 6): import unittest2 as unittest import simplejson as json from ordereddict import OrderedDict else: import unittest import json ...
360
114
from typing import Union from flask import request from flask_restful import Resource from exceptions import InvalidRequestError from models import Scoring from utils import flask_response, rank, sort class ScoringRoute(Resource): @flask_response def get(self, side_of_ball: str) -> Union[Scoring, list[Scori...
2,782
768
import configparser c = configparser.ConfigParser() c.read("production.ini") config = {} config['host'] = c['dboption']['chost'] config['port'] = int(c['dboption']['cport']) config['user'] = c['dboption']['cuser'] config['pw'] = c['dboption']['cpw'] config['db'] = c['dboption']['cdb'] config['homepath'] = c['option'][...
15,419
4,964
""" Coderpad solution """ def pend(arr): ## arr = [2,3,5,1,4] ## vrr = [0,0,0,0,0] var = [0] * len(arr) mid = (len(var) - 1) / 2 ## sort_arr = [1,2,3,4,5] ## vrr = [0,0,1,0,0] sort_arr = sorted(arr) var[mid] = sort_arr[0] # ^ # focus...
1,798
697
import os import configparser import json import time from IO.inputConfigParser import InputConfigParser from IO.redisDB import RedisDB from optimization.ModelException import MissingKeysException from optimization.controllerDiscrete import OptControllerDiscrete from optimization.controllerMpc import OptControllerMPC...
13,745
3,649
"""Unit tests for math-oriented common classes.""" import unittest import math import numpy as np from .vector import Vec3, OrthonormalBasis from .raycast_base import Ray from .camera import Camera class Vec3Tests(unittest.TestCase): """Test for Vec3 class.""" def test_vec3_basic(self): """Basic cr...
8,141
3,286
# MIT License # # Copyright (c) 2015-2020 Iakiv Kramarenko # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modif...
2,336
776
# -*- coding: utf-8 -*- # Copyright 2019 Cohesity Inc. import cohesity_management_sdk.models.continuous_schedule import cohesity_management_sdk.models.daily_schedule import cohesity_management_sdk.models.monthly_schedule import cohesity_management_sdk.models.rpo_schedule class SchedulingPolicy(object): """Implem...
3,970
1,060
#!/usr/bin/python # Copyright 2013 Mellanox Technologies, Ltd # # 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 applicab...
3,575
1,164
from .launcher import Launcher from .model import DataModel from .layers import LayerManager from .labels import LabelManager from .singleton import Singleton
161
43
from typing import List, Union import numpy as np import pandas_datareader as pdr import pandas as pd import matplotlib.pyplot as plt def rsi(symbol :str ,name :str, date :str) -> None : """ Calculates and visualises the Relative Stock Index on a Stock of the company. Parameters: symbol(str) : Sy...
2,567
961
import unittest import logging from ..basic import DictDatastore from ..key import Key from ..query import Query class TestDatastore(unittest.TestCase): def subtest_simple(self, stores, numelems=1000): def checkLength(len): try: for sn in stores: self.assertEqual(len(sn), numelems) ...
26,892
10,715
from django.db import models class Room(models.Model): code = models.CharField('Code', max_length=128) tab_url = models.CharField('Tab url', max_length=512, default='', blank=True) def to_dict(self): return { 'users': [u.to_dict() for u in self.users.all()], 'tabUrl': self...
852
280
import torch DEVICE = torch.device("cuda") SAVED_CHECKPOINTS = [32*1000, 100*1000, 150*1000, 200*1000, 300*1000, 400*1000] SAVED_CHECKPOINTS += [10*1000, 20*1000, 30*1000, 40*1000, 50*1000, 60*1000, 70*1000, 80*1000, 90*1000] SAVED_CHECKPOINTS += [25*1000, 50*1000, 75*1000] SAVED_CHECKPOINTS = set(SAVED_CHECKPOINTS)...
321
243
#!/usr/bin/env python3 ############################################################################### # Module Imports ############################################################################### import pyscp import textwrap from dominate import tags as dt from . import core, lex, ext ########################...
6,496
1,979
#!/usr/bin/env python3 import json from allenyoucert import Cert def main(): certList = list() a = json() main()
124
43
from .common import * def tsminmax(v): mv = NaN xv = NaN for v in x: if x == x: if mv == mv: mv = min(mv,x) else: mv = x if xv == xv: xv = max(xv,x) else: xv = x retu...
340
122
import os from cs50 import SQL from flask import Flask, flash, redirect, render_template, request, session from flask_session import Session from tempfile import mkdtemp from werkzeug.exceptions import default_exceptions, HTTPException, InternalServerError from werkzeug.security import check_password_hash, generate_pa...
3,552
1,083
from django import forms from django.contrib.auth.models import User from django.forms.utils import ErrorList class UserForm(forms.Form): name = forms.CharField(required=True) email = forms.EmailField(required=True) password = forms.CharField(required=True) phone = forms.CharField(required=True) n...
882
255
from telethon.sync import TelegramClient from telethon.errors.rpcerrorlist import PhoneNumberBannedError import pickle, os from colorama import init, Fore from time import sleep init() n = Fore.RESET lg = Fore.LIGHTGREEN_EX r = Fore.RED w = Fore.WHITE cy = Fore.CYAN ye = Fore.YELLOW colors = [lg, r, w, cy, ye] try: ...
6,547
2,114
# # Copyright (C) 2009 Mendix. All rights reserved. # SUCCESS = 0 # Starting the Mendix Runtime can fail in both a temporary or permanent way. # Some of the errors can be fixed with some help of the user. # # The default m2ee cli program will only handle a few of these cases, by # providing additional hints or intera...
1,212
389
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import torch.utils.data import torchvision def get_coco_api_from_dataset(dataset_val): for _ in range(10): # if isinstance(dataset, torchvision.datasets.CocoDetection): # break if isinstance(dataset_val, torch.utils...
2,456
790
# dkhomeleague.py import json import logging import os from string import ascii_uppercase import pandas as pd from requests_html import HTMLSession import browser_cookie3 import pdsheet class Scraper: """scrapes league results""" def __init__(self, league_key=None, username=None): """Creates instan...
11,139
3,415
#!/usr/bin/python3 import numpy as np import matplotlib.pyplot as plt t = np.arange(0.0, 3.0, 0.01) s = np.sin(2.5 * np.pi * t) plt.plot(t, s) plt.xlabel('time (s)') plt.ylabel('voltage (mV)') plt.title('Sine Wave') plt.grid(True) plt.show()
246
128
#Escreva um programa que leia um valor em metros e o exiba convertido em centimetros e milimetros. n = float(input('\033[32mDigite o numero:\033[m')) print('O número digitado é \033[33m{0:.0f}m\033[m.\n' 'Ele apresentado em centimetros fica \033[33m{0:.2f}cm\033[m.\n' 'Apresentado em milímetros fica \033[33...
517
233
# -*- coding: utf-8 -*- """ Created on Mon Oct 21 08:47:08 2019 @author: dordoloy """ import os import pika import config import getpass def publish_fanout(): amqp_url=config.amqp_url # Parse CLODUAMQP_URL (fallback to localhost) url = os.environ.get('CLOUDAMQP_URL',amqp_url) params = pika...
795
265
<<<<<<< HEAD # Lint as: python3 ======= >>>>>>> a811a3b7e640722318ad868c99feddf3f3063e36 # Copyright 2020 The Orbit 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 ...
16,112
4,895
def count_words(sentence): sentence = sentence.lower() words = {} shit = ',\n:!&@$%^&._' for s in shit: sentence = sentence.replace(s, ' ') for w in sentence.split(): if w.endswith('\''): w = w[:-1] if w.startswith('\''): w = w[1:] words...
364
135
from dataclasses import dataclass from apischema import deserialize, deserializer from apischema.json_schema import deserialization_schema @dataclass class Expression: value: int @deserializer def evaluate_expression(expr: str) -> Expression: return Expression(int(eval(expr))) # Could be shorten into des...
705
214
# -*- coding: utf-8 -*- ''' Created on 02/12/2011 @author: chra ''' import csv from operator import itemgetter # ----- Función media de la notas de los alumnos ---------- def media(alumno): #devuelve la nota media a partir de un diccionario con datos de un alumno nota1 = int(alumno['Nota1']) nota2 = int...
1,509
544
from src.interpreter.functions.math.add import add from src.interpreter.functions.math.div import div from src.interpreter.functions.math.mod import mod from src.interpreter.functions.math.mul import mul from src.interpreter.functions.math.pow import pow_func from src.interpreter.functions.math.sub import sub def mat...
799
231
from setuptools import setup setup(name='pygazetteer', version='0.1.0', description='Location extractor by looking up gazetteer', url='https://github.com/monkey2000/pygazetteer', license='MIT', packages=['pygazetteer'], install_requires=[ 'pyahocorasick' ], zip...
367
124
ID = {"Worldwide":0, "AF": 1, "AL": 2, "DZ": 3, "AD": 5, "AO": 6, "AI": 7, "AG": 9, "AR": 10, "AM": 11, "AW": 12, "AT": 14, "AZ": 15, "BS": 16, "BH": 17, "BD": 18, "BB": 19, "BY": 20, "BZ": 22, "BJ": 23, ...
3,145
1,876
""" These classes are a collection of the needed tools to read external data. The External type objects created by these classes are initialized before the Stateful objects by functions.Model.initialize. """ import re import os import warnings import pandas as pd # TODO move to openpyxl import numpy as np import xarr...
34,771
9,762
# File: C (Python 2.4) from direct.gui.DirectGui import * from direct.interval.IntervalGlobal import * from direct.fsm.FSM import FSM from direct.showbase.PythonUtil import Functor from pandac.PandaModules import * from pirates.piratesbase import PiratesGlobals from pirates.piratesbase import PLocalizer from pirates.p...
15,921
6,018
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at http://mozilla.org/MPL/2.0/. from logging import getLogger as getSysLogger from logging import * # Some of the build slave environments don't see the...
6,610
1,825
#!/usr/bin/env python # -*- coding: utf8 -*- # ***************************************************************** # ** PTS -- Python Toolkit for working with SKIRT ** # ** © Astronomical Observatory, Ghent University ** # ***************************************************************** ##...
14,335
3,820
# RiveScript-Python # # This code is released under the MIT License. # See the "LICENSE" file for more information. # # https://www.rivescript.com/ def get_topic_triggers(rs, topic, thats, depth=0, inheritance=0, inherited=False): """Recursively scan a topic and return a list of all triggers. Arguments: ...
5,876
1,631
#Copyright 2009 Humanitarian International Services Group # #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...
2,560
862
#!/usr/bin/env python # -*- coding: utf-8 -*- from os import path from setuptools import setup, find_packages here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.md')) as fin: long_description = fin.read() setup( name='pylint-pytest', version='1.0.3', author='Reverb Chu', ...
1,617
507
# Reverse TCP Shell in Python For Offensive Security/Penetration Testing Assignments # Connect on LinkedIn https://www.linkedin.com/in/lismore or Twitter @patricklismore #========================================================================================================================================= # Python...
1,637
410
# This file is dual licensed under the terms of the Apache License, Version # 2.0, and the BSD License. See the LICENSE file in the root of this repository # for complete details. from __future__ import absolute_import, division, print_function INCLUDES = """ #include <openssl/engine.h> """ TYPES = """ static const ...
6,395
2,814
import pytest from httpx import AsyncClient from conf_test_db import app from tests.shared.info import category_info, product_info @pytest.mark.asyncio async def test_new_product(): async with AsyncClient(app=app, base_url="http://test") as ac: category_obj = await category_info() payload = { ...
1,324
407
# This file was automatically generated by SWIG (http://www.swig.org). # Version 3.0.12 # # Do not make changes to this file unless you know what you are doing--modify # the SWIG interface file instead. from sys import version_info as _swig_python_version_info if _swig_python_version_info >= (2, 7, 0): def swig_im...
59,840
21,933
# -*- coding: utf-8 -*- import asyncio import datetime import json import logging import sys from typing import Optional import aiohttp from aiohttp import ClientSession from . import __version__ from .errors import ( BadGateway, BadRequest, Forbidden, HTTPException, InternalServerError, NotFo...
4,251
1,306
''' What is a Mother Vertex? A mother vertex in a graph G = (V,E) is a vertex v such that all other vertices in G can be reached by a path from v. How to find mother vertex? Case 1:- Undirected Connected Graph : In this case, all the vertices are mother vertices as we can reach to all the other nodes in the graph...
1,518
423
#!/usr/bin/env python # -*- coding: utf-8 -*- import os class Config: api_group = os.environ.get('API_GROUP', 'hello-k8s.s5t.dev') auth_method = os.environ.get("AUTH_METHOD", "cluster") examples_plural = os.environ.get('API_PLURAL', 'examples') examples_version = os.environ.get('API_VERSION', 'v1alpha...
516
201
""" Copyright (c) Microsoft Corporation. Licensed under the MIT License. """ import re import yaml from html.parser import HTMLParser from mistune import Renderer from mechanical_markdown.step import Step start_token = 'STEP' end_token = 'END_STEP' ignore_links_token = 'IGNORE_LINKS' end_ignore_links_token = 'END_...
2,613
764
#!/usr/bin/env python from __future__ import print_function import argparse import sys from compliance_checker.runner import ComplianceChecker, CheckSuite from compliance_checker.cf.util import download_cf_standard_name_table from compliance_checker import __version__ def main(): # Load all available checker cla...
7,082
1,736
from cms.app_base import CMSApp from cms.apphook_pool import apphook_pool from django.utils.translation import gettext as _ class CategoriesAppHook(CMSApp): name = _("Categories") def get_urls(self, page=None, language=None, **kwargs): return ["apps.articles.urls"] apphook_pool.register(CategoriesA...
328
110
from django.db.models.signals import pre_save from django.dispatch import receiver from blacklist import models from hashlib import sha256 @receiver(pre_save, sender=models.EmailEntry) def email_entry_handler(sender, instance, **kwargs): """ Handler that assigns to lower_case_entry_value the entry_value.lower...
821
260
# Generated by Django 3.1 on 2020-08-22 17:48 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='BoardGame', fields=[ ('id', models.AutoField(...
971
282
import re # regex for a user or channel mention at the beginning of a message # example matches: " <@UJQ07L30Q> ", "<#C010P8N1ABB|interns>" # interactive playground: https://regex101.com/r/2Z7eun/2 MENTION_PATTERN = r"(?:^\s?<@(.*?)>\s?)|(?:^\s?<#(.*?)\|.*?>\s?)" def get_set_element(_set): """get the element fr...
2,181
703
# In Search for the Lost Memory [Explorer Thief] (3526) # To be replaced with GMS's exact dialogue. # Following dialogue has been edited from DeepL on JMS's dialogue transcript (no KMS footage anywhere): # https://kaengouraiu2.blog.fc2.com/blog-entry-46.html recoveredMemory = 7081 darkLord = 1052001 sm.setSpeakerID(...
1,058
354
from django.contrib.auth.views import LoginView from django.urls import path from student import views urlpatterns = [ path('studentclick', views.studentclick_view, name='student-click'), path('studentlogin', LoginView.as_view( template_name='student/studentlogin.html'), name='studentlogin'), path...
1,404
455
# -*- coding: utf-8 -*- from aiida.common import NotExistent from aiida.orm import Dict from aiida_quantumespresso.calculations.pw import PwCalculation from aiida_quantumespresso.parsers import QEOutputParsingError from aiida_quantumespresso.parsers.parse_raw import convert_qe_to_aiida_structure from aiida_quantumespr...
10,381
2,909
from django.utils.translation import ugettext_lazy as _ from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from cms.models.pluginmodel import CMSPlugin class SubmenuPlugin(CMSPluginBase): model = CMSPlugin name = _("Submenu") render_template = "cms/plugins/submenu.html" pl...
361
117
import collections import datetime import json import multiprocessing import os import subprocess import sys import time _SSHD_BINARY_PATH = "/usr/sbin/sshd" EnvironmentConfig = collections.namedtuple( "EnvironmentConfig", ["hosts", "port", "is_chief", "pools", "job_id"]) class DeadlineExceededError(Excepti...
6,942
2,411
import datetime from pydantic import Field from typing import ( ClassVar, List, Dict, Optional, ) from smaregipy.base_api import ( BaseServiceRecordApi, BaseServiceCollectionApi, ) from smaregipy.utils import NoData, DictUtil class CustomerGroup(BaseServiceRecordApi): RECORD_NAME = 'custo...
2,539
825
#!/usr/bin/env python3 """ Base-Client Class This is the parent-class of all client-classes and holds properties and functions they all depend on. Author: Jason Cabezuela """ import src.util.debugger as Debugger import src.util.configmaker as configmaker class BaseClient(object): """Base-Client Class""" def ...
960
258
# -*- coding: utf-8 -*- import sys from cryptomon.common import Colors if sys.version_info >= (3, 0): import io else: import StringIO as io ascii_title = """ /$$$$$$ /$$ /$$ /$$ /$$__ $$ | $$ ...
1,575
559
import cv2 video=cv2.VideoCapture(r'C:\Users\ISHITA\Desktop\ML project\UEM_PROJECT_COM\pedestrian.mp4') #pre trained pedestrian and car classifier car_tracker_file=(r'C:\Users\ISHITA\Desktop\ML project\UEM_PROJECT_COM\car.xml') pedestrian_tracker_file=(r'C:\Users\ISHITA\Desktop\ML project\UEM_PROJECT_COM\pedestrian.x...
1,332
555
# site settings rest api serializers from rest_framework import serializers from saleor.wing.models import Wing as Table class TableListSerializer(serializers.ModelSerializer): update_url = serializers.HyperlinkedIdentityField(view_name='wing:api-update') delete_url = serializers.HyperlinkedIdentityField(vie...
1,658
419
from . import FishBase from . import FishGlobals class FishCollection: def __init__(self): self.fishList = [] def __len__(self): return len(self.fishList) def getFish(self): return self.fishList def makeFromNetLists(self, genusList, speciesList, weightList): self.fis...
2,165
637
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # # Distributed under terms of the MIT license. """ Strategy base class """ from abc import ABCMeta, abstractmethod from tinydb import TinyDB, Query from node import Node import json class Strategy(object): def __init__(self, this_controller, thi...
1,550
470
''' Problem Statement: If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3,5,6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below N. ''' from __future__ import print_function try: raw_input # Python 2 except NameError: raw_input = i...
525
208
import copy from django.db import NotSupportedError from django.db.models import Expression from .fields import mysql_compile_json_path, postgres_compile_json_path, FallbackJSONField class JSONExtract(Expression): def __init__(self, expression, *path, output_field=FallbackJSONField(), **extra): super()._...
2,017
587
import unittest import tempfile import pathlib import datetime import warnings from IPython.testing.globalipapp import start_ipython, get_ipython import pandas.util.testing as tm from pandas.core.frame import DataFrame from pandas.core.series import Series from pandas import read_excel import pytest ip = get_ipytho...
6,460
2,107
# https://www.reddit.com/r/dailyprogrammer/comments/3ltee2/20150921_challenge_233_easy_the_house_that_ascii/ import random import sys def main(): data = open(sys.argv[1]).read().splitlines()[1::] door = random.randrange(len(data[-1])) wideData = [] for row in data: curStr = '' for...
702
245
#!/usr/bin/env python # encoding: utf-8 from __future__ import division from decimal import Decimal import subprocess import threading import urllib2 import urllib import httplib import json import re import hashlib import base64 # import zlib from lib.command.runtime import UserInput from lib.helper.CameraHelper ...
11,103
3,341
############################# # Collaborators: (enter people or resources who/that helped you) # If none, write none # # ############################# base = input('Enter the base: ") height = area = # Calculate the area of the triangle print("The area of the triangle is (area).")
286
78
""" an adaptation of pyopencl's reduction kernel for weighted avarages like sum(a*b) mweigert@mpi-cbg.de """ from __future__ import print_function, unicode_literals, absolute_import, division from six.moves import zip import pyopencl as cl from pyopencl.tools import ( context_dependent_memoize, dtype_to_cty...
13,015
4,223
#! /usr/bin/env python import mcpi.minecraft as minecraft import mcpi.block as block import random import time mc = minecraft.Minecraft.create() # ---------------------------------------------------------------------- # S E T U P # ---------------------------------------------------------------------- # Where Am ...
596
237
#-*- encoding:utf-8 -*- from __future__ import print_function import sys try: reload(sys) sys.setdefaultencoding('utf-8') except: pass import codecs from textrank4zh import TextRank4Keyword, TextRank4Sentence text = codecs.open('../test/doc/01.txt', 'r', 'utf-8').read() tr4w = TextRank4Keyword() tr4w.an...
831
378
import random import uuid import sys import json from faker import Factory from faker.providers.person.fi_FI import Provider as PersonProvider fake = Factory.create('fi_FI') email_by_user = {} users_by_id = {} def anonymize_users(users): usernames = set() emails = set() for data in users: if data...
1,833
561
import random from typing import Optional, Tuple, Union import numpy as np import torch from torch import Tensor from torch_geometric.utils import coalesce, degree, remove_self_loops from .num_nodes import maybe_num_nodes def negative_sampling(edge_index: Tensor, num_nodes: Optional[Union[int...
12,252
3,964
import sys if sys.version_info[:2] >= (3, 0): # pylint: disable=E0611,F0401,I0011 from urllib.request import build_opener else: from urllib2 import build_opener from . import __version__ urls = { 'gdata': "https://www.googleapis.com/youtube/v3/", 'watchv': "http://www.youtube.com/watch?v=%s", ...
3,924
2,018
# Copyright (C) 2015, 2016 GoSecure Inc. """ Telnet Transport and Authentication for the Honeypot @author: Olivier Bilodeau <obilodeau@gosecure.ca> """ from __future__ import annotations import struct from twisted.conch.telnet import ( ECHO, LINEMODE, NAWS, SGA, AuthenticatingTelnetProtocol, ...
4,827
1,404
class WebException(Exception): pass class ParserException(Exception): """ 解析异常 """ pass class ApiException(Exception): """ api异常 """ pass class WsException(Exception): """ 轮询异常 """ pass class SsoException(Exception): """ sso异...
578
265
import astropy.io.fits as fits import matplotlib import matplotlib.pyplot as plt import numpy as np import obj_data as od import saphires as saph from astropy.time import Time from astropy.visualization import ZScaleInterval, SqrtStretch, ImageNormalize from matplotlib.backends.backend_pdf import PdfPages ra = od.ra d...
6,230
2,285
"""Tests for tools and arithmetics for monomials of distributed polynomials. """ from sympy.polys.monomialtools import ( monomials, monomial_count, monomial_key, lex, grlex, grevlex, monomial_mul, monomial_div, monomial_gcd, monomial_lcm, monomial_max, monomial_min, monomial_divides, Monomi...
5,590
2,635
import re import base64 import hmac import hashlib import logging import requests from datetime import datetime class AzureSentinel: def __init__(self, workspace_id, workspace_key, log_type, log_analytics_url=''): self._workspace_id = workspace_id self._workspace_key = workspace_key self....
2,752
851
from tkinter import * from PIL import ImageGrab import numpy as np import cv2 import time import pyautogui as pg import DirectInputRoutines as DIR from LogKey import key_check last_time = time.time() one_hot = [0, 0, 0, 0, 0, 0] hash_dict = {'w':0, 's':1, 'a':2, 'd':3, 'c':4, 'v':5} X = [] y = [] def a...
3,553
1,451
# Generated by Django 2.2.5 on 2019-10-05 23:22 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Password', fields=[ ('id', models.IntegerFi...
825
241
from django.template.loaders.base import Loader as BaseLoader from django.template.base import TemplateDoesNotExist class Mock(): pass class MockLoader(BaseLoader): is_usable = True def load_template_source(self, template_name, template_dirs=None): if template_name == 'cms_mock_template.html':...
515
155
import sigvisa.database.db from sigvisa.database.dataset import * import sigvisa.utils.geog cursor = database.db.connect().cursor() detections, arid2num = read_detections(cursor, 1237680000, 1237680000 + 168 * 3600, arrival_table="leb_arrival", noarrays=False) last_det = dict() overlaps = 0 for det in detections: ...
732
280
import pytest from onnx import TensorProto from onnx import helper as oh import finn.core.onnx_exec as oxe from finn.core.modelwrapper import ModelWrapper from finn.transformation.streamline.reorder import MoveTransposePastJoinAdd from finn.util.basic import gen_finn_dt_tensor def create_model(perm): if perm ==...
3,227
1,195
import json from lib import authz from lib.logger import logger from lib.exclusions import exclusions, state_machine def get_allowed_actions(user, account_id, requirement, exclusion): allowed_actions = { 'remediate': False, 'requestExclusion': False, 'requestExclusionChange': False, }...
1,537
454
#!/usr/bin/env python ''' Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License")...
9,545
2,588
import quandl import math import numpy as np from sklearn import preprocessing, cross_validation, svm from sklearn.linear_model import LinearRegression import pickle import datetime from matplotlib import style import matplotlib.pyplot as plot # Config isLoadFromLocal = True quandl.ApiConfig.api_key = '76eCnz6z9XTH8nf...
2,158
848
class IccProfile(): """Parses an ICC Colour Profile. According to spec: all Profile data shall be encoded as big-endian""" def __init__(self, bytes): self.header = {} self.parse_icc(bytes) def get_colour_space(self): """Returns the data colour space type, or None if not defi...
7,824
2,696
from .binary_search import binary_search def test_binary_search_empty_array(): assert binary_search([], 0) == -1 def test_binary_search_find_single_array(): assert binary_search([3], 3) == 0 def test_binary_search_not_found_single_array(): assert binary_search([1], 0) == -1 def test_binary_search_no...
1,179
476
def f(): print('f from module 2') if __name__ == '__main__': print('Module 2')
88
35