text stringlengths 1 927k |
|---|
# Copyright 2019 Open Source Robotics Foundation, 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... |
from __future__ import print_function, division
import re
import sys
import numpy as np
import scipy.sparse
import codecs
from sklearn.decomposition import PCA
if sys.version_info[0] < 3:
import io
open = io.open
else:
unicode = str
"""
Tools for debiasing word embeddings
Man is to Computer Programmer as W... |
import numpy as np
import inspect
from lumopt.geometries.geometry import Geometry
class ParameterizedGeometry(Geometry):
"""
Defines a parametrized geometry using any of the built-in geometric structures available in the FDTD CAD.
Users must provide a Python function with the signature ('params',... |
from functools import partial
from itertools import count
from typing import List
from tutils import lmap, splitstrip, load_and_process_input
DAY = "15"
INPUT = f"input-{DAY}.txt"
ANSWER1 = 240
ANSWER2 = 505
testdata = [
([0, 3, 6], 2020, 436),
([1, 3, 2], 2020, 1),
([2, 1, 3], 2020, 10),
([1, 2, 3], 2... |
"""integration tests for BridgeDB ."""
from __future__ import print_function
import smtplib
import asyncore
import threading
import queue
import random
import os
from smtpd import SMTPServer
from twisted.trial import unittest
from twisted.trial.unittest import FailTest
from twisted.trial.unittest import SkipTest
f... |
import numpy as np
import struct
# CMU Sphinx 4 mfc file opener
# takes file path as input
# Sphinx uses feature vectors of length 13 by default
def run(input, featureVectorSize):
file = open(input, 'r')
size = struct.unpack('>i', ''.join(file.read(4)))[0]
if ((float)(size)) / featureVectorSize - (float)(size // fe... |
#!/usr/bin/env python3
# Copyright (c) 2017-2019 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Combine logs from multiple techcoin nodes as well as the test_framework log.
This streams the combined... |
import click
from .current import current
from .update import update
__all__ = [
'build'
]
@click.group(help='Manage tool versions.')
def versions() -> None:
pass
def build(cmd: click.Group) -> None:
"""親コマンドにサブコマンドを追加する。
Args:
cmd (click.Group): 親コマンド
"""
versions.add_command(cu... |
import numpy as np
# import plotly
import plotly.graph_objects as go
def draw_plotly_half_court(fig, fig_width=600, margins=10):
# From: https://community.plot.ly/t/arc-shape-with-path/7205/5
def ellipse_arc(x_center=0.0, y_center=0.0, a=10.5, b=10.5, start_angle=0.0, end_angle=2 * np.pi, N=200, closed=False... |
from django.urls import path
from .views import (
CategoriasListView, pagina_principal,
CuestionarioListView, cuestionario_vista, cuestionario_datos,
guardar_resultados, resultado, nuevo_cuestionario, editar_cuestionario, eliminar_cuestionario, nueva_pregunta, nueva_respuesta, agregar_categoria,
)
url... |
# Copyright 2021 (David) Siu-Kei Muk. 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 applicable... |
# encoding=utf-8
import sys
from imp import reload
reload(sys)
# sys.setdefaultencoding('utf8')
import os, time
# from configure import config
from datetime import datetime as dt
import requests
# requests.adapters.DEFAULT_RETRIES = 5
# import chardet
class HttpSpider:
headers = {
# 'User-Agent':'Mozi... |
from __future__ import annotations
import json
from dataclasses import dataclass, field
from math import inf, sqrt
from queue import PriorityQueue
from typing import Any, Callable, Collection, TYPE_CHECKING, Iterable, Literal
from bitarray import bitarray
from turing_complete_interface.circuit_parser import Circuit,... |
import logging
import os
import re
from itertools import groupby
from pathspec.patterns import GitWildMatchPattern
from pathspec.util import normalize_file
from pygtrie import StringTrie
from dvc.path_info import PathInfo
from dvc.pathspec_math import merge_patterns
from dvc.system import System
from dvc.utils import... |
import os
from functools import wraps
from flask import flash, redirect, render_template, url_for, current_app, Markup, request
from flask_login import login_user, login_required, logout_user, current_user
from app.auth import bp
from app.auth.forms import SignUpForm, RegistrationForm, LoginForm, ResetPasswordForm, New... |
#!/home/catskills/anaconda3/envs/xview2/bin/python
import glob, os
from shutil import copyfile
from tqdm import tqdm
from subprocess import call
from IPython.utils.path import ensure_dir_exists
# os.environ["CUDA_VISIBLE_DEVICES"]="1" # second gpu
VERSION=os.getenv('VERSION')
PROJECT='xview2-catskills'
USERDIR='/home... |
# coding: utf-8
"""
Hydrogen Integration API
The Hydrogen Integration API # noqa: E501
OpenAPI spec version: 1.2.1
Contact: info@hydrogenplatform.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class BaasSubAccountVO(... |
from typing import Optional
import torch
import torch.nn as nn
from torch.nn.utils import spectral_norm
import numpy as np
def get_generator(latent_size: int, use_spectral_norm: bool) -> nn.Module:
"""
Returns the generator network.
:param latent_size: (int) Size of the latent input vector
:param use... |
from . import lexer
from .parseRoll import parser
def roll(expression : str):
"Runs the dice expression provided and returns long form result"
try:
tree = parser.parse(expression)
result, hist = tree.roll()
except Exception as E:
return str(E)
return result, hist, tree
de... |
from machine import Pin, Timer
def check_sensor(timer):
global sensor
if sensor.value() == 1:
gp1.value(1)
else:
gp1.value(0)
#GP4 - 5v output
gp4 = Pin(4,Pin.OUT)
gp4.value(1)
#GP1 - output for LED
gp1= Pin(1,Pin.OUT)
#GP5 - input from sensor
sensor = Pin(5,Pin.IN)
tim = Timer()
tim.init(... |
'''
Created on 04-Feb-2017
@author: vijay
'''
keyword = [
'ABORT'
, 'ACTION'
, 'ADD'
, 'AFTER'
, 'ALL'
, 'ALTER'
, 'ANALYZE'
, 'AND'
, 'AS'
, 'ASC'
, 'ATTACH'
, 'AUTOINCREMENT'
, 'BEFORE'
, 'BEGIN'
, 'BETWEEN'
, 'BY'
, 'CASCADE'
, 'CASE'
, 'CAST'
, 'CHECK'
, 'COLLATE'
, 'COLUMN'
, 'COMMIT'
, 'CONFLICT'
, 'C... |
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 07 21:00:11 2017
@author: galad-loth
"""
import numpy as npy
import mxnet as mx
class HashLossLayer(mx.operator.NumpyOp):
def __init__(self, w_bin,w_balance):
super(HashLossLayer, self).__init__(False)
self.w_bin=w_bin
self.w_balance=w_balance... |
from plotly_study.basedatatypes import BaseLayoutHierarchyType as _BaseLayoutHierarchyType
import copy as _copy
class Title(_BaseLayoutHierarchyType):
# font
# ----
@property
def font(self):
"""
Sets this axis' title font. Note that the title's font used to
be customized by th... |
import os
import pytest
import numpy as np
from pandas.compat import zip
from pandas import (Series, isna, to_datetime, DatetimeIndex,
Timestamp, Interval, IntervalIndex, Categorical,
cut, qcut, date_range)
import pandas.util.testing as tm
from pandas.api.types import Categoric... |
# Generated by Django 3.0.6 on 2020-06-30 04:54
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app1', '0028_resources_resource_date_time'),
]
operations = [
migrations.AlterField(
model_name='resources',
... |
"""HALO Home integration tests.""" |
import json
from pathlib import Path
from pprint import pprint
import re, os
from time import sleep
class StatsFile:
def __init__(self, file_path):
self.current_offset = 0
self.file_size = 0
self.file_path = file_path
self.cached_stats = {}
self.backup_file_path = file_path.... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-03-23 19:21
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("shop", "0037_auto_20170319_2204")]
operations = [
migrations.AlterField(
mod... |
from typing import Tuple
import torch
import triton
import triton.language as tl
def rz_linear_backward_tl(input: torch.tensor, hashed_weight: torch.tensor, output_grad: torch.tensor,
M: int, K: int, N: int, H: int,
R3: int, R2: int, R1: int, R0: int,
... |
#!/usr/bin/env python3
import torch
import unittest
from gpytorch.lazy import NonLazyTensor, DiagLazyTensor, AddedDiagLazyTensor
from test.lazy._lazy_tensor_test_case import LazyTensorTestCase
class TestAddedDiagLazyTensor(LazyTensorTestCase, unittest.TestCase):
seed = 0
should_test_sample = True
def cr... |
# 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 applicable law or agreed to in... |
import os
import torch
import torch.nn as nn
from collections import deque
from onmt.utils.logging import logger
from copy import deepcopy
def build_model_saver(model_opt, opt, model, fields, optim):
model_saver = ModelSaver(opt.save_model,
model,
model_... |
"""
WSGI config for CTForces project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.0/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETT... |
'''
Created on Jul 27, 2016
@author: zehemz
'''
from lxml import html
from lxml import etree
from io import StringIO, BytesIO
from copy import deepcopy
import requests
import re
import pickle
def writeList(list):
file = open("websScrapeadas.txt", "wb")
for element in list:
file.write(element+ '\n')
... |
from routes.band import write_comment
class Help:
def __init__(self, get_all_post):
self.get_all_post = get_all_post
self.help_information()
def help_information(self):
get_all_post = self.get_all_post
post_response_content = get_all_post['result_data']['items']
for i... |
import copy
from typing import Any, MutableMapping, MutableSequence, Union
from .data import DataGetValue, Data, BaseData
from .exception import InvalidOperationError
class DataBuilder:
def build_prop(self, data: Union[MutableMapping, MutableSequence], key: Any) -> None:
"""
Cleanup instances of ... |
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'blogsrc.settings')
try:
from django.core.management import execute_from_command_line
except Impo... |
#------------------------------------------------------------------------------
# Copyright (c) 2013, Nucleic Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-------------------------------------------------... |
# -*- coding: utf-8 -*-
import json
import os.path
from robot.api import logger
from robot.api.deco import keyword
from jsonpath_rw import Index, Fields
#from jsonpath_rw_ext import parse
from jsonpath_ng.ext import parse
from .version import VERSION
__author__ = 'Traitanit Huangsri'
__email__ = 'traitanit.hua@gmail.c... |
import datetime
import os
import re
import yaml
from pathlib import Path
from plugin.patterns import WIKI_LINK, MD_LINK
from plugin.gitutil import GitUtil
class Zettel:
def __init__(self, abs_src_path):
self.id = 0
self.title = ""
self.path = abs_src_path
self.backlinks = []
... |
# -*- coding: utf-8 -*-
# @Author : William
# @Project : TextGAN-william
# @FileName : data_loader.py
# @Time : Created at 2019-05-31
# @Blog : http://zhiweil.ml/
# @Description :
# Copyrights (C) 2018. All Rights Reserved.
import random
from torch.utils.data import Dataset, DataLoader... |
import _plotly_utils.basevalidators
class FamilyValidator(_plotly_utils.basevalidators.StringValidator):
def __init__(
self,
plotly_name='family',
parent_name='mesh3d.colorbar.tickfont',
**kwargs
):
super(FamilyValidator, self).__init__(
plotly_name=plotly_... |
def radsort(unslist):
"""Returns a sorted list. Accepts only a list containing positive
integers."""
# find max for iterative solution
maxval = max(unslist)
ntimes = len(str(maxval))
slist = unslist[:]
for n in range(ntimes):
# Making radix bins
bins = [[] for _ in range(10... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from typing import Dict
import torch
from detectron2.layers import ShapeSpec, cat
from detectron2.modeling import ROI_HEADS_REGISTRY
from detectron2.modeling.poolers import ROIPooler
from detectron2.modeling.roi_heads.fast_rcnn import FastRCNNOutput... |
#!/usr/bin/env/python
import yaml
import json
from pprint import pprint
def output_format(my_list, my_str):
# Make the output format easier to read
# '''
print "Converting from " , my_str ,"FORMAT"
print "#" * 30
pprint (my_list)
def main():
#my_dict={'karim':'32','yasmine':'26','amine'... |
"""
This module exposes CyberGISCompute class which creates a CyberGISCompute
object that serves as an entry point to the CyberGISX environment from a Python/Jupyter notebook.
All interactions with the High Performance Computing (HPC) backend are performed using this object.
Example:
cybergis = CyberGISCompute... |
# Copyright (C) 2020 Intel Corporation
#
# SPDX-License-Identifier: MIT
from cvat.apps.dataset_manager.annotation import TrackManager
from unittest import TestCase
class TrackManagerTest(TestCase):
def _check_interpolation(self, track):
interpolated = TrackManager.get_interpolated_shapes(track, 0, 7)
... |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('course_modes', '0007_coursemode_bulk_sku'),
('bulk_email', '0005_move_target_data'),
]
operations = [
migrations.CreateModel(
name='CourseModeTarget',
fields... |
class UserModel:
def __init__(self, name = None, login = None, password = None):
self.id = None
self.name = name
self.login = login
self.password = password |
from django.conf.urls import include
from django.urls import path
from django.contrib import admin
urlpatterns = [
path('', include('chat.urls')),
path('admin/', admin.site.urls),
] |
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
from itertools import product
import os
from mpl_toolkits.axes_grid1 import make_axes_locatable
from matplotlib import ticker, cm
from mpl_toolkits.axes_grid1 import make_axes_locatable
from matplotlib.ticker import FormatStrFormatter
from matplot... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: mesh/v1alpha1/config.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf.internal import enum_type_wrapper
from google.protobuf import descriptor as _descriptor
from... |
# 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 logging
from typing import List, Optional
import torch.nn as nn
import torch.nn.functional as F
logger = logging.getLogger(__name__)... |
#!/usr/bin/env python3
# Copyright (c) 2015-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# Test new Atixcoin multisig prefix functionality.
#
from test_framework.test_framework import Bitcoin... |
from tfchain.polyfill.encoding.jsmods.ipaddrjs import api as ipaddrjs
import tfchain.polyfill.array as jsarr
class IPAddress:
def __init__(self, value):
if isinstance(value, str):
v = None
err = None
__pragma__("js", "{}", """
try {
v = ipaddr... |
import numpy as np
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
# ----------------------------------------------------------------------------------
# Commonly used layers and operations based on ethereon's implementation
# https://github.com/ethereon/caffe-tensorflow
# Slight modifications may apply. F... |
from flask import Flask
from config import Config
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login import LoginManager
app = Flask(__name__)
app.config.from_object(Config)
db = SQLAlchemy(app)
migrate = Migrate(app, db)
login = LoginManager(app)
login.login_view = 'login'
f... |
###############################################################################
#
# Tests for XlsxWriter.
#
# Copyright (c), 2013-2021, John McNamara, jmcnamara@cpan.org
#
from ..excel_comparison_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompareXLSXFiles(ExcelComparisonTest):
"""... |
"""
@brief test log(time=10s)
"""
import os
import sys
import unittest
from pyquickhelper.loghelper import fLOG
from pyquickhelper.pycode import get_temp_folder, is_travis_or_appveyor
try:
import src
except ImportError:
path = os.path.normpath(
os.path.abspath(
os.path.join(
... |
import datetime as dt
from django.core.cache import cache
from django.utils import translation
from django.utils.timezone import now
from parler import appsettings
from .utils import AppTestCase, override_parler_settings
from .testapp.models import SimpleModel, DateTimeModel
class QueryCountTests(AppTestCase):
... |
# Copyright 1996-2021 Cyberbotics Ltd.
#
# 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... |
# coding=utf-8
# Copyright 2018 The HuggingFace Inc. team.
#
# 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 unittest
from pathlib import Path
import re
import tempfile
import d2vg
class ParserTest(unittest.TestCase):
def test_text_file(self):
with tempfile.TemporaryDirectory() as tempdir:
p = Path(tempdir) / "a.txt"
content = "1st line.\n2nd line.\n"
p.write_text(con... |
# Generated by Django 3.1.5 on 2021-03-05 05:59
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0007_auto_20210305_0539'),
]
operations = [
migrations.AddField(
model_name='post',
name='snippet',
... |
#1.
class LR_LinearDecay():
'''
Function : -Learning rate decay linearly(a constant factor) after each epoch
-Eg. LR= 5, 5.8, 5.6, 5.4, ........
'''
def __init__(self, min_lr=1e-5, max_lr=1e-2, epochs=None):
super().__init__()
self.min_lr = min_lr
s... |
# coding: utf-8
import pytest
import mock
import workdays
import datetime
import dmutils.dates as dates_package
class TestPublishingDates():
def test_get_publishing_dates_formats_time(self):
with mock.patch('dmutils.dates.datetime') as mock_date:
mock_date.utcnow.return_value = datetime.dateti... |
# coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and DMLC.
#
# 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 req... |
# flake8: noqa
from .analysis import add_airline_info, clean_vector
from .database import Database
from .openflights import fetch_reference_data
from .opensky import fetch_live_aircraft_data
from .position import Area, Position, bounding_box |
# Copyright 2021 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... |
import argparse
import logging
from logging.handlers import RotatingFileHandler
from dquant.datafeed import Datafeed
class EntryPoint:
datafeed = None
def exec_command(self, args ):
logging.debug('exec_command:%s' % args)
if "feed" in args.command:
self.datafeed = Datafeed()
... |
# -*- coding: utf-8 -*-
import os
import sys
import functools
DATABASE_FILE = "version"
def MakeDirs(dirname):
dirname = os.path.abspath(dirname)
dirname = dirname.replace("\\","/")
dirnames = dirname.split("/")
destdir = ""
destdir = os.path.join(dirnames[0] + "/",dirnames[1])
if not os.p... |
# -*- coding: utf-8 -*-
# Copyright (c) 2021, libracore AG and Contributors
# See license.txt
from __future__ import unicode_literals
# import frappe
import unittest
class TestCustomerStatus(unittest.TestCase):
pass |
"""Some nn utilities."""
import torch
from abstract import ParametricFunction
def copy_buffer(net: ParametricFunction, target_net: ParametricFunction):
"""Copy all buffers from net to target_net."""
with torch.no_grad():
for target_buf, buf in zip(target_net.buffers(), net.buffers()): # type: ignore
... |
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django import forms
from .models import *
class RegisterForm(UserCreationForm):
email = forms.EmailField()
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
... |
from cms.admin.dialog.forms import get_copy_dialog_form
from django.shortcuts import render_to_response, get_object_or_404
from django.contrib.admin.views.decorators import staff_member_required
from django.http import Http404, HttpResponse
from django.conf import settings
from cms.models import Page
@staff_member_req... |
from unittest.mock import MagicMock
import pytest
from gb_chat.db.user_history_storage import UserHistoryStorage
from gb_chat.db.user_storage import (InvalidName, InvalidPassword, UserExists,
UserNotFound, UserStorage)
from conftest import VALID_PASSWORD, VALID_USERNAME
@pytest.... |
import subprocess
import sys
import os
from io import StringIO, BytesIO
import dnaio
import pytest
from cutadapt.__main__ import main
from utils import assert_files_equal, datapath, cutpath
# pytest.mark.timeout will not fail even if pytest-timeout is not installed
try:
import pytest_timeout as _unused
except Im... |
import unittest
import pytest
import cupy
import cupyx
class TestSyncDetect(unittest.TestCase):
def test_disallowed(self):
a = cupy.array([2, 3])
with cupyx.allow_synchronize(False):
with pytest.raises(cupyx.DeviceSynchronized):
a.get()
def test_allowed(self):
... |
s=input();f=True
try:
while s!="":
if s[0]=="p":
t=s[:2]
if t=="pi":
s=s[2:]
else:
f=False; break
elif s[0]=="k":
t=s[:2]
if t=="ka":
s=s[2:]
else:
f=False; break
... |
# generated from catkin/cmake/template/pkg.context.pc.in
CATKIN_PACKAGE_PREFIX = ""
PROJECT_PKG_CONFIG_INCLUDE_DIRS = "".split(';') if "" != "" else []
PROJECT_CATKIN_DEPENDS = "".replace(';', ' ')
PKG_CONFIG_LIBRARIES_WITH_PREFIX = "".split(';') if "" != "" else []
PROJECT_NAME = "check_obstacle"
PROJECT_SPACE_DIR = "... |
# Copyright (c) 2022 PaddlePaddle 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 appli... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Train the language model on texts from the file pride And Prejudice. Before using it to train the language model,
you need to first sentence segment, then tokenize, then lower case each line of the file using Spacy. Append
start-of-sentence token ’<s>’ and end-of-sent... |
# Generated by Django 3.2.5 on 2021-09-08 01:39
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('AssetsApp', '0009_alter_assetscategories_datetime_added'),
]
operations = [
migrations.AlterField(
model_name='a... |
import urllib.request
import urllib.parse
import urllib.error
import string
import requests
import time
import random
from Jumpscale import j
JSConfigClient = j.application.JSBaseConfigClass
class OauthClient(JSConfigClient):
_SCHEMATEXT = """
@url = jumpscale.oauth.client
name* = "" (S)
... |
"""
Copyright (c) Microsoft Corporation.
Licensed under the MIT license.
precompute hidden states of CMLM teacher to speedup KD training
"""
import argparse
import io
import os
import shelve
import numpy as np
import torch
from torch.utils.data import Dataset, DataLoader
from tqdm import tqdm
from pytorch_pretrained_... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
t = int(input().strip())
for i in range(t):
n,c,m = input().strip().split(' ')
n,c,m = [int(n),int(c),int(m)]
tot_choc=n//c
wrap=tot_choc
#print(tot_choc, wrap)
while wrap >= m:
extra_choc = wrap//m
wrap-=m*extra_choc
wrap+=extra_choc
tot_choc+= extra_choc
pri... |
from cereal import car
from common.numpy_fast import clip
from selfdrive.car import apply_std_steer_torque_limits
from selfdrive.car.hyundai.hyundaican import create_lkas11, create_clu11, create_lfa_mfa, \
create_scc11, create_scc12, create_mdps12, \
... |
import numpy as np
from filter import movingaverage
def gentrends(x, window=1/3.0, charts=True):
"""
Returns a Pandas dataframe with support and resistance lines.
:param x: One-dimensional data set
:param window: How long the trendlines should be. If window < 1, then it
will be take... |
import itertools
import logging
import os
import textwrap
from typing import List
import numpy as np
import pandas as pd
import requests
from bs4 import BeautifulSoup
from gamestonk_terminal.decorators import log_start_end
from gamestonk_terminal.helper_funcs import (
export_data,
patch_pandas_text_adjustment... |
# The small linear cone program of section 8.1 (Linear cone programs).
from cvxopt import matrix, solvers
c = matrix([-6., -4., -5.])
G = matrix([[ 16., 7., 24., -8., 8., -1., 0., -1., 0., 0., 7.,
-5., 1., -5., 1., -7., 1., -7., -4.],
[-14., 2., 7., -13., -18., 3., 0., 0.,... |
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from builtins import range
import os
import shutil
import tempfile
import unittest
import mock
from stacker.context import Context, Config
from stacker.dag import walk
from stacker.util import stack_template_k... |
from pathlib import Path
import django_heroku
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: ... |
#!/usr/bin/env python
"""
Mark the start and end of the prompt with Final term (iterm2) escape sequences.
See: https://iterm2.com/finalterm.html
"""
from __future__ import unicode_literals
from prompt_toolkit import prompt
from prompt_toolkit.token import Token
import sys
BEFORE_PROMPT = '\033]133;A\a'
AFTER_PROMPT ... |
# Copyright 2007-2017 UShareSoft SAS, 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 ads
ads.config.token = 'my token'
import numpy as np
# Filenames
## Enter the filename for first-author publications here:
first_author = "first_author.bib"
## Enter the filename for cd-authored publications here:
co_author = "co_author.bib"
# Function Declarations
def extract_bibcodes(filename):
"""Tak... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import unittest
try:
from itertools import zip_longest
except ImportError:
from itertools import izip_longest as zip_longest
from paka.breadcrumbs import Bread, Crumb
class BreadcrumbsTest(unittest.TestCase):
def setUp(self):
self... |
#!/usr/bin/env python
"""An in memory database implementation used for testing."""
import sys
import threading
from grr_response_core.lib import rdfvalue
from grr_response_core.lib import utils
from grr_response_server import db
from grr_response_server.databases import mem_blobs
from grr_response_server.databases i... |
from duckduckgo import query, Topic
from sys import argv
visited = []
def build_web_tree(qr, depth=0):
print ' '* depth * 4 + qr
ds = query(qr)
if depth == 2:
return
if ds.error_code != 0:
return
visited.append(qr)
if ds.related == []:
return
else:
for r ... |
"""add default value to is_invited
Revision ID: 51387d8fda8d
Revises: 6779bebb64e6
Create Date: 2021-12-21 18:19:50.864781
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '51387d8fda8d'
down_revision = '6779bebb64e6'
branch_labels = None
depends_on = None
def... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.