content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
from connect_four.envs import TwoPlayerGameEnvVariables
from connect_four.problem.connecting_group_manager import ConnectingGroupManager
class ConnectFourGroupManager(ConnectingGroupManager):
def __init__(self, env_variables: TwoPlayerGameEnvVariables):
super().__init__(env_variables, num_to_connect=4)
| nilq/baby-python | python |
__author__ = 'Felix Simkovic'
__date__ = '2019-05-11'
__license__ = 'MIT License'
import os
import sys
APPLICATION_NAME = 'Pomodoro TaskWarrior'
if sys.platform.startswith('darwin'):
try:
from Foundation import NSBundle
bundle = NSBundle.mainBundle()
if bundle:
app_info = bun... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# pylint: disable=C0103,C0111
import argparse
import sys
from snake.game import PureGame, GameConf
from snake.utils import dotdict
from snake.rl.coach import Coach
from snake.rl.nnet_wrapper import NNetWrapper
import logging
logging.basicConfig(level=logging.INFO)
sys.s... | nilq/baby-python | python |
# flake8: noqa
# This file is autogenerated by /metadata-ingestion/scripts/avro_codegen.py
# Do not modify manually!
# fmt: off
from ......schema_classes import ChartKeyClass
from ......schema_classes import CorpGroupKeyClass
from ......schema_classes import CorpUserKeyClass
from ......schema_classes import Dashboard... | nilq/baby-python | python |
# // Copyright 2016 The go-vgo Project Developers. See the COPYRIGHT
# // file at the top-level directory of this distribution and at
# // https://github.com/go-vgo/robotgo/blob/master/LICENSE
# //
# // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
# // http://www.apache.org/licenses/LICENSE-2.0> or... | nilq/baby-python | python |
class Solution:
def arrayNesting(self, nums: List[int]) -> int:
max_length = -1
visited = [False] * len(nums)
for i in range(0, len(nums)):
if visited[i]:
continue
start, count = nums[i], 0
visited[i] = True
... | nilq/baby-python | python |
from typing import Dict, List
from elasticsearch_dsl.query import Q
from elasticsearch_dsl.response import Response
from elasticsearch_dsl.response.hit import Hit
from elasticsearch_dsl.search import Search
from flask_restful import Resource, reqparse
from meetup_search.models.group import Group
from .argument_valid... | nilq/baby-python | python |
from a10sdk.common.A10BaseClass import A10BaseClass
class Crl(A10BaseClass):
"""This class does not support CRUD Operations please use parent.
:param crl_sec: {"minLength": 1, "maxLength": 255, "type": "string", "description": "Secondary CRL File Name or URL (http://www.example.com/ocsp) (only .der file... | nilq/baby-python | python |
"""
Noop migration to test rollback
"""
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('oauth_dispatch', '0010_noop_migration_to_test_rollback'),
]
operations = [
migrations.RunSQL(migrations.RunSQL.noop, reverse_sql=migrations.RunSQL.noop)
... | nilq/baby-python | python |
from senscritiquescraper.utils import survey_utils
def test_get_category_from_survey(survey_movie):
if survey_utils.get_category_from_survey(survey_movie) != "films":
raise AssertionError()
def test_get_rows_from_survey(survey_movie):
rows = survey_utils.get_rows_from_survey(survey_movie)
if len... | nilq/baby-python | python |
from jira.exceptions import JIRAError
from tests.conftest import JiraTestCase
class VersionTests(JiraTestCase):
def test_create_version(self):
name = "new version " + self.project_b
desc = "test version of " + self.project_b
release_date = "2015-03-11"
version = self.jira.create_ve... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import logging
from _pytest.main import EXIT_OK, EXIT_NOTESTSCOLLECTED, EXIT_INTERRUPTED # NOQA
def assert_fnmatch_lines(output, matches):
if isinstance(output, str):
output = output.split('\n')
missing = []
for match in matches:
if match not in output:
... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: Deformable ConvNets v2: More Deformable, Better Results
# Modified by: RainbowSecret(yuyua@microsoft.com)
# Select Seg Model for img segmentation.
import pdb
import torch
import torch.nn as nn
import torch.utils.checkpoint as cp
from collections import O... | nilq/baby-python | python |
class LoggerError(Exception):
""" Base class for all logger error classes.
All exceptions raised by the benchmark runner library should inherit from this class. """
pass
class MethodError(LoggerError):
"""
This class is fot method error
"""
def __init__(self, method_name, exception):
... | nilq/baby-python | python |
# Generated by Django 3.1.7 on 2021-12-24 18:34
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('tracker', '0005_movie_poster'),
]
operations = [
migrations.AddField(
model_name='movie',
name='cast',
f... | nilq/baby-python | python |
"""Coding Quiz: Check for Prime Numbers
Prime numbers are whole numbers that have only two factors: 1 and the number itself. The first few prime numbers are 2, 3, 5, 7.
For instance, 6 has four factors: 1, 2, 3, 6.
1 X 6 = 6
2 X 3 = 6
So we know 6 is not a prime number.
In the following coding environment, write cod... | nilq/baby-python | python |
import timm
import torchvision.models as models
""""
timm_models = [
'adv_inception_v3',
'cait_m36_384',
'cait_m48_448',
'cait_s24_224',
'cait_s24_384',
'cait_s36_384',
'cait_xs24_384',
'cait_xxs24_224',
'cait_xxs24_384',
'cait_xxs36_224',
'cait_xxs36_384',
'coat_lite_min... | nilq/baby-python | python |
#
# Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
#
"""
Service monitor to instantiate/scale/monitor services like firewall, LB, ...
"""
import sys
reload(sys)
sys.setdefaultencoding('UTF8')
import gevent
from gevent import monkey
monkey.patch_all(thread=not 'unittest' in sys.modules)
from cfgm_comm... | nilq/baby-python | python |
from .db.models import ModelWorker
from .db.connection import DbEngine
ModelWorker.metadata.create_all(DbEngine)
| nilq/baby-python | python |
import string
def encotel(frase):
teclado = {
'abc' : '2',
'def' : '3',
'ghi': '4',
'jkl': '5',
'mno' : '6',
'pqrs' : '7',
'tuv' : '8',
'wxyz' : '9',
}
numeros = []
for letra in frase:
if letra not in string.letters:
numeros.append(letra)
continue
numeros.extend([teclado[chave... | nilq/baby-python | python |
import itertools
import beatbox
import pandas as pd
def query_salesforce(line, query=''):
"""Runs SQL statement against a salesforce, using specified user,password and security token and beatbox.
If no user,password and security token has been given, an error will be raised
Examples::
... | nilq/baby-python | python |
#!/usr/bin/env python3
import functools
import logging
import queue
import threading
class AsyncCaller:
'''Singleton class which executes function calls in separate thread'''
class _Caller:
class Thread(threading.Thread):
def __init__(self, queue, error_handler):
self.queue... | nilq/baby-python | python |
from pyson0.json0diff import diff
from pyson0.json0 import TypeJSON | nilq/baby-python | python |
import uuid
import json
import os
import pytest
import postgraas_server.backends.docker.postgres_instance_driver as pid
import postgraas_server.backends.postgres_cluster.postgres_cluster_driver as pgcd
import postgraas_server.configuration as configuration
from postgraas_server.backends.exceptions import PostgraasApiE... | nilq/baby-python | python |
import argparse
import ibapi
from ib_tws_server.codegen.asyncio_client_generator import AsyncioWrapperGenerator
from ib_tws_server.codegen import *
from ib_tws_server.api_definition import *
import logging
import os
import shutil
import sys
logging.basicConfig(stream=sys.stdout, level=logging.ERROR)
def generate(out... | nilq/baby-python | python |
import unittest
from cornflow_client.airflow import dag_utilities as du
from unittest.mock import Mock, patch
class DagUtilities(unittest.TestCase):
@patch("cornflow_client.airflow.dag_utilities.CornFlow")
def test_env_connection_vars(self, CornFlow):
secrets = Mock()
conn_uris = [
... | nilq/baby-python | python |
import http
import json
from unittest import mock
import pytest
from sqlalchemy import orm
from todos import crud, db, serializers
from todos.db import models
@pytest.fixture()
def exemplary_event_path_parameters(exemplary_task_model: models.Task) -> dict:
return {"task_id": exemplary_task_model.id}
@pytest.f... | nilq/baby-python | python |
'''Standard Simple feedforward model
feedforward takes in a single image
Model-specific config.py options: (inherits from models.base_net):
'batch_size': An int. The number of input bundle to use in a batch
'hidden_size': An int. The size of representation size before FC layer
In metri... | nilq/baby-python | python |
"""
"""
PROMPT_COLORS = {
"purple": '\033[95m',
"blue": '\033[94m',
"green": '\033[92m',
"yellow": '\033[93m',
"red": '\033[91m',
"bold": '\033[1m',
"underline": '\033[4m'}
PROMPT_TAILER = '\033[0m'
class ColoredPrinter(object):
def __init__(self, color):
if not color in P... | nilq/baby-python | python |
import math
import os
import random
import re
import sys
n = int(input())
arr = list(map(int, input().rstrip().split()))
numSwaps = 0
i = 0
while(i < len(arr)-1):
if arr[i] != i+1:
tmp = arr[i]
arr[i], arr[tmp-1] = arr[tmp-1], arr[i]
numSwaps += 1
else:
i += 1
print(numSwaps)... | nilq/baby-python | python |
"""
This is a reST markup explaining the following code, compatible with
`Sphinx Gallery <https://sphinx-gallery.github.io/>`_.
"""
# You can convert the file to a Jupyter notebook using the
# sphx_glr_python_to_jupyter.py utility from Sphinx Gallery.
import math
sin = math.sin(0.13587)
print(sin)
#%%
# And a sum w... | nilq/baby-python | python |
import os.path
from os import listdir
import re
from numpy.distutils.core import setup
def find_version(*paths):
fname = os.path.join(os.path.dirname(__file__), *paths)
with open(fname) as fp:
code = fp.read()
match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", code, re.M)
if match:
... | nilq/baby-python | python |
# Simulate a Thomas cluster process on a rectangle.
# Author: H. Paul Keeler, 2018.
# Website: hpaulkeeler.com
# Repository: github.com/hpaulkeeler/posts
# For more details, see the post:
# hpaulkeeler.com/simulating-a-thomas-cluster-point-process/
import numpy as np; # NumPy package for arrays, random number ... | nilq/baby-python | python |
#
# (c) 2019, Ansible by Red Hat, inc
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from ansible_collections.cisco.ios.tests.unit.compat.mock import patch
from ansible_collections.ci... | nilq/baby-python | python |
# Generated by Django 4.0 on 2021-12-29 18:47
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
dependencies = [
('games', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='game',
... | nilq/baby-python | python |
#! /usr/bin/env python3
import sys
f = sys.stdin
s = f.read()
words = s.split()
n = len(words)
d = {}
for w in words:
if w in d:
d[w] += 1
else:
d[w] = 1
def foo(s):
return d[s]
#sorted_keys = sorted(d.keys(), key=foo, reverse=True)
sorted_keys = sorted(d.keys(), key = lambda x: d[x],... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
""" Generic tests for all animations.
These tests run against all animation classes found in
earthstar.effects.animations.*.
"""
import glob
import os
import pytest
import earthstar.effects.animations as animations
from earthstar.effects.engine import EffectEngine
from earthstar.fra... | nilq/baby-python | python |
import pandas as pd
import os
import sys
in_dir = sys.argv[1]
types = ['Right', 'Left']
out_df_base = 'russian_combined_{}'
files = [os.path.join(in_dir, f) for f in os.listdir(in_dir)
if f.lower().endswith('.csv')]
# dfs = [pd.read_csv(f) for f in files]
for type in types:
outdir = type.lower()
if ... | nilq/baby-python | python |
""" Contains all the models that can be used to impute missing data. """
from .daema import Daema
from .holoclean import Holoclean
from .mida import MIDA
from .miss_forest import MissForestImpute
from .baseline_imputations import MeanImputation, Identity
MODELS = {
"DAEMA": Daema,
"Holoclean": Holoclean,
... | nilq/baby-python | python |
from django.contrib import admin
from .models import AdminlteLog, AdminlteLogType
admin.site.register(AdminlteLog)
admin.site.register(AdminlteLogType)
| nilq/baby-python | python |
from libsvm.python.svmutil import *
from libsvm.python.svm import *
import os
import struct
import numpy
dic={}
#数据加载函数,kind值标明了读取文件的类型
def loadforSVM(path, kind='train'):
labels_path = os.path.join(path,'%s-labels.idx1-ubyte'% kind)
images_path = os.path.join(path,'%s-images.idx3-ubyte'% kind)
wi... | nilq/baby-python | python |
from abc import abstractmethod, ABC
from typing import Callable, TypeVar
T = TypeVar("T")
class Policy(ABC):
@abstractmethod
def execute(self, function: Callable[[], T]) -> T:
"""
Accepts lambda function and execute it with pre-defined policy parameters
Example: p.execute(lambda: api.... | nilq/baby-python | python |
# Generated by Django 4.0.2 on 2022-03-06 06:44
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('polls', '0002_challenges_game_delete_choice_delete_question_and_more'),
]
operations = [
migrations.AddField(
model_name='game',... | nilq/baby-python | python |
import os, sys, time
sys.path.append(os.getcwd())
import torch
import torchvision
from torch import nn
from torch import autograd
from torch import optim
import torch.nn.functional as F
import time
import tflib as lib
import tflib.save_images
import tflib.mnist
import tflib.cifar10
import tflib.plot
#import tflib.in... | nilq/baby-python | python |
# @Author: Anas Mazouni <Stormix>
# @Date: 2017-05-17T23:59:31+01:00
# @Email: madadj4@gmail.com
# @Project: PluralSight Scraper V1.0
# @Last modified by: Stormix
# @Last modified time: 2017-05-18T17:08:22+01:00
import selenium as sl
import os,time,inspect
from sys import platform
from selenium import webdriver
f... | nilq/baby-python | python |
''' Learning rate schedulers. '''
import json
import torch
import torch.optim.lr_scheduler as lr_sched
from typing import Any
from cosine_scheduler import CosineLRWithRestarts
def step(optimizer, last_epoch, step_size=10, gamma=0.1, **_) -> Any:
return lr_sched.StepLR(optimizer, step_size=step_size, gamma=gam... | nilq/baby-python | python |
#!/usr/bin/python
# encoding: utf-8
"""
@author: Ian
@file: serializers.py.py
@time: 2019-04-30 12:23
"""
from rest_framework import serializers
from snippets.models import Snippet
from dicproj.models import Dic, CsvFile
class SnippetSerializer(serializers.ModelSerializer):
class Meta:
model = Snippet
... | nilq/baby-python | python |
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
import app.core.patch
# La solución planteada tiene ventajas y desventajas. Como ventaja, se usa el
# sistema de autenticación d... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" run_file2db is a tool to migrate a labeled dataset in a pickle file to a
mongo db.
It must be invoked using
python run_file2db.py <project_folder>
Created on Dec, 2016
@autor: Jesus Cid.
"""
import ast
import time
import sys
import os
import... | nilq/baby-python | python |
from django.contrib.auth.models import User
from django.db import models
import datetime as dt
from tinymce.models import HTMLField
from django.db.models.signals import post_save
from django.dispatch import receiver
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if ... | nilq/baby-python | python |
"""
This code is based on these codebases associated with Yuta Saito's research.
- Unbiased Recommender Learning from Missing-Not-At-Random Implicit Feedback: https://github.com/usaito/unbiased-implicit-rec-real
- Unbiased Pairwise Learning from Biased Implicit Feedback: https://github.com/usaito/unbiased-pairwise-rec
... | nilq/baby-python | python |
def is_super(connection):
with connection.cursor() as cursor:
cursor.execute('show grants for current_user()')
query_result = cursor.fetchone()
return 'SUPER' in query_result
| nilq/baby-python | python |
from pixiedust.display.app import *
@PixieApp
class TestEntity():
@route()
def main_screen(self):
return """
<h1><center>Simple PixieApp with dynamically computed dataframe</center></h1>
<div pd_entity="compute_pdf('prefix')" pd_options="handlerId=dataframe" pd_render_onload></div>
... | nilq/baby-python | python |
# --coding:utf-8--
#
# Copyright (c) 2020 vesoft inc. All rights reserved.
#
# This source code is licensed under Apache 2.0 License,
# attached with Common Clause Condition 1.0, found in the LICENSES directory.
import pytest
from nebula2.graph import ttypes
from tests.common.nebula_test_suite import NebulaTestSuite
... | nilq/baby-python | python |
from os import environ
from .app_settings import *
SECRET_KEY=environ.get('SECRET_KEY')
STATIC_ROOT=environ.get('STATIC_ROOT')
ALLOWED_HOSTS = list(environ.get('ALLOWED_HOSTS', default='').split(','))
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': environ.get('DB_NAME... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.14 on 2018-08-23 08:01
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('cms', '0020_old_tree_cleanup'),
('articles', '0002... | nilq/baby-python | python |
class Solution:
# Solution using Mancher's Algorithm
@staticmethod
def longest_palindromic(s: str) -> str:
if(type(s) != str):
raise ValueError(f"{type(s)} not allowed only string type is allowed")
def adjust_string(s: str) -> str: # method to adjus... | nilq/baby-python | python |
#!/usr/bin/env python
# coding=utf-8
# ====================================================
#
# File Name : pc_nd_conv_plot.py
# Creation Date : 17-04-2018
# Created By : Min-Ye Zhang
# Contact : stevezhang@pku.edu.cn
#
# ====================================================
from __future__ import print_f... | nilq/baby-python | python |
sandwich_orders = ['pastrami', 'fish', 'pastrami', 'cabbage', 'pastrami', 'sala', 'pig', 'chicken']
finished_sandwich_orders = []
print(sandwich_orders)
print("'pastrami' soled out!")
while 'pastrami' in sandwich_orders:
sandwich_orders.remove('pastrami')
print(sandwich_orders)
while sandwich_orders:
finished ... | nilq/baby-python | python |
import tensorflow as tf
import src.lib as tl
class DNN:
def __init__(self,conf_data):
n_classes = len(conf_data["classes_list"])
data_size = conf_data["size"]
self.name = "selector"
self.show_kernel_map = []
with tf.name_scope('Input'):
self.input = tf.placehol... | nilq/baby-python | python |
"""
Wrap Google Prediction API into something that looks
kind of like the standard scikit-learn interface to
learning models.
Derived from Google API example code examples found here:
https://github.com/google/google-api-python-client
@author: Jed Ludlow
"""
from __future__ import print_function
import argparse
i... | nilq/baby-python | python |
def findDecision(obj): #obj[0]: Coupon, obj[1]: Education, obj[2]: Occupation
# {"feature": "Coupon", "instances": 8147, "metric_value": 0.4744, "depth": 1}
if obj[0]>1:
# {"feature": "Education", "instances": 5889, "metric_value": 0.4676, "depth": 2}
if obj[1]>1:
# {"feature": "Occupation", "instances": 3337,... | nilq/baby-python | python |
from typing import Callable, Dict, Optional
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from kornia.metrics import accuracy, mean_average_precision, mean_iou
from .trainer import Trainer
from .utils import Configuration
class ImageClassifierTrainer(Trainer):
"""Module to be used ... | nilq/baby-python | python |
# Created on Mar 07, 2021
# author: Hosein Hadipour
# contact: hsn.hadipour@gmail.com
import os
output_dir = os.path.curdir
str_feedback1 = lambda a24, b15, b0, b1, b2: a24 + ' + ' + b15 + ' + ' + b0 + ' + ' + b1 + '*' + b2
str_feedback2 = lambda b6, a27, a0, a1, a2: b6 + ' + ' + a27 + ' + ' + a0 + ' + ' + a1 + '*'... | nilq/baby-python | python |
from django.utils.translation import ugettext_lazy as _
from django.contrib.comments.models import CommentFlag
from django.contrib.comments.admin import CommentsAdmin
from django.contrib import admin
from scipy_central.comments.models import SpcComment
class SpcCommentAdmin(CommentsAdmin):
"""
Custom admin in... | nilq/baby-python | python |
# 3.11 随机选择
import random
values = [1,2,3,4,5,6]
for i in range(0, 4):
print(random.choice(values))
for i in range(0, 4):
print(random.sample(values, 2))
random.shuffle(values)
print(values)
for i in range(0, 10):
print(random.randint(0, 10))
for i in range(0, 3):
print(random.random())
print(random.ge... | nilq/baby-python | python |
import json
from pytorch_pretrained_bert import cached_path
from pytorch_pretrained_bert import OpenAIGPTTokenizer
from keras_gpt_2 import load_trained_model_from_checkpoint, get_bpe_from_files, generate
tokenizer = OpenAIGPTTokenizer.from_pretrained('openai-gpt')
url = "s3://datasets.huggingface.co/personachat/person... | nilq/baby-python | python |
import unittest
import pandas as pd
import os
from requests import Response
from computerMetricCollector.metricsCollector.StorageAPI import store_to_database
from computerMetricCollector.crypto import encrypt_data
from computerMetricCollector.test.crypto import read_key, decrypt_data
from computerMetricCollector... | nilq/baby-python | python |
import unittest
from util.bean import deepNaviReqToNaviModel
from model import DeepNaviReq
import time
def generateReq():
req = DeepNaviReq()
req.time = int(time.time() * 1000)
print()
# magnetic = req.magneticList.add()
# magnetic.x = 1
# magnetic.y = 2
# magnetic.z = 3
accelerometer = ... | nilq/baby-python | python |
# Generated by Django 2.1.11 on 2019-12-03 21:08
from django.db import migrations
from qatrack.qatrack_core.dates import (
format_as_date,
format_datetime,
parse_date,
parse_datetime,
)
def datestrings_to_dates(apps, schema):
TestInstance = apps.get_model("qa", "TestInstance")
for ti in Te... | nilq/baby-python | python |
#!/usr/bin/env python
"""Software Carpentry Windows Installer
Helps mimic a *nix environment on Windows with as little work as possible.
The script:
* Installs nano and makes it accessible from msysgit
* Provides standard nosetests behavior for msysgit
To use:
1. Install Python, IPython, and Nose. An easy way to ... | nilq/baby-python | python |
import sqlalchemy as sa
from sqlalchemy import orm
from data.db_session import BaseModel
import datetime
class Post(BaseModel):
__tablename__ = 'posts'
__repr_attrs__ = ["title", "tournament"]
serialize_only = (
"id",
"title",
"content",
"status",
"now",
"t... | nilq/baby-python | python |
from geniusweb.issuevalue.Bid import Bid
from geniusweb.issuevalue.Domain import Domain
from geniusweb.issuevalue.Value import Value
from geniusweb.profile.utilityspace.LinearAdditive import LinearAdditive
from tudelft.utilities.immutablelist.AbstractImmutableList import AbstractImmutableList
from tudelft.utilities.i... | nilq/baby-python | python |
import discord
from discord.ext import commands
from WhiteFox.core.config.config import Config
class WhiteFox(commands.Bot):
def __init__(self, token=None, client_id=None, prefixes=None):
self.configs = None
self._init_configs()
if token is not None:
self.configs.discord.toke... | nilq/baby-python | python |
import re
import json
import requests
import time
from urllib.parse import unquote
import os
headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36', 'referer': 'https://youtube.com'}
class Caption:
def __init__(self, url, l... | nilq/baby-python | python |
import torch
from torch.autograd import Function
from torch.autograd.function import once_differentiable
from torch._thnn import type2backend
from .thnn.auto import function_by_name
import torch.backends.cudnn as cudnn
MODE_ZEROS = 0
MODE_BORDER = 1
class GridSampler(Function):
@staticmethod
def forward(ctx... | nilq/baby-python | python |
from unittest import TestCase
from starmie import AStarProblem
class Maze(AStarProblem):
WALL = 'O'
START = 'S'
GOAL = 'G'
ROAD = ' '
PATH = '*'
def __init__(self, map_data, allow_slant=True):
self.map = []
self.start = None
self.goal = None
for x, line in enum... | nilq/baby-python | python |
"""cmlkit exceptions."""
class DependencyMissing(Exception):
"""Raised when an optional dependency is needed."""
...
| nilq/baby-python | python |
#!/usr/bin/env python
__description__ = \
"""
compareAncestor.py
"""
__author__ = "Michael J. Harms"
__usage__ = "comapreAncestors.py ancestor_file1 ancestor_file2"
__date__ = "100726"
import sys, phyloBase
class CompareAncestorError(Exception):
"""
General error class for this module.
"""
pass
... | nilq/baby-python | python |
conv_encoder = km.Sequential(name="ConvEncoderModel")
conv_encoder.add(kl.Conv2D(16, (3,3) , activation='relu', input_shape=(28,28,1) , padding='same' ))
conv_encoder.add(kl.MaxPooling2D((2, 2), padding='same'))
conv_encoder.add(kl.Conv2D(8, (3, 3), activation='relu', padding='same'))
conv_encoder.add(kl.MaxPooling2D((... | nilq/baby-python | python |
"""Tests for appname application."""
from unittest import TestCase
from django.test import TestCase as DjangoTestCase
class TestSuiteTestCase(TestCase):
"""General test to make sure that the setup works."""
def test_test_suite_can_be_run(self):
self.assertTrue(True)
class ExampleTestCase(DjangoTest... | nilq/baby-python | python |
#
# PySNMP MIB module EXPAND-NETWORKS-SMI (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/EXPAND-NETWORKS-SMI
# Produced by pysmi-0.3.4 at Wed May 1 13:07:01 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default... | nilq/baby-python | python |
'''
思路:
位图1,用于判断是否存在该词。对于每次读进来的词,计算哈希值,相应比特位置1。
位图2,用于标志是否重复。对于读进来的并且是被位图1标志过存在的词,则置1
队列,用于保存不重复词。队尾保留最新不重复词,每次push都是在队尾,pop则不一定
(改用队列,主要是为了防止大文件都是不相同词时,要遍历整个hashmap,相当于遍历大文件两遍)
'''
# 伪码
# 遍历文件
for word in largeFile:
if bitmap1.isExist(word):
bitmap2.add(word)
pop word from dueue
else:
... | nilq/baby-python | python |
import datetime
from django.conf import settings
from rest_framework.settings import APISettings
from .utils import hash_string
USER_SETTINGS = getattr(settings, 'JWT2FA_AUTH', None)
DEFAULTS = {
# Length of the verification code (digits)
'CODE_LENGTH': 7,
# Characters used in the verification code
... | nilq/baby-python | python |
from __future__ import unicode_literals
from django.core.exceptions import ObjectDoesNotExist
from django.forms.models import ModelForm, model_to_dict
from .constants import (MODERATION_STATUS_PENDING, MODERATION_STATUS_REJECTED)
from .utils import django_17
class BaseModeratedObjectForm(ModelForm):
class Meta:... | nilq/baby-python | python |
"""Lightly modified build_ext which captures stderr.
isort:skip_file
"""
# IMPORTANT: `import setuptools` MUST come before any module imports `distutils`
# background: https://bugs.python.org/issue23102
import setuptools # noqa: F401
import distutils.command.build_ext
import distutils.core
import io
import os
impor... | nilq/baby-python | python |
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init
import numpy as np
from unet import *
from utils import *
def weight_init(m):
if isinstance(m, nn.Conv3d) or isinstance(m, nn.Conv2d):
torch.nn.init.kaiming_normal_(m.weight.data)
if m.bias is not None:
m.bias.data.fill_(... | nilq/baby-python | python |
# modified jetbot physical implementation
import atexit
import subprocess
import traitlets
from traitlets.config.configurable import Configurable
class Motor(Configurable):
value = traitlets.Float()
# config
alpha = traitlets.Float(default_value=1.0).tag(config=True)
beta = traitlets.Float(defau... | nilq/baby-python | python |
from gui.contract import IView, IPresenter
from gui.presenter import Presenter
import time
from tkinter import *
from command.queue.buildthread import BuildThread
from command.queue.properties import QueueProperties
from utils.context import Context
from utils.travian_utils import login_to_account, create_browser
fro... | nilq/baby-python | python |
#!/usr/bin/env python3
#
# Given a configuration executes p2rank and all components.
#
import json
import os
import logging
import requests
import shutil
import subprocess
import conservation_wrapper
from model import *
from output_prankweb import prepare_output_prankweb
from output_p2rank import prepare_output_p2rank... | nilq/baby-python | python |
import ConfigParser
def readConfig():
config = ConfigParser.ConfigParser()
config.readfp(open("sharenet.ini"))
binDir = config.get("Import", "bin")
inDir = config.get("Import", "in")
workDir = config.get("Import", "work")
doneDir = config.get("Import", "done")
dbHost = config.get("Database", "host")
dbName = c... | nilq/baby-python | python |
import bpy
from ..sollumz_properties import SollumType, SOLLUMZ_UI_NAMES, BOUND_POLYGON_TYPES
from ..ybn.collision_materials import create_collision_material_from_index
from ..tools.meshhelper import create_box, create_sphere, create_capsule, create_cylinder
from mathutils import Vector, Matrix
def create_bound_shap... | nilq/baby-python | python |
import asyncio
from netschoolapi import NetSchoolAPI
async def main():
login_data = {
"login": "Иван",
"password": "Иван228",
"school": "МАОУ многопрофильный лицей №20"
}
async with NetSchoolAPI("http://sgo.cit73.ru/", **login_data) as api:
print(await api.get_announcement... | nilq/baby-python | python |
import datetime
import unittest
from search.ql import Query, Q, GeoQueryArguments
from search.fields import TextField, GeoField, DateField
from search.indexes import DocumentModel
class FakeDocument(DocumentModel):
foo = TextField()
bar = DateField()
class FakeGeoDocument(DocumentModel):
my_loc = GeoFi... | nilq/baby-python | python |
import copy
import random
import math
import numpy as np
from Higashi_backend.utils import *
from Higashi_backend.Functions import *
import multiprocessing
import time
from torch.nn.utils.rnn import pad_sequence
from sklearn.decomposition import PCA
from sklearn.preprocessing import normalize
from scipy.sparse import... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models, api
class RemovalStrategy(models.Model):
_name = 'product.removal'
_description = 'Removal Strategy'
name = fields.Char('Name', required=True)
method = fields.Char("Met... | nilq/baby-python | python |
# AUTOGENERATED! DO NOT EDIT! File to edit: 01c_grad_utils.ipynb (unless otherwise specified).
__all__ = ['cg', 'cat_list_to_tensor', 'reverse_unroll', 'reverse', 'fixed_point', 'CG', 'CG_normaleq', 'neumann',
'exact', 'grd', 'list_dot', 'jvp', 'get_outer_gradients', 'cat_list_to_tensor', 'update_tensor_gra... | nilq/baby-python | python |
import bisect
import keyword
import rope.base.simplify
MINIMAL_LEN_FOR_AS = 5
def get_name_at(resource, offset):
source_code = resource.read()
word_finder = Worder(source_code)
return word_finder.get_word_at(offset)
class Worder(object):
"""A class for finding boundaries of words and expressions
... | nilq/baby-python | python |
def main():
import RPi.GPIO as GPIO
try:
print('UNKNOWN:%d' % GPIO.UNKNOWN)
print('SERIAL:%d' % GPIO.SERIAL)
print('SPI:%d' % GPIO.SPI)
print('I2C:%d' % GPIO.I2C)
print('HARD_PWM:%d' % GPIO.HARD_PWM)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(3, GPIO.OUT)
... | nilq/baby-python | python |
"""
.. module:: Facemovie
:platform: Unix, Windows
:synopsis: Main class of the application. Contains the core image processing functions, and contains API methods.
.. moduleauthor:: Julien Lengrand-Lambert <jlengrand@gmail.com>
"""
import os
import sys
import logging
import cv
from util import exif
import G... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.