content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
from functools import reduce
num = '7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828... | nilq/baby-python | python |
import numpy as np
import matplotlib.pyplot as plt
x = np.array([1., 2., 3., 4., 5.])
y = np.array([1., 3., 2., 3., 5.])
plt.scatter(x, y)
plt.axis([0, 6, 0, 6])
plt.show()
x_mean = np.mean(x)
y_mean = np.mean(y)
num = 0.0
d = 0.0
for x_i, y_i in zip(x, y):
num += (x_i - x_mean) * (y_i - y_mean)
d += (x_i - x_m... | nilq/baby-python | python |
import pika
from collections import deque
class Messaging():
def __init__(self, identity):
self._connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
self._channel = self._connection.channel()
self._queue = None
self._identity = identity
self._c... | nilq/baby-python | python |
#Desenvolva um gerador de tabuada
n = int(input("Tabuada de que número? "))
i = 0
while i < 10:
print("{} X {} = {}".format(n, i + 1, (n*(i + 1))))
i = i + 1
| nilq/baby-python | python |
# Register your models here.
from django.contrib import admin
from .models import Photo, Metadata, Album
admin.site.register(Photo)
admin.site.register(Metadata)
admin.site.register(Album)
| nilq/baby-python | python |
t = 5
sentences = []
while t:
sentences.append(input("Podaj zdanie")+"\n")
t -= 1
f = open("sentence.txt", "w")
for i in sentences:
f.write(i)
f.close()
f = open("sentence.txt", "a")
f.writelines(sentences)
f.close()
f = open("sentence.txt", "r")
for line in f:
print(line, end="")
f.close()
f = open... | nilq/baby-python | python |
import toml
output_file = ".streamlit/secrets.toml"
with open("project-327006-2314b3476b3a.json") as json_file:
json_text = json_file.read()
config = {"textkey": json_text}
toml_config = toml.dumps(config)
with open(output_file, "w") as target:
target.write(toml_config)
| nilq/baby-python | python |
from setuptools import find_packages, setup
setup(
name='robotframework-historic',
version="0.2.9",
description='Custom report to display robotframework historical execution records',
long_description='Robotframework Historic is custom report to display historical execution records using MySQL ... | nilq/baby-python | python |
import numpy as np
import random
import math
import cmath
import itertools
from tqdm import tqdm
from PIL import Image
from matplotlib import cm
def log_density_map(val, max_count):
brightness = math.log(val) / math.log(max_count)
gamma = 3.2 #7.2
brightness = math.pow(brightness, 1... | nilq/baby-python | python |
from typing import *
# extmod/modtrezorcrypto/modtrezorcrypto-bip32.h
class HDNode:
'''
BIP0032 HD node structure.
'''
def __init__(self,
depth: int,
fingerprint: int,
child_num: int,
chain_code: bytes,
private_key: b... | nilq/baby-python | python |
import django.core.management.base as djcmb
import anwesende.room.models as arm
import anwesende.users.models as aum
class Command(djcmb.BaseCommand):
help = "Silently creates group 'datenverwalter'"
def handle(self, *args, **options):
aum.User.get_datenverwalter_group() # so admin has it on first ... | nilq/baby-python | python |
'''
English_digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
Below is marathi numbers list
This program will convert the input number into english number
'''
marathi_digits = ['०', '१', '२', '१', '४', '५', '६', '७', '८', '९']
a = input("Enter marathi digit: ")
if a in marathi_digits:
print("English Digi... | nilq/baby-python | python |
# This file is part of sner4 project governed by MIT license, see the LICENSE.txt file.
"""
storage hosts views
"""
from datatables import ColumnDT, DataTables
from flask import jsonify, redirect, render_template, request, url_for
from sqlalchemy import func, literal_column
from sqlalchemy_filters import apply_filters... | nilq/baby-python | python |
import platform
import sys
class AppMapPyVerException(Exception):
pass
# Library code uses these, so provide intermediate
# functions that can be stubbed when testing.
def _get_py_version():
return sys.version_info
def _get_platform_version():
return platform.python_version()
def check_py_version():
... | nilq/baby-python | python |
'''
GaussGammaDistr.py
Joint Gaussian-Gamma distribution: D independent Gaussian-Gamma distributions
Attributes
--------
m : mean for Gaussian, length D
kappa : scalar precision parameter for Gaussian covariance
a : parameter for Gamma, vector length D
b : parameter for Gamma, vector length D
'''
import numpy as n... | nilq/baby-python | python |
import torch
from .defaults import get_default_config
def update_config(config):
if config.dataset.name in ['CIFAR10', 'CIFAR100']:
dataset_dir = f'~/.torch/datasets/{config.dataset.name}'
config.dataset.dataset_dir = dataset_dir
config.dataset.image_size = 32
config.dataset.n_cha... | nilq/baby-python | python |
from time import sleep
import logging
import pytest
from common.utils import resize_browser
from common.asserts import assert_customer_logo, assert_customer_testimonial, assert_typography, assert_overflowing
from common.svb_form import assert_required_fields_top, assert_bad_email_top, assert_non_business_email_top, ass... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import glob
import re
import json
import os
import shutil
from PIL import Image
import numpy as np
from keras.preprocessing.image import img_to_array, load_img
# 画像サイズ
IMAGE_SIZE = 224
# チャネル数
CHANNEL_SIZE = 3
# ラベル作成
def make_label_list():
# ディレクトリのパスを取得
dir_path_list = glob.glob('im... | nilq/baby-python | python |
from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from .models import CustomUser
class CustomUserCreationForm(UserCreationForm):
password1 = forms.CharField(
label= ("Password"),
strip=False,
widget=forms.PasswordInput,
)
password2 = for... | nilq/baby-python | python |
'''
Created on Sep 20, 2013
@author: nshearer
'''
from ConsoleYesNoQuestion import ConsoleYesNoQuestion
class ConsoleActionPrompt(ConsoleYesNoQuestion):
'''Present an action prompt on the console'''
# def __init__(self, question):
# super(ConsoleActionPrompt, self).__init__(question)
... | nilq/baby-python | python |
import sedate
from datetime import timedelta, time
from itertools import groupby
from sqlalchemy import types
from sqlalchemy.schema import Column
from sqlalchemy.schema import Index
from sqlalchemy.schema import UniqueConstraint
from sqlalchemy.orm import object_session
from sqlalchemy.orm.util import has_identity
... | nilq/baby-python | python |
from collections.abc import Mapping
import shelve
import random
import time
class ConcurrentShelf(Mapping):
def __init__(self, file_name, time_out_seconds=60):
self._file_name = file_name
self._time_out_seconds = time_out_seconds
self._locked_shelf = None
shelf = self._open(write=T... | nilq/baby-python | python |
from flask import Blueprint, request, jsonify
from ortools.sat.python import cp_model
import numpy
bp = Blueprint('optimize', __name__)
@bp.route('/', methods=['POST'])
def recieve_data():
model = model = cp_model.CpModel()
juniors = request.get_json()[0]
boat_parameters = request.get_json()[... | nilq/baby-python | python |
import os
import re
import datetime
from mod_python import apache
NOW = str(datetime.datetime.utcnow().strftime("%s"))
DUMP_DIR="/var/www/html/dump"
if not os.path.exists(DUMP_DIR):
os.makedirs(DUMP_DIR)
def index(req):
if not 'file' in req.form or not req.form['file'].filename:
return "Error: Please upload a fi... | nilq/baby-python | python |
# Ryan McCarthy, rbmccart@usc.edu
# ITP 115, Fall 2020
# Assignment 4
# Description:
# Part 1 takes a sentence from the user and counts the number of times a letter or special character appear
# this info is returned to the user
# Part 1: this gets the sentence
sentence = input('PART 1 - Character Counter\nPlease ente... | nilq/baby-python | python |
import peewee as pw
from core.model.base import BaseModel
from playhouse.shortcuts import model_to_dict
class Activity(BaseModel):
name = pw.CharField(null=False)
url_image = pw.CharField(null=False)
def to_dict(self, recurse=False, backrefs=False):
return model_to_dict(self, recurse=recurse, ba... | nilq/baby-python | python |
# [M / F] while not strip upper
sexo = str(input('Digite seu sexo: [M/F] ')) .strip().upper()[0]
while sexo not in 'MmFf':
sexo = str(input('Dados inválidos. Por favor, informe corretamente: ')).strip().upper()[0]
print(sexo) | nilq/baby-python | python |
import json
import jsonschema
import os
import re
from urllib.request import urlopen, Request
show_descriptions = True # If False, don't include 'name' as the description of 'licenseId'
repo = 'https://github.com/spdx/license-list-data/tree/master/json'
files = ['licenses.json', 'exceptions.json']
outfile = 'sp... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Module that contains implementation for type editor
"""
from __future__ import print_function, division, absolute_import
__author__ = "Tomas Poveda"
__license__ = "MIT"
__maintainer__ = "Tomas Poveda"
__email__ = "tpovedatd@gmail.com"
import logging
from functools i... | nilq/baby-python | python |
import random
def n_list(n):
nl = [] #int list to be returned
#creating a list of integers from 1 to n
for i in xrange(1,n+1):
nl.extend([i])
#shuffle the list of integers into random order
#to the best ability of python prng
while n > 1:
choice = int(random.random()*n)
pick = nl.pop(choice)
nl.exten... | nilq/baby-python | python |
"""
--- Day 18: Operation Order ---
As you look out the window and notice a heavily-forested continent slowly appear over the horizon, you are interrupted by the child sitting next to you. They're curious if you could help them with their math homework.
Unfortunately, it seems like this "math" follows different rules... | nilq/baby-python | python |
"""Exceptions raised by the s3control service."""
from moto.core.exceptions import RESTError
ERROR_WITH_ACCESS_POINT_NAME = """{% extends 'wrapped_single_error' %}
{% block extra %}<AccessPointName>{{ name }}</AccessPointName>{% endblock %}
"""
ERROR_WITH_ACCESS_POINT_POLICY = """{% extends 'wrapped_single_error' %... | nilq/baby-python | python |
# encoding: utf-8
from __future__ import unicode_literals
import os
from django.test import TestCase
from data_importer.core.descriptor import ReadDescriptor
from data_importer.core.descriptor import InvalidDescriptor
from data_importer.core.descriptor import InvalidModel
from data_importer.importers.base import BaseIm... | nilq/baby-python | python |
#---------------------------------------------
# Set up Trick executive parameters.
#---------------------------------------------
#instruments.echo_jobs.echo_jobs_on()
trick.exec_set_trap_sigfpe(True)
#trick.checkpoint_pre_init(1)
trick.checkpoint_post_init(1)
#trick.add_read(0.0 , '''trick.checkpoint('chkpnt_point')... | nilq/baby-python | python |
import hglib
import os
__all__ = ['HGState']
class HGState(object):
def __init__(self, path):
self.client, self.hg_root_path = self.find_hg_root(path)
def find_hg_root(self, path):
input_path = path
found_root = False
while not found_root:
try:
clie... | nilq/baby-python | python |
def isPalindrome(word):
for i in range(len(word)//2):
if word[i]!=word[-(i+1)]:
return False
return True
for t in range(10):
N=int(input())
L=[]
for i in range(8):
L.append(input())
ans=0
for i in range(8):
for j in range(9-N):
if isPalindro... | nilq/baby-python | python |
"""
pyStatic_problem
"""
# =============================================================================
# Imports
# =============================================================================
import warnings
import os
import numpy as np
from collections import OrderedDict
import time
from .base import TACSProblem
i... | nilq/baby-python | python |
# A collection of functions for loading the esm2m perturbation experiments
import xarray as xr
from gfdl_utils.core import get_pathspp
def get_path(variable=None,
ppname=None,
override=False,
experiments=None,
timespan=None):
"""Returns a dictionary of paths rele... | nilq/baby-python | python |
import imports.dataHandler as jdata
import imports.passwordToKey as keys
import imports.randomText as rand_text
import pyperclip as clipboard
import imports.CONSTS as CONSTS
import os
from cryptography.fernet import Fernet
from getpass import getpass
import json
protected = ["key", "state"]
MAIN_MENU = 0
RECORDS = ... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from doodle.config import CONFIG
from doodle.core.models.article import Article, ArticleHitCount
from doodle.core.models.comment import ArticleComments
from ..base_handler import BaseHandler
class HomeHandler(BaseHandler):
def get(self):
articles, next_cursor = Article.get_articl... | nilq/baby-python | python |
# NOTICE
# This software was produced for the U.S. Government under contract FA8702-21-C-0001,
# and is subject to the Rights in Data-General Clause 52.227-14, Alt. IV (DEC 2007)
# ©2021 The MITRE Corporation. All Rights Reserved.
'''
A PropertyConstraints object describes type and cardinality constraints
for a single... | nilq/baby-python | python |
from mock import Mock
from flows.simulacra.youtube_dl.factory import youtube_dl_flow_factory
from flows.simulacra.youtube_dl.post import download_videos
from tests.testcase import TestCase
class TestDownloadVideos(TestCase):
def setUp(self):
self.open = self.set_up_patch(
'flows.simulacra.you... | nilq/baby-python | python |
# Copyright 2015 - Mirantis, 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 or ag... | nilq/baby-python | python |
# Copyright 2021 Prayas Energy Group(https://www.prayaspune.org/peg/)
#
# 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 |
import gym
import numpy as np
from gym.spaces import Discrete
from gym_holdem.holdem import Table, Player, BetRound
from pokereval_cactus import Card
class HoldemEnv(gym.Env):
def __init__(self, player_amount=4, small_blind=25, big_blind=50, stakes=1000):
super().__init__()
self.player_amount =... | nilq/baby-python | python |
# Generated by Django 4.0.1 on 2022-01-27 07:04
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('catalog', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='bookinstance',
options={'ordering': ... | nilq/baby-python | python |
"""
return 0 = Success
return 1 = Login = 'Invalid username or password!', Register = 'User is already'
return 2 = 'Something went wrong'
"""
from connect_db import megatronDBC
# login sys / ระบบล็อคอิน
def loginSYS(userInput, passInput):
try:
cursor = megatronDBC.cursor()
select... | nilq/baby-python | python |
from datetime import timedelta
from app import hackathon_variables
from django.db import models
from django.utils import timezone
from user.models import User
class ItemType(models.Model):
"""Represents a kind of hardware"""
# Human readable name
name = models.CharField(max_length=50, unique=True)
#... | nilq/baby-python | python |
from __future__ import print_function
from builtins import object
import copy
import numpy as np
class Observer(object):
def __init__(self):
pass
def update(self, state):
pass
def reset(self):
pass
class Printer(object):
def __init__(self, elems=1, msg=None, skip=1):
... | nilq/baby-python | python |
# proxy module
from __future__ import absolute_import
from chaco.abstract_plot_data import *
| nilq/baby-python | python |
__author__ = "Doug Napoleone"
__version__ = "0.0.1"
__email__ = 'Doug.Napoleone+niche_scraper@gmail.com' | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'ipetrash'
import logging
from flask import Flask
from flask_debugtoolbar import DebugToolbarExtension
app = Flask(__name__)
# set a 'SECRET_KEY' to enable the Flask session cookies
app.config['SECRET_KEY'] = '<replace with a secret key>'
@app.route("/... | nilq/baby-python | python |
from loggers import Actions
from stopping_decision_makers.base_decision_maker import BaseDecisionMaker
class SequentialNonrelDecisionMaker(BaseDecisionMaker):
"""
A concrete implementation of a decision maker.
Returns True iif the depth at which a user is in a SERP is less than a predetermined value.
"... | nilq/baby-python | python |
from django.db import models
from django.contrib.auth.models import User
from course.models import Course
# Create your models here.
class Answer(models.Model):
user = models.ForeignKey(User, name="user", on_delete=models.CASCADE)
answer = models.TextField()
def __str__(self) -> str:
return se... | nilq/baby-python | python |
# Time: O(k * log(min(n, m, k))), with n x m matrix
# Space: O(min(n, m, k))
from heapq import heappush, heappop
class Solution(object):
def kthSmallest(self, matrix, k):
"""
:type matrix: List[List[int]]
:type k: int
:rtype: int
"""
kth_smallest = 0
min_he... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from . import main_menu, signals, slides, widgets # noqa
| nilq/baby-python | python |
# -*- coding: utf-8 -*-
'''
@author: wj3235@126.com
说明:(1)程序仅供技术学习,严禁用于任何商业用途
(2)对于抓取内容及其分析,请勿乱发布,后果自负
(3)软件可能有bug,如果发现望及时告知
(4)成交数据,需要提供修改账户密码,请查找 admin 或者password 修改
'''
import sqlite3
import os
from ErShouFangDbHelper import GetXiaoquNianDai
from ErShouFangDbHelper imp... | nilq/baby-python | python |
from flask import Blueprint, request
from libs.tools import json_response, JsonParser, Argument
from .models import NotifyWay
blueprint = Blueprint(__name__, __name__)
@blueprint.route('/', methods=['GET'])
def get():
form, error = JsonParser(Argument('page', type=int, default=1, required=False),
... | nilq/baby-python | python |
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
#
# 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 Licen... | nilq/baby-python | python |
import pytest
from django.contrib.auth.models import User
from shrubberies.factories import UserFactory
from shrubberies.models import Profile
from .rules import Is, current_user
@pytest.mark.django_db
def test_is_user_function():
u1 = UserFactory()
u2 = UserFactory()
is_own_profile = Is(lambda u: u.prof... | nilq/baby-python | python |
if __name__ == '__main__':
from scummer.validator import Validator
t = {
'a': 'x',
'b': {
'b1': 123
},
'c': [1,2],
'd': {
'x': 1,
'y': 'aaaa'
}
}
v = Validator(schema={
'a': ('enum',{
'items': ['x',... | nilq/baby-python | python |
import pandas as pd
import matplotlib.pyplot as plt
import pdb
def main():
results_df = pd.read_csv("results_nm.csv", delimiter=",")
fig_0, ax_0 = plt.subplots()
fig_1, ax_1 = plt.subplots()
for m in results_df.m.unique():
m_subset = results_df[results_df.m == m]
m_means = []
m_... | nilq/baby-python | python |
import json
import sys
import os
def get_offset(call):
s = call.split("+")
try:
return int(s[1], 16)
except:
pass
def get_hashsum(call):
s = call.split("{")
try:
ss = s[1].split("}")
return ss[0]
except:
s = call.split("!")
try:
retur... | nilq/baby-python | python |
import os
import shutil
# optional: if you get a SSL CERTIFICATE_VERIFY_FAILED exception
import ssl
import sys
from io import BytesIO
from pathlib import Path
from urllib.parse import urlparse
from urllib.request import urlopen, urlretrieve
from zipfile import ZipFile, is_zipfile
import pandas as pd
from tqdm import ... | nilq/baby-python | python |
def test_latest():
print('\n >>> start Latest Features... \n')
import talos
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
x, y = talos.templates.datasets.iris()
p = {'activation': ['relu', 'elu'],
'optimizer': ['Nadam', 'Adam'],
'l... | nilq/baby-python | python |
# Time Complexity: O(n^2)
# Space Complexity: O(n)
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
res = []
nums.sort()
for cur in range(len(nums)):
if nums[cur] > 0: break
if cur>0 and nums[cur]==nums[cur-1]: continue # 重点理解
... | nilq/baby-python | python |
import pandas as pd
import os
# df = pd.read_csv('./train_annotation_list.csv')
# for i in range (len(df['Image_Path'])):
# dirname = os.path.dirname(df['Image_Path'][i])
# patient_name = os.path.basename(df['Image_Path'][i])
# patient_no = int(patient_name.split('.')[0].split('_')[1])
# folder = 'center_'+str(in... | nilq/baby-python | python |
import pandas as pd
import matplotlib.pyplot as plt
import errno
import os
import numpy as np
from pathlib import Path
import data_helper as dh
# Counts the number of learning agents in one log path
def count_learning_agents_in_logs_path(logs_path):
count = 0
# loop through win rates directories in logs
... | nilq/baby-python | python |
# TODO: change name to queue
from db_works import db_connect, db_tables
import datetime
def get_settings(interval_param_):
db_schema_name, db_table_name, db_settings_table_name = db_tables()
cursor, cnxn = db_connect()
# interval parameter: current - API data; daily_hist - data from daily files; monthly... | nilq/baby-python | python |
from tests.utils import TEST_DATA_DIR
from dexy.doc import Doc
from tests.utils import wrap
import os
markdown_file = os.path.join(TEST_DATA_DIR, "markdown-test.md")
def run_kramdown(ext):
with open(markdown_file, 'r') as f:
example_markdown = f.read()
with wrap() as wrapper:
node = Doc("mark... | nilq/baby-python | python |
from flask import Blueprint
from flask import redirect
from flask import render_template
from flask import abort, jsonify, request
from flask_login import current_user
from flask_login import login_required
from app.models import User, load_user
from app.extensions import db
import os
import stripe
stripe.api_key =... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import get_object_or_404
from django.db import models, migrations
def encrypt_secrets(apps, schema_editor):
Secret = apps.get_model("server", "Secret")
for secret in Secret.objects.all():
secret.save()
class Migrat... | nilq/baby-python | python |
import pytest
from tartiflette_middleware.examples.standalone import\
StandaloneMiddleware
from tartiflette_middleware.exceptions import\
RequestDataNotStoredException
class TestStandaloneMiddleware:
def test_standalone_example_init(self):
service = StandaloneMiddleware()
@pytest.mark.asyncio... | nilq/baby-python | python |
import pyrebase
config={
"apiKey": "AIzaSyDYt-fmafI1kkMZSIphL829C6QgdlE1Tro",
"authDomain": "cp19-12.firebaseapp.com",
"databaseURL": "https://cp19-12.firebaseio.com",
" projectId": "cp19-12",
"storageBucket": "cp19-12.appspot.com",
"messagingSenderId": "681358965828",
"appId": "1:681358965828:we... | nilq/baby-python | python |
# 代码仅供学习交流,不得用于商业/非法使用
# 作者:Charles
# 公众号:Charles的皮卡丘
# 视频下载器-Demo版
# 目前支持的平台:
# 网易云课堂: wangyiyun.wangyiyun()
# 音悦台: yinyuetai.yinyuetai()
# B站: bilibili.bilibili()
import os
import threading
from platforms import *
from utils.utils import *
from tkinter import *
from tkinter import messagebox
from tkinter import fi... | nilq/baby-python | python |
from __future__ import print_function
import urllib2
import json
import re,datetime
import sys
import csv
class L():
"Anonymous container"
def __init__(i,**fields) :
i.override(fields)
def override(i,d): i.__dict__.update(d); return i
def __repr__(i):
d = i.__dict__
name = i.__class__.__name__
... | nilq/baby-python | python |
#!/usr/bin/env python3
print(2+4)
print(5**2) # is like 5 power 2 (5^2)
print(5*7 - 9*1)
print(4/2)
print(5/2)
print(5//2) # removes the values after the point
print(7 % 3) # This is the remainder or modulus operator
print(1+1 +(2*5))
print(len("Linux"))
| nilq/baby-python | python |
# SPDX-FileCopyrightText: 2020 Jeff Epler for Adafruit Industries
#
# SPDX-License-Identifier: MIT
import time
import os
# First, just write the file 'hello.txt' to the card
with open("/sd/hello.txt", "w") as f:
print("hello world", file=f)
print()
print("SD card I/O benchmarks")
# Test read and write speed in... | nilq/baby-python | python |
#!/usr/bin/env python
import rospy
from std_msgs.msg import String
from geometry_msgs.msg import Twist
key_mapping = {'w': [0, 1], 'x': [0, -1],
'a': [-1, 0], 'd': [1, 0],
's': [0, 0]}
g_last_twist = None
def keys_cb(msg, twist_pub):
global g_last_twist
if len(msg.data) == 0 ... | nilq/baby-python | python |
import abc
import json
import logging
import os
import numpy as np
import tensorflow as tf
def zip_weights(model, ckpt, variables_mapping, self_weight_names, **kwargs):
weights, values = [], []
used_weights = [w for w in model.trainable_weights if w.name in self_weight_names]
for w in used_weights:
... | nilq/baby-python | python |
import tensorflow as tf
import value_fns
class ValueFnTests(tf.test.TestCase):
def test_label_attention_fn(self):
with self.test_session():
mode = tf.estimator.ModeKeys.TRAIN
# num_labels x label_embedding_dim
label_embeddings = tf.constant([[0.1, 0.1, 0.1, 0.1],
... | nilq/baby-python | python |
"""
fabfile module containing application-specific tasks.
"""
from fabric.api import task
from fabric.colors import cyan
from fabfile.utils import do
from fabfile.virtualenv import venv_path
@task
def build():
"""
Run application build tasks.
"""
# Generate static assets. Note that we always build ass... | nilq/baby-python | python |
"""
OpenOpt SOCP example
for the problem http://openopt.org/images/2/28/SOCP.png
"""
from numpy import *
from openopt import SOCP
f = array([-2, 1, 5])
C0 = mat('-13 3 5; -12 12 -6')
d0 = [-3, -2]
q0 = array([-12, -6, 5])
s0 = -12
C1 = mat('-3 6 2; 1 9 2; -1 -19 3')
d1 = [0, 3, -42]
q1 = array([-3, 6, -10])
s1 = 27... | nilq/baby-python | python |
from splinter import Browser
b = Browser()
b.visit('http://selenium.dunossauro.live/aula_09_a.html')
if b.is_text_not_present('Carregamento concluído'):
b.find_by_text('Barrinha top').click()
print(b.is_text_present('Barrinha top', wait_time=10))
| nilq/baby-python | python |
""" Shows how to combine surface terrain with surface properties
"""
from __future__ import print_function
from __future__ import division
import matplotlib as mpl
mpl.interactive(False)
import sys
import numpy as np
import matplotlib.pyplot as plt
from plotting import make_test_data
from plotting import draw
from ... | nilq/baby-python | python |
# Now make a simple example using the custom projection.
import pdb
import sys
import os
import pkg_resources
pkg_resources.require('matplotlib==1.4.0')
import datetime
from dateutil.relativedelta import relativedelta
import re
import math
from matplotlib.ticker import ScalarFormatter, MultipleLocator
from matplotlib... | nilq/baby-python | python |
"""
Stores all the view logic for deckr.
"""
# pylint can't detect the constructor for a Django
# form. So we disable the no-value-for-parameter here.
# pylint: disable=no-value-for-parameter
from os.path import join as pjoin
from django.core.urlresolvers import reverse
from django.shortcuts import get_object_or_404... | nilq/baby-python | python |
from org.transcrypt.stubs.browser import *
import random
array = []
array_str = ""
def gen_random_int(number, seed):
# console.log("random")
random.seed(seed)
array = list(range(0, number))
random.shuffle(array)
return array
def generate():
global array
global array_str
number = 10
seed = 200
array = ... | nilq/baby-python | python |
"""Mathematical utility functions (intended for internal purposes).
A lot of this is experimental and has a high probability of changing in the future.
"""
import functools
import itertools
import math
import operator
import numpy as np
__all__ = [
"argmax",
"chain_dot",
"clamp",
"dot",
"dotvecm... | nilq/baby-python | python |
from pymocap.color_terminal import ColorTerminal
from pymocap.event import Event
import struct, os
from datetime import datetime
class NatnetFile:
def __init__(self, path=None, loop=True):
self.path = path
self.loop = loop
# file handles
self.read_file = None
self.write_fi... | nilq/baby-python | python |
import io
import re
from math import ceil
from . import *
from config import Config
from userbot import CMD_LIST, CMD_HELP
from telethon import custom, events
Andencento_pic = Config.PMPERMIT_PIC or "https://telegra.ph/file/ac32724650ef92663fbd1.png"
cstm_pmp = Config.CUSTOM_PMPERMIT
ALV_PIC = Config.ALIVE_PIC
mssge = ... | nilq/baby-python | python |
import numpy as np
import sys
def get_randn(n=10):
randints = np.random.randint(100, size=n)
return ":".join(["%02d" % i for i in randints])
| nilq/baby-python | python |
'''
hms_client
'''
from hubsync.http_client import client
class Repo(object):
''' Repo
Namespace string `json:"namespace,omitempty"`
Name string `json:"name,omitempty"`
LogoUrl string `json:"logoUrl"`
Summary string `json:"summary,omitempty"`
Description string `json:"descri... | nilq/baby-python | python |
#!/usr/bin/env python
from peyotl.nexson_validation.helper import _NEXEL, errorReturn
from peyotl.nexson_validation.err_generator import (gen_InvalidKeyWarning,
gen_MissingCrucialContentWarning,
gen_MissingMandatoryK... | nilq/baby-python | python |
pytest_plugins = "beancount.ingest.regression_pytest"
| nilq/baby-python | python |
import sys
sys.path.append('../../')
import open3d
import numpy as np
import time
import os
from ThreeDMatch.Test.tools import get_pcd, get_ETH_keypts, get_desc, loadlog
from sklearn.neighbors import KDTree
import glob
def calculate_M(source_desc, target_desc):
"""
Find the mutually closest point pairs in fe... | nilq/baby-python | python |
class Space(object):
def __init__(self, col, row, terrain='.'):
self.col = col
self.row = row
self.terrain = terrain
self.occupied = False
| nilq/baby-python | python |
from django.contrib import admin
from .models import AcademicNotice
# Register your models here.
class MyModelAdmin(admin.ModelAdmin):
fields = ['title','body']
def save_model(self,request,obj,form,change):
obj.author = request.user
super().save_model(request, obj, form, change)
admin.site.register(AcademicNotice... | nilq/baby-python | python |
import tensorflow as tf
from tensorflow import keras
# from tensorflow.
model = tf.keras.models.Sequential([
keras.layers.Dense(512, activation='relu', input_shape=(784,)),
keras.layers.Dropout(0.2),
keras.layers.Dense(10)
])
#1
# model.compile(loss='mean_squared_error', optimizer='sgd')
#2
from keras i... | nilq/baby-python | python |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def constructMaximumBinaryTree(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.