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

Hi there,

I have a split function like:

content = re.split('[,\*]+', self.get_log())

It works great for this line

LOG,-16.90,M,14,0281*21

and I get a list with ['-16.90', 'M', '14', '0281', '21\n']

but for this log, where the last fields before the last field are empty:

LOG,-16.90,M,,*21

I want to get ['-16.90', 'M', '', '', '21\n']

but I get ['-16.90', 'M', '21\n']

How can I fix this?  Thank you.
0
Free Tool: Site Down Detector
LVL 10
Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Python Gurus--

I am utilizing a 3rd-party API which returns the data I'm looking for in JSON--however, there is a u'foo' in front of everthing. Maybe a unicode thing?  I want to extract the elements to toss into a tabe that has the same element names.

Here's what I am getting:

[{u'comment': u'', u'enableSpeedWarning': False, u'major': 17, u'licensePlate': u'', u'enableMustReprogram': False, u'immobilizeArming': 30, u'engineVehicleIdentificationNumber': u'1XPBDP9X3GD301269', u'isActiveTrackingEnabled': False, u'workTime': u'WorkTimeStandardHoursId', u'isReverseDetectOn': False, u'brakingWarningThreshold': -34, u'gpsOffDelay': 10, u'minAccidentSpeed': 3.0, u'serialNumber': u'G7DF20DBD6F6', u'timeToDownload': u'1.00:00:00', u'maxSecondsBetweenLogs': 200.0, u'isSpeedIndicator': False, u'id': u'b18', u'customParameters': [], u'hardwareId': 551278326, u'name': u'1579', u'activeFrom': datetime.datetime(2017, 7, 31, 18, 13, 27, 296000, tzinfo=<UTC>), u'corneringWarningThreshold': 26, u'deviceType': u'GO7', u'disableBuzzer': False, u'accelerometerThresholdWarningFactor': 0, u'speedingOff': 90.0, u'minor': 59, u'productId': 109, u'odometerOffset': 0, u'isDriverSeatbeltWarningOn': False, u'deviceFlags': {u'isGarminAllowed': True, u'isOdometerAllowed': True, u'isTripDetailAllowed': True, u'isIridiumAllowed': True, u'isEngineAllowed': True, u'isVINAllowed': True, u'activeFeatures': [], u'ratePlans': [], u'isActiveTrackingAllowed': True, u'isUIAllowed': True, u'isHOSAllowed': …
0
question:1---I have 4 fields early and also have one to many lines where there is list of date and time.
now i want to compare first item of list with fixed date and result goes to early.
for example:
i have list of datetime. now i want to compare first item of list with that fixed time.
list like=[01/02/2017 11:00:00] [01/02/2017 12:00:00] [01/02/2017 13:00:00]
from here pick first list item time only that is 11:00:00
and compare with fixed time which we will fixed like=10:00:00
now difference of both time goes to early field..
please anyone tell me how to do this.


question2:-----please tell me how to set any time(i.e. i want some fixed time 10:00:00). how to set in odoo.
becoz i tired this:-
from datime import datetime
@api.onchange("employee_is")
def _onchange(self):
fixed_time = datetime.datetime.now("%h,%m,%s","10:00:00")

Open in new window

please tel me is this correct way to set fixed random time.
0
Dear forum contributors,

I'm experiencing a issue trying to use Google Cloud APIs with Python.
My cenario:
=== Hardware and OS ====
OS Name      Microsoft Windows 10 Pro
Version      10.0.14393 Build 14393
System Manufacturer      LENOVO
System Model      20BGCTO1WW
System Type      x64-based PC
System SKU      LENOVO_MT_20BG
Processor      Intel(R) Core(TM) i7-4700MQ CPU @ 2.40GHz, 2394 Mhz, 4 Core(s), 8 Logical Processor(s)
BIOS Version/Date      LENOVO GNET73WW (2.21 ), 03/12/2015
SMBIOS Version      2.7
Embedded Controller Version      1.11
BIOS Mode      UEFI
BaseBoard Manufacturer      LENOVO
Secure Boot State      Off
PCR7 Configuration      Elevation Required to View
Windows Directory      C:\WINDOWS
System Directory      C:\WINDOWS\system32
Boot Device      \Device\HarddiskVolume2
Hardware Abstraction Layer      Version = "10.0.14393.206"
Installed Physical Memory (RAM)      32.0 GB
Total Physical Memory      31.9 GB
Available Physical Memory      18.7 GB
Total Virtual Memory      36.6 GB
======================
=== Python version 3.4.4

When I try to run the command 'gcloud init':
Welcome! This command will take you through the configuration of gcloud.

Your current configuration has been set to: [default]

You can skip diagnostics next time by using the following flag:
  gcloud init --skip-diagnostics

Network diagnostic detects and fixes local network connection issues.
Checking network connection...done.
Reachability Check passed.
Network diagnostic (1/1 checks) passed.

ERROR: gcloud crashed (UnicodeEncodeError): 'ascii'…
0
Hi,

I'm struggling to understand why the first bar in an hbar plot is being chopping in half horizontally. The yaxis label is also missing for that bar.

Here is the script and attached is the plt.show()

import networkx as nx
import matplotlib.pyplot as plt
from matplotlib import cm
import numpy as np
import neptcon as nc
import sys
import pickle
    
fp = open("C:\Python27\Internal_reports\\shared.pkl")
shared = pickle.load(fp)

con = None

cur, con = nc.connect()
cur = con.cursor()   
scriptFile = open("C:\Python27\Internal_reports\Ann_report_sql\Den diff.sql", 'r')
script = scriptFile.read()
scriptFile.close()    
cur.execute(script.format(**shared))
items = cur.fetchall()
client, ship, imo, diff = zip(*items)
new_list = []
for item in diff:
    new_list.append(int(item))          
N = len( new_list )
x = range( N )   
n_groups = N
index = np.arange(n_groups)
fig = plt.figure()
f, (ax1) = plt.subplots(1, 1, figsize=(8, N/2), sharex=False)
bar_width = 0.95
opacity = 0.5
G = nx.complete_graph(10)
pos = nx.spring_layout(G)

plt.yticks(index+(bar_width/2), ship, fontsize = 9)
ax1.yaxis.grid(True, which='major', color='0.95',linestyle='-')
ax1.set_ylim(0, N)
ax1.xaxis.set_ticks_position('bottom')
ax1.yaxis.set_ticks_position('right')
ax1.spines['right'].set_visible(False)
ax1.spines['top'].set_visible(False)
ax1.spines['left'].set_visible(False)
for a,b in zip(index,new_list):
	plt.text(b, a-0.2, str(b))	
	

Open in new window

0
Hello,

We have a JSON file that we are trying to read and put the Key and the values in a CSV file. We are getting an error as below. can someone please help?

Attached is the sample JSON file and the Python code we are using.

Our program Parse_workitem.py accepts 2 arguments one is  input_file which is json and the other one is output_file which is csv. When we execute the code as below with both arguments the code is failing with the following error. We are using Python version 2.7.5


./parse_workitem.py --input_file /home/dqadmin/json/work_items.json  --output_file /home/dqadmin/json/work_items.csv
Traceback (most recent call last):
  File "./parse_workitem.py", line 66, in <module>
    main()
  File "./parse_workitem.py", line 54, in main
    value = item.get(key, '')
AttributeError: 'unicode' object has no attribute 'get'


Thank you
parse_workitem.py
sample.txt
0
While trying to install
sudo apt-get install -y python-wxgtk2.8

**i got the following error**

/etc/logstash/startup.options is not a file path
To manually specify a startup style, put the path to startup.options as the
first argument, followed by the startup style (sysv, upstart, systemd)
dpkg: error processing package logstash (--configure):
 subprocess installed post-installation script returned error exit status 1
Errors were encountered while processing:

so i removed the logstash . how do i reset? i dont know what to do ?
0
What are steps to install selenium automation in robot framework in ubuntu 16.04 in python?
0
root@stack-ThinkCentre-M83:~# sudo apt-get install python-wxgtk2.8

Reading package lists... Done
Building dependency tree
Reading state information... Done
python-wxgtk2.8 is already the newest version (2.8.12.1+dfsg2-2ubuntu2+1~webupd8~xenial0).
0 upgraded, 0 newly installed, 0 to remove and 128 not upgraded.
1 not fully installed or removed.
After this operation, 0 B of additional disk space will be used.
Do you want to continue? [Y/n]
Setting up logstash (1:5.5.2-1) ...
sed: can't read /etc/logstash/logstash.yml: No such file or directory
/etc/logstash/startup.options is not a file path
To manually specify a startup style, put the path to startup.options as the
first argument, followed by the startup style (sysv, upstart, systemd)
dpkg: error processing package logstash (--configure):
 subprocess installed post-installation script returned error exit status 1
Errors were encountered while processing:
 logstash
E: Sub-process /usr/bin/dpkg returned an error code (1)
root@stack-ThinkCentre-M83:~#
0
I need a python(2.7) coder to help me with this script:  https://pastebin.com/zYLbFwpi  (rdpy-rdpscreenshot.py)
Original site: https://github.com/citronneur/rdpy 
Now i run this .bat: https://pastebin.com/SYHy0EsB  ,everything goes well but the problem is that it stops at line 2 trying and re-trying  to connect endlessly without going to the 3rd line (maybe NLA is activated),anyway all i want is to close & exit and pass to the 3rd line.
THANK YOU!

P.S.
- here a succesull line: https://pastebin.com/XqWpn3RU
- here problem line: https://pastebin.com/daRqSV0Y

i used a small tool to compare the 2 files and the diference is this:
rdpy.core.error.RDPSecurityNegoFail: negotiation failure code 5
[*] INFO:       save screenshot into C:/tmp/24.73.34.125.jpg

Open in new window

0
Free Tool: SSL Checker
LVL 10
Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Hello, I'm new to Tkinter with some basic Python experience. I have version 8.5 and want to update it to 8.6 on an OS X machine to access and learn the latest features. I can import Tkinter but when I look up documentation from sources like python.org and ActiveState's website, the information is confusing so far on what to import, make, install, etc. I would like to update Tkinter from the command line.

As a reference, this link confirms the latest recommended version for Mac OS X Sierra (10.2) is version 8.5.x. Is an 8.6 update even possible?

https://www.python.org/download/mac/tcltk/

Please help. Thanks.
0
Hi
i need a help of creating a script that runs tcpdump and request for arguments of ip address src and dest and port,
saves the outcome to a file
appreciate your help
Amir
0
I am using Visual Studio Code and am running this code:

from sys import argv
script, first, second, third = argv
print("This script is called:", script)
print("Your first variable is:", first)
print("Your second variable is:", second)
print("Your third variable is:", third)

I get the error message:  
Traceback (most recent call last):
  File "e:\PythonProjects\LPTHW\ex13_Parameters_Unpacking_Variables.py", line 5, in <module>
    script, first, second, third = argv
ValueError: not enough values to unpack (expected 4, got 1)


But when I run it via PowerShell , I get the below and it works.

C:\PythonProjects> python ex13_Parameters_Unpacking_Variables.py apple orange dragonfly
This script is called: ex13_Parameters_Unpacking_Variables.py
Your first variable is: apple
Your second variable is: orange
Your third variable is: dragonfly

What do I have to do to get it to work in Visual Studio Code?

Thanks
0
Hi experts, i wonder if you can help me, need some help with a small problem.
I need to know how to change the image on a button once the button is clicked.

Using: from tkinter import *
no classes please

Thank you
0
i have two model hr_work_shifts.hr_shifts and hr.contract.
when i select employee and set schedule (Onchange) in model
hr_work_shifts.hr_shifts
then working hours in model
hr.contract
change according to that schedule which i select in
hr_work_shifts.hr_shifts
for that particular employee. it woks correctly but the problem is that when i save the information in
hr_work_shifts.hr_shifts
then it gives waring..
The code which i use in .py file:----
# -*- coding: utf-8 -*-

from odoo import models, fields, api,_

class hrWorkShifts(models.Model):
	_name = 'hr_work_shifts.hr_shifts'
	_inherit = ['mail.followers','mail.thread','ir.needaction_mixin']
	
	@api.onchange('schedule')
	def _onchange_schedule(self):
		for item in self.hr_shifts_line:
			current=self.env['hr.contract'].search([('employee_id','=',item.emp_name_ids.id)])
			current.write({'working_hours':self.schedule.id})

	@api.depends('hr_shifts_line.emp_name_ids')     
	def _emp_name_ids(self):
		for item in self.hr_shifts_line:
			current=self.env['hr.contract'].search([('employee_id','=',item.emp_name_ids.id)])
			current.write({'working_hours':self.schedule.id})

name = fields.Char(string="Work Shift Name",required=True,)
	description = fields.Text(string="Description",)
	schedule = fields.Many2one('resource.calendar',)
	location = fields.Char(string="Location")
	

Open in new window

0
I need run the python py file into the ssis package using execute process task
0
In model employee.loan there is tree view below the form view where
page loan_disburse is editable
to administrator but i want it is also editable to hr and not to employee.
Below is the code what i am tried:
<page string="Loan Disburse" attrs="{'invisible': [('state', 'not in', ['approved','paid'])]}">
						    	<field name="disburse_line_ids" 
					    			string='Disbursement lines' 
					    			widget="many2one_list" 
					    			attrs="{'readonly':[('disburse_check','in',True)]}" >
							    	<tree editable="bottom" groups="hr.group_hr_manager">
						    			<field name="date_to"/>
						    			<field name="percentages"/>
						    			<field name="total_disburse"/>
						    		</tree>
					    		</field>
						    </page>

Open in new window

Also see the attachment for more clearance:
loan_disburse.png
loan.png
0
In model hr_leave_rules.leave_rules there is field can_manager_override_paid_leaves_to_unpaid which is selection field(contain 'yes' and 'no') and there is another model hr.holidays here is button override_to_unpaid. now i want when selection field is 'yes' then button override_to_unpaid show and when selection field is 'no' then button override_to_unpaid hide.

here is the code which i use:
code for
class LeaveRulesConditions(models.Model):
	_inherit = "hr.holidays"

	@api.multi
	def action_override(self):
		self.action_refuse() 
		contract = self.env['hr.holidays']
		contract.create({'name':self.name,
					'holiday_status_id': 4,
					'date_from': self.date_from,
					'date_to': self.date_to,
					'number_of_days_temp':self.number_of_days_temp,
					'employee_id':self.employee_id.id,
					'type':'remove'})

Open in new window


<?xml version="1.0" encoding="UTF-8"?>
<odoo>
	<data>
		<record id="leave_request_override" model="ir.ui.view">
			<field name="name">Leave Request</field>
			<field name="model">hr.holidays</field>
			<field name="inherit_id" ref="hr_holidays.edit_holiday_new"/>
			<field name="arch" type="xml">
				<xpath expr="//header" position="inside">
					<button string="Override to unpaid" name="action_override" type="object" groups="hr_holidays.group_hr_holidays_user" attrs="{'invisible':[('state','=','draft')]}"/>
				</xpath>
			</field>
		</record>
	</data>
</odoo>

Open in new window

Also see the attached images for more clearance.
override_leave_to_unpaid.png
override_to_paid.png
0
i got a list of lists in ,
outerlist = [['name Belgian Waffles', 'price $5.95', 'description Two of our famous Belgian Waffles with plenty of real maple syrup', 'calories 650']
['name Strawberry Belgian Waffles', 'price $7.95', 'description Light Belgian waffles covered with strawberries and whipped cream', 'calories 900']]

The requirement is  to write the list to a csv file in the format

name                                                 description                                                                                                             price           calories      
Belgian Waffles                                Two of our famous Belgian Waffles with plenty of real maple syrup        $5.95         650             
Strawberry Belgian Waffles        Light Belgian waffles covered with strawberries and whipped cream        $7.95         900             
 

I tried the following python code

l = []

for item in outerlist:
    d = {kv.split()[0]:' '.join(kv.split()[1:]) for kv in item}
    l.append(d)
print (l)                     #----> returns random order

keys = l[0].keys()

with open(csvFileDir ,'w', newline = '') as o:
    writer = csv.DictWriter(o,fieldnames=keys)
    writer.writeheader()
    writer.writerows(l)

I am able to parse the same to a csv file , but the order returned is random .

What should I do to make sure the order returned is the same as the order given as input .

I tried OrderedDict but it returned

ValueError: too many values to unpack …
0
Enroll in September's Course of the Month
LVL 10
Enroll in September's Course of the Month

This month’s featured course covers 16 hours of training in installation, management, and deployment of VMware vSphere virtualization environments. It's free for Premium Members, Team Accounts, and Qualified Experts!

ab= [['name Belgian Waffles', 'price $5.95', 'description Two of our famous Belgian Waffles ', 'calories 650'] ]

I would like to parse this list to an CSV file in the table format

Ex. :
name                       price                      description                                                    Calories
Belgian Waffles      $5.95                     Two of our famous Belgian Waffles         650


Note : List size may vary . The values can vary . No hard coding should be there
0
pip install twilio
works perfectly on a Pi2.   Just bought a new Pi3 with the latest NOOB.  
same version of python (2.7.9), same version of pip (1.5.6).  I keep getting the error:

TypeError: __str__ returned non-string (type Error)

Googling around, I checked and verified that
- no network issue, Chromium connects to https://pypi.python.org/simple/twilio/
- my date/time on the computer is correct
- some talk about --trusted-host=http://pypi.python.org/simple/ but that parameter is not valid on pip
- some talk about creating an /etc/pip.conf file and adding trusted-host=pypi.python.org but that makes no difference (assuming pip every reads that file...)

My guess is that it has something to do with the SSL certificates... but I have no idea how to solve it.  
sudo apt-get install libssl-dev did not help

Thoughts?
pip.log
0
from flask.ext.api import FlaskAPI
from flask import request, current_app, abort
from functools import wraps

app = FlaskAPI(__name__)
app.config.from_object('settings')

def token_auth(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if request.headers.get('X-API-TOKEN', None) != current_app.config['API_TOKEN']:
            abort(403)
        return f(*args, **kwargs)
    return decorated_function

@app.route('/predict', methods=['POST'])
@token_auth
def predict():
    from big_model import model
    item = request.data.get('item')
    total_predictions = request.data.get('num', 100)
    if not item:
        return []
    return model.predict(str(item), total_predictions)


@app.route('/train')
@token_auth
def train():
    from big_model import model
    data_url = request.data.get('data-url', None)
    model.train(data_url)
    return {"message": "Success!", "success": 1}

if __name__ == '__main__':
    app.debug = True
    app.run()
0
Hello Python Individuals,

I need to connect to the Lotus Notes and do some operations (Send/Receive mail with Attachments).
However, I am not able to get past even the ‘Dispatch’ step:

import os, sys, stat, shutil
import os.path
import string
from configparser import SafeConfigParser
import tempfile
import logging
import getpass
import time
from win32com.client import makepy
from win32com.client import Dispatch
import win32com.client
import pywintypes
import smtplib
import csv # imports the csv module
makepy.GenerateFromTypeLibSpec('Lotus Domino Objects')
makepy.GenerateFromTypeLibSpec('IBM Notes Automation Classes')
Session = win32com.client.Dispatch('Lotus.NotesSession')

Open in new window


This rises an exception (Traceback)
File ..\Anaconda3\Lib\site-packages\win32com\client\dynamic.py in _GetGoodDispatch
IDispatch = pythoncom.connect(IDispatch)
Pywinttypes.com.error: (-2147221021, ‘Operation unavailable’, None, None)

During handling of above exception, another exception occurred:

Traceback
File My file
Session = win32com.client.Dispatch('Lotus.NotesSession')
File ..\Anaconda3\Lib\site-packages\win32com\client\__init__.py in Dispatch
  dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx)
File ..\Anaconda3\Lib\site-packages\win32com\client\dynamic.py in _GetGoodDispatchAndUserName
      return (_GetGoodDispatch(IDispatch, clsctx), userName)
File ..\Anaconda3\Lib\site-packages\win32com\client\dynamic.py in  _GetGoodDispatch
      IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.IID_IDispatch)
Pywinttypes.com.error: (-2147221164, ‘Class not registered’, None, None)


Thanks in advance for any ideas or aid.

Doug
0
Basically I am an Electrical Engineer. I am doing estimation & Design.

I am repeating the same work again and again. I decide to automate my boring works

From google i found Python to make the script.

Since I need output in .xls & .dxf i selected xlxwriter and dxf write module.

To create user interface i selected Pyqt..

But I got stuck how to convert this all files as a single file. So i can distribute the same company with commercial befit.

Can you please advice the next step..
0
input xml can be any. It is dynamic file. so there is no pre determined tags. it should be created depending on the input xml file.

And i need the code for following requierments.

Parse XML file to create a tree of objects
   - create an object for each xml element
   -object mainly contains xml element name, value, attributes, list of sub elements where each member in the list is another xml element object
   - a function to create object tree
  - a function to iterate
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.