content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
from itertools import product
with open('output.txt') as f:
s = f.read().strip()
for i, j in product(range(10), repeat=2):
try:
bits = '1'*i + s + '1'*j
x = bytes.fromhex(f'{int(bits, 2):x}')
if b'CCTF{' in x:
print(x)
break
except:
pass
| nilq/baby-python | python |
class Solution:
def setZeroes(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
row = []
column = []
for i in range(len(matrix)):
for j in range(len(matrix[0])):
... | nilq/baby-python | python |
import pytest
from numpy.testing import assert_array_almost_equal
from Auto import *
class Test_AutoSample:
@classmethod
def setup_method(cls):
np.random.seed(123)
cls.target = lambda x: np.where(x < 0, 0, np.exp(-x))
cls.shape = (1,)
cls.njobs = 1
cls.algo = AutoSampl... | nilq/baby-python | python |
#!python
# This generates a java source file by taking each method that has a
# parameters (String s, int off, int end) and generating a copy that
# takes (char[] s, int off, int end).
# Fix emacs syntax highlighting "
src = r"""
// Copyright (C) 2011 Google Inc.
//
// Licensed under the Apache License, Version 2.0 ... | nilq/baby-python | python |
def print_me(y):
return 10 + y # pragma: no cover
def return_val(val):
val += 1
return val
def return_val2(val):
val += 1
return val
| nilq/baby-python | python |
"""
endpoint schemas for knoweng
"""
| nilq/baby-python | python |
"""Integration tests for dice_roller.py"""
import unittest
import dice_roller
class DiceRollerIntegrationTests(unittest.TestCase):
"""
Integration tests for DiceRoller that check that history() and clear() are working
"""
def test_no_history(self):
"""
test that .history() returns {} ... | nilq/baby-python | python |
from presentation.models import Liked, Author
from django.shortcuts import get_object_or_404
from presentation.Serializers.liked_serializer import LikedSerializer
from presentation.Serializers.author_serializer import AuthorSerializer
from rest_framework import viewsets, status
from rest_framework.response import Respo... | nilq/baby-python | python |
import argparse
import sys
import os.path as osp
import os
sys.path.insert(1, osp.abspath(osp.join(os.getcwd(), *('..',)*2)))
from dataset_preprocess import CoraDataset, PlanetoidDataset
from attack.models import *
import torch
import pandas as pd
from tqdm.notebook import tqdm
from attack.GAFNC import GNNAttack
from t... | nilq/baby-python | python |
import sympy
class Curtis:
type = 0
# module for computing zUy and UxU
deodhar = 0
# Bruhat form
bruhat = 0
# the Chevalley group
group = 0
# the Weyl group
weyl = 0
# standard parabolics
para = 0
# distinguished expressions for standard parabolics
dist_expr_p = 0... | nilq/baby-python | python |
from django.http import HttpResponse, Http404
from django.shortcuts import render
from django.template import TemplateDoesNotExist
from django.template.loader import get_template
from django.contrib.auth.views import LoginView
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins imp... | nilq/baby-python | python |
"""Updating max length of s3_name in account table
Revision ID: 1727fb4309d8
Revises: 51170afa2b48
Create Date: 2015-07-06 12:29:48.859104
"""
# revision identifiers, used by Alembic.
revision = '1727fb4309d8'
down_revision = '51170afa2b48'
from alembic import op
import sqlalchemy as sa
def upgrade():
### com... | nilq/baby-python | python |
# criando uma sequencia de fibonacci
# o proximo numero e sempre a soma dos 2 anteriores
print('Seguencia de Finonacci')
print('--'*20)
# pedindo um numero
n = int(input('Quantos termos voce quer mostrar: '))
# primeiro termo
t1 = 0
# segundo termo
t2 = 1
# mostrando os 2 primerios termos
print(f'{t1} -> {t2}', end='')... | nilq/baby-python | python |
from org.transcrypt.stubs.browser import *
import random
array = []
def gen_random_int(number, seed):
my_list = [i for i in range(number)]
random.seed(seed)
random.shuffle(my_list)
result = my_list
return result
def generate():
global array
number = 10
seed = 200
gen_random_int(number, seed... | nilq/baby-python | python |
import math
import random
import itertools
import collections
import numpy as np
def grouper(lst, num):
args = [iter(lst)]*num
out = itertools.zip_longest(*args, fillvalue=None)
out = list(out)
return out
def get_batch(batch_data, config, rot='_rot'):
"""Given a batch of data, determine the input ... | nilq/baby-python | python |
"""This program searches through an email file and returns the sender email and date of sending """
user_input = input('Enter filename: ')
fhand = open(user_input)
for line in fhand:
line = line.rstrip()
if not line.startswith('From '): continue
words = line.split()
# print(words)
print(words[1:5], w... | nilq/baby-python | python |
import oi
import os
import sys
import logging
from logging.handlers import SysLogHandler
import time
import service
try:
import config
except ImportError:
import example1.config as config
def stop_function():
ctl = oi.CtlProgram('ctl program', config.ctl_url)
ctl.call('stop')
ctl.client.close()
c... | nilq/baby-python | python |
# (C) Datadog, Inc. 2020-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
METRICS = (
'hazelcast.instance.managed_executor_service.completed_task_count',
'hazelcast.instance.managed_executor_service.is_shutdown',
'hazelcast.instance.managed_executor_service.is_termin... | nilq/baby-python | python |
import time
import webhook_listener
import json
# arduino = serial.Serial(port='COM14', baudrate=115200, timeout=0)
def process_post_request(request, *args, **kwargs):
req = (format(
request.body.read(int(request.headers["Content-Length"]))
if int(request.headers.get("Content-Length", 0)) ... | nilq/baby-python | python |
#!/bin/env python
#
# Copyright 2013-2014 Graham McVicker and Bryce van de Geijn
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless ... | nilq/baby-python | python |
#!/bin/python
# -*- coding: utf-8 -*-
import requests
CITY = "787657"
API_KEY = "yourapikey(can be registered on openweathermap.org)"
UNITS = "Metric"
LANG = "en"
REQ = requests.get("http://api.openweathermap.org/data/2.5/weather?id={}&lang={}&appid={}&units={}".format(CITY, LANG, API_KEY, UNITS))
try:
if REQ.s... | nilq/baby-python | python |
#Build In
import os
import sys
import pickle
import copy
import random
# Installed
import numpy as np
from scipy.spatial.transform import Rotation as R
from pathlib import Path
import torch
import spconv
from argoverse.data_loading.argoverse_tracking_loader import ArgoverseTrackingLoader
# Local
from pcdet.utils impo... | nilq/baby-python | python |
import pytest
from app.core.enums import CaseStatus
from app.entities import RecordOnAppeal, Court
def test_roa_from_district_case(simple_case) -> None:
'''
It should create an record of appeal for this case, set the original_case_id.
'''
court = Court.from_id('ca9')
roa = simple_case.create_recor... | nilq/baby-python | python |
import asyncio
# 获取事件循环
import time
loop = asyncio.get_event_loop()
async def main():
await asyncio.sleep(10)
print("main coroutine running")
print(time.time_ns())
# 运行一个协程函数
loop.run_until_complete(main())
print(time.time_ns())
# 在线程池中运行一个协程函数
# loop.run_in_executor()
# 运行一个事件循环
loop.run_forever() | nilq/baby-python | python |
"""
ga2vcf cli
"""
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import ga4gh.converters.cli as cli
import ga4gh.converters.converters as converters
import ga4gh.common.cli as common_cli
import ga4gh.client.cli as cli_client
class Ga2VcfRunner(cli_clie... | nilq/baby-python | python |
#MenuTitle: Angularizzle
# -*- coding: utf-8 -*-
__doc__="""
Creates angular versions of glyphs made up of cubic paths.
"""
import math
import vanilla
import copy
import GlyphsApp
f = Glyphs.font
masterlen = len(f.masters)
# Script name by Type Overlord Florian Horatio Runge of Flensborre @FlorianRunge
class Angela(... | nilq/baby-python | python |
from django.contrib import admin
from .models import ContactQuery
# Register your models here.
admin.site.register(ContactQuery)
| nilq/baby-python | python |
######### Third-party software locations #########
hmmer_dir = "./hmmer_linux/bin/"
phobius_dir = "./phobius/"
#these can be overriden by the --hmerdir, --phobiusdir and -wp options
phobius_url = "https://phobius.sbc.su.se/cgi-bin/predict.pl"
######### Profile HMM locations #########
PTKhmm_dir = "./pHMMs/"
JM... | nilq/baby-python | python |
import logging
from quarkchain.evm.slogging import get_logger, configure_logging
"""
slogging module used by ethereum is configured via a comman-separated string,
and each named logger will receive custom level (defaults to INFO)
examples:
':info'
':info,p2p.discovery:debug'
because of the way that configure_logging... | nilq/baby-python | python |
"""
The module opens the camera capture a point cloud and:
- mesh the point cloud and give back a water-tight mesh
"""
import copy
import sys
from tomlkit import key
if sys.version_info[0] == 2: # the tkinter library changed it's name from Python 2 to 3.
import Tkinter
tkinter = Tkinter #I decided to use a... | nilq/baby-python | python |
#
# Copyright (C) [2020] Futurewei Technologies, Inc.
#
# FORCE-RISCV is licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# THIS SOFTWARE IS PRO... | nilq/baby-python | python |
#!/usr/bin/env python3
# encoding: utf-8
import sys
def trace_calls_and_returns(frame, event, arg):
co = frame.f_code
func_name = co.co_name
if func_name == 'write':
# Ignore write() calls from printing
return
line_no = frame.f_lineno
filename = co.co_filename
if not filename.... | nilq/baby-python | python |
from django.contrib import admin
from .models import Customer
# Register your models here.
admin.site.register(Customer) | nilq/baby-python | python |
"""main API module."""
from __future__ import annotations
import dataclasses
from dataclasses import dataclass
from enum import Enum
from typing import Any, Union, cast
import aiohttp
from siyuanhelper import exceptions
data_type = Union[dict, list, None]
class Siyuan:
"""Siyuan Helper Instance."""
def... | nilq/baby-python | python |
from texthooks.macro_expand import main as macro_expand_main
def test_macro_expand_no_changes(runner):
result = runner(macro_expand_main, "foo")
assert result.exit_code == 0
assert result.file_data == "foo"
def test_macro_expand_simple(runner):
result = runner(macro_expand_main, "f:bar", add_args=["... | nilq/baby-python | python |
from tkinter import Tk, Label, Button, N, E, S, W
def exitMsg(save, dest):
def saveFunc():
save()
exitFunc()
def exitFunc():
dest.destroy()
window.destroy()
window = Tk()
Label(window, text="Do you really want to close this window without saving?").grid(row=0, column=... | nilq/baby-python | python |
"""
=========================================================================
Decoding sensor space data with generalization across time and conditions
=========================================================================
This example runs the analysis described in :footcite:`KingDehaene2014`. It
illustrates how o... | nilq/baby-python | python |
import os
import uuid
from tests.graph_case import GraphTestCase
from office365.graph.onedrive.drive import Drive
from office365.graph.onedrive.driveItem import DriveItem
from office365.graph.onedrive.file_upload import ResumableFileUpload
def create_list_drive(client):
list_info = {
"displayName": "Lib... | nilq/baby-python | python |
#coding:utf-8
import numpy as np
# 2.使用函数创建
# 如果生成一定规则的数据,可以使用NumPy提供的专门函数
# arange函数类似于python的range函数:指定起始值、终止值和步长来创建数组
# 和Python的range类似,arange同样不包括终值;但arange可以生成浮点类型,而range只能是整数类型
np.set_printoptions(linewidth=100, suppress=True)
a = np.arange(1, 10, 0.5)
print('a = ', a)
# linspace函数通过指定起始值、终止值和元素个数来创建数组,缺省包括终止值... | nilq/baby-python | python |
def a1(str):
print(str[::-1])
def a2(str):
list=str.split()
print(" ".join(list[::-1]))
def a3(str):
if str[:(len(str)//2)]==str[(len(str)//2):]:
print("Symmetric")
else:
print("Asymmetric")
def a4(str):
if str==str[::-1]:
print("Palindrome")
else:
... | nilq/baby-python | python |
import os
import glob
import shutil
import tarfile
from pathlib import Path
DESCRIPTION = """
Prifysgol Bangor University
"""
TECHIAITH_RELEASE=os.environ["TECHIAITH_RELEASE"]
#
def copy_for_evaluation_or_publishing(source_dir, target_dir):
Path(target_dir).mkdir(parents=True, exist_ok=True)
# copy ... | nilq/baby-python | python |
def count_substring(string, sub_string):
found = 0
sub_length = len(sub_string)
for index, _ in enumerate(string):
string_slice = string[index:sub_length + index]
# Debug print statement to confirm assumptions about what the slice looks like.
#print(f'Found: {string_slice}')
... | nilq/baby-python | python |
def build_person(first_name, last_name):
"""Return a dictionary of information about a person."""
person = {'first': first_name, 'last': last_name}
return person
musician = build_person('jimi', 'hendrix')
print(musician)
| nilq/baby-python | python |
import sys, os, threading, queue
sys.path.append('.')
os.chdir('..')
import normalize
from singleton import db
num_workers = 64
in_q = queue.Queue()
out_q = queue.Queue()
class Worker(threading.Thread):
def run(self):
while True:
uid, url = in_q.get()
if uid is None:
out_q.put((None, None, N... | nilq/baby-python | python |
import lemma
import re
TAG_RE = re.compile(r'<[^>]+>')
def remove_tags(text):
return TAG_RE.sub('', text)
# def lem_parse(data):
# pass
def lem_parse(text,cnt,check,all_ham,all_spam):
content = remove_tags(text)
x,all_ham,all_spam = lemma.data(content,cnt,check,all_ham,all_spam)
return (x,all_ham,al... | nilq/baby-python | python |
#!/usr/bin/env python3
import sys
import os
import argparse
import logging
from traitlets.config import Config
import nbformat
from nbconvert import NotebookExporter
import utils
from clean import clean
CLEAN = 1
# TODO: would be nice to do some Make-like shortcuts to avoid processing notebooks
# whose rendered mti... | nilq/baby-python | python |
# plugin method for deleting files from an archive
# using the linux "find" commmand.
# this only works if you have a configuration
# with a single archive server which is
# defined in the servers dictionary
from plugins.handyrepplugin import HandyRepPlugin
class archive_delete_find(HandyRepPlugin):
# plugin to d... | nilq/baby-python | python |
import os.path
import random
class AutomaticPotato:
def parent_dir(self):
return os.path.dirname(__file__)
def public_dir(self):
pd = self.parent_dir()
return os.path.abspath(os.path.join(pd, '../../public'))
def potatoes(self):
return os.listdir(self.public_dir())
de... | nilq/baby-python | python |
# encoding=utf8
# This is temporary fix to import module from parent folder
# It will be removed when package is published on PyPI
import sys
sys.path.append('../')
# End of fix
from NiaPy.algorithms.basic import CuckooSearch
from NiaPy.benchmarks import Sphere
from NiaPy.task import StoppingTask
# we will run Cuckoo... | nilq/baby-python | python |
from zipfile import ZipFile
from os.path import isdir, isfile, expanduser
from os import getcwd, popen
from shutil import rmtree
from threading import Thread
import sys, ctypes, os
import requests
def run_follower_maker(path):
file = "{}\\followerMaker.exe".format(path)
if isfile(file):
print('run in... | nilq/baby-python | python |
lines = open('input.txt', 'r').readlines()
positions = [int(p) for p in lines[0].split(",")]
# part one
costs = 10e20
optimal_height = 0
for height in range(max(positions)):
current_cost = 0
# calculate cost for height
for p in positions:
current_cost += abs(p-height)
# check if the current ... | nilq/baby-python | python |
# pylint: skip-file
# type: ignore
# -*- coding: utf-8 -*-
#
# tests.models.function.function_unit_test.py is part of The RAMSTK Project
#
# All rights reserved.
# Copyright since 2007 Doyle "weibullguy" Rowland doyle.rowland <AT> reliaqual <DOT> com
"""Test class for testing function module algorithms and models... | nilq/baby-python | python |
from __future__ import annotations
import os
import platform
from typing import Union
from numpy import arange, array, cumsum, dot, ones, vstack
from numpy.linalg import pinv
from numpy.random import Generator, RandomState
from arch.typing import UnitRootTrend
# Storage Location
if platform.system() == "Linux":
... | nilq/baby-python | python |
import json
import requests
from src import env
from src.utils import response_contains_json
CVE_URL = '/api/cve'
cve_id = 'CVE-1999-0001'
update_cve_id = create_cve_id = 'CVE-2000-0008'
#### GET /cve ####
def test_get_all_cves(org_admin_headers):
""" services api rejects requests for admin orgs """
res = re... | nilq/baby-python | python |
"""
Python library for interacting with ACINQ's Strike API for lightning
network payments.
"""
import json
import base64
import http.client
import urllib.parse
import ssl
import abc
import socket
from .exceptions import ConnectionException, ClientRequestException, \
ChargeNotFoundException, UnexpectedResponse... | nilq/baby-python | python |
import uuid
import datetime
from common.database import Database
class Post(object):
# we can have default parameters in the end id=None
def __init__(self, title, content, author, blog_id, created_date=datetime.datetime.utcnow(), _id=None):
# id = post id, blog_id = blog id,
self.title = title... | nilq/baby-python | python |
import npyscreen
class ProcessBar(npyscreen.Slider):
def __init__(self, *args, **keywords):
super(ProcessBar, self).__init__(*args, **keywords)
self.editable = False
class ProcessBarBox(npyscreen.BoxTitle):
_contained_widget = ProcessBar
class TestApp(npyscreen.NPSApp):
... | nilq/baby-python | python |
from django.db import models
from django.contrib.auth.models import User
from django.conf import settings
import os.path
import re
import shutil
class UserProfile(models.Model):
user = models.ForeignKey(User, unique = True)
pic = models.ImageField(upload_to = 'profiles')
best_answers = models.I... | nilq/baby-python | python |
#!/usr/bin/env python
import json
import re
import requests
import sys
FOLDER = 'debug' #'analyses'
GENS = ['sm' ] #['rb', 'gs', 'rs', 'dp', 'bw', 'xy', 'sm']
def dexUrl(gen):
return 'https://www.smogon.com/dex/' + gen + '/pokemon'
def setUrl(gen, poke):
return dexUrl(gen) + '/' + poke
for gen in GENS:
dex ... | nilq/baby-python | python |
#coding=utf-8
from sklearn.datasets import load_svmlight_file
from sklearn.datasets import dump_svmlight_file
from sklearn.cluster import AgglomerativeClustering
from sklearn.externals import joblib
hac_model = joblib.load('hac_result.pkl')
tfidf_matrix, y_train = load_svmlight_file("./d_train.txt")
dump_svmlight_... | nilq/baby-python | python |
from glue_utils import InputExample
import sys
import torch
# convert .pth file to .txt file (use for generating adversarial examples in text format)
def create_file(mode):
examples = torch.load(f'{sys.argv[1]}_adv/{mode}-examples.pth')
with open(f'{sys.argv[1]}_adv/{mode}.txt', 'w') as f:
for example ... | nilq/baby-python | python |
"""Instrument sqlite3 to report SQLite queries.
``patch_all`` will automatically patch your sqlite3 connection to make it work.
::
from ddtrace import Pin, patch
import sqlite3
# If not patched yet, you can patch sqlite3 specifically
patch(sqlite3=True)
# This will report a span with the default... | nilq/baby-python | python |
__package__ = "PyUtil_Lib"
__author__ = "Phong Lam"
| nilq/baby-python | python |
# Copyright 2020-2021 Exactpro (Exactpro Systems Limited)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... | nilq/baby-python | python |
# pylint: disable=unused-argument
"""Testing Module nlp.pdflib_dcr."""
import os
import cfg.glob
import pytest
import dcr
# -----------------------------------------------------------------------------
# Constants & Globals.
# -----------------------------------------------------------------------------
# pylint: di... | nilq/baby-python | python |
import json
import os
import random
from bonsai_common import SimulatorSession, Schema
import dotenv
from microsoft_bonsai_api.simulator.client import BonsaiClientConfig
from microsoft_bonsai_api.simulator.generated.models import SimulatorInterface
from sim import extrusion_model as em
from sim import units
# time ... | nilq/baby-python | python |
# flake8: noqa pylint: skip-file
"""Tests for the TelldusLive config flow."""
import asyncio
from unittest.mock import Mock, patch
import pytest
from homeassistant import data_entry_flow
from homeassistant.components.tellduslive import (
APPLICATION_NAME, DOMAIN, KEY_SCAN_INTERVAL, SCAN_INTERVAL,
config_flow)... | nilq/baby-python | python |
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... | nilq/baby-python | python |
import unittest
from translator import english_to_french, french_to_english
class TestE2F(unittest.TestCase):
def test1(self):
self.assertEqual(english_to_french(""), "API Exception") # test null
self.assertEqual(english_to_french("Hello"), "Bonjour") # test positive
self.assertNotEq... | nilq/baby-python | python |
import errno
import logging
import os
from typing import TYPE_CHECKING, Optional
from .errors import ObjectFormatError
if TYPE_CHECKING:
from dvc.fs.base import FileSystem
from dvc.hash_info import HashInfo
from dvc.types import AnyPath
from .db.base import ObjectDB
logger = logging.getLogger(__name... | nilq/baby-python | python |
"""Generators - Small
=====================
Some small graphs
"""
import pytest
from networkx.generators.tests.test_small import TestGeneratorsSmall
from graphscope.framework.errors import UnimplementedError
from graphscope.nx.utils.compat import with_graphscope_nx_context
@pytest.mark.usefixtures("graphscope_ses... | nilq/baby-python | python |
import random
def bogoSort(a):
while (is_sorted(a)== False):
shuffle(a)
def is_sorted(a):
n = len(a)
for i in range(0, n-1):
if (a[i] > a[i+1] ):
return False
return True
def shuffle(a):
n = len(a)
for i in range (0,n):
r = random.randint... | nilq/baby-python | python |
from alembic import op
import sqlalchemy as sa
"""add ride resync date
Revision ID: 21518d40552c
Revises: d4be89cbab08
Create Date: 2020-02-01 08:53:33.632416
"""
# revision identifiers, used by Alembic.
revision = '21518d40552c'
down_revision = 'd4be89cbab08'
def upgrade():
op.add_column('rides', sa.Column('... | nilq/baby-python | python |
from flask import Flask, render_template, request
from wtforms import Form, DecimalField, validators
app = Flask(__name__)
class EntryForm(Form):
x_entry = DecimalField('x:',
places=10,
validators=[validators.NumberRange(-1e10, 1e10)])
y_entry = DecimalFi... | nilq/baby-python | python |
"""Try out other sklearn score to measure the
"""
import os
import sys
import glob
import numpy as np
import argparse
import tqdm
import matplotlib.pyplot as plt
from sklearn.neighbors import LocalOutlierFactor
from pathlib import Path
sys.path.append('../')
from eval.metric import silhouette, hsic_gam_mat, inertia_ap... | nilq/baby-python | python |
from setuptools import find_packages, setup
with open('requirements.txt') as f:
required = f.read().splitlines()
setup(
name="ml_example",
packages=find_packages(),
version="0.1.0",
description="Example of ml project",
author="Your name (or your organization/company/team)",
entry_points=... | nilq/baby-python | python |
import shutil
from dataclasses import dataclass
from pathlib import Path
import requests
from mealie.core import root_logger
from mealie.schema.recipe import Recipe
from mealie.services.image import minify
logger = root_logger.get_logger()
@dataclass
class ImageOptions:
ORIGINAL_IMAGE: str = "original.webp"
... | nilq/baby-python | python |
"""
Mesh Normalization
"""
import os
import sys
import cv2
import numpy as np
from scipy import io as io
import torch
import pickle
import trimesh
import argparse
from external.smplx.smplx import body_models
sys.path.insert(0, '../external/pyrender')
import pyrender
def main(opt):
model = body_models.create(mo... | nilq/baby-python | python |
import logging
import time
from datetime import datetime
import IOstation
import clim2bry
import configM2R
import decimateGrid
import model2roms
__author__ = 'Trond Kristiansen'
__email__ = 'trond.kristiansen@niva.no'
__created__ = datetime(2009, 1, 30)
__modified__ = datetime(2021, 7, 27)
__version__ = "1.6"
__statu... | nilq/baby-python | python |
from gpt2.data.dataset import Dataset
from gpt2.data.vocabulary import Vocab
from gpt2.data.tokenization import Tokenizer
from gpt2.data.corpus import TokenizedCorpus
| nilq/baby-python | python |
aspect_ratio=1.0
batchSize=1
checkpoints_dir='../checkpoints/'
cluster_path='features_clustered_010.npy'
data_type=32
dataroot='./data/1/test'
display_winsize=512
engine=None
export_onnx=None
feat_num=3
fineSize=512
fine_size=480
how_many=50
input_nc=3
instance_feat=False
isTrain=False
label_feat=False
label_nc=36
load... | nilq/baby-python | python |
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... | nilq/baby-python | python |
"""Test for kernel functionality."""
import functools
import jax
import jax.numpy as jnp
import pytest
import pytest_cases
from probfindiff.utils import autodiff, kernel, kernel_zoo
def case_exponentiated_quadratic():
k = lambda x, y: jnp.exp(-(x - y).dot(x - y))
return kernel.batch_gram(k)[0]
def case_... | nilq/baby-python | python |
#!/usr/bin/env python3
import json, os
print("Content-type:text/html\r\n\r\n")
print("<title>Testing CGI</title>")
#Lab code
# Q1
print(os.environ)
json_object = json.dumps(dict(os.environ))
print(json_object)
# Q2
for param in os.environ.keys():
if param == "QUERY_STRING":
print("<b>%20s</b>: %s<br>".form... | nilq/baby-python | python |
#!/usr/bin/env python
"""
This example shows how to create shipments. The variables populated below
represents the minimum required values. You will need to fill all of these, or
risk seeing a SchemaValidationError exception thrown.
Near the bottom of the module, you'll see some different ways to handle the
label data... | nilq/baby-python | python |
#! /usr/bin/python
"""radargrab
Get the images and backgrounds associated with a storm event and save them to
a directory or something
"""
import urllib2
import httplib
import time
from xml.dom import minidom
from HTMLParser import HTMLParser
_n0r = "http://radar.weather.gov/ridge/RadarImg/N0R/%s/"
_overlay = "http://... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import platform
from ctypes import cdll, c_wchar_p, create_unicode_buffer
from platformpaths import sopaths, ridelibpaths
APL = cdll.LoadLibrary(sopaths[platform.architecture()[0]][platform.system()])
def InitAPL(runtime, WSargs):
__C_APL_WSargs_Binding_Pa... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# pylint: disable=unidiomatic-typecheck
# *****************************************************************************
# NICOS, the Networked Instrument Control System of the MLZ
# Copyright (c) 2009-2021 by the NICOS contributors (see AUTHORS)
#
# This program is free software; you can redis... | nilq/baby-python | python |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
from frappe.utils.nestedset import NestedSet, get_root_of
from erpnext.utilities.transaction_base import delete_events
from frappe.model.d... | nilq/baby-python | python |
class PartitionScheme(basestring):
"""
mbr|gpt|unknown
Possible values:
<ul>
<li> "mbr" - Master Boot Record Partition Table Scheme.,
<li> "gpt" - GUID Partition Table Scheme.,
<li> "unknown" - Partition Scheme other than MBR or GPT or an
unformatted LUN.
</ul>
"""
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""字典树实现敏感词过滤"""
import codecs
class TrieNode(object):
def __init__(self, value=None):
self._end = False
self._child = dict()
self._value = value
def add(self, ch):
if not self._child.has_key(ch):
node = TrieNode(ch)
self._child... | nilq/baby-python | python |
import json
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def hello(event, context):
logger.info(f"AWS Lambda processing message from GitHub: {event}.")
body = {
"message": "Your function executed successfully!",
"input": event
}
response = {
"st... | nilq/baby-python | python |
import json
import os
import psycopg2
import time
#import pdb; pdb.set_trace()
POSTGRES_HOST = "database"
POSTGRES_USER = os.environ["POSTGRES_USER"]
POSTGRES_PASSWORD = os.environ["POSTGRES_PASSWORD"]
DB = "datamonitor"
DATA_DIR = "data"
def load_data():
wait_for_db()
#only load once
if is_data_there(... | nilq/baby-python | python |
import logging
import os
import mock
import unittest
import vixen
from vixen.processor import PythonFunctionFactory
from vixen.project import Project, TagInfo
from vixen.vixen import VixenUI, Vixen, UIErrorHandler, is_valid_tag
from vixen.vixen_ui import get_html, get_html_file
from vixen.tests.test_project import Te... | nilq/baby-python | python |
import yaml
import os
from pathlib import Path
from utils.dict_wrapper import DictWrapper
class EvaluationConfiguration:
'''
Represents the configuration parameters for running the evaluation process
'''
def __init__(self, path):
'''
Initializes the configuration with contents from t... | nilq/baby-python | python |
#!/usr/bin/env python
#
# Copyright 2009 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | nilq/baby-python | python |
import json
import boto3
import os
import urllib.parse
s3 = boto3.client('s3')
# Cliente do Amazon Textract
textract = boto3.client('textract')
def getTextractData(bucketName, documentKey):
# Chamando o Amazon Textract com os parâmetros do bucket e do arquivo .png
response = textract.detect... | nilq/baby-python | python |
BLOCK_SIZE = 1024
BACKING_FNs = ['../../songs/lamprey/drums.wav', '../../songs/lamprey/bass.wav',
'../../songs/lamprey/piano.wav', '../../songs/lamprey/violin.wav']
| nilq/baby-python | python |
#!/usr/bin/env python
"""find_profit is O(n) over a list, given a window, to find the maximum profit
possible given a single pair of trades taking place in that window"""
import unittest
def find_profit(prices, window):
"""Given a certain window size and a list of prices, find the highest
profit possible if e... | nilq/baby-python | python |
# Generated by Django 3.1.2 on 2020-10-27 22:37
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('tailscout_app', '0005_auto_20201015_2047'),
]
operations = [
migrations.AlterField(
model_name='job',
name='bacteria... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.