Python

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

Dear Experts,

Please find the attached simple chart in Excel on the print screen and also as attached file,

Creating chart in Excel
my target would be to do the same but in Python.

Actually having the following code which imports the data from .csv and the matplotlib.pyplot library to have the base for it, but unfortunately having no experience how to continue for having the same Week1, Week2, Week3, Week4 categories on the X axis and showing the values on the same way like in Excel:

import csv
import matplotlib.pyplot as plt

with open(r"C:\Users\ac324485\Downloads\Daily files\Demo.csv") as csvfile:
    rows = list(csv.reader(csvfile))
    data_header = rows[0]
    data_rows = rows[1:]
    
for x in data_header:
    print(x)
    
for x in data_rows:
    print(x)

plt.ylabel("Points")
plt.xlabel("Weeks") 
plt.title('Demo chart')
plt.show()

Open in new window


Chart in Python
Could you please help which Python syntax could show the data on the same way like in that above Excel demo?

Thanks in advance,
Demo.xlsx
0
Cloud Class® Course: Microsoft Exchange Server
LVL 12
Cloud Class® Course: Microsoft Exchange Server

The MCTS: Microsoft Exchange Server 2010 certification validates your skills in supporting the maintenance and administration of the Exchange servers in an enterprise environment. Learn everything you need to know with this course.

I have made a script which is my first whats happening is when it hits 404 script just stops it don't crash it waits forever how can i set if image URL don't exist 404 error download alternative image url then continue ?

headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 '
                                 '(KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}

        result = requests.get(image_url, stream=True, verify=False, headers=headers)
        if result.status_code == 200:
            sys.stdout.write("Saving Image... " + full_image_name + "\n")
            image = result.raw.read()
            open(complete_path, "wb").write(image)
            sys.stdout.flush()

Open in new window

0
Hi Experts,

   How to delete the existing elasticsearch cluster and how to create a new elasticsearch cluster?  Please throw some best practices.

With Many thanks,

Bharath AK
0
Hi:

 Trying to return all columns that contain the max of the same column, but seem to be running into an error:


import numpy as np

def answer_one():      
    return [df.where(df['Combined total']=numpy.max(df['Combined total']))]


  File "<ipython-input-8-ff62b3bbcead>", line 4
    return [df.where(df['Combined total']=numpy.max(df['Combined total']))]
                    ^
SyntaxError: keyword can't be an expression
0
Dear experts,

I need to write a Linux shell script that can automate filesharing using Implicit SSL/TLS (Port 990).

Python can be useful as well for this...

This needs to be done using a Linux Mate desktop.

Bottom line I need something like this to work (I think): curl --cert us.pem --user usergiven:passworm --upload-file file.txt ftp://sftp.remoteserver.com:990

I am not able to find anything on the internet yet...

Thank you in advance
0
i have 50+  plus standalone servers running windows 2008 std edition, not in a domain , uses the same userid and password across the servers

Im looking for a script for C drive, if server C drive space is less than 10gb, it will give me the hostnames.

So that I can logon and clear some space, as 10gb is expected to have server free space in each of 50 Systems
0
Sorry for the general question but I have researched on the internet and not found the definitive answer I was looking for and was looking for clarification.

I am looking to set a process on my web server (I am running Apache on Linux) to run each night to email a summary to a user of their data (based on some SQL query.

I just want to know the general approach that people would take to do this, in that...

  • how do you set processes to run at specific times or based on an event and;
  • which language is conducive to doing this in terms of running a process based on SQL and generating emails from it?
  • I am also looking at how to run a process that deletes data more than 10 years old (i.e., if the created date in the database was more than 10 years ago, run a process to delete that data each night - would this be the same approach?

Thanks in advance ofr the advice.
0
Hi Team,

I have an XML file i need to parse the XML and covert the output into CSV file .

I need output like below . Please help me with the code.
StableChangeVersion|LocalId|Trading Account|type|Value|Status
2|0171375670|NTPA|Y37F40|Active|
2|0171375670|0170485038|SDSMARSH38LONGB|ActiveFB|  
2|0171375670|FXOP|XXXX|Active

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<StandingSettlementInstruction xmlns="http://www.service.cdds.cs.com/ssiData_2">
    <StableChangeVersion>2</StableChangeVersion>
    <Core>
        <LocalId>0171375670</LocalId>
    </Core>
    <TradingAccount>
        <Core>
            <LocalId>0170485038</LocalId>
        </Core>
        <SystemCodes>
            <SystemCodeType>
                <Id>TradingAccountGSID</Id>
            </SystemCodeType>
            <Value>4973662</Value>
            <ValueStatus>Active</ValueStatus>
        </SystemCodes>
        <SystemCodes>
            <SystemCodeType>
                <Id>NTPA</Id>
            </SystemCodeType>
            <Value>Y37F40</Value>
            <ValueStatus>Active</ValueStatus>
        </SystemCodes>
        <SystemCodes>
            <SystemCodeType>
                <Id>FXOPs</Id>
            </SystemCodeType>
            <Value>L61774</Value>
            <ValueStatus>Active</ValueStatus>
        </SystemCodes>
        <SystemCodes>
            <SystemCodeType>
                <Id>SDSFB</Id>
            </SystemCodeType>
            …
0
Hello guys,

I have to implement an xml signature routine using smart card / token using x.509 signatures in a web application using python. The initial purpose would be for the user to sign xml files that the system generated using the client's certificate. I know that one kind of solution to this situation involves several steps. I'm primarily thinking of python communication with the user's smarcard / token.

I did some testing using python-pkcs11, worked well with an eToken Alladin Pro 72. But when I tried to use a newer smartcard (OberThur Cosmo v7.0.1 PCKS # 15) did not work.

Is there any library in python with pkcs11 and pkcs15 support?

Or will my life go easier by creating middleware in .net or java?

Charles
1
Project's task can have many tags. Now when the user creates a task he can choose from all tags. But he wants to be able to choose tags only from those tags that are used for that project.

What domain rule should I have on the field "tag" (on the form) to let user when creating new project task to see (and eventually to choose) only those tags that are used in the project the user creates task for?
0
Cloud Class® Course: Microsoft Azure 2017
LVL 12
Cloud Class® Course: Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

Greetings.
I have been struggling to get particles.JS working for my Django Website and I am not finding where I am going wrong. Hope someone can help me.
Inserting the code below.

html file-
    <div id="particles-js">
      <div class="jumbotron">
    <h1 class="display-4">Welcome To Crpyto News Network</h1>
    <p class="lead">Maybe we can prevent a second BitConnect.</p>
      </div>
    </div>
    <script type="text/javascript" src= {% static 'js/particles.min.js' %}> 
    </script>
    <script>
        particlesJS.load('particles-js', '{% static 'js/particles.json' %}', 
    function(){
            console.log('particles.json loaded...');
        });
    </script>

Open in new window

urls.py
   
    from django.urls import path
    from . import views
    from django.conf import settings
    from django.conf.urls.static import static

    urlpatterns = [
    path('', views.home, name="home"),

    ]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    
    

Open in new window

0
In "Project -> Tasks" Kanban view for each stage there are buttons ("+") to create tasks for that stage. These buttons are for "quick create". But the user asked to have additional button "Create" to open a form for "New task".

How to add additional buttons that open task creation form? Each button should appear next to "+" button.

Odoo version 10.
0
Hlw,

My self Abhinay Raj

I had made project on self driving car, In this project car will be move forward by follow the road lane using raspberry pi camera and some python program.

I want to develop this project by including fully automation in the self driving car. for this i have made one android application for booking cab(like uber). App. is working like such a way,that we will book cab same like as uber where app. will take the user current location and destination location. So, now i want to send the both (current,destination) location to the firebase database.And it will send to the raspberry pi than raspberry pi motor will move or follow the google map to arrive to the user first and than to the destination location.

Suppose that, if we have to go somewhere unknown place, here we use the google map, and it will provide me road on the map which is focus by blue line.. Means, i want to ask that similarly raspberry pi will also get loacation and it should follow the (blue line) the google map.

Please Help me....how can i do this...

thanks...
0
Odoo kanban “quick create” redirect to “New” form.

In Project tasks kanban view there is a button "+" (for each stage) to "quick create" a task for a stage. How to make this button open not "a quick create" (small form) but instead open a "Task create" form for that stage? So that when the user clicks "+" on the stage then the user is redirected to the "New task" form (and the stage is preselected). Much like when the user clicks "New" button to create a task.

Odoo version: 10.
0
I'd like to have a command line solution, maybe python, but am open to other solutions/utilities.

Frequently, I manually download an excel file from a webpage. It requires me to first logon.

Hovering my mouse over the link doesn't show anything, i.e. to give a clue to the link.
Picking the link opens another page.
The page's link address is: https://website.com/V006498/FileDownload.htm?item=SomeRandomNumber
Then, a dialog pops up asking to download the file w/ OK prompt.

If possible, I'd like to run this as a scheduled task.
0
I have a python file with several variables declared right at the beginning of the code. I then have a few small classes declared (in-line inside of the same file) and finally a large loop with all the logic. What I've noticed is that at the end of the outer loop I zero-out the variable and begin again (note: the zeroing-out does work...I can see it in the debugger). The strange thing is that as soon as the loop starts again, the variables revert back to what they were when the loop completed (as if the zeroing...initializing...never happened).

I am stepping through line by line.

What am I not understanding here? Does python just deal with scope differently than other languages?

import statements
variables

class declared
class declared

outer loop:
  .
  .
  inner loop:
     .
     .
  reset variables

Open in new window

0
Hi Team,

I have multiple XML files I have to covert the XML data into CSV file and to generate the into CSV output file.
Could you please help me in this.


i need data in csv file ;
StableChangeVersion|LocalId|EffectiveDate|so..no
2|170900|018-06-24T06:38:47.093-04:00|....
sample-file.txt
0
Hello there!

I have the following, working and tested, powershell code:

I'd need to port it to python but I rellay cannot understand how to make the authentication.
Function Connect-Sharepoint {
 # Connects to Sharepoint using the $user and $password
 $http_success = '2\d{2}';$http_headers = @{"accept"="application/json
 odata=verbose"};Try { $password = ConvertTo-SecureString $password -AsPlainText -Force
 $creds = New-Object System.Management.Automation.PSCredential ($user, $password)
 $req_auth = Invoke-WebRequest -Uri $auth_url -SessionVariable "session" -Credential $creds -ErrorAction 'SilentlyContinue'
  if ($req_auth.statuscode -notmatch $http_success) {    throw 'Issue with authenticating to sharepoint site - ' + $req_auth.statuscode
  }  else {    Write-Host 'Successfully connected to Sharepoint'
  };}Catch [Exception] {  Write-Host ('ERROR: ' + $_.Exception.Message);};
}

Open in new window



I've tried several solutions like this:
auth = HttpNtlmAuth(sharepoint_user, sharepoint_password)
r=requests.get("https://sp15.mosaic-services.net/content/90000223/_api/Web/Lists/getbytitle('SOP DOC DB')/Items?$top=5000", auth=auth, verify=False)

print r.content

Open in new window


But I cannot authenticate, I always get "Access Denied".

What am I doing wrong?
0
I tried this (excuse me for not formatting the code, because I sent this from a mobile phone) :

import cv2
img = cv2.imread('Bez názvu.png',cv2.IMREAD_GRAYSCALE)
cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Open in new window

But when I run it:

Traceback (most recent call last):
  File "C:/Users/Andrej/Documents/Python projects/edges.py", line 5, in <module>
    cv2.imshow('image',img)
cv2.error: OpenCV(3.4.2) C:\projects\opencv-python\opencv\modules\highgui\src\window.cpp:356: error: (-215:Assertion failed) size.width>0 && size.height>0 in function 'cv::imshow'

Open in new window


cv2 was installed by:
 py -m pip install opencv-python 

Open in new window

in Powershell. My computer is running Windows 10 and the picture and the program are in the same folder. The picture' s size is bigger than zero, I draw it in MS Paint. EDIT: Code formatting added. Thank you
0
Keep up with what's happening at Experts Exchange!
LVL 12
Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Hi Team,

I have multiple XML file in a txt file in same format with attributes and the data . I have convert the XML file data into CSV with | separator and to generate the CSV out file

I need generate  the data in csv  file as below format
SystemCodes|LastApprovedVersion|LocalId|EffectiveDate|DataStatus|InternalIdentifier|LocalId
Y37F40|2|0171375670|2018-06-24T06:38:47.093-04:00|Active|00000000-0000-0000-0000-000008180d98|0171375670.

could you please help me in this .

PFA sample txt file

Many thanks in Advance,
Hari.

sample file:-
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<StandingSettlementInstruction xmlns="http://www.service.cdds.cs.com/ssiData_2">
    <StableChangeVersion>2</StableChangeVersion>
    <Core>
        <LocalId>0171375670</LocalId>
        <EffectiveDate>2018-06-24T06:38:47.093-04:00</EffectiveDate>
        <DataStatus>Active</DataStatus>
        <InternalIdentifier>00000000-0000-0000-0000-000008180d98</InternalIdentifier>
    </Core>
    <Change>
        <LastApprovedVersion>2</LastApprovedVersion>
        <LatestReviewTime>2018-06-24T06:38:47.013-04:00</LatestReviewTime>
    </Change>
    <SystemCodes>
        <SystemCodeType>
            <Id>NTPA</Id>
        </SystemCodeType>
        <Value>Y37F40</Value>
        <ValueStatus>Active</ValueStatus>
    </SystemCodes>
    <LatestReviewers>
        <userName>msiepra</userName>
    </LatestReviewers>
    <TradingAccount>
        <Core>
            …
0
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<StandingSettlementInstruction xmlns="http://www.service.cdds.cs.com/ssiData_2">
    <StableChangeVersion>2</StableChangeVersion>
    <Core>
        <LocalId>0171375670</LocalId>
        <EffectiveDate>2018-06-24T06:38:47.093-04:00</EffectiveDate>
        <DataStatus>Active</DataStatus>
        <InternalIdentifier>00000000-0000-0000-0000-000008180d98</InternalIdentifier>
    </Core>
    <Change>
        <LastApprovedVersion>2</LastApprovedVersion>
        <LatestReviewTime>2018-06-24T06:38:47.013-04:00</LatestReviewTime>
    </Change>
    <SystemCodes>
        <SystemCodeType>
            <Id>NTPA</Id>
        </SystemCodeType>
        <Value>Y37F40</Value>
        <ValueStatus>Active</ValueStatus>
    </SystemCodes>
    <LatestReviewers>
        <userName>msiepra</userName>
    </LatestReviewers>
    <TradingAccount>
        <Core>
            <LocalId>0170485038</LocalId>
        </Core>
        <SystemCodes>
            <SystemCodeType>
                <Id>TradingAccountGSID</Id>
            </SystemCodeType>
            <Value>4973662</Value>
            <ValueStatus>Active</ValueStatus>
        </SystemCodes>
        <SystemCodes>
            <SystemCodeType>
                <Id>NTPA</Id>
            </SystemCodeType>
            <Value>Y37F40</Value>
            <ValueStatus>Active</ValueStatus>
        </SystemCodes>
        <SystemCodes>
            <SystemCodeType>
    …
0
getting api data from posts from another sources to django
hello guys ,

is there any way where

when users can add the link of the post they want to save and the django should add that post allong with description and image to database

eg:

https://www.reddit.com/r/memes/comments/91jdgp/everything_goes_back_to_spongebob/

if i want to save this post

then dango should get data from this post as a json format and should save this post image, description ,title and all to the database

i know this can only be done using api/praw

but cant understand how to make it happen

any kind of help is appreciated
0
Hi,

Each day I have several horses that I bet on. To keep up to date with the results I go here: https://www.sportinglife.com/racing/fast-results

I have a script that will pull the data from the races but its ensuring the script is only run 5 minutes after each race when the results are up is the issue.

Can anyone recommend how I could use a python script to scrape the page only when the results are updated rather then constantly every 5 minutes 24/7 on my home server via a job?
0
Hey Im new to python tried executing my registry value change code but getting an error at line 8 parameter is incorrect
import os
import winreg
def usbenordis(value):
    print(value)
    keyval = r"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\UsbStor"
    if not os.path.exists(keyval):
        print("creating key")
        key = winreg.CreateKey(winreg.HKEY_LOCAL_MACHINE, keyval)
    registrykey= winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\UsbStor", 0,KEY_WRITE)
    print("open key")
    if value == True:
        winreg.SetValueEx(registrykey,"start",0,REG_DWORD,4)
        print("usb disabled")
    elif value == False:
        SetValueEx(registrykey,"start",0,REG_DWORD,3)
        print("usb enabled")
    else:
        print("op cancelled")
        winreg.CloseKey(registrykey)
    return True

def main():
    usbenordis(True)


if __name__== "__main__":
    main()

Open in new window

0
Hi there,

I am try to learning a home automation system on Raspberry pi through GSM, but unfortunetally I am getting error in my python coding.
The Problem is When I want to print my received message that time I am getting this kind of response b'b\xf1\xe2\xe2\xe2' ,
So, I cant able to decode that message and If I decode that the python giving me a error like unorderable types: int() < str(().

So , I am really confused about it , can anybody help me out in this problem, How I can match my actual message and print?

here is my code and its output.
import serial
import time
import os

print('Welcome to Test GSM SIM900')
ser = serial.Serial ("/dev/ttyS0", 19200, timeout=1) #9600 is the default for SIM900A modem
print('Waiting for Response')

ser.write(('AT+CMGF=1' + '\r').encode('utf-8'))
time.sleep(1)
print('Connection Establish')
ser.write(('AT+CMGDA="DEL ALL"'+'\r').encode('utf-8'))
time.sleep(1)
print('All messages has been Deleted')

message = ser.read(1000) # inWaiting- get the number of bytes in the inout buffer

print(message)

while True:
      if message == 'LED1':
          print ("LED 1 is on")
      elif message == 'LED2':
          print ("LED 2 is on")
      elif message == 'EXIT':
          print ("shuting down")
          ser.close ()
          break
      else:
          print ("Try again")
          break

ser.close() #close the serial port
  
>>> %Run GSMTRY.py
Welcome to Test GSM SIM900
Waiting for Response
Connection Establish
All 

Open in new window

0

Python

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.