id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
4879013 | from PIL import Image
import pytesseract
import re
def getText(path):
return pytesseract.image_to_string(Image.open(path))
def paragraph(text):
para = list(filter(lambda x: x != "" and len(re.sub(r" ", "", x)) != 0, text.split("\n\n")))
return para
if __name__ == "__main__":
print(
paragra... |
4879026 | from django.contrib.postgres import fields as psql_fields
from django.db import migrations
# This query generates full text search index based
# the following data ranked from A to D:
# - Namespace name (weight A
# - Collection name (weight A)
# - Collection tags (weight B)
# - Collection content names (weight... |
4879157 | import re
_camelcase_invalid_chars = re.compile(r'[^a-zA-Z\d]')
_camelcase_split_chars = re.compile(r'(.)([A-Z][a-z]+)')
_camelcase_split_chars2 = re.compile(r'([a-z0-9])([A-Z])')
def string_camelcase(s):
a = _camelcase_invalid_chars.split(s)
return ''.join([(i[0].upper() + i[1:]) for i in a if i])
def st... |
4879235 | import os
from sklearn.model_selection import KFold
import pandas as pd
from params.params import args
if __name__ == '__main__':
path = os.path.join(args.output_data, 'train', 'images')
cv_total = args.n_folds
seed = args.seed
all_files = os.listdir(path)
all_ids = list(set(['_'.join(el.split('_')[4:]).split('.... |
4879247 | from string import ascii_uppercase as v, ascii_lowercase as k
def check_flag(s):
if len(s) != 0x19:
return False
s = list(s)
if int(`[s.pop(r) for r in ([2] + [i for i in range(11, 18, 2)] + [20])[::-1]][::-1]`[2::5]) != 0x61a83:
return False
if len(list(set([s.pop(r) for r in map(lambda p: int(p, 2), [("1"*5)[... |
4879259 | import csv
from pathlib import Path
target_dirs = [Path('ja'),Path('en')]
fixed_characters = r'''
English
日本語
簡体中文
简体中文
繁體中文
繁体中文
=== auto generated ===
'''
characters = set()
for target_dir in target_dirs:
for csv_file_path in target_dir.glob('*.csv'):
with open(csv_file_path, 'r', encoding='utf8') a... |
4879261 | import json
from collections import OrderedDict
from tqdm.auto import tqdm
import torch
import pytorch_lightning as pl
from transformers import (
BertTokenizer,
BertForQuestionAnswering,
get_constant_schedule_with_warmup,
get_constant_schedule,
)
from ..utils.util import accuracy_precision_recall_f1
... |
4879294 | import bpy
bpy.context.cloth.settings.quality = 5
bpy.context.cloth.settings.mass = 0.150
bpy.context.cloth.settings.tension_stiffness = 5
bpy.context.cloth.settings.compression_stiffness = 5
bpy.context.cloth.settings.shear_stiffness = 5
bpy.context.cloth.settings.bending_stiffness = 0.05
bpy.context.cloth.settings.te... |
4879302 | from .bio import EXTENDED_IUPAC_PROTEIN_ALPHABET, SeqIO, parse
from .config import get_config
from .imports import try_import_pytorch
from .io_utils import create_df, get_data_home, get_weights_path
from .logger import get_logger
from .sync import SynchronizedCounter
from .network import count_parameters, load_nn, set_... |
4879346 | def make_trie(*words):
root = dict()
for w in words:
cur = root
for ch in w:
cur = cur.setdefault(ch, {})
cur['end'] = 'end'
return root
def in_trie(trie, word):
cur = trie
for ch in word:
if ch in cur:
cur = cur[ch]
else:
... |
4879374 | from fabric.api import run
def deploy():
run("service rsp stop")
run("cd /home/rsp/rsp/src && git pull origin master && make clean && make && make install")
run("service rsp start")
|
4879376 | import torch
import torch.nn as nn
import numpy as np
class AutoEncoder(nn.Module):
def __init__(self):
super(AutoEncoder, self).__init__()
self.encoder_layer1 = nn.Sequential(
nn.Linear(768, 256), nn.ReLU(),
nn.Linear(256, 128), nn.ReLU(),
nn.Linear(128, 64), n... |
4879428 | from vis import scene, local_light, color, vector
# scene parameters and settings:
scene.x, scene.y = 250, 80 # centering the window (optimized for SXGA displays)
scene.width, scene.height = 800, 600
scene.title = "Solar System"
scene.lights = []
scene.ambient = 0.4 # turning off default lights and turning on some... |
4879458 | import numpy as np
import learnergy.math.scale as s
# Creates an input array
a = np.array([1, 2, 3, 4, 5])
# Scales the input array between 0 and 1
u = s.unitary_scale(a)
# Prints the result
print(u)
|
4879459 | import logging
import time
import re
import requests
import unicodedata
import shutil
import json
from datetime import datetime
from os import path
from pathlib import Path
from PIL import Image
from requests.exceptions import ConnectionError
from xml.etree.ElementTree import SubElement, Element, Comment,... |
4879507 | import ast
import json
import logging
import re
import subprocess
from itertools import chain
from .utils import run
log = logging.getLogger(__name__)
def restart_os_functions():
for item in ('Finder', 'Dock', 'SystemUIServer', 'cfprefsd'):
cmd = ['killall', item]
log.info(f"Executing command: {... |
4879571 | bgp_v4_neighbors_output = \
"""
BGP neighbor is 10.0.0.57, remote AS 64600, local AS 65100, external link
Description: ARISTA01T1
Member of peer-group PEER_V4 for session parameters
BGP version 4, remote router ID 172.16.58.3, local router ID 10.1.0.32
BGP state = Established, up for 00:00:39
Last read 00:00:00... |
4879601 | from .core.client import Client, AsyncClient
from .core.generic_client import ALL_NS
from .core.exceptions import ApiError, ConfigError, LoadResourceError
from .config.kubeconfig import KubeConfig, SingleConfig
|
4879680 | expected_output = {
"interfaces":{
"GigabitEthernet3/0/3":{
"mac_address":{
"34db.fde5.34ab":{
"acct_session_id":"0a6a1841000000b4",
"common_session_id":"41186A0A000000F43F4FBBBE",
"current_policy":"POLICY_Gi3/0/3",
"domain":"VOIC... |
4879699 | import fileinput
from collections import defaultdict
from utils import parse_nums, memoize
@memoize
def resolve(r):
if type(rules[r]) == str:
return [rules[r]]
matches = []
for subrule in rules[r]:
submatches = ['']
for n in subrule:
new = []
for m in resolv... |
4879715 | import sys
if sys.version_info[0] >= 3:
appName = "DrawBotPy3"
else:
appName = "DrawBot"
__version__ = "3.114"
|
4879757 | from collections import namedtuple
from typing import Generator
Coordinates = namedtuple('Coordinates', 'x y z')
class LorenzModel:
def __init__(self, sigma: float, beta: float, rho: float, time_step: float) -> None:
self.sigma = sigma
self.beta = beta
self.rho = rho
self.time_st... |
4879758 | import argparse
import tensorflow as tf
import numpy as np
def main(params):
cell_numbers = params.cells_number
fashion_mnist = tf.keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
train_images = train_images / 255.0
test_images = test... |
4879768 | import functools
import hashlib
import inspect
import json
import os
import pathlib
from datetime import datetime
from typing import Any, Callable, Dict, List, Tuple, Type, Union
import h5py
import numpy as np
import pandas as pd
import tables
pandas_function = Callable[..., Union[Tuple[pd.DataFrame], pd.DataFrame]]
... |
4879806 | import numpy as np
class Config():
def __init__(self):
# Model Params
self.N = 3
self.input_H = 160
self.input_W = 160
self.fix_vgg = True
self.vgg_dropout = False
# Tracker Params
self.qimage_size = 80 # be careful when extended for multiple scales... |
4879830 | import logging
from typing import List
import numpy
from cephlib.units import unit_conversion_coef_f
from cephlib.plot import PlotParams, provide_plot
from .resources import IOSummary
logger = logging.getLogger("wally")
@provide_plot(eng=False, no_legend=True, grid='y', style_name='ioqd', noadjust=True)
def io_c... |
4879876 | def setup():
import config
import logging
level = logging.INFO
if config.DEBUG:
level = logging.DEBUG
logging.basicConfig(level=level)
|
4879974 | from ztk.api.base import RestApi
class TbkScShopConvertRequest(RestApi):
'''__init__(self, site_id, fields, user_ids, adzone_id, platform=None, unid=None, signurl=2, domain='api.zhetaoke.com', port=10001):
site_id 备案的网站id, mm_xx_xx_xx pid三段式中的第二段
fields 需返回的字段列表,如:user_id,click_url
user_ids 卖家ID串,用... |
4879992 | import subprocess
import os
import logging
import threading
import time
if __name__ == '__main__':
import exceptions
else:
from chiptools.common import exceptions
log = logging.getLogger(__name__)
def iterate_tests(test_suite_or_case):
"""Iterate through all of the test cases in 'test_suite_or_case'."""... |
4880002 | import json
import os
import shutil
from config import Config
from mss import mss
from utils.misc import close_down_bnet_launcher, close_down_d2
def get_d2r_folder() -> str:
"""
Get D2r folder
try to find pre-set D2r folder
:param config: the general config possibly containing 'saved_games_folder'
... |
4880025 | import numpy as np
from . import pi
def get_bbox_type(bboxes, with_score=False):
dim = bboxes.shape[-1]
if with_score:
dim -= 1
if dim == 4:
return 'hbb'
if dim == 5:
return 'obb'
if dim == 8:
return 'poly'
return 'notype'
def get_bbox_dim(bbox_type, with_sco... |
4880110 | from fixtures.builder import FixtureBuilder
def build():
# Set up a repo using `path_hash_prefixes`, which is currently not supported.
fixture = FixtureBuilder('TUFTestFixtureUnsupportedDelegation')\
.create_target('testtarget.txt')\
.publish(with_client=True)
# Delegate to an unclaimed t... |
4880130 | from collections import deque
from itertools import chain, islice
def chunks(items, chunksize):
"""Turn generator sequence into sequence of chunks."""
items = iter(items)
for first in items:
chunk = chain((first,), islice(items, chunksize - 1))
yield chunk
deque(chunk, 0)
|
4880177 | from scrapy.http import HtmlResponse, Request
from twisted.internet.defer import inlineCallbacks
from twisted.spread import pb
from .cookies import sync_cookies
class _RemoteRequestCounter(pb.Referenceable):
def __init__(self, request):
super().__init__()
self._browser_request = request
def... |
4880194 | import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import supershape as sshape
import numpy as np
# Create shape
shape=(50,50)
with np.errstate(divide='raise'):
for i in range(500000):
params = np.random.uniform(
low =[0.00,1,1,0.0,0.0, 0.0],
high=[20.00,1,1,4... |
4880232 | import numpy as np
from menten_gcn.decorators.base import Decorator
class Sequence(Decorator):
"""
One-hot encode the canonical amino acid identity on each node.
- 20 Node Features
- 0 Edge Features
"""
def get_version_name(self):
return "Sequence"
def __init__(self):
... |
4880261 | r"""
Dependency checking
"""
import re
import types
from typing import Optional
from packaging.version import parse
from .utils import run_command
class Checker:
r"""
Checks availability and version of a dependency
Parameters
----------
name
Name of the dependency
cmd
Comm... |
4880294 | import numpy as np
import numpy.linalg as npl
def mgrid_to_points(mgrid):
"""
Takes a NxD1xD2xD3 meshgrid or tuple(meshgrid) and outputs a D1*D2*D3xN
matrix of coordinate points
"""
points = np.empty(shape=(np.prod(mgrid[0].shape), len(mgrid)),
dtype=mgrid[0].dtype)
for i... |
4880359 | from dataclasses import dataclass
from typing import Any
from coworks.config import Config as CwsConfig
@dataclass
class Config(CwsConfig):
environment_variables_file: str = "vars.json"
@dataclass
class LocalConfig(Config):
root: str = ''
workspace: str = 'local'
auth: Any = lambda _, __: True
@d... |
4880371 | from parameterized import parameterized
try:
import numpy as np
except ImportError:
np = None
from tests.numpy.testcase import NumpyBaseTestCase
class FloatTestCase(NumpyBaseTestCase):
n = 10
def check_result(self, rv, col_type):
self.assertArraysEqual(rv[0], np.array(range(self.n)))
... |
4880433 | from pyapacheatlas.core.entity import AtlasClassification
from pyapacheatlas.core.typedef import (
AtlasRelationshipEndDef, Cardinality,
ParentEndDef, ChildEndDef
)
import sys
sys.path.append('.')
def test_json_contract_atlas_classification():
typeName = "test"
entityStatus = "ACTIVE"
propagate = ... |
4880441 | import os
import numpy as np
import tensorflow as tf
def get_arrays(data_dir):
data = np.load(os.path.join(data_dir, "data-simplified.npz"))
try:
X_train = data["X_train"].astype(np.int32)
except: # For spitted large X_train, such as in Amazon_review_polarity
X_train_part1 = data["X_train_part1"].astyp... |
4880445 | import random
import numpy as np
import torch
from fastNLP.core import Trainer, Tester, AccuracyMetric, Const
from fastNLP.core.callback import WarmupCallback, EvaluateCallback
from fastNLP.core.optimizer import AdamW
from fastNLP.embeddings import BertEmbedding
from fastNLP.io.pipe.matching import SNLIBertPipe, RTEBe... |
4880531 | import os
import sys
from typing import Any, Tuple
import networkx as nx
def _import_graph_tool():
# Naively assume everything is set up try and see if can just be imported
try:
import graph_tool as gt
return gt
except ModuleNotFoundError:
pass
# Note: graph-tool installs to ... |
4880575 | from .base_graph_ql import BaseGraphQL
from .parser import Parser
class Story(BaseGraphQL):
def viewers_for(self, item_id):
variables = {
"item_id": item_id,
"story_viewer_fetch_count": 50,
"story_viewer_cursor": "0"
}
return self._loop("42c6ec100f5e57a... |
4880587 | from easy_py_server import EasyPyServer, Request, Response, MultipartFile, ResponseFile, ResponseConfig
eps = EasyPyServer('0.0.0.0', 8090, static_folder="www")
# method GET
@eps.get("/api")
def demo(a: int, b: int):
return dict(success=True, content="%d + %d = %d" % (a, b, a + b))
@eps.get("/test_bool")
def t... |
4880595 | from adapt.intent import IntentBuilder
from mycroft import MycroftSkill, intent_handler
from mycroft.util.log import LOG
import requests
class MyRobot(MycroftSkill):
def __init__(self):
super().__init__()
self.base_url = self.settings.get("base_url")
@intent_handler(IntentBuilder("")
... |
4880610 | import requests
def Nx():
try:
proxy = {
'http': 'http://baidu.com',
'https': 'http://baidu.com'
}
'''head 信息'''
head = {'User-Agent': 'User-Agent": "NCP/5.3.1 (iPhone; iOS 13.5; Scale/2.00)', 'Connection': 'keep-alive'}
# http://icanhazip.com
... |
4880616 | from ml.linear_regression import LinearRegression
# data
x = sorted([0.1, 2.3, 6.3, 9.2, 1.6, 2.3, 5.1, 7.2, 4.3, 1.5, 6.3, 8.9, 3.2, 3.5, 5.6])
y = list(map(lambda x: 0.3*x + 0.2, x))
l = LinearRegression()
l.fit(data=x, labels=y, graph=True)
|
4880634 | import htmlgenerator as hg
from django.contrib.messages.views import SuccessMessageMixin
from django.utils.translation import gettext as _
from django.views.generic import CreateView
from guardian.mixins import PermissionRequiredMixin
from ..utils import pretty_modelname
from .util import BreadView, CustomFormMixin
... |
4880636 | import json
import traceback
from flask import Response as FlaskResponse
class ValidationError(Exception):
pass
class HttpErrorBase(Exception):
status_code = None
default_message = None
def __init__(self, message=None, headers=None, code=None):
self.headers = headers if headers else {}
... |
4880637 | import re
from collections import defaultdict
from datetime import datetime, time
from io import BytesIO, StringIO
import scrapy
from city_scrapers_core.constants import BOARD
from city_scrapers_core.items import Meeting
from city_scrapers_core.spiders import CityScrapersSpider
from pdfminer.high_level import extract_... |
4880666 | from Crypto.Cipher import ChaCha20_Poly1305
from Crypto.Random import get_random_bytes
import base64
def base64Encoding(input):
dataBase64 = base64.b64encode(input)
dataBase64P = dataBase64.decode("UTF-8")
return dataBase64P
def base64Decoding(input):
return base64.decodebytes(input.encode("ascii"... |
4880671 | from django.db import models
from django.conf import settings
from django.urls import reverse
import photograph
import campi
class Directory(
campi.models.labeledModel,
campi.models.descriptionModel,
campi.models.userModifiedModel,
):
"""
A directory from the original image filesystem. Photographs... |
4880698 | n = int(input())
l = set()
for i in range(n):
l.add(input())
print("\n".join(sorted(l, key = lambda i : [len(i), i]))) |
4880709 | import pytest
import raccoon as rc
def test_sorted_exists():
a = [1, 2, 3, 6, 7, 8]
assert rc.dataframe.sorted_exists(a, 0) == (False, 0)
assert rc.dataframe.sorted_exists(a, 1) == (True, 0)
assert rc.dataframe.sorted_exists(a, 3) == (True, 2)
assert rc.dataframe.sorted_exists(a, 4) == (False, 3... |
4880778 | from django import forms
from pipeline.models import Action
class ActionChangeForm(forms.ModelForm):
fee = forms.IntegerField(required=False, label='Reward')
approvable = forms.BooleanField(required=False)
def __init__(self, **kwargs):
super().__init__(**kwargs)
instance = getattr(self, ... |
4880812 | import cv2
import numpy
from cimbar.util.geometry import calculate_midpoints
def next_power_of_two_plus_one(x):
return 2**((x - 1).bit_length()) + 1
# should be thought of as a line, not an area
class Anchor:
__slots__ = 'x', 'xmax', 'y', 'ymax'
def __init__(self, x, y, xmax=None, ymax=None):
... |
4880889 | from mpl_toolkits.basemap import Basemap
def get_Bgrid_proj(Bgrd, type='merc', resolution='h'):
"""
map = get_Bgrid_proj(Bgrd)
optional arguments:
- type set projection type (default is merc)
- resolution set resolution parameter (default is high)
return a Basemap object tha... |
4880932 | import logging
from time import clock
import numpy as np
from scipy.optimize import minimize
from theano import function, gof, shared, config
import theano.tensor as T
from mle.util import memoize
__all__ = ['Model']
class Model(object):
def __init__(self):
self.exprs = dict()
self.submodels = ... |
4880938 | import base64
import os
from algosdk import *
from algosdk.logic import get_application_address
from algosdk.future.transaction import *
from algosdk.v2client import algod
from algosdk.v2client.models import DryrunRequest, DryrunSource
from sandbox import get_accounts
token = "<KEY>"
url = "http://localhost:4001"
... |
4880959 | from unittest import TestCase
from jumpscale.loader import j
import os
class TestIdentity(TestCase):
def setUp(self):
self.instance_name = j.data.random_names.random_name()
self.me = None
if j.core.identity.list_all() and hasattr(j.core.identity, "me"):
self.me = j.core.identit... |
4880980 | import os
import sys
import glob
from PIL import Image
from tqdm import tqdm
DATASETS = ['IC15', 'IC13',
'HRSC2016', 'DOTA', 'UCAS_AOD', 'NWPU_VHR' ,
'GaoFenShip', 'GaoFenAirplane',
'VOC']
def bmpToJpg(file_path):
for fileName in tqdm(os.listdir(file_path)):
newFileName... |
4880992 | from logging import getLogger
from django.conf import settings
from django.utils.six import text_type
from api.api_views import APIView
# noinspection PyProtectedMember
from api.fields import get_boolean_value
from api.exceptions import NodeIsNotOperational, PreconditionRequired, ObjectNotFound, GatewayTimeout
from a... |
4881002 | import server
import tangelo
tangelo.log("Plugin has value server.TestConstant %s" % str(server.TestConstant))
|
4881033 | from boa3.builtin import public
@public
def Main() -> bytearray:
a = bytearray(b'\x01\x02\x03')
a.extend(b'\x04\x05\x06')
return a
|
4881068 | import asyncio
from datetime import datetime
import pytest
from env_canada import ec_hydro, ECHydro
def test_get_hydro_sites():
sites = asyncio.run(ec_hydro.get_hydro_sites())
assert len(sites) > 0
@pytest.mark.parametrize(
"init_parameters",
[{"coordinates": (50, -100)}, {"province": "ON", "stati... |
4881122 | import os
from countryinfo import CountryInfo
from pyrogram import Client, filters
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, InlineQueryResultArticle, InputTextMessageContent
from .database import db
START_TEXT = """Hello {} 😌
I am a country information finder bot.
>> `I can find inform... |
4881130 | class OddEven:
def __init__(self, data):
self._data = data
self.indexes = (list(range(0, len(data), 2)) +
list(range(1, len(data), 2)))
def __iter__(self):
return self
def __next__(self):
if self.indexes:
return self._data[self.indexes.pop(0)]
... |
4881184 | import re
import cv2
import time
from copy import deepcopy
from src.utils.utils import *
class Station:
def __init__(self):
self.station_index = 0
self.station_box = 0
self.station_node = 0
self.processing_count = 1000
self.is_free = 1
self.counter = 0
self.... |
4881210 | import json
import pytest
import time
from fhir.resources.bundle import Bundle
from .conftest import DB_NAME
# These tests assumes an already existing store exists
# (store.bootstrap was run)
RESOURCES_TOTAL_COUNT = 702
STRUCTUREDEF_TOTAL_COUNT = 649
@pytest.fixture(scope="module")
def index_bundles(store):
... |
4881241 | from __future__ import print_function
# -*- coding: utf-8 -*-
# %run py_eddy_tracker_property_classes.py
"""
===========================================================================
This file is part of py-eddy-tracker.
py-eddy-tracker is free software: you can redistribute it and/or modify
it under the te... |
4881253 | from .accuracy import Accuracy
from .metric_bundle import MetricBundle
def create_metric_bundle(metrics):
metric_bundle = MetricBundle([metric() for metric in metrics])
return metric_bundle
|
4881262 | import pytest
import tidyms as ms
def test_class_remover(data_container_with_order):
rm = ["QC"]
data = data_container_with_order
n_qc_samples = (data.sample_metadata["class"] == 'QC').sum()
n_samples = data.data_matrix.shape[0]
crm = ms.filter.ClassRemover(rm)
crm.process(data)
assert da... |
4881293 | import collections
_REGISTRY = collections.defaultdict(dict)
def build_register_decorator(_type):
type_registry = _REGISTRY[_type]
def register_type(key):
def inner(fn):
type_registry[key] = fn
return fn
return inner
return register_type
def build_make_functio... |
4881312 | from __future__ import absolute_import
from frontera.contrib.backends.sqlalchemy.components import Metadata, Queue, States, DomainMetadata
from frontera.contrib.backends.sqlalchemy.models import DeclarativeBase
from frontera.core.components import DistributedBackend
from frontera.utils.misc import load_object
from sql... |
4881328 | from __future__ import division, unicode_literals, print_function, absolute_import
from podpac.core.cache import cache_ctrl
import traitlets as tl
from copy import deepcopy
from collections import OrderedDict
from six import string_types
import logging
import traitlets as tl
import numpy as np
from podpac.core.setti... |
4881417 | from typing import Dict
from segtypes.n64.palette import N64SegPalette as Palette
from segtypes.n64.ci8 import N64SegCi8 as Raster
from segtypes.common.group import CommonSegGroup
# Resolve Raster#palette and Palette#raster links
def initialize(all_segments):
global palettes_remaining
def process(segments):
... |
4881437 | from tir import Webapp
import unittest
from datetime import datetime
import string
import random
class PCOA170(unittest.TestCase):
@classmethod
def setUpClass(inst):
inst.oHelper = Webapp()
inst.oHelper.Setup('SIGAPCO', '08/04/2020', 'T1', 'D MG 02 ')
inst.oHelper.Program('PCOA170')
... |
4881498 | from .download_utils import download_decorator, download_file
from .main_utils import import_module
from .lib_decorators import get_from_config, expand_input, get_elapsed_time, rgb2bgr, cast_kwargs_dict
from .decorators import get_method_time, get_func_time
|
4881508 | import inspect
from rest_framework.serializers import BaseSerializer
from rest_framework.compat import View
from jinja2 import contextfunction, FileSystemLoader, Environment
from .config import VERSION, EXACT_VERSION
templateLoader = FileSystemLoader(searchpath="templates")
templateEnv = Environment(loader=templateL... |
4881512 | favorite_languages={
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python',
}
for nombre, lenguaje in favorite_languages.items():
print("El lenguaje favorito de "+nombre.title()+" es "+lenguaje.title())
|
4881634 | import info
class subinfo(info.infoclass):
def setTargets(self):
arch = "x86"
if CraftCore.compiler.isX64():
arch = "x64"
self.targets['2.2'] = 'http://www.dependencywalker.com/depends22_' + arch + '.zip'
self.targetInstallPath['2.2'] = "dev-utils/bin"
self.defa... |
4881653 | from django.conf.urls import patterns, url
urlpatterns = patterns('pinry.pins.views',
url(r'^user/all/$', 'recent_pins', name='recent-pins'),
url(r'^user/all/.+?/$', 'recent_pins', name='taged-pins'),
url(r'^user/$', 'recent_pins', name='user'),
url(r'^pin/(?P<pinId>\d+)/$', 'pin_detail', name='pin-de... |
4881665 | from rasa.shared.core.slots import Slot
class TableSlot(Slot):
type_name = "table"
def _feature_dimensionality(self):
return 3
def _as_feature(self):
r = [0.0] * self._feature_dimensionality()
if self.value:
if self.value <= 4:
r[0] = 1.0
e... |
4881727 | import cv2 as cv
import numpy as np
img = cv.imread("number.png")
gray_img = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
# 降噪
ret, thresh = cv.threshold(gray_img, 127, 255, 0)
# 寻找轮廓
contours, hierarchy = cv.findContours(gray_img, cv.RETR_TREE, cv.CHAIN_APPROX_NONE)
cnt = contours[0]
# 外接正矩形
x, y, w, h = cv.boundingRect(cn... |
4881737 | from recaptcha_solver import RecaptchaSolver
import signal
if __name__ == "__main__":
signal.signal(signal.SIGINT, signal.SIG_DFL)
rcs = RecaptchaSolver("https://www.google.com/recaptcha/api2/demo")
recaptcha_token = rcs.solve() |
4881787 | def partition(array, start, end):
pivot = array[start]
low = start + 1
high = end
while True:
# If the current value we're looking at is larger than the pivot
# it's in the right place (right side of pivot) and we can move left,
# to the next element.
# We also need to m... |
4881796 | import torch
import librosa as libr
import numpy as np
class ToMFCC:
'''
Transformation to convert soundfile loaded via LibriSpeechDataset to Mel-
frequency cepstral coefficients (MFCCs)
Args:
number_of_mels: Number of bins to use for cepstral coefficients
Returns:
torch.float tensor
... |
4881799 | import numpy as np
import pyturb.utils.constants as cts
import pyturb.utils.units as units
from pyturb.gas_models.perfect_ideal_gas import PerfectIdealGas
from pyturb.gas_models.thermo_properties import ThermoProperties
print('tests_1')
print('-----------------')
#print(cts.Ru, units.m_to_nm)
#print()
#tp = ThermoPrope... |
4881812 | from __future__ import absolute_import, division, print_function
import signal
from contextlib import contextmanager
class TimeoutError(Exception):
pass
@contextmanager
def timeout(seconds):
def signal_handler(signum, frame):
raise TimeoutError("Timed out!")
if seconds > 0:
signal.sign... |
4881865 | import os
import json
from jumbo.core import nodes
from jumbo.utils import exceptions as ex, session as ss
from jumbo.utils.settings import JUMBODIR
from jumbo.utils.checks import valid_cluster
def load_services_conf():
"""Load the global services configuration.
:return: The configuration JSON file
:rty... |
4881946 | from django.forms import models, fields
class AdvancedModelChoiceIterator(models.ModelChoiceIterator):
def choice(self, obj):
return self.field.prepare_value(obj), self.field.label_from_instance(obj), obj
class AdvancedSelectMultiple(models.ModelMultipleChoiceField):
def _get_choices(self):
... |
4881947 | import threading
class StoppableThread(threading.Thread):
"""Thread with an event object to stop itself.
Args:
stop_event (threading.Event): Event that stops the thread if it is set.
*args, **kwargs: Forwarded to `threading.Thread`.
"""
def __init__(self, stop_event, *args, **kwargs)... |
4881989 | from .lsp_client import ServerClient, WorkerClient
from .service_proxy import ServiceProxy
from .logger import log
import json
import threading
try:
from Queue import Queue
except ImportError:
from queue import Queue # python 3.x
class LspClientManager():
def __init__(self):
self.client_mapping... |
4882021 | from __future__ import absolute_import, division, print_function, unicode_literals
from collections import defaultdict, OrderedDict
import numpy as np
import chronic
from ase import Atoms
from ase.data import covalent_radii
from ase.io import write
import matid.geometry
from matid.data import constants
import netw... |
4882023 | print("""IF YOU SEE THIS MESSAGE YOU DID NOT PROPERLY INSTALL THE SNIPER.
THE VIDEO / WRITTEN GUIDE YOU WERE FOLLOWING WAS OUT OF DATE
GO TO THE README @ https://mcsniperpy.com/git AND FOLLOW THE INSTRUCTIONS THERE""")
input("")
|
4882051 | import pickle
import logging
import attr
@attr.s
class PickleGateway(object):
"""
Simple read/write handler for pickle files
"""
fp = attr.ib()
def read(self):
logging.debug("Reading")
try:
with open(self.fp, "rb") as f:
items = pickle.load(f)
... |
4882086 | import pytest
import datetime
from unittest import mock
from django.utils import timezone
from share.celery import TaskResultCleaner, CeleryTaskResult
from tests import factories
@pytest.mark.django_db
class TestResultArchiver:
@pytest.fixture(autouse=True)
def task_result_data(self):
return fact... |
4882088 | class Solution(object):
def numDupDigitsAtMostN(self, N):
"""
:type N: int
:rtype: int
"""
# given number n, see whether n has repeated number
def has_repeated(n):
str_n = str(n)
return len(set(str_n)) != len(str_n)
def pe... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.