content stringlengths 5 1.05M |
|---|
# -*- coding: utf-8 -*-
#
# Copyright (C) 2019 Chris Caron <lead2gold@gmail.com>
# All rights reserved.
#
# This code is licensed under the MIT License.
#
# 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 th... |
# Get Launcher as well as OpenGL imports
from projects.launcher import *
w, h = 500, 500
square_posx, square_posy = 0.0, 0.0
triangle_scale = 1.0
def square(size=(100, 100)):
global square_posx, square_posy
square_posx = (square_posx + 0.05) % w
square_posy = (square_posy + 0.05) % h
glTranslated(squ... |
#!/dls_sw/tools/bin/python2.4
from pkg_resources import require
require('dls_serial_sim')
from dls_serial_sim import serial_device
import re, os, time
class elcomat3000(serial_device):
Terminator = "\n"
def __init__(self):
'''Constructor. Remember to call the base class constructor.'''
s... |
from mongoengine import *
class ConfigurationReference(EmbeddedDocument):
configId = ObjectIdField()
name = StringField()
filename = StringField() |
#!/usr/bin/env python3
"""
stores mysql DB secrets, should be kept secret for production
"""
from cryptography.fernet import Fernet
import os
import sys
MY_API_TOKEN = (
"bCCHjJ4CddOvuz&Yoce4^hpQqSr5393LtxF8#Dlv@a*O0MXlp8sdwQI%LwYlPAB*cNbVV9EUG"
"lDsAkwPpcBeQ$F0A1Tdtnf%9eEe"
)
KEY = os.getenv('TODO_KEY', '1OW... |
class UserResponse(object):
def __init__(self):
self.swaggerTypes = {
'ResponseStatus': 'ResponseStatus',
'Response': 'User',
'Notifications': 'list<Str>'
}
|
import os, sys, subprocess, shutil
sys.path.append(os.path.dirname(__file__) + "/../lib")
from test_helper import create_virtenv, run_test
ENV_NAME = "unidecode_test_env_" + os.path.basename(sys.executable)
SRC_DIR = os.path.abspath(os.path.join(ENV_NAME, "src"))
PYTHON_EXE = os.path.abspath(os.path.join(ENV_NAME, "b... |
load("@com_vistarmedia_rules_js//js:def.bzl", "npm_install")
load(
"@com_vistarmedia_rules_js//js:def.bzl",
"js_binary",
"js_library",
"js_test",
)
load(
"//coffee/private:rules.bzl",
"cjsx_src",
"cjsx_srcs",
)
def coffee_repositories():
npm_install(
name = "coffee-script",
... |
# puzzle3a.py
def main():
horiz_step = 3
vert_step = 1
tree_char = "#"
horiz_pos = 0
trees = 0
input_file = open("input.txt", "r")
lines = input_file.readlines()
line_len = len(lines[0]) - 1 # Subtract 1 to account for '\n'
lines = lines[1:]
for line in lines:
h... |
from collections import OrderedDict
from tartiflette.types.field import GraphQLField
from tartiflette.types.interface import GraphQLInterfaceType
def test_graphql_interface_init(mocked_resolver_factory):
interface = GraphQLInterfaceType(
name="Name",
fields=OrderedDict(
[
... |
# Copyright 2014-2019 The PySCF Developers. 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 appl... |
import plac
from rdflib import Graph
def main(page_ids_ttl, page_links_ttl, out_csv):
graph = Graph()
graph.parse(page_ids_ttl, format="ttl")
if __name__ == "__main__":
plac.call(main)
|
import sys
import os
import urllib
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import tensorflow as tf
import pickle
from Network import nmt_model,SplitIUPAC
import unicodedata
import re
import selfies
import subprocess
import urllib.request
os.environ["CUDA_VISIBLE_DEVICES"]="2"
def main():
# Declaration of Glob... |
from PIL import Image, ImageOps
def add_border(input_image, output_image, border):
img = Image.open(input_image)
if isinstance(border, int) or isinstance(border, tuple):
bimg = ImageOps.expand(img, border=border)
else:
raise RuntimeError('Border is not an integer or tuple!')
bimg.sav... |
import random
OPTIONS = ['rock', 'paper', 'scissors']
def print_options():
"""
This function prints game's options
:return:
"""
print('(1) Rock\n(2) Paper\n(3) Scissors')
def get_human_choice():
"""
This function gets the choice of the human
:return:
"""
human_choice_numb... |
'''
Plot accuracy
'''
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import seaborn as sns
import argparse
acc_vs_param = {
"TRBA": { "Accuracy": 84.3, "Parameters": 49.6},
"STAR-Net": { "Accuracy": 81.8, "Parameters": 48.9},
"RARE": { "Accuracy": 81.9, "Parameters": 10.9... |
# coding: utf-8
# Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... |
import requests
import json
# Create via https://127.0.0.1:5000/account/settings/applications/tokens/new/
api = "https://127.0.0.1:5000"
token = "...."
# Define a list of records you want to upload:
# ('<record metadata json>.json', ['<datafile1>', '<datafile2>'])
records = [
('record.json', ['1911.00295.pdf',])
... |
n = int(input()) #lost fights
helmet_price = float(input())
sword_price = float(input())
shield_price = float(input())
armor_price = float(input())
lost_fights_count = 0
helmet_brakes = 0
sword_brakes = 0
shield_brakes = 0
armor_brakes = 0
total_shield_brakes = 0
for x in range(n):
lost_fights_count += 1
if ... |
from flask import Blueprint
bp = Blueprint('pages', __name__)
@bp.record_once
def register(state):
from sopy.pages import views
state.app.add_url_rule('/chatroom', None, views.page, defaults={'name': 'chatroom'})
|
from ead.models import EAD
def run():
EAD.objects.all().delete()
|
from typing import BinaryIO, Union
from pymarc import MARCReader
from pymarc.constants import END_OF_RECORD
from pymarc import exceptions
from bookops_marc import Bib
class SierraBibReader(MARCReader):
"""
An interator class for reading file of local Sierra MARC records.
"""
def __init__(
s... |
# Copyright (c) 2017-2021 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
import logging
from dazl.testing import connect_with_new_party
import pytest
from .dars import PostOffice
@pytest.mark.asyncio
async def test_protocol_ledger_api(sandbox):
... |
'''
Manage App Service Environments
'''
from ... pyaz_utils import _call_az
def list(resource_group=None):
'''
List app service environments.
Optional Parameters:
- resource_group -- Name of resource group. You can configure the default group using `az configure --defaults group=<name>`
'''
re... |
# -*- coding: utf-8 -*-
""" SOXMOS spectrometer file parser, plotter"""
from .SOXMOSFile import SOXMOSFile
__version__ = "0.1.0"
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
# -*- coding: utf-8 -*-
#BEGIN_HEADER
import os
import ntpath
from PIL import Image
import subprocess
from installed_clients.KBaseReportClient import KBaseReport
from installed_clients.GenomeFileUtilClient import GenomeFileUtil
from installed_clients.DataFileUtilClient import DataFileUtil as DFUClient
#END_HEADER
c... |
import pytest
import pandas as pd
from data import clean, read_data
from unittest import mock
def test_clean():
plot = "\n\nHello\r\nWorld\'[1]"
assert clean(plot) == " Hello World"
@mock.patch('data.os.path.isfile', return_value=False)
def test_read_data_bad_file(_):
with pytest.raises(ValueError):
... |
"""
:mod:`response`
---------------
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import os
import sys
from six import text_type
from . import status_strings
from .baseheaders import BaseHeaders as Headers
c... |
# Copyright 2021 The SODA Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http:#www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... |
#!/usr/bin/env python3
from __future__ import annotations
from typing import List, Callable, Optional
import bagua_core as B
import torch
from bagua.torch_api.globals import _get_global_state
from bagua.torch_api.tensor import BaguaTensor
from bagua.torch_api.utils import check_contiguous
class BaguaBucket:
de... |
"""Tests for RC Config."""
import unittest
from grow.common import rc_config
def mock_time(value):
"""Mock out the time value."""
def _mock():
return value
return _mock
class RCConfigTestCase(unittest.TestCase):
"""Test the RC Config."""
def _create_config(self, time_value=None):
... |
#encoding:utf-8
import datetime
import csv
import logging
from multiprocessing import Process
import time
import yaml
from croniter import croniter
from supplier import supply
logger = logging.getLogger(__name__)
def read_own_cron(own_cron_filename, config):
with open(own_cron_filename) as tsv_file:
... |
# -*- encoding: utf-8 -*-
from cooka.common import util
from cooka.common.exceptions import EntityNotExistsException
from cooka.common.model import Model, ModelStatusType
from cooka.dao.entity import ExperimentEntity, DatasetEntity
from sqlalchemy.sql import func
class BaseDao:
def require_one(self, items, entit... |
"""
TODO: Exit out of all demon programs when quit
TODO: Check the characters position before it moves or performs certain actions.
TODO: Integrate the BUY function into the shops.
"""
import pathlib as pathlib
import textwrap as textwrap
from app.main import world, enemies, command_parser, config, npcs, combat, e... |
# This file was scaffold by idol_data, but it will not be overwritten, so feel free to edit.
# This file will be regenerated if you delete it.
from ..codegen.schema.literal import SchemaLiteralDataclass as LiteralCodegen
class Literal(LiteralCodegen):
pass
|
import streamlit.components.v1 as components
import pandas as pd
import matplotlib.pyplot as plt
import streamlit as st
import plotly.express as px
import plotly.io as pio
import os
import base64
import pickle
import collections
from ..constants import *
from ...graph_utils import get_k_common_followers, get_top_foll... |
import time, json, logging
from typing import Dict
from twisted.internet import reactor
from twisted.internet.defer import inlineCallbacks
import treq
from light9 import networking
log = logging.getLogger()
class MusicTime(object):
"""
fetch times from ascoltami in a background thread; return times
upo... |
import boto3, os, json
from typing import Dict, List, Any, Union
from boto3 import Session
from botocore.exceptions import ClientError
class Entry:
def __init__(self, name, publickey, fingerprint):
self.name = name
self.publickey = publickey
self.fingerprint = fingerprint
def __str__... |
import pandas as pd
import numpy as np
from scipy import stats
import os, sys
sys.path.append("../utils/")
from utils import *
data_dir = '../../out/'
games = []
games += get_games(data_dir, 'experiment')
lengths = {}
count = 0
for game_id in games:
data_dir = in_dir + game_id + '/games/'
for game... |
from common_data_structures.periodic_bar import Quote, PeriodicBar
from ctypes import *
from datetime import datetime
from event_processing.external_data_listener import ExternalDataListener
from event_processing.market_book import MarketBook
from utils.datetime_convertor import get_unix_timestamp_from_hhmm_tz
import ... |
import os
def renameFile():
# get thefile names
original_path = os.getcwd()
print(original_path)
os.chdir(original_path + "\prank")
file_list = os.listdir(original_path + "\prank")
print(file_list)
# for each file, rename the file
for file in file_list:
print(file)
try:... |
#!/usr/bin/env python3
"""
Purpose: Describe what is off the larboard bow using the correct a/an article.
"""
import argparse
def get_args():
"""Get command-line arguments"""
parser = argparse.ArgumentParser(
description="Warn the captain",
formatter_class=argparse.ArgumentDefaultsHelpFormatt... |
import pytest
from mongomap import *
@pytest.fixture(scope='module')
def schema():
class ASchema(Schema):
foo = Field(IntType)
bar = Field(FloatType)
return ASchema
@pytest.fixture(scope='module')
def nested_schema(schema):
class BSchema(Schema):
spam = Field(StringType)
... |
from setuptools import setup, find_packages
with open('README.md') as f:
readme = f.read()
with open('LICENSE.md') as f:
license = f.read()
setup(
name='hafalin',
version='0.1.0',
description='Hafalin API, an API to generate questions given document',
long_description=readme,
author='Gera... |
from graph import *
class WeightedEdge(Edge):
def __init__(self, src, dest, weight):
self.src = src
self.dest = dest
self.weight = weight
def getWeight(self):
return self.weight
def __str__(self):
return str(self.src) + "->" + str(self.dest) + " (" + str(self.weight)... |
from os import getenv
from gitWebScrapper import logger
GITLAB_API_BASE_URL = 'https://gitlab.com/api/v4'
def check_token():
token = getenv('ACCESS_TOKEN_LAB')
if token is None:
logger.error('ACCESS_TOKEN_LAB not found')
return token
ACCESS_TOKEN = check_token() |
# ___________________________________________________________________________
#
# Prescient
# Copyright 2020 National Technology & Engineering Solutions of Sandia, LLC
# (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S.
# Government retains certain rights in this software.
# This softwa... |
from limits import limits
class TestGranularity:
def test_seconds_value(self):
assert limits.RateLimitItemPerSecond(1).get_expiry() == 1
assert limits.RateLimitItemPerMinute(1).get_expiry() == 60
assert limits.RateLimitItemPerHour(1).get_expiry() == 60 * 60
assert limits.RateLimitI... |
import numpy as np
from scipy.spatial.distance import cdist
from scipy.misc import imresize
def nearest_icons(icons, dataset, scale=None, grayscale=False, get_dist=False):
""" Find nearest neighbour in the set for a given icon
Args:
icons: array of icons to which the nearest neighbour is to be... |
import cv2
from lib.tracking_utils.timer import Timer
tracking_model_name = 'fair_mot'
url = '0.0.0.0:8001'
protocol = 'grpc'
batch_size = 1
is_async = True
is_streaming = True
cap = cv2.VideoCapture('./data/MOT16-03.mp4')
frame_rate = int(round(cap.get(cv2.CAP_PROP_FPS)))
count = 0
w, h = 1920, 1080
input_size=(576... |
import asyncio
import colorsys
from colorthief import ColorThief
from govee_api_laggat import Govee, GoveeAbstractLearningStorage, GoveeLearnedInfo
from os import getenv
from time import sleep
from typing import Dict
from watchdog.events import FileSystemEventHandler
from watchdog.observers import Observer
from logipy ... |
from .shapenet import Dataset as ShapeNet
from .dfaust import Dataset as DFaust
|
import json
import os.path
def _load_items():
global _items
fname = 'items.json'
if os.path.exists(fname):
f = open(fname, "r")
_items = json.loads(f.read())
f.close
else:
_items = []
def _save_items():
global _items
fname = 'items.json'
f = open(fname, "w")
f.write(json.dumps(_items))
f.close
def i... |
# Generated by Django 2.1.8 on 2019-06-03 18:12
from django.db import migrations, models
import wagtail.core.blocks
import wagtail.core.fields
class Migration(migrations.Migration):
dependencies = [
('content', '0007_auto_20190603_1322'),
]
operations = [
migrations.AddField(
... |
#!/usr/bin/env python
"""
build.py
Build HTML output
"""
from __future__ import absolute_import, division, print_function
import re
import os
import argparse
import datetime
import subprocess
import shutil
import lxml.html
def main():
p = argparse.ArgumentParser(usage=__doc__.rstrip())
p.add_argument('--htm... |
import random
import string
strGen = lambda length:"".join([random.choice(string.ascii_letters+string.digits) for _ in range(length)])
|
from .base import Base
from .models import Player
|
# encoding: utf-8
# =========================================================================
# ©2017-2018 北京国美云服科技有限公司
# -------------------------------------------------------------------------
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this work except in compliance with the ... |
import pandas as pd
import re
import tempfile
import matplotlib.pyplot as plt
def read_log(path):
edited_lines = []
with open(path, 'r') as file:
lines = file.readlines()
for line in lines:
# Extract set if necessary
result = re.search(r'{(.*)}', line)
if re... |
#!/usr/bin/env pvbatch
# state file generated using paraview version 5.8.0
from paraview.simple import *
paraview.simple._DisableFirstRenderCameraReset()
import argparse
import numpy as np
import paratools
parser = argparse.ArgumentParser(
description="Renders vorticity magnitude with LAMMPS polymers")
parser... |
'''
Verify correct handling of session and transaction delay.
'''
# @file
#
# Copyright 2021, Verizon Media
# SPDX-License-Identifier: Apache-2.0
#
Test.Summary = '''
Verify correct handling of session and transaction delay.
'''
#
# Test 1: Run a few sessions and transactions with client-side delay.
#
r = Test.AddTes... |
# -*- coding: utf-8 -*-
"""
d7sms
"""
import unittest
from ..http_response_catcher import HttpResponseCatcher
from d7sms.d_7_sms_client import D7smsClient
from d7sms.configuration import Configuration
class ControllerTestBase(unittest.TestCase):
"""All test classes inherit from this base clas... |
# PyDia Self Documentation Series - Part III : All Objects
# Copyright (c) 2007, Hans Breuer <hans@breuer.org>
#
# generates a new diagram which contains all the currently
# registered objects sorted to layers by their containing package
#
# This program is free software; you can redistribute it and... |
"""
"""
import turtle
class Pluma():
def __init__(self, color, grosor):
self.color = color
self.grosor = grosor
self.posicion = [0, 0]
self.previa = self.posicion
def mueve(self, x, y):
self.previa = self.posicion
self.posicion = [x, y]
turtle.goto(*se... |
from django.contrib.localflavor.au.models import AUStateField, AUPostCodeField
from django.db import models
class AustralianPlace(models.Model):
state = AUStateField(blank=True)
state_required = AUStateField()
state_default = AUStateField(default="NSW", blank=True)
postcode = AUPostCodeField(blank=True... |
# Copyright (C) 2004-2018 by
# All rights reserved.
# MIT license.
#
# Author: Vadim Ivlev
# Some functions to show tree graphs.
# Can be used both in standalone programs
# and in `jupyther` nonebooks.
# Preconditions
# -------------
# The folowing libraries should be installed
# `matplotlib, networkx, grap... |
import lane_lines
from moviepy.editor import VideoFileClip
def process_image(image):
result = lane_lines_finder.run(image)
return result
lane_lines_finder = lane_lines.LaneFinder('calibration_output/wide_dist_pickle.p')
video = 'project_video'
input_video = video + '.mp4'
output_video = 'out_videos/' + video... |
from django.conf.urls import url
from sound.views import AuthorDetail, AuthorList, AuthorUpdate, \
SoundDetail, SoundList, \
RequestDetail, RequestGetOut, RequestGetIn, RequestList, RequestCreate
urlpatterns = [
url(r'^author/(?P<pk>[\d]+)/edit/$', AuthorUpdate.as_view(), name="sound-author-update"),
u... |
import pygame
class MeleeAttack():
def __init__(self, damage, player, handler):
self.damage = damage
self.handler = handler
self.player = player
self.attackrange = 100
self.lfist = pygame.transform.rotate(pygame.image.load("media/Misc/fist.png").convert_alpha(), 90)
... |
import sys
import argparse
from sklearn.model_selection import KFold
from sklearn.externals import joblib
import numpy as np
import h5py
from sklearn.metrics import confusion_matrix, accuracy_score
from sklearn.metrics import confusion_matrix, accuracy_score, matthews_corrcoef, \
classificat... |
from setuptools import find_packages, setup
VERSION = '0.0.9'
setup(
name='lywsd02',
version=VERSION,
packages=find_packages(exclude=("tests",)),
url='https://github.com/h4/lywsd02',
license='MIT',
author='h4',
classifiers=[
'Programming Language :: Python :: 3.7',
],
insta... |
from ..schema import types
from .extensions import SpecificationExtensions
Contact = types.Schema(
name='Contact',
pattern_properties=SpecificationExtensions,
additional_properties=False,
properties={
'name': types.StringType(),
'url': types.UrlType(),
'email': types.EmailType... |
class vocab(object):
"""
Base CRIPTs vocabulary object. Does nothing right now.
"""
@classmethod
def values(cls, sort=False):
"""
Get available values in a list.
:param sort: Should the list be sorted.
:type sort: bool
:returns: list
"""
l =... |
print '***** Guided Proofreading *****'
from theano.sandbox.cuda import dnn
print 'CuDNN support:', dnn.dnn_available()
|
from flask_ember.util.string import dasherize
class ResourceGenerator:
def __init__(self, ember, resource_class):
self.ember = ember
self.resource_class = resource_class
def generate(self, app):
# TODO generation of api endpoints etc
resource = self.resource_class
nam... |
workerNameList = hero.findNearest(hero.findFriends()).workerList
def build(construction, start):
for i in range(start, workerNameList.length, 3):
hero.say(workerNameList[i] + " - " + construction)
build("tower", 1)
build("tent", 0)
build("fence", 2)
while True:
enemy = hero.findNearest... |
#! /usr/bin/env python
import pysnmp
import paramiko
import my_func
def print_ver():
print "\nPySNMP Version: %s" % (pysnmp.__version__)
print "Paramiko Version: %s\n" % (paramiko.__version__)
if __name__ == '__main__':
print_ver()
|
#CONFIG FILE
#Made by Luka Dragar
#@thelukadragar
operatingmode="xyz"
#"xy"---move only in xy
#"xyz"--move in xy and z
#----------------------------------------------
sendinginterval=0.15
#interval to send points[seconds]
#try changing if there are problems
myIP= "127.0.0.1" # localhost or your ip "192.168.... |
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class BrokerZerodhaTxn(models.Model):
bzt_id = models.AutoField(primary_key=True)
bzt_user = models.ForeignKey(User, on_delete=models.DO_NOTHING)
bzt_tdate = models.DateField(blank=True, null=True)
bzt... |
from ice.jcache import JCache
import functools
import hashlib
import datetime
#Source: https://unterwaditzer.net/2016/sync-algorithm.html
class SyncMap:
def __init__(self,identifier):
"""
The identifier is e.g. the account + calendar name / address book name... must be unique.
E.g. CalDav... |
# coding: utf-8
"""
Copyright 2016 SmartBear Software
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... |
n = int(input())
buttonList = list()
for _ in range(n):
buttonList.append(int(input()))
if n % 2 != 0:
print('still running')
else:
syn = '+'
Sum = 0
for i in buttonList:
if syn == '+':
Sum += i
syn = '-'
else:
Sum -= i
syn = '+'
... |
from datetime import datetime
from .base import CpObject
class ApplepaySession(CpObject):
epoch_timestamp: datetime = None
expires_at: datetime = None
merchant_session_identifier: str = None
nonce: str = None
merchant_identifier: str = None
domain_name: str = None
display_name: str = Non... |
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
#添加层
def add_layer(inputs, in_size, out_size, n_layer, activation_function=None):
layer_name = 'layer' + n_layer
with tf.name_scope(layer_name):
with tf.name_scope('weights'):
Weights = tf.Variable(tf.random_normal([... |
from .api.players import * |
"""Template tags provided by projectroles for use in other apps"""
import mistune
from importlib import import_module
from django import template
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.staticfiles import finders
from django.core.exceptions import ObjectDoe... |
import torch.nn as nn
import torch
from at_learner_core.models.wrappers.losses import get_loss
from at_learner_core.models.wrappers.simple_classifier_wrapper import SimpleClassifierWrapper
from at_learner_core.models.architectures import get_backbone_block
from ..architectures.transformer import TransformerEncoder
from... |
# -*- coding: utf-8 -*-
##############################################################################
# Copyright (c), Gianfranco Ulian and Giovanni Valdre'. #
# All rights reserved. #
# ... |
'''def fatorial(num = 1):
f = 1
for c in range(num, 0, -1):
f *= c
return f
n = int(input('Digite um número:'))
print(f'O fatoria de {n} é {fatorial(n)}')
f1 = fatorial(4)
f2 = fatorial(5)
f3 = fatorial()
print(f'Os resultados são {f1}, {f2} e {f3}')'''
def parOuImpar(n = 0):
if n % 2 == 0:... |
"""
This script provides an example to wrap UER-py for feature extraction.
"""
import sys
import os
import torch
import torch.nn as nn
import argparse
import numpy as np
uer_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
sys.path.append(uer_dir)
from uer.layers import *
from uer.... |
from w3lib.http import basic_auth_header
from scrapy.utils.project import get_project_settings
class ProxyMiddleware(object):
def process_request(self, request, spider):
settings = get_project_settings()
request.meta['proxy'] = settings.get('PROXY_HOST') + ':' + settings.get('PROXY_PORT')
... |
from __future__ import print_function
import subprocess
import logging
from ..address_translator import AT
l = logging.getLogger('cle.backends.symbol')
class Symbol:
"""
Representation of a symbol from a binary file. Smart enough to rebase itself.
There should never be more than one Symbol instance rep... |
import polars as pl
class GroupClassification:
def __init__(self, zid, df, min_thickness):
self.zid = zid
start_depth = df["depth"][0]
df_group = df[:, ["depth", "soil_type"]]
self.df_group = (
df_group.pipe(self.group_equal_layers, "soil_type", "depth", start_depth)
... |
# Copyright 2013 Google 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 ... |
## Train a D2v Model on 100% of data
import pandas as pd
import sanalytics.estimators.d2vestimator as sed
import logging
logging.basicConfig(level=logging.DEBUG)
## Read all data
X = pd.read_parquet("datasets/model_selection_CV/train.parquet")
x = pd.read_parquet("datasets/model_selection_CV/test.parquet")
X = pd.conc... |
# -*- coding: utf-8 -*-
# Copyright 2020 The HuggingFace Inc. team and Minh Nguyen (@dathudeptrai)
#
# 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/LICEN... |
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
from bs4 import BeautifulSoup
import numpy as np
import requests
setList = np.genfromtxt(r'20190926.txt')
session = requests.Session()
pieces = 0
unfound = 0
sets = len(setList)
for i, st in enumerate(setList):
re... |
'''
https://www.kdnuggets.com/2019/08/numpy-neural-networks-computational-graphs.html
neuron
z = w1⋅x1 + w2⋅x2 + b,
σ(z) = 1 / (1 + e^-z)
∂L / ∂ŷ = ∂(1/2(ŷ - y)^2) / ∂ŷ = -(y - ŷ)
dŷ / dz = ŷ⋅(1 - ŷ) => ∂L / ∂z = (∂L / ∂ŷ)⋅(∂ŷ / ∂z)
∂L / ∂w1 = (∂L / ∂z)⋅(∂z / ∂w1) = (∂L / ∂z)⋅x1
∂L /... |
import argparse
import os
import re
import importlib
from core_data_modules.logging import Logger
from storage.google_cloud import google_cloud_utils
log = Logger(__name__)
def get_file_paths(dir_path):
# search for .gzip archive files only because os.listdir(dir_path)
# returns all files in the directory... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.