Python is a widely used general-purpose, high-level programming language. Its design philosophy emphasizes code readability, and its syntax allows programmers to express concepts in fewer lines of code than would be possible in other languages. Python supports multiple programming paradigms, including object-oriented, imperative and functional programming or procedural styles. It features a dynamic type system and automatic memory management and has a large and comprehensive set of standard libraries, including NumPy, SciPy, Django, PyQuery, and PyLibrary.

Share tech news, updates, or what's on your mind.

Sign up to Post

I needed help with few things in relation with the code in the above link.

I wanted to delete all unwanted records. Like what we are printing now are the missing values from the subsequent years which I wanted to delete and come up with a new csv file with records for all years which are in start year.

like for this data

X              year
13750      2015
15143      2018
15161      2015
15161      2016
15024      2018
19358      2017
9817        2016
9817        2017
9817        2018
1908        2015
1908        2016
1908        2017
1908        2018

should give this output

1908       2015
1908       2016
1908       2017
1908       2018

as only 1908 is in 2015 which has X for all other years.
Rowby Goren Makes an Impact on Screen and Online
LVL 19
Rowby Goren Makes an Impact on Screen and Online

Learn about longtime user Rowby Goren and his great contributions to the site. We explore his method for posing questions that are likely to yield a solution, and take a look at how his career transformed from a Hollywood writer to a website entrepreneur.

I have been learning core. based on the tutorials, what it means that application will be hosted/served by kesterl server.

I have come across same idea reading about python, ruby on rails or  vue js, that the framework will spin up a web server. what does that mean? what actually happens in the background.

I apologize if the question is little vague, but I want to know what does the framework exactly do  in above situations compared to hosting an application in IIS?
Any idea how to display the pyplot graph in php code ? Any example or reference on this ?

I want to create a bar chart and export it to a PDF file using the pandas code below. This produces a blank image. Is there some way to associate plt with the data frame (df)?


import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("fileName.csv")
fig = plt.figure()
trying to parse nested html via regex in python and convert it to csv file
Ran the command npm start to boot up my Magic Mirror with the MMM-Facial-Recognition module and I am given this error.  I am not sure how to fix it.The error I am given
Any idea how the follow result is calculated :

Testlabels3           = ['Red', 'Green', 'Green', 'Red', 'Yellow']
PredictedLabels3 = ['Red', 'Red', 'Green', 'Yellow', 'Yellow']

precision_score(TestLabels3, PredictedLabels3, average=None)
result : array([1. , 0.5, 0.5])

precision_score(TestLabels3, PredictedLabels3, average='weighted')
result : 0.7
Good Afternoon all for some reason i am getting a error mysql.connector.errors.ProgrammingError: Not all parameters were used in the SQL statement, i have checked all the %s and they all show as 7 as well as all the items in the sql, i am sure is not much but if someone could take a look that would be great

    from requests_html import HTMLSession
import mysql.connector

mydb = mysql.connector.connect(

mycursor = mydb.cursor()

# create an HTML Session object
session = HTMLSession()

# Use the object above to connect to needed webpage
resp = session.get("")

# Run JavaScript code on webpage

airline_spans = resp.html.find('.SearchResultFlightListRow')
print (airline_spans)
airline_list = [span.text.split('\n') for span in airline_spans]

for flight in airline_list:
    if len(flight) == 7:
        flightno, From, to, scheduled, estimated, gate, status = flight
        print ("This is a " + estimated)
        if estimated == "":
            print (" currently no dely ")
            print ("This is a " + estimated)
            estimated = 'IDEL'
        print (f'Flight no {flightno} from  {From} to {to} is scheduled to depart at {scheduled} from gate {gate} and flight status is {status}')

    elif len(flight) == 6:
Hi all , so i have scrapped a website and got the data, ( i tihnk :)) i want to know how i can split it all apart and save each item of text in their own element list, , at the end of it i want to save the data to a mysql database , here is my code, please let me know if you feel anything else can be changed

from requests_html import HTMLSession

# create an HTML Session object
session = HTMLSession()

# Use the object above to connect to needed webpage
resp = session.get("")

# Run JavaScript code on webpage

# parse <span class="with-image"> elements containing airline names
airline_list = []
airline_spans = resp.html.find('.SearchResultFlightListRow')
for span in airline_spans:

I now use an app that generates a 'work' file each time its run. The work file is always generated with the same treename.  Now I run a new program that will process a set of the 'work' files... But only if I remember to save&rename each 'work' file before running the app.

So I am interested in a new program that runs continuously on Windows( 7&10) that checks for a new version of the work file (pauses/sleeps for 30 seconds, then checks ) .  If this program finds a new work file, the program copies the file to a particular directory, and removes the work file from the app's directory.

I would have this program start up when Windows is started.  This program would retrieve its parameters (treename of target work file and the save directory) from a 'INI' type file. The name of the INI file would be a command line argument or queried to the user.. All INI files are stored on one base directory This allows me to have 2 or more instances running at the same time.

Are there scripting languages that run on Windows?  If not, my computers do currently have Python running.

Don OHara
OWASP Proactive Controls
LVL 19
OWASP Proactive Controls

Learn the most important control and control categories that every architect and developer should include in their projects.

Hi Experts,
I get when I try to pip install a python library called probfit.  My python is 3.7.

error: Unable to find vcvarsall.bat
Django Migrate error

I have the with Databases section configured as below:

    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'Mydjangoproject',
        'HOST': '',
        'PORT': '',
        'USER': 'root',
        'PASSWORD': '123456',

Open in new window

When  I run the command :  python migrate

I get this output :
(py1) C:\Python-Projects\Mydjangoproject>python migrate
Traceback (most recent call last):
  File "C:\Users\user\Envs\py1\lib\site-packages\django\db\backends\base\", line 217, in ensure_connection
  File "C:\Users\user\Envs\py1\lib\site-packages\django\db\backends\base\", line 195, in connect
    self.connection = self.get_new_connection(conn_params)
  File "C:\Users\user\Envs\py1\lib\site-packages\django\db\backends\mysql\", line 227, in get_new_connection
    return Database.connect(**conn_params)
  File "C:\Users\user\Envs\py1\lib\site-packages\MySQLdb\", line 84, in Connect
    return Connection(*args, **kwargs)
  File "C:\Users\user\Envs\py1\lib\site-packages\MySQLdb\", line 179, in __init__
    super(Connection, self).__init__(*args, **kwargs2)
MySQLdb._exceptions.OperationalError: (1045, "Access denied for user 'root'@'localhost' (using password: YES)")

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "", line 21, in 

Open in new window

Hey Everyone,

 Here is my

class K8Points(models.Model):
    point_id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True, primary_key= True)
    date = models.DateField( 
    teacherclass_id= models.ForeignKey(TeacherClass,on_delete = models.CASCADE, default ="")
    student_id = models.ForeignKey(Student,on_delete = models.CASCADE, default ="")
    week_of = models.IntegerField(default=weeknumber)
    day = models.CharField(max_length= 10, default = dayofweek)
    TIME_FRAME = Choices('8:45AM - 9:00AM','9:00AM - 9:30AM','9:30AM - 10:00AM','REC. I 10:00AM -10:10AM','10:10AM-10:40AM','10:40AM-11:10AM','11:10AM-11:40AM','REC II LUNCH 11:40AM-12:20PM'
    ,'12:20PM-12:50PM','12:20PM-12:50PM', '12:50PM-1:20PM','1:20PM-1:50PM','1:50PM-2:20PM','REC. III 2:20PM-2:30PM')
    time_frame = models.CharField(max_length = 20, choices= TIME_FRAME,default="")
    behavior = models.IntegerField(default="")
    academic = models.IntegerField(default="" )
    subtotal_one= models.Sum(default="", null= True )
    subtotal_two = models.Sum(default="", null = True)
    subtotal_three = models.Sum(default="", null = True)
    daily_total = models.Sum(default="", null = True)

Open in new window

What i want to accomplish is sum the following records if the following time frames are entered from fields behavior and academic.

'8:45AM - 9:00AM','9:00AM - 9:30AM','9:30AM - 10:00AM'

So to make this more clear

Record 1  8:45AM-9:00AM   Behavior : 5   Academic: 4        
Record 2 9:00AM - 9:30AM  Behavior: 8   Academic : 5
Record 3 9:30AM - 10:00AM Behavior 2 Academic :3

Behavior + Academic Times frames are added together and inserted into Subtotal 1. Total would be 27
How do i do that ?
Hey Everyone,

So here is my file

from django.db import models
from django.utils import timezone
from django.forms import ModelForm
import datetime
from datetime import date
from django.utils.translation import gettext_lazy as _
import uuid
from model_utils import Choices


# Create your models here.

class TeacherClass(models.Model):
    teacherclass_id = models.UUIDField(primary_key= True,default=uuid.uuid4, editable=False, unique=True)
    class_name = models.CharField(max_length = 50)

    class Meta:
        verbose_name = "Teacher Class Room"

    def __str__(self):
        return self.class_name  

class Teachers(models.Model):
     teacher_id = models.CharField(primary_key = True , default = "", max_length = 50, unique = True)
     teacher_name = models.CharField(max_length= 50)
     grade = models.CharField(max_length = 2)
     class_name = models.ManyToManyField(TeacherClass)

     class Meta:
        verbose_name = "Teacher"

     def __str__(self):
        return self.teacher_name  

class Student(models.Model):
    student_id= models.CharField(primary_key = True , default = "", max_length = 50, unique = True)
    student_name = models.CharField(max_length = 50)
    student_grade = models.CharField(max_length = 2, default = "")
    counseling_goal = models.CharField(max_length = 255)
    class_name = models.ManyToManyField(TeacherClass)


    def __str__(self):
        return self.student_name             


Open in new window

how to attach document in flask i have this code
def download():
    file = open('name.doc','r')
    returnfile ='latin-1')
    return Response(returnfile,
                 "attachment; filename=name.doc"})

i what to attach the document
this my html i create the download folder
{% extends "layout.html" %}
{% block content %}
<div class="home">
    <h1>My homepage</h1>
    <p>Curriculium Vita</p>
{% endblock %}

Open in new window

How can we use this Keyword TextResultOrderModes in Dynamsoft using python?
Python for o365 login fail ; it must force you click home/business user before password.

I used    selenium chrome driver and want to click this but this click event hidden and class not able click ...any  idea ? thx
my code is like this : tried class_name/ xpath/csss still cannot locate the exact class click event
selenium module click business / home users fail to proceedbutton = driver.find_element_by_class_name('inline-block')
button1 = driver.find_element_by_xpath("//*[@class='table']")
#button1 = driver.find_element_by_class_name('animate slide-in-back')
I am trying to setup an autostart function in AWS Lambda with Python.
I already have an autostop function that work:

But matching autostart function does not turn the instance on.

StartedInstances and StoppedInstanes are arrays of instance ids found by applying a filter for a specific tag.

The result I get when running a Test on the start Lambda is as follows:
START RequestId: 8cd154b2-390e-46d0-9a20-831247c4bc1f Version: $LATEST
[{'StartingInstances': [{'CurrentState': {'Code': 0, 'Name': 'pending'}, 'InstanceId': 'i-eae111caa 'PreviousState': {'Code': 80, 'Name': 'stopped'}}], 'ResponseMetadata': {'RequestId': '8135e59a-ab7d-4329-b7b4-7725ea9c7223', 'HTTPStatusCode': 200, 'HTTPHeaders': {'content-type': 'text/xml;charset=UTF-8', 'content-length': '570', 'date': 'Thu, 07 Nov 2019 22:14:59 GMT', 'server': 'AmazonEC2'}, 'RetryAttempts': 0}}]
END RequestId: 8cd154b2-390e-46d0-9a20-831247c4bc1f
REPORT RequestId: 8cd154b2-390e-46d0-9a20-831247c4bc1f      Duration: 977.91 ms      Billed Duration: 1000 ms      Memory Size: 128 MB      Max Memory Used: 87 MB      Init Duration: 395.54 ms      

Can someone please help me figure why this is not actually starting the server?
Code a method in python 3 to find factors of a number.

    def find_factors(self, n):
        # TODO: Implement this method
        p = 0
        q = 0

        return p, q

Open in new window

Learn Ruby Fundamentals
LVL 19
Learn Ruby Fundamentals

This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

Hey i have the following code for a sudokosolver:

def solve_rule(sudoku):
    for row in range(9):
        for colum in range(9):
            if len(candidates(sudoku,row,colum)) == 1:
                sudoku[row][colum] = candidates(sudoku,row,colum)
    return sudoku

Open in new window

But it gives the following error:

TypeError                                 Traceback (most recent call last)
<ipython-input-23-3ff637fed85f> in <module>
     10     return sudoku
---> 11 solve_rule(load("easy/puzzle1.sudoku"))

<ipython-input-23-3ff637fed85f> in solve_rule(sudoku)
      2     for row in range(9):
      3         for colum in range(9):
----> 4             if len(candidates(sudoku,row,colum)) == 1:
      5                 sudoku[row][colum] = candidates(sudoku,row,colum)

<ipython-input-22-81f854e2844c> in candidates(sudoku, x, y)
     11             numbers_block.append(sudoku[col_finder_x + x_buffer][col_finder_y + y_buffer])
     12     numbers = ["1","2","3","4","5","6","7","8","9"]
---> 13     candidates = set(numbers) - set(numbers_row) - set(numbers_col) - set(numbers_block)
     14     return list(candidates)

TypeError: unhashable type: 'list'

Open in new window

This is the candidates function:

def candidates(sudoku, x, y):
    numbers_row = sudoku[x]
    numbers_col = []
    for row_number in range(9):
    col_finder_x = ((int(x / 3)) * 3)
    col_finder_y = (int(y / 3) * 3)
    numbers_block = []
    for x_buffer in range(3):
        for y_buffer in range(3):
            numbers_block.append(sudoku[col_finder_x + x_buffer][col_finder_y + y_buffer])
    numbers = ["1","2","3","4","5","6","7","8","9"]
    candidates = set(numbers) - set(numbers_row) - set(numbers_col) - set(numbers_block)
    return list(candidates)


Open in new window

Can anyone help me with this?
I've made progress with this scrapy script but cannot get the full lyrics to be within the title and genre grouping of the xml file. I have two classes, one for the main page to grab the title, composer, shortened lyrics, and genre and the other class function (all_lyrics) follows the title link to get the full lyrics.  I've included a XML file and screen shot to show you how the FULL LYRICS is not getting grouped with the correct section but is grouped completely separate.  The full lyrics should be under lyrics.  The function named PARSE runs first and calls out to the all_lyrics function to get the complete lyrics and chords.  The issue is getting all_lyrics to return or yield the results back to the PARSE function so that I can get all the data under the correct xml schema grouping.

-------start of code--------------
import scrapy
import re
from ..items import HopamItem, HopamItem_lyrics

class hopamspider(scrapy.Spider):
    name = 'hopam_or'
    page_number = 10
    start_urls = ['']
    custom_settings = {'DUPEFILTER_CLASS': 'scrapy.dupefilters.BaseDupeFilter'}

    def all_lyrics(self, response):
        global items
        items = HopamItem()
        items['full_lyrics'] = response.xpath("//div[@id='lyric']/text()").extract() #no yield here!!!
        yield items

    def parse(self, response):
        items = HopamItem()
        x = 0
        xy = 0
        all_hopam = response.xpath("//div[@class='col-md-12']")

Open in new window

Python Regular expression for IP4, IP6 and Port Number .  I need to replace IP4,IP6  and Port number with specific format "XXXXX" . Basically I need to do log scrubbing so those information can be hide in the  log file. Please send me regular expression for re.compile, re.findall and re.sub for IP4, IP6 and Port Number.
It could be any other order of IP4,IP6 and Port Number in the log file . It means It could be beginning, middle or end of the line in the log file.
I would appreciate If any one can help me at your earliest convenience time.
Hey i need to make an algorithm which fills in a sudoku block if there is just one possibility left.

This is how that alghoritm needs to look like:

    candidates(x,y) = 1..9 - numbers_row - numbers_col - numbers_block

I need to impliment candidates() like this:

    >>> from sudoku import candidates, load
    >>> candidates(load("easy/puzzle1.sudoku"), 1, 1)
    {2, 3, 4, 5}

So i already made a load function which looks like this:

def load(filename):
    sudoku = []                                       
    with open(filename,"r") as sudoku_raw:     
        for line in sudoku_raw:                         
            line = line.rstrip("\n").replace(" ","")
            row = line.split(',')                   
    return sudoku

Open in new window

The output of this code is:
[['7', '9', '0', '0', '0', '0', '3', '0', '1'],
 ['0', '0', '0', '0', '0', '6', '9', '0', '0'],
 ['8', '0', '0', '0', '3', '0', '0', '7', '6'],
 ['0', '0', '0', '0', '0', '5', '0', '0', '2'],
 ['0', '0', '5', '4', '1', '8', '7', '0', '0'],
 ['4', '0', '0', '7', '0', '0', '0', '0', '0'],
 ['6', '1', '0', '0', '9', '0', '0', '0', '8'],
 ['0', '0', '2', '3', '0', '0', '0', '0', '0'],
 ['0', '0', '9', '0', '0', '0', '0', '5', '4']]

The file that i am using looks like this:


Can anyone help me write this code?
I need to log into Cisco's serial number check periodically to make sure that a given device is covered. (Their API does not have maintenance contract data.) So I am trying to use Selenium and Python to log into my Cisco account and navigate to the upload page. I've pasted in the code, it works . . . .sometimes and throws an error: "TypError: rect is undefine" other times. I cannot figure out why it works, why it fails and it appears to be random.

Here's the code I am using (Windows 10, Python 3.7.1, Selenium 3.141.59):

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from import By
from import WebDriverWait
from import expected_conditions as EC
from import Select
from selenium.webdriver.common.action_chains import ActionChains

driver = webdriver.Firefox(executable_path="C:\\work\\selenium\\geckodriver.exe")

assert "" in driver.title

wait = WebDriverWait(driver,10).until(EC.url_changes(""))
elem = driver.find_element_by_name("pf.username")

def move_to_element(self, locater, *args, **kwargs):
    if (self.browser_type == 'firefox' and self.browser_version >= 60 and 'rect is undefined' in e.msg):

actions = ActionChains(driver)


Open in new window

Hello Experts,

I have had help with the following python script, however I'm getting the error 'No module named 'sql'' see image

Can someone let me know how to import the module?


Python is a widely used general-purpose, high-level programming language. Its design philosophy emphasizes code readability, and its syntax allows programmers to express concepts in fewer lines of code than would be possible in other languages. Python supports multiple programming paradigms, including object-oriented, imperative and functional programming or procedural styles. It features a dynamic type system and automatic memory management and has a large and comprehensive set of standard libraries, including NumPy, SciPy, Django, PyQuery, and PyLibrary.