Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x

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

How much experience is required to get hired as a back-end developer or Python,PHP and Ruby.But now i'm looking for php experience.or How i can earn $1500 per month with PHP.
0
Free Tool: IP Lookup
LVL 10
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

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.

Greetings,

I'm working with Windows Scheduler and windows batch files.

Here's what I have:

in \\SHARE\PROCESSOR\  I have three objects:
MASTER.bat  (MASTER BATCH FILE)
processA (FOLDER)
processB(FOLDER)

inside each folder I have a python executable, plus other artifacts the python code needs to operate.

I have two users:  myself and the service account.  Both AD users.

The problem is not the batch.  When I click on MASTER.bat in folder \\SHARE\PROCESSOR\ it all works.
If I use runas on the command line to start MASTER.bat, still no problem.  everything good.

My issue is with windows scheduler.

Scheduled task
The action settings are:
Program/script:  \\SHARE\folder\MASTEr.bat
Arguments and Start in are both blank.

When this is executed by Windows Scheduler.  It runs for one minute then exits successfully with error code: 2147942401

This is where I take issue because I can see the batch file plus associated python scripts in the task scheduler.  

What I need:
I need the scheduler to not lose focus on the task.  If the action takes too long, i need it to be able to stop Master.bat.

Any wisdom would be greatly appreciated.

Thanks
Evan
0
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
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
This is my program. This program basically is a prime number check. It will see if your number that you type in is a prime number or not. If it is then it will say "is a prime number"
The question that i am having is wondering how my main function can be contained in a while loop and at the end ask if i would like to test another number. If i type in y it should run again.



def main():
print("Mirage Jelani's Prime Number Checker")
user_number = int(input("Please enter a number:"))
if is_prime(user_number):
print(user_number, "is prime")
else:
print(user_number, "is NOT prime")

def is_prime( num ):
even_div = 0
if num <= 1:
return False
for currentnum in range (1,num + 1):
if num % currentnum == 0:
even_div = even_div + 1
if even_div > 2:
return False
return True

main()
0
Hi

I'm hoping somebody can help me with the following Python question:

I have been using sympy to generate a function e.g. 5*x**3 - 375*x + 18 called polynomial. The type is: <class 'sympy.core.add.Add'>

>>> polynomial
5*x**3 - 375*x + 18

I want to plot this function using something like:

x_axis = np.arange(-10,10,0.01)

plt.plot(x_axis, polynomial)

However, when I attempt this, I get the following:

Traceback (most recent call last):
  File "<pyshell#56>", line 1, in <module>
    plt.plot(x_axis, polynomial)
  File "C:\Users\user\AppData\Local\Programs\Python\Python35-32\lib\site-packages\matplotlib\pyplot.py", line 3161, in plot
    ret = ax.plot(*args, **kwargs)
  File "C:\Users\user\AppData\Local\Programs\Python\Python35-32\lib\site-packages\matplotlib\__init__.py", line 1819, in inner
    return func(ax, *args, **kwargs)
  File "C:\Users\user\AppData\Local\Programs\Python\Python35-32\lib\site-packages\matplotlib\axes\_axes.py", line 1382, in plot
    for line in self._get_lines(*args, **kwargs):
  File "C:\Users\user\AppData\Local\Programs\Python\Python35-32\lib\site-packages\matplotlib\axes\_base.py", line 381, in _grab_next_args
    for seg in self._plot_args(remaining, kwargs):
  File "C:\Users\user\AppData\Local\Programs\Python\Python35-32\lib\site-packages\matplotlib\axes\_base.py", line 359, in _plot_args
    x, y = self._xy_from_xy(x, y)
  File …
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,

We have Windows 10 laptops each with a local administrator account for our teachers, and one or more local standard user accounts for our students. Now and then these standard user accounts are deleted and new ones are added as students come and go.

Now, I have tried to install Python 3.6.2 for ALL users from within the adminstrator account, hoping that the students then can start all the installed components from within their standard user accounts. But when I log in to these standard accounts I cannot find the applications I installed into my administrator account.

Thus if I log into the adminstrator account, there is a Python 3.6 folder with IDLE, Python application, Python 3.6 module Doc and Python manuals. However if I log into the standard user account, I cannot see those items at all?

How to I install Python 3.6 on a Windows 10 PC so that also other user accounts on that machine can use Python in the same way as they would be able to do if they were logged into the administator account?

Thanks!
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
On Demand Webinar: Networking for the Cloud Era
LVL 10
On Demand Webinar: Networking for the Cloud Era

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

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
Hi,
My  7th grader has a probability problem I am trying to write a small script for.

"If you have a spinner with three letters on on (K,V and H) and you spin it three times, list all possible outcomes."
The number of outcomes is 27. I won't list them all here, but it's along the lines of KKK, KVH, VHK, VVK, etc... you get the idea. We have them all listed out already and the HW problem is solved.

I was thinking a small perl script would be fun to write to calculate this. But it's harder then I anticipated. I created an AOA but I can't figure out how to loop through it to get every combo.

I tried a nested for loop but that's not working.

@letters = (
['K','V','H'],
['K','V','H'],
['K','V','H'],
);

for ($i=0; $i<3; $i++){


        for ($j=0; $j<3; $j++){
        print "i=$i, j=$j\n";
        print $letters[$i][$j];
        }
print "\n";
}

I am posting this in Python also as I could do it in python if I can get the logic right.

Thanks!
Nacht
0
can anyone create this type of batch?
I run this Simple-Script.bat:
python my.py -w200
python my.py -w132
python my.py -w900
python my.py -w211

Open in new window

Each line runs well ---> python.exe process opens for each line(do his job) then closes automatically,but it seems that some lines cause problems,python.exe process opens but it never closes and i receive this error message:
failure code 5

Open in new window


Can someone make python.exe automatically when a line receives that error? then continue with the next (line) command?
thxx!

P.S.
or if someone knows the Python scripts can change directly from there.
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
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
How to Use the Help Bell
LVL 10
How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

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 have never used classmethod in my code, appreciate if I can get some example on how to use and which condition it will be beneficial? Thanks!
0
I would like to access a url say example.company.com but it's protected via okta. I have my user and password which I login via chrome and access. though I would like to access it via python + requests module.

Appreciate if I can get a leads on how should I proceed here. Thanks!
0
I need run the python py file into the ssis package using execute process task
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.