content stringlengths 5 1.05M |
|---|
import numpy as np
import pandas as pd
from sklearn.metrics.regression import mean_squared_error
from sklearn.metrics import make_scorer
from sklearn.model_selection import KFold
from mlens.visualization import corrmat
from utils.io_utils import save_csv, pickle_file, FITTED_MODEL_PATH, REPORT_PATH, REPORT_FORMAT, \
... |
class Solution(object):
def XXX(self, root):
self.res = True
def search_depth(node):
if not node:
return 0
left_depth = search_depth(node.left) + 1
right_depth = search_depth(node.right) + 1
ans = abs(left_depth - right_depth)
... |
# =============================================================================== #
# #
# This file has been generated automatically!! Do not change this manually! #
# ... |
# Write a Python program to get the volume of a sphere with radius input from user.
import math
r = int(input("Enter a radius: "))
constant = 4 / 3
ans = constant * math.pi * math.pow(r, 3)
print(ans)
|
__prog__ = 's3pypi'
__version__ = u'0.7.1'
|
from collections import OrderedDict
import json
from autobahn.twisted.websocket import WebSocketClientFactory
from delorean import Delorean
import treq
from twisted.internet import defer, reactor
from twisted.python import log
import gryphon.data_service.consts as consts
import gryphon.data_service.util as util
from ... |
''' This is the script to make figure 1. of the paper
This script is a a good exampel of how to implement 1-loop calculations.
See line 24 (or around line 24 ) for the call to FAST-PT
J. E. McEwen
email: jmcewen314@gmail.com
'''
import numpy as np
#from matter_power_spt import one_loop
import FASTPT
from time ... |
#!/usr/bin/env python3
#https://codeforces.com/problemset/problem/1312/A
divok = lambda l: l[0]%l[1]==0
[print('YES' if divok(list(map(int,input().split()))) else 'NO') for _ in range(int(input()))]
|
# -*- coding: utf-8 -*-
"""
Contains the Email class that handles generation of the email message
per configuration defined in the Coordinator class.
"""
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email import encoders
import os
from s... |
import sys
import re
from pathlib import Path
p = re.compile('^[ぁ-ゟ]+')
path = Path(sys.argv[1])
name = path.name
print(name)
kpath = path.parent / f'K{name}'
hpath = path.parent / f'H{name}'
with path.open() as f:
with open(str(kpath), 'w') as kf:
with open(str(hpath), 'w') as hf:
for line i... |
"""
Collection of PyTorch activation functions, wrapped to fit Ivy syntax and signature.
"""
from typing import Optional
# global
import numpy as np
import torch
# local
import ivy
def relu(x: torch.Tensor,
out: Optional[torch.Tensor] = None)\
-> torch.Tensor:
ret = torch.relu(x)
if ivy.ex... |
"""
URL configuration for django-cloudprojects.
"""
from django.conf import settings
from django.urls import include, path
urlpatterns = []
if 'django_saml' in settings.INSTALLED_APPS:
urlpatterns = [
path('saml/', include('django_saml.urls')),
]
urlpatterns += [
path('', include('allauth.urls')... |
import pandas as pd
from constants import PARTS_DIR, DAY
from featnames import LOOKUP, START_TIME, END_TIME, START_PRICE, DEC_PRICE, \
ACC_PRICE, START_DATE
from processing.util import get_lstgs
from utils import topickle, input_partition, load_feats
def create_lookup(lstgs=None):
# load data
listings = l... |
import torch
from torch import nn as nn, Tensor
import os
import pandas as pd
import numpy as np
class PartialSelectiveLoss(nn.Module):
def __init__(self, args):
super(PartialSelectiveLoss, self).__init__()
self.args = args
self.clip = args.clip
self.gamma_pos = args.gamma_pos
... |
#!/usr/bin/env python3
import sys
import cv2
import rospy
import base64
import random
import numpy as np
sys.path.append(r'./database')
from database import *
from rosproject.srv import Img
from obj_detect import object_detection
def object_detect_server():
rospy.init_node('object_detect_server', anonymous = T... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
#
import find_newest_files
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import os
import sys
class Window(QWidget):
def __init__(self, parent=None):
QWidget.__init__(self, parent)
# -- inputs ----------------... |
import discord
from helpers import get_gif
commands = ["drinkcoffee"]
requires_mention = False
accepts_mention = False
description = "KAFFEE!!! :coffee:"
async def execute(message):
gif = get_gif('coffee', lmt=25, pos=0)
embed = discord.Embed()
embed.description = '<:metalcoffee:707941148777512966>'
... |
from PIL import Image, ImageOps
def normalize_image(img):
"""Normalize image between 0 and 255.
Args:
img (PIL image): An image.
Returns:
PIL image: A normalized image.
Examples:
>>> img = Image.open('share/Lenna.png')
>>> vals = img.getextrema() #gets mi... |
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOW_ALL_ORIGINS = True
|
from alpyro_msgs import RosMessage
from alpyro_msgs.actionlib_msgs.goalid import GoalID
from alpyro_msgs.nav_msgs.getmapgoal import GetMapGoal
from alpyro_msgs.std_msgs.header import Header
class GetMapActionGoal(RosMessage):
__msg_typ__ = "nav_msgs/GetMapActionGoal"
__msg_def__ = "c3RkX21zZ3MvSGVhZGVyIGhlYWRlcgo... |
"""frontend.main"""
import json
from flask import Flask, request, render_template
from concurrent.futures import ThreadPoolExecutor
from agent_connector import Agent
tools = [
'exeinfope',
'pestudio'
]
app = Flask('hhfrontend')
executor = ThreadPoolExecutor(2)
agent_controllers = dict()
with open('agents.... |
import csv,io
class CiteFile():
global csvfileinmem
csvfileinmem = None
def __init__(self):
self.filename = "C:\git\wikieupmcanalytics\citations-enwiki-20151002.csv"
self.csvfile = open(self.filename, "r", encoding='utf-8', newline='\r\n')
global csvfileinmem
if csvfileinme... |
import click
from eth_wallet.cli.utils_cli import (
get_api,
)
from eth_wallet.configuration import (
Configuration,
)
@click.command()
def list_tokens():
"""List all added tokens."""
configuration = Configuration().load_configuration()
api = get_api()
tokens = api.list_tokens(configuration)
... |
from collections import defaultdict
def generate(c1,c2,bitlen):
y = 2**bitlen
a = c1 & ~y
b = c2 & ~y
c = c1 / 2
d = c2 / 2
return (a&~b&~c&~d) | (~a&b&~c&~d) | (~a&~b&c&~d) | (~a&~b&~c&d)
def buildMap(n, generations):
mapping = defaultdict(set)
generations = set(generations)
... |
"""
Demo/test program for the AE_Button driver.
See https://github.com/sensemakersamsterdam/astroplant_explorer
"""
#
# (c) Sensemakersams.org and others. See https://github.com/sensemakersamsterdam/astroplant_explorer
# Author: Gijs Mos
#
# Warning: if import of ae_* modules fails, then you need to set up PYTHONPATH.
... |
# TODO : strict minimal ipython REPL launcher to use aiokraken.
# Nice TUI|GUI can be done in another project.
# !/usr/bin/env python
# Ref : https://ipython.org/ipython-doc/stable/interactive/reference.html#embedding-ipython
"""
__main__ has only the code required to start IPython and provide interactive introspect... |
import itertools as it
import numpy as np
import tensorflow as tf
def get_cifar10(batch_size=16):
print("loading cifar10 data ... ")
from skdata.cifar10.dataset import CIFAR10
cifar10 = CIFAR10()
cifar10.fetch(True)
trn_labels = []
trn_pixels = []
for i in range(1,6):
data = cifa... |
from suds.client import Client
from suds import WebFault
class SoapHelper:
def __init__(self, app):
self.app = app
def take_array_project(self, username, password):
client = Client(self.app.service)
try:
client.service.mc_projects_get_user_accessible(username, password)
... |
#
# (c) 2008-2020 Matthew Shaw
#
import sys
import os
import re
import logging
import nelly
from .scanner import Scanner
from .program import Program
from .types import *
class Parser(object):
def __init__(self, include_dirs=[]):
self.include_dirs = include_dirs + [ os.path.join(nelly.root, 'grammars... |
import dash
import pandas as pd
import pathlib
import dash_core_components as dcc
import dash_html_components as html
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__)
# get relative data folder
PATH = pathlib.Path(__file__).parent
print(PATH)
DATA_PATH = PATH.joinpath(... |
from models import MPNN, DoubleLayerMLP
from mao import MAOdataset
import torch
import torch.nn as nn
import torch.nn.functional as F
import os.path
class MultiMNNP_MOA(nn.Module):
"""
A class for a complex a message-passing graph neural network for MOA classification.
Based on the generalization... |
# Seeeduino XIAO (SAMD21 Cortex® M0+)
#
# Hardware: https://www.seeedstudio.com/Seeeduino-XIAO-Arduino-Microcontroller-SAMD21-Cortex-M0+-p-4426.html
# CircuitPython: https://circuitpython.org/board/seeeduino_xiao/
#
# Reset: RST pads short-cut two times
#
import os
import microcontroller
import board
import time
fro... |
#
# 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
# ... |
#
# Copyright: Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.compat.tests.mock import patch
from ansible.modules.network.on... |
import unittest
from mplisp import evaluator
class TestSyntax(unittest.TestCase):
def test_string(self):
"""test string"""
input1 = """
(def a \'str\')
(assert-equal! a 'str')
"""
output1 = evaluator.evaluate(input1, None, True)
output2 = evaluator.evalua... |
# -*- coding: utf-8 -*-
# Copyright Noronha Development Team
#
# 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 applica... |
# Copyright 2018, Red Hat, Inc.
# Ryan Petrello <rpetrell@redhat.com>
#
# 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... |
#from django import forms
from django.forms import ModelForm
from .models import Resource, Topic
class ResourceCreateForm(ModelForm):
class Meta:
model = Resource
exclude = ('created_by', 'slug', 'help_text', 'show')
class ResourceUpdateForm(ModelForm):
class Meta:
model = Resource
... |
from more_itertools.more import *
from more_itertools.recipes import *
|
from Card import *
import random
class Deck:
def __init__(self):
self.cards = []
def build(self):
#2 of each number but 0, two of each special card, and 4 of each wilds.
for c in ["Red", "Blue", "Green", "Yellow"]:
self.cards.append(Card(c, 0))
for ... |
from cli import *
from sim_commands import *
def shadow_cmd(obj):
r = [ [ "Base", "Read", "Write" ] ]
read_write = ("PCI", "RAM")
crs = obj.config_register
for i in range(384/2):
subrange = crs[i]
if subrange:
r.append(["%x" % ((640 + i * 2) * 1024), read_write[subrange & 1]... |
import numpy as np
import sys # for sys.float_info.epsilon
######################################################################
### class QDA
######################################################################
class QDA(object):
def __init__(self):
# Define all instance variables here. Not nece... |
#!/usr/bin/env python
import argparse
from collections import defaultdict
import glob
import inspect
import json
import logging
import os
import shutil
from astropy.io import fits
from astropy.time import Time
import numpy as np
import pandas as pd
from tqdm import tqdm
logging.basicConfig(format='%(levelname)-4s '... |
from socket import *
import random
serverSocket = socket(AF_INET, SOCK_DGRAM)
serverSocket.bind(('', 12000))
while True:
rand = random.randint(0, 10)
message, address = serverSocket.recvfrom(1024)
message = message.upper()
if rand < 4:
continue
serverSocket.sendto(message, address) |
# Generated by Django 2.2.10 on 2020-04-30 04:36
from django.db import migrations, models
import uuid
class Migration(migrations.Migration):
dependencies = [
('bank', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='walletaccount',
name='user_id... |
# coding=utf-8
# Copyright 2019 The Google Research Authors.
#
# 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 applicab... |
# Copyright 2021 Sony Semiconductors Israel, Inc. All rights reserved.
#
# 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 b... |
import json
import math
from scipy.stats import poisson
import sys
import logging
import numpy as np
from mpmath import *
from probabilistic import *
from multiprocessing import Pool, TimeoutError, Manager
from calcGenerativeTask import calculationTask
mp.dps=snakemake.params['dps']
logging.basicConfig(filename=snakem... |
import inspect
import functools
from typing import OrderedDict, Tuple
def _cast(
obj: object,
cast_to: type,
cast_rules: OrderedDict[Tuple[type, type], callable]):
for (input_type, output_type), func in cast_rules.items():
if isinstance(obj, input_type):
return func(obj... |
from scripttest import TestFileEnvironment
import re
# from filecmp import cmp
bindir = "graphprot/"
script = "graphprot_seqmodel"
# test file environment
datadir = "test/"
testdir = "test/testenv_graphprot_seqmodel/"
# directories relative to test file environment
bindir_rel = "../../" + bindir
datadir_rel = "../../"... |
import math
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
import matplotlib.pyplot as plt
import deepdish as dd
from sklearn.linear_model import LinearRegression
from collections import deque
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import m... |
# 전자레인지
T = int(input())
button = [300, 60, 10]
count = [0, 0, 0]
for i in range(len(button)):
if T >= button[i]:
count[i] += T // button[i]
T %= button[i]
if T != 0:
print(-1)
else:
for j in range(0, len(count)):
print(count[j], end = " ")
|
# Generated by Django 3.0.5 on 2020-04-11 23:14
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('users', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='customuser',
name='user_name',
... |
#!/usr/bin/env python
"""Extract individual letter images using Tesseract box files.
Usage:
./extract_box.py path/to/data.box path/to/data.png outputdir
"""
import errno
import os
import re
import sys
from PIL import Image
import box
def path_for_letter(output_dir, image_path, idx, letter):
image_base = ... |
from .base import set_plots, heatmap, add_watermark
|
from enum import Enum
class PortModeEnum(str, Enum):
POM_UNTAGGED = "POM_UNTAGGED"
POM_TAGGED_STATIC = "POM_TAGGED_STATIC"
POM_FORBIDDEN = "POM_FORBIDDEN"
|
import bs4, requests, sys, urllib, simplejson
def search(searchText, playlist=False):
results = []
query = requests.get("https://www.youtube.com/results?search_query=" + searchText).text
soup = bs4.BeautifulSoup(query, features="html.parser")
div = [d for d in soup.find_all('div') if d.has_attr('class... |
import logging
logger = logging.getLogger(__name__)
def transform_subject(subject, loop_size):
value = 1
for i in range(loop_size):
value *= subject
value = value % 20201227
return value
def reverse_loop_size(subject, result):
loop_size = 2
value = subject
while True:
... |
#!/usr/bin/env python3
########################################################################################################################
##### INFORMATION ######################################################################################################
### @PROJECT_NAME: SPLAT: Speech Processing and Lingu... |
# 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... |
from meiga import Error
class GivenInputIsNotValidError(Error):
def __init__(self, message):
self.message = f"{self.__class__.__name__:s}: [{message:s}]"
|
import unittest
import json
import jsonasobj
from dict_compare import compare_dicts
from jsonasobj._jsonobj import as_json, as_dict
test_data = {
"@context": {
"name": "http://xmlns.com/foaf/0.1/name",
"knows": "http://xmlns.com/foaf/0.1/knows",
"menu": {
"@id": "name:foo",
"@type": "@id"
... |
import os
get_abs_path = lambda p: os.path.abspath(os.path.join(os.path.dirname(__file__), p))
MIDI_DIR = get_abs_path("../data/raw/")
SEQUENCE_FILE = get_abs_path("../data/interim/notesequences.tfrecord")
OUTPUT_DIR = get_abs_path("../data/processed")
MODEL_DIR = get_abs_path("../models")
GENERATED_DIR = get_abs_... |
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
import pymongo
from readability import Document
class NewsPipeline(object):
def process_item(self, item, spider):
r... |
"""Tests for interpreting and handling job configuration submissions."""
# NOTE: importing entire job_service us to modify module's global variables
from datetime import date
from json import dumps, load, loads
from pathlib import Path
from time import time
from typing import Union
from moto import mock_s3, mock_sqs
fr... |
class HapiError(ValueError):
"""Any problems get thrown as HapiError exceptions with the relevant info inside"""
def __init__(self, result, request):
super(HapiError,self).__init__(result.reason)
self.result = result
self.request = request
def __str__(self):
return "\n---- ... |
from xylophone import resources
from xylophone.stages.base import StageBase, ArgumentParser, register_stage
@register_stage("words-dict")
class WordsDict(StageBase):
_parser = ArgumentParser(
usage="xylophone -s words-dict [--obj-add OBJECTS_ADDITIONAL] [--adj-add ADJECTIVES_ADDITIONAL] "
"[... |
from setuptools import find_packages, setup
setup(
name='src',
packages=find_packages(),
version='0.1.0',
description='Predicting Android build Performance using Machine Learning',
author='Dheeraj Bajaj',
license='MIT',
)
|
DEBUG = True
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql_psycopg2",
"NAME": "test",
"USER": "postgres",
"PASSWORD": "",
"HOST": "",
"PORT": "",
}
}
INSTALLED_APPS = (
'banner',
'banner.tests',
'django_comments',
'jmbo',
... |
from dipsim import multiframe, util
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import matplotlib.patches as patches
import os; import time; start = time.time(); print('Running...')
import matplotlib.gridspec as gridspec
# Main input parameters
col_labels = ['Geometry\n (NA = 0.6, $\\beta=80{}... |
#!/usr/bin/env python
'''
An example of a tagging service using NER suite.
'''
from argparse import ArgumentParser
from os.path import join as path_join
from os.path import dirname
try:
from json import dumps
except ImportError:
# likely old Python; try to fall back on ujson in brat distrib
from sys imp... |
import sys
import numpy as np
import schwimmbad
import multiprocessing
import logging
import time
import fitsio
from mdetsims.metacal import (
MetacalPlusMOF,
MetacalTrueDetect,
MetacalSepDetect)
from mdetsims.run_utils import (
estimate_m_and_c, cut_nones,
measure_shear_metadetect,
measure_she... |
total = 0
for i in range(2,101,2):
total += i
print(total) |
# Generated by Django 3.0.3 on 2020-03-20 15:26
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('project_core', '0111_remove_project_duration_months'),
]
operations = [
migrations.AddField(
model... |
import numpy as np
from scipy import signal, ndimage
from skimage.feature import blob_dog, blob_log
from skimage.exposure import rescale_intensity
from hexrd import convolution
from hexrd.constants import fwhm_to_sigma
# =============================================================================
# BACKGROUND REMO... |
# Generated by Django 3.2.7 on 2021-09-18 13:04
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pokecards', '0003_alter_cards_start_date'),
]
operations = [
migrations.AlterField(
model_name='cards',
... |
from django.contrib.gis.db import models
class SamplingMethod(models.Model):
"""Sampling method model definition"""
sampling_method = models.CharField(
max_length=200,
null=False,
blank=False
)
effort_measure = models.CharField(
max_length=300,
null=True,
... |
import discord
import configparser
import asyncio
import os
client = discord.Client()
@client.event
async def on_ready():
a = configparser.ConfigParser()
print(client.user.id)
print("ready")
game = discord.Game("p!help")
await client.change_presence(status=discord.Status.online, a... |
import torch
from torch import nn
from torch.nn import functional as F
from torch.nn.parameter import Parameter
# adapted from https://colab.research.google.com/github/bayesgroup/deepbayes-2019/blob/master/seminars/day6/SparseVD-solution.ipynb
class LinearSVDO(nn.Module):
def __init__(self, in_features, out_feat... |
import shutil
from pathlib import Path
from uuid import uuid4
import pytest
from panimg.models import ImageType, PanImgFile
from panimg.post_processors.tiff_to_dzi import tiff_to_dzi
from tests import RESOURCE_PATH
def test_dzi_creation(tmpdir_factory):
filename = "valid_tiff.tif"
temp_file = Path(tmpdir_f... |
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import copy
import json
import unittest
from dashboard import bisect_report
from dashboard.common import testing_common
from dashboard.models import try_job... |
class Script(bytes):
Opcode = {
"NOP": 0x00,
"BURN": 0x01,
"SUCCESS": 0x02,
"FAIL": 0x03,
"NOT": 0x10,
"EQ": 0x11,
"JMP": 0x20,
"JNZ": 0x21,
"JZ": 0x22,
"PUSH": 0x30,
"POP": 0x31,
"PUSHB": 0x32,
"DUP": 0x33,
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('party', '0002_remove_portfolio_is_deleted'),
]
operations = [
migrations.AlterField(
model_name='party',
... |
from random import randint
import zero_division
def randomly_stringify_list_items(num_list):
amount_to_str = randint(0,len(num_list))
# print(f'amount = {amount_to_str}')
for i in range(0,amount_to_str):
# print(f'i = {i}')
to_be_stred = randint(0,len(num_list)-1)
# print(f'to_be_st... |
"""
uniquePath1
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
How many possible unique paths ar... |
from .cookie import Cookie
from .exceptions import Disconnect
from .request import Request
from .response import Response
from .socket import Socket
from .wrappers import asgi_to_jackie, jackie_to_asgi
__all__ = [
'asgi_to_jackie',
'Cookie',
'Disconnect',
'jackie_to_asgi',
'Request',
'Response... |
# -------------------------------------------------------------------#
# Contact: mrinalhaloi11@gmail.com
# Copyright 2017, Mrinal Haloi
# -------------------------------------------------------------------#
from __future__ import division, print_function, absolute_import
import numpy as np
import pickle
import tensor... |
from mixers import BaseMixer, AckermannSteeringMixer, DifferentialSteeringMixer
|
"""Calculator script that pretty much solves general AI.
Trains machine learning models for operations every time you enter an expression.
Accuracy may vary but is pretty much guaranteed to be bad for multiplication and division."""
import random
import sys
from sklearn import linear_model
from sklearn.preprocessing... |
class Node:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def countnodes(self, A):
if not A:
return 0
# count = 1
# count += self.countnodes(A.left)
# count += self.countnodes(A.right)
# return count
# A More Compact Implementation
return 1 + self... |
from random import randint, choice
from operator import add, mul, sub
from uuid import uuid4
from tkinter import *
from tkinter import ttk
from Classes.Mongo import Mongo
class MathsQuiz(object):
def __init__(self):
self.root = Tk()
self.studentName = 0
self.studentInput = IntVar()
... |
# ---------------------------------------------------------------------
# Huawei.VRP.get_switchport
# ---------------------------------------------------------------------
# Copyright (C) 2007-2020 The NOC Project
# See LICENSE for details
# ---------------------------------------------------------------------
# Pytho... |
import numpy as np
import scipy as sp
import pylab as p
xa=.2
xb=1.99
C=np.linspace(xa,xb,100)
print( C)
i=1000
Y = np.ones(len(C))
# for x in range(iter):
# Y = Y*C*(1-Y)#Y**2 - C #get rid of early transients
fig, ax = p.subplots(figsize=(8,6))
for x in range(i):
Y = Y**2 - C
ax.plot(C,Y, '.', co... |
import rltk.utils as utils
def string_equal(str1, str2):
"""
Args:
n1 (str): String 1.
n2 (str): String 2.
Returns:
int: 0 for unequal and 1 for equal.
"""
utils.check_for_none(str1, str2)
utils.check_for_type(str, str1, str2)
return int(str1 == str2)
def number... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
from os import path
import cvmfs
readme_path = path.join(path.dirname(__file__), 'README')
setup(
name=cvmfs.__package_name__,
version=cvmfs.__version__,
url='http://cernvm.cern.ch',
author='Rene Meusel',
aut... |
import discord
import colorsys
import random
def error(text):
return "\N{NO ENTRY SIGN} {}".format(text)
def warning(text):
return "\N{WARNING SIGN} {}".format(text)
def info(text):
return "\N{INFORMATION SOURCE} {}".format(text)
def question(text):
return "\N{BLACK QUESTION MARK ORNAM... |
import setup_util
import subprocess
def start(args, logfile, errfile):
setup_util.replace_text("play-java/conf/application.conf", "jdbc:mysql:\/\/.*:3306", "jdbc:mysql://" + args.database_host + ":3306")
subprocess.Popen(["play","start"], stdin=subprocess.PIPE, cwd="play-java", stderr=errfile, stdout=logfile)
re... |
from django.shortcuts import render,get_object_or_404,redirect
from .models import GonderiModel
from .forms import GonderiForm
from django.contrib.auth.models import User
from django.utils import timezone
def gonderListe(request):
gonderiler = GonderiModel.objects.all()
return render(request,"blog/gonderilist.... |
import os
import numpy as np
from opencv_sudoku_solver.pyimagesearch.sudoku import \
find_puzzle, extract_digit, multi_img_view
from matplotlib import pyplot as plt
import cv2
import typing
class BoardImgArr:
def __init__(self, img_path: str,
roi_shape: typing.Tuple[int, int],
... |
import time
from servo_device import ServoDevice
# create the servo Device
SERVO_PIN = 17
servo = ServoDevice(SERVO_PIN)
angles = [0, 45, 90, 135, 180, 135, 90, 45]
print('Looping with Servo angles (Ctrl-C to quit)...')
try:
while True:
servo.set_angle(0)
time.sleep(3)
servo.set_angle(45)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.