content stringlengths 5 1.05M |
|---|
from io import BytesIO
from buidl.op import (
decode_num,
encode_num,
op_checklocktimeverify,
op_checkmultisig,
op_checksequenceverify,
op_checksig,
op_hash160,
)
from buidl.script import Script
from buidl.timelock import Locktime, Sequence
from buidl.tx import Tx, TxIn, TxOut
from buidl.t... |
#!/usr/bin/env python3
from ctf_gameserver import checkerlib
class TestChecker(checkerlib.BaseChecker):
def place_flag(self, tick):
if checkerlib.load_state('key2') is not None:
raise Exception('Got state where there should be none')
if tick == 0:
if checkerlib.load_stat... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2016-10-13 23:11
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('picture', '0007_auto_20161013_2250'),
]
operations = [
migrations.RenameField(
... |
from check_if_valid_url import *
from selenium import webdriver
def str_to_py_code(get_input_str:str):
"""Converts the given string starting with `^` to Python code \n
Every char more than one `^` counts one indent up
"""
if get_input_str.startswith('^'):
count = get_input_str.count('^')
... |
import pandas as pd
import os
from statistics import mean
from sklearn.model_selection import train_test_split
from heartpredictions.LogisticRegression import *
from heartpredictions.Tree.DecisionTree import DecisionTree
from heartpredictions.Tree.RandomForest import RandomForest
from heartpredictions.Tree.utils impo... |
from django.contrib import admin
import billing.models as billing_models
admin.site.register(billing_models.GCNewOrderNotification)
admin.site.register(billing_models.AuthorizeAIMResponse)
admin.site.register(billing_models.WorldPayResponse)
admin.site.register(billing_models.AmazonFPSResponse)
class PaylaneTransact... |
"""
Napisać program, który wczytuje wprowadzany z klawiatury ciąg liczb naturalnych zakończonych zerem
stanowiącym wyłącznie znacznik końca danych. Program powinien wypisać 10 co do wielkości wartość,
jaka wystąpiła w ciągu. Można założyć, że w ciągu znajduje się wystarczająca liczba elementów.
"""
def value_sequence... |
import webbrowser
import os
gitinit = input("git init? [y]es / [n]o: ")
if gitinit.lower() == 'y':
# gitinit
print("\ninitialized git repo")
os.system("git init")
# open browser to create repo
print("create remote Github repo")
webbrowser.open('https://github.com/new', new=2)
# add remote
remote = input("en... |
__version__ = '2.8.1'
# Links to documentation to use over the project sources
DOCS_LINK = "https://shub.readthedocs.io/en/stable/"
DEPLOY_DOCS_LINK = DOCS_LINK + "deploying.html#deploying-dependencies"
CONFIG_DOCS_LINK = DOCS_LINK + "configuration.html"
|
import pandas as pd
import nltk
# nltk.download("stopwords")
from nltk.corpus import stopwords
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import train_test_split
from sklearn import naive_bayes
import numpy as np
df = pd.read_csv("./datasets/d04_sentimentAnalysis.csv", nam... |
from spotify_dl.models import Song
from peewee import DoesNotExist
from spotify_dl.scaffold import log
def check_if_in_cache(search_term):
"""
Checks if the specified search term is in the local database cache.
and returns the video id if it exists.
:param search_term: String to be searched f... |
# Technical validation - Controls
import pandas as pd
# Read .xlsx files
pos_ctls = pd.read_excel("data_records/Data Record 1 - Positive Controls.xlsx")
neg_ctls = pd.read_excel("data_records/Data Record 2 - Negative Controls.xlsx")
# Random control selection
pos_sample = pos_ctls.sample(n=40, random_state=... |
"""
Run DCRNN and NRI with extracted/learned graph on the Elergone dataset.
The underlying graph is generated by using correntropy in the DCRNN case, while it is learned by the NRI model.
"""
import os
import copy
import pytorch_lightning as pl
from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint
f... |
# coding=utf-8
"""
Copyright (c) 2018-present, Ant Financial Service 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
Un... |
import os
from dask.distributed import Nanny
from distributed.system import MEMORY_LIMIT
from .initialize import initialize
from .local_cuda_cluster import cuda_visible_devices
from .utils import CPUAffinity, get_cpu_affinity, get_gpu_count
def worker_spec(
interface=None,
protocol=None,
dashboard_addre... |
from shiva.resources.base import ArtistResource, AlbumResource, TrackResource
from shiva.resources.static import AboutResource, ClientResource
from shiva.resources.dynamic import (ConvertResource, LyricsResource,
RandomResource, ShowsResource,
Wh... |
from explainable_cnn.explainers import *
|
from ppf_date_time import weekdays
def is_business_day(t, financial_centers=None):
''' Test whether the given date is a business day.
In this version, only weekends are considered
holidays.
>>> from ppf_date_time import date
>>> from ppf_date_time import months_of_year
>>> Jun = mont... |
from setuptools import setup, find_packages
import os
# extract version
with open(os.path.join(os.path.dirname(__file__),
"fides", "version.py")) as f:
version = f.read().split('\n')[0].split('=')[-1].strip(' ').strip('"')
# read a file
def read(fname):
return open(os.path.join(os.path.dirname(__f... |
#!/usr/bin/env python
""" for documentation in index.rst """
import asyncio
import logging
import sys
from pathlib import Path
from mode import Worker
sys.path.insert(0, str(Path(__file__).parent / "munggoggo"))
from behaviour import Behaviour
from core import Core
logging.getLogger("aio_pika").setLevel(logging.WA... |
import json
import os
from flask import Flask
from flask import request
from aog import conv
from flask import make_response
# Flask app should start in global layout
app = Flask(__name__)
@app.route('/', methods=['POST'])
def fullfillment():
req = request.get_json(silent=True, force=True)
print("Reques... |
# This file will contain the shiprocket api communication constants
AUTHENTICATION_API = "https://apiv2.shiprocket.in/v1/external/auth/login"
AUTHENTICATION_HEADER_NAME = "Authorization"
AUTHENTICATION_TOKEN_PREFIX = "Bearer"
COURIER_SERVICEABILITY_URL = "https://apiv2.shiprocket.in/v1/external/courier/serviceability... |
initialDrinkList = [
{'key': 'rum', 'name': 'Rum', 'img': 'JoeTheBarman/images/rum.jpg'},
{'key': 'gin', 'name': 'Gin Tonic', 'img': 'JoeTheBarman/images/gin.jpg'},
{'key': 'tequila', 'name': 'Flaming Tequila', 'img': 'JoeTheBarman/images/tequila.jpg'},
{'key': 'soda', 'name': 'Soda', 'img': 'JoeTheBarm... |
import pandas as pd
import os
import re
column_names = ["Name", "RandomForest", "MLPClassifier", "DTExtract", "DTExtract Relative", "DTTrained", "CORELS", "CORELSRELRF", "CORELRELMLP", "sklearn-expertsys", "sklearn-expertsys-relrf", "sklearn-expertsys-relmlp"]
def readlogs():
df = pd.DataFrame(columns=column_name... |
# -*- coding: utf-8 -*-
"""
------------------------------------------------
util.rest.modules.__init__
------------------------------------------------
Author: Tony Ben (email: nanjinghhu@vip.qq.com)
Create: 11/29/2021
------------------------------------------------
ChangeLog
----------------------------... |
""" To start the tests, type from CLI: python test_solution_sum_of_missing_numbers.py """
import unittest
from solution_roman_numerals_helper import RomanNumerals
class TestSolution(unittest.TestCase):
def test_to_roman(self):
self.assertEqual(RomanNumerals.to_roman(1000), 'M')
self.assertEqual... |
import json
Settings = json.load(open('../settings.txt'))
import matplotlib.pyplot as plt
import numpy as np
from os.path import join
from cselect import color as cs
import sys
sys.path.insert(0,'../')
sys.path.insert(0,'../samples')
from mvpose.data import shelf
from time import time
root = Settings['data_root']
root... |
import copy
import os.path
import pandas as pd
from scipy import interpolate
import numpy as np
# from datetime import datetime # , date, time
import datetime
import matplotlib.pyplot as plt
class PandasTools:
def __init__(self):
raise RuntimeError('')
@staticmethod
def convert_index_from_us_to... |
''' Encontre todos os números promos de 2 até n'''
'''Pegar o ultimo numeros e tirar sua raiz arredondando para baixo'''
'''
raiz = 10 ** (1/2)
print(raiz)
# vai dar um número 3.1623.1622776601683795'''
'''
from math import floor
raiz = floor(10 ** (1/2))
print(raiz)
# vai dar um número 3'''
# colocando em codigo
fro... |
import requests
import uuid
from bs4 import BeautifulSoup
# get all the svgs from a page and save them as individual files
def get_page_svgs(url):
page = requests.get(url)
soup = BeautifulSoup(page.content, 'html.parser')
info = {"url": page.url.replace("?ref=producthunt", ""), "title": soup.find("title")... |
# -*- coding: utf-8 -*-
from datetime import datetime
from time import sleep
import pytest
from mock import Mock
import beer_garden.metrics as metrics
@pytest.fixture
def prometheus_mocks(monkeypatch):
# TODO - Test http api latency
# monkeypatch.setattr(metrics, "http_api_latency_total", Mock())
monkey... |
try:
import unzip_requirements
except ImportError:
pass
import os
import json
import time
import boto3
import tensorflow as tf
import census_data
import logging
logger = logging.getLogger()
logger.setLevel(logging.WARNING)
FILE_DIR = '/tmp/'
BUCKET = os.environ['BUCKET']
def uploadHandler(event, context):
... |
while 1:
(a,b) = map(int,raw_input().split())
if a==0 and b==0 : break;
print min(a,b),max(a,b)
|
__version__ = '0.1.0'
# import engine module
import sirf.Gadgetron as pMR
import sirf.Reg as pReg
# import further modules
import numpy as np
import matplotlib.pyplot as plt
import sys
from ccpi.optimisation.functions import LeastSquares, L2NormSquared, ZeroFunction, \
Indicator... |
# Face Detection Example
#
# This example shows off the built-in face detection feature of the OpenMV Cam.
#
# Face detection works by using the Haar Cascade feature detector on an image. A
# Haar Cascade is a series of simple area contrasts checks. For the built-in
# frontalface detector there are 25 stages of checks ... |
import pytest
import multio
def pytest_addoption(parser):
parser.addoption(
"--async", action="store", default="trio", help="asynclib: trio or curio"
)
@pytest.fixture
def asynclib(request):
libstr = request.config.getoption("--async")
multio.init(libstr)
return multio.asynclib
|
import os
from cs50 import SQL
from flask import Flask, flash, jsonify, 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, ge... |
import MeCab
mecab = MeCab.Tagger()
# python3-mecabのバグ回避のため,空文字をparse
mecab.parse('')
# 標準入力からテキストを受け取る
text = input(">")
node = mecab.parseToNode(text)
while node:
print(node.surface, node.feature)
node = node.next
|
import os
import random
import tensorflow as tf
from common.network_helpers import save_network, load_network
def train_supervised(game_spec, create_network, network_file_path,
positions,
test_set_ratio=0.4,
regularization_coefficent=1e-5,
... |
# Copyright 2020 Makani Technologies 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... |
from scipy import stats
import numpy as np
from neupy import layers
from neupy.exceptions import LayerConnectionError
from base import BaseTestCase
class DropoutLayerTestCase(BaseTestCase):
def test_dropout_layer(self):
test_input = np.ones((50, 20))
dropout_layer = layers.Dropout(proba=0.5)
... |
import os
from solr import SolrConnection
from django.db.models import signals
from django.conf import settings
from evidence.models import *
def update_index(sender, instance, created, **kwargs):
if isinstance(instance, MedicineEvidenceSummary):
#print "Atualizando desde o medicamento"
evidence ... |
#!/usr/bin/env python
"""
@author: Jordan Graesser
Date Created: 9/24/2011
"""
from __future__ import division
from future.utils import viewitems
from builtins import int
import os
import sys
import shutil
import time
import argparse
import subprocess
import ast
import copy
import fnmatch
# import atexit
import tar... |
n1 = int(input('Qual o primeiro numero?'))
n2 = int(input('Qual o segundo numero?'))
n3 = n1+n2
print('O resultado da soma dos dois numeros é:', n3)
print('O resultado é {}'.format(n3))
print('A soma entre {} e {} é {}'.format(n1, n2, n3))
print('A soma vale {}'.format(n1+n2))
|
#!/usr/bin/env python
import argparse
import glob
import os
import shutil
import codecs
import pathlib
import subprocess
################################################################
# String Data for clarity
################################################################
description = 'Helper script for managing... |
# -*- coding: UTF-8 -*-
from vulkan import *
from PySide2 import (QtGui, QtCore)
class HelloTriangleApplication(QtGui.QWindow):
def __init__(self):
super(HelloTriangleApplication, self).__init__()
self.setWidth(1280)
self.setHeight(720)
self.setTitle("Vulkan Python - PySide2")
... |
import argparse
import logging
import json
from abc import abstractmethod
from typing import List, Optional
import sciencebeam_trainer_delft.utils.no_warn_if_disabled # noqa, pylint: disable=unused-import
import sciencebeam_trainer_delft.utils.no_keras_backend_message # noqa, pylint: disable=unused-import
# pylint: ... |
import numpy as np
import pytest
# ~~!~~ TESTS ~~!~~
def test_rime_equation(n_time, n_chan, n_dir, load_data):
(tbin_indices, tbin_counts, ant1, ant2,
clean_vis, _, model, weight, jones) = load_data
for t in range(n_time):
start = tbin_indices[t]
end = tbin_indices[t] + tbin... |
from random import *
def CriarLista():
NumRandom=randint(1,10)
Array = [0,0,0,0]
ArrayReserva=[]
inx=0
iny=0
Loop=False
while (len(Array) > inx):
NumRandom = randint(1, 10)
Array[inx] = NumRandom
for n in Array:
if Array[inx] == n:
print(str(n) + " " + str(Array[inx]))
... |
#
# Copyright Cloudlab URV 2020
#
# 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 writin... |
#!/usr/bin/env python
from itertools import product
from random import randint
from sys import modules
from typing import Any, Callable, List
try:
from matplotlib import pyplot
except:
pass
class Card(object):
"""A playing card.
Arguments:
suit: str
The suit of the card
... |
import numpy as np
import networkx as nx
import gzip
import json
from datetime import datetime
from .errors import *
class AdaptiveVoter(object):
"""
Simulation class for the Adaptive Voter Model.
"""
__version__ = 0.1
def __init__(self, prebuilt=False, **kwargs):
"""
Input:
kap (int/float): Node... |
import os
import datetime as dt
import matplotlib.pyplot as plt
IMG_DIRECTORY = "./imgs" # "/Volumes/LaCie/final_imgs_hproblem" # # "/Volumes/LaCie/final_imgs_hproblem" #
STYLES_DIRECTORY = "./src/mpl_styles"
def initialization_mpl(stylesheet_name="latex_ready"):
plt.style.use(os.path.join(STYLES_DIRECTORY, sty... |
from parse import parse
import os
def clear_images(path:str, dryrun: bool = True, prod:str = 'SSM1km'):
# clean up input data before reshuffling, this removes duplicate images.
# dryrun means that no files in path will be deleted.
if prod.startswith('SWI'):
sens = 'SCATSAR'
else:
sens... |
import interface
class Itbit(interface.MarketExplorer):
def __init__(self):
pass
def exchange_name(self):
return 'itbit'
def markets(self):
return ['btc/usd', 'btc/sgd', 'btc/eur']
|
# Copyright (C) 2020 University of Oxford
#
# 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 t... |
import cv2
def extractLipsHaarCascade(haarDetector, frame):
"""Function to extract lips from a frame"""
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
roi_gray = 0
status = False
faces = haarDetector.detectMultiScale(gray, 1.3, 5)
if len(faces) == 0:
roi_gray = cv2.resize(gray, (150, 1... |
from pynput import keyboard
import time
def on_press(key):
try:
print('alphanumeric key {0} pressed'.format(
key.char))
except AttributeError:
print('special key {0} pressed'.format(
key))
def on_release(key):
print('{0} released'.format(
key))
if key == keyboard.Key.esc:
# Stop listener
return Fa... |
# coding: utf8
from threading import Timer
import redis
from common.mylog import logger
CONN_CHECK_INTERVAL = 60 # 连接检测间隔(秒)
from myutil.config_tool import get_redis_conf
class RedisHelper(object):
rcfg_2_pool = {}
def __init__(self, r_cfg=None, w_cfg=None):
self.read_cfg = r_cfg
self.w... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) The Swiboe development team. All rights reserved.
# Licensed under the Apache License, Version 2.0. See LICENSE.txt
# in the project root for license information.
from ctypes import byref, c_char_p
import argparse
import json
import os
import subprocess
imp... |
# Advent of Code Day 4
import re
def byr(pp_dict):
return 1900 <= int(pp_dict['byr']) <= 2002
def iyr(pp_dict):
return 2010 <= int(pp_dict['iyr']) <= 2020
def eyr(pp_dict):
return 2020 <= int(pp_dict['eyr']) <= 2030
def hgt(pp_dict):
val = pp_dict['hgt']
if val.endswith('cm'):
return ... |
#!/usr/bin/env python
def encode(string):
print 'Encoding string {}'.format(string)
# Replace backslashes
string = string.replace('\\', '\\\\')
print ' Replace \\: {}'.format(string)
# Replace quotes
string = string.replace('"', '\\"')
print ' Replace ": {}'.format(string)
# Add quotes
string = ... |
import heapq
import math
import numpy as np
import gurobipy as grb
from gurobipy import GRB
from uam_simulator.my_utils import get_trajectory_circle_intersection
# For details about the implementation of a priority queue in python see # https://docs.python.org/2/library/heapq.html
class PriorityQueue:
def __init_... |
# -*- coding: utf-8 -*-
# *****************************************************************************
# NICOS, the Networked Instrument Control System of the MLZ
# Copyright (c) 2009-2021 by the NICOS contributors (see AUTHORS)
#
# This program is free software; you can redistribute it and/or modify it under
# the t... |
import random
import numpy as np
from srl.base.env.base import EnvRun
def rescaling(x, eps=0.001):
return np.sign(x) * (np.sqrt(np.abs(x) + 1.0) - 1.0) + eps * x
def inverse_rescaling(x, eps=0.001):
n = np.sqrt(1.0 + 4.0 * eps * (np.abs(x) + 1.0 + eps)) - 1.0
n = n / (2.0 * eps)
return np.sign(x) *... |
import os
import logging
from pathlib import Path
from functools import reduce, partial
from operator import getitem
from datetime import datetime
from sklearn.utils.fixes import loguniform
from sklearn.experimental import enable_halving_search_cv # noqa
from utils.utils import read_json, write_json
class ConfigPars... |
default_app_config = 'kn_defaults.logging.apps.KnDefault'
|
from math import sqrt, atan2
class Vector2D:
def __init__(self, x=0, y=0):
self.point = [float(x), float(y)]
def __hash__(self):
return hash(tuple(self.point))
def __str__(self):
return str(self.point)
def __repr__(self):
return str(self.point)
def __eq__(self, ... |
class Solution:
def __init__(self):
self._id = set()
self.bxr = set()
self.all_info = dict()
def findJudge(self, N: 'int', trust: 'List[List[int]]') -> 'int':
if not trust:
return 1
for tmp in trust:
a, b = tmp
if self.all_info.get(... |
#! /usr/bin/env python3
import sys, os, os.path as op
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import numpy as np
import cv2
import argparse
import progressbar
import logging
import imageio
from lib.backend import backendMedia
def subtractMask_parser():
parser = argparse.Argum... |
import tensorflow as tf
def main(unused_argv):
pass
if __name__ == '__main__':
tf.app.run()
|
from random import uniform
class Personagem:
def __init__(
self, nome, vida, p_ataque, p_defesa
): # definir características dos personagens
self.nome = nome
self.vida = vida
self.p_ataque = p_ataque
self.p_defesa = p_defesa
self.vivo = True
def carac(self... |
# -*- coding: utf-8 -*-
"""
The same code as word2vec.py, but different input data and only two models instead four.
Competition: HomeDepot Search Relevance
Author: Kostia Omelianchuk
Team: Turing test
"""
from config_IgorKostia import *
import gensim
import logging
import numpy as np
from sklearn.ensemble import ... |
from .models import Thread
def user_messages(request):
context = {}
if request.user.is_authenticated:
context["inbox_threads"] = Thread.thread_objects.of_user(request.user).inbox()
context["unread_threads"] = Thread.thread_objects.of_user(request.user).unread()
return context
|
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import View, ListView
from blog.models import Post
class FavoriteList(LoginRequiredMixin, View):
template_name = 'post/favorite-list.html'
def get... |
# python3
import random
# Rabin Karp's Algorithms
def poly_hash(text, begin, length, a, p, ap, last=None):
'''
h(a, p) = sum(text[begin + length - 1] * a ^ (length - 1),
text[begin + length - 2] * a ^ (length - 2), ..., text[begin])
'''
ret = 0
if not last:
for i in range(begin + leng... |
# -*- coding: utf-8 -*-
"""
Pygments regex lexer tests
~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: Copyright 2006-2012 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import unittest
from pygments.token import Text
from pygments.lexer import RegexLexer
class TestLexer(Rege... |
class Solution(object):
def XXX(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
i = 0
j = len(nums) - 1
if j < 1:
return []
sortednums = nums[:]
sortednums.sort()
while sortedn... |
import GenConfig
import time
import RPi.GPIO as GPIO
class Motor:
def __init__(self, max_speed, step_pin, dir_pin, motor_index):
self.__max_speed = max_speed
self.motor_index = motor_index
self.step_pin = step_pin
self.dir_pin = dir_pin
GPIO.setup(step_pin, GPIO.OUT)
... |
import os
import sys
from time import sleep
from django.core.management import BaseCommand
sys.path.append("..")
from app.anacreon.models import GameData
from lib.anacreonlib.anacreon import Anacreon
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument(
'-i', '--i... |
try:
from ConfigParser import SafeConfigParser as ConfigParser
except ImportError:
from configparser import ConfigParser
from unittest import TestCase
from rapid.lib.configuration import ConfigurationDefaults, Configuration
class TestConfigurationDefaults(TestCase):
def test_defaults_are_set_to_defaults... |
import unittest
import numpy as np
from .kpinunu import *
import flavio
constraints = flavio.default_parameters
wc_obj = flavio.WilsonCoefficients()
constraints_no_deltaPcu = constraints.copy()
constraints_no_deltaPcu.set_constraint('deltaPcu', 0)
class TestKpinunu(unittest.TestCase):
# check that the known SM va... |
__author__ = 'shikun'
from testDAL import adbCommon
def attached_devices():
return adbCommon.AndroidDebugBridge().attached_devices()
def open_app(package_name, activity):
return adbCommon.AndroidDebugBridge().open_app(package_name, activity)
|
# This file is not directly used from Perforce, but it is the
# script on the Perforce daemon that is responsible for updating & executing
# the second-level bootstrap script, in bootstrap.py.
import os
import subprocess
import sys
SECOND_STAGE_WORKSPACE = 'perforce-admin-tools'
SECOND_STAGE_RELATIVE_PATH = ("tools",... |
# https://www.hackerrank.com/challenges/bigger-is-greater
def bigger_is_greater(string):
s = list(string)
if len(set(s)) == 1:
return 'no answer'
else:
last = s[-1]
for i, c in reversed(list(enumerate(s))):
if c > last:
last = c
elif c < last... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.9 on 2018-03-20 18:02
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('cmdb', '0001_initial'),
]
oper... |
#!/usr/bin/env python
"""A utility tool for extracting the identifier tokens from existing .jsonl.gz data. Primarily used for exporting
data for MSR's tool for dataset deduplication at https://github.com/Microsoft/near-duplicate-code-detector.
Usage:
jsonl2iddata.py [options] INPUT_PATH OUTPUT_PATH
Options:
-... |
"""=============================================================================
IMPORTS
============================================================================="""
# Python package imports
import logging
"""=====================================================================... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from conans import ConanFile, tools
import os
class LibLinearConan(ConanFile):
name = "liblinear"
version = "2.20"
github_version = "220"
description = "A Library for Large Linear Classification"
url = "https://github.com/konijnendijk/conan-libname"
... |
#!/usr/bin/env python3
"""RSA"""
import math
import random
from tkinter import *
from tkinter import ttk
#SPECIFICATION
"""Public key
P and Q are prime number
N = P * Q
M = ( P - 1) * (Q -1)
C = prime number of M, GCD(C,M) = 1
Public key = (N,C)
"""
"""
Private key
We have need U
C * U + M * V = 1
U is ]2,M[
2 < U ... |
'''
@author: Reem Alatrash
@version: 1.0
=======================
This script takes the pre-trained parser model and runs it on an unseen dataset.
'''
'''
******* ********* *********
******* imports *********
******* ********* *********
'''
import sys
from collections import deque
from classes import *
'''
*******... |
import torch
import torch.nn as nn
from .non_local_block.non_local_embedded_gaussian import NONLocalBlock2D
# from utils.tensorboardx_writer import tensorboardx_visualize_average_features
from torchvision.models.resnet import resnet34, resnet18, resnet50
from dropblock import DropBlock2D, LinearScheduler
class ResNet... |
# Original article https://blog.loadero.com/2022/05/19/local-tests-with-selenium-and-python-browser-automation/
def test_on_loadero(driver: TestUIDriver) -> None:
driver.navigate_to("https://loadero.com/")
time.sleep(10)
|
import os
def convert_to_iso_8859_1(oldfile):
'''\
Encoding translation from UTF-8 to ISO-8859-1
oldfile: file encoded in UTF-8
Note:
- codecs class is obsolete in 3.x, since open() gains an encoding argument
'''
sourceFile = open(oldfile, "r", encoding="utf_8")
targetFile = open("... |
# Crie uma tupla preenchida com os 20 primeiros colocados
# da Tabela do Campeonato Brasileiro de Futebol, na ordem
# de colocação. Depois mostre:
# a) Os 5 primeiros times.
# b) Os últimos 4 colocados.
# c) Times em ordem alfabética.
# d) Em que posição está o time da Chapecoense.
times = ('Flamengo', 'Santos', 'Palm... |
# Generated by Django 3.0.6 on 2020-05-20 08:04
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('accounts', '0005_book_usersfav'),
]
operations = [
migrations.RemoveField(
model_name='book',
name='usersfav',
),
... |
# -*- coding: utf-8 -*-
from django.db import models
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
from website.models import AnalysePeptide
class ClientCalculation(models.Model):
STATES = [(1,u"Envoyé"),(2,u"Reçu"),(3,u"Déconnecté")]
client = ... |
from __future__ import annotations
from abc import ABCMeta, abstractmethod
from typing import (
Any,
Dict,
Literal,
Mapping,
MutableMapping,
Optional,
Sequence,
Tuple,
Type,
Union,
overload,
)
from .api_key import API_KEY
from .data import Alliance, Color, Data, Nation, Tra... |
__author__ = 'Daniel Lindsley'
__version__ = (2, 1, 0)
|
from .wordgen import Wordgen
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.