text stringlengths 2 999k |
|---|
from src.function import generate_random_names
def test_generate_random_names():
names = generate_random_names(12)
assert len(names.split(",")) == 12
|
#! -*- coding: utf-8 -*-
# 代码合集
import six
import logging
import numpy as np
import re
import sys
from collections import defaultdict
import json
import tensorflow as tf
from bert4keras.backend import K, keras
_open_ = open
is_py2 = six.PY2
if not is_py2:
basestring = str
def to_array(*args):
"""批量转numpy的a... |
# Copyright 2016 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... |
# Sieve of Eratosthenes
# Code by David Eppstein, UC Irvine, 28 Feb 2002
# http://code.activestate.com/recipes/117119/
class SieveEratosthenes(object):
# Maps composites to primes witnessing their compositeness.
# This is memory efficient, as the sieve is not "run forward"
# indefinitely, but only as long... |
# Copyright 2015 Spotify AB. All rights reserved.
#
# The contents of this file are 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... |
example = """00100
11110
10110
10111
10101
01111
00111
11100
10000
11001
00010
01010
"""
f = open("input/03.input")
text = f.read()
def parse(t):
return[[int(b) for b in line] for line in t.strip().split('\n')]
def to_dec(a):
return sum([b * (2 ** n) for (n, b) in enumerate(reversed(a))])
# splits elements in... |
import discord
from discord.ext import commands
from Globals import Globals
def return_category(guild: discord.Guild, category_id_to_check: int):
category_dict = {i.id: i for i in guild.categories}
if category_id_to_check in category_dict:
return category_dict[category_id_to_check]
return None
... |
import cv2 as cv
import numpy as np
class ColourCast:
def __init__(self, img_input: np.ndarray) -> None:
self.img_input = img_input
def color_cast(self):
# RGB to La*b*
img_float = self.img_input.astype(np.float32) / 255.0
np_R = img_float[:, :, 2]
np_G = img_float[:... |
from stix_shifter_utils.stix_transmission.utils.RestApiClient import RestApiClient
from stix_shifter_utils.utils import logger
from stix_shifter_utils.utils.error_response import ErrorResponder
from .response_mapper import ResponseMapper
from datetime import datetime, timezone
import secrets
import string
import hashli... |
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from accounts.models import *
from django.utils.translation import gettext_lazy as _
|
import itertools
import math
import random
grad = [(1, 1, 0), (-1, 1, 0), (1, -1, 0), (-1, -1, 0),
(1, 0, 1), (-1, 0, 1), (1, 0, -1), (-1, 0, -1),
(0, 1, 1), (0, -1, 1), (0, 1, -1), (0, -1, -1)]
F = 0.5 * (math.sqrt(3) - 1.0)
G = (3.0 - math.sqrt(3)) / 6.0
class Terrain:
def __init__(self, poin... |
from django.conf import settings
from django.core.files.uploadedfile import SimpleUploadedFile
from mock import patch
from nose.tools import eq_
import amo
import amo.tests
from mkt.comm.forms import CommAttachmentForm
@patch.object(settings, 'MAX_REVIEW_ATTACHMENT_UPLOAD_SIZE', 1024)
class TestReviewAppAttachment... |
"""Machinery to parse columns in accordance with their unit indicator.
Parsers to convert column values of uncontrolled data types into values with a data type
consistent with the intended representation given the column's unit indicator.
A data-type-specific parser is implemented for each of the allowable StarTable ... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-02-21 08:03
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('suite', '0009_merge_20170220_0640'),
('suite', '0003_auto_20170219_2310'),
]
operat... |
# Generated by Django 2.2.10 on 2020-03-27 21:00
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('references', '0042_cgac_is_shared'),
]
operations = [
migrations.CreateModel(
name='PopCongressionalDistrict',
fiel... |
import logging
import re
from typing import Callable, Any
import sentry_sdk
from os import getenv
import functools
from df_engine.core import Context, Actor
import df_engine.conditions as cnd
from common.books import about_book, BOOK_PATTERN, book_skill_was_proposed
from common.dff.integration import condition as int... |
#%%
import os
import numpy as np
import pytest
from natural_bm.datasets.common import threshold_data
from natural_bm.datasets import mnist, svhn, fast
import natural_bm.backend as B
#%%
def test_treshold_data():
datasets = {'train.data': 0.6*np.ones((100, 10))}
datasets = threshold_data(datasets, threshold=N... |
# MIT License
#
# Copyright (c) 2020 HENSOLDT
#
# 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, merge, pub... |
def test_clear_basic_type(get_contract_with_gas_estimation):
contracts = [
"""
foobar: int128
@public
def foo():
self.foobar = 1
bar: int128 = 1
clear(self.foobar)
clear(bar)
assert self.foobar == 0
assert bar == 0
""",
"""
foobar: uint256
@public
def foo():
self.foobar ... |
from django.contrib import admin
# Register your models here.
from cars.models import Car, Person
class CarAdmin(admin.ModelAdmin):
list_display = ('__str__', 'tyre_type', 'contact_email', 'owner')
list_editable = ('contact_email', 'owner')
list_filter = ('owner',)
search_fields = ('color', 'owner__l... |
import math
import Levenshtein as Lev # see https://pypi.python.org/pypi/python-Levenshtein
#see https://stackoverflow.com/q/29233888/2583476
keyboard_cartesian = {'q': {'x':0, 'y':0}, 'w': {'x':1, 'y':0}, 'e': {'x':2, 'y':0}, 'r': {'x':3, 'y':0}, 't': {'x':4, 'y':0}, 'y': {'x':5, 'y':0}, 'u': {'x':6, 'y':0}, 'i':... |
import ode
import numpy as np
import matplotlib.pyplot as plt
def fun(t,y):
ydot = y - t**2 + 1
return ydot
def main():
tn = np.linspace( 0.0, 2.0, 5 ) # Grid
y0 = np.array( [ 0.5 ] ) # Initial condition
y_ef = ode.euler( fun, tn, y0 ) # Forward Euler
y_mp = ode.midpoi... |
# -*- coding: utf-8 -*-
import os
import json
from pymongo import MongoClient
class DB(object):
def __init__(self, host="0.0.0.0", port=27017):
self.connection = MongoClient(host=host, port=port)
self.bugs = self.connection["bugs"]
self.assignees = self.connection["assignees"]
se... |
import sys
def main():
num_of_card, choosen_card, steps = list(map(int, sys.stdin.readline().split()))
for _ in range(steps):
choosen = list(map(int, sys.stdin.readline().split()))
choosen.pop(0)
if choosen_card in choosen:
print("KEEP")
else:
print("REMOV... |
# A list definition
age_list = [82, 42, 30, 67, 32]
# Get the first element
age_list[0]
# > 82
age_list.append(20) # age_list ow contains [82, 42, 30, 67, 32, 20]
# Slices
age_list[:2] # The first two elements
# > [82, 42]
age_list[-2:] # The last two elements
# > [32, 20]
age_list[:] # All elements
#> [82, 42, 30... |
# Time: O(b * b! * h!)
# Space: O(b * b! * h!)
import collections
class Solution(object):
def findMinStep(self, board, hand):
"""
:type board: str
:type hand: str
:rtype: int
"""
def shrink(s): # Time: O(n), Space: O(n)
stack = []
start = ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Filename: ilqr
# @Date: 2019-06-23-14-00
# @Author: Hany Abdulsamad
# @Contact: hany@robot-learning.de
import autograd.numpy as np
from trajopt.ilqr.objects import AnalyticalLinearDynamics, AnalyticalQuadraticCost
from trajopt.ilqr.objects import QuadraticStateValue, ... |
__author__ = 'bartek'
from py2neo import Relationship
class Security:
def __init__(self):
pass
KNOWS = "KNOWS"
SECURITY = "SECURITY"
IS_MEMBER_OF = "IS_MEMBER_OF"
def __int__(self):
pass
@staticmethod
def create_permission(db, entity, resource, permissions):
se... |
smallest_so_far = None
for the_num in [9,41,12,74,3,15]:
if smallest_so_far is None:
smallest_so_far = the_num
elif the_num < smallest_so_far :
smallest_so_far = the_num
print(smallest_so_far,the_num)
print("smallest number is",smallest_so_far)
|
from discord.ext import commands
from discord import Member
class id(commands.Cog):
def __init__(
self,
client
):
self.client = client
@commands.command()
async def id(
self,
ctx,
member: Member = None
):
if not member:
member = c... |
# Generated by Django 2.2.8 on 2020-01-16 11:26
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('sponsors', '0005_sponsorlevel_highlight_color'),
]
operations = [
migrations.AlterField(
model_name='sponsorlevel',
... |
import torch.nn as nn
import torch.nn.functional as F
class PolicyNetwork(nn.Module):
def __init__(self, state_size, action_size, hidsize1=128, hidsize2=128):
super(PolicyNetwork, self).__init__()
self.fc1 = nn.Linear(state_size, hidsize1)
self.fc2 = nn.Linear(hidsize1, hidsize2)
... |
#!/usr/bin/env python3
import binascii
from elftools.elf.elffile import ELFFile
def inFlash(addr, size):
FlashBase = 0x10000000
FlashSize = (2 * 1024 * 1024)
return (addr >= FlashBase) and (addr + size <= FlashBase + FlashSize)
def main():
entrypointAddress = 0x0
flashStartAddress = 0x0
rawFi... |
from oscar.agent.custom_agent import CustomAgent
from oscar.meta_action import *
class Economic(CustomAgent):
def __init__(self, message="I hate you"):
self.supply_depot_built = False
self.barracks_built = False
self._message = message
super().__init__()
def set_supply_depot_b... |
#!/usr/bin/env python3
# -*- mode: python -*-
# -*- coding: utf-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you... |
import discord
import json
from config import config
bot = config.bot()
def get_role(role, ctx):
return discord.utils.get(ctx.guild.roles, name=role)
def roles():
with open("Moderating/Perms/roles.json") as file:
return json.load(file)
async def is_muted(user):
return get_role(role="Muted", c... |
#!/usr/bin/env python
# --------------------------------------------------------
# Tensorflow Faster R-CNN
# Licensed under The MIT License [see LICENSE for details]
# Written by Xinlei Chen, based on code from Ross Girshick
# --------------------------------------------------------
"""
Demo script showing detections... |
import keras.backend as K
import numpy as np
import pandas as pd
from datetime import time, datetime
import tensorflow as tf
from argparse import ArgumentParser
def get_flops(model):
run_meta = tf.RunMetadata()
opts = tf.profiler.ProfileOptionBuilder.float_operation()
# We use the Keras session graph in ... |
#!/usr/bin/env python3
import requests
import json
from pprint import pprint
from jnpr.healthbot import HealthBotClient
from jnpr.healthbot import DeviceSchema
from jnpr.healthbot import DeviceGroupSchema
import argparse
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
parser = argpa... |
for num in range(1,101):
if (num % 3 == 0) and (num % 5 == 0):
print("FizzBuzz")
elif num % 3 == 0:
print("Fizz")
elif num % 5 == 0:
print("Buzz")
else:
print(num)
|
"""
Django settings for teste project.
Generated by 'django-admin startproject' using Django 1.11.10.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import os
... |
""" Smartthings TV integration """
from datetime import timedelta
from enum import Enum
import logging
from typing import Dict, Optional
from aiohttp import ClientSession, ClientConnectionError, ClientResponseError
from asyncio import TimeoutError as AsyncTimeoutError
import json
from homeassistant.util import Thrott... |
"""
Given a non-empty integer array, find the minimum number of moves required to
make all array elements equal, where a move is incrementing a selected element
by 1 or decrementing a selected element by 1.
You may assume the array's length is at most 10,000.
Example:
Input:
[1,2,3]
Output:
2
Explanation:
Only two... |
import numpy as np
import random
class extrema:
def __init__(self, a, b):
'''
a, b are the row and column sum constraints
'''
self.a = a
self.b = b
self.P = None
def NWC(self):
P = np.zeros((len(self.a),len(self.b)))
nR = len(self.a)
... |
#!/usr/bin/env python3
# Copyright (c) 2014-2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Base class for RPC testing."""
from enum import Enum
from io import BytesIO
import logging
import optp... |
from django.db import models
# Create your models here.
class RefundPolicyIntroduction(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(default="Introduction", max_length=50)
body = models.TextField()
def __str__(self):
return self.name
class OrderCancelat... |
"""
WSGI config for weatherwarner 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.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO... |
import datetime
import json
import os
import os.path as osp
from contextlib import contextmanager
try:
from torch.utils.tensorboard.writer import SummaryWriter
except ImportError:
print("Unable to import tensorboard SummaryWriter, proceeding without.")
from rlpyt.utils.logging import logger
LOG_DIR = osp.absp... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
# Copyright 2018 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 sys
import py2app
__all__ = ['infoPlistDict']
def infoPlistDict(CFBundleExecutable, plist={}):
CFBundleExecutable = CFBundleExecutable
NSPrincipalClass = ''.join(CFBundleExecutable.split())
version = sys.version[:3]
pdict = dict(
CFBundleDevelopmentRegion='English',
CFBundleDisp... |
#!/usr/bin/env python3
# Copyright 2021 Stanford University
#
# 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 applicab... |
#Importing all the necessary libraries to form the alarm clock:
from tkinter import *
import datetime
import time
import winsound
def alarm(set_alarm_timer):
while True:
time.sleep(1)
current_time = datetime.datetime.now()
now = current_time.strftime("%H:%M:%S")
date ... |
#!/usr/bin/env python
# Copyright (c) 2020 Computer Vision Center (CVC) at the Universitat Autonoma de
# Barcelona (UAB).
#
# This work is licensed under the terms of the MIT license.
# For a copy, see <https://opensource.org/licenses/MIT>.
"""
Raycast sensor profiler
This script can be used to test, visu... |
from typing import List
from bson import ObjectId
from decouple import config
from pymongo import MongoClient
from fastapi import APIRouter, status
from models import Task
client = MongoClient(config('DB_HOST'))
db = client['3do']
router = APIRouter()
# Gets all tasks
@router.get(
'/tasks',
tags=['tasks']... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class AntMerchantExpandOrderQueryModel(object):
def __init__(self):
self._order_id = None
@property
def order_id(self):
return self._order_id
@order_id.setter
def orde... |
"""
Provide a generic structure to support window functions,
similar to how we have a Groupby object.
"""
from datetime import timedelta
from functools import partial
import inspect
from textwrap import dedent
from typing import Callable, Dict, List, Optional, Set, Tuple, Type, Union
import numpy as np
from pandas._l... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import theano
import theano.tensor as T
from theano.tensor.signal import downsample
from .. import activations, initializations, regularizers, constraints
from ..utils.theano_utils import shared_zeros
from ..layers.core import Layer
class Convolution1D(... |
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from builtins import (
bytes, dict, int, list, object, range, str,
ascii, chr, hex, input, next, oct, open,
pow, round, super,
filter, map, zip)
import fileinput
import stri... |
# coding: utf-8
"""
DocuSign REST API
The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
OpenAPI spec version: v2.1
Contact: devcenter@docusign.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from p... |
#!/usr/bin/env python3
import argparse
from Bio import SeqIO
def parse_args():
parser = argparse.ArgumentParser(prog='fa_filter.py', conflict_handler='resolve')
parser.add_argument('-bl', type = str, required = True, help = '=> .txt with organism blacklist e.g. mm10')
parser.add_argument('-i', type = str, ... |
import time
from signal import Signals
from typing import Callable, Generator, Tuple, Union
import MySQLdb
from loguru import logger
from MySQLdb.cursors import DictCursor
from pymysqlreplication import BinLogStreamReader
from pymysqlreplication.event import QueryEvent
from pymysqlreplication.row_event import DeleteRo... |
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.widget import Widget
from kivy.properties import ObjectProperty
from kivy.lang import Builder
class MyGrid(Widget):
name = O... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from .. import _utilities, _tables
from ... |
import discord
from discord.ext import commands
from discord import utils
class Moderation(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(name='ping')
async def ping(self, ctx):
"""Pings to someone."""
await ctx.send(f'{ctx.author.mention}... |
import mxnet.gluon as mxg
class VGGSmallModel(mxg.HybridBlock):
def __init__(self, classes=10, **kwargs):
super(VGGSmallModel, self).__init__(**kwargs)
# 32
self.conv0 = mxg.nn.Conv2D(128, 3, padding=1, use_bias=False, prefix='conv0')
self.bn1 = mxg.nn.BatchNorm(prefix='bn1')
... |
from .swish import Swish
|
from datapackage_pipelines_knesset.common.base_processors.base import BaseProcessor
from datapackage_pipelines.utilities.resources import PROP_STREAMING
class BaseResourceProcessor(BaseProcessor):
"""Base class for processing a single resource"""
def __init__(self, *args, **kwargs):
super(BaseResource... |
# Generated by Django 3.0.6 on 2020-06-04 22:44
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('digital_books', '0008_digital_book_rating'),
('adquisitions', '0048_auto_20200604_2238'),
]
operations = [
... |
import logging
from django.conf import settings
from django.contrib.sites.models import Site
from django.core.exceptions import ObjectDoesNotExist
from django.core.mail import EmailMessage
from django.http import Http404, HttpResponse, HttpResponseRedirect
from django.template import TemplateSyntaxError
from django.te... |
from django import template
register = template.Library()
def won(value):
"""숫자를 원화로 변경"""
if value >= 0:
value = str(value)
length = len(value)
new_val_list = []
if length <= 3:
new_val_list.append(value[0:length])
else:
if length % 3 == 0:
... |
import itertools
# sensor model for true and false positives
starting_prob = 0.5
prob_sense_emp_given_occ = 0.2
prob_sense_emp_given_emp = 0.9
prob_sense_occ_given_occ_rate = 0.1
prob_sense_occ_given_occ_offset = 0.3
prob_sense_occ_given_emp_rate = -0.1
prob_sense_occ_given_emp_offset = 0.5
def dynamic_sense_occ_gi... |
import random
import threading
class Environnement(threading.Thread):
def __init__(self):
super().__init__()
# vie de l'environnement
self.life = True
# coordonnees du robot
self.posRobotX = None
self.posRobotY = None
# performance du robot
self.c... |
import click
from chatbot.run_it import app
from chatbot.cli_interface import train_command
from chatbot.cli_interface import del_command
from chatbot.cli_interface import crawl_command
from chatbot.cli_interface import clean_command
from chatbot.constants import *
import os
# Usage: run "pytest" from the project roo... |
# coding:utf-8
import math
import os
import shutil
import time
import cv2
import numpy as np
import torch
from torchvision import transforms
from tqdm import tqdm
import lanms
from config import device, result_root
from data_gen import data_transforms, test_data_path
from icdar import restore_rectangle, polygon_area
... |
from setuptools import setup
import re
# borrowed from Agile Scientific bruges tools
verstr = 'unknown'
VERSIONFILE = "psm/_version.py"
with open(VERSIONFILE, "r") as f:
verstrline = f.read().strip()
pattern = re.compile(r"__version__ = ['\"](.*)['\"]")
mo = pattern.search(verstrline)
if mo:
verstr = ... |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
# This fil... |
import codecs
import json
import logging
import os
import sys
import requests
import time
from pgnumbra.config import cfg_get, get_pgpool_system_id
log = logging.getLogger(__name__)
def get_pokemon_name(pokemon_id):
fmt = cfg_get('pokemon_format')
if fmt == 'id':
return "{:3}".format(pokemon_id)
... |
# ******************************************************************************
# Copyright 2017-2020 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apa... |
from PhotonMap import add_photon_map_to_scene, optimize_photon_map
from PostProcessing import sigmoid_scale, basic_tone_map_scale
from objParser import *
from RayTraceCore import *
if __name__ == '__main__':
with open("glass2.obj", "r") as file:
scene = parse_obj(file.read())
with open("scenes/north.sc... |
"""Lyndon.py
Algorithms on strings and sequences based on Lyndon words.
David Eppstein, October 2011."""
from .eratosthenes import moebius_function
def LengthLimitedLyndonWords(s, n):
"""Generate nonempty Lyndon words of length <= n over an s-symbol alphabet.
The words are generated in lexicographic order, u... |
from resources import PROCESSED_PATH,LEARNT_RANKER_PATH
from summariser.utils.reader import readSampleSummaries
from summariser.vector.vector_generator import Vectoriser
from summariser.rl.td_agent import *
from summariser.rl.deep_td import *
from summariser.utils.evaluator import evaluateSummary
import os
def addRes... |
import sys, re, os, yaml
from collections import OrderedDict
path = os.path.dirname(os.path.realpath(__file__)) + '/../_episodes/'
def get_all_episodes():
return sorted(os.listdir(path))
def add_to_data(raw_content, data_to_add):
data_list = raw_content.split('---')
data_list[1] = data_list[1] + data_to_add
... |
# Copyright (c) 2014 Rackspace US, Inc
# 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 req... |
# MIT License
#
# Copyright (c) 2018 Evgeny Medvedev, evge.medvedev@gmail.com
#
# 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
# ... |
# coding: utf8
from __future__ import unicode_literals
"""
Example sentences to test spaCy and its language models.
>>> from spacy.lang.ko.examples import sentences
>>> docs = nlp.pipe(sentences)
"""
sentences = [
"애플이 영국의 스타트업을 10억 달러에 인수하는 것을 알아보고 있다.",
"자율주행 자동차의 손해 배상 책임이 제조 업체로 옮겨 가다",
"샌프란시스코 시가 자동... |
import rmc.shared.constants as c
import rmc.models as m
import rmc.data.evals.conversion as conv
import mongoengine as me
import sys
def import_all_critiques(eng_file):
m.CritiqueCourse.objects._collection.drop()
conv.import_engineering_critiques(eng_file)
if __name__ == '__main__':
if (len(sys.argv) < ... |
from PEPit import PEP
from PEPit.functions import SmoothStronglyConvexFunction
from PEPit.functions import SmoothConvexFunction
from PEPit.functions import ConvexFunction
from PEPit.primitive_steps import proximal_step
def wc_three_operator_splitting(mu1, L1, L3, alpha, theta, n, verbose=1):
"""
Consider the ... |
from data_stack.repository.repository import DatasetRepository
from data_stack.io.storage_connectors import StorageConnectorFactory
from ml_gym.blueprints.constructables import DatasetRepositoryConstructable, ModelRegistryConstructable, ComponentConstructable, \
LossFunctionRegistryConstructable
from outlier_hub.da... |
import setuptools
if __name__ == '__main__':
setuptools.setup() |
import argparse
import os
from collections import defaultdict
from src.core.util import read_json, write_json
parser = argparse.ArgumentParser()
parser.add_argument('--transcripts', help='Path to transcritps of mixed partners')
parser.add_argument('--output', help='Output directories')
args = parser.parse_args()
chat... |
import pickle
import matplotlib.pyplot as plt
sorted_hashtag_counts = pickle.load(open("sorted_hashtag_counts.p", "rb"))
sorted_mention_counts = pickle.load(open("sorted_mention_counts.p", "rb"))
k = 30
print('Top %d most popular hashtags:' % k)
for i in range(1,k+1):
print('Hashtag: %s, used %d times' % (sorted_... |
# -*- coding: utf-8 -*-
import unittest
import pymcmcstat
import re
class ImportPymcmcstat(unittest.TestCase):
def test_version_attribute(self):
version = pymcmcstat.__version__
self.assertTrue(isinstance(version, str),
msg='Expect string output')
pattern = '\d+\.\... |
# Generated by Django 3.2 on 2021-05-23 20:38
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0003_rename_post_code_postcode_pin_code'),
('storemaster', '0003_webstore_post_code'),
]
operatio... |
#######################################################################
# Copyright (c) 2013 Adam Wisniewski, http://adamw523.com
#
# 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 res... |
#!/usr/bin/python
# coding=utf-8
# File Name: find_median.py
# Developer: VVgege
# Data: Tue Feb 3 22:27:20 2015
'''
Question:
There are two sorted arrays A and B of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
'''
|
#!python
# Copyright 2018 Datawire. 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 ... |
import os
import aiohttp_session
import aiohttp_session.cookie_storage
from hailtop.config import get_deploy_config
def setup_aiohttp_session(app):
deploy_config = get_deploy_config()
with open('/session-secret-key/session-secret-key', 'rb') as f:
aiohttp_session.setup(
app,
... |
from core.himesis import Himesis, HimesisPreConditionPatternLHS
import uuid
class HAssignmentInstance_ConnectedLHS(HimesisPreConditionPatternLHS):
def __init__(self):
"""
Creates the himesis graph representing the AToM3 model HAssignmentInstance_ConnectedLHS
"""
# Flag this instance as compiled now
self.is_... |
from unittest import mock
import pytest
import numpy as np
from mlagents_envs.environment import UnityEnvironment
from mlagents_envs.base_env import DecisionSteps, TerminalSteps
from mlagents_envs.exception import UnityEnvironmentException, UnityActionException
from mlagents_envs.mock_communicator import MockCommunic... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.