content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
import sys
from pathlib import Path
from setuptools import find_packages, setup
project_slug = "nptyping"
here = Path(__file__).parent.absolute()
def _get_dependencies(dependency_file):
with open(here / "dependencies" / dependency_file, mode="r", encoding="utf-8") as f:
return f.read().strip().split("\n... | nilq/baby-python | python |
from math import pi
import numpy as np
cm = 0.23
km = 370.0
WIND = 5.0
OMEGA = 0.84
AMPLITUDE = 0.5
CHOPPY_FACTOR = np.array([2.3, 2.1, 1.3, 0.9], dtype=np.float32)
PASSES = 8 # number of passes needed for the FFT 6 -> 64, 7 -> 128, 8 -> 256, etc
FFT_SIZE = 1 << PASSES # size of the textures storing the waves in... | nilq/baby-python | python |
from datasets.kitti import *
from Archs_3D.build_retina3d_model import build_model
from Solver.Solver import Solver
import operator
import logging
import os
import sys
import copy
import datetime
from datasets.distributed_sampler import *
from datasets.dataset_utils import AspectRatioGroupedDataset
import numpy as np
i... | nilq/baby-python | python |
from __future__ import absolute_import, division, print_function
import tensorflow as tf
FLAGS = tf.app.flags.FLAGS
def create_flags():
# Importer
# ========
tf.app.flags.DEFINE_string ('train_files', '', 'comma separated list of files specifying the dataset used for training. multiple ... | nilq/baby-python | python |
"""
Original Demo: http://js.cytoscape.org/demos/concentric-layout/
Original Code: https://github.com/cytoscape/cytoscape.js/blob/master/documentation/demos/concentric-layout/code.js
Note: This example is broken because layout takes a function as input, i.e.
```
layout: {
name: 'concentric',
concentric: func... | nilq/baby-python | python |
import json
import hikari
async def debug(event: hikari.GuildMessageCreateEvent, command: str, config, *args) -> None:
await event.message.respond(json.dumps({
"command": command,
"args": args,
"user": event.message.author.username,
}))
| nilq/baby-python | python |
from .models import TopLevelDomain,WhoisServer,Domain
import json
import dateutil.parser
from django.db.models.functions import Length
import xmltodict
import socket
import pythonwhois
TLD_FIELDS_MAP = {
'@name':"name",
'countryCode' : "country_code" ,
"created": 'created',
"changed": 'changed',
... | nilq/baby-python | python |
# Copyright (c) 2020 - for information on the respective copyright owner
# see the NOTICE file and/or the repository https://github.com/boschresearch/blackboxopt
#
# SPDX-License-Identifier: Apache-2.0
import time
from typing import Callable
import parameterspace as ps
from blackboxopt import Evaluation, EvaluationS... | nilq/baby-python | python |
from typing import Iterator # noqa
from pyramid.config import Configurator
from pyramid.httpexceptions import HTTPInternalServerError
from pyramid.response import Response
from pyramid.request import Request # noqa
import httpretty
import pytest
import _pytest # noqa
import webtest
httpretty.HTTPretty.allow_net_c... | nilq/baby-python | python |
from xmlrpc.server import SimpleXMLRPCServer
from xmlrpc.server import SimpleXMLRPCRequestHandler
import xmlrpc.client
import time
import ntplib
from time import ctime
import _thread
import math
import psutil
s = xmlrpc.client.ServerProxy("http://localhost:9700")
while(True):
per_cpu = psutil.cpu_percent();
... | nilq/baby-python | python |
from models.connection import get_cnx, tables
ballot_table = tables["ballot"]
ballot_info = tables["ballot_info"]
score_table = tables["scores"]
ranks_table = tables["ranks"]
class Ballot:
@staticmethod
def _bool_to_SQL(witness: bool):
return 1 if witness else 0
@staticmethod
def create_ball... | nilq/baby-python | python |
"""
Martin Kersner, m.kersner@gmail.com
seoulai.com
2018
Adapted by Gabriela B. to work with python 2.7 and ROS
"""
from base import Constants
from base import Piece
import rospy #to print debug info
class Rules(object):
@staticmethod
def get_opponent_type(ptype) :
"""Get a type of opponent agent.
... | nilq/baby-python | python |
"""Bubble sort Implementation in python."""
def bubble_sort(unsorted_list):
"""Iterate through an unsorted list and swap elements accordingly."""
# make a copy of the list
unsorted_copy = unsorted_list[:]
for index in range(len(unsorted_list) - 1):
if unsorted_copy[index] > unsorted_copy[ind... | nilq/baby-python | python |
"""Builds a pip package suitable for redistribution.
Adapted from tensorflow/tools/pip_package/build_pip_package.sh. This might have
to change if Bazel changes how it modifies paths.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
impor... | nilq/baby-python | python |
"""
TODO: Insert player name in combat text
"""
import random as random
import threading as threading
import config as config
import items as items
lock = threading.Lock()
def link_terminal(terminal):
global terminal_output
terminal_output = terminal
def success(strength, attack_modifier, defense, att... | nilq/baby-python | python |
# Generated by Django 3.2.3 on 2021-05-26 16:20
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('TrafficMan', '0003_alter_violationprocess_options'),
]
operations = [
migrations.AlterField(
model_name='vehicle',
n... | nilq/baby-python | python |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... | nilq/baby-python | python |
#!/usr/bin/env python
'''
We get the lidar point cloud and use it to determine if there are any obstacles ahead
Author:
Sleiman Safaoui & Kevin Daniel
Email:
snsafaoui@gmail.com
Github:
The-SS
Date:
Oct 3, 2018
'''
# python
from __future__ import print_function
import numpy as np
import copy
import math
from numpy ... | nilq/baby-python | python |
from b3get import to_numpy
import numpy as np
def test_available():
assert dir(to_numpy)
def test_wrong_ds():
assert to_numpy(43) == (None, None)
def test_008():
imgs, labs = to_numpy(8)
assert len(imgs) > 0
assert len(imgs) == 24
assert isinstance(imgs[0], np.ndarray)
assert imgs[0].... | nilq/baby-python | python |
"""/**
* @author [Jai Miles]
* @email [jaimiles23@gmail.com]
* @create date 2020-05-20 13:17:50
* @modify date 2020-08-15 14:38:03
* @desc [
Handlers for mode statistics.
- ModeStatsHandler
TODO: Consider refactoring this into differnet handlers??
]
*/
"""
##########
# Imports
##########
from as... | nilq/baby-python | python |
import re
class Particle:
def __init__(self, number, position, velocity, acceleration):
self.number = number
self.position = position
self.velocity = velocity
self.acceleration = acceleration
self.destroyed = False
def move(self):
for i in range(len(self.accele... | nilq/baby-python | python |
"""
Python code for hashing function
"""
def search(x):
if x > 0:
if has[x][0] == 1:
return True
# if X is negative take the absolute value of x.
x = abs(x)
if has[x][1] == 1:
return True
return False
def insert(a, n):
for i in range(0, n):
if a[i] >= 0:
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import numpy as np
from votesim.votemethods.ranked import borda
def test_wiki_1():
"""Test wiki example,
https://en.wikipedia.org/wiki/Borda_count, Mar-3-2021
"""
# Andrew Brian Catherine David
# A B C D
d = (
[[1, 3, 2, 4]] * 51 +
[[4, 2, 1, 3]]... | nilq/baby-python | python |
from pypy.rpython.memory.gctransform.test.test_transform import rtype
from pypy.rpython.memory.gctransform.stacklessframework import \
StacklessFrameworkGCTransformer
from pypy.rpython.lltypesystem import lltype
from pypy.translator.c.gc import StacklessFrameworkGcPolicy
from pypy.translator.translator import Tran... | nilq/baby-python | python |
from applauncher.kernel import ConfigurationReadyEvent
import redis
class RedisBundle(object):
def __init__(self):
self.config_mapping = {
'redis': {
'host': {'type': 'string', 'default': 'localhost'},
'port': {'type': 'integer', 'default': 6379},
... | nilq/baby-python | python |
"""This class stores all of the samples for training. It is able to
construct randomly selected batches of phi's from the stored history.
"""
import numpy as np
import time
floatX = 'float32'
class DataSet(object):
"""A replay memory consisting of circular buffers for observed images,
actions, and rewards.
... | nilq/baby-python | python |
from .client import ExClient
from .mock import MockTransport
from .models import ResponseMixin
from .transport import AsyncHTTPTransportMixin
| nilq/baby-python | python |
import asyncio
import logging
import synapse.exc as s_exc
import synapse.telepath as s_telepath
import synapse.lib.base as s_base
import synapse.lib.stormtypes as s_stormtypes
logger = logging.getLogger(__name__)
stormcmds = (
{
'name': 'service.add',
'descr': 'Add a storm service to the cortex.... | nilq/baby-python | python |
from datetime import date, datetime
import pytz
from Cinema.models.Actor import Discount
from Cinema.models.Actor import Actor
from Cinema.models.Movie import Movie
from Cinema.models.Projection import Projection, Entry
from Cinema.models.Hall import Seat
from django.db.models import Sum
from django.db.models impo... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
After 40755, what is the next triangle number
that is also pentagonal and hexagonal?
T285 = P165 = H143 = 40755.
"""
def pe45():
"""
>>> pe45()
(1533776805, 27549)
"""
limit = 30000
h = [n * ((n << 1) - 1) for n in range(144, limit)]
p = set... | nilq/baby-python | python |
from kikola.core.context_processors import path
from kikola.core.decorators import render_to, render_to_json
@render_to_json
def context_processors_path(request):
return path(request)
@render_to('core/render_to.html')
def decorators_render_to(request):
return {'text': 'It works!'}
@render_to('core/render_... | nilq/baby-python | python |
from .tasks import (
AsyncTasks,
Tasks,
CloudFunction,
as_completed,
GroupTerminalException,
BoundGlobalError,
)
# Backwards compatibility
from descarteslabs.common.tasks import FutureTask, TransientResultError
TransientResultException = TransientResultError
__all__ = [
"AsyncTasks",
... | nilq/baby-python | python |
#!/usr/bin/env python
#
# utils.py
"""
Utility functions for Markdown -> HTML -> LaTeX conversion.
"""
#
# Copyright © 2020-2021 Dominic Davis-Foster <dominic@davis-foster.co.uk>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (t... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Unit tests for nginxfmt module."""
import contextlib
import logging
import pathlib
import shutil
import tempfile
import unittest
import nginxfmt
__author__ = "Michał Słomkowski"
__license__ = "Apache 2.0"
class TestFormatter(unittest.TestCase):
fmt = nginxfmt.F... | nilq/baby-python | python |
#!/usr/bin/python3
"""
Revision history:
24 Sep 2020 | 1.0 - initial release
"""
DOCUMENTATION = '''
---
module: hjson_to_json.py
author: Sanjeevi Kumar, Wipro Technologies
version_added: "1.0"
short_description: Read an .hjson file and output JSON
description:
- Read the HJON file specified and out... | nilq/baby-python | python |
import django_userhistory.models as models
from django.contrib import admin
try:
admin.site.register(models.UserAction)
admin.site.register(models.UserHistory)
admin.site.register(models.UserTrackedContent)
except Exception, e:
pass | nilq/baby-python | python |
"""
"""
load("@bazel_skylib//lib:shell.bzl", "shell")
def _stately_copy_impl(ctx):
input_files = ctx.files.srcs
if ctx.attr.state_file:
state_file = ctx.attr.state_file
else:
state_file = ".stately.yaml"
args = [
a
for a in ["copy"] + [f.short_path for f in input_files... | nilq/baby-python | python |
from __future__ import unicode_literals
import logging
from django.utils.translation import ugettext as _
import django.views.decorators.cache
import django.views.decorators.csrf
import django.views.decorators.debug
import django.contrib.auth.decorators
import django.contrib.auth.views
import django.contrib.auth.forms... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import unittest
import tempson
from .coloredPrint import *
vm = tempson.vm()
class vmTest(unittest.TestCase):
def test_execute_code (self):
result = vm.evalExpToStr('a + 3', { 'a': 1 }, True)
try:
self.assertEqual(result, '4', 'Evaluate error')
except A... | nilq/baby-python | python |
#!/usr/bin/env python3
# Copyright (c) 2020, the Dart project authors. Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.
import json
import os.path
import re
import sys
_COMPAT_KEY = '__compat'
_EXPERIME... | nilq/baby-python | python |
from django.utils import timezone
def get_now():
"""
Separado para poder establecer el tiempo como sea necesario durante los tests
"""
return timezone.now()
def setallattr(obj, **kwargs):
for k in kwargs:
setattr(obj, k, kwargs.get(k))
def dict_except(obj, *args):
result = {}
f... | nilq/baby-python | python |
"""
Link: https://www.hackerrank.com/challenges/py-if-else/problem?isFullScreen=true
Problem: Python If-ELse
"""
#Solution
#!/bin/python3
import math
import os
import random
import re
import sys
if __name__ == '__main__':
n = int(input().strip())
if n % 2 != 0:
print("Weird")
else:
... | nilq/baby-python | python |
import unittest
from pymal import account
from pymal.account_objects import account_animes
from pymal import anime
from pymal.account_objects import my_anime
from tests.constants_for_testing import ACCOUNT_TEST_USERNAME, ACCOUNT_TEST_PASSWORD, ANIME_ID
class AccountAnimeListTestCase(unittest.TestCase):
EXPECTED... | nilq/baby-python | python |
from django.core.exceptions import ObjectDoesNotExist
from rest_framework.views import APIView
from rest_framework import permissions
from views.retrieve_test_view import TEST_QUESTIONS, retrieve_test_data, is_test_public
class TestQuestionsSet(APIView):
def get(self, request):
return retrieve_tes... | nilq/baby-python | python |
from flask import request
from flask_restplus import Namespace, Resource, fields
from api.utils import validator
from api.service.community_question import get_all_community_questions, create_community_question, get_all_question_comments
from .community_comment import community_comment_schema
import json
api = Names... | nilq/baby-python | python |
import straws_screen
import gravity_screen
import diagon_screen
# 3440 x 1440
# WIDTH = 3440
# HEIGHT = 1440
# 2880 x 1800
WIDTH = 2880
HEIGHT = 1800
# 800 x 800
# WIDTH = 800
# HEIGHT = 800
#my_screen = straws_screen.StrawsScreen();
my_screen = gravity_screen.GravityScreen();
#my_screen = diagon_screen.DiagonScree... | nilq/baby-python | python |
"""
File: hailstone.py
Name: Justin Kao
-----------------------
This program should implement a console program that simulates
the execution of the Hailstone sequence, defined by Douglas
Hofstadter. Output format should match what is shown in the sample
run in the Assignment 2 Handout.
"""
def main():
"""
Use... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Base class for Topologies.
You can use this class to create your own topology. Note that every Topology
should implement a way to compute the (1) best particle, the (2) next
position, and the (3) next velocity given the Swarm's attributes at a given
timestep. Not implementing these methods... | nilq/baby-python | python |
import numpy as np
import numpy.linalg as lin
MAX_ITERS = 20
EPSILON = 1.0e-7
def h(theta, X, y):
margins = y * X.dot(theta)
return 1 / (1 + np.exp(-margins))
def J(theta, X, y):
probs = h(theta, X, y)
mm = probs.size
return (-1 / mm) * np.sum(np.log(probs))
def gradJ(theta, X, y):
... | nilq/baby-python | python |
#############################################################################
#
# Author: Ruth HUEY, Michel F. SANNER
#
# Copyright: M. Sanner TSRI 2000
#
#############################################################################
#
# $Header: /opt/cvs/python/packages/share1.5/AutoDockTools/autotors4Commands.py,v 1.... | nilq/baby-python | python |
################################################################################
# siegkx1.py
#
# Post Processor for the Sieg KX1 machine
# It is just an ISO machine, but I don't want the tool definition lines
#
# Dan Heeks, 5th March 2009
import nc
import iso_modal
import math
###########################... | nilq/baby-python | python |
#!/Users/duhuifeng/Code/RentHouseSite/renthouse/macvenv/bin/python
from django.core import management
if __name__ == "__main__":
management.execute_from_command_line()
| nilq/baby-python | python |
from __future__ import absolute_import
from datetime import timedelta
from django.utils import timezone
from rest_framework.response import Response
from sentry.app import tsdb
from sentry.api.base import EnvironmentMixin
from sentry.api.bases.project import ProjectEndpoint
from sentry.api.exceptions import ResourceD... | nilq/baby-python | python |
# Generated by Django 2.2.1 on 2019-06-08 01:31
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Palace',
fields=[
... | nilq/baby-python | python |
import re
from SingleLog.log import Logger
from . import i18n
from . import connect_core
from . import screens
from . import command
from . import _api_util
def has_new_mail(api) -> int:
cmd_list = list()
cmd_list.append(command.go_main_menu)
cmd_list.append(command.ctrl_z)
cmd_list.append('m')
... | nilq/baby-python | python |
numerator = 32
denominator = 1
print numerator / denominator #dividing by zero, big no-no
#all code below this won't get executed
print "won't get executed"
| nilq/baby-python | python |
from PIL import Image
import os
import glob
saveToPath = "C:\\Users\\phili\\Desktop\\"
filePath = input("File: ")
filePath = filePath[1:-1]
fileName = filePath.split("\\")[len(filePath.split("\\")) - 1]
image = Image.open(filePath)
size = image.size
print("Current image size of " + fileName + " is: " + str(size))... | nilq/baby-python | python |
def log(msg, dry_run=False):
prefix = ''
if dry_run:
prefix = '[DRY RUN] '
print('{}{}'.format(prefix, msg))
| nilq/baby-python | python |
#!/usr/bin/python3
"""
some code taken from huffman.py
"""
import sys
from functools import reduce
from operator import add
from math import log, log2
from random import shuffle, choice, randint, seed
from bruhat.argv import argv
EPSILON = 1e-8
def is_close(a, b):
return abs(a-b) < EPSILON
class Multiset... | nilq/baby-python | python |
from graphene.types.generic import GenericScalar
from ..utils import dashed_to_camel
class CamelJSON(GenericScalar):
@classmethod
def serialize(cls, value):
return dashed_to_camel(value)
| nilq/baby-python | python |
from django.conf.urls import url
from . import views
app_name = 'users'
urlpatterns = [
url(
regex=r'^~redirect/$',
view=views.UserRedirectView.as_view(),
name='redirect'
),
url(
regex=r'^$',
view=views.UserDetailView.as_view(),
name='detail'
),
url(... | nilq/baby-python | python |
import torch
from PIL import Image
import torch.nn.functional as F
def load_image(filename, size=None, scale=None):
img = Image.open(filename).convert('RGB')
if size is not None:
img = img.resize((size, size), Image.ANTIALIAS)
elif scale is not None:
img = img.resize((int(img.size[0] / sca... | nilq/baby-python | python |
class TrapException(RuntimeError):
pass
class Memory:
def __init__(self, comp):
self.storage = dict()
self.comp = comp
def __getitem__(self, key):
if not isinstance(key, int) or key < 0:
self.comp.trap("Invalid memory access key {}".format(key))
else:
... | nilq/baby-python | python |
"""Dependency labeling Edge Probing task.
Task source paper: https://arxiv.org/pdf/1905.06316.pdf.
Task data prep directions: https://github.com/nyu-mll/jiant/blob/master/probing/data/README.md.
"""
from dataclasses import dataclass
from jiant.tasks.lib.templates.shared import labels_to_bimap
from jiant.tasks.lib.te... | nilq/baby-python | python |
from pydigilent import *
import time
ad2 = AnalogDiscovery2()
v = 3.5
ad2.power.vplus.enable = 1
ad2.power.vplus.voltage = v
# after configuring power options, the master must be switched to enable
ad2.power.master.enable = 1
ad2.scope.channel1.vertical_division = 1.
while ad2.scope.channel1.voltage < v:
print... | nilq/baby-python | python |
#!/usr/bin/env python3
#-*- coding:utf-8 -*-
import os
author = " * author:tlming16\n"
email = " * email:tlming16@fudan.edu.cn\n"
license = " * all wrong reserved\n"
text= "/* \n" + author + email+ license +"*/\n";
file_list =os.listdir("./test");
def write_file( f):
if not f.endswith(".cpp"):
return
conte... | nilq/baby-python | python |
# coding: utf-8
# Copyright (c) 2016, 2021, 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... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
pygments.lexers.inferno
~~~~~~~~~~~~~~~~~~~~~~~
Lexers for Inferno os and all the related stuff.
:copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
from pygments.lexer import RegexLexer, include, by... | nilq/baby-python | python |
# Generated by Django 3.2.7 on 2021-11-23 16:39
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Brand',
fields=[
... | nilq/baby-python | python |
#!/user/bin/env python
# -*- coding: utf-8 -*-
import re
import sys
from flask import render_template, request, redirect
from flask_login import current_user
from Web import right_url_prefix as url_prefix, create_blue
from Web import control
sys.path.append('..')
__author__ = 'Zhouheng'
html_dir = "/RIGHT"
develo... | nilq/baby-python | python |
#!/usr/bin/env python 3
# -*- coding: utf-8 -*-
#
# Copyright (c) 2021 PanXu, Inc. All Rights Reserved
#
"""
flat pretrained vocabulary
Authors: PanXu
Date: 2021/02/24 10:36:00
"""
from easytext.data import PretrainedVocabulary, Vocabulary
class FlatPretrainedVocabulary(PretrainedVocabulary):
"""
Flat p... | nilq/baby-python | python |
# This file is part of Indico.
# Copyright (C) 2002 - 2021 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from datetime import timedelta
import pytest
from indico.modules.events import Event
from indico.modules... | nilq/baby-python | python |
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(color_codes=True, font_scale=1)
import itertools
# marker = itertools.cycle(("o", "^", "s"))
marker = itertools.cycle((None,))
markevery = 20
from tensorboard.backend.event_processing import event_accumulator
def plot_result_csv(folders... | nilq/baby-python | python |
loglevel = 'info'
errorlog = "-"
accesslog = "-"
bind = '0.0.0.0:5000'
workers = 2
timeout = 60
| nilq/baby-python | python |
#!/usr/bin/env python
# coding: utf-8
# In[2]:
# In[6]:
# In[16]:
# In[18]:
# In[21]:
from __future__ import division, print_function
# coding=utf-8
import streamlit as st
import h5py
from PIL import Image
import os
import numpy as np
import json
import predict3
from tensorflow.keras.models impor... | nilq/baby-python | python |
#!/usr/bin/env python3
from mpl_toolkits.mplot3d import Axes3D
from rasterization import Rasterizer
from transformation import multiply
from transformation import TransformGenerator
import argparse
import DirectLinearTransform
import json
import math
import matplotlib
import matplotlib.image as mpimg
import matplotlib.... | nilq/baby-python | python |
#!/usr/bin/env python3
import argparse
import gym
import gym-minigrid
from baselines import bench, logger
from baselines.common import set_global_seeds
from baselines.common.cmd_util import make_atari_env, atari_arg_parser
from baselines.a2c.a2c import learn
from baselines.ppo2.policies import MlpPolicy
from baselines... | nilq/baby-python | python |
import os
import torch
from torch import tensor
from typing import Optional, Tuple
from dataclasses import dataclass
from schemes import EventDetectorOutput
from models import BaseComponent
from models.event_detection.src.models.SingleLabelSequenceClassification import SingleLabelSequenceClassification
from stores.onto... | nilq/baby-python | python |
"""test2 URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based... | nilq/baby-python | python |
import xarray as xr
import numpy as np
from xrspatial import hillshade
def _do_sparse_array(data_array):
import random
indx = list(zip(*np.where(data_array)))
pos = random.sample(range(data_array.size), data_array.size//2)
indx = np.asarray(indx)[pos]
r = indx[:, 0]
c = indx[:, 1]
data_ha... | nilq/baby-python | python |
from django.test import TestCase
from django.contrib.auth.models import User
from .models import Profile,Procedure
# Create your tests here.
class ProfileTestClass(TestCase):
def setUp(self):
self.new_user = User.objects.create_user(username='user',password='password')
self.new_profile = Profile(id... | nilq/baby-python | python |
'''Create a segmentation by thresholding a predicted probability map'''
import os
import logging
from time import time as now
import numpy as np
import configargparse as argparse
import daisy
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
# patch: suppre... | nilq/baby-python | python |
import os
import time
import pandas as pd
import numpy as np
import xgboost as xgb
import lightgbm as lgb
import warnings
warnings.filterwarnings('ignore')
from sklearn.metrics import log_loss
from sklearn.model_selection import train_test_split, StratifiedKFold
def lgb_foldrun(X, y, params, name):
skf = Stratif... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Session'
db.create_table('django_session', (
('session_key', self.gf('django.db.... | nilq/baby-python | python |
# ===============================================================================
# Copyright 2012 Jake Ross
#
# 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/licens... | nilq/baby-python | python |
import unittest
from circleofgifts.dealer import Dealer
class DealerTestCase(unittest.TestCase):
def test_sorted_deal(self):
"""Test deal which uses sorted() as the sort method for both teams
and players. This makes the results predicable."""
players = [['Pierre', 'Paul'], ['Jeanne', 'Jul... | nilq/baby-python | python |
from django.shortcuts import render
from django.http import HttpResponse
def explore(request):
return HttpResponse('This will list all chemicals.')
def my_chemicals(request):
return HttpResponse('This will list MY chemicals!')
| nilq/baby-python | python |
import re
# Your puzzle input is 246540-787419.
## Part 1
pwords = []
for i in range(246540,787419):
if(int(str(i)[0]) <= int(str(i)[1]) <= int(str(i)[2]) <= int(str(i)[3]) <= int(str(i)[4]) <= int(str(i)[5])):
if((str(i)[0] == str(i)[1]) or (str(i)[1] == str(i)[2]) or (str(i)[2] == str(i)[3]) or (str(i)[... | nilq/baby-python | python |
class Server(object):
def __init__(self, host, port):
self.host = host
self.port = port
def get_host(self):
return self.host
def get_port(self):
return self.port
class MailType(object):
def __init__(self):
pass | nilq/baby-python | python |
from django import template
import base64
from socialDistribution.models.post import Post, InboxPost
from socialDistribution.utility import get_post_like_info, get_like_text
register = template.Library()
# Django Software Foundation, "Custom Template tags and Filters", 2021-10-10
# https://docs.djangoproject.com/en/3... | nilq/baby-python | python |
"""
Setup of core python codebase
Author: Jeff Mahler
"""
import os
from setuptools import setup
requirements = [
"numpy",
"scipy",
"scikit-image",
"scikit-learn",
"ruamel.yaml",
"matplotlib",
"multiprocess",
"setproctitle",
"opencv-python",
"Pillow",
"joblib",
"colorlog... | nilq/baby-python | python |
from collections.abc import Iterable
from itertools import chain, product
import pprint
import inspect
from .nodes import *
from .graph import *
class GraphGenerator():
def __init__(self, specifications):
"""
Parameters
----------
specifications: Iterable[Specification] -- TODO
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# ---------------------------------------------------------------------
# Allocated Blocks Report
# ---------------------------------------------------------------------
# Copyright (C) 2007-2019 The NOC Project
# See LICENSE for details
# --------------------------------------------------------... | nilq/baby-python | python |
from buildbot.config import BuilderConfig
from buildbot.changes.gitpoller import GitPoller
from buildbot.plugins import util, schedulers
from buildbot.process.factory import BuildFactory
from buildbot.process.properties import Interpolate
from buildbot.process import results
from buildbot.steps.source.git import Git
fr... | nilq/baby-python | python |
import numpy as np
# from crf import Sample, CRF
from crf_bin import Sample, CRFBin
trainCorpus = "/home/laboratory/github/homeWork/machineTranslation/data/train.txt"
testCorpus = "/home/laboratory/github/homeWork/machineTranslation/data/test.txt"
labelTableverse = {}
print("cache label...")
with open("/home/laborat... | nilq/baby-python | python |
# architecture.py ---
#
# Filename: architecture.py
# Description: defines the architecture of the 3DSmoothNet
# Author: Zan Gojcic, Caifa Zhou
#
# Project: 3DSmoothNet https://github.com/zgojcic/3DSmoothNet
# Created: 04.04.2019
# Version: 1.0
# Copyright (C)
# IGP @ ETHZ
# Code:
# Import python dependencies
import... | nilq/baby-python | python |
from django.db import models
from django.contrib.auth.models import User
class UserProfile(models.Model):
""" Extension of User model """
user = models.OneToOneField(User,
on_delete=models.CASCADE,
primary_key=True)
# if vacation mode is set ... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""DigitRecognizer.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/149_-4guTkO2Vzex8bjA402nPcJ_Z7G7W
#***Digit Recognizer(MNIST) dataset using CNN***
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as... | nilq/baby-python | python |
# See LICENSE file for full copyright and licensing details.
#from . import models
| nilq/baby-python | python |
import numpy as np
import utils
# class Piece:
# def __init__(self,color = 0, pos=(-1,-1)):
# self.color = color
# self.pos = pos
class Player:
def __init__(self, collected_flag=np.zeros(9), collected_shape_dict={}, collected_num=0):
self.collected_flag = np.zeros((9,2)) # 收集过... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.