Python

3K

Solutions

23

Articles & Videos

2K

Contributors

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 All,

kindly help me to write a shell or python script to delete the weblogic files. The files are rotated but need to be deleted which are 30 days old. the find command doesn't delete the files because the number of files are huge.

below is the  .logs format of the weblogic servers
/wls1034/Middleware/user_projects/domains/Domain/servers/server3/logs/

server3.log00585
 server3.log00586
 server3.log00587
server3.log00588
server3.log00589
server3.log00590
server3.log00603
server3.log00604

server3.out00035
server3.out00034
server3.out00036
server3.out00037
0
On Demand Webinar: Networking for the Cloud Era
LVL 8
On Demand Webinar: Networking for the Cloud Era

Ready to improve network connectivity? Watch this webinar to learn how SD-WANs and a one-click instant connect tool can boost provisions, deployment, and management of your cloud connection.

Hi all,

Need to write a python or shell script for email alert on memory utilisation of the server.
we are glance tool to monitor the cpu and memory utilisation for our weblogic servers. If the memory utilisation reached 80% it should alert us through mail so that we can check and restart if required.

below is the output of glance file
B0000A Glance C.04.70.000       04:56:38    x86_64                                                                     Current  Avg  High
------------------------------------------------------------------------------------------------------------------------------------------------------
CPU  Util   SU                                                                                                                       |  1%    3%   27%
Disk Util                                                                                                                            |  0%    0%    7%
Mem  Util   U                      UB     B                                                                                          | 26%   26%   26%
Swap Util                                                                                                                            |  0%    0%    0%
------------------------------------------------------------------------------------------------------------------------------------------------------
                                                                     PROCESS LIST                     …
0
Hello All,

I am new to python and coding overall. I am trying to make sense out of a particular line in the code below. This code will be used to see the files in my recycle bin. In  the second line, what are "curr, dirs, files"? are those fields, arguments of os.walk() function? I have noticed that if I change for instance "curr" for any other name, and change that parameter in the "path" line, the program still works. I am actually a little confused.

import os
rootrec = "C:\\$Recycle.Bin"
for curr, dirs, files in os.walk():
    for f in files:
        path = "%s/%s" % (curr,f)
        print(path)

Any clarification will be helpful!
0
I am looking to replace the value between two spaces in a string with a backslash. Can someone assist with the syntax.

E.G. I want

RED 123456789 White

to become

RED\White

Thanks
0
Hello all,

I am new to Python and I have a couple of questions regarding the code below. I am currently going through a lesson that shows you how to replay packets using scapy. In my try block on the code below, what does "frame[Ether].src" and "frame[IP].src" where did I get these variables from?
Is ".src" a module? what is "[Ether]" and [IP]?

I hope you guys can clarify.

Thank you!

from scapy.all import *
from scapy.utils import rdpcap

src_mac = "08:00:27:ae:6f:d7"
dst_mac = "08:00:27:87:57:be"
src_ip = "192.168.1.118"
dst_ip = "192.168.1.117"

frames = rdpcap("/root/pcaps/ping_traffic.pcap")
for frame in frames:
    try:
        frame[Ether].src = src_mac
        frame[Ether].dst = dst_mac

        if IP in frame:
            frame[IP].src = src_ip
            frame[IP].dst = dst_ip

        sendp(frame)
    except Exception as e:
        print(e)
0
I have a python script that will construct a list of futures contracts for a specified symbol, exchange, and year window.  The script will download pricing information from Quandl for each contract in the strip.  This script works properly.

import pandas as pd
from pandas import ExcelWriter
import quandl

symbol = 'ES'
exchange = 'CME/'

start_year = 2015
end_year = 2016


#Constructs a list of futures contract codes for a particular symbol
#and timeframe.
futures = []
months = 'HMUZ'
for y in range(start_year, end_year+1):
    for m in months:
        futures.append("%s%s%s%s" % (exchange, symbol, m, y))

#Download the data from Quandl.
for f in futures:
    quandl.ApiConfig.api_key = "xxxx"  
    data = quandl.get(str(f))
    data = data.drop(data.columns[[3, 4, 7]], axis=1)

I have another python script that will create a continuous futures contract from 2 consecutive contracts in the futures strip.  It uses the perpetual method; identifying the roll date as the first day where volume of the far contract exceeds volume of near contract, and then adjusts the prices of the previous 4 sessions to roll date by weighting the near and far contracts in increments/decrements of 20%.  This script works properly.

import pandas as pd
from pandas import ExcelWriter
import quandl

#Get quandl futures data
quandl.ApiConfig.api_key = "xxxx"    
contract_near = quandl.get("CME/ESH2015")
contract_far = quandl.get("CME/ESM2015")

#Drop the columns …
0
I am new to python, Now am trying to update a cell with hyperlink which refer to another cell sheet. i have tryed with below code but while click the cell its showing error with "Cannot open the specified file". Could you any one can help on this ?

from win32com.client import Dispatch
excel = Dispatch('Excel.Application')
book = excel.Workbooks.Open("Location.xls")
sheet = book.Worksheets(1)
cell_location = sheet.Cells(2,2)
cell_destination = book.Worksheets(2).Cells(1,3)
sheet.Hyperlinks.Add(Anchor=cell_location, Address=cell_destination)
book.Save()
0
I have a list (named bob) and I want to reverse the order of the list without reversing the whole list.  So, for example my bob list would be [Bob, Mom, Dad, Kelsey] and I want to reverse it to read [boB, moM, daD, yesleK] instead of [yesleK, daD, moM, boB].  

I know I have to iterate through each line and add the extracted line in from of the accumulating string, but I’m not sure how to set up the FOR loop to do so.  How would I do that?
0
like how can i create 2X2 or 4X4 or 3X4 matrices, instead of create while writing the program, i just want to read my own values from keyboard using python code.
0
I have need of a context menu in Windows 7 Explorer that is essentially the "move to folder" command, but with a twist.

Instead of bringing up a dialog of where to move a file, I'd like to bring up a list.  The list would have three types of entries:
1) Recently visited folders
2) List of favorite folders (pinned)
3) Standard browse to folder

So, I have a few questions:

  1. Has this been done already?  If so, where can I get it?
  2. Where can I get Windows' recently visited folders programmatically?  If necessary, I can get these from recently used files, so where would I get the recently used files list programmatically?
  3. Is there any source code I can build off of which does something similar (preferably Python)?  If necessary: C++, C#,  Java?

Thanks!

I'm aware of the CodePlex source code for the MS examples, but they are long and pretty different from what I'm trying to acheive.
http://1code.codeplex.com/SourceControl/changeset/view/57974#Visual Studio 2010/VBShellExtContextMenuHandler/FileContextMenuExt.vb
0
On Demand Webinar: Networking for the Cloud Era
LVL 8
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.

I had this question after viewing linux crontab output.

Hi everyone,
right now I am manually running this script to start a python app. I would like to do this @ reboot.

cd /home/ec2-user/console

python console.py 8090 cloud& <<this runs fine

I tried to create a small bash script ,but cant seem to make it run @ reboot time

#!/bin/bash
cd /home/ec2-user/console
python console.py 8090 cloud&

crontab -e

@reboot sh $HOME/boot_python.sh <<dosnt work

the script runs when executed manually but not @ reboot

Peter
0
Hi Experts,

 I am looking  for a data science project(using python) with complete source code and documentation , please help me with the same and will appreciate your help in this regard.  

Thanks,
SRK,
0
I currently login to the time from website using the following script.


browser = webdriver.Chrome('E:/Shared Folders/Users/runnerjp/chromedriver/chromedriver.exe')
browser.get("https://www.timeform.com/horse-racing/account/sign-in?returnUrl=%2Fhorse-racing%2F") 
time.sleep(3)
username = browser.find_element_by_id("EmailAddress")
password = browser.find_element_by_id("Password")
username.send_keys("usr")
password.send_keys("pass")
login_attempt = browser.find_element_by_xpath("//input[@type='submit']")
time.sleep(3)
login_attempt.submit()

Open in new window


it works but I find using Chrome web driver is hammering my CPU. Is there an alternative code I could use that does not mean I need to physically load the page to sign in?
0
There are x students and y tents placed randomly on a field of dimensions 1000 by 1000 (including(0,0,)). A tent can only house up to 10 students. As a curfew is in place, all students have to find a place in the tents. I have to assign students to tents such that the number of steps walked by the students will be miNimized. Students can only move horizontally and vertically, so if their location is (0,0) and the tent's location is (10,10) then they must walk 20 steps to reach the tent.
The location of the tents will be stored in a file called tents.csv, and the location of the students stored in a file called students.csv.  
The program should read the locations of each and output the results in a file named output.csv where:
- the first row contains the number of total steps walked
- from the second row, each row contains [student ID, tent ID, steps walked, student x location, student y location, tent x location, tent y location]

The program should be able to execute any range of values as defined in the problem definition.


P/s: anyone who know how to solve please please please help me...this is the project that can decide my future......ㅠㅠㅠ
0
This code does 3 things:
1. Gets a list of ticker symbols
2. Gets pricing information from Google finance
3. Inserts the pricing information into a MySQL table

The code runs without returning any errors.  However, the MySQL table is not populated with the information.  The following is returned:
Empty DataFrame
Columns: [open_price high_price, low_price, close_price]
Index: []

I can't figure out why. Advice is needed and appreciated, thank you.

# price_retrieval.py

import datetime as dt
import MySQLdb as mdb
import pandas_datareader.data as web

# Obtain a database connection to the MySQL instance
db_host = 'localhost'
db_user = 'xxx'
db_pass = 'xxxxx'
db_name = 'securities_master'
conn = mdb.connect(db_host, db_user, db_pass, db_name)

#Obtains a list of the ticker symbols in the database.
cur = conn.cursor()
cur.execute("SELECT id, ticker FROM symbol")
data = cur.fetchmany(10)    

#Get daily historic data from google
start_date = dt.datetime(2005, 2, 1)
end_date = dt.datetime(2005, 2, 28)          
for d in data:
    try:
        gf_data = web.DataReader(str(d[1]), "google", start_date, end_date)
    except:
        pass
   
    # Create the time now
    now = dt.datetime.utcnow()
   
    #Create dictionary for db
    pricing_info = {
        'symbol_id': d[1],
        'price_date': now,
        'created_date': now,
        'last_updated_date': now,
        'open_price': gf_data['Open'],
        'high_price': …
0
How to save the output of show run (Router) in text file on desktop using python.
I have a router i have to save its config file in desktop in text format using python
0
Im trying to save the output of show run to my desktop but its not getting executed.. pls help

import paramiko

client=paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
com="ls ~/desktop"
client.connect('192.168.1.12', username='cisco', password='cisco')
output=""
stdin, stdout, stderr = client.exec_command('show run')

print "ssh succuessful. Closing connection"
stdout=stdout.readlines()
client.close()
print "Connection closed"

print stdout
print com
for line in stdout:
    output=output+line
if output!="":
    print output
else:
    print "There was no output for this command"

Open in new window

0
I'm in the Business Intelligence Department, but practically speaking we're the Reporting Department, your basic operational type of reports - lists, lists, and more lists.

I'm at an institution of higher learning, and a new project has come up for the Math Department. They want to know relationships between courses, grades, etc.

Examples:

- if someone gets a D in Calc I, what's the likelihood of graduation?  with various permutations, like taking Calc I again
- what's the likelihood of someone getting a D in Calc I, getting a D or F in Calc II
- for placing incoming students in Pre-Calc or Calc I, what are the factors that indicate success? such as Verbal SAT

So I think I've targeted the right discipline (Analytics), but not sure where to take this project.
0
Please review below code, not able to copy config from device to tftp and vice versa
import paramiko
ssh = paramiko.SSHClient()

ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

ssh.connect('192.168.1.12', port=22, username='cisco', password='cisco')

stdin, stdout, stderr = ssh.exec_command('copy tftp: flash: ')

stdin.write('192.168.1.10')

stdin.write('\n')

stdin.flush()

stdin.write('demotesting')
stdin.write('\n')
stdin.flush()

stdin.write('dest_demo')
stdin.write('\n')

output = stdout.readlines()
print '\n'.join(output)
ssh.close()

Open in new window


error :

L
ine has invalid autocommand "copy tftp: flash: "

Open in new window

0
[Webinar] Learn How Hackers Steal Your Credentials
LVL 8
[Webinar] Learn How Hackers Steal Your Credentials

Do You Know How Hackers Steal Your Credentials? Join us and Skyport Systems to learn how hackers steal your credentials and why Active Directory must be secure to stop them. Thursday, July 13, 2017 10:00 A.M. PDT

I want to invoke a python script from my C++ app and get the data from the python script into my C++ app. How do I do this?

example: testing.py   reads data from and ADC -

C++ app - invoke testing.py  ; data = python testing.py
0
Im using python and paramiko. Im trying to backup a network device router using python. Below is my script. However im getting error

import paramiko
import sys
import time

HOST = "10.11.214.143"
USER = "admin"
PASS = "passwd"


client1=paramiko.SSHClient()
client1.set_missing_host_key_policy(paramiko.AutoAddPolicy())

client1.connect(HOST,username=USER,password=PASS)
  print "SSH connection to %s established" %HOST

#copying config to tftp
stdin, stdout, stderr = client1.exec_command('copy nvram:startup-config tftp: 10.11.214.144')
print stdout.read()


Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    client1.exec_command('copy nvram:startup-config tftp:')
  File "C:\Python27\lib\site-packages\paramiko\client.py", line 436, in exec_command
    chan = self._transport.open_session(timeout=timeout)
  File "C:\Python27\lib\site-packages\paramiko\transport.py", line 716, in open_session
    timeout=timeout)
  File "C:\Python27\lib\site-packages\paramiko\transport.py", line 800, in open_channel
    raise SSHException('SSH session not active')
SSHException: SSH session not active

Open in new window

0
It seems I need to write an Inkscape extension to fill in names from a csv file and write the name on gravesites in cemetery lots.  There are about 100 lots with 12 gravesites per lot.  I could draw all of the names by hand but it seems like more fun to learn perl, python, and extensions.   Does anybody have any hints?
0
I am trying to write a python script to send an email. I get the Import Error SMPTLib not found.
0
Need a python script that will take backup of cisco ios switch to tftp server
0
Is there a way to export/extract all the values/items from a drop-down field in a PDF?

I have a PDF form, and it contains a few drop-down boxes that I can select.  I want to be able to export/extract all the values contained inside this drop-down.  Is that possible?
0

Python

3K

Solutions

23

Articles & Videos

2K

Contributors

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.