text
string
size
int64
token_count
int64
import sqlite3 import sys import os import io def cleanName(m_name): lis = [] lis = m_name result_lis = {} for data in lis: text = str(data) text = (((((text[2:len(text)-3].rstrip()).replace("@","")).replace("smt.","")).strip()).replace(".","")).replace("smt","") temp_lis = text...
1,075
396
from defcon.objects.base import BaseDictObject class Lib(BaseDictObject): """ This object contains arbitrary data. **This object posts the following notifications:** =========== ==== Name Note =========== ==== Lib.Changed Posted when the *dirty* attribute is set. ========...
1,389
408
from django.apps import AppConfig class PresenterConfig(AppConfig): name = 'Presenter'
93
28
#this program is atm that withdraw any money amount #allowed papers: 100,50,10,5, and the rest of requests def withdraw(balance,request): if request>balance: print "can`t give you all this money" while request>0: if request>=100: request-=100 print "give 100" elif request>=50: request-=50 print "g...
685
321
#!/usr/bin/env python3 from statistics import mode def execute(): with open('./input/day.3.txt') as inp: lines = inp.readlines() data = [l.strip() for l in lines if len(l.strip()) > 0] return power_consumption(data), life_support_rating(data) tests_failed = 0 tests_executed = 0 def verify(a, b):...
2,973
1,136
import cv2 import numpy as np from scipy.signal import medfilt from utils import init_dict, l2_dst def keypoint_transform(H, keypoint): """ Input: H: homography matrix of dimension (3*3) keypoint: the (x, y) point to be transformed Output: keypoint_trans: Transformed point keypoint_trans = H ...
6,194
2,304
# GENERATED BY KOMAND SDK - DO NOT EDIT import komand import json class Component: DESCRIPTION = "Returns VPN status" class Input: pass class Output: VPNS = "vpns" class VpnStatusInput(komand.Input): schema = json.loads(""" {} """) def __init__(self): super(self.__class__,...
1,140
408
import os import struct from .compilation.scout_flags import * from .compilation.scout_files import * from .compilation.arc_intel import arcIntel from .compilation.arc_arm import arcArm, arcArmThumb from .compilation.arc_mips import arcMips from .context_creator import * #############################...
15,306
4,540
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
6,870
2,337
# -*- coding: utf-8 -*- from selenium.webdriver.firefox.webdriver import WebDriver import unittest from group import Group from contact import Contact def is_alert_present(wd): try: wd.switch_to_alert().text return True except: return False class HW_new_contact(unittest.TestCase): ...
8,095
2,805
## using output of king and plink --miss identify worse performing duplicate for exclusion ## this script is run as follows ## python ExcludeDuplicates.py <king output> <plink --miss output> <output file> import sys print "Reading in sample missingness from", sys.argv[2] sampleMissing = file(sys.argv[2], "r") sam...
2,189
794
import numpy as np import pandas as pd from .jscatter import Scatter, component_idx_to_name from .utils import minmax_scale def test_component_idx_to_name(): assert 'valueA' == component_idx_to_name(2) assert 'valueB' == component_idx_to_name(3) assert None == component_idx_to_name(4) assert None == c...
3,375
1,272
import logging import sys from typing import Iterable # 3rd party imports import numpy as np # import matplotlib.pyplot as plt from scipy.io.wavfile import read as wavread # local imports from .dio import dio from .stonemask import stonemask from .harvest import harvest from .cheaptrick import cheaptrick from .d4c im...
10,917
3,611
"""Utilities to help building Docker images.""" import argparse import os import subprocess from typing import List, Optional from universal_build import build_utils FLAG_DOCKER_IMAGE_PREFIX = "docker_image_prefix" def parse_arguments( input_args: List[str] = None, argument_parser: argparse.ArgumentParser = No...
8,165
2,377
version https://git-lfs.github.com/spec/v1 oid sha256:ea33786bb4be2c91d879beaff23346f37c5b4b5b8504df61a909e3570d67eb08 size 5150
129
89
# Generated by Django 2.0.5 on 2018-05-22 21:02 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('status', '0003_auto_20180522_1745'), ('gear', '0005_weapon_reach'), ] operations = [ migrations.Cre...
1,415
449
expected_output = { "sort": { 1: { "invoked": 3321960, "usecs": 109, "tty": 0, "one_min_cpu": 0.54, "process": "PIM Process", "five_min_cpu": 0.48, "runtime": 362874, "pid": 368, "five_sec_cpu": 1.03,...
1,121
470
# -*- encoding: utf-8 -*- # Copyright (c) 2015 b<>com # # 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 o...
4,702
1,370
#!/usr/bin/env python from setuptools import setup setup( name="earthlyw", version="0.1", packages=[ "ibidem", "ibidem.earthlyw", ], install_requires=[ "setuptools", "colorlog<6", "appdirs<2", "requests<3", ], extras_require={ "dev": ...
873
311
#!/usr/bin/env python # -*- coding= UTF-8 -*- # Fad from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import A4 # setup the empty canvas from io import FileIO as file from reportlab.platypus import Flowable # from Common.pyPdf import PdfFileWriter, PdfFileReader from PyPDF2 import PdfFileWriter, PdfFil...
5,547
2,069
from __future__ import print_function, absolute_import import random import torch.utils.data as data from pose.utils.osutils import * from pose.utils.transforms import * from scipy.io import loadmat import argparse class Real_Animal_All(data.Dataset): def __init__(self, is_train=True, is_aug=False, **kwargs): ...
9,073
3,167
import sklearn from sklearn.cluster import KMeans from src.features.feature_selection import PCA_Variants2Gene_FeatureSelection class SLEuth(sklearn.base.TransformerMixin, sklearn.base.ClusterMixin): def __init__(self, cluster_num, variants_genes_path="../../data/interim/variants_top56_genes.csv", ...
2,376
716
p = [1, 4, 9, 10, 20, 25] e1 = int(input('Primeiro elemento: ')) e2 = int(input('Segundo elemento: ')) x = 0 achou = False primeiro = 0 while x < len(p): if p[x] == e1: print(f'Elemento 1 encontrado na posição {x} da lista!') if primeiro == 0: primeiro = 1 if p[x] == e2: prin...
492
199
from lk_db.ents.Ent import Ent class EntTime(Ent): pass
62
25
""" Visual Genome in Scene Graph Generation by Iterative Message Passing split """ import os import cv2 import json import h5py import pickle import numpy as np import scipy.sparse import os.path as osp from datasets.imdb import imdb from model.utils.config import cfg from IPython import embed class vg_sggimp(imdb)...
8,084
2,879
# SL030 RFID reader driver for skpang supplied SL030 Mifare reader # (c) 2013-2014 Thinking Binaries Ltd, David Whale #=============================================================================== # CONFIGURATION # # You can change these configuration items either by editing them in this # file, or by refering to th...
6,213
2,134
# parser.py - parses a given sentence using a given grammar definition import sys, os import argparse from utils import load_grammar def get_parser(grammar_file, *args, **kwargs): """ loads a parser from the given grammar """ return load_grammar(grammar_file, *args, **kwargs) def tokenize(sentence): """...
1,293
389
import re from typing import List, Any, Generator, Tuple, Pattern, Optional, Callable, Dict class Token: """ A Token class. Parameters ---------- lex: str Token's lexeme. token_type: Enum Token's type. """ def __init__(self, lex, token_type, line=0, column=0): ...
3,821
1,155
import random from django.core.management.base import BaseCommand from pandas import Series from src.cache.cache import put_labelled_logs from src.core.core import get_encoded_logs from src.jobs.models import Job from src.jobs.tasks import prediction_task from src.runtime.tasks import create_prediction_job from src....
3,975
1,123
#emacs, this is -*-Python-*- mode from __future__ import division from __future__ import with_statement import contextlib import threading, Queue class ChainLink(object): """essentially a linked list of threads""" def __init__(self): self._queue = Queue.Queue() self._lock = threading.Lock() ...
1,646
471
from flask import Flask, render_template, request, redirect, logging, make_response, json from ethw3 import genkey, create_chain_data, verify_chain_data, create_acct, mine, history_slice from utils_s3 import load_from_fetchlist # Initialize flask an other global variables app = Flask(__name__) address, username, addr,...
3,439
1,064
import json import os from datetime import date from typing import List, Dict from d3m_metadata.metadata import PrimitiveMetadata, PrimitiveFamily, PrimitiveAlgorithmType from d3m import index from dsbox.planner.common.primitive import Primitive from dsbox.schema.profile_schema import DataProfileType as dpt from col...
8,800
2,497
# Program 64 : Capitalize the First Character of a String my_string = input() cap_string = my_string.capitalize() print(cap_string)
134
45
# -*- coding: utf-8 -*- ''' Created on Fri Nov 16 09:36:50 2018 @author: Visa Suomi Turku University Hospital November 2018 @description: This model is used to predict radiation dose from pre-treatment patient parameters ''' #%% clear variables %reset -f %clear #%% import ne...
18,487
6,623
from dolfin import * parameters['form_compiler']['representation'] = 'uflacs' parameters['form_compiler']['cpp_optimize'] = True parameters['form_compiler']['cpp_optimize_flags'] = '-O3 -ffast-math -march=native' parameters['ghost_mode'] = 'shared_facet' mesh_file = 'cell_grid.h5' comm = mpi_comm_world() h5 = HDF5Fi...
3,610
1,405
from django.test import TestCase from customers.gems_utils import Gems class GemUtilsCase(TestCase): def setUp(self): self.gems = Gems() pass
165
51
import click import pandas import pickle import json from clients import s3, redis @click.command() @click.option('--both', 'upload', flag_value='s3_and_redis', default=True, help='Upload metadata to both s3 and Redis') @click.option('--s3', 'upload', flag_value='only_s3', help='Upload metadata only to s3') @click.op...
2,855
866
#!/usr/bin/env python3 import argparse import os import io import subprocess import sys from tabulate import tabulate def parse_args(): desc = ( 'Performance testing script for OasisLMF input file generation' 'This script expects a set of nested sub directories each containing' 'acc.csv, ...
5,158
1,884
#!/bin/env python from app import create_app, socketio from app.db_setup import init_db app = create_app(debug=False) init_db() if __name__ == '__main__': socketio.run(app, port=5001)
191
74
# from tkinter import * # root = Tk() # frametop = Frame(root) # framebottom = Frame(root) # frameleft = Frame(framebottom) # frameright = Frame(framebottom) # text = Text(frametop) # scroll = Scrollbar(frametop, command=text.yview) # btn1 = Button(frameleft, text="Course") # btn2 = Button(frameleft, text="Abscences...
1,427
612
import os import logging import shutil from optimus.i18n.manager import I18NManager def test_update_catalogs_all( minimal_i18n_settings, caplog, temp_builds_dir, fixtures_settings ): """ Update every catalogs """ basepath = temp_builds_dir.join("i18n_update_catalogs_all") # Copy sample proje...
2,270
731
"""This module contains examples of stream_func where f_type is 'element' and stream_func has a single input stream, and a single output stream, and the operation is stateful. The state captures information in the past input streams; this information is required to append values to the tails of the output streams. Th...
3,707
1,186
# mpqa3_to_dict helps to convert MPQA stand-off format to python dictionaries. # It provides the following functionalities: # 1) Clean up the MPQA 3.0 corpus # 2) Convert an MPQA document to a dictionary # 3) Convert an entire corpus to a dictionary import os import re HAS_LIST_OF_IDS = [ # These attributes may have ...
7,815
2,269
# # All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or # its licensors. # # For complete copyright and license terms please see the LICENSE at the root of this # distribution (the "License"). All use of this software is governed by the License, # or, if provided, by the license below or th...
1,283
388
#Crie um programa que tenha uma tupla com várias palavras (não usar acentos). Depois disso, você deve mostrar, para cada palavra, quais são as suas vogais. palavras=('SOPA','BATATAS','CACAU','CASTANHA','LASANHA','GOSTOSURAS','TRAVESSURAS','PARMEGIANA') for p in palavras: print(f'\n As Vogais de {p} são: ',end='') ...
402
160
import os from django.conf import * from django.shortcuts import render_to_response, render from django.http import HttpResponse from .models import Data, MovingAvg, Movements, Sigma from datetime import datetime from django.template import RequestContext def index(request): ticker = Data.objects.values_list('tic...
2,534
785
# Method_#1 #Regex_Pattern = r"\S\S\s\S\S\s\S\S" # Do not delete 'r'. # Method_#2 Regex_Pattern = r"(\S\S\s){2}(\S\S){1}" import re print(str(bool(re.search(Regex_Pattern, input()))).lower())
195
97
import os import shutil class TempFolder: def __init__(self, folder: str, **kwargs): self.folder = folder self.lock = kwargs.pop("LOCK", None) def lockit(self): if self.lock is not None: self.lock.acquire() def unlockit(self): if self.lock is not None: ...
842
275
regno='1941012661' year=2019 # print('My Regd. No is %s and I have taken admission in B. Tech. In %d.' %(regno, year)) print('My Regd. No is', regno,'and I have taken admission in B. Tech. In', year,'.' )
205
90
""" Описывается база данных для хранения, промежуточных результатов """ from django.db import models class SpeechApiModel(models.Model): encoded_data = models.TextField() ext = models.CharField(max_length=300) # blank=True означает, что поле может быть пустым при заполнении бд model = models.CharFiel...
483
157
"""setuptools entry point.""" from codecs import open from os import path from setuptools import find_packages, setup HERE = path.abspath(path.dirname(__file__)) with open(path.join(HERE, "README.rst"), encoding="utf-8") as f: LONG_DESCRIPTION = f.read() with open(path.join(HERE, "src", "den", "VERSION")) as ve...
1,690
567
''' Created on 31 Jul 2009 @author: charanpal ''' from __future__ import print_function import sys import os import numpy from contextlib import contextmanager import numpy.random as rand import logging import scipy.linalg import scipy.sparse as sparse import scipy.special import pickle from apgl.util.Parameter imp...
25,807
8,300
#!/usr/bin/python # -*- coding: utf-8 -*- ''' .. codeauthor: Albert Weichselbraun <albert.weichselbraun@htwchur.ch> .. codeauthor:: Heinz-Peter Lang <lang@weblyzard.com> ''' from __future__ import print_function from __future__ import unicode_literals from eWRT.ws.rest import MultiRESTClient from weblyzard_api.client ...
7,242
2,082
class Config(object): DEBUG = True DEVELOPMENT = True SECRET_KEY = 'do-i-really-need-this' SQLALCHEMY_DATABASE_URI = 'sqlite:///testing.db' SQLALCHEMY_TRACK_MODIFICATIONS = False KARAOKE_MEDIA_ROOT = "/path/to/app/static/media" class ProductionConfig(Config): DEVELOPMENT = False ...
395
159
import datetime, os from django.contrib.auth.models import User from products.lib.data_load import LoadProducts from zendesk.lib.load_tickets import LoadTickets from tasks.engine.maintenance import Maintenance from tasks.models import LastRun class TaskRunner: def __init__(self): """ Initialize t...
3,342
1,013
# -*- coding: utf-8 -*- """ Created on Sat Oct 23 10:51:14 2018 @author: peter """ from sklearn.feature_extraction.text import TfidfVectorizer import os from sklearn.model_selection import train_test_split from sklearn.neural_network import MLPClassifier from sklearn import metrics import urllib.parse from sklearn.ex...
1,667
670
import random import string from sqlalchemy.orm import Session import models, schemas def get_brand(db: Session, brand_id: int): return db.query(models.Brand).filter(models.Brand.id == brand_id).first() def get_brand_by_name(db: Session, name: str): return db.query(models.Brand).filter(models.Brand.name ==...
3,176
982
#!/usr/bin/env python3 from mdpyformat import * import pprintex header_md("""Python object primer for Python3 / meta classes""" ) header_md("""Introduction""", nesting = 2) print_md(""" Python is good at creating the illusion of being a simple programming language. Sometimes this illusion fails, like when you have...
28,847
8,851
import speech_recognition as sr #Recognition Module import pyttsx3 #Speaking package import json import series_counter as s_c engine = pyttsx3.init() #initialising pyttsx value def speak(text): engine.say(text) engine.runAndWait() speak('hi user') def Voice_recognize(wait...
3,508
1,095
# MIT License # # Copyright (c) 2019 SSL-Roots # # 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, modify, merge, pu...
14,431
6,555
# # Script to fuse features per member per family (i.e., for each FID.MID, average all encodings across feature dim). # Any features can be fused. Here is link to ArcFace features, # https://www.dropbox.com/s/5rbj68dqud2folu/FIDs-features.tar.gz?dl=0 # import pickle from pathlib import Path import numpy as np from tqd...
2,432
756
# Python > Collections > Company Logo # Print the number of character occurrences in descending order. # # https://www.hackerrank.com/challenges/most-commons/problem # from collections import Counter from itertools import groupby name = input() nb = 0 for c, g in groupby(Counter(name).most_common(), key=lambda x: x[...
454
156
# 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 ...
19,174
5,794
import os from torch.optim import Adam, SGD import skopt import torch from utils.data_utils import select_data from utils.visualization_utils import plot_data_and_fit from learning_models.logistic import Logistic # df_file = os.path.join(os.getcwd(), "dati-regioni", "dpc-covid19-ita-regioni.csv") df_file = os.path.j...
2,960
1,238
#!/usr/bin/env python from confluent_kafka import Producer, Consumer, KafkaError import sys import time import subprocess from datetime import datetime import threading from collections import defaultdict import re import uuid def log(text, to_file=False): global output_file print(text) if to_file: ...
16,181
5,188
"""Tests for string representations of Quantities and Units, i.e. __repr__ and __str__""" from units import unit from units.predefined import define_units from units.quantity import Quantity from units.registry import REGISTRY def test_quantity_repr(): """Developer-friendly string representation of quantities."""...
2,374
742
from rest_framework.permissions import BasePermission, SAFE_METHODS class IsOwnerOrReadOnly(BasePermission): message = 'You must be the owner of this object' def has_object_permission(self, request, view, obj): if request.method in SAFE_METHODS: return True return obj.seller == re...
643
192
#!/usr/bin/python # # FishPi - An autonomous drop in the ocean # # Simple test of PWM motor and servo drive # import logging import raspberrypi from time import sleep from drive_controller import AdafruitDriveController if __name__ == "__main__": logger = logging.getLogger() logger.setLevel(logging.DEBUG) ...
969
365
import logging import numpy as np import pandas as pd import scipy.stats as ss from scipy.linalg import eig from numba import jit import sg_covid_impact # from mi_scotland.utils.pandas import preview logger = logging.getLogger(__name__) np.seterr(all="raise") # Raise errors on floating point errors def process_c...
13,246
4,470
'''Ex 019 - Um professor quer sortear um dos seus quatro alunos para apagar o quadro. Faça um programa que ajude ele, lendo o nome dos alunos e escrevendo na tela o nome do escolhido.''' print('-' * 15, '>Ex 19<', '-' * 15) from random import choice # Usando Random para sortiar o escolhido. # Recebendo dados. aluno...
768
281
from sklearn.model_selection import StratifiedKFold from evalml.preprocessing.data_splitters.balanced_classification_sampler import ( BalancedClassificationSampler ) from evalml.preprocessing.data_splitters.base_splitters import ( BaseUnderSamplingSplitter ) from evalml.preprocessing.data_splitters.training_va...
4,807
1,358
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class AlipayOpenAuthUserauthTokenCreateModel(object): def __init__(self): self._scopes = None self._user_id = None @property def scopes(self): return self._scopes ...
1,327
442
from .data import CovidData import datetime as dt from matplotlib.offsetbox import AnchoredText import pandas as pd import seaborn as sns import geopandas as gpd import matplotlib.pyplot as plt plt.style.use('ggplot') def pan_duration(date): """Return the duration in days of the pandemic. As...
46,745
16,417
# -*- coding: utf-8 -*- from __future__ import absolute_import import logging from contextlib import contextmanager from System.Runtime.InteropServices import Marshal @contextmanager def autorelease(comobj): """COM auto release contextmanager""" try: yield comobj finally: Marshal.ReleaseComObject(c...
12,969
3,542
from pymongo import MongoClient client = MongoClient('mongodb+srv://<username>:<password>@cluster0.27gwi.mongodb.net/Cluster0?retryWrites=true&w=majority') username = "" password = "" url = f'mongodb+srv://{username}:{password}@cluster0.27gwi.mongodb.net/Cluster0?retryWrites=true&w=majority' client = MongoClient(url) ...
389
142
""" Blurring of images =================== An example showing various processes that blur an image. """ import scipy.misc from scipy import ndimage import matplotlib.pyplot as plt face = scipy.misc.face(gray=True) blurred_face = ndimage.gaussian_filter(face, sigma=3) very_blurred = ndimage.gaussian_filter(face, sigm...
750
332
#! /usr/bin/env python import json from optparse import OptionParser usage = "usage: %prog [options] message" parser = OptionParser(usage) (options, args) = parser.parse_args() if len(args) != 1: parser.error("You must supply a label") label = args[0] try: with open('pylintReport.json', 'r') as reportFile:...
2,845
778
# -*- coding: utf-8 -*- """Unit test package for jinja_inflection."""
71
30
from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from cms.plugins.utils import downcast_plugins from cms.models.placeholdermodel import Placeholder from cms.models.pluginmodel import CMSPlugin from smartsnippets_inherit.models import InheritPageContent from smartsnippets_inherit.forms i...
4,376
1,163
from django.conf import settings from rest_framework.exceptions import ParseError from rest_framework.parsers import BaseParser import orjson __all__ = ["ORJSONParser"] class ORJSONParser(BaseParser): """ Parses JSON-serialized data by orjson parser. """ media_type = "application/json" def pa...
1,389
341
from djangosanetesting.cases import TemplateTagTestCase class TestTagLib(TemplateTagTestCase): preload = ('dsttesttags',) def test_tag_error(self): self.assert_raises(self.TemplateSyntaxError, self.render_template, '{% table %}') def test_tag_output(self): self....
1,942
633
# An example WSGI for use with mod_wsgi, edit as necessary # See http://mercurial.selenic.com/wiki/modwsgi for more information # Path to repo or hgweb config to serve (see 'hg help hgweb') config = "/path/to/repo/or/config" # Uncomment and adjust if Mercurial is not installed system-wide # (consult "installed module...
680
213
import os from subprocess import run import pyperclip import webbrowser from urllib import parse location = 'production' def runOnSingleFolder(folder): file_list = os.listdir(os.path.join(location, folder)) for file in file_list: file_noextend = file[:-(len(folder) + 1)] url = f'https://2021....
727
264
from .mscff_model import MSCFF
31
13
from .InputLayerStructure import InputLayerStructure from .LayerStructure import LayerStructure
96
24
from ursina import * app = Ursina() snake = Entity(model='cube', texture = 'assets\snake', scale=0.4, z=-1, collider='box') ground = Entity(model='cube', texture='grass',rotation=(90,0,0),scale=(5,1,5), z=1) apple = Entity(model='cube', texture='assets\\apple', scale=0.4, position=(1,-1,-1), collider='mesh') body = [...
1,180
513
import json from cp_request import Attribute, NamedEntity, Unit, Value from cp_request.named_entity import NamedEntityEncoder, NamedEntityDecoder class TestNamedEntity: def test_entity(self): e1 = NamedEntity(name="one", reference="http://one.one") e2 = NamedEntity(name="one", reference="http://...
3,153
981
import tensorflow as tf from utils.decorators import shape_check @shape_check def photometric_loss_l1(synt_target, orig_target, reduce=True): """ :param synt_target: scaled synthesized target image [batch, numsrc, height/scale, width/scale, 3] :param orig_target: scaled original target image [batch, heigh...
4,282
1,598
# -*- coding: utf-8 -*- ''' Created on 2015-08-21 @author: xhj ''' import requests import StringIO import gzip import threading from loginer import Loginer import time from my_log import WeiboSearchLog import os import traceback from bs4 import BeautifulSoup import re from Queue import Queue import datetime from st...
23,127
8,152
from datetime import datetime, time from enum import Enum from typing import Optional, Sequence, Union from pydantic import BaseModel class Direction(Enum): enum_1 = 1 enum_2 = 2 class PetLocationSet(BaseModel): where: Direction
246
75
########################## #### # WARNING: THIS FILE IS DEPRECATED AND IS ONLY RETAINED FOR INFORMATIONAL PURPOSES # ../dumb_topic_client is the up-to-date sample program ### ######################### from tweepy.streaming import StreamListener from tweepy import OAuthHandler from tweepy import Stream import requests ...
1,303
443
#!/usr/bin/env python # -*- coding:utf-8 -*- # @Filename: DROP3.py # @Author: Daniel Puente Ramírez # @Time: 31/12/21 16:00 # @Version: 5.0 import copy from sys import maxsize import numpy as np import pandas as pd from sklearn.neighbors import NearestNeighbors from .utils import transform class...
11,186
3,267
from django.apps import AppConfig from orchestra.core import accounts, administration from orchestra.core.translations import ModelTranslation class IssuesConfig(AppConfig): name = 'orchestra.contrib.issues' verbose_name = "Issues" def ready(self): from .models import Queue, Ticket a...
485
136
import numpy as np import matplotlib.pyplot as plt x = np.random.rand(10, 10) plt.imshow(x, cmap=plt.cm.hot) # 显示右边颜色条 plt.colorbar() plt.savefig('imshow_demo.png')
178
92
# This test code was written by the `hypothesis.extra.ghostwriter` module # and is provided under the Creative Commons Zero public domain dedication. from pathlib import Path from hypothesis import given, strategies as st import attack_surface_pypy.core.exceptions @given(message=st.text()) def test_fuzz_InvalidFile...
942
317
#! /usr/bin/python3 from Crypto.Cipher import AES from random import randint # https://www.cryptopals.com/sets/4/challenges/27 # Recover the key from CBC with IV=Key import sys sys.path.append('..') from cryptopals import ctr,xor,random_aes_key,cbc_decrypt,cbc_encrypt def random_aes_key(blocksize=16): return...
1,445
588
import os import sys DIRNAME = os.path.abspath(os.path.dirname(__file__)) rel = lambda *x: os.path.abspath(os.path.join(DIRNAME, *x)) PROJECT_DIR = rel('..') activate_this = rel('env', 'bin', 'activate_this.py') # Activate virtualenv execfile(activate_this, {'__file__': activate_this}) os.environ['DJANGO_SETTINGS_...
577
220
"""Functions for generating random data with injected relationships""" from itertools import product import os import json import re import random import numpy as np from numpy import random as rd from scipy.special import comb from ntp.util.util_kb import load_from_list def gen_relationships(n_pred, n_rel, body_...
8,057
2,381
from django.urls import reverse from rest_framework import status from rest_framework.test import APITestCase from accounts.models import Account from accounts.serializers import AccountSerializer from .utils import create_accounts class AccountViewsTests(APITestCase): def test_create_account(self): """...
1,116
312
#!/usr/bin/python3 FILE_PATH = "./littleschoolbus.bmp" with open(FILE_PATH,"rb") as f: bytes = bytearray(f.read()) result = "" for byte in bytes[54:]: result += str(byte & 1) print(result)
202
85