text stringlengths 1 927k |
|---|
from scipy.special import comb
def mendelian_probability(k, m, n):
'''
Calculates the chance of getting dominant alleles in a population
Input params:
k = homozygous dominant
m = heterozygous
n = homozygous recessive
'''
total_population = k + m + n
total_combinations = comb(total... |
import aiohttp
from flask import Flask
from aio_executor import run_with_asyncio
app = Flask(__name__)
async def get_random_quote():
async with aiohttp.ClientSession() as session:
async with session.get('https://api.quotable.io/random') as response:
quote = await response.json()
return f'... |
from .platform_mapping import PlatformMapper |
import pandas as pd
from test_importer import Importer
from functools import lru_cache
class Analyzer:
def __init__(self, *args, **kwargs):
self._importer = Importer(database_name=kwargs["database_name"])
self.data = self._importer.create_dataframe()
# Without maxsize the cache will preserve ... |
from Main.Tools import *
from time import time
import matplotlib.pyplot as plt
import numpy
#Parametros Globales
dataset_path = "../Data/ciudades_europa" # 1- "../Data/ciudades_europa 2- "../Data/region_metropolitana 3- "../Data/cities
origin_name = "Madrid" #Nombre de la ciudad, depende del dataset
population_siz... |
def make_docker_file(language, algo_name, handler):
docker_setup = '# syntax=docker/dockerfile:1'
lambda_language = 'FROM public.ecr.aws/lambda/' + language
copy_reqs = 'COPY requirements.txt .'
run_reqs = 'RUN pip install -r requirements.txt'
copy_algo = 'COPY ' + algo_name + ' ./'
cmd_handler ... |
class Solution:
# @param A : string
# @return a strings
def solve(self, a):
stack=[]
for c in a:
if(len(stack)==0 or c!=stack[-1]):
stack.append(c)
else:
stack.pop()
return "".join(stack)
"""
Problem Description
You are give... |
"""
CanICA
"""
# Author: Alexandre Abraham, Gael Varoquaux,
# License: BSD 3 clause
from operator import itemgetter
import numpy as np
from scipy.stats import scoreatpercentile
from sklearn.decomposition import fastica
from sklearn.externals.joblib import Memory, delayed, Parallel
from sklearn.utils import check_ran... |
#! /usr/bin/python
# -*- coding: utf-8 -*-
import os
import sys
import gzip
import math
import pickle
import progressbar
import re
import requests
import shutil
import tarfile
import time
import zipfile
from tqdm import tqdm
from six.moves import cPickle
# from six.moves import zip
from lxml import etree
import xm... |
description = """
One platform for many solutions regarding health issues. 🚀


:
def __init__(self,nombre, apellido1, apellido2):
self.nombre=nombre
self.apellido1=apellido1
self.apellido2=apellido2
def saludo1(resquest): # primera vista
#nombr... |
from tensorflow_od_saved_model import *
camera = cv2.VideoCapture(0)
_,image_np=camera.read()
input_tensor = np.expand_dims(image_np, 0)
detections= detect_fn(input_tensor) |
__copyright__ = "Copyright (c) 2020 Jina AI Limited. All rights reserved."
__license__ = "Apache-2.0"
import glob
import json
import urllib.parse
import urllib.request
import webbrowser
from typing import Dict
from .checker import *
from .database import MongoDBHandler
from .helper import handle_dot_in_keys
from ..cl... |
#!/usr/bin/env python
# This returns a formattedDate attribute on each occurrence,
# this is deprecated, as it requires i18n on both client and
# server side. Formatting is now done on the client side.
from wsgiref.simple_server import make_server
from wsgiref.util import setup_testing_defaults
from mimetypes import ... |
# -*- coding: utf-8 -*-
#
# Unless explicitly stated otherwise all files in this repository are licensed
# under the Apache 2 License.
#
# This product includes software developed at Datadog
# (https://www.datadoghq.com/).
#
# Copyright 2018 Datadog, Inc.
#
"""config.py
Configuration for the Flask application.
"""
... |
#!/usr/bin/env python
#
# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution... |
import re
import sys
def simplifyPath(Path):
Pathstore = re.split('/',Path)
Pathoutput = []
for item in Pathstore:
if item == '':
pass
elif item == '..':
try:
Pathoutput.pop()
except:
pass
elif item == '.':
... |
import cgi
import os
import time
import mimetypes
from wsgiref.headers import Headers
import json
from wsgiref.simple_server import make_server
from http.cookies import SimpleCookie
def notfound_404(environ, start_response):
start_response('404 Not Found', [ ('Content-type', 'text/plain; charset=UTF-8') ])
re... |
#
# * The source code in this file is based on the soure code of CuPy.
#
# # NLCPy License #
#
# Copyright (c) 2020-2021 NEC Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are ... |
# Ranger deep learning optimizer - RAdam + Lookahead + Gradient Centralization, combined into one optimizer.
# https://github.com/lessw2020/Ranger-Deep-Learning-Optimizer
# and/or
# https://github.com/lessw2020/Best-Deep-Learning-Optimizers
# Ranger has now been used to capture 12 records on the FastAI leaderboard.
... |
# Toolkit used for Classification
# Importing Libraries
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from sklearn.ensemble import RandomForestClassifier
# Logistic Regression Classification
def logRegress(X_train, y_train, X_test, y_test):
# Fitting Logistic Regression to the Tr... |
# Copyright 2012 OpenStack Foundation
#
# 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 -*-
from openprocurement.auctions.core.utils import opresource
from openprocurement.auctions.core.views.mixins import AuctionAuctionResource
@opresource(name='belowThreshold:Auction Auction',
collection_path='/auctions/{auction_id}/auction',
path='/auctions/{auction_id}/auc... |
import io
from contextlib import redirect_stdout
from unittest.mock import Mock, patch
from urllib.parse import urljoin
import pytest
from django.db.models import Case, F, When
from django.shortcuts import reverse
from django.templatetags.static import static
from django.urls import translate_url
from measurement.mea... |
from . import db
from flask_login import UserMixin
class User(db.Model, UserMixin):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(150), nullable=False)
email = db.Column(db.String(150), unique=True, nullable=False)
password = db.Column(db.String(15... |
import logging
import requests
from django.conf import settings
from django.contrib.sitemaps import ping_google
logger = logging.getLogger(__name__)
class SpiderNotify():
@staticmethod
def baidu_notify(urls):
try:
data = '\n'.join(urls)
result = requests.post(settings.BAIDU_N... |
# coding: utf-8
"""
Onshape Clients CLI
The CLI for managing the Onshape Clients.
"""
from setuptools import setup, find_packages # noqa: H301
import os
NAME = "cli"
REQUIRES = ["click", "twine", "black"]
setup(
name=NAME,
version="0.0.0",
description="Onshape Clients CLI",
author_email="... |
# This script takes a bed file that is the result of the wig2bed operation and converts it to the bed format expected by mutperiod.
from mutperiodpy.helper_scripts.UsefulFileSystemFunctions import DataTypeStr, getDataDirectory
from mutperiodpy.Tkinter_scripts.TkinterDialog import TkinterDialog
from typing import List
i... |
# -*- coding: utf-8 -*-
# ---------------------------------------------------------------------
# Upvel.UP.get_arp
# ---------------------------------------------------------------------
# Copyright (C) 2007-2018 The NOC Project
# See LICENSE for details
# ---------------------------------------------------------------... |
import os
import random
import shutil
def chooseFile(filepath, tarpath):
filedir = os.listdir(filepath)
sample = random.sample(filedir, 500) # random choose 500 contracts
for s in sample:
shutil.copyfile(filepath+"/" + s, tarpath+ "/" +s)
if __name__ == '__main__':
filepath = "/Users/luliu/... |
from brownie import interface
from datetime import datetime
import json
TOTAL_SUPPLY = 10_000
def main():
# address => [token_id]
owners = {}
rkl = interface.IRumbleKongLeague("0xef0182dc0574cd5874494a120750fd222fdb909a")
for i in range(TOTAL_SUPPLY):
print(i)
owner = rkl.ownerOf(i)
... |
#
# Thread safe version
#
# Usage:
#
# 1. Create record keeper object in the main thread:
#
# keeper = TraceRecordKeeper()
#
# 2. Pass the keeper reference to each thread and have them create their own tracers:
#
# class MyThread(Thread):
# def __init__(self, ..., trace_keeper, ...):
# ...
# ... |
import subprocess
from i3pystatus import IntervalModule
class Keyboard_locks(IntervalModule):
"""
Shows the status of CAPS LOCK, NUM LOCK and SCROLL LOCK
Available formatters:
* `{caps}` — the current status of CAPS LOCK
* `{num}` — the current status of NUM LOCK
* `{scroll}` — the current ... |
# ah but I am not interested in web development with python! |
import enum
class Colour(enum.Enum):
BLACK = 0
WHITE = 1 |
# TF code scaffolding for building simple models.
# 为模型训练和评估定义一个通用的代码框架
import tensorflow as tf
# 初始化变量和模型参数,定义训练闭环中的运算
# initialize variables/model parameters
# define the training loop operations
def inference(X):
# compute inference model over data X and return the result
# 计算推断模型在数据X上的输出,并将结果返回
return... |
def accepts(*types):
def check_accepts(f):
assert len(types) == f.__code__.co_argcount
def new_f(*args, **kwds):
for (a, t) in zip(args, types):
if not isinstance(a, t):
raise TypeError("arg %r does not match type %s" % (a, t))
return f(*a... |
import asyncio
import random
import toga
from toga.constants import ROW, COLUMN
from toga.style import Pack
from .bot import Eliza
class BeelizaApp(toga.App):
async def handle_input(self, widget, **kwargs):
# Display the input as a chat entry.
input_text = self.text_input.value
self.chat... |
import numpy as np
import pandas as pd
import pytest
from autogluon.core.constants import BINARY, MULTICLASS, REGRESSION, SOFTCLASS
from autogluon.core.data.label_cleaner import LabelCleaner, LabelCleanerBinary, LabelCleanerMulticlass, LabelCleanerMulticlassToBinary, LabelCleanerDummy
def test_label_cleaner_binary()... |
from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
import pickle
from audio_system import *
class PollGoogle():
def __init__(self):
#sets up spreadsheet connection
self.SCOPES = 'https://www.googleapis.com/auth/spreadsheets'
s... |
"""
83 删除排序链表中的重复元素
"""
from TreeNode import ListNode
print("83. 删除排序链表中的重复元素")
def deleteDuplicatesOne(head):
dp = []
last = ListNode(0)
pre = head
while pre:
if pre.val not in dp:
dp.append(pre.val)
last.next = pre
last = pre
pre = pre.next
l... |
"""
Test the SensitivityDriver component
"""
import unittest
# pylint: disable-msg=F0401,E0611
from openmdao.main.datatypes.api import Array, Float
from openmdao.lib.drivers.sensitivity import SensitivityDriver
from openmdao.main.interfaces import IHasParameters, implements
from openmdao.main.hasparameters import Has... |
from xnas.search_space.NASBench1shot1.ops import *
from xnas.core.utils import index_to_one_hot, one_hot_to_index
class NASBench1shot1Cell(nn.Module):
def __init__(self, steps, C_prev, C, layer, search_space):
super(NASBench1shot1Cell, self).__init__()
self._steps = steps
self._choice_bl... |
import unittest
from anchore_engine.util.maven import MavenVersion
class TestMavenVersionHandling(unittest.TestCase):
_versions_qualifier_ = ['1-alpha2snapshot', '1-alpha2', '1-alpha-123', '1-beta-2', '1-beta123', '1-m2', '1-m11',
'1-rc', '1-cr2', '1-rc123', '1-SNAPSHOT', '1', '1-sp',... |
"""mysite URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based ... |
from LinkedList import LinkedList
class HashTable:
def __init__(self):
self.__length = 16
self.__buckets = []
for _ in range(self.__length):
self.__buckets.append(LinkedList())
def _get_bucket(self, key):
return hash(key) % self.__length
def insert(self, item):
bucket_key = self._get... |
"""show_ntp.py
NXOS parsers for the following show commands:
* show ntp peer-status
* show ntp peers
"""
# Python
import re
# Metaparser
from genie.metaparser import MetaParser
from genie.metaparser.util.schemaengine import Schema, Any, Optional
# import parser utils
from genie.libs.parser.utils.common im... |
from controller import get_logger
START = "startMessage"
class Parser:
logger = get_logger("Parser")
def __init__(self):
self._data = None
def parse(self, data):
self.logger.debug("Parsing data: \"%s\"", data)
if data.startswith(START):
self._data = data
... |
# -*- coding: utf-8 -*-
import datetime
from django.contrib.auth.decorators import login_required
from django.forms import ModelForm
from django.http import HttpResponse
from django.shortcuts import render
from django.template import RequestContext
from django.template.loader import render_to_string
from autenticar.co... |
#!/usr/bin/env python
'''
Parser for articles retrieved from the Wikipedia API for CitationHunt.
Given a file with one pageid per line, this script will find unsourced
snippets in the pages in the pageid file. It will store the pages containing
valid snippets in the `articles` database table, and the snippets in the
... |
matriz = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
somap = cont = somat = 0
for l in range(0, 3):
for c in range(0, 3):
n = ' '
while n.isnumeric() == False:
n = input(f'digite um valor para [{l}, {c}]: ')
if n.isnumeric() == False:
print('o valor digitado não e um nú... |
"""
Revision ID: 0314_no_reply_template
Revises: 0313_disable_pinpoint_provider
Create Date: 2021-02-09 13:37:42
"""
from alembic import op
from flask import current_app
revision = '0314_no_reply_template'
down_revision = '0313_disable_pinpoint_provider'
templates = [
{
'id': current_app.config['NO_RE... |
class Solution(object):
def backspaceCompare(self, S1, S2):
r1 = len(S1) - 1
r2 = len (S2) - 1
while r1 >= 0 or r2 >= 0:
char1 = char2 = ""
if r1 >= 0:
char1, r1 = self.getChar(S1, r1)
if r2 >= 0:
char2, r2 = self.... |
#!/usr/bin/env python
# compatibility with python 2/3:
from __future__ import print_function
from __future__ import division
import numpy as np
def init():
# Accepted file types
global ftypes
ftypes = {}
ftypes['1d'] = ['S1D',
's1d',
'ADP',
... |
import numpy as np
from bokeh.plotting import figure, show, output_notebook
from bokeh.layouts import gridplot
from bokeh.io import push_notebook
#output_notebook()
import numpy as np
def local_regression(x0, X, Y, tau):
# add bias term
x0 = np.r_[1, x0] # Add one to avoid the loss in information
X = np.... |
"""
This file is for models creation, which consults options
and creates each encoder and decoder accordingly.
"""
import re
import torch
import torch.nn as nn
from torch.nn.init import xavier_uniform_
import onmt.inputters as inputters
import onmt.modules
from onmt.encoders.rnn_encoder import RNNEncoder
from onmt.enc... |
def hasCycle(self, head):
fast = slow = head
while slow and fast and fast.next:
slow = slow.next # Step of 1
fast = fast.next.next # Setp of 2
if slow is fast: # Checking whether two pointers meet
return True
return False |
def do_twice(func):
def wrapper_do_twice():
func()
func()
return |
frase = str(input('Digite uma frase: ')).upper().strip()
print(f'A letra "A" aparece {frase.count("A")} vezes na frase.')
print(f'A primeira letra A apareceu na posição {frase.find("A")+1}.')
print(f'A última letra A apareceu na posição {frase.rfind("A")+1}.')
## .join(frase.split()) juntar tudo, remover espaços |
#!/usr/bin/env python
#-*- coding:utf-8; mode:python; indent-tabs-mode: nil; c-basic-offset: 2; tab-width: 2 -*-
from .criteria import criteria
class max_depth_criteria(criteria):
'make sure the file path depth is less than or equal to a max depth.'
def __init__(self, max_depth):
super(max_depth_criteria, se... |
import json
logger = None
name = 'Vendor'
uuid = 'vendor-123'
level = 'device'
vendor_file = 'plugins/vendor/mac_vendor'
with open(vendor_file, 'r', encoding="utf-8") as fp:
vendor_data = fp.readlines()
vendors = {}
for vnd in vendor_data:
vnd_parts = vnd.split('\t')
vendors[vnd_parts[0].strip()] = vnd_pa... |
'''
Python MySQL Drop Table
Delete a Table
You can delete an existing table by using the "DROP TABLE" statement.
Drop Only if Exist
If the the table you want to delete is already deleted, or for any other reason does not exist, you can use the IF EXISTS keyword to avoid getting an error.
'''
import mysql.connect... |
# Coding challenges solutions on Edabit platform
# TASK - How Edabit Works
def hello():
return "hello edabit.com"
# TASK - Return the Sum of Two Numbers
# Create a function that takes two numbers as arguments and return their sum.
def addition(num1, num2):
return num1 + num2
# TASK - Return the Next Numbe... |
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 31 07:32:13 2021
@author: Gary
In this script, the cas master list is merged with the CAS reference list
created from the SciFinder searches.
The steps in this process:
- fetch the reference dataframes for authoritative CAS numbers and deprecated ones.
- find and mark... |
from .validate import anyof, bool_type, dictof, keyed, listof, int_type, nullable, \
numeric, oneof, regex, required, str_type, switch, ValidationError
__all__ = [
'anyof',
'bool_type',
'dictof',
'keyed',
'listof',
'int_type',
'nullable',
'numeric',
'oneof',
'regex',
're... |
"""
Module containing base classes that represent object entities that can accept
configuration, start/stop/run/abort, create results and have some state.
"""
import os
import sys
import time
import signal
import threading
import traceback
from collections import deque, OrderedDict
import psutil
from schema import Or... |
"""
Basic loop implementation for ffi-based cores.
"""
# pylint: disable=too-many-lines, protected-access, redefined-outer-name, not-callable
from __future__ import absolute_import, print_function
from collections import deque
import sys
import os
import traceback
from gevent._ffi import _dbg
from gevent._ffi import ... |
# !/usr/bin/env python
from distutils.core import setup
setup(
name="gitlab-ci-linter",
packages=["gitlab_ci_linter"],
version="1.0.0",
description=".gitlab-ci.yml linter script",
author="Alexey Burov",
license="MIT",
author_email="allburov@gmail.com",
url="https://gitlab.com/devopshq/... |
from flask import Flask
from flask_restful import Resource, Api
#import para ações
from yahoo_fin import stock_info
#import para opções
from lxml import html
import requests
#
#---------------------------------------------
#
app = Flask(__name__)
api = Api(app)
class Home(Resource):
def get(self):
re... |
# coding=utf-8
"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from tests import IntegrationTestCase
from tests.holodeck import Request
from twilio.base.exceptions import TwilioException
from twilio.http.response import Response
class MemberTestCase(Integration... |
"""
https://www.codewars.com/kata/57f781872e3d8ca2a000007e/train/python
Given a list, return a list in which each of the values of the input list is doubled.
Use map()
"""
def maps(a):
return list(map(lambda x: x*2, a))
print(maps([1, 2, 3])) |
"""
Restaurant management System is a genuine project developed by Somdev Behera and Soumya Ranjan Barik for
their academic year computer science project. This project is aimed to be used for the betterment of the targeted
audience. Restaurant management system is developed using python and MySql date bases. This proj... |
# -*- coding: utf-8 -*-
#
# Copyright 2019-2021 - Swiss Data Science Center (SDSC)
# A partnership between École Polytechnique Fédérale de Lausanne (EPFL) and
# Eidgenössische Technische Hochschule Zürich (ETHZ).
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in c... |
import Tkinter as tk
import ScrolledText as tkst
import time
import csv
from enum import Enum
class GUI(tk.Tk):
MAX_PORTS = 6
AnalogFrames = ["A0", "A1", "A2", "A3","A4", "A5"]
SensorFrames = AnalogFrames + ["SDC30", "SDS011"]
FramesList = SensorFrames
_sensor_update_flag = False
sensorList... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.autosummary",
"sphinx.ext.coverage",
"sphinx.ext.doctest",
"sphinx.ext.extlinks",
"sphinx.ext.ifconfig",
"sphinx.ext.napoleon",
"sphinx.ext.todo",
"sphinx.ext.... |
#!/usr/bin/python
#
# Copyright 2014 Google 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 required b... |
import os
import qrcode
from ckeditor.fields import RichTextField
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
from django.db import models
from mptt.models import MPTTModel, TreeForeignKey
from . import constants
User = get_user_m... |
import numpy as np
import torch
from torch import Tensor
from PIL import Image, ImageEnhance
def torch_none(x: Tensor):
return x
def torch_rot90_(x: Tensor):
return x.transpose_(2, 3).flip(2)
def torch_rot90(x: Tensor):
return x.transpose(2, 3).flip(2)
def torch_rot180(x: Tensor):
return x.flip... |
import wikipedia
import os
from bs4 import BeautifulSoup
import sys, os
pathname = os.path.dirname(sys.argv[0])
fullpath = os.path.abspath(pathname)
mpsrc = "https://en.wikipedia.org/wiki/Main_Page"
os.system("touch " + fullpath + "/temp/wmpsrc.html")
os.system("wget " + mpsrc + " -O "+ fullpath + "/temp/wmpsrc.html ... |
#!/usr/bin/env python
# pi_power_led.py
# Copyright (c) 2016 Robert Jones, Craic Computing LLC
# Freely distributed under the terms of the MIT License
# Read the contents of /home/pi/.pi_power_status and light red and green leds accordingly
# The default configuration for the LEDs is Common Anode which works for mo... |
from django.contrib import admin
from .models import Monitoreo
# Register your models here.
admin.site.register(Monitoreo) |
from flask import Flask, current_app, request
from flask import render_template
app = Flask(__name__)
@app.route('/')
def hello_world():
return render_template('index.html')
@app.route('/favicon.ico')
def get_fav():
print(__name__)
return current_app.send_static_file('img/favicon.ico')
@app.route('/e... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'preferences_ui.ui'
#
# Created by: PyQt5 UI code generator 5.14.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Preferences(object):
def setupUi(self, Preferences):
... |
class Problem:
def __init__(self):
self.dist = {}
self.prev = {}
self.edges = {}
self.vertices = set()
self.risk = []
def readInput(self):
f = open(__file__[:-3] + '.in', 'r')
self.risk = []
for line in f.read().strip().split('\n'):
... |
# A test suite for pdb; not very comprehensive at the moment.
import doctest
import os
import pdb
import sys
import types
import codecs
import unittest
import subprocess
import textwrap
from contextlib import ExitStack
from io import StringIO
from test import support
# This little helper class is essential for testin... |
#!/usr/bin/env python
# encoding: utf-8
#
# Copyright (c) 2010 Doug Hellmann. All rights reserved.
#
"""All configuration variables.
"""
#end_pymotw_header
import sysconfig
print 'User base directory:', sysconfig.get_config_var('userbase')
print 'Unknown variable :', sysconfig.get_config_var('NoSuchVariable') |
import torch
def clip_grad(gradient, clip_value):
""" clip between clip_min and clip_max
"""
return torch.clamp(gradient, min=-clip_value, max=clip_value)
def clip_grad_norm(gradient, clip_value):
norm = (gradient**2).sum(-1)
divisor = torch.max(torch.ones_like(norm).cuda(), norm / clip_value)
... |
# -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# 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... |
host = "database-2.crrxsiyyabpk.us-east-2.rds.amazonaws.com"
user = "admin"
passwd = "j79m2xW2boiNvSyjDjvp"
db = "papeles" |
from .get_recent_merges import get_recent_merges
# ======================================================================
### Local Variables:
### eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
### End: |
import sys
import numpy as np
import cv2
import time
import argparse
import yolov2tiny
def resize_input(im):
imsz = cv2.resize(im, (416, 416))
imsz = imsz / 255.0
imsz = imsz[:, :, ::-1]
return np.asarray(imsz, dtype=np.float32)
def image_object_detection(in_image, out_image, debug):
frame = cv... |
#!/usr/bin/env python3
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""
Repos in `yum.conf` can (and do) share Repodata and Rpm objects, so the best
estimate of their total space usage ... |
# Copyright 2015 Huawei Technologies India Pvt Ltd.
# 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
#
# ... |
import math
from random import randrange
quitCheck = False # This variable is what triggers quitting the game
beta = False # This disables the beta cheats
class helpTips:
def helpOpening(self) -> None: # Displays a help menu to the player
print("\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~... |
#!/usr/bin/env python3
# Copyright (c) 2020 The Widecoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
import argparse
import subprocess
import requests
import sys
parser = argparse.ArgumentParser(description='S... |
import random
from django.db import models
from django import forms
from staging.generators import BaseGenerator
class NotInitialized():
pass
class Generator(BaseGenerator):
name = 'Random choice'
slug = 'random-choice'
for_fields = [models.BigIntegerField, models.CharField, models.DecimalField, mod... |
# Copyright (c) 2018-2021, NVIDIA CORPORATION.
from __future__ import annotations
from numbers import Number
from typing import Any, Callable, Sequence, Union, cast
import numpy as np
import pandas as pd
from nvtx import annotate
from pandas.api.types import is_integer_dtype
import cudf
from cudf import _lib as libc... |
##############################################################################
#
# A simple program to write some data to an Excel file using the XlsxWriter
# Python module.
#
# This program is shown, with explanations, in Tutorial 2 of the XlsxWriter
# documentation.
#
# Copyright 2013, John McNamara, jmcnamara@cpan.o... |
r"""
Free modules
Sage supports computation with free modules over an arbitrary commutative ring.
Nontrivial functionality is available over `\ZZ`, fields, and some principal
ideal domains (e.g. `\QQ[x]` and rings of integers of number fields). All free
modules over an integral domain are equipped with an embedding in... |
"""Collect pop music dataset."""
import argparse
import logging
import operator
import random
from pathlib import Path
import joblib
import muspy
import tqdm
from arranger.utils import load_config, setup_loggers
# Load configuration
CONFIG = load_config()
def parse_arguments():
"""Parse command-line arguments.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.