content stringlengths 5 1.05M |
|---|
for i in range(1, 6):
for j in range(6 - i, 0, -1):
print(j, end=" ")
print()
|
# -*- coding: utf-8 -*-
"""
A test harness for gnupg.py.
Copyright (C) 2008-2022 Vinay Sajip. All rights reserved.
"""
import argparse
import json
import logging
import os.path
import os
import re
import shutil
import stat
import sys
import tempfile
import unittest
try:
from unittest import skipIf
except ImportEr... |
{
'target_defaults': {
'defines': [
'_U_='
]
},
'targets': [
{
'target_name': 'nghttp2',
'type': 'static_library',
'include_dirs': ['lib/includes'],
'conditions': [
['OS=="win"', {
'defines': [
'WIN32',
'_WINDOWS',
'HA... |
# -*- coding: utf-8 -*-
train_src = [
('Unknown', 'Unknown'),
('技术', '技术'),
('技术', '性能'),
('大数据', '大数据'),
('大数据', 'BigData'),
('大数据', 'Spark'),
('大数据', 'Hadoop'),
('大数据', 'HBase'),
('大数据', 'Storm'),
('大数据', 'Kafka'),
('大数据', 'JStorm'),
('大数据', 'MapReduce'),
('JavaScript', 'Angular'),
('JavaScript', 'JavaScript'),
... |
import cv2
import glob
import sys
import time
def play_with_opencv():
vc = cv2.VideoCapture("chika.mp4")
if not vc.isOpened():
print("Error opening video stream")
sys.exit(1)
fps = vc.get(cv2.CAP_PROP_FPS)
mspf = 1000.0 / fps
key = None
last_frame_time = time.time()
while key != 27: # Escape to... |
from ..utility import settings
from ..psdl import lightcmd
from ..psdl import materialcmd
from ..psdl.cmd import RawCommand
from .export import naming
from .. import utility
from ..psdl import clause
from ..psdl.pysdl import (
SDLReal,
SDLVector3,
SDLQuaternion,
SDLString,
SDLReference,
SDLLightSource)
from ..p... |
import os
from argparse import ArgumentParser, Namespace
from collections import OrderedDict
import numpy as np
from PIL import Image
import itertools
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
import torchvision.transforms as transforms
from torch.autograd import Variable
fr... |
"""Support for APCUPSd sensors."""
from __future__ import annotations
import logging
from apcaccess.status import ALL_UNITS
import voluptuous as vol
from homeassistant.components.sensor import (
PLATFORM_SCHEMA,
SensorEntity,
SensorEntityDescription,
)
from homeassistant.const import (
CONF_RESOURCES... |
"""
Copyright (c) Facebook, Inc. and its affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
"""
import contextlib
from typing import Optional, Sequence, Tuple, Union
import numpy as np
import torch
@contextlib.contextmanager
def temp_... |
import os
from pywps import Service
from pywps.tests import assert_response_success
from . common import client_for
from copernicus.processes.wps_blocking import Blocking
def test_wps_blocking():
client = client_for(Service(processes=[Blocking()], cfgfiles=[".custom.cfg"]))
resp = client.get(
servic... |
"""
Helper class to specify included regions of the genome when iterating events.
"""
import io
import re
import sys
import gzip
import logging
from collections import defaultdict, OrderedDict
from intervaltree import IntervalTree
import truvari.comparisons as tcomp
HEADERMAT=re.compile("##\w+=<ID=(?P<name>\w+),Numb... |
from fpioa_manager import fm
# maixduino board_info PIN10/PIN11
# from board import board_info
# fm.register(board_info.PIN10, fm.fpioa.UART1_TX, force=True)
# fm.register(board_info.PIN11, fm.fpioa.UART1_RX, force=True)
# need your connect hardware IO 10/11 to loopback
fm.register(10, fm.fpioa.UART1_TX, force=True)
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import basic
CUTOFF = 10
def insertion_sort(sequence):
for i in range(1, len(sequence)):
value = sequence[i]
j = i - 1
while j >= 0 and sequence[j] >= value:
sequence[j + 1] = sequence[j]
j -= 1
sequence[j + 1] = value
def median(sequence, i, j):
first =... |
count = 0
total = 0
for i in range(0,1000):
if i % 3 == 0 or i % 5 == 0:
count += i
print i
total = count
print 'The sum of multiple 3 and 5 is ',total |
from __future__ import division
try:
import boost.python
except Exception:
ext = None
else:
ext = boost.python.import_ext("fractbx_ext", optional=False)
if not ext is None:
from fractbx_ext import *
|
import tensorflow as tf
class PatchCreator(tf.keras.layers.Layer):
'''
Used to create patches to be fed into ViT
Input:
patch_size - size of the single patch
images - images to be divided into patches
Output:
patches - images divided into patches of given size
'''
def __... |
#!/usr/bin/env python3
"""
Forward prometheus notifications to teams.
Usage:
python prom2teams --help
"""
import logging
import prom2teams.configuration
import prom2teams.server
import prom2teams.processor
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging... |
import types
from functools import wraps
def add_forward_with_shift(generator):
def gen_shifted(self, z, shift, *args, **kwargs):
return self.forward(z + shift, *args, **kwargs)
generator.gen_shifted = types.MethodType(gen_shifted, generator)
generator.dim_shift = generator.dim_z
def gan_with_s... |
from time import time
from utils import BST
import gc
'''
Given a binary tree, design an algorithm which creates a linked list
of all the nodes at each depth (e.g., if you have a tree with depth D, you will have D linked lists)
'''
class BST_with_height(BST):
def __init__(self, key = None, parent = None):
... |
"""Test HomeKit img_util module."""
from homeassistant.components.camera import Image
from homeassistant.components.homekit.img_util import (
TurboJPEGSingleton,
scale_jpeg_camera_image,
)
from .common import EMPTY_8_6_JPEG, mock_turbo_jpeg
from tests.async_mock import patch
EMPTY_16_12_JPEG = b"empty_16_12"... |
_base_ = [
'../_base_/models/yolov3_d53.py',
'../_base_/datasets/coco_detection.py',
'../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py'
]
model = dict(
backbone=dict(
type='DarknetEMOD',
ar=dict(ratio=1. / 4.),
stage_with_ar=(True, True, True, True, True)
),... |
import pytest
from cartoframes.exceptions import DiscoveryException
from cartoframes.data.observatory.catalog.category import Category
from cartoframes.data.observatory.catalog.entity import CatalogList
from cartoframes.data.observatory.catalog.repository.category_repo import CategoryRepository
from cartoframes.data.o... |
import os.path
from git import *
import git, os, shutil
import shutil
import stat
import subprocess
from random import randrange
from pprint import pprint
import json
import sys
import requests
import psycopg2
import time
import urllib.request, json
from collections import OrderedDict
#THIS SCRIPT CREATES REFERENCE V... |
import numpy as np
import h5py
import scipy.interpolate as interpolate
import scipy.integrate as integrate
from IPython.display import HTML
from pyspi.io.package_data import get_path_of_data_file
class SPIResponse(object):
def __init__(self):
"""FIXME! briefly describe function
:returns:
... |
import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from sklearn.datasets import make_circles
from O5 import rbf_kernel_pca
X, y = make_circles(n_samples=1000, random_state=123, noise=0.1,
factor=0.2)
plt.scatter(X[y == 0, 0], X[y == 0, 1],
color=... |
#!/usr/bin/python
#
# Copyright 2008-2015 Semantic Discovery, 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 re... |
# Copyright 2016 Medical Research Council Harwell.
#
# 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... |
from django.contrib import admin
from .models import Unsubscribe
# Register your models here.
admin.site.register(Unsubscribe)
|
from django.urls import path
from .views import ChatSessionView, ChatSessionMessageView
app_name = 'chat'
urlpatterns = [
path('chats/', ChatSessionView.as_view()),
path('chats/<uri>/', ChatSessionView.as_view()),
path('chats/<uri>/messages/', ChatSessionMessageView.as_view()),
] |
# -*- coding: utf-8 -*-
"""
Defines unit tests for :mod:`colour.colorimetry.lefs` module.
"""
from __future__ import division, unicode_literals
import numpy as np
import unittest
from colour.colorimetry import (mesopic_weighting_function,
sd_mesopic_luminous_efficiency_function)
from ... |
import sys
sys.path.append('../../configs')
sys.path.append('../../utils')
sys.path.append('../../tfops')
# ../../utils
from datasetmanager import DATASETMANAGER_DICT
from format_op import params2id, listformat
from shutil_op import remove_file, remove_dir, copy_file, copy_dir
from csv_op import CsvWriter2, CsvWriter
... |
import unittest
from datetime import datetime
from movie_lib import Movie, User, Rating
movies ={1: Movie(1, 'Toy Story (1995)', datetime.strptime('01-Jan-1995', '%d-%b-%Y')),
2: Movie(2, 'GoldenEye (1995)', datetime.strptime('01-Jan-1995', '%d-%b-%Y')),
3: Movie(3, 'Four Rooms (1995)', datetime.strpt... |
""" this module is used as a global context across multiple layouts and filters """
# Constants that are initialized once when the application starts and will not be changed during runtime
MATCH = "Yes"
ALL = "All"
NOT_LABELED = "Not-Labeled"
NON_MATCH = "Not-Matched"
NOT_SURE = "Not-Sure"
ALL_ATTRIBUTES = None
DEFAUL... |
# Generated by Django 2.1.5 on 2019-01-12 12:58
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('webview', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Category',
fields=[
('id',... |
"""
TensorFlow implementation of ConvMixer
Based on timm/models/convmixer.py by Ross Wightman.
Copyright 2021 Martins Bruveris
"""
from dataclasses import dataclass
from typing import List, Tuple
import tensorflow as tf
from tfimm.layers import act_layer_factory, norm_layer_factory
from tfimm.models import ModelCon... |
''' Use this for constants used strictly for crud processes '''
from projects.models.paragraphs import (Category, Group, # noqa: F401
GroupParagraph, Paragraph,
ParagraphReference, Reference)
FILE_DATA = 'file_data'
VALID_RETRIEVAL_KEYS... |
import json
from redis import StrictRedis
from encoded.searches.interfaces import REDIS_LRU_CACHE
from snosearch.parsers import ParamsParser
from snosearch.responses import FieldedInMemoryResponse
from snosearch.responses import FieldedResponse
_redis_lru_cache = None
def includeme(config):
# Handle to grab ou... |
import torch.nn as nn
class TwoLayerModel(nn.Module):
def __init__(self):
super().__init__()
self.fc = nn.Sequential(
nn.Linear(4,128, bias=True),
nn.ReLU(),
nn.Linear(128,2, bias=True),
nn.Softmax(dim=1)
)
def forward(self, ... |
# Autogenerated from KST: please remove this line if doing any edits by hand!
import unittest
from docstrings_docref import _schema
class TestDocstringsDocref(unittest.TestCase):
def test_docstrings_docref(self):
r = _schema.parse_file('src/fixed_struct.bin')
|
from PageManager import PageManager
class login(PageManager):
"controlador de Login"
def __init__(self):
super(self)
print "jiji"
|
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 27 18:30:32 2017
@author: ZechT
"""
import os, sys
import numpy as np
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import configparser
import handler.DataItem as data
import ui.AskHandler as AskHandler
class DirTreeWidget(QTreeW... |
def collision(controller):
bullet = controller.owner
if (bullet["left"]):
from bge import logic
from random import uniform
from math import pi
bullet = controller.owner
controller.sensors[0].hitObject["hit"] = True
if (controller.sensors[0].hitObject["isAsteroid"]... |
import json
import subprocess
from os import path
from contextlib import nullcontext
from anytree import AnyNode, PreOrderIter
from yaspin import yaspin
from license_sh.runners.runners_shared import fetch_npm_licenses
def flatten_package_lock_dependencies(package_lock_dependencies):
"""
Flattens package.lock... |
import io
def msg_select_battlecmd(self, data):
data = io.BytesIO(data[1:])
player = self.read_u8(data)
activatable = self.read_cardlist(data, True)
attackable = self.read_cardlist(data, True, True)
to_m2 = self.read_u8(data)
to_ep = self.read_u8(data)
self.cm.call_callbacks('select_battlecmd', player,... |
# python3
#https://docs.python.org/3.0/library/heapq.html
#https://stackoverflow.com/questions/47564075/most-efficient-1-loop-way-to-use-priority-queue-in-parallel-jobs-task
#https://codereview.stackexchange.com/questions/208772/parallel-processing-simulation
from collections import namedtuple
class Worker:
def ... |
#try:
first = 10
second = 0
third = first / second
#except Exception as e:
# pass
#pass
|
"""
Detecting Loops in Linked Lists
In this notebook, you'll implement a function that detects if a loop exists
in a linked list. The way we'll do this is by having two pointers, called
"runners", moving through the list at different rates. Typically we have a
"slow" runner which moves at one node per step and a "fast"... |
#!/usr/bin/env python
'''
Read orbits data.
'''
import os
import numpy as np
class ReadOrbits(object):
def __init__(self, I_file,
rawdata_path='/dgalex2/qinyj/data/3042_orbsave/'):
rawdata_fname = rawdata_path + ('orbits%03u' % I_file) + '.res'
print('\nLoading ', rawdata_... |
from django.db import models
from django.db.models import Q
class PaperQuerySet(models.QuerySet):
def published(self):
"""Get all published items."""
return self.filter(Q(publish=True))
|
"""
test_cyclefeatures.py
Test measurement of cycle-by-cycle features of oscillatory waveforms
"""
import numpy as np
import pandas as pd
import os
import neurodsp
from neurodsp import shape
from neurodsp.tests import _load_example_data
def test_cyclefeatures_consistent():
"""
Confirm consistency in peak fin... |
from flask import Flask, jsonify, request
from flask.json.tag import JSONTag
from Blockchain import Blockchain
from apis import get_api_keys, push_log
app = Flask(__name__)
blockchain = Blockchain()
def get_and_check():
api_key = request.headers.get('x-api-key')
keys = get_api_keys()
if k... |
from main import main, KwikStatsServer
|
from corpus import Corpus
from summary import Summary
import objectives
from objectives import AggregateObjective
import logging
logger = logging.getLogger("linBilmes.py")
def optimizeGreedy(sizeBudget, objective, corpus):
summary = Summary()
sentencesLeft = corpus.getSentences()
objective.setCorpus(co... |
import asyncio
from telethon import events
from bot.functions import white_list
def run(client, logger, lg, ct, cw):
my_entity = client.get_me()
logger.debug(ct['rm_white'])
logger.debug(ct['rm_white']['pattern_str'])
@client.on(events.NewMessage(
outgoing=True,
chats=my_entity,
... |
# Runs entire flow to preprocess engine data to NWC pattern generic format
# Then it uses NWC pattern package to generate sequential patterns
import os
import argparse
import pandas as pd
from .constants import *
from nwc_pattern_miner import mine_sequence_patterns
from .config_parser import parse_config
from .prep... |
# https://github.com/COLAB2/midca/blob/c3e4cc9fab5683f44435816d90a7a2eb591c4ce4/midca/rosrun.py
class coloredBlocksworldEntitiesHandler(IncomingMsgHandler):
'''
class that receives Point messages, where each message indicates that the given object
has been identified at that location. Args include the top... |
from tinydb import TinyDB, Query
import crypto as crp
from hashlib import sha256
import binascii
from binascii import unhexlify
import IOTtransaction as iotr
import chain
wallet_db = TinyDB('wallet_db.json')
class client:
#validate receiver
def validate_receiver(self,receiver):
if(receiver.... |
#!/usr/bin/env python
import numpy as np
import os
import random
import asyncio
import traceback
from datetime import datetime
from pickle import Pickler, Unpickler
from args import parse_args, AsyncNone
from game import Game
from model import Model
from mcts_tree import MCTS
from memory import Memory
from play import... |
# MIT License
#
# Copyright (c) 2018 Michael DeFelice
#
# 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, ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Module documentation goes here."""
from __future__ import print_function
__author__ = "Vladimir Poplavskij"
__copyright__ = "Copyright 2020, Vladimir Poplavskij"
__credits__ = ["C D", "A B"]
__license__ = "Apache 2.0"
__version__ = "1.0.1"
__maintainer__ = "Vladimir P... |
from django.shortcuts import render, get_object_or_404
from django.views.generic import View
from django.http import HttpResponseRedirect
from django.urls import reverse
import requests
requests.packages.urllib3.disable_warnings()
import urllib.request as ur
from django.shortcuts import render, redirect
from bs4 import... |
from decimal import Decimal
import pytest # type:ignore[import]
from bo4e.com.betrag import Betrag
from bo4e.com.kostenblock import Kostenblock, KostenblockSchema
from bo4e.com.kostenposition import Kostenposition
from bo4e.com.preis import Preis
from bo4e.enum.mengeneinheit import Mengeneinheit
from bo4e.enum.preis... |
import numpy as np
import torch
import math
import re
from . import BaseWrapperDataset, data_utils
def get_number_value(tensor, tokenizer, send_log_value):
number_str = re.sub(" ", "", tokenizer.decode(tensor.tolist()))
# number_str = ''.join([vocab.symbols[id] for id in tensor]) # sp tokenizer symbols conta... |
class Solution(object):
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
left = 0
right = len(s) - 1
while left < right:
left_flag = s[left].isalnum()
right_flag = s[right].isalnum()
if left_flag and right_flag:
if s[left].lower() != s[right].lower():
return False
lef... |
import logging
import json
import datetime
import pathlib
from typing import Optional
from config import DATA_DIR
from helpers import count_and_log, is_json_line, create_ln_str_with_json_boilerplate, get_file_size_info_str
def _split_extracted_at_once(in_fp: pathlib.Path, prefix: str, subreddit: str):
out_sub_dn ... |
#!/usr/bin/env python
from setuptools import setup, find_packages
import os, versioneer, subprocess, re
__author__ = "Lukas Elflein, Johannes Hörmann"
__copyright__ = "Copyright 2019, IMTEK Simulation, University of Freiburg"
__maintainer__ = "Johannes Hörmann"
__email__ = "johannes.hoermann@imtek.uni-freib... |
#!/usr/bin/env python3
import unittest
from prng import PRNG
from math import sqrt, fabs
class TestPRNG(unittest.TestCase):
def setUp(self):
self.INT32_MIN = -2**31
self.INT32_MAX = 2**31 - 1
def test_ok(self):
png = PRNG(101)
self.assertEqual(png.next(-9, 7), -8)
... |
from org.transcrypt.stubs.browser import *
import random
array = []
def gen_random_int(number, seed):
pass
def generate():
new_array = []
new_array_string = []
global array
number = 10
while len(new_array) != number:
new_array.append(random.randint(0, number))
array = new_array
for x in new_array:
new_ar... |
#----------------------------------------------------------------------------------------------------------
#
# AUTOMATICALLY GENERATED FILE TO BE USED BY W_HOTBOX
#
# NAME: Toggle Adjust Points
# COLOR: #3a97bd
#
#---------------------------------------------------------------------------------------------------------... |
from dags.spark.union_transactions import union_transactions
from dags.spark.enrich_transactions import enrich_transactions
from dags.spark.filter_countries import filter_countries
def test_filter_countries(spark):
spark.sql("USE tst_app").collect()
union_transactions(spark, "tst")
enrich_transactions(spa... |
from nachbarstrom.commons.world import Location
from nachbarstrom.commons.image_provider import GoogleImageProvider
GERMANY_LOCATION = Location(latitude=48.267991, longitude=11.665950)
IMG_PROVIDER = GoogleImageProvider()
SATELLITE_IMG = IMG_PROVIDER.get_image_from(GERMANY_LOCATION)
SATELLITE_IMG.save("img.png")
|
""" Utility functions for tests. """
import os
import numpy as np
import pytest
from affine import Affine
import rasterio as rio
import geopandas as gpd
from shapely.geometry import Polygon
@pytest.fixture
def basic_image():
"""
A 10x10 array with a square (3x3) feature
Equivalent to results of rasterizin... |
from django.db import models
from django.contrib.auth.models import User
from PIL import Image
# Create your models here.
class KhaanDaanUsers(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
name = models.CharField(max_length=50)
mobile_no = models.CharField(max_length=10,null=Fa... |
#!/usr/bin/python
import logging
import os
import os.path
import shutil
import sys
from flask.ext.script import Manager
from compass.api import app
from compass.config_management.utils import config_manager
from compass.db import database
from compass.db.model import Adapter, Role, Switch, Machine, HostState, Cluster... |
class RBNode:
def __init__(self, val, color="R"):
self.val = val
self.color = color
self.left = None
self.right = None
self.parent = None
def is_black_node(self):
return self.color == "B"
def is_red_node(self):
return self.color == "R"
def set_b... |
import numpy
import math
import scipy
# ---------------------------------------------------------------------------------
#
# Utilities
#
# ---------------------------------------------------------------------------------
def bounded_nonlinear_curve_fit(func, xdata, ydata,
yerr=None, f... |
from __future__ import division
from builtins import object
import pytest
try:
import cupy as cp
try:
cp.cuda.Device(0).compute_capability
except cp.cuda.runtime.CUDARuntimeError:
pytest.skip("GPU device inaccessible", allow_module_level=True)
except ImportError:
pytest.skip("cupy not i... |
def load_menu():
menu = []
f_menu = open("../kitchin_menu.txt", 'r')
while True:
line = f_menu.readline()
if not line: break
menu.append(line)
f_menu.close()
return menu
def total_price(price):
total = 0
for p in price:
p = int(p)
total += p
ret... |
import argparse
import _pickle as pickle
from pymongo import MongoClient
import csh_db_cfg
def main(label_path):
# connection to mongodb
mongoConn = MongoClient(csh_db_cfg.DB_HOST + ":" + str(csh_db_cfg.DB_PORT))
cshTransDB = mongoConn[csh_db_cfg.TRANSCRIPTION_DB_NAME]
cshTransDB.authenticate(csh_db_c... |
# -*- coding: latin-1 -*-
# -----------------------------------------------------------------------------
# Copyright 2011-2013
# Stephen Tiedemann <stephen.tiedemann@googlemail.com>,
# Alexander Knaub <sanyok.og@googlemail.com>
#
# Licensed under the EUPL, Version 1.1 or - as soon they
# will be approved by the ... |
import torch
from . import misc
from torch.nn.modules.batchnorm import _BatchNorm
def sync_grad_sum(network):
if misc.get_world_size() == 1: return
misc.all_reduce_sum([param.grad.data for param in network.parameters() if param.grad is not None])
def sync_bn_stat(network):
if misc.get_world_size() == 1: r... |
from lxml import etree
from onegov.core.utils import scan_morepath_modules
from onegov.core.widgets import transform_structure
from onegov.org import OrgApp
def test_widgets():
class App(OrgApp):
pass
scan_morepath_modules(App)
App.commit()
widgets = App().config.homepage_widget_registry.va... |
from http.cookies import SimpleCookie
import pytest
from tests.factories.tag import (
TagFactory,
tag_instant_traceable,
tag_instant_analytical,
tag_instant_delayed,
tag_instant_functional,
)
from tests.factories.trigger import TriggerFactory
from wagtail_tag_manager.models import Tag
@pytest.ma... |
import sys
try:
from blessed import Terminal
except ImportError:
Terminal = None
def ask_key():
if Terminal is None:
try:
value = raw_input(
"Type the decryption key, "
"without spaces or other special characters: ")
return value.strip().deco... |
#!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""
Main launch script for single-host, multi-GPU training.
This is a drop-in replacement for train_model.py. This scr... |
# Copyright 2017 Mycroft AI 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 law or agreed to in writin... |
from django.db import models
from djrichtextfield.sanitizer import SanitizerMixin
from djrichtextfield.widgets import RichTextWidget
class RichTextField(SanitizerMixin, models.TextField):
def __init__(self, *args, field_settings=None, **kwargs):
self.field_settings = field_settings
super(RichText... |
import tempfile
import subprocess
import os
import shutil
import logging
from typing import List
log = logging.getLogger(__name__)
def fetch_dependency(module_name: str, specifier: str, install_path: str, pip_args: List[str]):
"""Shells out to PIP in order to download and unzip the named package into
the sp... |
#!/usr/bin/env python
# Authors: Andrew Jewett (jewett.aij at g mail)
# http://www.moltemplate.org
# http://www.chem.ucsb.edu/~sheagroup
# License: 3-clause BSD License (See LICENSE.TXT)
# Copyright (c) 2011, Regents of the University of California
# All rights reserved.
"""
ttree.py is a simpl... |
from typing import Any, Dict, Generic, List, Optional, TypeVar, Union
import enum
import os
from pydantic import BaseModel, Field
from pydantic.generics import GenericModel
PRED_UNIT_KEY = "predictive_unit_id"
PRED_UNIT_ID = os.environ.get("PREDICTIVE_UNIT_ID", "0")
DEPLOYMENT_ID = os.environ.get("SELDON_DEPLOYMENT_... |
t = int(input())
finalAns = []
for i in range(t):
n, s = map(int, input().split())
p = list(map(int, input().split()))
ptype = list(map(int, input().split()))
minDef = 100
minFor = 100
for j in range(n):
if(ptype[j]==0):
if(p[j]<minDef):
minDef = p[j]
... |
# %%
import json
import itertools as it
import functools as ft
def wtree(words):
wt = dict()
rwt = dict()
for w in words:
if len(w) not in wt:
wt[len(w)] = {'CNT': 0}
if len(w) not in rwt:
rwt[len(w)] = {'CNT': 0}
curr = wt[len(w)]
curr['CNT'] += 1
... |
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="wicked_python-hotness",
version="0.0.1",
author="Graham Williasmon",
author_email="author@example.com",
description="A wicked new package that is the new hotness",
long_description=lon... |
import re
from bs4 import BeautifulSoup as bs
hashPattern = re.compile(r"staff\.php\?id=")
soup = bs(open("/root/Documents/baze.html"), "html.parser")
clean = soup.prettify("utf8")
soup = bs(clean, "html.parser")
divs = soup.find_all("a", attrs={"href":hashPattern})
for div in divs:
soup = bs(str(div), "html.pa... |
from unittest import TestCase, skip
from unittest.mock import create_autospec, call
from connection import ConnectionSelectLive, ssl
from ssl import SSLSocket, SSLZeroReturnError
from exception import ValidationException
import settings
class CreateTest(TestCase):
def test_connect_success(self):
create_ssl... |
# -*- coding: utf-8 -*-
# Copyright 2019, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
Persistent value.
"""
from qiskit.exceptions import QiskitError
from qiskit.pulse.commands.pulse_command import PulseCom... |
import numpy as np
import utilities
import threading
import time
from logging import getLogger
from matrix_board import MatrixBoard
from bit_board import BitBoard
from libfastbb import FastBitBoard
class Engine(object):
def __init__(self, player_black, player_white, board_rows, board_columns):
self._board_... |
import datetime
from db import connection
mydb = connection.mydb
def update_stock(stock_symbol, application_id, balance, buy_date, initial_balance, qtd):
mycursor = mydb.cursor()
sql = "UPDATE current_account_applications SET balance = %s, initial_balance= %s, quantity= %s WHERE description= %s AND id= %s"... |
class Solution(object):
def twoSum(self, numbers, target):
"""
:type numbers: List[int]
:type target: int
:rtype: List[int]
"""
left, right = 0, len(numbers) - 1
while True:
sum = numbers[left] + numbers[right]
if sum == target... |
#-*-coding utf-8-*-
import json
import io
import sys
import urllib.request, json
url = "http://3.94.119.184/location"
response = urllib.request.urlopen(url)
data = json.loads(response.read())
# 한글 깨짐 막기 위한 코드. python3부터 지원
sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding = 'utf-8')
sys.stderr = io.TextI... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.