content stringlengths 5 1.05M |
|---|
from .views import bp |
#!/usr/bin/env python3
# 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.
# types of exceptions thrown when an agent exits the chat. These are thrown
# on a failed act call call. If one of these... |
# pyOCD debugger
# Copyright (c) 2018-2019 Arm Limited
# Copyright (c) 2021 Chris Reed
# SPDX-License-Identifier: Apache-2.0
#
# 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... |
import itertools
import numpy as np
from src.competitors.competitor_models import UMAP, tSNE
from src.competitors.config import ConfigGrid_Competitors
from src.datasets.datasets import SwissRoll, MNIST_offline
from src.evaluation.config import ConfigEval
umap_mnist_euler_multi = [ConfigGrid_Competitors(
model_c... |
import argparse
import sys
import math
sys.path.append('_model')
from environment import *
### Parsing arguments
parser = argparse.ArgumentParser()
parser.add_argument('--visualize', help='whether to plot the swarm or not, default is 0', required=False, type=int, default=0)
parser.add_argument('--numIndividuals', hel... |
""" Writing our first randomforest code.
Author : NaHopayega
Date : 18th dec 2016
"""
import pandas as pd
import numpy as np
import random
import csv as csv
from sklearn.ensemble import RandomForestClassifier
from sklearn import linear_model, decomposition, datasets
from collections import Counter
from sklearn.svm im... |
import difflib
import winreg
import os
keys = []
def get_uninstall_key(package_name : str):
def get_registry_info():
proc_arch = os.environ['PROCESSOR_ARCHITECTURE'].lower()
proc_arch64 = None if 'PROCESSOR_ARCHITEW6432' not in os.environ.keys() else os.environ['PROCESSOR_ARCHITEW6432'].lower()
... |
import numpy as np
import unittest as ut
from VOID.dockers import BatchDocker
from VOID.samplers import OriginSampler
from VOID.fitness import MinDistanceFitness
from VOID.tests.test_inputs import load_structure, load_molecule
class TestBatch(ut.TestCase):
def setUp(self):
self.host = load_structure()
... |
# -*- coding: utf-8 -*-
"""Base class for compartmental models."""
from typing import Any, Dict, List
from chime2.util.timeseries import DatetimeArray
class CompartmentalModel(object):
_model_params: List[str] = ['dates']
_alternate_params: List[str] = list()
_compartments: List[str] = list()
@clas... |
import os
from django.conf import settings
from django.core.management import call_command
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from core import models
class Command(BaseCommand):
@property
def help(self):
return 'Dump a game\'s data in... |
# coding: utf-8
"""
anchore_engine.services.policy_engine
This is a policy evaluation service. It receives push-events from external systems for data updates and provides an api for requesting image policy checks # noqa: E501
OpenAPI spec version: 1.0.0
Contact: zach@anchore.com
Generated by: ht... |
from multiprocessing import Process
from time import time_ns
from ptlib.core.queue import BaseQueue
class Worker(Process):
""" Worker class. *** come back*** """
def __init__(self, Task, num_workers, task_id, worker_id, input_q, output_q, meta_q):
self.EXIT_FLAG = False
self.num_workers = nu... |
from pivy import coin
from pivy.utils import get_point_on_screen
from .colors import COLORS
from .plot import plot
from .mesh import simple_quad_mesh, simple_poly_mesh
class Object3D(coin.SoSeparator):
std_col = "black"
ovr_col = "red"
sel_col = "yellow"
non_col = "grey"
def __init__(self, points... |
#!/usr/bin/python
# Author : David DEVANT
# Desc : Generate a map with OSM
# File : MapGenerator.py
# Date : Sept. 11th, 2021
import Logger
from staticmap import * # Used to generate a map from OpenStreetMap database
class MapGenerator:
# CONSTANTS
MARKER_OUTLINE_COLOR = "wh... |
from sharpy.plans.acts import ActUnit
from sc2.ids.unit_typeid import UnitTypeId
from sc2.dicts.unit_trained_from import UNIT_TRAINED_FROM
class TerranUnit(ActUnit):
def __init__(self, unit_type: UnitTypeId, to_count: int = 9999, priority: bool = False, only_once: bool = False):
production_units: set = UN... |
# -*- coding: utf-8 -*-
# copyright: (c) 2020 by Jesse Johnson.
# license: Apache 2.0, see LICENSE for more details.
'''Provide configuration for package management.'''
import os
from dataclasses import dataclass
from typing import Optional
from compendium.config_manager import ConfigFile
# from . import exception
... |
import matplotlib.pyplot as plt
from batching import RiskTopN, BatchBisect
from utils import line_styles, project_list
from learning import IncrementalLearningModel
import sys
sys.setrecursionlimit(15000)
MAX_BATCH_SIZE = 20
RISK_TOP_N = 2
def get_number(prj, approach):
l = IncrementalLearningModel(prj['name'... |
#Demonstração do Laços For's Aninhados
for linha in range (1, 11):
for coluna in range (1, 11):
#Imprimi linha x coluna com tabulação no final
print ( linha * coluna, end="\t" )
#Para saltar linha
print()
|
number = 5
message = 'hello'
none = None
a = 10
b = 20
if number == 5:
print('number is 5')
else:
print('number is not 5')
if number:
print("Number is integer and not empty")
if message:
print("message is not empty and is a str")
if none:
print("print this is none is true")
if number or message... |
import requests
import json
import html
import os
import numpy as np
from time import sleep
import random
import urllib
from bs4 import BeautifulSoup
imdbUrl = "https://www.imdb.com/search/title/?title_type=feature,tv_movie&user_rating=3.0,9.5&num_votes=10000,&sort=user_rating,desc&count=250&"
rotten_url = "https://ww... |
import torch
import torch.nn as nn
class StudentNet(nn.Module):
def __init__(self):
super(StudentNet, self).__init__()
self.features = self._make_layers([64, 'M', 64, 'M', 64, 'M', 64, 'M'])
self.classifier = nn.Linear(256, 10)
def forward(self, x):
out = self.features(x)
... |
from __future__ import unicode_literals
import difflib
def simple_merge(txt1, txt2):
"""Merges two texts"""
differ = difflib.Differ(charjunk=difflib.IS_CHARACTER_JUNK)
diff = differ.compare(txt1.splitlines(1), txt2.splitlines(1))
content = "".join([l[2:] for l in diff])
return content
|
from config import get_arguments
from SinGAN.manipulate import *
from SinGAN.training import *
import SinGAN.functions as functions
import random
if __name__ == '__main__':
parser = get_arguments()
parser.add_argument('--run_name', help='name of experimental run', required=True)
parser.add_argum... |
import pytest
from ansiblemetrics.playbook.num_distinct_modules import NumDistinctModules
script_0 = '- name: install httpd and memcached\n\tcustommodule1:\n\t\tname: "{{ item }}"\n\t\tstate: present\n- ' \
'name: apply the foo config template\n\ttcustommodule3:\n\t\tsrc: templates/src.j2\n\t\tdest: ' \
... |
import asyncio
import pytest
from modelkit.core.model import AsyncModel, Model
def _identity(x):
return x
def _double(x):
return [y * 2 for y in x]
@pytest.mark.parametrize(
"func,items,batch_size,expected",
[
(_identity, [], None, []),
(_identity, [1], None, [1]),
(_iden... |
import logging
import certifi
from ssl import create_default_context
from elasticsearch import Elasticsearch
from jobtech.common import settings
log = logging.getLogger(__name__)
log.info("Using Elasticsearch node for apikeys at %s:%s" %
(settings.ES_HOST, settings.ES_PORT))
if settings.ES_USER and settings... |
__all__ = [
'VtkScene', 'VisApp', '__VERSION__'
]
from .scene import VtkScene
from .app import VisApp
from .animation import VtkSceneAnimation
|
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'GUI_SEMI_FINAL.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 im... |
import sunspec.core.client as client
import time
ipaddr = '134.253.142.29'
port = 502
comm_id = 126
device = client.SunSpecClientDevice(client.TCP, slave_id=comm_id, ipaddr=ipaddr, ipport=port)
for x in range(3):
for p in [25, 50, 75, 100]:
device.settings.read()
print(device.settings)
de... |
"""
https://leetcode.com/problems/final-prices-with-a-special-discount-in-a-shop/
Given the array prices where prices[i] is the price of the ith item in a shop. There is a special discount for items in the shop, if you buy the ith item, then you will receive a discount equivalent to prices[j] where j is the minimum ind... |
# -*- encoding: utf-8 -*-
"""
@File Name : sqlalchemy.py
@Create Time : 2021/7/12 15:53
@Description :
@Version :
@License :
@Author : diklios
@Contact Email : diklios5768@gmail.com
@Github : https://github.com/diklios5768
@Blog :
@Motto ... |
import os
import json
import numpy as np
import librosa
from inputs import get_bit_rates_and_waveforms
from inputs import get_truth_ds_filename_pairs
import tensorflow as tf
from models import deep_residual_network
data_settings_file = 'settings/data_settings.json'
model_settings_file = 'settings/model_settings.json'
... |
ANYCHAR = '.'; ESCAPE = '\\'
REGIONA = '['; REGIONO = ']'; RANGE = '-'; COMPLEMENT = '^'
GROUPA = '(' ; GROUPO = ')'; ALTERNATIVE = '|'
PERHAPS = '?' ; STAR = '*'; JUST_ONE_and_STAR = '+'
EXTENSION = '(?'; SKIPSTORE = '?:'
def match_region(ch, pattern):
""" region: a list of comparation chars and ranges in [] or [... |
from django.contrib.auth import get_user_model
from django.urls import reverse
from django.test import Client
from mixer.backend.django import mixer
from itassets.test_api import ApiTestCase
User = get_user_model()
class RegistersAdminTestCase(ApiTestCase):
client = Client()
def setUp(self):
super(R... |
"""
Django settings for ckc00 project.
Generated by 'django-admin startproject' using Django 1.11.14.
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
... |
#!/usr/bin/env python3
"""
precision
"""
import numpy as np
def precision(confusion):
"""
precision
"""
m = np.diagonal(confusion)
return (m / confusion.sum(axis=0))
|
from datetime import datetime
from math import ceil, floor
import click
from ._base import TG_PLAYER
from ..tinygrail.api import top_week, character_auction, my_auctions
from ..tinygrail.bigc import BigC
def calculate_target_extra(target_rank):
if target_rank in range(1, 4):
return 2000 - 500 * (target_... |
import requests
response = requests.get("http://aosabook.org/en/posa/introduction.html")
print 'status code:', response.status_code
print 'content length:', response.headers['content-length']
print response.text
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 9 09:17:05 2019
@author: timallan
"""
from PIL import Image, ImageDraw
import random
im = Image.open('/Users/timallan/Desktop/whiteFang/01_ASSETS/__IMAGES/_DL/northernLights_1920x1080.png')
w, h = im.size
pixelTotal = w * h
pixelTarget = int(pix... |
import os
import pgu_util
import shu
with open("rexx-archive-list.txt") as tree_listing:
lines = [line.rstrip('\n') for line in tree_listing]
current_directory = "."
file_list = []
for line in lines:
tokens = line.split()
if tokens and len(tokens) >= 3:
if tokens[0] == "Directory":
current_directory = " ".jo... |
# _*_ coding : UTF-8 _*_
import argparse
import pickle
import sys
import time
import numpy as np
import torch
import torch.backends.cudnn as cudnn
import torchvision
import torchvision.transforms as transforms
mean = [0.5070751592371323, 0.48654887331495095, 0.4409178433670343]
std = [0.2673342858792401,... |
import os
import pymongo
from mspasspy.db.client import DBClient
from mspasspy.db.database import Database
from mspasspy.global_history.manager import GlobalHistoryManager
from pyspark import SparkConf, SparkContext
from pyspark.sql import SparkSession
from mspasspy.ccore.utility import MsPASSError
from dask.distribut... |
import sys
sys.path.insert(0,'./../../..')
from limix.core.mean.mean_base import MeanBase as lin_mean
from limix.core.covar import SQExpCov
from limix.core.covar import FixedCov
from limix.core.covar import SumCov
from limix.core.gp import GP
import pdb
import scipy as sp
import scipy.linalg as LA
import time as TIME... |
"""
Copyright (c) 2019 Atos Spain SA. All rights reserved.
This file is part of Croupier.
Croupier is free software: you can redistribute it and/or modify it
under the terms of the Apache License, Version 2.0 (the License) License.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT ANY WARRANTY OF ANY KIND, EXPRESS OR
IMPLIE... |
import json
import os
from cached_property import cached_property
from web3 import Web3, HTTPProvider
from web3.middleware import geth_poa_middleware
from workerregistry.utils import whereami
class Eth(object):
def __init__(self, eth_uri):
self.eth_uri = eth_uri
self.contracts = {}
@cached_p... |
name='networkit'
version='4.1.1'
url='https://networkit.iti.kit.edu/'
download_url='https://pypi.python.org/pypi/networkit'
license='MIT'
author='Christian L. Staudt, Henning Meyerhenke'
author_email = 'christian.staudt@kit.edu, meyerhenke@kit.edu'
description = 'NetworKit is a toolbox for high-performance netwo... |
# Generated by Django 2.0.6 on 2019-11-12 08:28
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Balance',
fields=[
... |
# Python - 3.6.0
litres = lambda time: time // 2
|
#!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import MITgcmutils as mit
plt.ion()
matplotlib.rcParams['ps.useafm'] = True
matplotlib.rcParams['pdf.use14corefonts'] = True
matplotlib.rcParams['text.usetex'] = True
dir0 = '../run/'
dir_grid = dir0 + 'mnc_test_0001/'
fi... |
# -*- coding: utf-8 -*-
from perftest.config import daint_common as default
modules = default.modules | {'PrgEnv-gnu',
'gcc/5.3.0'}
env = dict(default.env,
CXX='g++',
CC='gcc')
cmake_command = default.cmake_command
make_command = default.make_command
sbatch = defau... |
import torchaudio
import torch.nn as nn
import torch
import torch.utils.data as data
import numpy as np
import glob
import os
from utils import all_seed
eps = 1e-6
# Data
class prep_dataset(torch.utils.data.Dataset):
def __init__(self, ds_dir):
self.ds_dir = ds_dir
self.ds_files = [x for x in ... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 24 23:04:17 2022
@author: ranusingh1993
"""
from flask import Flask, jsonify
from flask_restful import Api
from flask_jwt_extended import JWTManager, get_jwt_identity
'''not required anymore with flask jwt extended library.'''
#from Security import authenticate, identity... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2019, Andrea Insabato, Gorka Zamora-López, Matthieu Gilson
#
# Released under the Apache License, Version 2.0 (the "License");
# you may not use this software except in compliance with the License.
# You may obtain a copy of the License at
#
# http://ww... |
#
# AUTO-GENERATED FILE. DO NOT EDIT
# CodeBuff 1.4.19 'Sat Jun 25 14:59:24 PDT 2016'
#
import numpy as np
import matplotlib.pyplot as plt
java_st=[0.07020408, 0.060402684, 0.053435113, 0.05352798, 0.05352798, 0.053435113, 0.053435113, 0.05352798, 0.053435113, 0.053435113, 0.05303761, 0.05303761, 0.05303761, 0.0530376... |
def uniquePathsWithObstacles(obstacleGrid: [[int]]) -> int:
m,n = len(obstacleGrid), len(obstacleGrid[0])
dp = [0] * n
if obstacleGrid[0][0] == 0 :
dp[0] = 1
for i in range(m) :
for j in range(n) :
if obstacleGrid[i][j] == 1 :
dp[j] = 0
continu... |
from conans import ConanFile, tools, CMake
from conans.errors import ConanInvalidConfiguration
from conans.tools import Version
from fnmatch import fnmatch
import os
import tarfile
class FruitConan(ConanFile):
name = "fruit"
description = "C++ dependency injection framework"
url = "https://github.com/cona... |
test_int = 5
test_float = 1.4
test_string = 'omg'
test_bytes = b'lolz'
|
import argparse # Parsing input arguments
import numpy as np # Array processing
import math # sqrt, etc
import matplotlib # Plotting
import matplotlib.pyplot as plt # Plotting
import scipy.constants as consts # Converting safari-time to sec... |
# This program is a simple calculator that takes in put from the user.
# It takes the input and determines the mathematical function to preform.
# Then determines the correct output then prints this to the user, and will
# continue to run until the users enters stop.
# Function that returns the sum of two numbers
def... |
from PyQt5.QtWidgets import QTableWidget, QTableWidgetItem, QWidget, QAbstractItemView
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot, pyqtSignal, Qt
from view.python_core.get_internal_files import get_internal_icons
import pandas as pd
import logging
class QTableWidgetPandasDF(QTableWidget):
de... |
import os
import os.path as osp
import argparse
import pickle
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import random
from operator import itemgetter
from functools import reduce
from argparse import Namespace
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument(... |
# Imports: standard library
import os
import copy
import math
import logging
import warnings
import itertools
# Imports: third party
import numpy as np
import matplotlib as mpl
from scipy import stats, linalg
from matplotlib import pyplot as plt
from scipy.spatial import distance
from tqdm.notebook import tqdm as log_... |
#!../../venv/bin/python3
from pushpy_examples.client.ex_push_manager import ExamplePushManager
m = ExamplePushManager()
m.connect()
ts = m.repl_ts()
print(m.repl_ts().flatten())
# dt = m.local_tasks()
# r = dt.apply(src=lambda *args, **kwargs: repl_ts.flatten())
# print(r)
|
# python 2.7, pytorch 0.3.1
import os, sys
sys.path.insert(1, '../')
import torch
import torchvision
import numpy as np
import subprocess
import random
import torch.nn as nn
import torch.optim as optim
import torchvision.transforms as transforms
import torch.nn.functional as F
from torch.autograd import Variable
from ... |
# MenuTitle: Add Anchors for Each Smart Axis
# -*- coding: utf-8 -*-
__doc__ = """
Adds anchors to the current layer for each smart axis if the current glyph is a smart glyph.
"""
# Glyphs.clearLog()
# Glyphs.showMacroWindow()
l = Glyphs.font.selectedLayers[0]
g = Glyphs.font.selectedLayers[0].parent
for ax in g.sma... |
import os
import json
import requests
from flask_restful import Resource
import util
import config
import model
import resources.apiError as apiError
import resources.kubernetesClient as kubernetesClient
class SystemInfoReport(Resource):
def put(self):
version_center_url = "https://version-center.iiidevo... |
from django.urls import path , include
from . import views
urlpatterns = [
path('', views.index , name = 'index'),
# User Authentication
path('account/login/' , views.login_user , name = 'login'),
path('account/logout/' , views.logout_user , name = 'logout'),
path('account/signup/' , views.signup... |
"""
Utility method for Sublime Text editor
"""
import re
import os.path
import sublime
import sublime_plugin
from zlib import adler32 # adler32 considered faster than crc32
# List of LiveStyle-supported file extensions
supported_syntaxes = ['css', 'less', 'scss']
_settings = None
_sels = {}
try:
isinstance("", bas... |
from unittest.mock import MagicMock, patch
import unittest
from helperFunctions.helperFunctions import fileAllowed
class TestHelperFunctions_fileAllowed(unittest.TestCase):
def setUp(self):
# Set up a number of items that will be used for these tests.
# -- Mock the os.environ method so that we c... |
# 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... |
def d(nums):
l = []
for i in range(0,len(nums),2):
while nums[i] != 0:
l.append(nums[i+1])
nums[i] -= 1
return l
print(d([1,1,2,3]))
|
from eis.EISDataIO import eis_dataframe_from_csv, eis_dataframe_to_csv
import pandas as pd
if __name__ == "__main__":
train_data = eis_dataframe_from_csv("train_data.csv")
train_data = train_data.sample(frac=0.1).reset_index(drop=True)
train_data_split = train_data.sample(frac=0.8).reset_index(drop=True)
... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
class VideoRecord(object):
def __init__(self, row):
self._data = row
@property
def segment_name(self):
return NotImplementedError()
@property
def participant(self):
return NotImp... |
"""
No: 571
Date: 11-04-2020
Problem:
Tower of Hanoi
The Tower of Hanoi is a puzzle game with three rods and n disks, each a different size.
All the disks start off on the first rod in a stack. They are ordered by size, with the largest disk on the bottom and the smallest one at the top.
The goal of ... |
"""
Documentation: https://www.quora.com/What-are-temporal-convolutional-neural-networks
"""
import torch.nn as nn
from typing import Dict
from torch import Tensor
import torch
from helpers import Reshape
class TCNClassifier(nn.Module):
def __init__(self, cfg: Dict):
super(TCNClassifier, self).__ini... |
# ===============================================================================
# Copyright 2017 EXu
#
# 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... |
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from fitclip.mall.views.product import ProductViewSet
from fitclip.mall.views.category import CategoryViewSet, SectionViewSet, SubViewSet
router = DefaultRouter()
router.register(r'products', ProductViewSet)
router.register(r'categ... |
def base_message(user, message, user_group=None):
resp = '''{body}\n
from: {fname} {lname}
'''.format(body=message.body, fname=user.fname, lname=user.lname)
return resp
|
# This is an interesting dice game.
# The game is about collecting the number closest to 13.
# Any number of players can play the game.
from abc import ABCMeta, abstractmethod
from random import randint
from getch import getch
import asyncio
import sys
def handle_stdin():
data = sys.stdin.readline()
event.... |
import os
import sys
import settings
class scm:
@staticmethod
def get_board_path(prjct_name, prjct_path):
pass
@staticmethod
def get_boards(diff1, diff2, prjct_name, kicad_project_path, prjct_path):
pass
@staticmethod
def get_artefacts(prjct_path, board_file):
pass
... |
### =============================================================================
### This script presents a module to create an HDR image from LDR images.
### The script automatically reads the exposure time of LDR images in a user-defined folder.
### The script uses OpenCV and exiftool modules.
### The script is a... |
import time
import numpy as np
import pandas as pd
import csv
from collections import defaultdict
import json
import os
import xlrd
label_map_path = "D:\\open_images\\4metadata\\oidv6-class-descriptions.csv"
train_label_path = "D:\\open_images\\1human\\oidv6-train-annotations-human-imagelabels.csv"
# train_json_file ... |
# -*- coding: utf-8 -*-
"""
A collection of tests for somelib
"""
|
class Solution(object):
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
spiral = [[0]*n for i in range(n)]
x, y, off = 0, 0, 0
for i in range(1, n*n +1):
spiral[y][x] = i
if x == (n-1-off) and y < (n-1-off): y ... |
####################
# POST /account/ #
####################
def test_create_account(flask_client):
shrek = {
"username": "Shrek",
"email": "ceo@swamp.com"
}
res = flask_client.post('/account/', json=shrek)
assert res.status_code == 200
created_user = res.get_json()
# Asse... |
import torch
import torch.nn.functional as F
try:
import torch.backends.cudnn.rnn
except ImportError:
pass
def RNNReLUCell(input, hidden, w_ih, w_hh, b_ih=None, b_hh=None):
hy = F.relu(F.linear(input, w_ih, b_ih) + F.linear(hidden, w_hh, b_hh))
return hy
def RNNTanhCell(input, hidden, w_ih, w_hh, b... |
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
# DSStoreParser
# ------------------------------------------------------
# Copyright 2019 G-C Partners, LLC
# Nicole Ibrahim
#
# G-C Partners licenses this file to you under the Apache License, Version
# 2.0 (the "License"); you may not use this file except in compli... |
import yaml
import os
from pathlib import Path
from django.conf import settings
from django.core.management.base import BaseCommand
from apps.methodologies.models import Task, TaskCondition
class Command(BaseCommand):
help = 'Import checklists'
def handle(self, *args, **options):
import_counter = 0
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
# dummy models to be used during tests
class ModelA(models.Model):
name = models.CharField(max_length=8)
class ModelB(models.Model):
name = models.CharField(max_length=8)
class ModelC(models.Model):
name = mode... |
#!/usr/bin/env python -*- coding: utf-8 -*-
from itertools import product
import numpy as np
from scipy.cluster.hierarchy import linkage, dendrogram, fcluster
import matplotlib.pylab as plt
from texeval import TexEval2015
nd = 2
texeval_corpus = TexEval2015()
sbcs = texeval_corpus.test_subcorpora
sbc = sbcs[nd]
ter... |
import setuptools
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setuptools.setup(
name="neop",
version="0.1.0",
author="Ananthan Sadagopan",
author_email="ananthans1000@gmail.com",
description="Python Package for Predicting Neoantigens and Obtainin... |
"""
Read, display, save video
Capture from camera and display video
cv2.
VideoCapture()
VideoWriter()
"""
# need VideoCapture object; argument is either device index or name of video file
# device index -- specifies which camera; normally one camera, so pass 0 or -1
# in the end, RELEASE the capture!
import n... |
import numpy as np
import matplotlib.cm as cm
import matplotlib.pyplot as plt
import seaborn as sns
from scipy.spatial.distance import cdist
# For reproducibility
np.random.seed(1000)
nb_samples = 1000
n_vectors = 16
delta = 0.05
n_iterations = 1000
if __name__ == '__main__':
# Initialize the dataset and th... |
import os
import logging
import jinja2
import shutil
logger = logging.getLogger(__name__)
class Style(object):
def __init__(self):
self.info = 'info'
self.success = 'success'
self.failure = 'failure'
self.failure_expected = 'failure-expected'
self.failure_result = 'failure... |
import datetime
import json
import urllib
from django.conf import settings
from django.contrib.auth.decorators import user_passes_test
from django.core.urlresolvers import reverse
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import Requ... |
"""
This file implements the engine class;
An instance of this class manages the
game screen and states.
"""
import tcod
from .states.main_menu_state import MainMenu
from .states.game_over_state import GameOver
from .messages import WorldMessage, MessageLog
import pickle
import lzma
from os import remove, path
# -- H... |
from setuptools import setup, find_packages
def scm_version():
def local_scheme(version):
if version.tag and not version.distance:
return version.format_with("")
else:
return version.format_choice("+{node}", "+{node}.dirty")
return {
"relative_to": __file__,
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2022/1/30 10:30 上午
# @Author : xinming
# @File : 160_get_intersection_node.py
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ... |
from setuptools import setup, find_packages
setup(
name='automatic-rvp',
version='1.0.0',
description='RVP Program',
packages=find_packages(),
url='https://github.com/yochai-safrai/RVP',
author='Yochai Safrai',
author_email='yochai.safrai@gmail.com',
py_modules=['rvp', 'makima', 'pade', 'clustering', 'stabiliz... |
#!/usr/bin/env python
import sys
import os
from subprocess import Popen, PIPE
import struct
BOOT_SIGNATURE = 0x6d697374
if __name__ == "__main__":
infile = sys.argv[1]
outfile = sys.argv[2]
# crc32 from libarchive-zip-perl
cksum = Popen(["crc32", infile], stdout=PIPE).communicate()[0]
cksum = in... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.