text stringlengths 38 1.54M |
|---|
import logging
from loguru import logger
class InterceptHandler(logging.Handler):
LEVELS_MAP = {
logging.CRITICAL: "CRITICAL",
logging.ERROR: "ERROR",
logging.WARNING: "WARNING",
logging.INFO: "INFO",
logging.DEBUG: "DEBUG",
}
def _get_level(self, record):
... |
import tensorflow as tf
if tf.__version__.split(".")[0] == "2":
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
import tensorflow.keras as K
else:
import tensorflow.contrib.keras as K
import numpy as np
import joblib
import layers
from tensorflow.python.keras.layers import Dense
def build... |
import sys
import pdb
#pdb.set_trace()
with open(sys.argv[1]) as f:
for line in f:
items = line.split()
sys.stdout.write('chr%s\t%s\t%s\t%s\n' % (items[1],items[3],items[3],items[9])) |
# Generated by Django 3.0.3 on 2020-03-10 17:35
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('webapp', '0003_auto_20200310_1657'),
]
operations = [
migrations.AlterField(
model_name='comment',
name='active',
... |
import pandas as pd
listaVariada=['a',1,2,4.6]
print (listaVariada)
seriesPandas = pd.Series ([1,2,5])
print(seriesPandas)
seriesPandas = pd.Series ([4.6,5.7,0.1])
print(seriesPandas)
dicGanancia ={}
dicGanancia['Enero'] = 4300
dicGanancia['Febrero'] = 4545
dicGanancia['Marzo'] = 2324
dicGanancia['Abril'] = 1244
series... |
"""Matchers for testing collections have specific items."""
from h_matchers.matcher.core import Matcher
class AnyIterableWithItemsInOrder(Matcher):
"""Matches any item which contains certain elements in order."""
def __init__(self, items_to_match):
super().__init__(
f"* contains {items_t... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Created on 2018-06-04 11:34:28
# Project: mafengwo
a="http://222.asdsad.com/asda/asdasd"
b=a.replace("://","")
inx=b.find("/")
print(a[:inx+4]) |
#-*- coding:utf-8 -*-
__author__ = 'chengmin'
try:
import psyco
psyco.full()
except ImportError:
pass # psyco not installed so continue as usual
import os
import chardet
import time
from zhtools.langconv import *
import Sentiment
import os
from zhtools.langconv import *
import jieba
#import codecs
#import s... |
'''
Created on 2012-4-21
@author: Sky
'''
from SimpleMUD.EntityDatabase import EntityDatabase
from BasicLib.BasicLibString import ParseWord
from SimpleMUD.Store import Store
from BasicLib.BasicLibLogger import USERLOG
class StoreDatabase(EntityDatabase):
def Load(self):
sr = EntityDatabase.Sr
... |
#
# Example file for working with Calendars
#
# import the calendar module
import calendar
# create a plain text calendar
c = calendar.TextCalendar(calendar.MONDAY)
string = c.formatmonth(1992, 2, 0, 0)
print(string)
# create an HTML formatted calendar
hc = calendar.HTMLCalendar(calendar.SUNDAY)
string = hc.formatm... |
# false.py
# A program to output whether a statement is true or false
# Author: Andy Walker
# these lines get the input
firstNumber = int(input("Please enter the first number: "))
print ("The first number is {}".format(firstNumber))
secondNumber = int(input("Please enter the second number: "))
print ("The second numbe... |
__title__ = "Optimum polynomial"
def solve():
from common import log
param = [1, -1, 1, -1, 1, -1, 1, -1, 1, -1, 1]
#param = [0, 0, 0, 1]
def u(n):
l = len(param)
s = 0
nn = 1
i = 0
while i < l:
s = s + nn*param[i]
i = i + 1
nn = nn*n
return s
def get_next_seq(seq):
r... |
# -*- coding: utf-8 -*-
"""
Natsort can sort strings with numbers in a natural order.
It provides the natsorted function to sort strings with
arbitrary numbers.
You can mix types with natsorted. This can get around the new
'unorderable types' issue with Python 3. Natsort will recursively
descend into lists of lists s... |
total_cost = int(input("Total cost:"))
received = int(input("Money received:"))
print("You will get {} doller back".format(received - total_cost))
|
import unittest
from poker.card import Card
from poker.validators import StraightFlushValidator
class TestStraightFlushValidator(unittest.TestCase):
def test_straigh_flush_is_not_valid(self):
'''
straight flush occurs when
all rank are sequential and
suite is same
'''
... |
# Decision Tree Regression
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeRegressor, plot_tree
from sklearn.metrics import r2_score
# Importing the dataset
df = pd.read_csv('htt... |
'''
(c) 2010 Thomas Holder
PyMOL python script (load with `run supercell.py`)
Usage: See "help supercell" and "help symexpcell"
'''
from pymol import cmd, cgo, xray
from math import cos, sin, radians, sqrt
import numpy
def cellbasis(angles, edges):
'''
For the unit cell with given angles and edge lengths calculate... |
import smtplib, ssl, sys
smtp_server = "smtp.gmail.com"
port = 587 # For SSL
sender_email = "wifiologyproject@gmail.com"
password = "Wifi1234-"
receiver_email = "wifiologyproject@gmail.com"
message = """\
Subject: Hi there
This message is sent from Python."""
# Create a secure SSL context
context = ssl.create_defa... |
import random
import functools
import os
import termcolor
class FileAdapter():
def __init__(self, file_name):
self.file_name = file_name
@functools.lru_cache(maxsize=1)
def readlines(self):
lines = list()
with open(self.file_name, "r") as f:
lines = self._save_readlines(f)
return lines
... |
import time
def timeofday():
"""Prints current time of day in 24 hour format,
along with days since 1st Jan 1970.
"""
t = time.time() #time in seconds since 1st Jan 1970
seconds = str(int(t%60))
minutes = str(int((t//60)%60))
hours = str(int((t//3600)%24))
days = str(int(t//(3600*24)))
... |
# -*- coding:utf-8 -*-
class Solution:
def VerifySquenceOfBST(self, sequence):
# write code here
# if sequence == []:
# return False # 这里应该为True 因为空树也能是二叉搜索树
#
# rootNum = sequence[-1]
# del sequence[-1] # 这里将根节点删除
#
# index = None
... |
#!/usr/bin/env python3
"""
Rotate Matrix: Given an image represented by an NxN matrix, where each pixel in
the image is 4 bytes, write a method to rotate the image by 90 degrees. Can you
do this in place?
"""
# Check if the provided matrix is 4Nx4N.
def is_4n_x_4n(matrix):
n = len(matrix)
if n == 0 or n % 4 !... |
import turtle
import random
turtle.mode("logo")
a = random.randint(3,18)
turtle.pensize(a)
turtle.pencolor("orange")
turtle.right(90)
turtle.forward(100)
turtle.right(120)
turtle.forward(100)
turtle.right(120)
turtle.forward(100)
turtle.right(120)
turtle.pu()
turtle.goto(0,-58)
turtle.pd()
turtle.pencolor("blue")
t... |
# rsync-system-backup: Linux system backups powered by rsync.
#
# Author: Peter Odding <peter@peterodding.com>
# Last Change: May 4, 2018
# URL: https://github.com/xolox/python-rsync-system-backup
"""Parsing of rsync destination syntax (and then some)."""
# Standard library modules.
import logging
import os
import re... |
from management import management_pb2
from operator import itemgetter
class GraphElementAdder:
SINGLE = False
ALL = False
name = None
ELEMENT = None
element_to_update = None
supported_parameters = ["properties", "readOnly", "partitioned", "direction", "multiplicity", "directed"]
def __i... |
"""
Test running
"""
from django.core.cache import cache
from django.test import SimpleTestCase
from cache_results import cache_results
class CacheResultsTest(SimpleTestCase):
def test_decorator(self):
nonlocal_dict = {}
def get_cache_key(arg1):
return 'foo.{}'.format(arg1)
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from recap import recap
def run():
recap.main(sys.argv[1:])
if __name__ == '__main__':
run()
|
#Console Clearing method
def clear_console():
"""This is used to clear console, specifically designed for PyCharm IDE users"""
import pyautogui
#print(pyautogui.position())
pyautogui.moveTo(520,580)
pyautogui.click()
pyautogui.hotkey('alt','l')
clear_console()
|
import logging
import zipfile
import click
from lxml import etree
@click.group()
@click.argument('genofile', type=click.File('r+b'))
@click.pass_context
def cli(ctx, genofile):
logging.basicConfig()
if genofile.seekable and zipfile.is_zipfile(genofile):
with zipfile.ZipFile(genofile, 'r') as zf:
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 22 05:52:20 2021
@author: profjahier
"""
import tkinter as tk
import tkinter.messagebox as msgb # boîte de dialogue
def verification():
if mot_de_passe.get() == 'python':
# le mot de passe est bon :
# on affiche une boîte de dia... |
'''程序入口,进行数据库的读取和存储,读取出来的数据提交给judger模块'''
import time
import config
import judger
import pymysql
from support import NoMatchError, LoginError, SubmitError
def main():
while True:
# 打开数据库
db = pymysql.connect(host = config.dbhost, port = config.dbport, user = config.dbuser, passwd = config.dbpassword, db = config... |
import sqlite3, os, threading, json, time, sys
import barcodenumber
from datetime import datetime
from domino.core import log
from domino.postgres import Postgres
from discount.actions import Action
from discount.series import Series
from discount.core import DISCOUNT_DB, SCHEMES_FOLDER, Engine
#from discount.a... |
"""
16. 最接近的三数之和
给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。
返回这三个数的和。假定每组输入只存在唯一答案。
例如,给定数组 nums = [-1,2,1,-4], 和 target = 1.
与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2).
"""
class Solution:
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type ... |
from pwn import *
def cmd(c):
p.sendlineafter("choice : ",str(c))
def add(name="XXXX",l=0x80,c="AAAA"):
cmd(1)
p.sendlineafter("name :",str(l))
p.sendafter("flower :",name)
p.sendlineafter("flower :",c)
def show():
cmd(2)
def free(idx):
cmd(3)
p.sendlineafter("garden:",str(idx))
def clear():
cmd(4)
#p=process(... |
import random
import matplotlib.pyplot as plot
from abc import ABC
from abc import abstractmethod
from math import sqrt
from math import log10
from typing import List
from random import random
from itertools import repeat
from bisect import bisect_right
from scipy.special import erfinv
class RandomGenerator(ABC):
... |
from typing import List
from collections import defaultdict, deque
class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
adj_list = defaultdict(list)
rotten_queue = deque() # (i, j, day)
fresh_set = set()
for i in range(len(grid)):
for j in range(len(... |
# -*- coding: utf-8 -*-
"""
Unit Tests for low level training data ingestion.
Usage:
python -m unittest tests/test_ingest.py
"""
import sys
import unittest
import pandas as pd
sys.path.append('src')
sys.path.append("src/Mask_RCNN")
from config import GlobalConfig
import ingest
class IngestTest(unittest.TestCa... |
"""
1st approach
- sort the array
- create an array of meeting rooms
- each interval, compare the last meeting(since sorted) amongst the meeting in the meeting rooms
- if there is no collision, put the meeting in that room, else create a new meeting room for the interval
Time O(nlogn) sort... |
import numpy as np
import pandas as pd
from collections import Counter
import random
import time
from scipy.io import arff
df = pd.read_csv('data.csv')
df=df.drop(columns=['id'])
start=time.time()
def k_nearest_neighbours(data,predict,k):
distances=[]
for group in data:
for features in data[group]:... |
from odoo import models, fields, api, _
class AccountTax(models.Model):
_inherit = 'account.tax'
# NEW FIELDS
ewt_structure_id = fields.Many2one('account.ewt.structure', string='EWT Structure')
# EXTEND
amount_type = fields.Selection(selection=[('group', 'Group of Taxes'), ('fixed', 'Fixed'), ('percent', 'Perce... |
# coding: utf-8
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'Pinbot.settings'
from resumes.models import (
ContactInfoData,
ResumeData,
)
from feed.models import (
FeedResult,
)
from pin_utils.django_utils import (
get_oid,
)
def main():
resume_sid_list = list(ContactInfoData.objects.filte... |
alien_color="green"
if alien_color=="green":
print("You get 5 points!")
alien_color="red"
if alien_color=="grenn":
print("You get 5 points!")
alien_color="grenn"
if alien_color=="green":
print("You get 5 points!")
else:
print("You get 10 points!")
alien_color = "grenn"
if alien_color !... |
"""
Tests of this module depends on external connectivity and availability of
openstreetmap services.
"""
from conftest import REDIS_HOST, REDIS_PORT
from geocoding import geocoding
import copy
import geojson
import pytest
from exceptions.exceptions import InvalidNGSIEntity
def assert_lon_lat(entity, expected_lon, ex... |
from mk_livestatus import Socket
import json,subprocess,re,time,collections,sys,pymongo,os,datetime
from pymongo import MongoClient
mongoserver = "app161vm4.glam.colo"
mongoport = 27017
mydb = "inventory"
mycollections = {'ansible':"ansible",'check_mk':"cmk",'inventory':"inventory"}
cmkdict = collections.defaultdict... |
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('<int:receita_id>', views.receita, name='receita'),
path('buscar', views.buscar, name='buscar'),
path('cria/receita', views.cria_receita, name='cria_receita'),
path('deleta/<int:receita_id>',... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import atexit
import time
import json
import getopt
import sys
from client import Client
def check_game_status(game_state):
if game_state['finished']:
print(game_state['reason'])
exit(0)
def my_algo(game_state):
"""This function contains your algor... |
def isEven(number):
#generate list of even numbers
evenNumbers=[]
for i in range((number)):
evenNumbers.append(i*2)
if number in evenNumbers:
return True
else:
return False
print(isEven(100)) |
import statistics
data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5]
statistics.mean(data) # 平均
# 1.6071428571428572
statistics.median(data) # 中央値
# 1.25
statistics.variance(data) # 分散
# 1.3720238095238095
|
import pyglet
from . import Player, Enemy, Bullet
pyglet.resource.path = ['./Assets']
pyglet.resource.reindex()
def centerImage(image):
"""Sets and image's anchor point to its center"""
image.anchor_x = image.width // 2
image.anchor_y = image.height // 2
def createBackground():
"""Creates the sprite... |
from django.contrib import admin
from .models import langkah, gambar_langkah
# Register your models here.
admin.site.register(langkah)
admin.site.register(gambar_langkah) |
import pytest
import os
import sys
import pickle
# If there is __init__.py in the directory where this file is, then Python adds das_decennial directory to sys.path
# automatically. Not sure why and how it works, therefore, keeping the following line as a double
sys.path.append(os.path.dirname(os.path.dirname(os.path.... |
from matplotlib import pyplot as plt
import pandas as pd
plt.style.use("fivethirtyeight")
#df['py_dev_y']
ages_x = [25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35]
dev_y = [38496, 42000, 46752, 49320, 53200,
56000, 62316, 64928, 67317, 68748, 73752]
fig, (ax, ax1) = plt.subplots(nrows = 2, ncols = 1, sharex = ... |
#using the led on the sense hat to display a user inputed message using left and right
import sense_hat, time, random
sense = sense_hat.SenseHat()
up_key = sense_hat.DIRECTION_UP
left_key = sense_hat.DIRECTION_DOWN
pressed = sense_hat.ACTION_PRESSED
message_right = input("Enter message for right joystick push:")
mess... |
# Copyright 2020 Xilinx 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 agreed to in writing, ... |
from django.conf.urls import url
from .views import checkout, checkout_buy_app, thank_you
urlpatterns = [
url(r'^$', checkout, name = 'checkout'),
url(r'^buy-app$', checkout_buy_app, name = 'checkout-app'),
url(r'^thank-you$', thank_you, name = 'thank-you'),
]
|
'''Auto-creates the database'''
from cfg import CONNECTION_STRING
from db import setup_db, populate
setup_db(CONNECTION_STRING)
populate(CONNECTION_STRING)
|
def bin_search(arr, target, kind="<="):
assert kind in ["<=", ">="]
if kind == "<=":
comp = lambda a, b: a <= b
else:
comp = lambda a, b: a < b
l = 0
r = len(a) - 1
while l < r - 1:
m = (l + r) // 2
if comp(a[m], target):
l = m
else:... |
import os
def check_dependencies():
pass
def make_directories():
try:
os.mkdir("output")
except:
print ("Unable to make directory 'output', it may already exist.")
try:
os.mkdir("temp")
except:
print ("Unable to make directory 'temp', it may already... |
#!/usr/bin/python3
import sys
import paramiko
import time
#print(sys.argv)
if len(sys.argv) != 4:
print("sudo apt install python3-pip")
print("pip3 install paramiko")
print("Usage: %s host port user" %sys.argv[0])
print(" %s 1.1.1.1 22 admin" %sys.argv[0])
exit()
host = sys.argv[1]
port = s... |
def binary_search(array, infi, supr, x):
if supr >= infi:
middle = (supr + infi) // 2
if array[middle] == x:
return middle
elif array[middle] > x:
return binary_search(array, infi, middle - 1, x)
else:
return binary_search(array, middle +... |
from typing import List
from BaseClasses.Proposition import Proposition
from PredicateLogic.Existent import Existent
from PredicateLogic.Quantifier import Quantifier
class PredicatedProposition(Proposition):
"""description of class"""
subProposition = None
existents = List[Existent]
quant : Qu... |
# -*- coding: utf-8 -*-
# django imports
from django.contrib.auth.models import User
from django import forms
from django.utils.translation import ugettext_lazy as _
# rewriters imports
from registration.backends.simple import SimpleBackend
from registration import signals
from registration.forms import RegistrationFo... |
from .type import POSSIBLE_TYPES
import itertools
import ast
import astor
class Profiler(ast.NodeTransformer):
def __init__(self):
super()
self.branches = dict()
self.branch_id = 1
self.current_lineno = None
self.line_and_vars = dict()
def visit_predicate(self, expr_no... |
from flask import Flask, render_template, redirect, request, session
app = Flask(__name__)
app.secret_key = "Keep it secret, keep it safe"
@app.route("/")
def index():
return render_template("index.html")
@app.route("/process_survey", methods=['POST'])
def process():
session['first_name'] = request.form['f... |
from django.shortcuts import render, redirect
from .models import Task
from .forms import TaskForm
def index(request):
count = Task.objects.all().count()
return render(request, "main/index.html", {'title': 'Главная страница сайта', 'count': count})
def task(request):
tasks = Task.objects.order_... |
#!/bin/env python
# Cap.6, p.144
alien_0 = {'x_position': 0, 'y_position': 25, 'speed': 'medium'}
# Mover alienigena de acordo com a velocidade.
if alien_0['speed'] == 'slow':
x_increment = 1
elif alien_0['speed'] == 'medium':
x_increment = 2
else:
x_increment = 3
# A nova posicao é a posicao antiga so... |
# Generated by Django 3.0.8 on 2020-10-12 08:22
from django.db import migrations, models
def apply_migration(apps, schema_editor):
Group = apps.get_model('auth', 'Group')
Group.objects.bulk_create([
Group(name='general_user'),
Group(name='admin'),
])
def revert_migration(apps, schema_ed... |
import os
os.environ['KMP_DUPLICATE_LIB_OK']='True'
import torch
import torch.nn as nn
from mnist import *
import glob
import cv2
import torch.nn.functional as F
from torch.autograd import Variable
from torchvision import datasets, transforms
import numpy as np
import torchvision
from skimage import io,tran... |
import json
import io
def util_load_json(path):
with io.open(path, mode="r", encoding="utf-8") as f:
return json.loads(f.read())
def util_load_raw(path):
with io.open(path, mode="r", encoding="utf-8") as f:
return f.read()
def test_parse_links():
from ZTAPParseLinks import parse_links
... |
#!/usr/bin/env python3
from argparse import ArgumentParser, Namespace
from typing import List
from shop_randomiser import generate_spoiler_log, load_rom_data, write_spoiler_log
import os
ff5_bytes: List[int] = []
def parse_arguments() -> str:
parser: ArgumentParser = ArgumentParser()
parser.add_argum... |
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Owner'
db.create_table(u'projects_owner', (
(... |
import pickle
import numpy as np
import pandas as pd
from sklearn import datasets
from sklearn.model_selection import cross_val_score
from sklearn.neighbors import KNeighborsClassifier
iris = datasets.load_iris()
# Load iris dataset
iris_df = pd.DataFrame(iris.data, columns=iris.feature_names)
# Convert iris to panda... |
from typing import Callable, Optional, Sequence, Union
import torch
from ignite.metrics import Metric, Precision, Recall
from ignite.metrics.metric import reinit__is_reduced
__all__ = ["FbetaScore"]
class FbetaScore(Metric):
def __init__(
self,
beta: int = 1,
output_transform: Callable =... |
from spellcheck.spellchecker import SpellingCorrection
import re
class DigitizationParser:
def __init__(self, end_of_essay='# # # # # # #'):
self.end_of_essay = end_of_essay
def _split(self, seq, sep):
chunk = []
for el in seq:
if el == sep:
yield chunk
... |
class Solution:
def removeKdigits(self, num, k):
"""
:type num: str
:type k: int
:rtype: str
"""
if k == len(num):
return '0'
n, i = len(num), 0
stack = []
while i < n:
while k > 0 and stack and stack[-1] > num[i]:
... |
#función que reciba 2 enteros y verifique si el 1ero es divisible en el segundo
def divisible(a, b):
if a % b == 0:
return True
else:
return False
def primo(c):
if c != 2:
for i in range(2, c):
if c % i == 0:
return "False"
else:
... |
from django.db import models
from django.core.urlresolvers import reverse
# Create your models here.
class Doctor(models.Model):
name = models.CharField(max_length=200)
age = models.CharField(max_length=200)
gender = models.CharField(max_length=200)
degree =models.CharField(max_length=200)
descript... |
WHITE, WHITE_STR = 1, "\u25cb"
BLACK, BLACK_STR = -1, "\u25cf"
EMPTY, EMPTY_STR = 0, " "
class Game:
"""
Every state of the game will be an instant of the class.
It contains every relevant information of the game.
"""
def __init__(self):
self.current_player = BLACK
self.board = [[... |
# Copyright 2013 Openstack Foundation
# 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 requ... |
from __future__ import absolute_import, unicode_literals, print_function
import mock
from unittest import TestCase
from libraries.lambda_handlers.list_endpoints_handler import ListEndpointsHandler
class TestListEndpointsHandler(TestCase):
@mock.patch('libraries.manager.manager.TxManager.setup_resources')
@mo... |
import pandas
import numpy as np
from sklearn.ensemble import RandomForestRegressor
#read data
data=pandas.read_csv("/home/alex/Desktop/telelis/data/meteo.txt", header=None)
#prepare training test
X_train=data.iloc[:3266,[2,3,4,5,6]]
y_train=data.iloc[:3266,0]
#prepare test set
X_test=data.iloc[-20:,[2,3,4,5,6]]
y_t... |
import urllib3
import requests
import json
import pymongo #importing pymongo library
#Creating mongodb connection
myclient = pymongo.MongoClient("mongodb://127.0.0.1:27017")
#Creating database and collection object
mydb = myclient["posts"]
mycol = mydb["posts_collection"]
#facebook url GET request
url_request_faceb... |
import os
def new_entry(item, value):
with open("./Max/files/list.csv", "a") as f:
f.write(item + ";" + value + "\n")
def delete_entry(i):
result = []
with open("./Max/files/list.csv", "r") as file:
# Text in Lines speichern
lines = file.readlines()
for v in lines:
... |
"""
A module with utility functions for vector calculus.
All inputs and outputs are expected to be in a numpy array
shaped (n, 3) where n is some positive number.
"""
import numpy as np
def cross_product(x, y):
N = np.stack(
[
x[:, 1] * y[:, 2] - x[:, 2] * y[:, 1],
x[:, 2] * y[:,... |
import os
from glob import glob
import cv2
import numpy as np
img_paths = glob(os.path.expanduser('~/Downloads/imgs/*.JPG'))
for i, ip in enumerate(img_paths):
rst_img = None
img = cv2.imread(ip)
img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
img = cv2.resize(img, dsize=(480, 340))
for l, h in [(0,... |
import random
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix="$", activity=discord.Activity(name="Teammake | $help", type=1))
class Teammake(commands.Cog):
def __init__(self, bot):
self.bot = bot
async def on_ready(self):
print('Logged on as {0}!'.fo... |
import numpy as np
import gensim
import tensorflow as tf
from os import listdir
import fasttext as ft
POS_tag = ['ADJ', 'ADP', 'ADV', 'AUX', 'CCONJ', 'DET', 'INTJ', 'NOUN', 'NUM', 'PART', 'PRON', 'PROPN', 'PUNCT', 'SCONJ', 'SYM', 'VERB', 'X']
X_POS_tag = ['H', 'RV', 'N', 'Eb', 'Mb', 'Np', 'm', 'v', 'Nu', 'Nc', 'V', ... |
"""
Create a dictionary with key value pairs to
represent words (key) and its definition (value)
"""
word_definitions = dict()
word_definitions['agitate'] = 'make (someone) troubled or nervous'
word_definitions['onomatopoeia'] = 'the formation of a word from a sound associated with what is named'
"""
Add several more ... |
from flask_sqlalchemy import SQLAlchemy
from flask import current_app
db = SQLAlchemy()
class DatabaseTables(db.Model):
__tablename__ = 'flask_app'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), nullable=False)
def __init__(self, id, name):
self.id = id
... |
from flask import Flask
from respberryController import RespberryController
app=Flask(__name__)
@app.route("/")
def hello_world():
return "hello world"
@app.route("/turn/<string:fx>")
def index(fx):
controller.control(fx)
return "turn " + fx
if __name__ == '__main__':
controller = RespberryControl... |
# This is a sample Python script.
# Press Umschalt+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
import numpy as np
import pandas as pd
import datetime
import matplotlib as plt
from matplotlib import pyplot as mpl
cum... |
from GompeiFunctions import load_json, save_json
from Permissions import administrator_perms
from discord.ext import commands
import Config
import pytimeparse
import os
class Automod(commands.Cog):
"""
Automatic moderation handler
"""
def __init__(self, bot):
self.bot = bot
@commands.gr... |
import cv2
import numpy as np
INPUT_PATH = 'input/'
OUTPUT_PATH = 'output/'
POINT_MAPS_PATH = 'point_maps/'
FRAMES_PATH = 'frames/'
BLUE = (255, 0, 0)
GREEN = (0, 255, 0)
RED = (0, 0, 255)
def drawInliersOutliers(image, point_map, inliers):
"""
inliers: set of (x1, y1) points
"""
rows, cols = image.s... |
from weibopy import WeiboOauth2,WeiboClient
import webbrowser
import json
import re
import time
from collections import defaultdict
from snownlp import SnowNLP
import pandas as pd
import echarts_countries_pypkg,echarts_china_provinces_pypkg
from pyecharts import Map
client_key='3536121960'
client_secret='29a7cb9342f584... |
from collections import deque
import random
class ReplayBuffer(object):
def __init__(self, buffer_size):
self.buffer_size = buffer_size
self.num_experiences = 0
self.buffer = deque()
def getBatch(self, batch_size):
if self.num_experiences < batch_size:
return random.sample(self.buffer, self.num_experien... |
# check tooCloseToCarInFront
def isTooCloseToCarInFront(carLineArray, c):
for row in carLineArray:
if row[0] == c.line:
if 50 > (c.x - row[1].x) > 0:
return True
return False
# check collision 4line
def isCarCollided(carLineArray, c):
for row in carLineArray:
if ro... |
line_break = "-----------------------------------------------------------------------------------"
students = {
'cohort1': 34,
'cohort2': 42,
'cohort3': 22
}
# function- display name and number or each student
def display_name_and_num(dict_name):
for student, number in dict_name.items():
print(f'... |
#Sum and Product
def calculate_sum(number:int):
return int((int(number)*(int(number) + 1)/ 2))
def calculate_product(number:int):
summa = 1
for x in range(1,number+1):
summa *= x
return summa
def menu():
print("1: Compute the sum of 1..n")
print("2: Compute the product of 1..n")
p... |
class csr_matrix(arg1, shape=None, dtype=None, copy=False): # scipy.sparse.csr_matrix
'''
Compressed Sparse Row matrix
'''
|
"""
Problem pet filozofa
Problem pet filozofa. Filozofi obavljaju samo dvije različite aktivnosti: misle ili jedu.
To rade na poseban način. Na jednom okruglom stolu nalazi se pet tanjura te pet
štapića (između svaka dva tanjura po jedan). Filozof prilazi stolu, uzima lijevi štapić,
pa desni te jede. Zatim vraća štapić... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.