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, this is my code:

def top_three(lista=[2,4,6,8,10,12]):
    sorted(top_three)
    print(top_three=lista[-3:])

Note: this is intended to be a function. Its purpose is to return or print the three largest values. First, my purpose is that the user type the values, but if I do this I get more errors.
0
Free Tool: ZipGrep
LVL 10
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

dear all,
I have got video and audio files I need to segment them based on their text.
I need to segment all the files. for example ( a single word contain n audio frames and n of visual frames (images) )
Can any one help or advice how can I make it?

Thanks
0
s= 70
if (s < 50):
    print ('you failed')
else (s > 50):
    print ('great, you passed')

File "<ipython-input-21-b663449d306a>", line 4
    else (s > 50):
         ^
SyntaxError: invalid syntax
0
Hello there,

I wrote a small Python script to send email and push notifications.

It clearly needs the user to store his email user and password and his push services access data.

How can I secure this data in a good way?

At the moment being I save the user and pass on a separate file and make that file readable only by the user that will run the script.

Is this sufficient?

Thanks for your time and help
1
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-63-41f0d72a57d4> in <module>()
----> 1 grocery_list.append (Onions)
      2 print (grocery_list2)

AttributeError: 'tuple' object has no attribute 'append'

What does the error message mean? Why won't my list append?
0
I am doing a loop using Python3 and BeautifulSoup4 and I want to be able to print out the next 10 lines after I found a word in the output.  I am using find_all to pull our all the text in the TR tag.  I mainly want the text in the TD tag, but what I have seems to be giving me what I want.  If I can improve, suggestion are always welcomed

But my first issue is just getting it to print when I found the word I am looking for.  If I remove the IF statement, then I can see I am getting all the text I want.

Here is what I have so far.

from bs4 import BeautifulSoup
import requests

 
url = 'http://www.somewebsite.com'
source_code = requests.get(url)
plain_text = source_code.text
soup = BeautifulSoup(plain_text, 'html.parser')


for table in soup.find_all('tr'):
    if table.text == 'Actuals':
        print(table.text)

Open in new window




Thank you
0
mylist = []

mylist

mylist.append ('0,1,2,3,4,5')

mylist

and then if I want to reverse it,

mylist.reverse ()
mylist

I don't get an output.
0
sudo apt-get upgrade

Open in new window


And I get this result:


Preparing to unpack .../debconf_1.5.56+deb8u1_all.deb ...
Traceback (most recent call last):
  File "/usr/bin/py3clean", line 24, in <module>
    import logging
  File "/usr/lib/python3.4/logging/__init__.py", line 26, in <module>
    import sys, os, time, io, traceback, warnings, weakref, collections
  File "/usr/lib/python3.4/traceback.py", line 3, in <module>
    import linecache
  File "/usr/lib/python3.4/linecache.py", line 10, in <module>
    import tokenize
  File "/usr/lib/python3.4/tokenize.py", line 29, in <module>
    import collections
TypeError: source code string cannot contain null bytes
dpkg: advarsel: underprosessen gammelt pre-removal-skript returnerte feilstatus 1
dpkg: trying script from the new package instead ...
Traceback (most recent call last):
  File "/usr/bin/py3clean", line 24, in <module>
    import logging
  File "/usr/lib/python3.4/logging/__init__.py", line 26, in <module>
    import sys, os, time, io, traceback, warnings, weakref, collections
  File "/usr/lib/python3.4/traceback.py", line 3, in <module>
    import linecache
  File "/usr/lib/python3.4/linecache.py", line 10, in <module>
    import tokenize
  File "/usr/lib/python3.4/tokenize.py", line 29, in <module>
    import collections
TypeError: source code string cannot contain null bytes
dpkg: error processing archive /var/cache/apt/archives/debconf_1.5.56+deb8u1_all.deb (--unpack):
 
0
Write a function called my_gcd() that takes parameters a and b and returns their greatest common divisor. Create your own implementation of the algorithm and test your code by comparing the output of your function to Python's gcd() function from math package.Test the code with the following inputs: (39, 91), (20, 30) and (40,40). Explain the logic of your function.
0
n=3

def countdown (n):
    if n <= 0:
        print ('Blastoff!')
    else:
        print (n)
        countdown (n-1)

when I press shift + enter I get a blank answer
0
Free Tool: Subnet Calculator
LVL 10
Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Hi,

If I have to judge or find out which is the best programming language for my project, i.e., enterprise high performance low latency app which requires to be secure as well, what is the criteria to compare various languages like C++, Java, Python etc? How do I come up with scientific data to justify my final conclusion? And how do I calculate performance, security etc for various languages? Thanks.
0
I want to be Back-end Developer.I want to get quick job.because i want money as possible.
0
I have the following code and am trying to figure out why my copy isn't working. For the record I have tried shutil.copy, shutil.copy2, shutil.copyfile. In my current code I am trying to concatenate just using the deprecated os.system function. My problem is when I use copy, copy2, or copyfile I get one error or another. I either get "Not a directory" or oddly enough if I switch it I get "Is a directory". It's like I can't win. Below is my code. All I am having trouble with is once a file is recursively put into my local drive I want to copy those files recursively to another directory on my local drive.

#!usr/bin/python
import os
import pysftp
import paramiko
import shutil
import os.path

HOST=""
USER=""
#PASSWORD=""
SUFFIX_TO_FETCH__AND_DELETE=".csv"
DESTINATION_PATH= "/mnt/sas/ftp"
DESTINATION_PATH2="/mnt/sas/ftp_ncdfs_coll"

cnopts=pysftp.CnOpts()
cnopts.hostkeys.load('/home/boro/.ssh/id_rsa')

srv = pysftp.Connection(host=HOST, username=USER, cnopts=cnopts)#, password=PASSWORD)


def do_nothing(fname):
        return " "

def fetch_and_remove(fname):
    if not fname.endswith(SUFFIX_TO_FETCH__AND_DELETE):
        return # skip files with wrong suffix
    filename = os.path.split(fname)[1]
    dst_fname = os.path.join(DESTINATION_PATH, filename)
    dst_dirname = os.path.dirname(dst_fname)
    if os.path.isfile(dst_fname):
        return " "
    else: (THIS IS WHERE THE PROBLEM OCCURS)
        srv.get(fname, dst_fname)
#     dst_fname = os.path.split(fname)[0]
  

Open in new window

0
Subject of the week | Tell us about a technology you'd like to learn.
I'm fascinated by developments in Machine Learning and want to, heh, learn more about it. Not so much because I want to create Machine Learning systems myself—I have very little interest in the math involved—but so I can know how to leverage the sort of things that are being built. I easily envision the future of most work being about managing various bots and knowing how to apply them to higher level problem solving.

To get started on that path, I'm currently teaching myself Python (via several books on the subject) and would then transition into the use of it to dig deeper into the Machine Learning libraries. (And if I have to, even some refresher on the math... I did pass the AP calculus test, but that was 20 years ago!)

Any of you out there with more knowledge in these areas have some advice on this?
1
I want to get a header name for columns where it has "No" value. How to achieve this in pandas? Please find the attached screenshot for the sample format.
Capture.JPG
0
docker version output as below it shows same API version but when i run command  it is throwing error

# docker version
Client:
 Version:         1.12.6
 API version:     1.24
 Package version: docker-1.12.6-48.git0fdc778.el7.x86_64
 Go version:      go1.8.3
 Git commit:      0fdc778/1.12.6
 Built:           Thu Jul 20 00:06:39 2017
 OS/Arch:         linux/amd64

Server:
 Version:         1.12.6
 API version:     1.24
 Package version: docker-1.12.6-48.git0fdc778.el7.x86_64
 Go version:      go1.8.3
 Git commit:      0fdc778/1.12.6
 Built:           Thu Jul 20 00:06:39 2017
 OS/Arch:         linux/amd64
#

Open in new window



But the error as below...

# python
Python 2.7.5 (default, Aug 29 2016, 10:12:21)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import docker
>>> client = docker.APIClient(base_url='unix://var/run/docker.sock')
>>> print client.version()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/site-packages/docker/api/daemon.py", line 177, in version
    return self._result(self._get(url), json=True)
  File "/usr/lib/python2.7/site-packages/docker/api/client.py", line 226, in _result
    self._raise_for_status(response)
  File "/usr/lib/python2.7/site-packages/docker/api/client.py", line 222, in _raise_for_status
    raise create_api_error_from_http_exception(e)
  File "/usr/lib/python2.7/site-packages/docker/errors.py", line 31, in create_api_error_from_http_exception
    raise cls(e, response=response, explanation=explanation)
docker.errors.APIError: 400 Client Error: Bad Request ("client is newer than server (client API version: 1.30, server API version: 1.24)")
>>>

Open in new window

0
We have a digital sign powered by Scala which includes info from an rss feed. It has been functioning correctly for years, but now suddenly it fails with the following message:
scala designer error message
This persists whether running from the Content Manager or from Scala Designer. There is a linked python script which pulls the rss info, and its contents are as follows:
----------------
import scalatools as st
import scalalib as sl

def clean_text(txt):
    tmp = st.scrub_html(txt)
    return tmp.strip()

svars = sl.sharedvars()
st.grab_url(svars.url, filename=svars.filename)
svars.total = st.auto_xml(svars.filename, transforms={'description':clean_text})
-----------------
Is there anything obviously wrong here? I am not a python expert, and originally obtained the script from Scala support.
0
Below code was working few days back ago.But suddenly i'm experience this error. I tried implicit,explicit wait, time.sleep but nothing is working out.  I have also verified that element are present.I have checked similar error in stackoverflow , where they have mentioned to use explicit wait. As I mentioned earlier, it's doesn't work. Am I new to selenium , so kindly help me on this issue.

Error code :
driver.find_element_by_xpath("//*[@id='wrapper']/main/div/p[5]/a").click()

Open in new window

Complete code for the  perusal.
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
import datetime 
import time 
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from bs4 import BeautifulSoup
from IPython.display import clear_output

def select_elements(system,yy,mm,dd,hr,mins,meridiem):
    select = Select(driver.find_element_by_id('fin_compatibility_system'))
    select.select_by_value(system)

    select = Select(driver.find_element_by_id('fin_gyear'))
    select.select_by_value(yy)

    select = Select(driver.find_element_by_id('fin_gmonth'))
    select.select_by_value(mm)

    select = Select(driver.find_element_by_id('fin_gday'))
    select.select_by_value(dd)

    select = Select(driver.find_element_by_id('fin_ghour'))
    select.select_by_value(hr)

Open in new window

0
i need to install metagoofil and the harvester on my ubuntu liveCD for a hacking project.

my first instict was to just download them and put them in their own directory and ./configure, make, and make install -- but it turns out i'm experienceing dependency hell.

i found a repository, ppa.launchpad.net/backbox/four ubuntu trusty main, which has theharvester, but after i install it i get an error in line 6 and line 10...   you think its just a corrupt install?

i don't know too much about linux .. just learning ..

metagoofil, i'm totally lost...
i've downloaded the source, unzipped it into it's own directory, and now i have four file in the directory: COPYING, LICENSES, metagoofil.py and README ....   i guess since it's written in python, it doesn't have a ./configure

any help is greatly appreciated

thanks

-dave.j
WhatsApp-Image-2017-10-01-at-4.52.0.jpeg
0
What’s Wrong with Your Cloud Strategy ?
LVL 10
What’s Wrong with Your Cloud Strategy ?

Even as many CIOs are embracing a cloud-first strategy, the reality is that moving to the cloud is a lengthy process and the end-state is likely to be a blend of multiple clouds—public and private. Learn why multicloud solutions matter in this webinar by Nimble Storage.

I want to map a network drive so I can use it in Python.
But I am not finding much on it.
When I try to use unc it doesn't seem to work with network permissions
0
I am trying to classify sentences in a document using LSTM by posing it as a sequence tagging problem. I think this question might already be discussed somewhere but I was not able to find, so please bear with me.

Now each of my sentence is made up of variable number of words and each document in turn has variable number of sentences. OS the problem is essentially one that of sequence of sequences where lengths of both are variable.

(word1, word2, ..., wordnk) --> sentencen
(sent1, sent2, ..., sentji) --> documentj

So essentially,
Documentj   <--  ((word1, word2, ..., word1k),   (word1, word2, ..., word2k),   ...,   (word1, word2, ..., wordjik))

Now how I want to model this is to capture the first sequence of words using LSTM(s) so that I get a fixed length representation of each sentence, and then use another LSTM(s) to do the sentence labelling task. Something like this:

(word1, word2, ..., wordk) --> LSTM --> Dense

This will give the fixed representation of the sentence

Dense --> LSTM ---> TimeDIstributedDense ---> SoftmaxActivation --> loss

So can this system be built as an end-to-end system or I have to build the two parts separately.

I have tried the Convolution already. I want to build this in Keras.
0
1. I load the page
2.input some data
3.click on submit button
4.It does the calculation , and result are shown below in the same page.

In-spite of simplicity wait, page_source doesn't have newly loaded content.

My test code:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
import time 
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from bs4 import BeautifulSoup

driver = webdriver.Chrome('C:\\Users\\Vivekanandhan\\Downloads\\Compressed\\chromedriver_win32\\chromedriver.exe')


driver.get('http://srirangaminfo.com/porutham.php')
#Input Value to the text box
inputElement = driver.find_element_by_id("name2")
inputElement.send_keys('1')

#Select value from the list box 
select = Select(driver.find_element_by_id('fdd2'))
select.select_by_value('4')

select = Select(driver.find_element_by_id('fmm2'))
select.select_by_value('6')

select = Select(driver.find_element_by_id('fyy2'))
select.select_by_value('1986')

select = Select(driver.find_element_by_id('fhr2'))
select.select_by_value('1')

select = Select(driver.find_element_by_id('fmin2'))
select.select_by_value('49')

select = Select(driver.find_element_by_id('fsec2'))
select.select_by_value('0')

select = Select(driver.find_element_by_id('fam2'))
select.select_by_value('1')

Open in new window

0
How to fill autocomplete text in selenium-Python Platform.
I need to enter the city information in the textbox.I tried using key.ARROW_DOWN, Keys.RETURN but it didn't workout. This textbox accepts the information only after clicking on the value from the drop-down list else it don't accept it.  I am not sure how to select option from the drop-down list.
Kindly help on this issue.

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
import time 
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


driver = webdriver.Chrome('C:\\Users\\Vivekanandhan\\Downloads\\Compressed\\chromedriver_win32\\chromedriver.exe')


driver.get('http://poorvapunya.com/marriage_match_horoscope.php')
girl_name = driver.find_element_by_name("girl_name")
girl_name.send_keys('girl_name')
birth_date_fm= driver.find_element_by_name("birth_date_fm")
birth_date_fm.send_keys('20.9.2017')

select = Select(driver.find_element_by_name('birth_hours_fm'))
select.select_by_value('1')

select = Select(driver.find_element_by_name('birth_minutes_fm'))
select.select_by_value('49')

select = Select(driver.find_element_by_name('birth_ampm_fm'))
select.select_by_value('0')

birth_city_fm = driver.find_element_by_id("birth_city_fm")
birth_city_fm.click()
birth_city_fm.clear()
#birth_city_fm.send_keys('India', 

Open in new window

0
Hi all,
I am new to python and would appreciate your help in transpose a wide file to a key value pairs to be loaded to database. Here is the input and output file format. Thanks!

Input file          
visitor_id  param_1 param_2 param_3
1           vp1     vp2     vp3
2           vp12    vp22    vp23

Output file        
vistor_id   converted_key   converted_value
1           param_1         vp1
1           param_2         vp2
1           param_3         vp3
2           param_1         vp12    
2           param_2         vp22    
2           param_3         vp23
0
Hi all, I have a few questions about memory scanning!
The following code attempts to print out all addresses whose value is  int(-143)!

1. I am using a for loop to go through all the addresses! Is this the right thing to do?
2. I feed the read process memory function with hex(i), correct?

3. I am a little bummed by what to put down for my buffer and buffer size, is
what I did proper?

4. This is not in the code, but if I actually know the value I want in the memory is
a Double, how do i modify my code to look at only doubles?

thanks all!
 
> code starts


User32 = ctypes.WinDLL('User32', use_last_error=True)
Kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
PROCESS_VM_READ = 0x0010
PID = 'given'


Process = Kernel32.OpenProcess(PROCESS_VM_READ, 0, PID)
ReadProcessMemory = Kernel32.ReadProcessMemory


buffer_size = 1000
buffer = ctypes.create_string_buffer(buffer_size)

# looking for the addresses where the values are -143, for example
# I used 10000000 as an abitrary number, I need to scan the entire application
# memory space, but I am not sure how to acquire that value.

for i in range(1,10000000):
        if ReadProcessMemory(Process, hex(i), buffer, buffer_size, None):
            if float(buffer) == int(-143) :
                print(float(buffer))


print('Done.')
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.