text
string
size
int64
token_count
int64
from typing import cast from grizzly.context import GrizzlyContext from grizzly.steps import * # pylint: disable=unused-wildcard-import # noqa: F403 from ....fixtures import BehaveFixture def test_step_results_fail_ratio(behave_fixture: BehaveFixture) -> None: behave = behave_fixture.context grizzly = cas...
1,785
632
"""Module for over expression tokenization.""" from .basic_regex_tokenizer import BasicRegexTokenizer class OverExpression(BasicRegexTokenizer): """Over Expression tokenizer class.""" def pattern(self) -> str: """Return over expression regex.""" return r'\bover ?expression\b' def token_t...
419
111
#!/usr/bin/env python3 from pathlib import Path from jq_normaliser import JqNormaliser, Filter class HypNormaliser(JqNormaliser): def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs, logger_tag='hypothesis-normaliser', delete_dominated=True, keep_both=False) # type: ignore ...
465
157
#! /usr/bin/env python # -*- coding: UTF-8 -*- # Author : Steeve Barbeau, Luca Invernizzi # This program is published under a GPLv2 license import re from scapy.all import TCP, bind_layers, Packet, StrField def _canonicalize_header(name): ''' Takes a header key (i.e., "Host" in "Host: www.google.com", an...
8,506
2,463
import os import unittest from flask_app.boot import load_dot_env, reset, is_loaded, load_env from tests.unit.testutils import BaseUnitTestCase, get_function_name from unittest_data_provider import data_provider def get_env(): return (None, True), ('dev', True), ('development', True), ('integration', True), ('sta...
1,800
566
def QuadraticRegression(px,py): sumy = 0 sumx1= 0 sumx2= 0 sumx3 = 0 sumx4 = 0 sumxy = 0 sum2y = 0 n=len(px) for i in range (n): x = px[i] y = py[i] sumx1 += x sumy += y sumx2 += x*x sumx3 += x*x*x sumx4 += x*x*x*x p...
805
419
from typing import Any, Dict, Optional from atcodertools.codegen.code_style_config import CodeStyleConfig from atcodertools.codegen.models.code_gen_args import CodeGenArgs from atcodertools.codegen.template_engine import render from atcodertools.fmtprediction.models.format import (Format, ParallelPattern, ...
5,591
1,607
""" This module contains an implementation for Binance Futures (BinanceFuturesExchangeHandler) """ from __future__ import annotations import pandas as pd import typing import json import logging import pandas as pd from datetime import datetime from dataclasses import dataclass from . import futurespy as fp from...
16,873
4,580
name = 'orbit' __version__ = '1.0.10'
39
22
import torch from typing import Union, Iterable def center(k: torch.Tensor) -> torch.Tensor: """Center features of a kernel by pre- and post-multiplying by the centering matrix H. In other words, if k_ij is dot(x_i, x_j), the result will be dot(x_i - mu_x, x_j - mu_x). :param k: a n by n Gram matrix of ...
1,971
695
#!/usr/bin/env python3 """Copyright (c) 2020 Cisco and/or its affiliates. This software is licensed to you under the terms of the Cisco Sample Code License, Version 1.1 (the "License"). You may obtain a copy of the License at https://developer.cisco.com/docs/licenses All use of the material herein must b...
6,253
1,827
from PyQt4.QtGui import * from PyQt4.QtCore import * class MyTabView(QTableView): def __init__(self, parent=None): super(MyTabView, self).__init__(parent) self.model = QStandardItemModel(4, 2) self.setModel(self.model) def mouseDoubleClickEvent(self, event): QTableView.mouseDo...
663
230
import logging from itertools import cycle import discord from discord.ext import commands, tasks from pyboss.controllers.guild import GuildController from .utils import youtube from .utils.checkers import is_guild_owner logger = logging.getLogger(__name__) class Commands(commands.Cog): def __init__(self, bot...
2,868
893
import tensorflow as tf import numpy as np from scipy.integrate import odeint import matplotlib.pyplot as plt from plotting import newfig, savefig import matplotlib.gridspec as gridspec import seaborn as sns import time from utilities import neural_net, fwd_gradients, heaviside, \ tf_session, mea...
19,860
8,654
# Generated by Django 3.1.2 on 2020-11-12 06:53 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('food_items', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='category', name='products', ...
775
230
from ciphers import StreamlinedNTRUPrime # choose your parameters p, q, w = 761, 4591, 286 print('Streamlined NTRU Prime Example for', f'p={p}, q={q}, w={w}') print('-' * 50) cipher = StreamlinedNTRUPrime(p, q, w, seed=1337) print('Generating key pair ... ') pk, sk = cipher.generate_keys() print('En/decrypting...')...
511
204
# -*- coding: utf-8 -*- import os, sys, shutil, re def trip_space(s): while len(s) > 0 and s[-1] == '\x00': s = s[:-1] ## while len(s) > 0 and s[:2] == b'\x00\x00': ## s = s[2:] return s def _print(*args): try: for arg in args: print arg, ...
3,721
1,452
from typing import Dict, Iterable, Iterator, List, Sequence, Optional, Tuple from word_ladder.types import WordDict from word_ladder.rung import Rung def get_word_with_letter_missing(word: str, position: int) -> str: """ >>> get_word_with_letter_missing('dog', 0) '?og' >>> get_word_with_letter_missing...
4,123
1,594
"""Package init file. We want the user to get everything right away upon `import nawrapper as nw`. """ from .power import * from .maptools import * from .covtools import * from . import planck
194
57
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('plea', '0014_auto_20151119_1136'), ] operations = [ migrations.CreateModel( name='DataValidation', f...
923
276
from cloudify import ctx from cloudify.decorators import operation from a4c_common.wrapper_util import (USE_EXTERNAL_RESOURCE_KEY,handle_external_resource,handle_resource_ids) from openstack import with_cinder_client from openstack.volume import create @operation @with_cinder_client def overrided_create_volume(cinde...
498
161
from typing import Iterator, List, Optional from drift_report.domain.model import Model class ModelRepository: def __init__(self) -> None: self.state: List[Model] = [] def create(self, model: Model): self.state.append(model) def all(self) -> Iterator[Model]: return iter(self.stat...
571
166
# PART 1 with open('input.txt') as input_file: x_pos = 0 y_pos = 0 for line in input_file: direction = line.split(' ')[0] distance = int(line.split(' ')[1]) if direction == "forward": x_pos += distance elif direction == "down": y_pos += distance ...
1,407
437
from typing import Optional from pydantic import BaseModel from cosmopy.model import CosmosModel class Engine(BaseModel): hp: int volume: int class Car(CosmosModel): make: str model: str engine: Optional[Engine] if __name__ == "__main__": passat = Car(make="VW", model="Passat") print...
794
312
#!/usr/bin/env python import rospy import tf import scipy.linalg as la import numpy as np from math import * import mavros_msgs.srv from mavros_msgs.msg import AttitudeTarget from nav_msgs.msg import Odometry from std_msgs.msg import * from test.msg import * from geometry_msgs.msg import * from mavros_msgs.msg import *...
6,882
3,137
#!/usr/bin/env python3 import argparse import asyncio import json from aiohttp import ClientSession, BasicAuth, ClientTimeout import os import aiohttp_github_helpers as h GITHUB_USER = os.environ.get('GITHUB_USER', None) GITHUB_PASS = os.environ.get('GITHUB_PASS', None) TIMEOUT = ClientTimeout(total=20) AUTH = None i...
1,233
417
# import support libraries import os import time import numpy as np # import main working libraries import cv2 import torch from torch.autograd import Variable from torchvision import transforms from PIL import Image # import app libraries from darknet import Darknet from utils import * from MeshPly import MeshPly ...
23,588
10,146
team_abbr_lookup = { "Toronto Raptors": "TOR", "Brooklyn Nets": "BRK", "New York Knicks": "NYK", "Boston Celtics": "BOS", "Philadelphia 76ers": "PHI", "Indiana Pacers": "IND", "Chicago Bulls": "CHI", "Cleveland Cavaliers": "CLE", "Detroit Pistons": "DET", "Milwaukee Bucks": "MIL...
4,028
1,754
from flask import Flask, request import redis app = Flask(__name__) rconn = redis.StrictRedis() def keygen(key): return "token:{key}".format(key=key) @app.route('/api/register', methods=["POST"]) def register_token(): userid = request.form['userid'] token = request.form['token'] rconn.set(keygen(u...
335
118
import random from collections import namedtuple MatrixShape = namedtuple("MatrixShape", ["rows", "columns"]) def array2d(shape, value): return [[value(i, j) for j in range(shape[1])] for i in range(shape[0])] class Matrix: def __init__(self, array): self.array = array rows = len(array) ...
4,832
1,460
import os.path from typing import Any, Iterable, Mapping, Optional, Tuple import tfx.v1 as tfx from absl import logging from ml_metadata.proto import metadata_store_pb2 from tfx.dsl.components.base.base_component import BaseComponent from tfx.types.channel import Channel from .base import BasePipelineHelper from .int...
3,975
1,138
"""Useful utility functions for services.""" import logging import re from datetime import datetime, timezone from inspect import Parameter, Signature from dateutil.parser import parse from humanize import naturaldelta, naturaltime logger = logging.getLogger(__name__) WORDS = {'1': 'one', '2': 'two', '3': 'three', ...
7,956
2,473
class Solution: def trapRainWater(self, heightMap: List[List[int]]) -> int: if not any(heightMap): return 0 m, n = len(heightMap), len(heightMap[0]) pq = [] visited = set() for j in range(n): pq.append((heightMap[0][j], 0, j)) pq.append((he...
1,084
400
import utils m = utils.opener.raw("input/16.txt") rm, tm, om = m.split("\n\n") rules = {} for line in rm.split("\n"): name, expr = line.split(": ") rules[name] = [[int(q) for q in x.split("-")] for x in expr.split(" or ")] myticket = [int(x) for x in tm.split("\n")[1].split(",")] tickets = [[int(q) for q in ...
1,233
497
from collections import Counter import random import math ### # Parameters of assumptions ### # How many initial investments and avg check size num_seed_rounds = 50 invested_per_seed_round = 0.5 # Probabilities of different outcomes (prob, outcome multiple) outcome_probs_seed = [ [0.01, 100], # N% chance of Mx ret...
4,931
1,750
import numpy as np def dice_ratio(pred, label): '''Note: pred & label should only contain 0 or 1. ''' return np.sum(pred[label==1])*2.0 / (np.sum(pred) + np.sum(label))
186
71
import PyQt5 import PyQt5.QtWidgets import PyQt5.QtCore import sys import requests import random import string import threading from Crypto.Cipher import AES from Crypto.Util.Padding import pad, unpad import os import shutil btcAdd = "" email = "" discordWebhook = "" fileTypes = ['.txt','.exe','.p...
8,408
3,828
import os from flask import Blueprint, Flask def create_app(opts = {}): app = Flask(__name__) # We will learn how to store our secrets properly in a few short weeks. # In the meantime, we'll use this: app.config['SECRET_KEY'] = os.getenv('SECRET_KEY') or "Don't ever store secrets in your actual code" ...
611
200
from datetime import datetime from unittest import TestCase from dateutil.tz import UTC from src.DateUtils import get_start_of_year, get_start_of_year_after, date_to_string, date_and_time_to_string class TestDateUtils(TestCase): def test_get_start_of_year(self): self.assertEqual(datetime(2018, 1, 1, 0,...
845
371
import cStringIO import hashlib import MySQLdb import os import random import signal import sys import threading import time import string import traceback CHARS = string.letters + string.digits def sha1(x): return hashlib.sha1(str(x)).hexdigest() # Should be deterministic given an idx def get_msg(do_blob, idx): ...
18,260
6,325
from configparser import ConfigParser from glob import glob from discord import Embed from discord.ext.commands import Cog, command, group, is_owner import asyncio import datetime import sys import discord from discord.ext.commands.context import Context #from tinker.ext.apps import * class Counter(discord.ui.View...
2,037
557
#!/usr/bin/env python # Copyright 2018 The JsCodeStyle Authors. # Copyright 2007 The Closure Linter 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...
20,820
5,817
#!/usr/bin/python # -*- coding:utf-8 -*- ''' 编写一个函数,其作用是将输入的字符串反转过来。 示例 1: 输入: "hello" 输出: "olleh" 示例 2: 输入: "A man, a plan, a canal: Panama" 输出: "amanaP :lanac a ,nalp a ,nam A" ''' class Solution: def reverseString(self, s): ''' :param s: str :return: str ''' return s[:...
326
161
from django.contrib import admin from .models import Profile,Neighborhood,Posts,Business # Register your models here. admin.site.register(Profile) admin.site.register(Neighborhood) admin.site.register(Posts) admin.site.register(Business) # admin.site.register(DisLike) # admin.site.register(MoringaMerch) # admin.site.r...
343
111
# This file is auto-genereated by bess-gen-doc. # See https://github.com/nemethf/bess-gen-doc # # It is based on bess/protobuf/module_msg.proto, which has the following copyright. # Copyright (c) 2016-2017, Nefeli Networks, Inc. # Copyright (c) 2017, The Regents of the University of California. # All rights reserved. ...
62,843
19,117
# Generated by Django 2.2.9 on 2020-11-20 02:29 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('posts', '0009_auto_20201115_0431'), ] operations = [ migrations.AddConstraint( model_name='follow', constraint=model...
409
144
import pytest from disterminal import helpers import numpy as np def main_call(x): out = np.zeros(x.shape) out[1] = 0.1 out[-1] = 0.1 return out def test_autorange(): x = helpers.autorange(main_call, '') assert x.shape == (100,) assert x.min() == pytest.approx(-9999.95) assert x.ma...
350
148
import pytest from listlookup import ListLookup sample_list = [ {"id": 1, "country": "us", "name": "Atlanta"}, {"id": 2, "country": "us", "name": "Miami"}, {"id": 3, "country": "uk", "name": "Britain"}, {"id": 5, "country": "uk", "name": "Bermingham"}, {"id": 4, "country": "ca", "name": "Barrie"},...
4,149
1,446
import time import numpy as np import os, sys, shutil from contextlib import contextmanager from numba import cuda as ncuda import PIL from PIL import Image, ImageFilter, ImageDraw, ImageFont import cv2 import contextlib from copy import deepcopy import subprocess from glob import glob from os import path as osp from o...
13,697
5,675
#coding=utf-8 #测试os.walk()递归遍历所有的子目录和子文件 import os all_files = [] path = os.getcwd() list_files = os.walk(path) for dirpath,dirnames,filenames in list_files: for dir in dirnames: all_files.append(os.path.join(dirpath,dir)) for file in filenames: all_files.append(os.path.join(dirpath,file)) #...
371
172
# -------------------------------------------------------- # Faster R-CNN # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick and Xinlei Chen # -------------------------------------------------------- from __future__ import absolute_import from __future__ import division from __future_...
2,801
1,020
from __future__ import print_function import os import time import numpy as np import tensorrt as trt import pycuda.driver as cuda import pycuda.autoinit import cv2 import mmcv from tqdm import tqdm import pickle as pkl from vis_util import show_corners from tools.model_zoo import model_zoo as zoo TRT_LOGGER = trt.L...
14,999
5,562
import os, time, sys, hashlib # Python Recreation of MonitorSauraus Rex. # Originally Developed by Luke Barlow, Dayan Patel, Rob Shire, Sian Skiggs. # Aims: # - Detect Rapid File Changes # - Cut Wifi Connections # - Create Logs for running processes at time of trigger, find source infection fil...
1,741
640
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved from .data_source import DataSchema, DataSchemaConfig, DataSource from .tsv import TSVDataSource __all__ = ["DataSchema", "DataSchemaConfig", "DataSource", "TSVDataSource"]
270
80
import math class Solution(object): def bfs(self, maze, i, j, fx, fy, m, n): if i == fx and j == fy: return 0 path = 0 bfsqueue = [] bfsvisit = [[0 for j in range(n)] for i in range(m)] bfscost = [[math.inf for j in range(n)] for i in range(m)] bfsvisit...
4,444
1,673
import requests import json from datetime import date, datetime, timedelta class Coinext: def __init__(self, ativo): self.ativo = ativo self.urlCoinext = 'https://api.coinext.com.br:8443/AP/' def service_url(service_name): return 'https://api.coinext.com.br:8443/AP/%s' % servic...
3,836
1,208
from raspi_io import SoftSPI, GPIO import raspi_io.utility as utility if __name__ == "__main__": address = utility.scan_server(0.05)[0] cpld = SoftSPI(address, GPIO.BCM, cs=7, clk=11, mosi=10, miso=9, bits_per_word=10) flash = SoftSPI(address, GPIO.BCM, cs=8, clk=11, mosi=10, miso=9, bits_per_word=8) ...
469
227
class Solution: def checkValidString(self, s): """ :type s: str :rtype: bool """ cmin = cmax = 0 for ch in s: cmax = cmax - 1 if ch == ')' else cmax + 1 cmin = cmin + 1 if ch == '(' else max(cmin - 1, 0) if cmax < 0: return False ...
342
119
from torch import nn, optim from torch.utils.tensorboard import SummaryWriter from tqdm import tqdm import torch def get_optimizer(model, lr): return optim.Adam(model.parameters(), lr=lr) def _to_one_hot(y, num_classes): scatter_dim = len(y.size()) y_tensor = y.view(*y.size(), -1) zeros = torch.zero...
2,527
890
""" Zip - Unindo iteráveis Zip_longest _ Itertools """ from itertools import zip_longest, count index = count() cidades = ['Sao Paulo', 'Belo Horizonte', 'Salvador', 'Monte Belo'] estados = ['SP', 'MG', 'BA'] cidades_estados = zip_longest(cidades, estados) for valor in cidades_estados: print(valor)
307
117
import os import ast import torch import torch.nn as nn from torch.nn import functional as F import torch.optim as optim from torch.utils.data import DataLoader from pytorch_lightning.core.lightning import LightningModule from pytorch_lightning import Trainer from argparse import ArgumentParser from model import Speech...
7,087
2,165
""" AWS DeepRacer reward function using only progress """ #=============================================================================== # # REWARD # #=============================================================================== def reward_function(params): # Skipping the explanation and verbose math here... ...
596
164
from __future__ import absolute_import, unicode_literals from hashlib import sha1 from time import sleep from celery import shared_task from .models import JPEGFile @shared_task def calculate_etag(pk): jpeg = JPEGFile.objects.get(pk=pk) jpeg.etag = sha1(jpeg.file.read()).hexdigest() sleep(5) jpeg.sav...
579
218
# coding=utf-8 """ Redirector tests """ from redirector import views def test_redirects_correctly(client): response = client.get('/foo/bar.html?foo=bar') assert response.status_code == 301 assert response.headers['Location'] == 'https://www.example.com/foo/bar.html?foo=bar' def test_normalize_port_norm...
2,028
782
"""multipy: Python library for multicomponent mass transfer""" __author__ = "James C. Sutherland, Kamila Zdybal" __copyright__ = "Copyright (c) 2022, James C. Sutherland, Kamila Zdybal" __license__ = "MIT" __version__ = "1.0.0" __maintainer__ = ["Kamila Zdybal"] __email__ = ["kamilazdybal@gmail.com"] __status__ = "Pro...
13,715
3,801
import numpy as np import pandas as pd from backtesting.analysis import plot_cost_proceeds, plot_holdings, \ plot_performance from backtesting.report import Report from backtesting.simulation import simulate def main() -> None: from string import ascii_uppercase np.random.seed(42) markets = list(asci...
1,311
491
''' Author: Geeticka Chauhan Performs pre-processing on a csv file independent of the dataset (once converters have been applied). Refer to notebooks/Data-Preprocessing for more details. The methods are specifically used in the non _original notebooks for all datasets. ''' import os, pandas as pd, numpy as np import ...
24,681
7,763
import datetime import seaborn as sns import pickle as pickle from scipy.spatial.distance import cdist, pdist, squareform import pandas as pd from sklearn.linear_model import LogisticRegression, LogisticRegressionCV #from sklearn.model_selection import StratifiedShuffleSplit from collections import defaultdict...
9,868
3,812
# Colorful VALORANT by b0kch01 import os, ctypes # Disable quick-edit mode (pauses bot) kernel32 = ctypes.windll.kernel32 kernel32.SetConsoleMode(kernel32.GetStdHandle(-10), 128) from pyfiglet import Figlet from termcolor import cprint, colored import colorama import keyboard import time # Fix legacy console color...
1,988
772
#!/usr/bin/env python import json import urllib import urllib2 import sys apikey = '843fa2012b619be746ead785b933d59820a2e357c7c186e581e8fcadbe2e550e' def usage(): print '''Submit hash to virtus-total (Place your VirusTotal apikey in this script) Usage: %s <hash>''' % sys.argv[0] exit(1) def collect(data): retr...
2,240
850
__all__ = ( 'ANYSP', 'DLQUO', 'DPRIME', 'LAQUO', 'LDQUO', 'LSQUO', 'MDASH', 'MDASH_PAIR', 'MINUS', 'NBSP', 'NDASH', 'NNBSP', 'RAQUO', 'RDQUO', 'RSQUO', 'SPRIME', 'THNSP', 'TIMES', 'WHSP', ) NBSP = '\u00A0' NNBSP = '\u202F' THNSP = '\u2009' WHS...
791
393
""" Wagtail Live models.""" from django.db import models from django.utils.timezone import now from wagtail.admin.edit_handlers import FieldPanel, StreamFieldPanel from wagtail.core.fields import StreamField from .blocks import LivePostBlock class LivePageMixin(models.Model): """A helper class for pages using W...
5,259
1,490
import numpy as np from inprod_analytic import * from params_maooam import natm, noc init_inprod() real_eps = 2.2204460492503131e-16 """This module print the coefficients computed in the inprod_analytic module""" for i in range(0, natm): for j in range(0, natm): if(abs(atmos.a[i, j]) >= real_eps): ...
2,291
998
from django.http import Http404, HttpResponse from django.shortcuts import redirect import boto3 from botocore.errorfactory import ClientError from ..models import PersonProxy def fallback(request): BUCKET_NAME = "legacy.openstates.org" key = request.path.lstrip("/") + "index.html" s3 = boto3.client("s3"...
849
268
import unittest from dhcppython import options class OptionListTestCases(unittest.TestCase): def gen_optionslist(self): return options.OptionList( [ options.options.short_value_to_object(61, {'hwtype': 1, 'hwaddr': "8c:45:00:1d:48:16"}), options.options.short_va...
12,534
4,657
"""Init file.""" from keras.legacy_tf_layers import migration_utils # pylint: disable=unused-import
102
35
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Codec: def serialize(self, root: TreeNode) -> str: """Encodes a tree to a single string. """ def DFSPreorder(root): ...
1,485
431
import os import sagemaker from sagemaker import get_execution_role from sagemaker.tensorflow.estimator import TensorFlow sagemaker_session = sagemaker.Session() # role = get_execution_role() region = sagemaker_session.boto_session.region_name training_input_path = "s3://intel-edge-poc/mask_dataset_datagen/train/" v...
1,038
398
import numpy as np import skimage import skimage.morphology as morph import skimage.filters as filt import skimage.exposure as expo def get_corrected_image(iimage, gamma=0.25): """Return filtered image to detect spots.""" image = skimage.util.img_as_float(iimage) image **= gamma return image
314
107
# coding: utf-8 """Test suite for our sysinfo utilities.""" # Copyright (c) yap_ipython Development Team. # Distributed under the terms of the Modified BSD License. import json import nose.tools as nt from yap_ipython.utils import sysinfo def test_json_getsysinfo(): """ test that it is easily jsonable and ...
398
129
from Pages.LoginPage import LoginPage def test_invalid_login(setup): login = LoginPage(setup) login.enter_username_false() login.enter_password_true() login.click_login() login.invalid_message_check() print("Correct Login Test Completed")
268
84
from pyimagesearch.shapedetector import ShapeDetector from pyimagesearch.colorlabeler import ColorLabeler import argparse import imutils import numpy as np import cv2 import argparse import imutils face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') if face_cascade.empty(): raise Exception("you...
2,040
863
#!/usr/bin/env python s = [n * (3 * n - 1) / 2 for n in range(0, 10000)] found = False i = 1900 while not found: i += 1 j = 1 while j < i: # actually, we cannot guarentee that j < i, the real condition would # be s[i] < 3 * j + 1, which is the distance of s[j] and s[j + 1]. But # t...
548
215
""" Module providing ML anonymization. This module contains methods for anonymizing ML model training data, so that when a model is retrained on the anonymized data, the model itself will also be considered anonymous. This may help exempt the model from different obligations and restrictions set out in data protection...
911
227
from qiskit import QuantumRegister,QuantumCircuit from qiskit.aqua.operators import StateFn from qiskit.aqua.operators import I from qiskit_code.quantumMethod import add,ini from qiskit_code.classicalMethod import Dec2Bi def DeutschJozsa(l,method): # Deutsch, D. and Jozsa, R., 1992. Rapid solution of problems b...
2,016
812
import requests import random, string x = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for _ in range(16)) URL = "http://localhost/" secret = "aA11111111" + x # Registering a user requests.post(url = "%s/add.php" % URL, data = { 'name': 'facebook' + ' '*64 + 'abc', 'secr...
480
188
import argparse import sys import traceback from .app import Application def new_excepthook(type, value, tb): # by default, Qt does not seem to output any errors, this prevents that traceback.print_exception(type, value, tb) sys.excepthook = new_excepthook def main(): parser = argparse.ArgumentParser...
737
241
from unittest import TestCase from exercicios.ex1030 import calcula_suicidio import random class TestEx1030(TestCase): def test_saida_com_erro_para_entradas_fora_do_intervalo(self): chamada = [(0, 10), (10, 0), (10001, 10), (10, 1001)] esperado = ("Case 1: entrada inválida\n" ...
848
347
# -*- coding: utf-8 -*- from json import load from logging import basicConfig from os.path import join, dirname from pathlib import Path ################################################################################ # CHECKING THE INPUT AND OUTPUT AND DIRECTORY PATH # INPUT with open(join(Path(dirname(__file__)).par...
656
171
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # Author: Lorand Cheng https://github.com/lorandcheng # Date: Nov 15, 2020 # Project: USC EE250 Final Project, Morse Code Translator and Messenger # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # import...
2,177
620
# -*- coding: utf-8 -*- import random from random_words import RandomWords from random_words import LoremIpsum from django.core.management.base import BaseCommand from app.models import Tag from app.models import Post class Command(BaseCommand): def __init__(self): super(Command, self).__init__() ...
1,637
479
import numpy as np import os class Dataset(): def __init__(self, images, labels): # convert from [0, 255] -> [0.0, 1.0] images = images.astype(np.float32) images = np.multiply(images, 1.0 / 255.0) self._images = images self._labels = labels @property # getter def ...
1,898
709
#!/usr/bin/env python """Waypoint Updater. This node will publish waypoints from the car's current position to some `x` distance ahead. As mentioned in the doc, you should ideally first implement a version which does not care about traffic lights or obstacles. Once you have created dbw_node, you will update this node...
6,764
2,206
# renames duplicate columns by suffixing _1, _2 etc class renamer(): def __init__(self): self.d = dict() def __call__(self, x): if x not in self.d: self.d[x] = 0 return x else: self.d[x] += 1 return "%s_%d" % (x, self.d[x])
305
107
''' sbc-ngs (c) University of Manchester 2019 All rights reserved. @author: neilswainston ''' # pylint: disable=no-member # pylint: disable=too-few-public-methods # pylint: disable=too-many-arguments # pylint: disable=too-many-instance-attributes # pylint: disable=unused-argument # pylint: disable=wrong-import-order ...
6,111
1,788
import argparse from time import sleep import requests import xmltodict # http://www.nationalrail.co.uk/100296.aspx # https://lite.realtime.nationalrail.co.uk/OpenLDBWS/ # http://zetcode.com/db/sqlitepythontutorial/ from utils.database import insert_into_db, delete_where, execute_sql xml_payload = """<?xml version=...
3,815
1,307
""" Problem 12 Highly divisible triangular number """ from utility.decorators import timeit, printit from utility.math_f import sum_naturals_to_n, get_divisors from math import ceil, sqrt def div_count(n): # Returns the count of divisors of a number total = 0 for i in range(1, int(ceil(sqrt(n)))+...
877
339
# uninhm # https://atcoder.jp/contests/abc183/tasks/abc183_d # data structures, sorting n, w = map(int, input().split()) needed = [] for _ in range(n): s, t, p = map(int, input().split()) needed.append((s, p)) needed.append((t, -p)) needed.sort() cum = 0 for i in range(len(needed)): cum += needed[i]...
469
192
#!/usr/bin/env python import os from slackclient import SlackClient def send(msg="no msg", rsp="ok"): channel = os.environ['SLACK_CHANNEL'] if "ok" == rsp: if 'SKIP_OK_MESSAGES' in os.environ and os.environ['SKIP_OK_MESSAGES']: return if 'SLACK_OK_CHANNEL' in os.environ and os.e...
635
239
#!/usr/bin/env python # Idea taken from www.wavepot.com import math from AudioPython import * from AudioPython.dsp import * def bass_osc(n): tri = triangle_wave(frequency=n, amplitude=0.24) sine = sine_wave(frequency=n*32, amplitude=0.052) while True: yield next(tri) + next(sine) def sub(gen, ...
678
289