text stringlengths 1 927k |
|---|
#!/usr/bin/python
import subprocess
import os
import sys
import re
import argparse
RE_LDD_LIB=re.compile(r"\s*(.+?)(?:\s=>\s(.+?))?\s\((0x[0-9A-Fa-f]+)\)")
RE_DPKG=re.compile(r"(.+?)(?::(.+?))?:\s()(.+?)")
DEFAULT_EXCLUDE=[
'linux-vdso.so',
'libc.so',
'libpthread.so',
'libdl.so',
'ld-linux-x86-6... |
import os
import sys
model_dirs_file = sys.argv[1]
example_cmd_file = sys.argv[2]
example_model = sys.argv[3]
out_file = sys.argv[4]
dirs = open(model_dirs_file).read().split('\n')
cmd = open(example_cmd_file).read()
str = ''
for dir in dirs:
new_cmd = cmd.replace(example_model, dir)
str += new_cmd + '\n'
... |
# Generated by Django 4.0 on 2021-12-17 12:11
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('Instructor', '0002_initial'),
]
operations = [
migrations.AlterField(
model_name='rubric',
name='name',
fie... |
from collections import defaultdict
from django.db.models import F
from promise import Promise
from ...checkout import CheckoutLineInfo
from ...checkout.models import Checkout, CheckoutLine
from ..core.dataloaders import DataLoader
from ..product.dataloaders import (
CollectionsByVariantIdLoader,
ProductByVar... |
# 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 the... |
# Generated by Django 3.1.1 on 2020-12-07 14:06
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('api', '0001_initial'),
... |
# -*- coding: utf-8 -*-
"""Webex Teams Webhooks API wrapper.
Copyright (c) 2016-2020 Cisco and/or its affiliates.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including wi... |
from django.conf.urls import *
urlpatterns = patterns('product.views',
(r'^(?P<parent_slugs>([-\w]+/)*)?(?P<slug>[-\w]+)/$',
'category_view', {}, 'satchmo_category'),
(r'^$', 'category_index', {}, 'satchmo_category_index'),
) |
from titlecase import titlecase
from django.conf import settings
from django.db.models import Q
from django.http import HttpResponse, HttpResponseBadRequest
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_page
from discovery.csv import get_memberships, get_membersh... |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: POGOProtos/Networking/Requests/Messages/DownloadRemoteConfigVersionMessage.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import m... |
from django.test import TestCase
from thumbs.fields import validate_size, split_original, determine_thumb, \
sting2tuple
from thumbs.fields import SizeError, OriginalError
import logging
logger = logging.getLogger(__name__)
try:
from PIL import Image, ImageOps
except ImportError:
import Image
import ... |
#
# This file is part of m.css.
#
# Copyright © 2017, 2018, 2019, 2020, 2021, 2022
# Vladimír Vondruš <mosra@centrum.cz>
#
# 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 Softwar... |
import pytest
import core.config
import modules.contrib.kernel
@pytest.fixture
def some_kernel():
return "this-is-my-kernel"
@pytest.fixture
def kernel_module():
return modules.contrib.kernel.Module(config=core.config.Config([]), theme=None)
def test_full_text(mocker, kernel_module):
platform = mocke... |
from __future__ import absolute_import
from __future__ import print_function
import sys
import os
# the next line can be removed after installation
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(
os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))))
from veriloggen import *
import ve... |
DOLLARS_TO_RUBLES = 65
EUROS_TO_RUBLES = 71
def predict_rub_salary(lower_salary, upper_salary, currency):
if lower_salary and upper_salary:
middle_salary = (lower_salary + upper_salary)/2
elif lower_salary:
middle_salary = lower_salary * 1.2
elif upper_salary:
middle_salary = upper... |
import asyncio
from dffml import train, accuracy, predict, Features, Feature
from dffml_model_scikit import LinearRegressionModel
async def main():
model = LinearRegressionModel(
features=Features(
Feature("Years", int, 1),
Feature("Expertise", int, 1),
Feature("Trust"... |
import jax.numpy as jnp
from prax import Oscillator
from jax.config import config; config.update("jax_enable_x64", True)
import matplotlib.pyplot as plt
class HodgkinHuxley(Oscillator):
def __init__(self, input_current, C=1.0, G_Na=120.0, G_K=36.0, G_L=0.3, E_Na=50.0, E_K=-77.0, E_L=-54.4, dt=0.01, eps=10**-5):
... |
"""
Dailymotion OAuth2 support.
This adds support for Dailymotion OAuth service. An application must
be registered first on dailymotion and the settings DAILYMOTION_CONSUMER_KEY
and DAILYMOTION_CONSUMER_SECRET must be defined with the corresponding
values.
User screen name is used to generate username.
By default ac... |
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from nltk import RegexpTokenizer
import re
def regex_clean_ruidos(text):
'''
função manual para eliminação de ruídos através de regex, descartar qualquer coisa
que na composição possua uma 'não letra', como símbolos e núme... |
import tornado.web
from app.domain.task_step import TaskStep
from app.service import token_service
from app.database import task_step_db
from app.utils import mytime
import json
class TaskStepApi(tornado.web.RequestHandler):
async def post(self, *args, **kwargs):
token = token_service.get_token(self.requ... |
'''
Project: Gui Gin Rummy
File name: info_messaging.py
Author: William Hale
Date created: 3/28/2020
'''
# from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from .game_canvas import GameCanvas
from typing import List
import rlcard.games.gin_rummy.utils.utils as... |
# -*- coding: utf-8 -*-
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='event',
name='logo_url',
field=models.CharField(defau... |
from samtranslator.public.sdk.resource import SamResourceType
from samtranslator.public.intrinsics import is_intrinsics
class Globals(object):
"""
Class to parse and process Globals section in SAM template. If a property is specified at Global section for
say Function, then this class will add it to each... |
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 1 18:09:27 2021
@author: lukas
"""
import cv2
import dlib
import numpy as np
import timeit
import utils
import queue
import multiprocessing
import pathlib
import argparse
import time
def _create_parser():
parser = argparse.ArgumentParser()
parser.add_argument(... |
"""
Copyright (C) 2018-2021 Intel Corporation
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 i... |
# Copyright 2018 Google LLC
#
# 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, s... |
import os, sys, inspect
import subprocess
from . import version
__version__ = version.get_current()
def get_current_dir_for_jupyter():
"""Get the current path for jupyter"""
return getCurrentDir(os.getcwd())
def get_current_dir(current_file):
"""Get the current path"""
current_dir = os.path.dirna... |
import logging
import time
import os
import torch
from utils.lr_scheduler import WarmupMultiStepLR
from net import Network
def create_logger(cfg):
dataset = cfg.DATASET.DATASET
net_type = cfg.BACKBONE.TYPE
module_type = cfg.MODULE.TYPE
log_dir = os.path.join(cfg.OUTPUT_DIR, cfg.NAME, "logs")
if n... |
'''
Learning How To Train Neural Networks in Parallel (The Right Way)
===
Author: Nicholas Geneva (MIT Liscense)
url: https://nicholasgeneva.com/blog/
github: https://github.com/NickGeneva/blog-code
===
'''
from abc import abstractmethod
class Distributed(object):
"""Parent class for distributed comm methods
... |
#Program to find the phone number of an employee
phone=dict()
i=1
n=int(input("Enter the no. of entries:"))
while i<=n:
a=input("Enter the phone number:")
b=input("Enter name:")
phone[b]=a
i=i+1
l=phone.keys()
x=input("Enter the name to be searched:")
for i in l:
if i==x:
print(x,"phone numb... |
#!/usr/bin/python
import simple_test
simple_test.test("test20", ["-a", "-b", ], expect_fail=True) |
#!/usr/bin/python3
# tm_splitter.py by Michael Henderson
# Split individual TM files from a bulk downloaded XML file containing an aggregation of TMs
# Write out a separate XML files and Solr ready XML file for each TM
import os
import re
import sys
import getopt
import xml.dom.minidom
def main(argv):
#de... |
# 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... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
import click
from flask.cli import FlaskGroup
from app import app, db
@click.group(cls=FlaskGroup, create_app=lambda: app)
def cli():
"""Management script for the flask application."""
@cli.command()
def init_db():
"""Creates database tables"""
db.create_all()
@cli.command()
def delete_db():
"""De... |
from django.contrib import admin
from models import UserFollow, UserProfile
class UserFollowAdmin(admin.ModelAdmin):
list_display=['user', 'followed_user']
class UserProfileAdmin(admin.ModelAdmin):
list_display=['user', 'location', 'url', 'profile_privacy']
admin.site.register(UserFollow, UserFollowAdmin)
a... |
#!/usr/bin/env python3
# Copyright (c) 2017 The Bitcoin Core developers
# Copyright (c) 2017-2018 The Marlin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test recovery from a crash during chainstate writing.
... |
# Generated by Django 3.1.3 on 2020-11-17 19:53
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('attendance', '0013_auto_20201115_1154'),
]
operations = [
migrations.AlterField(
model_name='case',
name='attorney',... |
"""
Make yaml respect OrderedDicts and stop sorting things
"""
from collections import OrderedDict
import sys
import yaml
_items = 'viewitems' if sys.version_info < (3,) else 'items'
def map_representer(dumper, data):
return dumper.represent_dict(getattr(data, _items)())
def map_constructor(loader, node): # ... |
from datetime import datetime, timedelta
import functools
import inspect
import re
from typing import Any, List
import warnings
import numpy as np
from pandas._libs import NaT, algos as libalgos, lib, tslib, writers
from pandas._libs.index import convert_scalar
import pandas._libs.internals as libinternals
from panda... |
# Copyright (C) 2019 The Raphielscape Company LLC.
#
# Licensed under the Raphielscape Public License, Version 1.d (the "License");
# you may not use this file except in compliance with the License.
#
""" Userbot module which contains afk-related commands """
import time
from datetime import datetime
from random impor... |
"""
Django settings for blog project.
Generated by 'django-admin startproject' using Django 2.1.5.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""
import os
# Bu... |
def extractMaynoveltranslationsCom(item):
'''
Parser for 'maynoveltranslations.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('president shen always top up money', 'president shen alw... |
ARCH_REGISTRY = dict()
def register_arch(cls):
ARCH_REGISTRY[cls.__name__] = cls
return cls
# explicitly import all models to register arch
from models import conv1d
__all__ = ["register_arch"] |
# -*- coding: utf-8 -*-
from flask import Blueprint
from flask_cors import CORS
# Flask Blueprint 정의
api = Blueprint('api', __name__)
CORS(api) # enable CORS on the API_v1.0 blueprint
from . import errors,transaction,authentication, news, users, search, stars |
# Copyright 2017 The TensorFlow 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 applica... |
from idunn.blocks.services_and_information import InternetAccessBlock
def test_internet_access_block():
internet_access_block = InternetAccessBlock.from_es({"properties": {"wifi": "no"}}, lang="en")
assert internet_access_block is None
def test_internet_access_block_ok():
internet_access_block = Interne... |
import adv_test
from adv import *
from slot.a import *
import slot.a
def module():
return Mikoto
class Mikoto(Adv):
a1 = ('cc', 0.10, 'hp70')
a3 = ('cc', 0.08)
def init(this):
if this.condition('connect s1'):
this.s1_proc = this.c_s1_proc
def prerun(this):
this.... |
# -*- coding: utf-8 -*-
#
# Copyright 2017 Ricequant, Inc
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... |
import os
strt = 'folder1/folder2/file3'
strt = 'folder1'
newl = strt.split('/')
print(newl)
'''
def list_files(startpath):
for root, dirs, files in os.walk(startpath):
level = root.replace(startpath, '').count(os.sep)
#print(level)
indent = ' ' * 4 * (level)
print('{}{}/'.format(i... |
import re
import sys
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import rcParams
from scipy.integrate import simps
from scipy.special import logsumexp
from scipy.optimize import minimize
# from sklearn.cluster import DBSCAN
# from sklearn.preprocessing import StandardScaler
import time
import ra... |
import abc
import tensorflow as tf
from railrl.core.neuralnet import NeuralNetwork
from rllab.misc.overrides import overrides
class StateActionNetwork(NeuralNetwork, metaclass=abc.ABCMeta):
"""
A map from (state, action) to a vector
"""
def __init__(
self,
name_or_scope,
... |
#1
first = int(input("Enter the value of the first number : "))
second = int(input("Enter the value of the second number : "))
#2
first = first + second
#3
second = first - second
#4
first = first - second
#5
print("After exchange, First number is : ",first," Second number is : ",second) |
from flask_restx import Namespace
ns_conf = Namespace('datasources', description='Data sources') |
# FORSETI - Feature extractor and classificator for ELF binaries
# Author: Lucas Galante
# Advisor: Marcus Botacin, Andre Gregio, Paulo de Geus
# 2019, UFPR, UNICAMP
import binaries # Object class for handling binaries
import ConfigParser # Configuration file for user
import dm # Data metrics... |
''' For loop
Used to iterate over a sequence.
Sequence is usually: (list,tuple, dictionary,set,string)
Does not require an indexing variable to initiate the loop.
I can use break abd continue statements.
'''
fruits = ["grapes", "berrys", ] |
import re
from .delta import Inf, d_expr_dimension
from .linear import Linear
from .lyndon import to_lyndon_basis
from .util import get_one_item
def word_expr_weight(expr):
return len(get_one_item(expr.items())[0])
def word_expr_max_char(expr):
return max([max(word) for word, _ in expr.items()])
def words_... |
# encoding: utf-8
"""A self maintained value stack."""
from __future__ import annotations
import dataclasses
import enum
import functools
import inspect
import sys
from copy import copy
from dis import Instruction
from types import FrameType
from typing import Optional
try:
from typing import TYPE_CHECKING, Lit... |
"""Play media via gstreamer."""
import logging
import voluptuous as vol
from homeassistant.components.media_player import (
MediaPlayerDevice, PLATFORM_SCHEMA)
from homeassistant.components.media_player.const import (
MEDIA_TYPE_MUSIC, SUPPORT_NEXT_TRACK, SUPPORT_PAUSE,
SUPPORT_PLAY, SUPPORT_PLAY_MEDIA, S... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-08-26 16:47
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('portal', '0008_auto_20170825_1249'),
]
operations = [
migrations.AddField(
... |
import os
import json
import shutil
import logging
from typing import Callable
class Config():
def __init__(self, configFile: str, log: logging.Logger):
""" init function of the Config class """
# set default values (None means that is has to be set)
self.configFile = configFile
self.log = log
s... |
# coding=utf8
# Copyright 2018 JDCLOUD.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 or agreed ... |
"""
Minimum Description Length Principle (MDLP) binning
- Original paper: http://sci2s.ugr.es/keel/pdf/algorithm/congreso/fayyad1993.pdf
- Implementation inspiration: https://www.ibm.com/support/knowledgecenter/it/SSLVMB_21.0.0/com.ibm.spss.statistics.help/alg_optimal-binning.htm
"""
import collections
import math
i... |
from sklearn.ensemble import AdaBoostClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.datasets import make_gaussian_quantiles
from sklearn.ensemble import RandomForestClassifier
def AdaBoost(X_train, y_train, X_test, DEPTH, N_ESTIMATORS):
# Create and fit an AdaBoosted decision tree
bdt = AdaB... |
#!/Users/alberthan/VSCodeProjects/hdlogger/bin/python3
# Author:
# Contact: grubert@users.sf.net
# Copyright: This module has been placed in the public domain.
"""
man.py
======
This module provides a simple command line interface that uses the
man page writer to output from ReStructuredText source.
"""
import loc... |
model_name= 'cv_biobert_lstm_ft'
import sys
sys.path.append('../')
import os
import tensorflow
import numpy as np
import random
seed_value = 123123
#seed_value = None
environment_name = sys.executable.split('/')[-3]
print('Environment:', environment_name)
os.environ[environment_name] = str(seed_value)
np.random.... |
from twilio.rest import Client
account = "ACeec37d10088b2826aa81746d709c57e3"
token = "e84982e1d3e37a080664f749f1027c0a"
client = Client(account, token)
def send_sms(number, body):
message = client.messages.create(to="+14383996776", from_="+1 778 654 6641",
body=body)
return m... |
from .units import Quantity, units
from .common import (
invert_dict,
CP_symbUpper_to_units,
preferred_units_from_type,
preferred_units_from_symbol,
)
from .realfluid import Properties as rfprop
from .plotting import PropertyPlot, plt
import CoolProp
from CoolProp.CoolProp import HAPropsSI,set_reference... |
from datetime import datetime as dt
from django.contrib.auth import get_user_model
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
from django.utils.translation import gettext_lazy as _
User = get_user_model()
"""
MAX_YEARS_TITLES: this value indicates which year ... |
#!/usr/bin/env python3
#
# Functions to generate basic documentation in HTML and LaTeX for CCPP metadata
#
# DH* TODO: create a Python module metadata.py with a class Metadata
# and use this for ccpp_prebuild.py; create to_html and to_latex routines for it
import logging
import os
from common import decode_containe... |
import pygame
_debugkeys_ = {
pygame.K_1: "wallClimb", pygame.K_2: "multiJump",
pygame.K_3: "highJump", pygame.K_4: "featherFalling",
pygame.K_5: "gravity", pygame.K_6: "hover",
pygame.K_7: "stickyCeil", pygame.K_8: "invertedGravity",
pygame.K_9: "permBodies", pygame.K_q: "solidH... |
# ********JOSEPHUS SURVIVOR********
#codewars
# In this kata you have to correctly return who is the "survivor", ie: the last element of a Josephus permutation.
# Basically you have to assume that n people are put into a circle and that they are eliminated in steps of k elements, like this:
# josephus_survivor(7,3)... |
#!/usr/bin/env python
# coding=utf-8
import tensorflow as tf
import os
import numpy as np
import argparse
import shutil
from tensorflow.examples.tutorials.mnist import input_data
parser = argparse.ArgumentParser('MNIST Softmax')
parser.add_argument('--data_dir', type=str, default='/tmp/mnist-data',
... |
import json
import pytest
from conftest import CI_ENV
@pytest.mark.skipif(CI_ENV, reason="avoid issuing HTTP requests on CI")
def test_user_tweets(api_client):
expected_keys = ['created_at', 'score_bert', 'score_lr', 'score_nb', 'status_id', 'status_text']
response = api_client.get('/api/v1/user_tweets/ber... |
import _plotly_utils.basevalidators
class ViolinValidator(_plotly_utils.basevalidators.CompoundValidator):
def __init__(self, plotly_name="violin", parent_name="", **kwargs):
super(ViolinValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
data_c... |
from dataclasses import dataclass
from boltons.cacheutils import cachedproperty
from boltons.strutils import split_punct_ws
from cltkv1.core.data_types import Process
from cltkv1.stops.words import Stops
@dataclass
class StopsProcess(Process):
"""
>>> from cltkv1.core.data_types import Doc, Word
>>> fr... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for `http_pipeline` package."""
import pytest
from http_pipeline import http_pipeline
@pytest.fixture
def response():
"""Sample pytest fixture.
See more at: http://doc.pytest.org/en/latest/fixture.html
"""
# import requests
# return reque... |
from __future__ import annotations
from abc import ABC, abstractmethod
import numpy as np
from numba import njit
@njit(cache=True)
def _clip(a: np.ndarray, epsilon: float) -> np.ndarray:
if ((a == 1) | (a <= 0)).any():
a = np.maximum(a, epsilon).astype(np.float32)
a = np.minimum(1 - epsilon, a).... |
import copy
class My_matrix:
def __init__(self, matrix):
self.matrix = matrix
def __str__(self):
out = f'{self.matrix_size}\n'
for row in self.matrix:
out += str(row) + '\n'
return out
def null_matrix(self):
return [[0 for i in self.range_row()] for j ... |
#!/usr/bin/env python
# Copyright 2002 Google Inc. All Rights Reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of c... |
"""Test the arraymodule.
Roger E. Masse
"""
import unittest
from test import support
from test.support import _2G, os_helper
import weakref
import pickle
import operator
import struct
import sys
import warnings
import array
from array import _array_reconstructor as array_reconstructor
sizeof_wchar = array.array('... |
import pygame
from pygameSettings import afficher_text
class Screen:
WAITING = 'waiting'
PROLOGUE = 'prologue'
MAIN = 'main'
sprites = pygame.sprite.Group()
on_screen = {}
def __init__(self) -> None:
"""Initialisation classe Screen pour gerer l'affichage
Arguments : screen ... |
"""
Given an array A[] of N positive integers.
The task is to find the maximum of j - i subjected to the constraint of A[i] <= A[j].
Example 1:
Input:
N = 2
A[] = {1, 10}
Output:
1
Explanation:
A[0]<=A[1] so (j-i) is 1-0 = 1.
Example 2:
Input:
N = 9
A[] = {34, 8, 10, 3, 2, 80, 30, 33, 1}
Output:
6
Explanation:
In t... |
# Copyright (c) James Percent, Byron Galbraith and Unlock contributors.
# All rights reserved.
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notic... |
from ktane.directors import BombSolver, from_pool
from ktane.mods.c import ColourFlash
from ktane.vanilla import (ComplicatedWires, Memory, WhosOnFirst, WireSequence,
Password, Wires, TheButton, Keypad)
BombSolver(
ColourFlash(),
ComplicatedWires(),
*from_pool(Memory, WhosOnFirst... |
import numpy as np
def ema(self, N):
"""
Simple Moving Average = (N - PeriodSum) / N
N = number of days in a given period
PeriodSum = sum of stock closing prices in that period
"""
name = 'ema_' + str(N)
dependent = 'sma_' + str(N)
try:
return self.data[name][self.index]
... |
# flake8: noqa: F811, F401
import asyncio
import atexit
import logging
from secrets import token_bytes
from typing import List, Optional
import pytest
from lotus.consensus.blockchain import ReceiveBlockResult
from lotus.consensus.multiprocess_validation import PreValidationResult
from lotus.consensus.pot_iterations i... |
"""
Build a dictionary from a key/map regex group expression
"""
from openpipe.pipeline.engine import ActionRuntime
from re import compile, MULTILINE
class Action(ActionRuntime):
category = "Data Transformation"
required_config = """
regex: # A regex expression that must match two groups:
... |
#!/usr/bin/python3
##############
# Load input #
##############
def load_input():
incomplete_steps = set() # incomplete steps, initalized to all steps
requirements = dict() # map steps to the required steps that must be completed first
with open("input.txt", "r") as f:
for line in f:
... |
#from fastai.text import *
from .core import *
class NERModel(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.use_elmo = config.use_elmo
if not self.use_elmo:
self.emb = nn.Embedding(self.config.nwords, self.config.dim_word, padding... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import itertools
from collections import defaultdict
from json import dumps as json_dumps
from typing import (
Any,
DefaultDict,
Dict,
List,
NamedTuple,
Optional,
Sequence,
Tuple,
Union,
)
... |
# coding: utf-8
#
# Copyright 2014 The Oppia 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 requi... |
import sys, os, BaseHTTPServer
#-------------------------------------------------------------------------------
class ServerException(Exception):
'''For internal error reporting.'''
pass
#-------------------------------------------------------------------------------
class case_no_file(object):
'''File ... |
# Copyright 2017 The TensorFlow 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 applica... |
from indy_common.constants import NYM, NODE, ATTRIB, SCHEMA, CLAIM_DEF, DISCLO, GET_ATTR, GET_NYM, GET_TXNS, \
GET_SCHEMA, GET_CLAIM_DEF, POOL_UPGRADE, NODE_UPGRADE, \
POOL_CONFIG, REVOC_REG_DEF, REVOC_REG_ENTRY, \
GET_REVOC_REG_DEF, GET_REVOC_REG, GET_REVOC_REG_DELTA, POOL_RESTART, VALIDATOR_INFO, CHANGE_K... |
import pytest
from isr.datasets.transforms import ChannelSelect
@pytest.mark.parametrize("channel_idx", [0, 1, 2])
def test_channel_select(pil_img, channel_idx: int):
transform = ChannelSelect(channel_idx)
channels = pil_img.split()
output = transform(pil_img)
assert output.mode == "L"
assert c... |
import sys
offset = "\t\t"
woms_keys = {
"title": "title",
"composer": "composer",
"mm_uid": "mm-uid"
}
def assert_and_report(element, one, another):
print(f"{offset} asserting that {element} is {one} ...")
try:
assert one == another
print(f"{offset}\u2713 {one} is {element}!")
... |
print("--- ADICIONANDO ELEMENTOS EM UM ARRAY ---")
def main():
registro = []
while True:
valores = str(input("Digite algo para adcionar a lista: "))
registro.append(valores)
condição = str(input("Deseja continuar? [S/N] ")).strip().upper()[0]
if condição in 'N':
bre... |
import numpy as np
class Quaternions:
"""
Quaternions is a wrapper around a numpy ndarray
that allows it to act as if it were an narray of
a quaternion data type.
Therefore addition, subtraction, multiplication,
division, negation, absolute, are all defined
in terms of quaternion opera... |
from datetime import datetime
import click
from pornhub.core import get_session
from pornhub.extractors import download_channel_videos, get_channel_info
from pornhub.models import Channel
@click.command(name="channel")
@click.argument("name")
def get_channel(name: str) -> None:
"""Download a specific channel.
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.